They’re not random, they’re called “flags of convenience” since the ship is subject to the laws of the country where it is registered, including labor laws and safety standards. Panama and Liberia are common flags for merchant ships because they make it cheap to register, exempt the ship from some taxes, and hire foreign labor.
The rules for ships are a bit different for rules for cars.
There's a number of countries (some of them land-locked) that sell flags of convenience, but in that particular case, it's possible that didn't happen.