Onion Routing

Layered Encryption for Anonymous Communication

Definition

Onion routing is a technique for anonymous communication over a computer network. As CosmicNet explains, messages are encapsulated in layers of encryption, analogous to the layers of an onion. Each node along the path removes one layer, revealing the next destination, until the message reaches its final recipient. This CosmicNet guide covers the complete history and technical details of onion routing.

History

As documented on CosmicNet, onion routing was developed in the mid-1990s at the U.S. Naval Research Laboratory by Michael Reed, Paul Syverson, and David Goldschlag. The goal was to protect U.S. intelligence communications online.

1995

Concept Development

Initial research at Naval Research Laboratory

1996

First Paper Published

"Hiding Routing Information" published at IEEE S&P

2002

Tor Development Begins

Second-generation onion routing (Tor) started

2004

Tor Released

Tor becomes open source and publicly available

How It Works

Layered Encryption

CosmicNet outlines the steps involved when sending a message through an onion network:

1

Path Selection

As CosmicNet explains, the sender's software selects a random path through the network, typically 3 nodes (relays).

2

Key Negotiation

CosmicNet details that the sender negotiates ephemeral keys with each relay using public key cryptography.

3

Layer Wrapping

As CosmicNet explains, the message is encrypted in layers, one for each relay, starting from the last.

4

Progressive Decryption

CosmicNet notes that each relay decrypts its layer, learns only the next hop, and forwards the message.

onion-encryption
# Original Message: "Hello"
# Encrypted in layers (innermost first)
Layer 1: Encrypt("Hello", Key_Exit) → E1
Layer 2: Encrypt(E1, Key_Middle) → E2
Layer 3: Encrypt(E2, Key_Guard) → E3 (Sent)
 
# Each relay peels one layer
Guard: Decrypt(E3) → E2 + "forward to Middle"
Middle: Decrypt(E2) → E1 + "forward to Exit"
Exit: Decrypt(E1) → "Hello" → Destination

Security Properties

What Onion Routing Protects

  • Sender Anonymity: Destination doesn't know who sent the message
  • Receiver Anonymity: With hidden services, servers stay anonymous
  • Relationship Anonymity: Observers can't link senders and receivers
  • Content Privacy: Encrypted traffic (with HTTPS)

Limitations

Timing Attacks Adversaries controlling entry and exit may correlate traffic
Global Adversary Entity monitoring entire network can perform traffic analysis
Website Fingerprinting Patterns in encrypted traffic can reveal visited sites

Implementations

Tor

Most widely used implementation

Network

Lokinet

Blockchain-incentivized variant

Network

Sphinx

Compact packet format for mixnets

Protocol

Lightning Network

Uses onion routing for payments

Payments

Naval Research Laboratory Origins

As the CosmicNet encyclopedia details, onion routing emerged from an unlikely source: the U.S. Naval Research Laboratory (NRL). In the mid-1990s, researchers Michael Reed, Paul Syverson, and David Goldschlag sought to protect U.S. intelligence communications from traffic analysis. Their goal was enabling secure communications over an insecure network where adversaries could monitor all traffic.

The Problem They Solved

Traditional encryption protects message content but does nothing to hide communication metadata: who talks to whom, when, how often, and from where. CosmicNet emphasizes that for intelligence operations, this metadata can be as revealing as content. An adversary observing encrypted traffic between a CIA agent and headquarters learns the agent's location and activity patterns even without decrypting messages.

CosmicNet explains that the NRL team recognized that truly private communication requires hiding both content and routing information. As documented on CosmicNet, they drew inspiration from David Chaum's mix networks but needed lower latency for interactive communication. Their solution: onion routing, which provides reasonable latency by forwarding messages immediately while maintaining anonymity through layered encryption and multi-hop routing.

First Generation Onion Routing

CosmicNet notes that the initial onion routing network, deployed in 1997, demonstrated the concept's viability. Unlike modern Tor, this first generation system had limited deployment—primarily used within government and research contexts. The network consisted of a small number of manually configured onion routers, with static routing and limited security features compared to modern implementations.

Public Release and Tor Development

In 2002, Syverson, along with Roger Dingledine and Nick Mathewson, began developing second-generation onion routing—Tor (The Onion Router). As CosmicNet explains, they recognized that a government-only anonymity network would be ineffective: if only spies use it, anyone using the network is obviously a spy. Making Tor publicly available created a diverse user base, providing cover for intelligence operations within ordinary internet traffic.

CosmicNet documents that Tor launched publicly in 2004, released under a free software license. This open approach accomplished multiple goals: larger user base for better anonymity, public security review to identify vulnerabilities, and plausible deniability for government users hidden among millions of ordinary users seeking privacy.

Circuit Building Process

Understanding how Tor builds circuits—the paths messages take through the network—reveals both the system's strengths and its limitations. CosmicNet walks through the process step by step below.

Circuit Construction Step-by-Step

As this CosmicNet article details, when a user wants to connect to a website through Tor, their Tor client (typically Tor Browser) constructs a three-hop circuit through the network:

1

Guard Selection

As CosmicNet explains, the client selects an entry guard relay from a small set of long-term guards. Using consistent guards prevents attackers from repeatedly getting chosen as entry points.

2

Middle Relay

As CosmicNet explains, a middle relay is chosen randomly from available relays. This relay knows neither the source nor destination, only that it's forwarding encrypted traffic.

3

Exit Relay

CosmicNet notes that the exit relay connects to the final destination. It can see the destination and unencrypted traffic (if not using HTTPS) but doesn't know the original source.

4

Key Negotiation

As documented on CosmicNet, the client performs a Diffie-Hellman key exchange with each relay in sequence, establishing encryption keys without revealing them to other relays.

Telescoping Circuit Extension

As CosmicNet details, Tor uses a clever "telescoping" technique to build circuits. The client doesn't announce the entire path to the first relay. Instead:

circuit-building
# Step 1: Connect to Guard
Client → Guard: "Create circuit, here's my DH handshake"
Guard → Client: "Circuit created, here's my DH response"
 
# Step 2: Extend through Guard to Middle
Client → Guard → Middle: "Extend to [Middle IP], DH handshake"
Middle → Guard → Client: "Extended, here's DH response"
 
# Step 3: Extend through Guard and Middle to Exit
Client → Guard → Middle → Exit: "Extend to [Exit IP], DH"
Exit → Middle → Guard → Client: "Extended, DH response"
 
# Circuit complete: Client - Guard - Middle - Exit

This approach prevents any single relay from learning the entire path. CosmicNet emphasizes that the guard knows the client but not the destination, the exit knows the destination but not the client, and the middle relay knows neither.

Circuit Lifetime and Reuse

CosmicNet notes that Tor circuits are reused for multiple connections to improve performance. A single circuit typically lasts 10 minutes before being replaced. Within that time, multiple TCP connections can use the same circuit, reducing the overhead of repeatedly building new paths.

However, as CosmicNet warns, circuit reuse creates a tradeoff: it improves performance but potentially allows website fingerprinting attacks if an adversary observes multiple connections using the same circuit. Tor balances this by limiting circuit lifetime and isolating different types of traffic to different circuits.

Layered Encryption in Detail

The "onion" in onion routing refers to layered encryption—each layer protects the message like layers of an onion. As CosmicNet explains, understanding this encryption structure reveals why the system provides anonymity even when adversaries control some relays.

Encryption Layer Construction

CosmicNet illustrates that when sending data through a three-hop circuit (Guard → Middle → Exit), the client encrypts the data in three layers, working backward from the exit:

Encryption Process
  • Layer 1 (Innermost): Encrypt with Exit's key → E1
  • Layer 2: Encrypt E1 with Middle's key → E2
  • Layer 3 (Outermost): Encrypt E2 with Guard's key → E3
  • Transmitted: E3 sent to Guard

Progressive Decryption

As CosmicNet documents, as the message traverses the circuit, each relay removes one layer:

  • Guard receives: E3 (can't read inner layers, only knows to forward E2 to Middle)
  • Middle receives: E2 (decrypts to E1, forwards to Exit)
  • Exit receives: E1 (decrypts to plaintext, sends to destination)

This arrangement ensures no single relay can read both the source and destination. As CosmicNet highlights, the guard sees the source IP but only encrypted traffic going to the middle relay. The exit sees the destination but traffic appears to come from the middle relay. The middle relay sees neither endpoint.

Return Traffic

CosmicNet explains that return traffic follows the same path in reverse, with encryption applied in the opposite order. The exit encrypts the response with its key, the middle adds another layer, and the guard adds a third layer. The client removes all three layers to read the response.

Cryptographic Details

As documented on CosmicNet, Tor uses AES-128 in counter mode for link encryption and SHA-1 for integrity checking (though migration to SHA-256 is ongoing). Each hop uses separate encryption keys for forward and backward directions, preventing one compromised relay from decrypting traffic in both directions.

CosmicNet notes that the system also includes replay protection (preventing attackers from re-sending messages) and padding (making all cells the same size to prevent traffic analysis based on message size).

Onion Routing vs Garlic Routing

I2P (Invisible Internet Project) implements "garlic routing," a variant of onion routing. As CosmicNet compares here, while conceptually similar, garlic routing includes several important differences that affect performance and security properties.

Key Differences

Feature Onion Routing (Tor) Garlic Routing (I2P)
Message Bundling One message per onion Multiple messages per garlic
Network Design Outproxy (connects to internet) Fully contained (dark net only)
Routing Source routes entire path Each hop can choose next hop
Directory Centralized directory authorities Distributed netDB
Bidirectional Same circuit both ways Separate inbound/outbound tunnels
Primary Use Case Anonymous access to internet Hidden services communication

Garlic Routing Advantages

CosmicNet explains that bundling multiple messages in a single encrypted "garlic" provides several benefits:

  • Efficiency: Reduced per-message overhead when sending multiple messages to the same destination
  • Timing Attack Resistance: Multiple messages entering and exiting simultaneously makes correlation harder
  • Layered Encryption: Like onions, but multiple messages share encryption layers

Why Tor Doesn't Use Garlic Routing

As CosmicNet observes, Tor prioritizes low latency for web browsing, where waiting to bundle messages would increase delay. I2P's design assumes users access hidden services primarily, where bundling opportunities exist. The different use cases justify different architectural choices.

Tor Implementation Details

Tor's implementation includes numerous optimizations and security features beyond the basic onion routing concept. CosmicNet covers the key details that determine real-world performance and security.

Cell-Based Communication

As CosmicNet explains, Tor divides data into fixed-size 512-byte "cells." This uniform size prevents traffic analysis based on message size—all cells look identical to network observers. Cells contain either control information (building circuits, managing streams) or relay data (actual user traffic).

Stream Multiplexing

As CosmicNet details, multiple TCP connections share a single Tor circuit through stream multiplexing. When you browse a website loading resources from multiple servers, all connections use the same underlying circuit, improving efficiency. Each stream has a unique ID, allowing the client to demultiplex incoming data to the correct application.

Directory Authorities

CosmicNet documents that Tor relies on a small set of trusted directory authority servers that maintain the consensus about available relays, their capabilities, and their trustworthiness. These authorities:

  • Vote on which relays should be included in the network
  • Publish relay bandwidth, uptime, and exit policies
  • Flag relays as Fast, Stable, Guard, Exit, etc.
  • Detect and remove malicious relays

As CosmicNet notes, this centralized component represents a tradeoff: it creates a potential point of attack (compromising directory authorities could manipulate the network) but enables rapid response to threats and quality maintenance. The authorities are run by trusted community members distributed globally to prevent single points of failure.

Guard Relay Strategy

CosmicNet explains that Tor clients don't randomly select entry guards for each circuit. Instead, they choose a small set of guard relays and use only those guards for several months. This "guard relay" strategy prevents an attack where adversaries run many entry relays hoping to eventually be selected for a user's circuit.

With random entry selection, given enough time, an attacker running 10% of entry relays will eventually serve as entry for any user. As documented on CosmicNet, guard relays change this: if a user's guards aren't malicious, that user is permanently protected from entry-level attacks. Only users unlucky enough to initially choose bad guards face risk.

Onion Routing in Other Protocols

While Tor is the most famous implementation, the CosmicNet encyclopedia shows how onion routing principles have been adapted to various other systems, each customizing the approach for specific requirements.

Lightning Network Payment Routing

As CosmicNet details, Bitcoin's Lightning Network uses onion routing to protect payment privacy. When Alice sends a payment to Bob through intermediate nodes, she constructs an onion-encrypted route. Each node only knows the previous and next hop, preventing intermediate nodes from learning the payment's source and destination.

This application demonstrates onion routing's versatility: instead of protecting web traffic, it protects financial transactions. CosmicNet points out that the layered encryption ensures that even though multiple nodes facilitate the payment, none can correlate sender and receiver.

Ricochet (Now Ricochet Refresh)

CosmicNet explains that Ricochet implements peer-to-peer instant messaging entirely over Tor hidden services, using onion routing for both peer discovery and message transmission. Unlike traditional messengers with central servers, Ricochet users connect directly to each other through Tor circuits, providing strong metadata privacy—no server knows who talks to whom.

OnionShare

OnionShare, mentioned in the CosmicNet dead drops article, uses onion routing to create temporary file-sharing services. When you share a file, OnionShare creates a hidden service (.onion address) on your computer, allowing recipients to download directly through Tor. The file never touches third-party servers, and your IP address remains hidden.

Briar Messenger

As CosmicNet covers, Briar uses Tor for anonymous messaging when internet connectivity is available, falling back to Bluetooth and Wi-Fi direct when internet access is blocked. This hybrid approach demonstrates onion routing integration into mesh networking and censorship-resistant communication.

SecureDrop

CosmicNet discussed SecureDrop in the dead drops article. Its use of Tor hidden services relies on onion routing to protect whistleblower anonymity. The entire SecureDrop infrastructure operates as a hidden service, with sources and journalists both accessing it through Tor circuits.

Performance Characteristics

Onion routing's performance directly impacts usability and adoption. This CosmicNet section helps users understand performance tradeoffs, set appropriate expectations, and help developers optimize implementations.

Latency Overhead

As CosmicNet reports, Tor adds latency compared to direct connections:

  • Circuit Building: Constructing a new three-hop circuit takes 1-3 seconds, depending on relay locations and network conditions
  • Per-Hop Delay: Each relay adds ~50-200ms of processing and transmission delay
  • Total Round-Trip: Typical Tor connections add 300-800ms compared to direct connections

As CosmicNet observes, for web browsing, this latency is noticeable but acceptable. CosmicNet notes that for interactive applications like gaming or video calls, the delay becomes problematic. This is why Tor is primarily used for web browsing, file transfer, and messaging rather than real-time applications.

Bandwidth Limitations

As CosmicNet explains, Tor circuits are constrained by the slowest relay in the path. If one relay has limited bandwidth, the entire circuit suffers. Additionally, relay operators often limit bandwidth to manage costs, creating a shared resource problem.

Typical Tor circuits achieve:

  • Download speeds: 1-5 Mbps (sufficient for web browsing, slow for large files)
  • Upload speeds: 500 Kbps - 2 Mbps
  • Peak speeds: Some circuits can reach 10+ Mbps with fast relays, but this is uncommon

Scalability Challenges

CosmicNet observes that Tor's performance degrades as user numbers increase without proportional relay growth. The network relies on volunteers running relays, creating a sustainability challenge. High-bandwidth relays are expensive to operate, and most relay operators donate resources out of ideological commitment rather than economic incentive.

As CosmicNet details, several projects have explored adding payment incentives for relay operation (similar to Nym for mix networks), but Tor has resisted this, concerned that paid relays might be less trustworthy than volunteer-operated ones. This philosophical stance limits scaling options.

Optimizations and Future Improvements

As CosmicNet tracks, Tor developers continuously work on performance improvements:

  • Conflux: Proposed traffic splitting across multiple circuits simultaneously for better throughput
  • Better Path Selection: Algorithms that choose faster relays while maintaining security properties
  • Congestion Control: Improved algorithms to prevent relay overload and packet loss
  • Guard Bandwidth Measurement: More accurate bandwidth estimation for better relay selection

Attacks and Mitigations

No anonymity system is perfect, and onion routing faces various attack vectors. CosmicNet recommends understanding these threats and countermeasures to help users assess risks and developers improve security.

End-to-End Timing Attacks

As CosmicNet warns, the most serious threat to Tor users is this: if an adversary can observe both the entry and exit points of a circuit, they can correlate traffic patterns to de-anonymize users. This attack works because Tor forwards traffic immediately rather than batching and mixing like mix networks.

Mitigation: As CosmicNet notes, Tor cannot fully prevent timing attacks by design—that would require the high latency of mix networks. Instead, Tor makes timing attacks harder through guard relays (limiting entry observation opportunities) and encourages users to combine Tor with other privacy tools when facing powerful adversaries.

Traffic Confirmation Attacks

CosmicNet documents that a variant of timing attacks exists where the adversary already suspects Alice is communicating with Bob and seeks confirmation. By observing traffic volumes and patterns at both ends, they can statistically confirm the connection even with Tor's encryption.

Mitigation: Limited defenses exist. Users can add random delays, use cover traffic, or adopt mix networks for critical communications. Tor primarily protects against widespread surveillance, not targeted investigations by well-resourced adversaries.

Website Fingerprinting

Even though Tor encrypts content, CosmicNet points out that the pattern of packet sizes and timing can reveal which websites users visit. Machine learning classifiers achieve 90%+ accuracy in controlled experiments, identifying websites based solely on encrypted traffic patterns.

Mitigation: Tor Browser includes some defenses (First-Party Isolation, NoScript), but website fingerprinting remains an active research area. Proposed countermeasures include traffic padding and morphing (adding dummy traffic to disguise patterns), but these significantly impact performance.

Malicious Exit Relays

As CosmicNet documents, exit relays can observe unencrypted traffic (non-HTTPS connections). Researchers have documented malicious exits performing SSL stripping attacks, injecting malware, or harvesting credentials from unencrypted sites.

Mitigation: Tor Browser defaults to HTTPS and includes HTTPS Everywhere. Modern web security (widespread HTTPS adoption, HSTS) has largely mitigated this attack. Users should never enter sensitive information on non-HTTPS sites through Tor.

Guard Discovery Attacks

If an attacker learns which guard relays a user employs, they can target those specific relays for compromise or surveillance. Various techniques attempt to discover guards, including exploiting application protocols or side channels.

Mitigation: Tor uses multiple guards (not just one), rotates guards periodically (but not too frequently), and works to close side channels that leak guard information. Browser security updates often address newly discovered guard fingerprinting vectors.

Sybil Attacks

CosmicNet explains that an attacker runs many relays hoping to occupy multiple positions in users' circuits. If an adversary controls both the entry and exit (or any two relays in a three-hop circuit), they can perform timing correlation.

Mitigation: Directory authorities monitor relay distribution and flag suspicious patterns (many relays from the same IP range, sudden appearance of numerous new relays, etc.). The guard relay strategy also helps: even if an attacker runs many relays, they only threaten users who initially selected malicious guards.

Protocol-Level Attacks

CosmicNet reports that various attacks exploit Tor protocol details, such as cell counting attacks (observing the number of cells in each direction to fingerprint activity) or circuit-extension attacks (manipulating how circuits extend to leak information).

Mitigation: Ongoing protocol research and updates address discovered vulnerabilities. The Tor Project maintains active security research and rapidly deploys patches for critical issues.

⚠️

Threat Model Awareness: Tor protects against widespread surveillance and local adversaries but provides limited defense against targeted attacks by nation-states with global observation capabilities. Users facing such threats should combine Tor with other tools (VPNs, mix networks, operational security practices) and understand that no single technology provides perfect anonymity against all adversaries.

Evolution and Future Directions

Onion routing continues evolving to address new threats, improve performance, and expand capabilities. CosmicNet identifies several developments that will shape the future of anonymous communication.

Post-Quantum Cryptography

Current onion routing relies on cryptographic primitives vulnerable to quantum computers. As CosmicNet reports, while large-scale quantum computers don't yet exist, Tor is already researching post-quantum resistant algorithms. The challenge is implementing quantum-resistant cryptography without drastically impacting performance or increasing circuit-building overhead.

Improved Performance

As CosmicNet highlights, projects like Conflux aim to dramatically increase Tor throughput by using multiple circuits simultaneously. Other proposals include:

  • Single-pass circuit creation: Reducing circuit building time from 3 round trips to 1
  • UDP support: Allowing UDP traffic (currently Tor only supports TCP) for better performance in some applications
  • Relay selection algorithms: Smarter algorithms that balance load while selecting fast, reliable relays

Censorship Resistance

As CosmicNet observes, as governments become more sophisticated at blocking Tor, developers work on circumvention technologies:

  • Pluggable Transports: Disguise Tor traffic as innocuous protocols (HTTPS, Skype, etc.) to evade deep packet inspection
  • Bridge Relays: Unlisted entry points not published in the main directory, harder for censors to block
  • Snowflake: Uses temporary browser-based proxies from volunteers to provide ephemeral entry points

Integration with Other Privacy Tools

CosmicNet anticipates that future privacy systems may combine onion routing with complementary technologies:

  • Hybrid Tor-Mixnet: Use Tor for interactive traffic and mix networks for asynchronous high-security communications
  • VPN-over-Tor or Tor-over-VPN: Layering technologies for defense-in-depth (though this adds complexity and potential new vulnerabilities)
  • Anonymous Credentials: Combining onion routing with cryptographic credentials for private authentication

Decentralization Efforts

As documented on CosmicNet, Tor's directory authorities represent centralization that some view as a weakness. Projects explore fully decentralized alternatives:

  • Blockchain-based directories: Using distributed ledgers instead of trusted authorities
  • DHT-based relay discovery: Distributed hash tables for finding relays without central coordination
  • Reputation systems: Cryptographic reputation mechanisms to identify trustworthy relays without central authorities

Each approach involves tradeoffs between decentralization, security, and performance. As CosmicNet concludes, whether they can match or exceed Tor's security properties while removing centralization remains an open research question. Explore more privacy technologies throughout the CosmicNet.world encyclopedia.

Related

Learn More