Coverage Report

Created: 2026-04-12 06:58

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