/
hardening.go
283 lines (257 loc) · 8.42 KB
/
hardening.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
package ctrlflow
import (
"fmt"
"go/ast"
"go/token"
mathrand "math/rand"
"strconv"
"golang.org/x/exp/rand"
"golang.org/x/tools/go/ssa"
ah "mvdan.cc/garble/internal/asthelper"
"mvdan.cc/garble/internal/literals"
)
var hardeningMap = map[string]dispatcherHardening{
"xor": xorHardening{},
"delegate_table": delegateTableHardening{},
}
func newDispatcherHardening(names []string) dispatcherHardening {
hardenings := make([]dispatcherHardening, len(names))
for i, name := range names {
h, ok := hardeningMap[name]
if !ok {
panic(fmt.Sprintf("unknown dispatcher hardening %q", name))
}
hardenings[i] = h
}
if len(hardenings) == 1 {
return hardenings[0]
}
return multiHardening(hardenings)
}
func getRandomName(rnd *mathrand.Rand) string {
return "_garble" + strconv.FormatUint(rnd.Uint64(), 32)
}
// generateKeys is used to generate a list of pseudo-random unique keys.
// Blacklist is needed to ensure that the result of a xor operation is not zero,
// which can lead to incorrect obfuscation of the control flow.
func generateKeys(count int, blacklistedKeys []int, rnd *mathrand.Rand) []int {
m := make(map[int]bool, count)
for _, i := range blacklistedKeys {
m[i] = true
}
arr := make([]int, 0, count)
for count > len(arr) {
key := int(rnd.Int31())
if key == 0 || m[key] {
continue
}
arr = append(arr, key)
m[key] = true
}
return arr
}
type dispatcherHardening interface {
Apply(dispatcher []cfgInfo, ssaRemap map[ssa.Value]ast.Expr, rnd *mathrand.Rand) (ast.Decl, ast.Stmt)
}
type multiHardening []dispatcherHardening
func (r multiHardening) Apply(info []cfgInfo, ssaRemap map[ssa.Value]ast.Expr, rnd *mathrand.Rand) (ast.Decl, ast.Stmt) {
return r[rnd.Intn(len(r))].Apply(info, ssaRemap, rnd)
}
// xorHardening replaces simple keys with obfuscated ones using xor with a global key
// that is decrypted when the package is initialized.
// Note: This hardening can be improved by literals obfuscation.
type xorHardening struct{}
func (xorHardening) Apply(dispatcher []cfgInfo, ssaRemap map[ssa.Value]ast.Expr, rnd *mathrand.Rand) (ast.Decl, ast.Stmt) {
globalKeyName, localKeyName := getRandomName(rnd), getRandomName(rnd)
firstKey := int(rnd.Int31())
secondKey := make([]byte, literals.MinSize+rand.Intn(literals.MinSize)) // make second part of key literals obfuscation friendly
if _, err := rnd.Read(secondKey); err != nil {
panic(err)
}
globalKey := firstKey
for _, b := range secondKey {
globalKey ^= int(b)
}
newKeys := generateKeys(len(dispatcher), []int{globalKey}, rnd)
for i, info := range dispatcher {
k := newKeys[i]
ssaRemap[info.CompareVar] = ah.IntLit(k ^ globalKey)
ssaRemap[info.StoreVar] = &ast.ParenExpr{X: &ast.BinaryExpr{X: ast.NewIdent(localKeyName), Op: token.XOR, Y: ah.IntLit(k)}}
}
// Global key decryption code:
/*
var <globalKeyName> = func(secondKey []byte) int {
r := <firstKey>
for _, b := range secondKey {
r ^= int(b)
}
return r
}([]byte{ <secondKey> })
*/
globalKeyDecl := &ast.GenDecl{
Tok: token.VAR,
Specs: []ast.Spec{
&ast.ValueSpec{
Names: []*ast.Ident{ast.NewIdent(globalKeyName)},
Values: []ast.Expr{ah.CallExpr(&ast.FuncLit{
Type: &ast.FuncType{
Params: &ast.FieldList{List: []*ast.Field{{
Names: []*ast.Ident{ast.NewIdent("secondKey")},
Type: &ast.ArrayType{Len: ah.IntLit(len(secondKey)), Elt: ast.NewIdent("byte")},
}}},
Results: &ast.FieldList{List: []*ast.Field{{
Type: ast.NewIdent("int"),
}}},
},
Body: &ast.BlockStmt{List: []ast.Stmt{
ah.AssignDefineStmt(ast.NewIdent("r"), ah.IntLit(firstKey)),
&ast.RangeStmt{
Key: ast.NewIdent("_"),
Value: ast.NewIdent("b"),
Tok: token.DEFINE,
X: ast.NewIdent("secondKey"),
Body: &ast.BlockStmt{List: []ast.Stmt{&ast.AssignStmt{
Lhs: []ast.Expr{ast.NewIdent("r")},
Tok: token.XOR_ASSIGN,
Rhs: []ast.Expr{&ast.CallExpr{
Fun: ast.NewIdent("int"),
Args: []ast.Expr{ast.NewIdent("b")},
}},
}}},
},
ah.ReturnStmt(ast.NewIdent("r")),
}},
}, ah.DataToArray(secondKey))},
},
},
}
return globalKeyDecl, ah.AssignDefineStmt(ast.NewIdent(localKeyName), ast.NewIdent(globalKeyName))
}
// delegateTableHardening replaces simple keys with a decryption function call
// from a table of randomly generated key decryption functions
// Note: This hardening can be improved by literals obfuscation.
type delegateTableHardening struct{}
func (delegateTableHardening) Apply(dispatcher []cfgInfo, ssaRemap map[ssa.Value]ast.Expr, rnd *mathrand.Rand) (ast.Decl, ast.Stmt) {
keySize := literals.MinSize + rand.Intn(literals.MinSize)
delegateCount := keySize
// Reusing multiple times one decryption function is fine,
// but it doesn't make sense to generate more functions than keys.
if delegateCount > len(dispatcher) {
delegateCount = len(dispatcher)
}
delegateKeyIdxs := rnd.Perm(keySize)[:delegateCount]
delegateLocalKeys := generateKeys(delegateCount, nil, rnd)
key := make([]byte, keySize)
if _, err := rnd.Read(key); err != nil {
panic(err)
}
delegateIndexes := make([]int, len(dispatcher))
delegateKeys := make([]int, len(dispatcher))
for i := range delegateIndexes {
delegateIdx := rnd.Intn(delegateCount)
delegateIndexes[i] = delegateIdx
delegateKeys[i] = int(key[delegateKeyIdxs[delegateIdx]]) ^ delegateLocalKeys[delegateIdx]
}
newKeys := generateKeys(len(dispatcher), delegateKeys, rnd)
globalTableName := getRandomName(rnd)
for i, info := range dispatcher {
k, delegateIdx, delegateKey := newKeys[i], delegateIndexes[i], delegateKeys[i]
encryptedKey := k ^ delegateKey
ssaRemap[info.CompareVar] = ah.IntLit(k)
ssaRemap[info.StoreVar] = ah.CallExpr(ah.IndexExprByExpr(ast.NewIdent(globalTableName), ah.IntLit(delegateIdx)), ah.IntLit(encryptedKey))
}
delegatesAst := make([]ast.Expr, delegateCount)
for i := 0; i < delegateCount; i++ {
// Code for single decryption delegate:
/*
func(i int) int {
return i ^ (int(key[<delegateKeyIdxs[i]>]) ^ <delegateLocalKeys[i]>)
}
*/
delegateAst := &ast.FuncLit{
Type: &ast.FuncType{
Params: &ast.FieldList{List: []*ast.Field{{
Names: []*ast.Ident{ast.NewIdent("i")},
Type: ast.NewIdent("int"),
}}},
Results: &ast.FieldList{List: []*ast.Field{{
Type: ast.NewIdent("int"),
}}},
},
Body: &ast.BlockStmt{List: []ast.Stmt{
&ast.ReturnStmt{Results: []ast.Expr{
&ast.BinaryExpr{
X: ast.NewIdent("i"),
Op: token.XOR,
Y: &ast.BinaryExpr{
X: ah.CallExprByName("int", &ast.IndexExpr{
X: ast.NewIdent("key"),
Index: ah.IntLit(delegateKeyIdxs[i]),
}),
Op: token.XOR,
Y: ah.IntLit(delegateLocalKeys[i]),
},
},
}},
}},
}
delegatesAst[i] = delegateAst
}
// Code for initialization of the decryption delegates table:
/*
var <globalTableName> = (func(key [<len(key)>]byte) [<len(key)>]func(int) int {
return [<delegateCount>]func(int) int{
<delegatesAst>
}
})(<key>)
*/
delegateTableDecl := &ast.GenDecl{
Tok: token.VAR,
Specs: []ast.Spec{
&ast.ValueSpec{
Names: []*ast.Ident{ast.NewIdent(globalTableName)},
Values: []ast.Expr{
&ast.CallExpr{
Fun: &ast.ParenExpr{X: &ast.FuncLit{
Type: &ast.FuncType{
Params: &ast.FieldList{List: []*ast.Field{{
Names: []*ast.Ident{ast.NewIdent("key")},
Type: &ast.ArrayType{Len: ah.IntLit(len(key)), Elt: ast.NewIdent("byte")},
}}},
Results: &ast.FieldList{List: []*ast.Field{{Type: &ast.ArrayType{
Len: ah.IntLit(delegateCount),
Elt: &ast.FuncType{
Params: &ast.FieldList{List: []*ast.Field{{
Type: ast.NewIdent("int"),
}}},
Results: &ast.FieldList{List: []*ast.Field{{
Type: ast.NewIdent("int"),
}}},
},
}}}},
},
Body: &ast.BlockStmt{List: []ast.Stmt{
&ast.ReturnStmt{Results: []ast.Expr{&ast.CompositeLit{
Type: &ast.ArrayType{
Len: ah.IntLit(delegateCount),
Elt: &ast.FuncType{
Params: &ast.FieldList{List: []*ast.Field{{
Type: ast.NewIdent("int"),
}}},
Results: &ast.FieldList{List: []*ast.Field{{
Type: ast.NewIdent("int"),
}}},
},
},
Elts: delegatesAst,
}}},
}},
}},
Args: []ast.Expr{ah.DataToArray(key)},
},
},
},
},
}
return delegateTableDecl, nil
}