Say you're an airline, and you notice that all your planes get fully booked, but on every flight, 2 to 5 passengers do not turn up or miss their flight.
That means that you can easily sell 2 extra tickets for each flight. That's free money (as good as; fuel consumption will go up a tiny bit)
Now, there's the rare case where too many passengers turn up. So, you pick out a college student or backpacker who is happy to take a flight an hour later in exchange for money, a free ticket for another flight, or whatever. That costs you a bit, but as long as it is rare enough, the net result still is extra money, and, ideally, everybody is happy.
Airlines have departments that compute the ideal amount of overbooking.
So, how can it be legal? That's easy; if you book a flight, you accept terms and conditions, and no government has seen reason to make it illegal.