msg.c 119 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/*
 * Copyright 2007 Juan Lang
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
 */
18 19 20 21

#include "config.h"
#include "wine/port.h"

22
#include <stdarg.h>
23
#define NONAMELESSUNION
24 25 26
#include "windef.h"
#include "winbase.h"
#include "wincrypt.h"
27
#include "snmp.h"
28 29

#include "wine/debug.h"
30 31
#include "wine/exception.h"
#include "crypt32_private.h"
32 33 34

WINE_DEFAULT_DEBUG_CHANNEL(crypt);

35 36 37 38 39
/* Called when a message's ref count reaches zero.  Free any message-specific
 * data here.
 */
typedef void (*CryptMsgCloseFunc)(HCRYPTMSG msg);

40 41 42
typedef BOOL (*CryptMsgGetParamFunc)(HCRYPTMSG hCryptMsg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData);

43 44 45
typedef BOOL (*CryptMsgUpdateFunc)(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal);

46 47 48
typedef BOOL (*CryptMsgControlFunc)(HCRYPTMSG hCryptMsg, DWORD dwFlags,
 DWORD dwCtrlType, const void *pvCtrlPara);

49
static BOOL CRYPT_DefaultMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
50 51 52 53 54 55 56
 DWORD dwCtrlType, const void *pvCtrlPara)
{
    TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
    SetLastError(E_INVALIDARG);
    return FALSE;
}

57 58
typedef enum _CryptMsgState {
    MsgStateInit,
59
    MsgStateUpdated,
60
    MsgStateDataFinalized,
61 62 63
    MsgStateFinalized
} CryptMsgState;

64 65
typedef struct _CryptMsgBase
{
66 67
    LONG                 ref;
    DWORD                open_flags;
68 69
    BOOL                 streamed;
    CMSG_STREAM_INFO     stream_info;
70
    CryptMsgState        state;
71
    CryptMsgCloseFunc    close;
72
    CryptMsgUpdateFunc   update;
73
    CryptMsgGetParamFunc get_param;
74
    CryptMsgControlFunc  control;
75 76
} CryptMsgBase;

77
static inline void CryptMsgBase_Init(CryptMsgBase *msg, DWORD dwFlags,
78
 PCMSG_STREAM_INFO pStreamInfo, CryptMsgCloseFunc close,
79 80
 CryptMsgGetParamFunc get_param, CryptMsgUpdateFunc update,
 CryptMsgControlFunc control)
81 82 83
{
    msg->ref = 1;
    msg->open_flags = dwFlags;
84 85 86
    if (pStreamInfo)
    {
        msg->streamed = TRUE;
87
        msg->stream_info = *pStreamInfo;
88 89 90 91 92 93
    }
    else
    {
        msg->streamed = FALSE;
        memset(&msg->stream_info, 0, sizeof(msg->stream_info));
    }
94 95 96
    msg->close = close;
    msg->get_param = get_param;
    msg->update = update;
97
    msg->control = control;
98
    msg->state = MsgStateInit;
99 100
}

101 102 103
typedef struct _CDataEncodeMsg
{
    CryptMsgBase base;
104 105
    DWORD        bare_content_len;
    LPBYTE       bare_content;
106 107
} CDataEncodeMsg;

108 109 110 111
static const BYTE empty_data_content[] = { 0x04,0x00 };

static void CDataEncodeMsg_Close(HCRYPTMSG hCryptMsg)
{
112
    CDataEncodeMsg *msg = hCryptMsg;
113 114 115 116 117

    if (msg->bare_content != empty_data_content)
        LocalFree(msg->bare_content);
}

118
static BOOL WINAPI CRYPT_EncodeContentLength(DWORD dwCertEncodingType,
119 120 121
 LPCSTR lpszStructType, const void *pvStructInfo, DWORD dwFlags,
 PCRYPT_ENCODE_PARA pEncodePara, BYTE *pbEncoded, DWORD *pcbEncoded)
{
122
    DWORD dataLen = *(DWORD *)pvStructInfo;
123 124 125 126 127 128 129
    DWORD lenBytes;
    BOOL ret = TRUE;

    /* Trick:  report bytes needed based on total message length, even though
     * the message isn't available yet.  The caller will use the length
     * reported here to encode its length.
     */
130
    CRYPT_EncodeLen(dataLen, NULL, &lenBytes);
131
    if (!pbEncoded)
132
        *pcbEncoded = 1 + lenBytes + dataLen;
133 134 135 136 137 138 139 140
    else
    {
        if ((ret = CRYPT_EncodeEnsureSpace(dwFlags, pEncodePara, pbEncoded,
         pcbEncoded, 1 + lenBytes)))
        {
            if (dwFlags & CRYPT_ENCODE_ALLOC_FLAG)
                pbEncoded = *(BYTE **)pbEncoded;
            *pbEncoded++ = ASN_OCTETSTRING;
141
            CRYPT_EncodeLen(dataLen, pbEncoded,
142 143 144 145 146 147
             &lenBytes);
        }
    }
    return ret;
}

148
static BOOL CRYPT_EncodeDataContentInfoHeader(const CDataEncodeMsg *msg,
149 150 151 152 153 154
 CRYPT_DATA_BLOB *header)
{
    BOOL ret;

    if (msg->base.streamed && msg->base.stream_info.cbContent == 0xffffffff)
    {
155 156 157 158 159 160 161 162 163 164 165 166
        static const BYTE headerValue[] = { 0x30,0x80,0x06,0x09,0x2a,0x86,0x48,
         0x86,0xf7,0x0d,0x01,0x07,0x01,0xa0,0x80,0x24,0x80 };

        header->pbData = LocalAlloc(0, sizeof(headerValue));
        if (header->pbData)
        {
            header->cbData = sizeof(headerValue);
            memcpy(header->pbData, headerValue, sizeof(headerValue));
            ret = TRUE;
        }
        else
            ret = FALSE;
167 168 169
    }
    else
    {
170 171
        struct AsnConstructedItem constructed = { 0,
         &msg->base.stream_info.cbContent, CRYPT_EncodeContentLength };
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
        struct AsnEncodeSequenceItem items[2] = {
         { szOID_RSA_data, CRYPT_AsnEncodeOid, 0 },
         { &constructed,   CRYPT_AsnEncodeConstructed, 0 },
        };

        ret = CRYPT_AsnEncodeSequence(X509_ASN_ENCODING, items,
         sizeof(items) / sizeof(items[0]), CRYPT_ENCODE_ALLOC_FLAG, NULL,
         (LPBYTE)&header->pbData, &header->cbData);
        if (ret)
        {
            /* Trick:  subtract the content length from the reported length,
             * as the actual content hasn't come yet.
             */
            header->cbData -= msg->base.stream_info.cbContent;
        }
    }
    return ret;
}

191 192 193
static BOOL CDataEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal)
{
194
    CDataEncodeMsg *msg = hCryptMsg;
195 196
    BOOL ret = FALSE;

197 198 199
    if (msg->base.state == MsgStateFinalized)
        SetLastError(CRYPT_E_MSG_ERROR);
    else if (msg->base.streamed)
200
    {
201 202
        __TRY
        {
203
            if (msg->base.state != MsgStateUpdated)
204 205 206 207 208 209 210 211 212 213 214 215
            {
                CRYPT_DATA_BLOB header;

                ret = CRYPT_EncodeDataContentInfoHeader(msg, &header);
                if (ret)
                {
                    ret = msg->base.stream_info.pfnStreamOutput(
                     msg->base.stream_info.pvArg, header.pbData, header.cbData,
                     FALSE);
                    LocalFree(header.pbData);
                }
            }
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
            /* Curiously, every indefinite-length streamed update appears to
             * get its own tag and length, regardless of fFinal.
             */
            if (msg->base.stream_info.cbContent == 0xffffffff)
            {
                BYTE *header;
                DWORD headerLen;

                ret = CRYPT_EncodeContentLength(X509_ASN_ENCODING, NULL,
                 &cbData, CRYPT_ENCODE_ALLOC_FLAG, NULL, (BYTE *)&header,
                 &headerLen);
                if (ret)
                {
                    ret = msg->base.stream_info.pfnStreamOutput(
                     msg->base.stream_info.pvArg, header, headerLen,
                     FALSE);
                    LocalFree(header);
                }
            }
235
            if (!fFinal)
236
            {
237 238 239
                ret = msg->base.stream_info.pfnStreamOutput(
                 msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
                 FALSE);
240 241
                msg->base.state = MsgStateUpdated;
            }
242 243
            else
            {
244
                msg->base.state = MsgStateFinalized;
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
                if (msg->base.stream_info.cbContent == 0xffffffff)
                {
                    BYTE indefinite_trailer[6] = { 0 };

                    ret = msg->base.stream_info.pfnStreamOutput(
                     msg->base.stream_info.pvArg, (BYTE *)pbData, cbData,
                     FALSE);
                    if (ret)
                        ret = msg->base.stream_info.pfnStreamOutput(
                         msg->base.stream_info.pvArg, indefinite_trailer,
                         sizeof(indefinite_trailer), TRUE);
                }
                else
                    ret = msg->base.stream_info.pfnStreamOutput(
                     msg->base.stream_info.pvArg, (BYTE *)pbData, cbData, TRUE);
            }
        }
        __EXCEPT_PAGE_FAULT
        {
            SetLastError(STATUS_ACCESS_VIOLATION);
265
            ret = FALSE;
266 267
        }
        __ENDTRY;
268 269 270
    }
    else
    {
271 272 273 274 275 276 277
        if (!fFinal)
        {
            if (msg->base.open_flags & CMSG_DETACHED_FLAG)
                SetLastError(E_INVALIDARG);
            else
                SetLastError(CRYPT_E_MSG_ERROR);
        }
278 279
        else
        {
280
            msg->base.state = MsgStateFinalized;
281 282 283 284 285
            if (!cbData)
                SetLastError(E_INVALIDARG);
            else
            {
                CRYPT_DATA_BLOB blob = { cbData, (LPBYTE)pbData };
286

287 288 289 290 291 292 293
                /* non-streamed data messages don't allow non-final updates,
                 * don't bother checking whether data already exist, they can't.
                 */
                ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
                 &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL, &msg->bare_content,
                 &msg->bare_content_len);
            }
294 295 296 297 298
        }
    }
    return ret;
}

299
static BOOL CRYPT_CopyParam(void *pvData, DWORD *pcbData, const void *src,
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
 DWORD len)
{
    BOOL ret = TRUE;

    if (!pvData)
        *pcbData = len;
    else if (*pcbData < len)
    {
        *pcbData = len;
        SetLastError(ERROR_MORE_DATA);
        ret = FALSE;
    }
    else
    {
        *pcbData = len;
        memcpy(pvData, src, len);
    }
    return ret;
}

320 321 322
static BOOL CDataEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
323
    CDataEncodeMsg *msg = hCryptMsg;
324 325 326 327 328
    BOOL ret = FALSE;

    switch (dwParamType)
    {
    case CMSG_CONTENT_PARAM:
329 330 331 332 333 334 335 336 337 338 339 340 341
        if (msg->base.streamed)
            SetLastError(E_INVALIDARG);
        else
        {
            CRYPT_CONTENT_INFO info;
            char rsa_data[] = "1.2.840.113549.1.7.1";

            info.pszObjId = rsa_data;
            info.Content.cbData = msg->bare_content_len;
            info.Content.pbData = msg->bare_content;
            ret = CryptEncodeObject(X509_ASN_ENCODING, PKCS_CONTENT_INFO, &info,
             pvData, pcbData);
        }
342
        break;
343
    case CMSG_BARE_CONTENT_PARAM:
344 345
        if (msg->base.streamed)
            SetLastError(E_INVALIDARG);
346
        else
347 348
            ret = CRYPT_CopyParam(pvData, pcbData, msg->bare_content,
             msg->bare_content_len);
349
        break;
350 351 352 353 354 355
    default:
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
    }
    return ret;
}

356 357 358 359 360 361 362 363 364 365 366 367 368
static HCRYPTMSG CDataEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
 LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
{
    CDataEncodeMsg *msg;

    if (pvMsgEncodeInfo)
    {
        SetLastError(E_INVALIDARG);
        return NULL;
    }
    msg = CryptMemAlloc(sizeof(CDataEncodeMsg));
    if (msg)
    {
369
        CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
370 371
         CDataEncodeMsg_Close, CDataEncodeMsg_GetParam, CDataEncodeMsg_Update,
         CRYPT_DefaultMsgControl);
372 373
        msg->bare_content_len = sizeof(empty_data_content);
        msg->bare_content = (LPBYTE)empty_data_content;
374
    }
375
    return msg;
376 377
}

378 379
typedef struct _CHashEncodeMsg
{
380 381 382 383
    CryptMsgBase    base;
    HCRYPTPROV      prov;
    HCRYPTHASH      hash;
    CRYPT_DATA_BLOB data;
384 385 386 387
} CHashEncodeMsg;

static void CHashEncodeMsg_Close(HCRYPTMSG hCryptMsg)
{
388
    CHashEncodeMsg *msg = hCryptMsg;
389

390
    CryptMemFree(msg->data.pbData);
391 392 393 394 395
    CryptDestroyHash(msg->hash);
    if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
        CryptReleaseContext(msg->prov, 0);
}

396 397 398 399 400 401 402 403 404 405
static BOOL CRYPT_EncodePKCSDigestedData(CHashEncodeMsg *msg, void *pvData,
 DWORD *pcbData)
{
    BOOL ret;
    ALG_ID algID;
    DWORD size = sizeof(algID);

    ret = CryptGetHashParam(msg->hash, HP_ALGID, (BYTE *)&algID, &size, 0);
    if (ret)
    {
406
        CRYPT_DIGESTED_DATA digestedData = { 0 };
407 408
        char oid_rsa_data[] = szOID_RSA_data;

409 410 411
        digestedData.version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;
        digestedData.DigestAlgorithm.pszObjId = (LPSTR)CertAlgIdToOID(algID);
        /* FIXME: what about digestedData.DigestAlgorithm.Parameters? */
412
        /* Quirk:  OID is only encoded messages if an update has happened */
413
        if (msg->base.state != MsgStateInit)
414
            digestedData.ContentInfo.pszObjId = oid_rsa_data;
415 416 417 418
        if (!(msg->base.open_flags & CMSG_DETACHED_FLAG) && msg->data.cbData)
        {
            ret = CRYPT_AsnEncodeOctets(0, NULL, &msg->data,
             CRYPT_ENCODE_ALLOC_FLAG, NULL,
419 420
             (LPBYTE)&digestedData.ContentInfo.Content.pbData,
             &digestedData.ContentInfo.Content.cbData);
421
        }
422
        if (msg->base.state == MsgStateFinalized)
423 424 425
        {
            size = sizeof(DWORD);
            ret = CryptGetHashParam(msg->hash, HP_HASHSIZE,
426
             (LPBYTE)&digestedData.hash.cbData, &size, 0);
427 428
            if (ret)
            {
429 430 431 432
                digestedData.hash.pbData = CryptMemAlloc(
                 digestedData.hash.cbData);
                ret = CryptGetHashParam(msg->hash, HP_HASHVAL,
                 digestedData.hash.pbData, &digestedData.hash.cbData, 0);
433 434 435
            }
        }
        if (ret)
436 437 438 439
            ret = CRYPT_AsnEncodePKCSDigestedData(&digestedData, pvData,
             pcbData);
        CryptMemFree(digestedData.hash.pbData);
        LocalFree(digestedData.ContentInfo.Content.pbData);
440 441 442 443
    }
    return ret;
}

444 445 446
static BOOL CHashEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
447
    CHashEncodeMsg *msg = hCryptMsg;
448 449 450
    BOOL ret = FALSE;

    TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
451
     pvData, pcbData);
452 453 454

    switch (dwParamType)
    {
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
    case CMSG_BARE_CONTENT_PARAM:
        if (msg->base.streamed)
            SetLastError(E_INVALIDARG);
        else
            ret = CRYPT_EncodePKCSDigestedData(msg, pvData, pcbData);
        break;
    case CMSG_CONTENT_PARAM:
    {
        CRYPT_CONTENT_INFO info;

        ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
         &info.Content.cbData);
        if (ret)
        {
            info.Content.pbData = CryptMemAlloc(info.Content.cbData);
            if (info.Content.pbData)
            {
                ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
                 info.Content.pbData, &info.Content.cbData);
                if (ret)
                {
                    char oid_rsa_hashed[] = szOID_RSA_hashedData;

                    info.pszObjId = oid_rsa_hashed;
                    ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
                     PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
                }
                CryptMemFree(info.Content.pbData);
            }
            else
                ret = FALSE;
        }
        break;
    }
489
    case CMSG_COMPUTED_HASH_PARAM:
490
        ret = CryptGetHashParam(msg->hash, HP_HASHVAL, pvData, pcbData, 0);
491
        break;
492
    case CMSG_VERSION_PARAM:
493
        if (msg->base.state != MsgStateFinalized)
494 495 496
            SetLastError(CRYPT_E_MSG_ERROR);
        else
        {
497 498
            DWORD version = CMSG_HASHED_DATA_PKCS_1_5_VERSION;

499 500 501
            /* Since the data are always encoded as octets, the version is
             * always 0 (see rfc3852, section 7)
             */
502
            ret = CRYPT_CopyParam(pvData, pcbData, &version, sizeof(version));
503 504
        }
        break;
505
    default:
506
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
507 508
    }
    return ret;
509 510 511 512 513
}

static BOOL CHashEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal)
{
514
    CHashEncodeMsg *msg = hCryptMsg;
515 516 517 518
    BOOL ret = FALSE;

    TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);

519 520 521
    if (msg->base.state == MsgStateFinalized)
        SetLastError(CRYPT_E_MSG_ERROR);
    else if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
522 523 524 525 526
    {
        /* Doesn't do much, as stream output is never called, and you
         * can't get the content.
         */
        ret = CryptHashData(msg->hash, pbData, cbData, 0);
527
        msg->base.state = fFinal ? MsgStateFinalized : MsgStateUpdated;
528
    }
529 530
    else
    {
531 532
        if (!fFinal)
            SetLastError(CRYPT_E_MSG_ERROR);
533 534
        else
        {
535 536
            ret = CryptHashData(msg->hash, pbData, cbData, 0);
            if (ret)
537
            {
538 539
                msg->data.pbData = CryptMemAlloc(cbData);
                if (msg->data.pbData)
540
                {
541 542
                    memcpy(msg->data.pbData + msg->data.cbData, pbData, cbData);
                    msg->data.cbData += cbData;
543
                }
544 545
                else
                    ret = FALSE;
546
            }
547
            msg->base.state = MsgStateFinalized;
548 549 550
        }
    }
    return ret;
551 552 553 554 555 556
}

static HCRYPTMSG CHashEncodeMsg_Open(DWORD dwFlags, const void *pvMsgEncodeInfo,
 LPSTR pszInnerContentObjID, PCMSG_STREAM_INFO pStreamInfo)
{
    CHashEncodeMsg *msg;
557
    const CMSG_HASHED_ENCODE_INFO *info = pvMsgEncodeInfo;
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
    HCRYPTPROV prov;
    ALG_ID algID;

    if (info->cbSize != sizeof(CMSG_HASHED_ENCODE_INFO))
    {
        SetLastError(E_INVALIDARG);
        return NULL;
    }
    if (!(algID = CertOIDToAlgId(info->HashAlgorithm.pszObjId)))
    {
        SetLastError(CRYPT_E_UNKNOWN_ALGO);
        return NULL;
    }
    if (info->hCryptProv)
        prov = info->hCryptProv;
    else
    {
        prov = CRYPT_GetDefaultProvider();
        dwFlags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
    }
    msg = CryptMemAlloc(sizeof(CHashEncodeMsg));
    if (msg)
    {
        CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
582 583
         CHashEncodeMsg_Close, CHashEncodeMsg_GetParam, CHashEncodeMsg_Update,
         CRYPT_DefaultMsgControl);
584
        msg->prov = prov;
585 586
        msg->data.cbData = 0;
        msg->data.pbData = NULL;
587 588 589 590 591 592
        if (!CryptCreateHash(prov, algID, 0, 0, &msg->hash))
        {
            CryptMsgClose(msg);
            msg = NULL;
        }
    }
593
    return msg;
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
typedef struct _CMSG_SIGNER_ENCODE_INFO_WITH_CMS
{
    DWORD                      cbSize;
    PCERT_INFO                 pCertInfo;
    HCRYPTPROV                 hCryptProv;
    DWORD                      dwKeySpec;
    CRYPT_ALGORITHM_IDENTIFIER HashAlgorithm;
    void                      *pvHashAuxInfo;
    DWORD                      cAuthAttr;
    PCRYPT_ATTRIBUTE           rgAuthAttr;
    DWORD                      cUnauthAttr;
    PCRYPT_ATTRIBUTE           rgUnauthAttr;
    CERT_ID                    SignerId;
    CRYPT_ALGORITHM_IDENTIFIER HashEncryptionAlgorithm;
    void                      *pvHashEncryptionAuxInfo;
} CMSG_SIGNER_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNER_ENCODE_INFO_WITH_CMS;

typedef struct _CMSG_SIGNED_ENCODE_INFO_WITH_CMS
{
    DWORD                             cbSize;
    DWORD                             cSigners;
    PCMSG_SIGNER_ENCODE_INFO_WITH_CMS rgSigners;
    DWORD                             cCertEncoded;
    PCERT_BLOB                        rgCertEncoded;
    DWORD                             cCrlEncoded;
    PCRL_BLOB                         rgCrlEncoded;
    DWORD                             cAttrCertEncoded;
    PCERT_BLOB                        rgAttrCertEncoded;
} CMSG_SIGNED_ENCODE_INFO_WITH_CMS, *PCMSG_SIGNED_ENCODE_INFO_WITH_CMS;

626
static BOOL CRYPT_IsValidSigner(const CMSG_SIGNER_ENCODE_INFO_WITH_CMS *signer)
627
{
628 629 630 631 632 633
    if (signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO) &&
     signer->cbSize != sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
    {
        SetLastError(E_INVALIDARG);
        return FALSE;
    }
634
    if (signer->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO))
635
    {
636 637 638 639 640 641 642 643 644 645
        if (!signer->pCertInfo->SerialNumber.cbData)
        {
            SetLastError(E_INVALIDARG);
            return FALSE;
        }
        if (!signer->pCertInfo->Issuer.cbData)
        {
            SetLastError(E_INVALIDARG);
            return FALSE;
        }
646
    }
647
    else if (signer->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS))
648
    {
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
        switch (signer->SignerId.dwIdChoice)
        {
        case 0:
            if (!signer->pCertInfo->SerialNumber.cbData)
            {
                SetLastError(E_INVALIDARG);
                return FALSE;
            }
            if (!signer->pCertInfo->Issuer.cbData)
            {
                SetLastError(E_INVALIDARG);
                return FALSE;
            }
            break;
        case CERT_ID_ISSUER_SERIAL_NUMBER:
664
            if (!signer->SignerId.u.IssuerSerialNumber.SerialNumber.cbData)
665 666 667 668
            {
                SetLastError(E_INVALIDARG);
                return FALSE;
            }
669
            if (!signer->SignerId.u.IssuerSerialNumber.Issuer.cbData)
670 671 672 673 674 675
            {
                SetLastError(E_INVALIDARG);
                return FALSE;
            }
            break;
        case CERT_ID_KEY_IDENTIFIER:
676
            if (!signer->SignerId.u.KeyId.cbData)
677 678 679 680 681 682 683 684 685 686 687 688 689
            {
                SetLastError(E_INVALIDARG);
                return FALSE;
            }
            break;
        default:
            SetLastError(E_INVALIDARG);
        }
        if (signer->HashEncryptionAlgorithm.pszObjId)
        {
            FIXME("CMSG_SIGNER_ENCODE_INFO with CMS fields unsupported\n");
            return FALSE;
        }
690 691 692 693 694 695 696 697 698 699 700 701 702 703
    }
    if (!signer->hCryptProv)
    {
        SetLastError(E_INVALIDARG);
        return FALSE;
    }
    if (!CertOIDToAlgId(signer->HashAlgorithm.pszObjId))
    {
        SetLastError(CRYPT_E_UNKNOWN_ALGO);
        return FALSE;
    }
    return TRUE;
}

704
static BOOL CRYPT_ConstructBlob(CRYPT_DATA_BLOB *out, const CRYPT_DATA_BLOB *in)
705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721
{
    BOOL ret = TRUE;

    out->cbData = in->cbData;
    if (out->cbData)
    {
        out->pbData = CryptMemAlloc(out->cbData);
        if (out->pbData)
            memcpy(out->pbData, in->pbData, out->cbData);
        else
            ret = FALSE;
    }
    else
        out->pbData = NULL;
    return ret;
}

722
static BOOL CRYPT_ConstructBlobArray(DWORD *outCBlobs,
723
 PCRYPT_DATA_BLOB *outPBlobs, DWORD cBlobs, const CRYPT_DATA_BLOB *pBlobs)
724 725 726
{
    BOOL ret = TRUE;

727 728
    *outCBlobs = cBlobs;
    if (cBlobs)
729
    {
730 731
        *outPBlobs = CryptMemAlloc(cBlobs * sizeof(CRYPT_DATA_BLOB));
        if (*outPBlobs)
732 733 734
        {
            DWORD i;

735 736 737
            memset(*outPBlobs, 0, cBlobs * sizeof(CRYPT_DATA_BLOB));
            for (i = 0; ret && i < cBlobs; i++)
                ret = CRYPT_ConstructBlob(&(*outPBlobs)[i], &pBlobs[i]);
738 739 740 741 742 743 744
        }
        else
            ret = FALSE;
    }
    return ret;
}

745
static void CRYPT_FreeBlobArray(DWORD cBlobs, PCRYPT_DATA_BLOB blobs)
746 747 748
{
    DWORD i;

749 750 751
    for (i = 0; i < cBlobs; i++)
        CryptMemFree(blobs[i].pbData);
    CryptMemFree(blobs);
752 753
}

754 755
static BOOL CRYPT_ConstructAttribute(CRYPT_ATTRIBUTE *out,
 const CRYPT_ATTRIBUTE *in)
756
{
757 758 759 760 761 762
    BOOL ret;

    out->pszObjId = CryptMemAlloc(strlen(in->pszObjId) + 1);
    if (out->pszObjId)
    {
        strcpy(out->pszObjId, in->pszObjId);
763 764
        ret = CRYPT_ConstructBlobArray(&out->cValue, &out->rgValue,
         in->cValue, in->rgValue);
765 766 767 768
    }
    else
        ret = FALSE;
    return ret;
769 770
}

771
static BOOL CRYPT_ConstructAttributes(CRYPT_ATTRIBUTES *out,
772 773 774 775 776 777 778 779 780 781 782 783 784 785
 const CRYPT_ATTRIBUTES *in)
{
    BOOL ret = TRUE;

    out->cAttr = in->cAttr;
    if (out->cAttr)
    {
        out->rgAttr = CryptMemAlloc(out->cAttr * sizeof(CRYPT_ATTRIBUTE));
        if (out->rgAttr)
        {
            DWORD i;

            memset(out->rgAttr, 0, out->cAttr * sizeof(CRYPT_ATTRIBUTE));
            for (i = 0; ret && i < out->cAttr; i++)
786
                ret = CRYPT_ConstructAttribute(&out->rgAttr[i], &in->rgAttr[i]);
787 788 789 790 791 792 793 794 795
        }
        else
            ret = FALSE;
    }
    else
        out->rgAttr = NULL;
    return ret;
}

796 797 798
/* Constructs a CMSG_CMS_SIGNER_INFO from a CMSG_SIGNER_ENCODE_INFO_WITH_CMS. */
static BOOL CSignerInfo_Construct(CMSG_CMS_SIGNER_INFO *info,
 const CMSG_SIGNER_ENCODE_INFO_WITH_CMS *in)
799 800 801
{
    BOOL ret;

802 803 804
    if (in->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO))
    {
        info->dwVersion = CMSG_SIGNER_INFO_V1;
805
        ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
806 807 808
         &in->pCertInfo->Issuer);
        if (ret)
            ret = CRYPT_ConstructBlob(
809
             &info->SignerId.u.IssuerSerialNumber.SerialNumber,
810 811
             &in->pCertInfo->SerialNumber);
        info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
812 813 814 815 816
        info->HashEncryptionAlgorithm.pszObjId =
         in->pCertInfo->SubjectPublicKeyInfo.Algorithm.pszObjId;
        if (ret)
            ret = CRYPT_ConstructBlob(&info->HashEncryptionAlgorithm.Parameters,
             &in->pCertInfo->SubjectPublicKeyInfo.Algorithm.Parameters);
817 818 819
    }
    else
    {
820 821
        const CRYPT_ALGORITHM_IDENTIFIER *pEncrAlg;

822 823 824 825 826 827
        /* Implicitly in->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS).
         * See CRYPT_IsValidSigner.
         */
        if (!in->SignerId.dwIdChoice)
        {
            info->dwVersion = CMSG_SIGNER_INFO_V1;
828
            ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
829 830 831
             &in->pCertInfo->Issuer);
            if (ret)
                ret = CRYPT_ConstructBlob(
832
                 &info->SignerId.u.IssuerSerialNumber.SerialNumber,
833 834 835 836 837 838 839
                 &in->pCertInfo->SerialNumber);
            info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
        }
        else if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
        {
            info->dwVersion = CMSG_SIGNER_INFO_V1;
            info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
840 841
            ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
             &in->SignerId.u.IssuerSerialNumber.Issuer);
842 843
            if (ret)
                ret = CRYPT_ConstructBlob(
844 845
                 &info->SignerId.u.IssuerSerialNumber.SerialNumber,
                 &in->SignerId.u.IssuerSerialNumber.SerialNumber);
846 847 848 849 850 851
        }
        else
        {
            /* Implicitly dwIdChoice == CERT_ID_KEY_IDENTIFIER */
            info->dwVersion = CMSG_SIGNER_INFO_V3;
            info->SignerId.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
852 853
            ret = CRYPT_ConstructBlob(&info->SignerId.u.KeyId,
             &in->SignerId.u.KeyId);
854
        }
855 856 857 858 859 860 861
        pEncrAlg = in->HashEncryptionAlgorithm.pszObjId ?
         &in->HashEncryptionAlgorithm :
         &in->pCertInfo->SubjectPublicKeyInfo.Algorithm;
        info->HashEncryptionAlgorithm.pszObjId = pEncrAlg->pszObjId;
        if (ret)
            ret = CRYPT_ConstructBlob(&info->HashEncryptionAlgorithm.Parameters,
             &pEncrAlg->Parameters);
862
    }
863 864 865 866 867 868 869 870 871 872 873 874 875
    /* Assumption:  algorithm IDs will point to static strings, not
     * stack-based ones, so copying the pointer values is safe.
     */
    info->HashAlgorithm.pszObjId = in->HashAlgorithm.pszObjId;
    if (ret)
        ret = CRYPT_ConstructBlob(&info->HashAlgorithm.Parameters,
         &in->HashAlgorithm.Parameters);
    if (ret)
        ret = CRYPT_ConstructAttributes(&info->AuthAttrs,
         (CRYPT_ATTRIBUTES *)&in->cAuthAttr);
    if (ret)
        ret = CRYPT_ConstructAttributes(&info->UnauthAttrs,
         (CRYPT_ATTRIBUTES *)&in->cUnauthAttr);
876 877 878
    return ret;
}

879
static void CSignerInfo_Free(CMSG_CMS_SIGNER_INFO *info)
880 881 882
{
    DWORD i, j;

883 884
    if (info->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
    {
885 886
        CryptMemFree(info->SignerId.u.IssuerSerialNumber.Issuer.pbData);
        CryptMemFree(info->SignerId.u.IssuerSerialNumber.SerialNumber.pbData);
887 888
    }
    else
889
        CryptMemFree(info->SignerId.u.KeyId.pbData);
890
    CryptMemFree(info->HashAlgorithm.Parameters.pbData);
891
    CryptMemFree(info->HashEncryptionAlgorithm.Parameters.pbData);
892 893
    CryptMemFree(info->EncryptedHash.pbData);
    for (i = 0; i < info->AuthAttrs.cAttr; i++)
894
    {
895 896 897
        for (j = 0; j < info->AuthAttrs.rgAttr[i].cValue; j++)
            CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue[j].pbData);
        CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue);
898
        CryptMemFree(info->AuthAttrs.rgAttr[i].pszObjId);
899
    }
900 901
    CryptMemFree(info->AuthAttrs.rgAttr);
    for (i = 0; i < info->UnauthAttrs.cAttr; i++)
902
    {
903 904 905
        for (j = 0; j < info->UnauthAttrs.rgAttr[i].cValue; j++)
            CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue[j].pbData);
        CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue);
906
        CryptMemFree(info->UnauthAttrs.rgAttr[i].pszObjId);
907
    }
908
    CryptMemFree(info->UnauthAttrs.rgAttr);
909 910
}

911 912 913 914 915 916
typedef struct _CSignerHandles
{
    HCRYPTHASH contentHash;
    HCRYPTHASH authAttrHash;
} CSignerHandles;

917 918 919
typedef struct _CSignedMsgData
{
    CRYPT_SIGNED_INFO *info;
920
    DWORD              cSignerHandle;
921 922 923
    CSignerHandles    *signerHandles;
} CSignedMsgData;

924 925 926
/* Constructs the signer handles for the signerIndex'th signer of msg_data.
 * Assumes signerIndex is a valid idnex, and that msg_data's info has already
 * been constructed.
927
 */
928 929
static BOOL CSignedMsgData_ConstructSignerHandles(CSignedMsgData *msg_data,
 DWORD signerIndex, HCRYPTPROV crypt_prov)
930 931 932 933
{
    ALG_ID algID;
    BOOL ret;

934 935 936 937 938 939 940
    algID = CertOIDToAlgId(
     msg_data->info->rgSignerInfo[signerIndex].HashAlgorithm.pszObjId);
    ret = CryptCreateHash(crypt_prov, algID, 0, 0,
     &msg_data->signerHandles->contentHash);
    if (ret && msg_data->info->rgSignerInfo[signerIndex].AuthAttrs.cAttr > 0)
        ret = CryptCreateHash(crypt_prov, algID, 0, 0,
         &msg_data->signerHandles->authAttrHash);
941 942 943
    return ret;
}

944 945 946 947 948 949 950 951 952 953 954 955
/* Allocates a CSignedMsgData's handles.  Assumes its info has already been
 * constructed.
 */
static BOOL CSignedMsgData_AllocateHandles(CSignedMsgData *msg_data)
{
    BOOL ret = TRUE;

    if (msg_data->info->cSignerInfo)
    {
        msg_data->signerHandles =
         CryptMemAlloc(msg_data->info->cSignerInfo * sizeof(CSignerHandles));
        if (msg_data->signerHandles)
956 957
        {
            msg_data->cSignerHandle = msg_data->info->cSignerInfo;
958 959
            memset(msg_data->signerHandles, 0,
             msg_data->info->cSignerInfo * sizeof(CSignerHandles));
960
        }
961
        else
962 963
        {
            msg_data->cSignerHandle = 0;
964
            ret = FALSE;
965
        }
966 967
    }
    else
968 969
    {
        msg_data->cSignerHandle = 0;
970
        msg_data->signerHandles = NULL;
971
    }
972 973 974
    return ret;
}

975 976 977 978
static void CSignedMsgData_CloseHandles(CSignedMsgData *msg_data)
{
    DWORD i;

979
    for (i = 0; i < msg_data->cSignerHandle; i++)
980
    {
981 982 983 984
        if (msg_data->signerHandles[i].contentHash)
            CryptDestroyHash(msg_data->signerHandles[i].contentHash);
        if (msg_data->signerHandles[i].authAttrHash)
            CryptDestroyHash(msg_data->signerHandles[i].authAttrHash);
985 986
    }
    CryptMemFree(msg_data->signerHandles);
987 988
    msg_data->signerHandles = NULL;
    msg_data->cSignerHandle = 0;
989 990
}

991 992 993 994 995 996
static BOOL CSignedMsgData_UpdateHash(CSignedMsgData *msg_data,
 const BYTE *pbData, DWORD cbData)
{
    DWORD i;
    BOOL ret = TRUE;

997
    for (i = 0; ret && i < msg_data->cSignerHandle; i++)
998 999 1000 1001 1002
        ret = CryptHashData(msg_data->signerHandles[i].contentHash, pbData,
         cbData, 0);
    return ret;
}

1003 1004 1005 1006 1007 1008 1009 1010 1011
static BOOL CRYPT_AppendAttribute(CRYPT_ATTRIBUTES *out,
 const CRYPT_ATTRIBUTE *in)
{
    BOOL ret = FALSE;

    out->rgAttr = CryptMemRealloc(out->rgAttr,
     (out->cAttr + 1) * sizeof(CRYPT_ATTRIBUTE));
    if (out->rgAttr)
    {
1012
        ret = CRYPT_ConstructAttribute(&out->rgAttr[out->cAttr], in);
1013 1014 1015 1016 1017 1018
        if (ret)
            out->cAttr++;
    }
    return ret;
}

1019 1020
static BOOL CSignedMsgData_AppendMessageDigestAttribute(
 CSignedMsgData *msg_data, DWORD signerIndex)
1021 1022 1023 1024 1025 1026 1027 1028
{
    BOOL ret;
    DWORD size;
    CRYPT_HASH_BLOB hash = { 0, NULL }, encodedHash = { 0, NULL };
    char messageDigest[] = szOID_RSA_messageDigest;
    CRYPT_ATTRIBUTE messageDigestAttr = { messageDigest, 1, &encodedHash };

    size = sizeof(DWORD);
1029
    ret = CryptGetHashParam(
1030
     msg_data->signerHandles[signerIndex].contentHash, HP_HASHSIZE,
1031
     (LPBYTE)&hash.cbData, &size, 0);
1032 1033 1034
    if (ret)
    {
        hash.pbData = CryptMemAlloc(hash.cbData);
1035
        ret = CryptGetHashParam(
1036
         msg_data->signerHandles[signerIndex].contentHash, HP_HASHVAL,
1037
         hash.pbData, &hash.cbData, 0);
1038 1039 1040 1041 1042 1043 1044
        if (ret)
        {
            ret = CRYPT_AsnEncodeOctets(0, NULL, &hash, CRYPT_ENCODE_ALLOC_FLAG,
             NULL, (LPBYTE)&encodedHash.pbData, &encodedHash.cbData);
            if (ret)
            {
                ret = CRYPT_AppendAttribute(
1045
                 &msg_data->info->rgSignerInfo[signerIndex].AuthAttrs,
1046 1047 1048 1049 1050 1051 1052 1053 1054
                 &messageDigestAttr);
                LocalFree(encodedHash.pbData);
            }
        }
        CryptMemFree(hash.pbData);
    }
    return ret;
}

1055 1056 1057 1058 1059
typedef enum {
    Sign,
    Verify
} SignOrVerify;

1060
static BOOL CSignedMsgData_UpdateAuthenticatedAttributes(
1061
 CSignedMsgData *msg_data, SignOrVerify flag)
1062 1063 1064 1065
{
    DWORD i;
    BOOL ret = TRUE;

1066
    TRACE("(%p)\n", msg_data);
1067

1068
    for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
1069
    {
1070
        if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
1071
        {
1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
            if (flag == Sign)
            {
                BYTE oid_rsa_data_encoded[] = { 0x06,0x09,0x2a,0x86,0x48,0x86,
                 0xf7,0x0d,0x01,0x07,0x01 };
                CRYPT_DATA_BLOB content = { sizeof(oid_rsa_data_encoded),
                 oid_rsa_data_encoded };
                char contentType[] = szOID_RSA_contentType;
                CRYPT_ATTRIBUTE contentTypeAttr = { contentType, 1, &content };

                /* FIXME: does this depend on inner OID? */
                ret = CRYPT_AppendAttribute(
                 &msg_data->info->rgSignerInfo[i].AuthAttrs, &contentTypeAttr);
                if (ret)
                    ret = CSignedMsgData_AppendMessageDigestAttribute(msg_data,
                     i);
            }
1088 1089 1090 1091 1092 1093
            if (ret)
            {
                LPBYTE encodedAttrs;
                DWORD size;

                ret = CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_ATTRIBUTES,
1094
                 &msg_data->info->rgSignerInfo[i].AuthAttrs,
1095
                 CRYPT_ENCODE_ALLOC_FLAG, NULL, &encodedAttrs, &size);
1096 1097
                if (ret)
                {
1098
                    ret = CryptHashData(
1099
                     msg_data->signerHandles[i].authAttrHash, encodedAttrs,
1100
                     size, 0);
1101 1102 1103 1104 1105 1106
                    LocalFree(encodedAttrs);
                }
            }
        }
    }
    TRACE("returning %d\n", ret);
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
    return ret;
}

static void CRYPT_ReverseBytes(CRYPT_HASH_BLOB *hash)
{
    DWORD i;
    BYTE tmp;

    for (i = 0; i < hash->cbData / 2; i++)
    {
        tmp = hash->pbData[hash->cbData - i - 1];
        hash->pbData[hash->cbData - i - 1] = hash->pbData[i];
        hash->pbData[i] = tmp;
    }
}

1123
static BOOL CSignedMsgData_Sign(CSignedMsgData *msg_data)
1124 1125 1126 1127
{
    DWORD i;
    BOOL ret = TRUE;

1128
    TRACE("(%p)\n", msg_data);
1129

1130
    for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
1131
    {
1132 1133
        HCRYPTHASH hash;

1134 1135
        if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
            hash = msg_data->signerHandles[i].authAttrHash;
1136
        else
1137
            hash = msg_data->signerHandles[i].contentHash;
1138
        ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0, NULL,
1139
         &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1140 1141
        if (ret)
        {
1142
            msg_data->info->rgSignerInfo[i].EncryptedHash.pbData =
1143
             CryptMemAlloc(
1144 1145
             msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
            if (msg_data->info->rgSignerInfo[i].EncryptedHash.pbData)
1146
            {
1147
                ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0,
1148 1149
                 msg_data->info->rgSignerInfo[i].EncryptedHash.pbData,
                 &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1150
                if (ret)
1151
                    CRYPT_ReverseBytes(
1152
                     &msg_data->info->rgSignerInfo[i].EncryptedHash);
1153 1154 1155 1156 1157 1158 1159 1160
            }
            else
                ret = FALSE;
        }
    }
    return ret;
}

1161
static BOOL CSignedMsgData_Update(CSignedMsgData *msg_data,
1162
 const BYTE *pbData, DWORD cbData, BOOL fFinal, SignOrVerify flag)
1163 1164 1165 1166 1167
{
    BOOL ret = CSignedMsgData_UpdateHash(msg_data, pbData, cbData);

    if (ret && fFinal)
    {
1168 1169
        ret = CSignedMsgData_UpdateAuthenticatedAttributes(msg_data, flag);
        if (ret && flag == Sign)
1170 1171 1172 1173 1174
            ret = CSignedMsgData_Sign(msg_data);
    }
    return ret;
}

1175 1176 1177
typedef struct _CSignedEncodeMsg
{
    CryptMsgBase    base;
1178
    LPSTR           innerOID;
1179 1180 1181 1182 1183 1184
    CRYPT_DATA_BLOB data;
    CSignedMsgData  msg_data;
} CSignedEncodeMsg;

static void CSignedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
{
1185
    CSignedEncodeMsg *msg = hCryptMsg;
1186 1187
    DWORD i;

1188
    CryptMemFree(msg->innerOID);
1189
    CryptMemFree(msg->data.pbData);
1190 1191 1192 1193
    CRYPT_FreeBlobArray(msg->msg_data.info->cCertEncoded,
     msg->msg_data.info->rgCertEncoded);
    CRYPT_FreeBlobArray(msg->msg_data.info->cCrlEncoded,
     msg->msg_data.info->rgCrlEncoded);
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
    for (i = 0; i < msg->msg_data.info->cSignerInfo; i++)
        CSignerInfo_Free(&msg->msg_data.info->rgSignerInfo[i]);
    CSignedMsgData_CloseHandles(&msg->msg_data);
    CryptMemFree(msg->msg_data.info->rgSignerInfo);
    CryptMemFree(msg->msg_data.info);
}

static BOOL CSignedEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
1204
    CSignedEncodeMsg *msg = hCryptMsg;
1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    BOOL ret = FALSE;

    switch (dwParamType)
    {
    case CMSG_CONTENT_PARAM:
    {
        CRYPT_CONTENT_INFO info;

        ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
         &info.Content.cbData);
        if (ret)
        {
            info.Content.pbData = CryptMemAlloc(info.Content.cbData);
            if (info.Content.pbData)
            {
                ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
                 info.Content.pbData, &info.Content.cbData);
                if (ret)
                {
                    char oid_rsa_signed[] = szOID_RSA_signedData;

                    info.pszObjId = oid_rsa_signed;
                    ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
                     PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
                }
                CryptMemFree(info.Content.pbData);
            }
            else
                ret = FALSE;
        }
        break;
    }
    case CMSG_BARE_CONTENT_PARAM:
    {
        CRYPT_SIGNED_INFO info;
1240
        BOOL freeContent = FALSE;
1241

1242
        info = *msg->msg_data.info;
1243
        if (!msg->innerOID || !strcmp(msg->innerOID, szOID_RSA_data))
1244
        {
1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
            char oid_rsa_data[] = szOID_RSA_data;

            /* Quirk:  OID is only encoded messages if an update has happened */
            if (msg->base.state != MsgStateInit)
                info.content.pszObjId = oid_rsa_data;
            else
                info.content.pszObjId = NULL;
            if (msg->data.cbData)
            {
                CRYPT_DATA_BLOB blob = { msg->data.cbData, msg->data.pbData };
1255

1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266
                ret = CryptEncodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
                 &blob, CRYPT_ENCODE_ALLOC_FLAG, NULL,
                 &info.content.Content.pbData, &info.content.Content.cbData);
                freeContent = TRUE;
            }
            else
            {
                info.content.Content.cbData = 0;
                info.content.Content.pbData = NULL;
                ret = TRUE;
            }
1267 1268 1269
        }
        else
        {
1270 1271 1272
            info.content.pszObjId = msg->innerOID;
            info.content.Content.cbData = msg->data.cbData;
            info.content.Content.pbData = msg->data.pbData;
1273 1274 1275 1276
            ret = TRUE;
        }
        if (ret)
        {
1277
            ret = CRYPT_AsnEncodeCMSSignedInfo(&info, pvData, pcbData);
1278 1279
            if (freeContent)
                LocalFree(info.content.Content.pbData);
1280 1281 1282 1283
        }
        break;
    }
    case CMSG_COMPUTED_HASH_PARAM:
1284
        if (dwIndex >= msg->msg_data.cSignerHandle)
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
            SetLastError(CRYPT_E_INVALID_INDEX);
        else
            ret = CryptGetHashParam(
             msg->msg_data.signerHandles[dwIndex].contentHash, HP_HASHVAL,
             pvData, pcbData, 0);
        break;
    case CMSG_ENCODED_SIGNER:
        if (dwIndex >= msg->msg_data.info->cSignerInfo)
            SetLastError(CRYPT_E_INVALID_INDEX);
        else
            ret = CryptEncodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
1296
             CMS_SIGNER_INFO, &msg->msg_data.info->rgSignerInfo[dwIndex], 0,
1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308
             NULL, pvData, pcbData);
        break;
    case CMSG_VERSION_PARAM:
        ret = CRYPT_CopyParam(pvData, pcbData, &msg->msg_data.info->version,
         sizeof(msg->msg_data.info->version));
        break;
    default:
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
    }
    return ret;
}

1309 1310 1311
static BOOL CSignedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal)
{
1312
    CSignedEncodeMsg *msg = hCryptMsg;
1313 1314
    BOOL ret = FALSE;

1315 1316 1317
    if (msg->base.state == MsgStateFinalized)
        SetLastError(CRYPT_E_MSG_ERROR);
    else if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
1318
    {
1319 1320
        ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData, fFinal,
         Sign);
1321 1322
        if (msg->base.streamed)
            FIXME("streamed partial stub\n");
1323
        msg->base.state = fFinal ? MsgStateFinalized : MsgStateUpdated;
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343
    }
    else
    {
        if (!fFinal)
            SetLastError(CRYPT_E_MSG_ERROR);
        else
        {
            if (cbData)
            {
                msg->data.pbData = CryptMemAlloc(cbData);
                if (msg->data.pbData)
                {
                    memcpy(msg->data.pbData, pbData, cbData);
                    msg->data.cbData = cbData;
                    ret = TRUE;
                }
            }
            else
                ret = TRUE;
            if (ret)
1344
                ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData,
1345
                 fFinal, Sign);
1346
            msg->base.state = MsgStateFinalized;
1347 1348 1349
        }
    }
    return ret;
1350 1351 1352
}

static HCRYPTMSG CSignedEncodeMsg_Open(DWORD dwFlags,
1353
 const void *pvMsgEncodeInfo, LPCSTR pszInnerContentObjID,
1354 1355
 PCMSG_STREAM_INFO pStreamInfo)
{
1356
    const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *info = pvMsgEncodeInfo;
1357 1358 1359 1360 1361 1362 1363 1364 1365
    DWORD i;
    CSignedEncodeMsg *msg;

    if (info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO) &&
     info->cbSize != sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS))
    {
        SetLastError(E_INVALIDARG);
        return NULL;
    }
1366
    if (info->cbSize == sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS) &&
Juan Lang's avatar
Juan Lang committed
1367
     info->cAttrCertEncoded)
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377
    {
        FIXME("CMSG_SIGNED_ENCODE_INFO with CMS fields unsupported\n");
        return NULL;
    }
    for (i = 0; i < info->cSigners; i++)
        if (!CRYPT_IsValidSigner(&info->rgSigners[i]))
            return NULL;
    msg = CryptMemAlloc(sizeof(CSignedEncodeMsg));
    if (msg)
    {
1378 1379
        BOOL ret = TRUE;

1380 1381
        CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
         CSignedEncodeMsg_Close, CSignedEncodeMsg_GetParam,
1382
         CSignedEncodeMsg_Update, CRYPT_DefaultMsgControl);
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
        if (pszInnerContentObjID)
        {
            msg->innerOID = CryptMemAlloc(strlen(pszInnerContentObjID) + 1);
            if (msg->innerOID)
                strcpy(msg->innerOID, pszInnerContentObjID);
            else
                ret = FALSE;
        }
        else
            msg->innerOID = NULL;
1393 1394
        msg->data.cbData = 0;
        msg->data.pbData = NULL;
1395 1396 1397 1398
        if (ret)
            msg->msg_data.info = CryptMemAlloc(sizeof(CRYPT_SIGNED_INFO));
        else
            msg->msg_data.info = NULL;
1399 1400 1401 1402 1403 1404 1405
        if (msg->msg_data.info)
        {
            memset(msg->msg_data.info, 0, sizeof(CRYPT_SIGNED_INFO));
            msg->msg_data.info->version = CMSG_SIGNED_DATA_V1;
        }
        else
            ret = FALSE;
1406
        if (ret)
1407
        {
1408
            if (info->cSigners)
1409
            {
1410
                msg->msg_data.info->rgSignerInfo =
1411
                 CryptMemAlloc(info->cSigners * sizeof(CMSG_CMS_SIGNER_INFO));
1412
                if (msg->msg_data.info->rgSignerInfo)
1413
                {
1414 1415
                    msg->msg_data.info->cSignerInfo = info->cSigners;
                    memset(msg->msg_data.info->rgSignerInfo, 0,
1416 1417
                     msg->msg_data.info->cSignerInfo *
                     sizeof(CMSG_CMS_SIGNER_INFO));
1418 1419
                    ret = CSignedMsgData_AllocateHandles(&msg->msg_data);
                    for (i = 0; ret && i < msg->msg_data.info->cSignerInfo; i++)
1420
                    {
1421 1422 1423
                        if (info->rgSigners[i].SignerId.dwIdChoice ==
                         CERT_ID_KEY_IDENTIFIER)
                            msg->msg_data.info->version = CMSG_SIGNED_DATA_V3;
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434
                        ret = CSignerInfo_Construct(
                         &msg->msg_data.info->rgSignerInfo[i],
                         &info->rgSigners[i]);
                        if (ret)
                        {
                            ret = CSignedMsgData_ConstructSignerHandles(
                             &msg->msg_data, i, info->rgSigners[i].hCryptProv);
                            if (dwFlags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
                                CryptReleaseContext(info->rgSigners[i].hCryptProv,
                                 0);
                        }
1435 1436
                    }
                }
1437 1438
                else
                    ret = FALSE;
1439 1440
            }
            else
1441 1442 1443
            {
                msg->msg_data.info->cSignerInfo = 0;
                msg->msg_data.signerHandles = NULL;
1444
                msg->msg_data.cSignerHandle = 0;
1445
            }
1446
        }
1447
        if (ret)
1448 1449 1450
            ret = CRYPT_ConstructBlobArray(&msg->msg_data.info->cCertEncoded,
             &msg->msg_data.info->rgCertEncoded, info->cCertEncoded,
             info->rgCertEncoded);
1451
        if (ret)
1452 1453 1454
            ret = CRYPT_ConstructBlobArray(&msg->msg_data.info->cCrlEncoded,
             &msg->msg_data.info->rgCrlEncoded, info->cCrlEncoded,
             info->rgCrlEncoded);
1455 1456 1457 1458 1459
        if (!ret)
        {
            CSignedEncodeMsg_Close(msg);
            msg = NULL;
        }
1460 1461 1462 1463
    }
    return msg;
}

1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
typedef struct _CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS
{
    DWORD                       cbSize;
    HCRYPTPROV_LEGACY           hCryptProv;
    CRYPT_ALGORITHM_IDENTIFIER  ContentEncryptionAlgorithm;
    void                       *pvEncryptionAuxInfo;
    DWORD                       cRecipients;
    PCERT_INFO                 *rgpRecipientCert;
    PCMSG_RECIPIENT_ENCODE_INFO rgCmsRecipients;
    DWORD                       cCertEncoded;
    PCERT_BLOB                  rgCertEncoded;
    DWORD                       cCrlEncoded;
    PCRL_BLOB                   rgCrlEncoded;
    DWORD                       cAttrCertEncoded;
    PCERT_BLOB                  rgAttrCertEncoded;
    DWORD                       cUnprotectedAttr;
    PCRYPT_ATTRIBUTE            rgUnprotectedAttr;
} CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS, *PCMSG_ENVELOPED_ENCODE_INFO_WITH_CMS;

typedef struct _CEnvelopedEncodeMsg
{
    CryptMsgBase                   base;
1486
    CRYPT_ALGORITHM_IDENTIFIER     algo;
1487
    HCRYPTPROV                     prov;
1488 1489 1490 1491
    HCRYPTKEY                      key;
    DWORD                          cRecipientInfo;
    CMSG_KEY_TRANS_RECIPIENT_INFO *recipientInfo;
    CRYPT_DATA_BLOB                data;
1492 1493
} CEnvelopedEncodeMsg;

1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
static BOOL CRYPT_ConstructAlgorithmId(CRYPT_ALGORITHM_IDENTIFIER *out,
 const CRYPT_ALGORITHM_IDENTIFIER *in)
{
    out->pszObjId = CryptMemAlloc(strlen(in->pszObjId) + 1);
    if (out->pszObjId)
    {
        strcpy(out->pszObjId, in->pszObjId);
        return CRYPT_ConstructBlob(&out->Parameters, &in->Parameters);
    }
    else
        return FALSE;
}

static BOOL CRYPT_ConstructBitBlob(CRYPT_BIT_BLOB *out, const CRYPT_BIT_BLOB *in)
{
    out->cbData = in->cbData;
    out->cUnusedBits = in->cUnusedBits;
    if (out->cbData)
    {
        out->pbData = CryptMemAlloc(out->cbData);
        if (out->pbData)
            memcpy(out->pbData, in->pbData, out->cbData);
        else
            return FALSE;
    }
    else
        out->pbData = NULL;
    return TRUE;
}

static BOOL CRYPT_GenKey(CMSG_CONTENT_ENCRYPT_INFO *info, ALG_ID algID)
{
    static HCRYPTOIDFUNCSET set = NULL;
    PFN_CMSG_GEN_CONTENT_ENCRYPT_KEY genKeyFunc = NULL;
    HCRYPTOIDFUNCADDR hFunc;
    BOOL ret;

    if (!set)
        set = CryptInitOIDFunctionSet(CMSG_OID_GEN_CONTENT_ENCRYPT_KEY_FUNC, 0);
    CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING,
     info->ContentEncryptionAlgorithm.pszObjId, 0, (void **)&genKeyFunc, &hFunc);
    if (genKeyFunc)
    {
        ret = genKeyFunc(info, 0, NULL);
        CryptFreeOIDFunctionAddress(hFunc, 0);
    }
    else
        ret = CryptGenKey(info->hCryptProv, algID, CRYPT_EXPORTABLE,
         &info->hContentEncryptKey);
    return ret;
}

static BOOL WINAPI CRYPT_ExportKeyTrans(
 PCMSG_CONTENT_ENCRYPT_INFO pContentEncryptInfo,
 PCMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO pKeyTransEncodeInfo,
 PCMSG_KEY_TRANS_ENCRYPT_INFO pKeyTransEncryptInfo,
 DWORD dwFlags, void *pvReserved)
{
    CERT_PUBLIC_KEY_INFO keyInfo;
    HCRYPTKEY expKey;
    BOOL ret;

    ret = CRYPT_ConstructAlgorithmId(&keyInfo.Algorithm,
        &pKeyTransEncodeInfo->KeyEncryptionAlgorithm);
    if (ret)
        CRYPT_ConstructBitBlob(&keyInfo.PublicKey,
         &pKeyTransEncodeInfo->RecipientPublicKey);

    if (ret)
        ret = CryptImportPublicKeyInfo(pKeyTransEncodeInfo->hCryptProv,
         X509_ASN_ENCODING, &keyInfo, &expKey);
    if (ret)
    {
        BYTE *keyBlob;
        DWORD size;

        ret = CryptExportKey(pContentEncryptInfo->hContentEncryptKey, expKey,
         SIMPLEBLOB, 0, NULL, &size);
        keyBlob = CryptMemAlloc(size);
        if (keyBlob)
        {
            ret = CryptExportKey(pContentEncryptInfo->hContentEncryptKey,
             expKey, SIMPLEBLOB, 0, keyBlob, &size);
            if (ret)
            {
                DWORD head = sizeof(BLOBHEADER) + sizeof(ALG_ID);

                pKeyTransEncryptInfo->EncryptedKey.pbData =
                 CryptMemAlloc(size - head);
                if (pKeyTransEncryptInfo->EncryptedKey.pbData)
                {
                    DWORD i, k = 0;

                    pKeyTransEncryptInfo->EncryptedKey.cbData = size - head;
                    for (i = size - 1; i >= head; --i, ++k)
                        pKeyTransEncryptInfo->EncryptedKey.pbData[k] =
                         keyBlob[i];
                }
                else
                    ret = FALSE;
            }
            CryptMemFree(keyBlob);
        }
        else
            ret = FALSE;
        CryptDestroyKey(expKey);
    }

    CryptMemFree(keyInfo.Algorithm.pszObjId);
    CryptMemFree(keyInfo.Algorithm.Parameters.pbData);
    return ret;
}

static BOOL CRYPT_ExportEncryptedKey(CMSG_CONTENT_ENCRYPT_INFO *info, DWORD i,
 CRYPT_DATA_BLOB *key)
{
    static HCRYPTOIDFUNCSET set = NULL;
    PFN_CMSG_EXPORT_KEY_TRANS exportKeyFunc = NULL;
    HCRYPTOIDFUNCADDR hFunc = NULL;
    CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO *encodeInfo =
     info->rgCmsRecipients[i].u.pKeyTrans;
    CMSG_KEY_TRANS_ENCRYPT_INFO encryptInfo;
    BOOL ret;

    memset(&encryptInfo, 0, sizeof(encryptInfo));
    encryptInfo.cbSize = sizeof(encryptInfo);
    encryptInfo.dwRecipientIndex = i;
    ret = CRYPT_ConstructAlgorithmId(&encryptInfo.KeyEncryptionAlgorithm,
     &encodeInfo->KeyEncryptionAlgorithm);

    if (!set)
        set = CryptInitOIDFunctionSet(CMSG_OID_EXPORT_KEY_TRANS_FUNC, 0);
    CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING,
     encryptInfo.KeyEncryptionAlgorithm.pszObjId, 0, (void **)&exportKeyFunc,
     &hFunc);
    if (!exportKeyFunc)
        exportKeyFunc = CRYPT_ExportKeyTrans;
    if (ret)
    {
        ret = exportKeyFunc(info, encodeInfo, &encryptInfo, 0, NULL);
        if (ret)
        {
            key->cbData = encryptInfo.EncryptedKey.cbData;
            key->pbData = encryptInfo.EncryptedKey.pbData;
        }
    }
    if (hFunc)
        CryptFreeOIDFunctionAddress(hFunc, 0);

    CryptMemFree(encryptInfo.KeyEncryptionAlgorithm.pszObjId);
    CryptMemFree(encryptInfo.KeyEncryptionAlgorithm.Parameters.pbData);
    return ret;
}

1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
static LPVOID WINAPI mem_alloc(size_t size)
{
    return HeapAlloc(GetProcessHeap(), 0, size);
}

static VOID WINAPI mem_free(LPVOID pv)
{
    HeapFree(GetProcessHeap(), 0, pv);
}


1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714
static BOOL CContentEncryptInfo_Construct(CMSG_CONTENT_ENCRYPT_INFO *info,
 const CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS *in, HCRYPTPROV prov)
{
    BOOL ret;

    info->cbSize = sizeof(CMSG_CONTENT_ENCRYPT_INFO);
    info->hCryptProv = prov;
    ret = CRYPT_ConstructAlgorithmId(&info->ContentEncryptionAlgorithm,
     &in->ContentEncryptionAlgorithm);
    info->pvEncryptionAuxInfo = in->pvEncryptionAuxInfo;
    info->cRecipients = in->cRecipients;
    if (ret)
    {
        info->rgCmsRecipients = CryptMemAlloc(in->cRecipients *
         sizeof(CMSG_RECIPIENT_ENCODE_INFO));
        if (info->rgCmsRecipients)
        {
            DWORD i;

            for (i = 0; ret && i < in->cRecipients; ++i)
            {
                CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO *encodeInfo;
                CERT_INFO *cert = in->rgpRecipientCert[i];

                info->rgCmsRecipients[i].dwRecipientChoice =
                 CMSG_KEY_TRANS_RECIPIENT;
                encodeInfo = CryptMemAlloc(sizeof(*encodeInfo));
                info->rgCmsRecipients[i].u.pKeyTrans = encodeInfo;
                if (encodeInfo)
                {
                    encodeInfo->cbSize = sizeof(*encodeInfo);
                    ret = CRYPT_ConstructAlgorithmId(
                     &encodeInfo->KeyEncryptionAlgorithm,
                     &cert->SubjectPublicKeyInfo.Algorithm);
                    encodeInfo->pvKeyEncryptionAuxInfo = NULL;
                    encodeInfo->hCryptProv = prov;
                    if (ret)
                        ret = CRYPT_ConstructBitBlob(
                         &encodeInfo->RecipientPublicKey,
                         &cert->SubjectPublicKeyInfo.PublicKey);
                    if (ret)
                        ret = CRYPT_ConstructBlob(
                         &encodeInfo->RecipientId.u.IssuerSerialNumber.Issuer,
                         &cert->Issuer);
                    if (ret)
                        ret = CRYPT_ConstructBlob(
                         &encodeInfo->RecipientId.u.IssuerSerialNumber.SerialNumber,
                         &cert->SerialNumber);
                }
                else
                    ret = FALSE;
            }
        }
        else
            ret = FALSE;
    }
1715 1716
    info->pfnAlloc = mem_alloc;
    info->pfnFree = mem_free;
1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775
    return ret;
}

static void CContentEncryptInfo_Free(CMSG_CONTENT_ENCRYPT_INFO *info)
{
    CryptMemFree(info->ContentEncryptionAlgorithm.pszObjId);
    CryptMemFree(info->ContentEncryptionAlgorithm.Parameters.pbData);
    if (info->rgCmsRecipients)
    {
        DWORD i;

        for (i = 0; i < info->cRecipients; ++i)
        {
            CMSG_KEY_TRANS_RECIPIENT_ENCODE_INFO *encodeInfo =
             info->rgCmsRecipients[i].u.pKeyTrans;

            CryptMemFree(encodeInfo->KeyEncryptionAlgorithm.pszObjId);
            CryptMemFree(encodeInfo->KeyEncryptionAlgorithm.Parameters.pbData);
            CryptMemFree(encodeInfo->RecipientPublicKey.pbData);
            CryptMemFree(
             encodeInfo->RecipientId.u.IssuerSerialNumber.Issuer.pbData);
            CryptMemFree(
             encodeInfo->RecipientId.u.IssuerSerialNumber.SerialNumber.pbData);
            CryptMemFree(encodeInfo);
        }
        CryptMemFree(info->rgCmsRecipients);
    }
}

static BOOL CRecipientInfo_Construct(CMSG_KEY_TRANS_RECIPIENT_INFO *info,
 const CERT_INFO *cert, CRYPT_DATA_BLOB *key)
{
    BOOL ret;

    info->dwVersion = CMSG_KEY_TRANS_PKCS_1_5_VERSION;
    info->RecipientId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
    ret = CRYPT_ConstructBlob(&info->RecipientId.u.IssuerSerialNumber.Issuer,
     &cert->Issuer);
    if (ret)
        ret = CRYPT_ConstructBlob(
         &info->RecipientId.u.IssuerSerialNumber.SerialNumber,
         &cert->SerialNumber);
    if (ret)
        ret = CRYPT_ConstructAlgorithmId(&info->KeyEncryptionAlgorithm,
         &cert->SubjectPublicKeyInfo.Algorithm);
    info->EncryptedKey.cbData = key->cbData;
    info->EncryptedKey.pbData = key->pbData;
    return ret;
}

static void CRecipientInfo_Free(CMSG_KEY_TRANS_RECIPIENT_INFO *info)
{
    CryptMemFree(info->RecipientId.u.IssuerSerialNumber.Issuer.pbData);
    CryptMemFree(info->RecipientId.u.IssuerSerialNumber.SerialNumber.pbData);
    CryptMemFree(info->KeyEncryptionAlgorithm.pszObjId);
    CryptMemFree(info->KeyEncryptionAlgorithm.Parameters.pbData);
    CryptMemFree(info->EncryptedKey.pbData);
}

1776 1777 1778 1779
static void CEnvelopedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
{
    CEnvelopedEncodeMsg *msg = hCryptMsg;

1780 1781
    CryptMemFree(msg->algo.pszObjId);
    CryptMemFree(msg->algo.Parameters.pbData);
1782 1783
    if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
        CryptReleaseContext(msg->prov, 0);
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793
    CryptDestroyKey(msg->key);
    if (msg->recipientInfo)
    {
        DWORD i;

        for (i = 0; i < msg->cRecipientInfo; ++i)
            CRecipientInfo_Free(&msg->recipientInfo[i]);
        CryptMemFree(msg->recipientInfo);
    }
    CryptMemFree(msg->data.pbData);
1794 1795 1796 1797 1798
}

static BOOL CEnvelopedEncodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850
    CEnvelopedEncodeMsg *msg = hCryptMsg;
    BOOL ret = FALSE;

    switch (dwParamType)
    {
    case CMSG_BARE_CONTENT_PARAM:
        if (msg->base.streamed)
            SetLastError(E_INVALIDARG);
        else
        {
            char oid_rsa_data[] = szOID_RSA_data;
            CRYPT_ENVELOPED_DATA envelopedData = {
             CMSG_ENVELOPED_DATA_PKCS_1_5_VERSION, msg->cRecipientInfo,
             msg->recipientInfo, { oid_rsa_data, msg->algo, msg->data }
            };

            ret = CRYPT_AsnEncodePKCSEnvelopedData(&envelopedData, pvData,
             pcbData);
        }
        break;
    case CMSG_CONTENT_PARAM:
    {
        CRYPT_CONTENT_INFO info;

        ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0, NULL,
         &info.Content.cbData);
        if (ret)
        {
            info.Content.pbData = CryptMemAlloc(info.Content.cbData);
            if (info.Content.pbData)
            {
                ret = CryptMsgGetParam(hCryptMsg, CMSG_BARE_CONTENT_PARAM, 0,
                 info.Content.pbData, &info.Content.cbData);
                if (ret)
                {
                    char oid_rsa_enveloped[] = szOID_RSA_envelopedData;

                    info.pszObjId = oid_rsa_enveloped;
                    ret = CryptEncodeObjectEx(X509_ASN_ENCODING,
                     PKCS_CONTENT_INFO, &info, 0, NULL, pvData, pcbData);
                }
                CryptMemFree(info.Content.pbData);
            }
            else
                ret = FALSE;
        }
        break;
    }
    default:
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
    }
    return ret;
1851 1852 1853 1854 1855
}

static BOOL CEnvelopedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal)
{
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919
    CEnvelopedEncodeMsg *msg = hCryptMsg;
    BOOL ret = FALSE;

    if (msg->base.state == MsgStateFinalized)
        SetLastError(CRYPT_E_MSG_ERROR);
    else if (msg->base.streamed)
    {
        FIXME("streamed stub\n");
        msg->base.state = fFinal ? MsgStateFinalized : MsgStateUpdated;
        ret = TRUE;
    }
    else
    {
        if (!fFinal)
        {
            if (msg->base.open_flags & CMSG_DETACHED_FLAG)
                SetLastError(E_INVALIDARG);
            else
                SetLastError(CRYPT_E_MSG_ERROR);
        }
        else
        {
            if (cbData)
            {
                DWORD dataLen = cbData;

                msg->data.cbData = cbData;
                msg->data.pbData = CryptMemAlloc(cbData);
                if (msg->data.pbData)
                {
                    memcpy(msg->data.pbData, pbData, cbData);
                    ret = CryptEncrypt(msg->key, 0, TRUE, 0, msg->data.pbData,
                     &dataLen, msg->data.cbData);
                    msg->data.cbData = dataLen;
                    if (dataLen > cbData)
                    {
                        msg->data.pbData = CryptMemRealloc(msg->data.pbData,
                         dataLen);
                        if (msg->data.pbData)
                        {
                            dataLen = cbData;
                            ret = CryptEncrypt(msg->key, 0, TRUE, 0,
                             msg->data.pbData, &dataLen, msg->data.cbData);
                        }
                        else
                            ret = FALSE;
                    }
                    if (!ret)
                        CryptMemFree(msg->data.pbData);
                }
                else
                    ret = FALSE;
                if (!ret)
                {
                    msg->data.cbData = 0;
                    msg->data.pbData = NULL;
                }
            }
            else
                ret = TRUE;
            msg->base.state = MsgStateFinalized;
        }
    }
    return ret;
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958
}

static HCRYPTMSG CEnvelopedEncodeMsg_Open(DWORD dwFlags,
 const void *pvMsgEncodeInfo, LPCSTR pszInnerContentObjID,
 PCMSG_STREAM_INFO pStreamInfo)
{
    CEnvelopedEncodeMsg *msg;
    const CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS *info = pvMsgEncodeInfo;
    HCRYPTPROV prov;
    ALG_ID algID;

    if (info->cbSize != sizeof(CMSG_ENVELOPED_ENCODE_INFO) &&
     info->cbSize != sizeof(CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS))
    {
        SetLastError(E_INVALIDARG);
        return NULL;
    }
    if (info->cbSize == sizeof(CMSG_ENVELOPED_ENCODE_INFO_WITH_CMS))
        FIXME("CMS fields unsupported\n");
    if (!(algID = CertOIDToAlgId(info->ContentEncryptionAlgorithm.pszObjId)))
    {
        SetLastError(CRYPT_E_UNKNOWN_ALGO);
        return NULL;
    }
    if (info->cRecipients && !info->rgpRecipientCert)
    {
        SetLastError(E_INVALIDARG);
        return NULL;
    }
    if (info->hCryptProv)
        prov = info->hCryptProv;
    else
    {
        prov = CRYPT_GetDefaultProvider();
        dwFlags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
    }
    msg = CryptMemAlloc(sizeof(CEnvelopedEncodeMsg));
    if (msg)
    {
1959 1960 1961 1962 1963
        CRYPT_DATA_BLOB encryptedKey = { 0, NULL };
        CMSG_CONTENT_ENCRYPT_INFO encryptInfo;
        BOOL ret;
        DWORD i;

1964 1965 1966
        CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
         CEnvelopedEncodeMsg_Close, CEnvelopedEncodeMsg_GetParam,
         CEnvelopedEncodeMsg_Update, CRYPT_DefaultMsgControl);
1967 1968
        ret = CRYPT_ConstructAlgorithmId(&msg->algo,
         &info->ContentEncryptionAlgorithm);
1969
        msg->prov = prov;
1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
        msg->data.cbData = 0;
        msg->data.pbData = NULL;
        msg->cRecipientInfo = info->cRecipients;
        msg->recipientInfo = CryptMemAlloc(info->cRecipients *
         sizeof(CMSG_KEY_TRANS_RECIPIENT_INFO));
        if (!msg->recipientInfo)
            ret = FALSE;
        memset(&encryptInfo, 0, sizeof(encryptInfo));
        if (ret)
        {
            ret = CContentEncryptInfo_Construct(&encryptInfo, info, prov);
            if (ret)
            {
                ret = CRYPT_GenKey(&encryptInfo, algID);
                if (ret)
                    msg->key = encryptInfo.hContentEncryptKey;
            }
        }
        for (i = 0; ret && i < msg->cRecipientInfo; ++i)
        {
            ret = CRYPT_ExportEncryptedKey(&encryptInfo, i, &encryptedKey);
            if (ret)
                ret = CRecipientInfo_Construct(&msg->recipientInfo[i],
                 info->rgpRecipientCert[i], &encryptedKey);
        }
        CContentEncryptInfo_Free(&encryptInfo);
        if (!ret)
        {
            CryptMsgClose(msg);
            msg = NULL;
        }
2001 2002 2003 2004 2005 2006
    }
    if (!msg && (dwFlags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG))
        CryptReleaseContext(prov, 0);
    return msg;
}

2007 2008 2009 2010
HCRYPTMSG WINAPI CryptMsgOpenToEncode(DWORD dwMsgEncodingType, DWORD dwFlags,
 DWORD dwMsgType, const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
 PCMSG_STREAM_INFO pStreamInfo)
{
2011 2012 2013
    HCRYPTMSG msg = NULL;

    TRACE("(%08x, %08x, %08x, %p, %s, %p)\n", dwMsgEncodingType, dwFlags,
2014
     dwMsgType, pvMsgEncodeInfo, debugstr_a(pszInnerContentObjID), pStreamInfo);
2015 2016 2017 2018 2019 2020 2021 2022 2023

    if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
    {
        SetLastError(E_INVALIDARG);
        return NULL;
    }
    switch (dwMsgType)
    {
    case CMSG_DATA:
2024 2025 2026
        msg = CDataEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
         pszInnerContentObjID, pStreamInfo);
        break;
2027 2028 2029 2030
    case CMSG_HASHED:
        msg = CHashEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
         pszInnerContentObjID, pStreamInfo);
        break;
2031
    case CMSG_SIGNED:
2032 2033 2034
        msg = CSignedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
         pszInnerContentObjID, pStreamInfo);
        break;
2035
    case CMSG_ENVELOPED:
2036 2037
        msg = CEnvelopedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
         pszInnerContentObjID, pStreamInfo);
2038 2039 2040 2041 2042 2043 2044 2045
        break;
    case CMSG_SIGNED_AND_ENVELOPED:
    case CMSG_ENCRYPTED:
        /* defined but invalid, fall through */
    default:
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
    }
    return msg;
2046 2047
}

2048 2049 2050 2051 2052 2053 2054 2055
typedef struct _CEnvelopedDecodeMsg
{
    CRYPT_ENVELOPED_DATA *data;
    HCRYPTPROV            crypt_prov;
    CRYPT_DATA_BLOB       content;
    BOOL                  decrypted;
} CEnvelopedDecodeMsg;

2056 2057
typedef struct _CDecodeMsg
{
2058 2059 2060
    CryptMsgBase           base;
    DWORD                  type;
    HCRYPTPROV             crypt_prov;
2061
    union {
2062 2063 2064
        HCRYPTHASH          hash;
        CSignedMsgData      signed_data;
        CEnvelopedDecodeMsg enveloped_data;
2065
    } u;
2066
    CRYPT_DATA_BLOB        msg_data;
2067
    CRYPT_DATA_BLOB        detached_data;
2068
    PCONTEXT_PROPERTY_LIST properties;
2069 2070 2071 2072
} CDecodeMsg;

static void CDecodeMsg_Close(HCRYPTMSG hCryptMsg)
{
2073
    CDecodeMsg *msg = hCryptMsg;
2074 2075 2076

    if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
        CryptReleaseContext(msg->crypt_prov, 0);
2077 2078 2079
    switch (msg->type)
    {
    case CMSG_HASHED:
2080 2081
        if (msg->u.hash)
            CryptDestroyHash(msg->u.hash);
2082
        break;
2083 2084 2085 2086 2087 2088
    case CMSG_ENVELOPED:
        if (msg->u.enveloped_data.crypt_prov)
            CryptReleaseContext(msg->u.enveloped_data.crypt_prov, 0);
        LocalFree(msg->u.enveloped_data.data);
        CryptMemFree(msg->u.enveloped_data.content.pbData);
        break;
2089
    case CMSG_SIGNED:
2090
        if (msg->u.signed_data.info)
2091
        {
2092
            LocalFree(msg->u.signed_data.info);
2093 2094
            CSignedMsgData_CloseHandles(&msg->u.signed_data);
        }
2095
        break;
2096
    }
2097
    CryptMemFree(msg->msg_data.pbData);
2098
    CryptMemFree(msg->detached_data.pbData);
2099
    ContextPropertyList_Free(msg->properties);
2100 2101
}

2102
static BOOL CDecodeMsg_CopyData(CRYPT_DATA_BLOB *blob, const BYTE *pbData,
2103 2104 2105 2106 2107 2108
 DWORD cbData)
{
    BOOL ret = TRUE;

    if (cbData)
    {
2109 2110 2111
        if (blob->cbData)
            blob->pbData = CryptMemRealloc(blob->pbData,
             blob->cbData + cbData);
2112
        else
2113 2114
            blob->pbData = CryptMemAlloc(cbData);
        if (blob->pbData)
2115
        {
2116 2117
            memcpy(blob->pbData + blob->cbData, pbData, cbData);
            blob->cbData += cbData;
2118 2119 2120 2121 2122 2123 2124
        }
        else
            ret = FALSE;
    }
    return ret;
}

2125
static BOOL CDecodeMsg_DecodeDataContent(CDecodeMsg *msg, const CRYPT_DER_BLOB *blob)
2126 2127 2128 2129 2130 2131
{
    BOOL ret;
    CRYPT_DATA_BLOB *data;
    DWORD size;

    ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
2132
     blob->pbData, blob->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &data, &size);
2133 2134 2135 2136 2137 2138 2139 2140 2141
    if (ret)
    {
        ret = ContextPropertyList_SetProperty(msg->properties,
         CMSG_CONTENT_PARAM, data->pbData, data->cbData);
        LocalFree(data);
    }
    return ret;
}

2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183
static void CDecodeMsg_SaveAlgorithmID(CDecodeMsg *msg, DWORD param,
 const CRYPT_ALGORITHM_IDENTIFIER *id)
{
    static const BYTE nullParams[] = { ASN_NULL, 0 };
    CRYPT_ALGORITHM_IDENTIFIER *copy;
    DWORD len = sizeof(CRYPT_ALGORITHM_IDENTIFIER);

    /* Linearize algorithm id */
    len += strlen(id->pszObjId) + 1;
    len += id->Parameters.cbData;
    copy = CryptMemAlloc(len);
    if (copy)
    {
        copy->pszObjId =
         (LPSTR)((BYTE *)copy + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
        strcpy(copy->pszObjId, id->pszObjId);
        copy->Parameters.pbData = (BYTE *)copy->pszObjId + strlen(id->pszObjId)
         + 1;
        /* Trick:  omit NULL parameters */
        if (id->Parameters.cbData == sizeof(nullParams) &&
         !memcmp(id->Parameters.pbData, nullParams, sizeof(nullParams)))
        {
            copy->Parameters.cbData = 0;
            len -= sizeof(nullParams);
        }
        else
            copy->Parameters.cbData = id->Parameters.cbData;
        if (copy->Parameters.cbData)
            memcpy(copy->Parameters.pbData, id->Parameters.pbData,
             id->Parameters.cbData);
        ContextPropertyList_SetProperty(msg->properties, param, (BYTE *)copy,
         len);
        CryptMemFree(copy);
    }
}

static inline void CRYPT_FixUpAlgorithmID(CRYPT_ALGORITHM_IDENTIFIER *id)
{
    id->pszObjId = (LPSTR)((BYTE *)id + sizeof(CRYPT_ALGORITHM_IDENTIFIER));
    id->Parameters.pbData = (BYTE *)id->pszObjId + strlen(id->pszObjId) + 1;
}

2184
static BOOL CDecodeMsg_DecodeHashedContent(CDecodeMsg *msg,
2185
 const CRYPT_DER_BLOB *blob)
2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
{
    BOOL ret;
    CRYPT_DIGESTED_DATA *digestedData;
    DWORD size;

    ret = CRYPT_AsnDecodePKCSDigestedData(blob->pbData, blob->cbData,
     CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_DIGESTED_DATA *)&digestedData,
     &size);
    if (ret)
    {
        ContextPropertyList_SetProperty(msg->properties, CMSG_VERSION_PARAM,
         (const BYTE *)&digestedData->version, sizeof(digestedData->version));
        CDecodeMsg_SaveAlgorithmID(msg, CMSG_HASH_ALGORITHM_PARAM,
         &digestedData->DigestAlgorithm);
        ContextPropertyList_SetProperty(msg->properties,
         CMSG_INNER_CONTENT_TYPE_PARAM,
         (const BYTE *)digestedData->ContentInfo.pszObjId,
         digestedData->ContentInfo.pszObjId ?
         strlen(digestedData->ContentInfo.pszObjId) + 1 : 0);
2205 2206 2207 2208 2209 2210 2211 2212 2213
        if (!(msg->base.open_flags & CMSG_DETACHED_FLAG))
        {
            if (digestedData->ContentInfo.Content.cbData)
                CDecodeMsg_DecodeDataContent(msg,
                 &digestedData->ContentInfo.Content);
            else
                ContextPropertyList_SetProperty(msg->properties,
                 CMSG_CONTENT_PARAM, NULL, 0);
        }
2214 2215 2216 2217 2218 2219 2220
        ContextPropertyList_SetProperty(msg->properties, CMSG_HASH_DATA_PARAM,
         digestedData->hash.pbData, digestedData->hash.cbData);
        LocalFree(digestedData);
    }
    return ret;
}

2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
static BOOL CDecodeMsg_DecodeEnvelopedContent(CDecodeMsg *msg,
 const CRYPT_DER_BLOB *blob)
{
    BOOL ret;
    CRYPT_ENVELOPED_DATA *envelopedData;
    DWORD size;

    ret = CRYPT_AsnDecodePKCSEnvelopedData(blob->pbData, blob->cbData,
     CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_ENVELOPED_DATA *)&envelopedData,
     &size);
    if (ret)
        msg->u.enveloped_data.data = envelopedData;
    return ret;
}

2236
static BOOL CDecodeMsg_DecodeSignedContent(CDecodeMsg *msg,
2237
 const CRYPT_DER_BLOB *blob)
2238 2239 2240 2241 2242
{
    BOOL ret;
    CRYPT_SIGNED_INFO *signedInfo;
    DWORD size;

2243
    ret = CRYPT_AsnDecodeCMSSignedInfo(blob->pbData, blob->cbData,
2244 2245 2246
     CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_SIGNED_INFO *)&signedInfo,
     &size);
    if (ret)
2247
        msg->u.signed_data.info = signedInfo;
2248 2249
    return ret;
}
2250

2251 2252 2253 2254 2255
/* Decodes the content in blob as the type given, and updates the value
 * (type, parameters, etc.) of msg based on what blob contains.
 * It doesn't just use msg's type, to allow a recursive call from an implicitly
 * typed message once the outer content info has been decoded.
 */
2256
static BOOL CDecodeMsg_DecodeContent(CDecodeMsg *msg, const CRYPT_DER_BLOB *blob,
2257 2258 2259 2260 2261 2262 2263
 DWORD type)
{
    BOOL ret;

    switch (type)
    {
    case CMSG_DATA:
2264
        if ((ret = CDecodeMsg_DecodeDataContent(msg, blob)))
2265 2266
            msg->type = CMSG_DATA;
        break;
2267
    case CMSG_HASHED:
2268
        if ((ret = CDecodeMsg_DecodeHashedContent(msg, blob)))
2269
            msg->type = CMSG_HASHED;
2270
        break;
2271
    case CMSG_ENVELOPED:
2272 2273
        if ((ret = CDecodeMsg_DecodeEnvelopedContent(msg, blob)))
            msg->type = CMSG_ENVELOPED;
2274
        break;
2275 2276
    case CMSG_SIGNED:
        if ((ret = CDecodeMsg_DecodeSignedContent(msg, blob)))
2277
            msg->type = CMSG_SIGNED;
2278
        break;
2279 2280 2281
    default:
    {
        CRYPT_CONTENT_INFO *info;
2282
        DWORD size;
2283 2284 2285

        ret = CryptDecodeObjectEx(X509_ASN_ENCODING, PKCS_CONTENT_INFO,
         msg->msg_data.pbData, msg->msg_data.cbData, CRYPT_DECODE_ALLOC_FLAG,
2286
         NULL, &info, &size);
2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309
        if (ret)
        {
            if (!strcmp(info->pszObjId, szOID_RSA_data))
                ret = CDecodeMsg_DecodeContent(msg, &info->Content, CMSG_DATA);
            else if (!strcmp(info->pszObjId, szOID_RSA_digestedData))
                ret = CDecodeMsg_DecodeContent(msg, &info->Content,
                 CMSG_HASHED);
            else if (!strcmp(info->pszObjId, szOID_RSA_envelopedData))
                ret = CDecodeMsg_DecodeContent(msg, &info->Content,
                 CMSG_ENVELOPED);
            else if (!strcmp(info->pszObjId, szOID_RSA_signedData))
                ret = CDecodeMsg_DecodeContent(msg, &info->Content,
                 CMSG_SIGNED);
            else
            {
                SetLastError(CRYPT_E_INVALID_MSG_TYPE);
                ret = FALSE;
            }
            LocalFree(info);
        }
    }
    }
    return ret;
2310 2311
}

2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330
static BOOL CDecodeMsg_FinalizeHashedContent(CDecodeMsg *msg,
 CRYPT_DER_BLOB *blob)
{
    CRYPT_ALGORITHM_IDENTIFIER *hashAlgoID = NULL;
    DWORD size = 0;
    ALG_ID algID = 0;
    BOOL ret;

    CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, NULL, &size);
    hashAlgoID = CryptMemAlloc(size);
    ret = CryptMsgGetParam(msg, CMSG_HASH_ALGORITHM_PARAM, 0, hashAlgoID,
     &size);
    if (ret)
        algID = CertOIDToAlgId(hashAlgoID->pszObjId);
    ret = CryptCreateHash(msg->crypt_prov, algID, 0, 0, &msg->u.hash);
    if (ret)
    {
        CRYPT_DATA_BLOB content;

2331 2332 2333 2334 2335
        if (msg->base.open_flags & CMSG_DETACHED_FLAG)
        {
            /* Unlike for non-detached messages, the data were never stored as
             * the content param, but were saved in msg->detached_data instead.
             */
2336 2337
            content.pbData = msg->detached_data.pbData;
            content.cbData = msg->detached_data.cbData;
2338
        }
2339 2340 2341
        else
            ret = ContextPropertyList_FindProperty(msg->properties,
             CMSG_CONTENT_PARAM, &content);
2342 2343 2344 2345 2346 2347 2348
        if (ret)
            ret = CryptHashData(msg->u.hash, content.pbData, content.cbData, 0);
    }
    CryptMemFree(hashAlgoID);
    return ret;
}

2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362
static BOOL CDecodeMsg_FinalizeEnvelopedContent(CDecodeMsg *msg,
 CRYPT_DER_BLOB *blob)
{
    CRYPT_DATA_BLOB *content;

    if (msg->base.open_flags & CMSG_DETACHED_FLAG)
        content = &msg->detached_data;
    else
        content =
         &msg->u.enveloped_data.data->encryptedContentInfo.encryptedContent;

    return CRYPT_ConstructBlob(&msg->u.enveloped_data.content, content);
}

2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
static BOOL CDecodeMsg_FinalizeSignedContent(CDecodeMsg *msg,
 CRYPT_DER_BLOB *blob)
{
    BOOL ret;
    DWORD i, size;

    ret = CSignedMsgData_AllocateHandles(&msg->u.signed_data);
    for (i = 0; ret && i < msg->u.signed_data.info->cSignerInfo; i++)
        ret = CSignedMsgData_ConstructSignerHandles(&msg->u.signed_data, i,
         msg->crypt_prov);
    if (ret)
    {
        CRYPT_DATA_BLOB *content;

        /* Now that we have all the content, update the hash handles with
         * it.  If the message is a detached message, the content is stored
         * in msg->detached_data rather than in the signed message's
         * content.
         */
        if (msg->base.open_flags & CMSG_DETACHED_FLAG)
            content = &msg->detached_data;
        else
            content = &msg->u.signed_data.info->content.Content;
        if (content->cbData)
        {
            /* If the message is not detached, have to decode the message's
             * content if the type is szOID_RSA_data.
             */
            if (!(msg->base.open_flags & CMSG_DETACHED_FLAG) &&
             !strcmp(msg->u.signed_data.info->content.pszObjId,
             szOID_RSA_data))
            {
                CRYPT_DATA_BLOB *blob;

                ret = CryptDecodeObjectEx(X509_ASN_ENCODING,
                 X509_OCTET_STRING, content->pbData, content->cbData,
2399
                 CRYPT_DECODE_ALLOC_FLAG, NULL, &blob, &size);
2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423
                if (ret)
                {
                    ret = CSignedMsgData_Update(&msg->u.signed_data,
                     blob->pbData, blob->cbData, TRUE, Verify);
                    LocalFree(blob);
                }
            }
            else
                ret = CSignedMsgData_Update(&msg->u.signed_data,
                 content->pbData, content->cbData, TRUE, Verify);
        }
    }
    return ret;
}

static BOOL CDecodeMsg_FinalizeContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob)
{
    BOOL ret = FALSE;

    switch (msg->type)
    {
    case CMSG_HASHED:
        ret = CDecodeMsg_FinalizeHashedContent(msg, blob);
        break;
2424 2425 2426
    case CMSG_ENVELOPED:
        ret = CDecodeMsg_FinalizeEnvelopedContent(msg, blob);
        break;
2427 2428 2429 2430 2431 2432 2433 2434 2435
    case CMSG_SIGNED:
        ret = CDecodeMsg_FinalizeSignedContent(msg, blob);
        break;
    default:
        ret = TRUE;
    }
    return ret;
}

2436 2437 2438
static BOOL CDecodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal)
{
2439
    CDecodeMsg *msg = hCryptMsg;
2440 2441 2442 2443
    BOOL ret = FALSE;

    TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);

2444 2445 2446
    if (msg->base.state == MsgStateFinalized)
        SetLastError(CRYPT_E_MSG_ERROR);
    else if (msg->base.streamed)
2447 2448 2449
    {
        FIXME("(%p, %p, %d, %d): streamed update stub\n", hCryptMsg, pbData,
         cbData, fFinal);
2450
        switch (msg->base.state)
2451
        {
2452 2453 2454
        case MsgStateInit:
            ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
            if (fFinal)
2455
            {
2456 2457 2458 2459
                if (msg->base.open_flags & CMSG_DETACHED_FLAG)
                    msg->base.state = MsgStateDataFinalized;
                else
                    msg->base.state = MsgStateFinalized;
2460 2461
            }
            else
2462 2463 2464 2465 2466
                msg->base.state = MsgStateUpdated;
            break;
        case MsgStateUpdated:
            ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
            if (fFinal)
2467
            {
2468 2469 2470 2471
                if (msg->base.open_flags & CMSG_DETACHED_FLAG)
                    msg->base.state = MsgStateDataFinalized;
                else
                    msg->base.state = MsgStateFinalized;
2472
            }
2473 2474 2475 2476 2477 2478 2479 2480 2481
            break;
        case MsgStateDataFinalized:
            ret = CDecodeMsg_CopyData(&msg->detached_data, pbData, cbData);
            if (fFinal)
                msg->base.state = MsgStateFinalized;
            break;
        default:
            SetLastError(CRYPT_E_MSG_ERROR);
            break;
2482
        }
2483 2484 2485 2486 2487 2488 2489
    }
    else
    {
        if (!fFinal)
            SetLastError(CRYPT_E_MSG_ERROR);
        else
        {
2490
            switch (msg->base.state)
2491
            {
2492
            case MsgStateInit:
2493
                ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
2494 2495 2496 2497
                if (msg->base.open_flags & CMSG_DETACHED_FLAG)
                    msg->base.state = MsgStateDataFinalized;
                else
                    msg->base.state = MsgStateFinalized;
2498 2499 2500
                break;
            case MsgStateDataFinalized:
                ret = CDecodeMsg_CopyData(&msg->detached_data, pbData, cbData);
2501
                msg->base.state = MsgStateFinalized;
2502 2503 2504
                break;
            default:
                SetLastError(CRYPT_E_MSG_ERROR);
2505
            }
2506 2507
        }
    }
2508
    if (ret && fFinal &&
2509 2510 2511 2512
     ((msg->base.open_flags & CMSG_DETACHED_FLAG && msg->base.state ==
     MsgStateDataFinalized) ||
     (!(msg->base.open_flags & CMSG_DETACHED_FLAG) && msg->base.state ==
     MsgStateFinalized)))
2513
        ret = CDecodeMsg_DecodeContent(msg, &msg->msg_data, msg->type);
2514 2515
    if (ret && msg->base.state == MsgStateFinalized)
        ret = CDecodeMsg_FinalizeContent(msg, &msg->msg_data);
2516
    return ret;
2517 2518
}

2519
static BOOL CDecodeHashMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
2520 2521
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
2522 2523 2524 2525 2526
    BOOL ret = FALSE;

    switch (dwParamType)
    {
    case CMSG_TYPE_PARAM:
2527
        ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
2528
        break;
2529 2530 2531 2532 2533 2534 2535 2536 2537 2538
    case CMSG_HASH_ALGORITHM_PARAM:
    {
        CRYPT_DATA_BLOB blob;

        ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
         &blob);
        if (ret)
        {
            ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
            if (ret && pvData)
2539
                CRYPT_FixUpAlgorithmID(pvData);
2540 2541 2542 2543 2544
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    }
2545
    case CMSG_COMPUTED_HASH_PARAM:
2546
        ret = CryptGetHashParam(msg->u.hash, HP_HASHVAL, pvData, pcbData, 0);
2547
        break;
2548 2549 2550 2551 2552 2553 2554 2555
    default:
    {
        CRYPT_DATA_BLOB blob;

        ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
         &blob);
        if (ret)
            ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
2556 2557
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2558
    }
2559 2560
    }
    return ret;
2561 2562
}

2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598
/* nextData is an in/out parameter - on input it's the memory location in
 * which a copy of in's data should be made, and on output it's the memory
 * location immediately after out's copy of in's data.
 */
static inline void CRYPT_CopyBlob(CRYPT_DATA_BLOB *out,
 const CRYPT_DATA_BLOB *in, LPBYTE *nextData)
{
    out->cbData = in->cbData;
    if (in->cbData)
    {
        out->pbData = *nextData;
        memcpy(out->pbData, in->pbData, in->cbData);
        *nextData += in->cbData;
    }
}

static inline void CRYPT_CopyAlgorithmId(CRYPT_ALGORITHM_IDENTIFIER *out,
 const CRYPT_ALGORITHM_IDENTIFIER *in, LPBYTE *nextData)
{
    if (in->pszObjId)
    {
        out->pszObjId = (LPSTR)*nextData;
        strcpy(out->pszObjId, in->pszObjId);
        *nextData += strlen(out->pszObjId) + 1;
    }
    CRYPT_CopyBlob(&out->Parameters, &in->Parameters, nextData);
}

static inline void CRYPT_CopyAttributes(CRYPT_ATTRIBUTES *out,
 const CRYPT_ATTRIBUTES *in, LPBYTE *nextData)
{
    out->cAttr = in->cAttr;
    if (in->cAttr)
    {
        DWORD i;

2599
        *nextData = POINTER_ALIGN_DWORD_PTR(*nextData);
2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614
        out->rgAttr = (CRYPT_ATTRIBUTE *)*nextData;
        *nextData += in->cAttr * sizeof(CRYPT_ATTRIBUTE);
        for (i = 0; i < in->cAttr; i++)
        {
            if (in->rgAttr[i].pszObjId)
            {
                out->rgAttr[i].pszObjId = (LPSTR)*nextData;
                strcpy(out->rgAttr[i].pszObjId, in->rgAttr[i].pszObjId);
                *nextData += strlen(in->rgAttr[i].pszObjId) + 1;
            }
            if (in->rgAttr[i].cValue)
            {
                DWORD j;

                out->rgAttr[i].cValue = in->rgAttr[i].cValue;
2615
                *nextData = POINTER_ALIGN_DWORD_PTR(*nextData);
2616
                out->rgAttr[i].rgValue = (PCRYPT_DATA_BLOB)*nextData;
2617
                *nextData += in->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634
                for (j = 0; j < in->rgAttr[i].cValue; j++)
                    CRYPT_CopyBlob(&out->rgAttr[i].rgValue[j],
                     &in->rgAttr[i].rgValue[j], nextData);
            }
        }
    }
}

static DWORD CRYPT_SizeOfAttributes(const CRYPT_ATTRIBUTES *attr)
{
    DWORD size = attr->cAttr * sizeof(CRYPT_ATTRIBUTE), i, j;

    for (i = 0; i < attr->cAttr; i++)
    {
        if (attr->rgAttr[i].pszObjId)
            size += strlen(attr->rgAttr[i].pszObjId) + 1;
        /* align pointer */
2635
        size = ALIGN_DWORD_PTR(size);
2636 2637 2638 2639
        size += attr->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
        for (j = 0; j < attr->rgAttr[i].cValue; j++)
            size += attr->rgAttr[i].rgValue[j].cbData;
    }
2640
    /* align pointer again to be conservative */
2641
    size = ALIGN_DWORD_PTR(size);
2642 2643 2644
    return size;
}

2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692
static DWORD CRYPT_SizeOfKeyIdAsIssuerAndSerial(const CRYPT_DATA_BLOB *keyId)
{
    static char oid_key_rdn[] = szOID_KEYID_RDN;
    DWORD size = 0;
    CERT_RDN_ATTR attr;
    CERT_RDN rdn = { 1, &attr };
    CERT_NAME_INFO name = { 1, &rdn };

    attr.pszObjId = oid_key_rdn;
    attr.dwValueType = CERT_RDN_OCTET_STRING;
    attr.Value.cbData = keyId->cbData;
    attr.Value.pbData = keyId->pbData;
    if (CryptEncodeObject(X509_ASN_ENCODING, X509_NAME, &name, NULL, &size))
        size++; /* Only include size of special zero serial number on success */
    return size;
}

static BOOL CRYPT_CopyKeyIdAsIssuerAndSerial(CERT_NAME_BLOB *issuer,
 CRYPT_INTEGER_BLOB *serialNumber, const CRYPT_DATA_BLOB *keyId, DWORD encodedLen,
 LPBYTE *nextData)
{
    static char oid_key_rdn[] = szOID_KEYID_RDN;
    CERT_RDN_ATTR attr;
    CERT_RDN rdn = { 1, &attr };
    CERT_NAME_INFO name = { 1, &rdn };
    BOOL ret;

    /* Encode special zero serial number */
    serialNumber->cbData = 1;
    serialNumber->pbData = *nextData;
    **nextData = 0;
    (*nextData)++;
    /* Encode issuer */
    issuer->pbData = *nextData;
    attr.pszObjId = oid_key_rdn;
    attr.dwValueType = CERT_RDN_OCTET_STRING;
    attr.Value.cbData = keyId->cbData;
    attr.Value.pbData = keyId->pbData;
    ret = CryptEncodeObject(X509_ASN_ENCODING, X509_NAME, &name, *nextData,
     &encodedLen);
    if (ret)
    {
        *nextData += encodedLen;
        issuer->cbData = encodedLen;
    }
    return ret;
}

2693
static BOOL CRYPT_CopySignerInfo(void *pvData, DWORD *pcbData,
2694
 const CMSG_CMS_SIGNER_INFO *in)
2695
{
2696
    DWORD size = sizeof(CMSG_SIGNER_INFO), rdnSize = 0;
2697 2698
    BOOL ret;

2699 2700
    TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);

2701 2702
    if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
    {
2703 2704
        size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
        size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2705 2706 2707
    }
    else
    {
2708
        rdnSize = CRYPT_SizeOfKeyIdAsIssuerAndSerial(&in->SignerId.u.KeyId);
2709
        size += rdnSize;
2710
    }
2711 2712 2713 2714 2715 2716 2717 2718
    if (in->HashAlgorithm.pszObjId)
        size += strlen(in->HashAlgorithm.pszObjId) + 1;
    size += in->HashAlgorithm.Parameters.cbData;
    if (in->HashEncryptionAlgorithm.pszObjId)
        size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
    size += in->HashEncryptionAlgorithm.Parameters.cbData;
    size += in->EncryptedHash.cbData;
    /* align pointer */
2719
    size = ALIGN_DWORD_PTR(size);
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735
    size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
    size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
    if (!pvData)
    {
        *pcbData = size;
        ret = TRUE;
    }
    else if (*pcbData < size)
    {
        *pcbData = size;
        SetLastError(ERROR_MORE_DATA);
        ret = FALSE;
    }
    else
    {
        LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_SIGNER_INFO);
2736
        CMSG_SIGNER_INFO *out = pvData;
2737

2738
        ret = TRUE;
2739
        out->dwVersion = in->dwVersion;
2740 2741 2742
        if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
        {
            CRYPT_CopyBlob(&out->Issuer,
2743
             &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2744
            CRYPT_CopyBlob(&out->SerialNumber,
2745
             &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2746
        }
2747 2748
        else
            ret = CRYPT_CopyKeyIdAsIssuerAndSerial(&out->Issuer, &out->SerialNumber,
2749
             &in->SignerId.u.KeyId, rdnSize, &nextData);
2750 2751 2752 2753 2754 2755 2756
        if (ret)
        {
            CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
             &nextData);
            CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
             &in->HashEncryptionAlgorithm, &nextData);
            CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
2757
            nextData = POINTER_ALIGN_DWORD_PTR(nextData);
2758 2759 2760
            CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
            CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
        }
2761
    }
2762
    TRACE("returning %d\n", ret);
2763 2764 2765
    return ret;
}

2766 2767 2768 2769 2770 2771 2772 2773 2774 2775
static BOOL CRYPT_CopyCMSSignerInfo(void *pvData, DWORD *pcbData,
 const CMSG_CMS_SIGNER_INFO *in)
{
    DWORD size = sizeof(CMSG_CMS_SIGNER_INFO);
    BOOL ret;

    TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);

    if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
    {
2776 2777
        size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
        size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2778 2779
    }
    else
2780
        size += in->SignerId.u.KeyId.cbData;
2781 2782 2783 2784 2785 2786 2787 2788
    if (in->HashAlgorithm.pszObjId)
        size += strlen(in->HashAlgorithm.pszObjId) + 1;
    size += in->HashAlgorithm.Parameters.cbData;
    if (in->HashEncryptionAlgorithm.pszObjId)
        size += strlen(in->HashEncryptionAlgorithm.pszObjId) + 1;
    size += in->HashEncryptionAlgorithm.Parameters.cbData;
    size += in->EncryptedHash.cbData;
    /* align pointer */
2789
    size = ALIGN_DWORD_PTR(size);
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805
    size += CRYPT_SizeOfAttributes(&in->AuthAttrs);
    size += CRYPT_SizeOfAttributes(&in->UnauthAttrs);
    if (!pvData)
    {
        *pcbData = size;
        ret = TRUE;
    }
    else if (*pcbData < size)
    {
        *pcbData = size;
        SetLastError(ERROR_MORE_DATA);
        ret = FALSE;
    }
    else
    {
        LPBYTE nextData = (BYTE *)pvData + sizeof(CMSG_CMS_SIGNER_INFO);
2806
        CMSG_CMS_SIGNER_INFO *out = pvData;
2807 2808 2809 2810 2811

        out->dwVersion = in->dwVersion;
        out->SignerId.dwIdChoice = in->SignerId.dwIdChoice;
        if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
        {
2812 2813 2814 2815
            CRYPT_CopyBlob(&out->SignerId.u.IssuerSerialNumber.Issuer,
             &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
            CRYPT_CopyBlob(&out->SignerId.u.IssuerSerialNumber.SerialNumber,
             &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2816 2817
        }
        else
2818
            CRYPT_CopyBlob(&out->SignerId.u.KeyId, &in->SignerId.u.KeyId, &nextData);
2819 2820 2821 2822 2823
        CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
         &nextData);
        CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
         &in->HashEncryptionAlgorithm, &nextData);
        CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
2824
        nextData = POINTER_ALIGN_DWORD_PTR(nextData);
2825 2826 2827 2828 2829 2830 2831 2832
        CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
        CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
        ret = TRUE;
    }
    TRACE("returning %d\n", ret);
    return ret;
}

2833
static BOOL CRYPT_CopySignerCertInfo(void *pvData, DWORD *pcbData,
2834
 const CMSG_CMS_SIGNER_INFO *in)
2835
{
2836
    DWORD size = sizeof(CERT_INFO), rdnSize = 0;
2837 2838
    BOOL ret;

2839 2840
    TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);

2841 2842
    if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
    {
2843 2844
        size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
        size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2845 2846 2847
    }
    else
    {
2848
        rdnSize = CRYPT_SizeOfKeyIdAsIssuerAndSerial(&in->SignerId.u.KeyId);
2849
        size += rdnSize;
2850
    }
2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864
    if (!pvData)
    {
        *pcbData = size;
        ret = TRUE;
    }
    else if (*pcbData < size)
    {
        *pcbData = size;
        SetLastError(ERROR_MORE_DATA);
        ret = FALSE;
    }
    else
    {
        LPBYTE nextData = (BYTE *)pvData + sizeof(CERT_INFO);
2865
        CERT_INFO *out = pvData;
2866 2867

        memset(out, 0, sizeof(CERT_INFO));
2868 2869 2870
        if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
        {
            CRYPT_CopyBlob(&out->Issuer,
2871
             &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2872
            CRYPT_CopyBlob(&out->SerialNumber,
2873
             &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2874 2875 2876 2877
            ret = TRUE;
        }
        else
            ret = CRYPT_CopyKeyIdAsIssuerAndSerial(&out->Issuer, &out->SerialNumber,
2878
             &in->SignerId.u.KeyId, rdnSize, &nextData);
2879
    }
2880
    TRACE("returning %d\n", ret);
2881 2882 2883
    return ret;
}

2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966
static BOOL CRYPT_CopyRecipientInfo(void *pvData, DWORD *pcbData,
 const CERT_ISSUER_SERIAL_NUMBER *in)
{
    DWORD size = sizeof(CERT_INFO);
    BOOL ret;

    TRACE("(%p, %d, %p)\n", pvData, pvData ? *pcbData : 0, in);

    size += in->SerialNumber.cbData;
    size += in->Issuer.cbData;
    if (!pvData)
    {
        *pcbData = size;
        ret = TRUE;
    }
    else if (*pcbData < size)
    {
        *pcbData = size;
        SetLastError(ERROR_MORE_DATA);
        ret = FALSE;
    }
    else
    {
        LPBYTE nextData = (BYTE *)pvData + sizeof(CERT_INFO);
        CERT_INFO *out = pvData;

        CRYPT_CopyBlob(&out->SerialNumber, &in->SerialNumber, &nextData);
        CRYPT_CopyBlob(&out->Issuer, &in->Issuer, &nextData);
        ret = TRUE;
    }
    TRACE("returning %d\n", ret);
    return ret;
}

static BOOL CDecodeEnvelopedMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
    BOOL ret = FALSE;

    switch (dwParamType)
    {
    case CMSG_TYPE_PARAM:
        ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
        break;
    case CMSG_CONTENT_PARAM:
        if (msg->u.enveloped_data.data)
            ret = CRYPT_CopyParam(pvData, pcbData,
             msg->u.enveloped_data.content.pbData,
             msg->u.enveloped_data.content.cbData);
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_RECIPIENT_COUNT_PARAM:
        if (msg->u.enveloped_data.data)
            ret = CRYPT_CopyParam(pvData, pcbData,
             &msg->u.enveloped_data.data->cRecipientInfo, sizeof(DWORD));
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_RECIPIENT_INFO_PARAM:
        if (msg->u.enveloped_data.data)
        {
            if (dwIndex < msg->u.enveloped_data.data->cRecipientInfo)
            {
                PCMSG_KEY_TRANS_RECIPIENT_INFO recipientInfo =
                 &msg->u.enveloped_data.data->rgRecipientInfo[dwIndex];

                ret = CRYPT_CopyRecipientInfo(pvData, pcbData,
                 &recipientInfo->RecipientId.u.IssuerSerialNumber);
            }
            else
                SetLastError(CRYPT_E_INVALID_INDEX);
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    default:
        FIXME("unimplemented for %d\n", dwParamType);
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
    }
    return ret;
}

2967 2968 2969 2970 2971 2972 2973 2974 2975 2976
static BOOL CDecodeSignedMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
    BOOL ret = FALSE;

    switch (dwParamType)
    {
    case CMSG_TYPE_PARAM:
        ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
        break;
2977
    case CMSG_CONTENT_PARAM:
2978
        if (msg->u.signed_data.info)
2979
        {
2980 2981
            if (!strcmp(msg->u.signed_data.info->content.pszObjId,
             szOID_RSA_data))
2982
            {
2983 2984 2985 2986
                CRYPT_DATA_BLOB *blob;
                DWORD size;

                ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
2987 2988
                 msg->u.signed_data.info->content.Content.pbData,
                 msg->u.signed_data.info->content.Content.cbData,
2989
                 CRYPT_DECODE_ALLOC_FLAG, NULL, &blob, &size);
2990 2991 2992 2993 2994 2995
                if (ret)
                {
                    ret = CRYPT_CopyParam(pvData, pcbData, blob->pbData,
                     blob->cbData);
                    LocalFree(blob);
                }
2996
            }
2997 2998
            else
                ret = CRYPT_CopyParam(pvData, pcbData,
2999 3000
                 msg->u.signed_data.info->content.Content.pbData,
                 msg->u.signed_data.info->content.Content.cbData);
3001 3002 3003
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3004 3005
        break;
    case CMSG_INNER_CONTENT_TYPE_PARAM:
3006
        if (msg->u.signed_data.info)
3007
            ret = CRYPT_CopyParam(pvData, pcbData,
3008 3009
             msg->u.signed_data.info->content.pszObjId,
             strlen(msg->u.signed_data.info->content.pszObjId) + 1);
3010 3011
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3012
        break;
3013
    case CMSG_SIGNER_COUNT_PARAM:
3014
        if (msg->u.signed_data.info)
3015
            ret = CRYPT_CopyParam(pvData, pcbData,
3016
             &msg->u.signed_data.info->cSignerInfo, sizeof(DWORD));
3017 3018
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3019 3020
        break;
    case CMSG_SIGNER_INFO_PARAM:
3021
        if (msg->u.signed_data.info)
3022
        {
3023
            if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
3024 3025 3026
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CRYPT_CopySignerInfo(pvData, pcbData,
3027
                 &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
3028 3029 3030
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3031 3032
        break;
    case CMSG_SIGNER_CERT_INFO_PARAM:
3033
        if (msg->u.signed_data.info)
3034
        {
3035
            if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
3036 3037 3038
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CRYPT_CopySignerCertInfo(pvData, pcbData,
3039
                 &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
3040 3041 3042
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
3043 3044
        break;
    case CMSG_CERT_COUNT_PARAM:
3045
        if (msg->u.signed_data.info)
3046
            ret = CRYPT_CopyParam(pvData, pcbData,
3047
             &msg->u.signed_data.info->cCertEncoded, sizeof(DWORD));
3048 3049 3050 3051
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_CERT_PARAM:
3052
        if (msg->u.signed_data.info)
3053
        {
3054
            if (dwIndex >= msg->u.signed_data.info->cCertEncoded)
3055 3056 3057
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CRYPT_CopyParam(pvData, pcbData,
3058 3059
                 msg->u.signed_data.info->rgCertEncoded[dwIndex].pbData,
                 msg->u.signed_data.info->rgCertEncoded[dwIndex].cbData);
3060 3061 3062 3063 3064
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_CRL_COUNT_PARAM:
3065
        if (msg->u.signed_data.info)
3066
            ret = CRYPT_CopyParam(pvData, pcbData,
3067
             &msg->u.signed_data.info->cCrlEncoded, sizeof(DWORD));
3068 3069 3070 3071
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_CRL_PARAM:
3072
        if (msg->u.signed_data.info)
3073
        {
3074
            if (dwIndex >= msg->u.signed_data.info->cCrlEncoded)
3075 3076 3077
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CRYPT_CopyParam(pvData, pcbData,
3078 3079
                 msg->u.signed_data.info->rgCrlEncoded[dwIndex].pbData,
                 msg->u.signed_data.info->rgCrlEncoded[dwIndex].cbData);
3080 3081 3082 3083
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
3084 3085 3086
    case CMSG_COMPUTED_HASH_PARAM:
        if (msg->u.signed_data.info)
        {
3087
            if (dwIndex >= msg->u.signed_data.cSignerHandle)
3088 3089 3090 3091 3092 3093 3094 3095 3096
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CryptGetHashParam(
                 msg->u.signed_data.signerHandles[dwIndex].contentHash,
                 HP_HASHVAL, pvData, pcbData, 0);
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110
    case CMSG_ENCODED_SIGNER:
        if (msg->u.signed_data.info)
        {
            if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CryptEncodeObjectEx(
                 X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, CMS_SIGNER_INFO,
                 &msg->u.signed_data.info->rgSignerInfo[dwIndex], 0, NULL,
                 pvData, pcbData);
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
3111
    case CMSG_ATTR_CERT_COUNT_PARAM:
3112
        if (msg->u.signed_data.info)
3113 3114 3115
        {
            DWORD attrCertCount = 0;

3116
            ret = CRYPT_CopyParam(pvData, pcbData,
3117 3118
             &attrCertCount, sizeof(DWORD));
        }
3119 3120 3121 3122
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_ATTR_CERT_PARAM:
3123
        if (msg->u.signed_data.info)
3124
            SetLastError(CRYPT_E_INVALID_INDEX);
3125 3126 3127
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139
    case CMSG_CMS_SIGNER_INFO_PARAM:
        if (msg->u.signed_data.info)
        {
            if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CRYPT_CopyCMSSignerInfo(pvData, pcbData,
                 &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
3140 3141 3142 3143 3144 3145 3146
    default:
        FIXME("unimplemented for %d\n", dwParamType);
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
    }
    return ret;
}

3147 3148 3149
static BOOL CDecodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
3150
    CDecodeMsg *msg = hCryptMsg;
3151 3152 3153 3154 3155 3156 3157 3158
    BOOL ret = FALSE;

    switch (msg->type)
    {
    case CMSG_HASHED:
        ret = CDecodeHashMsg_GetParam(msg, dwParamType, dwIndex, pvData,
         pcbData);
        break;
3159 3160 3161 3162
    case CMSG_ENVELOPED:
        ret = CDecodeEnvelopedMsg_GetParam(msg, dwParamType, dwIndex, pvData,
         pcbData);
        break;
3163 3164 3165 3166
    case CMSG_SIGNED:
        ret = CDecodeSignedMsg_GetParam(msg, dwParamType, dwIndex, pvData,
         pcbData);
        break;
3167 3168 3169 3170
    default:
        switch (dwParamType)
        {
        case CMSG_TYPE_PARAM:
3171
            ret = CRYPT_CopyParam(pvData, pcbData, &msg->type,
3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190
             sizeof(msg->type));
            break;
        default:
        {
            CRYPT_DATA_BLOB blob;

            ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
             &blob);
            if (ret)
                ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData,
                 blob.cbData);
            else
                SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        }
        }
    }
    return ret;
}

3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
static BOOL CDecodeHashMsg_VerifyHash(CDecodeMsg *msg)
{
    BOOL ret;
    CRYPT_DATA_BLOB hashBlob;

    ret = ContextPropertyList_FindProperty(msg->properties,
     CMSG_HASH_DATA_PARAM, &hashBlob);
    if (ret)
    {
        DWORD computedHashSize = 0;

        ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0, NULL,
         &computedHashSize);
        if (hashBlob.cbData == computedHashSize)
        {
            LPBYTE computedHash = CryptMemAlloc(computedHashSize);

            if (computedHash)
            {
                ret = CDecodeHashMsg_GetParam(msg, CMSG_COMPUTED_HASH_PARAM, 0,
                 computedHash, &computedHashSize);
                if (ret)
3213 3214 3215 3216 3217 3218 3219
                {
                    if (memcmp(hashBlob.pbData, computedHash, hashBlob.cbData))
                    {
                        SetLastError(CRYPT_E_HASH_VALUE);
                        ret = FALSE;
                    }
                }
3220
                CryptMemFree(computedHash);
3221 3222
            }
            else
3223 3224
            {
                SetLastError(ERROR_OUTOFMEMORY);
3225
                ret = FALSE;
3226 3227 3228 3229 3230 3231
            }
        }
        else
        {
            SetLastError(CRYPT_E_HASH_VALUE);
            ret = FALSE;
3232 3233 3234 3235 3236
        }
    }
    return ret;
}

3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268
static BOOL CDecodeSignedMsg_VerifySignatureWithKey(CDecodeMsg *msg,
 HCRYPTPROV prov, DWORD signerIndex, PCERT_PUBLIC_KEY_INFO keyInfo)
{
    HCRYPTKEY key;
    BOOL ret;

    if (!prov)
        prov = msg->crypt_prov;
    ret = CryptImportPublicKeyInfo(prov, X509_ASN_ENCODING, keyInfo, &key);
    if (ret)
    {
        HCRYPTHASH hash;
        CRYPT_HASH_BLOB reversedHash;

        if (msg->u.signed_data.info->rgSignerInfo[signerIndex].AuthAttrs.cAttr)
            hash = msg->u.signed_data.signerHandles[signerIndex].authAttrHash;
        else
            hash = msg->u.signed_data.signerHandles[signerIndex].contentHash;
        ret = CRYPT_ConstructBlob(&reversedHash,
         &msg->u.signed_data.info->rgSignerInfo[signerIndex].EncryptedHash);
        if (ret)
        {
            CRYPT_ReverseBytes(&reversedHash);
            ret = CryptVerifySignatureW(hash, reversedHash.pbData,
             reversedHash.cbData, key, NULL, 0);
            CryptMemFree(reversedHash.pbData);
        }
        CryptDestroyKey(key);
    }
    return ret;
}

3269 3270 3271 3272 3273
static BOOL CDecodeSignedMsg_VerifySignature(CDecodeMsg *msg, PCERT_INFO info)
{
    BOOL ret = FALSE;
    DWORD i;

3274 3275 3276 3277 3278
    if (!msg->u.signed_data.signerHandles)
    {
        SetLastError(NTE_BAD_SIGNATURE);
        return FALSE;
    }
3279 3280
    for (i = 0; !ret && i < msg->u.signed_data.info->cSignerInfo; i++)
    {
3281 3282 3283 3284
        PCMSG_CMS_SIGNER_INFO signerInfo =
         &msg->u.signed_data.info->rgSignerInfo[i];

        if (signerInfo->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
3285
        {
3286
            ret = CertCompareCertificateName(X509_ASN_ENCODING,
3287
             &signerInfo->SignerId.u.IssuerSerialNumber.Issuer,
3288
             &info->Issuer);
3289
            if (ret)
3290 3291
            {
                ret = CertCompareIntegerBlob(
3292
                 &signerInfo->SignerId.u.IssuerSerialNumber.SerialNumber,
3293 3294 3295 3296 3297 3298 3299 3300
                 &info->SerialNumber);
                if (ret)
                    break;
            }
        }
        else
        {
            FIXME("signer %d: unimplemented for key id\n", i);
3301
        }
3302 3303
    }
    if (ret)
3304 3305 3306 3307
        ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, 0, i,
         &info->SubjectPublicKeyInfo);
    else
        SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
3308

3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320
    return ret;
}

static BOOL CDecodeSignedMsg_VerifySignatureEx(CDecodeMsg *msg,
 PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA para)
{
    BOOL ret = FALSE;

    if (para->cbSize != sizeof(CMSG_CTRL_VERIFY_SIGNATURE_EX_PARA))
        SetLastError(ERROR_INVALID_PARAMETER);
    else if (para->dwSignerIndex >= msg->u.signed_data.info->cSignerInfo)
        SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
3321 3322
    else if (!msg->u.signed_data.signerHandles)
        SetLastError(NTE_BAD_SIGNATURE);
3323 3324 3325 3326 3327 3328
    else
    {
        switch (para->dwSignerType)
        {
        case CMSG_VERIFY_SIGNER_PUBKEY:
            ret = CDecodeSignedMsg_VerifySignatureWithKey(msg,
3329
             para->hCryptProv, para->dwSignerIndex, para->pvSigner);
3330 3331
            break;
        case CMSG_VERIFY_SIGNER_CERT:
3332
        {
3333
            PCCERT_CONTEXT cert = para->pvSigner;
3334

3335 3336 3337 3338 3339 3340 3341
            ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, para->hCryptProv,
             para->dwSignerIndex, &cert->pCertInfo->SubjectPublicKeyInfo);
            break;
        }
        default:
            FIXME("unimplemented for signer type %d\n", para->dwSignerType);
            SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
3342 3343 3344 3345 3346
        }
    }
    return ret;
}

3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458
static BOOL WINAPI CRYPT_ImportKeyTrans(
 PCRYPT_ALGORITHM_IDENTIFIER pContentEncryptionAlgorithm,
 PCMSG_CTRL_KEY_TRANS_DECRYPT_PARA pKeyTransDecryptPara, DWORD dwFlags,
 void *pvReserved, HCRYPTKEY *phContentEncryptKey)
{
    BOOL ret;
    HCRYPTKEY key;

    ret = CryptGetUserKey(pKeyTransDecryptPara->hCryptProv,
     pKeyTransDecryptPara->dwKeySpec ? pKeyTransDecryptPara->dwKeySpec :
     AT_KEYEXCHANGE, &key);
    if (ret)
    {
        CMSG_KEY_TRANS_RECIPIENT_INFO *info =
         &pKeyTransDecryptPara->pKeyTrans[pKeyTransDecryptPara->dwRecipientIndex];
        CRYPT_DATA_BLOB *encryptedKey = &info->EncryptedKey;
        DWORD size = encryptedKey->cbData + sizeof(BLOBHEADER) + sizeof(ALG_ID);
        BYTE *keyBlob = CryptMemAlloc(size);

        if (keyBlob)
        {
            DWORD i, k = size - 1;
            BLOBHEADER *blobHeader = (BLOBHEADER *)keyBlob;
            ALG_ID *algID = (ALG_ID *)(keyBlob + sizeof(BLOBHEADER));

            blobHeader->bType = SIMPLEBLOB;
            blobHeader->bVersion = CUR_BLOB_VERSION;
            blobHeader->reserved = 0;
            blobHeader->aiKeyAlg = CertOIDToAlgId(
             pContentEncryptionAlgorithm->pszObjId);
            *algID = CertOIDToAlgId(info->KeyEncryptionAlgorithm.pszObjId);
            for (i = 0; i < encryptedKey->cbData; ++i, --k)
                keyBlob[k] = encryptedKey->pbData[i];

            ret = CryptImportKey(pKeyTransDecryptPara->hCryptProv, keyBlob,
             size, key, 0, phContentEncryptKey);
            CryptMemFree(keyBlob);
        }
        else
            ret = FALSE;
        CryptDestroyKey(key);
    }
    return ret;
}

static BOOL CRYPT_ImportEncryptedKey(PCRYPT_ALGORITHM_IDENTIFIER contEncrAlg,
 PCMSG_CTRL_DECRYPT_PARA para, PCMSG_KEY_TRANS_RECIPIENT_INFO info,
 HCRYPTKEY *key)
{
    static HCRYPTOIDFUNCSET set = NULL;
    PFN_CMSG_IMPORT_KEY_TRANS importKeyFunc = NULL;
    HCRYPTOIDFUNCADDR hFunc = NULL;
    CMSG_CTRL_KEY_TRANS_DECRYPT_PARA decryptPara;
    BOOL ret;

    memset(&decryptPara, 0, sizeof(decryptPara));
    decryptPara.cbSize = sizeof(decryptPara);
    decryptPara.hCryptProv = para->hCryptProv;
    decryptPara.dwKeySpec = para->dwKeySpec;
    decryptPara.pKeyTrans = info;
    decryptPara.dwRecipientIndex = para->dwRecipientIndex;

    if (!set)
        set = CryptInitOIDFunctionSet(CMSG_OID_IMPORT_KEY_TRANS_FUNC, 0);
    CryptGetOIDFunctionAddress(set, X509_ASN_ENCODING, contEncrAlg->pszObjId, 0,
     (void **)&importKeyFunc, &hFunc);
    if (!importKeyFunc)
        importKeyFunc = CRYPT_ImportKeyTrans;
    ret = importKeyFunc(contEncrAlg, &decryptPara, 0, NULL, key);
    if (hFunc)
        CryptFreeOIDFunctionAddress(hFunc, 0);
    return ret;
}

static BOOL CDecodeEnvelopedMsg_CrtlDecrypt(CDecodeMsg *msg,
 PCMSG_CTRL_DECRYPT_PARA para)
{
    BOOL ret = FALSE;
    CEnvelopedDecodeMsg *enveloped_data = &msg->u.enveloped_data;
    CRYPT_ENVELOPED_DATA *data = enveloped_data->data;

    if (para->cbSize != sizeof(CMSG_CTRL_DECRYPT_PARA))
        SetLastError(E_INVALIDARG);
    else if (!data)
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
    else if (para->dwRecipientIndex >= data->cRecipientInfo)
        SetLastError(CRYPT_E_INVALID_INDEX);
    else if (enveloped_data->decrypted)
        SetLastError(CRYPT_E_ALREADY_DECRYPTED);
    else if (!para->hCryptProv)
        SetLastError(ERROR_INVALID_PARAMETER);
    else if (enveloped_data->content.cbData)
    {
        HCRYPTKEY key;

        ret = CRYPT_ImportEncryptedKey(
         &data->encryptedContentInfo.contentEncryptionAlgorithm, para,
         data->rgRecipientInfo, &key);
        if (ret)
        {
            ret = CryptDecrypt(key, 0, TRUE, 0, enveloped_data->content.pbData,
             &enveloped_data->content.cbData);
            CryptDestroyKey(key);
        }
    }
    else
        ret = TRUE;
    if (ret)
        enveloped_data->decrypted = TRUE;
    return ret;
}

3459 3460 3461
static BOOL CDecodeMsg_Control(HCRYPTMSG hCryptMsg, DWORD dwFlags,
 DWORD dwCtrlType, const void *pvCtrlPara)
{
3462
    CDecodeMsg *msg = hCryptMsg;
3463 3464 3465 3466 3467 3468 3469 3470
    BOOL ret = FALSE;

    switch (dwCtrlType)
    {
    case CMSG_CTRL_VERIFY_SIGNATURE:
        switch (msg->type)
        {
        case CMSG_SIGNED:
3471
            ret = CDecodeSignedMsg_VerifySignature(msg, (PCERT_INFO)pvCtrlPara);
3472 3473 3474 3475 3476 3477 3478 3479
            break;
        default:
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        }
        break;
    case CMSG_CTRL_DECRYPT:
        switch (msg->type)
        {
3480 3481 3482 3483 3484 3485 3486
        case CMSG_ENVELOPED:
            ret = CDecodeEnvelopedMsg_CrtlDecrypt(msg,
             (PCMSG_CTRL_DECRYPT_PARA)pvCtrlPara);
            if (ret && (dwFlags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG))
                msg->u.enveloped_data.crypt_prov =
                 ((PCMSG_CTRL_DECRYPT_PARA)pvCtrlPara)->hCryptProv;
            break;
3487 3488 3489 3490 3491 3492 3493 3494
        default:
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        }
        break;
    case CMSG_CTRL_VERIFY_HASH:
        switch (msg->type)
        {
        case CMSG_HASHED:
3495
            ret = CDecodeHashMsg_VerifyHash(msg);
3496 3497 3498 3499 3500
            break;
        default:
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        }
        break;
3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511
    case CMSG_CTRL_VERIFY_SIGNATURE_EX:
        switch (msg->type)
        {
        case CMSG_SIGNED:
            ret = CDecodeSignedMsg_VerifySignatureEx(msg,
             (PCMSG_CTRL_VERIFY_SIGNATURE_EX_PARA)pvCtrlPara);
            break;
        default:
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        }
        break;
3512 3513 3514 3515 3516 3517
    default:
        SetLastError(CRYPT_E_CONTROL_TYPE);
    }
    return ret;
}

3518
HCRYPTMSG WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags,
3519
 DWORD dwMsgType, HCRYPTPROV_LEGACY hCryptProv, PCERT_INFO pRecipientInfo,
3520 3521
 PCMSG_STREAM_INFO pStreamInfo)
{
3522 3523 3524
    CDecodeMsg *msg;

    TRACE("(%08x, %08x, %08x, %08lx, %p, %p)\n", dwMsgEncodingType,
3525
     dwFlags, dwMsgType, hCryptProv, pRecipientInfo, pStreamInfo);
3526 3527 3528 3529 3530 3531

    if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
    {
        SetLastError(E_INVALIDARG);
        return NULL;
    }
3532 3533 3534 3535
    msg = CryptMemAlloc(sizeof(CDecodeMsg));
    if (msg)
    {
        CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
3536
         CDecodeMsg_Close, CDecodeMsg_GetParam, CDecodeMsg_Update,
3537
         CDecodeMsg_Control);
3538
        msg->type = dwMsgType;
3539 3540 3541 3542 3543 3544 3545
        if (hCryptProv)
            msg->crypt_prov = hCryptProv;
        else
        {
            msg->crypt_prov = CRYPT_GetDefaultProvider();
            msg->base.open_flags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
        }
3546
        memset(&msg->u, 0, sizeof(msg->u));
3547 3548
        msg->msg_data.cbData = 0;
        msg->msg_data.pbData = NULL;
3549 3550
        msg->detached_data.cbData = 0;
        msg->detached_data.pbData = NULL;
3551
        msg->properties = ContextPropertyList_Create();
3552 3553
    }
    return msg;
3554 3555 3556 3557
}

HCRYPTMSG WINAPI CryptMsgDuplicate(HCRYPTMSG hCryptMsg)
{
3558 3559 3560 3561
    TRACE("(%p)\n", hCryptMsg);

    if (hCryptMsg)
    {
3562
        CryptMsgBase *msg = hCryptMsg;
3563 3564 3565

        InterlockedIncrement(&msg->ref);
    }
3566 3567 3568 3569 3570
    return hCryptMsg;
}

BOOL WINAPI CryptMsgClose(HCRYPTMSG hCryptMsg)
{
3571 3572 3573 3574
    TRACE("(%p)\n", hCryptMsg);

    if (hCryptMsg)
    {
3575
        CryptMsgBase *msg = hCryptMsg;
3576 3577 3578 3579 3580 3581 3582 3583 3584

        if (InterlockedDecrement(&msg->ref) == 0)
        {
            TRACE("freeing %p\n", msg);
            if (msg->close)
                msg->close(msg);
            CryptMemFree(msg);
        }
    }
3585 3586 3587 3588 3589 3590
    return TRUE;
}

BOOL WINAPI CryptMsgUpdate(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal)
{
3591
    CryptMsgBase *msg = hCryptMsg;
3592 3593

    TRACE("(%p, %p, %d, %d)\n", hCryptMsg, pbData, cbData, fFinal);
3594

3595
    return msg->update(hCryptMsg, pbData, cbData, fFinal);
3596 3597 3598 3599 3600
}

BOOL WINAPI CryptMsgGetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
3601
    CryptMsgBase *msg = hCryptMsg;
3602 3603

    TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
3604
     pvData, pcbData);
3605
    return msg->get_param(hCryptMsg, dwParamType, dwIndex, pvData, pcbData);
3606
}
3607 3608 3609 3610

BOOL WINAPI CryptMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
 DWORD dwCtrlType, const void *pvCtrlPara)
{
3611
    CryptMsgBase *msg = hCryptMsg;
3612 3613

    TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType,
3614
     pvCtrlPara);
3615
    return msg->control(hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
3616
}
3617

3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
static CERT_INFO *CRYPT_GetSignerCertInfoFromMsg(HCRYPTMSG msg,
 DWORD dwSignerIndex)
{
    CERT_INFO *certInfo = NULL;
    DWORD size;

    if (CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM, dwSignerIndex, NULL,
     &size))
    {
        certInfo = CryptMemAlloc(size);
        if (certInfo)
        {
            if (!CryptMsgGetParam(msg, CMSG_SIGNER_CERT_INFO_PARAM,
             dwSignerIndex, certInfo, &size))
            {
                CryptMemFree(certInfo);
                certInfo = NULL;
            }
        }
    }
    return certInfo;
}

3641 3642 3643 3644
BOOL WINAPI CryptMsgGetAndVerifySigner(HCRYPTMSG hCryptMsg, DWORD cSignerStore,
 HCERTSTORE *rghSignerStore, DWORD dwFlags, PCCERT_CONTEXT *ppSigner,
 DWORD *pdwSignerIndex)
{
3645
    HCERTSTORE store;
3646
    DWORD i, signerIndex = 0;
3647 3648 3649 3650
    PCCERT_CONTEXT signerCert = NULL;
    BOOL ret = FALSE;

    TRACE("(%p, %d, %p, %08x, %p, %p)\n", hCryptMsg, cSignerStore,
3651
     rghSignerStore, dwFlags, ppSigner, pdwSignerIndex);
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731

    /* Clear output parameters */
    if (ppSigner)
        *ppSigner = NULL;
    if (pdwSignerIndex && !(dwFlags & CMSG_USE_SIGNER_INDEX_FLAG))
        *pdwSignerIndex = 0;

    /* Create store to search for signer certificates */
    store = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0, 0,
     CERT_STORE_CREATE_NEW_FLAG, NULL);
    if (!(dwFlags & CMSG_TRUSTED_SIGNER_FLAG))
    {
        HCERTSTORE msgStore = CertOpenStore(CERT_STORE_PROV_MSG, 0, 0, 0,
         hCryptMsg);

        CertAddStoreToCollection(store, msgStore, 0, 0);
        CertCloseStore(msgStore, 0);
    }
    for (i = 0; i < cSignerStore; i++)
        CertAddStoreToCollection(store, rghSignerStore[i], 0, 0);

    /* Find signer cert */
    if (dwFlags & CMSG_USE_SIGNER_INDEX_FLAG)
    {
        CERT_INFO *signer = CRYPT_GetSignerCertInfoFromMsg(hCryptMsg,
         *pdwSignerIndex);

        if (signer)
        {
            signerIndex = *pdwSignerIndex;
            signerCert = CertFindCertificateInStore(store, X509_ASN_ENCODING,
             0, CERT_FIND_SUBJECT_CERT, signer, NULL);
            CryptMemFree(signer);
        }
    }
    else
    {
        DWORD count, size = sizeof(count);

        if (CryptMsgGetParam(hCryptMsg, CMSG_SIGNER_COUNT_PARAM, 0, &count,
         &size))
        {
            for (i = 0; !signerCert && i < count; i++)
            {
                CERT_INFO *signer = CRYPT_GetSignerCertInfoFromMsg(hCryptMsg,
                 i);

                if (signer)
                {
                    signerCert = CertFindCertificateInStore(store,
                     X509_ASN_ENCODING, 0, CERT_FIND_SUBJECT_CERT, signer,
                     NULL);
                    if (signerCert)
                        signerIndex = i;
                    CryptMemFree(signer);
                }
            }
        }
        if (!signerCert)
            SetLastError(CRYPT_E_NO_TRUSTED_SIGNER);
    }
    if (signerCert)
    {
        if (!(dwFlags & CMSG_SIGNER_ONLY_FLAG))
            ret = CryptMsgControl(hCryptMsg, 0, CMSG_CTRL_VERIFY_SIGNATURE,
             signerCert->pCertInfo);
        else
            ret = TRUE;
        if (ret)
        {
            if (ppSigner)
                *ppSigner = CertDuplicateCertificateContext(signerCert);
            if (pdwSignerIndex)
                *pdwSignerIndex = signerIndex;
        }
        CertFreeCertificateContext(signerCert);
    }

    CertCloseStore(store, 0);
    return ret;
3732
}
3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743

BOOL WINAPI CryptMsgVerifyCountersignatureEncodedEx(HCRYPTPROV_LEGACY hCryptProv,
 DWORD dwEncodingType, PBYTE pbSignerInfo, DWORD cbSignerInfo,
 PBYTE pbSignerInfoCountersignature, DWORD cbSignerInfoCountersignature,
 DWORD dwSignerType, void *pvSigner, DWORD dwFlags, void *pvReserved)
{
    FIXME("(%08lx, %08x, %p, %d, %p, %d, %d, %p, %08x, %p): stub\n", hCryptProv,
     dwEncodingType, pbSignerInfo, cbSignerInfo, pbSignerInfoCountersignature,
     cbSignerInfoCountersignature, dwSignerType, pvSigner, dwFlags, pvReserved);
    return FALSE;
}
3744 3745 3746 3747 3748

BOOL WINAPI CryptMsgEncodeAndSignCTL(DWORD dwMsgEncodingType,
 PCTL_INFO pCtlInfo, PCMSG_SIGNED_ENCODE_INFO pSignInfo, DWORD dwFlags,
 BYTE *pbEncoded, DWORD *pcbEncoded)
{
3749 3750 3751 3752 3753
    BOOL ret;
    BYTE *pbCtlContent;
    DWORD cbCtlContent;

    TRACE("(%08x, %p, %p, %08x, %p, %p)\n", dwMsgEncodingType, pCtlInfo,
3754
     pSignInfo, dwFlags, pbEncoded, pcbEncoded);
3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768

    if (dwFlags)
    {
        FIXME("unimplemented for flags %08x\n", dwFlags);
        return FALSE;
    }
    if ((ret = CryptEncodeObjectEx(dwMsgEncodingType, PKCS_CTL, pCtlInfo,
     CRYPT_ENCODE_ALLOC_FLAG, NULL, &pbCtlContent, &cbCtlContent)))
    {
        ret = CryptMsgSignCTL(dwMsgEncodingType, pbCtlContent, cbCtlContent,
         pSignInfo, dwFlags, pbEncoded, pcbEncoded);
        LocalFree(pbCtlContent);
    }
    return ret;
3769
}
3770 3771 3772 3773 3774

BOOL WINAPI CryptMsgSignCTL(DWORD dwMsgEncodingType, BYTE *pbCtlContent,
 DWORD cbCtlContent, PCMSG_SIGNED_ENCODE_INFO pSignInfo, DWORD dwFlags,
 BYTE *pbEncoded, DWORD *pcbEncoded)
{
3775 3776 3777 3778 3779
    static char oid_ctl[] = szOID_CTL;
    BOOL ret;
    HCRYPTMSG msg;

    TRACE("(%08x, %p, %d, %p, %08x, %p, %p)\n", dwMsgEncodingType,
3780
     pbCtlContent, cbCtlContent, pSignInfo, dwFlags, pbEncoded, pcbEncoded);
3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799

    if (dwFlags)
    {
        FIXME("unimplemented for flags %08x\n", dwFlags);
        return FALSE;
    }
    msg = CryptMsgOpenToEncode(dwMsgEncodingType, 0, CMSG_SIGNED, pSignInfo,
     oid_ctl, NULL);
    if (msg)
    {
        ret = CryptMsgUpdate(msg, pbCtlContent, cbCtlContent, TRUE);
        if (ret)
            ret = CryptMsgGetParam(msg, CMSG_CONTENT_PARAM, 0, pbEncoded,
             pcbEncoded);
        CryptMsgClose(msg);
    }
    else
        ret = FALSE;
    return ret;
3800
}