Strictly speaking, it is never legal to buy a passport. Passports are official documents issued by sovereign states. They indicate citizenship and provide certain rights and benefits to aid in international travel. Nations typically charge fees to issue passports, but these fees should not be considered a purchase price. Countries in good standing in the international community do not allow the re-sale of passports. A few do, however, issue passports to anyone willing to pay a very sizable service fee, which essentially amounts to the sale of a passport.
In much of the world, it is simple to obtain a passport. Typically, the process simply involves presenting proof of citizenship to the appropriate authorities and then paying some sort of processing fee. This resembles a commercial transaction but is more akin to the process of obtaining a driver’s license or similar official document. A citizen does not buy a passport. The associated cost is not a purchase price but rather a fee to cover the expense of processing.
As a rule of thumb, any person or service offering to actually sell a passport is working on the black market. Passport buying scams are common, especially in countries where the rule of law is not strong. These scams may provide some kind of document, but it will typically be either an outright forgery or a modified copy of an existing passport. Travel using such documents is extraordinarily risky and is apt to lead to serious legal problems.
Attempts to buy a passport from the United States or other first-world nation are especially likely to end in tragedy for a consumer. The global concern over terrorism has led to much more stringent measures to monitor passports and international travel more generally. An attempt to buy a passport from one of these nations and to travel using it will almost certainly be detected in the first world, as customs agents employ quite sophisticated computer systems to check the validity of passports.
A few nations do come close to allowing the sale of passports. These nations, which often depend very heavily on offshore banking and finance to keep their economies afloat, have found that it is helpful to allow wealthy investors to essentially buy a passport by paying an extremely sizable fee. Technically, the nations involved still issue the passports to men and women who have suddenly acquired a new citizenship. In practice, since these nations usually require only the payment of a very large fee in order to become a citizen, this amounts to a legal system of selling passports.