-
Notifications
You must be signed in to change notification settings - Fork 98
/
Copy pathopenssl.cpp
1864 lines (1591 loc) · 59.3 KB
/
openssl.cpp
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
// Compiler for PHP (aka KPHP)
// Copyright (c) 2020 LLC «V Kontakte»
// Distributed under the GPL v3 License, see LICENSE.notice.txt
#include "runtime/openssl.h"
#include <cerrno>
#include <memory>
#include <netdb.h>
#include <poll.h>
#include <sys/time.h>
#include <unistd.h>
#include "openssl/asn1.h"
#include "openssl/err.h"
#include "openssl/evp.h"
#include "openssl/hmac.h"
#include "openssl/md5.h"
#include "openssl/pem.h"
#include "openssl/rsa.h"
#include "openssl/sha.h"
#include "openssl/ssl.h"
#include "openssl/x509v3.h"
#include "common/crc32.h"
#include "common/resolver.h"
#include "common/smart_ptrs/unique_ptr_with_delete_function.h"
#include "common/wrappers/openssl.h"
#include "common/wrappers/string_view.h"
#include "common/wrappers/to_array.h"
#include "runtime-common/stdlib/string/string-context.h"
#include "runtime-common/stdlib/string/string-functions.h"
#include "runtime/allocator.h"
#include "runtime/array_functions.h"
#include "runtime/critical_section.h"
#include "runtime/datetime/datetime_functions.h"
#include "runtime/files.h"
#include "runtime/net_events.h"
#include "runtime/streams.h"
#include "runtime/string_functions.h"
#include "runtime/url.h"
namespace {
struct HashTraits {
private:
template<class F>
string call_hash_algo(bool raw_output, const F &hash_algo) const noexcept {
string res{hash_len * (raw_output ? 1 : 2), false};
hash_algo(res);
if (!raw_output) {
for (int64_t i = hash_len - 1; i >= 0; i--) {
res[2 * i + 1] = StringLibConstants::get().lhex_digits[res[i] & 15];
res[2 * i] = StringLibConstants::get().lhex_digits[(res[i] >> 4) & 15];
}
}
return res;
}
public:
const char *name;
unsigned char *(*algo_function)(const unsigned char *, size_t, unsigned char *);
uint32_t hash_len;
const EVP_MD *(*get_evp)();
string hash(const string &s, bool raw_output) const noexcept {
return call_hash_algo(raw_output, [this, &s](string &out) {
dl::critical_section_call(algo_function,
reinterpret_cast<const unsigned char *>(s.c_str()), s.size(),
reinterpret_cast<unsigned char *>(out.buffer()));
});
}
string hash_hmac(const string &data, const string &key, bool raw_output) const noexcept {
return call_hash_algo(raw_output, [this, &data, &key](string &out) {
unsigned int md_len = 0;
dl::critical_section_call(HMAC, get_evp(), key.c_str(), static_cast<int>(key.size()),
reinterpret_cast<const unsigned char *> (data.c_str()), static_cast<int>(data.size()),
reinterpret_cast<unsigned char *> (out.buffer()), &md_len);
php_assert (md_len == hash_len);
});
}
};
HashTraits make_sha1_traits() noexcept {
return HashTraits{"sha1", SHA1, SHA_DIGEST_LENGTH, EVP_sha1};
}
HashTraits make_md5_traits() noexcept {
return HashTraits{"md5", MD5, MD5_DIGEST_LENGTH, EVP_md5};
}
const auto &get_supported_hash_algorithms() noexcept {
const static auto supported_algorithms = vk::to_array<HashTraits>(
{
make_sha1_traits(),
HashTraits{"sha224", SHA224, SHA224_DIGEST_LENGTH, EVP_sha224},
HashTraits{"sha256", SHA256, SHA256_DIGEST_LENGTH, EVP_sha256},
HashTraits{"sha384", SHA384, SHA384_DIGEST_LENGTH, EVP_sha384},
HashTraits{"sha512", SHA512, SHA512_DIGEST_LENGTH, EVP_sha512},
make_md5_traits()
});
return supported_algorithms;
}
const HashTraits &find_hash_algorithm(const char *algo) noexcept {
const auto &supported_algorithms = get_supported_hash_algorithms();
const auto *const it = std::find_if(supported_algorithms.begin(), supported_algorithms.end(),
[algo](const HashTraits &traits) { return !strcmp(algo, traits.name); });
if (it == supported_algorithms.end()) {
php_critical_error ("algo %s not supported in function hash", algo);
}
return *it;
}
} // namespace
array<string> f$hash_algos() noexcept {
const auto &supported_algorithms = get_supported_hash_algorithms();
array<string> result{array_size{static_cast<int64_t>(supported_algorithms.size()), true}};
for (const auto &algo : supported_algorithms) {
result.emplace_back(string{algo.name});
}
return result;
}
array<string> f$hash_hmac_algos() noexcept {
return f$hash_algos();
}
string f$hash(const string &algo, const string &s, bool raw_output) noexcept {
return find_hash_algorithm(algo.c_str()).hash(s, raw_output);
}
string f$hash_hmac(const string &algo, const string &data, const string &key, bool raw_output) noexcept {
return find_hash_algorithm(algo.c_str()).hash_hmac(data, key, raw_output);
}
string f$sha1(const string &s, bool raw_output) noexcept {
return make_sha1_traits().hash(s, raw_output);
}
string f$md5(const string &s, bool raw_output) noexcept {
return make_md5_traits().hash(s, raw_output);
}
Optional<string> f$md5_file(const string &file_name, bool raw_output) {
dl::CriticalSectionSmartGuard critical_section;
struct stat stat_buf;
int read_fd = open(file_name.c_str(), O_RDONLY);
if (read_fd < 0) {
return false;
}
if (fstat(read_fd, &stat_buf) < 0) {
close(read_fd);
return false;
}
if (!S_ISREG (stat_buf.st_mode)) {
close(read_fd);
critical_section.leave_critical_section();
php_warning("Regular file expected in function md5_file, \"%s\" is given", file_name.c_str());
return false;
}
MD5_CTX c;
php_assert (MD5_Init(&c) == 1);
size_t size = stat_buf.st_size;
while (size > 0) {
size_t len = min(size, (size_t)StringLibContext::STATIC_BUFFER_LENGTH);
if (read_safe(read_fd, StringLibContext::get().static_buf.data(), len, file_name) < (ssize_t)len) {
break;
}
php_assert (MD5_Update(&c, static_cast <const void *> (StringLibContext::get().static_buf.data()), (unsigned long)len) == 1);
size -= len;
}
close(read_fd);
php_assert (MD5_Final(reinterpret_cast <unsigned char *> (StringLibContext::get().static_buf.data()), &c) == 1);
critical_section.leave_critical_section();
if (size > 0) {
php_warning("Error while reading file \"%s\"", file_name.c_str());
return false;
}
if (!raw_output) {
string res(32, false);
for (int i = 15; i >= 0; i--) {
res[2 * i + 1] = StringLibConstants::get().lhex_digits[StringLibContext::get().static_buf.data()[i] & 15];
res[2 * i] = StringLibConstants::get().lhex_digits[(StringLibContext::get().static_buf.data()[i] >> 4) & 15];
}
return res;
} else {
return string(StringLibContext::get().static_buf.data(), 16);
}
}
int64_t f$crc32(const string &s) {
return compute_crc32(static_cast <const void *> (s.c_str()), s.size());
}
int64_t f$crc32_file(const string &file_name) {
dl::CriticalSectionSmartGuard critical_section;
struct stat stat_buf;
int read_fd = open(file_name.c_str(), O_RDONLY);
if (read_fd < 0) {
return -1;
}
if (fstat(read_fd, &stat_buf) < 0) {
close(read_fd);
return -1;
}
if (!S_ISREG (stat_buf.st_mode)) {
close(read_fd);
critical_section.leave_critical_section();
php_warning("Regular file expected in function crc32_file, \"%s\" is given", file_name.c_str());
return -1;
}
uint32_t res = std::numeric_limits<uint32_t>::max();
size_t size = stat_buf.st_size;
while (size > 0) {
size_t len = min(size, (size_t)StringLibContext::STATIC_BUFFER_LENGTH);
if (read_safe(read_fd, StringLibContext::get().static_buf.data(), len, file_name) < (ssize_t)len) {
break;
}
res = crc32_partial(StringLibContext::get().static_buf.data(), (int)len, res);
size -= len;
}
close(read_fd);
if (size > 0) {
return -1;
}
return res ^ std::numeric_limits<uint32_t>::max();
}
template<char PREFIX_CHAR>
struct EVPKeyResourceStorage {
public:
string register_resource_and_leave_critical_section(EVP_PKEY *pkey, dl::CriticalSectionSmartGuard &critical_section) {
php_assert(registered_keys_);
const int64_t elements = registered_keys_->count();
php_assert(elements > 0);
auto &reserved_place = (*registered_keys_)[elements - 1];
php_assert(!reserved_place);
reserved_place = pkey;
critical_section.leave_critical_section();
// reserve place for next key
registered_keys_->emplace_back(nullptr);
string result(2, PREFIX_CHAR);
result.append(elements - 1);
return result;
}
EVP_PKEY *find_resource(const string &key) {
php_assert(registered_keys_);
int64_t num = 0;
if (key.size() > 2 && key[0] == PREFIX_CHAR && key[1] == PREFIX_CHAR &&
php_try_to_int(key.c_str() + 2, key.size() - 2, &num)) {
return registered_keys_->get_value(num);
}
return nullptr;
}
void init_resources() {
registered_keys_ = reinterpret_cast<KeysArray *>(&storage_);
new(registered_keys_) KeysArray();
registered_keys_->emplace_back(nullptr);
}
void free_resources() {
if (registered_keys_) {
for (auto keyIt : *registered_keys_) {
EVP_PKEY_free(keyIt.get_value());
}
registered_keys_ = nullptr;
}
}
private:
using KeysArray = array<EVP_PKEY *>;
using KeysArrayStorage = std::aligned_storage<sizeof(KeysArray), alignof(KeysArray)>::type;
KeysArrayStorage storage_{};
KeysArray *registered_keys_{nullptr};
};
// uses different prefixes for avoid of resource identifier collisions
static EVPKeyResourceStorage<';'> public_keys;
static EVPKeyResourceStorage<':'> private_keys;
static EVP_PKEY *openssl_get_private_evp(const string &key, const string &passphrase, bool &from_cache) {
if (EVP_PKEY *evp_pkey = private_keys.find_resource(key)) {
from_cache = true;
return evp_pkey;
}
from_cache = false;
EVP_PKEY *evp_pkey = nullptr;
if (BIO *in = BIO_new_mem_buf(const_cast<char *>(key.c_str()), key.size())) {
evp_pkey = PEM_read_bio_PrivateKey(in, nullptr, nullptr, passphrase.empty() ? nullptr : const_cast<char *>(passphrase.c_str()));
BIO_free(in);
}
return evp_pkey;
}
static EVP_PKEY *openssl_get_public_evp(const string &key, bool &from_cache) {
if (EVP_PKEY *evp_pkey = public_keys.find_resource(key)) {
from_cache = true;
return evp_pkey;
}
from_cache = false;
EVP_PKEY *evp_pkey = nullptr;
BIO *cert_in = BIO_new_mem_buf(const_cast<char *>(key.c_str()), key.size());
if (cert_in == nullptr) {
return nullptr;
}
X509 *cert = reinterpret_cast<X509 *>(PEM_ASN1_read_bio(
reinterpret_cast<d2i_of_void *>(d2i_X509), PEM_STRING_X509, cert_in, nullptr, nullptr, nullptr));
BIO_free(cert_in);
if (cert) {
evp_pkey = X509_get_pubkey(cert);
X509_free(cert);
} else if (BIO *key_in = BIO_new_mem_buf(const_cast<char *>(key.c_str()), key.size())) {
evp_pkey = PEM_read_bio_PUBKEY(key_in, nullptr, nullptr, nullptr);
BIO_free(key_in);
}
return evp_pkey;
}
using RSA_ptr = vk::unique_ptr_with_delete_function<rsa_st, RSA_free>;
bool f$openssl_public_encrypt(const string &data, string &result, const string &key) {
bool from_cache = false;
dl::CriticalSectionSmartGuard critical_section;
EVP_PKEY *pkey = openssl_get_public_evp(key, from_cache);
if (pkey == nullptr) {
critical_section.leave_critical_section();
php_warning("Parameter key is not a valid public key");
result = string();
return false;
}
if (EVP_PKEY_id(pkey) != EVP_PKEY_RSA && EVP_PKEY_id(pkey) != EVP_PKEY_RSA2) {
if (!from_cache) {
EVP_PKEY_free(pkey);
}
critical_section.leave_critical_section();
php_warning("Key type is neither RSA nor RSA2");
result = string();
return false;
}
int key_size = EVP_PKEY_size(pkey);
php_assert (StringLibContext::STATIC_BUFFER_LENGTH >= key_size);
RSA_ptr rsa{EVP_PKEY_get1_RSA(pkey)};
if (RSA_public_encrypt(static_cast<int>(data.size()), reinterpret_cast<const unsigned char *>(data.c_str()),
reinterpret_cast<unsigned char *>(StringLibContext::get().static_buf.data()), rsa.get(), RSA_PKCS1_PADDING) != key_size) {
if (!from_cache) {
EVP_PKEY_free(pkey);
}
php_warning("RSA public encrypt failed");
result = string();
return false;
}
if (!from_cache) {
EVP_PKEY_free(pkey);
}
result = string(StringLibContext::get().static_buf.data(), key_size);
return true;
}
bool f$openssl_public_encrypt(const string &data, mixed &result, const string &key) {
string result_string;
if (f$openssl_public_encrypt(data, result_string, key)) {
result = result_string;
return true;
}
result = mixed();
return false;
}
bool f$openssl_private_decrypt(const string &data, string &result, const string &key) {
bool from_cache = false;
dl::CriticalSectionSmartGuard critical_section;
EVP_PKEY *pkey = openssl_get_private_evp(key, string(), from_cache);
if (pkey == nullptr) {
critical_section.leave_critical_section();
php_warning("Parameter key is not a valid private key");
return false;
}
if (EVP_PKEY_id(pkey) != EVP_PKEY_RSA && EVP_PKEY_id(pkey) != EVP_PKEY_RSA2) {
if (!from_cache) {
EVP_PKEY_free(pkey);
}
critical_section.leave_critical_section();
php_warning("Key type is not an RSA nor RSA2");
return false;
}
int key_size = EVP_PKEY_size(pkey);
php_assert (StringLibContext::STATIC_BUFFER_LENGTH >= key_size);
RSA_ptr rsa{EVP_PKEY_get1_RSA(pkey)};
int len = RSA_private_decrypt(static_cast<int>(data.size()), reinterpret_cast<const unsigned char *>(data.c_str()),
reinterpret_cast<unsigned char *>(StringLibContext::get().static_buf.data()), rsa.get(), RSA_PKCS1_PADDING);
if (!from_cache) {
EVP_PKEY_free(pkey);
}
if (len == -1) {
//php_warning ("RSA private decrypt failed");
result = string();
return false;
}
result.assign(StringLibContext::get().static_buf.data(), len);
return true;
}
bool f$openssl_private_decrypt(const string &data, mixed &result, const string &key) {
string result_string;
if (f$openssl_private_decrypt(data, result_string, key)) {
result = result_string;
return true;
}
result = mixed();
return false;
}
Optional<string> f$openssl_pkey_get_private(const string &key, const string &passphrase) {
Optional<string> result = false;
dl::CriticalSectionSmartGuard critical_section;
bool from_cache = false;
if (EVP_PKEY *pkey = openssl_get_private_evp(key, passphrase, from_cache)) {
result = from_cache ? key : private_keys.register_resource_and_leave_critical_section(pkey, critical_section);
} else {
critical_section.leave_critical_section();
php_warning("Parameter key is not a valid key or passphrase is not a valid password");
}
return result;
}
Optional<string> f$openssl_pkey_get_public(const string &key) {
Optional<string> result = false;
dl::CriticalSectionSmartGuard critical_section;
bool from_cache = false;
if (EVP_PKEY *pkey = openssl_get_public_evp(key, from_cache)) {
result = from_cache ? key : public_keys.register_resource_and_leave_critical_section(pkey, critical_section);
} else {
critical_section.leave_critical_section();
php_warning("Parameter key is not a valid key");
}
return result;
}
static const EVP_MD *openssl_algo_to_evp_md(openssl_algo algo) {
switch (algo) {
case OPENSSL_ALGO_SHA1:
return EVP_sha1();
# ifndef OPENSSL_NO_MD5
case OPENSSL_ALGO_MD5:
return EVP_md5();
# endif
# ifndef OPENSSL_NO_MD4
case OPENSSL_ALGO_MD4:
return EVP_md4();
#endif
#ifndef OPENSSL_NO_MD2
case OPENSSL_ALGO_MD2: return EVP_md2();
#endif
case OPENSSL_ALGO_SHA224:
return EVP_sha224();
case OPENSSL_ALGO_SHA256:
return EVP_sha256();
case OPENSSL_ALGO_SHA384:
return EVP_sha384();
case OPENSSL_ALGO_SHA512:
return EVP_sha512();
#ifndef OPENSSL_NO_RMD160
case OPENSSL_ALGO_RMD160:
return EVP_ripemd160();
#endif
default:
return nullptr;
}
}
static const char *ssl_get_error_string() {
kphp_runtime_context.static_SB.clean();
while (unsigned long error_code = ERR_get_error()) {
kphp_runtime_context.static_SB << "Error " << (int)error_code << ": [" << ERR_error_string(error_code, nullptr) << "]\n";
}
return kphp_runtime_context.static_SB.c_str();
}
bool f$openssl_sign(const string &data, string &signature, const string &priv_key_id, int64_t algo) {
dl::CriticalSectionSmartGuard critical_section;
const EVP_MD *mdtype = openssl_algo_to_evp_md(static_cast<openssl_algo>(algo));
if (!mdtype) {
critical_section.leave_critical_section();
php_warning("Unknown signature algorithm");
return false;
}
bool from_cache = false;
EVP_PKEY *pkey = openssl_get_private_evp(priv_key_id, string{}, from_cache);
if (pkey == nullptr) {
critical_section.leave_critical_section();
php_warning("Parameter key cannot be converted into a private key");
return false;
}
const int pkey_size = EVP_PKEY_size(pkey);
php_assert(pkey_size >= 0);
signature.assign(static_cast<unsigned int>(pkey_size), '\0');
unsigned int siglen = 0;
bool result = false;
EVP_MD_CTX *md_ctx = EVP_MD_CTX_create();
if (md_ctx &&
EVP_SignInit(md_ctx, mdtype) &&
EVP_SignUpdate(md_ctx, data.c_str(), data.size()) &&
EVP_SignFinal(md_ctx, reinterpret_cast<unsigned char *>(signature.buffer()), &siglen, pkey)) {
php_assert(siglen <= signature.size());
signature.shrink(siglen);
result = true;
} else {
signature = string{};
php_warning("Can't create signature for data\n%s", ssl_get_error_string());
}
EVP_MD_CTX_destroy(md_ctx);
if (!from_cache) {
EVP_PKEY_free(pkey);
}
return result;
}
int64_t f$openssl_verify(const string &data, const string &signature, const string &pub_key_id, int64_t algo) {
dl::CriticalSectionSmartGuard critical_section;
const EVP_MD *mdtype = openssl_algo_to_evp_md(static_cast<openssl_algo>(algo));
if (!mdtype) {
critical_section.leave_critical_section();
php_warning("Unknown signature algorithm");
return 0;
}
bool from_cache = false;
EVP_PKEY *pkey = openssl_get_public_evp(pub_key_id, from_cache);
if (pkey == nullptr) {
critical_section.leave_critical_section();
php_warning("Parameter key cannot be converted into a public key");
return 0;
}
int err = 0;
EVP_MD_CTX *md_ctx = EVP_MD_CTX_create();
if (md_ctx == nullptr ||
!EVP_VerifyInit (md_ctx, mdtype) ||
!EVP_VerifyUpdate (md_ctx, data.c_str(), data.size()) ||
(err = EVP_VerifyFinal(md_ctx, (unsigned char *)signature.c_str(), (unsigned int)signature.size(), pkey)) < 0) {
}
EVP_MD_CTX_destroy(md_ctx);
if (!from_cache) {
EVP_PKEY_free(pkey);
}
return err;
}
Optional<string> f$openssl_random_pseudo_bytes(int64_t length) {
if (length <= 0 || length > string::max_size()) {
return false;
}
string buffer{static_cast<string::size_type>(length), false};
timeval tv{};
gettimeofday(&tv, nullptr);
dl::CriticalSectionGuard critical_section;
RAND_add(&tv, sizeof(tv), 0.0);
if (RAND_bytes(reinterpret_cast<unsigned char *>(buffer.buffer()), static_cast<int32_t>(length)) <= 0) {
return false;
}
return buffer;
}
struct ssl_connection {
int sock;
bool is_blocking;
SSL *ssl_handle;
SSL_CTX *ssl_ctx;
};
static char ssl_connections_storage[sizeof(array<ssl_connection>)];
static array<ssl_connection> *ssl_connections = reinterpret_cast <array<ssl_connection> *> (ssl_connections_storage);
static long long ssl_connections_last_query_num = -1;
const int DEFAULT_SOCKET_TIMEOUT = 60;
static Stream ssl_stream_socket_client(const string &url, int64_t &error_number, string &error_description, double timeout, int64_t flags __attribute__((unused)), const mixed &options) {
#define RETURN(dump_error_stack) \
if (dump_error_stack) { \
php_warning ("%s: %s", error_description.c_str(), \
ssl_get_error_string()); \
} else { \
php_warning ("%s", error_description.c_str()); \
} \
if (ssl_handle != nullptr) { \
SSL_free (ssl_handle); \
} \
if (ssl_ctx != nullptr) { \
SSL_CTX_free (ssl_ctx); \
} \
if (sock != -1) { \
close (sock); \
} \
return false
#define RETURN_ERROR(dump_error_stack, error_no, error) \
error_number = error_no; \
error_description = CONST_STRING(error); \
RETURN(dump_error_stack)
#define RETURN_ERROR_FORMAT(dump_error_stack, error_no, format, ...) \
error_number = error_no; \
error_description = f$sprintf ( \
CONST_STRING(format), array<mixed>::create(__VA_ARGS__)); \
RETURN(dump_error_stack)
if (timeout < 0) {
timeout = DEFAULT_SOCKET_TIMEOUT;
}
double end_time = microtime_monotonic() + timeout;
int sock = -1;
SSL *ssl_handle = nullptr;
SSL_CTX *ssl_ctx = nullptr;
mixed parsed_url = f$parse_url(url);
string host = f$strval(parsed_url.get_value(string("host", 4)));
int64_t port = f$intval(parsed_url.get_value(string("port", 4)));
//getting connection options
#define GET_OPTION(option_name) options.get_value (string (option_name, sizeof (option_name) - 1))
bool verify_peer = GET_OPTION("verify_peer").to_bool();
mixed verify_depth_var = GET_OPTION("verify_depth");
int64_t verify_depth = verify_depth_var.to_int();
if (verify_depth_var.is_null()) {
verify_depth = -1;
}
string cafile = GET_OPTION("cafile").to_string();
string capath = GET_OPTION("capath").to_string();
string cipher_list = GET_OPTION("ciphers").to_string();
string local_cert = GET_OPTION("local_cert").to_string();
Optional<string> local_cert_file_path = local_cert.empty() ? false : f$realpath(local_cert);
#undef GET_OPTION
if (host.empty()) {
RETURN_ERROR_FORMAT(false, -1, "Wrong host specified in url \"%s\"", url);
}
if (port <= 0 || port >= 65536) {
RETURN_ERROR_FORMAT(false, -2, "Wrong port specified in url \"%s\"", url);
}
// gethostbyname often uses heap => it must be under critical section, otherwise we will get UB on timeout in the middle of it
struct hostent *h = dl::critical_section_call(kdb_gethostbyname, host.c_str());
if (!h || !h->h_addr_list || !h->h_addr_list[0]) {
RETURN_ERROR_FORMAT(false, -3, "Can't resolve host \"%s\"", host);
}
struct sockaddr_storage addr;
addr.ss_family = static_cast<sa_family_t>(h->h_addrtype);
int addrlen;
switch (h->h_addrtype) {
case AF_INET:
php_assert (h->h_length == 4);
(reinterpret_cast <struct sockaddr_in *> (&addr))->sin_port = htons(static_cast<uint16_t>(port));
(reinterpret_cast <struct sockaddr_in *> (&addr))->sin_addr = *(struct in_addr *)h->h_addr;
addrlen = sizeof(struct sockaddr_in);
break;
case AF_INET6:
php_assert (h->h_length == 16);
(reinterpret_cast <struct sockaddr_in6 *> (&addr))->sin6_port = htons(static_cast<uint16_t>(port));
memcpy(&(reinterpret_cast <struct sockaddr_in6 *> (&addr))->sin6_addr, h->h_addr, h->h_length);
addrlen = sizeof(struct sockaddr_in6);
break;
default:
//there is no other known address types
php_assert (0);
}
dl::CriticalSectionSmartGuard critical_section;
sock = socket(h->h_addrtype, SOCK_STREAM, 0);
if (sock == -1) {
RETURN_ERROR(false, -4, "Can't create tcp socket");
}
php_assert (fcntl(sock, F_SETFL, O_NONBLOCK) == 0);
if (connect(sock, reinterpret_cast <const sockaddr *> (&addr), addrlen) == -1) {
if (errno != EINPROGRESS) {
RETURN_ERROR(false, -5, "Can't connect to tcp socket");
}
pollfd poll_fds;
poll_fds.fd = sock;
poll_fds.events = POLLIN | POLLERR | POLLHUP | POLLOUT | POLLPRI;
double left_time = end_time - microtime_monotonic();
if (left_time <= 0 || poll(&poll_fds, 1, timeout_convert_to_ms(left_time)) <= 0) {
RETURN_ERROR(false, -6, "Can't connect to tcp socket");
}
}
ERR_clear_error();
ssl_ctx = SSL_CTX_new(TLSv1_client_method());
if (ssl_ctx == nullptr) {
RETURN_ERROR(true, -7, "Failed to create an SSL context");
}
// SSL_CTX_set_options (ssl_ctx, SSL_OP_ALL); don't want others bugs workarounds
SSL_CTX_set_mode (ssl_ctx, SSL_MODE_AUTO_RETRY | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
if (verify_peer) {
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, nullptr);
if (verify_depth != -1) {
SSL_CTX_set_verify_depth(ssl_ctx, static_cast<int32_t>(verify_depth));
}
if (cafile.empty() && capath.empty()) {
SSL_CTX_set_default_verify_paths(ssl_ctx);
} else {
if (SSL_CTX_load_verify_locations(ssl_ctx, cafile.empty() ? nullptr : cafile.c_str(), capath.empty() ? nullptr : capath.c_str()) == 0) {
RETURN_ERROR_FORMAT(true, -8, "Failed to load verify locations \"%s\" and \"%s\"", cafile, capath);
}
}
} else {
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_NONE, nullptr);
}
if (SSL_CTX_set_cipher_list(ssl_ctx, cipher_list.empty() ? "DEFAULT" : cipher_list.c_str()) == 0) {
RETURN_ERROR_FORMAT(true, -9, "Failed to set cipher list \"%s\"", cipher_list);
}
if (f$boolval(local_cert_file_path)) {
if (SSL_CTX_use_certificate_chain_file(ssl_ctx, local_cert_file_path.val().c_str()) != 1) {
RETURN_ERROR_FORMAT(true, -10, "Failed to use certificate from local_cert \"%s\"", local_cert);
}
if (SSL_CTX_use_PrivateKey_file(ssl_ctx, local_cert_file_path.val().c_str(), SSL_FILETYPE_PEM) != 1) {
RETURN_ERROR_FORMAT(true, -11, "Failed to use private key from local_cert \"%s\"", local_cert);
}
if (SSL_CTX_check_private_key(ssl_ctx) != 1) {
RETURN_ERROR(true, -12, "Private key doesn't match certificate");
}
}
ssl_handle = SSL_new(ssl_ctx);
if (ssl_handle == nullptr) {
RETURN_ERROR(true, -13, "Failed to create an SSL handle");
}
if (!SSL_set_fd(ssl_handle, sock)) {
RETURN_ERROR(true, -14, "Failed to set fd");
}
#if OPENSSL_VERSION_NUMBER >= 0x0090806fL && !defined(OPENSSL_NO_TLSEXT)
SSL_set_tlsext_host_name (ssl_handle, host.c_str());
#endif
SSL_set_connect_state(ssl_handle); //TODO remove
while (true) {
int connect_result = SSL_connect(ssl_handle);
if (connect_result == 1) {
if (verify_peer) {
X509 *peer_cert = SSL_get_peer_certificate(ssl_handle);
if (peer_cert == nullptr) {
SSL_shutdown(ssl_handle);
RETURN_ERROR(false, -15, "Failed to get peer certificate");
}
X509_free(peer_cert);
php_assert (SSL_get_verify_result(ssl_handle) == X509_V_OK);
}
break;
}
int error = SSL_get_error(ssl_handle, connect_result);
if (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE) {
RETURN_ERROR(true, -16, "Failed to do SSL_connect");
}
pollfd poll_fds;
poll_fds.fd = sock;
poll_fds.events = POLLIN | POLLERR | POLLHUP | POLLOUT | POLLPRI;
double left_time = end_time - microtime_monotonic();
if (left_time <= 0 || poll(&poll_fds, 1, timeout_convert_to_ms(left_time)) <= 0) {
RETURN_ERROR(false, -17, "Can't establish SSL connect due to timeout");
}
}
php_assert (fcntl(sock, F_SETFL, 0) == 0);
critical_section.leave_critical_section();
if (dl::query_num != ssl_connections_last_query_num) {
new(ssl_connections_storage) array<ssl_connection>();
ssl_connections_last_query_num = dl::query_num;
}
ssl_connection result;
result.sock = sock;
result.is_blocking = true;
result.ssl_handle = ssl_handle;
result.ssl_ctx = ssl_ctx;
string stream_key = url;
if (ssl_connections->has_key(stream_key)) {
int try_count;
for (try_count = 0; try_count < 3; try_count++) {
stream_key = url;
stream_key.append("#", 1);
stream_key.append(string(rand()));
if (!ssl_connections->has_key(stream_key)) {
break;
}
}
if (try_count == 3) {
SSL_shutdown(ssl_handle);
RETURN_ERROR(false, -18, "Can't generate stream_name in 3 tries. Something is definitely wrong.");
}
}
dl::critical_section_call([&] { ssl_connections->set_value(stream_key, result); });
return stream_key;
#undef RETURN
#undef RETURN_ERROR
#undef RETURN_ERROR_FORMAT
}
static bool ssl_context_set_option(mixed &context_ssl, const string &option, const mixed &value) {
if (STRING_EQUALS(option, "verify_peer") ||
STRING_EQUALS(option, "verify_depth") ||
STRING_EQUALS(option, "cafile") ||
STRING_EQUALS(option, "capath") ||
STRING_EQUALS(option, "local_cert") ||
STRING_EQUALS(option, "ciphers")) {
context_ssl[option] = value;
return true;
}
php_warning("Option \"%s\" for wrapper ssl is not supported", option.c_str());
return false;
}
ssl_connection *get_connection(const Stream &stream) {
if (dl::query_num != ssl_connections_last_query_num || !ssl_connections->has_key(stream.to_string())) {
php_warning("Connection to \"%s\" not found", stream.to_string().c_str());
return nullptr;
}
return &(*ssl_connections)[stream.to_string()];
}
static void ssl_do_shutdown(ssl_connection *c) {
php_assert (dl::in_critical_section > 0);
if (c->sock == -1) {
return;
}
if (!c->is_blocking) {
php_assert (fcntl(c->sock, F_SETFL, 0) == 0);
}
php_assert (c->ssl_ctx != nullptr);
php_assert (c->ssl_handle != nullptr);
SSL_shutdown(c->ssl_handle);
SSL_free(c->ssl_handle);
SSL_CTX_free(c->ssl_ctx);
close(c->sock);
c->sock = -1;
c->ssl_ctx = nullptr;
c->ssl_handle = nullptr;
}
static bool process_ssl_error(ssl_connection *c, int result) {
php_assert (dl::in_critical_section > 0);
int error = SSL_get_error(c->ssl_handle, result);
switch (error) {
case SSL_ERROR_NONE:
php_assert (0);
return false;
case SSL_ERROR_ZERO_RETURN:
if (c->sock != -1) {
ssl_do_shutdown(c);
} else {
php_warning("SSL connection is already closed");
}
return false;
case SSL_ERROR_WANT_READ:
case SSL_ERROR_WANT_WRITE:
return true;
case SSL_ERROR_WANT_CONNECT:
case SSL_ERROR_WANT_ACCEPT:
case SSL_ERROR_WANT_X509_LOOKUP:
php_assert (0);
return false;
case SSL_ERROR_SYSCALL:
if (ERR_peek_error() == 0) {
if (result != 0) {
if (errno == EAGAIN) {
return true;
}
php_warning("SSL gets error %d: %s", errno, strerror(errno));
} else {
//socket was closed from other side, not an error
ssl_do_shutdown(c);
}
return false;
}
/* fall through */
default:
php_warning("SSL gets error %d: %s", error, ssl_get_error_string());
ssl_do_shutdown(c);
return false;
}
}
static Optional<int64_t> ssl_fwrite(const Stream &stream, const string &data) {
ssl_connection *c = get_connection(stream);
if (c == nullptr || c->sock == -1) {
return false;
}
const void *data_ptr = static_cast <const void *> (data.c_str());
int data_len = static_cast <int> (data.size());
if (data_len == 0) {
return 0;
}
dl::CriticalSectionSmartGuard critical_section;
ERR_clear_error();
int written = SSL_write(c->ssl_handle, data_ptr, data_len);
if (written <= 0) {
bool ok = process_ssl_error(c, written);
if (ok) {
critical_section.leave_critical_section();
php_assert (!c->is_blocking);//because of SSL_MODE_AUTO_RETRY
return 0;
}
return false;
} else {
critical_section.leave_critical_section();
if (c->is_blocking) {
php_assert (written == data_len);
} else {
php_assert (written <= data_len);
}
return written;
}
}