Can I blindly trust 127.0.0.1?

Communicating through 127.0.0.1 can be thought of as just another IPC mechanism, but one that re-uses existing protocols. Just like shared memory or UNIX domain sockets or pipes, it's one of countless ways that two processes can communicate on a single system. If you trust that the processes on your system have not been compromised, then you can "blindly" trust connections going through 127.0.0.1.


If you know that the IP address at the other end of a TCP socket is 127.0.0.1, this guarantees that either the system administrator has configured the firewall to redirect this particular connection, or the other end of the TCP socket is a process running on the same machine. So if you trust your server machine as a whole, you can trust 127.0.0.1. However, there are advantages to not using a TCP socket, for defense in depth.

You need to be careful about how you implement the localhost check. Localhost is 127.0.0.1 until the day it isn't, for example because you switch to a version of some library that uses IPv6 by default, or because you decide to add some form of forwarding proxy to the mix to allow you to run the two services on different machines or containers. If you start using a proxy, be careful to check at the right place. And of course you must make sure never to host anything else that could be dodgy on the same machine (though why would you in those days of VMs and containers).

Knowing that you're talking with the same machine only tells you that some process on the same machine is at the other end of the connection. It doesn't tell you that it's the right process. Under normal operation, presumably, both processes are running. But if something wrong happens, such as one process crashing after running out of memory due to a denial-of-service attack, the port would be free for another process to listen. And at any time, any local process can connect to a running server. This requires the attacker to be able to run some process locally, but it could be some unprivileged process that would otherwise not be able to do much. So while relying on 127.0.0.1 isn't a vulnerability, it leaves you open to privilege escalation.

I you can, use a Unix socket instead. Unix and TCP sockets work the same except for specifying the address to connect to or listen on, so it wouldn't require much code change. A Unix socket can have permissions, or can be created by the parent supervisor, and nothing else can connect to it. With a Unix socket, you have the guarantee that not only what's at the other end of the socket is running on the same machine, but that it's the expected process. This only leaves you vulnerable to a security breach in the authenticator service or the main service, rather than a breach in anything running on the same machine.