Are residence and citizenship by investment programs legal?

Yes. Not only are they legal, they are also actively promoted by the governments of countries that have such programs.