-
Notifications
You must be signed in to change notification settings - Fork 64
/
signcrypt_open.go
290 lines (251 loc) · 8.5 KB
/
signcrypt_open.go
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.
package saltpack
import (
"bytes"
"crypto/hmac"
"crypto/sha512"
"io"
"golang.org/x/crypto/ed25519"
"golang.org/x/crypto/nacl/secretbox"
)
type signcryptOpenStream struct {
mps *msgpackStream
payloadKey *SymmetricKey
signingPublicKey SigningPublicKey
senderAnonymous bool
headerHash headerHash
keyring SigncryptKeyring
resolver SymmetricKeyResolver
}
func (sos *signcryptOpenStream) getNextChunk() ([]byte, error) {
var sb signcryptionBlock
seqno, err := sos.mps.Read(&sb)
if err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
chunk, err := sos.processBlock(sb.PayloadCiphertext, sb.IsFinal, seqno)
if err != nil {
return nil, err
}
err = checkDecodedChunkState(Version2(), chunk, seqno, sb.IsFinal)
if err != nil {
return nil, err
}
if sb.IsFinal {
return chunk, assertEndOfStream(sos.mps)
}
return chunk, nil
}
func (sos *signcryptOpenStream) readHeader() error {
// Read the header bytes.
headerBytes := []byte{}
_, err := sos.mps.Read(&headerBytes)
if err != nil {
return ErrFailedToReadHeaderBytes
}
// Compute the header hash.
sos.headerHash = sha512.Sum512(headerBytes)
// Parse the header bytes.
var header SigncryptionHeader
err = decodeFromBytes(&header, headerBytes)
if err != nil {
return err
}
err = sos.processHeader(&header)
if err != nil {
return err
}
return nil
}
func (sos *signcryptOpenStream) tryBoxSecretKeys(hdr *SigncryptionHeader, ephemeralPub BoxPublicKey) (*SymmetricKey, error) {
derivedKeys := []*SymmetricKey{}
for _, receiverBoxSecretKey := range sos.keyring.GetAllBoxSecretKeys() {
derivedKey := derivedEphemeralKeyFromBoxKeys(ephemeralPub, receiverBoxSecretKey)
derivedKeys = append(derivedKeys, derivedKey)
}
// Try each of the box secret keys against each of the receiver pairs in
// the message header. The actual expected number of box secret keys is
// one, so this shouldn't be as quadratic as it looks.
for receiverIndex, receiver := range hdr.Receivers {
for _, derivedKey := range derivedKeys {
identifier := keyIdentifierFromDerivedKey(derivedKey, uint64(receiverIndex))
if hmac.Equal(identifier, receiver.ReceiverKID) {
// This is the right key! Open the sender secretbox and return the sender key.
nonce := nonceForPayloadKeyBoxV2(uint64(receiverIndex))
payloadKey, isValid := secretbox.Open(
nil,
receiver.PayloadKeyBox,
(*[24]byte)(&nonce),
(*[32]byte)(derivedKey))
if !isValid {
return nil, ErrDecryptionFailed
}
return symmetricKeyFromSlice(payloadKey)
}
}
}
// None of the box keys worked. We'll fall back to the secretbox keys.
return nil, nil
}
func (sos *signcryptOpenStream) trySharedSymmetricKeys(hdr *SigncryptionHeader, ephemeralPub BoxPublicKey) (*SymmetricKey, error) {
identifiers := [][]byte{}
for _, receiver := range hdr.Receivers {
identifiers = append(identifiers, receiver.ReceiverKID)
}
if sos.resolver == nil {
return nil, nil
}
resolvedKeys, err := sos.resolver.ResolveKeys(identifiers)
if err != nil {
return nil, err
}
if len(resolvedKeys) != len(identifiers) {
return nil, ErrWrongNumberOfKeys
}
for index, resolved := range resolvedKeys {
if resolved == nil {
// This key didn't resolve.
continue
}
// We got a key. It should decrypt the corresponding receiver secretbox.
derivedKeyDigest := hmac.New(sha512.New, []byte(signcryptionSymmetricKeyContext))
_, err = derivedKeyDigest.Write(ephemeralPub.ToKID())
if err != nil {
return nil, err
}
_, err = derivedKeyDigest.Write(resolved[:])
if err != nil {
return nil, err
}
derivedKey, err := rawBoxKeyFromSlice(derivedKeyDigest.Sum(nil)[0:32])
if err != nil {
panic(err) // should be statically impossible, if the slice above is the right length
}
nonce := nonceForPayloadKeyBoxV2(uint64(index))
payloadKey, isValid := secretbox.Open(
nil,
hdr.Receivers[index].PayloadKeyBox,
(*[24]byte)(&nonce),
(*[32]byte)(derivedKey))
if !isValid {
return nil, ErrDecryptionFailed
}
return symmetricKeyFromSlice(payloadKey)
}
// If we get out of the loop, all the resolved keys were nil (failed to resolve).
return nil, nil
}
func (sos *signcryptOpenStream) processHeader(hdr *SigncryptionHeader) error {
if err := hdr.validate(); err != nil {
return err
}
ephemeralPub := sos.keyring.ImportBoxEphemeralKey(hdr.Ephemeral)
var err error
sos.payloadKey, err = sos.tryBoxSecretKeys(hdr, ephemeralPub)
if err != nil {
return err
}
if sos.payloadKey == nil {
sos.payloadKey, err = sos.trySharedSymmetricKeys(hdr, ephemeralPub)
if err != nil {
return err
}
}
if sos.payloadKey == nil {
return ErrNoDecryptionKey
}
// Decrypt the sender's public key, and check for anonymous mode.
nonce := nonceForSenderKeySecretBox()
senderKeySlice, ok := secretbox.Open([]byte{}, hdr.SenderSecretbox, (*[24]byte)(&nonce), (*[32]byte)(sos.payloadKey))
if !ok {
return ErrBadSenderKeySecretbox
}
zeroSlice := make([]byte, len(senderKeySlice))
if bytes.Equal(zeroSlice, senderKeySlice) {
// anonymous mode, an all zero sender signing public key
sos.senderAnonymous = true
} else {
// regular mode, with a real signing public key
spk := sos.keyring.LookupSigningPublicKey(senderKeySlice)
if spk == nil {
return ErrNoSenderKey{Sender: senderKeySlice}
}
sos.signingPublicKey = spk
}
return nil
}
func (sos *signcryptOpenStream) processBlock(payloadCiphertext []byte, isFinal bool, seqno packetSeqno) ([]byte, error) {
blockNum := encryptionBlockNumber(seqno - 1)
if err := blockNum.check(); err != nil {
return nil, err
}
nonce := nonceForChunkSigncryption(sos.headerHash, isFinal, blockNum)
attachedSig, isValid := secretbox.Open([]byte{}, payloadCiphertext, (*[24]byte)(&nonce), (*[32]byte)(sos.payloadKey))
if !isValid || len(attachedSig) < ed25519.SignatureSize {
return nil, ErrBadCiphertext(seqno)
}
detachedSig := sliceToByte64(attachedSig[:ed25519.SignatureSize])
chunkPlaintext := attachedSig[ed25519.SignatureSize:]
// Handle anonymous sender mode by skipping signature verification. By
// convention the signature bytes are all zeroes, but here we ignore them.
if !sos.senderAnonymous {
signatureInput := computeSigncryptionSignatureInput(sos.headerHash, nonce, isFinal, chunkPlaintext)
sigErr := sos.signingPublicKey.Verify(signatureInput, detachedSig[:])
if sigErr != nil {
return nil, ErrBadSignature
}
}
return chunkPlaintext, nil
}
// NewSigncryptOpenStream starts a streaming verification and decryption. It
// synchronously ingests and parses the given Reader's encryption header. It
// consults the passed keyring for the decryption keys needed to decrypt the
// message. On failure, it returns a null Reader and an error message. On
// success, it returns a Reader with the plaintext stream, and a nil error. In
// either case, it will return a `MessageKeyInfo` which tells about who the
// sender was, and which of the Receiver's keys was used to decrypt the
// message.
//
// Note that the caller has an opportunity not to ingest the plaintext if he
// doesn't trust the sender revealed in the MessageKeyInfo.
func NewSigncryptOpenStream(r io.Reader, keyring SigncryptKeyring, resolver SymmetricKeyResolver) (senderPub SigningPublicKey, plaintext io.Reader, err error) {
sos := &signcryptOpenStream{
mps: newMsgpackStream(r),
keyring: keyring,
resolver: resolver,
}
err = sos.readHeader()
if err != nil {
return nil, nil, err
}
return sos.signingPublicKey, newChunkReader(sos), nil
}
// SymmetricKeyResolver is an interface for resolving identifiers to keys.
type SymmetricKeyResolver interface {
ResolveKeys(identifiers [][]byte) ([]*SymmetricKey, error)
}
// SigncryptOpen simply opens a ciphertext given the set of keys in the specified keyring.
// It returns a plaintext on sucess, and an error on failure. It returns the header's
// MessageKeyInfo in either case.
func SigncryptOpen(ciphertext []byte, keyring SigncryptKeyring, resolver SymmetricKeyResolver) (senderPub SigningPublicKey, plaintext []byte, err error) {
buf := bytes.NewBuffer(ciphertext)
senderPub, plaintextStream, err := NewSigncryptOpenStream(buf, keyring, resolver)
if err != nil {
return senderPub, nil, err
}
ret, err := io.ReadAll(plaintextStream)
if err != nil {
return nil, nil, err
}
return senderPub, ret, err
}
// SigncryptKeyring is a combination of the Keyring and SigKeyring
// interfaces.
type SigncryptKeyring interface {
Keyring
SigKeyring
}