-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathcertifier.c
More file actions
1551 lines (1256 loc) · 46.7 KB
/
certifier.c
File metadata and controls
1551 lines (1256 loc) · 46.7 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 2019 Comcast Cable Communications Management, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "certifier/base64.h"
#include "certifier/log.h"
#include "certifier/util.h"
#include "certifier/certifier.h"
#include "certifier/certifier_internal.h"
#include "certifier/certifierclient.h"
#include "certifier/error.h"
#include "certifier/parson.h"
#include "certifier/property.h"
#include "certifier/property_internal.h"
#include "certifier/system.h"
#include "certifier/timer.h"
#include "curl/curl.h"
#ifndef CERTIFIER_VERSION
#define CERTIFIER_VERSION "0.1-071320 (opensource)"
#endif
#define PEM_BEGIN_CERTIFICATE "-----BEGIN CERTIFICATE-----"
#define PEM_BEGIN_CERTIFICATE_LENGTH 27
#define PEM_END_CERTIFICATE "-----END CERTIFICATE-----"
#define PEM_END_CERTIFICATE_LENGTH 25
static CERTIFIER_LOG_callback logger;
typedef struct Map
{
char node_address[SMALL_STRING_SIZE];
char * base64_public_key;
unsigned char * der_public_key;
int der_public_key_len;
ECC_KEY * private_ec_key;
X509_CERT * x509_cert;
} Map;
struct Certifier
{
CertifierPropMap * prop_map;
Map tmp_map;
CertifierError last_error;
};
static inline void free_tmp(Certifier * certifier);
static inline void assign_last_error(Certifier * certifier, CertifierError * error);
/**
* @param certifier
* @param error_code
* @param error_string A heap allocated string. Be sure to XSTRDUP() any constants
*/
static void set_last_error(Certifier * certifier, const int error_code, char * error_string);
/**
* Load certificate info
* @pre This device is registered
* @pre CERTIFIER_OPT_INPUT_P12_PATH is set to a valid pkcs#12 file
* @pre CERTIFIER_OPT_INPUT_P12_PASSWORD is set
* @post tmp_map.x509_cert is set
* @post last error info is set on failure
* @return 0 on success or an error code
*/
static int load_cert(Certifier * certifier);
static const X509_CERT * get_cert(Certifier * certifier)
{
if (certifier->tmp_map.x509_cert == NULL)
{
if (load_cert(certifier) != 0)
{
return NULL;
}
}
return certifier->tmp_map.x509_cert;
}
const ECC_KEY * _certifier_get_privkey(Certifier * certifier)
{
if (certifier->tmp_map.private_ec_key == NULL)
{
if (certifier_setup_keys(certifier) != 0)
{
return NULL;
}
}
return certifier->tmp_map.private_ec_key;
}
int certifier_set_keys_and_node_address_with_cn_prefix(Certifier * certifier, ECC_KEY * new_key, char * cn_prefix,
CertifierError rc)
{
int return_code = 0;
char * tmp_node_address = NULL;
security_free_eckey(certifier->tmp_map.private_ec_key);
certifier->tmp_map.private_ec_key = new_key;
assign_last_error(certifier, &rc);
return_code = rc.application_error_code;
if (rc.application_error_code != 0)
{
return_code = CERTIFIER_ERR_SETUP_ECKEY_FAILURE;
char * err_json = util_format_error(
"setup_keys", "propMap.ecKey is null. This was most likely because the .p12 existed with a different pwd?", __FILE__,
__LINE__);
set_last_error(certifier, return_code, err_json);
goto cleanup;
}
(void) load_cert(certifier);
// Save public key
XFREE(certifier->tmp_map.der_public_key);
certifier->tmp_map.der_public_key = NULL;
certifier->tmp_map.der_public_key_len =
security_serialize_der_public_key(certifier->tmp_map.private_ec_key, &certifier->tmp_map.der_public_key);
if (certifier->tmp_map.der_public_key_len == 0)
goto cleanup;
XFREE(certifier->tmp_map.base64_public_key);
certifier->tmp_map.base64_public_key = XMALLOC(base64_encode_len(certifier->tmp_map.der_public_key_len));
if (certifier->tmp_map.base64_public_key == NULL)
{
set_last_error(certifier, return_code,
"Could not allocate enough memory for "
"certifier->tmp_map.base64_public_key");
goto cleanup;
}
base64_encode(certifier->tmp_map.base64_public_key, certifier->tmp_map.der_public_key, certifier->tmp_map.der_public_key_len);
if (util_is_not_empty(cn_prefix))
{
strncpy(certifier->tmp_map.node_address, cn_prefix, sizeof(certifier->tmp_map.node_address) - 1);
}
else
{
// Create Node Address based on public key DER format
XMEMSET(certifier->tmp_map.node_address, 0, sizeof(certifier->tmp_map.node_address));
return_code = certifier_create_node_address(certifier->tmp_map.der_public_key, certifier->tmp_map.der_public_key_len,
&tmp_node_address);
if ((util_is_empty(tmp_node_address)) || (return_code != 0))
{
return_code = CERTIFIER_ERR_SETUP_INTERNAL_NODE_ADDRESS_2;
char * err_json = util_format_error("setup_keys", "Internal error. tmpNodeAddress is NULL!", __FILE__, __LINE__);
set_last_error(certifier, return_code, err_json);
goto cleanup;
}
XSTRNCPY(certifier->tmp_map.node_address, tmp_node_address, sizeof(certifier->tmp_map.node_address) - 1);
certifier->tmp_map.node_address[sizeof(certifier->tmp_map.node_address) - 1] = '\0';
}
log_debug("\nNode Address: %s\n", certifier->tmp_map.node_address);
// Clean up
cleanup:
XFREE(tmp_node_address);
return return_code;
}
/* createKeys */
int certifier_setup_keys(Certifier * certifier)
{
NULL_CHECK(certifier);
CertifierError rc = CERTIFIER_ERROR_INITIALIZER;
int return_code = 0;
char * tmp_node_address = NULL;
const char * p12_filename = certifier_get_property(certifier, CERTIFIER_OPT_INPUT_P12_PATH);
const char * password = certifier_get_property(certifier, CERTIFIER_OPT_INPUT_P12_PASSWORD);
const char * ecc_curve_id = certifier_get_property(certifier, CERTIFIER_OPT_ECC_CURVE_ID);
char * cn_prefix = certifier_get_property(certifier, CERTIFIER_OPT_CN_PREFIX);
ECC_KEY * new_key = NULL;
if (util_is_empty(p12_filename))
{
return_code = CERTIFIER_ERR_SETUP_EMPTY_FILENAME;
goto cleanup;
}
if (util_is_empty(password))
{
return_code = CERTIFIER_ERR_SETUP_EMPTY_PASSWORD;
goto cleanup;
}
if (util_is_empty(ecc_curve_id))
{
return_code = CERTIFIER_ERR_SETUP_EMPTY_ECC_CURVE;
goto cleanup;
}
// Get or Create the Elliptical Curve Keys
rc = security_find_or_create_keys(certifier->prop_map, p12_filename, password, NULL, ecc_curve_id, &new_key);
return_code = certifier_set_keys_and_node_address_with_cn_prefix(certifier, new_key, cn_prefix, rc);
// Clean up
cleanup:
XFREE(tmp_node_address);
return return_code;
} /* setup_keys */
static int load_cert(Certifier * certifier)
{
X509_CERT * cert = NULL;
const char * p12_filename = certifier_get_property(certifier, CERTIFIER_OPT_INPUT_P12_PATH);
const char * password = certifier_get_property(certifier, CERTIFIER_OPT_INPUT_P12_PASSWORD);
int return_code = 0;
// If there is a .p12 file, then we were already registered
if (util_file_exists(p12_filename))
{
log_debug("PKCS12 file %s exists. Loading x509", p12_filename);
CertifierError result = security_get_X509_PKCS12_file(p12_filename, password, NULL, &cert, NULL);
assign_last_error(certifier, &result);
return_code = result.application_error_code;
if (result.application_error_code != 0)
{
return_code = CERTIFIER_ERR_REGISTRATION_STATUS_X509_NONEXISTENT;
char * err_json = util_format_error_here("Internal error. Failed to parse x509.");
set_last_error(certifier, return_code, err_json);
goto cleanup;
}
security_free_cert(certifier->tmp_map.x509_cert);
certifier->tmp_map.x509_cert = cert;
cert = NULL;
}
else
{
return_code = CERTIFIER_ERR_REGISTRATION_STATUS_P12_NONEXISTENT;
char * err_json =
util_format_error("certifier_get_device_registration_status", "Could not find the P12 file.", __FILE__, __LINE__);
set_last_error(certifier, return_code, err_json);
goto cleanup;
}
cleanup:
security_free_cert(cert);
return return_code;
}
int certifier_get_device_registration_status(Certifier * certifier)
{
NULL_CHECK(certifier);
int return_code = 0;
CertifierError time_range_valid = CERTIFIER_ERROR_INITIALIZER;
time_t raw_time = 0;
const char * simulated_cert_expiration_date_before = NULL;
const char * simulated_cert_expiration_date_after = NULL;
// Check certificate expiration against current time
time(&raw_time);
log_debug("BEFORE raw_time%lld\n", (long long) raw_time);
if (!raw_time)
{
return_code = CERTIFIER_ERR_REGISTRATION_STATUS_CERT_TIME_CHECK_1;
char * err_json =
util_format_error("certifier_get_device_registration_status", "Could not obtain the system time!", __FILE__, __LINE__);
set_last_error(certifier, return_code, err_json);
goto cleanup;
}
free_tmp(certifier);
return_code = load_cert(certifier);
if (return_code != 0)
{
/* load_cert() will set_last_error on failure */
goto cleanup;
}
simulated_cert_expiration_date_before = certifier_get_property(certifier, CERTIFIER_OPT_SIMULATION_CERT_EXP_DATE_BEFORE);
simulated_cert_expiration_date_after = certifier_get_property(certifier, CERTIFIER_OPT_SIMULATION_CERT_EXP_DATE_AFTER);
// Check to see if it is about to expire
time_range_valid = security_check_x509_valid_range(
raw_time, (size_t) certifier_get_property(certifier, CERTIFIER_OPT_CERT_MIN_TIME_LEFT_S), certifier->tmp_map.x509_cert,
simulated_cert_expiration_date_before, simulated_cert_expiration_date_after);
assign_last_error(certifier, &time_range_valid);
return_code = time_range_valid.application_error_code;
cleanup:
return (return_code);
}
int certifier_get_device_certificate_status(Certifier * certifier)
{
NULL_CHECK(certifier);
int return_code = 0;
CertifierError certificate_status = CERTIFIER_ERROR_INITIALIZER;
unsigned char der_cert_hash[CERTIFIER_SHA1_DIGEST_LENGTH];
unsigned char * p_der_cert = NULL;
size_t der_cert_len = 0;
free_tmp(certifier);
return_code = load_cert(certifier);
if (return_code != 0)
{
/* load_cert() will set_last_error on failure */
goto cleanup;
}
p_der_cert = security_X509_to_DER(certifier->tmp_map.x509_cert, &der_cert_len);
security_sha1(der_cert_hash, p_der_cert, der_cert_len);
// Check certificate's status (good, unknown or revoked)
certificate_status = certifierclient_check_certificate_status(certifier->prop_map, der_cert_hash, sizeof(der_cert_hash));
assign_last_error(certifier, &certificate_status);
return_code = certificate_status.application_error_code;
cleanup:
XFREE(p_der_cert);
return (return_code);
}
int certifier_revoke_certificate(Certifier * certifier)
{
NULL_CHECK(certifier);
int return_code = 0;
CertifierError certificate_status = CERTIFIER_ERROR_INITIALIZER;
unsigned char der_cert_hash[CERTIFIER_SHA1_DIGEST_LENGTH];
unsigned char * p_der_cert = NULL;
size_t der_cert_len = 0;
free_tmp(certifier);
return_code = load_cert(certifier);
if (return_code != 0)
{
return return_code;
}
p_der_cert = security_X509_to_DER(certifier->tmp_map.x509_cert, &der_cert_len);
security_sha1(der_cert_hash, p_der_cert, der_cert_len);
// Check certificate's status (good, unknown or revoked)
certificate_status = certifierclient_revoke_x509_certificate(certifier->prop_map, der_cert_hash, sizeof(der_cert_hash));
assign_last_error(certifier, &certificate_status);
return_code = certificate_status.application_error_code;
XFREE(p_der_cert);
return (return_code);
}
static int save_x509certs_to_filesystem(Certifier * certifier, char * x509_certs, bool renew_mode, const char * p12_filename)
{
int rc = 0;
CertifierError certifier_err_info = CERTIFIER_ERROR_INITIALIZER;
X509_LIST * certs = NULL;
const char * password = NULL;
unsigned char *x509_der;
size_t x509_len;
log_info("\nTrimming x509 certificates...\n");
util_trim(x509_certs);
log_info("\nLoading Certs from PKCS7...\n");
certifier_err_info = security_load_certs_from_pem(x509_certs, &certs);
assign_last_error(certifier, &certifier_err_info);
rc = certifier_err_info.application_error_code;
if (certifier_err_info.application_error_code != 0)
{
log_error("\n<<< Failed to load certs from pkcs7. >>>\n");
rc = CERTIFIER_ERR_REGISTER_SECURITY_5;
goto cleanup;
}
int log_level = (int) (size_t) certifier_get_property(certifier, CERTIFIER_OPT_LOG_LEVEL);
if (log_level != 4)
{
security_print_certs_in_list(certs, stderr);
}
/* Cert is owned by the 'certs' stack; create our own copy and save it */
_certifier_set_x509_cert(certifier, security_cert_list_pop(certs, 0));
if (certifier->tmp_map.x509_cert == NULL)
{
rc = CERTIFIER_ERR_REGISTER_SECURITY_6;
set_last_error(certifier, rc, util_format_error_here("Failed to get certificate from certificate list!"));
goto cleanup;
}
else
{
// Export X509 certificate to be used externally
X509_CERT * cert_x509_dup = security_dup_cert(certifier->tmp_map.x509_cert);
if (cert_x509_dup)
{
rc = certifier_set_property(certifier, CERTIFIER_OPT_CERT_X509_OUT, (const void *) cert_x509_dup);
if (rc)
{
set_last_error(certifier, rc, util_format_error_here("Failed to set certificate property CERTIFIER_OPT_CERT_X509_OUT!"));
security_free_cert(cert_x509_dup);
goto cleanup;
}
}
}
password = certifier_get_property(certifier, CERTIFIER_OPT_INPUT_P12_PASSWORD);
// FIXME: This decision is done too late. Overwrite policy should be explicit
// and checked before trying to register (e.g., CERTIFIER_OPT_FORCE_REGISTRATION).
if (util_file_exists(p12_filename) && !renew_mode)
{
log_info("\nPKCS12 file %s exists. NOT overwriting!\n", p12_filename);
}
else
{
log_info("\nSaving PKCS12 file %s...\n", p12_filename);
security_persist_pkcs_12_file(p12_filename, password, certifier->tmp_map.private_ec_key, certifier->tmp_map.x509_cert,
certs, &certifier_err_info);
assign_last_error(certifier, &certifier_err_info);
rc = certifier_err_info.application_error_code;
log_info("\nPersisted PKCS12 file %s\n", p12_filename);
if (certifier_err_info.application_error_code != 0)
{
rc = CERTIFIER_ERR_REGISTER_SECURITY_7;
goto cleanup;
}
}
// Clean up
cleanup:
security_free_cert_list(certs);
return rc;
}
int certifier_renew_certificate(Certifier * certifier)
{
NULL_CHECK(certifier);
int return_code = 0;
CertifierError certificate_status = CERTIFIER_ERROR_INITIALIZER;
unsigned char der_cert_hash[CERTIFIER_SHA1_DIGEST_LENGTH];
unsigned char * p_der_cert = NULL;
size_t der_cert_len = 0;
char * x509_certs = NULL;
char * p12_filename = certifier_get_property(certifier, CERTIFIER_OPT_INPUT_P12_PATH);
free_tmp(certifier);
return_code = load_cert(certifier);
if (return_code != 0)
{
return return_code;
}
p_der_cert = security_X509_to_DER(certifier->tmp_map.x509_cert, &der_cert_len);
security_sha1(der_cert_hash, p_der_cert, der_cert_len);
// Renew certificate
certificate_status =
certifierclient_renew_x509_certificate(certifier->prop_map, der_cert_hash, sizeof(der_cert_hash), &x509_certs);
assign_last_error(certifier, &certificate_status);
return_code = certificate_status.application_error_code;
if (x509_certs == NULL || certificate_status.application_error_code != 0)
{
log_error("\n<<< Failed to Request X509 Certificate! >>>\n");
assign_last_error(certifier, &certificate_status);
return_code = CERTIFIER_ERR_RENEW_CERT_1 + certificate_status.application_error_code;
goto cleanup;
}
else
{
log_info("\nObtained x509 Certificate Successfully!\n");
}
if (_certifier_get_privkey(certifier) == NULL || certifier->tmp_map.der_public_key == NULL ||
certifier->tmp_map.base64_public_key == NULL)
{
log_error("Error in Setup.");
return_code = CERTIFIER_ERR_REGISTER_SETUP + return_code;
goto cleanup;
}
save_x509certs_to_filesystem(certifier, x509_certs, true, p12_filename);
cleanup:
XFREE(x509_certs);
XFREE(p_der_cert);
return return_code;
}
int certifier_create_node_address(const unsigned char * input, int input_len, char ** node_address)
{
int return_code = 0;
if (util_is_empty((const char *) input))
{
return CERTIFIER_ERR_CREATE_NODE_ADDRESS_1;
}
*node_address = security_encode(input, input_len, &return_code);
if (return_code != 0)
{
return_code = CERTIFIER_ERR_CREATE_NODE_ADDRESS_2 + return_code;
}
return return_code;
}
const char * certifier_get_node_address(Certifier * certifier)
{
if (util_is_empty(certifier->tmp_map.node_address))
{
/* Loading keys will also load the node_address (derived from public key) */
if (certifier_setup_keys(certifier) != 0)
{
return NULL;
}
}
return certifier->tmp_map.node_address;
}
int certifier_create_crt(Certifier * certifier, char ** out_crt, const char * token_type)
{
NULL_CHECK(certifier);
int return_code = 0;
int64_t timestamp_msec; /* timestamp in millisecond. */
char * transaction_id = NULL;
JSON_Value * root_value = json_value_init_object();
JSON_Object * root_object = json_value_get_object(root_value);
char * serialized_string = NULL;
const char * token = certifier_get_property(certifier, CERTIFIER_OPT_AUTH_TOKEN);
if (util_is_empty(token))
{
return_code = CERTIFIER_ERR_CREATE_CRT_1;
goto cleanup;
}
if (out_crt == NULL)
{
return_code = CERTIFIER_ERR_CREATE_CRT_2;
goto cleanup;
}
if (token_type == NULL)
{
return_code = CERTIFIER_ERR_CREATE_CRT_5;
goto cleanup;
}
json_object_set_string(root_object, "tokenType", token_type);
// set the token
json_object_set_string(root_object, "token", token);
// generate the transaction_id, and timestamps
transaction_id = util_generate_random_value(16, ALLOWABLE_CHARACTERS);
if (util_is_empty(transaction_id))
{
log_error("ERROR: Transaction ID is NULL");
return_code = CERTIFIER_ERR_CREATE_CRT_3;
goto cleanup;
}
log_debug("Transaction ID is: %s", transaction_id);
if (util_get_unixtime_ms(×tamp_msec) != 0)
{
log_error("ERROR: Could not generate milliseconds from epoch #2.");
return_code = CERTIFIER_ERR_CREATE_CRT_4;
goto cleanup;
}
log_debug("timestamp in milliseconds since epoch is: %" PRIi64, timestamp_msec);
json_object_set_string(root_object, "nonce", transaction_id);
json_object_set_number(root_object, "timestamp", timestamp_msec);
serialized_string = json_serialize_to_string_pretty(root_value);
if (util_is_empty(serialized_string))
{
return_code = CERTIFIER_ERR_CREATE_CRT_3;
goto cleanup;
}
log_info("Generated CRT is: %s\n", serialized_string);
*out_crt = XSTRDUP(serialized_string);
if (util_is_empty(*out_crt))
{
return_code = CERTIFIER_ERR_CREATE_CRT_4;
goto cleanup;
}
cleanup:
if (root_value)
{
json_value_free(root_value);
}
if (serialized_string)
{
json_free_serialized_string(serialized_string);
}
if (transaction_id != NULL)
{
XFREE(transaction_id);
}
return return_code;
}
int certifier_create_x509_crt(Certifier * certifier, char ** out_crt)
{
NULL_CHECK(certifier);
int return_code = 0;
char * generated_crt = NULL;
const X509_CERT * cert = NULL;
const ECC_KEY * private_key = NULL;
if (out_crt == NULL)
{
return_code = CERTIFIER_ERR_CREATE_X509_CERT_3;
goto cleanup;
}
log_info("Calling get_cert()");
cert = get_cert(certifier);
if (cert == NULL)
{
return_code = CERTIFIER_ERR_CREATE_X509_CERT_6;
log_error("Could not lazily obtain the cert as it was NULL. Received error code: <%i>", return_code);
goto cleanup;
}
private_key = _certifier_get_privkey(certifier);
if (private_key == NULL)
{
return_code = CERTIFIER_ERR_CREATE_X509_CERT_7;
log_error("Could not lazily obtain the private key as it was NULL. Received error code: <%i>", return_code);
goto cleanup;
}
return_code = security_generate_x509_crt(&generated_crt, (X509_CERT *) cert, (ECC_KEY *) private_key);
if (return_code)
{
log_error("Received an error code: <%i> while calling security_generate_x509_crt(). Exiting.", return_code);
return_code = CERTIFIER_ERR_CREATE_X509_CERT_4 + return_code;
goto cleanup;
}
if ((!generated_crt) || (XSTRLEN(generated_crt) == 0))
{
log_error("Could not generate the CRT.");
return_code = CERTIFIER_ERR_CREATE_X509_CERT_5;
goto cleanup;
}
log_info("Generated CRT is: %s\n", generated_crt);
*out_crt = generated_crt;
cleanup:
free_tmp(certifier);
return return_code;
}
static void handle_log_msg(const log_level level, const char * file, const int line, const char * msg)
{
if (logger != NULL)
{
CertifierLogPriority prio = CERTIFIER_LOG_DEBUG;
switch (level)
{
case LOG_TRACE:
prio = CERTIFIER_LOG_TRACE;
break;
case LOG_DEBUG:
prio = CERTIFIER_LOG_DEBUG;
break;
case LOG_INFO:
prio = CERTIFIER_LOG_INFO;
break;
case LOG_WARN:
prio = CERTIFIER_LOG_WARN;
break;
case LOG_ERROR:
prio = CERTIFIER_LOG_ERROR;
break;
case LOG_FATAL:
prio = CERTIFIER_LOG_FATAL;
break;
default:
prio = CERTIFIER_LOG_DEBUG;
break;
}
logger(prio, file, (uint32_t) line, msg);
}
}
void certifier_set_log_callback(Certifier * certifier, CERTIFIER_LOG_callback cb)
{
// TODO: Connect logging to context
logger = cb;
if (cb == NULL)
{
log_set_callback(NULL);
}
else
{
log_set_callback(handle_log_msg);
}
}
char * certifier_get_x509_pem(Certifier * certifier)
{
if (certifier == NULL)
{
return NULL;
}
const X509_CERT * cert = get_cert(certifier);
if (cert == NULL)
{
return NULL;
}
size_t der_len = 0;
unsigned char * der = security_X509_to_DER((X509_CERT *) cert, &der_len);
char * pem = NULL;
if (der != NULL && der_len > 0)
{
pem = XMALLOC(base64_encode_len(der_len));
if (pem == NULL)
{
log_error("Could not allocate enough memory for pem in certifier_get_x509_pem()");
goto cleanup;
}
base64_encode(pem, der, der_len);
}
cleanup:
XFREE(der);
return pem;
}
void certifier_print_certificate(Certifier * certifier, const char * pem, int pem_len)
{
if (certifier == NULL)
{
return;
}
const X509_CERT * cert = get_cert(certifier);
if (cert == NULL)
{
return;
}
security_print_subject_issuer(cert);
char tmp[65];
printf(PEM_BEGIN_CERTIFICATE "\n");
for (int i = 0; i < pem_len; i += 64)
{
snprintf(tmp, sizeof(tmp), "%s", &pem[i]);
puts(tmp);
}
printf(PEM_END_CERTIFICATE "\n");
}
void certifier_print_certificate_validity(Certifier * certifier)
{
char time[64];
security_get_before_time_validity(get_cert(certifier), time, sizeof(time));
XFPRINTF(stdout, "Valid from: \t%s\n", time);
security_get_not_after_time_validity(get_cert(certifier), time, sizeof(time));
XFPRINTF(stdout, "Valid to: \t%s\n", time);
}
static inline void assign_last_error(Certifier * certifier, CertifierError * error)
{
error_clear(&certifier->last_error);
certifier->last_error.application_error_code = error->application_error_code;
certifier->last_error.library_error_code = error->library_error_code;
certifier->last_error.application_error_msg = error->application_error_msg;
certifier->last_error.library_error_msg = error->library_error_msg;
// Prevent double-free by nulling source pointers
error->application_error_msg = NULL;
error->library_error_msg = NULL;
error->application_error_code = 0;
error->library_error_code = 0;
}
/**
* Set the last error info
* @param certifier
* @param error_code
* @param error_string a description of the error.
* @note This function transfers ownership of error_string away from the caller. The value passed to this
* parameter MUST NOT be freed and SHOULD NOT be referred to beyond the call site.
*/
static void set_last_error(Certifier * certifier, const int error_code, char * error_string)
{
certifier->last_error.application_error_code = error_code;
XFREE(certifier->last_error.application_error_msg);
// todo - should last_error.library_error_msg be freed as well?
certifier->last_error.application_error_msg = error_string;
}
/*
* [package] private functions
*/
CertifierPropMap * _certifier_get_properties(Certifier * certifier)
{
return certifier->prop_map;
}
void _certifier_set_x509_cert(Certifier * certifier, const X509_CERT * cert)
{
security_free_cert(certifier->tmp_map.x509_cert);
X509_CERT * tmp = NULL;
if (cert != NULL)
{
tmp = cert;
}
certifier->tmp_map.x509_cert = tmp;
}
void _certifier_set_ecc_key(Certifier * certifier, const ECC_KEY * key)
{
security_free_eckey(certifier->tmp_map.private_ec_key);
ECC_KEY * tmp = NULL;
if (key != NULL)
{
tmp = security_dup_eckey(key);
}
certifier->tmp_map.private_ec_key = tmp;
}
// Functions
Certifier * certifier_new(void)
{
int error_code = 0;
CertifierError result = CERTIFIER_ERROR_INITIALIZER;
const char * cfgfile = NULL;
// set initial logging properties
log_set_stripped(0);
log_set_newlines(1);
Certifier * certifier = XCALLOC(1, sizeof(Certifier));
if (certifier == NULL)
{
log_error("Could not allocate enough memory to construct a certifier\n");
error_code = CERTIFIER_ERR_INIT_MEMORY;
goto exit;
}
certifier->prop_map = property_new();
if (certifier->prop_map == NULL)
{
log_error("Could not allocate enough memory to construct a prop_map\n");
error_code = CERTIFIER_ERR_INIT_MEMORY;
goto exit;
}
error_code = certifierclient_init();
if (error_code)
{
log_error("certifierclient_init failed\n");
error_code = CERTIFIER_ERR_INIT_CERTIFIER + error_code;
goto exit;
}
result = security_init();
if (result.application_error_code != 0)
{
log_error("security_init failed\n");
error_code = CERTIFIER_ERR_INIT_SECURITY + error_code;
goto exit;
}
/* A default cfgfile may be set, but it is optional. Only attempt to load if set and exists */
cfgfile = certifier_get_property(certifier, CERTIFIER_OPT_CFG_FILENAME);
if (!util_is_empty(cfgfile) && access(cfgfile, F_OK) == 0)
{
/* This will reconfigure() automatically. */
error_code = certifier_load_cfg_file(certifier);
}
else
{
}
exit:
error_clear(&result);
if (error_code != 0)
{
certifier_destroy(certifier);
certifier = NULL;
}
return certifier;
} /* certifier_new */
int certifier_destroy(Certifier * certifier)
{
int error_code = 0;
if (certifier == NULL)
{
return error_code;
}
error_code = certifierclient_destroy();
if (error_code)
{
error_code = CERTIFIER_ERR_DESTROY_CERTIFIER + error_code;
goto exit;
}
security_destroy();
error_code = log_destroy();
if (error_code)
{
error_code = CERTIFIER_ERR_DESTROY_LOG + error_code;
goto exit;