-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathuserlib.go
546 lines (422 loc) · 12.6 KB
/
userlib.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
package userlib
import (
"errors"
"fmt"
"log"
"strings"
"sync"
"time"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/rsa"
"crypto/sha512"
. "github.com/onsi/ginkgo/v2"
"github.com/google/uuid"
"golang.org/x/crypto/argon2"
)
// More info about the UUID type:
// github.com/google/uuid
type UUID = uuid.UUID
// AES block size (in bytes)
// https://pkg.go.dev/crypto/aes
const AESBlockSizeBytes = aes.BlockSize
// AES key size (in bytes)
const AESKeySizeBytes = 16
// Output size (in bytes) of Hash, HMAC, and HashKDF
const HashSizeBytes = sha512.Size
const rsaKeySizeBits = 2048
// UUID size (in bytes)
const UUIDSizeBytes = 16
/*
********************************************
** Global Definitions ***
********************************************
Here, we declare a number of global data
structures and types: Keystore/Datastore,
Public/Private Key structures, etc.
*/
type PublicKeyType struct {
KeyType string
PubKey rsa.PublicKey
}
type PrivateKeyType struct {
KeyType string
PrivKey rsa.PrivateKey
}
// Bandwidth tracker (for measuring efficient append)
// var datastoreBandwidth = 0
// map[int]*int
var datastoreBandwidth sync.Map
// Datastore and Keystore variables
type keystoreType map[string]PublicKeyType
type datastoreType map[UUID][]byte
// map[int]keystoreType
var datastore sync.Map
// map[int]datastoreType
var keystore sync.Map
// var datastore map[UUID][]byte = make(map[UUID][]byte)
// var keystore map[string]PublicKeyType = make(map[string]PublicKeyType)
type DatastoreEntry struct {
UUID string
Value string
}
func getKeystoreShard() keystoreType {
pid := CurrentSpecReport().LineNumber()
shard, _ := keystore.LoadOrStore(pid, make(keystoreType))
shardMap := shard.(keystoreType)
return shardMap
}
func getDatastoreShard() datastoreType {
pid := CurrentSpecReport().LineNumber()
shard, _ := datastore.LoadOrStore(pid, make(datastoreType))
shardMap := shard.(datastoreType)
return shardMap
}
func getDatastoreBandwidthShard() *int {
pid := CurrentSpecReport().LineNumber()
newBandwidth := 0
bandwidth, _ := datastoreBandwidth.LoadOrStore(pid, &newBandwidth)
return bandwidth.(*int)
}
/*
********************************************
** Datastore Functions **
** DatastoreSet, DatastoreGet, **
** DatastoreDelete, DatastoreClear **
********************************************
*/
// Sets the value in the datastore
func datastoreSet(key UUID, value []byte) {
// Update bandwidth tracker
bandwidth := getDatastoreBandwidthShard()
*bandwidth += len(value)
foo := make([]byte, len(value))
copy(foo, value)
datastoreShard := getDatastoreShard()
datastoreShard[key] = foo
}
var DatastoreSet = datastoreSet
// Returns the value if it exists
func datastoreGet(key UUID) (value []byte, ok bool) {
datastoreShard := getDatastoreShard()
value, ok = datastoreShard[key]
if ok && value != nil {
// Update bandwidth tracker
bandwidth := getDatastoreBandwidthShard()
*bandwidth += len(value)
foo := make([]byte, len(value))
copy(foo, value)
return foo, ok
}
return
}
var DatastoreGet = datastoreGet
// Deletes a key
func datastoreDelete(key UUID) {
datastoreShard := getDatastoreShard()
delete(datastoreShard, key)
}
var DatastoreDelete = datastoreDelete
// Use this in testing to reset the datastore to empty
func datastoreClear() {
datastoreShard := getDatastoreShard()
for k := range datastoreShard {
delete(datastoreShard, k)
}
}
var DatastoreClear = datastoreClear
func DatastoreResetBandwidth() {
bandwidth := getDatastoreBandwidthShard()
*bandwidth = 0
}
// Get number of bytes uploaded/downloaded to/from Datastore.
func DatastoreGetBandwidth() int {
bandwidth := getDatastoreBandwidthShard()
return *bandwidth
}
// Use this in testing to reset the keystore to empty
func keystoreClear() {
keystoreShard := getKeystoreShard()
for k := range keystoreShard {
delete(keystoreShard, k)
}
}
var KeystoreClear = keystoreClear
// Sets the value in the keystore
func keystoreSet(key string, value PublicKeyType) error {
keystoreShard := getKeystoreShard()
_, present := keystoreShard[key]
if present {
return errors.New("entry in keystore has been taken")
}
keystoreShard[key] = value
return nil
}
var KeystoreSet = keystoreSet
// Returns the value if it exists
func keystoreGet(key string) (value PublicKeyType, ok bool) {
keystoreShard := getKeystoreShard()
value, ok = keystoreShard[key]
return
}
var KeystoreGet = keystoreGet
// Use this in testing to get the underlying map if you want
// to play with the datastore.
func DatastoreGetMap() map[UUID][]byte {
datastoreShard := getDatastoreShard()
return datastoreShard
}
// Use this in testing to get the underlying map if you want
// to play with the keystore.
func KeystoreGetMap() map[string]PublicKeyType {
keystoreShard := getKeystoreShard()
return keystoreShard
}
/*
********************************************
** Random Byte Generator ***
********************************************
This method may help with random byte generation.
*/
// RandomBytes. Helper function: Returns a byte slice of the specified
// size filled with random data
func randomBytes(size int) (data []byte) {
data = make([]byte, size)
_, err := rand.Read(data)
if err != nil {
panic(err)
}
return
}
var RandomBytes = randomBytes
/*
********************************************
** KDF **
** Argon2Key **
********************************************
*/
// Argon2: Automatically chooses a decent combination of iterations and memory
// Use this to generate a key from a password
func argon2Key(password []byte, salt []byte, keyLen uint32) []byte {
result := argon2.IDKey(password, salt, 1, 64*1024, 4, keyLen)
return result
}
var Argon2Key = argon2Key
/*
********************************************
** Hash **
** SHA512 **
********************************************
*/
// SHA512: Returns the checksum of data.
func hash(data []byte) []byte {
hashVal := sha512.Sum512(data)
// Converting from [64]byte array to []byte slice
result := hashVal[:]
return result
}
// Hash returns a byte slice containing the SHA512 hash of the given byte slice.
var Hash = hash
/*
********************************************
** Public Key Encryption **
** PKEKeyGen, PKEEnc, PKEDec **
********************************************
*/
// Four structs to help you manage your different keys
// You should only have 1 of each struct
// keyType should be either:
// "PKE": encryption
// "DS": authentication and integrity
type PKEEncKey = PublicKeyType
type PKEDecKey = PrivateKeyType
type DSSignKey = PrivateKeyType
type DSVerifyKey = PublicKeyType
// Generates a key pair for public-key encryption via RSA
func pkeKeyGen() (PKEEncKey, PKEDecKey, error) {
RSAPrivKey, err := rsa.GenerateKey(rand.Reader, rsaKeySizeBits)
RSAPubKey := RSAPrivKey.PublicKey
var PKEEncKeyRes PKEEncKey
PKEEncKeyRes.KeyType = "PKE"
PKEEncKeyRes.PubKey = RSAPubKey
var PKEDecKeyRes PKEDecKey
PKEDecKeyRes.KeyType = "PKE"
PKEDecKeyRes.PrivKey = *RSAPrivKey
return PKEEncKeyRes, PKEDecKeyRes, err
}
var PKEKeyGen = pkeKeyGen
// Encrypts a byte stream via RSA-OAEP with sha512 as hash
func pkeEnc(ek PKEEncKey, plaintext []byte) ([]byte, error) {
RSAPubKey := &ek.PubKey
if ek.KeyType != "PKE" {
return nil, errors.New("using a non-pke key for pke")
}
ciphertext, err := rsa.EncryptOAEP(sha512.New(), rand.Reader, RSAPubKey, plaintext, nil)
if err != nil {
return nil, err
}
return ciphertext, nil
}
var PKEEnc = pkeEnc
// Decrypts a byte stream encrypted with RSA-OAEP/sha512
func pkeDec(dk PKEDecKey, ciphertext []byte) ([]byte, error) {
RSAPrivKey := &dk.PrivKey
if dk.KeyType != "PKE" {
return nil, errors.New("using a non-pke for pke")
}
decryption, err := rsa.DecryptOAEP(sha512.New(), rand.Reader, RSAPrivKey, ciphertext, nil)
if err != nil {
return nil, err
}
return decryption, nil
}
var PKEDec = pkeDec
/*
********************************************
** Digital Signature **
** DSKeyGen, DSSign, DSVerify **
********************************************
*/
// Generates a key pair for digital signature via RSA
func dsKeyGen() (DSSignKey, DSVerifyKey, error) {
RSAPrivKey, err := rsa.GenerateKey(rand.Reader, rsaKeySizeBits)
RSAPubKey := RSAPrivKey.PublicKey
var DSSignKeyRes DSSignKey
DSSignKeyRes.KeyType = "DS"
DSSignKeyRes.PrivKey = *RSAPrivKey
var DSVerifyKeyRes DSVerifyKey
DSVerifyKeyRes.KeyType = "DS"
DSVerifyKeyRes.PubKey = RSAPubKey
return DSSignKeyRes, DSVerifyKeyRes, err
}
var DSKeyGen = dsKeyGen
// Signs a byte stream via SHA256 and PKCS1v15
func dsSign(sk DSSignKey, msg []byte) ([]byte, error) {
RSAPrivKey := &sk.PrivKey
if sk.KeyType != "DS" {
return nil, errors.New("using a non-ds key for ds")
}
hashed := sha512.Sum512(msg)
sig, err := rsa.SignPKCS1v15(rand.Reader, RSAPrivKey, crypto.SHA512, hashed[:])
if err != nil {
return nil, err
}
return sig, nil
}
var DSSign = dsSign
// Verifies a signature signed with SHA256 and PKCS1v15
func dsVerify(vk DSVerifyKey, msg []byte, sig []byte) error {
RSAPubKey := &vk.PubKey
if vk.KeyType != "DS" {
return errors.New("using a non-ds key for ds")
}
hashed := sha512.Sum512(msg)
err := rsa.VerifyPKCS1v15(RSAPubKey, crypto.SHA512, hashed[:], sig)
if err != nil {
return err
} else {
return nil
}
}
var DSVerify = dsVerify
/*
********************************************
** HMAC **
** HMACEval, HMACEqual **
********************************************
*/
// Evaluate the HMAC using sha512
func hmacEval(key []byte, msg []byte) ([]byte, error) {
if len(key) != 16 { // && len(key) != 24 && len(key) != 32 {
return nil, errors.New("input as key for hmac should be a 16-byte key")
}
mac := hmac.New(sha512.New, key)
mac.Write(msg)
res := mac.Sum(nil)
return res, nil
}
var HMACEval = hmacEval
// Equals comparison for hashes/MACs
// Does NOT leak timing.
func hmacEqual(a []byte, b []byte) bool {
return hmac.Equal(a, b)
}
var HMACEqual = hmacEqual
/*
********************************************
** Hash-Based Key Derivation Function **
** HashKDF **
********************************************
*/
// HashKDF (uses the same algorithm as hmacEval, wrapped to provide a useful
// error)
func hashKDF(key []byte, msg []byte) ([]byte, error) {
if len(key) != 16 {
return nil, errors.New("input as key for HashKDF should be a 16-byte key")
}
mac := hmac.New(sha512.New, key)
mac.Write(msg)
res := mac.Sum(nil)
return res, nil
}
var HashKDF = hashKDF
/*
********************************************
** Symmetric Encryption **
** SymEnc, SymDec **
********************************************
*/
// Encrypts a byte slice with AES-CTR
// Length of iv should be == AESBlockSizeBytes
func symEnc(key []byte, iv []byte, plaintext []byte) []byte {
if len(iv) != AESBlockSizeBytes {
panic("IV length not equal to AESBlockSizeBytes")
}
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
// The IV needs to be unique, but not secret. Therefore it's common to
// include it at the beginning of the ciphertext.
ciphertext := make([]byte, AESBlockSizeBytes+len(plaintext))
mode := cipher.NewCTR(block, iv)
mode.XORKeyStream(ciphertext[AESBlockSizeBytes:], plaintext)
copy(ciphertext[:AESBlockSizeBytes], iv)
return ciphertext
}
var SymEnc = symEnc
// Decrypts a ciphertext encrypted with AES-CTR
func symDec(key []byte, ciphertext []byte) []byte {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
if len(ciphertext) < AESBlockSizeBytes {
panic("ciphertext too short")
}
iv := ciphertext[:AESBlockSizeBytes]
ciphertext = ciphertext[AESBlockSizeBytes:]
plaintext := make([]byte, len(ciphertext))
mode := cipher.NewCTR(block, iv)
mode.XORKeyStream(plaintext, ciphertext)
return plaintext
}
var SymDec = symDec
// If DebugOutput is set to false, then DebugMsg will suppress output.
var DebugOutput = true
// Feel free to use userlib.DebugMsg(...) to print strings to the console.
func DebugMsg(format string, args ...interface{}) {
if DebugOutput {
msg := fmt.Sprintf("%v ", time.Now().Format("15:04:05.00000"))
log.Printf(msg+strings.Trim(format, "\r\n ")+"\n", args...)
}
}
// Deterministically converts a byte slice to a string of length 128 that is
// suitable to use as the storage key in a map and marshal/unmarshal to/from
// JSON.
func MapKeyFromBytes(data []byte) (truncated string) {
return fmt.Sprintf("%x", sha512.Sum512(data))
}