netpkt/ssh.rs#
Source: lib/netpkt/ssh.rs
ssh -- SSH version 2 without I/O (RFC 4250 to 4254, RFC 8731, RFC 8332, RFC 8709): the codec and
a core for both sides of a connection: feed it the bytes that came, take the bytes to send and
the events; no sockets, no clock. Random bytes come from a seed the caller passes in, so a
connection is the same byte for byte for the same seed
PORT 22
MSG_*, msg_name(code) the message numbers and their names
DISC_*, reason_name(c) the reason codes of SSH_MSG_DISCONNECT
W, R writing and reading the wire types (byte, boolean, uint32, string,
mpint, name-list)
KeyPair Ed25519 or RSA: generate from the caller's random bytes, blob(),
key_type() ("ssh-ed25519", "ssh-rsa"), alg() ("ssh-ed25519",
"rsa-sha2-256"), sign(data), bits(), public_line(comment),
private_file(comment) and parse_private(text) (OpenSSH's unencrypted
"OPENSSH PRIVATE KEY" format)
verify(alg, blob, data, sig), fingerprint(blob) ("SHA256:..."), blob_type(blob), blob_bits(blob),
parse_public(line) -> PublicLine { key_type, blob, comment } (authorized_keys, known_hosts)
KexInit parse / to_payload; negotiate(client, server) -> Algos
exchange_hash(...), derive_key(k, h, letter, session_id, len) RFC 4253 7.2, RFC 5656 4
Cipher one direction's protection: make(name, key, iv, mac), key_len(name),
padding(n), seal(seq, payload, pad), open(seq, rx, head)
Config ident ("SSH-2.0-..."), ciphers, host key algorithms, the methods a
failed login names
Core::client(cfg, seed) / Core::server(cfg, keys, seed)
push(bytes) what the connection brought; take_out() the bytes to send;
take_events() what happened (Event); dead(): nothing more will come or go
host_key_verdict(ok) the client's answer to Event::HostKey (the exchange waits for it)
auth_none / auth_password / auth_key(user, ..) the client's logins (after Event::AuthReady)
auth_accept / auth_reject / auth_pk_ok(alg, blob) / banner(text) the server's answers to
Event::AuthRequest (they may come later: a RADIUS server may be asked)
open_session() -> id, accept_channel(id) / refuse_channel(id, reason, text),
request(id, Request, want_reply), reply(id, ok), send(id, bytes), send_ext(id, 1, bytes),
eof(id), close(id) channels, with windows both ways (what the window does not take waits)
rekey() a new key exchange, as either side may start one
disconnect(reason, text)
algos() / session_id() / peer_ident() / authenticated() / encrypted() / footprint()
Event PeerIdent, Algos, HostKey, Encrypted, AuthReady, Banner, AuthSuccess,
AuthFailure, AuthRequest, ChannelOpen, ChannelOpened, ChannelRefused,
ChannelRequest, ChannelReply, Data, Eof, Closed, Debug, Unimplemented,
Rekeyed, Disconnected, Failed
Part, dissect(segment) what a dissector sees in a TCP segment: the identification line,
packets in the clear with their fields, or bytes that are no packet
in the clear (encrypted, or the rest of one)
Algorithms: curve25519-sha256 (also under the name @libssh.org), host and user keys ssh-ed25519
and rsa-sha2-256 (host keys; user keys too), ciphers chacha20-poly1305@openssh.com, aes128-ctr
and aes256-ctr with hmac-sha2-256, compression none. Not here: encrypted key files, the older
ssh-rsa with SHA-1, port forwarding (a channel of another type is the embedder's to refuse),
the extension negotiation of RFC 8308 (SSH_MSG_EXT_INFO is tolerated, none is sent).
OpenSSH's strict key exchange (kex-strict-c/s-v00@openssh.com, against the Terrapin prefix
truncation, CVE-2023-48795) is offered in the first KEXINIT and kept when the peer offers it
too: the peer's KEXINIT must be its first packet, nothing but key exchange messages may come
during the first exchange, and each direction counts its packets from 0 again after a NEWKEYS.
The embedder decides what the protocol leaves open: which host key to trust, who logs in, which
channels and requests to take. A protocol error from the peer sends SSH_MSG_DISCONNECT and
ends in Event::Failed. netio::ssh is the other SSH of the library, a blocking client on real
sockets.
/// the well-known port
PORT: u16 = 22
MSG_DISCONNECT: u8 = 1
MSG_IGNORE: u8 = 2
MSG_UNIMPLEMENTED: u8 = 3
MSG_DEBUG: u8 = 4
MSG_SERVICE_REQUEST: u8 = 5
MSG_SERVICE_ACCEPT: u8 = 6
MSG_EXT_INFO: u8 = 7
MSG_KEXINIT: u8 = 20
MSG_NEWKEYS: u8 = 21
MSG_KEX_ECDH_INIT: u8 = 30
MSG_KEX_ECDH_REPLY: u8 = 31
MSG_USERAUTH_REQUEST: u8 = 50
MSG_USERAUTH_FAILURE: u8 = 51
MSG_USERAUTH_SUCCESS: u8 = 52
MSG_USERAUTH_BANNER: u8 = 53
MSG_USERAUTH_PK_OK: u8 = 60
MSG_GLOBAL_REQUEST: u8 = 80
MSG_REQUEST_SUCCESS: u8 = 81
MSG_REQUEST_FAILURE: u8 = 82
MSG_CHANNEL_OPEN: u8 = 90
MSG_CHANNEL_OPEN_CONFIRMATION: u8 = 91
MSG_CHANNEL_OPEN_FAILURE: u8 = 92
MSG_CHANNEL_WINDOW_ADJUST: u8 = 93
MSG_CHANNEL_DATA: u8 = 94
MSG_CHANNEL_EXTENDED_DATA: u8 = 95
MSG_CHANNEL_EOF: u8 = 96
MSG_CHANNEL_CLOSE: u8 = 97
MSG_CHANNEL_REQUEST: u8 = 98
MSG_CHANNEL_SUCCESS: u8 = 99
MSG_CHANNEL_FAILURE: u8 = 100
fn msg_name(code: u8) -> &'static strthe name of a message number (RFC 4250 4.1)
DISC_HOST_NOT_ALLOWED: u32 = 1
DISC_PROTOCOL_ERROR: u32 = 2
DISC_KEY_EXCHANGE_FAILED: u32 = 3
DISC_MAC_ERROR: u32 = 5
DISC_SERVICE_NOT_AVAILABLE: u32 = 7
DISC_VERSION_NOT_SUPPORTED: u32 = 8
DISC_HOST_KEY_NOT_VERIFIABLE: u32 = 9
DISC_CONNECTION_LOST: u32 = 10
DISC_BY_APPLICATION: u32 = 11
DISC_TOO_MANY_CONNECTIONS: u32 = 12
DISC_AUTH_CANCELLED: u32 = 13
DISC_NO_MORE_AUTH_METHODS: u32 = 14
fn reason_name(c: u32) -> &'static strthe name of a disconnect reason (RFC 4250 4.2.2)struct W(pub Vec<u8>)a message under construction
impl W
fn msg(t: u8) -> Wfn u8(mut self, v: u8) -> Wfn u32(mut self, v: u32) -> Wfn bool(self, v: bool) -> Wfn bytes(mut self, v: &[u8]) -> Wfn str(self, v: &str) -> Wfn mpint(self, v: &[u8]) -> Wan unsigned big-endian number as mpint (no leading zeros but the one a set top bit asks for)fn raw(mut self, v: &[u8]) -> Wstruct R<'a>reading a message
impl<'a> R<'a>
fn new(b: &'a [u8]) -> R<'a>fn u8(&mut self) -> Option<u8>fn u32(&mut self) -> Option<u32>fn bool(&mut self) -> Option<bool>fn bytes(&mut self) -> Option<&'a [u8]>fn str(&mut self) -> Option<&'a str>fn names(&mut self) -> Option<Vec<String>>a name-listfn skip(&mut self, n: usize) -> Option<&'a [u8]>fn rest(&self) -> &'a [u8]fn pos(&self) -> usizehow many bytes were readenum KeyPaira key pair of a host or a userEd25519(ed25519::Keypair)Rsa(Box<rsa::PrivateKey>)
impl KeyPair
fn ed25519(seed: &[u8; 32]) -> KeyPaira new Ed25519 key from 32 random bytesfn rsa(bits: usize, rand: &mut dyn FnMut(&mut [u8])) -> Option<KeyPair>a new RSA key ofbitsbits (see rsa::PrivateKey::generate)fn key_type(&self) -> &'static strthe type of the key in blobs and filesfn alg(&self) -> &'static strthe algorithm it signs withfn blob(&self) -> Vec<u8>the public key as the protocol carries itfn bits(&self) -> u32fn sign(&self, data: &[u8]) -> Vec<u8>a signature as the protocol carries itfn public_line(&self, comment: &str) -> String"ssh-ed25519 AAAA... comment"fn private_file(&self, comment: &str) -> Stringthe key file in OpenSSH's format, unencryptedfn parse_private(text: &str) -> Option<(KeyPair, String)>a key from a file in OpenSSH's format, unencrypted -> the key and its commentfn fingerprint(blob: &[u8]) -> String"SHA256:<base64 without padding>" of a public key blobfn blob_type(blob: &[u8]) -> &strthe first string of a public key blob ("ssh-ed25519", "ssh-rsa")fn blob_bits(blob: &[u8]) -> u32the bits of a public key blobfn public_line(key_type: &str, blob: &[u8], comment: &str) -> Stringa public key line: "TYPE BASE64 [COMMENT]"struct PublicLinea line of a public key file, authorized_keys or (after the host names) known_hostskey_type: Stringblob: Vec<u8>comment: String
fn parse_public(line: &str) -> Option<PublicLine>reads "TYPE BASE64 [COMMENT]"fn verify(alg: &str, blob: &[u8], data: &[u8], sig: &[u8]) -> boola signature blob overdatais good for the public key blob, by the algorithmalgstruct KexInitwhat a side offers in SSH_MSG_KEXINITcookie: [u8; 16]kex: Vec<String>host_key: Vec<String>enc_cs: Vec<String>enc_sc: Vec<String>mac_cs: Vec<String>mac_sc: Vec<String>comp_cs: Vec<String>comp_sc: Vec<String>lang_cs: Vec<String>lang_sc: Vec<String>follows: bool
impl KexInit
fn parse(p: &[u8]) -> Option<KexInit>reads the message (with its number)fn to_payload(&self) -> Vec<u8>the messagestruct Algoswhat two KEXINITs agree onkex: Stringhost_key: Stringenc_cs: Stringenc_sc: Stringmac_cs: String-- "" where the cipher authenticates by itselfmac_sc: Stringcomp_cs: Stringcomp_sc: String
fn negotiate(c: &KexInit, s: &KexInit) -> Option<Algos>RFC 4253 7.1: the client's preference decides -> None when a list has nothing in commonfn exchange_hash(v_c: &str, v_s: &str, i_c: &[u8], i_s: &[u8], k_s: &[u8], q_c: &[u8], q_s: &[u8], k: &[u8]) -> [u8; 32]the exchange hash of curve25519-sha256 (RFC 8731, RFC 5656 4):kthe shared secret as a big-endian numberfn derive_key(k: &[u8], h: &[u8], letter: u8, sid: &[u8], len: usize) -> Vec<u8>HASH(K || H || letter || session_id), extended as RFC 4253 7.2 says tolenbytesenum Cipherthe protection of one direction of a connection: nothing before the first NEWKEYS, then a cipher with its keysNoneChaCha { main: [u8; 32], header: [u8; 32] }-- chacha20-poly1305@openssh.com: the packet's key and the length's keyAesCtr { aes: Box<Aes>, ctr: [u8; 16], mac: [u8; 32] }-- aes128-ctr or aes256-ctr with hmac-sha2-256
impl Cipher
fn make(enc: &str, key: &[u8], iv: &[u8], mac: &[u8]) -> Cipherfrom a cipher's name and the keys derive_key gave (key_len(enc), 16 and 32 bytes)fn padding(&self, payload: usize) -> usizehow many padding bytes a payload takes (RFC 4253 6: at least 4, whole blocks)fn seal(&mut self, seq: u32, payload: &[u8], pad: &[u8]) -> Vec<u8>one binary packet:padthe padding bytes (self.padding(payload.len()) of them)fn open(&mut self, seq: u32, rx: &mut Vec<u8>, head: &mut Option<[u8; 16]>) -> Result<Option<Vec<u8>>, (u32, &'static str)>the next packet ofrx: its payload when it is here whole and good (the bytes go), None when more must come; Err: a reason code and a text.headkeeps a first block decrypted already (AES-CTR) between two callsfn key_len(enc: &str) -> usizethe length of the key of a cipherenum AuthMethodhow a login attempt cameNone-- "none": a client asks which methods there arePassword(String)PublicKey { alg: String, blob: Vec<u8>, signed: bool, valid: bool }-- "publickey":signedfalse is a question (auth_pk_ok answers it); elsevalidsays the signature is good for this key
enum Requesta channel requestPty { term: String, cols: u32, rows: u32 }ShellExec(String)Env { name: String, value: String }WindowChange { cols: u32, rows: u32 }ExitStatus(u32)ExitSignal(String)Other(String)-- any other request by its name
enum Eventwhat happened on a connectionPeerIdent(String)-- the peer's identification line cameAlgos(Algos)-- the algorithms are agreedHostKey { alg: String, blob: Vec<u8> }-- client: the server's key signed the exchange; host_key_verdict goes on (or does not)Encrypted-- new keys are in force both waysAuthReady-- client: the service ssh-userauth is there, a login may startBanner(String)-- client: a text from the server to show before the loginAuthSuccess-- client: logged inAuthFailure { methods: Vec<String>, partial: bool }-- client: that failed; the methods that can go onAuthRequest { user: String, method: AuthMethod }-- server: a login attempt; auth_accept, auth_reject or (for a question) auth_pk_ok answerChannelOpen { channel: u32, kind: String }-- a peer asks for a channel: accept_channel or refuse_channelChannelOpened { channel: u32 }-- the peer took the channel of open_sessionChannelRefused { channel: u32, reason: u32, text: String }ChannelRequest { channel: u32, request: Request, want_reply: bool }ChannelReply { channel: u32, ok: bool }-- the answer to a request with want_replyData { channel: u32, ext: Option<u32>, data: Vec<u8> }-- data on a channel (ext: Some(1) is stderr)Eof { channel: u32 }Closed { channel: u32 }-- both sides closed the channelDebug(String)-- SSH_MSG_DEBUG with display setUnimplemented(u32)-- the peer does not know our packet of that numberRekeyed-- a later key exchange is done (the keys changed, the session goes on)Disconnected { reason: u32, text: String }-- the peer ended the connectionFailed { reason: u32, text: String }-- the peer broke the protocol, the MAC was wrong or no algorithms are common: we told it so
enum Rolewhat a connection is aboutClientServer
struct Configthe settings of a connectionident: String-- the identification line without its line end ("SSH-2.0-...")ciphers: Vec<String>-- in order of preferencehost_key_algs: Vec<String>-- client: the host key algorithms it takesmethods: String-- server: what a failed login names ("publickey,password")
struct Coreone side of an SSH connection
impl Core
fn client(cfg: Config, seed: &[u8; 32]) -> Corea client: what it sends starts with its identification linefn server(cfg: Config, keys: Vec<KeyPair>, seed: &[u8; 32]) -> Corea server with its host keysfn take_out(&mut self) -> Vec<u8>the bytes to sendfn take_events(&mut self) -> Vec<Event>what happened since the last callfn dead(&self) -> boolnothing more will come or go (after the last take_out)fn encrypted(&self) -> boolkeys are in force both waysfn authenticated(&self) -> boola login succeededfn algos(&self) -> &Algosthe algorithms of the last exchangefn session_id(&self) -> &[u8]the session's identifier: H of the first exchangefn peer_ident(&self) -> &strthe peer's identification linefn footprint(&self) -> usizethe bytes it holds (a simulator's memory budget)fn disconnect(&mut self, reason: u32, text: &str)ends the connection from our sidefn push(&mut self, bytes: &[u8])what the connection broughtfn rekey(&mut self)starts a new key exchange (either side may)fn host_key_verdict(&mut self, ok: bool)the client's answer to Event::HostKey: the exchange goes on, or the connection endsfn auth_accept(&mut self)server: the login is good: channels may openfn auth_reject(&mut self)server: the login failed; the client may try anotherfn auth_pk_ok(&mut self, alg: &str, blob: &[u8])server: the answer to a question about a key: it would be takenfn set_methods(&mut self, methods: &str)server: the methods a failed login names from now onfn auth_none(&mut self, user: &str)client: a login without credentials (it asks which methods there are)fn auth_password(&mut self, user: &str, password: &str)client: a login with a passwordfn auth_key(&mut self, user: &str, key: &KeyPair)client: a login with a key: first the question, the signature when the server would take itfn open_session(&mut self) -> u32client: asks for a session channel -> its id (Event::ChannelOpened or ChannelRefused)fn accept_channel(&mut self, id: u32)takes a channel the peer asked forfn refuse_channel(&mut self, id: u32, reason: u32, text: &str)refuses a channel the peer asked for (reason 1: administratively prohibited, 3: unknown channel type)fn request(&mut self, id: u32, req: &Request, want_reply: bool)sends a channel requestfn reply(&mut self, id: u32, ok: bool)answers a request with want_replyfn send(&mut self, id: u32, data: &[u8])data on a channel (what its window does not take waits)fn send_ext(&mut self, id: u32, code: u32, data: &[u8])stderr data on a channel; it goes when nothing waitsfn eof(&mut self, id: u32)no more data from us on this channelfn close(&mut self, id: u32)closes the channel when what waits went outfn channel_open(&self, id: u32) -> boolthe channel is still therefn channel_pending(&self, id: u32) -> usizebytes that wait for a channel's windowenum Partwhat is in a TCP segment of an SSH connectionIdent { at: usize, len: usize, line: String }-- an identification line (without its line end)Packet { at: usize, len: usize, packet_length: u32, padding: u8, code: u8 }-- a packet in the clear;lenits bytes here (fewer than 4 + packet_length when it goes on in the next segment)Opaque { at: usize, len: usize }-- bytes that are no packet in the clear: encrypted, or the rest of a packet
fn dissect(b: &[u8]) -> Vec<Part>a segment's parts. A packet in the clear has a length that fits, a padding of at least 4 and a known message number; what does not look like one is opaque (an encrypted length looks like one only by rare chance)