-
Notifications
You must be signed in to change notification settings - Fork 125
/
buffer.go
697 lines (564 loc) · 17.1 KB
/
buffer.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
package memguard
import (
"bytes"
"io"
"os"
"unsafe"
"github.com/awnumar/memguard/core"
)
/*
LockedBuffer is a structure that holds raw sensitive data.
The number of LockedBuffers that you are able to create is limited by how much memory your system's kernel allows each process to mlock/VirtualLock. Therefore you should call Destroy on LockedBuffers that you no longer need or defer a Destroy call after creating a new LockedBuffer.
*/
type LockedBuffer struct {
*core.Buffer
}
// Constructs a LockedBuffer object from a core.Buffer while also setting up the finalizer for it.
func newBuffer(buf *core.Buffer) *LockedBuffer {
return &LockedBuffer{buf}
}
// Constructs a quasi-destroyed LockedBuffer with size zero.
func newNullBuffer() *LockedBuffer {
return &LockedBuffer{new(core.Buffer)}
}
/*
NewBuffer creates a mutable data container of the specified size.
*/
func NewBuffer(size int) *LockedBuffer {
// Construct a Buffer of the specified size.
buf, err := core.NewBuffer(size)
if err != nil {
return newNullBuffer()
}
// Construct and return the wrapped container object.
return newBuffer(buf)
}
/*
NewBufferFromBytes constructs an immutable buffer from a byte slice. The source buffer is wiped after the value has been copied over to the created container.
*/
func NewBufferFromBytes(src []byte) *LockedBuffer {
// Construct a buffer of the correct size.
b := NewBuffer(len(src))
if b.Size() == 0 {
return b
}
// Move the data over.
b.Move(src)
// Make the buffer immutable.
b.Freeze()
// Return the created Buffer object.
return b
}
/*
NewBufferFromReader reads some number of bytes from an io.Reader into an immutable LockedBuffer.
An error is returned precisely when the number of bytes read is less than the requested amount. Any data read is returned in either case.
*/
func NewBufferFromReader(r io.Reader, size int) (*LockedBuffer, error) {
// Construct a buffer of the provided size.
b := NewBuffer(size)
if b.Size() == 0 {
return b, nil
}
// Attempt to fill it with data from the Reader.
if n, err := io.ReadFull(r, b.Bytes()); err != nil {
if n == 0 {
// nothing was read
b.Destroy()
return newNullBuffer(), err
}
// partial read
d := NewBuffer(n)
d.Copy(b.Bytes()[:n])
d.Freeze()
b.Destroy()
return d, err
}
// success
b.Freeze()
return b, nil
}
/*
NewBufferFromReaderUntil constructs an immutable buffer containing data sourced from an io.Reader object.
If an error is encountered before the delimiter value, the error will be returned along with the data read up until that point.
*/
func NewBufferFromReaderUntil(r io.Reader, delim byte) (*LockedBuffer, error) {
// Construct a buffer with a data page that fills an entire memory page.
b := NewBuffer(os.Getpagesize())
// Loop over the buffer a byte at a time.
for i := 0; ; i++ {
// If we have filled this buffer...
if i == b.Size() {
// Construct a new buffer that is a page size larger.
c := NewBuffer(b.Size() + os.Getpagesize())
// Copy the data over.
c.Copy(b.Bytes())
// Destroy the old one and reassign its variable.
b.Destroy()
b = c
}
// Attempt to read a single byte.
n, err := r.Read(b.Bytes()[i : i+1])
if n != 1 { // if we did not read a byte
if err == nil { // and there was no error
i-- // try again
continue
}
// if instead there was an error, we're done early
if i == 0 { // no data read
b.Destroy()
return newNullBuffer(), err
}
d := NewBuffer(i)
d.Copy(b.Bytes()[:i])
d.Freeze()
b.Destroy()
return d, err
}
// we managed to read a byte, check if it was the delimiter
// note that errors are ignored in this case where we got data
if b.Bytes()[i] == delim {
if i == 0 {
// if first byte was delimiter, there's no data to return
b.Destroy()
return newNullBuffer(), nil
}
d := NewBuffer(i)
d.Copy(b.Bytes()[:i])
d.Freeze()
b.Destroy()
return d, nil
}
}
}
/*
NewBufferFromEntireReader reads from an io.Reader into an immutable buffer. It will continue reading until EOF.
A nil error is returned precisely when we managed to read all the way until EOF. Any data read is returned in either case.
*/
func NewBufferFromEntireReader(r io.Reader) (*LockedBuffer, error) {
// Create a buffer with a data region of one page size.
b := NewBuffer(os.Getpagesize())
for read := 0; ; {
// Attempt to read some data from the reader.
n, err := r.Read(b.Bytes()[read:])
// Nothing read but no error, try again.
if n == 0 && err == nil {
continue
}
// 1) so either have data and no error
// 2) or have error and no data
// 3) or both have data and have error
// Increment the read count by the number of bytes that we just read.
read += n
if err != nil {
// Suppress EOF error
if err == io.EOF {
err = nil
}
// We're done, return the data.
if read == 0 {
// No data read.
b.Destroy()
return newNullBuffer(), err
}
d := NewBuffer(read)
d.Copy(b.Bytes()[:read])
d.Freeze()
b.Destroy()
return d, err
}
// If we've filled this buffer, grow it by another page size.
if len(b.Bytes()[read:]) == 0 {
d := NewBuffer(b.Size() + os.Getpagesize())
d.Copy(b.Bytes())
b.Destroy()
b = d
}
}
}
/*
NewBufferRandom constructs an immutable buffer filled with cryptographically-secure random bytes.
*/
func NewBufferRandom(size int) *LockedBuffer {
// Construct a buffer of the specified size.
b := NewBuffer(size)
if b.Size() == 0 {
return b
}
// Fill the buffer with random bytes.
b.Scramble()
// Make the buffer immutable.
b.Freeze()
// Return the created Buffer object.
return b
}
// Freeze makes a LockedBuffer's memory immutable. The call can be reversed with Melt.
func (b *LockedBuffer) Freeze() {
b.Buffer.Freeze()
}
// Melt makes a LockedBuffer's memory mutable. The call can be reversed with Freeze.
func (b *LockedBuffer) Melt() {
b.Buffer.Melt()
}
/*
Seal takes a LockedBuffer object and returns its contents encrypted inside a sealed Enclave object. The LockedBuffer is subsequently destroyed and its contents wiped.
If Seal is called on a destroyed buffer, a nil enclave is returned.
*/
func (b *LockedBuffer) Seal() *Enclave {
e, err := core.Seal(b.Buffer)
if err != nil {
if err == core.ErrBufferExpired {
return nil
}
core.Panic(err)
}
return &Enclave{e}
}
/*
Copy performs a time-constant copy into a LockedBuffer. Move is preferred if the source is not also a LockedBuffer or if the source is no longer needed.
*/
func (b *LockedBuffer) Copy(src []byte) {
b.CopyAt(0, src)
}
/*
CopyAt performs a time-constant copy into a LockedBuffer at an offset. Move is preferred if the source is not also a LockedBuffer or if the source is no longer needed.
*/
func (b *LockedBuffer) CopyAt(offset int, src []byte) {
if !b.IsAlive() {
return
}
b.Lock()
defer b.Unlock()
core.Copy(b.Bytes()[offset:], src)
}
/*
Move performs a time-constant move into a LockedBuffer. The source is wiped after the bytes are copied.
*/
func (b *LockedBuffer) Move(src []byte) {
b.MoveAt(0, src)
}
/*
MoveAt performs a time-constant move into a LockedBuffer at an offset. The source is wiped after the bytes are copied.
*/
func (b *LockedBuffer) MoveAt(offset int, src []byte) {
if !b.IsAlive() {
return
}
b.Lock()
defer b.Unlock()
core.Move(b.Bytes()[offset:], src)
}
/*
Scramble attempts to overwrite the data with cryptographically-secure random bytes.
*/
func (b *LockedBuffer) Scramble() {
if !b.IsAlive() {
return
}
b.Buffer.Scramble()
}
/*
Wipe attempts to overwrite the data with zeros.
*/
func (b *LockedBuffer) Wipe() {
if !b.IsAlive() {
return
}
b.Lock()
defer b.Unlock()
core.Wipe(b.Bytes())
}
/*
Size gives you the length of a given LockedBuffer's data segment. A destroyed LockedBuffer will have a size of zero.
*/
func (b *LockedBuffer) Size() int {
return len(b.Bytes())
}
/*
Destroy wipes and frees the underlying memory of a LockedBuffer. The LockedBuffer will not be accessible or usable after this calls is made.
*/
func (b *LockedBuffer) Destroy() {
b.Buffer.Destroy()
}
/*
IsAlive returns a boolean value indicating if a LockedBuffer is alive, i.e. that it has not been destroyed.
*/
func (b *LockedBuffer) IsAlive() bool {
return b.Buffer.Alive()
}
/*
IsMutable returns a boolean value indicating if a LockedBuffer is mutable.
*/
func (b *LockedBuffer) IsMutable() bool {
return b.Buffer.Mutable()
}
/*
EqualTo performs a time-constant comparison on the contents of a LockedBuffer with a given buffer. A destroyed LockedBuffer will always return false.
*/
func (b *LockedBuffer) EqualTo(buf []byte) bool {
b.RLock()
defer b.RUnlock()
return core.Equal(b.Bytes(), buf)
}
/*
Functions for representing the memory region as various data types.
*/
/*
Bytes returns a byte slice referencing the protected region of memory.
*/
func (b *LockedBuffer) Bytes() []byte {
return b.Buffer.Data()
}
/*
Reader returns a Reader object referencing the protected region of memory.
*/
func (b *LockedBuffer) Reader() *bytes.Reader {
return bytes.NewReader(b.Bytes())
}
/*
String returns a string representation of the protected region of memory.
*/
func (b *LockedBuffer) String() string {
slice := b.Bytes()
return *(*string)(unsafe.Pointer(&slice))
}
/*
Uint16 returns a slice pointing to the protected region of memory with the data represented as a sequence of unsigned 16 bit integers. Its length will be half that of the byte slice, excluding any remaining part that doesn't form a complete uint16 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Uint16() []uint16 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 2
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]uint16)(unsafe.Pointer(&sl))
}
/*
Uint32 returns a slice pointing to the protected region of memory with the data represented as a sequence of unsigned 32 bit integers. Its length will be one quarter that of the byte slice, excluding any remaining part that doesn't form a complete uint32 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Uint32() []uint32 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 4
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]uint32)(unsafe.Pointer(&sl))
}
/*
Uint64 returns a slice pointing to the protected region of memory with the data represented as a sequence of unsigned 64 bit integers. Its length will be one eighth that of the byte slice, excluding any remaining part that doesn't form a complete uint64 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Uint64() []uint64 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 8
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]uint64)(unsafe.Pointer(&sl))
}
/*
Int8 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 8 bit integers. If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Int8() []int8 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), b.Size(), b.Size()}
// Cast the representation to the correct type and return it.
return *(*[]int8)(unsafe.Pointer(&sl))
}
/*
Int16 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 16 bit integers. Its length will be half that of the byte slice, excluding any remaining part that doesn't form a complete int16 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Int16() []int16 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 2
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]int16)(unsafe.Pointer(&sl))
}
/*
Int32 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 32 bit integers. Its length will be one quarter that of the byte slice, excluding any remaining part that doesn't form a complete int32 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Int32() []int32 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 4
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]int32)(unsafe.Pointer(&sl))
}
/*
Int64 returns a slice pointing to the protected region of memory with the data represented as a sequence of signed 64 bit integers. Its length will be one eighth that of the byte slice, excluding any remaining part that doesn't form a complete int64 value.
If called on a destroyed LockedBuffer, a nil slice will be returned.
*/
func (b *LockedBuffer) Int64() []int64 {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Compute size of new slice representation.
size := b.Size() / 8
if size < 1 {
return nil
}
// Construct the new slice representation.
var sl = struct {
addr uintptr
len int
cap int
}{uintptr(unsafe.Pointer(&b.Bytes()[0])), size, size}
// Cast the representation to the correct type and return it.
return *(*[]int64)(unsafe.Pointer(&sl))
}
/*
ByteArray8 returns a pointer to some 8 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
The length of the buffer must be at least 8 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
*/
func (b *LockedBuffer) ByteArray8() *[8]byte {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Check if the length is large enough.
if len(b.Bytes()) < 8 {
return nil
}
// Cast the representation to the correct type.
return (*[8]byte)(unsafe.Pointer(&b.Bytes()[0]))
}
/*
ByteArray16 returns a pointer to some 16 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
The length of the buffer must be at least 16 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
*/
func (b *LockedBuffer) ByteArray16() *[16]byte {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Check if the length is large enough.
if len(b.Bytes()) < 16 {
return nil
}
// Cast the representation to the correct type.
return (*[16]byte)(unsafe.Pointer(&b.Bytes()[0]))
}
/*
ByteArray32 returns a pointer to some 32 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
The length of the buffer must be at least 32 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
*/
func (b *LockedBuffer) ByteArray32() *[32]byte {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Check if the length is large enough.
if len(b.Bytes()) < 32 {
return nil
}
// Cast the representation to the correct type.
return (*[32]byte)(unsafe.Pointer(&b.Bytes()[0]))
}
/*
ByteArray64 returns a pointer to some 64 byte array. Care must be taken not to dereference the pointer and instead pass it around as-is.
The length of the buffer must be at least 64 bytes in size and the LockedBuffer should not be destroyed. In either of these cases a nil value is returned.
*/
func (b *LockedBuffer) ByteArray64() *[64]byte {
// Check if still alive.
if !b.Buffer.Alive() {
return nil
}
b.RLock()
defer b.RUnlock()
// Check if the length is large enough.
if len(b.Bytes()) < 64 {
return nil
}
// Cast the representation to the correct type.
return (*[64]byte)(unsafe.Pointer(&b.Bytes()[0]))
}