forked from ThomasMertes/seed7
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asn1.s7i
543 lines (499 loc) · 16.1 KB
/
asn1.s7i
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
(********************************************************************)
(* *)
(* asn1.s7i Support for Abstract Syntax Notation One (ASN.1). *)
(* Copyright (C) 2013, 2022, 2023 Thomas Mertes *)
(* *)
(* This file is part of the Seed7 Runtime Library. *)
(* *)
(* The Seed7 Runtime Library is free software; you can *)
(* redistribute it and/or modify it under the terms of the GNU *)
(* Lesser General Public License as published by the Free Software *)
(* Foundation; either version 2.1 of the License, or (at your *)
(* option) any later version. *)
(* *)
(* The Seed7 Runtime Library is distributed in the hope that it *)
(* will be useful, but WITHOUT ANY WARRANTY; without even the *)
(* implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR *)
(* PURPOSE. See the GNU Lesser General Public License for more *)
(* details. *)
(* *)
(* You should have received a copy of the GNU Lesser General *)
(* Public License along with this program; if not, write to the *)
(* Free Software Foundation, Inc., 51 Franklin Street, *)
(* Fifth Floor, Boston, MA 02110-1301, USA. *)
(* *)
(********************************************************************)
include "bytedata.s7i";
include "unicode.s7i";
const array string: classTagName is [0] (
"EOC (End-of-Content)",
"BOOLEAN",
"INTEGER",
"BIT STRING",
"OCTET STRING",
"NULL",
"OBJECT IDENTIFIER",
"Object Descriptor",
"EXTERNAL",
"REAL (float)",
"ENUMERATED",
"EMBEDDED PDV",
"UTF8String",
"RELATIVE-OID",
"(reserved 14)",
"(reserved 15)",
"SEQUENCE",
"SET",
"NumericString",
"PrintableString",
"T61String",
"VideotexString",
"IA5String",
"UTCTime",
"GeneralizedTime",
"GraphicString",
"VisibleString",
"GeneralString",
"UniversalString",
"CHARACTER STRING",
"BMPString",
"(use long-form)"
);
(**
* Tag type used by ASN.1/BER data elements.
*)
const type: asn1TagType is new enum
tagEndOfContent,
tagBoolean,
tagInteger,
tagBitString,
tagOctetString,
tagNull,
tagObjectIdentifier,
tagObjectDescriptor,
tagExternal,
tagReal,
tagEnumerated,
tagEmbeddedPdv,
tagUTF8String,
tagRelativeOid,
tagReserved14,
tagReserved15,
tagSequence,
tagSet,
tagNumericString,
tagPrintableString,
tagT61String,
tagVideotexString,
tagIA5String,
tagUTCTime,
tagGeneralizedTime,
tagGraphicString,
tagVisibleString,
tagGeneralString,
tagUniversalString,
tagCharacterString,
tagBMPString,
tagUseLongForm
end enum;
const type: asn1TagClass is new enum
universalTagClass, applicationTagClass, contextSpecificTagClass, privateTagClass
end enum;
(**
* ASN.1/BER data element.
* This type is used for reading ASN.1/BER data.
*)
const type: asn1DataElement is new struct
var asn1TagClass: tagClass is universalTagClass;
var boolean: constructed is FALSE;
var asn1TagType: tagType is tagEndOfContent;
var boolean: indefinite is FALSE;
var integer: dataStart is 0;
var integer: length is 0;
end struct;
# The element tagCategory is deprecated. Use tagType instead.
const func asn1TagType: (in asn1DataElement: dataElem) . tagCategory is
return dataElem.tagType;
const varfunc asn1TagType: (inout asn1DataElement: dataElem) . tagCategory is
return var dataElem.tagType;
const func string: encodeObjectIdentifier (in array integer: oid) is func
result
var string: encodedOid is "";
local
var integer: pos is 3;
var integer: subId is 0;
var string: subIdStri is "";
begin
encodedOid := str(chr(oid[1] * 40 + oid[2]));
while pos <= length(oid) do
subId := oid[pos];
if subId < 0 then
raise RANGE_ERROR;
elsif subId <= 127 then
# Encode in one byte
encodedOid &:= chr(subId);
else
subIdStri := str(chr(subId mod 128));
subId := subId mdiv 128;
repeat
subIdStri := str(chr(subId mod 128 + 128)) & subIdStri;
subId := subId mdiv 128;
until subId = 0;
encodedOid &:= subIdStri;
end if;
incr(pos);
end while;
end func;
const func array integer: decodeObjectIdentifier (in string: encodedOid) is func
result
var array integer: oid is 0 times 0;
local
var integer: pos is 2;
var integer: subId is 0;
var boolean: highBitClear is FALSE;
begin
oid &:= ord(encodedOid[1]) mdiv 40;
oid &:= ord(encodedOid[1]) mod 40;
while pos <= length(encodedOid) do
subId := 0;
repeat
subId *:= 128;
subId +:= ord(encodedOid[pos]) mod 128;
highBitClear := ord(encodedOid[pos]) <= 127;
incr(pos);
until highBitClear;
oid &:= subId;
end while;
end func;
const func string: objectIdentifier (in string: encodedOid) is func
result
var string: stri is "";
local
var integer: pos is 2;
var integer: subId is 0;
var boolean: highBitClear is FALSE;
begin
stri := str(ord(encodedOid[1]) mdiv 40);
stri &:= " " & str(ord(encodedOid[1]) mod 40);
while pos <= length(encodedOid) do
subId := 0;
repeat
subId *:= 128;
subId +:= ord(encodedOid[pos]) mod 128;
highBitClear := ord(encodedOid[pos]) <= 127;
incr(pos);
until highBitClear;
stri &:= " " & str(subId);
end while;
end func;
(**
* Read the header of an ASN.1/BER data element, from ''stri''.
* It is assumed that the data element header starts at position ''pos''.
* The function advances ''pos'' beyond the header to the actual data.
* The actual data can be read afterwards, with the function ''getData''.
* dataElem := getAsn1DataElement(asn1, pos);
* if dataElem.tagType = tagObjectIdentifier then
* contentType := getData(asn1, pos, dataElem);
* ...
* @return the header of an ASN.1/BER data element.
*)
const func asn1DataElement: getAsn1DataElement (in string: stri, inout integer: pos) is func
result
var asn1DataElement: dataElement is asn1DataElement.value;
local
var integer: classTag is 0;
var integer: length is 0;
var integer: eocPos is 0;
var integer: numOctets is 0;
begin
classTag := ord(stri[pos]);
incr(pos);
length := ord(stri[pos]);
incr(pos);
dataElement.tagClass := asn1TagClass conv (classTag >> 6);
dataElement.constructed := (classTag >> 5) mod 2 <> 0;
dataElement.tagType := asn1TagType conv (classTag mod 32);
if length <= 127 then
# Short form
# writeln("Short form: length=" <& length <& ", pos=" <& pos);
dataElement.length := length;
elsif length = 128 then
# Indefinite form
# writeln(" *** indefinite form ***");
dataElement.indefinite := TRUE;
eocPos := pos(stri, "\0;\0;", pos);
if eocPos <> 0 then
dataElement.length := eocPos - pos;
else
dataElement.length := length(stri) + 1 - pos;
end if;
else
# Long form
numOctets := length mod 128;
dataElement.length := bytes2Int(stri[pos fixLen numOctets], UNSIGNED, BE);
pos +:= numOctets;
end if;
dataElement.dataStart := pos;
end func;
(**
* Read the data of a given ASN.1/BER ''dataElement'', from ''stri''.
* It is assumed that the actual data starts at position ''pos''.
* The function advances ''pos'' beyond the ''dataElement'' data.
* @return the data of the ASN.1/BER ''dataElement''.
*)
const func string: getData (in string: stri, inout integer: pos,
in asn1DataElement: dataElement) is func
result
var string: data is "";
begin
data := stri[dataElement.dataStart len dataElement.length];
pos +:= dataElement.length;
end func;
(**
* Skip the data of a given ASN.1/BER ''dataElement'', from ''stri''.
* It is assumed that the actual data starts at position ''pos''.
* The function advances ''pos'' beyond the ''dataElement'' data.
*)
const proc: skipData (inout integer: pos, in asn1DataElement: dataElement) is func
begin
pos +:= dataElement.length;
end func;
const func string: genAsn1Length (in integer: length) is func
result
var string: asn1 is "";
local
var string: lengthAsBytes is "";
begin
if length <= 127 then
# Short form
asn1 &:= chr(length);
else
# Long form
lengthAsBytes := bytes(length, UNSIGNED, BE);
asn1 &:= chr(128 + length(lengthAsBytes));
asn1 &:= lengthAsBytes;
end if;
end func;
const func asn1TagType: asn1TagTypeOfString (in string: stri) is func
result
var asn1TagType: tagType is tagEndOfContent;
local
const set of char: visibleChar is {' ' .. '~'}; # ASCII without control chars
const set of char: printableChar is
{'A' .. 'Z'} | {'a' .. 'z'} | {'0' .. '9'} |
{' ', ''', '(', ')', '+', ',', '-', '.', '/', ':', '=', '?'};
var boolean: isPrintableString is TRUE;
var boolean: isVisibleString is TRUE;
var char: ch is ' ';
begin
for ch range stri until not isPrintableString do
if ch not in printableChar then
isPrintableString := FALSE;
end if;
if ch not in visibleChar then
isVisibleString := FALSE;
end if;
end for;
if isPrintableString then
tagType := tagPrintableString;
elsif isVisibleString then
tagType := tagVisibleString;
else
tagType := tagUTF8String;
end if;
end func;
(**
* Create an ASN.1/BER data element from ''tagType'' and ''data''.
* @return the ASN.1/BER data element as [[string]].
*)
const func string: genAsn1Element (in asn1TagType: tagType, in string: data) is func
result
var string: asn1 is "";
begin
asn1 &:= chr(ord(tagType));
asn1 &:= genAsn1Length(length(data));
asn1 &:= data;
end func;
(**
* Create an integer ASN.1/BER data element from ''data''.
* The tag type of the generated data element is tagInteger.
* genAsn1Integer(bytes(123, SIGNED, BE)) returns "\2;\1;{"
* @return the integer ASN.1/BER data element as [[string]].
*)
const func string: genAsn1Integer (in string: data) is func
result
var string: asn1 is "";
begin
asn1 &:= chr(ord(tagInteger));
asn1 &:= genAsn1Length(length(data));
asn1 &:= data;
end func;
(**
* Create a string ASN.1/BER data element from ''data''.
* Depending on ''data'' the tag type of the generated data element
* is tagPrintableString, tagVisibleString or tagUTF8String.
* genAsn1String("abc") returns "\19;\3;abc"
* genAsn1String("#%&") returns "\26;\3;#%&"
* genAsn1String("€") returns "\f\3;â\130;¬"
* @return the string ASN.1/BER data element as [[string]].
*)
const func string: genAsn1String (in string: data) is func
result
var string: asn1 is "";
local
var asn1TagType: tagType is tagEndOfContent;
begin
tagType := asn1TagTypeOfString(data);
if tagType = tagUTF8String then
asn1 := genAsn1Element(tagUTF8String, toUtf8(data));
else
asn1 := genAsn1Element(tagType, data);
end if;
end func;
(**
* Create a sequence ASN.1/BER data element from ''data''.
* The tag type of the generated data element is tagSequence.
* @return the sequence ASN.1/BER data element as [[string]].
*)
const func string: genAsn1Sequence (in string: data) is func
result
var string: asn1 is "";
begin
# A sequence is universal (0) and constructed (32).
asn1 &:= chr(ord(tagSequence) + 32);
asn1 &:= genAsn1Length(length(data));
asn1 &:= data;
end func;
(**
* Create a set ASN.1/BER data element from ''data''.
* The tag type of the generated data element is tagSet.
* @return the set ASN.1/BER data element as [[string]].
*)
const func string: genAsn1Set (in string: data) is func
result
var string: asn1 is "";
begin
# A set is universal (0) and constructed (32).
asn1 &:= chr(ord(tagSet) + 32);
asn1 &:= genAsn1Length(length(data));
asn1 &:= data;
end func;
(**
* Create an explicit ASN.1/BER tag with ''tagNumber'' from ''data''.
* @return the explicit ASN.1/BER tag as [[string]].
*)
const func string: genExplicitAsn1Tag (in integer: tagNumber, in string: data) is func
result
var string: asn1 is "";
begin
# A tag is context-specific (128) and constructed (32).
asn1 &:= chr(tagNumber + 160);
asn1 &:= genAsn1Length(length(data));
asn1 &:= data;
end func;
const proc: printAsn1 (in string: stri, inout integer: pos) is func
local
var integer: startPos is 0;
var boolean: constructed is TRUE;
var integer: classTag is 0;
var asn1TagType: tagType is tagEndOfContent;
var integer: length is 0;
var integer: numOctets is 0;
var string: contents is "";
var integer: posAfterwards is 0;
var integer: subId is 0;
begin
startPos := pos;
write(pos lpad 5 <& ": ");
classTag := ord(stri[pos]);
incr(pos);
length := ord(stri[pos]);
incr(pos);
write(classTag radix 16 lpad0 2 <& " ");
write("UACP"[(classTag >> 6) + 1]);
constructed := (classTag >> 5) mod 2 <> 0;
write("PC"[succ(ord(constructed))]);
tagType := asn1TagType conv (classTag mod 32);
write(" " <& length radix 16 lpad0 2);
if classTag mod 32 = 31 then
writeln(" *** long form *** ");
end if;
if length <= 127 then
# Short form
# writeln("Short form: length=" <& length <& ", pos=" <& pos);
contents := stri[pos len length];
posAfterwards := pos + length;
elsif length = 128 then
# Indefinite form
writeln(" *** indefinite form ***");
posAfterwards := pos;
contents := getAsciiz(stri, posAfterwards);
if pos <= length(stri) and stri[pos] = '\0;' then
incr(pos);
else
writeln(" *** Second byte of EOC (End-of-Content) not 0");
end if;
else
# Long form
numOctets := length mod 128;
if numOctets <= 7 then
length := bytes2Int(stri[pos fixLen numOctets], UNSIGNED, BE);
# writeln("Long form: numOctets=" <& numOctets <& ", length=" <& length);
else
writeln(" *** numOctets (" <& numOctets <& ") too big.");
length := 0;
end if;
pos +:= numOctets;
contents := stri[pos len length];
posAfterwards := pos + length;
end if;
write(" " <& length lpad 4);
if (classTag >> 6) = 2 then
write(" EXPLICIT TAG [" <& ord(tagType) <& "]");
else
write(" " <& classTagName[ord(tagType)]);
end if;
if tagType = tagObjectIdentifier then
write(":");
for subId range decodeObjectIdentifier(contents) do
write(" " <& subId);
end for;
writeln(" (" <& literal(contents) <& ")");
else
writeln(": " <& literal(contents));
end if;
if constructed then
while pos < posAfterwards do
printAsn1(stri, pos);
end while;
if pos <> posAfterwards then
writeln("strange things happen " <& pos <& " " <& posAfterwards);
end if;
writeln("Leaving construct started at " <& startPos);
else
if posAfterwards > succ(length(stri)) then
writeln("strange things happen " <& posAfterwards <& " " <& succ(length(stri)));
end if;
pos := posAfterwards;
end if;
end func;
const proc: printAsn1 (in string: stri) is func
local
var integer: pos is 1;
begin
while pos < length(stri) do
printAsn1(stri, pos);
end while;
end func;
const proc: searchLengthByte (in string: stri, in integer: pos) is func
local
var integer: testPos is 0;
var integer: printPos is 0;
begin
for testPos range pred(pos) downto 2 do
if ord(stri[testPos]) = pred(pos - testPos) then
printPos := pred(testPos);
printAsn1(stri, printPos);
end if;
end for;
end func;