forked from intel/QAT_Engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qat_hw_ciphers.c
1906 lines (1740 loc) · 70.2 KB
/
qat_hw_ciphers.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.
*
*
* ====================================================================
*/
/*
* This file contains modified code from OpenSSL/BoringSSL used
* in order to run certain operations in constant time.
* It is subject to the following license:
*/
/*
* Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/*****************************************************************************
* @file qat_hw_ciphers.c
*
* This file contains the engine implementations for cipher operations
*
*****************************************************************************/
#ifndef _GNU_SOURCE
# define _GNU_SOURCE
#endif
#include <pthread.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"
#include "qat_evp.h"
#include "cpa.h"
#include "cpa_types.h"
#include "cpa_cy_sym.h"
#include "qat_hw_ciphers.h"
#include "qat_constant_time.h"
#ifdef ENABLE_QAT_FIPS
# include "qat_prov_cmvp.h"
#endif
#include <openssl/evp.h>
#include <openssl/aes.h>
#include <openssl/err.h>
#include <openssl/sha.h>
#include <openssl/tls1.h>
#include <openssl/lhash.h>
#include <openssl/ssl.h>
#include <string.h>
#ifdef ENABLE_QAT_FIPS
extern int qat_fips_key_zeroize;
#endif
#define GET_TLS_HDR(qctx, i) ((qctx)->aad[(i)])
#define GET_TLS_VERSION(hdr) (((hdr)[9]) << QAT_BYTE_SHIFT | (hdr)[10])
#define GET_TLS_PAYLOAD_LEN(hdr) (((((hdr)[11]) << QAT_BYTE_SHIFT) & 0xff00) | \
((hdr)[12] & 0x00ff))
#define SET_TLS_PAYLOAD_LEN(hdr, len) \
do { \
hdr[11] = (len & 0xff00) >> QAT_BYTE_SHIFT; \
hdr[12] = len & 0xff; \
} while(0)
# define GET_SW_CIPHER(ctx) \
qat_chained_cipher_sw_impl(EVP_CIPHER_CTX_nid((ctx)))
#define GET_SW_NON_CHAINED_CIPHER(ctx) \
get_cipher_from_nid(EVP_CIPHER_CTX_nid((ctx)))
#define DEBUG_PPL DEBUG
int qatPerformOpRetries = 0;
/* Setup template for Session Setup Data as most of the fields
* are constant. The constant values of some of the fields are
* chosen for Encryption operation.
*/
static const CpaCySymSessionSetupData template_ssd = {
.sessionPriority = CPA_CY_PRIORITY_HIGH,
.symOperation = CPA_CY_SYM_OP_ALGORITHM_CHAINING,
.cipherSetupData = {
.cipherAlgorithm = CPA_CY_SYM_CIPHER_AES_CBC,
.cipherKeyLenInBytes = 0,
.pCipherKey = NULL,
.cipherDirection = CPA_CY_SYM_CIPHER_DIRECTION_ENCRYPT,
},
.hashSetupData = {
.hashAlgorithm = CPA_CY_SYM_HASH_SHA1,
.hashMode = CPA_CY_SYM_HASH_MODE_AUTH,
.digestResultLenInBytes = 0,
.authModeSetupData = {
.authKey = NULL,
.authKeyLenInBytes = HMAC_KEY_SIZE,
.aadLenInBytes = 0,
},
.nestedModeSetupData = {0},
},
.algChainOrder = CPA_CY_SYM_ALG_CHAIN_ORDER_HASH_THEN_CIPHER,
.digestIsAppended = CPA_TRUE,
.verifyDigest = CPA_FALSE,
.partialsNotRequired = CPA_TRUE,
};
static const CpaCySymOpData template_opData = {
.sessionCtx = NULL,
.packetType = CPA_CY_SYM_PACKET_TYPE_FULL,
.pIv = NULL,
.ivLenInBytes = 0,
.cryptoStartSrcOffsetInBytes = QAT_BYTE_ALIGNMENT,
.messageLenToCipherInBytes = 0,
.hashStartSrcOffsetInBytes = QAT_BYTE_ALIGNMENT - TLS_VIRT_HDR_SIZE,
.messageLenToHashInBytes = 0,
.pDigestResult = NULL,
.pAdditionalAuthData = NULL
};
static inline int get_digest_len(int nid)
{
return (((nid) == NID_aes_128_cbc_hmac_sha1 ||
(nid) == NID_aes_256_cbc_hmac_sha1) ?
SHA_DIGEST_LENGTH : SHA256_DIGEST_LENGTH);
}
static inline const EVP_CIPHER *qat_chained_cipher_sw_impl(int nid)
{
switch (nid) {
case NID_aes_128_cbc_hmac_sha1:
return EVP_aes_128_cbc_hmac_sha1();
case NID_aes_256_cbc_hmac_sha1:
return EVP_aes_256_cbc_hmac_sha1();
case NID_aes_128_cbc_hmac_sha256:
return EVP_aes_128_cbc_hmac_sha256();
case NID_aes_256_cbc_hmac_sha256:
return EVP_aes_256_cbc_hmac_sha256();
default:
WARN("Invalid nid %d\n", nid);
return NULL;
}
}
#ifdef QAT_OPENSSL_PROVIDER
static inline const char *qat_get_cipher_name_from_nid(int nid)
{
switch (nid) {
case NID_aes_128_cbc_hmac_sha1:
return "AES-128-CBC-HMAC-SHA1";
case NID_aes_256_cbc_hmac_sha1:
return "AES-256-CBC-HMAC-SHA1";
case NID_aes_128_cbc_hmac_sha256:
return "AES-128-CBC-HMAC-SHA256";
case NID_aes_256_cbc_hmac_sha256:
return "AES-256-CBC-HMAC-SHA256";
default:
WARN("Invalid nid %d\n", nid);
return NULL;
}
}
#endif
static inline const EVP_CIPHER *get_cipher_from_nid(int nid)
{
switch (nid) {
case NID_aes_128_cbc_hmac_sha1:
case NID_aes_128_cbc_hmac_sha256:
return EVP_aes_128_cbc();
case NID_aes_256_cbc_hmac_sha1:
case NID_aes_256_cbc_hmac_sha256:
return EVP_aes_256_cbc();
default:
WARN("Invalid nid %d\n", nid);
return NULL;
}
}
static inline void qat_chained_ciphers_free_qop(qat_op_params **pqop,
unsigned int *num_elem, int qat_svm)
{
unsigned int i = 0;
qat_op_params *qop = NULL;
if (pqop != NULL && ((qop = *pqop) != NULL)) {
for (i = 0; i < *num_elem; i++) {
if (!qat_svm)
qaeCryptoMemFreeNonZero(qop[i].src_fbuf[1].pData);
QAT_MEM_FREE_FLATBUFF(qop[i].src_fbuf[0], qat_svm);
QAT_MEM_FREE_BUFF(qop[i].src_sgl.pPrivateMetaData, qat_svm);
QAT_MEM_FREE_BUFF(qop[i].dst_sgl.pPrivateMetaData, qat_svm);
QAT_MEM_FREE_BUFF(qop[i].op_data.pIv, qat_svm);
}
OPENSSL_free(qop);
*pqop = NULL;
*num_elem = 0;
}
}
const EVP_CIPHER *qat_create_cipher_meth(int nid, int keylen)
{
EVP_CIPHER *c = NULL;
#ifndef QAT_OPENSSL_PROVIDER
int res = 1;
#endif
if (qat_hw_offload &&
(qat_hw_algo_enable_mask & ALGO_ENABLE_MASK_AES_CBC_HMAC_SHA)) {
if ((c = EVP_CIPHER_meth_new(nid, AES_BLOCK_SIZE, keylen)) == NULL) {
WARN("Failed to allocate cipher methods for nid %d\n", nid);
return NULL;
}
#ifndef QAT_OPENSSL_PROVIDER
res &= EVP_CIPHER_meth_set_iv_length(c, AES_IV_LEN);
res &= EVP_CIPHER_meth_set_flags(c, QAT_CHAINED_FLAG);
res &= EVP_CIPHER_meth_set_init(c, qat_chained_ciphers_init);
res &= EVP_CIPHER_meth_set_do_cipher(c, qat_chained_ciphers_do_cipher);
res &= EVP_CIPHER_meth_set_cleanup(c, qat_chained_ciphers_cleanup);
res &= EVP_CIPHER_meth_set_impl_ctx_size(c, sizeof(qat_chained_ctx));
res &= EVP_CIPHER_meth_set_set_asn1_params(c, EVP_CIPH_FLAG_DEFAULT_ASN1 ?
NULL : EVP_CIPHER_set_asn1_iv);
res &= EVP_CIPHER_meth_set_get_asn1_params(c, EVP_CIPH_FLAG_DEFAULT_ASN1 ?
NULL : EVP_CIPHER_get_asn1_iv);
res &= EVP_CIPHER_meth_set_ctrl(c, qat_chained_ciphers_ctrl);
if (res == 0) {
WARN("Failed to set cipher methods for nid %d\n", nid);
EVP_CIPHER_meth_free(c);
c = NULL;
}
qat_hw_aes_cbc_hmac_sha_offload = 1;
DEBUG("QAT HW AES_CBC_%d_HMAC_SHA registration succeeded\n", keylen*8);
#endif
return c;
} else {
qat_hw_aes_cbc_hmac_sha_offload = 0;
DEBUG("QAT HW AES_CBC_%d_HMAC_SHA is disabled, using OpenSSL SW\n", keylen*8);
EVP_CIPHER_meth_free(c);
return qat_chained_cipher_sw_impl(nid);
}
}
/******************************************************************************
* function:
* qat_chained_callbackFn(void *callbackTag, CpaStatus status,
* const CpaCySymOp operationType, void *pOpData,
* CpaBufferList * pDstBuffer, CpaBoolean verifyResult)
*
* @param pCallbackTag [IN] - Opaque value provided by user while making
* individual function call. Cast to op_done_pipe_t.
* @param status [IN] - Status of the operation.
* @param operationType [IN] - Identifies the operation type requested.
* @param pOpData [IN] - Pointer to structure with input parameters.
* @param pDstBuffer [IN] - Destination buffer to hold the data output.
* @param verifyResult [IN] - Used to verify digest result.
*
* description:
* Callback function used by chained ciphers with pipeline support. This
* function is called when operation is completed for each pipeline. However
* the paused job is woken up when all the pipelines have been processed.
*
******************************************************************************/
static void qat_chained_callbackFn(void *callbackTag, CpaStatus status,
const CpaCySymOp operationType,
void *pOpData, CpaBufferList *pDstBuffer,
CpaBoolean verifyResult)
{
ASYNC_JOB *job = NULL;
op_done_pipe_t *opdone = (op_done_pipe_t *)callbackTag;
CpaBoolean res = CPA_FALSE;
if (opdone == NULL) {
WARN("Callback Tag NULL\n");
return;
}
opdone->num_processed++;
res = (status == CPA_STATUS_SUCCESS) && verifyResult ? CPA_TRUE : CPA_FALSE;
/* If any single pipe processing failed, the entire operation
* is treated as failure. The default value of opDone.verifyResult
* is TRUE. Change it to false on Failure.
*/
if (res == CPA_FALSE) {
WARN("Pipe %u failed (status %d, verifyResult %d)\n",
opdone->num_processed, status, verifyResult);
opdone->opDone.verifyResult = CPA_FALSE;
}
/* The QAT API guarantees submission order for request
* i.e. first in first out. If not all requests have been
* submitted or processed, wait for more callbacks.
*/
if ((opdone->num_submitted != opdone->num_pipes) ||
(opdone->num_submitted != opdone->num_processed))
return;
if (enable_heuristic_polling) {
QAT_ATOMIC_DEC(num_cipher_pipeline_requests_in_flight);
}
/* Cache job pointer to avoid a race condition if opdone gets cleaned up
* in the calling thread.
*/
job = (ASYNC_JOB *)opdone->opDone.job;
/* Mark job as done when all the requests have been submitted and
* subsequently processed.
*/
opdone->opDone.flag = 1;
if (job) {
qat_wake_job(job, ASYNC_STATUS_OK);
}
}
/******************************************************************************
* function:
* qat_setup_op_params(EVP_CIPHER_CTX *ctx)
*
* @param qctx [IN] - pointer to existing qat_chained_ctx
*
* @retval 1 function succeeded
* @retval 0 function failed
*
* description:
* This function initialises the flatbuffer and flat buffer list for use.
*
******************************************************************************/
#ifdef QAT_OPENSSL_PROVIDER
static int qat_setup_op_params(PROV_CIPHER_CTX *ctx)
#else
static int qat_setup_op_params(EVP_CIPHER_CTX *ctx)
#endif
{
CpaCySymOpData *opd = NULL;
Cpa32U msize = 0;
#ifdef QAT_OPENSSL_PROVIDER
qat_chained_ctx *qctx = (qat_chained_ctx *)ctx->qat_cipher_ctx;
#else
qat_chained_ctx *qctx = qat_chained_data(ctx);
#endif
int i = 0;
unsigned int start;
/* When no pipelines are used, numpipes = 1. The actual number of pipes are
* not known until the start of do_cipher.
*/
if (PIPELINE_USED(qctx)) {
/* When Pipes have been previously used, the memory has been allocated
* for max supported pipes although initialised only for numpipes.
*/
start = qctx->npipes_last_used;
} else {
start = 1;
/* When the context switches from using no pipes to using pipes,
* free the previous allocated memory.
*/
if (qctx->qop != NULL && qctx->qop_len < qctx->numpipes) {
qat_chained_ciphers_free_qop(&qctx->qop, &qctx->qop_len, qctx->qat_svm);
DEBUG_PPL("[%p] qop memory freed\n", ctx);
}
}
/* Allocate memory for qop depending on whether pipes are used or not.
* In case of pipes, allocate for the maximum supported pipes.
*/
if (qctx->qop == NULL) {
if (PIPELINE_USED(qctx)) {
WARN("Pipeline used but no data allocated. Possible memory leak\n");
}
qctx->qop_len = qctx->numpipes > 1 ? QAT_MAX_PIPELINES : 1;
qctx->qop = (qat_op_params *) OPENSSL_zalloc(sizeof(qat_op_params)
* qctx->qop_len);
if (qctx->qop == NULL) {
WARN("Unable to allocate memory[%lu bytes] for qat op params\n",
sizeof(qat_op_params) * qctx->qop_len);
return 0;
}
/* start from 0 as New array of qat_op_params */
start = 0;
}
for (i = start; i < qctx->numpipes; i++) {
/* This is a whole block the size of the memory alignment. If the
* alignment was to become smaller than the header size
* (TLS_VIRT_HEADER_SIZE) which is unlikely then we would need to add
* some more logic here to work out how many blocks of size
* QAT_BYTE_ALIGNMENT we need to allocate to fit the header in.
*/
if (!qctx->qat_svm)
FLATBUFF_ALLOC_AND_CHAIN(qctx->qop[i].src_fbuf[0],
qctx->qop[i].dst_fbuf[0],
QAT_BYTE_ALIGNMENT);
else
FLATBUFF_ALLOC_AND_CHAIN_SVM(qctx->qop[i].src_fbuf[0],
qctx->qop[i].dst_fbuf[0],
QAT_BYTE_ALIGNMENT);
if (qctx->qop[i].src_fbuf[0].pData == NULL) {
WARN("Unable to allocate memory for TLS header\n");
goto err;
}
memset(qctx->qop[i].src_fbuf[0].pData, 0, QAT_BYTE_ALIGNMENT);
qctx->qop[i].src_fbuf[1].pData = NULL;
qctx->qop[i].dst_fbuf[1].pData = NULL;
qctx->qop[i].src_sgl.numBuffers = 2;
qctx->qop[i].src_sgl.pBuffers = qctx->qop[i].src_fbuf;
qctx->qop[i].src_sgl.pUserData = NULL;
qctx->qop[i].src_sgl.pPrivateMetaData = NULL;
qctx->qop[i].dst_sgl.numBuffers = 2;
qctx->qop[i].dst_sgl.pBuffers = qctx->qop[i].dst_fbuf;
qctx->qop[i].dst_sgl.pUserData = NULL;
qctx->qop[i].dst_sgl.pPrivateMetaData = NULL;
DEBUG("Pipe [%d] inst_num = %d\n", i, qctx->inst_num);
DEBUG("Pipe [%d] No of buffers = %d\n", i, qctx->qop[i].src_sgl.numBuffers);
/* setup meta data for buffer lists */
if (msize == 0 &&
cpaCyBufferListGetMetaSize(qat_instance_handles[qctx->inst_num],
qctx->qop[i].src_sgl.numBuffers,
&msize) != CPA_STATUS_SUCCESS) {
WARN("cpaCyBufferListGetBufferSize failed.\n");
goto err;
}
DEBUG("Pipe [%d] Size of meta data = %d\n", i, msize);
if (msize) {
qctx->qop[i].src_sgl.pPrivateMetaData =
qat_mem_alloc(msize, qctx->qat_svm, __FILE__, __LINE__);
qctx->qop[i].dst_sgl.pPrivateMetaData =
qat_mem_alloc(msize, qctx->qat_svm, __FILE__, __LINE__);
if (qctx->qop[i].src_sgl.pPrivateMetaData == NULL ||
qctx->qop[i].dst_sgl.pPrivateMetaData == NULL) {
WARN("QMEM alloc failed for PrivateData\n");
goto err;
}
}
opd = &qctx->qop[i].op_data;
/* Copy the opData template */
memcpy(opd, &template_opData, sizeof(template_opData));
/* Update Opdata */
opd->sessionCtx = qctx->session_ctx;
#ifdef QAT_OPENSSL_PROVIDER
opd->pIv = qat_mem_alloc(ctx->ivlen, qctx->qat_svm, __FILE__, __LINE__);
#else
opd->pIv = qat_mem_alloc(EVP_CIPHER_CTX_iv_length(ctx), qctx->qat_svm, __FILE__, __LINE__);
#endif
if (opd->pIv == NULL) {
WARN("QMEM Mem Alloc failed for pIv for pipe %d.\n", i);
goto err;
}
#ifdef QAT_OPENSSL_PROVIDER
opd->ivLenInBytes = (Cpa32U) ctx->ivlen;
#else
opd->ivLenInBytes = (Cpa32U) EVP_CIPHER_CTX_iv_length(ctx);
#endif
}
DEBUG_PPL("[%p] qop setup for %u elements\n", ctx, qctx->qop_len);
return 1;
err:
qat_chained_ciphers_free_qop(&qctx->qop, &qctx->qop_len, qctx->qat_svm);
return 0;
}
/******************************************************************************
* function:
* qat_chained_ciphers_init(EVP_CIPHER_CTX *ctx,
* const unsigned char *inkey,
* const unsigned char *iv,
* int enc)
*
* @param ctx [IN] - pointer to existing ctx
* @param inKey [IN] - input cipher key
* @param iv [IN] - initialisation vector
* @param enc [IN] - 1 encrypt 0 decrypt
*
* @retval 1 function succeeded
* @retval 0 function failed
*
* description:
* This function initialises the cipher and hash algorithm parameters for this
* EVP context.
*
******************************************************************************/
#ifdef QAT_OPENSSL_PROVIDER
int qat_chained_ciphers_init(PROV_CIPHER_CTX *ctx,
const unsigned char *inkey, size_t keylen,
const unsigned char *iv, size_t ivlen, int enc)
#else
int qat_chained_ciphers_init(EVP_CIPHER_CTX *ctx,
const unsigned char *inkey,
const unsigned char *iv, int enc)
#endif
{
CpaCySymSessionSetupData *ssd = NULL;
Cpa32U sctx_size = 0;
CpaCySymSessionCtx sctx = NULL;
CpaStatus sts = 0;
qat_chained_ctx *qctx = NULL;
unsigned char *ckey = NULL;
int ckeylen;
int dlen;
int ret = 0;
EVP_CIPHER *sw_cipher = NULL;
#ifndef QAT_OPENSSL_PROVIDER
unsigned int sw_size = 0;
#endif
if (ctx == NULL || inkey == NULL) {
WARN("ctx or inkey is NULL.\n");
return 0;
}
#ifdef QAT_OPENSSL_PROVIDER
qctx = (qat_chained_ctx *)ctx->qat_cipher_ctx;
#else
qctx = qat_chained_data(ctx);
#endif
if (qctx == NULL) {
WARN("qctx is NULL.\n");
return 0;
}
DEBUG("QAT HW Ciphers Started\n");
INIT_SEQ_CLEAR_ALL_FLAGS(qctx);
/* iv has been initialized in qatprovider, we don't
need to do any operations if using qatprovider here. */
#ifdef QAT_OPENSSL_PROVIDER
if (qat_get_sw_fallback_enabled()){
if (iv != NULL)
memcpy(EVP_CIPHER_CTX_iv_noconst(ctx->sw_ctx), iv, ivlen);
else
memset(EVP_CIPHER_CTX_iv_noconst(ctx->sw_ctx), 0, ivlen);
}
ckeylen = keylen;
ckey = OPENSSL_malloc(keylen);
#else
if (iv != NULL)
memcpy(EVP_CIPHER_CTX_iv_noconst(ctx), iv,
EVP_CIPHER_CTX_iv_length(ctx));
else
memset(EVP_CIPHER_CTX_iv_noconst(ctx), 0,
EVP_CIPHER_CTX_iv_length(ctx));
ckeylen = EVP_CIPHER_CTX_key_length(ctx);
ckey = OPENSSL_malloc(ckeylen);
#endif
if (ckey == NULL) {
WARN("Unable to allocate memory for Cipher key.\n");
return 0;
}
memcpy(ckey, inkey, ckeylen);
memset(qctx, 0, sizeof(*qctx));
qctx->numpipes = 1;
qctx->total_op = 0;
qctx->npipes_last_used = 1;
qctx->fallback = 0;
qctx->hmac_key = OPENSSL_zalloc(HMAC_KEY_SIZE);
if (qctx->hmac_key == NULL) {
WARN("Unable to allocate memory for HMAC Key\n");
goto err;
}
#ifdef QAT_OPENSSL_PROVIDER
# ifndef ENABLE_QAT_SMALL_PKT_OFFLOAD
sw_cipher = EVP_CIPHER_fetch(NULL,
qat_get_cipher_name_from_nid(ctx->nid),
"provider=default");
if (sw_cipher == NULL){
WARN("SW cipher fetch failed!\n");
goto err;
}
if (!EVP_CipherInit_ex2(ctx->sw_ctx, sw_cipher, inkey, iv, enc, NULL)){
WARN("SW cipher init error!\n");
goto err;
}
ctx->sw_cipher = sw_cipher;
# else
if (qat_get_sw_fallback_enabled()){
sw_cipher = EVP_CIPHER_fetch(NULL,
qat_get_cipher_name_from_nid(ctx->nid),
"provider=default");
if (sw_cipher == NULL){
WARN("SW cipher fetch failed!\n");
goto err;
}
if (!EVP_CipherInit_ex2(ctx->sw_ctx, sw_cipher, inkey, iv, enc, NULL)){
WARN("SW cipher init error!\n");
goto err;
}
ctx->sw_cipher = sw_cipher;
}
# endif
#else
sw_cipher = (EVP_CIPHER *)GET_SW_CIPHER(ctx);
sw_size = EVP_CIPHER_impl_ctx_size(sw_cipher);
if (sw_size != 0) {
qctx->sw_ctx_cipher_data = OPENSSL_zalloc(sw_size);
if (qctx->sw_ctx_cipher_data == NULL) {
WARN("Unable to allocate memory [%u bytes] for sw_ctx_cipher_data\n",
sw_size);
goto err;
}
}
EVP_CIPHER_CTX_set_cipher_data(ctx, qctx->sw_ctx_cipher_data);
/* Run the software init function */
ret = EVP_CIPHER_meth_get_init(sw_cipher)(ctx, inkey, iv, enc);
EVP_CIPHER_CTX_set_cipher_data(ctx, qctx);
if (ret != 1)
goto err;
#endif
if (qat_get_qat_offload_disabled()) {
/*
* Setting qctx->fallback as a flag for the other functions.
* This means in the other functions (and in the err section in this function)
* we no longer need to check qat_get_qat_offload_disabled() but just check
* the fallback flag instead. This has the added benefit that even if
* the engine control message to enable HW offload is sent it will not affect
* requests that have already been init'd, they will continue to use SW until
* the request is complete, i.e. no race condition.
*/
qctx->fallback = 1;
goto err;
}
ssd = OPENSSL_zalloc(sizeof(CpaCySymSessionSetupData));
if (ssd == NULL) {
WARN("Failed to allocate session setup data\n");
goto err;
}
qctx->session_data = ssd;
/* Copy over the template for most of the values */
memcpy(ssd, &template_ssd, sizeof(template_ssd));
/* Change constant values for decryption */
if (!enc) {
ssd->cipherSetupData.cipherDirection =
CPA_CY_SYM_CIPHER_DIRECTION_DECRYPT;
ssd->algChainOrder = CPA_CY_SYM_ALG_CHAIN_ORDER_CIPHER_THEN_HASH;
ssd->verifyDigest = CPA_TRUE;
}
ssd->cipherSetupData.cipherKeyLenInBytes = ckeylen;
ssd->cipherSetupData.pCipherKey = ckey;
#ifdef QAT_OPENSSL_PROVIDER
dlen = get_digest_len(ctx->nid);
#else
dlen = get_digest_len(EVP_CIPHER_CTX_nid(ctx));
#endif
ssd->hashSetupData.digestResultLenInBytes = dlen;
if (dlen != SHA_DIGEST_LENGTH)
ssd->hashSetupData.hashAlgorithm = CPA_CY_SYM_HASH_SHA256;
ssd->hashSetupData.authModeSetupData.authKey = qctx->hmac_key;
qctx->inst_num = get_instance(QAT_INSTANCE_SYM, QAT_INSTANCE_ANY);
if (qctx->inst_num == QAT_INVALID_INSTANCE) {
WARN("Failed to get a QAT instance.\n");
if (qat_get_sw_fallback_enabled()) {
CRYPTO_QAT_LOG("Failed to get an instance - fallback to SW - %s\n", __func__);
qctx->fallback = 1;
}
goto err;
}
qctx->qat_svm = !qat_instance_details[qctx->inst_num].qat_instance_info.requiresPhysicallyContiguousMemory;
DUMP_SESSION_SETUP_DATA(ssd);
sts = cpaCySymSessionCtxGetSize(qat_instance_handles[qctx->inst_num], ssd, &sctx_size);
if (sts != CPA_STATUS_SUCCESS) {
WARN("Failed to get SessionCtx size.\n");
if (qat_get_sw_fallback_enabled()) {
CRYPTO_QAT_LOG("Failed to submit request to qat inst_num %d device_id %d - fallback to SW - %s\n",
qctx->inst_num,
qat_instance_details[qctx->inst_num].qat_instance_info.physInstId.packageId,
__func__);
qctx->fallback = 1;
}
goto err;
}
DEBUG("Size of session ctx = %d\n", sctx_size);
sctx = (CpaCySymSessionCtx) qat_mem_alloc(sctx_size, qctx->qat_svm, __FILE__,
__LINE__);
if (sctx == NULL) {
WARN("QMEM alloc failed for session ctx!\n");
goto err;
}
qctx->session_ctx = sctx;
qctx->qop = NULL;
qctx->qop_len = 0;
INIT_SEQ_SET_FLAG(qctx, INIT_SEQ_QAT_CTX_INIT);
DEBUG_PPL("[%p] qat chained cipher ctx %p initialised\n",ctx, qctx);
return 1;
err:
/* NOTE: no init seq flags will have been set if this 'err:' label code section is entered. */
OPENSSL_clear_free(ckey, ckeylen);
OPENSSL_clear_free(qctx->hmac_key, HMAC_KEY_SIZE);
if (ssd != NULL)
OPENSSL_free(ssd);
qctx->session_data = NULL;
QAT_MEM_FREE_BUFF(qctx->session_ctx, qctx->qat_svm);
if ((qctx->fallback == 1) && (qctx->sw_ctx_cipher_data != NULL) && (ret == 1)) {
DEBUG("- Fallback to software mode.\n");
CRYPTO_QAT_LOG("Resubmitting request to SW - %s\n", __func__);
return ret; /* result returned from running software init function */
}
if (qctx->sw_ctx_cipher_data != NULL) {
OPENSSL_free(qctx->sw_ctx_cipher_data);
qctx->sw_ctx_cipher_data = NULL;
}
return 0;
}
/******************************************************************************
* function:
* qat_chained_ciphers_ctrl(EVP_CIPHER_CTX *ctx,
* int type, int arg, void *ptr)
*
* @param ctx [IN] - pointer to existing ctx
* @param type [IN] - type of request either
* EVP_CTRL_AEAD_SET_MAC_KEY or EVP_CTRL_AEAD_TLS1_AAD
* @param arg [IN] - size of the pointed to by ptr
* @param ptr [IN] - input buffer contain the necessary parameters
*
* @retval x The return value is dependent on the type of request being made
* EVP_CTRL_AEAD_SET_MAC_KEY return of 1 is success
* EVP_CTRL_AEAD_TLS1_AAD return value indicates the amount of padding to
* be applied to the SSL/TLS record
* @retval -1 function failed
*
* description:
* This function is a generic control interface provided by the EVP API. For
* chained requests this interface is used for setting the hmac key value for
* authentication of the SSL/TLS record. The second type is used to specify the
* TLS virtual header which is used in the authentication calculation and to
* identify record payload size.
*
******************************************************************************/
#ifdef QAT_OPENSSL_PROVIDER
int qat_chained_ciphers_ctrl(PROV_AES_HMAC_SHA_CTX *ctx, int type, int arg, void *ptr)
#else
int qat_chained_ciphers_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr)
#endif
{
qat_chained_ctx *qctx = NULL;
unsigned char *hmac_key = NULL;
CpaCySymSessionSetupData *ssd = NULL;
SHA_CTX hkey1;
SHA256_CTX hkey256;
CpaStatus sts;
char *hdr = NULL;
unsigned int len = 0;
int retVal = 0;
int retVal_sw = 0;
int dlen = 0;
if (ctx == NULL) {
WARN("ctx parameter is NULL.\n");
return -1;
}
#ifdef QAT_OPENSSL_PROVIDER
qctx = (qat_chained_ctx *)ctx->base.qat_cipher_ctx;
#else
qctx = qat_chained_data(ctx);
#endif
if (qctx == NULL) {
WARN("qctx is NULL.\n");
return -1;
}
if (qctx->fallback == 1)
goto sw_ctrl;
#ifdef QAT_OPENSSL_PROVIDER
dlen = get_digest_len(ctx->base.nid);
#else
dlen = get_digest_len(EVP_CIPHER_CTX_nid(ctx));
#endif
switch (type) {
case EVP_CTRL_AEAD_SET_MAC_KEY:
hmac_key = qctx->hmac_key;
ssd = qctx->session_data;
memset(hmac_key, 0, HMAC_KEY_SIZE);
if (arg > HMAC_KEY_SIZE) {
if (dlen == SHA_DIGEST_LENGTH) {
SHA1_Init(&hkey1);
SHA1_Update(&hkey1, ptr, arg);
SHA1_Final(hmac_key, &hkey1);
} else {
SHA256_Init(&hkey256);
SHA256_Update(&hkey256, ptr, arg);
SHA256_Final(hmac_key, &hkey256);
}
} else {
memcpy(hmac_key, ptr, arg);
ssd->hashSetupData.authModeSetupData.authKeyLenInBytes = arg;
}
INIT_SEQ_SET_FLAG(qctx, INIT_SEQ_HMAC_KEY_SET);
DEBUG("inst_num = %d\n", qctx->inst_num);
DUMP_SESSION_SETUP_DATA(ssd);
DEBUG("session_ctx = %p\n", qctx->session_ctx);
if (!(is_instance_available(qctx->inst_num))) {
WARN("No QAT instance available so not creating session.\n");
if (qat_get_sw_fallback_enabled()) {
CRYPTO_QAT_LOG("Failed to get an instance - fallback to SW - %s\n", __func__);
qctx->fallback = 1; /* Set fallback even if already set */
}
else {
WARN("- No QAT instance available and s/w fallback not enabled.\n");
retVal = 0; /* Fail if software fallback not enabled. */
}
} else {
sts = cpaCySymInitSession(qat_instance_handles[qctx->inst_num],
qat_chained_callbackFn,
ssd, qctx->session_ctx);
if (sts != CPA_STATUS_SUCCESS) {
WARN("cpaCySymInitSession failed! 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",
qctx->inst_num,
qat_instance_details[qctx->inst_num].qat_instance_info.physInstId.packageId,
__func__);
qctx->fallback = 1;
}
else
retVal = 0;
} else {
if (qat_get_sw_fallback_enabled()) {
CRYPTO_QAT_LOG("Submit success qat inst_num %d device_id %d - %s\n",
qctx->inst_num,
qat_instance_details[qctx->inst_num].qat_instance_info.physInstId.packageId,
__func__);
}
INIT_SEQ_SET_FLAG(qctx, INIT_SEQ_QAT_SESSION_INIT);
retVal = 1;
}
}
break;
case EVP_CTRL_AEAD_TLS1_AAD:
/* This returns the amount of padding required for
the send/encrypt direction.
*/
if (arg != TLS_VIRT_HDR_SIZE || qctx->aad_ctr >= QAT_MAX_PIPELINES) {
WARN("Invalid argument for AEAD_TLS1_AAD.\n");
retVal = -1;
break;
}
hdr = GET_TLS_HDR(qctx, qctx->aad_ctr);
memcpy(hdr, ptr, TLS_VIRT_HDR_SIZE);
qctx->aad_ctr++;
if (qctx->aad_ctr > 1)
INIT_SEQ_SET_FLAG(qctx, INIT_SEQ_PPL_AADCTR_SET);
len = GET_TLS_PAYLOAD_LEN(((char *)ptr));
if (GET_TLS_VERSION(((char *)ptr)) >= TLS1_1_VERSION) {
#ifdef QAT_OPENSSL_PROVIDER
if (len < ctx->base.ivlen) {
#else
if (len < EVP_CIPHER_CTX_iv_length(ctx)) {
#endif
WARN("Length is smaller than the IV length\n");
retVal = 0;
break;
}
#ifdef QAT_OPENSSL_PROVIDER
len -= ctx->base.ivlen;
#else
len -= EVP_CIPHER_CTX_iv_length(ctx);
#endif
} else if (qctx->aad_ctr > 1) {
/* pipelines are not supported for
* TLS version < TLS1.1
*/
WARN("AAD already set for TLS1.0\n");
retVal = -1;
break;
}
#ifdef QAT_OPENSSL_PROVIDER
if (ctx->base.enc){
ctx->tls_aad_pad = (int)(((len + dlen + AES_BLOCK_SIZE)
& -AES_BLOCK_SIZE) - len);
retVal = ctx->tls_aad_pad;
} else {
ctx->payload_length = arg;
ctx->tls_aad_pad = SHA_DIGEST_LENGTH;
retVal = 1;
}
#else
if (EVP_CIPHER_CTX_encrypting(ctx))
retVal = (int)(((len + dlen + AES_BLOCK_SIZE)
& -AES_BLOCK_SIZE) - len);
else
retVal = dlen;
#endif
INIT_SEQ_SET_FLAG(qctx, INIT_SEQ_TLS_HDR_SET);
break;
/* All remaining cases are exclusive to pipelines and are not
* used with small packet offload feature.
*/
case EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS:
if (arg > QAT_MAX_PIPELINES) {
WARN("PIPELINE_OUTPUT_BUFS npipes(%d) > Max(%d).\n",
arg, QAT_MAX_PIPELINES);
return -1;
}
qctx->p_out = (unsigned char **)ptr;
qctx->numpipes = arg;
INIT_SEQ_SET_FLAG(qctx, INIT_SEQ_PPL_OBUF_SET);
return 1;
case EVP_CTRL_SET_PIPELINE_INPUT_BUFS:
if (arg > QAT_MAX_PIPELINES) {
WARN("PIPELINE_OUTPUT_BUFS npipes(%d) > Max(%d).\n",
arg, QAT_MAX_PIPELINES);
return -1;
}
qctx->p_in = (unsigned char **)ptr;
qctx->numpipes = arg;
INIT_SEQ_SET_FLAG(qctx, INIT_SEQ_PPL_IBUF_SET);
return 1;