• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

randombit / botan / 19730695394

27 Nov 2025 08:58AM UTC coverage: 91.763% (+1.1%) from 90.661%
19730695394

push

github

web-flow
Merge pull request #4540 from Rohde-Schwarz/feature/pkcs11v32

PKCS #11 Version 3.2 Support

102511 of 111713 relevant lines covered (91.76%)

12543169.22 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.49
/src/tests/test_pkcs11_low_level.cpp
1
/*
2
* (C) 2016 Daniel Neus
3
* (C) 2016 Philipp Weber
4
* (C) 2019 Michael Boric
5
*
6
* Botan is released under the Simplified BSD License (see license.txt)
7
*/
8

9
#include "test_pkcs11.h"
10
#include "tests.h"
11

12
#include <array>
13
#include <functional>
14
#include <map>
15
#include <memory>
16
#include <string>
17
#include <vector>
18

19
#if defined(BOTAN_HAS_PKCS11)
20
   #include <botan/p11.h>
21
   #include <botan/internal/dyn_load.h>
22
#endif
23

24
namespace Botan_Tests {
25

26
namespace {
27

28
#if defined(BOTAN_HAS_PKCS11)
29
   #if defined(BOTAN_HAS_DYNAMIC_LOADER)
30

31
using namespace Botan;
32
using namespace PKCS11;
33

34
class RAII_LowLevel {
35
   public:
36
      RAII_LowLevel() :
20✔
37
            m_module(Test::pkcs11_lib()),
20✔
38
            m_func_list(nullptr),
20✔
39
            m_session_handle(0),
20✔
40
            m_is_session_open(false),
20✔
41
            m_is_logged_in(false) {
20✔
42
         LowLevel::C_GetFunctionList(m_module, &m_func_list);
20✔
43
         m_low_level = std::make_unique<LowLevel>(m_func_list);
20✔
44

45
         C_InitializeArgs init_args = {
20✔
46
            nullptr, nullptr, nullptr, nullptr, static_cast<CK_FLAGS>(Flag::OsLockingOk), nullptr};
47

48
         m_low_level->C_Initialize(&init_args);
20✔
49
      }
20✔
50

51
      ~RAII_LowLevel() noexcept {
20✔
52
         try {
20✔
53
            if(m_is_session_open) {
20✔
54
               if(m_is_logged_in) {
10✔
55
                  m_low_level->C_Logout(m_session_handle, nullptr);
7✔
56
               }
57

58
               m_low_level->C_CloseSession(m_session_handle, nullptr);
10✔
59
            }
60
            m_low_level->C_Finalize(nullptr, nullptr);
20✔
61
         } catch(...) {
×
62
            // ignore errors here
63
         }
×
64
      }
40✔
65

66
      RAII_LowLevel(const RAII_LowLevel& other) = delete;
67
      RAII_LowLevel(RAII_LowLevel&& other) = delete;
68
      RAII_LowLevel& operator=(const RAII_LowLevel& other) = delete;
69
      RAII_LowLevel& operator=(RAII_LowLevel&& other) = delete;
70

71
      std::vector<SlotId> get_slots(bool token_present) const {
19✔
72
         std::vector<SlotId> slots;
19✔
73
         m_low_level->C_GetSlotList(token_present, slots);
19✔
74

75
         if(slots.empty()) {
19✔
76
            throw Test_Error("No slot with attached token found");
×
77
         }
78

79
         return slots;
19✔
80
      }
×
81

82
      SessionHandle open_session(Flags session_flags) {
11✔
83
         std::vector<SlotId> slots = get_slots(true);
11✔
84
         m_low_level->C_OpenSession(slots.at(0), session_flags, nullptr, nullptr, &m_session_handle);
11✔
85
         m_is_session_open = true;
11✔
86
         return m_session_handle;
11✔
87
      }
11✔
88

89
      SessionHandle open_rw_session_with_user_login() {
3✔
90
         Flags session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
3✔
91
         SessionHandle handle = open_session(session_flags);
3✔
92
         login(UserType::User, PIN());
3✔
93
         return handle;
3✔
94
      }
95

96
      SessionHandle get_session_handle() const {
4✔
97
         if(!m_is_session_open) {
4✔
98
            throw Test_Error("no open session");
×
99
         }
100
         return m_session_handle;
4✔
101
      }
102

103
      void close_session() {
1✔
104
         if(!m_is_session_open) {
1✔
105
            throw Test_Error("no open session");
×
106
         }
107

108
         m_low_level->C_CloseSession(m_session_handle);
1✔
109
         m_is_session_open = false;
1✔
110
      }
1✔
111

112
      void login(UserType user_type, const secure_vector<uint8_t>& pin) {
8✔
113
         if(!m_is_session_open) {
8✔
114
            throw Test_Error("no open session");
×
115
         }
116

117
         if(m_is_logged_in) {
8✔
118
            throw Test_Error("Already logged in");
×
119
         }
120

121
         m_low_level->C_Login(m_session_handle, user_type, pin);
8✔
122
         m_is_logged_in = true;
8✔
123
      }
8✔
124

125
      void logout() {
1✔
126
         if(!m_is_logged_in) {
1✔
127
            throw Test_Error("Not logged in");
×
128
         }
129

130
         m_low_level->C_Logout(m_session_handle);
1✔
131
         m_is_logged_in = false;
1✔
132
      }
1✔
133

134
      LowLevel* get() const { return m_low_level.get(); }
1✔
135

136
   private:
137
      Dynamically_Loaded_Library m_module;
138
      FunctionList* m_func_list;
139
      std::unique_ptr<LowLevel> m_low_level;
140
      SessionHandle m_session_handle;
141
      bool m_is_session_open;
142
      bool m_is_logged_in;
143
};
144

145
bool no_op(ReturnValue* /*unused*/) {
×
146
   return true;
×
147
}
148

149
using PKCS11_BoundTestFunction = std::function<bool(ReturnValue* return_value)>;
150

151
// tests all 3 variants
152
Test::Result test_function(const std::string& name,
26✔
153
                           const PKCS11_BoundTestFunction& test_func,
154
                           const std::string& revert_fn_name,
155
                           const PKCS11_BoundTestFunction& revert_func,
156
                           bool expect_failure,
157
                           ReturnValue expected_return_value) {
158
   std::string test_name =
26✔
159
      revert_fn_name.empty() ? "PKCS 11 low level - " + name : "PKCS 11 low level - " + name + "/" + revert_fn_name;
56✔
160
   Test::Result result(test_name);
52✔
161

162
   // test throw variant
163
   if(expect_failure) {
26✔
164
      result.test_throws(name + " fails as expected", [test_func]() { test_func(ThrowException); });
11✔
165
   } else {
166
      test_func(ThrowException);
25✔
167
      result.test_success(name + " did not throw and completed successfully");
25✔
168

169
      if(!revert_fn_name.empty()) {
25✔
170
         revert_func(ThrowException);
10✔
171
         result.test_success(revert_fn_name + " did not throw and completed successfully");
20✔
172
      }
173
   }
174

175
   // test bool return variant
176
   bool success = test_func(nullptr);
26✔
177
   result.test_eq(name, success, !expect_failure);
26✔
178
   if(success && !revert_fn_name.empty()) {
26✔
179
      success = revert_func(nullptr);
10✔
180
      result.test_eq(revert_fn_name, success, !expect_failure);
10✔
181
   }
182

183
   // test ReturnValue variant
184
   ReturnValue rv = ReturnValue::OK;
26✔
185
   success = test_func(&rv);
26✔
186
   result.test_eq(name, success, !expect_failure);
26✔
187
   if(!expect_failure) {
26✔
188
      result.test_rc_ok(name, static_cast<uint32_t>(rv));
25✔
189
   } else {
190
      result.test_rc_fail(name,
2✔
191
                          "return value should be: " + std::to_string(static_cast<uint32_t>(expected_return_value)),
3✔
192
                          static_cast<uint32_t>(rv));
193
   }
194

195
   if(success && !revert_fn_name.empty()) {
26✔
196
      success = revert_func(&rv);
10✔
197
      result.test_eq(revert_fn_name, success, !expect_failure);
10✔
198
      result.test_rc_ok(revert_fn_name, static_cast<uint32_t>(rv));
10✔
199
   }
200

201
   return result;
26✔
202
}
26✔
203

204
Test::Result test_function(const std::string& name,
1✔
205
                           const PKCS11_BoundTestFunction& test_func,
206
                           bool expect_failure,
207
                           ReturnValue expected_return_value) {
208
   return test_function(name, test_func, std::string(), no_op, expect_failure, expected_return_value);
3✔
209
}
210

211
Test::Result test_function(const std::string& name, const PKCS11_BoundTestFunction& test_func) {
15✔
212
   return test_function(name, test_func, std::string(), no_op, false, ReturnValue::OK);
45✔
213
}
214

215
Test::Result test_function(const std::string& name,
10✔
216
                           const PKCS11_BoundTestFunction& test_func,
217
                           const std::string& revert_fn_name,
218
                           const PKCS11_BoundTestFunction& revert_func) {
219
   return test_function(name, test_func, revert_fn_name, revert_func, false, ReturnValue::OK);
10✔
220
}
221

222
Test::Result test_low_level_ctor() {
1✔
223
   Test::Result result("PKCS 11 low level - LowLevel ctor");
1✔
224

225
   Dynamically_Loaded_Library pkcs11_module(Test::pkcs11_lib());
1✔
226
   FunctionList* func_list(nullptr);
1✔
227
   LowLevel::C_GetFunctionList(pkcs11_module, &func_list);
1✔
228

229
   LowLevel p11_low_level(func_list);
1✔
230
   result.test_success("LowLevel ctor does complete for valid function list");
1✔
231

232
   result.test_throws("LowLevel ctor fails for invalid function list pointer",
2✔
233
                      []() { LowLevel p11_low_level2(nullptr); });
1✔
234

235
   return result;
1✔
236
}
1✔
237

238
// NOLINTBEGIN(*-avoid-bind)
239

240
Test::Result test_c_get_function_list() {
1✔
241
   Dynamically_Loaded_Library pkcs11_module(Test::pkcs11_lib());
1✔
242
   FunctionList* func_list = nullptr;
1✔
243
   return test_function(
1✔
244
      "C_GetFunctionList",
245
      std::bind(&LowLevel::C_GetFunctionList, std::ref(pkcs11_module), &func_list, std::placeholders::_1));
3✔
246
}
1✔
247

248
Test::Result test_initialize_finalize() {
1✔
249
   Dynamically_Loaded_Library pkcs11_module(Test::pkcs11_lib());
1✔
250
   FunctionList* func_list = nullptr;
1✔
251
   LowLevel::C_GetFunctionList(pkcs11_module, &func_list);
1✔
252

253
   LowLevel p11_low_level(func_list);
1✔
254

255
   // setting Flag::OsLockingOk should be the normal use case
256
   C_InitializeArgs init_args = {nullptr, nullptr, nullptr, nullptr, static_cast<CK_FLAGS>(Flag::OsLockingOk), nullptr};
1✔
257

258
   auto init_bind = std::bind(&LowLevel::C_Initialize, std::ref(p11_low_level), &init_args, std::placeholders::_1);
1✔
259
   auto finalize_bind = std::bind(&LowLevel::C_Finalize, std::ref(p11_low_level), nullptr, std::placeholders::_1);
1✔
260
   return test_function("C_Initialize", init_bind, "C_Finalize", finalize_bind);
4✔
261
}
1✔
262

263
Test::Result test_c_get_info() {
1✔
264
   RAII_LowLevel p11_low_level;
1✔
265

266
   Info info = {};
1✔
267
   Test::Result result =
1✔
268
      test_function("C_GetInfo", std::bind(&LowLevel::C_GetInfo, p11_low_level.get(), &info, std::placeholders::_1));
2✔
269
   result.test_ne("C_GetInfo crypto major version", info.cryptokiVersion.major, 0);
1✔
270

271
   return result;
1✔
272
}
1✔
273

274
Test::Result test_c_get_slot_list() {
1✔
275
   RAII_LowLevel p11_low_level;
1✔
276

277
   std::vector<SlotId> slot_vec;
1✔
278

279
   // assumes smartcard reader is attached without card
280

281
   auto slots_no_card = std::bind(
1✔
282
      static_cast<bool (LowLevel::*)(bool, std::vector<SlotId>&, ReturnValue*) const>(&LowLevel::C_GetSlotList),
1✔
283
      p11_low_level.get(),
1✔
284
      false,  // no card present
1✔
285
      std::ref(slot_vec),
1✔
286
      std::placeholders::_1);
1✔
287

288
   Test::Result result = test_function("C_GetSlotList", slots_no_card);
2✔
289
   result.test_ne("C_GetSlotList number of slots without attached token > 0", slot_vec.size(), 0);
1✔
290

291
   // assumes smartcard reader is attached with a card
292

293
   auto slots_with_card = std::bind(
1✔
294
      static_cast<bool (LowLevel::*)(bool, std::vector<SlotId>&, ReturnValue*) const>(&LowLevel::C_GetSlotList),
1✔
295
      p11_low_level.get(),
1✔
296
      true,  // card present
1✔
297
      std::ref(slot_vec),
1✔
298
      std::placeholders::_1);
1✔
299

300
   slot_vec.clear();
1✔
301
   result.merge(test_function("C_GetSlotList", slots_with_card));
1✔
302
   result.test_ne("C_GetSlotList number of slots with attached token > 0", slot_vec.size(), 0);
1✔
303

304
   return result;
1✔
305
}
1✔
306

307
Test::Result test_c_get_slot_info() {
1✔
308
   RAII_LowLevel p11_low_level;
1✔
309
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(false);
1✔
310

311
   SlotInfo slot_info = {};
1✔
312
   Test::Result result = test_function(
1✔
313
      "C_GetSlotInfo",
314
      std::bind(&LowLevel::C_GetSlotInfo, p11_low_level.get(), slot_vec.at(0), &slot_info, std::placeholders::_1));
2✔
315

316
   std::string slot_desc(reinterpret_cast<char*>(slot_info.slotDescription));
1✔
317
   result.test_ne("C_GetSlotInfo returns non empty description", slot_desc.size(), 0);
1✔
318

319
   return result;
2✔
320
}
2✔
321

322
Test::Result test_c_get_token_info() {
1✔
323
   RAII_LowLevel p11_low_level;
1✔
324
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
325

326
   TokenInfo token_info = {};
1✔
327
   Test::Result result = test_function(
1✔
328
      "C_GetTokenInfo",
329
      std::bind(&LowLevel::C_GetTokenInfo, p11_low_level.get(), slot_vec.at(0), &token_info, std::placeholders::_1));
3✔
330

331
   std::string serial(reinterpret_cast<char*>(token_info.serialNumber));
1✔
332
   result.test_ne("C_GetTokenInfo returns non empty serial number", serial.size(), 0);
1✔
333

334
   return result;
2✔
335
}
1✔
336

337
Test::Result test_c_wait_for_slot_event() {
1✔
338
   RAII_LowLevel p11_low_level;
1✔
339

340
   Flags flags = PKCS11::flags(Flag::DontBlock);
1✔
341
   SlotId slot_id = 0;
1✔
342

343
   return test_function(
1✔
344
      "C_WaitForSlotEvent",
345
      std::bind(&LowLevel::C_WaitForSlotEvent, p11_low_level.get(), flags, &slot_id, nullptr, std::placeholders::_1),
1✔
346
      true,
347
      ReturnValue::NoEvent);
4✔
348
}
1✔
349

350
Test::Result test_c_get_mechanism_list() {
1✔
351
   RAII_LowLevel p11_low_level;
1✔
352
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
353

354
   std::vector<MechanismType> mechanisms;
1✔
355

356
   auto binder = std::bind(static_cast<bool (LowLevel::*)(SlotId, std::vector<MechanismType>&, ReturnValue*) const>(
1✔
357
                              &LowLevel::C_GetMechanismList),
358
                           p11_low_level.get(),
1✔
359
                           slot_vec.at(0),
1✔
360
                           std::ref(mechanisms),
1✔
361
                           std::placeholders::_1);
1✔
362

363
   Test::Result result = test_function("C_GetMechanismList", binder);
2✔
364
   result.confirm("C_GetMechanismList returns non empty mechanisms list", !mechanisms.empty());
2✔
365

366
   return result;
1✔
367
}
1✔
368

369
Test::Result test_c_get_mechanism_info() {
1✔
370
   RAII_LowLevel p11_low_level;
1✔
371
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
372

373
   std::vector<MechanismType> mechanisms;
1✔
374
   p11_low_level.get()->C_GetMechanismList(slot_vec.at(0), mechanisms);
1✔
375

376
   MechanismInfo mechanism_info = {};
1✔
377
   return test_function("C_GetMechanismInfo",
1✔
378
                        std::bind(&LowLevel::C_GetMechanismInfo,
2✔
379
                                  p11_low_level.get(),
1✔
380
                                  slot_vec.at(0),
1✔
381
                                  mechanisms.at(0),
1✔
382
                                  &mechanism_info,
1✔
383
                                  std::placeholders::_1));
4✔
384
}
1✔
385

386
Test::Result test_c_init_token() {
1✔
387
   RAII_LowLevel p11_low_level;
1✔
388
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
389

390
   const std::string token_label = "Botan PKCS#11 tests";
1✔
391
   std::string_view label_view(token_label);
1✔
392

393
   auto sec_vec_binder = std::bind(
1✔
394
      static_cast<bool (LowLevel::*)(SlotId, const secure_vector<uint8_t>&, std::string_view, ReturnValue*) const>(
1✔
395
         &LowLevel::C_InitToken<secure_allocator<uint8_t>>),
396
      p11_low_level.get(),
1✔
397
      slot_vec.at(0),
1✔
398
      SO_PIN(),
×
399
      std::ref(label_view),
1✔
400
      std::placeholders::_1);
1✔
401

402
   return test_function("C_InitToken", sec_vec_binder);
4✔
403
}
1✔
404

405
Test::Result test_open_close_session() {
1✔
406
   RAII_LowLevel p11_low_level;
1✔
407
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
408

409
   // public read only session
410
   const Flags ro_flags = PKCS11::flags(Flag::SerialSession);
1✔
411
   SessionHandle session_handle = 0;
1✔
412

413
   auto open_session_ro = std::bind(&LowLevel::C_OpenSession,
2✔
414
                                    p11_low_level.get(),
1✔
415
                                    slot_vec.at(0),
1✔
416
                                    ro_flags,
417
                                    nullptr,
1✔
418
                                    nullptr,
419
                                    &session_handle,
420
                                    std::placeholders::_1);
1✔
421

422
   auto close_session =
1✔
423
      std::bind(&LowLevel::C_CloseSession, p11_low_level.get(), std::ref(session_handle), std::placeholders::_1);
1✔
424

425
   Test::Result result = test_function("C_OpenSession", open_session_ro, "C_CloseSession", close_session);
3✔
426

427
   // public read write session
428
   const Flags rw_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
429

430
   auto open_session_rw = std::bind(&LowLevel::C_OpenSession,
2✔
431
                                    p11_low_level.get(),
1✔
432
                                    slot_vec.at(0),
1✔
433
                                    rw_flags,
434
                                    nullptr,
1✔
435
                                    nullptr,
436
                                    &session_handle,
437
                                    std::placeholders::_1);
1✔
438

439
   result.merge(test_function("C_OpenSession", open_session_rw, "C_CloseSession", close_session));
3✔
440

441
   return result;
1✔
442
}
1✔
443

444
Test::Result test_c_close_all_sessions() {
1✔
445
   RAII_LowLevel p11_low_level;
1✔
446
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
447

448
   auto open_two_sessions = [&slot_vec, &p11_low_level]() -> void {
4✔
449
      // public read only session
450
      Flags flags = PKCS11::flags(Flag::SerialSession);
3✔
451
      SessionHandle first_session_handle = 0;
3✔
452
      SessionHandle second_session_handle = 0;
3✔
453

454
      p11_low_level.get()->C_OpenSession(slot_vec.at(0), flags, nullptr, nullptr, &first_session_handle);
3✔
455

456
      flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
3✔
457
      p11_low_level.get()->C_OpenSession(slot_vec.at(0), flags, nullptr, nullptr, &second_session_handle);
3✔
458
   };
4✔
459

460
   open_two_sessions();
1✔
461

462
   Test::Result result("PKCS 11 low level - C_CloseAllSessions");
1✔
463

464
   // test throw variant
465
   p11_low_level.get()->C_CloseAllSessions(slot_vec.at(0));
1✔
466
   result.test_success("C_CloseAllSessions does not throw");
1✔
467

468
   // test bool return variant
469
   open_two_sessions();
1✔
470

471
   bool success = p11_low_level.get()->C_CloseAllSessions(slot_vec.at(0), nullptr);
1✔
472
   result.test_eq("C_CloseAllSessions", success, true);
1✔
473

474
   // test ReturnValue variant
475
   open_two_sessions();
1✔
476

477
   ReturnValue rv = ReturnValue::OK;
1✔
478
   success = p11_low_level.get()->C_CloseAllSessions(slot_vec.at(0), &rv);
1✔
479
   result.test_eq("C_CloseAllSessions", success, true);
1✔
480
   result.test_rc_ok("C_CloseAllSessions", static_cast<uint32_t>(rv));
1✔
481

482
   return result;
1✔
483
}
1✔
484

485
Test::Result test_c_get_session_info() {
1✔
486
   RAII_LowLevel p11_low_level;
1✔
487
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
488

489
   // public read only session
490
   Flags flags = PKCS11::flags(Flag::SerialSession);
1✔
491
   SessionHandle session_handle = p11_low_level.open_session(flags);
1✔
492

493
   SessionInfo session_info = {};
1✔
494
   Test::Result result = test_function(
1✔
495
      "C_GetSessionInfo",
496
      std::bind(
1✔
497
         &LowLevel::C_GetSessionInfo, p11_low_level.get(), session_handle, &session_info, std::placeholders::_1));
3✔
498

499
   result.confirm("C_GetSessionInfo returns same slot id as during call to C_OpenSession",
1✔
500
                  session_info.slotID == slot_vec.at(0));
1✔
501
   result.confirm("C_GetSessionInfo returns same flags as during call to C_OpenSession", session_info.flags == flags);
2✔
502
   result.confirm("C_GetSessionInfo returns public read only session state",
1✔
503
                  session_info.state == static_cast<CK_FLAGS>(SessionState::RoPublicSession));
1✔
504

505
   return result;
1✔
506
}
1✔
507

508
Test::Result login_logout_helper(const RAII_LowLevel& p11_low_level,
3✔
509
                                 SessionHandle handle,
510
                                 UserType user_type,
511
                                 std::string_view pin) {
512
   secure_vector<uint8_t> pin_as_sec_vec(pin.begin(), pin.end());
3✔
513

514
   auto login_secvec_binder = std::bind(
3✔
515
      static_cast<bool (LowLevel::*)(SessionHandle, UserType, const secure_vector<uint8_t>&, ReturnValue*) const>(
3✔
516
         &LowLevel::C_Login<secure_allocator<uint8_t>>),
517
      p11_low_level.get(),
3✔
518
      handle,
519
      user_type,
520
      std::ref(pin_as_sec_vec),
3✔
521
      std::placeholders::_1);
3✔
522

523
   auto logout_binder =
3✔
524
      std::bind(static_cast<bool (LowLevel::*)(SessionHandle, ReturnValue*) const>(&LowLevel::C_Logout),
3✔
525
                p11_low_level.get(),
3✔
526
                handle,
527
                std::placeholders::_1);
3✔
528

529
   return test_function("C_Login", login_secvec_binder, "C_Logout", logout_binder);
12✔
530
}
3✔
531

532
Test::Result test_c_login_logout_security_officier() {
1✔
533
   RAII_LowLevel p11_low_level;
1✔
534

535
   // can only login to R/W session
536
   Flags session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
537
   SessionHandle session_handle = p11_low_level.open_session(session_flags);
1✔
538

539
   return login_logout_helper(p11_low_level, session_handle, UserType::SO, PKCS11_SO_PIN);
2✔
540
}
1✔
541

542
Test::Result test_c_login_logout_user() {
1✔
543
   RAII_LowLevel p11_low_level;
1✔
544

545
   // R/O session
546
   Flags session_flags = PKCS11::flags(Flag::SerialSession);
1✔
547
   SessionHandle session_handle = p11_low_level.open_session(session_flags);
1✔
548
   Test::Result result = login_logout_helper(p11_low_level, session_handle, UserType::User, PKCS11_USER_PIN);
1✔
549
   p11_low_level.close_session();
1✔
550

551
   // R/W session
552
   session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
553
   session_handle = p11_low_level.open_session(session_flags);
1✔
554

555
   result.merge(login_logout_helper(p11_low_level, session_handle, UserType::User, PKCS11_USER_PIN));
1✔
556

557
   return result;
1✔
558
}
1✔
559

560
Test::Result test_c_init_pin() {
1✔
561
   RAII_LowLevel p11_low_level;
1✔
562

563
   // C_InitPIN can only be called in the "R/W SO Functions" state
564
   Flags session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
565
   SessionHandle session_handle = p11_low_level.open_session(session_flags);
1✔
566

567
   p11_low_level.login(UserType::SO, SO_PIN());
1✔
568

569
   auto sec_vec_binder =
1✔
570
      std::bind(static_cast<bool (LowLevel::*)(SessionHandle, const secure_vector<uint8_t>&, ReturnValue*) const>(
1✔
571
                   &LowLevel::C_InitPIN<secure_allocator<uint8_t>>),
572
                p11_low_level.get(),
1✔
573
                session_handle,
574
                PIN(),
1✔
575
                std::placeholders::_1);
1✔
576

577
   return test_function("C_InitPIN", sec_vec_binder);
4✔
578
}
1✔
579

580
Test::Result test_c_set_pin() {
1✔
581
   RAII_LowLevel p11_low_level;
1✔
582

583
   // C_SetPIN can only be called in the "R / W Public Session" state, "R / W SO Functions" state, or "R / W User Functions" state
584
   Flags session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
585
   SessionHandle session_handle = p11_low_level.open_session(session_flags);
1✔
586

587
   // now we are in "R / W Public Session" state: this will change the pin of the user
588

589
   auto get_pin_bind = [&session_handle, &p11_low_level](
5✔
590
                          const secure_vector<uint8_t>& old_pin,
591
                          const secure_vector<uint8_t>& new_pin) -> PKCS11_BoundTestFunction {
592
      return std::bind(
12✔
593
         static_cast<bool (LowLevel::*)(
4✔
594
            SessionHandle, const secure_vector<uint8_t>&, const secure_vector<uint8_t>&, ReturnValue*) const>(
595
            &LowLevel::C_SetPIN<secure_allocator<uint8_t>>),
596
         p11_low_level.get(),
4✔
597
         session_handle,
598
         old_pin,
599
         new_pin,
600
         std::placeholders::_1);
8✔
601
   };
1✔
602

603
   const std::string test_pin("654321");
1✔
604
   const auto test_pin_secvec = secure_vector<uint8_t>(test_pin.begin(), test_pin.end());
1✔
605

606
   PKCS11_BoundTestFunction set_pin_bind = get_pin_bind(PIN(), test_pin_secvec);
1✔
607
   PKCS11_BoundTestFunction revert_pin_bind = get_pin_bind(test_pin_secvec, PIN());
1✔
608

609
   Test::Result result = test_function("C_SetPIN", set_pin_bind, "C_SetPIN", revert_pin_bind);
2✔
610

611
   // change pin in "R / W User Functions" state
612
   p11_low_level.login(UserType::User, PIN());
1✔
613

614
   result.merge(test_function("C_SetPIN", set_pin_bind, "C_SetPIN", revert_pin_bind));
2✔
615
   p11_low_level.logout();
1✔
616

617
   // change so_pin in "R / W SO Functions" state
618
   const std::string test_so_pin = "87654321";
1✔
619
   secure_vector<uint8_t> test_so_pin_secvec(test_so_pin.begin(), test_so_pin.end());
1✔
620
   p11_low_level.login(UserType::SO, SO_PIN());
1✔
621

622
   PKCS11_BoundTestFunction set_so_pin_bind = get_pin_bind(SO_PIN(), test_so_pin_secvec);
1✔
623
   PKCS11_BoundTestFunction revert_so_pin_bind = get_pin_bind(test_so_pin_secvec, SO_PIN());
1✔
624

625
   result.merge(test_function("C_SetPIN", set_so_pin_bind, "C_SetPIN", revert_so_pin_bind));
2✔
626

627
   return result;
2✔
628
}
6✔
629

630
// Simple data object
631
const ObjectClass object_class = ObjectClass::Data;
632
const std::string_view label = "A data object";
633
const std::string_view data = "Sample data";
634
const Bbool btrue = True;
635

636
const std::array<Attribute, 4> data_template = {
637
   {{static_cast<CK_ATTRIBUTE_TYPE>(AttributeType::Class),
638
     const_cast<ObjectClass*>(&object_class),
639
     sizeof(object_class)},
640
    {static_cast<CK_ATTRIBUTE_TYPE>(AttributeType::Token), const_cast<Bbool*>(&btrue), sizeof(btrue)},
641
    {static_cast<CK_ATTRIBUTE_TYPE>(AttributeType::Label),
642
     const_cast<char*>(label.data()),
643
     static_cast<CK_ULONG>(label.size())},
644
    {static_cast<CK_ATTRIBUTE_TYPE>(AttributeType::Value),
645
     const_cast<char*>(data.data()),
646
     static_cast<CK_ULONG>(data.size())}}};
647

648
ObjectHandle create_simple_data_object(const RAII_LowLevel& p11_low_level) {
4✔
649
   ObjectHandle object_handle = {};
4✔
650

651
   auto dtemplate = data_template;
4✔
652
   p11_low_level.get()->C_CreateObject(
4✔
653
      p11_low_level.get_session_handle(), dtemplate.data(), static_cast<Ulong>(dtemplate.size()), &object_handle);
654
   return object_handle;
4✔
655
}
656

657
Test::Result test_c_create_object_c_destroy_object() {
1✔
658
   RAII_LowLevel p11_low_level;
1✔
659
   SessionHandle session_handle = p11_low_level.open_rw_session_with_user_login();
1✔
660

661
   ObjectHandle object_handle(0);
1✔
662

663
   auto dtemplate = data_template;
1✔
664

665
   auto create_bind = std::bind(&LowLevel::C_CreateObject,
1✔
666
                                p11_low_level.get(),
1✔
667
                                session_handle,
668
                                dtemplate.data(),
1✔
669
                                static_cast<Ulong>(dtemplate.size()),
1✔
670
                                &object_handle,
671
                                std::placeholders::_1);
1✔
672

673
   auto destroy_bind = std::bind(
1✔
674
      &LowLevel::C_DestroyObject, p11_low_level.get(), session_handle, std::ref(object_handle), std::placeholders::_1);
1✔
675

676
   return test_function("C_CreateObject", create_bind, "C_DestroyObject", destroy_bind);
4✔
677
}
1✔
678

679
Test::Result test_c_get_object_size() {
1✔
680
   RAII_LowLevel p11_low_level;
1✔
681

682
   Flags session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
683
   SessionHandle session_handle = p11_low_level.open_session(session_flags);
1✔
684

685
   p11_low_level.login(UserType::User, PIN());
1✔
686

687
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
688
   Ulong object_size = 0;
1✔
689

690
   auto bind = std::bind(&LowLevel::C_GetObjectSize,
1✔
691
                         p11_low_level.get(),
1✔
692
                         session_handle,
693
                         object_handle,
694
                         &object_size,
1✔
695
                         std::placeholders::_1);
1✔
696

697
   Test::Result result = test_function("C_GetObjectSize", bind);
2✔
698
   result.test_ne("Object size", object_size, 0);
1✔
699

700
   // cleanup
701
   p11_low_level.get()->C_DestroyObject(session_handle, object_handle);
1✔
702

703
   return result;
1✔
704
}
1✔
705

706
Test::Result test_c_get_attribute_value() {
1✔
707
   RAII_LowLevel p11_low_level;
1✔
708
   SessionHandle session_handle = p11_low_level.open_rw_session_with_user_login();
1✔
709

710
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
711

712
   std::map<AttributeType, secure_vector<uint8_t>> getter = {{AttributeType::Label, secure_vector<uint8_t>()},
1✔
713
                                                             {AttributeType::Value, secure_vector<uint8_t>()}};
3✔
714

715
   auto bind =
1✔
716
      std::bind(static_cast<bool (LowLevel::*)(
1✔
717
                   SessionHandle, ObjectHandle, std::map<AttributeType, secure_vector<uint8_t>>&, ReturnValue*) const>(
718
                   &LowLevel::C_GetAttributeValue<secure_allocator<uint8_t>>),
719
                p11_low_level.get(),
1✔
720
                session_handle,
721
                object_handle,
722
                std::ref(getter),
1✔
723
                std::placeholders::_1);
1✔
724

725
   Test::Result result = test_function("C_GetAttributeValue", bind);
2✔
726

727
   std::string _label(getter[AttributeType::Label].begin(), getter[AttributeType::Label].end());
2✔
728
   std::string value(getter[AttributeType::Value].begin(), getter[AttributeType::Value].end());
2✔
729
   result.test_eq("label", _label, "A data object");
2✔
730
   result.test_eq("value", value, "Sample data");
2✔
731

732
   // cleanup
733
   p11_low_level.get()->C_DestroyObject(session_handle, object_handle);
1✔
734

735
   return result;
2✔
736
}
1✔
737

738
std::map<AttributeType, std::vector<uint8_t>> get_attribute_values(const RAII_LowLevel& p11_low_level,
2✔
739
                                                                   SessionHandle session_handle,
740
                                                                   ObjectHandle object_handle,
741
                                                                   const std::vector<AttributeType>& attribute_types) {
742
   std::map<AttributeType, std::vector<uint8_t>> received_attributes;
2✔
743

744
   for(const auto& type : attribute_types) {
6✔
745
      received_attributes.emplace(type, std::vector<uint8_t>());
8✔
746
   }
747

748
   p11_low_level.get()->C_GetAttributeValue(session_handle, object_handle, received_attributes);
2✔
749

750
   return received_attributes;
2✔
751
}
×
752

753
Test::Result test_c_set_attribute_value() {
1✔
754
   RAII_LowLevel p11_low_level;
1✔
755

756
   Flags session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
757
   SessionHandle session_handle = p11_low_level.open_session(session_flags);
1✔
758

759
   p11_low_level.login(UserType::User, PIN());
1✔
760

761
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
762

763
   std::string new_label = "A modified data object";
1✔
764

765
   std::map<AttributeType, secure_vector<uint8_t>> new_attributes = {
1✔
766
      {AttributeType::Label, secure_vector<uint8_t>(new_label.begin(), new_label.end())}};
3✔
767

768
   auto bind =
1✔
769
      std::bind(static_cast<bool (LowLevel::*)(
1✔
770
                   SessionHandle, ObjectHandle, std::map<AttributeType, secure_vector<uint8_t>>&, ReturnValue*) const>(
771
                   &LowLevel::C_SetAttributeValue<secure_allocator<uint8_t>>),
772
                p11_low_level.get(),
1✔
773
                session_handle,
774
                object_handle,
775
                std::ref(new_attributes),
1✔
776
                std::placeholders::_1);
1✔
777

778
   Test::Result result = test_function("C_SetAttributeValue", bind);
2✔
779

780
   // get attributes and check if they are changed correctly
781
   std::vector<AttributeType> types = {AttributeType::Label, AttributeType::Value};
1✔
782
   auto received_attributes = get_attribute_values(p11_low_level, session_handle, object_handle, types);
1✔
783

784
   std::string retrieved_label(received_attributes[AttributeType::Label].begin(),
1✔
785
                               received_attributes[AttributeType::Label].end());
2✔
786

787
   result.test_eq("label", new_label, retrieved_label);
1✔
788

789
   // cleanup
790
   p11_low_level.get()->C_DestroyObject(session_handle, object_handle);
1✔
791

792
   return result;
2✔
793
}
2✔
794

795
Test::Result test_c_copy_object() {
1✔
796
   RAII_LowLevel p11_low_level;
1✔
797
   SessionHandle session_handle = p11_low_level.open_rw_session_with_user_login();
1✔
798

799
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
800
   ObjectHandle copied_object_handle = 0;
1✔
801

802
   std::string copied_label = "A copied data object";
1✔
803

804
   Attribute copy_attribute_values = {static_cast<CK_ATTRIBUTE_TYPE>(AttributeType::Label),
1✔
805
                                      const_cast<char*>(copied_label.c_str()),
1✔
806
                                      static_cast<CK_ULONG>(copied_label.size())};
1✔
807

808
   auto binder = std::bind(&LowLevel::C_CopyObject,
1✔
809
                           p11_low_level.get(),
1✔
810
                           session_handle,
811
                           object_handle,
812
                           &copy_attribute_values,
1✔
813
                           1,
814
                           &copied_object_handle,
815
                           std::placeholders::_1);
1✔
816

817
   Test::Result result = test_function("C_CopyObject", binder);
2✔
818

819
   // get attributes and check if its copied correctly
820
   std::vector<AttributeType> types = {AttributeType::Label, AttributeType::Value};
1✔
821
   auto received_attributes = get_attribute_values(p11_low_level, session_handle, copied_object_handle, types);
1✔
822

823
   std::string retrieved_label(received_attributes[AttributeType::Label].begin(),
1✔
824
                               received_attributes[AttributeType::Label].end());
2✔
825

826
   result.test_eq("label", copied_label, retrieved_label);
1✔
827

828
   // cleanup
829
   p11_low_level.get()->C_DestroyObject(session_handle, object_handle);
1✔
830
   p11_low_level.get()->C_DestroyObject(session_handle, copied_object_handle);
1✔
831

832
   return result;
2✔
833
}
1✔
834

835
// NOLINTEND(*-avoid-bind)
836

837
Test::Result test_load_latest_interface() {
1✔
838
   Test::Result res("Load latest PKCS #11 interface");
1✔
839
   Botan::Dynamically_Loaded_Library pkcs11_module(Test::pkcs11_lib());
1✔
840
   res.test_no_throw("Get function lists of latest interface", [&] {
2✔
841
      auto latest_interface = InterfaceWrapper::latest_p11_interface(pkcs11_module);
1✔
842
      latest_interface.func_2_40();
1✔
843
      if(latest_interface.version().major >= 3) {
1✔
844
         latest_interface.func_3_0();
×
845

846
         if(latest_interface.version().major > 3 || latest_interface.version().minor >= 2) {
×
847
            latest_interface.func_3_2();
×
848
         }
849
      }
850
   });
1✔
851
   return res;
1✔
852
}
1✔
853

854
class LowLevelTests final : public Test {
×
855
   public:
856
      std::vector<Test::Result> run() override {
1✔
857
         std::vector<std::pair<std::string, std::function<Test::Result()>>> fns = {
1✔
858
            {STRING_AND_FUNCTION(test_c_get_function_list)},
859
            {STRING_AND_FUNCTION(test_low_level_ctor)},
860
            {STRING_AND_FUNCTION(test_initialize_finalize)},
861
            {STRING_AND_FUNCTION(test_c_get_info)},
862
            {STRING_AND_FUNCTION(test_c_get_slot_list)},
863
            {STRING_AND_FUNCTION(test_c_get_slot_info)},
864
            {STRING_AND_FUNCTION(test_c_get_token_info)},
865
            {STRING_AND_FUNCTION(test_c_wait_for_slot_event)},
866
            {STRING_AND_FUNCTION(test_c_get_mechanism_list)},
867
            {STRING_AND_FUNCTION(test_c_get_mechanism_info)},
868
            {STRING_AND_FUNCTION(test_open_close_session)},
869
            {STRING_AND_FUNCTION(test_c_close_all_sessions)},
870
            {STRING_AND_FUNCTION(test_c_get_session_info)},
871
            {STRING_AND_FUNCTION(test_c_init_token)},
872
            {STRING_AND_FUNCTION(test_c_login_logout_security_officier)}, /* only possible if token is initialized */
873
            {STRING_AND_FUNCTION(test_c_init_pin)},
874
            {STRING_AND_FUNCTION(
875
               test_c_login_logout_user)}, /* only possible if token is initialized and user pin is set */
876
            {STRING_AND_FUNCTION(test_c_set_pin)},
877
            {STRING_AND_FUNCTION(test_c_create_object_c_destroy_object)},
878
            {STRING_AND_FUNCTION(test_c_get_object_size)},
879
            {STRING_AND_FUNCTION(test_c_get_attribute_value)},
880
            {STRING_AND_FUNCTION(test_c_set_attribute_value)},
881
            {STRING_AND_FUNCTION(test_c_copy_object)},
882
            {STRING_AND_FUNCTION(test_load_latest_interface)},
883
         };
25✔
884

885
         return run_pkcs11_tests("PKCS11 low level", fns);
2✔
886
      }
2✔
887
};
888

889
BOTAN_REGISTER_SERIALIZED_TEST("pkcs11", "pkcs11-lowlevel", LowLevelTests);
890

891
   #endif
892
#endif
893

894
}  // namespace
895
}  // namespace Botan_Tests
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc