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
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
// How to run this file:
// 1. [obtain firefox source code]
// 2. [build/obtain firefox binaries]
// 3. run `[path to]/run-mozilla.sh [path to]/xpcshell \
// [path to]/genHPKPStaticpins.js \
// [absolute path to]/PreloadedHPKPins.json \
// [absolute path to]/StaticHPKPins.h
"use strict";
if (arguments.length != 2) {
throw new Error(
"Usage: genHPKPStaticPins.js " +
"<absolute path to PreloadedHPKPins.json> " +
"<absolute path to StaticHPKPins.h>"
);
}
var { NetUtil } = ChromeUtils.import("resource://gre/modules/NetUtil.jsm");
var { FileUtils } = ChromeUtils.importESModule(
"resource://gre/modules/FileUtils.sys.mjs"
);
var gCertDB = Cc["@mozilla.org/security/x509certdb;1"].getService(
Ci.nsIX509CertDB
);
const SHA256_PREFIX = "sha256/";
const GOOGLE_PIN_PREFIX = "GOOGLE_PIN_";
// Pins expire in 14 weeks (6 weeks on Beta + 8 weeks on stable)
const PINNING_MINIMUM_REQUIRED_MAX_AGE = 60 * 60 * 24 * 7 * 14;
const FILE_HEADER =
"/* This Source Code Form is subject to the terms of the Mozilla Public\n" +
" * License, v. 2.0. If a copy of the MPL was not distributed with this\n" +
" * file, You can obtain one at http://mozilla.org/MPL/2.0/. */\n" +
"\n" +
"/*****************************************************************************/\n" +
"/* This is an automatically generated file. If you're not */\n" +
"/* PublicKeyPinningService.cpp, you shouldn't be #including it. */\n" +
"/*****************************************************************************/\n" +
"#include <stdint.h>" +
"\n";
const DOMAINHEADER =
"/* Domainlist */\n" +
"struct TransportSecurityPreload {\n" +
" // See bug 1338873 about making these fields const.\n" +
" const char* mHost;\n" +
" bool mIncludeSubdomains;\n" +
" bool mTestMode;\n" +
" bool mIsMoz;\n" +
" int32_t mId;\n" +
" const StaticFingerprints* pinset;\n" +
"};\n\n";
const PINSETDEF =
"/* Pinsets are each an ordered list by the actual value of the fingerprint */\n" +
"struct StaticFingerprints {\n" +
" // See bug 1338873 about making these fields const.\n" +
" size_t size;\n" +
" const char* const* data;\n" +
"};\n\n";
// Command-line arguments
var gStaticPins = parseJson(arguments[0]);
// Open the output file.
var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
file.initWithPath(arguments[1]);
var gFileOutputStream = FileUtils.openSafeFileOutputStream(file);
function writeString(string) {
gFileOutputStream.write(string, string.length);
}
function readFileToString(filename) {
let file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsIFile);
file.initWithPath(filename);
let stream = Cc["@mozilla.org/network/file-input-stream;1"].createInstance(
Ci.nsIFileInputStream
);
stream.init(file, -1, 0, 0);
let buf = NetUtil.readInputStreamToString(stream, stream.available());
return buf;
}
function stripComments(buf) {
let lines = buf.split("\n");
let entryRegex = /^\s*\/\//;
let data = "";
for (let i = 0; i < lines.length; ++i) {
let match = entryRegex.exec(lines[i]);
if (!match) {
data = data + lines[i];
}
}
return data;
}
function download(filename) {
let req = new XMLHttpRequest();
req.open("GET", filename, false); // doing the request synchronously
try {
req.send();
} catch (e) {
throw new Error(`ERROR: problem downloading '${filename}': ${e}`);
}
if (req.status != 200) {
throw new Error(
"ERROR: problem downloading '" + filename + "': status " + req.status
);
}
let resultDecoded;
try {
resultDecoded = atob(req.responseText);
} catch (e) {
throw new Error(
"ERROR: could not decode data as base64 from '" + filename + "': " + e
);
}
return resultDecoded;
}
function downloadAsJson(filename) {
// we have to filter out '//' comments, while not mangling the json
let result = download(filename).replace(/^(\s*)?\/\/[^\n]*\n/gm, "");
let data = null;
try {
data = JSON.parse(result);
} catch (e) {
throw new Error(
"ERROR: could not parse data from '" + filename + "': " + e
);
}
return data;
}
// Returns a Subject Public Key Digest from the given pem, if it exists.
function getSKDFromPem(pem) {
let cert = gCertDB.constructX509FromBase64(pem, pem.length);
return cert.sha256SubjectPublicKeyInfoDigest;
}
/**
* Hashes |input| using the SHA-256 algorithm in the following manner:
* btoa(sha256(atob(input)))
*
* @param {string} input Base64 string to decode and return the hash of.
* @returns {string} Base64 encoded SHA-256 hash.
*/
function sha256Base64(input) {
let decodedValue;
try {
decodedValue = atob(input);
} catch (e) {
throw new Error(`ERROR: could not decode as base64: '${input}': ${e}`);
}
// Convert |decodedValue| to an array so that it can be hashed by the
// nsICryptoHash instance below.
// In most cases across the code base, convertToByteArray() of
// nsIScriptableUnicodeConverter is used to do this, but the method doesn't
// seem to work here.
let data = [];
for (let i = 0; i < decodedValue.length; i++) {
data[i] = decodedValue.charCodeAt(i);
}
let hasher = Cc["@mozilla.org/security/hash;1"].createInstance(
Ci.nsICryptoHash
);
hasher.init(hasher.SHA256);
hasher.update(data, data.length);
// true is passed so that the hasher returns a Base64 encoded string.
return hasher.finish(true);
}
// Downloads the static certs file and tries to map Google Chrome nicknames
// to Mozilla nicknames, as well as storing any hashes for pins for which we
// don't have root PEMs. Each entry consists of a line containing the name of
// the pin followed either by a hash in the format "sha256/" + base64(hash),
// a PEM encoded public key, or a PEM encoded certificate.
// For certificates that we have in our database,
// return a map of Google's nickname to ours. For ones that aren't return a
// map of Google's nickname to SHA-256 values. This code is modeled after agl's
// https://github.com/agl/transport-security-state-generate, which doesn't
// live in the Chromium repo because go is not an official language in
// Chromium.
// For all of the entries in this file:
// - If the entry has a hash format, find the Mozilla pin name (cert nickname)
// and stick the hash into certSKDToName
// - If the entry has a PEM format, parse the PEM, find the Mozilla pin name
// and stick the hash in certSKDToName
// We MUST be able to find a corresponding cert nickname for the Chrome names,
// otherwise we skip all pinsets referring to that Chrome name.
function downloadAndParseChromeCerts(filename, certNameToSKD, certSKDToName) {
// Prefixes that we care about.
const BEGIN_CERT = "-----BEGIN CERTIFICATE-----";
const END_CERT = "-----END CERTIFICATE-----";
const BEGIN_PUB_KEY = "-----BEGIN PUBLIC KEY-----";
const END_PUB_KEY = "-----END PUBLIC KEY-----";
// Parsing states.
const PRE_NAME = 0;
const POST_NAME = 1;
const IN_CERT = 2;
const IN_PUB_KEY = 3;
let state = PRE_NAME;
let lines = download(filename).split("\n");
let pemCert = "";
let pemPubKey = "";
let hash = "";
let chromeNameToHash = {};
let chromeNameToMozName = {};
let chromeName;
for (let line of lines) {
// Skip comments and newlines.
if (!line.length || line[0] == "#") {
continue;
}
switch (state) {
case PRE_NAME:
chromeName = line;
state = POST_NAME;
break;
case POST_NAME:
if (line.startsWith(SHA256_PREFIX)) {
hash = line.substring(SHA256_PREFIX.length);
chromeNameToHash[chromeName] = hash;
certNameToSKD[chromeName] = hash;
certSKDToName[hash] = chromeName;
state = PRE_NAME;
} else if (line.startsWith(BEGIN_CERT)) {
state = IN_CERT;
} else if (line.startsWith(BEGIN_PUB_KEY)) {
state = IN_PUB_KEY;
} else if (
chromeName == "PinsListTimestamp" &&
line.match(/^[0-9]+$/)
) {
// If the name of this entry is "PinsListTimestamp", this line should
// be the pins list timestamp. It should consist solely of digits.
// Ignore it and expect other entries to come.
state = PRE_NAME;
} else {
throw new Error(
"ERROR: couldn't parse Chrome certificate file line: " + line
);
}
break;
case IN_CERT:
if (line.startsWith(END_CERT)) {
state = PRE_NAME;
hash = getSKDFromPem(pemCert);
pemCert = "";
let mozName;
if (hash in certSKDToName) {
mozName = certSKDToName[hash];
} else {
// Not one of our built-in certs. Prefix the name with
// GOOGLE_PIN_.
mozName = GOOGLE_PIN_PREFIX + chromeName;
dump(
"Can't find hash in builtin certs for Chrome nickname " +
chromeName +
", inserting " +
mozName +
"\n"
);
certSKDToName[hash] = mozName;
certNameToSKD[mozName] = hash;
}
chromeNameToMozName[chromeName] = mozName;
} else {
pemCert += line;
}
break;
case IN_PUB_KEY:
if (line.startsWith(END_PUB_KEY)) {
state = PRE_NAME;
hash = sha256Base64(pemPubKey);
pemPubKey = "";
chromeNameToHash[chromeName] = hash;
certNameToSKD[chromeName] = hash;
certSKDToName[hash] = chromeName;
} else {
pemPubKey += line;
}
break;
default:
throw new Error(
"ERROR: couldn't parse Chrome certificate file " + line
);
}
}
return [chromeNameToHash, chromeNameToMozName];
}
// We can only import pinsets from chrome if for every name in the pinset:
// - We have a hash from Chrome's static certificate file
// - We have a builtin cert
// If the pinset meets these requirements, we store a map array of pinset
// objects:
// {
// pinset_name : {
// // Array of names with entries in certNameToSKD
// sha256_hashes: []
// }
// }
// and an array of imported pinset entries:
// { name: string, include_subdomains: boolean, test_mode: boolean,
// pins: pinset_name }
function downloadAndParseChromePins(
filename,
chromeNameToHash,
chromeNameToMozName,
certNameToSKD,
certSKDToName
) {
let chromePreloads = downloadAsJson(filename);
let chromePins = chromePreloads.pinsets;
let chromeImportedPinsets = {};
let chromeImportedEntries = [];
chromePins.forEach(function (pin) {
let valid = true;
let pinset = { name: pin.name, sha256_hashes: [] };
// Translate the Chrome pinset format to ours
pin.static_spki_hashes.forEach(function (name) {
if (name in chromeNameToHash) {
let hash = chromeNameToHash[name];
pinset.sha256_hashes.push(certSKDToName[hash]);
// We should have already added hashes for all of these when we
// imported the certificate file.
if (!certNameToSKD[name]) {
throw new Error("ERROR: No hash for name: " + name);
}
} else if (name in chromeNameToMozName) {
pinset.sha256_hashes.push(chromeNameToMozName[name]);
} else {
dump(
"Skipping Chrome pinset " +
pinset.name +
", couldn't find " +
"builtin " +
name +
" from cert file\n"
);
valid = false;
}
});
if (valid) {
chromeImportedPinsets[pinset.name] = pinset;
}
});
// Grab the domain entry lists. Chrome's entry format is similar to
// ours, except theirs includes a HSTS mode.
const cData = gStaticPins.chromium_data;
let entries = chromePreloads.entries;
entries.forEach(function (entry) {
// HSTS entry only
if (!entry.pins) {
return;
}
let pinsetName = cData.substitute_pinsets[entry.pins];
if (!pinsetName) {
pinsetName = entry.pins;
}
// We trim the entry name here to avoid breaking hostname comparisons in the
// HPKP implementation.
entry.name = entry.name.trim();
let isProductionDomain = cData.production_domains.includes(entry.name);
let isProductionPinset = cData.production_pinsets.includes(pinsetName);
let excludeDomain = cData.exclude_domains.includes(entry.name);
let isTestMode = !isProductionPinset && !isProductionDomain;
if (entry.pins && !excludeDomain && chromeImportedPinsets[entry.pins]) {
chromeImportedEntries.push({
name: entry.name,
include_subdomains: entry.include_subdomains,
test_mode: isTestMode,
is_moz: false,
pins: pinsetName,
});
}
});
return [chromeImportedPinsets, chromeImportedEntries];
}
// Returns a pair of maps [certNameToSKD, certSKDToName] between cert
// nicknames and digests of the SPKInfo for the mozilla trust store
function loadNSSCertinfo(extraCertificates) {
let allCerts = gCertDB.getCerts();
let certNameToSKD = {};
let certSKDToName = {};
for (let cert of allCerts) {
if (!cert.isBuiltInRoot) {
continue;
}
let name = cert.displayName;
let SKD = cert.sha256SubjectPublicKeyInfoDigest;
certNameToSKD[name] = SKD;
certSKDToName[SKD] = name;
}
for (let cert of extraCertificates) {
let name = cert.commonName;
let SKD = cert.sha256SubjectPublicKeyInfoDigest;
certNameToSKD[name] = SKD;
certSKDToName[SKD] = name;
}
{
// This is the pinning test certificate. The key hash identifies the
// default RSA key from pykey.
let name = "End Entity Test Cert";
let SKD = "VCIlmPM9NkgFQtrs4Oa5TeFcDu6MWRTKSNdePEhOgD8=";
certNameToSKD[name] = SKD;
certSKDToName[SKD] = name;
}
return [certNameToSKD, certSKDToName];
}
function parseJson(filename) {
let json = stripComments(readFileToString(filename));
return JSON.parse(json);
}
function nameToAlias(certName) {
// change the name to a string valid as a c identifier
// remove non-ascii characters
certName = certName.replace(/[^[:ascii:]]/g, "_");
// replace non word characters
certName = certName.replace(/[^A-Za-z0-9]/g, "_");
return "k" + certName + "Fingerprint";
}
function compareByName(a, b) {
return a.name.localeCompare(b.name);
}
function genExpirationTime() {
let now = new Date();
let nowMillis = now.getTime();
let expirationMillis = nowMillis + PINNING_MINIMUM_REQUIRED_MAX_AGE * 1000;
let expirationMicros = expirationMillis * 1000;
return (
"static const PRTime kPreloadPKPinsExpirationTime = INT64_C(" +
expirationMicros +
");\n"
);
}
function writeFullPinset(certNameToSKD, certSKDToName, pinset) {
if (!pinset.sha256_hashes || !pinset.sha256_hashes.length) {
throw new Error(`ERROR: Pinset ${pinset.name} does not contain any hashes`);
}
writeFingerprints(
certNameToSKD,
certSKDToName,
pinset.name,
pinset.sha256_hashes
);
}
function writeFingerprints(certNameToSKD, certSKDToName, name, hashes) {
let varPrefix = "kPinset_" + name;
writeString("static const char* const " + varPrefix + "_Data[] = {\n");
let SKDList = [];
for (let certName of hashes) {
if (!(certName in certNameToSKD)) {
throw new Error(`ERROR: Can't find '${certName}' in certNameToSKD`);
}
SKDList.push(certNameToSKD[certName]);
}
for (let skd of SKDList.sort()) {
writeString(" " + nameToAlias(certSKDToName[skd]) + ",\n");
}
if (!hashes.length) {
// ANSI C requires that an initialiser list be non-empty.
writeString(" 0\n");
}
writeString("};\n");
writeString(
"static const StaticFingerprints " +
varPrefix +
" = {\n " +
"sizeof(" +
varPrefix +
"_Data) / sizeof(const char*),\n " +
varPrefix +
"_Data\n};\n\n"
);
}
function writeEntry(entry) {
let printVal = ` { "${entry.name}", `;
if (entry.include_subdomains) {
printVal += "true, ";
} else {
printVal += "false, ";
}
// Default to test mode if not specified.
let testMode = true;
if (entry.hasOwnProperty("test_mode")) {
testMode = entry.test_mode;
}
if (testMode) {
printVal += "true, ";
} else {
printVal += "false, ";
}
if (
entry.is_moz ||
(entry.pins.includes("mozilla") && entry.pins != "mozilla_test")
) {
printVal += "true, ";
} else {
printVal += "false, ";
}
if ("id" in entry) {
if (entry.id >= 256) {
throw new Error("ERROR: Not enough buckets in histogram");
}
if (entry.id >= 0) {
printVal += entry.id + ", ";
}
} else {
printVal += "-1, ";
}
printVal += "&kPinset_" + entry.pins;
printVal += " },\n";
writeString(printVal);
}
function writeDomainList(chromeImportedEntries) {
writeString("/* Sort hostnames for binary search. */\n");
writeString(
"static const TransportSecurityPreload " +
"kPublicKeyPinningPreloadList[] = {\n"
);
let count = 0;
let mozillaDomains = {};
gStaticPins.entries.forEach(function (entry) {
mozillaDomains[entry.name] = true;
});
// For any domain for which we have set pins, exclude them from
// chromeImportedEntries.
for (let i = chromeImportedEntries.length - 1; i >= 0; i--) {
if (mozillaDomains[chromeImportedEntries[i].name]) {
dump(
"Skipping duplicate pinset for domain " +
JSON.stringify(chromeImportedEntries[i], undefined, 2) +
"\n"
);
chromeImportedEntries.splice(i, 1);
}
}
let sortedEntries = gStaticPins.entries;
sortedEntries.push.apply(sortedEntries, chromeImportedEntries);
for (let entry of sortedEntries.sort(compareByName)) {
count++;
writeEntry(entry);
}
writeString("};\n");
writeString("\n// Pinning Preload List Length = " + count + ";\n");
writeString("\nstatic const int32_t kUnknownId = -1;\n");
}
function writeFile(
certNameToSKD,
certSKDToName,
chromeImportedPinsets,
chromeImportedEntries
) {
// Compute used pins from both Chrome's and our pinsets, so we can output
// them later.
let usedFingerprints = {};
let mozillaPins = {};
gStaticPins.pinsets.forEach(function (pinset) {
mozillaPins[pinset.name] = true;
pinset.sha256_hashes.forEach(function (name) {
usedFingerprints[name] = true;
});
});
for (let key in chromeImportedPinsets) {
let pinset = chromeImportedPinsets[key];
pinset.sha256_hashes.forEach(function (name) {
usedFingerprints[name] = true;
});
}
writeString(FILE_HEADER);
// Write actual fingerprints.
Object.keys(usedFingerprints)
.sort()
.forEach(function (certName) {
if (certName) {
writeString("/* " + certName + " */\n");
writeString("static const char " + nameToAlias(certName) + "[] =\n");
writeString(' "' + certNameToSKD[certName] + '";\n');
writeString("\n");
}
});
// Write the pinsets
writeString(PINSETDEF);
writeString("/* PreloadedHPKPins.json pinsets */\n");
gStaticPins.pinsets.sort(compareByName).forEach(function (pinset) {
writeFullPinset(certNameToSKD, certSKDToName, pinset);
});
writeString("/* Chrome static pinsets */\n");
for (let key in chromeImportedPinsets) {
if (mozillaPins[key]) {
dump("Skipping duplicate pinset " + key + "\n");
} else {
dump("Writing pinset " + key + "\n");
writeFullPinset(certNameToSKD, certSKDToName, chromeImportedPinsets[key]);
}
}
// Write the domainlist entries.
writeString(DOMAINHEADER);
writeDomainList(chromeImportedEntries);
writeString("\n");
writeString(genExpirationTime());
}
function loadExtraCertificates(certStringList) {
let constructedCerts = [];
for (let certString of certStringList) {
constructedCerts.push(gCertDB.constructX509FromBase64(certString));
}
return constructedCerts;
}
var extraCertificates = loadExtraCertificates(gStaticPins.extra_certificates);
var [certNameToSKD, certSKDToName] = loadNSSCertinfo(extraCertificates);
var [chromeNameToHash, chromeNameToMozName] = downloadAndParseChromeCerts(
gStaticPins.chromium_data.cert_file_url,
certNameToSKD,
certSKDToName
);
var [chromeImportedPinsets, chromeImportedEntries] = downloadAndParseChromePins(
gStaticPins.chromium_data.json_file_url,
chromeNameToHash,
chromeNameToMozName,
certNameToSKD,
certSKDToName
);
writeFile(
certNameToSKD,
certSKDToName,
chromeImportedPinsets,
chromeImportedEntries
);
FileUtils.closeSafeFileOutputStream(gFileOutputStream);
|