
SSH Networking & Security for P2P Messaging
Learn the AWS concepts relevant to building the Just Peers decentralized messaging system, including EC2, VPC, subnets, routing, NAT, security groups, IAM, KMS, S3, and CloudWatch. Focus on how cloud networking and security concepts relate to peer discovery, direct connections, NAT traversal, cryptographic identity, secure communication, and encrypted backups.
Just Peers
Rethinking messaging around cryptographic identity, SSH, and direct peer-to-peer connections
Most messaging systems make the server disappear.
You open an application, select a contact, type a message, and press send. The interface gives you almost no reason to think about what happens next. Somewhere behind it, a service authenticates your account, discovers the other user, routes the message, stores state, handles reconnects, queues messages for offline devices, synchronizes your history, and keeps enough infrastructure alive for the whole thing to work.
That abstraction is useful. It is also a set of assumptions.
I wanted to build a messenger by removing as many of those assumptions as possible: no central account service owning identities, no central database holding conversations, and no hosted messaging API sitting in the middle of every exchange. The peers should own their identities, establish authenticated sessions with each other, and move messages directly whenever the network permits it.
On paper, that sounds almost trivial:
Peer A ──────────── Peer B direct connectionThe interesting part starts when you try to make those two machines actually find each other.
They need identities before they can trust each other. They need a way to discover addresses. Those addresses may be useless because both machines are behind NAT. A peer may disappear halfway through a conversation. One machine may be powered off when the other sends a message. Keys can be stolen. Discovery infrastructure can become a source of metadata. And even a perfectly encrypted connection does not make the endpoints anonymous.
Removing the server does not remove the hard problems.
It moves them.
That is what makes the architecture interesting.

Starting with identity instead of accounts
The first design decision is also the one that changes the rest of the system: identity should exist independently of an account database.
In a conventional application, identity usually looks something like:
username ↓password ↓authentication service ↓accountThe account is authoritative because a server says it is.
For a peer-owned identity, the relationship is different:
private key ↓public key ↓fingerprint ↓peer verificationA new installation can generate a cryptographic keypair locally. The private key stays with the device. The corresponding public identity can be shared with another peer, and the fingerprint becomes a compact representation that users can verify through a trusted channel.
There is something appealing about this model. The identity exists before the application has an account system. There is no username reservation, password database, password reset endpoint, or central authority required simply to establish who a device claims to be.
But removing the account server also removes a lot of conveniences that normally remain invisible.
If the private key is lost, there is no "forgot password" flow. If a laptop is replaced, the new machine does not automatically inherit the old identity. If someone has several devices, the system has to decide whether those devices represent one user-level identity or several independent identities. If the private key is stolen, the attacker has acquired something far more consequential than a password stored in a remote database.
Those aren't edge cases to postpone until the UI is finished. They are consequences of the identity model itself.
For the first version, a device-centric identity is considerably easier to reason about. Each installation owns a keypair, stores the private portion locally, exposes a public identity, and requires explicit peer verification before trusting a connection. A more sophisticated implementation could later introduce user-level identities and securely linked devices, but that adds another layer of key management that the core protocol does not need on day one.
The principle remains the same: the cryptographic identity belongs to the endpoint, not to the messaging service.
Why SSH became interesting
SSH was an obvious candidate because it already treats cryptographic identity as a first-class concept.
A public/private keypair can authenticate a peer without a password being transmitted or a central application database deciding whether the identity is legitimate. SSH also provides an established model for encrypted sessions, host identity, key verification, and rekeying.
That makes it much more interesting here than simply saying, "SSH encrypts the chat."
The real question is what SSH should actually be responsible for.
I initially considered the possibility of making SSH the entire transport layer. It is attractive: mature implementations exist, public-key authentication is well understood, and the protocol already solves secure authenticated communication. But once the problem expands beyond "securely connect to this known host," the cracks in that approach become obvious.
SSH does not solve peer discovery.
It does not make two devices behind unrelated NATs reachable.
It does not define a decentralized peer-routing system.
It does not provide application-level message synchronization.
It does not decide how a user should represent one identity across multiple devices.
Those are separate problems, and forcing SSH to solve them would make the architecture worse rather than better.
That led to a more useful way of thinking about the stack.
SSH can provide an important identity and secure-session model. A P2P networking framework such as libp2p can address the problems that appear below that layer: peer identifiers, discovery, connection management and NAT traversal. Noise provides another mature approach to establishing secure sessions when that is more appropriate to the selected transport. Cryptographic primitives should come from established libraries rather than being implemented inside the application.
The point isn't to assemble a pile of fashionable protocols.
It is to assign each technology the problem it is actually good at solving.
SSH is good at authenticated secure communication. libp2p is designed around peer networking. Noise provides well-defined secure handshake patterns. Mature cryptographic libraries provide the primitives.
The application should sit above those pieces and define what a conversation actually means.
The first real problem: finding the peer
Suppose Alice and Bob have already exchanged public identities.
Alice knows Bob's fingerprint.
Bob knows Alice's fingerprint.
Both identities are valid.
The cryptography is sound.
There is still one problem:
Where is Bob?
A centralized messenger answers that question through its own infrastructure. Alice asks the service for Bob's current presence and connection information, and the service takes care of the rest.
A P2P application has to build that mechanism itself.
On a local network, the answer can be relatively simple. mDNS or another LAN discovery mechanism can allow peers to announce themselves without requiring a globally reachable service.
For a direct connection, users could exchange an address, port, public key and fingerprint manually. It is technically straightforward and particularly useful for a niche tool, although it is obviously less convenient than searching someone's username.
At a larger scale, decentralized discovery becomes more interesting. A peer-to-peer networking stack can provide peer IDs and mechanisms for discovering peers without putting an application-owned database in charge of every identity.
But discovery introduces a subtle privacy problem of its own.
A system can avoid storing messages centrally while still exposing a lot of information about who is online, which peers exist, or which addresses are associated with which identities. Discovery therefore belongs to the architecture's threat model, not merely its networking layer.
This is one of the recurring themes of the project: removing centralized storage does not automatically remove metadata.
It changes where the metadata comes from and who has access to it.
When both peers know each other and still can't connect
There is a moment in a P2P design where the cryptography stops being the interesting problem.
Imagine Alice and Bob have successfully exchanged identities. Their protocol knows which peer it wants to reach. Both endpoints are authenticated. The connection is encrypted.
So they should be able to connect.
They can't.
Alice might have a private address such as
192.168.1.20 . Bob might have 10.0.0.14 . Both devices may be behind routers performing NAT. Their public addresses may change. A firewall may reject unsolicited inbound traffic. With carrier-grade NAT, even traditional port forwarding may not be available.The protocol can be completely correct and the connection can still fail before the secure session ever begins.
That is why P2P networking is not simply "encrypted sockets."
A practical connection strategy has to try several paths:
Direct connection ↓IPv6 / reachable endpoint ↓NAT traversal ↓Hole punching / connection upgrade ↓Direct encrypted session ↓Relay fallback, if the product permits oneTechnologies such as AutoNAT and DCUtR in the libp2p ecosystem are relevant here, as are UDP hole punching, QUIC where appropriate, IPv6 and conventional port forwarding.
The exact strategy depends heavily on the transport and deployment model. There is no universal traversal trick that makes arbitrary networks transparent.
And there is an important product decision at the end of the chain.
If the project has a strict requirement that messages must never pass through a third-party relay, then some users simply won't be able to establish a connection from some networks.
That isn't a security bug.
It is a networking constraint.
The alternative is to introduce a relay for difficult cases. That improves reachability but changes the privacy model. A relay may be unable to decrypt the message payload if the application maintains end-to-end encryption, but it can still potentially observe connection metadata such as addresses, timing and traffic volume.
So a relay is not merely an implementation detail. It is a trust boundary.
A system that uses one should say so.
The uncomfortable question: what happens when Bob is offline?
Consider a simple message.
Alice writes:
hey, are you around?She presses send.
Bob's laptop is powered off.
There is no central messaging server.
Where does the message go?
There are only a few honest answers.
The simplest is to keep the encrypted message locally on Alice's machine. When Bob reconnects, the peers establish a session and the pending message can be transmitted.
Another possibility is a trusted store-and-forward peer. The message remains encrypted, but another online node temporarily retains it until Bob becomes reachable. That solves an availability problem while introducing a new infrastructure and trust relationship.
The third option is to not support offline delivery.
None of these approaches is magical.
A powered-off computer cannot receive a packet.
Offline messaging requires some machine to remain online and retain the message. In a centralized system, that machine is usually the provider's infrastructure, so users rarely have to think about it. In a P2P design, the decision becomes explicit.
For a privacy-first architecture, a local encrypted queue is the cleanest starting point. It keeps pending messages under endpoint control and avoids quietly turning the system into a distributed mailbox.
It also means users have to accept a limitation that centralized messaging has trained them not to notice: availability depends on the peers.
That trade-off is fundamental.
The endpoint becomes the infrastructure
Once the server disappears, the endpoint becomes much more important.
The device now has to protect the identity key, maintain peer state, store conversation history, manage reconnects and enforce protocol rules. A compromised endpoint can undermine protections that were otherwise perfectly implemented over the network.
Private keys deserve the strongest protection.
The application should prefer OS-level key stores where available, or protect locally persisted key material with an appropriate encryption scheme. If a user chooses password protection, a password-based KDF such as Argon2id can be considered for deriving encryption keys. Message history can live in an encrypted local database, with filesystem permissions providing another layer of isolation.
There is also a practical distinction between deleting a message and proving that every physical representation of that message has disappeared. Modern filesystems and SSD controllers make secure deletion more complicated than calling
unlink() and declaring victory.That does not make local storage useless.
It means the threat model needs to describe what the application actually guarantees.
The same principle applies to backups. An encrypted backup can provide recovery when a device is lost, but the backup key becomes another security boundary. If the user loses both the device and the means to decrypt the backup, there may be no recovery path.
A decentralized identity model gives the user more ownership.
It also gives the user more responsibility.
Separating connection establishment from conversation
At this point the architecture naturally separates into two related systems.
The first is concerned with making a trustworthy connection possible:
Identity ↓Discovery ↓Connection negotiation ↓Authentication ↓Secure sessionThe second begins once that session exists:
Encrypted message ↓Sequence / replay checks ↓Integrity verification ↓Delivery ↓Local persistenceThat distinction is useful because the application should not treat "connected" and "ready to exchange trusted messages" as the same state.
A peer may have discovered an address without authenticating the identity associated with it. A transport may exist without the application having established the appropriate trust relationship. A session may be encrypted while the peer itself is malicious.
The protocol therefore needs explicit states rather than one boolean called
connected .A simplified connection lifecycle might look like:
DISCOVERED ↓CONNECTING ↓AUTHENTICATING ↓VERIFIED ↓SECURE SESSION ↓MESSAGE STREAMThat also makes the interface more useful. Instead of merely showing a green dot, the application can expose whether the connection is direct, whether the peer identity was verified, and what transport is carrying the session.
The UI becomes a reflection of the protocol rather than a decorative layer placed on top of it.
Messages need a protocol, not just a socket
Once the secure session exists, it is tempting to send JSON objects across it and call the problem finished.
It isn't.
A messaging protocol has to survive reconnects, duplicates, malicious input and interruptions.
A conceptual message envelope might contain:
message_idsender_idrecipient_idtimestampsequence_numbernonceciphertextauthentication_dataThe exact wire representation is a separate implementation decision, but the semantics matter.
If a packet arrives twice, the recipient should not display the message twice.
If a sequence number is unexpectedly old, the protocol needs to determine whether it is a legitimate retransmission or a replay.
If a peer sends an enormous payload, the application should reject it before it becomes a memory-management problem.
If malformed input reaches a parser, it should produce an error rather than a crash.
When a connection disappears and later returns, both sides need a way to determine what was successfully delivered and what remains pending.
This is where seemingly boring details become security properties.
Message IDs, sequence numbers, nonces, acknowledgements, strict size limits and state-machine validation are not glamorous features. They are the things that prevent a small networking tool from becoming an unreliable or easily abused protocol implementation.
Security begins with the attacker, not the encryption algorithm
The easiest way to make a security section meaningless is to list algorithms.
Ed25519. X25519. ChaCha20-Poly1305. AES-GCM.
All useful primitives in the right contexts, but their names do not constitute a threat model.
Start with an attacker.
A passive observer can potentially capture network traffic. Properly encrypted message contents should remain unreadable, but the observer may still learn which IP addresses communicate, when sessions begin, how long they last, and potentially how much data is exchanged.
An active attacker has a different goal. They may attempt to impersonate a peer or interfere with the connection. Cryptographic authentication and explicit fingerprint verification are designed to make that substantially harder, provided the identity being verified is actually trusted.
Then there is the authenticated attacker.
A malicious peer can possess a perfectly valid cryptographic identity and still send hostile input. Authentication answers "who owns this key?" It does not answer "is this peer trustworthy?"
That distinction matters for protocol design.
The application still needs strict input validation, message limits, safe parsing, replay protection and defensive handling of malformed network traffic.
A stolen private key is more serious still. If the key representing a peer's identity is compromised, an attacker may be able to impersonate that peer. Encryption between the attacker's machine and another peer does not solve an identity compromise.
Finally, the endpoint itself can be compromised.
If malware has access to the running process, decrypted messages may be available after they have already crossed every cryptographic boundary. No network protocol can encrypt a message against the machine that is legitimately displaying it.
The resulting security model is therefore layered:
Cryptography +Authentication +Peer verification +Protocol validation +Key protection +Endpoint securityThere is no final checkbox marked "secure."
Encryption is not anonymity
This distinction deserves its own place in the design because "privacy-first" can easily be misunderstood.
Suppose the application establishes a correctly encrypted direct connection between two peers.
An observer may not be able to read:
"meet me at 8"But they may still be able to observe:
Alice's IPBob's IPConnection timeSession durationPacket sizesTraffic volumeOnline/offline transitionsDepending on the networking architecture, peer discovery can expose additional information.
Encryption protects the contents of communication. It does not automatically conceal the existence or shape of communication.
If stronger anonymity is required, Tor or I2P could be considered as separate networking layers. That would be another architectural decision with its own performance, availability and usability trade-offs.
It should not be quietly bundled into the word "encrypted."
Choosing the stack without turning the project into a protocol collection
There are several plausible implementations.
A Go implementation is attractive because of its networking ecosystem, straightforward concurrency model and strong support for systems-oriented tooling. Rust offers stronger compile-time guarantees and mature networking and cryptography ecosystems, at the cost of a steeper implementation curve.
The more important decision is not the language alone.
It is how the responsibilities are divided.
SSH can contribute authenticated secure sessions and a useful public-key identity model.
libp2p can provide a foundation for peer networking, discovery, connection management and NAT traversal.
Noise can provide well-defined secure handshake patterns when the selected transport calls for them.
Established cryptographic libraries should handle the actual primitives.
The application should not implement its own Ed25519 signing routine, invent a key exchange algorithm, or design a new authenticated cipher because an existing library API looked inconvenient.
Cryptography is one of the worst places to be original.
The strongest implementation is therefore likely to be a combination of mature components rather than a "pure SSH" experiment simply because SSH is in the project's name.
SSH remains meaningful because its identity and authenticated-session model are central to the design. It simply does not have to become the answer to every networking problem.
The interface should expose the connection, not hide it
A conventional messenger tries to make infrastructure invisible.
For this project, hiding it would actually make the product less interesting.
A minimal terminal or desktop interface could show something like:
┌──────────────────────────────────────────────────────────┐│ PEER 7F3A...92C1 ● DIRECT AUTHENTICATED│├──────────────────────────────────────────────────────────┤│ ││ YOU ││ hey ││ ││ PEER ││ connected directly. ││ ││ YOU ││ no server in the middle. ││ │├──────────────────────────────────────────────────────────┤│ > Type a message... │└──────────────────────────────────────────────────────────┘
transport: directidentity: verifiedsession: encryptedThe point isn't to recreate Discord in a terminal.
The interface should communicate the things that actually matter to this architecture: which peer is connected, which identity was verified, whether the connection is direct, and what state the session is in.
Commands can remain similarly deliberate:
identityfingerprintpeersconnectrequestacceptchathistoryverifydisconnectblockbackupstatusThat makes the product feel more like a network tool than a social platform.
"No third party" needs a precise definition
The phrase sounds stronger than it really is unless the architecture defines it carefully.
In this project, the boundary is about ownership of the core messaging path.
The application should not require a central service to own:
- user identities
- authentication state
- message routing
- conversation history
- message storage
That does not necessarily mean that no infrastructure can exist anywhere in the system.
A decentralized discovery mechanism may need bootstrap information. A DHT may consist of many participating nodes. A future implementation might support optional relays for networks where direct connections are impossible.
Those components have different roles.
A discovery mechanism that helps two peers find each other is not equivalent to a central database storing every conversation. A relay that forwards encrypted traffic is not equivalent to a messaging server that can read and persist plaintext. A self-hosted bootstrap node is not the same trust model as a proprietary cloud service controlled by the application developer.
Those distinctions should remain visible in the architecture.
If the project eventually supports a relay, the UI and documentation should say so. If a relay cannot decrypt the payload but can observe source and destination addresses, that limitation should be documented.
"Serverless" is useful shorthand only when everyone agrees what it means.
For a serious system, the actual dependency graph is more useful than the slogan.
What the first version should actually solve
There is a temptation with a project like this to implement everything at once: DHT discovery, multi-device identities, NAT traversal, encrypted backups, offline delivery, anonymous routing, a polished GUI and a full messaging protocol.
That is how a focused networking project turns into an unfinished distributed-systems thesis.
The first implementation should prove the core trust path.
A useful MVP is much smaller:
Local cryptographic identity ↓Secure private-key storage ↓Peer identity exchange ↓Fingerprint verification ↓Direct connection ↓Authenticated secure session ↓Encrypted message exchange ↓Local encrypted historyOnce that path is reliable, the next problems become measurable engineering work rather than guesses.
LAN discovery can be added.
NAT traversal can be introduced.
Reconnect and synchronization can become explicit protocol work.
Offline queues can be designed around actual session semantics.
Multi-device identity can be addressed without simultaneously debugging the transport.
That order matters.
The project is interesting because the server is gone
The strongest argument for this architecture is not that centralized messaging is inherently bad.
Centralized systems solve real problems extremely well. They make discovery easy, provide reliable offline delivery, simplify account recovery and hide a tremendous amount of networking complexity from the user.
The P2P model gives some of that convenience back.
What it gets in exchange is ownership.
The identity lives on the endpoint.
The conversation history can live on the endpoint.
The connection can be established directly between endpoints.
The trust relationship can be explicit rather than represented by an account row in someone else's database.
And every limitation that the central server previously absorbed becomes visible.
Two peers need a way to discover each other.
They need to establish trust.
They need to cross whatever network stands between them.
They need to decide what happens when one disappears.
They need to protect their own keys.
They need to understand what metadata remains visible.
They need to handle hostile peers even after authentication succeeds.
None of that is a flaw in the concept.
It is the concept.
A central server makes many of these problems disappear behind an API. A peer-to-peer architecture forces them back into the design.
That is why the project is less interesting as a claim about "secure messaging" than it is as an exercise in where trust, state and responsibility actually live.
The final system can be reduced to a surprisingly small chain:
IDENTITY ↓DISCOVERY ↓CONNECTION ↓AUTHENTICATION ↓SECURE SESSION ↓MESSAGEThere is no promise that every network will permit the last step directly. No promise that encryption makes the participants anonymous. No promise that a lost key can be recovered. No promise that an authenticated peer is benign.
Just a different boundary.
Instead of asking a server to own the identity, find the peer, carry the message and remember the conversation, the system asks the endpoints to do more of that work themselves.
That is the real experiment behind the project.
Not eliminating every server.
Eliminating the assumption that every conversation needs one.
#buildatpce
Enjoyed reading this content? Let the author know!
Your likes, comments, shares, and saves help creators reach more builders.
Loading recommendations
Loading article