Coverage Report

Created: 2026-02-26 06:50

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