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

randombit / botan / 5200168067

07 Jun 2023 12:49PM UTC coverage: 91.738% (-0.009%) from 91.747%
5200168067

push

github

randombit
Merge GH #3573 Enable some additional clang-tidy warnings

76197 of 83059 relevant lines covered (91.74%)

11891039.95 hits per line

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

97.24
/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
      inline 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
      inline 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
      inline 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
      inline 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
      inline 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
      inline 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*/) { return true; }
×
147

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

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

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

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

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

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

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

200
   return result;
26✔
201
}
26✔
202

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

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

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

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

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

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

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

234
   return result;
1✔
235
}
1✔
236

237
Test::Result test_c_get_function_list() {
1✔
238
   Dynamically_Loaded_Library pkcs11_module(Test::pkcs11_lib());
1✔
239
   FunctionListPtr func_list = nullptr;
1✔
240
   return test_function(
1✔
241
      "C_GetFunctionList",
242
      std::bind(&LowLevel::C_GetFunctionList, std::ref(pkcs11_module), &func_list, std::placeholders::_1));
3✔
243
}
1✔
244

245
Test::Result test_initialize_finalize() {
1✔
246
   Dynamically_Loaded_Library pkcs11_module(Test::pkcs11_lib());
1✔
247
   FunctionListPtr func_list = nullptr;
1✔
248
   LowLevel::C_GetFunctionList(pkcs11_module, &func_list);
1✔
249

250
   LowLevel p11_low_level(func_list);
1✔
251

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

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

260
Test::Result test_c_get_info() {
1✔
261
   RAII_LowLevel p11_low_level;
1✔
262

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

268
   return result;
1✔
269
}
1✔
270

271
Test::Result test_c_get_slot_list() {
1✔
272
   RAII_LowLevel p11_low_level;
1✔
273

274
   std::vector<SlotId> slot_vec;
1✔
275

276
   // assumes smartcard reader is attached without card
277

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

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

288
   // assumes smartcard reader is attached with a card
289

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

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

301
   return result;
2✔
302
}
1✔
303

304
Test::Result test_c_get_slot_info() {
1✔
305
   RAII_LowLevel p11_low_level;
1✔
306
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(false);
1✔
307

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

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

316
   return result;
2✔
317
}
2✔
318

319
Test::Result test_c_get_token_info() {
1✔
320
   RAII_LowLevel p11_low_level;
1✔
321
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
322

323
   TokenInfo token_info = {};
1✔
324
   Test::Result result = test_function(
1✔
325
      "C_GetTokenInfo",
326
      std::bind(&LowLevel::C_GetTokenInfo, *p11_low_level.get(), slot_vec.at(0), &token_info, std::placeholders::_1));
2✔
327

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

331
   return result;
2✔
332
}
2✔
333

334
Test::Result test_c_wait_for_slot_event() {
1✔
335
   RAII_LowLevel p11_low_level;
1✔
336

337
   Flags flags = PKCS11::flags(Flag::DontBlock);
1✔
338
   SlotId slot_id = 0;
1✔
339

340
   return test_function(
1✔
341
      "C_WaitForSlotEvent",
342
      std::bind(&LowLevel::C_WaitForSlotEvent, *p11_low_level.get(), flags, &slot_id, nullptr, std::placeholders::_1),
1✔
343
      true,
344
      ReturnValue::NoEvent);
3✔
345
}
1✔
346

347
Test::Result test_c_get_mechanism_list() {
1✔
348
   RAII_LowLevel p11_low_level;
1✔
349
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
350

351
   std::vector<MechanismType> mechanisms;
1✔
352

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

360
   Test::Result result = test_function("C_GetMechanismList", binder);
2✔
361
   result.confirm("C_GetMechanismList returns non empty mechanisms list", !mechanisms.empty());
2✔
362

363
   return result;
2✔
364
}
2✔
365

366
Test::Result test_c_get_mechanism_info() {
1✔
367
   RAII_LowLevel p11_low_level;
1✔
368
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
369

370
   std::vector<MechanismType> mechanisms;
1✔
371
   p11_low_level.get()->C_GetMechanismList(slot_vec.at(0), mechanisms);
1✔
372

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

383
Test::Result test_c_init_token() {
1✔
384
   RAII_LowLevel p11_low_level;
1✔
385
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
386

387
   const std::string label = "Botan PKCS#11 tests";
1✔
388
   std::string_view label_view(label);
1✔
389

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

399
   return test_function("C_InitToken", sec_vec_binder);
4✔
400
}
3✔
401

402
Test::Result test_open_close_session() {
1✔
403
   RAII_LowLevel p11_low_level;
1✔
404
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
405

406
   // public read only session
407
   const Flags ro_flags = PKCS11::flags(Flag::SerialSession);
1✔
408
   SessionHandle session_handle = 0;
1✔
409

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

419
   auto close_session =
1✔
420
      std::bind(&LowLevel::C_CloseSession, *p11_low_level.get(), std::ref(session_handle), std::placeholders::_1);
1✔
421

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

424
   // public read write session
425
   const Flags rw_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
426

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

436
   result.merge(test_function("C_OpenSession", open_session_rw, "C_CloseSession", close_session));
3✔
437

438
   return result;
2✔
439
}
1✔
440

441
Test::Result test_c_close_all_sessions() {
1✔
442
   RAII_LowLevel p11_low_level;
1✔
443
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
444

445
   auto open_two_sessions = [&slot_vec, &p11_low_level]() -> void {
7✔
446
      // public read only session
447
      Flags flags = PKCS11::flags(Flag::SerialSession);
3✔
448
      SessionHandle first_session_handle = 0, second_session_handle = 0;
3✔
449

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

452
      flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
3✔
453
      p11_low_level.get()->C_OpenSession(slot_vec.at(0), flags, nullptr, nullptr, &second_session_handle);
3✔
454
   };
4✔
455

456
   open_two_sessions();
1✔
457

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

460
   // test throw variant
461
   p11_low_level.get()->C_CloseAllSessions(slot_vec.at(0));
1✔
462
   result.test_success("C_CloseAllSessions does not throw");
1✔
463

464
   // test bool return variant
465
   open_two_sessions();
1✔
466

467
   bool success = p11_low_level.get()->C_CloseAllSessions(slot_vec.at(0), nullptr);
1✔
468
   result.test_eq("C_CloseAllSessions", success, true);
1✔
469

470
   // test ReturnValue variant
471
   open_two_sessions();
1✔
472

473
   ReturnValue rv = static_cast<ReturnValue>(-1);
1✔
474
   success = p11_low_level.get()->C_CloseAllSessions(slot_vec.at(0), &rv);
1✔
475
   result.test_eq("C_CloseAllSessions", success, true);
1✔
476
   result.test_rc_ok("C_CloseAllSessions", static_cast<uint32_t>(rv));
1✔
477

478
   return result;
2✔
479
}
1✔
480

481
Test::Result test_c_get_session_info() {
1✔
482
   RAII_LowLevel p11_low_level;
1✔
483
   std::vector<SlotId> slot_vec = p11_low_level.get_slots(true);
1✔
484

485
   // public read only session
486
   Flags flags = PKCS11::flags(Flag::SerialSession);
1✔
487
   SessionHandle session_handle = p11_low_level.open_session(flags);
1✔
488

489
   SessionInfo session_info = {};
1✔
490
   Test::Result result = test_function(
1✔
491
      "C_GetSessionInfo",
492
      std::bind(
1✔
493
         &LowLevel::C_GetSessionInfo, *p11_low_level.get(), session_handle, &session_info, std::placeholders::_1));
2✔
494

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

501
   return result;
2✔
502
}
1✔
503

504
Test::Result login_logout_helper(const RAII_LowLevel& p11_low_level,
3✔
505
                                 SessionHandle handle,
506
                                 UserType user_type,
507
                                 const std::string& pin) {
508
   secure_vector<uint8_t> pin_as_sec_vec(pin.begin(), pin.end());
3✔
509

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

519
   auto logout_binder =
3✔
520
      std::bind(static_cast<bool (LowLevel::*)(SessionHandle, ReturnValue*) const>(&LowLevel::C_Logout),
3✔
521
                *p11_low_level.get(),
3✔
522
                handle,
523
                std::placeholders::_1);
3✔
524

525
   return test_function("C_Login", login_secvec_binder, "C_Logout", logout_binder);
12✔
526
}
3✔
527

528
Test::Result test_c_login_logout_security_officier() {
1✔
529
   RAII_LowLevel p11_low_level;
1✔
530

531
   // can only login to R/W session
532
   Flags session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
533
   SessionHandle session_handle = p11_low_level.open_session(session_flags);
1✔
534

535
   return login_logout_helper(p11_low_level, session_handle, UserType::SO, PKCS11_SO_PIN);
2✔
536
}
1✔
537

538
Test::Result test_c_login_logout_user() {
1✔
539
   RAII_LowLevel p11_low_level;
1✔
540

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

547
   // R/W session
548
   session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
549
   session_handle = p11_low_level.open_session(session_flags);
1✔
550

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

553
   return result;
1✔
554
}
1✔
555

556
Test::Result test_c_init_pin() {
1✔
557
   RAII_LowLevel p11_low_level;
1✔
558

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

563
   p11_low_level.login(UserType::SO, SO_PIN());
1✔
564

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

573
   return test_function("C_InitPIN", sec_vec_binder);
4✔
574
}
1✔
575

576
Test::Result test_c_set_pin() {
1✔
577
   RAII_LowLevel p11_low_level;
1✔
578

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

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

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

599
   const std::string test_pin("654321");
1✔
600
   const auto test_pin_secvec = secure_vector<uint8_t>(test_pin.begin(), test_pin.end());
1✔
601

602
   PKCS11_BoundTestFunction set_pin_bind = get_pin_bind(PIN(), test_pin_secvec);
1✔
603
   PKCS11_BoundTestFunction revert_pin_bind = get_pin_bind(test_pin_secvec, PIN());
1✔
604

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

607
   // change pin in "R / W User Functions" state
608
   p11_low_level.login(UserType::User, PIN());
1✔
609

610
   result.merge(test_function("C_SetPIN", set_pin_bind, "C_SetPIN", revert_pin_bind));
2✔
611
   p11_low_level.logout();
1✔
612

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

618
   PKCS11_BoundTestFunction set_so_pin_bind = get_pin_bind(SO_PIN(), test_so_pin_secvec);
1✔
619
   PKCS11_BoundTestFunction revert_so_pin_bind = get_pin_bind(test_so_pin_secvec, SO_PIN());
1✔
620

621
   result.merge(test_function("C_SetPIN", set_so_pin_bind, "C_SetPIN", revert_so_pin_bind));
2✔
622

623
   return result;
2✔
624
}
6✔
625

626
// Simple data object
627
const ObjectClass object_class = ObjectClass::Data;
628
const std::string label = "A data object";
629
const std::string data = "Sample data";
630
const Bbool btrue = True;
631

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

644
ObjectHandle create_simple_data_object(const RAII_LowLevel& p11_low_level) {
4✔
645
   ObjectHandle object_handle;
4✔
646

647
   auto dtemplate = data_template;
4✔
648
   p11_low_level.get()->C_CreateObject(
4✔
649
      p11_low_level.get_session_handle(), dtemplate.data(), static_cast<Ulong>(dtemplate.size()), &object_handle);
650
   return object_handle;
4✔
651
}
652

653
Test::Result test_c_create_object_c_destroy_object() {
1✔
654
   RAII_LowLevel p11_low_level;
1✔
655
   SessionHandle session_handle = p11_low_level.open_rw_session_with_user_login();
1✔
656

657
   ObjectHandle object_handle(0);
1✔
658

659
   auto dtemplate = data_template;
1✔
660

661
   auto create_bind = std::bind(&LowLevel::C_CreateObject,
1✔
662
                                *p11_low_level.get(),
1✔
663
                                session_handle,
664
                                dtemplate.data(),
1✔
665
                                static_cast<Ulong>(dtemplate.size()),
1✔
666
                                &object_handle,
667
                                std::placeholders::_1);
1✔
668

669
   auto destroy_bind = std::bind(
1✔
670
      &LowLevel::C_DestroyObject, *p11_low_level.get(), session_handle, std::ref(object_handle), std::placeholders::_1);
1✔
671

672
   return test_function("C_CreateObject", create_bind, "C_DestroyObject", destroy_bind);
4✔
673
}
1✔
674

675
Test::Result test_c_get_object_size() {
1✔
676
   RAII_LowLevel p11_low_level;
1✔
677

678
   Flags session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
679
   SessionHandle session_handle = p11_low_level.open_session(session_flags);
1✔
680

681
   p11_low_level.login(UserType::User, PIN());
1✔
682

683
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
684
   Ulong object_size = 0;
1✔
685

686
   auto bind = std::bind(&LowLevel::C_GetObjectSize,
1✔
687
                         *p11_low_level.get(),
1✔
688
                         session_handle,
689
                         object_handle,
690
                         &object_size,
1✔
691
                         std::placeholders::_1);
1✔
692

693
   Test::Result result = test_function("C_GetObjectSize", bind);
2✔
694
   result.test_ne("Object size", object_size, 0);
1✔
695

696
   // cleanup
697
   p11_low_level.get()->C_DestroyObject(session_handle, object_handle);
1✔
698

699
   return result;
1✔
700
}
1✔
701

702
Test::Result test_c_get_attribute_value() {
1✔
703
   RAII_LowLevel p11_low_level;
1✔
704
   SessionHandle session_handle = p11_low_level.open_rw_session_with_user_login();
1✔
705

706
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
707

708
   std::map<AttributeType, secure_vector<uint8_t>> getter = {{AttributeType::Label, secure_vector<uint8_t>()},
1✔
709
                                                             {AttributeType::Value, secure_vector<uint8_t>()}};
3✔
710

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

721
   Test::Result result = test_function("C_GetAttributeValue", bind);
2✔
722

723
   std::string _label(getter[AttributeType::Label].begin(), getter[AttributeType::Label].end());
1✔
724
   std::string value(getter[AttributeType::Value].begin(), getter[AttributeType::Value].end());
1✔
725
   result.test_eq("label", _label, "A data object");
2✔
726
   result.test_eq("value", value, "Sample data");
2✔
727

728
   // cleanup
729
   p11_low_level.get()->C_DestroyObject(session_handle, object_handle);
1✔
730

731
   return result;
2✔
732
}
1✔
733

734
std::map<AttributeType, std::vector<uint8_t>> get_attribute_values(const RAII_LowLevel& p11_low_level,
2✔
735
                                                                   SessionHandle session_handle,
736
                                                                   ObjectHandle object_handle,
737
                                                                   const std::vector<AttributeType>& attribute_types) {
738
   std::map<AttributeType, std::vector<uint8_t>> received_attributes;
2✔
739

740
   for(const auto& type : attribute_types) {
6✔
741
      received_attributes.emplace(type, std::vector<uint8_t>());
4✔
742
   }
743

744
   p11_low_level.get()->C_GetAttributeValue(session_handle, object_handle, received_attributes);
2✔
745

746
   return received_attributes;
2✔
747
}
×
748

749
Test::Result test_c_set_attribute_value() {
1✔
750
   RAII_LowLevel p11_low_level;
1✔
751

752
   Flags session_flags = PKCS11::flags(Flag::SerialSession | Flag::RwSession);
1✔
753
   SessionHandle session_handle = p11_low_level.open_session(session_flags);
1✔
754

755
   p11_low_level.login(UserType::User, PIN());
1✔
756

757
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
758

759
   std::string new_label = "A modified data object";
1✔
760

761
   std::map<AttributeType, secure_vector<uint8_t>> new_attributes = {
1✔
762
      {AttributeType::Label, secure_vector<uint8_t>(new_label.begin(), new_label.end())}};
2✔
763

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

774
   Test::Result result = test_function("C_SetAttributeValue", bind);
2✔
775

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

780
   std::string retrieved_label(received_attributes[AttributeType::Label].begin(),
1✔
781
                               received_attributes[AttributeType::Label].end());
1✔
782

783
   result.test_eq("label", new_label, retrieved_label);
1✔
784

785
   // cleanup
786
   p11_low_level.get()->C_DestroyObject(session_handle, object_handle);
1✔
787

788
   return result;
2✔
789
}
3✔
790

791
Test::Result test_c_copy_object() {
1✔
792
   RAII_LowLevel p11_low_level;
1✔
793
   SessionHandle session_handle = p11_low_level.open_rw_session_with_user_login();
1✔
794

795
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
796
   ObjectHandle copied_object_handle = 0;
1✔
797

798
   std::string copied_label = "A copied data object";
1✔
799

800
   Attribute copy_attribute_values = {static_cast<CK_ATTRIBUTE_TYPE>(AttributeType::Label),
1✔
801
                                      const_cast<char*>(copied_label.c_str()),
1✔
802
                                      static_cast<CK_ULONG>(copied_label.size())};
1✔
803

804
   auto binder = std::bind(&LowLevel::C_CopyObject,
1✔
805
                           *p11_low_level.get(),
1✔
806
                           session_handle,
807
                           object_handle,
808
                           &copy_attribute_values,
1✔
809
                           1,
810
                           &copied_object_handle,
811
                           std::placeholders::_1);
1✔
812

813
   Test::Result result = test_function("C_CopyObject", binder);
2✔
814

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

819
   std::string retrieved_label(received_attributes[AttributeType::Label].begin(),
1✔
820
                               received_attributes[AttributeType::Label].end());
1✔
821

822
   result.test_eq("label", copied_label, retrieved_label);
1✔
823

824
   // cleanup
825
   p11_low_level.get()->C_DestroyObject(session_handle, object_handle);
1✔
826
   p11_low_level.get()->C_DestroyObject(session_handle, copied_object_handle);
1✔
827

828
   return result;
2✔
829
}
3✔
830

831
class LowLevelTests final : public Test {
×
832
   public:
833
      std::vector<Test::Result> run() override {
1✔
834
         std::vector<std::pair<std::string, std::function<Test::Result()>>> fns = {
1✔
835
            {STRING_AND_FUNCTION(test_c_get_function_list)},
836
            {STRING_AND_FUNCTION(test_low_level_ctor)},
837
            {STRING_AND_FUNCTION(test_initialize_finalize)},
838
            {STRING_AND_FUNCTION(test_c_get_info)},
839
            {STRING_AND_FUNCTION(test_c_get_slot_list)},
840
            {STRING_AND_FUNCTION(test_c_get_slot_info)},
841
            {STRING_AND_FUNCTION(test_c_get_token_info)},
842
            {STRING_AND_FUNCTION(test_c_wait_for_slot_event)},
843
            {STRING_AND_FUNCTION(test_c_get_mechanism_list)},
844
            {STRING_AND_FUNCTION(test_c_get_mechanism_info)},
845
            {STRING_AND_FUNCTION(test_open_close_session)},
846
            {STRING_AND_FUNCTION(test_c_close_all_sessions)},
847
            {STRING_AND_FUNCTION(test_c_get_session_info)},
848
            {STRING_AND_FUNCTION(test_c_init_token)},
849
            {STRING_AND_FUNCTION(test_c_login_logout_security_officier)}, /* only possible if token is initialized */
850
            {STRING_AND_FUNCTION(test_c_init_pin)},
851
            {STRING_AND_FUNCTION(
852
               test_c_login_logout_user)}, /* only possible if token is initialized and user pin is set */
853
            {STRING_AND_FUNCTION(test_c_set_pin)},
854
            {STRING_AND_FUNCTION(test_c_create_object_c_destroy_object)},
855
            {STRING_AND_FUNCTION(test_c_get_object_size)},
856
            {STRING_AND_FUNCTION(test_c_get_attribute_value)},
857
            {STRING_AND_FUNCTION(test_c_set_attribute_value)},
858
            {STRING_AND_FUNCTION(test_c_copy_object)}};
24✔
859

860
         return run_pkcs11_tests("PKCS11 low level", fns);
2✔
861
      }
1✔
862
};
863

864
BOTAN_REGISTER_SERIALIZED_TEST("pkcs11", "pkcs11-lowlevel", LowLevelTests);
865

866
   #endif
867
#endif
868

869
}  // namespace
870
}  // 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

© 2025 Coveralls, Inc