File: ber.go

package info (click to toggle)
golang-github-notaryproject-tspclient-go 0.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid, trixie
  • size: 772 kB
  • sloc: makefile: 20
file content (308 lines) | stat: -rw-r--r-- 9,350 bytes parent folder | download
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
// Copyright The Notary Project Authors.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Package ber decodes BER-encoded ASN.1 data structures and encodes in DER.
// Note:
//   - DER is a subset of BER.
//   - Indefinite length is not supported.
//   - The length of the encoded data must fit the memory space of the int type
//     (4 bytes).
//
// Reference:
// - http://luca.ntop.org/Teaching/Appunti/asn1.html
// - ISO/IEC 8825-1:2021
// - https://learn.microsoft.com/windows/win32/seccertenroll/about-introduction-to-asn-1-syntax-and-encoding
package ber

import (
	"bytes"
	"encoding/asn1"
	"fmt"
)

// value is the interface for an ASN.1 value node.
type value interface {
	// EncodeMetadata encodes the identifier and length in DER to the buffer.
	EncodeMetadata(writer) error

	// EncodedLen returns the length in bytes of the data when encoding in DER.
	EncodedLen() int

	// Content returns the content of the value.
	// For primitive values, it returns the content octets.
	// For constructed values, it returns nil because the content is
	// the data of all members.
	Content() []byte
}

// ConvertToDER converts BER-encoded ASN.1 data structures to DER-encoded.
func ConvertToDER(ber []byte) ([]byte, error) {
	if len(ber) == 0 {
		return nil, asn1.SyntaxError{Msg: "BER-encoded ASN.1 data structures is empty"}
	}

	flatValues, err := decode(ber)
	if err != nil {
		return nil, err
	}

	// get the total length from the root value and allocate a buffer
	buf := bytes.NewBuffer(make([]byte, 0, flatValues[0].EncodedLen()))
	for _, v := range flatValues {
		if err = v.EncodeMetadata(buf); err != nil {
			return nil, err
		}

		if content := v.Content(); content != nil {
			// primitive value
			_, err = buf.Write(content)
			if err != nil {
				return nil, err
			}
		}
	}

	return buf.Bytes(), nil
}

// decode decodes BER-encoded ASN.1 data structures.
// To get the DER of `r`, encode the values
// in the returned slice in order.
//
// Parameters:
// r - The input byte slice.
//
// Return:
// []value - The returned value, which is the flat slice of ASN.1 values,
// contains the nodes from a depth-first traversal.
// error - An error that can occur during the decoding process.
//
// Reference: ISO/IEC 8825-1: 8.1.1.3
func decode(r []byte) ([]value, error) {
	// prepare the first value
	identifier, contentLen, r, err := decodeMetadata(r)
	if err != nil {
		return nil, err
	}
	if len(r) != contentLen {
		return nil, asn1.SyntaxError{Msg: fmt.Sprintf("decoding BER: length octets value %d does not match with content length %d", contentLen, len(r))}
	}

	// primitive value
	if isPrimitive(identifier) {
		return []value{&primitive{
			identifier: identifier,
			content:    r,
		}}, nil
	}

	// constructed value
	rootConstructed := &constructed{
		identifier: identifier,
		rawContent: r,
	}
	flatValues := []value{rootConstructed}

	// start depth-first decoding with stack
	contructedStack := []*constructed{rootConstructed}
	for {
		stackLen := len(contructedStack)
		if stackLen == 0 {
			break
		}

		// top
		node := contructedStack[stackLen-1]

		// check that the constructed value is fully decoded
		if len(node.rawContent) == 0 {
			// calculate the length of the members
			for _, m := range node.members {
				node.length += m.EncodedLen()
			}
			// pop
			contructedStack = contructedStack[:stackLen-1]
			continue
		}

		// decode the next member of the constructed value
		nextNodeIdentifier, nextNodeContentLen, remainingContent, err := decodeMetadata(node.rawContent)
		if err != nil {
			return nil, err
		}
		nextNodeContent := remainingContent[:nextNodeContentLen]
		node.rawContent = remainingContent[nextNodeContentLen:]

		if isPrimitive(nextNodeIdentifier) {
			// primitive value
			primitiveNode := &primitive{
				identifier: nextNodeIdentifier,
				content:    nextNodeContent,
			}
			node.members = append(node.members, primitiveNode)
			flatValues = append(flatValues, primitiveNode)
		} else {
			// constructed value
			constructedNode := &constructed{
				identifier: nextNodeIdentifier,
				rawContent: nextNodeContent,
			}
			node.members = append(node.members, constructedNode)

			// add a new constructed node to the stack
			contructedStack = append(contructedStack, constructedNode)
			flatValues = append(flatValues, constructedNode)
		}
	}
	return flatValues, nil
}

// decodeMetadata decodes the metadata of a BER-encoded ASN.1 value.
//
// Parameters:
// r - The input byte slice.
//
// Return:
// []byte - The identifier octets.
// int - The length octets value.
// []byte - The subsequent octets after the length octets.
// error - An error that can occur during the decoding process.
//
// Reference: ISO/IEC 8825-1: 8.1.1.3
func decodeMetadata(r []byte) ([]byte, int, []byte, error) {
	// structure of an encoding (primitive or constructed)
	// +----------------+----------------+----------------+
	// | identifier     | length         | content        |
	// +----------------+----------------+----------------+
	identifier, r, err := decodeIdentifier(r)
	if err != nil {
		return nil, 0, nil, err
	}

	contentLen, r, err := decodeLength(r)
	if err != nil {
		return nil, 0, nil, err
	}

	return identifier, contentLen, r, nil
}

// decodeIdentifier decodes decodeIdentifier octets.
//
// Parameters:
// r - The input byte slice from which the identifier octets are to be decoded.
//
// Returns:
// []byte - The identifier octets decoded from the input byte slice.
// []byte - The remaining part of the input byte slice after the identifier octets.
// error - An error that can occur during the decoding process.
//
// Reference: ISO/IEC 8825-1: 8.1.2
func decodeIdentifier(r []byte) ([]byte, []byte, error) {
	if len(r) < 1 {
		return nil, nil, asn1.SyntaxError{Msg: "decoding BER identifier octets: identifier octets is empty"}
	}
	offset := 0
	b := r[offset]
	offset++

	// high-tag-number form
	// Reference: ISO/IEC 8825-1: 8.1.2.4
	if b&0x1f == 0x1f {
		for offset < len(r) && r[offset]&0x80 == 0x80 {
			offset++
		}
		if offset >= len(r) {
			return nil, nil, asn1.SyntaxError{Msg: "decoding BER identifier octets: high-tag-number form with early EOF"}
		}
		offset++
	}

	if offset >= len(r) {
		return nil, nil, asn1.SyntaxError{Msg: "decoding BER identifier octets: early EOF due to missing length and content octets"}
	}
	return r[:offset], r[offset:], nil
}

// decodeLength decodes length octets.
// Indefinite length is not supported
//
// Parameters:
// r - The input byte slice from which the length octets are to be decoded.
//
// Returns:
// int - The length decoded from the input byte slice.
// []byte - The remaining part of the input byte slice after the length octets.
// error - An error that can occur during the decoding process.
//
// Reference: ISO/IEC 8825-1: 8.1.3
func decodeLength(r []byte) (int, []byte, error) {
	if len(r) < 1 {
		return 0, nil, asn1.SyntaxError{Msg: "decoding BER length octets: length octets is empty"}
	}
	offset := 0
	b := r[offset]
	offset++

	if b < 0x80 {
		// short form
		// Reference: ISO/IEC 8825-1: 8.1.3.4
		contentLen := int(b)
		subsequentOctets := r[offset:]
		if contentLen > len(subsequentOctets) {
			return 0, nil, asn1.SyntaxError{Msg: "decoding BER length octets: short form length octets value should be less or equal to the subsequent octets length"}
		}
		return contentLen, subsequentOctets, nil
	}

	if b == 0x80 {
		// Indefinite-length method is not supported.
		// Reference: ISO/IEC 8825-1: 8.1.3.6.1
		return 0, nil, asn1.StructuralError{Msg: "decoding BER length octets: indefinite length not supported"}
	}

	// long form
	// Reference: ISO/IEC 8825-1: 8.1.3.5
	n := int(b & 0x7f)
	if n > 4 {
		// length must fit the memory space of the int type (4 bytes).
		return 0, nil, asn1.StructuralError{Msg: fmt.Sprintf("decoding BER length octets: length of encoded data (%d bytes) cannot exceed 4 bytes", n)}
	}
	if offset+n >= len(r) {
		return 0, nil, asn1.SyntaxError{Msg: "decoding BER length octets: long form length octets with early EOF"}
	}
	var length uint64
	for i := 0; i < n; i++ {
		length = (length << 8) | uint64(r[offset])
		offset++
	}

	// length must fit the memory space of the int32.
	if (length >> 31) > 0 {
		return 0, nil, asn1.StructuralError{Msg: fmt.Sprintf("decoding BER length octets: length %d does not fit the memory space of int32", length)}
	}

	contentLen := int(length)
	subsequentOctets := r[offset:]
	if contentLen > len(subsequentOctets) {
		return 0, nil, asn1.SyntaxError{Msg: "decoding BER length octets: long form length octets value should be less or equal to the subsequent octets length"}
	}
	return contentLen, subsequentOctets, nil
}

// isPrimitive returns true if the first identifier octet is marked
// as primitive.
// Reference: ISO/IEC 8825-1: 8.1.2.5
func isPrimitive(identifier []byte) bool {
	return identifier[0]&0x20 == 0
}