msg.c 92.4 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 148 149 150 151 152 153 154
             &lenBytes);
        }
    }
    return ret;
}

static BOOL CRYPT_EncodeDataContentInfoHeader(CDataEncodeMsg *msg,
 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 626 627
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;

static BOOL CRYPT_IsValidSigner(CMSG_SIGNER_ENCODE_INFO_WITH_CMS *signer)
{
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 723 724 725 726 727
typedef struct _BlobArray
{
    DWORD            cBlobs;
    PCRYPT_DATA_BLOB blobs;
} BlobArray;

728
static BOOL CRYPT_ConstructBlobArray(BlobArray *out, const BlobArray *in)
729 730 731
{
    BOOL ret = TRUE;

732 733
    out->cBlobs = in->cBlobs;
    if (out->cBlobs)
734
    {
735 736
        out->blobs = CryptMemAlloc(out->cBlobs * sizeof(CRYPT_DATA_BLOB));
        if (out->blobs)
737 738 739
        {
            DWORD i;

740 741
            memset(out->blobs, 0, out->cBlobs * sizeof(CRYPT_DATA_BLOB));
            for (i = 0; ret && i < out->cBlobs; i++)
742
                ret = CRYPT_ConstructBlob(&out->blobs[i], &in->blobs[i]);
743 744 745 746 747 748 749
        }
        else
            ret = FALSE;
    }
    return ret;
}

750 751 752 753 754 755 756 757 758
static void CRYPT_FreeBlobArray(BlobArray *array)
{
    DWORD i;

    for (i = 0; i < array->cBlobs; i++)
        CryptMemFree(array->blobs[i].pbData);
    CryptMemFree(array->blobs);
}

759 760
static BOOL CRYPT_ConstructAttribute(CRYPT_ATTRIBUTE *out,
 const CRYPT_ATTRIBUTE *in)
761
{
762 763 764 765 766 767
    BOOL ret;

    out->pszObjId = CryptMemAlloc(strlen(in->pszObjId) + 1);
    if (out->pszObjId)
    {
        strcpy(out->pszObjId, in->pszObjId);
768
        ret = CRYPT_ConstructBlobArray((BlobArray *)&out->cValue,
769 770 771 772 773
         (const BlobArray *)&in->cValue);
    }
    else
        ret = FALSE;
    return ret;
774 775
}

776
static BOOL CRYPT_ConstructAttributes(CRYPT_ATTRIBUTES *out,
777 778 779 780 781 782 783 784 785 786 787 788 789 790
 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++)
791
                ret = CRYPT_ConstructAttribute(&out->rgAttr[i], &in->rgAttr[i]);
792 793 794 795 796 797 798 799 800
        }
        else
            ret = FALSE;
    }
    else
        out->rgAttr = NULL;
    return ret;
}

801 802 803
/* 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)
804 805 806
{
    BOOL ret;

807 808 809
    if (in->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO))
    {
        info->dwVersion = CMSG_SIGNER_INFO_V1;
810
        ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
811 812 813
         &in->pCertInfo->Issuer);
        if (ret)
            ret = CRYPT_ConstructBlob(
814
             &info->SignerId.u.IssuerSerialNumber.SerialNumber,
815 816 817 818 819 820 821 822 823 824 825
             &in->pCertInfo->SerialNumber);
        info->SignerId.dwIdChoice = CERT_ID_ISSUER_SERIAL_NUMBER;
    }
    else
    {
        /* Implicitly in->cbSize == sizeof(CMSG_SIGNER_ENCODE_INFO_WITH_CMS).
         * See CRYPT_IsValidSigner.
         */
        if (!in->SignerId.dwIdChoice)
        {
            info->dwVersion = CMSG_SIGNER_INFO_V1;
826
            ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
827 828 829
             &in->pCertInfo->Issuer);
            if (ret)
                ret = CRYPT_ConstructBlob(
830
                 &info->SignerId.u.IssuerSerialNumber.SerialNumber,
831 832 833 834 835 836 837
                 &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;
838 839
            ret = CRYPT_ConstructBlob(&info->SignerId.u.IssuerSerialNumber.Issuer,
             &in->SignerId.u.IssuerSerialNumber.Issuer);
840 841
            if (ret)
                ret = CRYPT_ConstructBlob(
842 843
                 &info->SignerId.u.IssuerSerialNumber.SerialNumber,
                 &in->SignerId.u.IssuerSerialNumber.SerialNumber);
844 845 846 847 848 849
        }
        else
        {
            /* Implicitly dwIdChoice == CERT_ID_KEY_IDENTIFIER */
            info->dwVersion = CMSG_SIGNER_INFO_V3;
            info->SignerId.dwIdChoice = CERT_ID_KEY_IDENTIFIER;
850 851
            ret = CRYPT_ConstructBlob(&info->SignerId.u.KeyId,
             &in->SignerId.u.KeyId);
852 853
        }
    }
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
    /* 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);
    memset(&info->HashEncryptionAlgorithm, 0,
     sizeof(info->HashEncryptionAlgorithm));
    if (ret)
        ret = CRYPT_ConstructAttributes(&info->AuthAttrs,
         (CRYPT_ATTRIBUTES *)&in->cAuthAttr);
    if (ret)
        ret = CRYPT_ConstructAttributes(&info->UnauthAttrs,
         (CRYPT_ATTRIBUTES *)&in->cUnauthAttr);
869 870 871
    return ret;
}

872
static void CSignerInfo_Free(CMSG_CMS_SIGNER_INFO *info)
873 874 875
{
    DWORD i, j;

876 877
    if (info->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
    {
878 879
        CryptMemFree(info->SignerId.u.IssuerSerialNumber.Issuer.pbData);
        CryptMemFree(info->SignerId.u.IssuerSerialNumber.SerialNumber.pbData);
880 881
    }
    else
882
        CryptMemFree(info->SignerId.u.KeyId.pbData);
883 884 885
    CryptMemFree(info->HashAlgorithm.Parameters.pbData);
    CryptMemFree(info->EncryptedHash.pbData);
    for (i = 0; i < info->AuthAttrs.cAttr; i++)
886
    {
887 888 889
        for (j = 0; j < info->AuthAttrs.rgAttr[i].cValue; j++)
            CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue[j].pbData);
        CryptMemFree(info->AuthAttrs.rgAttr[i].rgValue);
890
        CryptMemFree(info->AuthAttrs.rgAttr[i].pszObjId);
891
    }
892 893
    CryptMemFree(info->AuthAttrs.rgAttr);
    for (i = 0; i < info->UnauthAttrs.cAttr; i++)
894
    {
895 896 897
        for (j = 0; j < info->UnauthAttrs.rgAttr[i].cValue; j++)
            CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue[j].pbData);
        CryptMemFree(info->UnauthAttrs.rgAttr[i].rgValue);
898
        CryptMemFree(info->UnauthAttrs.rgAttr[i].pszObjId);
899
    }
900
    CryptMemFree(info->UnauthAttrs.rgAttr);
901 902
}

903 904 905 906 907 908
typedef struct _CSignerHandles
{
    HCRYPTHASH contentHash;
    HCRYPTHASH authAttrHash;
} CSignerHandles;

909 910 911
typedef struct _CSignedMsgData
{
    CRYPT_SIGNED_INFO *info;
912
    DWORD              cSignerHandle;
913 914 915
    CSignerHandles    *signerHandles;
} CSignedMsgData;

916 917 918
/* 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.
919
 */
920 921
static BOOL CSignedMsgData_ConstructSignerHandles(CSignedMsgData *msg_data,
 DWORD signerIndex, HCRYPTPROV crypt_prov)
922 923 924 925
{
    ALG_ID algID;
    BOOL ret;

926 927 928 929 930 931 932
    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);
933 934 935
    return ret;
}

936 937 938 939 940 941 942 943 944 945 946 947
/* 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)
948 949
        {
            msg_data->cSignerHandle = msg_data->info->cSignerInfo;
950 951
            memset(msg_data->signerHandles, 0,
             msg_data->info->cSignerInfo * sizeof(CSignerHandles));
952
        }
953
        else
954 955
        {
            msg_data->cSignerHandle = 0;
956
            ret = FALSE;
957
        }
958 959
    }
    else
960 961
    {
        msg_data->cSignerHandle = 0;
962
        msg_data->signerHandles = NULL;
963
    }
964 965 966
    return ret;
}

967 968 969 970
static void CSignedMsgData_CloseHandles(CSignedMsgData *msg_data)
{
    DWORD i;

971
    for (i = 0; i < msg_data->cSignerHandle; i++)
972
    {
973 974 975 976
        if (msg_data->signerHandles[i].contentHash)
            CryptDestroyHash(msg_data->signerHandles[i].contentHash);
        if (msg_data->signerHandles[i].authAttrHash)
            CryptDestroyHash(msg_data->signerHandles[i].authAttrHash);
977 978
    }
    CryptMemFree(msg_data->signerHandles);
979 980
    msg_data->signerHandles = NULL;
    msg_data->cSignerHandle = 0;
981 982
}

983 984 985 986 987 988
static BOOL CSignedMsgData_UpdateHash(CSignedMsgData *msg_data,
 const BYTE *pbData, DWORD cbData)
{
    DWORD i;
    BOOL ret = TRUE;

989
    for (i = 0; ret && i < msg_data->cSignerHandle; i++)
990 991 992 993 994
        ret = CryptHashData(msg_data->signerHandles[i].contentHash, pbData,
         cbData, 0);
    return ret;
}

995 996 997 998 999 1000 1001 1002 1003
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)
    {
1004
        ret = CRYPT_ConstructAttribute(&out->rgAttr[out->cAttr], in);
1005 1006 1007 1008 1009 1010
        if (ret)
            out->cAttr++;
    }
    return ret;
}

1011 1012
static BOOL CSignedMsgData_AppendMessageDigestAttribute(
 CSignedMsgData *msg_data, DWORD signerIndex)
1013 1014 1015 1016 1017 1018 1019 1020
{
    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);
1021
    ret = CryptGetHashParam(
1022
     msg_data->signerHandles[signerIndex].contentHash, HP_HASHSIZE,
1023
     (LPBYTE)&hash.cbData, &size, 0);
1024 1025 1026
    if (ret)
    {
        hash.pbData = CryptMemAlloc(hash.cbData);
1027
        ret = CryptGetHashParam(
1028
         msg_data->signerHandles[signerIndex].contentHash, HP_HASHVAL,
1029
         hash.pbData, &hash.cbData, 0);
1030 1031 1032 1033 1034 1035 1036
        if (ret)
        {
            ret = CRYPT_AsnEncodeOctets(0, NULL, &hash, CRYPT_ENCODE_ALLOC_FLAG,
             NULL, (LPBYTE)&encodedHash.pbData, &encodedHash.cbData);
            if (ret)
            {
                ret = CRYPT_AppendAttribute(
1037
                 &msg_data->info->rgSignerInfo[signerIndex].AuthAttrs,
1038 1039 1040 1041 1042 1043 1044 1045 1046
                 &messageDigestAttr);
                LocalFree(encodedHash.pbData);
            }
        }
        CryptMemFree(hash.pbData);
    }
    return ret;
}

1047 1048 1049 1050 1051
typedef enum {
    Sign,
    Verify
} SignOrVerify;

1052
static BOOL CSignedMsgData_UpdateAuthenticatedAttributes(
1053
 CSignedMsgData *msg_data, SignOrVerify flag)
1054 1055 1056 1057
{
    DWORD i;
    BOOL ret = TRUE;

1058
    TRACE("(%p)\n", msg_data);
1059

1060
    for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
1061
    {
1062
        if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
1063
        {
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
            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);
            }
1080 1081 1082 1083 1084 1085
            if (ret)
            {
                LPBYTE encodedAttrs;
                DWORD size;

                ret = CryptEncodeObjectEx(X509_ASN_ENCODING, PKCS_ATTRIBUTES,
1086
                 &msg_data->info->rgSignerInfo[i].AuthAttrs,
1087
                 CRYPT_ENCODE_ALLOC_FLAG, NULL, &encodedAttrs, &size);
1088 1089
                if (ret)
                {
1090
                    ret = CryptHashData(
1091
                     msg_data->signerHandles[i].authAttrHash, encodedAttrs,
1092
                     size, 0);
1093 1094 1095 1096 1097 1098
                    LocalFree(encodedAttrs);
                }
            }
        }
    }
    TRACE("returning %d\n", ret);
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
    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;
    }
}

1115
static BOOL CSignedMsgData_Sign(CSignedMsgData *msg_data)
1116 1117 1118 1119
{
    DWORD i;
    BOOL ret = TRUE;

1120
    TRACE("(%p)\n", msg_data);
1121

1122
    for (i = 0; ret && i < msg_data->info->cSignerInfo; i++)
1123
    {
1124 1125
        HCRYPTHASH hash;

1126 1127
        if (msg_data->info->rgSignerInfo[i].AuthAttrs.cAttr)
            hash = msg_data->signerHandles[i].authAttrHash;
1128
        else
1129
            hash = msg_data->signerHandles[i].contentHash;
1130
        ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0, NULL,
1131
         &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1132 1133
        if (ret)
        {
1134
            msg_data->info->rgSignerInfo[i].EncryptedHash.pbData =
1135
             CryptMemAlloc(
1136 1137
             msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
            if (msg_data->info->rgSignerInfo[i].EncryptedHash.pbData)
1138
            {
1139
                ret = CryptSignHashW(hash, AT_SIGNATURE, NULL, 0,
1140 1141
                 msg_data->info->rgSignerInfo[i].EncryptedHash.pbData,
                 &msg_data->info->rgSignerInfo[i].EncryptedHash.cbData);
1142
                if (ret)
1143
                    CRYPT_ReverseBytes(
1144
                     &msg_data->info->rgSignerInfo[i].EncryptedHash);
1145 1146 1147 1148 1149 1150 1151 1152
            }
            else
                ret = FALSE;
        }
    }
    return ret;
}

1153
static BOOL CSignedMsgData_Update(CSignedMsgData *msg_data,
1154
 const BYTE *pbData, DWORD cbData, BOOL fFinal, SignOrVerify flag)
1155 1156 1157 1158 1159
{
    BOOL ret = CSignedMsgData_UpdateHash(msg_data, pbData, cbData);

    if (ret && fFinal)
    {
1160 1161
        ret = CSignedMsgData_UpdateAuthenticatedAttributes(msg_data, flag);
        if (ret && flag == Sign)
1162 1163 1164 1165 1166
            ret = CSignedMsgData_Sign(msg_data);
    }
    return ret;
}

1167 1168 1169
typedef struct _CSignedEncodeMsg
{
    CryptMsgBase    base;
1170
    LPSTR           innerOID;
1171 1172 1173 1174 1175 1176
    CRYPT_DATA_BLOB data;
    CSignedMsgData  msg_data;
} CSignedEncodeMsg;

static void CSignedEncodeMsg_Close(HCRYPTMSG hCryptMsg)
{
1177
    CSignedEncodeMsg *msg = hCryptMsg;
1178 1179
    DWORD i;

1180
    CryptMemFree(msg->innerOID);
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
    CryptMemFree(msg->data.pbData);
    CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCertEncoded);
    CRYPT_FreeBlobArray((BlobArray *)&msg->msg_data.info->cCrlEncoded);
    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)
{
1194
    CSignedEncodeMsg *msg = hCryptMsg;
1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 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
    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;
1230
        BOOL freeContent = FALSE;
1231

1232
        info = *msg->msg_data.info;
1233
        if (!msg->innerOID || !strcmp(msg->innerOID, szOID_RSA_data))
1234
        {
1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
            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 };
1245

1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
                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;
            }
1257 1258 1259
        }
        else
        {
1260 1261 1262
            info.content.pszObjId = msg->innerOID;
            info.content.Content.cbData = msg->data.cbData;
            info.content.Content.pbData = msg->data.pbData;
1263 1264 1265 1266
            ret = TRUE;
        }
        if (ret)
        {
1267
            ret = CRYPT_AsnEncodeCMSSignedInfo(&info, pvData, pcbData);
1268 1269
            if (freeContent)
                LocalFree(info.content.Content.pbData);
1270 1271 1272 1273
        }
        break;
    }
    case CMSG_COMPUTED_HASH_PARAM:
1274
        if (dwIndex >= msg->msg_data.cSignerHandle)
1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285
            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,
1286
             CMS_SIGNER_INFO, &msg->msg_data.info->rgSignerInfo[dwIndex], 0,
1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
             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;
}

1299 1300 1301
static BOOL CSignedEncodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal)
{
1302
    CSignedEncodeMsg *msg = hCryptMsg;
1303 1304
    BOOL ret = FALSE;

1305 1306 1307
    if (msg->base.state == MsgStateFinalized)
        SetLastError(CRYPT_E_MSG_ERROR);
    else if (msg->base.streamed || (msg->base.open_flags & CMSG_DETACHED_FLAG))
1308
    {
1309 1310
        ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData, fFinal,
         Sign);
1311 1312
        if (msg->base.streamed)
            FIXME("streamed partial stub\n");
1313
        msg->base.state = fFinal ? MsgStateFinalized : MsgStateUpdated;
1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
    }
    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)
1334
                ret = CSignedMsgData_Update(&msg->msg_data, pbData, cbData,
1335
                 fFinal, Sign);
1336
            msg->base.state = MsgStateFinalized;
1337 1338 1339
        }
    }
    return ret;
1340 1341 1342
}

static HCRYPTMSG CSignedEncodeMsg_Open(DWORD dwFlags,
1343
 const void *pvMsgEncodeInfo, LPCSTR pszInnerContentObjID,
1344 1345
 PCMSG_STREAM_INFO pStreamInfo)
{
1346
    const CMSG_SIGNED_ENCODE_INFO_WITH_CMS *info = pvMsgEncodeInfo;
1347 1348 1349 1350 1351 1352 1353 1354 1355
    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;
    }
1356
    if (info->cbSize == sizeof(CMSG_SIGNED_ENCODE_INFO_WITH_CMS) &&
Juan Lang's avatar
Juan Lang committed
1357
     info->cAttrCertEncoded)
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
    {
        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)
    {
1368 1369
        BOOL ret = TRUE;

1370 1371
        CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
         CSignedEncodeMsg_Close, CSignedEncodeMsg_GetParam,
1372
         CSignedEncodeMsg_Update, CRYPT_DefaultMsgControl);
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382
        if (pszInnerContentObjID)
        {
            msg->innerOID = CryptMemAlloc(strlen(pszInnerContentObjID) + 1);
            if (msg->innerOID)
                strcpy(msg->innerOID, pszInnerContentObjID);
            else
                ret = FALSE;
        }
        else
            msg->innerOID = NULL;
1383 1384
        msg->data.cbData = 0;
        msg->data.pbData = NULL;
1385 1386 1387 1388
        if (ret)
            msg->msg_data.info = CryptMemAlloc(sizeof(CRYPT_SIGNED_INFO));
        else
            msg->msg_data.info = NULL;
1389 1390 1391 1392 1393 1394 1395
        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;
1396
        if (ret)
1397
        {
1398
            if (info->cSigners)
1399
            {
1400
                msg->msg_data.info->rgSignerInfo =
1401
                 CryptMemAlloc(info->cSigners * sizeof(CMSG_CMS_SIGNER_INFO));
1402
                if (msg->msg_data.info->rgSignerInfo)
1403
                {
1404 1405
                    msg->msg_data.info->cSignerInfo = info->cSigners;
                    memset(msg->msg_data.info->rgSignerInfo, 0,
1406 1407
                     msg->msg_data.info->cSignerInfo *
                     sizeof(CMSG_CMS_SIGNER_INFO));
1408 1409
                    ret = CSignedMsgData_AllocateHandles(&msg->msg_data);
                    for (i = 0; ret && i < msg->msg_data.info->cSignerInfo; i++)
1410
                    {
1411 1412 1413
                        if (info->rgSigners[i].SignerId.dwIdChoice ==
                         CERT_ID_KEY_IDENTIFIER)
                            msg->msg_data.info->version = CMSG_SIGNED_DATA_V3;
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
                        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);
                        }
1425 1426
                    }
                }
1427 1428
                else
                    ret = FALSE;
1429 1430
            }
            else
1431 1432 1433
            {
                msg->msg_data.info->cSignerInfo = 0;
                msg->msg_data.signerHandles = NULL;
1434
                msg->msg_data.cSignerHandle = 0;
1435
            }
1436
        }
1437
        if (ret)
1438 1439
            ret = CRYPT_ConstructBlobArray(
             (BlobArray *)&msg->msg_data.info->cCertEncoded,
1440 1441
             (const BlobArray *)&info->cCertEncoded);
        if (ret)
1442 1443
            ret = CRYPT_ConstructBlobArray(
             (BlobArray *)&msg->msg_data.info->cCrlEncoded,
1444
             (const BlobArray *)&info->cCrlEncoded);
1445 1446 1447 1448 1449
        if (!ret)
        {
            CSignedEncodeMsg_Close(msg);
            msg = NULL;
        }
1450 1451 1452 1453
    }
    return msg;
}

1454 1455 1456 1457
HCRYPTMSG WINAPI CryptMsgOpenToEncode(DWORD dwMsgEncodingType, DWORD dwFlags,
 DWORD dwMsgType, const void *pvMsgEncodeInfo, LPSTR pszInnerContentObjID,
 PCMSG_STREAM_INFO pStreamInfo)
{
1458 1459 1460
    HCRYPTMSG msg = NULL;

    TRACE("(%08x, %08x, %08x, %p, %s, %p)\n", dwMsgEncodingType, dwFlags,
1461
     dwMsgType, pvMsgEncodeInfo, debugstr_a(pszInnerContentObjID), pStreamInfo);
1462 1463 1464 1465 1466 1467 1468 1469 1470

    if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
    {
        SetLastError(E_INVALIDARG);
        return NULL;
    }
    switch (dwMsgType)
    {
    case CMSG_DATA:
1471 1472 1473
        msg = CDataEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
         pszInnerContentObjID, pStreamInfo);
        break;
1474 1475 1476 1477
    case CMSG_HASHED:
        msg = CHashEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
         pszInnerContentObjID, pStreamInfo);
        break;
1478
    case CMSG_SIGNED:
1479 1480 1481
        msg = CSignedEncodeMsg_Open(dwFlags, pvMsgEncodeInfo,
         pszInnerContentObjID, pStreamInfo);
        break;
1482
    case CMSG_ENVELOPED:
1483
        FIXME("unimplemented for type CMSG_ENVELOPED\n");
1484 1485 1486 1487 1488 1489 1490 1491
        break;
    case CMSG_SIGNED_AND_ENVELOPED:
    case CMSG_ENCRYPTED:
        /* defined but invalid, fall through */
    default:
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
    }
    return msg;
1492 1493
}

1494 1495
typedef struct _CDecodeMsg
{
1496 1497 1498
    CryptMsgBase           base;
    DWORD                  type;
    HCRYPTPROV             crypt_prov;
1499
    union {
1500 1501
        HCRYPTHASH     hash;
        CSignedMsgData signed_data;
1502
    } u;
1503
    CRYPT_DATA_BLOB        msg_data;
1504
    CRYPT_DATA_BLOB        detached_data;
1505
    PCONTEXT_PROPERTY_LIST properties;
1506 1507 1508 1509
} CDecodeMsg;

static void CDecodeMsg_Close(HCRYPTMSG hCryptMsg)
{
1510
    CDecodeMsg *msg = hCryptMsg;
1511 1512 1513

    if (msg->base.open_flags & CMSG_CRYPT_RELEASE_CONTEXT_FLAG)
        CryptReleaseContext(msg->crypt_prov, 0);
1514 1515 1516
    switch (msg->type)
    {
    case CMSG_HASHED:
1517 1518
        if (msg->u.hash)
            CryptDestroyHash(msg->u.hash);
1519
        break;
1520
    case CMSG_SIGNED:
1521
        if (msg->u.signed_data.info)
1522
        {
1523
            LocalFree(msg->u.signed_data.info);
1524 1525
            CSignedMsgData_CloseHandles(&msg->u.signed_data);
        }
1526
        break;
1527
    }
1528
    CryptMemFree(msg->msg_data.pbData);
1529
    CryptMemFree(msg->detached_data.pbData);
1530
    ContextPropertyList_Free(msg->properties);
1531 1532
}

1533
static BOOL CDecodeMsg_CopyData(CRYPT_DATA_BLOB *blob, const BYTE *pbData,
1534 1535 1536 1537 1538 1539
 DWORD cbData)
{
    BOOL ret = TRUE;

    if (cbData)
    {
1540 1541 1542
        if (blob->cbData)
            blob->pbData = CryptMemRealloc(blob->pbData,
             blob->cbData + cbData);
1543
        else
1544 1545
            blob->pbData = CryptMemAlloc(cbData);
        if (blob->pbData)
1546
        {
1547 1548
            memcpy(blob->pbData + blob->cbData, pbData, cbData);
            blob->cbData += cbData;
1549 1550 1551 1552 1553 1554 1555
        }
        else
            ret = FALSE;
    }
    return ret;
}

1556
static BOOL CDecodeMsg_DecodeDataContent(CDecodeMsg *msg, const CRYPT_DER_BLOB *blob)
1557 1558 1559 1560 1561 1562
{
    BOOL ret;
    CRYPT_DATA_BLOB *data;
    DWORD size;

    ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
1563
     blob->pbData, blob->cbData, CRYPT_DECODE_ALLOC_FLAG, NULL, &data, &size);
1564 1565 1566 1567 1568 1569 1570 1571 1572
    if (ret)
    {
        ret = ContextPropertyList_SetProperty(msg->properties,
         CMSG_CONTENT_PARAM, data->pbData, data->cbData);
        LocalFree(data);
    }
    return ret;
}

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
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;
}

1615
static BOOL CDecodeMsg_DecodeHashedContent(CDecodeMsg *msg,
1616
 const CRYPT_DER_BLOB *blob)
1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
{
    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);
1636 1637 1638 1639 1640 1641 1642 1643 1644
        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);
        }
1645 1646 1647 1648 1649 1650 1651
        ContextPropertyList_SetProperty(msg->properties, CMSG_HASH_DATA_PARAM,
         digestedData->hash.pbData, digestedData->hash.cbData);
        LocalFree(digestedData);
    }
    return ret;
}

1652 1653 1654 1655 1656 1657 1658
static BOOL CDecodeMsg_DecodeSignedContent(CDecodeMsg *msg,
 CRYPT_DER_BLOB *blob)
{
    BOOL ret;
    CRYPT_SIGNED_INFO *signedInfo;
    DWORD size;

1659
    ret = CRYPT_AsnDecodeCMSSignedInfo(blob->pbData, blob->cbData,
1660 1661 1662
     CRYPT_DECODE_ALLOC_FLAG, NULL, (CRYPT_SIGNED_INFO *)&signedInfo,
     &size);
    if (ret)
1663
        msg->u.signed_data.info = signedInfo;
1664 1665
    return ret;
}
1666

1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
/* 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.
 */
static BOOL CDecodeMsg_DecodeContent(CDecodeMsg *msg, CRYPT_DER_BLOB *blob,
 DWORD type)
{
    BOOL ret;

    switch (type)
    {
    case CMSG_DATA:
1680
        if ((ret = CDecodeMsg_DecodeDataContent(msg, blob)))
1681 1682
            msg->type = CMSG_DATA;
        break;
1683
    case CMSG_HASHED:
1684
        if ((ret = CDecodeMsg_DecodeHashedContent(msg, blob)))
1685
            msg->type = CMSG_HASHED;
1686
        break;
1687
    case CMSG_ENVELOPED:
1688
        FIXME("unimplemented for type CMSG_ENVELOPED\n");
1689 1690
        ret = TRUE;
        break;
1691 1692
    case CMSG_SIGNED:
        if ((ret = CDecodeMsg_DecodeSignedContent(msg, blob)))
1693
            msg->type = CMSG_SIGNED;
1694
        break;
1695 1696 1697
    default:
    {
        CRYPT_CONTENT_INFO *info;
1698
        DWORD size;
1699 1700 1701

        ret = CryptDecodeObjectEx(X509_ASN_ENCODING, PKCS_CONTENT_INFO,
         msg->msg_data.pbData, msg->msg_data.cbData, CRYPT_DECODE_ALLOC_FLAG,
1702
         NULL, &info, &size);
1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
        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;
1726 1727
}

1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746
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;

1747 1748 1749 1750 1751
        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.
             */
1752 1753
            content.pbData = msg->detached_data.pbData;
            content.cbData = msg->detached_data.cbData;
1754
        }
1755 1756 1757
        else
            ret = ContextPropertyList_FindProperty(msg->properties,
             CMSG_CONTENT_PARAM, &content);
1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800
        if (ret)
            ret = CryptHashData(msg->u.hash, content.pbData, content.cbData, 0);
    }
    CryptMemFree(hashAlgoID);
    return ret;
}

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,
1801
                 CRYPT_DECODE_ALLOC_FLAG, NULL, &blob, &size);
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
                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;
    case CMSG_SIGNED:
        ret = CDecodeMsg_FinalizeSignedContent(msg, blob);
        break;
    default:
        ret = TRUE;
    }
    return ret;
}

1835 1836 1837
static BOOL CDecodeMsg_Update(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal)
{
1838
    CDecodeMsg *msg = hCryptMsg;
1839 1840 1841 1842
    BOOL ret = FALSE;

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

1843 1844 1845
    if (msg->base.state == MsgStateFinalized)
        SetLastError(CRYPT_E_MSG_ERROR);
    else if (msg->base.streamed)
1846 1847 1848
    {
        FIXME("(%p, %p, %d, %d): streamed update stub\n", hCryptMsg, pbData,
         cbData, fFinal);
1849
        switch (msg->base.state)
1850
        {
1851 1852 1853
        case MsgStateInit:
            ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
            if (fFinal)
1854
            {
1855 1856 1857 1858
                if (msg->base.open_flags & CMSG_DETACHED_FLAG)
                    msg->base.state = MsgStateDataFinalized;
                else
                    msg->base.state = MsgStateFinalized;
1859 1860
            }
            else
1861 1862 1863 1864 1865
                msg->base.state = MsgStateUpdated;
            break;
        case MsgStateUpdated:
            ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
            if (fFinal)
1866
            {
1867 1868 1869 1870
                if (msg->base.open_flags & CMSG_DETACHED_FLAG)
                    msg->base.state = MsgStateDataFinalized;
                else
                    msg->base.state = MsgStateFinalized;
1871
            }
1872 1873 1874 1875 1876 1877 1878 1879 1880
            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;
1881
        }
1882 1883 1884 1885 1886 1887 1888
    }
    else
    {
        if (!fFinal)
            SetLastError(CRYPT_E_MSG_ERROR);
        else
        {
1889
            switch (msg->base.state)
1890
            {
1891
            case MsgStateInit:
1892
                ret = CDecodeMsg_CopyData(&msg->msg_data, pbData, cbData);
1893 1894 1895 1896
                if (msg->base.open_flags & CMSG_DETACHED_FLAG)
                    msg->base.state = MsgStateDataFinalized;
                else
                    msg->base.state = MsgStateFinalized;
1897 1898 1899
                break;
            case MsgStateDataFinalized:
                ret = CDecodeMsg_CopyData(&msg->detached_data, pbData, cbData);
1900
                msg->base.state = MsgStateFinalized;
1901 1902 1903
                break;
            default:
                SetLastError(CRYPT_E_MSG_ERROR);
1904
            }
1905 1906
        }
    }
1907
    if (ret && fFinal &&
1908 1909 1910 1911
     ((msg->base.open_flags & CMSG_DETACHED_FLAG && msg->base.state ==
     MsgStateDataFinalized) ||
     (!(msg->base.open_flags & CMSG_DETACHED_FLAG) && msg->base.state ==
     MsgStateFinalized)))
1912
        ret = CDecodeMsg_DecodeContent(msg, &msg->msg_data, msg->type);
1913 1914
    if (ret && msg->base.state == MsgStateFinalized)
        ret = CDecodeMsg_FinalizeContent(msg, &msg->msg_data);
1915
    return ret;
1916 1917
}

1918
static BOOL CDecodeHashMsg_GetParam(CDecodeMsg *msg, DWORD dwParamType,
1919 1920
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
1921 1922 1923 1924 1925
    BOOL ret = FALSE;

    switch (dwParamType)
    {
    case CMSG_TYPE_PARAM:
1926
        ret = CRYPT_CopyParam(pvData, pcbData, &msg->type, sizeof(msg->type));
1927
        break;
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937
    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)
1938
                CRYPT_FixUpAlgorithmID(pvData);
1939 1940 1941 1942 1943
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    }
1944
    case CMSG_COMPUTED_HASH_PARAM:
1945
        ret = CryptGetHashParam(msg->u.hash, HP_HASHVAL, pvData, pcbData, 0);
1946
        break;
1947 1948 1949 1950 1951 1952 1953 1954
    default:
    {
        CRYPT_DATA_BLOB blob;

        ret = ContextPropertyList_FindProperty(msg->properties, dwParamType,
         &blob);
        if (ret)
            ret = CRYPT_CopyParam(pvData, pcbData, blob.pbData, blob.cbData);
1955 1956
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
1957
    }
1958 1959
    }
    return ret;
1960 1961
}

1962 1963 1964 1965 1966 1967 1968 1969 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
/* 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;

1998
        *nextData = POINTER_ALIGN_DWORD_PTR(*nextData);
1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013
        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;
2014
                *nextData = POINTER_ALIGN_DWORD_PTR(*nextData);
2015
                out->rgAttr[i].rgValue = (PCRYPT_DATA_BLOB)*nextData;
2016
                *nextData += in->rgAttr[i].cValue * sizeof(CRYPT_DATA_BLOB);
2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033
                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 */
2034
        size = ALIGN_DWORD_PTR(size);
2035 2036 2037 2038
        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;
    }
2039
    /* align pointer again to be conservative */
2040
    size = ALIGN_DWORD_PTR(size);
2041 2042 2043
    return size;
}

2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
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;
}

2092
static BOOL CRYPT_CopySignerInfo(void *pvData, DWORD *pcbData,
2093
 const CMSG_CMS_SIGNER_INFO *in)
2094
{
2095
    DWORD size = sizeof(CMSG_SIGNER_INFO), rdnSize = 0;
2096 2097
    BOOL ret;

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

2100 2101
    if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
    {
2102 2103
        size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
        size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2104 2105 2106
    }
    else
    {
2107
        rdnSize = CRYPT_SizeOfKeyIdAsIssuerAndSerial(&in->SignerId.u.KeyId);
2108
        size += rdnSize;
2109
    }
2110 2111 2112 2113 2114 2115 2116 2117
    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 */
2118
    size = ALIGN_DWORD_PTR(size);
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134
    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);
2135
        CMSG_SIGNER_INFO *out = pvData;
2136

2137
        ret = TRUE;
2138
        out->dwVersion = in->dwVersion;
2139 2140 2141
        if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
        {
            CRYPT_CopyBlob(&out->Issuer,
2142
             &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2143
            CRYPT_CopyBlob(&out->SerialNumber,
2144
             &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2145
        }
2146 2147
        else
            ret = CRYPT_CopyKeyIdAsIssuerAndSerial(&out->Issuer, &out->SerialNumber,
2148
             &in->SignerId.u.KeyId, rdnSize, &nextData);
2149 2150 2151 2152 2153 2154 2155
        if (ret)
        {
            CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
             &nextData);
            CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
             &in->HashEncryptionAlgorithm, &nextData);
            CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
2156
            nextData = POINTER_ALIGN_DWORD_PTR(nextData);
2157 2158 2159
            CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
            CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
        }
2160
    }
2161
    TRACE("returning %d\n", ret);
2162 2163 2164
    return ret;
}

2165 2166 2167 2168 2169 2170 2171 2172 2173 2174
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)
    {
2175 2176
        size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
        size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2177 2178
    }
    else
2179
        size += in->SignerId.u.KeyId.cbData;
2180 2181 2182 2183 2184 2185 2186 2187
    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 */
2188
    size = ALIGN_DWORD_PTR(size);
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204
    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);
2205
        CMSG_CMS_SIGNER_INFO *out = pvData;
2206 2207 2208 2209 2210

        out->dwVersion = in->dwVersion;
        out->SignerId.dwIdChoice = in->SignerId.dwIdChoice;
        if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
        {
2211 2212 2213 2214
            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);
2215 2216
        }
        else
2217
            CRYPT_CopyBlob(&out->SignerId.u.KeyId, &in->SignerId.u.KeyId, &nextData);
2218 2219 2220 2221 2222
        CRYPT_CopyAlgorithmId(&out->HashAlgorithm, &in->HashAlgorithm,
         &nextData);
        CRYPT_CopyAlgorithmId(&out->HashEncryptionAlgorithm,
         &in->HashEncryptionAlgorithm, &nextData);
        CRYPT_CopyBlob(&out->EncryptedHash, &in->EncryptedHash, &nextData);
2223
        nextData = POINTER_ALIGN_DWORD_PTR(nextData);
2224 2225 2226 2227 2228 2229 2230 2231
        CRYPT_CopyAttributes(&out->AuthAttrs, &in->AuthAttrs, &nextData);
        CRYPT_CopyAttributes(&out->UnauthAttrs, &in->UnauthAttrs, &nextData);
        ret = TRUE;
    }
    TRACE("returning %d\n", ret);
    return ret;
}

2232
static BOOL CRYPT_CopySignerCertInfo(void *pvData, DWORD *pcbData,
2233
 const CMSG_CMS_SIGNER_INFO *in)
2234
{
2235
    DWORD size = sizeof(CERT_INFO), rdnSize = 0;
2236 2237
    BOOL ret;

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

2240 2241
    if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
    {
2242 2243
        size += in->SignerId.u.IssuerSerialNumber.Issuer.cbData;
        size += in->SignerId.u.IssuerSerialNumber.SerialNumber.cbData;
2244 2245 2246
    }
    else
    {
2247
        rdnSize = CRYPT_SizeOfKeyIdAsIssuerAndSerial(&in->SignerId.u.KeyId);
2248
        size += rdnSize;
2249
    }
2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
    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);
2264
        CERT_INFO *out = pvData;
2265 2266

        memset(out, 0, sizeof(CERT_INFO));
2267 2268 2269
        if (in->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
        {
            CRYPT_CopyBlob(&out->Issuer,
2270
             &in->SignerId.u.IssuerSerialNumber.Issuer, &nextData);
2271
            CRYPT_CopyBlob(&out->SerialNumber,
2272
             &in->SignerId.u.IssuerSerialNumber.SerialNumber, &nextData);
2273 2274 2275 2276
            ret = TRUE;
        }
        else
            ret = CRYPT_CopyKeyIdAsIssuerAndSerial(&out->Issuer, &out->SerialNumber,
2277
             &in->SignerId.u.KeyId, rdnSize, &nextData);
2278
    }
2279
    TRACE("returning %d\n", ret);
2280 2281 2282
    return ret;
}

2283 2284 2285 2286 2287 2288 2289 2290 2291 2292
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;
2293
    case CMSG_CONTENT_PARAM:
2294
        if (msg->u.signed_data.info)
2295
        {
2296 2297
            if (!strcmp(msg->u.signed_data.info->content.pszObjId,
             szOID_RSA_data))
2298
            {
2299 2300 2301 2302
                CRYPT_DATA_BLOB *blob;
                DWORD size;

                ret = CryptDecodeObjectEx(X509_ASN_ENCODING, X509_OCTET_STRING,
2303 2304
                 msg->u.signed_data.info->content.Content.pbData,
                 msg->u.signed_data.info->content.Content.cbData,
2305
                 CRYPT_DECODE_ALLOC_FLAG, NULL, &blob, &size);
2306 2307 2308 2309 2310 2311
                if (ret)
                {
                    ret = CRYPT_CopyParam(pvData, pcbData, blob->pbData,
                     blob->cbData);
                    LocalFree(blob);
                }
2312
            }
2313 2314
            else
                ret = CRYPT_CopyParam(pvData, pcbData,
2315 2316
                 msg->u.signed_data.info->content.Content.pbData,
                 msg->u.signed_data.info->content.Content.cbData);
2317 2318 2319
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2320 2321
        break;
    case CMSG_INNER_CONTENT_TYPE_PARAM:
2322
        if (msg->u.signed_data.info)
2323
            ret = CRYPT_CopyParam(pvData, pcbData,
2324 2325
             msg->u.signed_data.info->content.pszObjId,
             strlen(msg->u.signed_data.info->content.pszObjId) + 1);
2326 2327
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2328
        break;
2329
    case CMSG_SIGNER_COUNT_PARAM:
2330
        if (msg->u.signed_data.info)
2331
            ret = CRYPT_CopyParam(pvData, pcbData,
2332
             &msg->u.signed_data.info->cSignerInfo, sizeof(DWORD));
2333 2334
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2335 2336
        break;
    case CMSG_SIGNER_INFO_PARAM:
2337
        if (msg->u.signed_data.info)
2338
        {
2339
            if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2340 2341 2342
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CRYPT_CopySignerInfo(pvData, pcbData,
2343
                 &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
2344 2345 2346
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2347 2348
        break;
    case CMSG_SIGNER_CERT_INFO_PARAM:
2349
        if (msg->u.signed_data.info)
2350
        {
2351
            if (dwIndex >= msg->u.signed_data.info->cSignerInfo)
2352 2353 2354
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CRYPT_CopySignerCertInfo(pvData, pcbData,
2355
                 &msg->u.signed_data.info->rgSignerInfo[dwIndex]);
2356 2357 2358
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
2359 2360
        break;
    case CMSG_CERT_COUNT_PARAM:
2361
        if (msg->u.signed_data.info)
2362
            ret = CRYPT_CopyParam(pvData, pcbData,
2363
             &msg->u.signed_data.info->cCertEncoded, sizeof(DWORD));
2364 2365 2366 2367
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_CERT_PARAM:
2368
        if (msg->u.signed_data.info)
2369
        {
2370
            if (dwIndex >= msg->u.signed_data.info->cCertEncoded)
2371 2372 2373
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CRYPT_CopyParam(pvData, pcbData,
2374 2375
                 msg->u.signed_data.info->rgCertEncoded[dwIndex].pbData,
                 msg->u.signed_data.info->rgCertEncoded[dwIndex].cbData);
2376 2377 2378 2379 2380
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_CRL_COUNT_PARAM:
2381
        if (msg->u.signed_data.info)
2382
            ret = CRYPT_CopyParam(pvData, pcbData,
2383
             &msg->u.signed_data.info->cCrlEncoded, sizeof(DWORD));
2384 2385 2386 2387
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_CRL_PARAM:
2388
        if (msg->u.signed_data.info)
2389
        {
2390
            if (dwIndex >= msg->u.signed_data.info->cCrlEncoded)
2391 2392 2393
                SetLastError(CRYPT_E_INVALID_INDEX);
            else
                ret = CRYPT_CopyParam(pvData, pcbData,
2394 2395
                 msg->u.signed_data.info->rgCrlEncoded[dwIndex].pbData,
                 msg->u.signed_data.info->rgCrlEncoded[dwIndex].cbData);
2396 2397 2398 2399
        }
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
2400 2401 2402
    case CMSG_COMPUTED_HASH_PARAM:
        if (msg->u.signed_data.info)
        {
2403
            if (dwIndex >= msg->u.signed_data.cSignerHandle)
2404 2405 2406 2407 2408 2409 2410 2411 2412
                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;
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426
    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;
2427
    case CMSG_ATTR_CERT_COUNT_PARAM:
2428
        if (msg->u.signed_data.info)
2429 2430 2431
        {
            DWORD attrCertCount = 0;

2432
            ret = CRYPT_CopyParam(pvData, pcbData,
2433 2434
             &attrCertCount, sizeof(DWORD));
        }
2435 2436 2437 2438
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
    case CMSG_ATTR_CERT_PARAM:
2439
        if (msg->u.signed_data.info)
2440
            SetLastError(CRYPT_E_INVALID_INDEX);
2441 2442 2443
        else
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        break;
2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455
    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;
2456 2457 2458 2459 2460 2461 2462
    default:
        FIXME("unimplemented for %d\n", dwParamType);
        SetLastError(CRYPT_E_INVALID_MSG_TYPE);
    }
    return ret;
}

2463 2464 2465
static BOOL CDecodeMsg_GetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
2466
    CDecodeMsg *msg = hCryptMsg;
2467 2468 2469 2470 2471 2472 2473 2474
    BOOL ret = FALSE;

    switch (msg->type)
    {
    case CMSG_HASHED:
        ret = CDecodeHashMsg_GetParam(msg, dwParamType, dwIndex, pvData,
         pcbData);
        break;
2475 2476 2477 2478
    case CMSG_SIGNED:
        ret = CDecodeSignedMsg_GetParam(msg, dwParamType, dwIndex, pvData,
         pcbData);
        break;
2479 2480 2481 2482
    default:
        switch (dwParamType)
        {
        case CMSG_TYPE_PARAM:
2483
            ret = CRYPT_CopyParam(pvData, pcbData, &msg->type,
2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
             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;
}

2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524
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)
2525 2526 2527 2528 2529 2530 2531
                {
                    if (memcmp(hashBlob.pbData, computedHash, hashBlob.cbData))
                    {
                        SetLastError(CRYPT_E_HASH_VALUE);
                        ret = FALSE;
                    }
                }
2532
                CryptMemFree(computedHash);
2533 2534
            }
            else
2535 2536
            {
                SetLastError(ERROR_OUTOFMEMORY);
2537
                ret = FALSE;
2538 2539 2540 2541 2542 2543
            }
        }
        else
        {
            SetLastError(CRYPT_E_HASH_VALUE);
            ret = FALSE;
2544 2545 2546 2547 2548
        }
    }
    return ret;
}

2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580
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;
}

2581 2582 2583 2584 2585
static BOOL CDecodeSignedMsg_VerifySignature(CDecodeMsg *msg, PCERT_INFO info)
{
    BOOL ret = FALSE;
    DWORD i;

2586 2587 2588 2589 2590
    if (!msg->u.signed_data.signerHandles)
    {
        SetLastError(NTE_BAD_SIGNATURE);
        return FALSE;
    }
2591 2592
    for (i = 0; !ret && i < msg->u.signed_data.info->cSignerInfo; i++)
    {
2593 2594 2595 2596
        PCMSG_CMS_SIGNER_INFO signerInfo =
         &msg->u.signed_data.info->rgSignerInfo[i];

        if (signerInfo->SignerId.dwIdChoice == CERT_ID_ISSUER_SERIAL_NUMBER)
2597
        {
2598
            ret = CertCompareCertificateName(X509_ASN_ENCODING,
2599
             &signerInfo->SignerId.u.IssuerSerialNumber.Issuer,
2600
             &info->Issuer);
2601
            if (ret)
2602 2603
            {
                ret = CertCompareIntegerBlob(
2604
                 &signerInfo->SignerId.u.IssuerSerialNumber.SerialNumber,
2605 2606 2607 2608 2609 2610 2611 2612
                 &info->SerialNumber);
                if (ret)
                    break;
            }
        }
        else
        {
            FIXME("signer %d: unimplemented for key id\n", i);
2613
        }
2614 2615
    }
    if (ret)
2616 2617 2618 2619
        ret = CDecodeSignedMsg_VerifySignatureWithKey(msg, 0, i,
         &info->SubjectPublicKeyInfo);
    else
        SetLastError(CRYPT_E_SIGNER_NOT_FOUND);
2620

2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632
    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);
2633 2634
    else if (!msg->u.signed_data.signerHandles)
        SetLastError(NTE_BAD_SIGNATURE);
2635 2636 2637 2638 2639 2640
    else
    {
        switch (para->dwSignerType)
        {
        case CMSG_VERIFY_SIGNER_PUBKEY:
            ret = CDecodeSignedMsg_VerifySignatureWithKey(msg,
2641
             para->hCryptProv, para->dwSignerIndex, para->pvSigner);
2642 2643
            break;
        case CMSG_VERIFY_SIGNER_CERT:
2644
        {
2645
            PCCERT_CONTEXT cert = para->pvSigner;
2646

2647 2648 2649 2650 2651 2652 2653
            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);
2654 2655 2656 2657 2658
        }
    }
    return ret;
}

2659 2660 2661
static BOOL CDecodeMsg_Control(HCRYPTMSG hCryptMsg, DWORD dwFlags,
 DWORD dwCtrlType, const void *pvCtrlPara)
{
2662
    CDecodeMsg *msg = hCryptMsg;
2663 2664 2665 2666 2667 2668 2669 2670
    BOOL ret = FALSE;

    switch (dwCtrlType)
    {
    case CMSG_CTRL_VERIFY_SIGNATURE:
        switch (msg->type)
        {
        case CMSG_SIGNED:
2671
            ret = CDecodeSignedMsg_VerifySignature(msg, (PCERT_INFO)pvCtrlPara);
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687
            break;
        default:
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        }
        break;
    case CMSG_CTRL_DECRYPT:
        switch (msg->type)
        {
        default:
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        }
        break;
    case CMSG_CTRL_VERIFY_HASH:
        switch (msg->type)
        {
        case CMSG_HASHED:
2688
            ret = CDecodeHashMsg_VerifyHash(msg);
2689 2690 2691 2692 2693
            break;
        default:
            SetLastError(CRYPT_E_INVALID_MSG_TYPE);
        }
        break;
2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704
    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;
2705 2706 2707 2708 2709 2710
    default:
        SetLastError(CRYPT_E_CONTROL_TYPE);
    }
    return ret;
}

2711
HCRYPTMSG WINAPI CryptMsgOpenToDecode(DWORD dwMsgEncodingType, DWORD dwFlags,
2712
 DWORD dwMsgType, HCRYPTPROV_LEGACY hCryptProv, PCERT_INFO pRecipientInfo,
2713 2714
 PCMSG_STREAM_INFO pStreamInfo)
{
2715 2716 2717
    CDecodeMsg *msg;

    TRACE("(%08x, %08x, %08x, %08lx, %p, %p)\n", dwMsgEncodingType,
2718
     dwFlags, dwMsgType, hCryptProv, pRecipientInfo, pStreamInfo);
2719 2720 2721 2722 2723 2724

    if (GET_CMSG_ENCODING_TYPE(dwMsgEncodingType) != PKCS_7_ASN_ENCODING)
    {
        SetLastError(E_INVALIDARG);
        return NULL;
    }
2725 2726 2727 2728
    msg = CryptMemAlloc(sizeof(CDecodeMsg));
    if (msg)
    {
        CryptMsgBase_Init((CryptMsgBase *)msg, dwFlags, pStreamInfo,
2729
         CDecodeMsg_Close, CDecodeMsg_GetParam, CDecodeMsg_Update,
2730
         CDecodeMsg_Control);
2731
        msg->type = dwMsgType;
2732 2733 2734 2735 2736 2737 2738
        if (hCryptProv)
            msg->crypt_prov = hCryptProv;
        else
        {
            msg->crypt_prov = CRYPT_GetDefaultProvider();
            msg->base.open_flags &= ~CMSG_CRYPT_RELEASE_CONTEXT_FLAG;
        }
2739
        memset(&msg->u, 0, sizeof(msg->u));
2740 2741
        msg->msg_data.cbData = 0;
        msg->msg_data.pbData = NULL;
2742 2743
        msg->detached_data.cbData = 0;
        msg->detached_data.pbData = NULL;
2744
        msg->properties = ContextPropertyList_Create();
2745 2746
    }
    return msg;
2747 2748 2749 2750
}

HCRYPTMSG WINAPI CryptMsgDuplicate(HCRYPTMSG hCryptMsg)
{
2751 2752 2753 2754
    TRACE("(%p)\n", hCryptMsg);

    if (hCryptMsg)
    {
2755
        CryptMsgBase *msg = hCryptMsg;
2756 2757 2758

        InterlockedIncrement(&msg->ref);
    }
2759 2760 2761 2762 2763
    return hCryptMsg;
}

BOOL WINAPI CryptMsgClose(HCRYPTMSG hCryptMsg)
{
2764 2765 2766 2767
    TRACE("(%p)\n", hCryptMsg);

    if (hCryptMsg)
    {
2768
        CryptMsgBase *msg = hCryptMsg;
2769 2770 2771 2772 2773 2774 2775 2776 2777

        if (InterlockedDecrement(&msg->ref) == 0)
        {
            TRACE("freeing %p\n", msg);
            if (msg->close)
                msg->close(msg);
            CryptMemFree(msg);
        }
    }
2778 2779 2780 2781 2782 2783
    return TRUE;
}

BOOL WINAPI CryptMsgUpdate(HCRYPTMSG hCryptMsg, const BYTE *pbData,
 DWORD cbData, BOOL fFinal)
{
2784
    CryptMsgBase *msg = hCryptMsg;
2785 2786

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

2788
    return msg->update(hCryptMsg, pbData, cbData, fFinal);
2789 2790 2791 2792 2793
}

BOOL WINAPI CryptMsgGetParam(HCRYPTMSG hCryptMsg, DWORD dwParamType,
 DWORD dwIndex, void *pvData, DWORD *pcbData)
{
2794
    CryptMsgBase *msg = hCryptMsg;
2795 2796

    TRACE("(%p, %d, %d, %p, %p)\n", hCryptMsg, dwParamType, dwIndex,
2797
     pvData, pcbData);
2798
    return msg->get_param(hCryptMsg, dwParamType, dwIndex, pvData, pcbData);
2799
}
2800 2801 2802 2803

BOOL WINAPI CryptMsgControl(HCRYPTMSG hCryptMsg, DWORD dwFlags,
 DWORD dwCtrlType, const void *pvCtrlPara)
{
2804
    CryptMsgBase *msg = hCryptMsg;
2805 2806

    TRACE("(%p, %08x, %d, %p)\n", hCryptMsg, dwFlags, dwCtrlType,
2807
     pvCtrlPara);
2808
    return msg->control(hCryptMsg, dwFlags, dwCtrlType, pvCtrlPara);
2809
}
2810

2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833
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;
}

2834 2835 2836 2837
BOOL WINAPI CryptMsgGetAndVerifySigner(HCRYPTMSG hCryptMsg, DWORD cSignerStore,
 HCERTSTORE *rghSignerStore, DWORD dwFlags, PCCERT_CONTEXT *ppSigner,
 DWORD *pdwSignerIndex)
{
2838
    HCERTSTORE store;
2839
    DWORD i, signerIndex = 0;
2840 2841 2842 2843
    PCCERT_CONTEXT signerCert = NULL;
    BOOL ret = FALSE;

    TRACE("(%p, %d, %p, %08x, %p, %p)\n", hCryptMsg, cSignerStore,
2844
     rghSignerStore, dwFlags, ppSigner, pdwSignerIndex);
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 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

    /* 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;
2925
}
2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936

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;
}
2937 2938 2939 2940 2941

BOOL WINAPI CryptMsgEncodeAndSignCTL(DWORD dwMsgEncodingType,
 PCTL_INFO pCtlInfo, PCMSG_SIGNED_ENCODE_INFO pSignInfo, DWORD dwFlags,
 BYTE *pbEncoded, DWORD *pcbEncoded)
{
2942 2943 2944 2945 2946
    BOOL ret;
    BYTE *pbCtlContent;
    DWORD cbCtlContent;

    TRACE("(%08x, %p, %p, %08x, %p, %p)\n", dwMsgEncodingType, pCtlInfo,
2947
     pSignInfo, dwFlags, pbEncoded, pcbEncoded);
2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961

    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;
2962
}
2963 2964 2965 2966 2967

BOOL WINAPI CryptMsgSignCTL(DWORD dwMsgEncodingType, BYTE *pbCtlContent,
 DWORD cbCtlContent, PCMSG_SIGNED_ENCODE_INFO pSignInfo, DWORD dwFlags,
 BYTE *pbEncoded, DWORD *pcbEncoded)
{
2968 2969 2970 2971 2972
    static char oid_ctl[] = szOID_CTL;
    BOOL ret;
    HCRYPTMSG msg;

    TRACE("(%08x, %p, %d, %p, %08x, %p, %p)\n", dwMsgEncodingType,
2973
     pbCtlContent, cbCtlContent, pSignInfo, dwFlags, pbEncoded, pcbEncoded);
2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992

    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;
2993
}