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

randombit / botan / 16055899095

03 Jul 2025 04:34PM UTC coverage: 90.571% (-0.003%) from 90.574%
16055899095

push

github

web-flow
Merge pull request #4931 from randombit/jack/moar-tidy

Address various warnings from clang-tidy

99050 of 109362 relevant lines covered (90.57%)

12478386.65 hits per line

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

97.03
/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_low_level(),
20✔
40
            m_session_handle(0),
20✔
41
            m_is_session_open(false),
20✔
42
            m_is_logged_in(false) {
20✔
43
         LowLevel::C_GetFunctionList(m_module, &m_func_list);
20✔
44
         m_low_level = std::make_unique<LowLevel>(m_func_list);
20✔
45

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

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

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

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

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

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

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

80
         return slots;
19✔
81
      }
×
82

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

202
   return result;
26✔
203
}
26✔
204

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

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

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

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

226
   Dynamically_Loaded_Library pkcs11_module(Test::pkcs11_lib());
1✔
227
   FunctionListPtr func_list(nullptr);
1✔
228
   LowLevel::C_GetFunctionList(pkcs11_module, &func_list);
1✔
229

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

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

236
   return result;
1✔
237
}
1✔
238

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

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

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

254
   LowLevel p11_low_level(func_list);
1✔
255

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

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

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

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

272
   return result;
1✔
273
}
1✔
274

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

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

280
   // assumes smartcard reader is attached without card
281

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

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

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

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

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

305
   return result;
1✔
306
}
1✔
307

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

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

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

320
   return result;
2✔
321
}
1✔
322

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

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

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

335
   return result;
2✔
336
}
1✔
337

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

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

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

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

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

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

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

367
   return result;
1✔
368
}
1✔
369

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

442
   return result;
1✔
443
}
1✔
444

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

449
   auto open_two_sessions = [&slot_vec, &p11_low_level]() -> void {
4✔
450
      // public read only session
451
      Flags flags = PKCS11::flags(Flag::SerialSession);
3✔
452
      SessionHandle first_session_handle = 0, 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
                                 const std::string& 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 label = "A data object";
633
const std::string 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.c_str()),
643
     static_cast<CK_ULONG>(label.size())},
644
    {static_cast<CK_ATTRIBUTE_TYPE>(AttributeType::Value),
645
     const_cast<char*>(data.c_str()),
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
class LowLevelTests final : public Test {
×
838
   public:
839
      std::vector<Test::Result> run() override {
1✔
840
         std::vector<std::pair<std::string, std::function<Test::Result()>>> fns = {
1✔
841
            {STRING_AND_FUNCTION(test_c_get_function_list)},
842
            {STRING_AND_FUNCTION(test_low_level_ctor)},
843
            {STRING_AND_FUNCTION(test_initialize_finalize)},
844
            {STRING_AND_FUNCTION(test_c_get_info)},
845
            {STRING_AND_FUNCTION(test_c_get_slot_list)},
846
            {STRING_AND_FUNCTION(test_c_get_slot_info)},
847
            {STRING_AND_FUNCTION(test_c_get_token_info)},
848
            {STRING_AND_FUNCTION(test_c_wait_for_slot_event)},
849
            {STRING_AND_FUNCTION(test_c_get_mechanism_list)},
850
            {STRING_AND_FUNCTION(test_c_get_mechanism_info)},
851
            {STRING_AND_FUNCTION(test_open_close_session)},
852
            {STRING_AND_FUNCTION(test_c_close_all_sessions)},
853
            {STRING_AND_FUNCTION(test_c_get_session_info)},
854
            {STRING_AND_FUNCTION(test_c_init_token)},
855
            {STRING_AND_FUNCTION(test_c_login_logout_security_officier)}, /* only possible if token is initialized */
856
            {STRING_AND_FUNCTION(test_c_init_pin)},
857
            {STRING_AND_FUNCTION(
858
               test_c_login_logout_user)}, /* only possible if token is initialized and user pin is set */
859
            {STRING_AND_FUNCTION(test_c_set_pin)},
860
            {STRING_AND_FUNCTION(test_c_create_object_c_destroy_object)},
861
            {STRING_AND_FUNCTION(test_c_get_object_size)},
862
            {STRING_AND_FUNCTION(test_c_get_attribute_value)},
863
            {STRING_AND_FUNCTION(test_c_set_attribute_value)},
864
            {STRING_AND_FUNCTION(test_c_copy_object)}};
24✔
865

866
         return run_pkcs11_tests("PKCS11 low level", fns);
2✔
867
      }
2✔
868
};
869

870
BOTAN_REGISTER_SERIALIZED_TEST("pkcs11", "pkcs11-lowlevel", LowLevelTests);
871

872
   #endif
873
#endif
874

875
}  // namespace
876
}  // 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