This repository has been archived by the owner on Oct 15, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
session_impl.cc
1391 lines (1322 loc) · 48 KB
/
session_impl.cc
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "session_impl.h"
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include <iostream>
#include <base/logging.h>
#include <brillo/secure_blob.h>
#include <openssl/bio.h>
#include <openssl/des.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include "p11net.h"
#include "p11net_factory.h"
#include "p11net_utility.h"
#include "object.h"
#include "object_pool.h"
#include "object_store.h"
#include "pkcs11/cryptoki.h"
using brillo::SecureBlob;
using std::hex;
using std::map;
using std::set;
using std::string;
using std::vector;
namespace p11net {
//static const int kDefaultAuthDataBytes = 20;
static const int kMaxCipherBlockBytes = 16;
static const int kMaxRSAOutputBytes = 2048;
static const int kMaxDigestOutputBytes = EVP_MAX_MD_SIZE;
static const int kMinRSAKeyBits = 512;
//static const int kMaxRSAKeyBitsHW = 2048; // Max supported by the TPM.
static const int kMaxRSAKeyBitsSW = kMaxRSAOutputBytes * 8;
SessionImpl::SessionImpl(int slot_id,
std::shared_ptr<ObjectPool> token_object_pool,
std::shared_ptr<NetUtility> net_utility,
std::shared_ptr<P11NetFactory> factory,
std::shared_ptr<HandleGenerator> handle_generator,
bool is_read_only)
: factory_(factory),
find_results_valid_(false),
is_read_only_(is_read_only),
slot_id_(slot_id),
token_object_pool_(token_object_pool),
net_utility_(net_utility),
is_legacy_loaded_(false),
private_root_key_(0),
public_root_key_(0) {
CHECK(token_object_pool_);
CHECK(net_utility_);
CHECK(factory_);
session_object_pool_.reset(
factory_->CreateObjectPool(handle_generator,
std::unique_ptr<ObjectStore>()));
CHECK(session_object_pool_.get());
}
SessionImpl::~SessionImpl() {
}
int SessionImpl::GetSlot() const {
return slot_id_;
}
CK_STATE SessionImpl::GetState() const {
return is_read_only_ ? CKS_RO_USER_FUNCTIONS : CKS_RW_USER_FUNCTIONS;
}
bool SessionImpl::IsReadOnly() const {
return is_read_only_;
}
bool SessionImpl::IsOperationActive(OperationType type) const {
CHECK(type < kNumOperationTypes);
return operation_context_[type].is_valid_;
}
CK_RV SessionImpl::CreateObject(const CK_ATTRIBUTE_PTR attributes,
int num_attributes,
int* new_object_handle) {
return CreateObjectInternal(attributes,
num_attributes,
NULL,
new_object_handle);
}
CK_RV SessionImpl::CopyObject(const CK_ATTRIBUTE_PTR attributes,
int num_attributes,
int object_handle,
int* new_object_handle) {
const Object* orig_object = NULL;
if (!GetObject(object_handle, &orig_object))
return CKR_OBJECT_HANDLE_INVALID;
CHECK(orig_object);
return CreateObjectInternal(attributes,
num_attributes,
orig_object,
new_object_handle);
}
CK_RV SessionImpl::DestroyObject(int object_handle) {
const Object* object = NULL;
if (!GetObject(object_handle, &object))
return CKR_OBJECT_HANDLE_INVALID;
CHECK(object);
std::shared_ptr<ObjectPool> pool = object->IsTokenObject() ? token_object_pool_
: session_object_pool_;
if (!pool->Delete(object))
return CKR_GENERAL_ERROR;
return CKR_OK;
}
bool SessionImpl::GetObject(int object_handle, const Object** object) {
CHECK(object);
if (token_object_pool_->FindByHandle(object_handle, object))
return true;
return session_object_pool_->FindByHandle(object_handle, object);
}
bool SessionImpl::GetModifiableObject(int object_handle, Object** object) {
CHECK(object);
const Object* const_object;
if (!GetObject(object_handle, &const_object))
return false;
std::shared_ptr<ObjectPool> pool = const_object->IsTokenObject() ? token_object_pool_
: session_object_pool_;
*object = pool->GetModifiableObject(const_object);
return true;
}
bool SessionImpl::FlushModifiableObject(Object* object) {
CHECK(object);
std::shared_ptr<ObjectPool> pool = object->IsTokenObject() ? token_object_pool_
: session_object_pool_;
return pool->Flush(object);
}
CK_RV SessionImpl::FindObjectsInit(const CK_ATTRIBUTE_PTR attributes,
int num_attributes) {
if (find_results_valid_)
return CKR_OPERATION_ACTIVE;
std::unique_ptr<Object> search_template(factory_->CreateObject());
CHECK(search_template.get());
search_template->SetAttributes(attributes, num_attributes);
std::string key_id;
if (search_template->IsAttributePresent(CKA_ID)) {
key_id = search_template->GetAttributeString(CKA_ID);
VLOG(1) << "CKA_ID is set: " << key_id;
}
net_utility_->LoadKeys(key_id);
vector<const Object*> objects;
if (!search_template->IsAttributePresent(CKA_TOKEN) ||
search_template->IsTokenObject()) {
if (!token_object_pool_->Find(search_template.get(), &objects))
return CKR_GENERAL_ERROR;
}
if (!search_template->IsAttributePresent(CKA_TOKEN) ||
!search_template->IsTokenObject()) {
if (!session_object_pool_->Find(search_template.get(), &objects))
return CKR_GENERAL_ERROR;
}
find_results_.clear();
find_results_offset_ = 0;
find_results_valid_ = true;
for (size_t i = 0; i < objects.size(); ++i) {
find_results_.push_back(objects[i]->handle());
}
return CKR_OK;
}
CK_RV SessionImpl::FindObjects(int max_object_count,
vector<int>* object_handles) {
CHECK(object_handles);
if (!find_results_valid_)
return CKR_OPERATION_NOT_INITIALIZED;
size_t end_offset = find_results_offset_ +
static_cast<size_t>(max_object_count);
if (end_offset > find_results_.size())
end_offset = find_results_.size();
for (size_t i = find_results_offset_; i < end_offset; ++i) {
object_handles->push_back(find_results_[i]);
}
find_results_offset_ += object_handles->size();
return CKR_OK;
}
CK_RV SessionImpl::FindObjectsFinal() {
if (!find_results_valid_)
return CKR_OPERATION_NOT_INITIALIZED;
find_results_valid_ = false;
return CKR_OK;
}
CK_RV SessionImpl::OperationInit(OperationType operation,
CK_MECHANISM_TYPE mechanism,
const string& mechanism_parameter,
const Object* key) {
CHECK(operation < kNumOperationTypes);
OperationContext* context = &operation_context_[operation];
if (context->is_valid_) {
LOG(ERROR) << "Operation is already active.";
return CKR_OPERATION_ACTIVE;
}
context->Clear();
context->mechanism_ = mechanism;
context->parameter_ = mechanism_parameter;
if (!IsValidMechanism(operation, mechanism)) {
LOG(ERROR) << "Mechanism not supported: 0x" << hex << mechanism;
return CKR_MECHANISM_INVALID;
}
if (operation != kDigest) {
// Make sure the key is valid for the mechanism.
CHECK(key);
if (!IsValidKeyType(operation,
mechanism,
key->GetObjectClass(),
key->GetAttributeInt(CKA_KEY_TYPE, -1))) {
LOG(ERROR) << "Key type mismatch.";
return CKR_KEY_TYPE_INCONSISTENT;
}
if (!key->GetAttributeBool(GetRequiredKeyUsage(operation), false)) {
LOG(ERROR) << "Key function not permitted.";
return CKR_KEY_FUNCTION_NOT_PERMITTED;
}
if (IsRSA(mechanism)) {
int key_size = key->GetAttributeString(CKA_MODULUS).length() * 8;
if (key_size < kMinRSAKeyBits || key_size > kMaxRSAKeyBitsSW) {
LOG(ERROR) << "Key size not supported: " << key_size;
return CKR_KEY_SIZE_RANGE;
}
}
}
if (operation == kEncrypt || operation == kDecrypt) {
if (mechanism == CKM_RSA_PKCS) {
context->key_ = key;
context->is_valid_ = true;
} else {
return CipherInit((operation == kEncrypt),
mechanism,
mechanism_parameter,
key);
}
} else {
// It is valid for GetOpenSSLDigest to return NULL (e.g. CKM_RSA_PKCS).
const EVP_MD* digest = GetOpenSSLDigest(mechanism);
if (IsHMAC(mechanism)) {
string key_material = key->GetAttributeString(CKA_VALUE);
HMAC_CTX_init(&context->hmac_context_);
HMAC_Init_ex(&context->hmac_context_,
key_material.data(),
key_material.length(),
digest,
NULL);
context->is_hmac_ = true;
} else if (digest) {
EVP_DigestInit(&context->digest_context_, digest);
context->is_digest_ = true;
}
if (IsRSA(mechanism))
context->key_ = key;
context->is_valid_ = true;
}
return CKR_OK;
}
CK_RV SessionImpl::OperationUpdate(OperationType operation,
const string& data_in,
int* required_out_length,
string* data_out) {
CHECK(operation < kNumOperationTypes);
OperationContext* context = &operation_context_[operation];
if (!context->is_valid_) {
LOG(ERROR) << "Operation is not initialized.";
return CKR_OPERATION_NOT_INITIALIZED;
}
if (context->is_finished_) {
LOG(ERROR) << "Operation is finished.";
OperationCancel(operation);
return CKR_OPERATION_ACTIVE;
}
context->is_incremental_ = true;
return OperationUpdateInternal(operation,
data_in,
required_out_length,
data_out);
}
CK_RV SessionImpl::OperationUpdateInternal(OperationType operation,
const string& data_in,
int* required_out_length,
string* data_out) {
CHECK(operation < kNumOperationTypes);
OperationContext* context = &operation_context_[operation];
if (context->is_cipher_) {
CK_RV rv = CipherUpdate(context, data_in, required_out_length, data_out);
if ((rv != CKR_OK) && (rv != CKR_BUFFER_TOO_SMALL))
OperationCancel(operation);
return rv;
} else if (context->is_digest_) {
EVP_DigestUpdate(&context->digest_context_,
data_in.data(),
data_in.length());
} else if (context->is_hmac_) {
HMAC_Update(&context->hmac_context_,
ConvertStringToByteBuffer(data_in.c_str()),
data_in.length());
} else {
// We don't need to process now; just queue the data.
context->data_ += data_in;
}
if (required_out_length)
*required_out_length = 0;
return CKR_OK;
}
void SessionImpl::OperationCancel(OperationType operation) {
CHECK(operation < kNumOperationTypes);
OperationContext* context = &operation_context_[operation];
if (!context->is_valid_) {
LOG(ERROR) << "Operation is not initialized.";
return;
}
// Drop the context and any associated data.
context->Clear();
}
CK_RV SessionImpl::OperationFinal(OperationType operation,
int* required_out_length,
string* data_out) {
CHECK(required_out_length);
CHECK(data_out);
CHECK(operation < kNumOperationTypes);
OperationContext* context = &operation_context_[operation];
if (!context->is_valid_) {
LOG(ERROR) << "Operation is not initialized.";
return CKR_OPERATION_NOT_INITIALIZED;
}
if (!context->is_incremental_ && context->is_finished_) {
LOG(ERROR) << "Operation is not incremental.";
OperationCancel(operation);
return CKR_OPERATION_ACTIVE;
}
context->is_incremental_ = true;
return OperationFinalInternal(operation, required_out_length, data_out);
}
CK_RV SessionImpl::OperationFinalInternal(OperationType operation,
int* required_out_length,
string* data_out) {
CHECK(operation < kNumOperationTypes);
OperationContext* context = &operation_context_[operation];
context->is_valid_ = false;
// Complete the operation if it has not already been done.
if (!context->is_finished_) {
if (context->is_cipher_) {
CK_RV result = CipherFinal(context);
if (result != CKR_OK)
return result;
} else if (context->is_digest_) {
unsigned char buffer[kMaxDigestOutputBytes];
unsigned int out_length = 0;
EVP_DigestFinal(&context->digest_context_, buffer, &out_length);
context->data_ = string(reinterpret_cast<char*>(buffer), out_length);
} else if (context->is_hmac_) {
unsigned char buffer[kMaxDigestOutputBytes];
unsigned int out_length = 0;
HMAC_Final(&context->hmac_context_, buffer, &out_length);
HMAC_CTX_cleanup(&context->hmac_context_);
context->data_ = string(reinterpret_cast<char*>(buffer), out_length);
}
// Some RSA mechanisms use a digest so it's important to finish the digest
// before finishing the RSA computation.
if (IsRSA(context->mechanism_)) {
if (operation == kEncrypt) {
if (!RSAEncrypt(context))
return CKR_FUNCTION_FAILED;
} else if (operation == kDecrypt) {
if (!RSADecrypt(context))
return CKR_FUNCTION_FAILED;
} else if (operation == kSign) {
if (!RSASign(context))
return CKR_FUNCTION_FAILED;
}
}
context->is_finished_ = true;
}
CK_RV result = GetOperationOutput(context,
required_out_length,
data_out);
if (result == CKR_BUFFER_TOO_SMALL) {
// We'll keep the context valid so a subsequent call can pick up the data.
context->is_valid_ = true;
}
return result;
}
CK_RV SessionImpl::VerifyFinal(const string& signature) {
OperationContext* context = &operation_context_[kVerify];
// Call the generic OperationFinal so any digest or HMAC computation gets
// finalized.
int max_out_length = std::numeric_limits<int>::max();
string data_out;
CK_RV result = OperationFinal(kVerify, &max_out_length, &data_out);
if (result != CKR_OK)
return result;
// We only support two Verify mechanisms, HMAC and RSA.
if (context->is_hmac_) {
// The data_out contents will be the computed HMAC. To verify an HMAC, it is
// recomputed and literally compared.
if (signature.length() != data_out.length())
return CKR_SIGNATURE_LEN_RANGE;
if (0 != brillo::SecureMemcmp(signature.data(),
data_out.data(),
signature.length()))
return CKR_SIGNATURE_INVALID;
} else {
// The data_out contents will be the computed digest.
return RSAVerify(context, data_out, signature);
}
return CKR_OK;
}
CK_RV SessionImpl::OperationSinglePart(OperationType operation,
const string& data_in,
int* required_out_length,
string* data_out) {
CHECK(operation < kNumOperationTypes);
OperationContext* context = &operation_context_[operation];
if (!context->is_valid_) {
LOG(ERROR) << "Operation is not initialized.";
return CKR_OPERATION_NOT_INITIALIZED;
}
if (context->is_incremental_) {
LOG(ERROR) << "Operation is incremental.";
OperationCancel(operation);
return CKR_OPERATION_ACTIVE;
}
CK_RV result = CKR_OK;
if (!context->is_finished_) {
string update, final;
int max = std::numeric_limits<int>::max();
result = OperationUpdateInternal(operation, data_in, &max, &update);
if (result != CKR_OK)
return result;
max = std::numeric_limits<int>::max();
result = OperationFinalInternal(operation, &max, &final);
if (result != CKR_OK)
return result;
context->data_ = update + final;
context->is_finished_ = true;
}
context->is_valid_ = false;
result = GetOperationOutput(context,
required_out_length,
data_out);
if (result == CKR_BUFFER_TOO_SMALL) {
// We'll keep the context valid so a subsequent call can pick up the data.
context->is_valid_ = true;
}
return result;
}
CK_RV SessionImpl::GenerateKey(CK_MECHANISM_TYPE mechanism,
const string& mechanism_parameter,
const CK_ATTRIBUTE_PTR attributes,
int num_attributes,
int* new_key_handle) {
CHECK(new_key_handle);
std::unique_ptr<Object> object(factory_->CreateObject());
CHECK(object.get());
CK_RV result = object->SetAttributes(attributes, num_attributes);
if (result != CKR_OK)
return result;
CK_KEY_TYPE key_type = 0;
string key_material;
switch (mechanism) {
case CKM_DES_KEY_GEN: {
key_type = CKK_DES;
if (!GenerateDESKey(&key_material))
return CKR_FUNCTION_FAILED;
break;
}
case CKM_DES3_KEY_GEN: {
key_type = CKK_DES3;
string des[3];
for (int i = 0; i < 3; ++i) {
if (!GenerateDESKey(&des[i]))
return CKR_FUNCTION_FAILED;
}
key_material = des[0] + des[1] + des[2];
break;
}
case CKM_AES_KEY_GEN: {
key_type = CKK_AES;
if (!object->IsAttributePresent(CKA_VALUE_LEN))
return CKR_TEMPLATE_INCOMPLETE;
int key_length = object->GetAttributeInt(CKA_VALUE_LEN, 0);
if (key_length != 16 && key_length != 24 && key_length != 32)
return CKR_KEY_SIZE_RANGE;
key_material = GenerateRandomSoftware(key_length);
break;
}
case CKM_GENERIC_SECRET_KEY_GEN: {
key_type = CKK_GENERIC_SECRET;
if (!object->IsAttributePresent(CKA_VALUE_LEN))
return CKR_TEMPLATE_INCOMPLETE;
int key_length = object->GetAttributeInt(CKA_VALUE_LEN, 0);
if (key_length < 1)
return CKR_KEY_SIZE_RANGE;
key_material = GenerateRandomSoftware(key_length);
break;
}
default: {
LOG(ERROR) << "GenerateKey: Mechanism not supported: " << hex
<< mechanism;
return CKR_MECHANISM_INVALID;
}
}
object->SetAttributeInt(CKA_CLASS, CKO_SECRET_KEY);
object->SetAttributeInt(CKA_KEY_TYPE, key_type);
object->SetAttributeString(CKA_VALUE, key_material);
object->SetAttributeBool(CKA_LOCAL, true);
object->SetAttributeInt(CKA_KEY_GEN_MECHANISM, mechanism);
result = object->FinalizeNewObject();
if (result != CKR_OK)
return result;
std::shared_ptr<ObjectPool> pool = object->IsTokenObject() ? token_object_pool_
: session_object_pool_;
if (!pool->Insert(object.get()))
return CKR_FUNCTION_FAILED;
*new_key_handle = object.release()->handle();
return CKR_OK;
}
CK_RV SessionImpl::GenerateKeyPair(CK_MECHANISM_TYPE mechanism,
const string& mechanism_parameter,
const CK_ATTRIBUTE_PTR public_attributes,
int num_public_attributes,
const CK_ATTRIBUTE_PTR private_attributes,
int num_private_attributes,
int* new_public_key_handle,
int* new_private_key_handle) {
CHECK(new_public_key_handle);
CHECK(new_private_key_handle);
if (mechanism != CKM_RSA_PKCS_KEY_PAIR_GEN) {
LOG(ERROR) << "GenerateKeyPair: Mechanism not supported: " << hex
<< mechanism;
return CKR_MECHANISM_INVALID;
}
std::unique_ptr<Object> public_object(factory_->CreateObject());
CHECK(public_object.get());
std::unique_ptr<Object> private_object(factory_->CreateObject());
CHECK(private_object.get());
CK_RV result = public_object->SetAttributes(public_attributes,
num_public_attributes);
if (result != CKR_OK)
return result;
result = private_object->SetAttributes(private_attributes,
num_private_attributes);
if (result != CKR_OK)
return result;
// CKA_PUBLIC_EXPONENT is optional. The default is 65537 (0x10001).
string public_exponent("\x01\x00\x01", 3);
if (public_object->IsAttributePresent(CKA_PUBLIC_EXPONENT))
public_exponent = public_object->GetAttributeString(CKA_PUBLIC_EXPONENT);
public_object->SetAttributeString(CKA_PUBLIC_EXPONENT, public_exponent);
private_object->SetAttributeString(CKA_PUBLIC_EXPONENT, public_exponent);
if (!public_object->IsAttributePresent(CKA_MODULUS_BITS))
return CKR_TEMPLATE_INCOMPLETE;
int modulus_bits = public_object->GetAttributeInt(CKA_MODULUS_BITS, 0);
if (modulus_bits < kMinRSAKeyBits || modulus_bits > kMaxRSAKeyBitsSW)
return CKR_KEY_SIZE_RANGE;
std::shared_ptr<ObjectPool> public_pool = (public_object->IsTokenObject() ?
token_object_pool_ : session_object_pool_);
std::shared_ptr<ObjectPool> private_pool = (private_object->IsTokenObject() ?
token_object_pool_ : session_object_pool_);
// Check if we are able to back this key with the TPM.
// if (tpm_utility_ && tpm_utility_->IsTPMAvailable() &&
// private_object->IsTokenObject() &&
// modulus_bits <= kMaxRSAKeyBitsHW) {
// string auth_data = GenerateRandomSoftware(kDefaultAuthDataBytes);
// string key_blob;
// int tpm_key_handle;
// if (!tpm_utility_->GenerateKey(slot_id_,
// modulus_bits,
// public_exponent,
// SecureBlob(auth_data.begin(),
// auth_data.end()),
// &key_blob,
// &tpm_key_handle))
// return CKR_FUNCTION_FAILED;
// string modulus;
// if (!tpm_utility_->GetPublicKey(tpm_key_handle, &public_exponent, &modulus))
// return CKR_FUNCTION_FAILED;
// public_object->SetAttributeString(CKA_MODULUS, modulus);
// private_object->SetAttributeString(CKA_MODULUS, modulus);
// private_object->SetAttributeString(kAuthDataAttribute, auth_data);
// private_object->SetAttributeString(kKeyBlobAttribute, key_blob);
// } else {
if (!GenerateKeyPairSoftware(modulus_bits,
public_exponent,
public_object.get(),
private_object.get()))
return CKR_FUNCTION_FAILED;
// }
public_object->SetAttributeInt(CKA_CLASS, CKO_PUBLIC_KEY);
public_object->SetAttributeInt(CKA_KEY_TYPE, CKK_RSA);
private_object->SetAttributeInt(CKA_CLASS, CKO_PRIVATE_KEY);
private_object->SetAttributeInt(CKA_KEY_TYPE, CKK_RSA);
public_object->SetAttributeBool(CKA_LOCAL, true);
private_object->SetAttributeBool(CKA_LOCAL, true);
public_object->SetAttributeInt(CKA_KEY_GEN_MECHANISM, mechanism);
private_object->SetAttributeInt(CKA_KEY_GEN_MECHANISM, mechanism);
result = public_object->FinalizeNewObject();
if (result != CKR_OK)
return result;
result = private_object->FinalizeNewObject();
if (result != CKR_OK)
return result;
if (!public_pool->Insert(public_object.get()))
return CKR_FUNCTION_FAILED;
if (!private_pool->Insert(private_object.get())) {
public_pool->Delete(public_object.release());
return CKR_FUNCTION_FAILED;
}
*new_public_key_handle = public_object.release()->handle();
*new_private_key_handle = private_object.release()->handle();
return CKR_OK;
}
CK_RV SessionImpl::SeedRandom(const string& seed) {
RAND_seed(seed.data(), seed.length());
return CKR_OK;
}
CK_RV SessionImpl::GenerateRandom(int num_bytes, string* random_data) {
*random_data = GenerateRandomSoftware(num_bytes);
return CKR_OK;
}
void SessionImpl::WaitForPrivateObjects() {
std::unique_ptr<Object> all_private(factory_->CreateObject());
CHECK(all_private.get());
all_private->SetAttributeBool(CKA_PRIVATE, true);
vector<const Object*> found;
token_object_pool_->Find(all_private.get(), &found);
}
bool SessionImpl::IsValidKeyType(OperationType operation,
CK_MECHANISM_TYPE mechanism,
CK_OBJECT_CLASS object_class,
CK_KEY_TYPE key_type) {
CK_KEY_TYPE expected_key_type = 0;
CK_OBJECT_CLASS expected_class = 0;
CK_OBJECT_CLASS asymmetric_class = CKO_PUBLIC_KEY;
if (operation == kSign || operation == kDecrypt)
asymmetric_class = CKO_PRIVATE_KEY;
switch (mechanism) {
case CKM_DES_ECB:
case CKM_DES_CBC:
case CKM_DES_CBC_PAD:
expected_key_type = CKK_DES;
expected_class = CKO_SECRET_KEY;
break;
case CKM_DES3_ECB:
case CKM_DES3_CBC:
case CKM_DES3_CBC_PAD:
expected_key_type = CKK_DES3;
expected_class = CKO_SECRET_KEY;
break;
case CKM_AES_ECB:
case CKM_AES_CBC:
case CKM_AES_CBC_PAD:
expected_key_type = CKK_AES;
expected_class = CKO_SECRET_KEY;
break;
case CKM_RSA_PKCS:
case CKM_MD5_RSA_PKCS:
case CKM_SHA1_RSA_PKCS:
case CKM_SHA256_RSA_PKCS:
case CKM_SHA384_RSA_PKCS:
case CKM_SHA512_RSA_PKCS:
expected_key_type = CKK_RSA;
expected_class = asymmetric_class;
break;
case CKM_MD5_HMAC:
case CKM_SHA_1_HMAC:
case CKM_SHA256_HMAC:
case CKM_SHA384_HMAC:
case CKM_SHA512_HMAC:
expected_key_type = CKK_GENERIC_SECRET;
expected_class = CKO_SECRET_KEY;
break;
default:
return false;
}
return (key_type == expected_key_type &&
object_class == expected_class);
}
bool SessionImpl::IsValidMechanism(OperationType operation,
CK_MECHANISM_TYPE mechanism) {
if (operation == kEncrypt || operation == kDecrypt) {
switch (mechanism) {
case CKM_DES_ECB:
case CKM_DES_CBC:
case CKM_DES_CBC_PAD:
case CKM_DES3_ECB:
case CKM_DES3_CBC:
case CKM_DES3_CBC_PAD:
case CKM_AES_ECB:
case CKM_AES_CBC:
case CKM_AES_CBC_PAD:
case CKM_RSA_PKCS:
return true;
}
} else if (operation == kSign || operation == kVerify) {
switch (mechanism) {
case CKM_RSA_PKCS:
case CKM_MD5_RSA_PKCS:
case CKM_SHA1_RSA_PKCS:
case CKM_SHA256_RSA_PKCS:
case CKM_SHA384_RSA_PKCS:
case CKM_SHA512_RSA_PKCS:
case CKM_MD5_HMAC:
case CKM_SHA_1_HMAC:
case CKM_SHA256_HMAC:
case CKM_SHA384_HMAC:
case CKM_SHA512_HMAC:
return true;
}
} else {
switch (mechanism) {
case CKM_MD5:
case CKM_SHA_1:
case CKM_SHA256:
case CKM_SHA384:
case CKM_SHA512:
return true;
}
}
return false;
}
CK_RV SessionImpl::CipherInit(bool is_encrypt,
CK_MECHANISM_TYPE mechanism,
const string& mechanism_parameter,
const Object* key) {
OperationType operation = is_encrypt ? kEncrypt : kDecrypt;
EVP_CIPHER_CTX* context =
&operation_context_[operation].cipher_context_;
string key_material = key->GetAttributeString(CKA_VALUE);
const EVP_CIPHER* cipher_type = GetOpenSSLCipher(mechanism,
key_material.size());
if (!cipher_type) {
LOG(ERROR) << "Mechanism not supported: 0x" << hex << mechanism;
return CKR_MECHANISM_INVALID;
}
// The mechanism parameter is the IV for cipher modes which require an IV,
// otherwise it is expected to be empty.
if (static_cast<int>(mechanism_parameter.size()) !=
EVP_CIPHER_iv_length(cipher_type)) {
LOG(ERROR) << "IV length is invalid: " << mechanism_parameter.size();
return CKR_MECHANISM_PARAM_INVALID;
}
if (static_cast<int>(key_material.size()) !=
EVP_CIPHER_key_length(cipher_type)) {
LOG(ERROR) << "Key size not supported: " << key_material.size();
return CKR_KEY_SIZE_RANGE;
}
if (!EVP_CipherInit(context,
cipher_type,
ConvertStringToByteBuffer(key_material.c_str()),
ConvertStringToByteBuffer(mechanism_parameter.c_str()),
is_encrypt)) {
LOG(ERROR) << "EVP_CipherInit failed: " << GetOpenSSLError();
return CKR_FUNCTION_FAILED;
}
EVP_CIPHER_CTX_set_padding(context, IsPaddingEnabled(mechanism));
operation_context_[operation].is_valid_ = true;
operation_context_[operation].is_cipher_ = true;
return CKR_OK;
}
CK_RV SessionImpl::CipherUpdate(OperationContext* context,
const string& data_in,
int* required_out_length,
string* data_out) {
CHECK(required_out_length);
CHECK(data_out);
// If we have output already waiting, we don't need to process input.
if (context->data_.empty()) {
int in_length = data_in.length();
int out_length = in_length + kMaxCipherBlockBytes;
context->data_.resize(out_length);
if (!EVP_CipherUpdate(
&context->cipher_context_,
ConvertStringToByteBuffer(context->data_.c_str()),
&out_length,
ConvertStringToByteBuffer(data_in.c_str()),
in_length)) {
EVP_CIPHER_CTX_cleanup(&context->cipher_context_);
context->is_valid_ = false;
LOG(ERROR) << "EVP_CipherUpdate failed: " << GetOpenSSLError();
return CKR_FUNCTION_FAILED;
}
context->data_.resize(out_length);
}
return GetOperationOutput(context,
required_out_length,
data_out);
}
CK_RV SessionImpl::CipherFinal(OperationContext* context) {
if (context->data_.empty()) {
int out_length = kMaxCipherBlockBytes * 2;
context->data_.resize(out_length);
if (!EVP_CipherFinal(
&context->cipher_context_,
ConvertStringToByteBuffer(context->data_.c_str()),
&out_length)) {
LOG(ERROR) << "EVP_CipherFinal failed: " << GetOpenSSLError();
EVP_CIPHER_CTX_cleanup(&context->cipher_context_);
return CKR_FUNCTION_FAILED;
}
EVP_CIPHER_CTX_cleanup(&context->cipher_context_);
context->data_.resize(out_length);
}
return CKR_OK;
}
CK_RV SessionImpl::CreateObjectInternal(const CK_ATTRIBUTE_PTR attributes,
int num_attributes,
const Object* copy_from_object,
int* new_object_handle) {
CHECK(new_object_handle);
CHECK(attributes || num_attributes == 0);
std::unique_ptr<Object> object(factory_->CreateObject());
CHECK(object.get());
CK_RV result = CKR_OK;
if (copy_from_object) {
result = object->Copy(copy_from_object);
if (result != CKR_OK)
return result;
}
result = object->SetAttributes(attributes, num_attributes);
if (result != CKR_OK)
return result;
if (!copy_from_object) {
result = object->FinalizeNewObject();
if (result != CKR_OK)
return result;
}
std::shared_ptr<ObjectPool> pool = token_object_pool_;
if (object->IsTokenObject()) {
result = WrapPrivateKey(object.get());
if (result != CKR_OK)
return result;
} else {
pool = session_object_pool_;
}
if (!pool->Insert(object.get()))
return CKR_GENERAL_ERROR;
*new_object_handle = object.release()->handle();
return CKR_OK;
}
bool SessionImpl::GenerateDESKey(string* key_material) {
static const int kDESKeySizeBytes = 8;
bool done = false;
while (!done) {
string tmp = GenerateRandomSoftware(kDESKeySizeBytes);
DES_cblock des;
memcpy(&des, tmp.data(), kDESKeySizeBytes);
if (!DES_is_weak_key(&des)) {
DES_set_odd_parity(&des);
*key_material = string(reinterpret_cast<char*>(des), kDESKeySizeBytes);
done = true;
}
}
return true;
}
bool SessionImpl::GenerateKeyPairSoftware(int modulus_bits,
const string& public_exponent,
Object* public_object,
Object* private_object) {
if (public_exponent.length() > sizeof(uint32_t) ||
public_exponent.empty())
return false;
BIGNUM* e = ConvertToBIGNUM(public_exponent);
RSA* key = RSA_generate_key(modulus_bits, BN_get_word(e), NULL, NULL);
CHECK(key);
string n = ConvertFromBIGNUM(key->n);
string d = ConvertFromBIGNUM(key->d);
string p = ConvertFromBIGNUM(key->p);
string q = ConvertFromBIGNUM(key->q);
string dmp1 = ConvertFromBIGNUM(key->dmp1);
string dmq1 = ConvertFromBIGNUM(key->dmq1);
string iqmp = ConvertFromBIGNUM(key->iqmp);
public_object->SetAttributeString(CKA_MODULUS, n);
private_object->SetAttributeString(CKA_MODULUS, n);
private_object->SetAttributeString(CKA_PRIVATE_EXPONENT, d);
private_object->SetAttributeString(CKA_PRIME_1, p);
private_object->SetAttributeString(CKA_PRIME_2, q);
private_object->SetAttributeString(CKA_EXPONENT_1, dmp1);
private_object->SetAttributeString(CKA_EXPONENT_2, dmq1);
private_object->SetAttributeString(CKA_COEFFICIENT, iqmp);
RSA_free(key);
BN_free(e);
return true;
}
string SessionImpl::GenerateRandomSoftware(int num_bytes) {
string random(num_bytes, 0);
RAND_bytes(ConvertStringToByteBuffer(random.data()), num_bytes);
return random;
}
string SessionImpl::GetDERDigestInfo(CK_MECHANISM_TYPE mechanism) {
const EVP_MD* md = GetOpenSSLDigest(mechanism);
if (md == EVP_md5()) {
return GetDigestAlgorithmEncoding(DigestAlgorithm::MD5);
} else if (md == EVP_sha1()) {
return GetDigestAlgorithmEncoding(DigestAlgorithm::SHA1);
} else if (md == EVP_sha256()) {
return GetDigestAlgorithmEncoding(DigestAlgorithm::SHA256);
} else if (md == EVP_sha384()) {
return GetDigestAlgorithmEncoding(DigestAlgorithm::SHA384);
} else if (md == EVP_sha512()) {
return GetDigestAlgorithmEncoding(DigestAlgorithm::SHA512);
}
// This is valid in some cases (e.g. CKM_RSA_PKCS).
return string();
}
CK_RV SessionImpl::GetOperationOutput(OperationContext* context,
int* required_out_length,
string* data_out) {
int out_length = context->data_.length();
int max_length = *required_out_length;
*required_out_length = out_length;
if (max_length < out_length)
return CKR_BUFFER_TOO_SMALL;
*data_out = context->data_;
context->data_.clear();
return CKR_OK;
}
CK_ATTRIBUTE_TYPE SessionImpl::GetRequiredKeyUsage(OperationType operation) {
switch (operation) {
case kEncrypt:
return CKA_ENCRYPT;
case kDecrypt:
return CKA_DECRYPT;
case kSign:
return CKA_SIGN;
case kVerify:
return CKA_VERIFY;
default:
break;
}
return 0;
}
// bool SessionImpl::GetTPMKeyHandle(const Object* key, int* key_handle) {
// map<const Object*, int>::iterator it = object_tpm_handle_map_.find(key);
// if (it == object_tpm_handle_map_.end()) {
// // Only private keys are loaded into the TPM. All public key operations do
// // not use the TPM (and use OpenSSL instead).
// if (key->GetObjectClass() == CKO_PRIVATE_KEY) {
// string auth_data = key->GetAttributeString(kAuthDataAttribute);
// if (key->GetAttributeBool(kLegacyAttribute, false)) {
// // This is a legacy key and it needs to be loaded with the legacy root
// // key.
// if (!LoadLegacyRootKeys())
// return false;
// bool is_private = key->GetAttributeBool(CKA_PRIVATE, true);
// int root_key_handle = is_private ? private_root_key_ : public_root_key_;
// if (!tpm_utility_ || !tpm_utility_->LoadKeyWithParent(
// slot_id_,
// key->GetAttributeString(kKeyBlobAttribute),