summaryrefslogtreecommitdiff
path: root/src/strongname/api/strongnameinternal.cpp
blob: 6b4472b1a0b6efdc57b01a34830a82e2c312278d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// 
// Strong name APIs which are not exposed publicly but are used by CLR code
// 

#include "common.h"
#include "strongnameinternal.h"
#include "strongnameholders.h"
#include "thekey.h"
#include "ecmakey.h"

#ifdef FEATURE_STRONGNAME_TESTKEY_ALLOWED
#include "thetestkey.h"

BYTE g_rbTestKeyBuffer[] = { TEST_KEY_HEADER TEST_KEY_BUFFER };
#endif // FEATURE_STRONGNAME_TESTKEY_ALLOWED

//---------------------------------------------------------------------------------------
//
// Check to see if a public key blob is the ECMA public key blob
//
// Arguments:
//   pbKey - public key blob to check
//   cbKey - size in bytes of pbKey
//

bool StrongNameIsEcmaKey(__in_ecount(cbKey) const BYTE *pbKey, DWORD cbKey)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    // The key should be the same size as the ECMA key
    if (cbKey != sizeof(g_rbNeutralPublicKey))
    {
        return false;
    }

    const PublicKeyBlob *pKeyBlob = reinterpret_cast<const PublicKeyBlob *>(pbKey);
    return StrongNameIsEcmaKey(*pKeyBlob);
}

//---------------------------------------------------------------------------------------
//
// Check to see if a public key blob is the ECMA public key blob
//
// Arguments:
//   keyPublicKey - Key to check to see if it matches the ECMA key
//

bool StrongNameIsEcmaKey(const PublicKeyBlob &keyPublicKey)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    return StrongNameSizeOfPublicKey(keyPublicKey) == sizeof(g_rbNeutralPublicKey) &&
           memcmp(reinterpret_cast<const BYTE *>(&keyPublicKey), g_rbNeutralPublicKey, sizeof(g_rbNeutralPublicKey)) == 0;
}

//---------------------------------------------------------------------------------------
//
// Check to see if a public key blob is the TheKey public key blob
//
// Arguments:
//   pbKey - public key blob to check
//   cbKey - size in bytes of pbKey
//
bool StrongNameIsTheKey(__in_ecount(cbKey) const BYTE *pbKey, DWORD cbKey)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    // The key should be the same size as the TheKey key
    if (cbKey != sizeof(g_rbTheKey))
    {
        return false;
    }

    return (memcmp(pbKey, g_rbTheKey, sizeof(g_rbTheKey)) == 0);
}

#ifdef FEATURE_CORECLR
//---------------------------------------------------------------------------------------
//
// Check to see if a public key blob is the Silverlight Platform public key blob
//
// Arguments:
//   pbKey - public key blob to check
//   cbKey - size in bytes of pbKey
//

bool StrongNameIsSilverlightPlatformKey(__in_ecount(cbKey) const BYTE *pbKey, DWORD cbKey)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    // The key should be the same size as the ECMA key
    if (cbKey != sizeof(g_rbTheSilverlightPlatformKey))
    {
        return false;
    }

    const PublicKeyBlob *pKeyBlob = reinterpret_cast<const PublicKeyBlob *>(pbKey);
    return StrongNameIsSilverlightPlatformKey(*pKeyBlob);
}

//---------------------------------------------------------------------------------------
//
// Check to see if a public key blob is the Silverlight Platform public key blob
//
// Arguments:
//   keyPublicKey - Key to check to see if it matches the ECMA key
//

bool StrongNameIsSilverlightPlatformKey(const PublicKeyBlob &keyPublicKey)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    return StrongNameSizeOfPublicKey(keyPublicKey) == sizeof(g_rbTheSilverlightPlatformKey) &&
           memcmp(reinterpret_cast<const BYTE *>(&keyPublicKey), g_rbTheSilverlightPlatformKey, sizeof(g_rbTheSilverlightPlatformKey)) == 0;
}
#endif //FEATURE_CORECLR

#ifdef FEATURE_STRONGNAME_TESTKEY_ALLOWED

//---------------------------------------------------------------------------------------
//
// Check to see if a public key blob is the Silverlight Platform public key blob
//
// See code:g_rbTestKeyBuffer#TestKeyStamping
//
// Arguments:
//   pbKey - public key blob to check
//   cbKey - size in bytes of pbKey
//

bool StrongNameIsTestKey(__in_ecount(cbKey) const BYTE *pbKey, DWORD cbKey)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    // The key should be the same size as the ECMA key
    if (cbKey != sizeof(g_rbTestKeyBuffer) - 2 * sizeof(GUID))
    {
        return false;
    }

    const PublicKeyBlob *pKeyBlob = reinterpret_cast<const PublicKeyBlob *>(pbKey);
    return StrongNameIsTestKey(*pKeyBlob);
}

//---------------------------------------------------------------------------------------
//
// Determine if the public key blob is the test public key stamped into the VM.
// 
// See code:g_rbTestKeyBuffer#TestKeyStamping
//
// Arguments:
//   keyPublicKey - public key blob to check for emptyness
//

bool StrongNameIsTestKey(const PublicKeyBlob &keyPublicKey)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    // Find the blob in the VM by looking past the two header GUIDs in the buffer
    _ASSERTE(sizeof(g_rbTestKeyBuffer) > 2 * sizeof(GUID) + sizeof(PublicKeyBlob));
    const PublicKeyBlob *pbTestPublicKey = reinterpret_cast<const PublicKeyBlob *>(g_rbTestKeyBuffer + 2 * sizeof(GUID));

    DWORD cbTestPublicKey = StrongNameSizeOfPublicKey(*pbTestPublicKey);
    DWORD cbCheckPublicKey = StrongNameSizeOfPublicKey(keyPublicKey);

    // Check whether valid test key was stamped in
    if (cbTestPublicKey == 0)
        return false;

    // This is the test public key if it is the same size as the public key in the buffer, and is identical
    // to the test key as well.
    return cbTestPublicKey == cbCheckPublicKey &&
           memcmp(reinterpret_cast<const void *>(pbTestPublicKey), reinterpret_cast<const void *>(&keyPublicKey), cbTestPublicKey) == 0;
}

#endif // FEATURE_STRONGNAME_TESTKEY_ALLOWED

//---------------------------------------------------------------------------------------
//
// Verify that a public key blob looks like a reasonable public key
//
// Arguments:
//   pbBuffer     - buffer to verify the format of
//   cbBuffer     - size of pbBuffer
//   fImportKeys  - do a more extensive check by attempting to import the keys
//

bool StrongNameIsValidPublicKey(__in_ecount(cbBuffer) const BYTE *pbBuffer, DWORD cbBuffer, bool fImportKeys)
{
    CONTRACTL
    {
        PRECONDITION(CheckPointer(pbBuffer));
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    // The buffer must be at least as large as the public key structure
    if (cbBuffer < sizeof(PublicKeyBlob))
    {
        return false;
    }

    // The buffer must be the same size as the structure header plus the trailing key data
    const PublicKeyBlob *pkeyPublicKey = reinterpret_cast<const PublicKeyBlob *>(pbBuffer);
    if (GET_UNALIGNED_VAL32(&pkeyPublicKey->cbPublicKey) != cbBuffer - offsetof(PublicKeyBlob, PublicKey))
    {
        return false;
    }

    // The buffer itself looks reasonable, but the public key structure needs to be validated as well
    return StrongNameIsValidPublicKey(*pkeyPublicKey, fImportKeys);
}

//---------------------------------------------------------------------------------------
//
// Verify that a public key blob looks like a reasonable public key.
// 
// Arguments:
//   keyPublicKey - key blob to verify 
//   fImportKeys  - do a more extensive check by verifying that the key data imports into CAPI
// 
// Notes:
//    This can be a very expensive operation, since it involves importing keys.  
//

bool StrongNameIsValidPublicKey(const PublicKeyBlob &keyPublicKey, bool fImportKeys)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    // The ECMA key doesn't look like a valid key so it will fail the below checks. If we were passed that
    // key, then we can skip them
    if (StrongNameIsEcmaKey(keyPublicKey))
    {
        return true;
    }

    // If a hash algorithm is specified, it must be a sensible value
    bool fHashAlgorithmValid = GET_ALG_CLASS(GET_UNALIGNED_VAL32(&keyPublicKey.HashAlgID)) == ALG_CLASS_HASH &&
                               GET_ALG_SID(GET_UNALIGNED_VAL32(&keyPublicKey.HashAlgID)) >= ALG_SID_SHA1;
    if (keyPublicKey.HashAlgID != 0 && !fHashAlgorithmValid)
    {
        return false;
    }

    // If a signature algorithm is specified, it must be a sensible value
    bool fSignatureAlgorithmValid = GET_ALG_CLASS(GET_UNALIGNED_VAL32(&keyPublicKey.SigAlgID)) == ALG_CLASS_SIGNATURE;
    if (keyPublicKey.SigAlgID != 0 && !fSignatureAlgorithmValid)
    {
        return false;
    }

    // The key blob must indicate that it is a PUBLICKEYBLOB
    if (keyPublicKey.PublicKey[0] != PUBLICKEYBLOB)
    {
        return false;
    }

#if !defined(FEATURE_CORECLR) || (defined(CROSSGEN_COMPILE) && !defined(PLATFORM_UNIX))
    // Make sure the public key blob imports properly
    if (fImportKeys)
    {
        CapiProviderHolder hProv;
        if (!StrongNameCryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
        {
            return false;
        }

        CapiKeyHolder hKey;
        if (!CryptImportKey(hProv, keyPublicKey.PublicKey, GET_UNALIGNED_VAL32(&keyPublicKey.cbPublicKey), NULL, 0, &hKey))
        {
            return false;
        }
    }
#else // !FEATURE_CORECLR || (CROSSGEN_COMPILE && !PLATFORM_UNIX)
    _ASSERTE(!fImportKeys);
#endif // !FEATURE_CORECLR || (CROSSGEN_COMPILE && !PLATFORM_UNIX)

    return true;
}


//---------------------------------------------------------------------------------------
//
// Determine the number of bytes that a public key blob occupies, including the key portion
// 
// Arguments:
//   keyPublicKey - key blob to calculate the size of
//

DWORD StrongNameSizeOfPublicKey(const PublicKeyBlob &keyPublicKey)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
    }
    CONTRACTL_END;

    return offsetof(PublicKeyBlob, PublicKey) +     // Size of the blob header plus
           GET_UNALIGNED_VAL32(&keyPublicKey.cbPublicKey);  // the number of bytes in the key
}

#if !defined(FEATURE_CORECLR) || (defined(CROSSGEN_COMPILE) && !defined(PLATFORM_UNIX))

//---------------------------------------------------------------------------------------
//
// Check to see if the value held in a buffer is a full strong name key pair
//
// Arguments:
//    pbBuffer - Blob to check
//    cbBuffer - Size of the buffer in bytes
//
// Return Value:
//    true if the buffer represents a full strong name key pair, false otherwise
//

bool StrongNameIsValidKeyPair(__in_ecount(cbKeyPair) const BYTE *pbKeyPair, DWORD cbKeyPair)
{
    CONTRACTL
    {
        NOTHROW;
        GC_NOTRIGGER;
        PRECONDITION(CheckPointer(pbKeyPair));
    }
    CONTRACTL_END;

    // Key pairs are just CAPI PRIVATEKEYBLOBs, so see if CAPI can import the blob
    CapiProviderHolder hProv;
    if (!StrongNameCryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
    {
        return false;
    }

    CapiKeyHolder hKey;
    if (!CryptImportKey(hProv, pbKeyPair, cbKeyPair, NULL, 0, &hKey))
    {
        return false;
    }

    return true;
}


BYTE HexToByteA (char c) {
    LIMITED_METHOD_CONTRACT;

    if (!isxdigit(c)) return (BYTE) 0xff;
    if (isdigit(c)) return (BYTE) (c - '0');
    if (isupper(c)) return (BYTE) (c - 'A' + 10);
    return (BYTE) (c - 'a' + 10);
}
    
// Read the hex string into a buffer
// Caller owns the buffer. 
// Returns NULL if the string contains non-hex characters, or doesn't contain a multiple of 2 characters.
bool GetBytesFromHex(LPCUTF8 szHexString, ULONG cchHexString, BYTE** buffer, ULONG *cbBufferSize) {
    LIMITED_METHOD_CONTRACT;

    ULONG cchHex = cchHexString;
    if (cchHex % 2 != 0)
        return false;
    *cbBufferSize = cchHex / 2;
    NewArrayHolder<BYTE> tempBuffer(new (nothrow) BYTE[*cbBufferSize]);
    if (tempBuffer == NULL)
        return false;

    for (ULONG i = 0; i < *cbBufferSize; i++) {
        BYTE msn = HexToByteA(*szHexString);
        BYTE lsn = HexToByteA(*(szHexString + 1));
        if(msn == 0xFF || lsn == 0xFF)
        {
            return false;
        }

        tempBuffer[i] = (BYTE) ( (msn << 4) | lsn );
        szHexString += 2;
    }

    *buffer = tempBuffer.Extract();
    return true;
}

// Helper method to call CryptAcquireContext, making sure we have a valid set of flags
bool StrongNameCryptAcquireContext(HCRYPTPROV *phProv, LPCWSTR pwszContainer, LPCWSTR pwszProvider, DWORD dwProvType, DWORD dwFlags)
{
    LIMITED_METHOD_CONTRACT;

#if defined(CRYPT_VERIFYCONTEXT) && defined(CRYPT_MACHINE_KEYSET)
    // Specifying both verify context (for an ephemeral key) and machine keyset (for a persisted machine key)
    // does not make sense.  Additionally, Widows is beginning to lock down against uses of MACHINE_KEYSET
    // (for instance in the app container), even if verify context is present.   Therefore, if we're using
    // an ephemeral key, strip out MACHINE_KEYSET from the flags.
    if ((dwFlags & CRYPT_VERIFYCONTEXT) && (dwFlags & CRYPT_MACHINE_KEYSET))
    {
        dwFlags &= ~CRYPT_MACHINE_KEYSET;
    }
#endif // FEATURE_CRYPTO

    return !!WszCryptAcquireContext(phProv, pwszContainer, pwszProvider, dwProvType, dwFlags);
}

#endif // !FEATURE_CORECLR || (CROSSGEN_COMPILE && !PLATFORM_UNIX)