-
Notifications
You must be signed in to change notification settings - Fork 2
/
CertPatrol.pjs
1105 lines (1005 loc) · 37.5 KB
/
CertPatrol.pjs
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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
### vim:syntax=javascript
###
### PREP SOURCE.. not in the mood for jaggler.. maybe i'll have to port later
### The following warning isn't for you if you can read this.
#// This file has been generated using prep. http://perl.pages.de
###
### Currently no ifdefs in here.
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* ''Certificate Patrol'' was conceived by Carlo v. Loesch and
* implemented by Aiko Barz, Gabor X Toth, Carlo v. Loesch and Mukunda Modell.
* Wildcard functionality was contributed by Georg Koppen, JonDos GmbH 2010.
*
* http://patrol.psyced.org
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// This source code is formatted according to half-indented KNF.
var CertPatrol = {
CHECK_ISSUER_ONLY: 1,
extID: "[email protected]",
locale: {},
// Main
onLoad: function() {
this.initialized = true;
## //this.strings = document.getElementById("CertPatrol-strings");
var self = this;
this.getMyVersion(function(version) {
self.version = version;
self.dbinit();
self.init();
});
},
onUnload: function() {
this.unregisterObserver("http-on-examine-response");
},
// DB init
dbinit: function() {
this.dbh = null;
this.db = {};
try {
var file = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("ProfD", Components.interfaces.nsIFile);
var storage = Components.classes["@mozilla.org/storage/service;1"]
.getService(Components.interfaces.mozIStorageService);
file.append("CertPatrol.sqlite");
// Must be checked before openDatabase()
var exists = file.exists();
// Now, CertPatrol.sqlite exists
this.dbh = storage.openDatabase(file);
// CertPatrol.sqlite initialization
## // "GMT" is a historic lie here.. before version 1.3 we used to work
## // with notAfterGMT etc and try to parse the various renderings of it.
## // now it is too late and pointless to change the name in the sqlite
## // field. how i love SQL for its terrific flexibility... ;)
## // why do most web apps still use this 1970s legacy interface?
if (!exists) {
this.dbh.executeSimpleSQL("CREATE TABLE version (version INT, extversion TEXT)");
this.dbh.executeSimpleSQL("INSERT INTO version (version, extversion) VALUES (3, '"+ this.version +"')");
this.dbh.executeSimpleSQL(
"CREATE TABLE certificates ("+
" host VARCHAR, commonName VARCHAR, organization VARCHAR, organizationalUnit VARCHAR, "+
" serialNumber VARCHAR, emailAddress VARCHAR, notBeforeGMT VARCHAR, notAfterGMT VARCHAR, "+
" issuerCommonName VARCHAR, issuerOrganization VARCHAR, issuerOrganizationUnit VARCHAR, "+
" md5Fingerprint VARCHAR, sha1Fingerprint VARCHAR, "+
" issuerMd5Fingerprint VARCHAR, issuerSha1Fingerprint VARCHAR, "+
" cert BLOB, flags INT, stored INT)");
} else {
var stmt = this.dbh.createStatement("SELECT version FROM version");
stmt.executeStep();
var version = stmt.row.version;
stmt.reset();
if (version < 2) {
this.dbh.executeSimpleSQL("ALTER TABLE certificates ADD COLUMN issuerMd5Fingerprint VARCHAR");
this.dbh.executeSimpleSQL("ALTER TABLE certificates ADD COLUMN issuerSha1Fingerprint VARCHAR");
this.dbh.executeSimpleSQL("ALTER TABLE certificates ADD COLUMN cert BLOB");
this.dbh.executeSimpleSQL("UPDATE version SET version = 2");
}
if (version < 3) {
this.dbh.executeSimpleSQL("ALTER TABLE certificates ADD COLUMN flags INT");
this.dbh.executeSimpleSQL("ALTER TABLE certificates ADD COLUMN stored INT");
this.dbh.executeSimpleSQL("UPDATE version SET version = 3");
}
var extversion;
try {
var stmt = this.dbh.createStatement("SELECT extversion FROM version");
stmt.executeStep();
extversion = stmt.row.extversion;
stmt.reset();
} catch (e) {
this.dbh.executeSimpleSQL("ALTER TABLE version ADD COLUMN extversion TEXT");
}
if (extversion && this.version && extversion != this.version) {
this.dbh.executeSimpleSQL("UPDATE version SET extversion='"+ this.version +"'");
## this.log("[CertPatrol] old: "+ extversion +" new: "+ this.version);
// show release notes for stable versions after upgrade when at least minor version changes
var re = /(.*?\..*?)\..*/;
var vold = extversion.replace(re, "$1"), vnew = this.version.replace(re, "$1");
if (!/[a-z]/.test(this.version) && vold != vnew) {
## //var msg = this.psycText(this.locale.updateMsg, {_version: this.version, _button: "OK"});
this.showRelNotes();
}
}
}
// Prepared statements
this.db = {
selectAll: this.dbh.createStatement("SELECT * FROM certificates"),
selectHost: this.dbh.createStatement("SELECT * FROM certificates WHERE host=?1"),
selectWild: this.dbh.createStatement("SELECT * FROM certificates WHERE md5Fingerprint=?12 AND sha1Fingerprint=?13"),
insert: this.dbh.createStatement(
"INSERT INTO certificates ("+
" host, commonName, organization, organizationalUnit, serialNumber, emailAddress, "+
" notBeforeGMT, notAfterGMT, issuerCommonName, issuerOrganization, issuerOrganizationUnit, "+
" md5Fingerprint, sha1Fingerprint, issuerMd5Fingerprint, issuerSha1Fingerprint, cert, flags, stored) "+
"VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17,?18)"),
update: this.dbh.createStatement(
"UPDATE certificates SET "+
" commonName=?2, organization=?3, organizationalUnit=?4, serialNumber=?5, emailAddress=?6, "+
" notBeforeGMT=?7, notAfterGMT=?8, issuerCommonName=?9, issuerOrganization=?10, issuerOrganizationUnit=?11, "+
" md5Fingerprint=?12, sha1Fingerprint=?13, issuerMd5Fingerprint=?14, issuerSha1Fingerprint=?15, cert=?16, flags=?17, stored=?18 "+
"WHERE host=?1"),
delHost: this.dbh.createStatement("DELETE FROM certificates WHERE host=?1"),
delSince: this.dbh.createStatement("DELETE FROM certificates WHERE stored >= ?18"),
delAll: this.dbh.createStatement("DELETE FROM certificates"),
};
} catch (err) {
this.warn("Error initializing SQLite operations: ", err);
}
},
dbclose: function() {
try {
if (this.dbh) {
this.dbh.close();
this.dbh = null;
}
} catch (err) {
this.log("CertPatrol: Error trying to close connection: ", err);
}
},
// Application trigger
init: function() {
var Cc = Components.classes, Ci = Components.interfaces;
this.prefs = Cc["@mozilla.org/preferences-service;1"]
.getService(Ci.nsIPrefService)
.getBranch("certpatrol.")
.QueryInterface(Ci.nsIPrefBranch2);
this.registerObserver("http-on-examine-response");
},
getMyVersion: function(callback) {
try {
// Firefox 4 and later; Mozilla 2 and later
Components.utils.import("resource://gre/modules/AddonManager.jsm");
AddonManager.getAddonByID(this.extID, function(addon) {
callback(addon.version);
});
} catch (ex) {
// Firefox 3.6 and before; Mozilla 1.9.2 and before
try {
var em = Components.classes["@mozilla.org/extensions/manager;1"]
.getService(Components.interfaces.nsIExtensionManager);
var addon = em.getItemForID(this.extID);
callback(addon.version);
} catch (ex) {
callback();
}
}
},
// helper functions for advanced patrol
isodate: function(tim) {
if (isNaN(tim)) {
## // this part of code can go when there are no more pre version 1.3
## // Certpatrol.sqlite instances around..
## //
## // i think i saw some cert dates without time info appended..
var iso = tim.replace(/^(\d\d)\/(\d\d)\/(\d+)/, "$3-$1-$2");
// upcoming Y3K bug, but you must delete this line before 2020
if (iso != tim) {
if (iso[0] != '2') iso = "20"+ iso;
return iso;
}
}
var d = new Date(tim / 1000);
## // locale string is too verbose. we don't need weekdays and time zones here
## // i was really afraid of having to do this. i love bad apis like Date().
## return d.getFullYear() +"-"+
## (d.getMonth() < 10 ? "0"+ d.getMonth() : d.getMonth()) +"-"+
## (d.getDay() < 10 ? "0"+ d.getDay() : d.getDay()) +" "+
## (d.getHours() < 10 ? "0"+ d.getHours() : d.getHours()) +":"+
## (d.getMinutes() < 10 ? "0"+ d.getMinutes() : d.getMinutes());
## // mozilla has this nice strftime extension to Date called toLocaleFormat()
return d.toLocaleFormat("%Y-%m-%d %H:%M:%S");
## // btw, this is not exactly ISO 8601 conformant but rather
## // preserves its original intent.. universal readability (thus no 'T')
},
timedelta: function(tim) {
if (!isNaN(tim)) tim /= 1000;
var d = new Date(tim);
// Y2K bug in Javascript... :)
if (d.getFullYear() < 1990) d.setFullYear(100 + d.getFullYear());
var now = new Date();
//alert("Now is "+ now.getTime() +" and cert is "+ d.getTime());
return d.getTime() - now.getTime();
},
daysdelta: function(td) {
td = Math.round(td / 86400000); // milliseconds per day
return " ("+ this.psycText(this.locale[td < 0 ? "daysPast" : "daysFuture"], {_days: td < 0 ? -td : td}) +")";
},
isodatedelta: function(tim) {
return tim ? this.isodate(tim) + this.daysdelta(this.timedelta(tim)) : "";
},
byteArrayToString: function(ba) {
var s = "";
for (var i = 0; i < ba.length; i++)
s += String.fromCharCode(ba[i]);
return s;
},
byteArrayToCert: function(ba) {
var Cc = Components.classes, Ci = Components.interfaces;
var c = "@mozilla.org/security/x509certdb;1", i= "nsIX509CertDB";
return Cc[c].getService(Ci[i]).constructX509FromBase64(window.btoa(this.byteArrayToString(ba.value)));
},
findASN1Object: function (struc, re) {
if (!struc) return;
if (re.test(struc.displayName)) return struc;
var s, Ci = Components.interfaces;
try {
s = struc.QueryInterface(Ci.nsIASN1Sequence);
}
catch (e) {}
if (!s || !s.isValidContainer) return;
for (var i=0; i<s.ASN1Objects.length; i++) {
struc = s.ASN1Objects.queryElementAt(i, Ci.nsIASN1Object);
var res = this.findASN1Object(struc, re);
if (res) return res;
}
},
newCertObj: function() {
return {
threat: 0,
flags: 0,
host: "",
threatLevel: "",
warn: {},
now: {
commonName: "",
organization: "",
organizationalUnit: "",
serialNumber: "",
emailAddress: "",
notBefore: "",
notAfter: "",
issuerCommonName: "",
issuerOrganization: "",
issuerOrganizationUnit: "",
md5Fingerprint: "",
sha1Fingerprint: "",
issuerMd5Fingerprint: "",
issuerSha1Fingerprint: "",
cert: null,
},
old: {
commonName: "",
organization: "",
organizationalUnit: "",
serialNumber: "",
emailAddress: "",
notBefore: "",
notAfter: "",
issuerCommonName: "",
issuerOrganization: "",
issuerOrganizationUnit: "",
md5Fingerprint: "",
sha1Fingerprint: "",
issuerMd5Fingerprint: "",
issuerSha1Fingerprint: "",
cert: null,
},
};
},
fillCertObj: function(obj, cert) {
obj.cert = cert;
obj.notBefore = cert.validity.notBefore;
obj.notAfter = cert.validity.notAfter;
if (cert.issuer) {
obj.issuerMd5Fingerprint = cert.issuer.md5Fingerprint;
obj.issuerSha1Fingerprint = cert.issuer.sha1Fingerprint;
} else {
//this.log("no issuer: "+ [cert.commonName, cert.issuer, cert.sha1Fingerprint]);
}
var keys = [
"commonName", "organization", "organizationalUnit", "serialNumber",
"emailAddress", // "subjectAlternativeName",
"issuerCommonName", "issuerOrganization", "issuerOrganizationUnit",
"md5Fingerprint", "sha1Fingerprint" ];
for (var i in keys)
obj[keys[i]] = cert[keys[i]];
obj.subjectAltName = [];
var san = this.findASN1Object(cert.ASN1Structure, /^Certificate Subject Alt Name$/);
if (san) {
//this.log("SAN:", [san.displayName, san.displayValue]);
var m, re = /DNS Name: ((?:\*\.)?[a-z0-9.-]+)/g;
while (m = re.exec(san.displayValue))
obj.subjectAltName.push(m[1]);
## this.log("SAN:", obj.subjectAltName);
// how do we use this now?
}
},
registerObserver: function(topic) {
var observerService = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.addObserver(this, topic, false);
},
unregisterObserver: function(topic) {
var observerService = Components.classes["@mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
observerService.removeObserver(this, topic);
},
observe: function(channel, topic, data) {
## this.log(">> observe:", [channel, topic, data]);
var Cc = Components.classes, Ci = Components.interfaces;
channel.QueryInterface(Ci.nsIHttpChannel);
var host = channel.URI.hostPort;
## this.log("URI: "+ channel.URI.spec);
var si = channel.securityInfo;
if (!si) return;
var nc = channel.notificationCallbacks;
if (!nc && channel.loadGroup)
nc = channel.loadGroup.notificationCallbacks;
if (!nc) return;
try {
var win = nc.getInterface(Ci.nsIDOMWindow);
} catch (e) {
return; // no window for e.g. favicons
}
if (!win.document) return;
var browser;
// thunderbird has no gBrowser
if (typeof gBrowser != "undefined") {
browser = gBrowser.getBrowserForDocument(win.top.document);
// We get notifications for a request in all of the open windows
// but browser is set only in the window the request is originated from,
// browser is null for favicons too.
if (!browser) return;
}
## this.log("browser: "+ browser);
## //var wpl = Ci.nsIWebProgressListener;
## //this.log("securityUI.state: "+ browser.securityUI.state +", "+ (browser.securityUI.state & wpl.STATE_IS_SECURE));
## // proceed only if the page is considered secure or browser is null -- disabled as it's not reliable
## //if (browser && !(browser.securityUI.state & wpl.STATE_IS_SECURE))
## //return;
si.QueryInterface(Ci.nsISSLStatusProvider);
var st = si.SSLStatus;
if (!st) return;
## this.log("st: "+ st);
st.QueryInterface(Ci.nsISSLStatus);
var cert = st.serverCert;
if (!cert) return;
## this.log("cert: "+ cert);
var obj = browser || win.top;
// store certs in the browser object so we can
// show only one notification per host for a browser tab
var key = [host, cert.md5Fingerprint, cert.sha1Fingerprint].join('|');
if (obj.__certs && obj.__certs[key] && cert.equals(obj.__certs[key]))
return;
obj.__certs = obj.__certs || {};
obj.__certs[key] = cert;
// The interesting part
var certobj = this.newCertObj();
certobj.host = host;
certobj.ciphername = st.cipherName;
certobj.keyLength = st.keyLength;
certobj.secretKeyLength = st.secretKeyLength;
this.fillCertObj(certobj.now, cert);
this.certCheck(browser, certobj);
},
// Certificate check
certCheck: function(browser, certobj) {
## this.log(">> certCheck: "+ certobj.host);
if (this.isIgnoredHost(certobj.host)) return;
var Cc = Components.classes, Ci = Components.interfaces;
var now = certobj.now, old = certobj.old;
var found = false;
## //if (this.last_sha1Fingerprint && this.last_sha1Fingerprint == now.sha1Fingerprint) return;
## //else this.last_sha1Fingerprint = now.sha1Fingerprint;
var pbs = Cc["@mozilla.org/privatebrowsing;1"];
if (pbs) {
pbs = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService);
var pbm = pbs.privateBrowsingEnabled;
}
var save = !pbm;
try {
if (pbm && this.prefs)
save = this.prefs.getBoolPref("privatebrowsing.save");
} catch (err) {}
##/*
## TODO: Before we even check the database we can make checks on the
## credibility of subCAs:
##
## + raise the threat level on subCAs that share no common substring
## like "verisign" with its root CA (like "bogus CA" being a subCA
## of "CNNIC"). here's a list of words to exclude, plus all strings
## shorter than 4 chars i suppose.
## "Internet Builtin Object Token Class Public Primary
## Certification Authority Extended Validation"
##
## + provide a hardcoded blacklist of CAs that sell subCAs for money
## (see website). raise threat level for those.
##
## + maybe add a whitelist of subCAs which happen to be okay anyway?
## (startssl case)
##*/
// Get certificate from storage
var stmt = this.db.selectHost;
try {
stmt.bindUTF8StringParameter(0, certobj.host);
if (stmt.executeStep()) {
found = true;
old.commonName = stmt.getUTF8String(1);
old.organization = stmt.getUTF8String(2);
old.organizationalUnit = stmt.getUTF8String(3);
old.serialNumber = stmt.getUTF8String(4);
old.emailAddress = stmt.getUTF8String(5);
old.notBefore = stmt.getUTF8String(6);
old.notAfter = stmt.getUTF8String(7);
old.issuerCommonName = stmt.getUTF8String(8);
old.issuerOrganization = stmt.getUTF8String(9);
old.issuerOrganizationUnit = stmt.getUTF8String(10);
old.md5Fingerprint = stmt.getUTF8String(11);
old.sha1Fingerprint = stmt.getUTF8String(12);
old.issuerMd5Fingerprint = stmt.getUTF8String(13);
old.issuerSha1Fingerprint = stmt.getUTF8String(14);
var blob = {};
stmt.getBlob(15, {}, blob);
if (blob.value.length)
old.cert = this.byteArrayToCert(blob);
certobj.flags = stmt.getInt64(16);
old.stored = stmt.getInt64(17) * 1000;
}
} catch(err) {
this.warn("Error trying to check certificate: ", err);
} finally {
stmt.reset();
}
var wild = this.wildcardCertCheck(now.cert);
// The certificate changed
if (found && (!old.cert || !now.cert.equals(old.cert))) {
// If the cert info was stored in the previous version of CertPatrol
// we don't have the full cert yet, so we just store it in the DB
// and return if everything looks fine.
if (!old.cert &&
old.sha1Fingerprint == now.sha1Fingerprint &&
old.md5Fingerprint == now.md5Fingerprint)
return this.saveCert(certobj);
// has the certificated hostname changed?
if (!wild && now.commonName != old.commonName) {
certobj.warn.commonName = true;
certobj.threat += 2;
}
if (!wild && !(certobj.flags & this.CHECK_ISSUER_ONLY)) {
// try to make some sense out of the certificate changes
var natd = this.timedelta(old.notAfter);
// certificate has expired
if (natd <= 0) certobj.warn.notAfter_expired = true;
// certificate still a long way to go
else if (natd > 7777777777) {
## //else if (natd > 10364400000) {
certobj.threat++;
certobj.warn.notAfter_notdue = true;
## // used to make it += 2 here, but in cases where server farms
## // use several valid certificates for the same host name that's
## // just too strict.
## } else if (natd > 5182200000) {
## certobj.threat++;
## certobj.warn.notAfter_due = true;
}
// certificate due sometime soonish
else if (natd > 0) certobj.warn.notAfter_due = true;
}
// now looking into the NEW certificate
var td = this.timedelta(now.notBefore);
if (td > 0) {
// new certificate isn't valid yet
certobj.warn.notBefore = true;
certobj.threat += 2;
}
// further checks done by agent before we even get here
// check if they have the same issuer
if (old.cert && now.cert.issuer && now.cert.issuer.equals(old.cert.issuer)) {
if (certobj.threat == 0 && certobj.flags & this.CHECK_ISSUER_ONLY)
return;
} else if (old.cert ||
(!old.cert && // old method, if we don't have a cert stored yet
(now.issuerOrganization != old.issuerOrganization ||
now.issuerCommonName != old.issuerCommonName))) {
certobj.warn.issuerCommonName = true;
// companies pick different CAs all the time unfortunately
certobj.threat++;
// TODO: implement more refined CA comparisons like
// has the root CA remained the same (
}
// fetch suitable scare message
if (certobj.threat > 3) certobj.threat = 3;
// produce human readable expiration dates
old.notBefore = this.isodatedelta(old.notBefore);
old.notAfter = this.isodatedelta(old.notAfter);
now.notBefore = this.isodatedelta(now.notBefore);
now.notAfter = this.isodatedelta(now.notAfter);
if (old.stored) old.stored = this.isodatedelta(old.stored * 1000);
if (wild && certobj.threat == 0) {
certobj.warn.wildcard = true;
certobj.event = this.locale.wildEvent;
} else {
certobj.event = this.locale.changeEvent +" "+
this.locale["threat"+ certobj.threat];
}
this.outchange(browser, certobj);
// New certificate
} else if (!found) {
if (save) {
// Store data
stmt = this.db.insert;
try {
stmt.bindUTF8StringParameter( 0, certobj.host);
stmt.bindUTF8StringParameter( 1, now.commonName);
stmt.bindUTF8StringParameter( 2, now.organization);
stmt.bindUTF8StringParameter( 3, now.organizationalUnit);
stmt.bindUTF8StringParameter( 4, now.serialNumber);
stmt.bindUTF8StringParameter( 5, now.emailAddress);
stmt.bindUTF8StringParameter( 6, now.notBefore);
stmt.bindUTF8StringParameter( 7, now.notAfter);
stmt.bindUTF8StringParameter( 8, now.issuerCommonName);
stmt.bindUTF8StringParameter( 9, now.issuerOrganization);
stmt.bindUTF8StringParameter(10, now.issuerOrganizationUnit);
stmt.bindUTF8StringParameter(11, now.md5Fingerprint);
stmt.bindUTF8StringParameter(12, now.sha1Fingerprint);
stmt.bindUTF8StringParameter(13, now.issuerMd5Fingerprint);
stmt.bindUTF8StringParameter(14, now.issuerSha1Fingerprint);
var der = now.cert.getRawDER({});
stmt.bindBlobParameter(15, der, der.length);
stmt.bindInt64Parameter(16, 0);
stmt.bindInt64Parameter(17, parseInt(new Date().getTime() / 1000));
stmt.execute();
} catch(err) {
this.warn("Error trying to insert certificate for "+
certobj.host +": ", err);
} finally {
stmt.reset();
}
}
## // checks are done by firefox before we even get here
## // that's why we don't complain about host != common name etc.
now.notBefore = this.isodatedelta(now.notBefore);
now.notAfter = this.isodatedelta(now.notAfter);
if (wild) {
certobj.warn.wildcard = true;
certobj.event = this.locale.wildEvent;
} else {
certobj.event = this.locale.newEvent;
}
this.outnew(browser, certobj);
}
},
// wildcardCertCheck contributed by Georg Koppen, JonDos GmbH 2010. Thanks!
// We are using it differently, though. The JonDos version is less paranoid.
//
wildcardCertCheck: function(cert) {
var stmt;
// First, we check whether we have a wildcard certificate at all. If not
// just return false and the new cert dialog will be schown. But even if
// we have one but no SHA1 fingerprint we should show it for security's
// sake...
## alert("doing wildcardCertCheck for "+ sha1Fingerprint);
if (cert.commonName.charAt(0) === '*' && cert.md5Fingerprint && cert.sha1Fingerprint) {
// We got one, check now if we have it already. If not, return false and
// the certificate will be shown. Otherwise, return yes and the new cert
// dialog will be omitted.
try {
stmt = this.db.selectWild;
// starts counting from 0, so ?13 is 12 here. you gotta love it.
stmt.bindUTF8StringParameter(11, cert.md5Fingerprint);
stmt.bindUTF8StringParameter(12, cert.sha1Fingerprint);
if (stmt.executeStep()) {
return true;
} else {
// This case could occur as well if we have *.example.com and
// foo.example.com with SHA1(1) saved and we find a cert with
// *.example.com and bar.example.com and SHA1(2): We would show
// the dialog even if we have already saved the wildcard cert. But
// that's okay due to the changed SHA1 fingerprint, thus prioritizing
// security and not convenience...
return false;
}
} catch (err) {
this.warn("Error trying to check wildcard certificate "+
cert.commonName +": ", err);
} finally {
stmt.reset();
}
} else return false;
},
// accept changed cert
saveCert: function(certobj) {
## this.log(">> saveCert: "+ certobj.host);
var stmt = this.db.update;
var cert = certobj.now.cert;
try {
stmt.bindUTF8StringParameter( 0, certobj.host);
stmt.bindUTF8StringParameter( 1, cert.commonName);
stmt.bindUTF8StringParameter( 2, cert.organization);
stmt.bindUTF8StringParameter( 3, cert.organizationalUnit);
stmt.bindUTF8StringParameter( 4, cert.serialNumber);
stmt.bindUTF8StringParameter( 5, cert.emailAddress);
stmt.bindUTF8StringParameter( 6, cert.validity.notBefore);
stmt.bindUTF8StringParameter( 7, cert.validity.notAfter);
stmt.bindUTF8StringParameter( 8, cert.issuerCommonName);
stmt.bindUTF8StringParameter( 9, cert.issuerOrganization);
stmt.bindUTF8StringParameter(10, cert.issuerOrganizationUnit);
stmt.bindUTF8StringParameter(11, cert.md5Fingerprint);
stmt.bindUTF8StringParameter(12, cert.sha1Fingerprint);
if (cert.issuer) {
stmt.bindUTF8StringParameter(13, cert.issuer.md5Fingerprint);
stmt.bindUTF8StringParameter(14, cert.issuer.sha1Fingerprint);
}
var der = cert.getRawDER({});
stmt.bindBlobParameter(15, der, der.length);
stmt.bindInt64Parameter(16, certobj.flags);
stmt.bindInt64Parameter(17, parseInt(new Date().getTime() / 1000));
stmt.execute();
} catch(err) {
this.warn("Error trying to update certificate: ", err);
} finally {
stmt.reset();
}
return true;
},
// reject new cert
delCert: function(host) {
var stmt;
try {
stmt = this.db.delHost;
stmt.bindUTF8StringParameter(0, host);
stmt.executeStep();
} catch (err) {
this.warn("Error while trying to remove certificate: ", err);
} finally {
stmt.reset();
}
},
delCerts: function(hosts) {
if (!hosts || !hosts.length) return;
if (!this.dbh) this.dbinit();
var params = [];
for (var i=1; i<=hosts.length; i++)
params.push('?'+i);
try {
var stmt = this.dbh.createStatement("DELETE FROM certificates WHERE host IN ("+ params.join(",") +")");
for (var i=0; i<hosts.length; i++)
stmt.bindUTF8StringParameter(i, hosts[i]);
stmt.executeStep();
} catch (err) {
this.warn("Error while trying to remove certificates: ", err);
} finally {
stmt.reset();
}
},
// sanitizer - clear recent history
delCertsSince: function(range) {
if (!this.dbh)
this.dbinit();
var stmt;
try {
if (range) {
stmt = this.db.delSince;
stmt.bindInt64Parameter(17, range[0] / 1000000);
} else {
stmt = this.db.delAll;
}
stmt.executeStep();
} catch (err) {
this.warn("Error while trying to remove certificates: ", err);
} finally {
stmt.reset();
}
try {
// delete stored certs in browser objects
var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
.getService(Components.interfaces.nsIWindowMediator);
var enumerator = wm.getEnumerator(null);
while (enumerator.hasMoreElements()) {
var win = enumerator.getNext();
if (win && win.gBrowser && win.gBrowser.browsers) {
var browsers = win.gBrowser.browsers;
for (var i=0; i<browsers.length; i++)
delete browsers[i].__certs;
}
}
} catch (err) {
this.warn("Error while trying to remove certificates from tabs: ", err);
}
},
updateFlags: function(hosts, flag, on) {
if (!hosts || !hosts.length) return;
if (typeof hosts != 'object') hosts = [hosts];
if (!this.dbh) this.dbinit();
var params = [];
for (var i=0; i<hosts.length; i++)
params.push('?'+ (i+2));
try {
var stmt;
if (on)
stmt = this.dbh.createStatement("UPDATE certificates SET flags = flags | ?1 WHERE host IN ("+ params.join(",") +")");
else
stmt = this.dbh.createStatement("UPDATE certificates SET flags = flags & ~?1 WHERE host IN ("+ params.join(",") +")");
stmt.bindInt64Parameter(0, flag);
for (var i=0; i<hosts.length; i++)
stmt.bindUTF8StringParameter(i+1, hosts[i]);
stmt.executeStep();
} catch (err) {
this.warn("Error while trying to update flags: ", err);
} finally {
stmt.reset();
}
try {
stmt = this.dbh.createStatement("UPDATE certificates SET flags = ?1 WHERE flags IS NULL AND host IN ("+ params.join(",") +")");
stmt.bindInt64Parameter(0, flag);
for (var i=0; i<hosts.length; i++)
stmt.bindUTF8StringParameter(i+1, hosts[i]);
stmt.executeStep();
} catch (err) {
this.warn("Error while trying to update flags: ", err);
} finally {
stmt.reset();
}
},
setFlag: function(certobj, flag, on) {
if (on)
certobj.flags |= flag;
else
certobj.flags &= ~flag;
},
getAllCerts: function() {
if (!this.dbh) this.dbinit();
var certs = [];
var stmt;
try {
stmt = this.db.selectAll;
while (stmt.executeStep()) {
var obj = {
host: stmt.getUTF8String(0),
commonName: stmt.getUTF8String(1),
organization: stmt.getUTF8String(2),
organizationalUnit: stmt.getUTF8String(3),
serialNumber: stmt.getUTF8String(4),
emailAddress: stmt.getUTF8String(5),
md5Fingerprint: stmt.getUTF8String(11),
sha1Fingerprint: stmt.getUTF8String(12),
validity: {
notBefore: stmt.getUTF8String(6),
notAfter: stmt.getUTF8String(7),
},
issuer: {
commonName: stmt.getUTF8String(8),
organization: stmt.getUTF8String(9),
organizationUnit: stmt.getUTF8String(10),
issuerMd5Fingerprint: stmt.getUTF8String(13),
issuerSha1Fingerprint: stmt.getUTF8String(14),
},
flags: stmt.getInt64(16),
stored: stmt.getInt64(17) * 1000,
};
var blob = {};
stmt.getBlob(15, {}, blob);
if (blob.value.length) {
var cert = this.byteArrayToCert(blob);
if (cert)
this.fillCertObj(obj, cert);
}
certs.push(obj);
}
} catch (err) {
this.warn("Error while trying to get certificates: ", err);
} finally {
stmt.reset();
}
return certs;
},
isIgnoredHost: function(host) {
try {
var list = this.prefs.getCharPref("hosts.ignore");
} catch (e) {
return false;
}
return new RegExp('(?:^|[\\s,])'+host.replace(/\./g,'\\.')+'(?:[\\s,]|$)').test(list);
},
ignoreHost: function(host) {
if (this.isIgnoredHost(host)) return;
var list = "";
try {
list = this.prefs.getCharPref("hosts.ignore");
} catch (e) {}
this.prefs.setCharPref("hosts.ignore", list +" "+ host);
},
outnew: function(browser, certobj) {
var forcePopup = false;
try {
if (this.prefs)
forcePopup = this.prefs.getBoolPref(certobj.warn.wildcard ? "popup.wild" : "popup.new");
} catch (err) {}
try {
if (!forcePopup && (!certobj.warn.wildcard && !this.prefs.getBoolPref("notify.new") ||
certobj.warn.wildcard && !this.prefs.getBoolPref("notify.wild")))
return;
} catch (err) {}
var win = browser && browser.contentWindow ? browser.contentWindow : window;
var notifyBox = this.getNotificationBox(browser);
var popup = forcePopup || !notifyBox;
## // https://developer.mozilla.org/en/XUL/Method/appendNotification
## // http://gist.github.com/256554
## // using certobj.host as the id for the notification
if (notifyBox && !popup) {
var timeout;
var n = notifyBox.appendNotification(
"(CertPatrol) "+ certobj.host +": "+certobj.event +" "+
certobj.now.commonName +". "+
this.locale.issuedBy +" "+
(certobj.now.issuerOrganization || certobj.now.issuerCommonName)
, certobj.host, null, notifyBox.PRIORITY_INFO_HIGH, [{
label: this.locale.reject,
accessKey: this.locale.reject_key,
callback: function(msg, btn) {
if (timeout) clearTimeout(timeout);
CertPatrol.delCert(certobj.host);
}
}, {
label: this.locale.viewDetails,
accessKey: this.locale.viewDetails_key,
callback: function(msg, btn) {
if (timeout) clearTimeout(timeout);
win.openDialog("chrome://certpatrol/content/new.xul",
"_blank", "chrome,dialog,modal",
certobj, CertPatrol);
}
}]);
n.persistence = 10; // make sure it stays visible after redirects
try {
var t = this.prefs.getIntPref("notify.timeout");
if (t > 0) {
timeout = setTimeout(function() {
if (n.parentNode) notifyBox.removeNotification(n);
n = null;
}, t * 1000);
}
} catch (err) {}
}
if (popup)
win.openDialog("chrome://certpatrol/content/new.xul", "_blank",
"chrome,dialog,modal", certobj, CertPatrol);
},
outchange: function(browser, certobj) {
var forcePopup = false;
try {
if (this.prefs)
forcePopup = this.prefs.getBoolPref("popup.change");
} catch (err) {}
var win = browser && browser.contentWindow ? browser.contentWindow : window;
var notifyBox = this.getNotificationBox(browser);
var popup = forcePopup || certobj.threat > 1 || !notifyBox;
if (notifyBox && !popup) {
var priority = [
notifyBox.PRIORITY_INFO_LOW,
notifyBox.PRIORITY_INFO_HIGH,
notifyBox.PRIORITY_WARNING_HIGH,
notifyBox.PRIORITY_CRITICAL_HIGH
];
var warn = "";
for (var k in certobj.warn)
if (this.locale["warn_"+k])
warn += " *** " + this.locale["warn_"+k];
var timeout;
var n = notifyBox.appendNotification(
"(CertPatrol) "+ certobj.host +": "+ certobj.event +" "+
certobj.now.commonName +". "+
this.locale.issuedBy +" "+
(certobj.now.issuerOrganization || certobj.now.issuerCommonName) +" "+
warn, certobj.host, null, priority[certobj.threat], [{
label: this.locale.accept,
accessKey: this.locale.accept_key,
callback: function(msg, btn) {
if (timeout) clearTimeout(timeout);