aboutsummaryrefslogtreecommitdiff
path: root/openssl/agent/pkcs11/private-key.cxx
blob: ddaf0eb9ea67fbbcb1d4af020b2cbaba96492cb9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
// file      : openssl/agent/pkcs11/private-key.cxx -*- C++ -*-
// license   : MIT; see accompanying LICENSE file

#include <openssl/agent/pkcs11/private-key.hxx>

#include <cstring> // memset(), strlen()

#include <openssl/agent/pkcs11/pkcs11.hxx>

#define API_STRING(S) api_string (S, sizeof (S))

namespace openssl
{
  namespace agent
  {
    namespace pkcs11
    {
      using namespace std;

      static void
      close_session (CK_SESSION_HANDLE* p)
      {
        if (p != nullptr)
        {
          api ()->C_CloseSession (*p);
          delete p;
        }
      }

      private_key::
      private_key (): session_ (nullptr, close_session)
      {
      }

      private_key::
      private_key (private_key&& k): private_key ()
      {
        *this = move (k);
      }

      private_key& private_key::
      operator= (private_key&& k)
      {
        description = move (k.description);
        session_    = move (k.session_);
        handle_     = k.handle_;
        simulate_   = move (k.simulate_);
        return *this;
      }

      private_key::
      private_key (const identity& idn,
                   const access& acc,
                   const char* pin,
                   optional<simulate_outcome> sim)
          : private_key ()
      {
        simulate_ = move (sim); // Can't initialize because of delegate ctor.

        // Verify the identity and access attributes.
        //
        if (idn.type && *idn.type != "private")
          throw invalid_argument ("unexpected object type " + *idn.type);

        if (pin == nullptr && acc.pin_value)
          pin = acc.pin_value->c_str ();

        if (pin == nullptr)
          throw invalid_argument ("PIN is required");

        auto no_key = [] ()
        {
          throw runtime_error ("no matching private key found");
        };

        auto simulate = [this, &no_key] ()
        {
          assert (simulate_ && session_ == nullptr);

          switch (*simulate_)
          {
          case simulate_outcome::success:
            {
              description = "simulated private key";
              return;
            }
          case simulate_outcome::failure:
            {
              no_key ();
            }
          }
        };

        // Get the Cryptoki functions pointer.
        //
        CK_FUNCTION_LIST* fs;
        {
          path p;

          if (acc.module_path)
          {
            if (acc.module_name)
              p = *acc.module_path / (*acc.module_name + ".so");
            else if (file_exists (*acc.module_path))
              p = *acc.module_path;
            else
              p = *acc.module_path / "opensc-pkcs11.so";
          }
          else if (acc.module_name)
            p = *acc.module_name + ".so";
          else
            p = path ("opensc-pkcs11.so");

          // Ignore non-existent PKCS#11 module in the simulated mode. Note
          // that if the module exists we will simulate as far as possible,
          // up to opening token sessions (but not logging into them).
          //
          fs = api (p, simulate_.has_value ());

          if (fs == nullptr)
          {
            assert (simulate_);
            simulate ();
            return;
          }
        }

        // Search for the private key.
        //
        // The overall plan is to match the PKCS#11 module, go though all the
        // matching slots it provides, log into all the matching tokens these
        // slots may contain and see if the tokens contain a matching RSA
        // private keys. Fail if unable to log into the matching tokens or
        // none or multiple private keys match. Otherwise keep both the
        // matching token session and the key handle.
        //
        auto mult_keys = [] ()
        {
          throw runtime_error ("multiple private keys match");
        };

        auto match = [] (const auto& attr, const auto& value)
        {
          return !attr || *attr == value;
        };

        // Match the module.
        //
        CK_INFO pi;
        CK_RV r (fs->C_GetInfo (&pi));

        if (r != CKR_OK)
          throw_api_error (r, "unable to obtain PKCS#11 module info");

        if (!match (idn.library_manufacturer,
                    API_STRING (pi.manufacturerID))            ||

            !match (idn.library_version,
                    library_version (pi.libraryVersion.major,
                                     pi.libraryVersion.minor)) ||

            !match (idn.library_description,
                    API_STRING (pi.libraryDescription)))
          no_key ();

        // Traverse through slots.
        //
        // In the PKCS#11 terminology a slot is something that may have token
        // be inserted into it. Not to be confused with Yubikey's 9a, 9c, etc
        // slots.
        //
        // Note that a set of slots is checked at the time when
        // C_GetSlotList() is called to obtain slots count (pSlotList argument
        // is NULL and the tokenPresent argument is false).
        //
        CK_ULONG nslots;
        r = fs->C_GetSlotList (false /* tokenPresent */,
                               nullptr /* pSlotList */,
                               &nslots);

        if (r != CKR_OK)
          throw_api_error (r, "unable to obtain slots count");

        vector<CK_SLOT_ID> slot_ids (nslots);
        r = fs->C_GetSlotList (false /* tokenPresent */,
                               slot_ids.data (),
                               &nslots);

        if (r != CKR_OK)
          throw_api_error (r, "unable to obtain slot ids");

        for (CK_SLOT_ID sid: slot_ids)
        {
          // Match the slot information.
          //
          if (!match (idn.slot_id, sid))
            continue;

          CK_SLOT_INFO si;
          r = fs->C_GetSlotInfo (sid, &si);

          if (r != CKR_OK)
            throw_api_error (
              r, "unable to obtain slot " + to_string (sid) + " info");

          if ((si.flags & CKF_TOKEN_PRESENT) == 0                            ||
              !match (idn.slot_manufacturer, API_STRING (si.manufacturerID)) ||
              !match (idn.slot_description, API_STRING (si.slotDescription)))
            continue;

          auto slot_desc = [&sid, &si] ()
          {
            string d (API_STRING (si.slotDescription));
            return "slot " + to_string (sid) + " (" +
                   (!d.empty () ? d : API_STRING (si.manufacturerID)) + ")";
          };

          // Match the token information.
          //
          CK_TOKEN_INFO ti;
          r = fs->C_GetTokenInfo (sid, &ti);

          if (r == CKR_TOKEN_NOT_PRESENT || r == CKR_TOKEN_NOT_RECOGNIZED)
            continue;

          if (r != CKR_OK)
            throw_api_error (
              r, "unable to obtain token info for " + slot_desc ());

          if ((ti.flags & CKF_TOKEN_INITIALIZED)             == 0 ||
              (ti.flags & CKF_USER_PIN_INITIALIZED)          == 0 ||
              (ti.flags & CKF_LOGIN_REQUIRED)                == 0 ||
              (ti.flags & CKF_PROTECTED_AUTHENTICATION_PATH) != 0 || // Pinpad?

              !match (idn.serial,       API_STRING (ti.serialNumber))  ||
              !match (idn.token,        API_STRING (ti.label))         ||
              !match (idn.model,        API_STRING (ti.model))         ||
              !match (idn.manufacturer, API_STRING (ti.manufacturerID)))
            continue;

          auto token_desc = [&ti] ()
          {
            string r ("token ");
            string l (API_STRING (ti.label));

            r += !l.empty ()
            ? "'" + l + "'"
            : "'" + API_STRING (ti.model) + "' by " +
              API_STRING (ti.manufacturerID);

            return r;
          };

          // Search for the matching RSA private key in the token.
          //
          // Open the read-only session with the token. Note that we can't see
          // private objects until login.
          //
          CK_SESSION_HANDLE sh;
          r = fs->C_OpenSession (sid,
                                 CKF_SERIAL_SESSION,
                                 nullptr /* pApplication */,
                                 nullptr /* Notify */,
                                 &sh);

          if (r == CKR_DEVICE_REMOVED    ||
              r == CKR_TOKEN_NOT_PRESENT ||
              r == CKR_TOKEN_NOT_RECOGNIZED)
            continue;

          if (r != CKR_OK)
            throw_api_error (
              r, "unable to open session with " + token_desc ());

          session_ptr session (new CK_SESSION_HANDLE (sh), close_session);

          // Log into the token unless simulating.
          //
          if (simulate_)
            continue;

          // Note that all sessions with a token share login, so need to login
          // once per all token sessions.
          //
          // Also note that there is no need to logout explicitly if you want
          // to keep all token sessions logged in during their lifetime.
          //
          r = fs->C_Login (
            *session,
            CKU_USER,
            reinterpret_cast<unsigned char*> (const_cast<char*> (pin)),
            strlen (pin));

          // We can fail because of the wrong PIN or trying to apply the PIN
          // to a wrong token. Should we just skip the token if that's the
          // case? Probably we should throw. Otherwise who knows how many pins
          // we will reset going forward.
          //
          if (r != CKR_USER_ALREADY_LOGGED_IN && r != CKR_OK)
            throw_api_error (r, "unable to login to " + token_desc ());

          // Search for the private key.
          //
          // Fill the search attributes.
          //
          CK_OBJECT_CLASS oc (CKO_PRIVATE_KEY);
          CK_KEY_TYPE     kt (CKK_RSA);

          vector<CK_ATTRIBUTE> sa ({{CKA_CLASS,    &oc, sizeof (oc)},
                                    {CKA_KEY_TYPE, &kt, sizeof (kt)}});
          if (idn.id)
            sa.push_back (
              CK_ATTRIBUTE {CKA_ID,
                  const_cast<unsigned char*> (idn.id->data ()),
                  idn.id->size ()});

          if (idn.object)
            sa.push_back (CK_ATTRIBUTE {CKA_LABEL,
                  const_cast<char*> (idn.object->c_str ()),
                  idn.object->size ()});

          // Initialize the search.
          //
          r = fs->C_FindObjectsInit (*session, sa.data (), sa.size ());

          if (r != CKR_OK)
            throw_api_error (
              r, "unable to enumerate private keys in " + token_desc ());

          // Finally, search for the key.
          //
          // Note that we will query 2 keys to handle the 'multiple keys
          // match' case.
          //
          CK_OBJECT_HANDLE key (0);
          {
            session_ptr search_deleter (
              session.get (),
              [] (CK_SESSION_HANDLE* p) {api ()->C_FindObjectsFinal (*p);});

            CK_ULONG n;
            CK_OBJECT_HANDLE keys[2];
            r = fs->C_FindObjects (*session,
                                   keys,
                                   2 /* ulMaxObjectCount */,
                                   &n);

            if (r != CKR_OK)
              throw_api_error (
                r,
                "unable to obtain private key handles from " + token_desc ());

            if (n == 1)
              key = keys[0]; // Exactly one key matches.
            else if (n == 0)
              continue;      // No key matches.
            else
              mult_keys ();  // Multiple keys match.
          }

          if (session_ != nullptr)
            mult_keys ();

          // Produce description for the found key.
          //
          description = "private key ";
          {
            CK_ATTRIBUTE attr {CKA_LABEL, nullptr, 0};
            r = fs->C_GetAttributeValue (*session,
                                         key,
                                         &attr,
                                         1 /* ulCount */);

            if (r == CKR_OK && attr.ulValueLen != 0)
            {
              vector<char> label (attr.ulValueLen);
              attr.pValue = label.data ();

              r = fs->C_GetAttributeValue (*session,
                                           key,
                                           &attr,
                                           1 /* ulCount */);
              if (r == CKR_OK)
                description += "'" + string (label.data (), label.size ()) +
                               "' ";
            }
          }

          description += "in " + token_desc ();

          // Note that for Yubikey 4 we cannot rely on the key's
          // CKA_ALWAYS_AUTHENTICATE attribute value for detecting if
          // authentication is required for the sign operation. For the
          // private key imported into the 9c (SIGN key) slot with the
          // --pin-policy=never option the sign operation doesn't require
          // authentication but the CKA_ALWAYS_AUTHENTICATE value is still on.
          // This seems to be some yubico-piv-tool issue (or deliberate
          // behavior) as for the 9a (PIV AUTH key) slot the sign
          // authentication is not required and the CKA_ALWAYS_AUTHENTICATE
          // value is off. This issue makes it impossible to evaluate if the
          // key requires sign authentication before the sign attempt. This is
          // probably not a big deal as, if we want, we can always check this
          // using some dummy data.
          //
#if 0
          CK_BBOOL always_auth (CK_FALSE);

          CK_ATTRIBUTE attr {
            CKA_ALWAYS_AUTHENTICATE, &always_auth, sizeof (always_auth)};

          r = fs->C_GetAttributeValue (*session,
                                       key,
                                       &attr,
                                       1 /* ulCount */);

          if (r != CKR_OK)
            throw_api_error (
              r,
              "unable to obtain 'always auth' attribute for " + description);
#endif

          // Despite the fact that the key is found we will continue to iterate
          // over slots to make sure that a single key matches the identity
          // attributes.
          //
          session_ = move (session);
          handle_ = key;
        }

        if (simulate_)
          simulate ();
        else if (session_ == nullptr)
          no_key ();
      }

      vector<char> private_key::
      sign (const vector<char>& data, const optional<simulate_outcome>& sim)
      {
        assert (!empty ());

        if (sim && *sim == simulate_outcome::failure)
          throw runtime_error ("unable to sign using " + description);

        if (sim || simulate_)
        {
          // Otherwise would fail in the private_key constructor.
          //
          assert (!simulate_ || *simulate_ == simulate_outcome::success);

          return vector<char> ({
              's', 'i', 'g', 'n', 'a', 't', 'u', 'r', 'e', '\n'});
        }

        CK_FUNCTION_LIST* fs (api ());

        CK_MECHANISM mech;
        memset (&mech, 0, sizeof (mech));
        mech.mechanism = CKM_RSA_PKCS;

        CK_RV r (fs->C_SignInit (*session_, &mech, handle_));

        if (r != CKR_OK)
          throw_api_error (
            r, "unable to init sign operation using " + description);

        for (vector<char> signature; true; signature_size_ *= 2)
        {
          signature.resize (signature_size_);

          CK_ULONG n (signature_size_);

          r = fs->C_Sign (*session_,
                          reinterpret_cast<unsigned char*> (
                            const_cast<char*> (data.data ())),
                          data.size (),
                          reinterpret_cast<unsigned char*> (
                            signature.data ()),
                          &n);

          if (r == CKR_BUFFER_TOO_SMALL)
            continue;

          if (r != CKR_OK)
            throw_api_error (r, "unable to sign using " + description);

          assert (n != 0 && n <= signature_size_);

          signature.resize (n);
          return signature;
        }
      }
    }
  }
}