Coverage Report

Created: 2026-09-14 06:31

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