Yes. It is permissible to buy these places in order to use them as Masjids because doing so means to use them in useful and legal purposes. Impurities and filthiness are not an inherent characteristic of these places, but it is a contingent attribute. (Part No. 6; Page No. 234) If these places are used for good purposes, impurity or filthiness will no longer be there.May Allah grant us success. May peace and blessings be upon our Prophet Muhammad, his family, and Companions.