summaryrefslogtreecommitdiffstats
path: root/lib/oracle.go
blob: 11f735a2bc8b4c90a08f15b4e1eca2bfd6e94af7 (plain) (blame)
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
// Copyright © 2020 rsiddharth <s@ricketyspace.net>
// SPDX-License-Identifier: ISC

package lib

import (
	"crypto/rand"
	"math/big"
)

var oracleUnknown string = `Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg
YnkK`

var OracleKey []byte = make([]byte, 16)
var oracleRandom []byte = make([]byte, RandomInt(1, 4096))

func init() {
	_, err := rand.Read(OracleKey)
	if err != nil {
		panic(err)
	}

	_, err = rand.Read(oracleRandom)
	if err != nil {
		panic(err)
	}
}

// Given an input `in`, this function AES encrypts `in` using a
// randomly generate 16-byte key using ECB or CBC mode and returns the
// cipher.
func OracleAESRandomEncrypt(in []byte) []byte {
	// Generate random key.
	key := make([]byte, 16)
	_, err := rand.Read(key)
	if err != nil {
		panic(err)
	}
	// Generate random initialization vector; needed for AES CBC.
	iv := make([]byte, 16)
	_, err = rand.Read(iv)
	if err != nil {
		panic(err)
	}

	// Add 5-10 bytes at the beginning and end of `in`
	in = append(randomBytes(5, 10), in...)
	in = append(in, randomBytes(5, 10)...)

	// Randomly encrypt `in` with AES in ECB or CBC mode.
	m, err := rand.Int(rand.Reader, big.NewInt(2))
	if err != nil {
		panic(err)
	}
	var out []byte
	if m.Int64() == 0 {
		// Encrypt with AES in ECB mode.
		out = AESEncryptECB(in, key)
	} else {
		// Encrypt with AES in CBC mode.
		out = AESEncryptCBC(in, key, iv)
	}
	return out
}

func OracleAESEncryptECB(in []byte) []byte {
	return AESEncryptECB(append(in, Base64ToBytes(oracleUnknown)...), OracleKey)
}

func OracleAESVarEncryptECB(in []byte) []byte {
	in = append(oracleRandom, in...)
	in = append(in, Base64ToBytes(oracleUnknown)...)
	return AESEncryptECB(in, OracleKey)
}

// Return a random number from range [min, max]
func RandomInt(min, max int64) int64 {
	if min >= max {
		panic("RandomInt: min cannot be >= max!")
	}

	var rn *big.Int
	var err error
	for {
		rn, err = rand.Int(rand.Reader, big.NewInt(max+1))
		if err != nil {
			panic(err)
		}
		if rn.Int64() >= min {
			return rn.Int64()
		}
	}
}

// Randomly generates `min` to `max` bytes.
func randomBytes(min, max int64) []byte {
	bs := make([]byte, RandomInt(min, max))
	_, err := rand.Read(bs)
	if err != nil {
		panic(err)
	}
	return bs
}