-
Notifications
You must be signed in to change notification settings - Fork 64
/
common.go
278 lines (235 loc) · 7.84 KB
/
common.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
// 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"
"encoding/binary"
"fmt"
"github.com/keybase/go-codec/codec"
"golang.org/x/crypto/chacha20poly1305"
)
// maxReceiverCount is the maximum number of receivers allowed
// for a single encrypted saltpack message, which is the maximum length
// of a msgpack array.
const maxReceiverCount = (1 << 32) - 1
// encryptionBlockNumber describes which block number we're at in the sequence
// of encrypted blocks. Each encrypted block of course fits into a packet.
type encryptionBlockNumber uint64
func codecHandle() *codec.MsgpackHandle {
var mh codec.MsgpackHandle
mh.WriteExt = true
return &mh
}
func (e encryptionBlockNumber) check() error {
if e >= encryptionBlockNumber(0xffffffffffffffff) {
return ErrPacketOverflow
}
return nil
}
// assertEndOfStream reads from stream, and converts a nil error into
// ErrTrailingGarbage. Thus, it always returns a non-nil error. This
// should be used in a context where io.EOF is expected, and anything
// else is an error.
func assertEndOfStream(stream *msgpackStream) error {
var i interface{}
_, err := stream.Read(&i)
if err == nil {
err = ErrTrailingGarbage
}
return err
}
type headerHash [sha512.Size]byte
func attachedSignatureInput(version Version, headerHash headerHash, payloadChunk []byte, seqno packetSeqno, isFinal bool) []byte {
hasher := sha512.New()
_, _ = hasher.Write(headerHash[:])
_ = binary.Write(hasher, binary.BigEndian, seqno)
switch version.Major {
case 1:
// Nothing to do.
case 2:
var isFinalByte byte
if isFinal {
isFinalByte = 1
}
_, _ = hasher.Write([]byte{isFinalByte})
default:
panic(ErrBadVersion{version})
}
_, _ = hasher.Write(payloadChunk)
var buf bytes.Buffer
_, _ = buf.Write([]byte(signatureAttachedString))
_, _ = buf.Write(hasher.Sum(nil))
return buf.Bytes()
}
func detachedSignatureInput(headerHash headerHash, plaintext []byte) []byte {
hasher := sha512.New()
_, _ = hasher.Write(headerHash[:])
_, _ = hasher.Write(plaintext)
return detachedSignatureInputFromHash(hasher.Sum(nil))
}
func detachedSignatureInputFromHash(plaintextAndHeaderHash []byte) []byte {
var buf bytes.Buffer
_, _ = buf.Write([]byte(signatureDetachedString))
_, _ = buf.Write(plaintextAndHeaderHash)
return buf.Bytes()
}
func copyEqualSize(out, in []byte) {
if len(out) != len(in) {
panic(fmt.Sprintf("len(out)=%d != len(in)=%d", len(out), len(in)))
}
copy(out, in)
}
func copyEqualSizeStr(out []byte, in string) {
if len(out) != len(in) {
panic(fmt.Sprintf("len(out)=%d != len(in)=%d", len(out), len(in)))
}
copy(out, in)
}
func sliceToByte24(in []byte) [24]byte {
var out [24]byte
copyEqualSize(out[:], in)
return out
}
func stringToByte24(in string) [24]byte {
var out [24]byte
copyEqualSizeStr(out[:], in)
return out
}
func sliceToByte32(in []byte) [32]byte {
var out [32]byte
copyEqualSize(out[:], in)
return out
}
func sliceToByte64(in []byte) [64]byte {
var out [64]byte
copyEqualSize(out[:], in)
return out
}
type macKey [cryptoAuthKeyBytes]byte
type payloadHash [sha512.Size]byte
type payloadAuthenticator [cryptoAuthBytes]byte
func (pa payloadAuthenticator) Equal(other payloadAuthenticator) bool {
return hmac.Equal(pa[:], other[:])
}
func computePayloadAuthenticator(macKey macKey, payloadHash payloadHash) payloadAuthenticator {
// Equivalent to crypto_auth, but using Go's builtin HMAC. Truncates
// SHA512, instead of calling SHA512/256, which has different IVs.
authenticatorDigest := hmac.New(sha512.New, macKey[:])
_, _ = authenticatorDigest.Write(payloadHash[:])
fullMAC := authenticatorDigest.Sum(nil)
return sliceToByte32(fullMAC[:cryptoAuthBytes])
}
func computeMACKeySingle(secret BoxSecretKey, public BoxPublicKey, nonce Nonce) macKey {
macKeyBox := secret.Box(public, nonce, make([]byte, cryptoAuthKeyBytes))
return sliceToByte32(macKeyBox[chacha20poly1305.Overhead : chacha20poly1305.Overhead+cryptoAuthKeyBytes])
}
func sum512Truncate256(in []byte) [32]byte {
// Consistent with computePayloadAuthenticator in that it
// truncates SHA512 instead of calling SHA512/256, which has
// different IVs.
sum512 := sha512.Sum512(in)
return sliceToByte32(sum512[:32])
}
func computePayloadHash(version Version, headerHash headerHash, nonce Nonce, ciphertext []byte, isFinal bool) payloadHash {
payloadDigest := sha512.New()
_, _ = payloadDigest.Write(headerHash[:])
_, _ = payloadDigest.Write(nonce[:])
switch version.Major {
case 1:
// Nothing to do.
case 2:
var isFinalByte byte
if isFinal {
isFinalByte = 1
}
_, _ = payloadDigest.Write([]byte{isFinalByte})
default:
panic(ErrBadVersion{version})
}
_, _ = payloadDigest.Write(ciphertext)
h := payloadDigest.Sum(nil)
return sliceToByte64(h)
}
func computeSigncryptionSignatureInput(headerHash headerHash, nonce Nonce, isFinal bool, chunkPlaintext []byte) []byte {
signatureInput := []byte(signatureEncryptedString)
// This is a bit redundant, as the nonce already contains part
// of the header hash and the isFinal flag. However, we
// truncate the header hash pretty severely for the nonce, so
// it seems a bit safer to be redundant.
signatureInput = append(signatureInput, headerHash[:]...)
signatureInput = append(signatureInput, nonce[:]...)
var isFinalByte byte
if isFinal {
isFinalByte = 1
}
signatureInput = append(signatureInput, isFinalByte)
plaintextHash := sha512.Sum512(chunkPlaintext)
signatureInput = append(signatureInput, plaintextHash[:]...)
return signatureInput
}
func hashHeader(headerBytes []byte) headerHash {
return sha512.Sum512(headerBytes)
}
// VersionValidator is a function that takes a version and returns nil
// if it's a valid version, and an error otherwise.
type VersionValidator func(version Version) error
// CheckKnownMajorVersion returns nil if the given version has a known
// major version. You probably want to use this with NewDecryptStream,
// unless you want to restrict to specific versions only.
func CheckKnownMajorVersion(version Version) error {
for _, knownVersion := range KnownVersions() {
if version.Major == knownVersion.Major {
return nil
}
}
return ErrBadVersion{version}
}
// SingleVersionValidator returns a VersionValidator that returns nil
// if its given version is equal to desiredVersion.
func SingleVersionValidator(desiredVersion Version) VersionValidator {
return func(version Version) error {
if version == desiredVersion {
return nil
}
return ErrBadVersion{version}
}
}
func checkChunkState(version Version, chunkLen int, blockIndex uint64, isFinal bool) error {
switch version.Major {
case 1:
// For V1, we derive isFinal from the chunk length, so
// if there's a mismatch, that's a bug and not a
// stream error.
if (chunkLen == 0) != isFinal {
panic(fmt.Sprintf("chunkLen=%d and isFinal=%t", chunkLen, isFinal))
}
case 2:
// TODO: Ideally, we'd have tests exercising this case.
if (chunkLen == 0) && (blockIndex != 0 || !isFinal) {
return ErrUnexpectedEmptyBlock
}
default:
panic(ErrBadVersion{version})
}
return nil
}
// assertEncodedChunkState sanity-checks some encoded chunk parameters.
func assertEncodedChunkState(version Version, encodedChunk []byte, encodingOverhead int, blockIndex uint64, isFinal bool) {
if len(encodedChunk) < encodingOverhead {
panic("encodedChunk is too small")
}
err := checkChunkState(version, len(encodedChunk)-encodingOverhead, blockIndex, isFinal)
if err != nil {
panic(err)
}
}
// checkDecodedChunkState sanity-checks some decoded chunk
// parameters. A returned error means there's something wrong with the
// decoded stream.
func checkDecodedChunkState(version Version, chunk []byte, seqno packetSeqno, isFinal bool) error {
// The first decoded block has seqno 1, since the header bytes
// are decoded first.
return checkChunkState(version, len(chunk), uint64(seqno-1), isFinal)
}