-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathcryptography_interface_kmc_crypto_service.template.c
More file actions
2356 lines (2103 loc) · 88.1 KB
/
cryptography_interface_kmc_crypto_service.template.c
File metadata and controls
2356 lines (2103 loc) · 88.1 KB
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 2021, by the California Institute of Technology.
* ALL RIGHTS RESERVED. United States Government Sponsorship acknowledged.
* Any commercial use must be negotiated with the Office of Technology
* Transfer at the California Institute of Technology.
*
* This software may be subject to U.S. export control laws. By accepting
* this software, the user agrees to comply with all applicable U.S.
* export laws and regulations. User has the responsibility to obtain
* export licenses, or other export authority as may be required before
* exporting such information to foreign countries or providing access to
* foreign persons.
*/
#include "crypto_error.h"
#include "cryptography_interface.h"
#include "crypto.h"
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <curl/curl.h>
// base64 & base64url encoding/decoding libraries
#include "base64url.h"
#include "base64.h"
// JSON marshalling libraries
#include "jsmn.h"
#define CAM_MAX_AUTH_RETRIES 4
// libcurl call-back response handling Structures
typedef struct
{
char *response;
size_t size;
} memory_write;
#define MEMORY_WRITE_SIZE (sizeof(memory_write))
typedef struct
{
char *response;
size_t size;
} memory_read;
#define MEMORY_READ_SIZE (sizeof(memory_read))
// Cryptography Interface Initialization & Management Functions
static int32_t cryptography_config(void);
static int32_t cryptography_init(void);
static int32_t cryptography_shutdown(void);
// Cryptography Interface Functions
static int32_t cryptography_encrypt(uint8_t *data_out, size_t len_data_out, uint8_t *data_in, size_t len_data_in,
uint8_t *key, uint32_t len_key, SecurityAssociation_t *sa_ptr, uint8_t *iv,
uint32_t iv_len, uint8_t *ecs, uint8_t padding, char *cam_cookies);
static int32_t cryptography_decrypt(uint8_t *data_out, size_t len_data_out, uint8_t *data_in, size_t len_data_in,
uint8_t *key, uint32_t len_key, SecurityAssociation_t *sa_ptr, uint8_t *iv,
uint32_t iv_len, uint8_t *ecs, uint8_t *acs, char *cam_cookies);
static int32_t cryptography_authenticate(uint8_t *data_out, size_t len_data_out, uint8_t *data_in, size_t len_data_in,
uint8_t *key, uint32_t len_key, SecurityAssociation_t *sa_ptr, uint8_t *iv,
uint32_t iv_len, uint8_t *mac, uint32_t mac_size, uint8_t *aad,
uint32_t aad_len, uint8_t ecs, uint8_t acs, char *cam_cookies);
static int32_t cryptography_validate_authentication(uint8_t *data_out, size_t len_data_out, const uint8_t *data_in,
const size_t len_data_in, uint8_t *key, uint32_t len_key,
SecurityAssociation_t *sa_ptr, const uint8_t *iv, uint32_t iv_len,
const uint8_t *mac, uint32_t mac_size, const uint8_t *aad,
uint32_t aad_len, uint8_t ecs, uint8_t acs, char *cam_cookies);
static int32_t cryptography_aead_encrypt(uint8_t *data_out, size_t len_data_out, uint8_t *data_in, size_t len_data_in,
uint8_t *key, uint32_t len_key, SecurityAssociation_t *sa_ptr, uint8_t *iv,
uint32_t iv_len, uint8_t *mac, uint32_t mac_size, uint8_t *aad,
uint32_t aad_len, uint8_t encrypt_bool, uint8_t authenticate_bool,
uint8_t aad_bool, uint8_t *ecs, uint8_t *acs, char *cam_cookies);
static int32_t cryptography_aead_decrypt(uint8_t *data_out, size_t len_data_out, uint8_t *data_in, size_t len_data_in,
uint8_t *key, uint32_t len_key, SecurityAssociation_t *sa_ptr, uint8_t *iv,
uint32_t iv_len, uint8_t *mac, uint32_t mac_size, uint8_t *aad,
uint32_t aad_len, uint8_t decrypt_bool, uint8_t authenticate_bool,
uint8_t aad_bool, uint8_t *ecs, uint8_t *acs, char *cam_cookies);
static int32_t cryptography_get_acs_algo(int8_t algo_enum);
static int32_t cryptography_get_ecs_algo(int8_t algo_enum);
// Local support functions
static int32_t get_auth_algorithm_from_acs(uint8_t acs_enum, const char **algo_ptr);
static int32_t get_cam_sso_token(void);
static int32_t initialize_kerberos_keytab_file_login(void);
static int32_t curl_perform_with_cam_retries(CURL *curl_handle, memory_write *chunk_write, memory_read *chunk_read);
// libcurl call back and support function declarations
static int32_t configure_curl_connect_opts(CURL *curl, char *cam_cookies);
static int32_t handle_cam_cookies(CURL *curl, char *cam_cookies);
static int32_t curl_response_error_check(CURL *curl, char *response);
static size_t write_callback(void *data, size_t size, size_t nmemb, void *userp);
static size_t read_callback(char *dest, size_t size, size_t nmemb, void *userp);
static char *int_to_str(uint32_t int_src, uint32_t *converted_str_length);
static int jsoneq(const char *json, jsmntok_t *tok, const char *s);
/*
** Module Variables
*/
// Cryptography Interface
static CryptographyInterfaceStruct cryptography_if_struct;
static CURL *curl;
struct curl_slist *http_headers_list;
// KMC Crypto Service Endpoints
static char *kmc_root_uri;
// static const char* status_endpoint = "/status";
static const char *encrypt_endpoint = "encrypt?keyRef=%s&transformation=%s&iv=%s";
static const char *encrypt_endpoint_null_iv = "encrypt?keyRef=%s&transformation=%s";
static const char *encrypt_offset_endpoint = "encrypt?keyRef=%s&transformation=%s&iv=%s&encryptOffset=%s&macLength=%s";
static const char *encrypt_offset_endpoint_null_iv =
"encrypt?keyRef=%s&transformation=%s&encryptOffset=%s&macLength=%s";
static const char *decrypt_endpoint = "decrypt?metadata=keyLength:%s,keyRef:%s,cipherTransformation:%s,initialVector:%"
"s,cryptoAlgorithm:%s,metadataType:EncryptionMetadata";
static const char *decrypt_offset_endpoint =
"decrypt?metadata=keyLength:%s,keyRef:%s,cipherTransformation:%s,initialVector:%s,cryptoAlgorithm:%s,macLength:%s,"
"metadataType:EncryptionMetadata,encryptOffset:%s";
static const char *icv_create_endpoint = "icv-create?keyRef=%s";
static const char *icv_verify_endpoint = "icv-verify?metadata=integrityCheckValue:%s,keyRef:%s,cryptoAlgorithm:%s,"
"macLength:%s,metadataType:IntegrityCheckMetadata";
// CAM Security Endpoints
static const char *cam_kerberos_uri = "%s/cam-api/ssoToken?loginMethod=kerberos";
// Supported KMC Cipher Transformation Strings
static const char *AES_GCM_TRANSFORMATION = "AES/GCM/NoPadding";
static const char *AES_CBC_TRANSFORMATION = "AES/CBC/PKCS5Padding";
static const char *AES_CRYPTO_ALGORITHM = "AES";
static const char *AES_CMAC_TRANSFORMATION = "AESCMAC";
static const char *HMAC_SHA256 = "HmacSHA256";
static const char *HMAC_SHA512 = "HmacSHA512";
CryptographyInterface get_cryptography_interface_kmc_crypto_service(void)
{
cryptography_if_struct.cryptography_config = cryptography_config;
cryptography_if_struct.cryptography_init = cryptography_init;
cryptography_if_struct.cryptography_shutdown = cryptography_shutdown;
cryptography_if_struct.cryptography_encrypt = cryptography_encrypt;
cryptography_if_struct.cryptography_decrypt = cryptography_decrypt;
cryptography_if_struct.cryptography_authenticate = cryptography_authenticate;
cryptography_if_struct.cryptography_validate_authentication = cryptography_validate_authentication;
cryptography_if_struct.cryptography_aead_encrypt = cryptography_aead_encrypt;
cryptography_if_struct.cryptography_aead_decrypt = cryptography_aead_decrypt;
cryptography_if_struct.cryptography_get_acs_algo = cryptography_get_acs_algo;
cryptography_if_struct.cryptography_get_ecs_algo = cryptography_get_ecs_algo;
return &cryptography_if_struct;
}
static int32_t cryptography_config(void)
{
int32_t status = CRYPTO_LIB_SUCCESS;
// Error out if Crypto_Config_Kmc_Crypto_Service(...) function was not called before intializing library.
if (cryptography_kmc_crypto_config == NULL)
{
fprintf(stderr, "You must configure the KMC Crypto Service before starting the interface!\n");
status = CRYPTOGRAPHY_KMC_CRYPTO_SERVICE_CONFIGURATION_NOT_COMPLETE;
return status;
}
if (curl)
{
// Determine length of port and convert to string for use in URL
uint32_t port_str_len = 0;
char *port_str = int_to_str(cryptography_kmc_crypto_config->kmc_crypto_port, &port_str_len);
// Form Root URI
// len(protocol)+len(://)+len(hostname)+ len(:) + len(port_str) + len(/) + len(app_uri) + strlen('\0')
uint32_t len_root_uri = strlen(cryptography_kmc_crypto_config->protocol) + 3 + // "://"
strlen(cryptography_kmc_crypto_config->kmc_crypto_hostname) + 1 + // ":"
port_str_len + 1 + // "/"
strlen(cryptography_kmc_crypto_config->kmc_crypto_app_uri) + 2; // "/\0"
kmc_root_uri = malloc(len_root_uri);
snprintf(kmc_root_uri, len_root_uri, "%s://%s:%s/%s/", cryptography_kmc_crypto_config->protocol,
cryptography_kmc_crypto_config->kmc_crypto_hostname, port_str,
cryptography_kmc_crypto_config->kmc_crypto_app_uri);
free(port_str);
// KMC Crypto Service status check is impossible in certain CAM configs, commenting it out.
// Also, when this library is started up (EG by SDLS service), there's no guarantee the Crypto Service is
// available at config time.
// char* status_uri = (char*) malloc(strlen(kmc_root_uri)+strlen(status_endpoint) + 1);
// status_uri[0] = '\0';
// strcat(status_uri, kmc_root_uri);
// strcat(status_uri, status_endpoint);
#ifdef DEBUG
printf("Setting up cURL connection to KMC Crypto Service with Params:\n");
printf("\tKMC Root URI: %s\n", kmc_root_uri);
// printf("\tKMC Status URL: %s\n",status_uri);
// printf("\tPort: %d\n",cryptography_kmc_crypto_config->kmc_crypto_port);
printf("\tSSL Client Cert: %s\n", cryptography_kmc_crypto_config->mtls_client_cert_path);
printf("\tSSL Client Key: %s\n", cryptography_kmc_crypto_config->mtls_client_key_path);
printf("\tSSL CA Bundle: %s\n", cryptography_kmc_crypto_config->mtls_ca_bundle);
#endif
}
return status;
}
static int32_t cryptography_init(void)
{
#ifdef DEBUG
printf(KYEL "Initializing KMC...\n" RESET);
#endif
int32_t status = CRYPTO_LIB_SUCCESS;
curl = curl_easy_init();
curl_global_init(CURL_GLOBAL_ALL);
http_headers_list = NULL;
// Prepare HTTP headers list
http_headers_list = curl_slist_append(http_headers_list, "Content-Type: application/octet-stream");
if (curl == NULL)
{
status = CRYPTOGRAPHY_KMC_CURL_INITIALIZATION_FAILURE;
}
kmc_root_uri = NULL;
return status;
}
static int32_t cryptography_shutdown(void)
{
if (curl)
{
curl_easy_cleanup(curl);
curl_global_cleanup();
}
if (http_headers_list != NULL)
{
curl_slist_free_all(http_headers_list);
}
if (kmc_root_uri != NULL)
{
free(kmc_root_uri);
}
return CRYPTO_LIB_SUCCESS;
}
static int32_t cryptography_encrypt(uint8_t *data_out, size_t len_data_out, uint8_t *data_in, size_t len_data_in,
uint8_t *key, uint32_t len_key, SecurityAssociation_t *sa_ptr, uint8_t *iv,
uint32_t iv_len, uint8_t *ecs, uint8_t padding, char *cam_cookies)
{
int32_t status = CRYPTO_LIB_SUCCESS;
key = key; // Direct key input is not supported in KMC interface
len_key = len_key; // Direct key input is not supported in KMC interface
// Remove pre-padding to block (KMC does not want it)
if (*ecs == CRYPTO_CIPHER_AES256_CBC && padding > 0)
{
len_data_in = len_data_in - padding;
}
#ifdef DEBUG
printf("PADLENGTH FIELD: 0x%02x\n", *(data_in - sa_ptr->shplf_len));
#endif
curl_easy_reset(curl);
status = configure_curl_connect_opts(curl, cam_cookies);
if (status != CRYPTO_LIB_SUCCESS)
{
return status;
}
// Base64 URL encode IV for KMC REST Encrypt
char *iv_base64 = (char *)calloc(1, B64ENCODE_OUT_SAFESIZE(iv_len) + 1);
if (iv != NULL)
base64urlEncode(iv, iv_len, iv_base64, NULL);
uint8_t *encrypt_payload = data_in;
size_t encrypt_payload_len = len_data_in;
#ifdef DEBUG
printf("IV Base64 URL Encoded: %s\n", iv_base64);
#endif
if (sa_ptr->ek_ref[0] == '\0')
{
status = CRYPTOGRAHPY_KMC_NULL_ENCRYPTION_KEY_REFERENCE_IN_SA;
return status;
}
char *encrypt_uri;
int len_encrypt_endpoint =
strlen(encrypt_endpoint) + strlen(sa_ptr->ek_ref) + strlen(iv_base64) + strlen(AES_CBC_TRANSFORMATION);
char *encrypt_endpoint_final = (char *)malloc(len_encrypt_endpoint);
if (iv == NULL)
{
snprintf(encrypt_endpoint_final, len_encrypt_endpoint, encrypt_endpoint_null_iv, sa_ptr->ek_ref,
AES_CBC_TRANSFORMATION);
}
else
{
snprintf(encrypt_endpoint_final, len_encrypt_endpoint, encrypt_endpoint, sa_ptr->ek_ref, AES_CBC_TRANSFORMATION,
iv_base64);
}
encrypt_uri = (char *)malloc(strlen(kmc_root_uri) + len_encrypt_endpoint);
encrypt_uri[0] = '\0';
strcat(encrypt_uri, kmc_root_uri);
strcat(encrypt_uri, encrypt_endpoint_final);
#ifdef DEBUG
printf("Encrypt URI: %s\n", encrypt_uri);
#endif
curl_easy_setopt(curl, CURLOPT_URL, encrypt_uri);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_headers_list);
memory_write *chunk_write = (memory_write *)calloc(1, MEMORY_WRITE_SIZE);
memory_read *chunk_read = (memory_read *)calloc(1, MEMORY_READ_SIZE);
;
/* Configure CURL for POST */
curl_easy_setopt(curl, CURLOPT_POST, 1L);
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_READDATA, chunk_read);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, chunk_write);
/* size of the POST data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)encrypt_payload_len);
/* binary data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, encrypt_payload);
#ifdef DEBUG
printf("Data to Encrypt: \n");
for (uint32_t i = 0; i < encrypt_payload_len; i++)
{
printf("%02x ", encrypt_payload[i]);
}
printf("\n");
#endif
status = curl_perform_with_cam_retries(curl, chunk_write, chunk_read);
if (status != CRYPTO_LIB_SUCCESS)
{
return status;
}
/* JSON Response Handling */
// Parse the JSON string response
jsmn_parser p;
jsmntok_t t[64]; /* We expect no more than 64 JSON tokens */
jsmn_init(&p);
int parse_result = jsmn_parse(&p, chunk_write->response, strlen(chunk_write->response), t,
64); // "chunk->response" is the char array holding the json content
// Find the 'base64ciphertext' token
if (parse_result < 0)
{
status = CRYPTOGRAHPY_KMC_CRYPTO_JSON_PARSE_ERROR;
printf("Failed to parse JSON: %d\n", parse_result);
return status;
}
int json_idx = 0;
uint8_t ciphertext_found = CRYPTO_FALSE;
char *ciphertext_base64 = NULL;
char *ciphertext_IV_base64 = NULL;
for (json_idx = 1; json_idx < parse_result; json_idx++)
{
if (jsoneq(chunk_write->response, &t[json_idx], "metadata") == 0)
{
uint32_t len_ciphertext = t[json_idx + 1].end - t[json_idx + 1].start;
ciphertext_IV_base64 = malloc(len_ciphertext + 1);
memcpy(ciphertext_IV_base64, chunk_write->response + t[json_idx + 1].start, len_ciphertext);
ciphertext_IV_base64[len_ciphertext] = '\0';
char *line;
char *token;
char temp_buff[256];
for (line = strtok(ciphertext_IV_base64, ","); line != NULL; line = strtok(line + strlen(line) + 1, ","))
{
strncpy(temp_buff, line, sizeof(temp_buff));
for (token = strtok(temp_buff, ":"); token != NULL; token = strtok(token + strlen(token) + 1, ":"))
{
if (strcmp(token, "initialVector") == 0)
{
token = strtok(token + strlen(token) + 1, ":");
char *ciphertext_token_base64 = malloc(strlen(token));
size_t cipher_text_token_len = strlen(token);
memcpy(ciphertext_token_base64, token, cipher_text_token_len);
#ifdef DEBUG
printf("IV LENGTH: %d\n", iv_len);
printf("IV ENCODED Text: %s\nIV ENCODED TEXT LEN: %ld\n", ciphertext_token_base64,
cipher_text_token_len);
#endif
char *iv_decoded = malloc((iv_len)*2 + 1);
size_t iv_decoded_len = 0;
base64urlDecode(ciphertext_token_base64, cipher_text_token_len, iv_decoded, &iv_decoded_len);
#ifdef DEBUG
printf("Decoded IV Text Length: %ld\n", iv_decoded_len);
printf("Decoded IV Text: \n");
for (uint32_t i = 0; i < iv_decoded_len; i++)
{
printf("%02x ", (uint8_t)iv_decoded[i]);
}
printf("\n");
#endif
if (iv == NULL)
{
memcpy(data_out - sa_ptr->shsnf_len - sa_ptr->shivf_len - sa_ptr->shplf_len, iv_decoded,
iv_decoded_len);
}
free(ciphertext_token_base64);
break;
}
}
}
json_idx++;
continue;
}
if (jsoneq(chunk_write->response, &t[json_idx], "base64ciphertext") == 0)
{
/* We may use strndup() to fetch string value */
#ifdef DEBUG
printf("Json base64ciphertext: %.*s\n", t[json_idx + 1].end - t[json_idx + 1].start,
chunk_write->response + t[json_idx + 1].start);
#endif
uint32_t len_ciphertext = t[json_idx + 1].end - t[json_idx + 1].start;
ciphertext_base64 = malloc(len_ciphertext + 1);
memcpy(ciphertext_base64, chunk_write->response + t[json_idx + 1].start, len_ciphertext);
ciphertext_base64[len_ciphertext] = '\0';
#ifdef DEBUG
printf("Parsed base64ciphertext: %s\n", ciphertext_base64);
#endif
json_idx++;
ciphertext_found = CRYPTO_TRUE;
continue;
}
if (jsoneq(chunk_write->response, &t[json_idx], "httpCode") == 0)
{
/* We may use strndup() to fetch string value */
#ifdef DEBUG
printf("httpCode: %.*s\n", t[json_idx + 1].end - t[json_idx + 1].start,
chunk_write->response + t[json_idx + 1].start);
#endif
uint32_t len_httpcode = t[json_idx + 1].end - t[json_idx + 1].start;
char *http_code_str = malloc(len_httpcode + 1);
memcpy(http_code_str, chunk_write->response + t[json_idx + 1].start, len_httpcode);
http_code_str[len_httpcode] = '\0';
int http_code = atoi(http_code_str);
#ifdef DEBUG
printf("Parsed http code: %d\n", http_code);
#endif
if (http_code != 200)
{
status = CRYPTOGRAHPY_KMC_CRYPTO_SERVICE_GENERIC_FAILURE;
fprintf(stderr, "KMC Crypto Failure Response:\n%s\n", chunk_write->response);
return status;
}
free(http_code_str);
json_idx++;
continue;
}
}
if (ciphertext_found == CRYPTO_FALSE)
{
status = CRYPTOGRAHPY_KMC_CIPHER_TEXT_NOT_FOUND_IN_JSON_RESPONSE;
return status;
}
/* JSON Response Handling End */
uint8_t *ciphertext_decoded = malloc((len_data_out)*2 + 1);
size_t ciphertext_decoded_len = 0;
base64Decode(ciphertext_base64, strlen(ciphertext_base64), ciphertext_decoded, &ciphertext_decoded_len);
#ifdef DEBUG
printf("Decoded Cipher Text Length: %ld\n", ciphertext_decoded_len);
printf("Decoded Cipher Text: \n");
printf("Data Out Len: %ld\n", len_data_out);
for (uint32_t i = 0; i < ciphertext_decoded_len; i++)
{
printf("%02x ", ciphertext_decoded[i]);
}
printf("\n");
#endif
// Crypto Service returns aad - cipher_text - tag
memcpy(data_out, ciphertext_decoded, ciphertext_decoded_len);
return status;
}
static int32_t cryptography_decrypt(uint8_t *data_out, size_t len_data_out, uint8_t *data_in, size_t len_data_in,
uint8_t *key, uint32_t len_key, SecurityAssociation_t *sa_ptr, uint8_t *iv,
uint32_t iv_len, uint8_t *ecs, uint8_t *acs, char *cam_cookies)
{
int32_t status = CRYPTO_LIB_SUCCESS;
key = key; // Direct key input is not supported in KMC interface
ecs = ecs;
acs = acs;
// Get the key length in bits, in string format.
// TODO -- Parse the key length from the keyInfo endpoint of the Crypto Service!
uint32_t key_len_in_bits = len_key * 8; // 8 bits per byte.
uint32_t key_len_in_bits_str_len = 0;
char *key_len_in_bits_str = int_to_str(key_len_in_bits, &key_len_in_bits);
curl_easy_reset(curl);
status = configure_curl_connect_opts(curl, cam_cookies);
if (status != CRYPTO_LIB_SUCCESS)
{
return status;
}
// Base64 URL encode IV for KMC REST Encrypt
char *iv_base64 = (char *)calloc(1, B64ENCODE_OUT_SAFESIZE(iv_len) + 1);
base64urlEncode(iv, iv_len, iv_base64, NULL);
uint8_t *decrypt_payload = data_in;
size_t decrypt_payload_len = len_data_in;
#ifdef DEBUG
printf("IV Base64 URL Encoded: %s\n", iv_base64);
#endif
if (sa_ptr->ek_ref[0] == '\0')
{
status = CRYPTOGRAHPY_KMC_NULL_ENCRYPTION_KEY_REFERENCE_IN_SA;
return status;
}
char *decrypt_uri;
int len_decrypt_endpoint = strlen(decrypt_endpoint) + key_len_in_bits_str_len + strlen(sa_ptr->ek_ref) +
strlen(iv_base64) + strlen(AES_CBC_TRANSFORMATION) + strlen(AES_CRYPTO_ALGORITHM);
char *decrypt_endpoint_final = (char *)malloc(len_decrypt_endpoint);
snprintf(decrypt_endpoint_final, len_decrypt_endpoint, decrypt_endpoint, key_len_in_bits_str, sa_ptr->ek_ref,
AES_CBC_TRANSFORMATION, iv_base64, AES_CRYPTO_ALGORITHM);
free(key_len_in_bits_str);
decrypt_uri = (char *)malloc(strlen(kmc_root_uri) + len_decrypt_endpoint);
decrypt_uri[0] = '\0';
strcat(decrypt_uri, kmc_root_uri);
strcat(decrypt_uri, decrypt_endpoint_final);
#ifdef DEBUG
printf("Decrypt URI: %s\n", decrypt_uri);
#endif
curl_easy_setopt(curl, CURLOPT_URL, decrypt_uri);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_headers_list);
memory_write *chunk_write = (memory_write *)calloc(1, MEMORY_WRITE_SIZE);
memory_read *chunk_read = (memory_read *)calloc(1, MEMORY_READ_SIZE);
;
/* Configure CURL for POST */
curl_easy_setopt(curl, CURLOPT_POST, 1L);
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_READDATA, chunk_read);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, chunk_write);
/* size of the POST data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)decrypt_payload_len);
/* binary data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, decrypt_payload);
#ifdef DEBUG
printf("Len of decrypt payload: %ld\n", decrypt_payload_len);
printf("Data to Decrypt: \n");
for (uint32_t i = 0; i < decrypt_payload_len; i++)
{
printf("%02x ", decrypt_payload[i]);
}
printf("\n");
#endif
status = curl_perform_with_cam_retries(curl, chunk_write, chunk_read);
if (status != CRYPTO_LIB_SUCCESS)
{
return status;
}
/* JSON Response Handling */
// Parse the JSON string response
jsmn_parser p;
jsmntok_t t[64]; /* We expect no more than 64 JSON tokens */
jsmn_init(&p);
int parse_result = jsmn_parse(&p, chunk_write->response, strlen(chunk_write->response), t,
64); // "chunk->response" is the char array holding the json content
// Find the 'base64ciphertext' token
if (parse_result < 0)
{
status = CRYPTOGRAHPY_KMC_CRYPTO_JSON_PARSE_ERROR;
printf("Failed to parse JSON: %d\n", parse_result);
return status;
}
int json_idx = 0;
uint8_t ciphertext_found = CRYPTO_FALSE;
char *cleartext_base64 = NULL;
for (json_idx = 1; json_idx < parse_result; json_idx++)
{
// check "httpCode" field for non-200 status codes!!!
if (jsoneq(chunk_write->response, &t[json_idx], "base64cleartext") == 0)
{
/* We may use strndup() to fetch string value */
#ifdef DEBUG
printf("Json base64cleartext: %.*s\n", t[json_idx + 1].end - t[json_idx + 1].start,
chunk_write->response + t[json_idx + 1].start);
#endif
uint32_t len_cleartext = t[json_idx + 1].end - t[json_idx + 1].start;
cleartext_base64 = malloc(len_cleartext + 1);
memcpy(cleartext_base64, chunk_write->response + t[json_idx + 1].start, len_cleartext);
cleartext_base64[len_cleartext] = '\0';
#ifdef DEBUG
printf("Parsed base64cleartext: %s\n", cleartext_base64);
#endif
json_idx++;
ciphertext_found = CRYPTO_TRUE;
continue;
}
if (jsoneq(chunk_write->response, &t[json_idx], "httpCode") == 0)
{
/* We may use strndup() to fetch string value */
#ifdef DEBUG
printf("httpCode: %.*s\n", t[json_idx + 1].end - t[json_idx + 1].start,
chunk_write->response + t[json_idx + 1].start);
#endif
uint32_t len_httpcode = t[json_idx + 1].end - t[json_idx + 1].start;
char *http_code_str = malloc(len_httpcode + 1);
memcpy(http_code_str, chunk_write->response + t[json_idx + 1].start, len_httpcode);
http_code_str[len_httpcode] = '\0';
int http_code = atoi(http_code_str);
#ifdef DEBUG
printf("Parsed http code: %d\n", http_code);
#endif
if (http_code != 200)
{
status = CRYPTOGRAHPY_KMC_CRYPTO_SERVICE_GENERIC_FAILURE;
fprintf(stderr, "KMC Crypto Failure Response:\n%s\n", chunk_write->response);
return status;
}
free(http_code_str);
json_idx++;
continue;
}
}
if (ciphertext_found == CRYPTO_FALSE)
{
status = CRYPTOGRAHPY_KMC_CIPHER_TEXT_NOT_FOUND_IN_JSON_RESPONSE;
return status;
}
/* JSON Response Handling End */
uint8_t *cleartext_decoded = malloc((len_data_out)*2 + 1);
size_t cleartext_decoded_len = 0;
base64Decode(cleartext_base64, strlen(cleartext_base64), cleartext_decoded, &cleartext_decoded_len);
#ifdef DEBUG
printf("Decoded Cipher Text Length: %ld\n", cleartext_decoded_len);
printf("Decoded Cipher Text: \n");
for (uint32_t i = 0; i < cleartext_decoded_len; i++)
{
printf("%02x ", cleartext_decoded[i]);
}
printf("\n");
#endif
// Copy the decrypted data to the output stream
// Crypto Service returns aad - clear_text
memcpy(data_out, cleartext_decoded, len_data_out);
return status;
}
static int32_t cryptography_authenticate(uint8_t *data_out, size_t len_data_out, uint8_t *data_in, size_t len_data_in,
uint8_t *key, uint32_t len_key, SecurityAssociation_t *sa_ptr, uint8_t *iv,
uint32_t iv_len, uint8_t *mac, uint32_t mac_size, uint8_t *aad,
uint32_t aad_len, uint8_t ecs, uint8_t acs, char *cam_cookies)
{
int32_t status = CRYPTO_LIB_SUCCESS;
// Unneeded cryptography interface vars for current implementation
len_data_out = len_data_out;
key = key;
len_key = len_key;
iv = iv;
iv_len = iv_len;
ecs = ecs;
curl_easy_reset(curl);
status = configure_curl_connect_opts(curl, cam_cookies);
if (status != CRYPTO_LIB_SUCCESS)
{
return status;
}
// Base64 URL encode IV for KMC REST Encrypt
// Not needed for CMAC/HMAC (only supported auth ciphers now)
// char* iv_base64 = (char*)calloc(1,B64ENCODE_OUT_SAFESIZE(iv_len)+1);
// base64urlEncode(iv,iv_len,iv_base64,NULL);
uint8_t *auth_payload = aad;
size_t auth_payload_len = aad_len;
// Verify valid acs enum
int32_t algo = cryptography_get_acs_algo(acs);
if (algo == CRYPTO_LIB_ERR_UNSUPPORTED_ACS)
{
return CRYPTO_LIB_ERR_UNSUPPORTED_ACS;
}
// Need to copy the data over, since authentication won't change/move the data directly
if (data_out != NULL)
{
memcpy(data_out, data_in, len_data_in);
}
else
{
return CRYPTO_LIB_ERR_NULL_BUFFER;
}
if (sa_ptr->ak_ref[0] == '\0')
{
status = CRYPTOGRAHPY_KMC_NULL_AUTHENTICATION_KEY_REFERENCE_IN_SA;
return status;
}
// Prepare the Authentication Endpoint URI for KMC Crypto Service
int len_auth_endpoint = strlen(icv_create_endpoint) + strlen(sa_ptr->ak_ref);
char *auth_endpoint_final = (char *)malloc(len_auth_endpoint);
snprintf(auth_endpoint_final, len_auth_endpoint, icv_create_endpoint, sa_ptr->ak_ref);
char *auth_uri = (char *)malloc(strlen(kmc_root_uri) + len_auth_endpoint);
auth_uri[0] = '\0';
strcat(auth_uri, kmc_root_uri);
strcat(auth_uri, auth_endpoint_final);
#ifdef DEBUG
printf("Authentication URI: %s\n", auth_uri);
#endif
curl_easy_setopt(curl, CURLOPT_URL, auth_uri);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_headers_list);
memory_write *chunk_write = (memory_write *)calloc(1, MEMORY_WRITE_SIZE);
memory_read *chunk_read = (memory_read *)calloc(1, MEMORY_READ_SIZE);
;
/* Configure CURL for POST */
curl_easy_setopt(curl, CURLOPT_POST, 1L);
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_READDATA, chunk_read);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_WRITEDATA, chunk_write);
/* size of the POST data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)auth_payload_len);
/* binary data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, auth_payload);
#ifdef DEBUG
printf("Authentication Payload Length: %ld\n", auth_payload_len);
printf("Data to Authenticate: \n");
for (uint32_t i = 0; i < auth_payload_len; i++)
{
printf("%02x ", auth_payload[i]);
}
printf("\n");
#endif
status = curl_perform_with_cam_retries(curl, chunk_write, chunk_read);
if (status != CRYPTO_LIB_SUCCESS)
{
return status;
}
/* JSON Response Handling */
// Parse the JSON string response
jsmn_parser p;
jsmntok_t t[64]; /* We expect no more than 64 JSON tokens */
jsmn_init(&p);
int parse_result = jsmn_parse(&p, chunk_write->response, strlen(chunk_write->response), t,
64); // "chunk->response" is the char array holding the json content
// Find the 'integrityCheckValue' token
if (parse_result < 0)
{
status = CRYPTOGRAHPY_KMC_CRYPTO_JSON_PARSE_ERROR;
printf("Failed to parse JSON: %d\n", parse_result);
return status;
}
int json_idx = 0;
uint8_t icvtext_found = CRYPTO_FALSE;
char *icv_base64 = NULL;
for (json_idx = 1; json_idx < parse_result; json_idx++)
{
if (jsoneq(chunk_write->response, &t[json_idx], "metadata") == 0)
{
/* We may use strndup() to fetch string value */
#ifdef DEBUG
printf("Json metadata: %.*s\n", t[json_idx + 1].end - t[json_idx + 1].start,
chunk_write->response + t[json_idx + 1].start);
#endif
// search through metadata string for base64 ICV end idx:
// Format:
// "integrityCheckValue:xQgnkVrrQj8FRALV3DxnVg==,keyRef:kmc/test/nist_cmac_90,cryptoAlgorithm:AESCMAC,metadataType:IntegrityCheckMetadata"
uint32_t len_metadata = t[json_idx + 1].end - t[json_idx + 1].start;
char *metadata = malloc(len_metadata + 1);
char *metadata_end = &metadata[len_metadata];
memcpy(metadata, chunk_write->response + t[json_idx + 1].start, len_metadata);
char *key = "";
size_t colon_idx;
size_t comma_idx;
while (CRYPTO_TRUE)
{
colon_idx = strcspn(metadata, ":");
comma_idx = strcspn(metadata, ",");
key = malloc(colon_idx + 1);
strncpy(key, metadata, colon_idx);
key[colon_idx] = '\0';
#ifdef DEBUG
printf("Found key in metadata: %s\n", key);
#endif
if (strcmp(key, "integrityCheckValue") == 0)
{
break; // key found!
}
if (strcmp(key, "integrityCheckValue") != 0)
{
metadata += comma_idx + 1;
if (metadata >= metadata_end)
{
status = CRYPTOGRAHPY_KMC_ICV_NOT_FOUND_IN_JSON_RESPONSE;
return status;
}
}
}
metadata += colon_idx + 1;
comma_idx = strcspn(metadata, ",");
icv_base64 = malloc(comma_idx + 1);
strncpy(icv_base64, metadata, comma_idx);
icv_base64[comma_idx] = '\0';
#ifdef DEBUG
printf("Parsed integrityCheckValue: %s\n", icv_base64);
#endif
json_idx++;
icvtext_found = CRYPTO_TRUE;
continue;
}
if (jsoneq(chunk_write->response, &t[json_idx], "httpCode") == 0)
{
/* We may use strndup() to fetch string value */
#ifdef DEBUG
printf("httpCode: %.*s\n", t[json_idx + 1].end - t[json_idx + 1].start,
chunk_write->response + t[json_idx + 1].start);
#endif
uint32_t len_httpcode = t[json_idx + 1].end - t[json_idx + 1].start;
char *http_code_str = malloc(len_httpcode + 1);
memcpy(http_code_str, chunk_write->response + t[json_idx + 1].start, len_httpcode);
http_code_str[len_httpcode] = '\0';
int http_code = atoi(http_code_str);
#ifdef DEBUG
printf("Parsed http code: %d\n", http_code);
#endif
if (http_code != 200)
{
status = CRYPTOGRAHPY_KMC_CRYPTO_SERVICE_GENERIC_FAILURE;
fprintf(stderr, "KMC Crypto Failure Response:\n%s\n", chunk_write->response);
return status;
}
json_idx++;
free(http_code_str);
continue;
}
}
if (icvtext_found == CRYPTO_FALSE)
{
status = CRYPTOGRAHPY_KMC_ICV_NOT_FOUND_IN_JSON_RESPONSE;
return status;
}
/* JSON Response Handling End */
// https://stackoverflow.com/questions/13378815/base64-length-calculation
uint8_t *icv_decoded = calloc(1, B64DECODE_OUT_SAFESIZE(strlen(icv_base64)) + 1);
size_t icv_decoded_len = 0;
base64urlDecode(icv_base64, strlen(icv_base64), icv_decoded, &icv_decoded_len);
#ifdef DEBUG
printf("Mac size: %d\n", mac_size);
printf("Decoded ICV Length: %ld\n", icv_decoded_len);
printf("Decoded ICV Text: \n");
for (uint32_t i = 0; i < icv_decoded_len; i++)
{
printf("%02x ", icv_decoded[i]);
}
printf("\n");
#endif
memcpy(mac, icv_decoded, mac_size);
return status;
}
static int32_t cryptography_validate_authentication(uint8_t *data_out, size_t len_data_out, const uint8_t *data_in,
const size_t len_data_in, uint8_t *key, uint32_t len_key,
SecurityAssociation_t *sa_ptr, const uint8_t *iv, uint32_t iv_len,
const uint8_t *mac, uint32_t mac_size, const uint8_t *aad,
uint32_t aad_len, uint8_t ecs, uint8_t acs, char *cam_cookies)
{
int32_t status = CRYPTO_LIB_SUCCESS;
// Unneeded cryptography interface vars for current implementation
len_data_out = len_data_out;
key = key;
len_key = len_key;
iv = iv;
iv_len = iv_len;
ecs = ecs;
// Verify valid acs enum
int32_t algo = cryptography_get_acs_algo(acs);
if (algo == CRYPTO_LIB_ERR_UNSUPPORTED_ACS)
{
return CRYPTO_LIB_ERR_UNSUPPORTED_ACS;
}
// Need to copy the data over, since authentication won't change/move the data directly
if (data_out != NULL)
{
memcpy(data_out, data_in, len_data_in);
}
else
{
return CRYPTO_LIB_ERR_NULL_BUFFER;
}
curl_easy_reset(curl);
status = configure_curl_connect_opts(curl, cam_cookies);
if (status != CRYPTO_LIB_SUCCESS)
{
return status;
}
const uint8_t *auth_payload = aad;
size_t auth_payload_len = aad_len;
// Base64 URL encode MAC for KMC REST Encrypt
char *mac_base64 = (char *)calloc(1, B64ENCODE_OUT_SAFESIZE(mac_size) + 1);
base64urlEncode(mac, mac_size, mac_base64, NULL);
#ifdef DEBUG
printf("MAC Base64 URL Encoded: %s\n", mac_base64);
printf("Hex Mac:\n");
Crypto_hexprint(mac, mac_size);
#endif
if (sa_ptr->ak_ref[0] == '\0')
{
status = CRYPTOGRAHPY_KMC_NULL_AUTHENTICATION_KEY_REFERENCE_IN_SA;
return status;
}
const char *auth_algorithm = NULL;
get_auth_algorithm_from_acs(acs, &auth_algorithm);
uint32_t mac_size_str_len = 0;
char *mac_size_str = int_to_str(mac_size * 8, &mac_size_str_len);
// Prepare the Authentication Endpoint URI for KMC Crypto Service
int len_auth_endpoint = strlen(icv_verify_endpoint) + strlen(mac_base64) + strlen(sa_ptr->ak_ref) +
strlen(auth_algorithm) + mac_size_str_len;
char *auth_endpoint_final = (char *)malloc(len_auth_endpoint);
snprintf(auth_endpoint_final, len_auth_endpoint, icv_verify_endpoint, mac_base64, sa_ptr->ak_ref, auth_algorithm,
mac_size_str);
free(mac_size_str);
char *auth_uri = (char *)malloc(strlen(kmc_root_uri) + len_auth_endpoint);
auth_uri[0] = '\0';
strcat(auth_uri, kmc_root_uri);
strcat(auth_uri, auth_endpoint_final);
#ifdef DEBUG
printf("Authentication Verification URI: %s\n", auth_uri);
#endif
curl_easy_setopt(curl, CURLOPT_URL, auth_uri);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_headers_list);
memory_write *chunk_write = (memory_write *)calloc(1, MEMORY_WRITE_SIZE);
memory_read *chunk_read = (memory_read *)calloc(1, MEMORY_READ_SIZE);
;
/* Configure CURL for POST */
curl_easy_setopt(curl, CURLOPT_POST, 1L);
/* send all data to this function */
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
/* we pass our 'chunk' struct to the callback function */
curl_easy_setopt(curl, CURLOPT_READDATA, chunk_read);