Debian Codegraph @

agessh/agessh.go

raw symbols SCIP
1 // Copyright 2019 The age Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package agessh provides age.Identity and age.Recipient implementations of
6 // types "ssh-rsa" and "ssh-ed25519", which allow reusing existing SSH keys for
7 // encryption with age-encryption.org/v1.
8 //
9 // These recipient types should only be used for compatibility with existing
10 // keys, and native keys should be preferred otherwise.
11 //
12 // Note that these recipient types are not anonymous: the encrypted message will
13 // include a short 32-bit ID of the public key.
14 package agessh
15
16 import (
17 "crypto/ed25519"
18 "crypto/rand"
19 "crypto/rsa"
20 "crypto/sha256"
21 "crypto/sha512"
22 "errors"
23 "fmt"
24 "io"
25
26 "filippo.io/age"
27 "filippo.io/age/internal/format"
28 "filippo.io/edwards25519"
29 "golang.org/x/crypto/chacha20poly1305"
30 "golang.org/x/crypto/curve25519"
31 "golang.org/x/crypto/hkdf"
32 "golang.org/x/crypto/ssh"
33 )
34
35 func sshFingerprint(pk ssh.PublicKey) string {
36 h := sha256.Sum256(pk.Marshal())
37 return format.EncodeToString(h[:4])
38 }
39
40 const oaepLabel = "age-encryption.org/v1/ssh-rsa"
41
42 type RSARecipient struct {
43 sshKey ssh.PublicKey
44 pubKey *rsa.PublicKey
45 }
46
47 var _ age.Recipient = &RSARecipient{}
48
49 func NewRSARecipient(pk ssh.PublicKey) (*RSARecipient, error) {
50 if pk.Type() != "ssh-rsa" {
51 return nil, errors.New("SSH public key is not an RSA key")
52 }
53 r := &RSARecipient{
54 sshKey: pk,
55 }
56
57 if pk, ok := pk.(ssh.CryptoPublicKey); ok {
58 if pk, ok := pk.CryptoPublicKey().(*rsa.PublicKey); ok {
59 r.pubKey = pk
60 } else {
61 return nil, errors.New("unexpected public key type")
62 }
63 } else {
64 return nil, errors.New("pk does not implement ssh.CryptoPublicKey")
65 }
66 if r.pubKey.N.BitLen() < 2048 {
67 return nil, errors.New("RSA key size is too small")
68 }
69 return r, nil
70 }
71
72 func (r *RSARecipient) Wrap(fileKey []byte) ([]*age.Stanza, error) {
73 if r.pubKey.N.BitLen() < 2048 {
74 return nil, errors.New("RSA key size is too small")
75 }
76 l := &age.Stanza{
77 Type: "ssh-rsa",
78 Args: []string{sshFingerprint(r.sshKey)},
79 }
80
81 wrappedKey, err := rsa.EncryptOAEP(sha256.New(), rand.Reader,
82 r.pubKey, fileKey, []byte(oaepLabel))
83 if err != nil {
84 return nil, err
85 }
86 l.Body = wrappedKey
87
88 return []*age.Stanza{l}, nil
89 }
90
91 type RSAIdentity struct {
92 k *rsa.PrivateKey
93 sshKey ssh.PublicKey
94 }
95
96 var _ age.Identity = &RSAIdentity{}
97
98 func NewRSAIdentity(key *rsa.PrivateKey) (*RSAIdentity, error) {
99 s, err := ssh.NewSignerFromKey(key)
100 if err != nil {
101 return nil, err
102 }
103 i := &RSAIdentity{
104 k: key, sshKey: s.PublicKey(),
105 }
106 return i, nil
107 }
108
109 func (i *RSAIdentity) Recipient() *RSARecipient {
110 return &RSARecipient{
111 sshKey: i.sshKey,
112 pubKey: &i.k.PublicKey,
113 }
114 }
115
116 func (i *RSAIdentity) Unwrap(stanzas []*age.Stanza) ([]byte, error) {
117 return multiUnwrap(i.unwrap, stanzas)
118 }
119
120 func (i *RSAIdentity) unwrap(block *age.Stanza) ([]byte, error) {
121 if block.Type != "ssh-rsa" {
122 return nil, age.ErrIncorrectIdentity
123 }
124 if len(block.Args) != 1 {
125 return nil, errors.New("invalid ssh-rsa recipient block")
126 }
127
128 if block.Args[0] != sshFingerprint(i.sshKey) {
129 return nil, age.ErrIncorrectIdentity
130 }
131
132 fileKey, err := rsa.DecryptOAEP(sha256.New(), rand.Reader, i.k,
133 block.Body, []byte(oaepLabel))
134 if err != nil {
135 // The fingerprint is only a short hint, and might collide with the
136 // fingerprint of a different recipient.
137 return nil, age.ErrIncorrectIdentity
138 }
139 return fileKey, nil
140 }
141
142 type Ed25519Recipient struct {
143 sshKey ssh.PublicKey
144 theirPublicKey []byte
145 }
146
147 var _ age.Recipient = &Ed25519Recipient{}
148
149 func NewEd25519Recipient(pk ssh.PublicKey) (*Ed25519Recipient, error) {
150 if pk.Type() != "ssh-ed25519" {
151 return nil, errors.New("SSH public key is not an Ed25519 key")
152 }
153
154 cpk, ok := pk.(ssh.CryptoPublicKey)
155 if !ok {
156 return nil, errors.New("pk does not implement ssh.CryptoPublicKey")
157 }
158 epk, ok := cpk.CryptoPublicKey().(ed25519.PublicKey)
159 if !ok {
160 return nil, errors.New("unexpected public key type")
161 }
162 mpk, err := ed25519PublicKeyToCurve25519(epk)
163 if err != nil {
164 return nil, fmt.Errorf("invalid Ed25519 public key: %v", err)
165 }
166
167 return &Ed25519Recipient{
168 sshKey: pk,
169 theirPublicKey: mpk,
170 }, nil
171 }
172
173 func ParseRecipient(s string) (age.Recipient, error) {
174 pubKey, _, _, _, err := ssh.ParseAuthorizedKey([]byte(s))
175 if err != nil {
176 return nil, fmt.Errorf("malformed SSH recipient: %q: %v", s, err)
177 }
178
179 var r age.Recipient
180 switch t := pubKey.Type(); t {
181 case "ssh-rsa":
182 r, err = NewRSARecipient(pubKey)
183 case "ssh-ed25519":
184 r, err = NewEd25519Recipient(pubKey)
185 default:
186 return nil, fmt.Errorf("unknown SSH recipient type: %q", t)
187 }
188 if err != nil {
189 return nil, fmt.Errorf("malformed SSH recipient: %q: %v", s, err)
190 }
191
192 return r, nil
193 }
194
195 func ed25519PublicKeyToCurve25519(pk ed25519.PublicKey) ([]byte, error) {
196 // See https://blog.filippo.io/using-ed25519-keys-for-encryption and
197 // https://pkg.go.dev/filippo.io/edwards25519#Point.BytesMontgomery.
198 p, err := new(edwards25519.Point).SetBytes(pk)
199 if err != nil {
200 return nil, err
201 }
202 return p.BytesMontgomery(), nil
203 }
204
205 const ed25519Label = "age-encryption.org/v1/ssh-ed25519"
206
207 func (r *Ed25519Recipient) Wrap(fileKey []byte) ([]*age.Stanza, error) {
208 ephemeral := make([]byte, curve25519.ScalarSize)
209 if _, err := rand.Read(ephemeral); err != nil {
210 return nil, err
211 }
212 ourPublicKey, err := curve25519.X25519(ephemeral, curve25519.Basepoint)
213 if err != nil {
214 return nil, err
215 }
216
217 sharedSecret, err := curve25519.X25519(ephemeral, r.theirPublicKey)
218 if err != nil {
219 return nil, err
220 }
221
222 tweak := make([]byte, curve25519.ScalarSize)
223 tH := hkdf.New(sha256.New, nil, r.sshKey.Marshal(), []byte(ed25519Label))
224 if _, err := io.ReadFull(tH, tweak); err != nil {
225 return nil, err
226 }
227 sharedSecret, _ = curve25519.X25519(tweak, sharedSecret)
228
229 l := &age.Stanza{
230 Type: "ssh-ed25519",
231 Args: []string{sshFingerprint(r.sshKey),
232 format.EncodeToString(ourPublicKey[:])},
233 }
234
235 salt := make([]byte, 0, len(ourPublicKey)+len(r.theirPublicKey))
236 salt = append(salt, ourPublicKey...)
237 salt = append(salt, r.theirPublicKey...)
238 h := hkdf.New(sha256.New, sharedSecret, salt, []byte(ed25519Label))
239 wrappingKey := make([]byte, chacha20poly1305.KeySize)
240 if _, err := io.ReadFull(h, wrappingKey); err != nil {
241 return nil, err
242 }
243
244 wrappedKey, err := aeadEncrypt(wrappingKey, fileKey)
245 if err != nil {
246 return nil, err
247 }
248 l.Body = wrappedKey
249
250 return []*age.Stanza{l}, nil
251 }
252
253 type Ed25519Identity struct {
254 secretKey, ourPublicKey []byte
255 sshKey ssh.PublicKey
256 }
257
258 var _ age.Identity = &Ed25519Identity{}
259
260 func NewEd25519Identity(key ed25519.PrivateKey) (*Ed25519Identity, error) {
261 s, err := ssh.NewSignerFromKey(key)
262 if err != nil {
263 return nil, err
264 }
265 i := &Ed25519Identity{
266 sshKey: s.PublicKey(),
267 secretKey: ed25519PrivateKeyToCurve25519(key),
268 }
269 i.ourPublicKey, _ = curve25519.X25519(i.secretKey, curve25519.Basepoint)
270 return i, nil
271 }
272
273 func ParseIdentity(pemBytes []byte) (age.Identity, error) {
274 k, err := ssh.ParseRawPrivateKey(pemBytes)
275 if err != nil {
276 return nil, err
277 }
278
279 switch k := k.(type) {
280 case *ed25519.PrivateKey:
281 return NewEd25519Identity(*k)
282 // ParseRawPrivateKey returns inconsistent types. See Issue 429.
283 case ed25519.PrivateKey:
284 return NewEd25519Identity(k)
285 case *rsa.PrivateKey:
286 return NewRSAIdentity(k)
287 }
288
289 return nil, fmt.Errorf("unsupported SSH identity type: %T", k)
290 }
291
292 func ed25519PrivateKeyToCurve25519(pk ed25519.PrivateKey) []byte {
293 h := sha512.New()
294 h.Write(pk.Seed())
295 out := h.Sum(nil)
296 return out[:curve25519.ScalarSize]
297 }
298
299 func (i *Ed25519Identity) Recipient() *Ed25519Recipient {
300 return &Ed25519Recipient{
301 sshKey: i.sshKey,
302 theirPublicKey: i.ourPublicKey,
303 }
304 }
305
306 func (i *Ed25519Identity) Unwrap(stanzas []*age.Stanza) ([]byte, error) {
307 return multiUnwrap(i.unwrap, stanzas)
308 }
309
310 func (i *Ed25519Identity) unwrap(block *age.Stanza) ([]byte, error) {
311 if block.Type != "ssh-ed25519" {
312 return nil, age.ErrIncorrectIdentity
313 }
314 if len(block.Args) != 2 {
315 return nil, errors.New("invalid ssh-ed25519 recipient block")
316 }
317 publicKey, err := format.DecodeString(block.Args[1])
318 if err != nil {
319 return nil, fmt.Errorf("failed to parse ssh-ed25519 recipient: %v", err)
320 }
321 if len(publicKey) != curve25519.PointSize {
322 return nil, errors.New("invalid ssh-ed25519 recipient block")
323 }
324
325 if block.Args[0] != sshFingerprint(i.sshKey) {
326 return nil, age.ErrIncorrectIdentity
327 }
328
329 sharedSecret, err := curve25519.X25519(i.secretKey, publicKey)
330 if err != nil {
331 return nil, fmt.Errorf("invalid X25519 recipient: %v", err)
332 }
333
334 tweak := make([]byte, curve25519.ScalarSize)
335 tH := hkdf.New(sha256.New, nil, i.sshKey.Marshal(), []byte(ed25519Label))
336 if _, err := io.ReadFull(tH, tweak); err != nil {
337 return nil, err
338 }
339 sharedSecret, _ = curve25519.X25519(tweak, sharedSecret)
340
341 salt := make([]byte, 0, len(publicKey)+len(i.ourPublicKey))
342 salt = append(salt, publicKey...)
343 salt = append(salt, i.ourPublicKey...)
344 h := hkdf.New(sha256.New, sharedSecret, salt, []byte(ed25519Label))
345 wrappingKey := make([]byte, chacha20poly1305.KeySize)
346 if _, err := io.ReadFull(h, wrappingKey); err != nil {
347 return nil, err
348 }
349
350 fileKey, err := aeadDecrypt(wrappingKey, block.Body)
351 if err != nil {
352 // The fingerprint is only a short hint, and might collide with the
353 // fingerprint of a different recipient.
354 return nil, age.ErrIncorrectIdentity
355 }
356 return fileKey, nil
357 }
358
359 // multiUnwrap is copied from package age. It's a helper that implements
360 // Identity.Unwrap in terms of a function that unwraps a single recipient
361 // stanza.
362 func multiUnwrap(unwrap func(*age.Stanza) ([]byte, error), stanzas []*age.Stanza) ([]byte, error) {
363 for _, s := range stanzas {
364 fileKey, err := unwrap(s)
365 if errors.Is(err, age.ErrIncorrectIdentity) {
366 // If we ever start returning something interesting wrapping
367 // ErrIncorrectIdentity, we should let it make its way up through
368 // Decrypt into NoIdentityMatchError.Errors.
369 continue
370 }
371 if err != nil {
372 return nil, err
373 }
374 return fileKey, nil
375 }
376 return nil, age.ErrIncorrectIdentity
377 }
378
379 // aeadEncrypt and aeadDecrypt are copied from package age.
380 //
381 // They don't limit the file key size because multi-key attacks are irrelevant
382 // against the ssh-ed25519 recipient. Being an asymmetric recipient, it would
383 // only allow a more efficient search for accepted public keys against a
384 // decryption oracle, but the ssh-X recipients are not anonymous (they have a
385 // short recipient hash).
386
387 func aeadEncrypt(key, plaintext []byte) ([]byte, error) {
388 aead, err := chacha20poly1305.New(key)
389 if err != nil {
390 return nil, err
391 }
392 nonce := make([]byte, chacha20poly1305.NonceSize)
393 return aead.Seal(nil, nonce, plaintext, nil), nil
394 }
395
396 func aeadDecrypt(key, ciphertext []byte) ([]byte, error) {
397 aead, err := chacha20poly1305.New(key)
398 if err != nil {
399 return nil, err
400 }
401 nonce := make([]byte, chacha20poly1305.NonceSize)
402 return aead.Open(nil, nonce, ciphertext, nil)
403 }