forked from platypusguy/jacobin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavaSecuritySecureRandom.go
More file actions
494 lines (402 loc) · 15.4 KB
/
javaSecuritySecureRandom.go
File metadata and controls
494 lines (402 loc) · 15.4 KB
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
/*
* Jacobin VM - A Java virtual machine
* Copyright (c) 2024 by the Jacobin authors. Consult jacobin.org.
* Licensed under Mozilla Public License 2.0 (MPL 2.0) All rights reserved.
*/
package javaSecurity
import (
"fmt"
"jacobin/src/excNames"
"jacobin/src/gfunction/ghelpers"
"jacobin/src/object"
"jacobin/src/types"
"math/rand"
"time"
)
/***
Jacobin should employ the most secure SecureRandom implementation available.
The Go crypto/rand package is the best choice for Jacobin.
Algorithm, Provider: The Go crypto/rand package automatically uses the most secure cryptographic random source
available on the system. It does not allow selecting a specific pseudo-random generator or cryptographic provider
because it relies on O/S-backed randomness (e.g., /dev/urandom on Linux, CryptGenRandom on Windows).
Seeding: Cryptographic pseudo-random generators derive their randomness from a system entropy pool,
which is automatically initialized. Allowing user-provided seeding would weaken security by
making the output more predictable. Unlike math/rand, which uses a deterministic algorithm based on a seed,
crypto/rand is designed for secure applications like encryption keys and authentication tokens.
***/
func Load_Security_SecureRandom() {
ghelpers.MethodSignatures["java/security/SecureRandom.<clinit>()V"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: ghelpers.ClinitGeneric,
}
ghelpers.MethodSignatures["java/security/SecureRandom.<init>()V"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomInit,
}
ghelpers.MethodSignatures["java/security/SecureRandom.<init>([B)V"] =
ghelpers.GMeth{
ParamSlots: 1,
GFunction: secureRandomInit,
}
ghelpers.MethodSignatures["java/security/SecureRandom.<init>(Ljava/security/SecureRandomSpi;Ljava/security/Provider;)V"] =
ghelpers.GMeth{
ParamSlots: 2,
GFunction: ghelpers.TrapFunction,
}
ghelpers.MethodSignatures["java/security/SecureRandom.generateSeed(I)[B"] =
ghelpers.GMeth{
ParamSlots: 1,
GFunction: secureRandomGenerateSeed,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getAlgorithm()Ljava/lang/String;"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomGetAlgorithm,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getInstance(Ljava/lang/String;)Ljava/security/SecureRandom;"] =
ghelpers.GMeth{
ParamSlots: 1, // String algorithm
GFunction: secureRandomGetInstance,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getInstance(Ljava/lang/String;Ljava/lang/String;)Ljava/security/SecureRandom;"] =
ghelpers.GMeth{
ParamSlots: 2, // String algorithm, String provider
GFunction: secureRandomGetInstance,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getInstance(Ljava/lang/String;Ljava/security/Provider;)Ljava/security/SecureRandom;"] =
ghelpers.GMeth{
ParamSlots: 2, // String algorithm, Provider provider
GFunction: secureRandomGetInstance,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getInstance(Ljava/lang/String;Ljava/security/SecureRandomParameters;)Ljava/security/SecureRandom;"] =
ghelpers.GMeth{
ParamSlots: 2, // String algorithm, SecureRandomParameters params
GFunction: secureRandomGetInstance,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getInstance(Ljava/lang/String;Ljava/security/SecureRandomParameters;Ljava/lang/String;)Ljava/security/SecureRandom;"] =
ghelpers.GMeth{
ParamSlots: 3, // String algorithm, SecureRandomParameters params, String provider
GFunction: secureRandomGetInstance,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getInstance(Ljava/lang/String;Ljava/security/SecureRandomParameters;Ljava/security/Provider;)Ljava/security/SecureRandom;"] =
ghelpers.GMeth{
ParamSlots: 3, // String algorithm, SecureRandomParameters params, Provider provider
GFunction: secureRandomGetInstance,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getInstanceStrong()Ljava/security/SecureRandom;"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomGetInstanceStrong,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getParameters()Ljava/security/SecureRandomParameters;"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomGetAlgorithm,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getProvider()Ljava/security/Provider;"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomGetAlgorithm,
}
ghelpers.MethodSignatures["java/security/SecureRandom.getSeed(I)[B"] =
ghelpers.GMeth{
ParamSlots: 1,
GFunction: secureRandomGetSeed,
}
ghelpers.MethodSignatures["java/security/SecureRandom.next(I)I"] =
ghelpers.GMeth{
ParamSlots: 1,
GFunction: ghelpers.TrapProtected,
}
ghelpers.MethodSignatures["java/security/SecureRandom.nextBoolean()Z"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomNextBoolean,
}
ghelpers.MethodSignatures["java/security/SecureRandom.nextBytes([B)V"] =
ghelpers.GMeth{
ParamSlots: 1,
GFunction: secureRandomNextBytes,
}
ghelpers.MethodSignatures["java/security/SecureRandom.nextBytes([BLjava/security/SecureRandomParameters;)V"] =
ghelpers.GMeth{
ParamSlots: 2,
GFunction: secureRandomNextBytes,
}
ghelpers.MethodSignatures["java/security/SecureRandom.nextDouble()D"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomNextFloat,
}
ghelpers.MethodSignatures["java/security/SecureRandom.nextFloat()F"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomNextFloat,
}
ghelpers.MethodSignatures["java/security/SecureRandom.nextGaussian()D"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: ghelpers.TrapFunction,
}
ghelpers.MethodSignatures["java/security/SecureRandom.nextInt()I"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomNextInt,
}
ghelpers.MethodSignatures["java/security/SecureRandom.nextLong()J"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomNextInt,
}
ghelpers.MethodSignatures["java/security/SecureRandom.reseed()V"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomReseed,
}
ghelpers.MethodSignatures["java/security/SecureRandom.reseed(Ljava/security/SecureRandomParameters;)V"] =
ghelpers.GMeth{
ParamSlots: 1,
GFunction: secureRandomReseed,
}
ghelpers.MethodSignatures["java/security/SecureRandom.setSeed([B)V"] =
ghelpers.GMeth{
ParamSlots: 1,
GFunction: secureRandomSetSeed,
}
ghelpers.MethodSignatures["java/security/SecureRandom.setSeed(J)V"] =
ghelpers.GMeth{
ParamSlots: 1,
GFunction: secureRandomSetSeed,
}
ghelpers.MethodSignatures["java/security/SecureRandom.toString()Ljava/lang/String;"] =
ghelpers.GMeth{
ParamSlots: 0,
GFunction: secureRandomToString,
}
}
var secureRandomClassName = "java/security/SecureRandom"
// Return a byte array holding a generated dummy seed of the specified byte size (count).
func _genSeed(count int64) []byte {
seed := time.Now().UnixNano()
byteArray := types.Int64ToBytesBE(seed)
if count < 0 {
count = 0
}
return byteArray[:count]
}
// Re-seed and update rng of a SecureRandom object with the specified new seed expressed as an int64.
func _reSeedObject(obj *object.Object, newSeed int64) {
// Update the seed field.
obj.FieldTable["seed"] = object.Field{
Ftype: types.Int,
Fvalue: newSeed,
}
}
// secureRandomInit - instantiate a SecureRandom object.
func secureRandomInit(params []interface{}) interface{} {
// Create SecureRandom object with default seed value.
obj := params[0].(*object.Object)
seed := time.Now().UnixNano()
_reSeedObject(obj, seed)
return nil
}
// SecureRandomGetInstance - several variations of SecureRandom getInstance.
func secureRandomGetInstance(params []interface{}) interface{} {
// Create SecureRandom object with default seed value.
obj := params[0].(*object.Object)
seed := time.Now().UnixNano()
_reSeedObject(obj, seed)
return obj
}
// secureRandomGetInstanceStrong.
func secureRandomGetInstanceStrong([]interface{}) interface{} {
// Create SecureRandom object with default seed value.
obj := object.MakeEmptyObjectWithClassName(&secureRandomClassName)
seed := time.Now().UnixNano()
_reSeedObject(obj, seed)
return obj
}
// Re-seed this SecureRandom object.
func secureRandomReseed(params []interface{}) interface{} {
obj := params[0].(*object.Object)
oldSeed, _ := obj.FieldTable["seed"].Fvalue.(int64)
newSeed := time.Now().UnixNano()
if newSeed == oldSeed {
// Ensure observable change even if clock resolution returns same value
newSeed = oldSeed + 1
}
_reSeedObject(obj, newSeed)
return nil
}
// Set the specified seed in this SecureRandom object.
func secureRandomSetSeed(params []interface{}) interface{} {
// Validate seed parameter.
switch params[1].(type) {
case int64:
_reSeedObject(params[0].(*object.Object), params[1].(int64))
return nil
case *object.Object:
default:
errMsg := fmt.Sprintf("secureRandomSetSeed: seed parameter must be int64 or an object, observed: %T", params[1])
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
// Get seed field.
fld, ok := params[1].(*object.Object).FieldTable["value"]
if !ok {
errMsg := "secureRandomSetSeed: parameter field \"value\" missing"
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
// Use seed to re-seed the object.
switch fld.Fvalue.(type) {
case []byte:
ii := types.BytesToInt64BE(fld.Fvalue.([]byte))
_reSeedObject(params[0].(*object.Object), ii)
case []types.JavaByte:
bb := object.GoByteArrayFromJavaByteArray(fld.Fvalue.([]types.JavaByte))
ii := types.BytesToInt64BE(bb)
_reSeedObject(params[0].(*object.Object), ii)
case int64:
_reSeedObject(params[0].(*object.Object), fld.Fvalue.(int64))
default:
errMsg := fmt.Sprintf("secureRandomSetSeed: unrecognized type for field \"value\", observed: %T", fld.Fvalue)
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
return nil
}
// secureRandomNextBytes generates a specified number of random bytes
func secureRandomNextBytes(params []interface{}) interface{} {
switch len(params) {
case 2, 3:
default:
errMsg := fmt.Sprintf("secureRandomNextBytes: Wrong number of parameters, observed %d", len(params))
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
// Get byte array object.
baObject, ok := params[1].(*object.Object)
if !ok {
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, "secureRandomNextBytes: Second parameter must be a byte array")
}
// Generate random bytes
fld := baObject.FieldTable["value"]
var byteArray []byte
switch fld.Fvalue.(type) {
case []byte:
byteArray = fld.Fvalue.([]byte)
case []types.JavaByte:
byteArray = object.GoByteArrayFromJavaByteArray(fld.Fvalue.([]types.JavaByte))
default:
errMsg := fmt.Sprintf("secureRandomNextBytes: unrecognized type for field \"value\", observed: %T", fld.Fvalue)
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
_, err := rand.Read(byteArray)
if err != nil {
return ghelpers.GetGErrBlk(excNames.RuntimeException, fmt.Sprintf("secureRandomNextBytes: rng.Read(byteArray), err: %v", err))
}
// Return objectified Java byte array.
fld.Fvalue = object.JavaByteArrayFromGoByteArray(byteArray)
baObject.FieldTable["value"] = fld
return nil
}
// secureRandomNextInt generates a random int64
func secureRandomNextInt(params []interface{}) interface{} {
// Validate parameter count.
if len(params) != 1 {
errMsg := fmt.Sprintf("secureRandomNextInt: Expected 1 parameter (SecureRandom object), got %d", len(params))
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
// Generate random int64.
var result int64
byteArray := make([]byte, 8) // int64 is 8 bytes
_, err := rand.Read(byteArray)
if err != nil {
return ghelpers.GetGErrBlk(excNames.RuntimeException, fmt.Sprintf("secureRandomNextInt: Failed to generate random int64: %v", err))
}
// Convert bytes to int64.
for i := 0; i < 8; i++ {
result = (result << 8) | int64(byteArray[i])
}
return result
}
// secureRandomNextFloat generates a random float64
func secureRandomNextFloat(params []interface{}) interface{} {
// Validate parameter count.
if len(params) != 1 {
errMsg := fmt.Sprintf("secureRandomNextFloat: Expected 1 parameter (SecureRandom object), got %d", len(params))
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
// Generate random float64 in the range [0, 1).
byteArray := make([]byte, 8) // float64 is 8 bytes
_, err := rand.Read(byteArray)
if err != nil {
return ghelpers.GetGErrBlk(excNames.RuntimeException, fmt.Sprintf("secureRandomNextFloat: rng.Read(byteArray) failed, err: %v", err))
}
// Convert bytes to a value in [0, 1).
var result float64
for i := 0; i < 8; i++ {
result = result*256 + float64(byteArray[i])
}
result /= 1 << 64
return result
}
// secureRandomGenerateSeed generates a new seed as a slice of JavaByte
func secureRandomGenerateSeed(params []interface{}) interface{} {
// Validate parameters and set up rng.
if len(params) != 2 {
errMsg := fmt.Sprintf("secureRandomGenerateSeed: Expected 2 parameters (SecureRandom object, int64 numBytes), got %d", len(params))
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
// Get seed byte array size.
numBytes, ok := params[1].(int64)
if !ok || numBytes <= 0 {
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, "secureRandomGenerateSeed: Second parameter must be a positive int64")
}
// Generate output byte array.
byteArray := _genSeed(numBytes)
_, err := rand.Read(byteArray)
if err != nil {
return ghelpers.GetGErrBlk(excNames.RuntimeException, fmt.Sprintf("secureRandomGenerateSeed: rng.Read(byteArray) failed, err: %v", err))
}
// Wrap as a String object holding the Java byte array, consistent with project conventions
jb := object.JavaByteArrayFromGoByteArray(byteArray)
result := object.StringObjectFromJavaByteArray(jb)
return result
}
// Get PRNG algorithm. This is simply whatever the O/S provides. Reference: Go package crypto/rand.
func secureRandomGetAlgorithm(params []interface{}) interface{} {
return object.StringObjectFromGoString("go/crypto/rand") // matches OpenJDK JVM
}
// toString - return the class name string.
func secureRandomToString(params []interface{}) interface{} {
return object.StringObjectFromGoString("go/crypto/rand")
}
func secureRandomNextBoolean(params []interface{}) interface{} {
byteArray := make([]byte, 1) // int64 is 8 bytes
_, err := rand.Read(byteArray)
if err != nil {
errMsg := fmt.Sprintf("secureRandomNextBoolean: rand.Read(byteArray) failed, err: %s", err.Error())
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
if byteArray[0]&0x01 == 0x01 {
return types.JavaBoolTrue
}
return types.JavaBoolFalse
}
// secureRandomGetSeed returns the current seed as a byte array of the specified size
func secureRandomGetSeed(params []interface{}) interface{} {
// Validate parameter count.
if len(params) != 1 {
errMsg := fmt.Sprintf("secureRandomGetSeed: Expected 1 parameter (int64 size), got %d", len(params))
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, errMsg)
}
size, ok := params[0].(int64)
if !ok {
return ghelpers.GetGErrBlk(excNames.IllegalArgumentException, "secureRandomGetSeed: Size parameter must be an int64")
}
// Form byte array for return to caller.
byteArray := _genSeed(size)
jb := object.JavaByteArrayFromGoByteArray(byteArray)
result := object.StringObjectFromJavaByteArray(jb)
return result
}