@tik-choco/mistsign 0.0.0-stage → 0.1.1
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.
- package/LICENSE +373 -0
- package/README.ja.md +125 -0
- package/README.md +129 -2
- package/README.zh.md +122 -0
- package/dist/agreement/bundle.d.ts +23 -0
- package/dist/agreement/bundle.js +139 -0
- package/dist/agreement/decision.d.ts +7 -0
- package/dist/agreement/decision.js +77 -0
- package/dist/agreement/errors.d.ts +9 -0
- package/dist/agreement/errors.js +19 -0
- package/dist/agreement/evaluate.d.ts +5 -0
- package/dist/agreement/evaluate.js +112 -0
- package/dist/agreement/index.d.ts +9 -0
- package/dist/agreement/index.js +6 -0
- package/dist/agreement/policy.d.ts +31 -0
- package/dist/agreement/policy.js +113 -0
- package/dist/agreement/proposal.d.ts +4 -0
- package/dist/agreement/proposal.js +107 -0
- package/dist/agreement/schema.d.ts +16 -0
- package/dist/agreement/schema.js +93 -0
- package/dist/agreement/strict.d.ts +5 -0
- package/dist/agreement/strict.js +167 -0
- package/dist/agreement/types.d.ts +214 -0
- package/dist/agreement/types.js +3 -0
- package/dist/agreement/verify.d.ts +4 -0
- package/dist/agreement/verify.js +151 -0
- package/dist/bytes.d.ts +6 -0
- package/dist/bytes.js +19 -0
- package/dist/content.d.ts +10 -0
- package/dist/content.js +58 -0
- package/dist/didKey.d.ts +4 -0
- package/dist/didKey.js +48 -0
- package/dist/elements/index.d.ts +1 -0
- package/dist/elements/index.js +2 -0
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +8 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +6 -0
- package/dist/json.d.ts +20 -0
- package/dist/json.js +170 -0
- package/dist/preact/index.d.ts +1 -0
- package/dist/preact/index.js +2 -0
- package/dist/preact/ui.css +0 -0
- package/dist/sha256.d.ts +11 -0
- package/dist/sha256.js +103 -0
- package/dist/sign.d.ts +33 -0
- package/dist/sign.js +61 -0
- package/dist/testing/index.d.ts +5 -0
- package/dist/testing/index.js +27 -0
- package/dist/time.d.ts +9 -0
- package/dist/time.js +36 -0
- package/dist/timestamp/asnTime.d.ts +2 -0
- package/dist/timestamp/asnTime.js +17 -0
- package/dist/timestamp/cms.d.ts +30 -0
- package/dist/timestamp/cms.js +126 -0
- package/dist/timestamp/constraints.d.ts +17 -0
- package/dist/timestamp/constraints.js +159 -0
- package/dist/timestamp/crypto.d.ts +6 -0
- package/dist/timestamp/crypto.js +101 -0
- package/dist/timestamp/der.d.ts +24 -0
- package/dist/timestamp/der.js +118 -0
- package/dist/timestamp/index.d.ts +2 -0
- package/dist/timestamp/index.js +1 -0
- package/dist/timestamp/name.d.ts +2 -0
- package/dist/timestamp/name.js +55 -0
- package/dist/timestamp/policy.d.ts +9 -0
- package/dist/timestamp/policy.js +56 -0
- package/dist/timestamp/verify.d.ts +33 -0
- package/dist/timestamp/verify.js +74 -0
- package/dist/timestamp/x509.d.ts +35 -0
- package/dist/timestamp/x509.js +232 -0
- package/dist/transport/index.d.ts +1 -0
- package/dist/transport/index.js +2 -0
- package/dist/trust/delegation.d.ts +15 -0
- package/dist/trust/delegation.js +40 -0
- package/dist/trust/index.d.ts +15 -0
- package/dist/trust/index.js +3 -0
- package/dist/trust/revocation.d.ts +33 -0
- package/dist/trust/revocation.js +78 -0
- package/dist/trust/signers.d.ts +31 -0
- package/dist/trust/signers.js +166 -0
- package/dist/verify.d.ts +88 -0
- package/dist/verify.js +195 -0
- package/dist/wire.d.ts +6 -0
- package/dist/wire.js +38 -0
- package/package.json +89 -4
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { check, fields } from './der.js';
|
|
2
|
+
function domain(s, subtree = false) {
|
|
3
|
+
const labels = subtree && s.startsWith('.') ? s.slice(1) : s;
|
|
4
|
+
check(s === '' || (labels.length > 0 && !/[^!-~]|^\.|\.$|\.\./.test(labels)));
|
|
5
|
+
return s.toLowerCase();
|
|
6
|
+
}
|
|
7
|
+
// Normalize the local part's quoting, but preserve its case.
|
|
8
|
+
function mailbox(s) {
|
|
9
|
+
const quoted = s.startsWith('"');
|
|
10
|
+
let i = quoted ? 1 : 0;
|
|
11
|
+
let local = '';
|
|
12
|
+
while (i < s.length) {
|
|
13
|
+
const c = s[i++];
|
|
14
|
+
if (quoted && c === '"')
|
|
15
|
+
break;
|
|
16
|
+
if (!quoted && c === '@') {
|
|
17
|
+
i--;
|
|
18
|
+
break;
|
|
19
|
+
}
|
|
20
|
+
if (c === '\\') {
|
|
21
|
+
check(i < s.length);
|
|
22
|
+
const escaped = s[i++];
|
|
23
|
+
if (quoted)
|
|
24
|
+
check(!/[\x00\n\r]/.test(escaped));
|
|
25
|
+
local += escaped;
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
if (quoted)
|
|
29
|
+
check(!/[\x00\t\n\r]/.test(c));
|
|
30
|
+
else
|
|
31
|
+
check(/^[a-zA-Z0-9!#$%&'*+/=?^_\x60{|}~.-]$/.test(c));
|
|
32
|
+
local += c;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
check(s[i] === '@' && (quoted || (local.length > 0 && !/^\.|\.$|\.\./.test(local))));
|
|
36
|
+
return [local, domain(s.slice(i + 1))];
|
|
37
|
+
}
|
|
38
|
+
function uriHost(uri) {
|
|
39
|
+
check(!/[\x00-\x20\x7f\\]|%(?![0-9a-f]{2})/i.test(uri));
|
|
40
|
+
// Read the RFC 3986 authority literally. WHATWG URL normalizes DNS and IP
|
|
41
|
+
// spellings, which can change the result of a signed name constraint.
|
|
42
|
+
const authority = /^(?:[a-z][a-z0-9+.-]*:)?\/\/([^/?#]*)/i.exec(uri)?.[1];
|
|
43
|
+
if (!authority)
|
|
44
|
+
return '';
|
|
45
|
+
const hostPort = authority.slice(authority.lastIndexOf('@') + 1);
|
|
46
|
+
const m = /^(\[[0-9a-f:.]+\]|[^:[\]%]*)(?::[0-9]*)?$/i.exec(hostPort);
|
|
47
|
+
check(m);
|
|
48
|
+
return domain(m[1]);
|
|
49
|
+
}
|
|
50
|
+
function ipLiteral(s) {
|
|
51
|
+
return s.startsWith('[') || /^(?:\d{1,3}\.){3}\d{1,3}$/.test(s);
|
|
52
|
+
}
|
|
53
|
+
function readName(v, subtree) {
|
|
54
|
+
if (v.tag === 0x87) {
|
|
55
|
+
const b = v.body;
|
|
56
|
+
check(subtree ? b.length === 8 || b.length === 32 : b.length === 4 || b.length === 16);
|
|
57
|
+
if (subtree) {
|
|
58
|
+
let zero = false;
|
|
59
|
+
for (const byte of b.subarray(b.length / 2)) {
|
|
60
|
+
for (let bit = 128; bit >= 1; bit /= 2) {
|
|
61
|
+
if (byte & bit)
|
|
62
|
+
check(!zero);
|
|
63
|
+
else
|
|
64
|
+
zero = true;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return { tag: v.tag, text: '', ip: b };
|
|
69
|
+
}
|
|
70
|
+
if (![0x81, 0x82, 0x86].includes(v.tag))
|
|
71
|
+
return;
|
|
72
|
+
check(v.body.every(b => b < 128));
|
|
73
|
+
let text = new TextDecoder().decode(v.body);
|
|
74
|
+
if (subtree) {
|
|
75
|
+
if (v.tag === 0x81 && text.includes('@'))
|
|
76
|
+
mailbox(text);
|
|
77
|
+
else
|
|
78
|
+
text = domain(text, true);
|
|
79
|
+
if (v.tag === 0x86)
|
|
80
|
+
check(!ipLiteral(text) && !text.includes(':'));
|
|
81
|
+
}
|
|
82
|
+
else if (v.tag === 0x86)
|
|
83
|
+
text = uriHost(text);
|
|
84
|
+
return { tag: v.tag, text, ip: v.body };
|
|
85
|
+
}
|
|
86
|
+
export function subjectAltNames(v) {
|
|
87
|
+
return fields(v).map(n => readName(n, false)).filter((n) => !!n);
|
|
88
|
+
}
|
|
89
|
+
export function nameConstraints(v) {
|
|
90
|
+
const result = { permitted: [], excluded: [], unhandled: false };
|
|
91
|
+
let lastTag = 0x9f;
|
|
92
|
+
for (const group of fields(v, 0x30, 1, 2)) {
|
|
93
|
+
check((group.tag === 0xa0 || group.tag === 0xa1) && group.tag > lastTag);
|
|
94
|
+
lastTag = group.tag;
|
|
95
|
+
for (const subtree of fields(group, group.tag, 1)) {
|
|
96
|
+
const [base] = fields(subtree, 0x30, 1, 1);
|
|
97
|
+
const name = readName(base, true);
|
|
98
|
+
if (!name)
|
|
99
|
+
result.unhandled = true;
|
|
100
|
+
else
|
|
101
|
+
(group.tag === 0xa0 ? result.permitted : result.excluded).push(name);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return result;
|
|
105
|
+
}
|
|
106
|
+
function ipv4Mapped(b) {
|
|
107
|
+
return b.length === 16 && b.subarray(0, 10).every(n => n === 0) && b[10] === 255 && b[11] === 255;
|
|
108
|
+
}
|
|
109
|
+
function matchesIP(ip, range) {
|
|
110
|
+
let network = range.subarray(0, range.length / 2), mask = range.subarray(range.length / 2);
|
|
111
|
+
if (ipv4Mapped(ip))
|
|
112
|
+
ip = ip.subarray(12);
|
|
113
|
+
if (ipv4Mapped(network)) {
|
|
114
|
+
network = network.subarray(12);
|
|
115
|
+
mask = mask.subarray(12);
|
|
116
|
+
}
|
|
117
|
+
return network.length === ip.length && network.every((b, i) => ((b ^ ip[i]) & mask[i]) === 0);
|
|
118
|
+
}
|
|
119
|
+
export function permitsNames(nc, names, budget) {
|
|
120
|
+
for (const name of names) {
|
|
121
|
+
const email = name.tag === 0x81 ? mailbox(name.text) : undefined;
|
|
122
|
+
const host = domain(email?.[1] ?? name.text);
|
|
123
|
+
if (name.tag === 0x86)
|
|
124
|
+
check(host && !ipLiteral(host));
|
|
125
|
+
function matches(rule, exclude) {
|
|
126
|
+
if (name.tag === 0x87)
|
|
127
|
+
return matchesIP(name.ip, rule.ip);
|
|
128
|
+
const s = rule.text;
|
|
129
|
+
if (email && s.includes('@')) {
|
|
130
|
+
const [local, suffix] = mailbox(s);
|
|
131
|
+
return local === email[0] && suffix === host;
|
|
132
|
+
}
|
|
133
|
+
if (!s || host === s || host.endsWith(s.startsWith('.') ? s : '.' + s))
|
|
134
|
+
return true;
|
|
135
|
+
// An excluded host inside a wildcard SAN also rules out that wildcard.
|
|
136
|
+
return exclude && host.startsWith('*') && s.includes('.') && host.includes('.') &&
|
|
137
|
+
host.slice(host.indexOf('.')) === s.slice(s.indexOf('.'));
|
|
138
|
+
}
|
|
139
|
+
let limited = false, allowed = false;
|
|
140
|
+
for (const rule of nc.excluded) {
|
|
141
|
+
check(--budget.remaining >= 0);
|
|
142
|
+
if (rule.tag === name.tag && matches(rule, true))
|
|
143
|
+
return false;
|
|
144
|
+
}
|
|
145
|
+
for (const rule of nc.permitted) {
|
|
146
|
+
check(--budget.remaining >= 0);
|
|
147
|
+
if (rule.tag !== name.tag)
|
|
148
|
+
continue;
|
|
149
|
+
limited = true;
|
|
150
|
+
if (matches(rule, false)) {
|
|
151
|
+
allowed = true;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
if (limited && !allowed)
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
return true;
|
|
159
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Algorithm, Der } from './der.js';
|
|
2
|
+
export type Hash = 'SHA-256' | 'SHA-384' | 'SHA-512';
|
|
3
|
+
export declare function digestAlgorithm(alg: Algorithm): Hash;
|
|
4
|
+
export declare function hashBytes(hash: Hash | 'SHA-1', data: Uint8Array<ArrayBuffer>): Promise<Uint8Array<ArrayBuffer>>;
|
|
5
|
+
/** CMS supplies the digest separately. X.509 requires a combined algorithm. */
|
|
6
|
+
export declare function verifySignature(spki: Der, alg: Algorithm, data: Uint8Array<ArrayBuffer>, signature: Uint8Array<ArrayBuffer>, cmsHash?: Hash): Promise<boolean>;
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { algorithm, bitString, check, decode, fields, nullOrAbsent, oid, only, positive, uint } from './der.js';
|
|
2
|
+
const hashes = {
|
|
3
|
+
'2.16.840.1.101.3.4.2.1': 'SHA-256',
|
|
4
|
+
'2.16.840.1.101.3.4.2.2': 'SHA-384',
|
|
5
|
+
'2.16.840.1.101.3.4.2.3': 'SHA-512',
|
|
6
|
+
};
|
|
7
|
+
const rsa = '1.2.840.113549.1.1.1';
|
|
8
|
+
const pss = '1.2.840.113549.1.1.10';
|
|
9
|
+
const ec = '1.2.840.10045.2.1';
|
|
10
|
+
const combinedRSA = {
|
|
11
|
+
'1.2.840.113549.1.1.11': 'SHA-256',
|
|
12
|
+
'1.2.840.113549.1.1.12': 'SHA-384',
|
|
13
|
+
'1.2.840.113549.1.1.13': 'SHA-512',
|
|
14
|
+
};
|
|
15
|
+
const combinedEC = {
|
|
16
|
+
'1.2.840.10045.4.3.2': 'SHA-256',
|
|
17
|
+
'1.2.840.10045.4.3.3': 'SHA-384',
|
|
18
|
+
'1.2.840.10045.4.3.4': 'SHA-512',
|
|
19
|
+
};
|
|
20
|
+
const curves = {
|
|
21
|
+
'1.2.840.10045.3.1.7': ['P-256', 32], '1.3.132.0.34': ['P-384', 48], '1.3.132.0.35': ['P-521', 66],
|
|
22
|
+
};
|
|
23
|
+
export function digestAlgorithm(alg) {
|
|
24
|
+
const hash = hashes[alg.id];
|
|
25
|
+
check(hash && nullOrAbsent(alg.params));
|
|
26
|
+
return hash;
|
|
27
|
+
}
|
|
28
|
+
export async function hashBytes(hash, data) {
|
|
29
|
+
return new Uint8Array(await crypto.subtle.digest(hash, data));
|
|
30
|
+
}
|
|
31
|
+
function pssParameters(params) {
|
|
32
|
+
const [hashField, mgfField, ...optional] = fields(params, 0x30, 2, 4);
|
|
33
|
+
const hash = digestAlgorithm(algorithm(only(hashField, 0xa0)));
|
|
34
|
+
const mgf = algorithm(only(mgfField, 0xa1));
|
|
35
|
+
check(mgf.id === '1.2.840.113549.1.1.8' && mgf.params && digestAlgorithm(algorithm(mgf.params)) === hash);
|
|
36
|
+
let saltLength = 20;
|
|
37
|
+
if (optional[0]?.tag === 0xa2)
|
|
38
|
+
saltLength = uint(only(optional.shift(), 0xa2));
|
|
39
|
+
if (optional.length)
|
|
40
|
+
check(uint(only(optional.shift(), 0xa3)) === 1);
|
|
41
|
+
check(!optional.length);
|
|
42
|
+
return { hash, saltLength };
|
|
43
|
+
}
|
|
44
|
+
function rawECDSA(der, width) {
|
|
45
|
+
const parts = fields(decode(der), 0x30, 2, 2);
|
|
46
|
+
const raw = new Uint8Array(2 * width);
|
|
47
|
+
for (const [i, part] of parts.entries()) {
|
|
48
|
+
const n = positive(part);
|
|
49
|
+
check(n.length > 0 && n.length <= width);
|
|
50
|
+
raw.set(n, (i + 1) * width - n.length);
|
|
51
|
+
}
|
|
52
|
+
return raw;
|
|
53
|
+
}
|
|
54
|
+
/** CMS supplies the digest separately. X.509 requires a combined algorithm. */
|
|
55
|
+
export async function verifySignature(spki, alg, data, signature, cmsHash) {
|
|
56
|
+
const [keyAlg, keyBits] = fields(spki, 0x30, 2, 2);
|
|
57
|
+
const publicKey = algorithm(keyAlg);
|
|
58
|
+
// Go's X.509 verifier accepts an Ed25519 issuer. CMS TSA signatures are
|
|
59
|
+
// independently restricted to RSA and ECDSA.
|
|
60
|
+
if (!cmsHash && alg.id === '1.3.101.112') {
|
|
61
|
+
check(publicKey.id === alg.id && !publicKey.params && !alg.params && bitString(keyBits).length === 32);
|
|
62
|
+
const key = await crypto.subtle.importKey('spki', spki.raw, 'Ed25519', false, ['verify']);
|
|
63
|
+
return crypto.subtle.verify('Ed25519', key, signature, data);
|
|
64
|
+
}
|
|
65
|
+
const pssParams = alg.id === pss ? pssParameters(alg.params) : undefined;
|
|
66
|
+
const combined = pssParams?.hash ?? combinedRSA[alg.id] ?? combinedEC[alg.id];
|
|
67
|
+
const hash = combined ?? cmsHash;
|
|
68
|
+
check(hash && (!cmsHash || cmsHash === hash));
|
|
69
|
+
check(pssParams || nullOrAbsent(alg.params));
|
|
70
|
+
if (alg.id === ec || combinedEC[alg.id]) {
|
|
71
|
+
check(publicKey.id === ec && publicKey.params);
|
|
72
|
+
const curve = curves[oid(publicKey.params)];
|
|
73
|
+
check(curve);
|
|
74
|
+
const [namedCurve, width] = curve;
|
|
75
|
+
const point = bitString(keyBits);
|
|
76
|
+
check(point[0] === 4 && point.length === 1 + 2 * width);
|
|
77
|
+
const key = await crypto.subtle.importKey('spki', spki.raw, { name: 'ECDSA', namedCurve }, false, ['verify']);
|
|
78
|
+
return crypto.subtle.verify({ name: 'ECDSA', hash }, key, rawECDSA(signature, width), data);
|
|
79
|
+
}
|
|
80
|
+
check(alg.id === rsa || alg.id === pss || combinedRSA[alg.id]);
|
|
81
|
+
check(publicKey.id === rsa && publicKey.params?.tag === 5 && nullOrAbsent(publicKey.params));
|
|
82
|
+
const [modulus, exponent] = fields(decode(bitString(keyBits)), 0x30, 2, 2);
|
|
83
|
+
const n = positive(modulus);
|
|
84
|
+
const bits = n.length * 8 - (Math.clz32(n[0]) - 24);
|
|
85
|
+
const e = uint(exponent);
|
|
86
|
+
check(bits >= 2048 && bits <= 16384 && (n[n.length - 1] & 1) === 1);
|
|
87
|
+
check(e >= 3 && e <= 0x7fffffff && e % 2 === 1);
|
|
88
|
+
if (signature.length !== n.length)
|
|
89
|
+
return false;
|
|
90
|
+
const name = pssParams ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5';
|
|
91
|
+
const key = await crypto.subtle.importKey('spki', spki.raw, { name, hash }, false, ['verify']);
|
|
92
|
+
if (pssParams) {
|
|
93
|
+
const hashBytes = Number(hash.slice(4)) / 8;
|
|
94
|
+
// Go's X.509 parser only recognizes PSS certificate signatures with
|
|
95
|
+
// digest-sized salts. CMS encodes its salt length independently.
|
|
96
|
+
check(pssParams.saltLength <= Math.ceil((bits - 1) / 8) - hashBytes - 2);
|
|
97
|
+
check(cmsHash || pssParams.saltLength === hashBytes);
|
|
98
|
+
return crypto.subtle.verify({ name, saltLength: pssParams.saltLength }, key, signature, data);
|
|
99
|
+
}
|
|
100
|
+
return crypto.subtle.verify(name, key, signature, data);
|
|
101
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface Der {
|
|
2
|
+
tag: number;
|
|
3
|
+
raw: Uint8Array<ArrayBuffer>;
|
|
4
|
+
body: Uint8Array<ArrayBuffer>;
|
|
5
|
+
children: Der[];
|
|
6
|
+
}
|
|
7
|
+
export declare function check(ok: unknown): asserts ok;
|
|
8
|
+
export declare function decode(bytes: Uint8Array<ArrayBuffer>): Der;
|
|
9
|
+
export declare function tagged(value: Der | undefined, tag: number): Der;
|
|
10
|
+
export declare function fields(value: Der | undefined, tag?: number, min?: number, max?: number): Der[];
|
|
11
|
+
export declare function only(value: Der | undefined, tag: number): Der;
|
|
12
|
+
export declare function oid(value: Der): string;
|
|
13
|
+
export declare function intBytes(value: Der, tag?: number): Uint8Array<ArrayBuffer>;
|
|
14
|
+
export declare function positive(value: Der, tag?: number): Uint8Array<ArrayBuffer>;
|
|
15
|
+
export declare function uint(value: Der, tag?: number): number;
|
|
16
|
+
export declare function bool(value: Der): boolean;
|
|
17
|
+
export declare function bitString(value: Der, aligned?: boolean): Uint8Array<ArrayBuffer>;
|
|
18
|
+
export declare function equal(a: Uint8Array, b: Uint8Array): boolean;
|
|
19
|
+
export interface Algorithm {
|
|
20
|
+
id: string;
|
|
21
|
+
params?: Der;
|
|
22
|
+
}
|
|
23
|
+
export declare function algorithm(value: Der): Algorithm;
|
|
24
|
+
export declare const nullOrAbsent: (p?: Der) => boolean;
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
export function check(ok) {
|
|
2
|
+
if (!ok)
|
|
3
|
+
throw new Error('Invalid DER');
|
|
4
|
+
}
|
|
5
|
+
export function decode(bytes) {
|
|
6
|
+
let offset = 0;
|
|
7
|
+
let nodes = 0;
|
|
8
|
+
function read(end, depth) {
|
|
9
|
+
check(depth <= 32 && ++nodes <= 16384 && end - offset >= 2);
|
|
10
|
+
const start = offset;
|
|
11
|
+
const tag = bytes[offset++];
|
|
12
|
+
check(tag !== 0 && (tag & 31) !== 31);
|
|
13
|
+
let length = bytes[offset++];
|
|
14
|
+
if (length >= 128) {
|
|
15
|
+
const count = length - 128;
|
|
16
|
+
check(count > 0 && count <= 4 && count <= end - offset && bytes[offset] !== 0);
|
|
17
|
+
length = 0;
|
|
18
|
+
for (let i = 0; i < count; i++)
|
|
19
|
+
length = length * 256 + bytes[offset++];
|
|
20
|
+
check(length >= 128);
|
|
21
|
+
}
|
|
22
|
+
check(length <= end - offset);
|
|
23
|
+
const limit = offset + length;
|
|
24
|
+
const body = bytes.subarray(offset, limit);
|
|
25
|
+
const children = [];
|
|
26
|
+
if (tag & 32) {
|
|
27
|
+
while (offset < limit)
|
|
28
|
+
children.push(read(limit, depth + 1));
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
offset = limit;
|
|
32
|
+
}
|
|
33
|
+
return { tag, body, raw: bytes.subarray(start, limit), children };
|
|
34
|
+
}
|
|
35
|
+
const value = read(bytes.length, 0);
|
|
36
|
+
check(offset === bytes.length);
|
|
37
|
+
return value;
|
|
38
|
+
}
|
|
39
|
+
export function tagged(value, tag) {
|
|
40
|
+
check(value?.tag === tag);
|
|
41
|
+
return value;
|
|
42
|
+
}
|
|
43
|
+
export function fields(value, tag = 0x30, min = 0, max = Infinity) {
|
|
44
|
+
const children = tagged(value, tag).children;
|
|
45
|
+
check(children.length >= min && children.length <= max);
|
|
46
|
+
return children;
|
|
47
|
+
}
|
|
48
|
+
export function only(value, tag) {
|
|
49
|
+
return fields(value, tag, 1, 1)[0];
|
|
50
|
+
}
|
|
51
|
+
export function oid(value) {
|
|
52
|
+
const bytes = tagged(value, 6).body;
|
|
53
|
+
check(bytes.length > 0);
|
|
54
|
+
const arcs = [];
|
|
55
|
+
let arc = 0;
|
|
56
|
+
for (const b of bytes) {
|
|
57
|
+
check(!(arc === 0 && b === 128));
|
|
58
|
+
arc = arc * 128 + (b & 127);
|
|
59
|
+
check(arc <= 0x7fffffff);
|
|
60
|
+
if (b < 128) {
|
|
61
|
+
if (!arcs.length) {
|
|
62
|
+
const first = Math.min(2, Math.floor(arc / 40));
|
|
63
|
+
arcs.push(first);
|
|
64
|
+
arc -= first * 40;
|
|
65
|
+
}
|
|
66
|
+
arcs.push(arc);
|
|
67
|
+
arc = 0;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
check(bytes[bytes.length - 1] < 128);
|
|
71
|
+
return arcs.join('.');
|
|
72
|
+
}
|
|
73
|
+
export function intBytes(value, tag = 2) {
|
|
74
|
+
const bytes = tagged(value, tag).body;
|
|
75
|
+
check(bytes.length && !(bytes.length > 1 &&
|
|
76
|
+
((bytes[0] === 0 && bytes[1] < 128) || (bytes[0] === 255 && bytes[1] >= 128))));
|
|
77
|
+
return bytes;
|
|
78
|
+
}
|
|
79
|
+
export function positive(value, tag = 2) {
|
|
80
|
+
const bytes = intBytes(value, tag);
|
|
81
|
+
check(bytes[0] < 128);
|
|
82
|
+
return bytes[0] === 0 ? bytes.subarray(1) : bytes;
|
|
83
|
+
}
|
|
84
|
+
export function uint(value, tag = 2) {
|
|
85
|
+
const bytes = positive(value, tag);
|
|
86
|
+
check(bytes.length <= 7);
|
|
87
|
+
let n = 0;
|
|
88
|
+
for (const b of bytes)
|
|
89
|
+
n = n * 256 + b;
|
|
90
|
+
check(Number.isSafeInteger(n));
|
|
91
|
+
return n;
|
|
92
|
+
}
|
|
93
|
+
export function bool(value) {
|
|
94
|
+
const b = tagged(value, 1).body;
|
|
95
|
+
check(b.length === 1 && (b[0] === 0 || b[0] === 255));
|
|
96
|
+
return b[0] !== 0;
|
|
97
|
+
}
|
|
98
|
+
export function bitString(value, aligned = true) {
|
|
99
|
+
const b = tagged(value, 3).body;
|
|
100
|
+
check(b.length > 0 && b[0] < 8);
|
|
101
|
+
if (aligned || b.length === 1)
|
|
102
|
+
check(b[0] === 0);
|
|
103
|
+
check((b[b.length - 1] & ((1 << b[0]) - 1)) === 0);
|
|
104
|
+
return b.subarray(1);
|
|
105
|
+
}
|
|
106
|
+
export function equal(a, b) {
|
|
107
|
+
if (a.length !== b.length)
|
|
108
|
+
return false;
|
|
109
|
+
let diff = 0;
|
|
110
|
+
for (let i = 0; i < a.length; i++)
|
|
111
|
+
diff |= a[i] ^ b[i];
|
|
112
|
+
return diff === 0;
|
|
113
|
+
}
|
|
114
|
+
export function algorithm(value) {
|
|
115
|
+
const [id, params] = fields(value, 0x30, 1, 2);
|
|
116
|
+
return { id: oid(id), params };
|
|
117
|
+
}
|
|
118
|
+
export const nullOrAbsent = (p) => !p || (p.tag === 5 && p.body.length === 0);
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { verifyTimestamp } from './verify.js';
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { hex, utf8 } from '../bytes.js';
|
|
2
|
+
import { check, fields, oid } from './der.js';
|
|
3
|
+
const labels = new Map(Object.entries({
|
|
4
|
+
'2.5.4.5': 'SERIALNUMBER', '2.5.4.3': 'CN', '2.5.4.11': 'OU', '2.5.4.10': 'O',
|
|
5
|
+
'2.5.4.17': 'POSTALCODE', '2.5.4.9': 'STREET', '2.5.4.7': 'L', '2.5.4.8': 'ST', '2.5.4.6': 'C',
|
|
6
|
+
}));
|
|
7
|
+
const printable = /^[a-zA-Z0-9 '()+,./:=?-]*$/;
|
|
8
|
+
function directoryString(value) {
|
|
9
|
+
const bytes = value.body;
|
|
10
|
+
if (value.tag === 30) {
|
|
11
|
+
check(bytes.length % 2 === 0);
|
|
12
|
+
return new TextDecoder('utf-16be', { ignoreBOM: true }).decode(bytes).replace(/\0$/, '');
|
|
13
|
+
}
|
|
14
|
+
check([12, 18, 19, 20, 22].includes(value.tag));
|
|
15
|
+
const s = new TextDecoder('utf-8', { fatal: value.tag !== 20, ignoreBOM: true }).decode(bytes);
|
|
16
|
+
if (value.tag === 18)
|
|
17
|
+
check(/^[0-9 ]*$/.test(s));
|
|
18
|
+
if (value.tag === 19)
|
|
19
|
+
check(printable.test(s.replace(/[*&]/g, '')));
|
|
20
|
+
if (value.tag === 22)
|
|
21
|
+
check(bytes.every(b => b < 128));
|
|
22
|
+
return s;
|
|
23
|
+
}
|
|
24
|
+
// pkix.Name.String re-marshals unknown string attributes as PrintableString
|
|
25
|
+
// or UTF8String, even if the certificate encoded them as an IA5String.
|
|
26
|
+
function derString(s) {
|
|
27
|
+
const bytes = utf8.encode(s);
|
|
28
|
+
const length = [];
|
|
29
|
+
for (let n = bytes.length; n > 0; n = Math.floor(n / 256))
|
|
30
|
+
length.unshift(n % 256);
|
|
31
|
+
const header = [printable.test(s) ? 19 : 12, ...(bytes.length < 128 ? [bytes.length] : [128 + length.length, ...length])];
|
|
32
|
+
return hex(Uint8Array.from(header)) + hex(bytes);
|
|
33
|
+
}
|
|
34
|
+
export function subjectName(value) {
|
|
35
|
+
const named = new Map();
|
|
36
|
+
const unknown = [];
|
|
37
|
+
for (const rdn of fields(value)) {
|
|
38
|
+
for (const attr of fields(rdn, 0x31)) {
|
|
39
|
+
const [type, val] = fields(attr, 0x30, 2, 2);
|
|
40
|
+
const id = oid(type), label = labels.get(id), s = directoryString(val);
|
|
41
|
+
if (!label) {
|
|
42
|
+
unknown.push(id + '=#' + derString(s));
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const escaped = s.replace(/[,+"\\<>;]|^#|^ | $/g, '\\$&');
|
|
46
|
+
const items = named.get(label) ?? [];
|
|
47
|
+
if (label === 'CN' || label === 'SERIALNUMBER')
|
|
48
|
+
items.length = 0;
|
|
49
|
+
if (s || (label !== 'CN' && label !== 'SERIALNUMBER'))
|
|
50
|
+
items.push(label + '=' + escaped);
|
|
51
|
+
named.set(label, items);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return [...Array.from(labels.values(), l => named.get(l)?.join('+')).filter(Boolean), ...unknown.reverse()].join(',');
|
|
55
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Certificate } from './x509.js';
|
|
2
|
+
export interface PolicyExtensions {
|
|
3
|
+
policies?: Set<string>;
|
|
4
|
+
mappings?: Map<string, Set<string>>;
|
|
5
|
+
requireExplicit?: number;
|
|
6
|
+
inhibitMapping?: number;
|
|
7
|
+
inhibitAny?: number;
|
|
8
|
+
}
|
|
9
|
+
export declare function validPolicies(chain: Certificate[]): boolean;
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { equal } from './der.js';
|
|
2
|
+
const anyPolicy = '2.5.29.32.0';
|
|
3
|
+
// The verifier requests anyPolicy, like tc-sign. For this user-policy set
|
|
4
|
+
// it suffices to track the reachable policies and their expected successors
|
|
5
|
+
// at each depth. No individual policy paths are returned to the caller.
|
|
6
|
+
export function validPolicies(chain) {
|
|
7
|
+
let explicit = chain.length, mapping = chain.length, any = chain.length;
|
|
8
|
+
let expected = new Set([anyPolicy]);
|
|
9
|
+
let hasPolicyGraph = true;
|
|
10
|
+
for (let i = chain.length - 2; i >= 0; i--) {
|
|
11
|
+
const c = chain[i];
|
|
12
|
+
const selfIssued = equal(c.issuer, c.subject);
|
|
13
|
+
const present = c.policies;
|
|
14
|
+
if (!present?.size)
|
|
15
|
+
hasPolicyGraph = false;
|
|
16
|
+
if (explicit === 0 && !hasPolicyGraph)
|
|
17
|
+
return false;
|
|
18
|
+
const current = new Set();
|
|
19
|
+
if (hasPolicyGraph && present) {
|
|
20
|
+
for (const id of present) {
|
|
21
|
+
if (id !== anyPolicy && (expected.has(anyPolicy) || expected.has(id)))
|
|
22
|
+
current.add(id);
|
|
23
|
+
}
|
|
24
|
+
if (present.has(anyPolicy) && (any > 0 || (i > 0 && selfIssued))) {
|
|
25
|
+
for (const id of expected)
|
|
26
|
+
current.add(id);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
expected = new Set(current);
|
|
30
|
+
if (i === 0)
|
|
31
|
+
break;
|
|
32
|
+
if (hasPolicyGraph && c.mappings) {
|
|
33
|
+
for (const issuer of c.mappings.keys())
|
|
34
|
+
expected.delete(issuer);
|
|
35
|
+
for (const [issuer, subjects] of c.mappings) {
|
|
36
|
+
if (mapping === 0)
|
|
37
|
+
continue;
|
|
38
|
+
if (issuer === anyPolicy || subjects.has(anyPolicy))
|
|
39
|
+
return false;
|
|
40
|
+
if (current.has(issuer) || current.has(anyPolicy)) {
|
|
41
|
+
for (const id of subjects)
|
|
42
|
+
expected.add(id);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!selfIssued) {
|
|
47
|
+
explicit = Math.max(0, explicit - 1);
|
|
48
|
+
mapping = Math.max(0, mapping - 1);
|
|
49
|
+
any = Math.max(0, any - 1);
|
|
50
|
+
}
|
|
51
|
+
explicit = Math.min(explicit, c.requireExplicit ?? explicit);
|
|
52
|
+
mapping = Math.min(mapping, c.inhibitMapping ?? mapping);
|
|
53
|
+
any = Math.min(any, c.inhibitAny ?? any);
|
|
54
|
+
}
|
|
55
|
+
return (explicit > 1 && chain[0].requireExplicit !== 0) || expected.size > 0;
|
|
56
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { TimestampFailureCode } from '../errors.js';
|
|
2
|
+
import type { TimeInput } from '../time.js';
|
|
3
|
+
import type { Certificate, CertificateInput } from './x509.js';
|
|
4
|
+
export type { CertificateInput, TimestampFailureCode };
|
|
5
|
+
export interface VerifyTimestampOptions {
|
|
6
|
+
/** SHA-256 digest of the timestamped data, exactly 32 bytes. */
|
|
7
|
+
digest: Uint8Array;
|
|
8
|
+
/** Each entry is one DER certificate or a PEM certificate bundle. */
|
|
9
|
+
roots?: readonly CertificateInput[];
|
|
10
|
+
now?: TimeInput;
|
|
11
|
+
}
|
|
12
|
+
export interface TimestampInfo {
|
|
13
|
+
/** UTC RFC 3339 with up to nine fractional digits. */
|
|
14
|
+
genTime: string;
|
|
15
|
+
tsa: string;
|
|
16
|
+
accuracyNs?: bigint;
|
|
17
|
+
}
|
|
18
|
+
export type TimestampResult = ({
|
|
19
|
+
status: 'verified';
|
|
20
|
+
} & TimestampInfo) | ({
|
|
21
|
+
status: 'unverified';
|
|
22
|
+
reason: 'timestamp-no-roots';
|
|
23
|
+
} & TimestampInfo) | {
|
|
24
|
+
status: 'unverified';
|
|
25
|
+
reason: TimestampFailureCode;
|
|
26
|
+
};
|
|
27
|
+
/** Verify a DER TimeStampToken offline. Only 'verified' establishes trusted time.
|
|
28
|
+
* With roots omitted, a successful signature check returns the TSA's claims
|
|
29
|
+
* with reason 'timestamp-no-roots', matching tc-sign's standalone inspection.
|
|
30
|
+
*/
|
|
31
|
+
export declare function verifyTimestamp(token: Uint8Array, options: VerifyTimestampOptions): Promise<TimestampResult>;
|
|
32
|
+
/** Internal entry point for verify(), which validates verifier inputs first. */
|
|
33
|
+
export declare function verifyTimestampWithRoots(token: Uint8Array, digest: Uint8Array, roots: Certificate[] | undefined, now: bigint): Promise<TimestampResult>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { CLOCK_SKEW, formatTime, nowInstant } from '../time.js';
|
|
2
|
+
import { selectSigner, signedData, signerInfo, signingAttributes, tstInfo, verifyESS } from './cms.js';
|
|
3
|
+
import { digestAlgorithm, verifySignature } from './crypto.js';
|
|
4
|
+
import { check, equal } from './der.js';
|
|
5
|
+
import { parseRoots, timestampEKU, verifyChain } from './x509.js';
|
|
6
|
+
/** Verify a DER TimeStampToken offline. Only 'verified' establishes trusted time.
|
|
7
|
+
* With roots omitted, a successful signature check returns the TSA's claims
|
|
8
|
+
* with reason 'timestamp-no-roots', matching tc-sign's standalone inspection.
|
|
9
|
+
*/
|
|
10
|
+
export async function verifyTimestamp(token, options) {
|
|
11
|
+
let roots;
|
|
12
|
+
try {
|
|
13
|
+
if (options.roots !== undefined)
|
|
14
|
+
roots = parseRoots(options.roots);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
return { status: 'unverified', reason: 'timestamp-roots' };
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
return await verifyTimestampWithRoots(token, options.digest, roots, nowInstant(options.now));
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return { status: 'unverified', reason: 'invalid-time' };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Internal entry point for verify(), which validates verifier inputs first. */
|
|
27
|
+
export async function verifyTimestampWithRoots(token, digest, roots, now) {
|
|
28
|
+
let reason = 'timestamp-malformed';
|
|
29
|
+
try {
|
|
30
|
+
if (!token.length)
|
|
31
|
+
return { status: 'unverified', reason: 'timestamp-unsupported' };
|
|
32
|
+
if (token.length > 65536)
|
|
33
|
+
return { status: 'unverified', reason: 'timestamp-too-large' };
|
|
34
|
+
// Own the signed bytes across all Web Crypto awaits (including Buffer inputs).
|
|
35
|
+
const sd = signedData(new Uint8Array(token));
|
|
36
|
+
const tst = tstInfo(sd.eContent);
|
|
37
|
+
reason = 'timestamp-imprint';
|
|
38
|
+
check(digestAlgorithm(tst.imprintAlgorithm) === 'SHA-256' && digest.length === 32 && equal(tst.digest, digest));
|
|
39
|
+
reason = 'timestamp-malformed';
|
|
40
|
+
const si = signerInfo(sd.signer);
|
|
41
|
+
reason = 'timestamp-algorithm';
|
|
42
|
+
const hash = digestAlgorithm(si.digest);
|
|
43
|
+
reason = 'timestamp-attributes';
|
|
44
|
+
const attrs = await signingAttributes(si.attrs, sd.eContent, hash);
|
|
45
|
+
reason = 'timestamp-signer';
|
|
46
|
+
const signer = selectSigner(sd.certs, si.matches);
|
|
47
|
+
reason = 'timestamp-ess';
|
|
48
|
+
await verifyESS(attrs, signer);
|
|
49
|
+
reason = 'timestamp-eku';
|
|
50
|
+
check(signer.ekuCritical && signer.eku?.length === 1 && signer.eku[0] === timestampEKU);
|
|
51
|
+
reason = 'timestamp-signature';
|
|
52
|
+
const signed = si.attrs.raw.slice();
|
|
53
|
+
signed[0] = 0x31; // RFC 5652 §5.4 preserves the original length and attribute order.
|
|
54
|
+
check(await verifySignature(signer.spki, si.sigAlg, signed, si.sig, hash));
|
|
55
|
+
reason = 'timestamp-future';
|
|
56
|
+
check(tst.at <= now + CLOCK_SKEW);
|
|
57
|
+
const nanos = (tst.at % 1000000000n + 1000000000n) % 1000000000n;
|
|
58
|
+
const fraction = nanos.toString().padStart(9, '0').replace(/0+$/, '');
|
|
59
|
+
const info = {
|
|
60
|
+
genTime: formatTime(tst.at).replace(/\.\d{3}Z$/, (fraction ? '.' + fraction : '') + 'Z'),
|
|
61
|
+
tsa: signer.name,
|
|
62
|
+
};
|
|
63
|
+
if (tst.accuracyNs !== undefined)
|
|
64
|
+
info.accuracyNs = tst.accuracyNs;
|
|
65
|
+
if (roots === undefined)
|
|
66
|
+
return { status: 'unverified', reason: 'timestamp-no-roots', ...info };
|
|
67
|
+
reason = 'timestamp-chain';
|
|
68
|
+
check(await verifyChain(signer, sd.certs, roots, tst.at));
|
|
69
|
+
return { status: 'verified', ...info };
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return { status: 'unverified', reason };
|
|
73
|
+
}
|
|
74
|
+
}
|