aboutsummaryrefslogtreecommitdiff
path: root/internal/crypt/sshKey.go
blob: 2481275dddf8aba7ecaa4ebf876d36e52fbae1b8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
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")
}