-
Notifications
You must be signed in to change notification settings - Fork 0
/
socketwrapper.c
1330 lines (1264 loc) · 35.3 KB
/
socketwrapper.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// socketwrapper.c
// Copyright (C) 2011 Suguru Kawamoto
// ソケットラッパー
// socket関連関数をOpenSSL用に置換
// socket関連関数のIPv6対応
// コンパイルにはOpenSSLのヘッダーファイルが必要
// 実行にはOpenSSLのDLLが必要
#include <ws2tcpip.h>
#include <windows.h>
#include <mmsystem.h>
#include <openssl/ssl.h>
#include "socketwrapper.h"
#include "protectprocess.h"
#include "mbswrapper.h"
#include "punycode.h"
// FTPS対応
typedef void (__cdecl* _SSL_load_error_strings)();
typedef int (__cdecl* _SSL_library_init)();
typedef SSL_METHOD* (__cdecl* _SSLv23_method)();
typedef SSL_CTX* (__cdecl* _SSL_CTX_new)(SSL_METHOD*);
typedef void (__cdecl* _SSL_CTX_free)(SSL_CTX*);
typedef SSL* (__cdecl* _SSL_new)(SSL_CTX*);
typedef void (__cdecl* _SSL_free)(SSL*);
typedef int (__cdecl* _SSL_shutdown)(SSL*);
typedef int (__cdecl* _SSL_get_fd)(SSL*);
typedef int (__cdecl* _SSL_set_fd)(SSL*, int);
typedef int (__cdecl* _SSL_accept)(SSL*);
typedef int (__cdecl* _SSL_connect)(SSL*);
typedef int (__cdecl* _SSL_write)(SSL*, const void*, int);
typedef int (__cdecl* _SSL_peek)(SSL*, void*, int);
typedef int (__cdecl* _SSL_read)(SSL*, void*, int);
typedef int (__cdecl* _SSL_get_error)(SSL*, int);
typedef X509* (__cdecl* _SSL_get_peer_certificate)(const SSL*);
typedef long (__cdecl* _SSL_get_verify_result)(const SSL*);
typedef SSL_SESSION* (__cdecl* _SSL_get_session)(SSL*);
typedef int (__cdecl* _SSL_set_session)(SSL*, SSL_SESSION*);
typedef X509_STORE* (__cdecl* _SSL_CTX_get_cert_store)(const SSL_CTX*);
typedef BIO_METHOD* (__cdecl* _BIO_s_mem)();
typedef BIO* (__cdecl* _BIO_new)(BIO_METHOD*);
typedef int (__cdecl* _BIO_free)(BIO*);
typedef BIO* (__cdecl* _BIO_new_mem_buf)(void*, int);
typedef long (__cdecl* _BIO_ctrl)(BIO*, int, long, void*);
typedef void (__cdecl* _X509_free)(X509*);
typedef int (__cdecl* _X509_print_ex)(BIO*, X509*, unsigned long, unsigned long);
typedef X509_NAME* (__cdecl* _X509_get_subject_name)(X509*);
typedef int (__cdecl* _X509_NAME_print_ex)(BIO*, X509_NAME*, int, unsigned long);
typedef X509* (__cdecl* _PEM_read_bio_X509)(BIO*, X509**, pem_password_cb*, void*);
typedef int (__cdecl* _X509_STORE_add_cert)(X509_STORE*, X509*);
_SSL_load_error_strings p_SSL_load_error_strings;
_SSL_library_init p_SSL_library_init;
_SSLv23_method p_SSLv23_method;
_SSL_CTX_new p_SSL_CTX_new;
_SSL_CTX_free p_SSL_CTX_free;
_SSL_new p_SSL_new;
_SSL_free p_SSL_free;
_SSL_shutdown p_SSL_shutdown;
_SSL_get_fd p_SSL_get_fd;
_SSL_set_fd p_SSL_set_fd;
_SSL_accept p_SSL_accept;
_SSL_connect p_SSL_connect;
_SSL_write p_SSL_write;
_SSL_peek p_SSL_peek;
_SSL_read p_SSL_read;
_SSL_get_error p_SSL_get_error;
_SSL_get_peer_certificate p_SSL_get_peer_certificate;
_SSL_get_verify_result p_SSL_get_verify_result;
_SSL_get_session p_SSL_get_session;
_SSL_set_session p_SSL_set_session;
_SSL_CTX_get_cert_store p_SSL_CTX_get_cert_store;
_BIO_s_mem p_BIO_s_mem;
_BIO_new p_BIO_new;
_BIO_free p_BIO_free;
_BIO_new_mem_buf p_BIO_new_mem_buf;
_BIO_ctrl p_BIO_ctrl;
_X509_free p_X509_free;
_X509_print_ex p_X509_print_ex;
_X509_get_subject_name p_X509_get_subject_name;
_X509_NAME_print_ex p_X509_NAME_print_ex;
_PEM_read_bio_X509 p_PEM_read_bio_X509;
_X509_STORE_add_cert p_X509_STORE_add_cert;
#define MAX_SSL_SOCKET 16
BOOL g_bOpenSSLLoaded;
HMODULE g_hOpenSSL;
HMODULE g_hOpenSSLCommon;
CRITICAL_SECTION g_OpenSSLLock;
DWORD g_OpenSSLTimeout;
LPSSLTIMEOUTCALLBACK g_pOpenSSLTimeoutCallback;
LPSSLCONFIRMCALLBACK g_pOpenSSLConfirmCallback;
SSL_CTX* g_pOpenSSLCTX;
SSL* g_pOpenSSLHandle[MAX_SSL_SOCKET];
BOOL __stdcall DefaultSSLTimeoutCallback(BOOL* pbAborted)
{
Sleep(100);
return *pbAborted;
}
BOOL __stdcall DefaultSSLConfirmCallback(BOOL* pbAborted, BOOL bVerified, LPCSTR Certificate, LPCSTR CommonName)
{
return bVerified;
}
// OpenSSLを初期化
BOOL LoadOpenSSL()
{
if(g_bOpenSSLLoaded)
return FALSE;
#ifdef ENABLE_PROCESS_PROTECTION
// 同梱するOpenSSLのバージョンに合わせてSHA1ハッシュ値を変更すること
// ssleay32.dll 1.0.0e
// libssl32.dll 1.0.0e
RegisterTrustedModuleSHA1Hash("\x4E\xB7\xA0\x22\x14\x4B\x58\x6D\xBC\xF5\x21\x0D\x96\x78\x0D\x79\x7D\x66\xB2\xB0");
// libeay32.dll 1.0.0e
RegisterTrustedModuleSHA1Hash("\x01\x32\x7A\xAE\x69\x26\xE6\x58\xC7\x63\x22\x1E\x53\x5A\x78\xBC\x61\xC7\xB5\xC1");
#endif
g_hOpenSSL = LoadLibrary("ssleay32.dll");
// バージョン固定のためlibssl32.dllの読み込みは脆弱性の原因になり得るので廃止
// if(!g_hOpenSSL)
// g_hOpenSSL = LoadLibrary("libssl32.dll");
if(!g_hOpenSSL
|| !(p_SSL_load_error_strings = (_SSL_load_error_strings)GetProcAddress(g_hOpenSSL, "SSL_load_error_strings"))
|| !(p_SSL_library_init = (_SSL_library_init)GetProcAddress(g_hOpenSSL, "SSL_library_init"))
|| !(p_SSLv23_method = (_SSLv23_method)GetProcAddress(g_hOpenSSL, "SSLv23_method"))
|| !(p_SSL_CTX_new = (_SSL_CTX_new)GetProcAddress(g_hOpenSSL, "SSL_CTX_new"))
|| !(p_SSL_CTX_free = (_SSL_CTX_free)GetProcAddress(g_hOpenSSL, "SSL_CTX_free"))
|| !(p_SSL_new = (_SSL_new)GetProcAddress(g_hOpenSSL, "SSL_new"))
|| !(p_SSL_free = (_SSL_free)GetProcAddress(g_hOpenSSL, "SSL_free"))
|| !(p_SSL_shutdown = (_SSL_shutdown)GetProcAddress(g_hOpenSSL, "SSL_shutdown"))
|| !(p_SSL_get_fd = (_SSL_get_fd)GetProcAddress(g_hOpenSSL, "SSL_get_fd"))
|| !(p_SSL_set_fd = (_SSL_set_fd)GetProcAddress(g_hOpenSSL, "SSL_set_fd"))
|| !(p_SSL_accept = (_SSL_accept)GetProcAddress(g_hOpenSSL, "SSL_accept"))
|| !(p_SSL_connect = (_SSL_connect)GetProcAddress(g_hOpenSSL, "SSL_connect"))
|| !(p_SSL_write = (_SSL_write)GetProcAddress(g_hOpenSSL, "SSL_write"))
|| !(p_SSL_peek = (_SSL_peek)GetProcAddress(g_hOpenSSL, "SSL_peek"))
|| !(p_SSL_read = (_SSL_read)GetProcAddress(g_hOpenSSL, "SSL_read"))
|| !(p_SSL_get_error = (_SSL_get_error)GetProcAddress(g_hOpenSSL, "SSL_get_error"))
|| !(p_SSL_get_peer_certificate = (_SSL_get_peer_certificate)GetProcAddress(g_hOpenSSL, "SSL_get_peer_certificate"))
|| !(p_SSL_get_verify_result = (_SSL_get_verify_result)GetProcAddress(g_hOpenSSL, "SSL_get_verify_result"))
|| !(p_SSL_get_session = (_SSL_get_session)GetProcAddress(g_hOpenSSL, "SSL_get_session"))
|| !(p_SSL_set_session = (_SSL_set_session)GetProcAddress(g_hOpenSSL, "SSL_set_session"))
|| !(p_SSL_CTX_get_cert_store = (_SSL_CTX_get_cert_store)GetProcAddress(g_hOpenSSL, "SSL_CTX_get_cert_store")))
{
if(g_hOpenSSL)
FreeLibrary(g_hOpenSSL);
g_hOpenSSL = NULL;
return FALSE;
}
g_hOpenSSLCommon = LoadLibrary("libeay32.dll");
if(!g_hOpenSSLCommon
|| !(p_BIO_s_mem = (_BIO_s_mem)GetProcAddress(g_hOpenSSLCommon, "BIO_s_mem"))
|| !(p_BIO_new = (_BIO_new)GetProcAddress(g_hOpenSSLCommon, "BIO_new"))
|| !(p_BIO_free = (_BIO_free)GetProcAddress(g_hOpenSSLCommon, "BIO_free"))
|| !(p_BIO_new_mem_buf = (_BIO_new_mem_buf)GetProcAddress(g_hOpenSSLCommon, "BIO_new_mem_buf"))
|| !(p_BIO_ctrl = (_BIO_ctrl)GetProcAddress(g_hOpenSSLCommon, "BIO_ctrl"))
|| !(p_X509_free = (_X509_free)GetProcAddress(g_hOpenSSLCommon, "X509_free"))
|| !(p_X509_print_ex = (_X509_print_ex)GetProcAddress(g_hOpenSSLCommon, "X509_print_ex"))
|| !(p_X509_get_subject_name = (_X509_get_subject_name)GetProcAddress(g_hOpenSSLCommon, "X509_get_subject_name"))
|| !(p_X509_NAME_print_ex = (_X509_NAME_print_ex)GetProcAddress(g_hOpenSSLCommon, "X509_NAME_print_ex"))
|| !(p_PEM_read_bio_X509 = (_PEM_read_bio_X509)GetProcAddress(g_hOpenSSLCommon, "PEM_read_bio_X509"))
|| !(p_X509_STORE_add_cert = (_X509_STORE_add_cert)GetProcAddress(g_hOpenSSLCommon, "X509_STORE_add_cert")))
{
if(g_hOpenSSL)
FreeLibrary(g_hOpenSSL);
g_hOpenSSL = NULL;
if(g_hOpenSSLCommon)
FreeLibrary(g_hOpenSSLCommon);
g_hOpenSSLCommon = NULL;
return FALSE;
}
InitializeCriticalSection(&g_OpenSSLLock);
p_SSL_load_error_strings();
p_SSL_library_init();
SetSSLTimeoutCallback(60000, DefaultSSLTimeoutCallback);
SetSSLConfirmCallback(DefaultSSLConfirmCallback);
g_bOpenSSLLoaded = TRUE;
return TRUE;
}
// OpenSSLを解放
void FreeOpenSSL()
{
int i;
if(!g_bOpenSSLLoaded)
return;
EnterCriticalSection(&g_OpenSSLLock);
for(i = 0; i < MAX_SSL_SOCKET; i++)
{
if(g_pOpenSSLHandle[i])
{
p_SSL_shutdown(g_pOpenSSLHandle[i]);
p_SSL_free(g_pOpenSSLHandle[i]);
g_pOpenSSLHandle[i] = NULL;
}
}
if(g_pOpenSSLCTX)
p_SSL_CTX_free(g_pOpenSSLCTX);
g_pOpenSSLCTX = NULL;
FreeLibrary(g_hOpenSSL);
g_hOpenSSL = NULL;
FreeLibrary(g_hOpenSSLCommon);
g_hOpenSSLCommon = NULL;
LeaveCriticalSection(&g_OpenSSLLock);
DeleteCriticalSection(&g_OpenSSLLock);
g_bOpenSSLLoaded = FALSE;
}
// OpenSSLが使用可能かどうか確認
BOOL IsOpenSSLLoaded()
{
return g_bOpenSSLLoaded;
}
SSL** GetUnusedSSLPointer()
{
int i;
for(i = 0; i < MAX_SSL_SOCKET; i++)
{
if(!g_pOpenSSLHandle[i])
return &g_pOpenSSLHandle[i];
}
return NULL;
}
SSL** FindSSLPointerFromSocket(SOCKET s)
{
int i;
for(i = 0; i < MAX_SSL_SOCKET; i++)
{
if(g_pOpenSSLHandle[i])
{
if(p_SSL_get_fd(g_pOpenSSLHandle[i]) == s)
return &g_pOpenSSLHandle[i];
}
}
return NULL;
}
BOOL ConfirmSSLCertificate(SSL* pSSL, BOOL* pbAborted)
{
BOOL bResult;
BOOL bVerified;
char* pData;
char* pSubject;
X509* pX509;
BIO* pBIO;
long Length;
char* pBuffer;
char* pCN;
char* p;
bResult = FALSE;
bVerified = FALSE;
pData = NULL;
pSubject = NULL;
if(pX509 = p_SSL_get_peer_certificate(pSSL))
{
if(pBIO = p_BIO_new(p_BIO_s_mem()))
{
p_X509_print_ex(pBIO, pX509, 0, XN_FLAG_RFC2253);
if((Length = p_BIO_ctrl(pBIO, BIO_CTRL_INFO, 0, &pBuffer)) > 0)
{
if(pData = (char*)malloc(Length + sizeof(char)))
{
memcpy(pData, pBuffer, Length);
*(char*)((size_t)pData + Length) = '\0';
}
}
p_BIO_free(pBIO);
}
if(pBIO = p_BIO_new(p_BIO_s_mem()))
{
p_X509_NAME_print_ex(pBIO, p_X509_get_subject_name(pX509), 0, XN_FLAG_RFC2253);
if((Length = p_BIO_ctrl(pBIO, BIO_CTRL_INFO, 0, &pBuffer)) > 0)
{
if(pSubject = (char*)malloc(Length + sizeof(char)))
{
memcpy(pSubject, pBuffer, Length);
*(char*)((size_t)pSubject + Length) = '\0';
}
}
p_BIO_free(pBIO);
}
p_X509_free(pX509);
}
if(pX509 && p_SSL_get_verify_result(pSSL) == X509_V_OK)
bVerified = TRUE;
pCN = pSubject;
while(pCN)
{
if(strncmp(pCN, "CN=", strlen("CN=")) == 0)
{
pCN += strlen("CN=");
if(p = strchr(pCN, ','))
*p = '\0';
break;
}
if(pCN = strchr(pCN, ','))
pCN++;
}
bResult = g_pOpenSSLConfirmCallback(pbAborted, bVerified, pData, pCN);
if(pData)
free(pData);
if(pSubject)
free(pSubject);
return bResult;
}
void SetSSLTimeoutCallback(DWORD Timeout, LPSSLTIMEOUTCALLBACK pCallback)
{
if(!g_bOpenSSLLoaded)
return;
EnterCriticalSection(&g_OpenSSLLock);
g_OpenSSLTimeout = Timeout;
g_pOpenSSLTimeoutCallback = pCallback;
LeaveCriticalSection(&g_OpenSSLLock);
}
void SetSSLConfirmCallback(LPSSLCONFIRMCALLBACK pCallback)
{
if(!g_bOpenSSLLoaded)
return;
EnterCriticalSection(&g_OpenSSLLock);
g_pOpenSSLConfirmCallback = pCallback;
LeaveCriticalSection(&g_OpenSSLLock);
}
// SSLルート証明書を設定
// PEM形式のみ指定可能
BOOL SetSSLRootCertificate(const void* pData, DWORD Length)
{
BOOL r;
X509_STORE* pStore;
BYTE* p;
BYTE* pBegin;
BYTE* pEnd;
BIO* pBIO;
X509* pX509;
if(!g_bOpenSSLLoaded)
return FALSE;
r = FALSE;
EnterCriticalSection(&g_OpenSSLLock);
if(!g_pOpenSSLCTX)
g_pOpenSSLCTX = p_SSL_CTX_new(p_SSLv23_method());
if(g_pOpenSSLCTX)
{
if(pStore = p_SSL_CTX_get_cert_store(g_pOpenSSLCTX))
{
p = (BYTE*)pData;
pBegin = NULL;
pEnd = NULL;
while(Length > 0)
{
if(!pBegin)
{
if(Length < 27)
break;
if(memcmp(p, "-----BEGIN CERTIFICATE-----", 27) == 0)
pBegin = p;
}
else if(!pEnd)
{
if(Length < 25)
break;
if(memcmp(p, "-----END CERTIFICATE-----", 25) == 0)
pEnd = p + 25;
}
if(pBegin && pEnd)
{
if(pBIO = p_BIO_new_mem_buf(pBegin, (int)((size_t)pEnd - (size_t)pBegin)))
{
if(pX509 = p_PEM_read_bio_X509(pBIO, NULL, NULL, NULL))
{
if(p_X509_STORE_add_cert(pStore, pX509) == 1)
r = TRUE;
p_X509_free(pX509);
}
p_BIO_free(pBIO);
}
pBegin = NULL;
pEnd = NULL;
}
p++;
Length--;
}
}
}
LeaveCriticalSection(&g_OpenSSLLock);
return r;
}
// ワイルドカードの比較
// 主にSSL証明書のCN確認用
BOOL IsHostNameMatched(LPCSTR HostName, LPCSTR CommonName)
{
BOOL bResult;
const char* pAsterisk;
size_t BeforeAsterisk;
const char* pBeginAsterisk;
const char* pEndAsterisk;
const char* pDot;
bResult = FALSE;
if(HostName && CommonName)
{
if(pAsterisk = strchr(CommonName, '*'))
{
BeforeAsterisk = ((size_t)pAsterisk - (size_t)CommonName) / sizeof(char);
pBeginAsterisk = HostName + BeforeAsterisk;
while(*pAsterisk == '*')
{
pAsterisk++;
}
pEndAsterisk = HostName + strlen(HostName) - strlen(pAsterisk);
// "*"より前は大文字小文字を無視して完全一致
if(_strnicmp(HostName, CommonName, BeforeAsterisk) == 0)
{
// "*"より後は大文字小文字を無視して完全一致
if(_stricmp(pEndAsterisk, pAsterisk) == 0)
{
// "*"と一致する範囲に"."が含まれてはならない
pDot = strchr(pBeginAsterisk, '.');
if(!pDot || pDot >= pEndAsterisk)
bResult = TRUE;
}
}
}
else if(_stricmp(HostName, CommonName) == 0)
bResult = TRUE;
}
return bResult;
}
// SSLセッションを開始
BOOL AttachSSL(SOCKET s, SOCKET parent, BOOL* pbAborted)
{
BOOL r;
DWORD Time;
SSL** ppSSL;
SSL** ppSSLParent;
SSL_SESSION* pSession;
int Return;
int Error;
if(!g_bOpenSSLLoaded)
return FALSE;
r = FALSE;
Time = timeGetTime();
EnterCriticalSection(&g_OpenSSLLock);
if(!g_pOpenSSLCTX)
g_pOpenSSLCTX = p_SSL_CTX_new(p_SSLv23_method());
if(g_pOpenSSLCTX)
{
if(ppSSL = GetUnusedSSLPointer())
{
if(*ppSSL = p_SSL_new(g_pOpenSSLCTX))
{
if(p_SSL_set_fd(*ppSSL, s) != 0)
{
if(parent != INVALID_SOCKET)
{
if(ppSSLParent = FindSSLPointerFromSocket(parent))
{
if(pSession = p_SSL_get_session(*ppSSLParent))
{
if(p_SSL_set_session(*ppSSL, pSession) == 1)
{
}
}
}
}
// SSLのネゴシエーションには時間がかかる場合がある
r = TRUE;
while(r)
{
Return = p_SSL_connect(*ppSSL);
if(Return == 1)
break;
Error = p_SSL_get_error(*ppSSL, Return);
if(Error == SSL_ERROR_WANT_READ || Error == SSL_ERROR_WANT_WRITE)
{
LeaveCriticalSection(&g_OpenSSLLock);
if(g_pOpenSSLTimeoutCallback(pbAborted) || (g_OpenSSLTimeout > 0 && timeGetTime() - Time >= g_OpenSSLTimeout))
r = FALSE;
EnterCriticalSection(&g_OpenSSLLock);
}
else
r = FALSE;
}
if(r)
{
if(ConfirmSSLCertificate(*ppSSL, pbAborted))
{
}
else
{
LeaveCriticalSection(&g_OpenSSLLock);
DetachSSL(s);
r = FALSE;
EnterCriticalSection(&g_OpenSSLLock);
}
}
else
{
LeaveCriticalSection(&g_OpenSSLLock);
DetachSSL(s);
EnterCriticalSection(&g_OpenSSLLock);
}
}
else
{
LeaveCriticalSection(&g_OpenSSLLock);
DetachSSL(s);
EnterCriticalSection(&g_OpenSSLLock);
}
}
}
}
LeaveCriticalSection(&g_OpenSSLLock);
return r;
}
// SSLセッションを終了
BOOL DetachSSL(SOCKET s)
{
BOOL r;
SSL** ppSSL;
if(!g_bOpenSSLLoaded)
return FALSE;
r = FALSE;
EnterCriticalSection(&g_OpenSSLLock);
if(ppSSL = FindSSLPointerFromSocket(s))
{
p_SSL_shutdown(*ppSSL);
p_SSL_free(*ppSSL);
*ppSSL = NULL;
r = TRUE;
}
LeaveCriticalSection(&g_OpenSSLLock);
return r;
}
// SSLとしてマークされているか確認
// マークされていればTRUEを返す
BOOL IsSSLAttached(SOCKET s)
{
SSL** ppSSL;
if(!g_bOpenSSLLoaded)
return FALSE;
EnterCriticalSection(&g_OpenSSLLock);
ppSSL = FindSSLPointerFromSocket(s);
LeaveCriticalSection(&g_OpenSSLLock);
if(!ppSSL)
return FALSE;
return TRUE;
}
SOCKET FTPS_socket(int af, int type, int protocol)
{
return socket(af, type, protocol);
}
int FTPS_bind(SOCKET s, const struct sockaddr *addr, int namelen)
{
return bind(s, addr, namelen);
}
int FTPS_listen(SOCKET s, int backlog)
{
return listen(s, backlog);
}
// accept相当の関数
// ただし初めからSSLのネゴシエーションを行う
SOCKET FTPS_accept(SOCKET s, struct sockaddr *addr, int *addrlen)
{
SOCKET r;
BOOL bAborted;
r = accept(s, addr, addrlen);
bAborted = FALSE;
if(!AttachSSL(r, INVALID_SOCKET, &bAborted))
{
closesocket(r);
return INVALID_SOCKET;
}
return r;
}
// connect相当の関数
// ただし初めからSSLのネゴシエーションを行う
int FTPS_connect(SOCKET s, const struct sockaddr *name, int namelen)
{
int r;
BOOL bAborted;
r = connect(s, name, namelen);
bAborted = FALSE;
if(!AttachSSL(r, INVALID_SOCKET, &bAborted))
return SOCKET_ERROR;
return r;
}
// closesocket相当の関数
int FTPS_closesocket(SOCKET s)
{
DetachSSL(s);
return closesocket(s);
}
// send相当の関数
int FTPS_send(SOCKET s, const char * buf, int len, int flags)
{
SSL** ppSSL;
if(!g_bOpenSSLLoaded)
return send(s, buf, len, flags);
EnterCriticalSection(&g_OpenSSLLock);
ppSSL = FindSSLPointerFromSocket(s);
LeaveCriticalSection(&g_OpenSSLLock);
if(!ppSSL)
return send(s, buf, len, flags);
return p_SSL_write(*ppSSL, buf, len);
}
// recv相当の関数
int FTPS_recv(SOCKET s, char * buf, int len, int flags)
{
SSL** ppSSL;
if(!g_bOpenSSLLoaded)
return recv(s, buf, len, flags);
EnterCriticalSection(&g_OpenSSLLock);
ppSSL = FindSSLPointerFromSocket(s);
LeaveCriticalSection(&g_OpenSSLLock);
if(!ppSSL)
return recv(s, buf, len, flags);
if(flags & MSG_PEEK)
return p_SSL_peek(*ppSSL, buf, len);
return p_SSL_read(*ppSSL, buf, len);
}
// IPv6対応
typedef struct
{
HANDLE h;
HWND hWnd;
u_int wMsg;
char * name;
char * buf;
int buflen;
short Family;
} GETHOSTBYNAMEDATA;
DWORD WINAPI WSAAsyncGetHostByNameIPv6ThreadProc(LPVOID lpParameter)
{
GETHOSTBYNAMEDATA* pData;
struct hostent* pHost;
struct addrinfo* pAddr;
struct addrinfo* p;
pHost = NULL;
pData = (GETHOSTBYNAMEDATA*)lpParameter;
if(getaddrinfo(pData->name, NULL, NULL, &pAddr) == 0)
{
p = pAddr;
while(p)
{
if(p->ai_family == pData->Family)
{
switch(p->ai_family)
{
case AF_INET:
pHost = (struct hostent*)pData->buf;
if((size_t)pData->buflen >= sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in_addr)
&& p->ai_addrlen >= sizeof(struct sockaddr_in))
{
pHost->h_name = NULL;
pHost->h_aliases = NULL;
pHost->h_addrtype = p->ai_family;
pHost->h_length = sizeof(struct in_addr);
pHost->h_addr_list = (char**)(&pHost[1]);
pHost->h_addr_list[0] = (char*)(&pHost->h_addr_list[2]);
pHost->h_addr_list[1] = NULL;
memcpy(pHost->h_addr_list[0], &((struct sockaddr_in*)p->ai_addr)->sin_addr, sizeof(struct in_addr));
PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(sizeof(struct hostent) + sizeof(char*) * 2 + p->ai_addrlen));
}
else
PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(WSAENOBUFS << 16));
break;
case AF_INET6:
pHost = (struct hostent*)pData->buf;
if((size_t)pData->buflen >= sizeof(struct hostent) + sizeof(char*) * 2 + sizeof(struct in6_addr)
&& p->ai_addrlen >= sizeof(struct sockaddr_in6))
{
pHost->h_name = NULL;
pHost->h_aliases = NULL;
pHost->h_addrtype = p->ai_family;
pHost->h_length = sizeof(struct in6_addr);
pHost->h_addr_list = (char**)(&pHost[1]);
pHost->h_addr_list[0] = (char*)(&pHost->h_addr_list[2]);
pHost->h_addr_list[1] = NULL;
memcpy(pHost->h_addr_list[0], &((struct sockaddr_in6*)p->ai_addr)->sin6_addr, sizeof(struct in6_addr));
PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(sizeof(struct hostent) + sizeof(char*) * 2 + p->ai_addrlen));
}
else
PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(WSAENOBUFS << 16));
break;
}
}
if(pHost)
break;
p = p->ai_next;
}
if(!p)
PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(ERROR_INVALID_FUNCTION << 16));
freeaddrinfo(pAddr);
}
else
PostMessage(pData->hWnd, pData->wMsg, (WPARAM)pData->h, (LPARAM)(ERROR_INVALID_FUNCTION << 16));
free(pData->name);
free(pData);
// CreateThreadが返すハンドルが重複するのを回避
Sleep(10000);
return 0;
}
// IPv6対応のWSAAsyncGetHostByName相当の関数
// FamilyにはAF_INETまたはAF_INET6を指定可能
// ただしANSI用
HANDLE WSAAsyncGetHostByNameIPv6(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen, short Family)
{
HANDLE hResult;
GETHOSTBYNAMEDATA* pData;
hResult = NULL;
if(pData = malloc(sizeof(GETHOSTBYNAMEDATA)))
{
pData->hWnd = hWnd;
pData->wMsg = wMsg;
if(pData->name = malloc(sizeof(char) * (strlen(name) + 1)))
{
strcpy(pData->name, name);
pData->buf = buf;
pData->buflen = buflen;
pData->Family = Family;
if(pData->h = CreateThread(NULL, 0, WSAAsyncGetHostByNameIPv6ThreadProc, pData, CREATE_SUSPENDED, NULL))
{
ResumeThread(pData->h);
hResult = pData->h;
}
}
}
if(!hResult)
{
if(pData)
{
if(pData->name)
free(pData->name);
free(pData);
}
}
return hResult;
}
// WSAAsyncGetHostByNameIPv6用のWSACancelAsyncRequest相当の関数
int WSACancelAsyncRequestIPv6(HANDLE hAsyncTaskHandle)
{
int Result;
Result = SOCKET_ERROR;
if(TerminateThread(hAsyncTaskHandle, 0))
Result = 0;
return Result;
}
char* AddressToStringIPv6(char* str, void* in6)
{
char* pResult;
unsigned char* p;
int MaxZero;
int MaxZeroLen;
int i;
int j;
char Tmp[5];
pResult = str;
p = (unsigned char*)in6;
MaxZero = 8;
MaxZeroLen = 1;
for(i = 0; i < 8; i++)
{
for(j = i; j < 8; j++)
{
if(p[j * 2] != 0 || p[j * 2 + 1] != 0)
break;
}
if(j - i > MaxZeroLen)
{
MaxZero = i;
MaxZeroLen = j - i;
}
}
strcpy(str, "");
for(i = 0; i < 8; i++)
{
if(i == MaxZero)
{
if(i == 0)
strcat(str, ":");
strcat(str, ":");
}
else if(i < MaxZero || i >= MaxZero + MaxZeroLen)
{
sprintf(Tmp, "%x", (((int)p[i * 2] & 0xff) << 8) | ((int)p[i * 2 + 1] & 0xff));
strcat(str, Tmp);
if(i < 7)
strcat(str, ":");
}
}
return pResult;
}
// IPv6対応のinet_ntoa相当の関数
// ただしANSI用
char* inet6_ntoa(struct in6_addr in6)
{
char* pResult;
static char Adrs[40];
pResult = NULL;
memset(Adrs, 0, sizeof(Adrs));
pResult = AddressToStringIPv6(Adrs, &in6);
return pResult;
}
// IPv6対応のinet_addr相当の関数
// ただしANSI用
struct in6_addr inet6_addr(const char* cp)
{
struct in6_addr Result;
int AfterZero;
int i;
char* p;
memset(&Result, 0, sizeof(Result));
AfterZero = 0;
for(i = 0; i < 8; i++)
{
if(!cp)
{
memset(&Result, 0xff, sizeof(Result));
break;
}
if(i >= AfterZero)
{
if(strncmp(cp, ":", 1) == 0)
{
cp = cp + 1;
if(i == 0 && strncmp(cp, ":", 1) == 0)
cp = cp + 1;
p = (char*)cp;
AfterZero = 7;
while(p = strstr(p, ":"))
{
p = p + 1;
AfterZero--;
}
}
else
{
Result.u.Word[i] = (USHORT)strtol(cp, &p, 16);
Result.u.Word[i] = ((Result.u.Word[i] & 0xff00) >> 8) | ((Result.u.Word[i] & 0x00ff) << 8);
if(strncmp(p, ":", 1) != 0 && strlen(p) > 0)
{
memset(&Result, 0xff, sizeof(Result));
break;
}
if(cp = strstr(cp, ":"))
cp = cp + 1;
}
}
}
return Result;
}
BOOL ConvertDomainNameToPunycode(LPSTR Output, DWORD Count, LPCSTR Input)
{
BOOL bResult;
punycode_uint* pUnicode;
punycode_uint* p;
BOOL bNeeded;
LPCSTR InputString;
punycode_uint Length;
punycode_uint OutputLength;
bResult = FALSE;
if(pUnicode = malloc(sizeof(punycode_uint) * strlen(Input)))
{
p = pUnicode;
bNeeded = FALSE;
InputString = Input;
Length = 0;
while(*InputString != '\0')
{
*p = (punycode_uint)GetNextCharM(InputString, &InputString);
if(*p >= 0x80)
bNeeded = TRUE;
p++;
Length++;
}
if(bNeeded)
{
if(Count >= strlen("xn--") + 1)
{
strcpy(Output, "xn--");
OutputLength = Count - strlen("xn--");
if(punycode_encode(Length, pUnicode, NULL, (punycode_uint*)&OutputLength, Output + strlen("xn--")) == punycode_success)
{
Output[strlen("xn--") + OutputLength] = '\0';
bResult = TRUE;
}
}
}
free(pUnicode);
}
if(!bResult)
{
if(Count >= strlen(Input) + 1)
{
strcpy(Output, Input);
bResult = TRUE;
}
}
return bResult;
}
BOOL ConvertNameToPunycode(LPSTR Output, LPCSTR Input)
{
BOOL bResult;
DWORD Length;
char* pm0;
char* pm1;
char* p;
char* pNext;
bResult = FALSE;
Length = strlen(Input);
if(pm0 = AllocateStringM(Length + 1))
{
if(pm1 = AllocateStringM(Length * 4 + 1))
{
strcpy(pm0, Input);
p = pm0;
while(p)
{
if(pNext = strchr(p, '.'))
{
*pNext = '\0';
pNext++;
}
if(ConvertDomainNameToPunycode(pm1, Length * 4, p))
strcat(Output, pm1);
if(pNext)
strcat(Output, ".");
p = pNext;
}
bResult = TRUE;
FreeDuplicatedString(pm1);
}
FreeDuplicatedString(pm0);
}
return bResult;
}
HANDLE WSAAsyncGetHostByNameM(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen)
{
HANDLE r = NULL;
char* pa0 = NULL;
if(pa0 = AllocateStringA(strlen(name) * 4))
{
if(ConvertNameToPunycode(pa0, name))
r = WSAAsyncGetHostByName(hWnd, wMsg, pa0, buf, buflen);
}
FreeDuplicatedString(pa0);
return r;
}
HANDLE WSAAsyncGetHostByNameIPv6M(HWND hWnd, u_int wMsg, const char * name, char * buf, int buflen, short Family)
{
HANDLE r = NULL;
char* pa0 = NULL;
if(pa0 = AllocateStringA(strlen(name) * 4))
{
if(ConvertNameToPunycode(pa0, name))
r = WSAAsyncGetHostByNameIPv6(hWnd, wMsg, pa0, buf, buflen, Family);
}
FreeDuplicatedString(pa0);
return r;
}
// SFTP対応
typedef void* (__cdecl* _SFTP_Create)();
typedef void (__cdecl* _SFTP_Destroy)(void*);
typedef BOOL (__cdecl* _SFTP_IsExited)(void*);
typedef BOOL (__cdecl* _SFTP_SetTimeoutCallback)(void*, void*);
typedef size_t (__cdecl* _SFTP_PeekStdOut)(void*, void*, size_t);