forked from Logicalis/asn1
-
Notifications
You must be signed in to change notification settings - Fork 3
/
types.go
496 lines (442 loc) · 11.5 KB
/
types.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
package asn1
import (
"bytes"
"fmt"
"math/big"
"reflect"
)
// Pre-calculated types for convenience
var (
bigIntType = reflect.TypeOf((*big.Int)(nil))
bitStringType = reflect.TypeOf(BitString{})
oidType = reflect.TypeOf(Oid{})
nullType = reflect.TypeOf(Null{})
enumType = reflect.TypeOf(Enum(0))
)
/*
* Basic encoders and decoders
*/
// A function that encodes data.
type encoderFunction func(reflect.Value) ([]byte, error)
// A function that decodes data.
type decoderFunction func([]byte, reflect.Value) error
func (ctx *Context) encodeBool(value reflect.Value) ([]byte, error) {
if value.Kind() != reflect.Bool {
return nil, wrongType(reflect.Bool.String(), value)
}
if value.Bool() {
return []byte{0xff}, nil
}
return []byte{0x00}, nil
}
func (ctx *Context) decodeBool(data []byte, value reflect.Value) error {
// TODO check value type
if !ctx.der.decoding {
boolValue := parseBigInt(data).Cmp(big.NewInt(0)) != 0
value.SetBool(boolValue)
return nil
}
// DER is more restrict regarding valid booleans
if len(data) == 1 {
switch data[0] {
case 0x00:
value.SetBool(false)
return nil
case 0xff:
value.SetBool(true)
return nil
}
}
return parseError("invalid bool value")
}
func (ctx *Context) encodeBigInt(value reflect.Value) ([]byte, error) {
num, ok := value.Interface().(*big.Int)
if !ok {
return nil, wrongType(bigIntType.String(), value)
}
if num == nil {
return []byte{0x00}, nil
}
var buf []byte
if num.Sign() >= 0 {
buf = append([]byte{0x00}, num.Bytes()...)
} else {
// Set absolute value
convertedNum := big.NewInt(0)
convertedNum.Abs(num)
// Subtract One
convertedNum.Sub(convertedNum, big.NewInt(1))
// Invert bytes
buf = convertedNum.Bytes()
for i, b := range buf {
buf[i] = ^b
}
buf = append([]byte{0xff}, buf...)
}
return removeIntLeadingBytes(buf), nil
}
func (ctx *Context) decodeBigInt(data []byte, value reflect.Value) error {
// TODO check value type
err := checkInt(ctx, data)
if err != nil {
return err
}
i := parseBigInt(data)
value.Set(reflect.ValueOf(i))
return nil
}
func (ctx *Context) encodeInt(value reflect.Value) ([]byte, error) {
switch value.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
default:
return nil, wrongType("signed integer", value)
}
n := value.Int()
buf := make([]byte, 8)
for i := range buf {
shift := 8 * uint(len(buf)-i-1)
mask := int64(0xff) << shift
buf[i] = byte((n & mask) >> shift)
}
return removeIntLeadingBytes(buf), nil
}
func (ctx *Context) decodeInt(data []byte, value reflect.Value) error {
// TODO check value type
err := checkInt(ctx, data)
if err != nil {
return err
}
if len(data) > 8 {
return parseError("integer too large for Go type '%s'", value.Type())
}
// Sign extend the value
extensionByte := byte(0x00)
if len(data) > 0 && data[0]&0x80 != 0 {
extensionByte = byte(0xff)
}
extension := make([]byte, 8-len(data))
for i := range extension {
extension[i] = extensionByte
}
data = append(extension, data...)
// Decode binary
num := int64(0)
for i := 0; i < len(data); i++ {
num <<= 8
num |= int64(data[i])
}
value.SetInt(num)
return nil
}
func (ctx *Context) encodeUint(value reflect.Value) ([]byte, error) {
switch value.Kind() {
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
default:
return nil, wrongType("unsigned integer", value)
}
n := value.Uint()
buf := make([]byte, 9)
for i := range buf {
shift := 8 * uint(len(buf)-i-1)
mask := uint64(0xff) << shift
buf[i] = byte((n & mask) >> shift)
}
return removeIntLeadingBytes(buf), nil
}
func (ctx *Context) decodeUint(data []byte, value reflect.Value) error {
// TODO check value type
err := checkInt(ctx, data)
if err != nil {
return err
}
if len(data) > 8 {
return parseError("integer too large for Go type '%s'", value.Type())
}
if len(data) > 0 && data[0]&0x80 != 0 {
return parseError("negative integer can't be assigned to Go type '%s'", value.Type())
}
num := uint64(0)
for i := 0; i < len(data); i++ {
num <<= 8
num |= uint64(data[i])
}
value.SetUint(num)
return nil
}
func (ctx *Context) encodeOctetString(value reflect.Value) ([]byte, error) {
// Check type
kind := value.Kind()
if !(kind == reflect.Array || kind == reflect.Slice) &&
value.Type().Elem().Kind() == reflect.Uint8 {
// Invalid type or element type
return nil, wrongType("array or slice of bytes", value)
}
if kind == reflect.Slice {
return value.Interface().([]byte), nil
}
data := make([]byte, value.Len())
for i := 0; i < value.Len(); i++ {
data[i] = value.Index(i).Interface().(byte)
}
return data, nil
}
func (ctx *Context) decodeOctetString(data []byte, value reflect.Value) error {
// Check type
kind := value.Kind()
if !(kind == reflect.Array || kind == reflect.Slice) &&
value.Type().Elem().Kind() == reflect.Uint8 {
// Invalid type or element type
return wrongType("array or slice of bytes", value)
}
if value.Kind() == reflect.Array {
// Check array length
if len(data) != value.Len() {
t := fmt.Sprintf("[%d]uint8", value.Len())
return wrongType(t, value)
}
// Get reference to the array as a slice
dest := value.Slice(0, value.Len()).Interface().([]byte)
// Copy data
copy(dest, data)
} else {
// Set value with a copy of the array data
value.Set(reflect.ValueOf(append([]byte{}, data...)))
}
return nil
}
func (ctx *Context) encodeString(value reflect.Value) ([]byte, error) {
if value.Kind() != reflect.String {
return nil, wrongType(reflect.String.String(), value)
}
return []byte(value.String()), nil
}
func (ctx *Context) decodeString(data []byte, value reflect.Value) error {
// TODO check value type
s := string(data)
value.SetString(s)
return nil
}
/*
* Custom types
*/
// ENUM
type Enum int
// BIT STRING
// BitString is the structure to use when you want an ASN.1 BIT STRING type. A
// bit string is padded up to the nearest byte in memory and the number of
// valid bits is recorded. Padding bits will be zero.
type BitString struct {
Bytes []byte // bits packed into bytes.
BitLength int // length in bits.
}
// At returns the bit at the given index. If the index is out of range it
// returns 0.
func (b BitString) At(i int) int {
if i < 0 || i >= b.BitLength {
return 0
}
x := i / 8
y := 7 - uint(i%8)
return int(b.Bytes[x]>>y) & 1
}
// RightAlign returns a slice where the padding bits are at the beginning. The
// slice may share memory with the BitString.
func (b BitString) RightAlign() []byte {
shift := uint(8 - (b.BitLength % 8))
if shift == 8 || len(b.Bytes) == 0 {
return b.Bytes
}
a := make([]byte, len(b.Bytes))
a[0] = b.Bytes[0] >> shift
for i := 1; i < len(b.Bytes); i++ {
a[i] = b.Bytes[i-1] << (8 - shift)
a[i] |= b.Bytes[i] >> shift
}
return a
}
func (ctx *Context) encodeBitString(value reflect.Value) ([]byte, error) {
bitString, ok := value.Interface().(BitString)
if !ok {
return nil, wrongType(bitStringType.String(), value)
}
data := make([]byte, len(bitString.Bytes)+1)
// As the first octet, we encode the number of unused bits at the end.
data[0] = byte(8 - (bitString.BitLength % 8))
copy(data[1:], bitString.Bytes)
return data, nil
}
func (ctx *Context) decodeBitString(data []byte, value reflect.Value) error {
// TODO check value type
if len(data) == 0 {
return syntaxError("zero length BIT STRING")
}
paddingBits := int(data[0])
if paddingBits > 7 ||
len(data) == 1 && paddingBits > 0 ||
data[len(data)-1]&((1<<data[0])-1) != 0 {
return syntaxError("invalid padding bits in BIT STRING")
}
var obj BitString
obj.BitLength = (len(data)-1)*8 - paddingBits
obj.Bytes = data[1:]
value.Set(reflect.ValueOf(obj))
return nil
}
// Oid is used to encode and decode ASN.1 OBJECT IDENTIFIERs.
type Oid []uint
// Cmp returns zero if both Oids are the same, a negative value if oid
// lexicographically precedes other and a positive value otherwise.
func (oid Oid) Cmp(other Oid) int {
for i, n := range oid {
if i >= len(other) {
return 1
}
if n != other[i] {
return int(n) - int(other[i])
}
}
return len(oid) - len(other)
}
// String returns the dotted representation of oid.
func (oid Oid) String() string {
if len(oid) == 0 {
return ""
}
s := fmt.Sprintf(".%d", oid[0])
for i := 1; i < len(oid); i++ {
s += fmt.Sprintf(".%d", oid[i])
}
return s
}
func (ctx *Context) encodeOid(value reflect.Value) ([]byte, error) {
// Check values
oid, ok := value.Interface().(Oid)
if !ok {
return nil, wrongType(oidType.String(), value)
}
value1 := uint(0)
if len(oid) >= 1 {
value1 = oid[0]
if value1 > 2 {
return nil, parseError("invalid value for first element of OID: %d", value1)
}
}
value2 := uint(0)
if len(oid) >= 2 {
value2 = oid[1]
if value2 > 39 {
return nil, parseError("invalid value for first element of OID: %d", value2)
}
}
bytes := []byte{byte(40*value1 + value2)}
for i := 2; i < len(oid); i++ {
bytes = append(bytes, encodeMultiByteTag(oid[i])...)
}
return bytes, nil
}
func (ctx *Context) decodeOid(data []byte, value reflect.Value) error {
// TODO check value type
if len(data) == 0 {
value.Set(reflect.ValueOf(Oid{}))
return nil
}
value1 := uint(data[0] / 40)
value2 := uint(data[0]) - 40*value1
oid := Oid{value1, value2}
reader := bytes.NewBuffer(data[1:])
for reader.Len() > 0 {
valueN, err := decodeMultiByteTag(reader)
if err != nil {
return parseError("invalid value element in Object Identifier")
}
oid = append(oid, valueN)
}
value.Set(reflect.ValueOf(oid))
return nil
}
// Null is used to encode and decode ASN.1 NULLs.
type Null struct{}
func (ctx *Context) encodeNull(value reflect.Value) ([]byte, error) {
_, ok := value.Interface().(Null)
if !ok {
return nil, wrongType(nullType.String(), value)
}
return []byte{}, nil
}
func (ctx *Context) decodeNull(data []byte, value reflect.Value) error {
// TODO check value type
_, ok := value.Interface().(Null)
if !ok {
return syntaxError("invalid type: %s", value.Type())
}
if len(data) != 0 {
return parseError("invalid data for Null type")
}
return nil
}
/*
* Helper functions
*/
// getActualType recursively gets the underlying type of Interfaces and Pointers.
func getActualType(value reflect.Value) reflect.Value {
for {
if value.Type() == bigIntType {
return value
}
switch value.Kind() {
case reflect.Interface, reflect.Ptr:
value = value.Elem()
default:
return value
}
}
}
func checkInt(ctx *Context, data []byte) error {
if ctx.der.decoding {
if len(data) >= 2 {
if data[0] == 0xff || data[0] == 0x00 {
if data[0]&0x80 == data[1]&0x80 {
return parseError("integer not encoded in the short form")
}
}
}
}
return nil
}
func parseBigInt(data []byte) *big.Int {
data = append([]byte{}, data...)
neg := false
if data[0]&0x80 != 0 {
neg = true
for i, b := range data {
data[i] = ^b
}
}
i := new(big.Int).SetBytes(data)
if neg {
i = i.Add(i, big.NewInt(1)).Neg(i)
}
return i
}
func removeIntLeadingBytes(buf []byte) []byte {
start := 0
for start < len(buf)-1 {
// Removes a leading byte when the first NINE bits are the same
// If the first 8 bits are not the same, skip
if buf[start] != 0x00 && buf[start] != 0xff {
break
}
// And if the 9th bit (1st bit of the second byte) is not the same as the previous 8 bits, also skip
if (buf[start] & 0x80) != (buf[start+1] & 0x80) {
break
}
// Remove a leading byte
start++
}
return buf[start:]
}
func wrongType(typeName string, value reflect.Value) error {
return syntaxError(
"invalid Go type '%s' found when expecting '%s'",
value.Type(), typeName)
}