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 (c291143e2401)

VCS Links

SDRResult

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 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
/* 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 "seccomon.h"
#include "secoid.h"
#include "secasn1.h"
#include "pkcs11.h"
#include "pk11func.h"
#include "pk11sdr.h"

/*
 * Data structure and template for encoding the result of an SDR operation
 *  This is temporary.  It should include the algorithm ID of the encryption mechanism
 */
struct SDRResult {
    SECItem keyid;
    SECAlgorithmID alg;
    SECItem data;
};
typedef struct SDRResult SDRResult;

SEC_ASN1_MKSUB(SECOID_AlgorithmIDTemplate)

static SEC_ASN1Template template[] = {
    { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(SDRResult) },
    { SEC_ASN1_OCTET_STRING, offsetof(SDRResult, keyid) },
    { SEC_ASN1_INLINE | SEC_ASN1_XTRN, offsetof(SDRResult, alg),
      SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
    { SEC_ASN1_OCTET_STRING, offsetof(SDRResult, data) },
    { 0 }
};

static unsigned char keyID[] = {
    0xF8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01
};

static SECItem keyIDItem = {
    0,
    keyID,
    sizeof keyID
};

/* local utility function for padding an incoming data block
 * to the mechanism block size.
 */
static SECStatus
padBlock(SECItem *data, int blockSize, SECItem *result)
{
    SECStatus rv = SECSuccess;
    int padLength;
    unsigned int i;

    result->data = 0;
    result->len = 0;

    /* This algorithm always adds to the block (to indicate the number
   * of pad bytes).  So allocate a block large enough.
   */
    padLength = blockSize - (data->len % blockSize);
    result->len = data->len + padLength;
    result->data = (unsigned char *)PORT_Alloc(result->len);

    /* Copy the data */
    PORT_Memcpy(result->data, data->data, data->len);

    /* Add the pad values */
    for (i = data->len; i < result->len; i++)
        result->data[i] = (unsigned char)padLength;

    return rv;
}

static SECStatus
unpadBlock(SECItem *data, int blockSize, SECItem *result)
{
    SECStatus rv = SECSuccess;
    int padLength;
    unsigned int i;

    result->data = 0;
    result->len = 0;

    /* Remove the padding from the end if the input data */
    if (data->len == 0 || data->len % blockSize != 0) {
        rv = SECFailure;
        goto loser;
    }

    padLength = data->data[data->len - 1];
    if (padLength > blockSize) {
        rv = SECFailure;
        goto loser;
    }

    /* verify padding */
    for (i = data->len - padLength; i < data->len; i++) {
        if (data->data[i] != padLength) {
            rv = SECFailure;
            goto loser;
        }
    }

    result->len = data->len - padLength;
    result->data = (unsigned char *)PORT_Alloc(result->len);
    if (!result->data) {
        rv = SECFailure;
        goto loser;
    }

    PORT_Memcpy(result->data, data->data, result->len);

    if (padLength < 2) {
        return SECWouldBlock;
    }

loser:
    return rv;
}

static PRLock *pk11sdrLock = NULL;

void
pk11sdr_Init(void)
{
    pk11sdrLock = PR_NewLock();
}

void
pk11sdr_Shutdown(void)
{
    if (pk11sdrLock) {
        PR_DestroyLock(pk11sdrLock);
        pk11sdrLock = NULL;
    }
}

/*
 * PK11SDR_Encrypt
 *  Encrypt a block of data using the symmetric key identified.  The result
 *  is an ASN.1 (DER) encoded block of keyid, params and data.
 */
SECStatus
PK11SDR_Encrypt(SECItem *keyid, SECItem *data, SECItem *result, void *cx)
{
    SECStatus rv = SECSuccess;
    PK11SlotInfo *slot = 0;
    PK11SymKey *key = 0;
    SECItem *params = 0;
    PK11Context *ctx = 0;
    CK_MECHANISM_TYPE type;
    SDRResult sdrResult;
    SECItem paddedData;
    SECItem *pKeyID;
    PLArenaPool *arena = 0;

    /* Initialize */
    paddedData.len = 0;
    paddedData.data = 0;

    arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
    if (!arena) {
        rv = SECFailure;
        goto loser;
    }

    /* 1. Locate the requested keyid, or the default key (which has a keyid)
     * 2. Create an encryption context
     * 3. Encrypt
     * 4. Encode the results (using ASN.1)
     */

    slot = PK11_GetInternalKeySlot();
    if (!slot) {
        rv = SECFailure;
        goto loser;
    }

    /* Use triple-DES */
    type = CKM_DES3_CBC;

    /*
     * Login to the internal token before we look for the key, otherwise we
     * won't find it.
     */
    rv = PK11_Authenticate(slot, PR_TRUE, cx);
    if (rv != SECSuccess)
        goto loser;

    /* Find the key to use */
    pKeyID = keyid;
    if (pKeyID->len == 0) {
        pKeyID = &keyIDItem; /* Use default value */

        /* put in a course lock to prevent a race between not finding the
         * key and creating  one.
         */

        if (pk11sdrLock)
            PR_Lock(pk11sdrLock);

        /* Try to find the key */
        key = PK11_FindFixedKey(slot, type, pKeyID, cx);

        /* If the default key doesn't exist yet, try to create it */
        if (!key)
            key = PK11_GenDES3TokenKey(slot, pKeyID, cx);
        if (pk11sdrLock)
            PR_Unlock(pk11sdrLock);
    } else {
        key = PK11_FindFixedKey(slot, type, pKeyID, cx);
    }

    if (!key) {
        rv = SECFailure;
        goto loser;
    }

    params = PK11_GenerateNewParam(type, key);
    if (!params) {
        rv = SECFailure;
        goto loser;
    }

    ctx = PK11_CreateContextBySymKey(type, CKA_ENCRYPT, key, params);
    if (!ctx) {
        rv = SECFailure;
        goto loser;
    }

    rv = padBlock(data, PK11_GetBlockSize(type, 0), &paddedData);
    if (rv != SECSuccess)
        goto loser;

    sdrResult.data.len = paddedData.len;
    sdrResult.data.data = (unsigned char *)PORT_ArenaAlloc(arena, sdrResult.data.len);

    rv = PK11_CipherOp(ctx, sdrResult.data.data, (int *)&sdrResult.data.len, sdrResult.data.len,
                       paddedData.data, paddedData.len);
    if (rv != SECSuccess)
        goto loser;

    PK11_Finalize(ctx);

    sdrResult.keyid = *pKeyID;

    rv = PK11_ParamToAlgid(SEC_OID_DES_EDE3_CBC, params, arena, &sdrResult.alg);
    if (rv != SECSuccess)
        goto loser;

    if (!SEC_ASN1EncodeItem(0, result, &sdrResult, template)) {
        rv = SECFailure;
        goto loser;
    }

loser:
    SECITEM_ZfreeItem(&paddedData, PR_FALSE);
    if (arena)
        PORT_FreeArena(arena, PR_TRUE);
    if (ctx)
        PK11_DestroyContext(ctx, PR_TRUE);
    if (params)
        SECITEM_ZfreeItem(params, PR_TRUE);
    if (key)
        PK11_FreeSymKey(key);
    if (slot)
        PK11_FreeSlot(slot);

    return rv;
}

/* decrypt a block */
static SECStatus
pk11Decrypt(PK11SlotInfo *slot, PLArenaPool *arena,
            CK_MECHANISM_TYPE type, PK11SymKey *key,
            SECItem *params, SECItem *in, SECItem *result)
{
    PK11Context *ctx = 0;
    SECItem paddedResult;
    SECStatus rv;

    paddedResult.len = 0;
    paddedResult.data = 0;

    ctx = PK11_CreateContextBySymKey(type, CKA_DECRYPT, key, params);
    if (!ctx) {
        rv = SECFailure;
        goto loser;
    }

    paddedResult.len = in->len;
    paddedResult.data = PORT_ArenaAlloc(arena, paddedResult.len);

    rv = PK11_CipherOp(ctx, paddedResult.data,
                       (int *)&paddedResult.len, paddedResult.len,
                       in->data, in->len);
    if (rv != SECSuccess)
        goto loser;

    PK11_Finalize(ctx);

    /* Remove the padding */
    rv = unpadBlock(&paddedResult, PK11_GetBlockSize(type, 0), result);
    if (rv)
        goto loser;

loser:
    if (ctx)
        PK11_DestroyContext(ctx, PR_TRUE);
    return rv;
}

/*
 * PK11SDR_Decrypt
 *  Decrypt a block of data produced by PK11SDR_Encrypt.  The key used is identified
 *  by the keyid field within the input.
 */
SECStatus
PK11SDR_Decrypt(SECItem *data, SECItem *result, void *cx)
{
    SECStatus rv = SECSuccess;
    PK11SlotInfo *slot = 0;
    PK11SymKey *key = 0;
    CK_MECHANISM_TYPE type;
    SDRResult sdrResult;
    SECItem *params = 0;
    SECItem possibleResult = { 0, NULL, 0 };
    PLArenaPool *arena = 0;

    arena = PORT_NewArena(SEC_ASN1_DEFAULT_ARENA_SIZE);
    if (!arena) {
        rv = SECFailure;
        goto loser;
    }

    /* Decode the incoming data */
    memset(&sdrResult, 0, sizeof sdrResult);
    rv = SEC_QuickDERDecodeItem(arena, &sdrResult, template, data);
    if (rv != SECSuccess)
        goto loser; /* Invalid format */

    /* Find the slot and key for the given keyid */
    slot = PK11_GetInternalKeySlot();
    if (!slot) {
        rv = SECFailure;
        goto loser;
    }

    rv = PK11_Authenticate(slot, PR_TRUE, cx);
    if (rv != SECSuccess)
        goto loser;

    /* Get the parameter values from the data */
    params = PK11_ParamFromAlgid(&sdrResult.alg);
    if (!params) {
        rv = SECFailure;
        goto loser;
    }

    /* Use triple-DES (Should look up the algorithm) */
    type = CKM_DES3_CBC;
    key = PK11_FindFixedKey(slot, type, &sdrResult.keyid, cx);
    if (!key) {
        rv = SECFailure;
    } else {
        rv = pk11Decrypt(slot, arena, type, key, params,
                         &sdrResult.data, result);
    }

    /*
     * if the pad value was too small (1 or 2), then it's statistically
     * 'likely' that (1 in 256) that we may not have the correct key.
     * Check the other keys for a better match. If we find none, use
     * this result.
     */
    if (rv == SECWouldBlock) {
        possibleResult = *result;
    }

    /*
     * handle the case where your key indicies may have been broken
     */
    if (rv != SECSuccess) {
        PK11SymKey *keyList = PK11_ListFixedKeysInSlot(slot, NULL, cx);
        PK11SymKey *testKey = NULL;
        PK11SymKey *nextKey = NULL;

        for (testKey = keyList; testKey;
             testKey = PK11_GetNextSymKey(testKey)) {
            rv = pk11Decrypt(slot, arena, type, testKey, params,
                             &sdrResult.data, result);
            if (rv == SECSuccess) {
                break;
            }
            /* found a close match. If it's our first remember it */
            if (rv == SECWouldBlock) {
                if (possibleResult.data) {
                    /* this is unlikely but possible. If we hit this condition,
                     * we have no way of knowing which possibility to prefer.
                     * in this case we just match the key the application
                     * thought was the right one */
                    SECITEM_ZfreeItem(result, PR_FALSE);
                } else {
                    possibleResult = *result;
                }
            }
        }

        /* free the list */
        for (testKey = keyList; testKey; testKey = nextKey) {
            nextKey = PK11_GetNextSymKey(testKey);
            PK11_FreeSymKey(testKey);
        }
    }

    /* we didn't find a better key, use the one with a small pad value */
    if ((rv != SECSuccess) && (possibleResult.data)) {
        *result = possibleResult;
        possibleResult.data = NULL;
        rv = SECSuccess;
    }

loser:
    if (arena)
        PORT_FreeArena(arena, PR_TRUE);
    if (key)
        PK11_FreeSymKey(key);
    if (params)
        SECITEM_ZfreeItem(params, PR_TRUE);
    if (slot)
        PK11_FreeSlot(slot);
    if (possibleResult.data)
        SECITEM_ZfreeItem(&possibleResult, PR_FALSE);

    return rv;
}