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

randombit / botan / 12805544433

16 Jan 2025 09:08AM UTC coverage: 90.876% (-0.4%) from 91.245%
12805544433

Pull #4540

github

web-flow
Merge cc1ceff51 into 9b798efbb
Pull Request #4540: PKCS #11 Version 3.2 Support

93425 of 102805 relevant lines covered (90.88%)

11409241.89 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_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
      FunctionList* 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
   FunctionList* 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;
2✔
237
}
1✔
238

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

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

252
   LowLevel p11_low_level(func_list);
1✔
253

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

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

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

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

270
   return result;
1✔
271
}
1✔
272

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

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

278
   // assumes smartcard reader is attached without card
279

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

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

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

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

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

303
   return result;
1✔
304
}
1✔
305

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

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

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

318
   return result;
2✔
319
}
1✔
320

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

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

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

333
   return result;
2✔
334
}
1✔
335

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

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

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

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

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

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

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

365
   return result;
1✔
366
}
1✔
367

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

440
   return result;
1✔
441
}
1✔
442

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

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

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

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

458
   open_two_sessions();
1✔
459

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

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

466
   // test bool return variant
467
   open_two_sessions();
1✔
468

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

472
   // test ReturnValue variant
473
   open_two_sessions();
1✔
474

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

480
   return result;
1✔
481
}
1✔
482

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

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

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

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

503
   return result;
1✔
504
}
1✔
505

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

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

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

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

530
Test::Result test_c_login_logout_security_officier() {
1✔
531
   RAII_LowLevel p11_low_level;
1✔
532

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

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

540
Test::Result test_c_login_logout_user() {
1✔
541
   RAII_LowLevel p11_low_level;
1✔
542

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

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

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

555
   return result;
1✔
556
}
1✔
557

558
Test::Result test_c_init_pin() {
1✔
559
   RAII_LowLevel p11_low_level;
1✔
560

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

565
   p11_low_level.login(UserType::SO, SO_PIN());
1✔
566

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

575
   return test_function("C_InitPIN", sec_vec_binder);
4✔
576
}
1✔
577

578
Test::Result test_c_set_pin() {
1✔
579
   RAII_LowLevel p11_low_level;
1✔
580

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

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

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

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

604
   PKCS11_BoundTestFunction set_pin_bind = get_pin_bind(PIN(), test_pin_secvec);
1✔
605
   PKCS11_BoundTestFunction revert_pin_bind = get_pin_bind(test_pin_secvec, PIN());
1✔
606

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

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

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

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

620
   PKCS11_BoundTestFunction set_so_pin_bind = get_pin_bind(SO_PIN(), test_so_pin_secvec);
1✔
621
   PKCS11_BoundTestFunction revert_so_pin_bind = get_pin_bind(test_so_pin_secvec, SO_PIN());
1✔
622

623
   result.merge(test_function("C_SetPIN", set_so_pin_bind, "C_SetPIN", revert_so_pin_bind));
2✔
624

625
   return result;
2✔
626
}
6✔
627

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

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

646
ObjectHandle create_simple_data_object(const RAII_LowLevel& p11_low_level) {
4✔
647
   ObjectHandle object_handle;
4✔
648

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

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

659
   ObjectHandle object_handle(0);
1✔
660

661
   auto dtemplate = data_template;
1✔
662

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

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

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

677
Test::Result test_c_get_object_size() {
1✔
678
   RAII_LowLevel p11_low_level;
1✔
679

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

683
   p11_low_level.login(UserType::User, PIN());
1✔
684

685
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
686
   Ulong object_size = 0;
1✔
687

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

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

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

701
   return result;
1✔
702
}
1✔
703

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

708
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
709

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

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

723
   Test::Result result = test_function("C_GetAttributeValue", bind);
2✔
724

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

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

733
   return result;
2✔
734
}
1✔
735

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

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

746
   p11_low_level.get()->C_GetAttributeValue(session_handle, object_handle, received_attributes);
2✔
747

748
   return received_attributes;
2✔
749
}
×
750

751
Test::Result test_c_set_attribute_value() {
1✔
752
   RAII_LowLevel p11_low_level;
1✔
753

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

757
   p11_low_level.login(UserType::User, PIN());
1✔
758

759
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
760

761
   std::string new_label = "A modified data object";
1✔
762

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

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

776
   Test::Result result = test_function("C_SetAttributeValue", bind);
2✔
777

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

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

785
   result.test_eq("label", new_label, retrieved_label);
1✔
786

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

790
   return result;
2✔
791
}
2✔
792

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

797
   ObjectHandle object_handle = create_simple_data_object(p11_low_level);
1✔
798
   ObjectHandle copied_object_handle = 0;
1✔
799

800
   std::string copied_label = "A copied data object";
1✔
801

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

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

815
   Test::Result result = test_function("C_CopyObject", binder);
2✔
816

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

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

824
   result.test_eq("label", copied_label, retrieved_label);
1✔
825

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

830
   return result;
2✔
831
}
1✔
832

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

842
         if(latest_interface->version().major > 3 || latest_interface->version().minor >= 2) {
×
843
            latest_interface->func_3_2();
×
844
         }
845
      }
846
   });
1✔
847
   return res;
1✔
848
}
1✔
849

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

881
         return run_pkcs11_tests("PKCS11 low level", fns);
2✔
882
      }
2✔
883
};
884

885
BOTAN_REGISTER_SERIALIZED_TEST("pkcs11", "pkcs11-lowlevel", LowLevelTests);
886

887
   #endif
888
#endif
889

890
}  // namespace
891
}  // 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