A man-in-the-middle attack is an active attack against a communication protocol where the attacker relays and modifies messages in transit. The parties believe they are talking to each other directly, but in fact both are talking to the attacker.
Protection against man-in-the-middle attacks depends on two things: establishing a secure channel, and making sure that the secure channel is established with the intended party: at least one of the parties must authenticate the other one. There are two major ways to set up a secure channel with the right party using cryptography:
- sharing secret keys or public keys in a secure environment before communication takes place (e.g. provisioning keys on a device during manufacturing, or exchanging PGP keys when meeting in person);
- relying on a trusted third party, with a public-key infrastructure pki.
SSL/TLS is the de facto standard way to establish a secure channel over the Internet, in HTTPS and other protocols. Authentication is achieved by either storing the server's certificate certificates on the client or by having the server's certificate delivered by a [certificate authority] certificate-authority.