@lapo/asn1js 2.0.1 → 2.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/README.md +28 -8
  2. package/asn1.js +41 -19
  3. package/defs.js +138 -0
  4. package/package.json +24 -5
  5. package/rfcdef.js +10377 -0
package/README.md CHANGED
@@ -5,8 +5,8 @@ asn1js is a JavaScript generic ASN.1 parser/decoder that can decode any valid AS
5
5
 
6
6
  An example page that can decode Base64-encoded (raw base64, PEM armoring and `begin-base64` are recognized) or Hex-encoded (or local files with some browsers) is included and can be used both [online on the official website](https://lapo.it/asn1js/) or [offline (ZIP file)](https://lapo.it/asn1js/asn1js.zip).
7
7
 
8
- Usage with `npm` / `yarn`
9
- -------------------------
8
+ Usage with `nodejs`
9
+ -------------------
10
10
 
11
11
  This package can be installed with either npm or yarn via the following commands:
12
12
 
@@ -17,19 +17,38 @@ pnpm install @lapo/asn1js
17
17
  yarn add @lapo/asn1js
18
18
  ```
19
19
 
20
- Assuming a standard javascript bundler is setup you can import it like so:
20
+ You can import the classes like this:
21
21
 
22
22
  ```js
23
- import ASN1 from '@lapo/asn1js';
23
+ import { ASN1 } from '@lapo/asn1js';
24
24
  ```
25
25
 
26
26
  A submodule of this package can also be imported:
27
27
 
28
28
  ```js
29
- import Hex from '@lapo/asn1js/hex';
29
+ import { Hex } from '@lapo/asn1js/hex.js';
30
30
  ```
31
31
 
32
- Unfortunately until [`require(esm)` gets released](https://joyeecheung.github.io/blog/2024/03/18/require-esm-in-node-js/) it is necessary to use async `import()` when used from CommonJS (legacy NodeJS) code.
32
+ If your code is still not using ES6 Modules (and is using CommonJS) you can `require` it normally [since NodeJS 22](https://joyeecheung.github.io/blog/2024/03/18/require-esm-in-node-js/) (with parameter `--experimental-require-module`):
33
+
34
+ ```js
35
+ const
36
+ { ASN1 } = require('@lapo/asn1js'),
37
+ { Hex } = require('@lapo/asn1js/hex.js');
38
+ console.log(ASN1.decode(Hex.decode('06032B6570')).content());
39
+ ```
40
+
41
+ On older NodeJS you instead need to use async `import`:
42
+
43
+ ```js
44
+ async function main() {
45
+ const
46
+ { ASN1 } = await import('@lapo/asn1js'),
47
+ { Hex } = await import('@lapo/asn1js/hex.js');
48
+ console.log(ASN1.decode(Hex.decode('06032B6570')).content());
49
+ }
50
+ main();
51
+ ```
33
52
 
34
53
  Usage on the web
35
54
  --------------------
@@ -38,7 +57,7 @@ Can be [tested on JSFiddle](https://jsfiddle.net/lapo/y6t2wo7q/).
38
57
 
39
58
  ```html
40
59
  <script>
41
- import { ASN1} from 'https://unpkg.com/@lapo/asn1js@2.0.0/asn1.js';
60
+ import { ASN1 } from 'https://unpkg.com/@lapo/asn1js@2.0.0/asn1.js';
42
61
  import { Hex } from 'https://unpkg.com/@lapo/asn1js@2.0.0/hex.js';
43
62
 
44
63
  document.body.innerText = ASN1.decode(Hex.decode('06032B6570')).content();
@@ -62,7 +81,7 @@ credits
62
81
  - extended tag support added by [Péter Budai](https://www.peterbudai.eu/)
63
82
  - patches by [Gergely Nagy](https://github.com/ngg)
64
83
  - Relative OID support added by [Mistial Developer](https://github.com/mistial-dev)
65
- - dark mode support added by [Oliver Burgmaier](https://github.com/olibu/)
84
+ - dark mode and other UI improvements by [Oliver Burgmaier](https://github.com/olibu/)
66
85
  - patches by [Nicolai Søborg](https://github.com/NicolaiSoeborg)
67
86
 
68
87
  links
@@ -70,6 +89,7 @@ links
70
89
 
71
90
  - [official website](https://lapo.it/asn1js/)
72
91
  - [dedicated domain](https://asn1js.eu/)
92
+ - [single-file version working locally](https://asn1js.eu/index-local.html) (just save this link)
73
93
  - [InDefero tracker](http://idf.lapo.it/p/asn1js/)
74
94
  - [GitHub mirror](https://github.com/lapo-luchini/asn1js)
75
95
  - [Ohloh code stats](https://www.openhub.net/p/asn1js)
package/asn1.js CHANGED
@@ -72,17 +72,21 @@ class Stream {
72
72
  if (pos === undefined)
73
73
  pos = this.pos++;
74
74
  if (pos >= this.enc.length)
75
- throw 'Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length;
75
+ throw new Error('Requesting byte offset ' + pos + ' on a stream of length ' + this.enc.length);
76
76
  return (typeof this.enc == 'string') ? this.enc.charCodeAt(pos) : this.enc[pos];
77
77
  }
78
78
  hexByte(b) {
79
79
  return hexDigits.charAt((b >> 4) & 0xF) + hexDigits.charAt(b & 0xF);
80
80
  }
81
- hexDump(start, end, raw) {
81
+ /** Hexadecimal dump.
82
+ * @param type 'raw', 'byte' or 'dump' */
83
+ hexDump(start, end, type = 'dump') {
82
84
  let s = '';
83
85
  for (let i = start; i < end; ++i) {
86
+ if (type == 'byte' && i > start)
87
+ s += ' ';
84
88
  s += this.hexByte(this.get(i));
85
- if (raw !== true)
89
+ if (type == 'dump')
86
90
  switch (i & 0xF) {
87
91
  case 0x7: s += ' '; break;
88
92
  case 0xF: s += '\n'; break;
@@ -190,7 +194,7 @@ class Stream {
190
194
  let s = this.parseStringISO(start, end).str,
191
195
  m = (shortYear ? reTimeS : reTimeL).exec(s);
192
196
  if (!m)
193
- return 'Unrecognized time: ' + s;
197
+ throw new Error('Unrecognized time: ' + s);
194
198
  if (shortYear) {
195
199
  // to avoid querying the timer, use the fixed range [1970, 2069]
196
200
  // it will conform with ITU X.400 [-10, +40] sliding window until 2030
@@ -245,7 +249,7 @@ class Stream {
245
249
  parseBitString(start, end, maxLength) {
246
250
  let unusedBits = this.get(start);
247
251
  if (unusedBits > 7)
248
- throw 'Invalid BitString with unusedBits=' + unusedBits;
252
+ throw new Error('Invalid BitString with unusedBits=' + unusedBits);
249
253
  let lenBit = ((end - start - 1) << 3) - unusedBits,
250
254
  s = '';
251
255
  for (let i = start + 1; i < end; ++i) {
@@ -368,7 +372,7 @@ class ASN1Tag {
368
372
 
369
373
  export class ASN1 {
370
374
  constructor(stream, header, length, tag, tagLen, sub) {
371
- if (!(tag instanceof ASN1Tag)) throw 'Invalid tag value.';
375
+ if (!(tag instanceof ASN1Tag)) throw new Error('Invalid tag value.');
372
376
  this.stream = stream;
373
377
  this.header = header;
374
378
  this.length = length;
@@ -485,7 +489,16 @@ export class ASN1 {
485
489
  }
486
490
  toPrettyString(indent) {
487
491
  if (indent === undefined) indent = '';
488
- let s = indent + this.typeName() + ' @' + this.stream.pos;
492
+ let s = indent;
493
+ if (this.def) {
494
+ if (this.def.id)
495
+ s += this.def.id + ' ';
496
+ if (this.def.name && this.def.name != this.typeName().replace(/_/g, ' '))
497
+ s+= this.def.name + ' ';
498
+ if (this.def.mismatch)
499
+ s += '[?] ';
500
+ }
501
+ s += this.typeName() + ' @' + this.stream.pos;
489
502
  if (this.length >= 0)
490
503
  s += '+';
491
504
  s += this.length;
@@ -517,9 +530,12 @@ export class ASN1 {
517
530
  posLen() {
518
531
  return this.stream.pos + this.tagLen;
519
532
  }
520
- toHexString() {
521
- return this.stream.hexDump(this.posStart(), this.posEnd(), true);
533
+ /** Hexadecimal dump of the node.
534
+ * @param type 'raw', 'byte' or 'dump' */
535
+ toHexString(type = 'raw') {
536
+ return this.stream.hexDump(this.posStart(), this.posEnd(), type);
522
537
  }
538
+ /** Base64 dump of the node. */
523
539
  toB64String() {
524
540
  return this.stream.b64Dump(this.posStart(), this.posEnd());
525
541
  }
@@ -531,7 +547,7 @@ export class ASN1 {
531
547
  if (len === 0) // long form with length 0 is a special case
532
548
  return null; // undefined length
533
549
  if (len > 6) // no reason to use Int10, as it would be a huge buffer anyways
534
- throw 'Length over 48 bits not supported at position ' + (stream.pos - 1);
550
+ throw new Error('Length over 48 bits not supported at position ' + (stream.pos - 1));
535
551
  buf = 0;
536
552
  for (let i = 0; i < len; ++i)
537
553
  buf = (buf * 256) + stream.get();
@@ -539,7 +555,7 @@ export class ASN1 {
539
555
  }
540
556
  static decode(stream, offset, type = ASN1) {
541
557
  if (!(type == ASN1 || type.prototype instanceof ASN1))
542
- throw 'Must pass a class that extends ASN1';
558
+ throw new Error('Must pass a class that extends ASN1');
543
559
  if (!(stream instanceof Stream))
544
560
  stream = new Stream(stream, offset || 0);
545
561
  let streamStart = new Stream(stream),
@@ -555,11 +571,11 @@ export class ASN1 {
555
571
  // definite length
556
572
  let end = start + len;
557
573
  if (end > stream.enc.length)
558
- throw 'Container at offset ' + start + ' has a length of ' + len + ', which is past the end of the stream';
574
+ throw new Error('Container at offset ' + start + ' has a length of ' + len + ', which is past the end of the stream');
559
575
  while (stream.pos < end)
560
576
  sub[sub.length] = type.decode(stream);
561
577
  if (stream.pos != end)
562
- throw 'Content size is not correct for container at offset ' + start;
578
+ throw new Error('Content size is not correct for container at offset ' + start);
563
579
  } else {
564
580
  // undefined length
565
581
  try {
@@ -571,7 +587,7 @@ export class ASN1 {
571
587
  }
572
588
  len = start - stream.pos; // undefined lengths are represented as negative values
573
589
  } catch (e) {
574
- throw 'Exception while decoding undefined length content at offset ' + start + ': ' + e;
590
+ throw new Error('Exception while decoding undefined length content at offset ' + start + ': ' + e);
575
591
  }
576
592
  }
577
593
  };
@@ -583,11 +599,17 @@ export class ASN1 {
583
599
  try {
584
600
  if (tag.tagNumber == 0x03)
585
601
  if (stream.get() != 0)
586
- throw 'BIT STRINGs with unused bits cannot encapsulate.';
602
+ throw new Error('BIT STRINGs with unused bits cannot encapsulate.');
587
603
  getSub();
588
- for (let i = 0; i < sub.length; ++i)
589
- if (sub[i].tag.isEOC())
590
- throw 'EOC is not supposed to be actual content.';
604
+ for (let s of sub) {
605
+ if (s.tag.isEOC())
606
+ throw new Error('EOC is not supposed to be actual content.');
607
+ try {
608
+ s.content();
609
+ } catch (e) {
610
+ throw new Error('Unable to parse content: ' + e);
611
+ }
612
+ }
591
613
  } catch (e) {
592
614
  // but silently ignore when they don't
593
615
  sub = null;
@@ -596,7 +618,7 @@ export class ASN1 {
596
618
  }
597
619
  if (sub === null) {
598
620
  if (len === null)
599
- throw "We can't skip over an invalid tag with undefined length at offset " + start;
621
+ throw new Error("We can't skip over an invalid tag with undefined length at offset " + start);
600
622
  stream.pos = start + Math.abs(len);
601
623
  }
602
624
  return new type(streamStart, header, len, tag, tagLen, sub);
package/defs.js ADDED
@@ -0,0 +1,138 @@
1
+ // ASN.1 RFC definitions matcher
2
+ // Copyright (c) 2023-2024 Lapo Luchini <lapo@lapo.it>
3
+
4
+ // Permission to use, copy, modify, and/or distribute this software for any
5
+ // purpose with or without fee is hereby granted, provided that the above
6
+ // copyright notice and this permission notice appear in all copies.
7
+ //
8
+ // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9
+ // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10
+ // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11
+ // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12
+ // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13
+ // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14
+ // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15
+
16
+ import { rfcdef } from './rfcdef.js';
17
+
18
+ function translate(def, tn, stats) {
19
+ if (def?.type == 'tag' && !def.explicit)
20
+ // def.type = def.content[0].type;
21
+ def = def.content[0].type;
22
+ if (def?.definedBy)
23
+ try {
24
+ // hope current OIDs contain the type name (will need to parse from RFC itself)
25
+ def = Defs.searchType(firstUpper(stats.defs[def.definedBy][1]));
26
+ } catch (e) { /*ignore*/ }
27
+ while (def?.type == 'defined' || def?.type?.type == 'defined') {
28
+ const name = def?.type?.type ? def.type.name : def.name;
29
+ def = Object.assign({}, def);
30
+ def.type = Defs.searchType(name).type;
31
+ }
32
+ if (def?.type?.name == 'CHOICE') {
33
+ for (let c of def.type.content) {
34
+ if (tn != c.type.name && tn != c.name)
35
+ c = translate(c);
36
+ if (tn == c.type.name || tn == c.name) {
37
+ def = Object.assign({}, def);
38
+ def.type = c.type.name ? c.type : c;
39
+ break;
40
+ }
41
+ }
42
+ }
43
+ const id = def?.id;
44
+ if (id)
45
+ def = Object.assign({}, def, { id });
46
+ return def ?? { type: {} };
47
+ }
48
+
49
+ function firstUpper(s) {
50
+ return s[0].toUpperCase() + s.slice(1);
51
+ }
52
+
53
+ export class Defs {
54
+
55
+ static moduleAndType(mod, name) {
56
+ return Object.assign({ module: { oid: mod.oid, name: mod.name, source: mod.source } }, mod.types[name]);
57
+ }
58
+
59
+ static searchType(name) {
60
+ for (const mod of Object.values(rfcdef))
61
+ if (name in mod.types) {
62
+ // console.log(name + ' found in ' + r.name);
63
+ // return r.types[name];
64
+ return Defs.moduleAndType(mod, name);
65
+ }
66
+ throw new Error('Type not found: ' + name);
67
+ }
68
+
69
+ static match(value, def, stats = { total: 0, recognized: 0, defs: {} }) {
70
+ value.def = {};
71
+ let tn = value.typeName().replaceAll('_', ' ');
72
+ def = translate(def, tn, stats);
73
+ ++stats.total;
74
+ if (def?.type) {
75
+ // if (def.id || def.name) ++stats.recognized;
76
+ if (tn == def.type.name || tn == def.name || def.name == 'ANY')
77
+ ++stats.recognized;
78
+ else if (def.name)
79
+ def = Object.assign({ mismatch: 1 }, def);
80
+ value.def = def;
81
+ }
82
+ if (value.sub !== null) {
83
+ if (def?.type?.type)
84
+ def = def.type;
85
+ let j = def?.content ? 0 : -1;
86
+ for (const subval of value.sub) {
87
+ let type;
88
+ if (j >= 0) {
89
+ if (def.typeOf)
90
+ type = def.content[0];
91
+ else {
92
+ let tn = subval.typeName().replaceAll('_', ' ');
93
+ for (;;) {
94
+ type = def.content[j++];
95
+ if (!type || typeof type != 'object') break;
96
+ if (type?.type?.type)
97
+ type = type.type;
98
+ if (type.type == 'defined') {
99
+ let t2 = translate(type, tn);
100
+ if (t2.type.name == tn) break; // exact match
101
+ if (t2.type.name == 'ANY') break; // good enough
102
+ }
103
+ if (type.name == tn) break; // exact match
104
+ if (type.name == 'ANY') break; // good enough
105
+ if (!('optional' in type || 'default' in type)) break;
106
+ }
107
+ if (type?.type == 'builtin' || type?.type == 'defined') {
108
+ let v = subval.content();
109
+ if (typeof v == 'string')
110
+ v = v.split(/\n/);
111
+ stats.defs[type.id] = v;
112
+ } else if (type?.definedBy && stats.defs?.[type.definedBy]?.[1]) { // hope current OIDs contain the type name (will need to parse from RFC itself)
113
+ try {
114
+ type = Defs.searchType(firstUpper(stats.defs[type.definedBy][1]));
115
+ } catch (e) { /*ignore*/ }
116
+ }
117
+ }
118
+ }
119
+ Defs.match(subval, type, stats);
120
+ }
121
+ }
122
+ return stats;
123
+ }
124
+
125
+ }
126
+
127
+ Defs.RFC = rfcdef;
128
+
129
+ Defs.commonTypes = [
130
+ [ 'X.509 certificate', '1.3.6.1.5.5.7.0.18', 'Certificate' ],
131
+ [ 'X.509 public key info', '1.3.6.1.5.5.7.0.18', 'SubjectPublicKeyInfo' ],
132
+ [ 'CMS / PKCS#7 envelope', '1.2.840.113549.1.9.16.0.14', 'ContentInfo' ],
133
+ [ 'PKCS#1 RSA private key', '1.2.840.113549.1.1.0.1', 'RSAPrivateKey' ],
134
+ [ 'PKCS#8 encrypted private key', '1.2.840.113549.1.8.1.1', 'EncryptedPrivateKeyInfo' ],
135
+ [ 'PKCS#8 private key', '1.2.840.113549.1.8.1.1', 'PrivateKeyInfo' ],
136
+ [ 'PKCS#10 certification request', '1.2.840.113549.1.10.1.1', 'CertificationRequest' ],
137
+ [ 'CMP PKI Message', '1.3.6.1.5.5.7.0.16', 'PKIMessage' ],
138
+ ].map(arr => ({ description: arr[0], ...Defs.moduleAndType(rfcdef[arr[1]], arr[2]) }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lapo/asn1js",
3
- "version": "2.0.1",
3
+ "version": "2.0.3",
4
4
  "description": "Generic ASN.1 parser/decoder that can decode any valid ASN.1 DER or BER structures.",
5
5
  "type": "module",
6
6
  "main": "asn1.js",
@@ -13,18 +13,32 @@
13
13
  "license": "ISC",
14
14
  "bugs": { "url": "https://github.com/lapo-luchini/asn1js/issues" },
15
15
  "homepage": "https://lapo.it/asn1js/",
16
- "files": [ "asn1.js", "base64.js", "hex.js", "int10.js", "oids.js" ],
16
+ "files": [ "asn1.js", "base64.js", "hex.js", "int10.js", "defs.js", "oids.js", "rfcdef.js" ],
17
17
  "scripts": {
18
- "lint": "npx eslint asn1.js base64.js hex.js int10.js oids.js tags.js index.js parseRFC.js dumpASN1.js",
18
+ "lint": "npx eslint asn1.js base64.js hex.js int10.js defs.js oids.js rfcdef.js tags.js context.js index.js parseRFC.js dumpASN1.js test.js testDefs.js vite.config.js",
19
19
  "lint-action": "npx @action-validator/cli .github/workflows/node.js.yml",
20
+ "build": "vite build",
20
21
  "serve": "echo 'Connect to http://localhost:3000/' ; npx statik --port 3000 .",
21
- "test": "node test"
22
+ "test": "node test",
23
+ "testdefs": "node testDefs"
22
24
  },
23
25
  "engines": {
24
26
  "node": ">=12.20.0"
25
27
  },
26
28
  "devDependencies": {
27
- "eslint": "^8.34.0"
29
+ "eslint": "^8.34.0",
30
+ "htmlparser2": "^9.1.0",
31
+ "vite": "^5.2.10",
32
+ "vite-plugin-dom": "^1.0.3",
33
+ "vite-plugin-singlefile": "^2.0.1"
34
+ },
35
+ "overrides": {
36
+ "rollup": "npm:@rollup/wasm-node"
37
+ },
38
+ "pnpm": {
39
+ "overrides": {
40
+ "rollup": "npm:@rollup/wasm-node"
41
+ }
28
42
  },
29
43
  "eslintConfig": {
30
44
  "env": {
@@ -81,6 +95,11 @@
81
95
  "parserOptions": {
82
96
  "ecmaVersion": 2021
83
97
  }
98
+ }, {
99
+ "files": [ "testDefs.js" ],
100
+ "parserOptions": {
101
+ "ecmaVersion": 2022
102
+ }
84
103
  }
85
104
  ]
86
105
  }