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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
|
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"
"os/signal"
"syscall"
"filippo.io/edwards25519/field"
"github.com/charmbracelet/x/term"
"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
}
func promptSSHKeyPassphrase(privKeyPath string) []byte {
fd := os.Stdin.Fd()
oldState, err := term.GetState(fd)
if err != nil {
fmt.Fprintf(os.Stderr, "eno: failed to get terminal state: %v\n", err)
return nil
}
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
defer signal.Stop(sigCh)
go func() {
<-sigCh
term.Restore(fd, oldState)
os.Exit(130)
}()
fmt.Fprintf(os.Stderr, "Enter passphrase for SSH key %s: ", privKeyPath)
passphrase, err := term.ReadPassword(fd)
fmt.Fprintln(os.Stderr)
if err != nil {
fmt.Fprintf(os.Stderr, "eno: failed to read passphrase: %v\n", err)
return nil
}
return passphrase
}
// 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")
}
|