-
Notifications
You must be signed in to change notification settings - Fork 2
/
sspisvcs.c
1843 lines (1642 loc) · 44.6 KB
/
sspisvcs.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
/*-------
* Module: sspisvcs.c
*
* Description: This module contains functions for low level socket
* operations (connecting/reading/writing to the backend)
*
* Classes: SocketClass (Functions prefix: "SOCK_")
*
* API functions: none
*
* Comments: See "readme.txt" for copyright and license information.
*-------
*/
#ifdef USE_SSPI
#define SECURITY_WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <security.h>
#include <sspi.h>
#pragma comment(lib, "secur32.lib")
#include "sspisvcs.h"
#include "socket.h"
#include "connection.h"
#include "environ.h"
/*
* To handle EWOULDBLOCK etc (mainly for libpq non-blocking connection).
*/
#define MAX_RETRY_COUNT 30
static int Socket_wait_for_ready(SOCKET socket, BOOL output, int retry_count)
{
int ret, gerrno;
fd_set fds, except_fds;
struct timeval tm;
BOOL no_timeout = (retry_count < 0);
do {
FD_ZERO(&fds);
FD_ZERO(&except_fds);
FD_SET(socket, &fds);
FD_SET(socket, &except_fds);
if (!no_timeout)
{
tm.tv_sec = retry_count;
tm.tv_usec = 0;
}
ret = select((int) socket + 1, output ? NULL : &fds, output ? &fds : NULL, &except_fds, no_timeout ? NULL : &tm);
gerrno = SOCK_ERRNO;
} while (ret < 0 && EINTR == gerrno);
if (retry_count < 0)
retry_count *= -1;
if (0 == ret && retry_count > MAX_RETRY_COUNT)
{
ret = -1;
}
return ret;
}
static int sendall(SOCKET sock, const void *buf, int len)
{
CSTR func = "sendall";
int wrtlen, ttllen, reqlen, retry_count;
retry_count = 0;
for (ttllen = 0, reqlen = len; reqlen > 0;)
{
if (0 > (wrtlen = send(sock, (const char *) buf + ttllen, reqlen, SEND_FLAG)))
{
int gerrno = SOCK_ERRNO;
mylog("%s:errno=%d\n", func, gerrno);
switch (gerrno)
{
case EINTR:
continue;
case EWOULDBLOCK:
retry_count++;
if (Socket_wait_for_ready(sock, TRUE, retry_count) >= 0)
continue;
break;
case ECONNRESET:
return 0;
}
return SOCKET_ERROR;
}
ttllen += wrtlen;
reqlen -= wrtlen;
retry_count = 0;
}
return ttllen;
}
static int recvall(SOCKET sock, void *buf, int len)
{
CSTR func = "recvall";
int rcvlen, ttllen, reqlen, retry_count = 0;
for (ttllen = 0, reqlen = len; reqlen > 0;)
{
if (0 > (rcvlen = recv(sock, (char *) buf + ttllen, reqlen, RECV_FLAG)))
{
int gerrno = SOCK_ERRNO;
switch (gerrno)
{
case EINTR:
continue;
case EWOULDBLOCK:
retry_count++;
if (Socket_wait_for_ready(sock, FALSE, retry_count) >= 0)
continue;
break;
case ECONNRESET:
return 0;
}
return -1;
}
ttllen += rcvlen;
reqlen -= rcvlen;
retry_count = 0;
}
return ttllen;
}
/*
* service specific data
*/
/* Schannel specific data */
typedef struct {
CredHandle hCred;
CtxtHandle hCtxt;
PBYTE ioovrbuf;
size_t ioovrlen;
PBYTE iobuf;
size_t iobuflen;
size_t ioread;
} SchannelSpec;
/* Kerberos/Negotiate common specific data */
typedef struct {
LPTSTR svcprinc;
CredHandle hKerbEtcCred;
BOOL ValidCtxt;
CtxtHandle hKerbEtcCtxt;
} KerberosEtcSpec;
typedef struct {
SchannelSpec sdata;
KerberosEtcSpec kdata;
} SspiData;
static int DoSchannelNegotiation(SocketClass *, SspiData *, const void *opt, int *bReconnect);
static int DoKerberosNegotiation(SocketClass *, SspiData *, const void *opt, int *bReconnect);
static int DoNegotiateNegotiation(SocketClass *, SspiData *, const void *opt, int *bReconnect);
static int DoKerberosEtcProcessAuthentication(SocketClass *, const void *opt);
static SspiData *SspiDataAlloc(SocketClass *self)
{
SspiData *sspidata;
if (sspidata = self->ssd, !sspidata)
sspidata = calloc(sizeof(SspiData), 1);
return sspidata;
}
int StartupSspiService(SocketClass *self, SSPI_Service svc, const void *opt, int *bReconnect)
{
CSTR func = "DoServicelNegotiation";
SspiData *sspidata;
if (bReconnect != NULL)
*bReconnect = 0;
if (NULL == (sspidata = SspiDataAlloc(self)))
return -1;
switch (svc)
{
case SchannelService:
return DoSchannelNegotiation(self, sspidata, opt, bReconnect);
case KerberosService:
return DoKerberosNegotiation(self, sspidata, opt, bReconnect);
case NegotiateService:
return DoNegotiateNegotiation(self, sspidata, opt, bReconnect);
}
free(sspidata);
return -1;
}
int ContinueSspiService(SocketClass *self, SSPI_Service svc, const void *opt)
{
CSTR func = "ContinueSspiService";
switch (svc)
{
case KerberosService:
case NegotiateService:
return DoKerberosEtcProcessAuthentication(self, opt);
}
return -1;
}
static BOOL format_sspierr(char *errmsg, size_t buflen, SECURITY_STATUS r, const char *cmd, const char *cmd2)
{
BOOL ret = FALSE;
if (!cmd2)
cmd2 = "";
if (FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL,
r, MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT),
errmsg, (DWORD)buflen, NULL))
ret = TRUE;
if (ret)
{
size_t tlen = strlen(errmsg);
errmsg += tlen;
buflen -= tlen;
snprintf(errmsg, buflen, " in %s:%s", cmd, cmd2);
}
else
snprintf(errmsg, buflen, "%s:%s failed ", cmd, cmd2);
return ret;
}
static void SSPI_set_error(SocketClass *s, SECURITY_STATUS r, const char *cmd, const char *cmd2)
{
int gerrno = SOCK_ERRNO;
char emsg[256];
format_sspierr(emsg, sizeof(emsg), r, cmd, cmd2);
s->errornumber = r;
if (NULL != s->_errormsg_)
free(s->_errormsg_);
if (NULL != emsg)
s->_errormsg_ = strdup(emsg);
else
s->_errormsg_ = NULL;
mylog("(%d)%s ERRNO=%d\n", r, emsg, gerrno);
}
/*
* Stuff for Schannel service
*/
#include <schannel.h>
#pragma comment(lib, "crypt32")
#define UNI_SCHANNEL TEXT("sChannel")
#define IO_BUFFER_SIZE 0x10000
static SECURITY_STATUS CreateSchannelCredentials(LPCTSTR, LPSTR, PCredHandle);
static SECURITY_STATUS PerformSchannelClientHandshake(SOCKET, PCredHandle, LPSTR, CtxtHandle *, SecBuffer *);
static SECURITY_STATUS SchannelClientHandshakeLoop(SOCKET, PCredHandle, CtxtHandle *, BOOL, SecBuffer *);
static void GetNewSchannelClientCredentials(PCredHandle, CtxtHandle *);
static BOOL bRootCALoaded = FALSE;
static BOOL bMyCert = FALSE;
static HCERTSTORE hMyCertStore = NULL;
static HCRYPTPROV hProv = (HCRYPTPROV) 0;
static PCCERT_CONTEXT pClientCertContext = NULL;
static void FreeCertStores(void)
{
shortterm_common_lock();
if (pClientCertContext)
{
CertFreeCertificateContext(pClientCertContext);
pClientCertContext = NULL;
}
if (hProv)
{
CryptReleaseContext(hProv, 0);
hProv = (HCRYPTPROV) 0;
}
if (hMyCertStore)
{
CertCloseStore(hMyCertStore, CERT_CLOSE_STORE_FORCE_FLAG);
hMyCertStore = NULL;
}
shortterm_common_unlock();
}
void LeaveSSPIService(void)
{
FreeCertStores();
bMyCert = FALSE;
bRootCALoaded = FALSE;
}
/*
* This driver allows certificates of PFX form when a pair of
* postgresql.crt and postgresql.key doesn't work well.
*/
static void CertStoreInit_pfx(void)
{
BOOL success = FALSE;
LPCTSTR pgsslpfx = NULL;
LPCTSTR appdata = NULL;
TCHAR sslpfx[256];
HANDLE fd = INVALID_HANDLE_VALUE;
DWORD flen, rlen;
CRYPT_DATA_BLOB crypt_data;
if (bMyCert) return;
if (hMyCertStore != NULL) return;
bMyCert = TRUE;
pgsslpfx = getenv("PGSSLPFX");
if (!pgsslpfx)
{
if (!appdata)
appdata = getenv("APPDATA");
if (!appdata) return;
snprintf(sslpfx, sizeof(sslpfx), "%s\\postgresql\\postgresql.pfx", appdata);
pgsslpfx = sslpfx;
}
fd = CreateFile(pgsslpfx, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == fd)
{
mylog("!!! pfxfile=%s not found\n", pgsslpfx);
goto cleanup;
}
flen = GetFileSize(fd, NULL);
if (flen <= 0)
{
goto cleanup;
}
crypt_data.cbData = flen;
crypt_data.pbData = (LPBYTE) CryptMemAlloc(flen);
ReadFile(fd, crypt_data.pbData, flen, &rlen, NULL);
CloseHandle(fd);
fd = INVALID_HANDLE_VALUE;
hMyCertStore = PFXImportCertStore(&crypt_data, L"", 0);
CryptMemFree(crypt_data.pbData);
success = TRUE;
cleanup:
if (fd != INVALID_HANDLE_VALUE)
CloseHandle(fd);
if (!success)
FreeCertStores();
}
static void CertStoreInit(void)
{
BOOL success = FALSE;
LPCTSTR pgsslkey = NULL, pgsslcert = NULL;
LPCTSTR appdata = NULL;
TCHAR sslkey[256], sslcert[256];
HANDLE fd = INVALID_HANDLE_VALUE;
DWORD flen, rlen;
char *pemdata = NULL;
DWORD dwBufferLen, cbKeyBlob;
LPBYTE pbBuffer = NULL, pbKeyBlob = NULL;
HCRYPTKEY hKey = (HCRYPTKEY) 0;
if (hMyCertStore != NULL) return;
bMyCert = TRUE;
pgsslkey = getenv("PGSSLKEY");
if (!pgsslkey)
{
if (!appdata)
appdata = getenv("APPDATA");
if (!appdata) goto cleanup;
snprintf(sslkey, sizeof(sslkey), "%s\\postgresql\\postgresql.key", appdata);
pgsslkey = sslkey;
}
fd = CreateFile(pgsslkey, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == fd)
{
mylog("!!! keyfile=%s not found\n", pgsslkey);
goto cleanup;
}
flen = GetFileSize(fd, NULL);
if (flen <= 0)
{
goto cleanup;
}
if (pemdata = malloc(flen), NULL == pemdata)
goto cleanup;
ReadFile(fd, pemdata, flen, &rlen, NULL);
CloseHandle(fd);
fd = INVALID_HANDLE_VALUE;
if (!CryptStringToBinaryA(pemdata, 0, CRYPT_STRING_BASE64HEADER,
NULL, &dwBufferLen, NULL, NULL))
{
mylog("Failed to convert BASE64 private key. Error 0x%.8X\n",
GetLastError());
goto cleanup;
}
if (pbBuffer = malloc(dwBufferLen), NULL == pbBuffer)
goto cleanup;
if (!CryptStringToBinaryA(pemdata, 0, CRYPT_STRING_BASE64HEADER,
pbBuffer, &dwBufferLen, NULL, NULL))
{
mylog("Failed to convert BASE64 private key. Error 0x%.8X\n", GetLastError());
goto cleanup;
}
free(pemdata);
pemdata = NULL;
if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
PKCS_RSA_PRIVATE_KEY, pbBuffer, dwBufferLen, 0, NULL, NULL, &cbKeyBlob))
{
mylog("Failed to parse private key. Error 0x%.8X\n", GetLastError());
goto cleanup;
}
if (pbKeyBlob = malloc(cbKeyBlob), NULL == pbKeyBlob)
goto cleanup;
if (!CryptDecodeObjectEx(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
PKCS_RSA_PRIVATE_KEY, pbBuffer, dwBufferLen, 0, NULL, pbKeyBlob, &cbKeyBlob))
{
mylog("Failed to parse private key. Error 0x%.8X\n", GetLastError());
goto cleanup;
}
free(pbBuffer);
pbBuffer = NULL;
// Create a temporary and volatile CSP context in order to import
// the key
if (!CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
{
mylog("CryptAcquireContext failed with error 0x%.8X\n", GetLastError());
goto cleanup;
}
// import private key
if (!CryptImportKey(hProv, pbKeyBlob, cbKeyBlob, (HCRYPTKEY) 0, 0, &hKey))
{
mylog("CryptImportKey failed with error 0x%.8X\n", GetLastError());
goto cleanup;
}
CryptDestroyKey(hKey);
hKey = (HCRYPTKEY) 0;
free(pbKeyBlob);
pbKeyBlob = NULL;
pgsslcert = getenv("PGSSLCERT");
if (!pgsslcert)
{
appdata = getenv("APPDATA");
if (!appdata) goto cleanup;
snprintf(sslcert, sizeof(sslcert), "%s\\postgresql\\postgresql.crt", appdata);
pgsslcert = sslcert;
}
hMyCertStore = CertOpenStore(
CERT_STORE_PROV_FILENAME_A
, 0
, (HCRYPTPROV) NULL
, CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG
, pgsslcert
);
mylog("!!! hMyCertStore=%p sslcert=%s sslkey=%s\n", hMyCertStore, pgsslcert, pgsslkey);
if (hMyCertStore != NULL)
{
PCCERT_CONTEXT pContext = NULL;
pContext = CertEnumCertificatesInStore(hMyCertStore, pContext);
while (pContext != NULL)
{
CertSetCertificateContextProperty(pContext, CERT_KEY_PROV_HANDLE_PROP_ID, 0, (const void *) hProv);
pContext = CertEnumCertificatesInStore(hMyCertStore, pContext);
}
}
success = TRUE;
cleanup:
if (pemdata)
free(pemdata);
if (pbBuffer)
free(pbBuffer);
if (pbKeyBlob)
free(pbKeyBlob);
if (fd != INVALID_HANDLE_VALUE)
CloseHandle(fd);
if (!success)
{
HCERTSTORE hSv = hMyCertStore;
FreeCertStores();
if (hSv == NULL)
CertStoreInit_pfx();
}
if (!hMyCertStore)
{
mylog("!!! hMyCertStore=%p %d\n", hMyCertStore, GetLastError());
}
return;
}
static int InstallRootCA(void)
{
HCERTSTORE hTempCertStore = NULL, hRootCertStore = NULL;
LPCTSTR pgsslroot = NULL;
LPCTSTR appdata = NULL;
TCHAR sslroot[256];
PCCERT_CONTEXT pContext = NULL;
int installed_count = 0, reject_count = 0;
shortterm_common_lock();
if (bRootCALoaded)
{
shortterm_common_unlock();
goto cleanup;
}
shortterm_common_unlock();
pgsslroot = getenv("PGSSLROOTCERT");
if (!pgsslroot)
{
appdata = getenv("APPDATA");
if (!appdata) goto cleanup;
snprintf(sslroot, sizeof(sslroot), "%s\\postgresql\\root.crt", appdata);
pgsslroot = sslroot;
}
hTempCertStore = CertOpenStore(
CERT_STORE_PROV_FILENAME_A
, 0
, (HCRYPTPROV) NULL
, CERT_STORE_OPEN_EXISTING_FLAG | CERT_STORE_READONLY_FLAG
, pgsslroot
);
if (hTempCertStore == NULL)
goto cleanup;
hRootCertStore = CertOpenSystemStore(0, TEXT("ROOT"));
mylog("hRootCertStore=%p sslroot=%s\n", hRootCertStore, pgsslroot);
if (hRootCertStore == NULL)
goto cleanup;
pContext = CertEnumCertificatesInStore(hTempCertStore, pContext);
while (pContext != NULL)
{
if (CertAddCertificateContextToStore(hRootCertStore, pContext, CERT_STORE_ADD_NEWER, NULL))
installed_count++;
else
{
int lasterror = GetLastError();
switch (lasterror)
{
case CRYPT_E_EXISTS:
mylog("Certificate already exists\n");
break;
case 1223: // ERROR_CANCELED
reject_count++;
mylog("Certificate canceled\n");
break;
default:
reject_count++;
mylog("Failed to install root certificate error=%08x\n", lasterror);
}
}
pContext = CertEnumCertificatesInStore(hRootCertStore, pContext);
}
shortterm_common_lock();
if (!bRootCALoaded)
{
if (installed_count > 0 || reject_count == 0)
bRootCALoaded = TRUE;
}
shortterm_common_unlock();
cleanup:
if (hTempCertStore)
CertCloseStore(hTempCertStore, CERT_CLOSE_STORE_FORCE_FLAG);
if (hRootCertStore)
CertCloseStore(hRootCertStore, CERT_CLOSE_STORE_FORCE_FLAG);
return installed_count;
}
static int DoSchannelNegotiation(SocketClass *self, SspiData *sspidata, const void *opt, int *bReconnect)
{
CSTR func = "DoSchannelNegotiation";
SECURITY_STATUS r = SEC_E_OK;
const char *cmd = NULL;
SecBuffer ExtraData;
BOOL ret = 0, cCreds = FALSE, cCtxt = FALSE;
SchannelSpec *ssd = &(sspidata->sdata);
char *server = NULL;
if (SEC_E_OK != (r = CreateSchannelCredentials(opt, NULL, &ssd->hCred)))
{
cmd = "CreateSchannelCredentials";
mylog("%s:%s failed\n", func, cmd);
goto cleanup;
}
cCreds = TRUE;
if (opt != NULL)
server = ((ConnInfo *) opt)->server;
if (SEC_E_OK != (r = PerformSchannelClientHandshake(self->socket, &ssd->hCred, server, &ssd->hCtxt, &ExtraData)))
{
cmd = "PerformSchannelClientHandshake";
switch (r)
{
case SEC_E_UNTRUSTED_ROOT:
mylog("Installing RootCA\n");
if (InstallRootCA() > 0)
*bReconnect = 1;
break;
default:
break;
}
mylog("%s:%s failed\n", func, cmd);
goto cleanup;
}
cCtxt = TRUE;
if (NULL != ExtraData.pvBuffer && 0 != ExtraData.cbBuffer)
{
ssd->iobuf = malloc(ExtraData.cbBuffer);
ssd->iobuflen =
ssd->ioread = ExtraData.cbBuffer;
memcpy(ssd->iobuf, ExtraData.pvBuffer, ssd->ioread);
free(ExtraData.pvBuffer);
}
ret = TRUE;
cleanup:
if (ret)
{
self->sspisvcs |= SchannelService;
self->ssd = sspidata;
}
else
{
SSPI_set_error(self, r, __FUNCTION__, cmd);
if (cCreds)
FreeCredentialHandle(&ssd->hCred);
if (cCtxt)
DeleteSecurityContext(&ssd->hCtxt);
if (ssd->iobuf)
free(ssd->iobuf);
if (!self->ssd)
free(sspidata);
}
return ret;
}
static
SECURITY_STATUS
CreateSchannelCredentials(
LPCTSTR opt, /* in */
LPSTR pszUserName, /* in */
PCredHandle phCreds) /* out */
{
TimeStamp tsExpiry;
SECURITY_STATUS Status;
SCHANNEL_CRED SchannelCred;
DWORD cSupportedAlgs = 0;
ALG_ID rgbSupportedAlgs[16];
DWORD dwProtocol = SP_PROT_SSL3 | SP_PROT_SSL2;
DWORD aiKeyExch = 0;
char *sslmode = NULL;
PCCERT_CONTEXT pCertContext = NULL;
/*
* If a user name is specified, then attempt to find a client
* certificate. Otherwise, just create a NULL credential.
*/
if (pClientCertContext)
pCertContext = pClientCertContext;
else if (pszUserName)
{
/* Find client certificate. Note that this sample just searchs for a
* certificate that contains the user name somewhere in the subject name.
* A real application should be a bit less casual.
*/
pCertContext = CertFindCertificateInStore(hMyCertStore,
X509_ASN_ENCODING,
0,
CERT_FIND_SUBJECT_STR_A,
pszUserName,
NULL);
if (pCertContext == NULL)
{
mylog("**** Error 0x%p returned by CertFindCertificateInStore\n",
GetLastError());
return SEC_E_NO_CREDENTIALS;
}
}
/*
* Build Schannel credential structure. Currently, this sample only
* specifies the protocol to be used (and optionally the certificate,
* of course). Real applications may wish to specify other parameters
* as well.
*/
ZeroMemory(&SchannelCred, sizeof(SchannelCred));
SchannelCred.dwVersion = SCHANNEL_CRED_VERSION;
if (pCertContext)
{
SchannelCred.cCreds = 1;
SchannelCred.paCred = &pCertContext;
}
SchannelCred.grbitEnabledProtocols = dwProtocol;
if (aiKeyExch)
{
rgbSupportedAlgs[cSupportedAlgs++] = aiKeyExch;
}
if (cSupportedAlgs)
{
SchannelCred.cSupportedAlgs = cSupportedAlgs;
SchannelCred.palgSupportedAlgs = rgbSupportedAlgs;
}
SchannelCred.dwFlags |= SCH_CRED_NO_DEFAULT_CREDS;
/* The SCH_CRED_MANUAL_CRED_VALIDATION flag is specified because
* this sample verifies the server certificate manually.
* Applications that expect to run on WinNT, Win9x, or WinME
* should specify this flag and also manually verify the server
* certificate. Applications running on newer versions of Windows can
* leave off this flag, in which case the InitializeSecurityContext
* function will validate the server certificate automatically.
*/
if (opt != NULL)
sslmode = ((ConnInfo *) opt)->sslmode;
if (sslmode == NULL || sslmode[0] != 'v')
SchannelCred.dwFlags |= SCH_CRED_MANUAL_CRED_VALIDATION;
else
{
if (strcmp(sslmode, "verify-full"))
SchannelCred.dwFlags |= SCH_CRED_NO_SERVERNAME_CHECK;
// InstallRootCA();
}
/*
* Create an SSPI credential.
*/
Status = AcquireCredentialsHandle(
NULL, /* Name of principal */
UNI_SCHANNEL, /* Name of package */
SECPKG_CRED_OUTBOUND, /* Flags indicating use */
NULL, /* Pointer to logon ID */
&SchannelCred, /* Package specific data */
NULL, /* Pointer to GetKey() func */
NULL, /* Value to pass to GetKey() */
phCreds, /* (out) Cred Handle */
&tsExpiry); /* (out) Lifetime (optional) */
if (Status != SEC_E_OK)
{
mylog("**** Error 0x%p returned by AcquireCredentialsHandle\n", Status);
goto cleanup;
}
cleanup:
/*
* Free the certificate context. Schannel has already made its own copy.
*/
if (pCertContext && pCertContext != pClientCertContext)
{
CertFreeCertificateContext(pCertContext);
}
return Status;
}
static
SECURITY_STATUS
PerformSchannelClientHandshake(
SOCKET Socket, /* in */
PCredHandle phCreds, /* in */
LPSTR pszServerName, /* in */
CtxtHandle *phContext, /* out */
SecBuffer *pExtraData) /* out */
{
SecBufferDesc OutBuffer;
SecBuffer OutBuffers[1];
DWORD dwSSPIFlags;
DWORD dwSSPIOutFlags;
TimeStamp tsExpiry;
SECURITY_STATUS scRet;
DWORD cbData;
dwSSPIFlags = ISC_REQ_SEQUENCE_DETECT |
ISC_REQ_REPLAY_DETECT |
ISC_REQ_CONFIDENTIALITY |
ISC_RET_EXTENDED_ERROR |
ISC_REQ_ALLOCATE_MEMORY |
ISC_REQ_STREAM;
/*
* Initiate a ClientHello message and generate a token.
*/
OutBuffers[0].pvBuffer = NULL;
OutBuffers[0].BufferType = SECBUFFER_TOKEN;
OutBuffers[0].cbBuffer = 0;
OutBuffer.cBuffers = 1;
OutBuffer.pBuffers = OutBuffers;
OutBuffer.ulVersion = SECBUFFER_VERSION;
scRet = InitializeSecurityContext(
phCreds,
NULL,
pszServerName,
dwSSPIFlags,
0,
SECURITY_NATIVE_DREP,
NULL,
0,
phContext,
&OutBuffer,
&dwSSPIOutFlags,
&tsExpiry);
if (scRet != SEC_I_CONTINUE_NEEDED)
{
mylog("**** Error %x returned by InitializeSecurityContext (1)\n", scRet);
return scRet;
}
/* Send response to server if there is one. */
if (OutBuffers[0].cbBuffer != 0 && OutBuffers[0].pvBuffer != NULL)
{
cbData = sendall(Socket,
OutBuffers[0].pvBuffer,
OutBuffers[0].cbBuffer);
if (cbData <= 0)
{
mylog("**** Error %x sending data to server\n", SOCK_ERRNO);
FreeContextBuffer(OutBuffers[0].pvBuffer);
DeleteSecurityContext(phContext);
return SEC_E_INTERNAL_ERROR;
}
mylog("%d bytes of handshake data sent\n", cbData);
/* Free output buffer. */
FreeContextBuffer(OutBuffers[0].pvBuffer);
OutBuffers[0].pvBuffer = NULL;
}
return SchannelClientHandshakeLoop(Socket, phCreds, phContext, TRUE, pExtraData);
}
static
SECURITY_STATUS
SchannelClientHandshakeLoop(
SOCKET Socket, /* in */
PCredHandle phCreds, /* in */
CtxtHandle *phContext, /* i-o */
BOOL fDoInitialRead, /* in */
SecBuffer *pExtraData) /* out */
{
SecBufferDesc InBuffer;
SecBuffer InBuffers[2];
SecBufferDesc OutBuffer;
SecBuffer OutBuffers[1];
DWORD dwSSPIFlags;
DWORD dwSSPIOutFlags;
TimeStamp tsExpiry;
SECURITY_STATUS scRet;
DWORD cbData;
PUCHAR IoBuffer;
DWORD cbIoBuffer;
BOOL fDoRead;
int retry_count;
dwSSPIFlags = ISC_REQ_SEQUENCE_DETECT |
ISC_REQ_REPLAY_DETECT |
ISC_REQ_CONFIDENTIALITY |
ISC_RET_EXTENDED_ERROR |
ISC_REQ_ALLOCATE_MEMORY |
ISC_REQ_STREAM;
/*
* Allocate data buffer.
*/
IoBuffer = malloc(IO_BUFFER_SIZE);
if (IoBuffer == NULL)
{
mylog("**** Out of memory (1)\n");
return SEC_E_INTERNAL_ERROR;
}
cbIoBuffer = 0;
fDoRead = fDoInitialRead;
/*
* Loop until the handshake is finished or an error occurs.
*/
retry_count = 0;
scRet = SEC_I_CONTINUE_NEEDED;
while (scRet == SEC_I_CONTINUE_NEEDED ||
scRet == SEC_E_INCOMPLETE_MESSAGE ||
scRet == SEC_I_INCOMPLETE_CREDENTIALS)
{
/*
* Read data from server.
*/
if( 0 == cbIoBuffer || scRet == SEC_E_INCOMPLETE_MESSAGE)
{
if (fDoRead)
{
cbData = recv(Socket,
IoBuffer + cbIoBuffer,
IO_BUFFER_SIZE - cbIoBuffer,
RECV_FLAG);
if (cbData == SOCKET_ERROR)
{
int gerrno = SOCK_ERRNO;
mylog("**** Error %d reading data from server\n", gerrno);
switch (gerrno)
{
case EINTR:
continue;
case ECONNRESET:
break;
case EWOULDBLOCK:
retry_count++;
if (Socket_wait_for_ready(Socket, FALSE, retry_count) >= 0)
continue;
default:
scRet = SEC_E_INTERNAL_ERROR;
SOCK_ERRNO_SET(gerrno);
break;
}
break;
}
else if(cbData == 0)
{
mylog("**** Server unexpectedly disconnected\n");
scRet = SEC_E_INTERNAL_ERROR;
break;
}
mylog("%d bytes of handshake data received\n", cbData);
cbIoBuffer += cbData;
retry_count = 0;
}
else
{
fDoRead = TRUE;
}
}
/*
* Set up the input buffers. Buffer 0 is used to pass in data
* received from the server. Schannel will consume some or all
* of this. Leftover data (if any) will be placed in buffer 1 and
* given a buffer type of SECBUFFER_EXTRA.
*/
InBuffers[0].pvBuffer = IoBuffer;
InBuffers[0].cbBuffer = cbIoBuffer;
InBuffers[0].BufferType = SECBUFFER_TOKEN;
InBuffers[1].pvBuffer = NULL;
InBuffers[1].cbBuffer = 0;
InBuffers[1].BufferType = SECBUFFER_EMPTY;
InBuffer.cBuffers = 2;
InBuffer.pBuffers = InBuffers;
InBuffer.ulVersion = SECBUFFER_VERSION;
/*
* Set up the output buffers. These are initialized to NULL
* so as to make it less likely we'll attempt to free random
* garbage later.
*/
OutBuffers[0].pvBuffer = NULL;
OutBuffers[0].BufferType= SECBUFFER_TOKEN;
OutBuffers[0].cbBuffer = 0;
OutBuffer.cBuffers = 1;
OutBuffer.pBuffers = OutBuffers;
OutBuffer.ulVersion = SECBUFFER_VERSION;
/*
* Call InitializeSecurityContext.
*/
scRet = InitializeSecurityContext(phCreds,
phContext,
NULL,
dwSSPIFlags,
0,
SECURITY_NATIVE_DREP,
&InBuffer,
0,