gunk-dev/the-valley

sign.go

sourcebc00697b19b5main's published tip history
6.1 KiB
1package approval
2
3import (
4 "bytes"
5 "crypto/ed25519"
6 "encoding/base64"
7 "encoding/binary"
8 "encoding/pem"
9 "errors"
10 "fmt"
11
12 "the-valley/note"
13)
14
15// A Signer makes the raw Ed25519 signature over a statement's text with
16// one key: a software key (Key) or a YubiKey's PIV slot (PIVSession).
17type Signer interface {
18 Public() ed25519.PublicKey
19 Sign(text []byte) ([]byte, error)
20}
21
22// Sign signs a statement as its principal and seals it in a note: the
23// complete statement text, a blank line, and one signature line named by
24// the principal. The note is opened under the signer's own key before it
25// is returned, so a signer that signed something else, or with another
26// key, returns an error and no note.
27func Sign(s Statement, signer Signer) ([]byte, error) {
28 text, err := s.Encode()
29 if err != nil {
30 return nil, err
31 }
32 pub := signer.Public()
33 if len(pub) != ed25519.PublicKeySize {
34 return nil, errors.New("the signer holds no ed25519 public key")
35 }
36 sig, err := signer.Sign(text)
37 if err != nil {
38 return nil, err
39 }
40 if len(sig) != ed25519.SignatureSize {
41 return nil, fmt.Errorf("the signer returned %d bytes, not an ed25519 signature", len(sig))
42 }
43 var hash [4]byte
44 binary.BigEndian.PutUint32(hash[:], note.KeyHash(s.Principal, pub))
45 var b bytes.Buffer
46 b.Write(text)
47 b.WriteString("\n" + note.Mark + s.Principal + " ")
48 b.WriteString(base64.StdEncoding.EncodeToString(append(hash[:], sig...)))
49 b.WriteString("\n")
50 if _, _, err := note.Open(b.Bytes(), []note.VerifierKey{note.NewVerifierKey(s.Principal, pub)}); err != nil {
51 return nil, fmt.Errorf("the signature does not verify under the signer's own key: %w", err)
52 }
53 return b.Bytes(), nil
54}
55
56// ParseNote reads an approval note's form, without checking its signature:
57// at most MaxNote bytes, one signature line, and a statement in its written
58// form whose principal names that line. The statement it returns is what
59// the note claims; only Verify, under the keys a reader holds, says whether
60// the claim is true.
61func ParseNote(n []byte) (Statement, error) {
62 if len(n) > MaxNote {
63 return Statement{}, fmt.Errorf("the approval note is %d bytes; one holds at most %d", len(n), MaxNote)
64 }
65 text, sigs, err := note.Split(n)
66 if err != nil {
67 return Statement{}, err
68 }
69 if len(sigs) != 1 {
70 return Statement{}, fmt.Errorf("an approval note carries one signature, and this carries %d", len(sigs))
71 }
72 s, err := Parse(text)
73 if err != nil {
74 return Statement{}, fmt.Errorf("the signed text %w", err)
75 }
76 if sigs[0].Name != s.Principal {
77 return Statement{}, fmt.Errorf("the approval is signed with a key of %s, and names %s as its approver", sigs[0].Name, s.Principal)
78 }
79 return s, nil
80}
81
82// Verify opens an approval note under the approval keys a reader holds,
83// and returns the statement it carries. The note has ParseNote's form, and
84// its one signature is by a key among those keys.
85//
86// Which keys a reader holds decides which approvals count: the keys of
87// approval-signers, or of approval-signers-hardware when only hardware
88// keys may approve.
89func Verify(n []byte, authority []note.VerifierKey) (Statement, error) {
90 s, err := ParseNote(n)
91 if err != nil {
92 return Statement{}, err
93 }
94 if _, _, err := note.Open(n, authority); err != nil {
95 return Statement{}, err
96 }
97 return s, nil
98}
99
100// Key is a software approval key.
101type Key struct {
102 priv ed25519.PrivateKey
103}
104
105// NewKey is the software key with this private half.
106func NewKey(priv ed25519.PrivateKey) Key { return Key{priv: priv} }
107
108func (k Key) Public() ed25519.PublicKey { return k.priv.Public().(ed25519.PublicKey) }
109
110func (k Key) Sign(text []byte) ([]byte, error) { return ed25519.Sign(k.priv, text), nil }
111
112// ParseKey reads the unencrypted OpenSSH Ed25519 private key that
113// `ssh-keygen -t ed25519 -N ”` writes, as attest/sign.go reads a host's.
114// A key behind a passphrase is refused.
115func ParseKey(raw []byte) (Key, error) {
116 block, _ := pem.Decode(raw)
117 if block == nil || block.Type != "OPENSSH PRIVATE KEY" {
118 return Key{}, errors.New("not an openssh private key")
119 }
120 body := sshBytes{rest: block.Bytes}
121 magic := []byte("openssh-key-v1\x00")
122 if !bytes.HasPrefix(body.rest, magic) {
123 return Key{}, errors.New("not an openssh private key: the container is unrecognised")
124 }
125 body.rest = body.rest[len(magic):]
126 cipher, kdf := body.str(), body.str()
127 body.str() // the kdf options
128 count := body.u32()
129 body.str() // the public key, which the private section repeats
130 section := sshBytes{rest: body.str()}
131 if body.err != nil {
132 return Key{}, body.err
133 }
134 if string(cipher) != "none" || string(kdf) != "none" {
135 return Key{}, fmt.Errorf("the key is encrypted with %s; only an unencrypted key is read", cipher)
136 }
137 if count != 1 {
138 return Key{}, fmt.Errorf("the file holds %d keys, not one", count)
139 }
140 if a, b := section.u32(), section.u32(); a != b {
141 return Key{}, errors.New("the key is encrypted or damaged: its check words differ")
142 }
143 if kind := section.str(); string(kind) != "ssh-ed25519" {
144 return Key{}, fmt.Errorf("the key is %s, not ssh-ed25519", kind)
145 }
146 pub, priv := section.str(), section.str()
147 if section.err != nil {
148 return Key{}, section.err
149 }
150 if len(pub) != ed25519.PublicKeySize || len(priv) != ed25519.PrivateKeySize {
151 return Key{}, errors.New("the key is not the size an ed25519 key is")
152 }
153 key := ed25519.PrivateKey(priv)
154 if !bytes.Equal(key.Public().(ed25519.PublicKey), pub) {
155 return Key{}, errors.New("the key's private half does not produce its public half")
156 }
157 return Key{priv: key}, nil
158}
159
160// sshBytes reads the ssh wire encoding, where a string is a four-byte
161// big-endian length and that many bytes. The first error is kept and every
162// later read is a no-op.
163type sshBytes struct {
164 rest []byte
165 err error
166}
167
168func (s *sshBytes) u32() uint32 {
169 if s.err != nil {
170 return 0
171 }
172 if len(s.rest) < 4 {
173 s.err = errors.New("the key ends in the middle of a field")
174 return 0
175 }
176 v := binary.BigEndian.Uint32(s.rest)
177 s.rest = s.rest[4:]
178 return v
179}
180
181func (s *sshBytes) str() []byte {
182 n := s.u32()
183 if s.err != nil {
184 return nil
185 }
186 if uint64(n) > uint64(len(s.rest)) {
187 s.err = fmt.Errorf("the key claims a %d-byte field with %d bytes left", n, len(s.rest))
188 return nil
189 }
190 v := s.rest[:n]
191 s.rest = s.rest[n:]
192 return v
193}