-
Notifications
You must be signed in to change notification settings - Fork 128
/
qat_hw_rsa.c
1811 lines (1630 loc) · 63.3 KB
/
qat_hw_rsa.c
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
/* ====================================================================
*
*
* BSD LICENSE
*
* Copyright(c) 2016-2024 Intel Corporation.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*
* ====================================================================
*/
/*****************************************************************************
* @file qat_hw_rsa.c
*
* This file contains the engine implementations for RSA operations
*
*****************************************************************************/
/* macros defined to allow use of the cpu get and set affinity functions */
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#define __USE_GNU
#include <pthread.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include "qat_utils.h"
#include "e_qat.h"
#include "qat_hw_callback.h"
#include "qat_hw_polling.h"
#include "qat_events.h"
#ifdef ENABLE_QAT_FIPS
# include "qat_prov_cmvp.h"
#endif
#include "cpa.h"
#include "cpa_types.h"
#include "cpa_cy_rsa.h"
#include "cpa_cy_ln.h"
#include "qat_hw_rsa.h"
#include "qat_hw_asym_common.h"
#include "icp_sal_poll.h"
#include "qat_evp.h"
#include "qat_constant_time.h"
#ifdef ENABLE_QAT_SW_RSA
# include "qat_sw_rsa.h"
#endif
/* To specify the RSA op sizes supported by QAT engine */
#ifdef QAT_INSECURE_ALGO
# define RSA_QAT_RANGE_MIN 512
#else
# define RSA_QAT_RANGE_MIN 2048
#endif
#if defined(QAT20_OOT) || defined(QAT_HW_INTREE) || defined(QAT_HW_FBSD_OOT) || defined(QAT_HW_FBSD_INTREE)
# define RSA_QAT_RANGE_MAX 8192
#else
# define RSA_QAT_RANGE_MAX 4096
#endif
#define NO_PADDING 0
#define PADDING 1
#ifdef ENABLE_QAT_HW_RSA
/*
* The RSA range check is performed so that if the op sizes are not in the
* range supported by QAT engine then fall back to software
*/
static inline int qat_rsa_range_check(int plen)
{
return ((plen >= RSA_QAT_RANGE_MIN) && (plen <= RSA_QAT_RANGE_MAX));
}
static RSA *copy_rsa_public_to_private_exponent(RSA *rsa)
{
RSA *rsa_copy = NULL;
const BIGNUM *lenstra_n = NULL;
const BIGNUM *lenstra_e = NULL;
RSA_get0_key((const RSA *)rsa, &lenstra_n, &lenstra_e, NULL);
rsa_copy = RSA_new();
if (rsa_copy == NULL)
return NULL;
RSA_set0_key(rsa_copy, (BIGNUM *)lenstra_n, NULL, (BIGNUM *)lenstra_e);
return rsa_copy;
}
/******************************************************************************
* function:
* qat_rsaCallbackFn(void *pCallbackTag, CpaStatus status,
* void *pOpData, CpaFlatBuffer * pOut)
*
* @param pCallbackTag [IN] - Opaque User Data for this specific call. Will
* be returned unchanged in the callback.
* @param status [IN] - Status result of the RSA operation.
* @param pOpData [IN] - Structure containing all the data needed to
* perform the RSA encryption operation.
* @param pOut [IN] - Pointer to buffer into which the result of
* the RSA encryption is written.
* description:
* Callback function used by RSA operations to indicate completion.
* Calls back to qat_crypto_callbackFn() as functionally it does the same.
*
******************************************************************************/
static void qat_rsaCallbackFn(void *pCallbackTag, CpaStatus status, void *pOpData,
CpaFlatBuffer * pOut)
{
# ifdef QAT_BORINGSSL
CpaBufferList pBuffer;
pBuffer.pBuffers = pOut;
qat_crypto_callbackFn(pCallbackTag, status, CPA_CY_SYM_OP_CIPHER, pOpData,
&pBuffer, CPA_TRUE);
# else
if (enable_heuristic_polling) {
QAT_ATOMIC_DEC(num_asym_requests_in_flight);
}
qat_crypto_callbackFn(pCallbackTag, status, CPA_CY_SYM_OP_CIPHER, pOpData,
NULL, CPA_TRUE);
# endif /* QAT_BORINGSSL */
}
static void
rsa_decrypt_op_buf_free(CpaCyRsaDecryptOpData * dec_op_data,
CpaFlatBuffer * out_buf, int qat_svm)
{
CpaCyRsaPrivateKeyRep2 *key = NULL;
DEBUG("- Started\n");
if (dec_op_data) {
QAT_CLEANSE_MEMFREE_NONZERO_FLATBUFF(dec_op_data->inputData, qat_svm);
if (dec_op_data->pRecipientPrivateKey) {
key = &dec_op_data->pRecipientPrivateKey->privateKeyRep2;
QAT_CLEANSE_MEMFREE_NONZERO_FLATBUFF(key->prime1P, qat_svm);
QAT_CLEANSE_MEMFREE_NONZERO_FLATBUFF(key->prime2Q, qat_svm);
QAT_CLEANSE_MEMFREE_NONZERO_FLATBUFF(key->exponent1Dp, qat_svm);
QAT_CLEANSE_MEMFREE_NONZERO_FLATBUFF(key->exponent2Dq, qat_svm);
QAT_CLEANSE_MEMFREE_NONZERO_FLATBUFF(key->coefficientQInv, qat_svm);
OPENSSL_free(dec_op_data->pRecipientPrivateKey);
}
OPENSSL_free(dec_op_data);
}
if (out_buf) {
if (out_buf->pData && !qat_svm)
qaeCryptoMemFreeNonZero(out_buf->pData);
OPENSSL_free(out_buf);
}
DEBUG("- Finished\n");
}
static int qat_rsa_decrypt(CpaCyRsaDecryptOpData * dec_op_data, int rsa_len,
CpaFlatBuffer * output_buf, int * fallback, int inst_num, int qat_svm)
{
/* Used for RSA Decrypt and RSA Sign */
op_done_t op_done;
CpaStatus sts = CPA_STATUS_FAIL;
thread_local_variables_t *tlv = NULL;
# ifdef QAT_BORINGSSL
op_done_t *op_done_bssl = NULL;
# endif
int job_ret = 0;
int iMsgRetry = getQatMsgRetryCount();
useconds_t ulPollInterval = getQatPollInterval();
int qatPerformOpRetries = 0;
DEBUG("- Started\n");
tlv = qat_check_create_local_variables();
if (NULL == tlv) {
WARN("could not create local variables\n");
QATerr(QAT_F_QAT_RSA_DECRYPT, ERR_R_INTERNAL_ERROR);
return 0;
}
#if defined(QAT_BORINGSSL)
qat_init_op_done(&op_done, qat_svm);
#else
qat_init_op_done(&op_done);
#endif
if (op_done.job != NULL) {
if (qat_setup_async_event_notification(op_done.job) == 0) {
WARN("Failed to setup async event notifications\n");
QATerr(QAT_F_QAT_RSA_DECRYPT, ERR_R_INTERNAL_ERROR);
qat_cleanup_op_done(&op_done);
return 0;
}
}
# ifdef QAT_BORINGSSL
if (op_done.job != NULL) {
op_done_bssl = (op_done_t*)op_done.job->copy_op_done(&op_done,
sizeof(op_done), (void (*)(void *, void *, int))rsa_decrypt_op_buf_free);
}
# endif
STOP_RDTSC(&qat_hw_rsa_dec_req_prepare, 1, "[QAT HW RSA: prepare]");
/*
* cpaCyRsaDecrypt() is the function called for RSA Sign in the API.
* For that particular case the dec_op_data [IN] contains both the
* private key value and the message (hash) value. The output_buf [OUT]
* stores the signature as the output once the request is fully completed.
* The sts return value contains 0 (CPA_STATUS_SUCCESS) if the request
* was successfully submitted.
*/
CRYPTO_QAT_LOG("- RSA\n");
do {
START_RDTSC(&qat_hw_rsa_dec_req_submit);
if (sts == CPA_STATUS_RETRY &&
(inst_num = get_instance(QAT_INSTANCE_ASYM, qat_svm))
== QAT_INVALID_INSTANCE) {
WARN("Failed to get an instance\n");
if (qat_get_sw_fallback_enabled()) {
CRYPTO_QAT_LOG("Failed to get an instance - fallback to SW - %s\n", __func__);
*fallback = 1;
} else {
QATerr(QAT_F_QAT_RSA_DECRYPT, ERR_R_INTERNAL_ERROR);
}
# ifdef QAT_BORINGSSL
if (op_done.job != NULL)
op_done.job->free_op_done(op_done_bssl);
# endif
if (op_done.job != NULL)
qat_clear_async_event_notification(op_done.job);
qat_cleanup_op_done(&op_done);
return 0;
}
DUMP_RSA_DECRYPT(qat_instance_handles[inst_num], &op_done,
dec_op_data, output_buf);
# ifndef QAT_BORINGSSL
sts = cpaCyRsaDecrypt(qat_instance_handles[inst_num],
qat_rsaCallbackFn, &op_done,
dec_op_data, output_buf);
# else
if (op_done.job != NULL) {
sts = cpaCyRsaDecrypt(qat_instance_handles[inst_num],
qat_rsaCallbackFn,
op_done_bssl, dec_op_data,
output_buf);
} /* No need for wake up job or pause job here */
else {
sts = cpaCyRsaDecrypt(qat_instance_handles[inst_num],
qat_rsaCallbackFn, &op_done,
dec_op_data, output_buf);
}
# endif
STOP_RDTSC(&qat_hw_rsa_dec_req_submit, 1, "[QAT HW RSA: submit]");
if (sts == CPA_STATUS_RETRY) {
DEBUG("cpaCyRsaDecrypt Retry \n");
if (qat_rsa_coexist) {
START_RDTSC(&qat_hw_rsa_dec_req_retry);
++num_rsa_priv_retry;
qat_sw_rsa_priv_req += QAT_SW_SWITCH_MB8;
*fallback = 1;
qat_cleanup_op_done(&op_done);
STOP_RDTSC(&qat_hw_rsa_dec_req_retry, 1, "[QAT HW RSA: retry]");
return 0;
} else {
if (op_done.job == NULL) {
usleep(ulPollInterval + qatPerformOpRetries);
qatPerformOpRetries++;
if (iMsgRetry != QAT_INFINITE_MAX_NUM_RETRIES) {
if (qatPerformOpRetries >= iMsgRetry) {
WARN("No. of retries exceeded max retry : %d\n", iMsgRetry);
break;
}
}
} else {
# ifndef QAT_BORINGSSL
if ((qat_wake_job(op_done.job, ASYNC_STATUS_EAGAIN) == 0) ||
(qat_pause_job(op_done.job, ASYNC_STATUS_EAGAIN) == 0)) {
WARN("qat_wake_job or qat_pause_job failed\n");
break;
}
# endif
}
}
}
}
while (sts == CPA_STATUS_RETRY);
if (sts != CPA_STATUS_SUCCESS) {
WARN("Failed to submit request to qat - status = %d\n", sts);
if (qat_get_sw_fallback_enabled() && (sts == CPA_STATUS_RESTARTING || sts == CPA_STATUS_FAIL)) {
CRYPTO_QAT_LOG("Failed to submit request to qat inst_num %d device_id %d - fallback to SW - %s\n",
inst_num,
qat_instance_details[inst_num].qat_instance_info.physInstId.packageId,
__func__);
*fallback = 1;
} else if (sts == CPA_STATUS_UNSUPPORTED) {
WARN("Algorithm Unsupported in QAT_HW! Using OpenSSL SW\n");
*fallback = 1;
} else {
QATerr(QAT_F_QAT_RSA_DECRYPT, ERR_R_INTERNAL_ERROR);
}
if (op_done.job != NULL) {
# ifdef QAT_BORINGSSL
op_done.job->free_op_done(op_done_bssl);
# endif
qat_clear_async_event_notification(op_done.job);
}
qat_cleanup_op_done(&op_done);
return 0;
}
QAT_INC_IN_FLIGHT_REQS(num_requests_in_flight, tlv);
if (qat_use_signals()) {
if (tlv->localOpsInFlight == 1) {
if (sem_post(&hw_polling_thread_sem) != 0) {
WARN("hw sem_post failed!, hw_polling_thread_sem address: %p.\n",
&hw_polling_thread_sem);
QATerr(QAT_F_QAT_RSA_DECRYPT, ERR_R_INTERNAL_ERROR);
QAT_DEC_IN_FLIGHT_REQS(num_requests_in_flight, tlv);
# ifdef QAT_BORINGSSL
if (op_done.job != NULL)
op_done.job->free_op_done(op_done_bssl);
# endif
return 0;
}
}
}
# ifdef QAT_BORINGSSL
if (op_done.job != NULL) {
qat_cleanup_op_done(&op_done);
return -1; /* Async mode for BoringSSL */
}
# endif
if (qat_get_sw_fallback_enabled()) {
CRYPTO_QAT_LOG("Submit success qat inst_num %d device_id %d - %s\n",
inst_num,
qat_instance_details[inst_num].qat_instance_info.physInstId.packageId,
__func__);
}
if (enable_heuristic_polling) {
QAT_ATOMIC_INC(num_asym_requests_in_flight);
}
if (qat_rsa_coexist)
++num_rsa_hw_priv_reqs;
do {
if(op_done.job != NULL) {
/* If we get a failure on qat_pause_job then we will
not flag an error here and quit because we have
an asynchronous request in flight.
We don't want to start cleaning up data
structures that are still being used. If
qat_pause_job fails we will just yield and
loop around and try again until the request
completes and we can continue. */
if ((job_ret = qat_pause_job(op_done.job, ASYNC_STATUS_OK)) == 0)
sched_yield();
}
else {
# ifdef QAT_BORINGSSL
/* Support inline polling in current scenario */
if(getEnableInlinePolling()) {
sts = icp_sal_CyPollInstance(qat_instance_handles[inst_num], 0);
if (sts == CPA_STATUS_FAIL) {
WARN("icp_sal_CyPollInstance failed - status %d\n", sts);
QATerr(QAT_F_QAT_RSA_DECRYPT, QAT_R_POLL_INSTANCE_FAILURE);
qat_cleanup_op_done(&op_done);
return 0;
}
RSA_INLINE_POLLING_USLEEP();
} else {
sched_yield();
}
# else
sched_yield();
# endif /* QAT_BORINGSSL */
}
}
while (!op_done.flag ||
QAT_CHK_JOB_RESUMED_UNEXPECTEDLY(job_ret));
DUMP_RSA_DECRYPT_OUTPUT(output_buf);
QAT_DEC_IN_FLIGHT_REQS(num_requests_in_flight, tlv);
if (op_done.verifyResult != CPA_TRUE) {
WARN("Verification of result failed\n");
if (qat_get_sw_fallback_enabled() && op_done.status == CPA_STATUS_FAIL) {
CRYPTO_QAT_LOG("Verification of result failed for qat inst_num %d device_id %d - fallback to SW - %s\n",
inst_num,
qat_instance_details[inst_num].qat_instance_info.physInstId.packageId,
__func__);
*fallback = 1;
} else {
QATerr(QAT_F_QAT_RSA_DECRYPT, ERR_R_INTERNAL_ERROR);
}
qat_cleanup_op_done(&op_done);
return 0;
}
qat_cleanup_op_done(&op_done);
DEBUG("- Finished\n");
return 1;
}
static int
build_decrypt_op_buf(int flen, const unsigned char *from, unsigned char *to,
RSA *rsa, int padding,
CpaCyRsaDecryptOpData ** dec_op_data,
CpaFlatBuffer ** output_buffer, int alloc_pad,
int inst_num, int qat_svm)
{
int rsa_len = 0;
int padding_result = 0;
CpaCyRsaPrivateKey *cpa_prv_key = NULL;
const BIGNUM *p = NULL;
const BIGNUM *q = NULL;
const BIGNUM *dmp1 = NULL;
const BIGNUM *dmq1 = NULL;
const BIGNUM *iqmp = NULL;
DEBUG("- Started\n");
RSA_get0_factors((const RSA*)rsa, &p, &q);
RSA_get0_crt_params((const RSA*)rsa, &dmp1, &dmq1, &iqmp);
if (p == NULL || q == NULL || dmp1 == NULL || dmq1 == NULL || iqmp == NULL) {
WARN("Either p %p, q %p, dmp1 %p, dmq1 %p, iqmp %p are NULL\n",
p, q, dmp1, dmq1, iqmp);
QATerr(QAT_F_BUILD_DECRYPT_OP_BUF, QAT_R_P_Q_DMP_DMQ_IQMP_NULL);
return 0;
}
DEBUG("flen = %d, padding = %d \n", flen, padding);
/* output signature should have same length as the RSA size */
rsa_len = RSA_size(rsa);
/* Padding check */
if ((padding != RSA_NO_PADDING) &&
(padding != RSA_PKCS1_PADDING) &&
(padding != RSA_PKCS1_OAEP_PADDING) &&
# ifndef QAT_OPENSSL_3
(padding != RSA_SSLV23_PADDING) &&
# endif
(padding != RSA_X931_PADDING)) {
WARN("Unknown Padding %d\n", padding);
QATerr(QAT_F_BUILD_DECRYPT_OP_BUF, QAT_R_PADDING_UNKNOWN);
return 0;
}
cpa_prv_key =
(CpaCyRsaPrivateKey *) OPENSSL_zalloc(sizeof(CpaCyRsaPrivateKey));
if (NULL == cpa_prv_key) {
WARN("Failed to allocate cpa_prv_key\n");
QATerr(QAT_F_BUILD_DECRYPT_OP_BUF, QAT_R_PRIV_KEY_MALLOC_FAILURE);
return 0;
}
/* output and input data MUST allocate memory for sign process */
/* memory allocation for DecOpdata[IN] */
*dec_op_data = OPENSSL_zalloc(sizeof(CpaCyRsaDecryptOpData));
if (NULL == *dec_op_data) {
WARN("Failed to allocate dec_op_data\n");
QATerr(QAT_F_BUILD_DECRYPT_OP_BUF, QAT_R_DEC_OP_DATA_MALLOC_FAILURE);
OPENSSL_free(cpa_prv_key);
return 0;
}
/* Setup the DecOpData structure */
(*dec_op_data)->pRecipientPrivateKey = cpa_prv_key;
cpa_prv_key->version = CPA_CY_RSA_VERSION_TWO_PRIME;
/* Setup the private key rep type 2 structure */
cpa_prv_key->privateKeyRepType = CPA_CY_RSA_PRIVATE_KEY_REP_TYPE_2;
if (qat_BN_to_FB(&cpa_prv_key->privateKeyRep2.prime1P, p, qat_svm) != 1 ||
qat_BN_to_FB(&cpa_prv_key->privateKeyRep2.prime2Q, q, qat_svm) != 1 ||
qat_BN_to_FB(&cpa_prv_key->privateKeyRep2.exponent1Dp, dmp1, qat_svm) != 1 ||
qat_BN_to_FB(&cpa_prv_key->privateKeyRep2.exponent2Dq, dmq1, qat_svm) != 1 ||
qat_BN_to_FB(&cpa_prv_key->privateKeyRep2.coefficientQInv, iqmp, qat_svm) != 1) {
WARN("Failed to convert privateKeyRep2 elements to flatbuffer\n");
QATerr(QAT_F_BUILD_DECRYPT_OP_BUF, QAT_R_P_Q_DMP_DMQ_CONVERT_TO_FB_FAILURE);
return 0;
}
(*dec_op_data)->inputData.pData = (Cpa8U *) qat_mem_alloc(
((padding != RSA_NO_PADDING) && alloc_pad) ? rsa_len : flen, qat_svm,
__FILE__,__LINE__);
if (NULL == (*dec_op_data)->inputData.pData) {
WARN("Failed to allocate (*dec_op_data)->inputData.pData\n");
QATerr(QAT_F_BUILD_DECRYPT_OP_BUF, QAT_R_INPUT_DATA_MALLOC_FAILURE);
return 0;
}
(*dec_op_data)->inputData.dataLenInBytes =
(padding != RSA_NO_PADDING) && alloc_pad ? rsa_len : flen;
if (alloc_pad) {
switch (padding) {
case RSA_PKCS1_PADDING:
padding_result =
RSA_padding_add_PKCS1_type_1((*dec_op_data)->inputData.pData,
rsa_len, from, flen);
break;
case RSA_X931_PADDING:
padding_result =
RSA_padding_add_X931((*dec_op_data)->inputData.pData,
rsa_len, from, flen);
break;
case RSA_NO_PADDING:
padding_result =
RSA_padding_add_none((*dec_op_data)->inputData.pData,
rsa_len, from, flen);
break;
default:
QATerr(QAT_F_BUILD_DECRYPT_OP_BUF, RSA_R_UNKNOWN_PADDING_TYPE);
break;
}
} else {
padding_result =
RSA_padding_add_none((*dec_op_data)->inputData.pData,
rsa_len, from, flen);
}
if (padding_result <= 0) {
WARN("Failed to add padding\n");
/* Error is raised within the padding function. */
return 0;
}
*output_buffer = OPENSSL_zalloc(sizeof(CpaFlatBuffer));
if (NULL == *output_buffer) {
WARN("Failed to allocate output_buffer\n");
QATerr(QAT_F_BUILD_DECRYPT_OP_BUF, QAT_R_OUTPUT_BUF_MALLOC_FAILURE);
return 0;
}
/*
* Memory allocation for DecOpdata[IN] the size of outputBuffer
* should big enough to contain RSA_size
*/
if (qat_svm)
(*output_buffer)->pData = (Cpa8U *) to;
else
(*output_buffer)->pData =
(Cpa8U *) qaeCryptoMemAlloc(rsa_len, __FILE__, __LINE__);
if (NULL == (*output_buffer)->pData) {
WARN("Failed to allocate output_buffer->pData\n");
QATerr(QAT_F_BUILD_DECRYPT_OP_BUF, QAT_R_RSA_OUTPUT_BUF_PDATA_MALLOC_FAILURE);
return 0;
}
(*output_buffer)->dataLenInBytes = rsa_len;
DEBUG("- Finished\n");
return 1;
}
static void
rsa_encrypt_op_buf_free(CpaCyRsaEncryptOpData * enc_op_data,
CpaFlatBuffer * out_buf, int qat_svm)
{
DEBUG("- Started\n");
if (enc_op_data) {
if (enc_op_data->pPublicKey) {
QAT_CLEANSE_MEMFREE_NONZERO_FLATBUFF(enc_op_data->pPublicKey->modulusN, qat_svm);
QAT_CLEANSE_MEMFREE_NONZERO_FLATBUFF(enc_op_data->pPublicKey->publicExponentE, qat_svm);
OPENSSL_free(enc_op_data->pPublicKey);
}
if (enc_op_data->inputData.pData) {
OPENSSL_cleanse(enc_op_data->inputData.pData, enc_op_data->inputData.dataLenInBytes);
QAT_MEM_FREE_NONZERO_BUFF(enc_op_data->inputData.pData,qat_svm);
}
OPENSSL_free(enc_op_data);
}
if (out_buf) {
if (out_buf->pData && !qat_svm) {
qaeCryptoMemFreeNonZero(out_buf->pData);
}
OPENSSL_free(out_buf);
}
DEBUG("- Finished\n");
}
static int qat_rsa_encrypt(CpaCyRsaEncryptOpData * enc_op_data,
CpaFlatBuffer * output_buf, int * fallback, int inst_num, int qat_svm)
{
/* Used for RSA Encrypt and RSA Verify */
op_done_t op_done;
CpaStatus sts = CPA_STATUS_FAIL;
int qatPerformOpRetries = 0;
int job_ret = 0;
thread_local_variables_t *tlv = NULL;
int iMsgRetry = getQatMsgRetryCount();
useconds_t ulPollInterval = getQatPollInterval();
DEBUG("- Started\n");
tlv = qat_check_create_local_variables();
if (NULL == tlv) {
WARN("could not create local variables\n");
QATerr(QAT_F_QAT_RSA_ENCRYPT, ERR_R_INTERNAL_ERROR);
return 0;
}
#if defined(QAT_BORINGSSL) && defined(ENABLE_QAT_HW_RSA)
qat_init_op_done(&op_done, qat_svm);
#else
qat_init_op_done(&op_done);
#endif
if (op_done.job != NULL) {
if (qat_setup_async_event_notification(op_done.job) == 0) {
WARN("Failed to setup async event notification\n");
QATerr(QAT_F_QAT_RSA_ENCRYPT, ERR_R_INTERNAL_ERROR);
qat_cleanup_op_done(&op_done);
return 0;
}
}
/*
* cpaCyRsaEncrypt() is the function called for RSA verify in the API.
* For that particular case the enc_op_data [IN] contains both the
* public key value and the signature value. The output_buf [OUT]
* stores the message as the output once the request is fully completed.
* The sts return value contains 0 (CPA_STATUS_SUCCESS) if the request
* was successfully submitted.
*/
CRYPTO_QAT_LOG("RSA - %s\n", __func__);
do {
if (sts == CPA_STATUS_RETRY &&
(inst_num = get_instance(QAT_INSTANCE_ASYM, qat_svm))
== QAT_INVALID_INSTANCE) {
WARN("Failed to get an instance\n");
if (qat_get_sw_fallback_enabled()) {
CRYPTO_QAT_LOG("Failed to get an instance - fallback to SW - %s\n", __func__);
*fallback = 1;
} else {
QATerr(QAT_F_QAT_RSA_ENCRYPT, ERR_R_INTERNAL_ERROR);
}
if (op_done.job != NULL) {
qat_clear_async_event_notification(op_done.job);
}
qat_cleanup_op_done(&op_done);
return 0;
}
DUMP_RSA_ENCRYPT(qat_instance_handles[inst_num], &op_done, enc_op_data, output_buf);
sts = cpaCyRsaEncrypt(qat_instance_handles[inst_num], qat_rsaCallbackFn, &op_done,
enc_op_data, output_buf);
if (sts == CPA_STATUS_RETRY) {
DEBUG("cpaCyRsaDecrypt Retry \n");
if (op_done.job == NULL) {
usleep(ulPollInterval + qatPerformOpRetries);
qatPerformOpRetries++;
if (iMsgRetry != QAT_INFINITE_MAX_NUM_RETRIES) {
if (qatPerformOpRetries >= iMsgRetry) {
WARN("No. of retries exceeded max retry : %d\n", iMsgRetry);
break;
}
}
} else {
if (qat_rsa_coexist) {
++num_rsa_pub_retry;
qat_sw_rsa_pub_req += QAT_SW_SWITCH_MB8;
*fallback = 1;
qat_cleanup_op_done(&op_done);
return 0;
} else {
if ((qat_wake_job(op_done.job, ASYNC_STATUS_EAGAIN) == 0) ||
(qat_pause_job(op_done.job, ASYNC_STATUS_EAGAIN) == 0)) {
WARN("qat_wake_job or qat_pause_job failed\n");
break;
}
}
}
}
}
while (sts == CPA_STATUS_RETRY);
if (sts != CPA_STATUS_SUCCESS) {
WARN("Failed to submit request to qat - status = %d\n", sts);
if (qat_get_sw_fallback_enabled() && (sts == CPA_STATUS_RESTARTING || sts == CPA_STATUS_FAIL)) {
CRYPTO_QAT_LOG("Failed to submit request to qat inst_num %d device_id %d - fallback to SW - %s\n",
inst_num,
qat_instance_details[inst_num].qat_instance_info.physInstId.packageId,
__func__);
*fallback = 1;
} else if (sts == CPA_STATUS_UNSUPPORTED) {
WARN("Algorithm Unsupported in QAT_HW! Using OpenSSL SW\n");
*fallback = 1;
} else {
QATerr(QAT_F_QAT_RSA_ENCRYPT, ERR_R_INTERNAL_ERROR);
}
if (op_done.job != NULL) {
qat_clear_async_event_notification(op_done.job);
}
qat_cleanup_op_done(&op_done);
return 0;
}
QAT_INC_IN_FLIGHT_REQS(num_requests_in_flight, tlv);
if (qat_use_signals()) {
if (tlv->localOpsInFlight == 1) {
if (sem_post(&hw_polling_thread_sem) != 0) {
WARN("hw sem_post failed!, hw_polling_thread_sem address: %p.\n",
&hw_polling_thread_sem);
QATerr(QAT_F_QAT_RSA_ENCRYPT, ERR_R_INTERNAL_ERROR);
QAT_DEC_IN_FLIGHT_REQS(num_requests_in_flight, tlv);
return 0;
}
}
}
if (qat_get_sw_fallback_enabled()) {
CRYPTO_QAT_LOG("Submit success qat inst_num %d device_id %d - %s\n",
inst_num,
qat_instance_details[inst_num].qat_instance_info.physInstId.packageId,
__func__);
}
if (enable_heuristic_polling) {
QAT_ATOMIC_INC(num_asym_requests_in_flight);
}
if (qat_rsa_coexist)
++num_rsa_hw_pub_reqs;
do {
if(op_done.job != NULL) {
/* If we get a failure on qat_pause_job then we will
not flag an error here and quit because we have
an asynchronous request in flight.
We don't want to start cleaning up data
structures that are still being used. If
qat_pause_job fails we will just yield and
loop around and try again until the request
completes and we can continue. */
if ((job_ret = qat_pause_job(op_done.job, ASYNC_STATUS_OK)) == 0)
sched_yield();
} else {
if(getEnableInlinePolling()) {
sts = icp_sal_CyPollInstance(qat_instance_handles[inst_num], 0);
if (sts == CPA_STATUS_FAIL) {
WARN("icp_sal_CyPollInstance failed - status %d\n", sts);
op_done.flag = 1;
}
} else
sched_yield();
}
} while (!op_done.flag || (sts == CPA_STATUS_RETRY) ||
QAT_CHK_JOB_RESUMED_UNEXPECTEDLY(job_ret));
DUMP_RSA_ENCRYPT_OUTPUT(output_buf);
QAT_DEC_IN_FLIGHT_REQS(num_requests_in_flight, tlv);
if (op_done.verifyResult != CPA_TRUE) {
WARN("Verification of result failed\n");
if (qat_get_sw_fallback_enabled() && op_done.status == CPA_STATUS_FAIL) {
CRYPTO_QAT_LOG("Verification of result failed for qat inst_num %d device_id %d - fallback to SW - %s\n",
inst_num,
qat_instance_details[inst_num].qat_instance_info.physInstId.packageId,
__func__);
*fallback = 1;
} else {
QATerr(QAT_F_QAT_RSA_ENCRYPT, ERR_R_INTERNAL_ERROR);
}
qat_cleanup_op_done(&op_done);
return 0;
}
qat_cleanup_op_done(&op_done);
return 1;
}
static int
build_encrypt_op_buf(int flen, const unsigned char *from, unsigned char *to,
RSA *rsa, int padding,
CpaCyRsaEncryptOpData ** enc_op_data,
CpaFlatBuffer ** output_buffer, int alloc_pad, int qat_svm)
{
CpaCyRsaPublicKey *cpa_pub_key = NULL;
int rsa_len = 0;
int padding_result = 0;
const BIGNUM *n = NULL;
const BIGNUM *e = NULL;
const BIGNUM *d = NULL;
DEBUG("- Started\n");
RSA_get0_key((const RSA*)rsa, &n, &e, &d);
/* Note: not checking 'd' as it is not used */
if (n == NULL || e == NULL) {
WARN("RSA key values n = %p or e = %p are NULL\n", n, e);
QATerr(QAT_F_BUILD_ENCRYPT_OP_BUF, QAT_R_N_E_NULL);
return 0;
}
DEBUG("flen =%d, padding = %d \n", flen, padding);
rsa_len = RSA_size(rsa);
if ((padding != RSA_NO_PADDING) &&
(padding != RSA_PKCS1_PADDING) &&
(padding != RSA_PKCS1_OAEP_PADDING) &&
# ifndef QAT_OPENSSL_3
(padding != RSA_SSLV23_PADDING) &&
# endif
(padding != RSA_X931_PADDING)) {
WARN("Unknown Padding %d\n", padding);
QATerr(QAT_F_BUILD_ENCRYPT_OP_BUF, QAT_R_UNKNOWN_PADDING);
return 0;
}
cpa_pub_key = OPENSSL_zalloc(sizeof(CpaCyRsaPublicKey));
if (NULL == cpa_pub_key) {
WARN("Public Key zalloc failed\n");
QATerr(QAT_F_BUILD_ENCRYPT_OP_BUF, QAT_R_PUB_KEY_MALLOC_FAILURE);
return 0;
}
/* Output and input data MUST allocate memory for RSA verify process */
/* Memory allocation for EncOpData[IN] */
*enc_op_data = OPENSSL_zalloc(sizeof(CpaCyRsaEncryptOpData));
if (NULL == *enc_op_data) {
WARN("Failed to allocate enc_op_data\n");
QATerr(QAT_F_BUILD_ENCRYPT_OP_BUF, QAT_R_ENC_OP_DATA_MALLOC_FAILURE);
OPENSSL_free(cpa_pub_key);
return 0;
}
/* Setup the Encrypt operation Data structure */
(*enc_op_data)->pPublicKey = cpa_pub_key;
/* Passing Public key from big number format to big endian order binary */
if (qat_BN_to_FB(&cpa_pub_key->modulusN, n, qat_svm) != 1 ||
qat_BN_to_FB(&cpa_pub_key->publicExponentE, e, qat_svm) != 1) {
WARN("Failed to convert cpa_pub_key elements to flatbuffer\n");
QATerr(QAT_F_BUILD_ENCRYPT_OP_BUF, QAT_R_N_E_CONVERT_TO_FB_FAILURE);
return 0;
}
(*enc_op_data)->inputData.pData = (Cpa8U *) qat_mem_alloc(
((padding != RSA_NO_PADDING) && alloc_pad) ? rsa_len : flen, qat_svm,
__FILE__,__LINE__);
if (NULL == (*enc_op_data)->inputData.pData) {
WARN("Failed to allocate (*enc_op_data)->inputData.pData\n");
QATerr(QAT_F_BUILD_ENCRYPT_OP_BUF, QAT_R_INPUT_DATA_MALLOC_FAILURE);
return 0;
}
(*enc_op_data)->inputData.dataLenInBytes =
((padding != RSA_NO_PADDING) && alloc_pad) ? rsa_len : flen;
if (alloc_pad) {
switch (padding) {
case RSA_PKCS1_PADDING:
padding_result =
RSA_padding_add_PKCS1_type_2((*enc_op_data)->inputData.pData,
rsa_len, from, flen);
break;
case RSA_PKCS1_OAEP_PADDING:
padding_result =
RSA_padding_add_PKCS1_OAEP((*enc_op_data)->inputData.pData,
rsa_len, from, flen, NULL, 0);
break;
# ifndef QAT_OPENSSL_3
case RSA_SSLV23_PADDING:
padding_result =
RSA_padding_add_SSLv23((*enc_op_data)->inputData.pData,
rsa_len, from, flen);
break;
# endif
case RSA_NO_PADDING:
padding_result =
RSA_padding_add_none((*enc_op_data)->inputData.pData,
rsa_len, from, flen);
break;
default:
QATerr(QAT_F_BUILD_ENCRYPT_OP_BUF, RSA_R_UNKNOWN_PADDING_TYPE);
break;
}
} else {
padding_result =
RSA_padding_add_none((*enc_op_data)->inputData.pData,
rsa_len, from, flen);
}
if (padding_result <= 0) {
WARN("Failed to add padding\n");
/* Error is raised within the padding function. */
return 0;
}
/*
* Memory allocation for outputBuffer[OUT] OutputBuffer size initialize
* as the size of rsa size
*/
(*output_buffer) =
(CpaFlatBuffer *) OPENSSL_zalloc(sizeof(CpaFlatBuffer));
if (NULL == (*output_buffer)) {
WARN("Failed to allocate output_buffer\n");
QATerr(QAT_F_BUILD_ENCRYPT_OP_BUF, QAT_R_OUTPUT_BUF_MALLOC_FAILURE);
return 0;
}
/*
* outputBuffer size should large enough to hold the Hash value but
* smaller than (RSA_size(rsa)-11)
*/
(*output_buffer)->dataLenInBytes = rsa_len;
if (!qat_svm)
(*output_buffer)->pData = qaeCryptoMemAlloc(rsa_len, __FILE__, __LINE__);
else
(*output_buffer)->pData = (Cpa8U *) to;
if (NULL == (*output_buffer)->pData) {
WARN("Failed to allocate (*output_buffer)->pData\n");
QATerr(QAT_F_BUILD_ENCRYPT_OP_BUF, QAT_R_OUTPUT_BUF_PDATA_MALLOC_FAILURE);
return 0;;
}
DEBUG("- Finished\n");
return 1;
}
/******************************************************************************
* function:
* qat_rsa_priv_enc (int flen,
* const unsigned char *from,
* unsigned char *to,
* RSA *rsa,
* int padding)
*
* @param flen [IN] - length in bytes of input file
* @param from [IN] - pointer to the input file
* @param to [OUT] - pointer to output signature
* @param rsa [IN] - pointer to private key structure
* @param padding [IN] - Padding scheme
*
* description: Perform an RSA private encrypt (RSA Sign)
* We use the decrypt implementation to achieve this.
******************************************************************************/
int qat_rsa_priv_enc(int flen, const unsigned char *from, unsigned char *to,
RSA *rsa, int padding)
{
int rsa_len = 0;
CpaCyRsaDecryptOpData *dec_op_data = NULL;
CpaFlatBuffer *output_buffer = NULL;
int sts = 1, fallback = 0, dec_ret = 0;
int inst_num = QAT_INVALID_INSTANCE;
int qat_svm = QAT_INSTANCE_ANY;
# ifndef DISABLE_QAT_HW_LENSTRA_PROTECTION
unsigned char *ver_msg = NULL;
const BIGNUM *d = NULL;
RSA *lenstra_rsa = NULL;
int lenstra_ret = -1;
int memcmp_ret = -1;
# endif
#ifdef ENABLE_QAT_HW_KPT
if (rsa && qat_check_rsa_wpk(rsa) > 0) {
if (is_kpt_mode()) {
DEBUG("Run the qat_rsa_priv_enc in KPT mode.\n");