You must race in a certified, qualifying race (full marathon distance) under a certain cut off time. Cut off times vary with age/gender. As an example, in my age group (40-44) men must run under 3:15 and women under 3:45.
A full list of cut off times can be found on the organizer's website (Boston Athletic Assoc).
Besides the approx. 20,000 qualifier spots, there is a fair amount of non-qualifier spots given for fundraising groups. I believe those are by lottery.
Let's hope we see this marathon continue after today's tragedy. It's a true Boston landmark, and deeply rooted in marathon history.