From 9eb2b774e9f0522a3547644453bf929dd560f05f Mon Sep 17 00:00:00 2001 From: ishaan Date: Tue, 14 Jul 2026 09:16:51 +0530 Subject: ssh helper funcs --- internal/crypt/sshKey.go | 191 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 191 insertions(+) create mode 100644 internal/crypt/sshKey.go (limited to 'internal/crypt/sshKey.go') diff --git a/internal/crypt/sshKey.go b/internal/crypt/sshKey.go new file mode 100644 index 0000000..2481275 --- /dev/null +++ b/internal/crypt/sshKey.go @@ -0,0 +1,191 @@ +package crypt + +// read/thanks to https://words.filippo.io/using-ed25519-keys-for-encryption/ + +import ( + "bytes" + "crypto/ed25519" + "crypto/rand" + "crypto/sha256" + "crypto/sha512" + "fmt" + "math/big" + "os" + + "golang.org/x/crypto/chacha20poly1305" + "golang.org/x/crypto/curve25519" + "golang.org/x/crypto/ssh" +) + +// j*vascript could never +var curve25519Prime, _ = new(big.Int).SetString("57896044618658097711785492504343953926634992332820282019728792003956564819949", 10) +var bigOne = big.NewInt(1) + +// Ed25519 pubkey -> X25519 pubkey. Both 32b +func edwardsToMontgomery(edPub []byte) []byte { + y := new(big.Int).SetBytes(edPub) + + num := new(big.Int).Add(bigOne, y) + + denom := new(big.Int).Sub(bigOne, y) + denom.Mod(denom, curve25519Prime) + denom.ModInverse(denom, curve25519Prime) + + u := new(big.Int).Mul(num, denom) + u.Mod(u, curve25519Prime) + + return u.FillBytes(make([]byte, 32)) +} + +// Ed25519 seed -> X25519 private key. +func ed25519SeedToX25519Priv(seed []byte) []byte { + h := sha512.Sum512(seed) + scalar := h[:32] + + scalar[0] &= 248 + scalar[31] &= 127 + scalar[31] |= 64 + + return scalar +} + +// Wraps noteKey once per PubKey. Returns WrappedKey for each. +func WrapNoteKeyForRecipients(noteKey []byte, pubKeys [][]byte) ([]WrappedKey, error) { + recipients := make([]WrappedKey, 0, len(pubKeys)) + for _, pubKeyBytes := range pubKeys { + parsed, _, _, _, err := ssh.ParseAuthorizedKey(pubKeyBytes) + if err != nil { + return nil, fmt.Errorf("parse SSH pub key: %w", err) + } + + cryptoPub := parsed.(ssh.CryptoPublicKey).CryptoPublicKey() + edPub, ok := cryptoPub.(ed25519.PublicKey) + if !ok { + return nil, fmt.Errorf("only Ed25519 SSH keys supported") + } + + xPub := edwardsToMontgomery(edPub) + + ephPriv := make([]byte, 32) + if _, err := rand.Read(ephPriv); err != nil { + return nil, fmt.Errorf("generate ephemeral key: %w", err) + } + ephPub, err := curve25519.X25519(ephPriv, curve25519.Basepoint) + if err != nil { + return nil, fmt.Errorf("ephemeral pub: %w", err) + } + + shared, err := curve25519.X25519(ephPriv, xPub) + if err != nil { + return nil, fmt.Errorf("ECDH: %w", err) + } + + wrapKey := sha256.Sum256(shared) + aead, err := chacha20poly1305.New(wrapKey[:]) + if err != nil { + return nil, fmt.Errorf("wrap cipher: %w", err) + } + + var nonce [12]byte + if _, err := rand.Read(nonce[:]); err != nil { + return nil, fmt.Errorf("nonce: %w", err) + } + + encNoteKey := aead.Seal(nil, nonce[:], noteKey, nil) + + recipients = append(recipients, WrappedKey{ + PKType: "ssh-ed25519", + PubKeyBytes: ssh.MarshalAuthorizedKey(parsed), + EphemeralPub: ephPub, + Nonce: nonce, + EncNoteKey: encNoteKey, + }) + } + return recipients, nil +} + +// Decrypts the note key using the private key at privKeyPath. +func UnwrapNoteKey(wrapped WrappedKey, privKeyPath string) ([]byte, error) { + pemBytes, err := os.ReadFile(privKeyPath) + if err != nil { + return nil, fmt.Errorf("read SSH key: %w", err) + } + TryMlock(pemBytes) + defer clear(pemBytes) + + parsed, err := ssh.ParseRawPrivateKey(pemBytes) + if err != nil { + return nil, fmt.Errorf("parse SSH priv key: %w", err) + } + + edPriv, ok := parsed.(*ed25519.PrivateKey) + if !ok { + return nil, fmt.Errorf("only Ed25519 SSH keys supported") + } + + seed := edPriv.Seed() + TryMlock(seed) + defer clear(seed) + + xPriv := ed25519SeedToX25519Priv(seed) + TryMlock(xPriv) + defer clear(xPriv) + + shared, err := curve25519.X25519(xPriv, wrapped.EphemeralPub) + if err != nil { + return nil, fmt.Errorf("ECDH: %w", err) + } + TryMlock(shared) + defer clear(shared) + + wrapKey := sha256.Sum256(shared) + aead, err := chacha20poly1305.New(wrapKey[:]) + if err != nil { + return nil, fmt.Errorf("unwrap cipher: %w", err) + } + TryMlock(wrapKey[:]) + defer clear(wrapKey[:]) + + noteKey, err := aead.Open(nil, wrapped.Nonce[:], wrapped.EncNoteKey, nil) + if err != nil { + return nil, fmt.Errorf("unwrap note key: %w", err) + } + TryMlock(noteKey) + + return noteKey, nil +} + +// Finds the recipient matching privKeyPath in case of multiple recipients, returns note key. +func FindAndUnwrapNoteKey(recipients []WrappedKey, privKeyPath string) ([]byte, error) { + pemBytes, err := os.ReadFile(privKeyPath) + if err != nil { + return nil, fmt.Errorf("read SSH key: %w", err) + } + TryMlock(pemBytes) + clear(pemBytes) + + parsed, err := ssh.ParseRawPrivateKey(pemBytes) + if err != nil { + return nil, fmt.Errorf("parse SSH priv key: %w", err) + } + + edPriv, ok := parsed.(*ed25519.PrivateKey) + if !ok { + return nil, fmt.Errorf("only Ed25519 SSH keys supported") + } + + pubKey := edPriv.Public().(ed25519.PublicKey) + sshPub, err := ssh.NewPublicKey(pubKey) + if err != nil { + return nil, fmt.Errorf("derive SSH pub key: %w", err) + } + ownPubKeyBytes := ssh.MarshalAuthorizedKey(sshPub) + + for _, recipient := range recipients { + if bytes.Equal(recipient.PubKeyBytes, ownPubKeyBytes) { + return UnwrapNoteKey(recipient, privKeyPath) + } + } + + return nil, fmt.Errorf("no matching recipient found") +} -- cgit v1.3