Coverage Report

Created: 2025-10-10 06:45

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/FreeRDP/winpr/libwinpr/ncrypt/ncrypt_pkcs11.c
Line
Count
Source
1
/**
2
 * WinPR: Windows Portable Runtime
3
 * NCrypt pkcs11 provider
4
 *
5
 * Copyright 2021 David Fort <contact@hardening-consulting.com>
6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
20
#include <stdlib.h>
21
22
#include <winpr/library.h>
23
#include <winpr/assert.h>
24
#include <winpr/spec.h>
25
#include <winpr/smartcard.h>
26
#include <winpr/asn1.h>
27
28
#include "../log.h"
29
#include "ncrypt.h"
30
31
/* https://github.com/latchset/pkcs11-headers/blob/main/public-domain/3.1/pkcs11.h */
32
#include "pkcs11-headers/pkcs11.h"
33
34
#define TAG WINPR_TAG("ncryptp11")
35
36
0
#define MAX_SLOTS 64
37
#define MAX_KEYS 64
38
#define MAX_KEYS_PER_SLOT 64
39
40
/** @brief ncrypt provider handle */
41
typedef struct
42
{
43
  NCryptBaseProvider baseProvider;
44
45
  HANDLE library;
46
  CK_FUNCTION_LIST_PTR p11;
47
  char* modulePath;
48
} NCryptP11ProviderHandle;
49
50
/** @brief a handle returned by NCryptOpenKey */
51
typedef struct
52
{
53
  NCryptBaseHandle base;
54
  NCryptP11ProviderHandle* provider;
55
  CK_SLOT_ID slotId;
56
  CK_BYTE keyCertId[64];
57
  CK_ULONG keyCertIdLen;
58
} NCryptP11KeyHandle;
59
60
typedef struct
61
{
62
  CK_SLOT_ID slotId;
63
  CK_SLOT_INFO slotInfo;
64
  CK_KEY_TYPE keyType;
65
  CK_CHAR keyLabel[256];
66
  CK_ULONG idLen;
67
  CK_BYTE id[64];
68
} NCryptKeyEnum;
69
70
typedef struct
71
{
72
  CK_ULONG nslots;
73
  CK_SLOT_ID slots[MAX_SLOTS];
74
  CK_ULONG nKeys;
75
  NCryptKeyEnum keys[MAX_KEYS];
76
  CK_ULONG keyIndex;
77
} P11EnumKeysState;
78
79
typedef struct
80
{
81
  const char* label;
82
  BYTE tag[3];
83
} piv_cert_tags_t;
84
static const piv_cert_tags_t piv_cert_tags[] = {
85
  { "X.509 Certificate for PIV Authentication", "\x5F\xC1\x05" },
86
  { "X.509 Certificate for Digital Signature", "\x5F\xC1\x0A" },
87
  { "X.509 Certificate for Key Management", "\x5F\xC1\x0B" },
88
  { "X.509 Certificate for Card Authentication", "\x5F\xC1\x01" },
89
90
  { "Certificate for PIV Authentication", "\x5F\xC1\x05" },
91
  { "Certificate for Digital Signature", "\x5F\xC1\x0A" },
92
  { "Certificate for Key Management", "\x5F\xC1\x0B" },
93
  { "Certificate for Card Authentication", "\x5F\xC1\x01" },
94
};
95
96
static const BYTE APDU_PIV_SELECT_AID[] = { 0x00, 0xA4, 0x04, 0x00, 0x09, 0xA0, 0x00, 0x00,
97
                                          0x03, 0x08, 0x00, 0x00, 0x10, 0x00, 0x00 };
98
static const BYTE APDU_PIV_GET_CHUID[] = { 0x00, 0xCB, 0x3F, 0xFF, 0x05, 0x5C,
99
                                         0x03, 0x5F, 0xC1, 0x02, 0x00 };
100
0
#define PIV_CONTAINER_NAME_LEN 36
101
102
static CK_OBJECT_CLASS object_class_public_key = CKO_PUBLIC_KEY;
103
static CK_BBOOL object_verify = CK_TRUE;
104
static CK_KEY_TYPE object_ktype_rsa = CKK_RSA;
105
106
static CK_ATTRIBUTE public_key_filter[] = {
107
  { CKA_CLASS, &object_class_public_key, sizeof(object_class_public_key) },
108
  { CKA_VERIFY, &object_verify, sizeof(object_verify) },
109
  { CKA_KEY_TYPE, &object_ktype_rsa, sizeof(object_ktype_rsa) }
110
};
111
112
static const char* CK_RV_error_string(CK_RV rv);
113
114
static SECURITY_STATUS NCryptP11StorageProvider_dtor(NCRYPT_HANDLE handle)
115
0
{
116
0
  NCryptP11ProviderHandle* provider = (NCryptP11ProviderHandle*)handle;
117
0
  CK_RV rv = CKR_OK;
118
119
0
  if (provider)
120
0
  {
121
0
    if (provider->p11 && provider->p11->C_Finalize)
122
0
      rv = provider->p11->C_Finalize(NULL);
123
0
    if (rv != CKR_OK)
124
0
      WLog_WARN(TAG, "C_Finalize failed with %s [0x%08" PRIx32 "]", CK_RV_error_string(rv),
125
0
                rv);
126
127
0
    free(provider->modulePath);
128
129
0
    if (provider->library)
130
0
      FreeLibrary(provider->library);
131
0
  }
132
133
0
  return winpr_NCryptDefault_dtor(handle);
134
0
}
135
136
static void fix_padded_string(char* str, size_t maxlen)
137
0
{
138
0
  if (maxlen == 0)
139
0
    return;
140
141
0
  WINPR_ASSERT(str);
142
0
  char* ptr = &str[maxlen - 1];
143
144
0
  while ((ptr > str) && (*ptr == ' '))
145
0
  {
146
0
    *ptr = '\0';
147
0
    ptr--;
148
0
  }
149
0
}
150
151
static BOOL attributes_have_unallocated_buffers(CK_ATTRIBUTE_PTR attributes, CK_ULONG count)
152
0
{
153
0
  for (CK_ULONG i = 0; i < count; i++)
154
0
  {
155
0
    if (!attributes[i].pValue && (attributes[i].ulValueLen != CK_UNAVAILABLE_INFORMATION))
156
0
      return TRUE;
157
0
  }
158
159
0
  return FALSE;
160
0
}
161
162
static BOOL attribute_allocate_attribute_array(CK_ATTRIBUTE_PTR attribute)
163
0
{
164
0
  WINPR_ASSERT(attribute);
165
0
  attribute->pValue = calloc(attribute->ulValueLen, sizeof(void*));
166
0
  return !!attribute->pValue;
167
0
}
168
169
static BOOL attribute_allocate_ulong_array(CK_ATTRIBUTE_PTR attribute)
170
0
{
171
0
  attribute->pValue = calloc(attribute->ulValueLen, sizeof(CK_ULONG));
172
0
  return !!attribute->pValue;
173
0
}
174
175
static BOOL attribute_allocate_buffer(CK_ATTRIBUTE_PTR attribute)
176
0
{
177
0
  attribute->pValue = calloc(attribute->ulValueLen, 1);
178
0
  return !!attribute->pValue;
179
0
}
180
181
static BOOL attributes_allocate_buffers(CK_ATTRIBUTE_PTR attributes, CK_ULONG count)
182
0
{
183
0
  BOOL ret = TRUE;
184
185
0
  for (CK_ULONG i = 0; i < count; i++)
186
0
  {
187
0
    if (attributes[i].pValue || (attributes[i].ulValueLen == CK_UNAVAILABLE_INFORMATION))
188
0
      continue;
189
190
0
    switch (attributes[i].type)
191
0
    {
192
0
      case CKA_WRAP_TEMPLATE:
193
0
      case CKA_UNWRAP_TEMPLATE:
194
0
        ret &= attribute_allocate_attribute_array(&attributes[i]);
195
0
        break;
196
197
0
      case CKA_ALLOWED_MECHANISMS:
198
0
        ret &= attribute_allocate_ulong_array(&attributes[i]);
199
0
        break;
200
201
0
      default:
202
0
        ret &= attribute_allocate_buffer(&attributes[i]);
203
0
        break;
204
0
    }
205
0
  }
206
207
0
  return ret;
208
0
}
209
210
static CK_RV object_load_attributes(NCryptP11ProviderHandle* provider, CK_SESSION_HANDLE session,
211
                                    CK_OBJECT_HANDLE object, CK_ATTRIBUTE_PTR attributes,
212
                                    CK_ULONG count)
213
0
{
214
0
  WINPR_ASSERT(provider);
215
0
  WINPR_ASSERT(provider->p11);
216
0
  WINPR_ASSERT(provider->p11->C_GetAttributeValue);
217
218
0
  CK_RV rv = provider->p11->C_GetAttributeValue(session, object, attributes, count);
219
220
0
  switch (rv)
221
0
  {
222
0
    case CKR_OK:
223
0
      if (!attributes_have_unallocated_buffers(attributes, count))
224
0
        return rv;
225
      /* fallthrough */
226
0
      WINPR_FALLTHROUGH
227
0
    case CKR_ATTRIBUTE_SENSITIVE:
228
0
    case CKR_ATTRIBUTE_TYPE_INVALID:
229
0
    case CKR_BUFFER_TOO_SMALL:
230
      /* attributes need some buffers for the result value */
231
0
      if (!attributes_allocate_buffers(attributes, count))
232
0
        return CKR_HOST_MEMORY;
233
234
0
      rv = provider->p11->C_GetAttributeValue(session, object, attributes, count);
235
0
      if (rv != CKR_OK)
236
0
        WLog_WARN(TAG, "C_GetAttributeValue failed with %s [0x%08" PRIx32 "]",
237
0
                  CK_RV_error_string(rv), rv);
238
0
      break;
239
0
    default:
240
0
      WLog_WARN(TAG, "C_GetAttributeValue failed with %s [0x%08" PRIx32 "]",
241
0
                CK_RV_error_string(rv), rv);
242
0
      return rv;
243
0
  }
244
245
0
  switch (rv)
246
0
  {
247
0
    case CKR_ATTRIBUTE_SENSITIVE:
248
0
    case CKR_ATTRIBUTE_TYPE_INVALID:
249
0
    case CKR_BUFFER_TOO_SMALL:
250
0
      WLog_ERR(TAG,
251
0
               "C_GetAttributeValue failed with %s [0x%08" PRIx32
252
0
               "] even after buffer allocation",
253
0
               CK_RV_error_string(rv), rv);
254
0
      break;
255
0
    default:
256
0
      break;
257
0
  }
258
0
  return rv;
259
0
}
260
261
static const char* CK_RV_error_string(CK_RV rv)
262
0
{
263
0
  static char generic_buffer[200];
264
0
#define ERR_ENTRY(X) \
265
0
  case X:          \
266
0
    return #X
267
268
0
  switch (rv)
269
0
  {
270
0
    ERR_ENTRY(CKR_OK);
271
0
    ERR_ENTRY(CKR_CANCEL);
272
0
    ERR_ENTRY(CKR_HOST_MEMORY);
273
0
    ERR_ENTRY(CKR_SLOT_ID_INVALID);
274
0
    ERR_ENTRY(CKR_GENERAL_ERROR);
275
0
    ERR_ENTRY(CKR_FUNCTION_FAILED);
276
0
    ERR_ENTRY(CKR_ARGUMENTS_BAD);
277
0
    ERR_ENTRY(CKR_NO_EVENT);
278
0
    ERR_ENTRY(CKR_NEED_TO_CREATE_THREADS);
279
0
    ERR_ENTRY(CKR_CANT_LOCK);
280
0
    ERR_ENTRY(CKR_ATTRIBUTE_READ_ONLY);
281
0
    ERR_ENTRY(CKR_ATTRIBUTE_SENSITIVE);
282
0
    ERR_ENTRY(CKR_ATTRIBUTE_TYPE_INVALID);
283
0
    ERR_ENTRY(CKR_ATTRIBUTE_VALUE_INVALID);
284
0
    ERR_ENTRY(CKR_DATA_INVALID);
285
0
    ERR_ENTRY(CKR_DATA_LEN_RANGE);
286
0
    ERR_ENTRY(CKR_DEVICE_ERROR);
287
0
    ERR_ENTRY(CKR_DEVICE_MEMORY);
288
0
    ERR_ENTRY(CKR_DEVICE_REMOVED);
289
0
    ERR_ENTRY(CKR_ENCRYPTED_DATA_INVALID);
290
0
    ERR_ENTRY(CKR_ENCRYPTED_DATA_LEN_RANGE);
291
0
    ERR_ENTRY(CKR_FUNCTION_CANCELED);
292
0
    ERR_ENTRY(CKR_FUNCTION_NOT_PARALLEL);
293
0
    ERR_ENTRY(CKR_FUNCTION_NOT_SUPPORTED);
294
0
    ERR_ENTRY(CKR_KEY_HANDLE_INVALID);
295
0
    ERR_ENTRY(CKR_KEY_SIZE_RANGE);
296
0
    ERR_ENTRY(CKR_KEY_TYPE_INCONSISTENT);
297
0
    ERR_ENTRY(CKR_KEY_NOT_NEEDED);
298
0
    ERR_ENTRY(CKR_KEY_CHANGED);
299
0
    ERR_ENTRY(CKR_KEY_NEEDED);
300
0
    ERR_ENTRY(CKR_KEY_INDIGESTIBLE);
301
0
    ERR_ENTRY(CKR_KEY_FUNCTION_NOT_PERMITTED);
302
0
    ERR_ENTRY(CKR_KEY_NOT_WRAPPABLE);
303
0
    ERR_ENTRY(CKR_KEY_UNEXTRACTABLE);
304
0
    ERR_ENTRY(CKR_MECHANISM_INVALID);
305
0
    ERR_ENTRY(CKR_MECHANISM_PARAM_INVALID);
306
0
    ERR_ENTRY(CKR_OBJECT_HANDLE_INVALID);
307
0
    ERR_ENTRY(CKR_OPERATION_ACTIVE);
308
0
    ERR_ENTRY(CKR_OPERATION_NOT_INITIALIZED);
309
0
    ERR_ENTRY(CKR_PIN_INCORRECT);
310
0
    ERR_ENTRY(CKR_PIN_INVALID);
311
0
    ERR_ENTRY(CKR_PIN_LEN_RANGE);
312
0
    ERR_ENTRY(CKR_PIN_EXPIRED);
313
0
    ERR_ENTRY(CKR_PIN_LOCKED);
314
0
    ERR_ENTRY(CKR_SESSION_CLOSED);
315
0
    ERR_ENTRY(CKR_SESSION_COUNT);
316
0
    ERR_ENTRY(CKR_SESSION_HANDLE_INVALID);
317
0
    ERR_ENTRY(CKR_SESSION_PARALLEL_NOT_SUPPORTED);
318
0
    ERR_ENTRY(CKR_SESSION_READ_ONLY);
319
0
    ERR_ENTRY(CKR_SESSION_EXISTS);
320
0
    ERR_ENTRY(CKR_SESSION_READ_ONLY_EXISTS);
321
0
    ERR_ENTRY(CKR_SESSION_READ_WRITE_SO_EXISTS);
322
0
    ERR_ENTRY(CKR_SIGNATURE_INVALID);
323
0
    ERR_ENTRY(CKR_SIGNATURE_LEN_RANGE);
324
0
    ERR_ENTRY(CKR_TEMPLATE_INCOMPLETE);
325
0
    ERR_ENTRY(CKR_TEMPLATE_INCONSISTENT);
326
0
    ERR_ENTRY(CKR_TOKEN_NOT_PRESENT);
327
0
    ERR_ENTRY(CKR_TOKEN_NOT_RECOGNIZED);
328
0
    ERR_ENTRY(CKR_TOKEN_WRITE_PROTECTED);
329
0
    ERR_ENTRY(CKR_UNWRAPPING_KEY_HANDLE_INVALID);
330
0
    ERR_ENTRY(CKR_UNWRAPPING_KEY_SIZE_RANGE);
331
0
    ERR_ENTRY(CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT);
332
0
    ERR_ENTRY(CKR_USER_ALREADY_LOGGED_IN);
333
0
    ERR_ENTRY(CKR_USER_NOT_LOGGED_IN);
334
0
    ERR_ENTRY(CKR_USER_PIN_NOT_INITIALIZED);
335
0
    ERR_ENTRY(CKR_USER_TYPE_INVALID);
336
0
    ERR_ENTRY(CKR_USER_ANOTHER_ALREADY_LOGGED_IN);
337
0
    ERR_ENTRY(CKR_USER_TOO_MANY_TYPES);
338
0
    ERR_ENTRY(CKR_WRAPPED_KEY_INVALID);
339
0
    ERR_ENTRY(CKR_WRAPPED_KEY_LEN_RANGE);
340
0
    ERR_ENTRY(CKR_WRAPPING_KEY_HANDLE_INVALID);
341
0
    ERR_ENTRY(CKR_WRAPPING_KEY_SIZE_RANGE);
342
0
    ERR_ENTRY(CKR_WRAPPING_KEY_TYPE_INCONSISTENT);
343
0
    ERR_ENTRY(CKR_RANDOM_SEED_NOT_SUPPORTED);
344
0
    ERR_ENTRY(CKR_RANDOM_NO_RNG);
345
0
    ERR_ENTRY(CKR_DOMAIN_PARAMS_INVALID);
346
0
    ERR_ENTRY(CKR_BUFFER_TOO_SMALL);
347
0
    ERR_ENTRY(CKR_SAVED_STATE_INVALID);
348
0
    ERR_ENTRY(CKR_INFORMATION_SENSITIVE);
349
0
    ERR_ENTRY(CKR_STATE_UNSAVEABLE);
350
0
    ERR_ENTRY(CKR_CRYPTOKI_NOT_INITIALIZED);
351
0
    ERR_ENTRY(CKR_CRYPTOKI_ALREADY_INITIALIZED);
352
0
    ERR_ENTRY(CKR_MUTEX_BAD);
353
0
    ERR_ENTRY(CKR_MUTEX_NOT_LOCKED);
354
0
    ERR_ENTRY(CKR_FUNCTION_REJECTED);
355
0
    default:
356
0
      (void)snprintf(generic_buffer, sizeof(generic_buffer), "unknown 0x%lx", rv);
357
0
      return generic_buffer;
358
0
  }
359
0
#undef ERR_ENTRY
360
0
}
361
362
#define loge(tag, msg, rv, index, slot) \
363
0
  log_((tag), (msg), (rv), (index), (slot), __FILE__, __func__, __LINE__)
364
static void log_(const char* tag, const char* msg, CK_RV rv, CK_ULONG index, CK_SLOT_ID slot,
365
                 const char* file, const char* fkt, size_t line)
366
0
{
367
0
  const DWORD log_level = WLOG_ERROR;
368
0
  static wLog* log_cached_ptr = NULL;
369
0
  if (!log_cached_ptr)
370
0
    log_cached_ptr = WLog_Get(tag);
371
0
  if (!WLog_IsLevelActive(log_cached_ptr, log_level))
372
0
    return;
373
374
0
  WLog_PrintTextMessage(log_cached_ptr, log_level, line, file, fkt,
375
0
                        "%s for slot #%lu(%lu), rv=%s", msg, index, slot, CK_RV_error_string(rv));
376
0
}
377
378
static SECURITY_STATUS collect_keys(NCryptP11ProviderHandle* provider, P11EnumKeysState* state)
379
0
{
380
0
  CK_OBJECT_HANDLE slotObjects[MAX_KEYS_PER_SLOT] = { 0 };
381
382
0
  WINPR_ASSERT(provider);
383
384
0
  CK_FUNCTION_LIST_PTR p11 = provider->p11;
385
0
  WINPR_ASSERT(p11);
386
387
0
  WLog_DBG(TAG, "checking %" PRIu32 " slots for valid keys...", state->nslots);
388
0
  state->nKeys = 0;
389
0
  for (CK_ULONG i = 0; i < state->nslots; i++)
390
0
  {
391
0
    CK_SESSION_HANDLE session = (CK_SESSION_HANDLE)NULL;
392
0
    CK_SLOT_INFO slotInfo = { 0 };
393
0
    CK_TOKEN_INFO tokenInfo = { 0 };
394
395
0
    WINPR_ASSERT(p11->C_GetSlotInfo);
396
0
    CK_RV rv = p11->C_GetSlotInfo(state->slots[i], &slotInfo);
397
0
    if (rv != CKR_OK)
398
0
    {
399
0
      loge(TAG, "unable to retrieve information", rv, i, state->slots[i]);
400
0
      continue;
401
0
    }
402
403
0
    fix_padded_string((char*)slotInfo.slotDescription, sizeof(slotInfo.slotDescription));
404
0
    WLog_DBG(TAG, "collecting keys for slot #%" PRIu32 "(%" PRIu32 ") descr='%s' flags=0x%x", i,
405
0
             state->slots[i], slotInfo.slotDescription, slotInfo.flags);
406
407
    /* this is a safety guard as we're supposed to have listed only readers with tokens in them
408
     */
409
0
    if (!(slotInfo.flags & CKF_TOKEN_PRESENT))
410
0
    {
411
0
      WLog_INFO(TAG, "token not present for slot #%" PRIu32 "(%" PRIu32 ")", i,
412
0
                state->slots[i]);
413
0
      continue;
414
0
    }
415
416
0
    WINPR_ASSERT(p11->C_GetTokenInfo);
417
0
    rv = p11->C_GetTokenInfo(state->slots[i], &tokenInfo);
418
0
    if (rv != CKR_OK)
419
0
      loge(TAG, "unable to retrieve token info", rv, i, state->slots[i]);
420
0
    else
421
0
    {
422
0
      fix_padded_string((char*)tokenInfo.label, sizeof(tokenInfo.label));
423
0
      WLog_DBG(TAG, "token, label='%s' flags=0x%x", tokenInfo.label, tokenInfo.flags);
424
0
    }
425
426
0
    WINPR_ASSERT(p11->C_OpenSession);
427
0
    rv = p11->C_OpenSession(state->slots[i], CKF_SERIAL_SESSION, NULL, NULL, &session);
428
0
    if (rv != CKR_OK)
429
0
    {
430
0
      WLog_ERR(TAG,
431
0
               "unable to openSession for slot #%" PRIu32 "(%" PRIu32 "), session=%p rv=%s",
432
0
               i, state->slots[i], session, CK_RV_error_string(rv));
433
0
      continue;
434
0
    }
435
436
0
    WINPR_ASSERT(p11->C_FindObjectsInit);
437
0
    rv = p11->C_FindObjectsInit(session, public_key_filter, ARRAYSIZE(public_key_filter));
438
0
    if (rv != CKR_OK)
439
0
    {
440
      // TODO: shall it be fatal ?
441
0
      loge(TAG, "unable to initiate search", rv, i, state->slots[i]);
442
0
      goto cleanup_FindObjectsInit;
443
0
    }
444
445
0
    CK_ULONG nslotObjects = 0;
446
0
    WINPR_ASSERT(p11->C_FindObjects);
447
0
    rv = p11->C_FindObjects(session, &slotObjects[0], ARRAYSIZE(slotObjects), &nslotObjects);
448
0
    if (rv != CKR_OK)
449
0
    {
450
0
      loge(TAG, "unable to findObjects", rv, i, state->slots[i]);
451
0
      goto cleanup_FindObjects;
452
0
    }
453
454
0
    WLog_DBG(TAG, "slot has %d objects", nslotObjects);
455
0
    for (CK_ULONG j = 0; j < nslotObjects; j++)
456
0
    {
457
0
      NCryptKeyEnum* key = &state->keys[state->nKeys];
458
0
      CK_OBJECT_CLASS dataClass = CKO_PUBLIC_KEY;
459
0
      CK_ATTRIBUTE key_or_certAttrs[] = {
460
0
        { CKA_ID, &key->id, sizeof(key->id) },
461
0
        { CKA_CLASS, &dataClass, sizeof(dataClass) },
462
0
        { CKA_LABEL, &key->keyLabel, sizeof(key->keyLabel) },
463
0
        { CKA_KEY_TYPE, &key->keyType, sizeof(key->keyType) }
464
0
      };
465
466
0
      rv = object_load_attributes(provider, session, slotObjects[j], key_or_certAttrs,
467
0
                                  ARRAYSIZE(key_or_certAttrs));
468
0
      if (rv != CKR_OK)
469
0
      {
470
0
        WLog_ERR(TAG, "error getting attributes, rv=%s", CK_RV_error_string(rv));
471
0
        continue;
472
0
      }
473
474
0
      key->idLen = key_or_certAttrs[0].ulValueLen;
475
0
      key->slotId = state->slots[i];
476
0
      key->slotInfo = slotInfo;
477
0
      state->nKeys++;
478
0
    }
479
480
0
  cleanup_FindObjects:
481
0
    WINPR_ASSERT(p11->C_FindObjectsFinal);
482
0
    rv = p11->C_FindObjectsFinal(session);
483
0
    if (rv != CKR_OK)
484
0
      loge(TAG, "error during C_FindObjectsFinal", rv, i, state->slots[i]);
485
0
  cleanup_FindObjectsInit:
486
0
    WINPR_ASSERT(p11->C_CloseSession);
487
0
    rv = p11->C_CloseSession(session);
488
0
    if (rv != CKR_OK)
489
0
      loge(TAG, "error closing session", rv, i, state->slots[i]);
490
0
  }
491
492
0
  return ERROR_SUCCESS;
493
0
}
494
495
static BOOL convertKeyType(CK_KEY_TYPE k, LPWSTR dest, DWORD len, DWORD* outlen)
496
0
{
497
0
  const WCHAR* r = NULL;
498
0
  size_t retLen = 0;
499
500
0
#define ALGO_CASE(V, S)                         \
501
0
  case V:                                     \
502
0
    r = S;                                  \
503
0
    retLen = _wcsnlen((S), ARRAYSIZE((S))); \
504
0
    break
505
0
  switch (k)
506
0
  {
507
0
    ALGO_CASE(CKK_RSA, BCRYPT_RSA_ALGORITHM);
508
0
    ALGO_CASE(CKK_DSA, BCRYPT_DSA_ALGORITHM);
509
0
    ALGO_CASE(CKK_DH, BCRYPT_DH_ALGORITHM);
510
0
    ALGO_CASE(CKK_EC, BCRYPT_ECDSA_ALGORITHM);
511
0
    ALGO_CASE(CKK_RC2, BCRYPT_RC2_ALGORITHM);
512
0
    ALGO_CASE(CKK_RC4, BCRYPT_RC4_ALGORITHM);
513
0
    ALGO_CASE(CKK_DES, BCRYPT_DES_ALGORITHM);
514
0
    ALGO_CASE(CKK_DES3, BCRYPT_3DES_ALGORITHM);
515
0
    case CKK_DES2:
516
0
    case CKK_X9_42_DH:
517
0
    case CKK_KEA:
518
0
    case CKK_GENERIC_SECRET:
519
0
    case CKK_CAST:
520
0
    case CKK_CAST3:
521
0
    case CKK_CAST128:
522
0
    case CKK_RC5:
523
0
    case CKK_IDEA:
524
0
    case CKK_SKIPJACK:
525
0
    case CKK_BATON:
526
0
    case CKK_JUNIPER:
527
0
    case CKK_CDMF:
528
0
    case CKK_AES:
529
0
    case CKK_BLOWFISH:
530
0
    case CKK_TWOFISH:
531
0
    default:
532
0
      break;
533
0
  }
534
0
#undef ALGO_CASE
535
536
0
  if (retLen > UINT32_MAX)
537
0
    return FALSE;
538
539
0
  if (outlen)
540
0
    *outlen = (UINT32)retLen;
541
542
0
  if (!r)
543
0
  {
544
0
    if (dest && len > 0)
545
0
      dest[0] = 0;
546
0
    return FALSE;
547
0
  }
548
549
0
  if (dest)
550
0
  {
551
0
    if (retLen + 1 > len)
552
0
    {
553
0
      WLog_ERR(TAG, "target buffer is too small for algo name");
554
0
      return FALSE;
555
0
    }
556
557
0
    memcpy(dest, r, sizeof(WCHAR) * retLen);
558
0
    dest[retLen] = 0;
559
0
  }
560
561
0
  return TRUE;
562
0
}
563
564
static void wprintKeyName(LPWSTR str, CK_SLOT_ID slotId, CK_BYTE* id, CK_ULONG idLen)
565
0
{
566
0
  char asciiName[128] = { 0 };
567
0
  char* ptr = asciiName;
568
0
  const CK_BYTE* bytePtr = NULL;
569
570
0
  *ptr = '\\';
571
0
  ptr++;
572
573
0
  bytePtr = ((CK_BYTE*)&slotId);
574
0
  for (CK_ULONG i = 0; i < sizeof(slotId); i++, bytePtr++, ptr += 2)
575
0
    (void)snprintf(ptr, 3, "%.2x", *bytePtr);
576
577
0
  *ptr = '\\';
578
0
  ptr++;
579
580
0
  for (CK_ULONG i = 0; i < idLen; i++, id++, ptr += 2)
581
0
    (void)snprintf(ptr, 3, "%.2x", *id);
582
583
0
  (void)ConvertUtf8NToWChar(asciiName, ARRAYSIZE(asciiName), str,
584
0
                            strnlen(asciiName, ARRAYSIZE(asciiName)) + 1);
585
0
}
586
587
static size_t parseHex(const char* str, const char* end, CK_BYTE* target)
588
0
{
589
0
  size_t ret = 0;
590
591
0
  for (; str != end && *str; str++, ret++, target++)
592
0
  {
593
0
    int v = 0;
594
0
    if (*str <= '9' && *str >= '0')
595
0
    {
596
0
      v = (*str - '0');
597
0
    }
598
0
    else if (*str <= 'f' && *str >= 'a')
599
0
    {
600
0
      v = (10 + *str - 'a');
601
0
    }
602
0
    else if (*str <= 'F' && *str >= 'A')
603
0
    {
604
0
      v |= (10 + *str - 'A');
605
0
    }
606
0
    else
607
0
    {
608
0
      return 0;
609
0
    }
610
0
    v <<= 4;
611
0
    str++;
612
613
0
    if (!*str || str == end)
614
0
      return 0;
615
616
0
    if (*str <= '9' && *str >= '0')
617
0
    {
618
0
      v |= (*str - '0');
619
0
    }
620
0
    else if (*str <= 'f' && *str >= 'a')
621
0
    {
622
0
      v |= (10 + *str - 'a');
623
0
    }
624
0
    else if (*str <= 'F' && *str >= 'A')
625
0
    {
626
0
      v |= (10 + *str - 'A');
627
0
    }
628
0
    else
629
0
    {
630
0
      return 0;
631
0
    }
632
633
0
    *target = v & 0xFF;
634
0
  }
635
0
  return ret;
636
0
}
637
638
static SECURITY_STATUS parseKeyName(LPCWSTR pszKeyName, CK_SLOT_ID* slotId, CK_BYTE* id,
639
                                    CK_ULONG* idLen)
640
0
{
641
0
  char asciiKeyName[128] = { 0 };
642
0
  char* pos = NULL;
643
644
0
  if (ConvertWCharToUtf8(pszKeyName, asciiKeyName, ARRAYSIZE(asciiKeyName)) < 0)
645
0
    return NTE_BAD_KEY;
646
647
0
  if (*asciiKeyName != '\\')
648
0
    return NTE_BAD_KEY;
649
650
0
  pos = strchr(&asciiKeyName[1], '\\');
651
0
  if (!pos)
652
0
    return NTE_BAD_KEY;
653
654
0
  if ((size_t)(pos - &asciiKeyName[1]) > sizeof(CK_SLOT_ID) * 2ull)
655
0
    return NTE_BAD_KEY;
656
657
0
  *slotId = (CK_SLOT_ID)0;
658
0
  if (parseHex(&asciiKeyName[1], pos, (CK_BYTE*)slotId) != sizeof(CK_SLOT_ID))
659
0
    return NTE_BAD_KEY;
660
661
0
  *idLen = parseHex(pos + 1, NULL, id);
662
0
  if (!*idLen)
663
0
    return NTE_BAD_KEY;
664
665
0
  return ERROR_SUCCESS;
666
0
}
667
668
static SECURITY_STATUS NCryptP11EnumKeys(NCRYPT_PROV_HANDLE hProvider, LPCWSTR pszScope,
669
                                         NCryptKeyName** ppKeyName, PVOID* ppEnumState,
670
                                         WINPR_ATTR_UNUSED DWORD dwFlags)
671
0
{
672
0
  NCryptP11ProviderHandle* provider = (NCryptP11ProviderHandle*)hProvider;
673
0
  P11EnumKeysState* state = (P11EnumKeysState*)*ppEnumState;
674
0
  CK_RV rv = { 0 };
675
0
  CK_SLOT_ID currentSlot = { 0 };
676
0
  CK_SESSION_HANDLE currentSession = (CK_SESSION_HANDLE)NULL;
677
0
  char slotFilterBuffer[65] = { 0 };
678
0
  char* slotFilter = NULL;
679
0
  size_t slotFilterLen = 0;
680
681
0
  SECURITY_STATUS ret = checkNCryptHandle((NCRYPT_HANDLE)hProvider, WINPR_NCRYPT_PROVIDER);
682
0
  if (ret != ERROR_SUCCESS)
683
0
    return ret;
684
685
0
  if (pszScope)
686
0
  {
687
    /*
688
     * check whether pszScope is of the form \\.\<reader name>\ for filtering by
689
     * card reader
690
     */
691
0
    char asciiScope[128 + 6 + 1] = { 0 };
692
0
    size_t asciiScopeLen = 0;
693
694
0
    if (ConvertWCharToUtf8(pszScope, asciiScope, ARRAYSIZE(asciiScope) - 1) < 0)
695
0
    {
696
0
      WLog_WARN(TAG, "Invalid scope");
697
0
      return NTE_INVALID_PARAMETER;
698
0
    }
699
700
0
    if (strstr(asciiScope, "\\\\.\\") != asciiScope)
701
0
    {
702
0
      WLog_WARN(TAG, "Invalid scope '%s'", asciiScope);
703
0
      return NTE_INVALID_PARAMETER;
704
0
    }
705
706
0
    asciiScopeLen = strnlen(asciiScope, ARRAYSIZE(asciiScope));
707
0
    if ((asciiScopeLen < 1) || (asciiScope[asciiScopeLen - 1] != '\\'))
708
0
    {
709
0
      WLog_WARN(TAG, "Invalid scope '%s'", asciiScope);
710
0
      return NTE_INVALID_PARAMETER;
711
0
    }
712
713
0
    asciiScope[asciiScopeLen - 1] = 0;
714
715
0
    strncpy(slotFilterBuffer, &asciiScope[4], sizeof(slotFilterBuffer));
716
0
    slotFilter = slotFilterBuffer;
717
0
    slotFilterLen = asciiScopeLen - 5;
718
0
  }
719
720
0
  if (!state)
721
0
  {
722
0
    state = (P11EnumKeysState*)calloc(1, sizeof(*state));
723
0
    if (!state)
724
0
      return NTE_NO_MEMORY;
725
726
0
    WINPR_ASSERT(provider->p11->C_GetSlotList);
727
0
    rv = provider->p11->C_GetSlotList(CK_TRUE, NULL, &state->nslots);
728
0
    if (rv != CKR_OK)
729
0
    {
730
0
      free(state);
731
      /* TODO: perhaps convert rv to NTE_*** errors */
732
0
      WLog_WARN(TAG, "C_GetSlotList failed with %s [0x%08" PRIx32 "]", CK_RV_error_string(rv),
733
0
                rv);
734
0
      return NTE_FAIL;
735
0
    }
736
737
0
    if (state->nslots > MAX_SLOTS)
738
0
      state->nslots = MAX_SLOTS;
739
740
0
    rv = provider->p11->C_GetSlotList(CK_TRUE, state->slots, &state->nslots);
741
0
    if (rv != CKR_OK)
742
0
    {
743
0
      free(state);
744
      /* TODO: perhaps convert rv to NTE_*** errors */
745
0
      WLog_WARN(TAG, "C_GetSlotList failed with %s [0x%08" PRIx32 "]", CK_RV_error_string(rv),
746
0
                rv);
747
0
      return NTE_FAIL;
748
0
    }
749
750
0
    ret = collect_keys(provider, state);
751
0
    if (ret != ERROR_SUCCESS)
752
0
    {
753
0
      free(state);
754
0
      return ret;
755
0
    }
756
757
0
    *ppEnumState = state;
758
0
  }
759
760
0
  for (; state->keyIndex < state->nKeys; state->keyIndex++)
761
0
  {
762
0
    NCryptKeyName* keyName = NULL;
763
0
    NCryptKeyEnum* key = &state->keys[state->keyIndex];
764
0
    CK_OBJECT_CLASS oclass = CKO_CERTIFICATE;
765
0
    CK_CERTIFICATE_TYPE ctype = CKC_X_509;
766
0
    CK_ATTRIBUTE certificateFilter[] = { { CKA_CLASS, &oclass, sizeof(oclass) },
767
0
                                       { CKA_CERTIFICATE_TYPE, &ctype, sizeof(ctype) },
768
0
                                       { CKA_ID, key->id, key->idLen } };
769
0
    CK_ULONG ncertObjects = 0;
770
0
    CK_OBJECT_HANDLE certObject = 0;
771
772
    /* check the reader filter if any */
773
0
    if (slotFilter && memcmp(key->slotInfo.slotDescription, slotFilter, slotFilterLen) != 0)
774
0
      continue;
775
776
0
    if (!currentSession || (currentSlot != key->slotId))
777
0
    {
778
      /* if the current session doesn't match the current key's slot, open a new one
779
       */
780
0
      if (currentSession)
781
0
      {
782
0
        WINPR_ASSERT(provider->p11->C_CloseSession);
783
0
        rv = provider->p11->C_CloseSession(currentSession);
784
0
        if (rv != CKR_OK)
785
0
          WLog_WARN(TAG, "C_CloseSession failed with %s [0x%08" PRIx32 "]",
786
0
                    CK_RV_error_string(rv), rv);
787
0
        currentSession = (CK_SESSION_HANDLE)NULL;
788
0
      }
789
790
0
      WINPR_ASSERT(provider->p11->C_OpenSession);
791
0
      rv = provider->p11->C_OpenSession(key->slotId, CKF_SERIAL_SESSION, NULL, NULL,
792
0
                                        &currentSession);
793
0
      if (rv != CKR_OK)
794
0
      {
795
0
        WLog_ERR(TAG, "C_OpenSession failed with %s [0x%08" PRIx32 "] for slot %d",
796
0
                 CK_RV_error_string(rv), rv, key->slotId);
797
0
        continue;
798
0
      }
799
0
      currentSlot = key->slotId;
800
0
    }
801
802
    /* look if we can find a certificate that matches the key's id */
803
0
    WINPR_ASSERT(provider->p11->C_FindObjectsInit);
804
0
    rv = provider->p11->C_FindObjectsInit(currentSession, certificateFilter,
805
0
                                          ARRAYSIZE(certificateFilter));
806
0
    if (rv != CKR_OK)
807
0
    {
808
0
      WLog_ERR(TAG, "C_FindObjectsInit failed with %s [0x%08" PRIx32 "] for slot %d",
809
0
               CK_RV_error_string(rv), rv, key->slotId);
810
0
      continue;
811
0
    }
812
813
0
    WINPR_ASSERT(provider->p11->C_FindObjects);
814
0
    rv = provider->p11->C_FindObjects(currentSession, &certObject, 1, &ncertObjects);
815
0
    if (rv != CKR_OK)
816
0
    {
817
0
      WLog_ERR(TAG, "C_FindObjects failed with %s [0x%08" PRIx32 "] for slot %d",
818
0
               CK_RV_error_string(rv), rv, currentSlot);
819
0
      goto cleanup_FindObjects;
820
0
    }
821
822
0
    if (ncertObjects)
823
0
    {
824
      /* sizeof keyName struct + "\<slotId>\<certId>" + keyName->pszAlgid */
825
0
      DWORD algoSz = 0;
826
0
      size_t KEYNAME_SZ =
827
0
          (1 + (sizeof(key->slotId) * 2) /*slotId*/ + 1 + (key->idLen * 2) + 1) * 2;
828
829
0
      convertKeyType(key->keyType, NULL, 0, &algoSz);
830
0
      KEYNAME_SZ += (1ULL + algoSz) * 2ULL;
831
832
0
      keyName = calloc(1, sizeof(*keyName) + KEYNAME_SZ);
833
0
      if (!keyName)
834
0
      {
835
0
        WLog_ERR(TAG, "unable to allocate keyName");
836
0
        goto cleanup_FindObjects;
837
0
      }
838
0
      keyName->dwLegacyKeySpec = AT_KEYEXCHANGE | AT_SIGNATURE;
839
0
      keyName->dwFlags = NCRYPT_MACHINE_KEY_FLAG;
840
0
      keyName->pszName = (LPWSTR)(keyName + 1);
841
0
      wprintKeyName(keyName->pszName, key->slotId, key->id, key->idLen);
842
843
0
      keyName->pszAlgid = keyName->pszName + _wcslen(keyName->pszName) + 1;
844
0
      convertKeyType(key->keyType, keyName->pszAlgid, algoSz + 1, NULL);
845
0
    }
846
847
0
  cleanup_FindObjects:
848
0
    WINPR_ASSERT(provider->p11->C_FindObjectsFinal);
849
0
    rv = provider->p11->C_FindObjectsFinal(currentSession);
850
0
    if (rv != CKR_OK)
851
0
      WLog_ERR(TAG, "C_FindObjectsFinal failed with %s [0x%08" PRIx32 "]",
852
0
               CK_RV_error_string(rv), rv);
853
854
0
    if (keyName)
855
0
    {
856
0
      *ppKeyName = keyName;
857
0
      state->keyIndex++;
858
0
      return ERROR_SUCCESS;
859
0
    }
860
0
  }
861
862
0
  return NTE_NO_MORE_ITEMS;
863
0
}
864
865
static SECURITY_STATUS get_piv_container_name(NCryptP11KeyHandle* key, const BYTE* piv_tag,
866
                                              BYTE* output, size_t output_len)
867
0
{
868
0
  CK_SLOT_INFO slot_info = { 0 };
869
0
  CK_FUNCTION_LIST_PTR p11 = NULL;
870
0
  WCHAR* reader = NULL;
871
0
  SCARDCONTEXT context = 0;
872
0
  SCARDHANDLE card = 0;
873
0
  DWORD proto = 0;
874
0
  const SCARD_IO_REQUEST* pci = NULL;
875
0
  BYTE buf[258] = { 0 };
876
0
  char container_name[PIV_CONTAINER_NAME_LEN + 1] = { 0 };
877
0
  DWORD buf_len = 0;
878
0
  SECURITY_STATUS ret = NTE_BAD_KEY;
879
0
  WinPrAsn1Decoder dec = { 0 };
880
0
  WinPrAsn1Decoder dec2 = { 0 };
881
0
  size_t len = 0;
882
0
  BYTE tag = 0;
883
0
  BYTE* p = NULL;
884
0
  wStream s = { 0 };
885
886
0
  WINPR_ASSERT(key);
887
0
  WINPR_ASSERT(piv_tag);
888
889
0
  WINPR_ASSERT(key->provider);
890
0
  p11 = key->provider->p11;
891
0
  WINPR_ASSERT(p11);
892
893
  /* Get the reader the card is in */
894
0
  WINPR_ASSERT(p11->C_GetSlotInfo);
895
0
  if (p11->C_GetSlotInfo(key->slotId, &slot_info) != CKR_OK)
896
0
    return NTE_BAD_KEY;
897
898
0
  fix_padded_string((char*)slot_info.slotDescription, sizeof(slot_info.slotDescription));
899
0
  reader = ConvertUtf8NToWCharAlloc((char*)slot_info.slotDescription,
900
0
                                    ARRAYSIZE(slot_info.slotDescription), NULL);
901
0
  ret = NTE_NO_MEMORY;
902
0
  if (!reader)
903
0
    goto out;
904
905
0
  ret = NTE_BAD_KEY;
906
0
  if (SCardEstablishContext(SCARD_SCOPE_USER, NULL, NULL, &context) != SCARD_S_SUCCESS)
907
0
    goto out;
908
909
0
  if (SCardConnectW(context, reader, SCARD_SHARE_SHARED, SCARD_PROTOCOL_Tx, &card, &proto) !=
910
0
      SCARD_S_SUCCESS)
911
0
    goto out;
912
0
  pci = (proto == SCARD_PROTOCOL_T0) ? SCARD_PCI_T0 : SCARD_PCI_T1;
913
914
0
  buf_len = sizeof(buf);
915
0
  if (SCardTransmit(card, pci, APDU_PIV_SELECT_AID, sizeof(APDU_PIV_SELECT_AID), NULL, buf,
916
0
                    &buf_len) != SCARD_S_SUCCESS)
917
0
    goto out;
918
0
  if ((buf[buf_len - 2] != 0x90 || buf[buf_len - 1] != 0) && buf[buf_len - 2] != 0x61)
919
0
    goto out;
920
921
0
  buf_len = sizeof(buf);
922
0
  if (SCardTransmit(card, pci, APDU_PIV_GET_CHUID, sizeof(APDU_PIV_GET_CHUID), NULL, buf,
923
0
                    &buf_len) != SCARD_S_SUCCESS)
924
0
    goto out;
925
0
  if ((buf[buf_len - 2] != 0x90 || buf[buf_len - 1] != 0) && buf[buf_len - 2] != 0x61)
926
0
    goto out;
927
928
  /* Find the GUID field in the CHUID data object */
929
0
  WinPrAsn1Decoder_InitMem(&dec, WINPR_ASN1_BER, buf, buf_len);
930
0
  if (!WinPrAsn1DecReadTagAndLen(&dec, &tag, &len) || tag != 0x53)
931
0
    goto out;
932
0
  while (WinPrAsn1DecReadTagLenValue(&dec, &tag, &len, &dec2) && tag != 0x34)
933
0
    ;
934
0
  if (tag != 0x34 || len != 16)
935
0
    goto out;
936
937
0
  s = WinPrAsn1DecGetStream(&dec2);
938
0
  p = Stream_Buffer(&s);
939
940
  /* Construct the value Windows would use for a PIV key's container name */
941
0
  (void)snprintf(container_name, PIV_CONTAINER_NAME_LEN + 1,
942
0
                 "%.2x%.2x%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x-%.2x%.2x%.2x%.2x%.2x%.2x", p[3],
943
0
                 p[2], p[1], p[0], p[5], p[4], p[7], p[6], p[8], p[9], p[10], p[11], p[12],
944
0
                 piv_tag[0], piv_tag[1], piv_tag[2]);
945
946
  /* And convert it to UTF-16 */
947
0
  union
948
0
  {
949
0
    WCHAR* wc;
950
0
    BYTE* b;
951
0
  } cnv;
952
0
  cnv.b = output;
953
0
  if (ConvertUtf8NToWChar(container_name, ARRAYSIZE(container_name), cnv.wc,
954
0
                          output_len / sizeof(WCHAR)) > 0)
955
0
    ret = ERROR_SUCCESS;
956
957
0
out:
958
0
  free(reader);
959
0
  if (card)
960
0
    SCardDisconnect(card, SCARD_LEAVE_CARD);
961
0
  if (context)
962
0
    SCardReleaseContext(context);
963
0
  return ret;
964
0
}
965
966
static SECURITY_STATUS check_for_piv_container_name(NCryptP11KeyHandle* key, BYTE* pbOutput,
967
                                                    DWORD cbOutput, DWORD* pcbResult, char* label,
968
                                                    size_t label_len)
969
0
{
970
0
  for (size_t i = 0; i < ARRAYSIZE(piv_cert_tags); i++)
971
0
  {
972
0
    const piv_cert_tags_t* cur = &piv_cert_tags[i];
973
0
    if (strncmp(label, cur->label, label_len) == 0)
974
0
    {
975
0
      *pcbResult = (PIV_CONTAINER_NAME_LEN + 1) * sizeof(WCHAR);
976
0
      if (!pbOutput)
977
0
        return ERROR_SUCCESS;
978
0
      else if (cbOutput < (PIV_CONTAINER_NAME_LEN + 1) * sizeof(WCHAR))
979
0
        return NTE_NO_MEMORY;
980
0
      else
981
0
        return get_piv_container_name(key, cur->tag, pbOutput, cbOutput);
982
0
    }
983
0
  }
984
0
  return NTE_NOT_FOUND;
985
0
}
986
987
static SECURITY_STATUS NCryptP11KeyGetProperties(NCryptP11KeyHandle* keyHandle,
988
                                                 NCryptKeyGetPropertyEnum property, PBYTE pbOutput,
989
                                                 DWORD cbOutput, DWORD* pcbResult,
990
                                                 WINPR_ATTR_UNUSED DWORD dwFlags)
991
0
{
992
0
  SECURITY_STATUS ret = NTE_FAIL;
993
0
  CK_RV rv = 0;
994
0
  CK_SESSION_HANDLE session = 0;
995
0
  CK_OBJECT_HANDLE objectHandle = 0;
996
0
  CK_ULONG objectCount = 0;
997
0
  NCryptP11ProviderHandle* provider = NULL;
998
0
  CK_OBJECT_CLASS oclass = CKO_CERTIFICATE;
999
0
  CK_CERTIFICATE_TYPE ctype = CKC_X_509;
1000
0
  CK_ATTRIBUTE certificateFilter[] = { { CKA_CLASS, &oclass, sizeof(oclass) },
1001
0
                                     { CKA_CERTIFICATE_TYPE, &ctype, sizeof(ctype) },
1002
0
                                     { CKA_ID, keyHandle->keyCertId,
1003
0
                                       keyHandle->keyCertIdLen } };
1004
0
  CK_ATTRIBUTE* objectFilter = certificateFilter;
1005
0
  CK_ULONG objectFilterLen = ARRAYSIZE(certificateFilter);
1006
1007
0
  WINPR_ASSERT(keyHandle);
1008
0
  provider = keyHandle->provider;
1009
0
  WINPR_ASSERT(provider);
1010
1011
0
  switch (property)
1012
1013
0
  {
1014
0
    case NCRYPT_PROPERTY_CERTIFICATE:
1015
0
    case NCRYPT_PROPERTY_NAME:
1016
0
      break;
1017
0
    case NCRYPT_PROPERTY_READER:
1018
0
    {
1019
0
      CK_SLOT_INFO slotInfo;
1020
1021
0
      WINPR_ASSERT(provider->p11->C_GetSlotInfo);
1022
0
      rv = provider->p11->C_GetSlotInfo(keyHandle->slotId, &slotInfo);
1023
0
      if (rv != CKR_OK)
1024
0
        return NTE_BAD_KEY;
1025
1026
0
#define SLOT_DESC_SZ sizeof(slotInfo.slotDescription)
1027
0
      fix_padded_string((char*)slotInfo.slotDescription, SLOT_DESC_SZ);
1028
0
      const size_t len = 2ULL * (strnlen((char*)slotInfo.slotDescription, SLOT_DESC_SZ) + 1);
1029
0
      if (len > UINT32_MAX)
1030
0
        return NTE_BAD_DATA;
1031
0
      *pcbResult = (UINT32)len;
1032
0
      if (pbOutput)
1033
0
      {
1034
0
        union
1035
0
        {
1036
0
          WCHAR* wc;
1037
0
          BYTE* b;
1038
0
        } cnv;
1039
0
        cnv.b = pbOutput;
1040
0
        if (cbOutput < *pcbResult)
1041
0
          return NTE_NO_MEMORY;
1042
1043
0
        if (ConvertUtf8ToWChar((char*)slotInfo.slotDescription, cnv.wc,
1044
0
                               cbOutput / sizeof(WCHAR)) < 0)
1045
0
          return NTE_NO_MEMORY;
1046
0
      }
1047
0
      return ERROR_SUCCESS;
1048
0
    }
1049
0
    case NCRYPT_PROPERTY_SLOTID:
1050
0
    {
1051
0
      *pcbResult = 4;
1052
0
      if (pbOutput)
1053
0
      {
1054
0
        UINT32* ptr = (UINT32*)pbOutput;
1055
1056
0
        if (cbOutput < 4)
1057
0
          return NTE_NO_MEMORY;
1058
0
        if (keyHandle->slotId > UINT32_MAX)
1059
0
        {
1060
0
          ret = NTE_BAD_DATA;
1061
0
          goto out_final;
1062
0
        }
1063
0
        *ptr = (UINT32)keyHandle->slotId;
1064
0
      }
1065
0
      return ERROR_SUCCESS;
1066
0
    }
1067
0
    case NCRYPT_PROPERTY_UNKNOWN:
1068
0
    default:
1069
0
      return NTE_NOT_SUPPORTED;
1070
0
  }
1071
1072
0
  WINPR_ASSERT(provider->p11->C_OpenSession);
1073
0
  rv = provider->p11->C_OpenSession(keyHandle->slotId, CKF_SERIAL_SESSION, NULL, NULL, &session);
1074
0
  if (rv != CKR_OK)
1075
0
  {
1076
0
    WLog_ERR(TAG, "error opening session on slot %d", keyHandle->slotId);
1077
0
    return NTE_FAIL;
1078
0
  }
1079
1080
0
  WINPR_ASSERT(provider->p11->C_FindObjectsInit);
1081
0
  rv = provider->p11->C_FindObjectsInit(session, objectFilter, objectFilterLen);
1082
0
  if (rv != CKR_OK)
1083
0
  {
1084
0
    WLog_ERR(TAG, "unable to initiate search for slot %d", keyHandle->slotId);
1085
0
    goto out;
1086
0
  }
1087
1088
0
  WINPR_ASSERT(provider->p11->C_FindObjects);
1089
0
  rv = provider->p11->C_FindObjects(session, &objectHandle, 1, &objectCount);
1090
0
  if (rv != CKR_OK)
1091
0
  {
1092
0
    WLog_ERR(TAG, "unable to findObjects for slot %d", keyHandle->slotId);
1093
0
    goto out_final;
1094
0
  }
1095
0
  if (!objectCount)
1096
0
  {
1097
0
    ret = NTE_NOT_FOUND;
1098
0
    goto out_final;
1099
0
  }
1100
1101
0
  switch (property)
1102
0
  {
1103
0
    case NCRYPT_PROPERTY_CERTIFICATE:
1104
0
    {
1105
0
      CK_ATTRIBUTE certValue = { CKA_VALUE, pbOutput, cbOutput };
1106
1107
0
      WINPR_ASSERT(provider->p11->C_GetAttributeValue);
1108
0
      rv = provider->p11->C_GetAttributeValue(session, objectHandle, &certValue, 1);
1109
0
      if (rv != CKR_OK)
1110
0
      {
1111
        // TODO: do a kind of translation from CKR_* to NTE_*
1112
0
      }
1113
1114
0
      if (certValue.ulValueLen > UINT32_MAX)
1115
0
      {
1116
0
        ret = NTE_BAD_DATA;
1117
0
        goto out_final;
1118
0
      }
1119
0
      *pcbResult = (UINT32)certValue.ulValueLen;
1120
0
      ret = ERROR_SUCCESS;
1121
0
      break;
1122
0
    }
1123
0
    case NCRYPT_PROPERTY_NAME:
1124
0
    {
1125
0
      CK_ATTRIBUTE attr = { CKA_LABEL, NULL, 0 };
1126
0
      char* label = NULL;
1127
1128
0
      WINPR_ASSERT(provider->p11->C_GetAttributeValue);
1129
0
      rv = provider->p11->C_GetAttributeValue(session, objectHandle, &attr, 1);
1130
0
      if (rv == CKR_OK)
1131
0
      {
1132
0
        label = calloc(1, attr.ulValueLen);
1133
0
        if (!label)
1134
0
        {
1135
0
          ret = NTE_NO_MEMORY;
1136
0
          break;
1137
0
        }
1138
1139
0
        attr.pValue = label;
1140
0
        rv = provider->p11->C_GetAttributeValue(session, objectHandle, &attr, 1);
1141
0
      }
1142
1143
0
      if (rv == CKR_OK)
1144
0
      {
1145
        /* Check if we have a PIV card */
1146
0
        ret = check_for_piv_container_name(keyHandle, pbOutput, cbOutput, pcbResult, label,
1147
0
                                           attr.ulValueLen);
1148
1149
        /* Otherwise, at least for GIDS cards the label will be the correct value */
1150
0
        if (ret == NTE_NOT_FOUND)
1151
0
        {
1152
0
          union
1153
0
          {
1154
0
            WCHAR* wc;
1155
0
            BYTE* b;
1156
0
          } cnv;
1157
0
          const size_t olen = pbOutput ? cbOutput / sizeof(WCHAR) : 0;
1158
0
          cnv.b = pbOutput;
1159
0
          SSIZE_T size = ConvertUtf8NToWChar(label, attr.ulValueLen, cnv.wc, olen);
1160
0
          if (size < 0)
1161
0
            ret = ERROR_CONVERT_TO_LARGE;
1162
0
          else
1163
0
            ret = ERROR_SUCCESS;
1164
0
        }
1165
0
      }
1166
1167
0
      free(label);
1168
0
      break;
1169
0
    }
1170
0
    default:
1171
0
      ret = NTE_NOT_SUPPORTED;
1172
0
      break;
1173
0
  }
1174
1175
0
out_final:
1176
0
  WINPR_ASSERT(provider->p11->C_FindObjectsFinal);
1177
0
  rv = provider->p11->C_FindObjectsFinal(session);
1178
0
  if (rv != CKR_OK)
1179
0
  {
1180
0
    WLog_ERR(TAG, "error in C_FindObjectsFinal() for slot %d", keyHandle->slotId);
1181
0
  }
1182
0
out:
1183
0
  WINPR_ASSERT(provider->p11->C_CloseSession);
1184
0
  rv = provider->p11->C_CloseSession(session);
1185
0
  if (rv != CKR_OK)
1186
0
  {
1187
0
    WLog_ERR(TAG, "error in C_CloseSession() for slot %d", keyHandle->slotId);
1188
0
  }
1189
0
  return ret;
1190
0
}
1191
1192
static SECURITY_STATUS NCryptP11GetProperty(NCRYPT_HANDLE hObject, NCryptKeyGetPropertyEnum prop,
1193
                                            PBYTE pbOutput, DWORD cbOutput, DWORD* pcbResult,
1194
                                            DWORD dwFlags)
1195
0
{
1196
0
  NCryptBaseHandle* base = (NCryptBaseHandle*)hObject;
1197
1198
0
  WINPR_ASSERT(base);
1199
0
  switch (base->type)
1200
0
  {
1201
0
    case WINPR_NCRYPT_PROVIDER:
1202
0
      return ERROR_CALL_NOT_IMPLEMENTED;
1203
0
    case WINPR_NCRYPT_KEY:
1204
0
      return NCryptP11KeyGetProperties((NCryptP11KeyHandle*)hObject, prop, pbOutput, cbOutput,
1205
0
                                       pcbResult, dwFlags);
1206
0
    default:
1207
0
      return ERROR_INVALID_HANDLE;
1208
0
  }
1209
0
  return ERROR_SUCCESS;
1210
0
}
1211
1212
static SECURITY_STATUS NCryptP11OpenKey(NCRYPT_PROV_HANDLE hProvider, NCRYPT_KEY_HANDLE* phKey,
1213
                                        LPCWSTR pszKeyName, WINPR_ATTR_UNUSED DWORD dwLegacyKeySpec,
1214
                                        WINPR_ATTR_UNUSED DWORD dwFlags)
1215
0
{
1216
0
  SECURITY_STATUS ret = 0;
1217
0
  CK_SLOT_ID slotId = 0;
1218
0
  CK_BYTE keyCertId[64] = { 0 };
1219
0
  CK_ULONG keyCertIdLen = 0;
1220
0
  NCryptP11KeyHandle* keyHandle = NULL;
1221
1222
0
  ret = parseKeyName(pszKeyName, &slotId, keyCertId, &keyCertIdLen);
1223
0
  if (ret != ERROR_SUCCESS)
1224
0
    return ret;
1225
1226
0
  keyHandle = (NCryptP11KeyHandle*)ncrypt_new_handle(
1227
0
      WINPR_NCRYPT_KEY, sizeof(*keyHandle), NCryptP11GetProperty, winpr_NCryptDefault_dtor);
1228
0
  if (!keyHandle)
1229
0
    return NTE_NO_MEMORY;
1230
1231
0
  keyHandle->provider = (NCryptP11ProviderHandle*)hProvider;
1232
0
  keyHandle->slotId = slotId;
1233
0
  memcpy(keyHandle->keyCertId, keyCertId, sizeof(keyCertId));
1234
0
  keyHandle->keyCertIdLen = keyCertIdLen;
1235
0
  *phKey = (NCRYPT_KEY_HANDLE)keyHandle;
1236
0
  return ERROR_SUCCESS;
1237
0
}
1238
1239
static SECURITY_STATUS initialize_pkcs11(HANDLE handle,
1240
                                         CK_RV (*c_get_function_list)(CK_FUNCTION_LIST_PTR_PTR),
1241
                                         NCRYPT_PROV_HANDLE* phProvider)
1242
0
{
1243
0
  SECURITY_STATUS status = ERROR_SUCCESS;
1244
0
  NCryptP11ProviderHandle* ret = NULL;
1245
0
  CK_RV rv = 0;
1246
1247
0
  WINPR_ASSERT(c_get_function_list);
1248
0
  WINPR_ASSERT(phProvider);
1249
1250
0
  ret = (NCryptP11ProviderHandle*)ncrypt_new_handle(
1251
0
      WINPR_NCRYPT_PROVIDER, sizeof(*ret), NCryptP11GetProperty, NCryptP11StorageProvider_dtor);
1252
0
  if (!ret)
1253
0
    return NTE_NO_MEMORY;
1254
1255
0
  ret->library = handle;
1256
0
  ret->baseProvider.enumKeysFn = NCryptP11EnumKeys;
1257
0
  ret->baseProvider.openKeyFn = NCryptP11OpenKey;
1258
1259
0
  rv = c_get_function_list(&ret->p11);
1260
0
  if (rv != CKR_OK)
1261
0
  {
1262
0
    status = NTE_PROVIDER_DLL_FAIL;
1263
0
    goto fail;
1264
0
  }
1265
1266
0
  WINPR_ASSERT(ret->p11);
1267
0
  WINPR_ASSERT(ret->p11->C_Initialize);
1268
0
  rv = ret->p11->C_Initialize(NULL);
1269
0
  if (rv != CKR_OK)
1270
0
  {
1271
0
    status = NTE_PROVIDER_DLL_FAIL;
1272
0
    goto fail;
1273
0
  }
1274
1275
0
  *phProvider = (NCRYPT_PROV_HANDLE)ret;
1276
1277
0
fail:
1278
0
  if (status != ERROR_SUCCESS)
1279
0
    ret->baseProvider.baseHandle.releaseFn((NCRYPT_HANDLE)ret);
1280
0
  return status;
1281
0
}
1282
1283
SECURITY_STATUS NCryptOpenP11StorageProviderEx(NCRYPT_PROV_HANDLE* phProvider,
1284
                                               WINPR_ATTR_UNUSED LPCWSTR pszProviderName,
1285
                                               WINPR_ATTR_UNUSED DWORD dwFlags, LPCSTR* modulePaths)
1286
0
{
1287
0
  SECURITY_STATUS status = ERROR_INVALID_PARAMETER;
1288
0
  LPCSTR defaultPaths[] = { "p11-kit-proxy.so", "opensc-pkcs11.so", NULL };
1289
1290
0
  if (!phProvider)
1291
0
    return ERROR_INVALID_PARAMETER;
1292
1293
0
  if (!modulePaths)
1294
0
    modulePaths = defaultPaths;
1295
1296
0
  while (*modulePaths)
1297
0
  {
1298
0
    const char* modulePath = *modulePaths++;
1299
0
    HANDLE library = LoadLibrary(modulePath);
1300
0
    typedef CK_RV (*c_get_function_list_t)(CK_FUNCTION_LIST_PTR_PTR);
1301
0
    NCryptP11ProviderHandle* provider = NULL;
1302
1303
0
    WLog_DBG(TAG, "Trying pkcs11 module '%s'", modulePath);
1304
0
    if (!library)
1305
0
    {
1306
0
      status = NTE_PROV_DLL_NOT_FOUND;
1307
0
      goto out_load_library;
1308
0
    }
1309
1310
0
    c_get_function_list_t c_get_function_list =
1311
0
        GetProcAddressAs(library, "C_GetFunctionList", c_get_function_list_t);
1312
1313
0
    if (!c_get_function_list)
1314
0
    {
1315
0
      status = NTE_PROV_TYPE_ENTRY_BAD;
1316
0
      goto out_load_library;
1317
0
    }
1318
1319
0
    status = initialize_pkcs11(library, c_get_function_list, phProvider);
1320
0
    if (status != ERROR_SUCCESS)
1321
0
    {
1322
0
      status = NTE_PROVIDER_DLL_FAIL;
1323
0
      goto out_load_library;
1324
0
    }
1325
1326
0
    provider = (NCryptP11ProviderHandle*)*phProvider;
1327
0
    provider->modulePath = _strdup(modulePath);
1328
0
    if (!provider->modulePath)
1329
0
    {
1330
0
      status = NTE_NO_MEMORY;
1331
0
      goto out_load_library;
1332
0
    }
1333
1334
0
    WLog_DBG(TAG, "module '%s' loaded", modulePath);
1335
0
    return ERROR_SUCCESS;
1336
1337
0
  out_load_library:
1338
0
    if (library)
1339
0
      FreeLibrary(library);
1340
0
  }
1341
1342
0
  return status;
1343
0
}
1344
1345
const char* NCryptGetModulePath(NCRYPT_PROV_HANDLE phProvider)
1346
0
{
1347
0
  NCryptP11ProviderHandle* provider = (NCryptP11ProviderHandle*)phProvider;
1348
1349
0
  WINPR_ASSERT(provider);
1350
1351
0
  return provider->modulePath;
1352
0
}