They were legal because there was no national or international law against them. The only "law" against them was Islamic law, and until it is put into official form in a constitution, it is not legally enforceable. While they may have been in bad taste or offensive, they were not technically illegal.
In the United States of America there has always been a looseness and levity with political and religious cartoons. In the 1800's many national papers depicted silly Native Americans performing rituals and devout Lutherans in compromising situations in ways that lampooned the religion but stayed lighthearted. These were acceptable in the past. No longer. Muslims and any other religious group have the right and sometimes the mission to protest and suppress these kinds of attacks on their religion. It is not a good idea to make fun of Muhammed in particular as this goes against Muslim religion and has brought terroristic retaliation in the past! So are these cartoons legal?? Yes freedom of speech protects it! Are they ethical? Not in any way and if the people presenting these cartoons want to avoid retaliation they should cease and desist.