/
writer.go
356 lines (311 loc) · 8.14 KB
/
writer.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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
//
// Copyright (c) 2015-2022 MinIO, Inc.
//
// This file is part of MinIO Object Storage stack
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
package estream
import (
"bytes"
crand "crypto/rand"
"crypto/rsa"
"crypto/sha512"
"crypto/x509"
"encoding/binary"
"errors"
"io"
"math"
"github.com/cespare/xxhash/v2"
"github.com/secure-io/sio-go"
"github.com/tinylib/msgp/msgp"
)
// Writer provides a stream writer.
// Streams can optionally be encrypted.
// All streams have checksum verification.
type Writer struct {
up io.Writer
err error
key *[32]byte
bw blockWriter
nonce uint64
}
const (
writerMajorVersion = 2
writerMinorVersion = 1
)
// NewWriter will return a writer that allows to add encrypted and non-encrypted data streams.
func NewWriter(w io.Writer) *Writer {
_, err := w.Write([]byte{writerMajorVersion, writerMinorVersion})
writer := &Writer{err: err, up: w}
writer.bw.init(w)
return writer
}
// Close will flush and close the output stream.
func (w *Writer) Close() error {
if w.err != nil {
return w.err
}
w.addBlock(blockEOF)
return w.sendBlock()
}
// AddKeyEncrypted will create a new encryption key and add it to the stream.
// The key will be encrypted with the public key provided.
// All following files will be encrypted with this key.
func (w *Writer) AddKeyEncrypted(publicKey *rsa.PublicKey) error {
if w.err != nil {
return w.err
}
var key [32]byte
_, err := io.ReadFull(crand.Reader, key[:])
if err != nil {
return w.setErr(err)
}
w.key = &key
cipherKey, err := rsa.EncryptOAEP(sha512.New(), crand.Reader, publicKey, key[:], nil)
if err != nil {
return w.setErr(err)
}
mw := w.addBlock(blockEncryptedKey)
// Write public key...
if err := mw.WriteBytes(x509.MarshalPKCS1PublicKey(publicKey)); err != nil {
return w.setErr(err)
}
// Write encrypted cipher key
w.setErr(mw.WriteBytes(cipherKey))
return w.sendBlock()
}
// AddKeyPlain will create a new encryption key and add it to the stream.
// The key will be stored without any encryption.
// All calls to AddEncryptedStream will use this key
func (w *Writer) AddKeyPlain() error {
if w.err != nil {
return w.err
}
var key [32]byte
_, err := io.ReadFull(crand.Reader, key[:])
if err != nil {
return w.setErr(err)
}
w.key = &key
mw := w.addBlock(blockPlainKey)
w.setErr(mw.WriteBytes(key[:]))
return w.sendBlock()
}
// AddError will indicate the writer encountered an error
// and the reader should abort the stream.
// The message will be returned as an error.
func (w *Writer) AddError(msg string) error {
if w.err != nil {
return w.err
}
mw := w.addBlock(blockError)
w.setErr(mw.WriteString(msg))
return w.sendBlock()
}
// AddUnencryptedStream adds a named stream.
// Extra data can be added, which is added without encryption or checksums.
func (w *Writer) AddUnencryptedStream(name string, extra []byte) (io.WriteCloser, error) {
if w.err != nil {
return nil, w.err
}
mw := w.addBlock(blockPlainStream)
// Write metadata...
w.setErr(mw.WriteString(name))
w.setErr(mw.WriteBytes(extra))
w.setErr(mw.WriteUint8(uint8(checksumTypeXxhash)))
if err := w.sendBlock(); err != nil {
return nil, err
}
return w.newStreamWriter(), nil
}
// AddEncryptedStream adds a named encrypted stream.
// AddKeyEncrypted must have been called before this, but
// multiple streams can safely use the same key.
// Extra data can be added, which is added without encryption or checksums.
func (w *Writer) AddEncryptedStream(name string, extra []byte) (io.WriteCloser, error) {
if w.err != nil {
return nil, w.err
}
if w.key == nil {
return nil, errors.New("AddEncryptedStream: No key on stream")
}
mw := w.addBlock(blockEncStream)
// Write metadata...
w.setErr(mw.WriteString(name))
w.setErr(mw.WriteBytes(extra))
w.setErr(mw.WriteUint8(uint8(checksumTypeXxhash)))
stream, err := sio.AES_256_GCM.Stream(w.key[:])
if err != nil {
return nil, w.setErr(err)
}
// Get nonce for stream.
nonce := make([]byte, stream.NonceSize())
binary.LittleEndian.PutUint64(nonce, w.nonce)
w.nonce++
// Write nonce as bin array.
w.setErr(mw.WriteBytes(nonce))
if err := w.sendBlock(); err != nil {
return nil, err
}
// Send output as blocks.
sw := w.newStreamWriter()
encw := stream.EncryptWriter(sw, nonce, nil)
return &closeWrapper{
up: encw,
after: func() error {
return sw.Close()
},
}, nil
}
// addBlock initializes a new block.
// Block content should be written to the returned writer.
// When done call sendBlock.
func (w *Writer) addBlock(id blockID) *msgp.Writer {
return w.bw.newBlock(id)
}
// sendBlock sends the queued block.
func (w *Writer) sendBlock() error {
if w.err != nil {
return w.err
}
return w.setErr(w.bw.send())
}
// newStreamWriter creates a new stream writer
func (w *Writer) newStreamWriter() *streamWriter {
sw := &streamWriter{w: w}
sw.h.Reset()
return sw
}
// setErr will set a stateful error on w.
// If an error has already been set that is returned instead.
func (w *Writer) setErr(err error) error {
if w.err != nil {
return w.err
}
if err == nil {
return err
}
w.err = err
return err
}
// streamWriter will send each individual write as a block on stream.
// Close must be called when writes have completed to send hashes.
type streamWriter struct {
w *Writer
h xxhash.Digest
eosWritten bool
}
// Write satisfies the io.Writer interface.
// Each write is sent as a separate block.
func (w *streamWriter) Write(b []byte) (int, error) {
mw := w.w.addBlock(blockDatablock)
// Update hash.
w.h.Write(b)
// Write as messagepack bin array.
if err := mw.WriteBytes(b); err != nil {
return 0, w.w.setErr(err)
}
// Write data as binary array.
return len(b), w.w.sendBlock()
}
// Close satisfies the io.Closer interface.
func (w *streamWriter) Close() error {
// Write EOS only once.
if !w.eosWritten {
mw := w.w.addBlock(blockEOS)
sum := w.h.Sum(nil)
w.w.setErr(mw.WriteBytes(sum))
w.eosWritten = true
return w.w.sendBlock()
}
return nil
}
type closeWrapper struct {
before, after func() error
up io.WriteCloser
}
func (w *closeWrapper) Write(b []byte) (int, error) {
return w.up.Write(b)
}
// Close satisfies the io.Closer interface.
func (w *closeWrapper) Close() error {
if w.before != nil {
if err := w.before(); err != nil {
return err
}
w.before = nil
}
if w.up != nil {
if err := w.up.Close(); err != nil {
return err
}
w.up = nil
}
if w.after != nil {
if err := w.after(); err != nil {
return err
}
w.after = nil
}
return nil
}
type blockWriter struct {
id blockID
w io.Writer
wr *msgp.Writer
buf bytes.Buffer
hdr [8 + 5]byte
}
// init the blockwriter
// blocks will be written to w.
func (b *blockWriter) init(w io.Writer) {
b.w = w
b.buf.Grow(1 << 10)
b.buf.Reset()
b.wr = msgp.NewWriter(&b.buf)
}
// newBlock starts a new block with the specified id.
// Content should be written to the returned writer.
func (b *blockWriter) newBlock(id blockID) *msgp.Writer {
b.id = id
b.buf.Reset()
b.wr.Reset(&b.buf)
return b.wr
}
func (b *blockWriter) send() error {
if b.id == 0 {
return errors.New("blockWriter: no block started")
}
// Flush block data into b.buf
if err := b.wr.Flush(); err != nil {
return err
}
// Add block id
hdr := msgp.AppendInt8(b.hdr[:0], int8(b.id))
if uint32(b.buf.Len()) > math.MaxUint32 {
return errors.New("max block size exceeded")
}
// Add block length.
hdr = msgp.AppendUint32(hdr, uint32(b.buf.Len()))
if _, err := b.w.Write(hdr); err != nil {
return err
}
// Write block.
_, err := b.w.Write(b.buf.Bytes())
// Reset for new block.
b.buf.Reset()
b.id = 0
return err
}