DecryptStreamNSS.cc 18 KB
Newer Older
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
//========================================================================
//
// DecryptStreamNSS.cc
//
// Copyright 1996-2003 Glyph & Cog, LLC
//
//========================================================================

//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
// Copyright (C) 2008 Julien Rebetez <julien@fhtagn.net>
// Copyright (C) 2008, 2010, 2016-2019 Albert Astals Cid <aacid@kde.org>
// Copyright (C) 2009 Matthias Franz <matthias@ktug.or.kr>
// Copyright (C) 2009 David Benjamin <davidben@mit.edu>
// Copyright (C) 2012 Fabio D'Urso <fabiodurso@hotmail.it>
// Copyright (C) 2013, 2017 Adrian Johnson <ajohnson@redneon.com>
// Copyright (C) 2016 Alok Anand <alok4nand@gmail.com>
// Copyright (C) 2016 Thomas Freitag <Thomas.Freitag@alfa.de>
// Copyright (C) 2018 Adam Reichold <adam.reichold@t-online.de>
// Copyright (C) 2019 Marek Kasik <mkasik@redhat.com>
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================

#include <config.h>

#include <cstdint>
#include <string.h>
#include <nss.h>
#include <prerror.h>
#include <sechash.h>
#include "goo/gmem.h"
#include "goo/grandom.h"
#include "DecryptStreamNSS.h"
#include "NSS.h"
#include "Error.h"

static PK11Context *rc4InitContext(const unsigned char *key, int keyLen);
static unsigned char rc4DecryptByte(PK11Context *context, unsigned char c);

static bool aesReadBlock(Stream  *str, unsigned char *in, bool addPadding);
static PK11Context *aesInitContext(const unsigned char *in, const unsigned char *objKey, int objKeyLength, bool decrypt);
static void aesEncryptBlock(DecryptAESState *s, unsigned char *in);
static void aesDecryptBlock(DecryptAESState *s, unsigned char *in, bool last);

//------------------------------------------------------------------------
// Helper functions for direct decryption/encryption
//------------------------------------------------------------------------

void rc4DecryptArray(const unsigned char *inputArray, const int inputArrayLen,
                     unsigned char       *outputArray,
                     const unsigned char *key, const int keyLen) {
  PK11Context *context;
  int i;

  context = rc4InitContext(key, keyLen);
  for (i = 0; i < inputArrayLen; ++i) {
    outputArray[i] = rc4DecryptByte(context, inputArray[i]);
  }
}

void aesDecryptArray(const unsigned char *IV,
                     const unsigned char *inputArray, const int inputArrayLen,
                     unsigned char       *outputArray,
                     const unsigned char *key, const int keyLen)
{
  DecryptAESState state;
  int i;

  state.context = aesInitContext(IV, key, keyLen, true);
  if (state.context) {
    for (i = 0; i < inputArrayLen / 16; i++) {
      aesDecryptBlock(&state, (unsigned char *)(inputArray + i * 16), i < inputArrayLen / 16 - 1 ? false : true);
      memcpy(outputArray + i * 16, state.buf, 16);
    }
    PK11_DestroyContext(state.context, PR_TRUE);
  }
}

void aesEncryptArray(const unsigned char *IV,
                     const unsigned char *inputArray, const int inputArrayLen,
                     unsigned char       *outputArray,
                     const unsigned char *key, const int keyLen)
{
  DecryptAESState state;
  int i;

  state.context = aesInitContext(IV, key, keyLen, false);
  if (state.context) {
    for (i = 0; i < inputArrayLen / 16; i++) {
      aesEncryptBlock(&state, (unsigned char *)(inputArray + i * 16));
      memcpy(outputArray + i * 16, state.buf, 16);
    }
    PK11_DestroyContext(state.context, PR_TRUE);
  }
}

//------------------------------------------------------------------------
// EncryptStream
//------------------------------------------------------------------------

EncryptStream::EncryptStream(Stream *strA, const unsigned char *fileKey, CryptAlgorithm algoA,
110 111
                             int keyLength, Ref refA):
  BaseCryptStream(strA, fileKey, algoA, keyLength, refA)
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
{
  // Fill the CBC initialization vector for AES and AES-256
  if (algo == cryptAES || algo == cryptAES256)
    grandom_fill(state.aes.cbc, 16);

  switch (algo) {
    case cryptRC4:
      state.rc4.context = nullptr;
      break;
    case cryptAES:
    case cryptAES256:
      state.aes.context = nullptr;
      break;
    case cryptNone:
      break;
  }

  setNSSDir({});
}

EncryptStream::~EncryptStream() {
  switch (algo) {
    case cryptRC4:
      if (state.rc4.context)
        PK11_DestroyContext(state.rc4.context, PR_TRUE);
      break;
    case cryptAES:
    case cryptAES256:
      if (state.aes.context)
        PK11_DestroyContext(state.aes.context, PR_TRUE);
      break;
    default:
      break;
  }
}

void EncryptStream::reset() {
  BaseCryptStream::reset();

  switch (algo) {
  case cryptRC4:
    if (state.rc4.context)
      PK11_DestroyContext(state.rc4.context, PR_TRUE);
    state.rc4.context = rc4InitContext(objKey, objKeyLength);
    break;
  case cryptAES:
  case cryptAES256:
    memcpy(state.aes.buf, state.aes.cbc, 16); // Copy CBC IV to buf
    if (state.aes.context)
      PK11_DestroyContext(state.aes.context, PR_TRUE);
    state.aes.context = aesInitContext(state.aes.cbc, objKey, objKeyLength,
                                       false);
    state.aes.bufIdx = 0;
    state.aes.paddingReached = false;
    break;
  case cryptNone:
    break;
  }
}

int EncryptStream::lookChar() {
  unsigned char in[16];
  int c;

  if (nextCharBuff != EOF)
    return nextCharBuff;

  c = EOF; // make gcc happy
  switch (algo) {
  case cryptRC4:
    if ((c = str->getChar()) != EOF) {
      // RC4 is XOR-based: the decryption algorithm works for encryption too
      c = rc4DecryptByte(state.rc4.context, (unsigned char)c);
    }
    break;
  case cryptAES:
  case cryptAES256:
    if (state.aes.bufIdx == 16 && !state.aes.paddingReached) {
      state.aes.paddingReached = !aesReadBlock(str, in, true);
      aesEncryptBlock(&state.aes, in);
    }
    if (state.aes.bufIdx == 16) {
      c = EOF;
    } else {
      c = state.aes.buf[state.aes.bufIdx++];
    }
    break;
  case cryptNone:
    break;
  }
  return (nextCharBuff = c);
}

//------------------------------------------------------------------------
// DecryptStream
//------------------------------------------------------------------------

DecryptStream::DecryptStream(Stream *strA, const unsigned char *fileKey, CryptAlgorithm algoA,
210 211
                             int keyLength, Ref refA):
  BaseCryptStream(strA, fileKey, algoA, keyLength, refA)
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
{
  switch (algo) {
    case cryptRC4:
      state.rc4.context = nullptr;
      break;
    case cryptAES:
    case cryptAES256:
      state.aes.context = nullptr;
      break;
    case cryptNone:
      break;
  }

  setNSSDir({});
}

DecryptStream::~DecryptStream() {
  switch (algo) {
    case cryptRC4:
      if (state.rc4.context)
        PK11_DestroyContext(state.rc4.context, PR_TRUE);
      break;
    case cryptAES:
    case cryptAES256:
      if (state.aes.context)
        PK11_DestroyContext(state.aes.context, PR_TRUE);
      break;
    default:
      break;
  }
}

void DecryptStream::reset() {
  int i;

  BaseCryptStream::reset();

  switch (algo) {
  case cryptRC4:
    if (state.rc4.context)
      PK11_DestroyContext(state.rc4.context, PR_TRUE);
    state.rc4.context = rc4InitContext(objKey, objKeyLength);
    break;
  case cryptAES:
  case cryptAES256:
    if (state.aes.context)
      PK11_DestroyContext(state.aes.context, PR_TRUE);
    for (i = 0; i < 16; ++i) {
      state.aes.cbc[i] = str->getChar();
    }
    state.aes.context = aesInitContext(state.aes.cbc, objKey, objKeyLength,
                                       true);
    state.aes.bufIdx = 16;
    break;
  case cryptNone:
    break;
  }
}

int DecryptStream::lookChar() {
  unsigned char in[16];
  int c;

  if (nextCharBuff != EOF)
    return nextCharBuff;

  c = EOF; // make gcc happy
  switch (algo) {
  case cryptRC4:
    if ((c = str->getChar()) != EOF) {
      if (unlikely(state.rc4.context == nullptr))
        c = EOF;
      else
        c = rc4DecryptByte(state.rc4.context, (unsigned char)c);
    }
    break;
  case cryptAES:
  case cryptAES256:
    if (unlikely(state.aes.context == nullptr))
      break;
    if (state.aes.bufIdx == 16) {
      if (aesReadBlock(str, in, false)) {
        aesDecryptBlock(&state.aes, in, str->lookChar() == EOF);
      }
    }
    if (state.aes.bufIdx == 16) {
      c = EOF;
    } else {
      c = state.aes.buf[state.aes.bufIdx++];
    }
    break;
  case cryptNone:
    break;
  }
  return (nextCharBuff = c);
}

//------------------------------------------------------------------------
// RC4-compatible decryption
//------------------------------------------------------------------------

/*
 * This function turns given key into token key (compared to a session key
 * which is prohibited in FIPS mode).
 */
static PK11SymKey *tokenizeKey(const unsigned char *key, int keyLen,
                               CK_ATTRIBUTE_TYPE operation) {
  CK_MECHANISM_TYPE  cipherMech = CKM_AES_CBC_PAD;
  PK11SlotInfo      *slot;
  PK11SymKey        *wrappingKey = nullptr;
  PK11SymKey        *symKey = nullptr;
  PK11SymKey        *token = nullptr;
  SECStatus          retval;
  SECItem           *secParam = nullptr;
  SECItem            ivItem, wrappedKey;
  unsigned char      output[48];   // Buffer to hold 256 bit key + padding
  unsigned char      iv[16];       // Initialization vector for AES
  unsigned int       outputLength;
  int                i;

  slot = PK11_GetBestSlot(CKM_AES_KEY_GEN, nullptr);
  if (slot == nullptr) {
    error(errInternal, -1, "Unable to find security device (err {0:d})",
          PR_GetError());
    goto err;
  }

  // Generate random key for wrapping of given key by AES-256
  wrappingKey = PK11_KeyGen(slot, CKM_AES_KEY_GEN, nullptr, 32, nullptr);
  if (wrappingKey == nullptr) {
    error(errInternal, -1, "Failed to generate wrapping key (err {0:d})",
          PR_GetError());
    goto err;
  }

  for (i = 0; i < 16; i++)
    iv[i] = i;

  ivItem.type = siBuffer;
  ivItem.data = iv;
  ivItem.len = 16;

  secParam = PK11_ParamFromIV(cipherMech, &ivItem);
  if (secParam == nullptr) {
    error(errInternal, -1, "Failed to set up PKCS11 param (err {0:d})",
          PR_GetError());
    goto err;
  }

  // Encrypt given key
  retval = PK11_Encrypt(wrappingKey,
                        cipherMech,
                        secParam,
                        output,
                        &outputLength,
                        sizeof(output),
                        key,
                        keyLen);
  if (retval != SECSuccess) {
    error(errInternal, -1, "Failed to encrypt key (err {0:d})",
          PR_GetError());
  }

  wrappedKey.type = siBuffer;
  wrappedKey.data = output;
  wrappedKey.len = outputLength;

  // Unwrap the wrapped key to token so it can be used in FIPS mode
  token = PK11_UnwrapSymKey(wrappingKey,
                            cipherMech,
                            &ivItem,
                            &wrappedKey,
                            operation,
                            CKA_UNWRAP,
                            keyLen);

  if (token == nullptr) {
    error(errInternal, -1, "Failed to unwrap symmetric key (err {0:d})",
          PR_GetError());
  }

err:
  if (secParam != nullptr)
    SECITEM_FreeItem(secParam, PR_TRUE);

  if (wrappingKey != nullptr)
    PK11_FreeSymKey(wrappingKey);

  if (symKey != nullptr)
    PK11_FreeSymKey(symKey);

  if (slot != nullptr)
    PK11_FreeSlot(slot);

  return token;
}

static PK11Context *rc4InitContext(const unsigned char *key, int keyLen) {
  CK_MECHANISM_TYPE  cipherMech = CKM_RC4;
  PK11SlotInfo      *slot = nullptr;
  PK11Context       *context = nullptr;
  PK11SymKey        *symKey = nullptr;
  SECItem           *secParam = nullptr;

  slot = PK11_GetBestSlot(cipherMech, nullptr);
  if (slot == nullptr) {
    error(errInternal, -1, "Unable to find security device (err {0:d})",
          PR_GetError());
    goto err;
  }

  symKey = tokenizeKey(key, keyLen, cipherMech);
  if (symKey == nullptr) {
    error(errInternal, -1, "Failed to create token from key (err {0:d})",
          PR_GetError());
    goto err;
  }

  secParam = PK11_ParamFromIV(cipherMech, nullptr);
  if (secParam == nullptr) {
    error(errInternal, -1, "Failed to set up PKCS11 param (err {0:d})",
          PR_GetError());
    goto err;
  }

  context = PK11_CreateContextBySymKey(cipherMech,
                                       CKA_DECRYPT,
                                       symKey,
                                       secParam);
  if (context == nullptr) {
    error(errInternal, -1, "Failed to create context (err {0:d})",
          PR_GetError());
  }

err:
  if (secParam != nullptr)
    SECITEM_FreeItem(secParam, PR_TRUE);

  if (symKey != nullptr)
    PK11_FreeSymKey(symKey);

  if (slot != nullptr)
    PK11_FreeSlot(slot);

  return context;
}

static unsigned char rc4DecryptByte(PK11Context *context, unsigned char c) {
  unsigned char outputChar = 0;
  SECStatus     retval;
  int           outputLength;

  retval = PK11_CipherOp(context,
                         &outputChar,
                         &outputLength,
                         1,
                         &c,
                         1);

  if (retval != SECSuccess) {
    error(errInternal, -1, "Failed to decrypt byte (err {0:d})",
          PR_GetError());
  }

  return outputChar;
}

//------------------------------------------------------------------------
// AES decryption
//------------------------------------------------------------------------

// Returns false if EOF was reached, true otherwise
static bool aesReadBlock(Stream *str, unsigned char *in, bool addPadding)
{
  int c, i;

  for (i = 0; i < 16; ++i) {
    if ((c = str->getChar()) != EOF) {
      in[i] = (unsigned char)c;
    } else {
      break;
    }
  }

  if (i == 16) {
    return true;
  } else {
    if (addPadding) {
      c = 16 - i;
      while (i < 16) {
        in[i++] = (unsigned char)c;
      }
    }
    return false;
  }
}

static PK11Context *aesInitContext(const unsigned char *in, const unsigned char *objKey,
                                   int objKeyLength, bool decrypt) {
  CK_MECHANISM_TYPE  cipherMech = CKM_AES_CBC;
  CK_ATTRIBUTE_TYPE  operationType = decrypt ? CKA_DECRYPT : CKA_ENCRYPT;
  PK11SlotInfo      *slot;
  PK11Context       *context = nullptr;
  PK11SymKey        *symKey = nullptr;
  SECItem           *secParam = nullptr;
  SECItem            ivItem;

  slot = PK11_GetBestSlot(cipherMech, nullptr);
  if (slot == nullptr) {
    error(errInternal, -1, "Unable to find security device (err {0:d})",
          PR_GetError());
    goto err;
  }

  symKey = tokenizeKey(objKey, objKeyLength, cipherMech);
  if (symKey == nullptr) {
    error(errInternal, -1, "Failed to create token from key (err {0:d})",
          PR_GetError());
    goto err;
  }

  ivItem.type = siBuffer;
  ivItem.data = (unsigned char *)in;
  ivItem.len = 16;

  secParam = PK11_ParamFromIV(cipherMech, &ivItem);
  if (secParam == nullptr) {
    error(errInternal, -1, "Failed to set up PKCS11 param (err {0:d})",
          PR_GetError());
    goto err;
  }

  context = PK11_CreateContextBySymKey(cipherMech,
                                       operationType,
                                       symKey,
                                       secParam);

err:
  if (secParam != nullptr)
    SECITEM_FreeItem(secParam, PR_TRUE);

  if (symKey != nullptr)
    PK11_FreeSymKey(symKey);

  if (slot != nullptr)
    PK11_FreeSlot(slot);

  return context;
}

static void aesEncryptBlock(DecryptAESState *s, unsigned char *in) {
  SECStatus rv;
  int       outputLength;

  rv = PK11_CipherOp(s->context,
                     s->buf,
                     &outputLength,
                     16,
                     in,
                     16);

  if (rv != SECSuccess) {
    error(errInternal, -1, "Failed to encrypt input block (err {0:d})",
          PR_GetError());
    return;
  }

  s->bufIdx = 0;
}

static void aesDecryptBlock(DecryptAESState *s, unsigned char *in, bool last) {
  SECStatus rv;
  int       outputLen;
  int       n, i;

  rv = PK11_CipherOp(s->context,
                     s->buf,
                     &outputLen,
                     16,
                     in,
                     16);

  if (rv != SECSuccess) {
    error(errInternal, -1, "Failed to decrypt input block (err {0:d})",
          PR_GetError());
    return;
  }

  s->bufIdx = 0;
  if (last) {
    n = s->buf[15];
    if (n < 1 || n > 16) // this should never happen
      n = 16;
    for (i = 15; i >= n; --i)
      s->buf[i] = s->buf[i-n];
    s->bufIdx = n;
  }
}

//------------------------------------------------------------------------
// Hash helper function
//------------------------------------------------------------------------

static void hashFunc(const unsigned char *msg, int msgLen, unsigned char *hash,
                     HASH_HashType type) {
  HASHContext *context;
  unsigned int hashLen = 0;

  setNSSDir({});

  context = HASH_Create(type);
  if (context == nullptr)
    return;

  HASH_Begin(context);
  HASH_Update(context, msg, msgLen);
  HASH_End(context, hash, &hashLen, HASH_ResultLen(type));
  HASH_Destroy(context);
}

//------------------------------------------------------------------------
// MD5 message digest
//------------------------------------------------------------------------

void md5(const unsigned char *msg, int msgLen, unsigned char *digest) {
  hashFunc(msg, msgLen, digest, HASH_AlgMD5);
}

//------------------------------------------------------------------------
// SHA-nnn hash
//------------------------------------------------------------------------

void sha256(unsigned char *msg, int msgLen, unsigned char *hash) {
  hashFunc(msg, msgLen, hash, HASH_AlgSHA256);
}

void sha384(unsigned char *msg, int msgLen, unsigned char *hash) {
  hashFunc(msg, msgLen, hash, HASH_AlgSHA384);
}

void sha512(unsigned char *msg, int msgLen, unsigned char *hash) {
  hashFunc(msg, msgLen, hash, HASH_AlgSHA512);
}