DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (409f3966645a)

VCS Links

Line Code
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
/* 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/. */

#include "nsPKCS12Blob.h"

#include "ScopedNSSTypes.h"
#include "mozilla/Assertions.h"
#include "mozilla/Casting.h"
#include "mozilla/Unused.h"
#include "nsICertificateDialogs.h"
#include "nsIFile.h"
#include "nsIInputStream.h"
#include "nsIPrompt.h"
#include "nsIWindowWatcher.h"
#include "nsIX509CertDB.h"
#include "nsNSSCertHelper.h"
#include "nsNSSCertificate.h"
#include "nsNSSHelper.h"
#include "nsNetUtil.h"
#include "nsReadableUtils.h"
#include "nsThreadUtils.h"
#include "p12plcy.h"
#include "pkix/pkixtypes.h"
#include "secerr.h"

using namespace mozilla;
extern LazyLogModule gPIPNSSLog;

#define PIP_PKCS12_BUFFER_SIZE 2048
#define PIP_PKCS12_NOSMARTCARD_EXPORT 4
#define PIP_PKCS12_RESTORE_FAILED 5
#define PIP_PKCS12_BACKUP_FAILED 6
#define PIP_PKCS12_NSS_ERROR 7

nsPKCS12Blob::nsPKCS12Blob()
  : mUIContext(new PipUIContext())
{
}

// Given a file handle, read a PKCS#12 blob from that file, decode it, and
// import the results into the internal database.
nsresult
nsPKCS12Blob::ImportFromFile(nsIFile* aFile, const nsAString& aPassword, uint32_t& aError)
{
  uint32_t passwordBufferLength;
  UniquePtr<uint8_t[]> passwordBuffer;

  UniquePK11SlotInfo slot(PK11_GetInternalKeySlot());
  if (!slot) {
    return NS_ERROR_FAILURE;
  }

  passwordBuffer = stringToBigEndianBytes(aPassword, passwordBufferLength);

  // initialize the decoder
  SECItem unicodePw = { siBuffer, passwordBuffer.get(), passwordBufferLength };
  UniqueSEC_PKCS12DecoderContext dcx(
    SEC_PKCS12DecoderStart(&unicodePw, slot.get(), nullptr, nullptr, nullptr,
                           nullptr, nullptr, nullptr));
  if (!dcx) {
    return NS_ERROR_FAILURE;
  }
  // read input aFile and feed it to the decoder
  PRErrorCode nssError;
  nsresult rv = inputToDecoder(dcx, aFile, nssError);
  if (NS_FAILED(rv)) {
    return rv;
  }
  if (nssError != 0) {
    aError = handlePRErrorCode(nssError);
    return NS_OK;
  }
  // verify the blob
  SECStatus srv = SEC_PKCS12DecoderVerify(dcx.get());
  if (srv != SECSuccess) {
    aError = handlePRErrorCode(PR_GetError());
    return NS_OK;
  }
  // validate bags
  srv = SEC_PKCS12DecoderValidateBags(dcx.get(), nicknameCollision);
  if (srv != SECSuccess) {
    aError = handlePRErrorCode(PR_GetError());
    return NS_OK;
  }
  // import cert and key
  srv = SEC_PKCS12DecoderImportBags(dcx.get());
  if (srv != SECSuccess) {
    aError = handlePRErrorCode(PR_GetError());
    return NS_OK;
  }
  aError = nsIX509CertDB::Success;
  return NS_OK;
}

static bool
isExtractable(UniqueSECKEYPrivateKey& privKey)
{
  ScopedAutoSECItem value;
  SECStatus rv = PK11_ReadRawAttribute(
    PK11_TypePrivKey, privKey.get(), CKA_EXTRACTABLE, &value);
  if (rv != SECSuccess) {
    return false;
  }

  bool isExtractable = false;
  if ((value.len == 1) && value.data) {
    isExtractable = !!(*(CK_BBOOL*)value.data);
  }
  return isExtractable;
}

// Having already loaded the certs, form them into a blob (loading the keys
// also), encode the blob, and stuff it into the file.
nsresult
nsPKCS12Blob::ExportToFile(nsIFile* aFile, nsIX509Cert** aCerts, int aNumCerts,
                           const nsAString& aPassword, uint32_t& aError)
{

  // get file password (unicode)
  uint32_t passwordBufferLength;
  UniquePtr<uint8_t[]> passwordBuffer;
  passwordBuffer = stringToBigEndianBytes(aPassword, passwordBufferLength);
  aError = nsIX509CertDB::Success;
  if (!passwordBuffer) {
    return NS_OK;
  }
  UniqueSEC_PKCS12ExportContext ecx(
    SEC_PKCS12CreateExportContext(nullptr, nullptr, nullptr, nullptr));
  if (!ecx) {
    aError = nsIX509CertDB::ERROR_PKCS12_BACKUP_FAILED;
    return NS_OK;
  }
  // add password integrity
  SECItem unicodePw = { siBuffer, passwordBuffer.get(), passwordBufferLength };
  SECStatus srv = SEC_PKCS12AddPasswordIntegrity(ecx.get(), &unicodePw,
                                                 SEC_OID_SHA1);
  if (srv != SECSuccess) {
    aError = nsIX509CertDB::ERROR_PKCS12_BACKUP_FAILED;
    return NS_OK;
  }
  for (int i = 0; i < aNumCerts; i++) {
    UniqueCERTCertificate nssCert(aCerts[i]->GetCert());
    if (!nssCert) {
      aError = nsIX509CertDB::ERROR_PKCS12_BACKUP_FAILED;
      return NS_OK;
    }
    // We can probably only successfully export certs that are on the internal
    // token. Most, if not all, smart card vendors won't let you extract the
    // private key (in any way shape or form) from the card. So let's punt if
    // the cert is not in the internal db.
    if (nssCert->slot && !PK11_IsInternal(nssCert->slot)) {
      // We aren't the internal token, see if the key is extractable.
      UniqueSECKEYPrivateKey privKey(
        PK11_FindKeyByDERCert(nssCert->slot, nssCert.get(), mUIContext));
      if (privKey && !isExtractable(privKey)) {
        // This is informative.  If a serious error occurs later it will
        // override it later and return.
        aError = nsIX509CertDB::ERROR_PKCS12_NOSMARTCARD_EXPORT;
        continue;
      }
    }

    // certSafe and keySafe are owned by ecx.
    SEC_PKCS12SafeInfo* certSafe;
    SEC_PKCS12SafeInfo* keySafe = SEC_PKCS12CreateUnencryptedSafe(ecx.get());
    if (!SEC_PKCS12IsEncryptionAllowed() || PK11_IsFIPS()) {
      certSafe = keySafe;
    } else {
      certSafe = SEC_PKCS12CreatePasswordPrivSafe(
        ecx.get(), &unicodePw,
        SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC);
    }
    if (!certSafe || !keySafe) {
      aError = nsIX509CertDB::ERROR_PKCS12_BACKUP_FAILED;
      return NS_OK;
    }
    // add the cert and key to the blob
    srv = SEC_PKCS12AddCertAndKey(
      ecx.get(),
      certSafe,
      nullptr,
      nssCert.get(),
      CERT_GetDefaultCertDB(),
      keySafe,
      nullptr,
      true,
      &unicodePw,
      SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC);
    if (srv != SECSuccess) {
      aError = nsIX509CertDB::ERROR_PKCS12_BACKUP_FAILED;
      return NS_OK;
    }
  }

  UniquePRFileDesc prFile;
  PRFileDesc* rawPRFile;
  nsresult rv = aFile->OpenNSPRFileDesc(PR_RDWR | PR_CREATE_FILE | PR_TRUNCATE,
                                        0664, &rawPRFile);
  if (NS_FAILED(rv) || !rawPRFile) {
    aError = nsIX509CertDB::ERROR_PKCS12_BACKUP_FAILED;
    return NS_OK;
  }
  prFile.reset(rawPRFile);
  // encode and write
  srv = SEC_PKCS12Encode(ecx.get(), writeExportFile, prFile.get());
  if (srv != SECSuccess) {
    aError = nsIX509CertDB::ERROR_PKCS12_BACKUP_FAILED;
  }
  return NS_OK;
}

// For the NSS PKCS#12 library, must convert PRUnichars (shorts) to a buffer of
// octets. Must handle byte order correctly.
UniquePtr<uint8_t[]>
nsPKCS12Blob::stringToBigEndianBytes(const nsAString& uni, uint32_t& bytesLength)
{
  if (uni.IsVoid()) {
    bytesLength = 0;
    return nullptr;
  }

  uint32_t wideLength = uni.Length() + 1; // +1 for the null terminator.
  bytesLength = wideLength * 2;
  auto buffer = MakeUnique<uint8_t[]>(bytesLength);

  // We have to use a cast here because on Windows, uni.get() returns
  // char16ptr_t instead of char16_t*.
  mozilla::NativeEndian::copyAndSwapToBigEndian(
    buffer.get(), static_cast<const char16_t*>(uni.BeginReading()), wideLength);

  return buffer;
}

// Given a decoder, read bytes from file and input them to the decoder.
nsresult
nsPKCS12Blob::inputToDecoder(UniqueSEC_PKCS12DecoderContext& dcx, nsIFile* file,
                             PRErrorCode& nssError)
{
  nssError = 0;

  nsCOMPtr<nsIInputStream> fileStream;
  nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(fileStream), file);
  if (NS_FAILED(rv)) {
    return rv;
  }

  char buf[PIP_PKCS12_BUFFER_SIZE];
  uint32_t amount;
  while (true) {
    rv = fileStream->Read(buf, PIP_PKCS12_BUFFER_SIZE, &amount);
    if (NS_FAILED(rv)) {
      return rv;
    }
    // feed the file data into the decoder
    SECStatus srv = SEC_PKCS12DecoderUpdate(
      dcx.get(), (unsigned char*)buf, amount);
    if (srv != SECSuccess) {
      nssError = PR_GetError();
      return NS_OK;
    }
    if (amount < PIP_PKCS12_BUFFER_SIZE) {
      break;
    }
  }
  return NS_OK;
}

// What to do when the nickname collides with one already in the db.
SECItem*
nsPKCS12Blob::nicknameCollision(SECItem* oldNick, PRBool* cancel, void* wincx)
{
  *cancel = false;
  int count = 1;
  nsCString nickname;
  nsAutoString nickFromProp;
  nsresult rv = GetPIPNSSBundleString("P12DefaultNickname", nickFromProp);
  if (NS_FAILED(rv)) {
    return nullptr;
  }
  NS_ConvertUTF16toUTF8 nickFromPropC(nickFromProp);
  // The user is trying to import a PKCS#12 file that doesn't have the
  // attribute we use to set the nickname.  So in order to reduce the
  // number of interactions we require with the user, we'll build a nickname
  // for the user.  The nickname isn't prominently displayed in the UI,
  // so it's OK if we generate one on our own here.
  //   XXX If the NSS API were smarter and actually passed a pointer to
  //       the CERTCertificate* we're importing we could actually just
  //       call default_nickname (which is what the issuance code path
  //       does) and come up with a reasonable nickname.  Alas, the NSS
  //       API limits our ability to produce a useful nickname without
  //       bugging the user.  :(
  while (1) {
    // If we've gotten this far, that means there isn't a certificate
    // in the database that has the same subject name as the cert we're
    // trying to import.  So we need to come up with a "nickname" to
    // satisfy the NSS requirement or fail in trying to import.
    // Basically we use a default nickname from a properties file and
    // see if a certificate exists with that nickname.  If there isn't, then
    // create update the count by one and append the string '#1' Or
    // whatever the count currently is, and look for a cert with
    // that nickname.  Keep updating the count until we find a nickname
    // without a corresponding cert.
    //  XXX If a user imports *many* certs without the 'friendly name'
    //      attribute, then this may take a long time.  :(
    nickname = nickFromPropC;
    if (count > 1) {
      nickname.AppendPrintf(" #%d", count);
    }
    UniqueCERTCertificate cert(
      CERT_FindCertByNickname(CERT_GetDefaultCertDB(), nickname.get()));
    if (!cert) {
      break;
    }
    count++;
  }
  UniqueSECItem newNick(SECITEM_AllocItem(nullptr, nullptr,
                                          nickname.Length() + 1));
  if (!newNick) {
    return nullptr;
  }
  memcpy(newNick->data, nickname.get(), nickname.Length());
  newNick->data[nickname.Length()] = 0;

  return newNick.release();
}

// write bytes to the exported PKCS#12 file
void
nsPKCS12Blob::writeExportFile(void* arg, const char* buf, unsigned long len)
{
  PRFileDesc* file = static_cast<PRFileDesc*>(arg);
  MOZ_RELEASE_ASSERT(file);
  PR_Write(file, buf, len);
}

// Translate PRErrorCode to nsIX509CertDB error
uint32_t
nsPKCS12Blob::handlePRErrorCode(PRErrorCode aPrerr)
{
  MOZ_ASSERT(aPrerr != 0);
  uint32_t error = nsIX509CertDB::ERROR_UNKNOWN;
  switch (aPrerr) {
    case SEC_ERROR_PKCS12_CERT_COLLISION:
      error = nsIX509CertDB::ERROR_PKCS12_DUPLICATE_DATA;
      break;
    // INVALID_ARGS is returned on bad password when importing cert
    // exported from firefox or generated by openssl
    case SEC_ERROR_INVALID_ARGS:
    case SEC_ERROR_BAD_PASSWORD:
      error = nsIX509CertDB::ERROR_BAD_PASSWORD;
      break;
    case SEC_ERROR_BAD_DER:
    case SEC_ERROR_PKCS12_CORRUPT_PFX_STRUCTURE:
    case SEC_ERROR_PKCS12_INVALID_MAC:
      error = nsIX509CertDB::ERROR_DECODE_ERROR;
      break;
    case SEC_ERROR_PKCS12_DUPLICATE_DATA:
      error = nsIX509CertDB::ERROR_PKCS12_DUPLICATE_DATA;
      break;
  }
  return error;
}