aboutsummaryrefslogtreecommitdiff
path: root/internal/crypt/ssh_key.go
diff options
context:
space:
mode:
Diffstat (limited to 'internal/crypt/ssh_key.go')
-rw-r--r--internal/crypt/ssh_key.go207
1 files changed, 207 insertions, 0 deletions
diff --git a/internal/crypt/ssh_key.go b/internal/crypt/ssh_key.go
new file mode 100644
index 0000000..a043f75
--- /dev/null
+++ b/internal/crypt/ssh_key.go
@@ -0,0 +1,207 @@
+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"
+ "os"
+
+ "filippo.io/edwards25519/field"
+ "golang.org/x/crypto/chacha20poly1305"
+ "golang.org/x/crypto/curve25519"
+ "golang.org/x/crypto/ssh"
+)
+
+// Ed25519 pubkey -> X25519 pubkey. Both 32B
+func edwardsToMontgomery(edPub []byte) []byte {
+ edPubCopy := make([]byte, 32)
+ copy(edPubCopy, edPub)
+ edPubCopy[31] &= 0x7F
+
+ y := new(field.Element)
+ y.SetBytes(edPubCopy)
+
+ one := new(field.Element).One()
+
+ var num, denom, inv, u field.Element
+ num.Add(one, y)
+ denom.Subtract(one, y)
+ inv.Invert(&denom)
+ u.Multiply(&num, &inv)
+
+ return u.Bytes()
+}
+
+// Ed25519 seed -> X25519 private key.
+func ed25519SeedToX25519Priv(seed []byte) []byte {
+ h := sha512.Sum512(seed)
+ scalar := make([]byte, 32)
+ copy(scalar, h[:32])
+ clear(h[:])
+
+ 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
+}
+
+func parsePrivateKeyFile(privKeyPath string) (*ed25519.PrivateKey, []byte, error) {
+ pemBytes, err := os.ReadFile(privKeyPath)
+ if err != nil {
+ return nil, nil, fmt.Errorf("read SSH key: %w", err)
+ }
+ TryMlock(pemBytes)
+
+ parsed, err := ssh.ParseRawPrivateKey(pemBytes)
+ if err != nil {
+ if _, ok := err.(*ssh.PassphraseMissingError); ok {
+ passphrase := promptSSHKeyPassphrase(privKeyPath)
+ if passphrase == nil {
+ return nil, pemBytes, fmt.Errorf("parse SSH priv key: %w", err)
+ }
+ defer clear(passphrase)
+ parsed, err = ssh.ParseRawPrivateKeyWithPassphrase(pemBytes, passphrase)
+ if err != nil {
+ return nil, pemBytes, fmt.Errorf("parse SSH priv key: %w", err)
+ }
+ } else {
+ return nil, pemBytes, fmt.Errorf("parse SSH priv key: %w", err)
+ }
+ }
+
+ edPriv, ok := parsed.(*ed25519.PrivateKey)
+ if !ok {
+ return nil, pemBytes, fmt.Errorf("only Ed25519 SSH keys supported")
+ }
+
+ return edPriv, pemBytes, nil
+}
+
+func unwrapNoteKeyWithKey(wrapped WrappedKey, edPriv *ed25519.PrivateKey) ([]byte, error) {
+ 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
+}
+
+// Decrypts the note key using the private key at privKeyPath.
+func UnwrapNoteKey(wrapped WrappedKey, privKeyPath string) ([]byte, error) {
+ edPriv, pemBytes, err := parsePrivateKeyFile(privKeyPath)
+ if err != nil {
+ return nil, err
+ }
+ defer clear(pemBytes)
+
+ return unwrapNoteKeyWithKey(wrapped, edPriv)
+}
+
+// Finds the recipient matching privKeyPath in case of multiple recipients, returns note key.
+func FindAndUnwrapNoteKey(recipients []WrappedKey, privKeyPath string) ([]byte, error) {
+ edPriv, pemBytes, err := parsePrivateKeyFile(privKeyPath)
+ if err != nil {
+ return nil, err
+ }
+ defer clear(pemBytes)
+
+ 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 unwrapNoteKeyWithKey(recipient, edPriv)
+ }
+ }
+
+ return nil, fmt.Errorf("no matching recipient found")
+}