nss_decryptor_system_nss.cc revision 72a454cd3513ac24fbdd0e0cb9ad70b86a99b801
1// Copyright (c) 2009 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/importer/nss_decryptor_system_nss.h"
6
7#include <pk11pub.h>
8#include <pk11sdr.h>
9
10#include "base/basictypes.h"
11#include "base/file_path.h"
12#include "base/nss_util.h"
13#include "base/string_util.h"
14#include "base/sys_string_conversions.h"
15
16NSSDecryptor::NSSDecryptor() : is_nss_initialized_(false), db_slot_(NULL) {}
17NSSDecryptor::~NSSDecryptor() {
18  if (db_slot_) {
19    // Deliberately leave the user db open, just in case we need to open more
20    // than one, because there's an NSS bug with reopening user dbs.
21    // https://bugzilla.mozilla.org/show_bug.cgi?id=506140
22    // SECMOD_CloseUserDB(db_slot_);
23    PK11_FreeSlot(db_slot_);
24  }
25}
26
27bool NSSDecryptor::Init(const FilePath& dll_path, const FilePath& db_path) {
28  base::EnsureNSSInit();
29  is_nss_initialized_ = true;
30  const std::string modspec =
31      StringPrintf("configDir='%s' tokenDescription='Firefox NSS database' "
32                   "flags=readOnly", db_path.value().c_str());
33  db_slot_ = SECMOD_OpenUserDB(modspec.c_str());
34  return db_slot_ != NULL;
35}
36
37// This method is based on some NSS code in
38//   security/nss/lib/pk11wrap/pk11sdr.c, CVS revision 1.22
39// This code is copied because the implementation assumes the use of the
40// internal key slot for decryption, but we need to use another slot.
41// The license block is:
42/* ***** BEGIN LICENSE BLOCK *****
43 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
44 *
45 * The contents of this file are subject to the Mozilla Public License Version
46 * 1.1 (the "License"); you may not use this file except in compliance with
47 * the License. You may obtain a copy of the License at
48 * http://www.mozilla.org/MPL/
49 *
50 * Software distributed under the License is distributed on an "AS IS" basis,
51 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
52 * for the specific language governing rights and limitations under the
53 * License.
54 *
55 * The Original Code is the Netscape security libraries.
56 *
57 * The Initial Developer of the Original Code is
58 * Netscape Communications Corporation.
59 * Portions created by the Initial Developer are Copyright (C) 1994-2000
60 * the Initial Developer. All Rights Reserved.
61 *
62 * Contributor(s):
63 *   thayes@netscape.com
64 *
65 * Alternatively, the contents of this file may be used under the terms of
66 * either the GNU General Public License Version 2 or later (the "GPL"), or
67 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
68 * in which case the provisions of the GPL or the LGPL are applicable instead
69 * of those above. If you wish to allow use of your version of this file only
70 * under the terms of either the GPL or the LGPL, and not to allow others to
71 * use your version of this file under the terms of the MPL, indicate your
72 * decision by deleting the provisions above and replace them with the notice
73 * and other provisions required by the GPL or the LGPL. If you do not delete
74 * the provisions above, a recipient may use your version of this file under
75 * the terms of any one of the MPL, the GPL or the LGPL.
76 *
77 * ***** END LICENSE BLOCK ***** */
78
79/*
80 * Data structure and template for encoding the result of an SDR operation
81 *  This is temporary.  It should include the algorithm ID of the encryption
82 *  mechanism
83 */
84struct SDRResult
85{
86  SECItem keyid;
87  SECAlgorithmID alg;
88  SECItem data;
89};
90typedef struct SDRResult SDRResult;
91
92static SEC_ASN1Template g_template[] = {
93  { SEC_ASN1_SEQUENCE, 0, NULL, sizeof (SDRResult) },
94  { SEC_ASN1_OCTET_STRING, offsetof(SDRResult, keyid) },
95  { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(SDRResult, alg),
96    SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
97  { SEC_ASN1_OCTET_STRING, offsetof(SDRResult, data) },
98  { 0 }
99};
100
101static SECStatus
102unpadBlock(SECItem *data, int blockSize, SECItem *result)
103{
104  SECStatus rv = SECSuccess;
105  int padLength;
106  int i;
107
108  result->data = 0;
109  result->len = 0;
110
111  /* Remove the padding from the end if the input data */
112  if (data->len == 0 || data->len % blockSize  != 0) {
113    rv = SECFailure;
114    goto loser;
115  }
116
117  padLength = data->data[data->len-1];
118  if (padLength > blockSize) { rv = SECFailure; goto loser; }
119
120  /* verify padding */
121  for (i=data->len - padLength; static_cast<uint32>(i) < data->len; i++) {
122    if (data->data[i] != padLength) {
123        rv = SECFailure;
124        goto loser;
125    }
126  }
127
128  result->len = data->len - padLength;
129  result->data = (unsigned char *)PORT_Alloc(result->len);
130  if (!result->data) { rv = SECFailure; goto loser; }
131
132  PORT_Memcpy(result->data, data->data, result->len);
133
134  if (padLength < 2) {
135    return SECWouldBlock;
136  }
137
138loser:
139  return rv;
140}
141
142/* decrypt a block */
143static SECStatus
144pk11Decrypt(PK11SlotInfo *slot, PLArenaPool *arena,
145            CK_MECHANISM_TYPE type, PK11SymKey *key,
146            SECItem *params, SECItem *in, SECItem *result)
147{
148  PK11Context *ctx = 0;
149  SECItem paddedResult;
150  SECStatus rv;
151
152  paddedResult.len = 0;
153  paddedResult.data = 0;
154
155  ctx = PK11_CreateContextBySymKey(type, CKA_DECRYPT, key, params);
156  if (!ctx) { rv = SECFailure; goto loser; }
157
158  paddedResult.len = in->len;
159  paddedResult.data = static_cast<unsigned char*>(
160      PORT_ArenaAlloc(arena, paddedResult.len));
161
162  rv = PK11_CipherOp(ctx, paddedResult.data,
163                        (int*)&paddedResult.len, paddedResult.len,
164                        in->data, in->len);
165  if (rv != SECSuccess) goto loser;
166
167  PK11_Finalize(ctx);
168
169  /* Remove the padding */
170  rv = unpadBlock(&paddedResult, PK11_GetBlockSize(type, 0), result);
171  if (rv) goto loser;
172
173loser:
174  if (ctx) PK11_DestroyContext(ctx, PR_TRUE);
175  return rv;
176}
177
178SECStatus NSSDecryptor::PK11SDR_DecryptWithSlot(
179    PK11SlotInfo* slot, SECItem* data, SECItem* result, void* cx) const {
180  SECStatus rv = SECSuccess;
181  PK11SymKey *key = 0;
182  CK_MECHANISM_TYPE type;
183  SDRResult sdrResult;
184  SECItem *params = 0;
185  SECItem possibleResult = { siBuffer, NULL, 0 };
186  PLArenaPool *arena = 0;
187
188  arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
189  if (!arena) { rv = SECFailure; goto loser; }
190
191  /* Decode the incoming data */
192  memset(&sdrResult, 0, sizeof sdrResult);
193  rv = SEC_QuickDERDecodeItem(arena, &sdrResult, g_template, data);
194  if (rv != SECSuccess) goto loser;  /* Invalid format */
195
196  /* Get the parameter values from the data */
197  params = PK11_ParamFromAlgid(&sdrResult.alg);
198  if (!params) { rv = SECFailure; goto loser; }
199
200  /* Use triple-DES (Should look up the algorithm) */
201  type = CKM_DES3_CBC;
202  key = PK11_FindFixedKey(slot, type, &sdrResult.keyid, cx);
203  if (!key) {
204    rv = SECFailure;
205  } else {
206    rv = pk11Decrypt(slot, arena, type, key, params,
207                     &sdrResult.data, result);
208  }
209
210  /*
211   * if the pad value was too small (1 or 2), then it's statistically
212   * 'likely' that (1 in 256) that we may not have the correct key.
213   * Check the other keys for a better match. If we find none, use
214   * this result.
215   */
216  if (rv == SECWouldBlock)
217    possibleResult = *result;
218
219  /*
220   * handle the case where your key indicies may have been broken
221   */
222  if (rv != SECSuccess) {
223    PK11SymKey *keyList = PK11_ListFixedKeysInSlot(slot, NULL, cx);
224    PK11SymKey *testKey = NULL;
225    PK11SymKey *nextKey = NULL;
226
227    for (testKey = keyList; testKey;
228         testKey = PK11_GetNextSymKey(testKey)) {
229      rv = pk11Decrypt(slot, arena, type, testKey, params,
230                       &sdrResult.data, result);
231      if (rv == SECSuccess)
232        break;
233
234      /* found a close match. If it's our first remember it */
235      if (rv == SECWouldBlock) {
236        if (possibleResult.data) {
237          /* this is unlikely but possible. If we hit this condition,
238           * we have no way of knowing which possibility to prefer.
239           * in this case we just match the key the application
240           * thought was the right one */
241          SECITEM_ZfreeItem(result, PR_FALSE);
242        } else {
243          possibleResult = *result;
244        }
245      }
246    }
247
248    /* free the list */
249    for (testKey = keyList; testKey; testKey = nextKey) {
250         nextKey = PK11_GetNextSymKey(testKey);
251      PK11_FreeSymKey(testKey);
252    }
253  }
254
255  /* we didn't find a better key, use the one with a small pad value */
256  if ((rv != SECSuccess) && (possibleResult.data)) {
257    *result = possibleResult;
258    possibleResult.data = NULL;
259    rv = SECSuccess;
260  }
261
262 loser:
263  if (arena) PORT_FreeArena(arena, PR_TRUE);
264  if (key) PK11_FreeSymKey(key);
265  if (params) SECITEM_ZfreeItem(params, PR_TRUE);
266  if (possibleResult.data) SECITEM_ZfreeItem(&possibleResult, PR_FALSE);
267
268  return rv;
269}
270