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
|
package crypt
import (
"bytes"
"crypto/ed25519"
"fmt"
"golang.org/x/crypto/ssh"
)
// Re-wraps the note key for new recipients, replacing only the caller's wrapped key.
func RekeySSH(inputBytes []byte, privKeyPath string, newPubKeys [][]byte) ([]byte, error) {
headers, ciphertext, err := ParseFileHeaders(inputBytes)
if err != nil {
return nil, fmt.Errorf("rekey: %w", err)
}
if headers.Auth != SSH {
return nil, fmt.Errorf("rekey: expected SSH auth, got %s", headers.Auth)
}
if len(newPubKeys) == 0 {
return nil, fmt.Errorf("rekey: at least one recipient public key is required")
}
edPriv, pemBytes, err := parsePrivateKeyFile(privKeyPath)
if err != nil {
return nil, fmt.Errorf("rekey: %w", err)
}
defer clear(pemBytes)
pubKey := edPriv.Public().(ed25519.PublicKey)
sshPub, err := ssh.NewPublicKey(pubKey)
if err != nil {
return nil, fmt.Errorf("rekey: derive SSH pub key: %w", err)
}
ownPubKeyBytes := ssh.MarshalAuthorizedKey(sshPub)
var noteKey []byte
remaining := make([]WrappedKey, 0, len(headers.Recipients))
for _, recipient := range headers.Recipients {
if bytes.Equal(recipient.PubKeyBytes, ownPubKeyBytes) {
noteKey, err = unwrapNoteKeyWithKey(recipient, edPriv)
if err != nil {
return nil, fmt.Errorf("rekey: failed to unwrap note key: %w", err)
}
continue
}
remaining = append(remaining, recipient)
}
if noteKey == nil {
return nil, fmt.Errorf("rekey: no matching recipient found")
}
defer clear(noteKey)
newRecipients, err := WrapNoteKeyForRecipients(noteKey, newPubKeys)
if err != nil {
return nil, fmt.Errorf("rekey: %w", err)
}
if len(remaining)+len(newRecipients) == 0 {
return nil, fmt.Errorf("rekey: at least one recipient is required")
}
headers.Recipients = append(remaining, newRecipients...)
packed, err := packFile(headers, ciphertext)
if err != nil {
return nil, fmt.Errorf("rekey: %w", err)
}
return packed, nil
}
|