# encryption (ssh/tls) ## scope * in-transit encryption, certificates, tls, ssh * not: at-rest encryption, low-level cryptanalysis * audience: practitioners needing fast comprehension and operational leverage ## cryptographic keys ### symmetric cryptography * one key both encrypts and decrypts * fast, suitable for large payloads * vulnerable: if shared key is exposed, all communication compromised ### asymmetric cryptography * pair: public key, private key * public key: distributed freely, used to encrypt or verify * private key: kept secret, used to decrypt or sign * security: possession of public key does not enable deriving private key ### analogy: the one-way chest * imagine a chest that anyone can close but only one person can open * the public key is the mechanism to close the chest: anyone may use it * the private key is the only mechanism that opens it * asymmetry: safe distribution of the "closing" mechanism without risking the "opening" one ### why two keys * distribution: server can publish a public key openly * bootstrap: clients use public key without prior secure channel * protection: private key never leaves server, exposure risk minimized * guarantee: math ensures that reversing public to private is computationally infeasible ### hybrid cryptosystems * asymmetric exchange derives a shared secret * symmetric keys encrypt bulk data efficiently ### encryption as computational asymmetry * summation analogy: adding integers is easy, finding the exact integers from a sum is hard without constraints * multiplication analogy: multiplying large primes is easy, factoring their product is hard * encryption leverages functions that are easy forward, hard inverse ## tls handshake * client hello: proposed ciphers, client random * server hello: cipher selected, server random, certificate with public key * key exchange: * rsa: client encrypts pre-master with server pubkey, server decrypts with private key * ecdhe: both exchange ephemeral keys, compute shared secret * session keys derived from secret + randoms * secure channel established with symmetric encryption ## ssh handshake * negotiate algorithms and nonces * server provides host key for identity * diffie-hellman exchange: derive shared secret * session key derived * server signs handshake with host private key; client verifies with host public key * user authentication: password or client pubkey signature * session key encrypts all subsequent traffic ## trust models ### tls trust model * global hierarchy of delegation * root cas: ultimate trust anchors, shipped with os and browsers * intermediates: signed by roots, issue end-entity certificates * server certificate: signed by intermediate or root, binds domain to public key * client validation: checks each signature in the chain until a trusted root is reached * purpose of delegation: * protect roots by keeping them offline and rarely used * scale issuance workload to many intermediates * allow policy separation (different intermediates for regions, business types) * contain compromise impact: revoking an intermediate leaves other chains intact * metaphor: stamped letters * a trusted root office stamps a letter authorizing a regional office * the regional office stamps letters for businesses * each letter carries the previous office's stamp, forming a chain back to the trusted root * verification is checking each stamp step by step until the trusted office is reached ### ssh trust model * flat or local authority * default: trust on first use (tofu) * first connection: client records host key in `~/.ssh/known_hosts` * later connections: client compares against stored key * mismatch indicates mitm attempt or legitimate rotation * enterprise alternative: ssh ca (openssh 5.4+) * organization designates a signing key as ca * host and user keys signed by ca * clients trust only the ca public key, not every host key * simplifies fleet management, rotation, and access control * metaphor: personal ledger vs organizational notary * tofu: you write down the server's "signature" the first time you meet it * ssh ca: instead of memorizing every signature, you trust a notary's seal on each one ### comparison * tls: hierarchical, global, relies on third-party roots * ssh: local, flat by default, optional single-ca trust in enterprise * tls trust is transitive through a chain of signatures * ssh trust is either direct (ledger) or mediated by one organizational signer ## deployment patterns * server config: cert + private key loaded * pkcs12 bundle import for os or app * enterprise issues: mutual tls, rollover, hsm key storage, internal pki, tls inspection, legacy iot roots, algorithm migration, acme renewal automation ### certificate file formats * pem: base64, human-readable, delimited by `-----begin/end-----` * der: binary encoding of the same structure * crt: usually pem or der, depending on platform * pkcs#12 (.pfx, .p12): bundle with private key + certificate + chain, encrypted with password * conversions: * pem to der: `openssl x509 -in cert.pem -out cert.der -outform der` * der to pem: `openssl x509 -in cert.der -inform der -out cert.pem` * pem + key to pkcs#12: `openssl pkcs12 -export -inkey key.pem -in cert.pem -certfile chain.pem -out bundle.p12` ## principles * symmetric is fast but key distribution fragile * asymmetric solves distribution but slower * hybrid combines both * ecc vs rsa: elliptic curve cryptography achieves same strength with shorter keys and less computation * forward secrecy: ephemeral keys prevent later compromise of session data ### ecc mechanism explained * based on elliptic curve discrete logarithm problem * given a point p on a curve and integer k, computing q = kp is easy * given p and q, finding k is computationally infeasible * contrast with rsa: security depends on difficulty of integer factorization * advantage: ecc offers equivalent security with smaller key sizes and lower computational cost ## tools * ssh-keygen -l -f key.pub (inspect) * ssh-keygen -t rsa -b 4096 -f id\_rsa (generate) * openssl rsa -in enc.key -out dec.key (remove passphrase) * openssl verify cert.pem (-untrusted, -capath/-cafile) * ssh -v user@host (debug) * ssh-copy-id -i id\_rsa.pub user@host (install key) * sshfs, sftp ## ssh config example ``` host example hostname example.com user myuser identityfile ~/.ssh/server.%r identitiesonly yes ``` ## faq (concepts, rationale, policy) * how a free service like letsencrypt works: acme protocol automates domain validation and issuance * can an attacker use my public key to decrypt messages?: no; asymmetry ensures only private key can decrypt * difference between encryption in transit and at rest * transit: protects data on the wire; at rest: protects stored data * why self-signed certificates are not automatically trusted: no external ca validation; only useful in closed environments * why reusing same key pair across services is risky: compromise of one service compromises all * does renewing a certificate change key pair?: not necessarily; best practice is to rotate keys periodically * how ocsp stapling improves revocation checks: server provides signed revocation proof, reducing client lookups and soft-fail gaps * why wildcard certificates are convenient and risky: cover many hosts but compromise exposes all subdomains * meaning of "perfect forward secrecy" in practice: past sessions remain confidential even if long-term keys are exposed * differences between tls versions and why older ones are disabled: newer versions close protocol-level weaknesses, deprecate unsafe primitives * how weak ciphers undermine otherwise valid certificates: encryption strength relies on cipher, not just certificate validity ## symptoms and fixes (operational errors) * expired certificate * symptom: browser "certificate expired" or `curl: (60)` * fix: renew and redeploy full chain * letsencrypt renewal failure * symptom: `certbot renew` fails, no updated cert * fix: ensure acme challenge reachable, renew manually if needed * incomplete chain * symptom: "unable to get local issuer certificate" * fix: include intermediate ca certs in server config * system clock skew * symptom: cert appears not yet valid or expired despite correct dates * fix: sync with ntp * hostname mismatch * symptom: "certificate does not match host" or `curl: (51)` * fix: correct hostname or reissue cert with proper san/cn * expired intermediate * symptom: browser rejects cert chain despite valid leaf * fix: deploy updated intermediates * ocsp stapling absent or stale * symptom: revocation check failure in some clients * fix: enable and refresh ocsp stapling on server * ssh host key changed * symptom: `remote host identification has changed!` * fix: verify legitimacy, update `known_hosts` if valid * ssh unknown host * symptom: authenticity warning on first connection * fix: verify host fingerprint out-of-band, then accept