forked from RetroShare/RetroShare
/
authssl.cc
1783 lines (1454 loc) · 55 KB
/
authssl.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*******************************************************************************
* libretroshare/src/pqi: authssl.cc *
* *
* libretroshare: retroshare core library *
* *
* Copyright (C) 2004-2008 Robert Fernie <retroshare@lunamutt.com> *
* Copyright (C) 2019 Gioacchino Mazzurco <gio@eigenlab.org> *
* *
* This program is free software: you can redistribute it and/or modify *
* it under the terms of the GNU Lesser General Public License as *
* published by the Free Software Foundation, either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this program. If not, see <https://www.gnu.org/licenses/>. *
* *
*******************************************************************************/
#ifdef WINDOWS_SYS
#include "util/rswin.h"
#endif // WINDOWS_SYS
#include "authssl.h"
#include "sslfns.h"
#include "pqinetwork.h"
#include "authgpg.h"
#include "rsitems/rsconfigitems.h"
#include "util/rsdir.h"
#include "util/rsstring.h"
#include "pgp/pgpkeyutil.h"
#include "retroshare/rspeers.h" // for RsPeerDetails structure
#include "retroshare/rsids.h" // for RsPeerDetails structure
#include "rsserver/p3face.h"
/******************** notify of new Cert **************************/
#include <openssl/rand.h>
#include <openssl/ssl.h>
#include <iomanip>
/* SSL connection diagnostic */
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_UNKNOWN = 0x00 ;
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_OK = 0x01 ;
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_CERTIFICATE_NOT_VALID = 0x02 ;
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_ISSUER_UNKNOWN = 0x03 ;
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_MALLOC_ERROR = 0x04 ;
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_WRONG_SIGNATURE = 0x05 ;
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_CERTIFICATE_MISSING = 0x06 ;
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_HASH_ALGORITHM_NOT_ACCEPTED = 0x07 ;
//const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_KEY_ALGORITHM_NOT_ACCEPTED = 0x08 ;
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_WRONG_SIGNATURE_TYPE = 0x09 ;
const uint32_t RS_SSL_HANDSHAKE_DIAGNOSTIC_WRONG_SIGNATURE_VERSION = 0x0a ;
/****
* #define AUTHSSL_DEBUG 1
***/
static pthread_mutex_t* mutex_buf = nullptr;
struct CRYPTO_dynlock_value
{
pthread_mutex_t mutex;
};
# if OPENSSL_VERSION_NUMBER < 0x10100000L
/**
* OpenSSL locking function.
*
* @param mode lock mode
* @param n lock number
* @param file source file name
* @param line source file line number
* @return none
*/
static void locking_function(int mode, int n, const char */*file*/, int /*line*/)
{
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&mutex_buf[n]);
} else {
pthread_mutex_unlock(&mutex_buf[n]);
}
}
#endif
# if OPENSSL_VERSION_NUMBER < 0x10100000L
/**
* OpenSSL uniq id function.
*
* @return thread id
*/
static unsigned long id_function(void)
{
#if defined( WINDOWS_SYS) && !defined(WIN_PTHREADS_H)
return (unsigned long) pthread_self().p;
#else
return (unsigned long) pthread_self();
#endif
}
#endif
# if OPENSSL_VERSION_NUMBER < 0x10100000L
/**
* OpenSSL allocate and initialize dynamic crypto lock.
*
* @param file source file name
* @param line source file line number
*/
static struct CRYPTO_dynlock_value *dyn_create_function(const char */*file*/, int /*line*/)
{
struct CRYPTO_dynlock_value *value;
value = (struct CRYPTO_dynlock_value*) rs_malloc(sizeof(struct CRYPTO_dynlock_value));
if (!value)
return NULL;
pthread_mutex_init(&value->mutex, NULL);
return value;
}
#endif
# if OPENSSL_VERSION_NUMBER < 0x10100000L
/**
* OpenSSL dynamic locking function.
*
* @param mode lock mode
* @param l lock structure pointer
* @param file source file name
* @param line source file line number
* @return none
*/
static void dyn_lock_function(int mode, struct CRYPTO_dynlock_value *l, const char */*file*/, int /*line*/)
{
if (mode & CRYPTO_LOCK) {
pthread_mutex_lock(&l->mutex);
} else {
pthread_mutex_unlock(&l->mutex);
}
}
#endif
# if OPENSSL_VERSION_NUMBER < 0x10100000L
/**
* OpenSSL destroy dynamic crypto lock.
*
* @param l lock structure pointer
* @param file source file name
* @param line source file line number
* @return none
*/
static void dyn_destroy_function(struct CRYPTO_dynlock_value *l, const char */*file*/, int /*line*/)
{
pthread_mutex_destroy(&l->mutex);
free(l);
}
#endif
/**
* Initialize TLS library.
*
* @return true on success, false on error
*/
bool tls_init()
{
/* static locks area */
mutex_buf = (pthread_mutex_t*) rs_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t));
if (mutex_buf == NULL)
return false;
for (int i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_init(&mutex_buf[i], NULL);
}
# if OPENSSL_VERSION_NUMBER < 0x10100000L
/* static locks callbacks */
CRYPTO_set_locking_callback(locking_function);
CRYPTO_set_id_callback(id_function);
/* dynamic locks callbacks */
CRYPTO_set_dynlock_create_callback(dyn_create_function);
CRYPTO_set_dynlock_lock_callback(dyn_lock_function);
CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function);
#endif
return true;
}
/**
* Cleanup TLS library.
*
* @return 0
*/
void tls_cleanup()
{
CRYPTO_set_dynlock_create_callback(NULL);
CRYPTO_set_dynlock_lock_callback(NULL);
CRYPTO_set_dynlock_destroy_callback(NULL);
CRYPTO_set_locking_callback(NULL);
CRYPTO_set_id_callback(NULL);
if (mutex_buf != NULL) {
for (int i = 0; i < CRYPTO_num_locks(); i++) {
pthread_mutex_destroy(&mutex_buf[i]);
}
free(mutex_buf);
mutex_buf = NULL;
}
}
/*static*/ AuthSSL& AuthSSL::instance()
{
static AuthSSLimpl mInstance;
return mInstance;
}
AuthSSL* AuthSSL::getAuthSSL() { return &instance(); }
AuthSSL::~AuthSSL() = default;
/********************************************************************************/
/********************************************************************************/
/********************* Cert Search / Add / Remove **************************/
/********************************************************************************/
/********************************************************************************/
static int verify_x509_callback(int preverify_ok, X509_STORE_CTX *ctx);
std::string RsX509Cert::getCertName(const X509& x509)
{
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
return getX509CNString(x509.cert_info->subject);
#else
return getX509CNString(X509_get_subject_name(&x509));
#endif
}
std::string RsX509Cert::getCertLocation(const X509& x509)
{
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
return getX509LocString(x509.cert_info->subject);
#else
return getX509LocString(X509_get_subject_name(&x509));
#endif
}
std::string RsX509Cert::getCertOrg(const X509& x509)
{
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
return getX509OrgString(x509.cert_info->subject);
#else
return getX509OrgString(X509_get_subject_name(&x509));
#endif
}
/*static*/ RsPgpId RsX509Cert::getCertIssuer(const X509& x509)
{
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
return RsPgpId(getX509CNString(x509.cert_info->issuer));
#else
return RsPgpId(getX509CNString(X509_get_issuer_name(&x509)));
#endif
}
/*static*/ std::string RsX509Cert::getCertIssuerString(const X509& x509)
{
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
return getX509CNString(x509.cert_info->issuer);
#else
return getX509CNString(X509_get_issuer_name(&x509));
#endif
}
/*static*/ RsPeerId RsX509Cert::getCertSslId(const X509& x509)
{
RsPeerId sslid;
return getX509id(const_cast<X509*>(&x509), sslid) ? sslid : RsPeerId();
}
/************************************************************************
*
*
* CODE IS DIVIDED INTO
*
* 1) SSL Setup.
* 3) Cert Access.
* 4) Cert Sign / Verify.
* 5) Cert Authentication
* 2) Cert Add / Remove
* 6) Cert Storage
*/
/********************************************************************************/
/********************************************************************************/
/********************* Cert Search / Add / Remove **************************/
/********************************************************************************/
/********************************************************************************/
AuthSSLimpl::AuthSSLimpl() :
p3Config(), sslctx(nullptr), mOwnCert(nullptr), sslMtx("AuthSSL"),
mOwnPrivateKey(nullptr), mOwnPublicKey(nullptr), init(0) {}
bool AuthSSLimpl::active() { return init; }
int AuthSSLimpl::InitAuth(
const char* cert_file, const char* priv_key_file, const char* passwd,
std::string locationName )
{
/* single call here si don't need to invoke mutex yet */
static int initLib = 0;
if (!initLib)
{
initLib = 1;
if (!tls_init()) {
return 0;
}
SSL_load_error_strings();
SSL_library_init();
}
if (init == 1)
{
std::cerr << "AuthSSLimpl::InitAuth already initialized." << std::endl;
return 1;
}
if ((cert_file == NULL) ||
(priv_key_file == NULL) ||
(passwd == NULL))
{
//fprintf(stderr, "sslroot::initssl() missing parameters!\n");
return 0;
}
// actions_to_seed_PRNG();
RAND_seed(passwd, strlen(passwd));
std::cerr << "SSL Library Init!" << std::endl;
// setup connection method
sslctx = SSL_CTX_new(SSLv23_method());
SSL_CTX_set_options(sslctx,SSL_OP_NO_SSLv3) ;
//SSL_OP_SINGLE_DH_USE CVE-2016-0701
//https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_set_options.html
//If "strong" primes were used, it is not strictly necessary to generate a new DH key during each handshake but it is also recommended. SSL_OP_SINGLE_DH_USE should therefore be enabled whenever temporary/ephemeral DH parameters are used.
//SSL_CTX_set_options() adds the options set via bitmask in options to ctx. Options already set before are not cleared!
SSL_CTX_set_options(sslctx,SSL_OP_SINGLE_DH_USE) ;
// Setup cipher lists:
//
// std::string cipherString = "HIGH:!DSS:!aNULL:!3DES";
// std::string cipherString = "DEFAULT";
//
// The current cipher list asks in priority for EDH which provides PFS. However EDH needs proper
// parameters to be set on the server side, so if we're a client for a RS instance that has no DH params,
// the connection will be refused. So we happend the HIGH cipher suite just after. In oder to force
// PFS, at the risk of not always connecting, one should use:
//
// std::string cipherString = "kEDH:HIGH:!DSS:!aNULL:!3DES";
//
// The following safe primes are 2048/4096 bits long. Should be enough.
//
// std::string dh_prime_2048_dec = "30651576830996935311378276950670996791883170963804289256203421500259588715033040934547350194073369837229137842804826417332761673984632102152477971341551955103053338169949165519208562998954887445690136488713010579430413255432398961330773637820158790237012997356731669148258317860643591694814197514454546928317578771868379525705082166818553884557266645700906836702542808787791878865135741211056957383668479369231868698451684633965462539374994559481908068730787128654626819903401038534403722014687647173327537458614224702967073490136394698912372792187651228785689025073104374674728645661275001416541267543884923191810923";
//
//Not used (should be here: /libretroshare/src/gxstunnel/p3gxstunnel.cc:1131
//std::string dh_prime_2048_hex = "B3B86A844550486C7EA459FA468D3A8EFD71139593FE1C658BBEFA9B2FC0AD2628242C2CDC2F91F5B220ED29AAC271192A7374DFA28CDDCA70252F342D0821273940344A7A6A3CB70C7897A39864309F6CAC5C7EA18020EF882693CA2C12BB211B7BA8367D5A7C7252A5B5E840C9E8F081469EBA0B98BCC3F593A4D9C4D5DF539362084F1B9581316C1F80FDAD452FD56DBC6B8ED0775F596F7BB22A3FE2B4753764221528D33DB4140DE58083DB660E3E105123FC963BFF108AC3A268B7380FFA72005A1515C371287C5706FFA6062C9AC73A9B1A6AC842C2764CDACFC85556607E86611FDF486C222E4896CDF6908F239E177ACC641FCBFF72A758D1C10CBB" ;
std::string dh_prime_4096_hex = "A6F5777292D9E6BB95559C9124B9119E6771F11F2048C8FE74F4E8140494520972A087EF1D60B73894F1C5D509DD15D96CF379E9DDD46CE51B748085BACB440D915565782C73AF3A9580CE788441D1DA4D114E3D302CAB45A061ABCFC1F7E9200AE019CB923B77E096FA9377454A16FFE91D86535FF23E075B3E714F785CD7606E9CBD9D06F01CAFA2271883D649F13ABE170D714F6B6EC064C5BF35C4F4BDA5EF5ED5E70D5DC78F1AC1CDC04EEDAE8ADD65C4A9E27368E0B2C8595DD7626D763BFFB15364B3CCA9FCE814B9226B35FE652F4B041F0FF6694D6A482B0EF48CA41163D083AD2DE7B7A068BB05C0453E9D008551C7F67993A3EF2C4874F0244F78C4E0997BD31AB3BD88446916B499B2513DD5BA002063BD38D2CE55D29D071399D5CEE99458AF6FDC104A61CA3FACDAC803CBDE62B4C0EAC946D0E12F05CE9E94497110D64E611D957423B8AA412D84EC83E6E70E0977A31D6EE056D0527D4667D7242A77C9B679D191562E4026DA9C35FF85666296D872ED548E0FFE1A677FCC373C1F490CAB4F53DFD8735C0F1DF02FEAD824A217FDF4E3404D38A5BBC719C6622630FCD34F6F1968AF1B66A4AB1A9FCF653DA96EB3A42AF6FCFEA0547B8F314A527C519949007D7FA1726FF3D33EC46393B0207AA029E5EA574BDAC94D78894B22A2E3303E65A3F820DF57DB44951DE4E973C016C57F7A242D0BC53BC563AF" ;
std::string cipherString = "kEDH+HIGH:!DSS:!aNULL:!3DES:!EXP";
SSL_CTX_set_cipher_list(sslctx, cipherString.c_str());
DH* dh = DH_new();
int codes = 0;
bool pfs_enabled = true ;
if (dh)
{
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
BN_hex2bn(&dh->p,dh_prime_4096_hex.c_str()) ;
BN_hex2bn(&dh->g,"5") ;
#else
BIGNUM *pp=NULL,*gg=NULL ;
BN_hex2bn(&pp,dh_prime_4096_hex.c_str()) ;
BN_hex2bn(&gg,"5");
DH_set0_pqg(dh,pp,NULL,gg) ;
#endif
std::cout.flush() ;
if(DH_check(dh, &codes) && codes == 0)
SSL_CTX_set_tmp_dh(sslctx, dh);
else
pfs_enabled = false ;
}
else
pfs_enabled = false ;
// certificates (Set Local Server Certificate).
FILE *ownfp = RsDirUtil::rs_fopen(cert_file, "r");
if (ownfp == NULL)
{
std::cerr << "Couldn't open Own Certificate!" << std::endl;
return -1;
}
// get xPGP certificate.
X509 *x509 = PEM_read_X509(ownfp, NULL, NULL, NULL);
fclose(ownfp);
if (x509 == NULL)
{
std::cerr << "AuthSSLimpl::InitAuth() PEM_read_X509() Failed";
std::cerr << std::endl;
return -1;
}
SSL_CTX_use_certificate(sslctx, x509);
mOwnPublicKey = X509_get_pubkey(x509);
// get private key
FILE *pkfp = RsDirUtil::rs_fopen(priv_key_file, "rb");
if (pkfp == NULL)
{
std::cerr << "Couldn't Open PrivKey File!" << std::endl;
CloseAuth();
return -1;
}
mOwnPrivateKey = PEM_read_PrivateKey(pkfp, NULL, NULL, (void *) passwd);
fclose(pkfp);
if (mOwnPrivateKey == NULL)
{
std::cerr << "AuthSSLimpl::InitAuth() PEM_read_PrivateKey() Failed";
std::cerr << std::endl;
return -1;
}
SSL_CTX_use_PrivateKey(sslctx, mOwnPrivateKey);
if (1 != SSL_CTX_check_private_key(sslctx))
{
std::cerr << "Issues With Private Key! - Doesn't match your Cert" << std::endl;
std::cerr << "Check your input key/certificate:" << std::endl;
std::cerr << priv_key_file << " & " << cert_file;
std::cerr << std::endl;
CloseAuth();
return -1;
}
RsPeerId mownidstr ;
if (!getX509id(x509, mownidstr))
{
std::cerr << "AuthSSLimpl::InitAuth() getX509id() Failed";
std::cerr << std::endl;
/* bad certificate */
CloseAuth();
return -1;
}
mOwnId = mownidstr ;
assert(!mOwnId.isNull()) ;
/* Check that Certificate is Ok ( virtual function )
* for gpg/pgp or CA verification
*/
if (!validateOwnCertificate(x509, mOwnPrivateKey))
{
std::cerr << "AuthSSLimpl::InitAuth() validateOwnCertificate() Failed";
std::cerr << std::endl;
/* bad certificate */
CloseAuth();
exit(1);
return -1;
}
// enable verification of certificates (PEER)
// and install verify callback.
SSL_CTX_set_verify(sslctx, SSL_VERIFY_PEER |
SSL_VERIFY_FAIL_IF_NO_PEER_CERT,
verify_x509_callback);
std::cerr << "SSL Verification Set" << std::endl;
mOwnCert = x509;
std::cerr << "Inited SSL context: " << std::endl;
std::cerr << " Certificate: " << mOwnId << std::endl;
std::cerr << " cipher list: " << cipherString << std::endl;
std::cerr << " PFS enabled: " << (pfs_enabled?"YES":"NO") ;
if(codes > 0)
{
std::cerr << " (reason: " ;
if(codes & DH_CHECK_P_NOT_PRIME ) std::cerr << "Not a prime number, " ;
if(codes & DH_CHECK_P_NOT_SAFE_PRIME) std::cerr << "Not a safe prime number, " ;
if(codes & DH_UNABLE_TO_CHECK_GENERATOR) std::cerr << "unable to check generator, " ;
if(codes & DH_NOT_SUITABLE_GENERATOR) std::cerr << "not a suitable generator" ;
std::cerr << ")" << std::endl;
}
else
std::cerr << std::endl;
mOwnLocationName = locationName;
init = 1;
return 1;
}
/* Dummy function to be overloaded by real implementation */
bool AuthSSLimpl::validateOwnCertificate(X509 *x509, EVP_PKEY *pkey)
{
(void) pkey; /* remove unused parameter warning */
uint32_t diagnostic ;
/* standard authentication */
if (!AuthX509WithGPG(x509,true,diagnostic))
{
std::cerr << "Validate Own certificate ERROR: diagnostic = " << diagnostic << std::endl;
return false;
}
return true;
}
bool AuthSSLimpl::CloseAuth()
{
tls_cleanup();
#ifdef AUTHSSL_DEBUG
std::cerr << "AuthSSLimpl::CloseAuth()";
std::cerr << std::endl;
#endif
SSL_CTX_free(sslctx);
// clean up private key....
// remove certificates etc -> opposite of initssl.
init = 0;
return 1;
}
/* Context handling */
SSL_CTX *AuthSSLimpl::getCTX()
{
#ifdef AUTHSSL_DEBUG
std::cerr << "AuthSSLimpl::getCTX()";
std::cerr << std::endl;
#endif
return sslctx;
}
const RsPeerId& AuthSSLimpl::OwnId()
{
#ifdef AUTHSSL_DEBUG
// std::cerr << "AuthSSLimpl::OwnId()" << std::endl;
#endif
return mOwnId;
}
std::string AuthSSLimpl::getOwnLocation()
{ return mOwnLocationName; }
std::string AuthSSLimpl::SaveOwnCertificateToString()
{ return saveX509ToPEM(mOwnCert); }
/********************************************************************************/
/********************************************************************************/
/********************* Cert Search / Add / Remove **************************/
/********************************************************************************/
/********************************************************************************/
bool AuthSSLimpl::SignData(std::string input, std::string &sign)
{
return SignData(input.c_str(), input.length(), sign);
}
bool AuthSSLimpl::SignData(const void *data, const uint32_t len, std::string &sign)
{
RsStackMutex stack(sslMtx); /***** STACK LOCK MUTEX *****/
EVP_MD_CTX *mdctx = EVP_MD_CTX_create();
unsigned int signlen = EVP_PKEY_size(mOwnPrivateKey);
unsigned char signature[signlen] ;
memset(signature,0,signlen) ;
if (0 == EVP_SignInit(mdctx, EVP_sha1()))
{
std::cerr << "EVP_SignInit Failure!" << std::endl;
EVP_MD_CTX_destroy(mdctx);
return false;
}
if (0 == EVP_SignUpdate(mdctx, data, len))
{
std::cerr << "EVP_SignUpdate Failure!" << std::endl;
EVP_MD_CTX_destroy(mdctx);
return false;
}
if (0 == EVP_SignFinal(mdctx, signature, &signlen, mOwnPrivateKey))
{
std::cerr << "EVP_SignFinal Failure!" << std::endl;
EVP_MD_CTX_destroy(mdctx);
return false;
}
EVP_MD_CTX_destroy(mdctx);
sign.clear();
for(uint32_t i = 0; i < signlen; i++)
{
rs_sprintf_append(sign, "%02x", (uint32_t) (signature[i]));
}
return true;
}
bool AuthSSLimpl::SignDataBin(std::string input, unsigned char *sign, unsigned int *signlen)
{
return SignDataBin(input.c_str(), input.length(), sign, signlen);
}
bool AuthSSLimpl::SignDataBin(const void *data, const uint32_t len,
unsigned char *sign, unsigned int *signlen)
{
RsStackMutex stack(sslMtx); /***** STACK LOCK MUTEX *****/
return SSL_SignDataBin(data, len, sign, signlen, mOwnPrivateKey);
}
bool AuthSSLimpl::VerifySignBin(const void *data, const uint32_t len,
unsigned char *sign, unsigned int signlen, const RsPeerId& sslId)
{
/* find certificate.
* if we don't have - fail.
*/
RsStackMutex stack(sslMtx); /***** STACK LOCK MUTEX *****/
/* find the peer */
X509* peercert;
if (sslId == mOwnId) peercert = mOwnCert;
else if (!locked_FindCert(sslId, &peercert))
{
std::cerr << "VerifySignBin() no peer" << std::endl;
return false;
}
return SSL_VerifySignBin(data, len, sign, signlen, peercert);
}
bool AuthSSLimpl::VerifyOwnSignBin(const void *data, const uint32_t len,
unsigned char *sign, unsigned int signlen)
{ return SSL_VerifySignBin(data, len, sign, signlen, mOwnCert); }
/********************************************************************************/
/********************************************************************************/
/********************* Sign and Auth with GPG **************************/
/********************************************************************************/
/********************************************************************************/
/* Note these functions don't need Mutexes -
* only using GPG functions - which lock themselves
*/
X509 *AuthSSLimpl::SignX509ReqWithGPG(X509_REQ *req, long /*days*/)
{
/* Transform the X509_REQ into a suitable format to
* generate DIGEST hash. (for SSL to do grunt work)
*/
#define SERIAL_RAND_BITS 64
//const EVP_MD *digest = EVP_sha1();
EVP_PKEY *tmppkey;
X509 *x509 = X509_new();
if (x509 == NULL)
{
std::cerr << "AuthSSLimpl::SignX509Req() FAIL" << std::endl;
return NULL;
}
//long version = 0x00;
unsigned long chtype = MBSTRING_UTF8;
X509_NAME *issuer_name = X509_NAME_new();
X509_NAME_add_entry_by_txt(issuer_name, "CN", chtype,
(unsigned char *) AuthGPG::getAuthGPG()->getGPGOwnId().toStdString().c_str(), -1, -1, 0);
/****
X509_NAME_add_entry_by_NID(issuer_name, 48, 0,
(unsigned char *) "email@email.com", -1, -1, 0);
X509_NAME_add_entry_by_txt(issuer_name, "O", chtype,
(unsigned char *) "org", -1, -1, 0);
X509_NAME_add_entry_by_txt(x509_name, "L", chtype,
(unsigned char *) "loc", -1, -1, 0);
****/
std::cerr << "AuthSSLimpl::SignX509Req() Issuer name: " << AuthGPG::getAuthGPG()->getGPGOwnId().toStdString() << std::endl;
#ifdef V07_NON_BACKWARD_COMPATIBLE_CHANGE_002
static const uint64_t CERTIFICATE_SERIAL_NUMBER = RS_CERTIFICATE_VERSION_NUMBER_07_0001 ;
#else
#ifdef V07_NON_BACKWARD_COMPATIBLE_CHANGE_001
static const uint64_t CERTIFICATE_SERIAL_NUMBER = RS_CERTIFICATE_VERSION_NUMBER_06_0001 ;
#else
static const uint64_t CERTIFICATE_SERIAL_NUMBER = RS_CERTIFICATE_VERSION_NUMBER_06_0000 ;
#endif
#endif
BIGNUM *btmp = BN_new();
BN_set_word(btmp,CERTIFICATE_SERIAL_NUMBER) ;
#ifdef OLD_CODE
if (!BN_pseudo_rand(btmp, SERIAL_RAND_BITS, 0, 0))
{
std::cerr << "AuthSSLimpl::SignX509Req() rand FAIL" << std::endl;
return NULL;
}
#endif
ASN1_INTEGER *serial = ASN1_INTEGER_new();
if (!BN_to_ASN1_INTEGER(btmp, serial))
{
std::cerr << "AuthSSLimpl::SignX509Req() asn1 FAIL" << std::endl;
return NULL;
}
BN_free(btmp);
if (!X509_set_serialNumber(x509, serial))
{
std::cerr << "AuthSSLimpl::SignX509Req() serial FAIL" << std::endl;
return NULL;
}
ASN1_INTEGER_free(serial);
/* Generate SUITABLE issuer name.
* Must reference OpenPGP key, that is used to verify it
*/
if (!X509_set_issuer_name(x509, issuer_name))
{
std::cerr << "AuthSSLimpl::SignX509Req() issue FAIL" << std::endl;
return NULL;
}
X509_NAME_free(issuer_name);
// NEW code, set validity time between null and null
// (does not leak the key creation date to the outside anymore. for more privacy)
ASN1_TIME_set(X509_get_notBefore(x509), 0);
ASN1_TIME_set(X509_get_notAfter(x509), 0);
if (!X509_set_subject_name(x509, X509_REQ_get_subject_name(req)))
{
std::cerr << "AuthSSLimpl::SignX509Req() sub FAIL" << std::endl;
return NULL;
}
tmppkey = X509_REQ_get_pubkey(req);
if (!tmppkey || !X509_set_pubkey(x509,tmppkey))
{
std::cerr << "AuthSSLimpl::SignX509Req() pub FAIL" << std::endl;
return NULL;
}
std::cerr << "X509 Cert, prepared for signing" << std::endl;
/*** NOW The Manual signing bit (HACKED FROM asn1/a_sign.c) ***/
//
// The code has been copied in order to use the PGP signing instead of supplying the
// private EVP_KEY to ASN1_sign(), which would be another alternative.
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
int (*i2d)(X509_CINF*, unsigned char**) = i2d_X509_CINF;
X509_ALGOR *algor1 = x509->cert_info->signature;
X509_ALGOR *algor2 = x509->sig_alg;
ASN1_BIT_STRING *signature = x509->signature;
X509_CINF *data = x509->cert_info;
#else
const X509_ALGOR *algor1 = X509_get0_tbs_sigalg(x509) ;
const X509_ALGOR *algor2 = NULL ;
const ASN1_BIT_STRING *tmp_signature = NULL ;
X509_get0_signature(&tmp_signature,&algor2,x509);
ASN1_BIT_STRING *signature = const_cast<ASN1_BIT_STRING*>(tmp_signature);
#endif
//EVP_PKEY *pkey = NULL;
#ifdef V07_NON_BACKWARD_COMPATIBLE_CHANGE_002
const EVP_MD *type = EVP_sha256();
#else
const EVP_MD *type = EVP_sha1();
#endif
EVP_MD_CTX *ctx = EVP_MD_CTX_create();
int inl=0;
X509_ALGOR *a;
/* FIX ALGORITHMS */
a = const_cast<X509_ALGOR*>(algor1);
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
ASN1_TYPE_free(a->parameter);
a->parameter=ASN1_TYPE_new();
a->parameter->type=V_ASN1_NULL;
ASN1_OBJECT_free(a->algorithm);
a->algorithm=OBJ_nid2obj(type->pkey_type);
#else
X509_ALGOR_set0(a,OBJ_nid2obj(EVP_MD_pkey_type(type)),V_ASN1_NULL,NULL);
#endif
a = const_cast<X509_ALGOR*>(algor2);
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
ASN1_TYPE_free(a->parameter);
a->parameter=ASN1_TYPE_new();
a->parameter->type=V_ASN1_NULL;
ASN1_OBJECT_free(a->algorithm);
a->algorithm=OBJ_nid2obj(type->pkey_type);
#else
X509_ALGOR_set0(a,OBJ_nid2obj(EVP_MD_pkey_type(type)),V_ASN1_NULL,NULL);
#endif
std::cerr << "Algorithms Fixed" << std::endl;
unsigned int sigoutl=2048; // hashoutl; //EVP_PKEY_size(pkey);
unsigned char *buf_sigout=(unsigned char *)OPENSSL_malloc((unsigned int)sigoutl);
/* input buffer */
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
inl=i2d(data,NULL);
unsigned char *buf_in=(unsigned char *)OPENSSL_malloc((unsigned int)inl);
if(buf_in == NULL)
{
sigoutl=0;
fprintf(stderr, "AuthSSLimpl::SignX509Req: ASN1err(ASN1_F_ASN1_SIGN,ERR_R_MALLOC_FAILURE)\n");
return NULL ;
}
unsigned char *p=buf_in; // This because i2d modifies the pointer after writing to it.
i2d(data,&p);
#else
unsigned char *buf_in=NULL;
inl=i2d_re_X509_tbs(x509,&buf_in) ; // this does the i2d over x509->cert_info
#endif
#ifdef V07_NON_BACKWARD_COMPATIBLE_CHANGE_003
if((buf_in == NULL) || (buf_sigout == NULL))
{
sigoutl=0;
fprintf(stderr, "AuthSSLimpl::SignX509Req: ASN1err(ASN1_F_ASN1_SIGN,ERR_R_MALLOC_FAILURE)\n");
goto err;
}
std::cerr << "Buffers Allocated" << std::endl;
/* NOW Sign via GPG Functions */
if (!AuthGPG::getAuthGPG()->SignDataBin(buf_in, inl, buf_sigout, (unsigned int *) &sigoutl,"AuthSSLimpl::SignX509ReqWithGPG()"))
{
sigoutl = 0;
goto err;
}
#else
unsigned int hashoutl=EVP_MD_size(type);
unsigned char *buf_hashout=(unsigned char *)OPENSSL_malloc((unsigned int)hashoutl);
if((buf_hashout == NULL) || (buf_sigout == NULL))
{
hashoutl=0;
sigoutl=0;
fprintf(stderr, "AuthSSLimpl::SignX509Req: ASN1err(ASN1_F_ASN1_SIGN,ERR_R_MALLOC_FAILURE)\n");
goto err;
}
std::cerr << "Buffers Allocated" << std::endl;
/* data in buf_in, ready to be hashed */
EVP_DigestInit_ex(ctx,type, NULL);
EVP_DigestUpdate(ctx,(unsigned char *)buf_in,inl);
if (!EVP_DigestFinal(ctx,(unsigned char *)buf_hashout, (unsigned int *)&hashoutl))
{
hashoutl=0;
fprintf(stderr, "AuthSSLimpl::SignX509Req: ASN1err(ASN1_F_ASN1_SIGN,ERR_R_EVP_LIB)\n");
goto err;
}
std::cerr << "Digest Applied: len: " << hashoutl << std::endl;
/* NOW Sign via GPG Functions */
if (!AuthGPG::getAuthGPG()->SignDataBin(buf_hashout, hashoutl, buf_sigout, (unsigned int *) &sigoutl,"AuthSSLimpl::SignX509ReqWithGPG()"))
{
sigoutl = 0;
goto err;
}
#endif
std::cerr << "Buffer Sizes: in: " << inl;
#ifndef V07_NON_BACKWARD_COMPATIBLE_CHANGE_003
std::cerr << " HashOut: " << hashoutl;
#endif
std::cerr << " SigOut: " << sigoutl;
std::cerr << std::endl;
//passphrase = "NULL";
std::cerr << "Signature done: len:" << sigoutl << std::endl;
/* ADD Signature back into Cert... Signed!. */
if (signature->data != NULL) OPENSSL_free(signature->data);
signature->data=buf_sigout;
buf_sigout=NULL;
signature->length=sigoutl;
/* In the interests of compatibility, I'll make sure that
* the bit string has a 'not-used bits' value of 0
*/
signature->flags&= ~(ASN1_STRING_FLAG_BITS_LEFT|0x07);
signature->flags|=ASN1_STRING_FLAG_BITS_LEFT;
std::cerr << "Certificate Complete" << std::endl;
EVP_MD_CTX_destroy(ctx) ;
// debug
// {
// int pkey_nid = OBJ_obj2nid(x509->sig_alg->algorithm);
// const char* sslbuf = OBJ_nid2ln(pkey_nid);
// std::cerr << "Signature hash algorithm: " << sslbuf << std::endl;
// }
return x509;
/* XXX CLEANUP */
err:
/* cleanup */
if(buf_in != NULL)
OPENSSL_free(buf_in) ;
#ifndef V07_NON_BACKWARD_COMPATIBLE_CHANGE_003
if(buf_hashout != NULL)
OPENSSL_free(buf_hashout) ;
#endif
if(buf_sigout != NULL)
OPENSSL_free(buf_sigout) ;
std::cerr << "GPGAuthMgr::SignX509Req() err: FAIL" << std::endl;
return NULL;
}
bool AuthSSLimpl::AuthX509WithGPG(X509 *x509,bool verbose, uint32_t& diagnostic)
{
RsPgpId issuer = RsX509Cert::getCertIssuer(*x509);
RsPeerDetails pd;
if (!AuthGPG::getAuthGPG()->getGPGDetails(issuer, pd))
{
RsInfo() << __PRETTY_FUNCTION__ << " X509 NOT authenticated : "
<< "AuthGPG::getAuthGPG()->getGPGDetails(" << issuer
<< ",...) returned false." << std::endl;
diagnostic = RS_SSL_HANDSHAKE_DIAGNOSTIC_ISSUER_UNKNOWN;
return false;
}
else
Dbg3() << __PRETTY_FUNCTION__ << " issuer: " << issuer << " found"
<< std::endl;
/* verify GPG signature */
/*** NOW The Manual signing bit (HACKED FROM asn1/a_sign.c) ***/
#if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
int (*i2d)(X509_CINF*, unsigned char**) = i2d_X509_CINF;
ASN1_BIT_STRING* signature = x509->signature;
X509_CINF* data = x509->cert_info;
#else
const ASN1_BIT_STRING* signature = nullptr;
const X509_ALGOR* algor2 = nullptr;
X509_get0_signature(&signature,&algor2,x509);
#endif