This repository has been archived by the owner on Oct 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
rubyasn1.y
469 lines (407 loc) · 12.9 KB
/
rubyasn1.y
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
# $Id: rubyasn1.y 84 2005-12-26 11:06:10Z mks $
# Copyright (C) 2005 MATSUYAMA Kengo <[email protected]>. All rights reserved.
# This program is free software; you can redistribute it and/or modify it
# under the GNU General Public License version 2, or any later version.
# BNF description is borrowed from Convert::ASN1 module for Perl.
# Convert::ASN1 is copyrighted by Graham Barr <[email protected]>.
class ASN1::Parser
token WORD
token CLASS
token SEQUENCE
token SET
token CHOICE
token OF
token IMPLICIT
token EXPLICIT
token OPTIONAL
token LBRACE
token RBRACE
token COMMA
token ANY
token ASSIGN
token NUMBER
token ENUM
token COMPONENTS
token POSTRBRACE
token DEFINED
token BY
rule
top: slist { result = { '' => val[0] } }
| module
;
module: WORD ASSIGN aitem { result = { val[0] => [val[2]] } }
| module WORD ASSIGN aitem { result[val[1]] = [val[3]] }
;
aitem: class plicit anyelem postrb
{
val[2].tag = val[0]
result = val[2]
result.tag_explicit! if val[1]
}
| celem
;
anyelem: onelem
| eelem
| oelem
| selem
;
celem: COMPONENTS OF WORD
{
result = ASN1Type.new( :type => val[0], :child => val[2] )
}
;
seqset: SEQUENCE
| SET
;
selem: seqset OF class plicit sselem optional
{
val[4].tag = val[2]
result = ASN1Type.new(
:type => val[0],
:child => [val[4]],
:loop => true,
:optional => val[5]
)
result.tag_explicit! if val[3]
}
;
sselem: eelem
| oelem
| onelem
;
onelem: SEQUENCE LBRACE slist RBRACE
{
result = ASN1Type.new( :type => val[0], :child => val[2] )
}
| SET LBRACE slist RBRACE
{
result = ASN1Type.new( :type => val[0], :child => val[2] )
}
| CHOICE LBRACE nlist RBRACE
{
result = ASN1Type.new( :type => val[0], :child => val[2] )
}
;
eelem: ENUM LBRACE elist RBRACE { result = ASN1Type.new( :type => 'ENUM' ) }
oielem: WORD { result = ASN1Type.new( :type => val[0] ) }
| SEQUENCE { result = ASN1Type.new( :type => val[0] ) }
| SET { result = ASN1Type.new( :type => val[0] ) }
| ANY defined
{
result = ASN1Type.new(
:type => val[0],
:child => [],
:def_by => val[1]
)
}
| ENUM { result = ASN1Type.new( :type => val[0] ) }
;
defined: /* none */ { result = nil }
| DEFINED BY WORD { result = val[2].gsub(/-/, '_').intern }
;
oelem: oielem
;
nlist: nlist1
| nlist1 POSTRBRACE
;
nlist1: nitem { result = [val[0]] }
| nlist1 POSTRBRACE nitem { result.push val[2] }
| nlist1 COMMA nitem { result.push val[2] }
;
nitem: varname class plicit anyelem
{
result = val[3]
result.name = val[0]
result.tag = val[1]
result.tag_explicit! if val[2]
}
;
slist: slist1
| slist1 POSTRBRACE
;
slist1: sitem { result = [val[0]] }
| slist1 COMMA sitem { result.push val[2] }
| slist1 POSTRBRACE sitem { result.push val[2] }
;
snitem: oelem optional { result.optional = val[1] }
| eelem
| selem
| onelem
;
sitem: varname class plicit snitem
{
result = val[3]
result.name = val[0]
result.tag = val[1]
result.tag_explicit! if val[2]
}
| celem
| class plicit onelem
{
result = val[2]
result.tag = val[0]
result.tag_explicit! if val[1]
}
;
varname: WORD { result = val[0].gsub(/-/, '_').intern }
;
optional: /* none */ { result = false }
| OPTIONAL { result = true }
;
class: /* none */ { result = nil }
| CLASS
;
plicit: /* none */ { result = false }
| EXPLICIT { result = true }
| IMPLICIT { result = false }
;
/* @todo: implement enum */
elist: eitem
| elist COMMA eitem
;
eitem: WORD NUMBER
;
postrb: /* none */
| POSTRBRACE
;
end
---- header
require 'strscan'
---- inner
RESERVED_WORDS = {
'OPTIONAL' => :OPTIONAL,
'CHOICE' => :CHOICE,
'OF' => :OF,
'IMPLICIT' => :IMPLICIT,
'EXPLICIT' => :EXPLICIT,
'SEQUENCE' => :SEQUENCE,
'SET' => :SET,
'ANY' => :ANY,
'ENUM' => :ENUM,
'ENUMERATED' => :ENUM,
'COMPONENTS' => :COMPONENTS,
'{' => :LBRACE,
'}' => :RBRACE,
',' => :COMMA,
'::=' => :ASSIGN,
'DEFINED' => :DEFINED,
'BY' => :BY
}
TAG_CLASSES = {
'APPLICATION' => CLASS_APPLICATION,
'UNIVERSAL' => CLASS_UNIVERSAL,
'PRIVATE' => CLASS_PRIVATE,
'CONTEXT' => CLASS_CONTEXT,
'' => CLASS_CONTEXT # if not specified, it's CONTEXT
}
REGEXP_PATTERN = /(?:
(\s+|--[^\n]*)
| ([,{}]|::=)
| (#{RESERVED_WORDS.keys.grep(/\w/).sort.join('|')})\b
| ( (?:OCTET|BIT)\s+STRING
| OBJECT\s+IDENTIFIER
| RELATIVE-OID
)\b
| (\w+(?:-\w+)*)
| \[\s* (
(?:(?:APPLICATION|PRIVATE|UNIVERSAL|CONTEXT)\s+)?
\d+
) \s*\]
| \((\d+)\)
)/mxo
BASE_TYPES = {
'BOOLEAN' => [ TAG_BOOLEAN.chr, :opBOOLEAN ],
'INTEGER' => [ TAG_INTEGER.chr, :opINTEGER ],
'BIT_STRING' => [ TAG_BIT_STRING.chr, :opBITSTR ],
'OCTET_STRING' => [ TAG_OCTET_STRING.chr, :opSTRING ],
'STRING' => [ TAG_OCTET_STRING.chr, :opSTRING ],
'NULL' => [ TAG_NULL.chr, :opNULL ],
'OBJECT_IDENTIFIER' => [ TAG_OBJECT_IDENTIFIER.chr, :opOBJID ],
'REAL' => [ TAG_REAL.chr, :opREAL ],
'ENUMERATED' => [ TAG_ENUMERATED.chr, :opINTEGER ],
'ENUM' => [ TAG_ENUMERATED.chr, :opINTEGER ],
'RELATIVE-OID' => [ TAG_RELATIVE_OID.chr, :opROID ],
'SEQUENCE' => [ (TAG_SEQUENCE | TAG_CONSTRUCTIVE).chr, :opSEQUENCE ],
'SET' => [ (TAG_SET | TAG_CONSTRUCTIVE).chr, :opSET ],
'ObjectDescriptor' => [ TAG_OBJECT_DESCRIPTOR.chr, :opSTRING ],
'UTF8String' => [ TAG_UTF8_STRING.chr, :opSTRING ],
'NumericString' => [ TAG_NUMERIC_STRING.chr, :opSTRING ],
'PrintableString' => [ TAG_PRINTABLE_STRING.chr, :opSTRING ],
'TeletexString' => [ TAG_TELETEX_STRING.chr, :opSTRING ],
'T61String' => [ TAG_TELETEX_STRING.chr, :opSTRING ],
'VideotexString' => [ TAG_VIDEOTEX_STRING.chr, :opSTRING ],
'IA5String' => [ TAG_IA5_STRING.chr, :opSTRING ],
'UTCTime' => [ TAG_UTC_TIME.chr, :opUTIME ],
'GeneralizedTime' => [ TAG_GENERALIZED_TIME.chr, :opGTIME ],
'GraphicString' => [ TAG_GRAPHIC_STRING.chr, :opSTRING ],
'VisibleString' => [ TAG_VISIBLE_STRING.chr, :opSTRING ],
'ISO646String' => [ TAG_VISIBLE_STRING.chr, :opSTRING ],
'GeneralString' => [ TAG_GENERAL_STRING.chr, :opSTRING ],
'CharacterString' => [ TAG_CHARACTER_STRING.chr, :opSTRING ],
'UniversalString' => [ TAG_CHARACTER_STRING.chr, :opSTRING ],
'BMPString' => [ TAG_BMP_STRING.chr, :opSTRING ],
'BCDString' => [ TAG_OCTET_STRING.chr, :opBCD ],
'CHOICE' => [ nil, :opCHOICE ],
'ANY' => [ nil, :opANY ],
}
attr_reader :error, :backtrace
def parse(str)
@scanner = StringScanner.new(str)
@stack = []
@lastpos = 0
@pos = 0
tree = nil
begin
tree = compile(verify(do_parse))
rescue ASN1Error, Racc::ParseError => e
@error = e.to_s
@backtrace = e.backtrace
return nil
end
return ASN1Converter.new(tree)
end
def next_token
return @stack.shift unless @stack.empty?
while (token = @scanner.scan(REGEXP_PATTERN))
if @scanner[1]
next # comment or whitespace
elsif @scanner[2] || @scanner[3]
# A comma is not required after a '}' so to aid the
# parser we insert a fake token after any '}'
@stack.push [:POSTRBRACE, ''] if token == '}'
return [RESERVED_WORDS[token], token]
elsif @scanner[4]
return [:WORD, token.gsub(/\s+/, '_')]
elsif @scanner[5]
return [:WORD, token]
elsif @scanner[6]
tag_class, num = /^([A-Z]*)\s*(\d+)$/.match(@scanner[6]).captures
tag = ASN1.encode_tag(TAG_CLASSES[tag_class], num.to_i)
return [:CLASS, tag]
elsif @scanner[7]
return [:NUMBER, @scanner[7]]
end
raise 'Internal error'
end
return nil if @scanner.eos?
raise ASN1Error, "Parse error before #{@scanner.string.slice(@scanner.pos, 40)}"
end
def verify(tree)
# Well it parsed correctly, now we
# - check references exist
# - flatten COMPONENTS OF (checking for loops)
# - check for duplicate var names
tree.each do |name, ops|
stash = {}
scope = []
path = ''
idx = 0
while true
if idx < ops.size
op = ops[idx]
idx += 1
if op.name
raise ASN1Error, "#{name}: #{path}.#{op.name} used multiple times." if stash[op.name]
stash[op.name] = true
end
if op.child
if op.child.is_a?(Array)
scope.push [stash, path, ops, idx]
if op.name
stash = {}
path += ".#{op.name}"
end
idx = 0
ops = op.child
elsif op.type == 'COMPONENTS'
idx -= 1
ops[idx, 1] = expand_ops(tree, op.child)
else
raise 'Internal error.'
end
end
else
break if scope.empty?
stash, path, ops, idx = scope.pop
end
end
end
return tree
end
def expand_ops(tree, want, seen = {})
raise ASN1Error, "COMPONENTS OF loop #{want}" if seen[want]
raise ASN1Error, "Undefined macro #{want}" unless tree.has_key?(want)
seen[want] = true
ops = tree[want]
if ops.size == 1 && (ops[0].type == 'SEQUENCE' || ops[0].type == 'SET') && ops[0].child.is_a?(Array)
ops = ops[0].child
idx = 0
while idx < ops.size
op = ops[idx]
if op.type == 'COMPONENTS'
ops[idx, 1] = expand_ops(tree, op.child, seen)
else
idx += 1
end
end
else
raise ASN1Error, "Bad macro COMPONENTS OF '#{want}'"
end
return ops
end
def compile(tree)
# The tree should be valid enough to be able to
# - resolve references
# - encode tags
# - verify CHOICEs do not contain duplicate tags
tree.each do |name, ops|
compile_one(tree, ops, name)
end
return tree
end
def compile_one(tree, ops, name)
ops.each do |op|
next if op.type.is_a?(Symbol) # skip if already compiled
type = op.type
if BASE_TYPES[type]
op.tag ||= BASE_TYPES[type][0]
op.type = BASE_TYPES[type][1]
else
raise ASN1Error, "Unknown type '#{type}'" unless tree[type]
ref = compile_one(tree, tree[type], op.name ? "#{name}.#{op.name}" : name)
op.tag ||= ref[0].tag
op.type = ref[0].type
op.child = ref[0].child
op.loop = ref[0].loop
end
op.tag_constructive! if op.type == :opSET || op.type == :opSEQUENCE
if op.child
# If we have children we are one of
# opSET opSEQUENCE opCHOICE
compile_one(tree, op.child, op.name ? "#{name}.#{op.name}" : name)
# If a CHOICE is given a tag, then it must be EXPLICIT
if op.type == :opCHOICE && op.tag
op.tag_explicit!
op.tag_constructive!
op.type = :opSEQUENCE
end
if op.child.size > 1
#if ($op->[cTYPE] != opSEQUENCE) {
# Here we need to flatten CHOICEs and check that SET and CHOICE
# do not contain duplicate tags
#}
if op.type == :opSET
# In case we do CER encoding we order the SET elements by thier tags
op.child = op.child.sort_by do |c|
c.tag || (c.type == :opCHOICE ? c.child.map { |cc| cc.tag }.min : '')
end
end
else
# A SET of one element can be treated the same as a SEQUENCE
op.type = :opSEQUENCE if op.type == :opSET
end
end
end
return ops
end
---- footer