-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathber.go
282 lines (241 loc) · 6.63 KB
/
ber.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
package ber
import (
"encoding/binary"
"errors"
"fmt"
"strings"
"github.com/ubavic/bas-celik/v2/card/cardErrors"
)
// Represents a node (or a tree) of a BER structure.
// Each leaf node contains data, and it is considered 'primitive'.
// Non-leaf nodes don't contain any data, but they contain references to child nodes.
type BER struct {
tag uint32 // Complete tag of a node.
primitive bool // Denotes if node is a leaf.
data []byte // Data of leaf node. Should only exist if primitive is true.
children []BER // Branch nodes children. Should only exist if primitive is false.
}
// Parses BER data (described in ISO/IEC 7816-4 (2005)).
func ParseBER(data []byte) (*BER, error) {
primitive, constructed, err := parseBERLayer(data)
if err != nil {
return nil, err
}
ber := BER{
tag: 0,
primitive: false,
data: nil,
children: []BER{},
}
for t, v := range primitive {
val := BER{
tag: t,
primitive: true,
data: v,
children: nil,
}
err = ber.add(val)
if err != nil {
return nil, fmt.Errorf("adding primitive value: %w", err)
}
}
for t, v := range constructed {
subBer, err := ParseBER(v)
if err != nil {
return nil, err
}
val := BER{
tag: t,
primitive: false,
data: nil,
children: subBer.children,
}
err = ber.add(val)
if err != nil {
return nil, fmt.Errorf("adding primitive value: %w", err)
}
}
return &ber, nil
}
// Access node's data with the provided address composed as a list of tags.
func (tree BER) access(address ...uint32) ([]byte, error) {
if len(address) == 0 {
return tree.data, nil
} else {
var found *BER = nil
for i := range tree.children {
if tree.children[i].tag == address[0] {
found = &tree.children[i]
break
}
}
if found != nil {
return found.access(address[1:]...)
} else {
return nil, errors.New("tag not found")
}
}
}
// Recursively inserts a new node (with all children nodes) into BER tree. It doesn't copy data.
// If a node with the same tag and the type (primitive/constructed) already exists in tree, then procedure continues
// inserting in deeper levels. If a node with the same tag and different type already exists, function return error.
func (into *BER) add(new BER) error {
if into.primitive {
return errors.New("can't add a value into primitive value")
}
var targetField *BER
alreadyExists := false
for i := range into.children {
if into.children[i].tag == new.tag {
alreadyExists = true
targetField = &into.children[i]
break
}
}
if !alreadyExists {
into.children = append(into.children, new)
return nil
} else {
if targetField.primitive == new.primitive {
if targetField.primitive {
*targetField = new
} else {
for i := range new.children {
err := targetField.add(new.children[i])
if err != nil {
return err
}
}
}
} else {
return errors.New("types don't match")
}
}
return nil
}
// Merge two BER trees by adding all nodes of the second tree into the first tree.
// Doesn't copy an data.+
func (into *BER) Merge(new BER) error {
if into.tag != new.tag {
return errors.New("tags don't match")
}
for _, c := range new.children {
if err := into.add(c); err != nil {
return err
}
}
return nil
}
// Parses one level of BER-TLV encoded data.
// Returns map of primitive and constructed fields.
func parseBERLayer(data []byte) (map[uint32][]byte, map[uint32][]byte, error) {
primF := make(map[uint32][]byte)
consF := make(map[uint32][]byte)
offset := uint32(0)
for {
tag, primitive, offsetDelta, err := ParseTag(data[offset:])
if err != nil {
return nil, nil, err
}
offset += offsetDelta
length, offsetDelta, err := ParseLength(data[offset:])
if err != nil {
return nil, nil, err
}
offset += offsetDelta
value := data[offset : offset+length]
if primitive {
primF[tag] = value
} else {
consF[tag] = value
}
offset += length
if offset == uint32(len(data)) {
break
} else if offset > uint32(len(data)) {
return nil, nil, cardErrors.ErrInvalidLength
}
}
return primF, consF, nil
}
func (tree *BER) AssignFrom(target *string, address ...uint32) {
bytes, err := tree.access(address...)
if err == nil {
*target = string(bytes)
}
}
// Flattens a BER tree into list of strings. Used for printing.
func (tree *BER) levels() []string {
if tree.primitive {
return []string{fmt.Sprintf("%X: %s", tree.tag, string(tree.data))}
} else {
strings := []string{fmt.Sprint(tree.tag) + ":"}
for _, child := range tree.children {
childrenStrings := child.levels()
for i := range childrenStrings {
childrenStrings[i] = " " + childrenStrings[i]
}
strings = append(strings, childrenStrings...)
}
return strings
}
}
// Flattens a BER tree into single string. Each line represents single node of a tree.
func (tree BER) String() string {
return strings.Join(tree.levels(), "\n")
}
// Parses length of a field according to specification given in ISO 7816-4 (5. Organization for interchange).
// Returns parsed length, number of parsed bytes and possible error.
func ParseLength(data []byte) (uint32, uint32, error) {
if len(data) == 0 {
return 0, 0, cardErrors.ErrInvalidLength
}
firstByte := uint32(data[0])
var offset, length uint32
if firstByte < 0x80 {
length = uint32(data[0])
offset = 1
} else if firstByte == 0x80 {
return 0, 0, cardErrors.ErrInvalidFormat
} else if firstByte == 0x81 && len(data) >= 2 {
length = uint32(data[1])
offset = 2
} else if firstByte == 0x82 && len(data) >= 3 {
length = uint32(binary.BigEndian.Uint16(data[1:]))
offset = 3
} else if firstByte == 0x83 && len(data) >= 4 {
length = 0x00FFFFFF & binary.BigEndian.Uint32(data)
offset = 4
} else if firstByte == 0x84 && len(data) >= 5 {
length = binary.BigEndian.Uint32(data[1:])
offset = 5
} else {
return 0, 0, cardErrors.ErrInvalidLength
}
return length, offset, nil
}
// Parses tag of a field according to specification given in ISO 7816-4 (5. Organization for interchange).
// Returns parsed tag, primitive flag, number of parsed bytes and possible error.
func ParseTag(data []byte) (uint32, bool, uint32, error) {
if len(data) == 0 {
return 0, false, 0, cardErrors.ErrInvalidLength
}
primitive := true
if data[0]&0b100000 != 0 {
primitive = false
}
var tag, offset uint32
if 0x1F&data[0] != 0x1F {
tag = uint32(data[0])
offset = 1
} else if len(data) >= 2 && data[1]&0x80 == 0x00 {
tag = uint32(binary.BigEndian.Uint16(data))
offset = 2
} else if len(data) >= 3 {
tag = uint32(data[0])<<16 | uint32(data[1])<<8 | uint32(data[2])
offset = 3
} else {
return 0, false, 0, cardErrors.ErrInvalidLength
}
return tag, primitive, offset, nil
}