How apple/swift-nio-ssh works
Project Type and Purpose
• This is a modular Swift library (“SwiftNIO SSH”) built on top of SwiftNIO and Swift Crypto, not a monolithic application.
• It exposes core SSH protocol building blocks (NIOSSHHandler, state machines, channel multiplexers) and ships three sample executables: a client (NIOSSHClient), a server (NIOSSHServer), and a performance tester (NIOSSHPerformanceTester).
• Its mission: let Swift programs speak SSH directly (like libssh2), providing an API-driven SSH implementation rather than standalone SSH binaries.
Key Architectural Components (to represent
a. External Dependencies
• SwiftNIO (networking/event loop)
• Swift Crypto (cryptographic primitives, CSPRNG)
b. Transport Layer (bottom layer)
• NIO Channel ↔ ByteBuffer
• SSHPacketParser & SSHPacketSerializer
• TransportProtection (AESGCM, SSHTransportProtection)
c. Core Protocol Engine (middle layer)
• NIOSSHHandler (entry point ChannelHandler)
• Connection State Machine (key exchange, authentication, version)
• Key Exchange State Machine (ECDH, curve choices)
• User Authentication State Machine & Delegates
• Channel Multiplexer & Child Channels
• ChildChannelStateMachine, Options, Window Manager, Flow Controller
• SSHChannelData (data vs. stderr, extended data)
d. Sample Executables (top layer)
• NIOSSHClient (ExecHandler, PortForwardingServer, CLI parser, user auth delegate)
• NIOSSHServer (GlueHandler, ExecHandler, RemotePortForwarding handler)
• NIOSSHPerformanceTester (benchmarks, handshake tests, throughput tests)
e. Configuration & Usage
• SSHClientConfiguration & SSHServerConfiguration
• GlobalRequestDelegate (for remote port forwarding)
Relationships & Data Flow
• Inbound TCP bytes → NIO Channel → SSHPacketParser → TransportProtection → Connection State Machine
• State Machine commands → SSHPacketSerializer → TransportProtection → NIO Channel → Remote peer
• Once SSH handshake/authentication completes, child channels spawn: each child channel has its own NIO Channel pipeline, carrying SSHChannelData up to user handlers.
• Sample executables implement user delegates upstream of NIOSSHHandler to react to events (exec requests, shell requests, port-forwarding requests).
Architectural Patterns & Design Principles
• Layered pipeline: clear separation of transport, framing (parser/serializer), crypto, protocol logic, and user handlers.
• State machines for connection, key exchange, user authentication, and child channel lifecycles.
• Delegate pattern: authentication and global-request delegates plug into the core protocol engine.
• Multiplexing: one physical channel hosts multiple logical child channels (session vs. TCP forwarding).