JFLib

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 str the 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 str the 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) -> W

  • fn u8(mut self, v: u8) -> W

  • fn u32(mut self, v: u32) -> W

  • fn bool(self, v: bool) -> W

  • fn bytes(mut self, v: &[u8]) -> W

  • fn str(self, v: &str) -> W

  • fn mpint(self, v: &[u8]) -> W an unsigned big-endian number as mpint (no leading zeros but the one a set top bit asks for)

  • fn raw(mut self, v: &[u8]) -> W

  • struct 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-list

  • fn skip(&mut self, n: usize) -> Option<&'a [u8]>

  • fn rest(&self) -> &'a [u8]

  • fn pos(&self) -> usize how many bytes were read

  • enum KeyPair a key pair of a host or a user

    • Ed25519(ed25519::Keypair)
    • Rsa(Box<rsa::PrivateKey>)

impl KeyPair

  • fn ed25519(seed: &[u8; 32]) -> KeyPair a new Ed25519 key from 32 random bytes

  • fn rsa(bits: usize, rand: &mut dyn FnMut(&mut [u8])) -> Option<KeyPair> a new RSA key of bits bits (see rsa::PrivateKey::generate)

  • fn key_type(&self) -> &'static str the type of the key in blobs and files

  • fn alg(&self) -> &'static str the algorithm it signs with

  • fn blob(&self) -> Vec<u8> the public key as the protocol carries it

  • fn bits(&self) -> u32

  • fn sign(&self, data: &[u8]) -> Vec<u8> a signature as the protocol carries it

  • fn public_line(&self, comment: &str) -> String "ssh-ed25519 AAAA... comment"

  • fn private_file(&self, comment: &str) -> String the key file in OpenSSH's format, unencrypted

  • fn parse_private(text: &str) -> Option<(KeyPair, String)> a key from a file in OpenSSH's format, unencrypted -> the key and its comment

  • fn fingerprint(blob: &[u8]) -> String "SHA256:<base64 without padding>" of a public key blob

  • fn blob_type(blob: &[u8]) -> &str the first string of a public key blob ("ssh-ed25519", "ssh-rsa")

  • fn blob_bits(blob: &[u8]) -> u32 the bits of a public key blob

  • fn public_line(key_type: &str, blob: &[u8], comment: &str) -> String a public key line: "TYPE BASE64 [COMMENT]"

  • struct PublicLine a line of a public key file, authorized_keys or (after the host names) known_hosts

    • key_type: String
    • blob: 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]) -> bool a signature blob over data is good for the public key blob, by the algorithm alg

  • struct KexInit what a side offers in SSH_MSG_KEXINIT

    • cookie: [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 message

  • struct Algos what two KEXINITs agree on

    • kex: String
    • host_key: String
    • enc_cs: String
    • enc_sc: String
    • mac_cs: String -- "" where the cipher authenticates by itself
    • mac_sc: String
    • comp_cs: String
    • comp_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 common

  • fn 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): k the shared secret as a big-endian number

  • fn 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 to len bytes

  • enum Cipher the protection of one direction of a connection: nothing before the first NEWKEYS, then a cipher with its keys

    • None
    • ChaCha { main: [u8; 32], header: [u8; 32] } -- chacha20-poly1305@openssh.com: the packet's key and the length's key
    • AesCtr { 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]) -> Cipher from a cipher's name and the keys derive_key gave (key_len(enc), 16 and 32 bytes)

  • fn padding(&self, payload: usize) -> usize how 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: pad the 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 of rx: its payload when it is here whole and good (the bytes go), None when more must come; Err: a reason code and a text. head keeps a first block decrypted already (AES-CTR) between two calls

  • fn key_len(enc: &str) -> usize the length of the key of a cipher

  • enum AuthMethod how a login attempt came

    • None -- "none": a client asks which methods there are
    • Password(String)
    • PublicKey { alg: String, blob: Vec<u8>, signed: bool, valid: bool } -- "publickey": signed false is a question (auth_pk_ok answers it); else valid says the signature is good for this key
  • enum Request a channel request

    • Pty { term: String, cols: u32, rows: u32 }
    • Shell
    • Exec(String)
    • Env { name: String, value: String }
    • WindowChange { cols: u32, rows: u32 }
    • ExitStatus(u32)
    • ExitSignal(String)
    • Other(String) -- any other request by its name
  • enum Event what happened on a connection

    • PeerIdent(String) -- the peer's identification line came
    • Algos(Algos) -- the algorithms are agreed
    • HostKey { 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 ways
    • AuthReady -- client: the service ssh-userauth is there, a login may start
    • Banner(String) -- client: a text from the server to show before the login
    • AuthSuccess -- client: logged in
    • AuthFailure { methods: Vec<String>, partial: bool } -- client: that failed; the methods that can go on
    • AuthRequest { user: String, method: AuthMethod } -- server: a login attempt; auth_accept, auth_reject or (for a question) auth_pk_ok answer
    • ChannelOpen { channel: u32, kind: String } -- a peer asks for a channel: accept_channel or refuse_channel
    • ChannelOpened { channel: u32 } -- the peer took the channel of open_session
    • ChannelRefused { 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_reply
    • Data { 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 channel
    • Debug(String) -- SSH_MSG_DEBUG with display set
    • Unimplemented(u32) -- the peer does not know our packet of that number
    • Rekeyed -- a later key exchange is done (the keys changed, the session goes on)
    • Disconnected { reason: u32, text: String } -- the peer ended the connection
    • Failed { reason: u32, text: String } -- the peer broke the protocol, the MAC was wrong or no algorithms are common: we told it so
  • enum Role what a connection is about

    • Client
    • Server
  • struct Config the settings of a connection

    • ident: String -- the identification line without its line end ("SSH-2.0-...")
    • ciphers: Vec<String> -- in order of preference
    • host_key_algs: Vec<String> -- client: the host key algorithms it takes
    • methods: String -- server: what a failed login names ("publickey,password")
  • struct Core one side of an SSH connection

impl Core

  • fn client(cfg: Config, seed: &[u8; 32]) -> Core a client: what it sends starts with its identification line

  • fn server(cfg: Config, keys: Vec<KeyPair>, seed: &[u8; 32]) -> Core a server with its host keys

  • fn take_out(&mut self) -> Vec<u8> the bytes to send

  • fn take_events(&mut self) -> Vec<Event> what happened since the last call

  • fn dead(&self) -> bool nothing more will come or go (after the last take_out)

  • fn encrypted(&self) -> bool keys are in force both ways

  • fn authenticated(&self) -> bool a login succeeded

  • fn algos(&self) -> &Algos the algorithms of the last exchange

  • fn session_id(&self) -> &[u8] the session's identifier: H of the first exchange

  • fn peer_ident(&self) -> &str the peer's identification line

  • fn footprint(&self) -> usize the bytes it holds (a simulator's memory budget)

  • fn disconnect(&mut self, reason: u32, text: &str) ends the connection from our side

  • fn push(&mut self, bytes: &[u8]) what the connection brought

  • fn 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 ends

  • fn auth_accept(&mut self) server: the login is good: channels may open

  • fn auth_reject(&mut self) server: the login failed; the client may try another

  • fn auth_pk_ok(&mut self, alg: &str, blob: &[u8]) server: the answer to a question about a key: it would be taken

  • fn banner(&mut self, text: &str) server: a text for the client before a login

  • fn set_methods(&mut self, methods: &str) server: the methods a failed login names from now on

  • fn 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 password

  • fn auth_key(&mut self, user: &str, key: &KeyPair) client: a login with a key: first the question, the signature when the server would take it

  • fn open_session(&mut self) -> u32 client: asks for a session channel -> its id (Event::ChannelOpened or ChannelRefused)

  • fn accept_channel(&mut self, id: u32) takes a channel the peer asked for

  • fn 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 request

  • fn reply(&mut self, id: u32, ok: bool) answers a request with want_reply

  • fn 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 waits

  • fn eof(&mut self, id: u32) no more data from us on this channel

  • fn close(&mut self, id: u32) closes the channel when what waits went out

  • fn channel_open(&self, id: u32) -> bool the channel is still there

  • fn channel_pending(&self, id: u32) -> usize bytes that wait for a channel's window

  • enum Part what is in a TCP segment of an SSH connection

    • Ident { 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; len its 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)

Source: docs/API.md in the JFLib repository.