Coverage Report

Created: 2026-10-15 06:26

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