summaryrefslogtreecommitdiffstats
path: root/mobile/android/components/NSSDialogService.js
blob: 671cc8c3517dfdc4c6cd63a6d03e5ae1bfba5463 (plain)
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
/* 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/. */

const Ci = Components.interfaces;
const Cu = Components.utils;
const Cc = Components.classes;

Cu.import("resource://gre/modules/XPCOMUtils.jsm");
Cu.import("resource://gre/modules/Services.jsm");

XPCOMUtils.defineLazyModuleGetter(this, "Prompt",
                                  "resource://gre/modules/Prompt.jsm");

// -----------------------------------------------------------------------
// NSS Dialog Service
// -----------------------------------------------------------------------

function NSSDialogs() { }

NSSDialogs.prototype = {
  classID: Components.ID("{cbc08081-49b6-4561-9c18-a7707a50bda1}"),
  QueryInterface: XPCOMUtils.generateQI([Ci.nsICertificateDialogs, Ci.nsIClientAuthDialogs]),

  /**
   * Escapes the given input via HTML entity encoding. Used to prevent HTML
   * injection when the input is to be placed inside an HTML body, but not in
   * any other context.
   *
   * @param {String} input The input to interpret as a plain string.
   * @returns {String} The escaped input.
   */
  escapeHTML: function(input) {
    return input.replace(/&/g, "&")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#x27;")
                .replace(/\//g, "&#x2F;");
  },

  getString: function(aName) {
    if (!this.bundle) {
        this.bundle = Services.strings.createBundle("chrome://browser/locale/pippki.properties");
    }
    return this.bundle.GetStringFromName(aName);
  },

  formatString: function(aName, argList) {
    if (!this.bundle) {
      this.bundle =
        Services.strings.createBundle("chrome://browser/locale/pippki.properties");
    }
    let escapedArgList = Array.from(argList, x => this.escapeHTML(x));
    return this.bundle.formatStringFromName(aName, escapedArgList,
                                            escapedArgList.length);
  },

  getPrompt: function(aTitle, aText, aButtons) {
    return new Prompt({
      title: aTitle,
      text: aText,
      buttons: aButtons,
    });
  },

  showPrompt: function(aPrompt) {
    let response = null;
    aPrompt.show(function(data) {
      response = data;
    });

    // Spin this thread while we wait for a result
    let thread = Services.tm.currentThread;
    while (response === null)
      thread.processNextEvent(true);

    return response;
  },

  confirmDownloadCACert: function(aCtx, aCert, aTrust) {
    while (true) {
      let prompt = this.getPrompt(this.getString("downloadCert.title"),
                                  this.getString("downloadCert.message1"),
                                  [ this.getString("nssdialogs.ok.label"),
                                    this.getString("downloadCert.viewCert.label"),
                                    this.getString("nssdialogs.cancel.label")
                                  ]);

      prompt.addCheckbox({ id: "trustSSL", label: this.getString("downloadCert.trustSSL"), checked: false })
            .addCheckbox({ id: "trustEmail", label: this.getString("downloadCert.trustEmail"), checked: false })
            .addCheckbox({ id: "trustSign", label: this.getString("downloadCert.trustObjSign"), checked: false });
      let response = this.showPrompt(prompt);

      // they hit the "view cert" button, so show the cert and try again
      if (response.button == 1) {
        this.viewCert(aCtx, aCert);
        continue;
      } else if (response.button != 0) {
        return false;
      }

      aTrust.value = Ci.nsIX509CertDB.UNTRUSTED;
      if (response.trustSSL) aTrust.value |= Ci.nsIX509CertDB.TRUSTED_SSL;
      if (response.trustEmail) aTrust.value |= Ci.nsIX509CertDB.TRUSTED_EMAIL;
      if (response.trustSign) aTrust.value |= Ci.nsIX509CertDB.TRUSTED_OBJSIGN;
      return true;
    }
  },

  setPKCS12FilePassword: function(aCtx, aPassword) {
    // this dialog is never shown in Fennec; in Desktop it is shown while backing up a personal
    // certificate to a file via Preferences->Advanced->Encryption->View Certificates->Your Certificates
    throw "Unimplemented";
  },

  getPKCS12FilePassword: function(aCtx, aPassword) {
    let prompt = this.getPrompt(this.getString("pkcs12.getpassword.title"),
                                this.getString("pkcs12.getpassword.message"),
                                [ this.getString("nssdialogs.ok.label"),
                                  this.getString("nssdialogs.cancel.label")
                                ]).addPassword({id: "pw"});
    let response = this.showPrompt(prompt);
    if (response.button != 0) {
      return false;
    }

    aPassword.value = response.pw;
    return true;
  },

  certInfoSection: function(aHeading, aDataPairs, aTrailingNewline = true) {
    let certInfoStrings = [
      "<big>" + this.getString(aHeading) + "</big>",
    ];

    for (let i = 0; i < aDataPairs.length; i += 2) {
      let key = aDataPairs[i];
      let value = aDataPairs[i + 1];
      certInfoStrings.push(this.formatString(key, [value]));
    }

    if (aTrailingNewline) {
      certInfoStrings.push("<br/>");
    }

    return certInfoStrings.join("<br/>");
  },

  viewCert: function(aCtx, aCert) {
    let p = this.getPrompt(this.getString("certmgr.title"), "", [
                             this.getString("nssdialogs.ok.label"),
                           ]);
    p.addLabel({ label: this.certInfoSection("certmgr.subjectinfo.label",
                          ["certdetail.cn", aCert.commonName,
                           "certdetail.o", aCert.organization,
                           "certdetail.ou", aCert.organizationalUnit,
                           "certdetail.serialnumber", aCert.serialNumber])})
     .addLabel({ label: this.certInfoSection("certmgr.issuerinfo.label",
                          ["certdetail.cn", aCert.issuerCommonName,
                           "certdetail.o", aCert.issuerOrganization,
                           "certdetail.ou", aCert.issuerOrganizationUnit])})
     .addLabel({ label: this.certInfoSection("certmgr.periodofvalidity.label",
                          ["certdetail.notBefore", aCert.validity.notBeforeLocalDay,
                           "certdetail.notAfter", aCert.validity.notAfterLocalDay])})
     .addLabel({ label: this.certInfoSection("certmgr.fingerprints.label",
                          ["certdetail.sha256fingerprint", aCert.sha256Fingerprint,
                           "certdetail.sha1fingerprint", aCert.sha1Fingerprint],
                          false) });
    this.showPrompt(p);
  },

  /**
   * Returns a list of details of the given cert relevant for TLS client
   * authentication.
   *
   * @param {nsIX509Cert} cert Cert to get the details of.
   * @returns {String} <br/> delimited list of details.
   */
  getCertDetails: function(cert) {
    let detailLines = [
      this.formatString("clientAuthAsk.issuedTo", [cert.subjectName]),
      this.formatString("clientAuthAsk.serial", [cert.serialNumber]),
      this.formatString("clientAuthAsk.validityPeriod",
                        [cert.validity.notBeforeLocalTime,
                         cert.validity.notAfterLocalTime]),
    ];
    let keyUsages = cert.keyUsages;
    if (keyUsages) {
      detailLines.push(this.formatString("clientAuthAsk.keyUsages",
                                         [keyUsages]));
    }
    let emailAddresses = cert.getEmailAddresses({});
    if (emailAddresses.length > 0) {
      let joinedAddresses = emailAddresses.join(", ");
      detailLines.push(this.formatString("clientAuthAsk.emailAddresses",
                                         [joinedAddresses]));
    }
    detailLines.push(this.formatString("clientAuthAsk.issuedBy",
                                       [cert.issuerName]));
    detailLines.push(this.formatString("clientAuthAsk.storedOn",
                                       [cert.tokenName]));

    return detailLines.join("<br/>");
  },

  viewCertDetails: function(details) {
    let p = this.getPrompt(this.getString("clientAuthAsk.message3"),
                    '',
                    [ this.getString("nssdialogs.ok.label") ]);
    p.addLabel({ label: details });
    this.showPrompt(p);
  },

  chooseCertificate: function(ctx, hostname, port, organization, issuerOrg,
                              certList, selectedIndex) {
    let rememberSetting =
      Services.prefs.getBoolPref("security.remember_cert_checkbox_default_setting");

    let serverRequestedDetails = [
      this.formatString("clientAuthAsk.hostnameAndPort",
                        [hostname, port.toString()]),
      this.formatString("clientAuthAsk.organization", [organization]),
      this.formatString("clientAuthAsk.issuer", [issuerOrg]),
    ].join("<br/>");

    let certNickList = [];
    let certDetailsList = [];
    for (let i = 0; i < certList.length; i++) {
      let cert = certList.queryElementAt(i, Ci.nsIX509Cert);
      certNickList.push(this.formatString("clientAuthAsk.nickAndSerial",
                                          [cert.nickname, cert.serialNumber]));
      certDetailsList.push(this.getCertDetails(cert));
    }

    selectedIndex.value = 0;
    while (true) {
      let buttons = [
        this.getString("nssdialogs.ok.label"),
        this.getString("clientAuthAsk.viewCert.label"),
        this.getString("nssdialogs.cancel.label"),
      ];
      let prompt = this.getPrompt(this.getString("clientAuthAsk.title"),
                                  this.getString("clientAuthAsk.message1"),
                                  buttons)
      .addLabel({ id: "requestedDetails", label: serverRequestedDetails } )
      .addMenulist({
        id: "nicknames",
        label: this.getString("clientAuthAsk.message2"),
        values: certNickList,
        selected: selectedIndex.value,
      }).addCheckbox({
        id: "rememberBox",
        label: this.getString("clientAuthAsk.remember.label"),
        checked: rememberSetting
      });
      let response = this.showPrompt(prompt);
      selectedIndex.value = response.nicknames;
      if (response.button == 1 /* buttons[1] */) {
        this.viewCertDetails(certDetailsList[selectedIndex.value]);
        continue;
      } else if (response.button == 0 /* buttons[0] */) {
        if (response.rememberBox == true) {
          let caud = ctx.QueryInterface(Ci.nsIClientAuthUserDecision);
          if (caud) {
            caud.rememberClientAuthCertificate = true;
          }
        }
        return true;
      }
      return false;
    }
  }
};

this.NSGetFactory = XPCOMUtils.generateNSGetFactory([NSSDialogs]);