forked from synopse/mORMot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SynSSPI.pas
563 lines (448 loc) · 18 KB
/
SynSSPI.pas
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
/// low level access to Windows SSPI/SChannel API for the Win32/Win64 platform
// - this unit is a part of the freeware Synopse framework,
// licensed under a MPL/GPL/LGPL tri-license; version 1.18
unit SynSSPI;
{
This file is part of Synopse mORMot framework.
Synopse mORMot framework. Copyright (C) 2017 Arnaud Bouchez
Synopse Informatique - http://synopse.info
*** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the License.
The Original Code is Synopse mORMot framework.
The Initial Developer of the Original Code is Chaa.
Portions created by the Initial Developer are Copyright (C) 2017
the Initial Developer. All Rights Reserved.
Contributor(s):
Arnaud Bouchez
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****
Version 1.18
- initial release, with code split from SynSSPIAuth.pas
- has no external unit dependency, so can be used e.g. by SynCrtSock
}
{$I Synopse.inc} // define HASINLINE and other compatibility switches
interface
uses
Windows,
SysUtils;
(* ================= Low-Level SSPI / SChannel API types and functions ====== *)
type
{$ifdef CPU64}
LONG_PTR = Int64;
{$else}
LONG_PTR = integer;
{$endif}
{$ifdef HASCODEPAGE}
TSSPIBuffer = RawByteString;
{$else}
TSSPIBuffer = AnsiString;
{$endif}
/// SSPI context handle
TSecHandle = record
dwLower: LONG_PTR;
dwUpper: LONG_PTR;
end;
PSecHandle = ^TSecHandle;
/// SSPI context
TSecContext = record
ID: Int64;
CredHandle: TSecHandle;
CtxHandle: TSecHandle;
CreatedTick64: Int64;
end;
PSecContext = ^TSecContext;
/// dynamic array of SSPI contexts
// - used to hold information between calls to ServerSSPIAuth
TSecContextDynArray = array of TSecContext;
/// defines a SSPI buffer
TSecBuffer = object
cbBuffer: Cardinal;
BufferType: Cardinal;
pvBuffer: Pointer;
procedure Init(aType: cardinal; aData: pointer; aSize: cardinal);
end;
PSecBuffer = ^TSecBuffer;
/// describes a SSPI buffer
TSecBufferDesc = object
ulVersion: Cardinal;
cBuffers: Cardinal;
pBuffers: PSecBuffer;
procedure Init(aVersion: cardinal; aBuffers: PSecBuffer; aBuffersCount: cardinal);
end;
PSecBufferDesc = ^TSecBufferDesc;
/// store information about a SSPI package
TSecPkgInfoW = record
fCapabilities: Cardinal;
wVersion: Word;
wRPCID: Word;
cbMaxToken: Cardinal;
Name: PWideChar;
Comment: PWideChar;
end;
/// pointer to information about a SSPI package
PSecPkgInfoW = ^TSecPkgInfoW;
/// store negotation information about a SSPI package
TSecPkgContext_NegotiationInfo = record
PackageInfo: PSecPkgInfoW;
NegotiationState: Cardinal;
end;
/// store various working buffer sizes of a SSPI command
TSecPkgContext_Sizes = record
cbMaxToken: Cardinal;
cbMaxSignature: Cardinal;
cbBlockSize: Cardinal;
cbSecurityTrailer: Cardinal;
end;
/// store various working buffer sizes of a SSPI stream
TSecPkgContext_StreamSizes = record
cbHeader: Cardinal;
cbTrailer: Cardinal;
cbMaximumMessage: Cardinal;
cBuffers: Cardinal;
cbBlockSize: Cardinal;
end;
/// information about SSPI supported algorithm
TSecPkgCred_SupportedAlgs = record
cSupportedAlgs: Cardinal;
palgSupportedAlgs: Pointer;
end;
/// pointer to SSPI supported algorithm
PSecPkgCred_SupportedAlgs = ^TSecPkgCred_SupportedAlgs;
/// information about SSPI Authority Identify
TSecWinntAuthIdentityW = record
User: PWideChar;
UserLength: Cardinal;
Domain: PWideChar;
DomainLength: Cardinal;
Password: PWideChar;
PasswordLength: Cardinal;
Flags: Cardinal
end;
/// pointer to SSPI Authority Identify
PSecWinntAuthIdentityW = ^TSecWinntAuthIdentityW;
const
SECBUFFER_VERSION = 0;
SECBUFFER_DATA = 1;
SECBUFFER_TOKEN = 2;
SECPKG_CRED_INBOUND = $00000001;
SECPKG_CRED_OUTBOUND = $00000002;
SECPKG_ATTR_SIZES = 0;
SECPKG_ATTR_STREAM_SIZES = 4;
SECPKG_ATTR_NEGOTIATION_INFO = 12;
SECURITY_NETWORK_DREP = 0;
SECURITY_NATIVE_DREP = $10;
ISC_REQ_MUTUAL_AUTH = $00000002;
ISC_REQ_CONFIDENTIALITY = $00000010;
ISC_REQ_ALLOCATE_MEMORY = $00000100;
ASC_REQ_CONFIDENTIALITY = $00000010;
ASC_REQ_ALLOCATE_MEMORY = $00000100;
SEC_I_CONTINUE_NEEDED = $00090312;
SEC_I_COMPLETE_NEEDED = $00090313;
SEC_I_COMPLETE_AND_CONTINUE = $00090314;
SEC_WINNT_AUTH_IDENTITY_UNICODE = $02;
function QuerySecurityPackageInfoW(pszPackageName: PWideChar;
var ppPackageInfo: PSecPkgInfoW): Integer; stdcall;
function AcquireCredentialsHandleW(pszPrincipal, pszPackage: PWideChar;
fCredentialUse: Cardinal; pvLogonId: Pointer; pAuthData: PSecWinntAuthIdentityW;
pGetKeyFn: Pointer; pvGetKeyArgument: Pointer; phCredential: PSecHandle;
var ptsExpiry: LARGE_INTEGER): Integer; stdcall;
function InitializeSecurityContextW(phCredential: PSecHandle; phContext: PSecHandle;
pszTargetName: PWideChar; fContextReq, Reserved1, TargetDataRep: Cardinal;
pInput: PSecBufferDesc; Reserved2: Cardinal; phNewContext: PSecHandle;
pOutput: PSecBufferDesc; var pfContextAttr: Cardinal; var ptsExpiry: LARGE_INTEGER): Integer; stdcall;
function AcceptSecurityContext(phCredential: PSecHandle; phContext: PSecHandle;
pInput: PSecBufferDesc; fContextReq, TargetDataRep: Cardinal;
phNewContext: PSecHandle; pOutput: PSecBufferDesc; var pfContextAttr: Cardinal;
var ptsExpiry: LARGE_INTEGER): Integer; stdcall;
function CompleteAuthToken(phContext: PSecHandle; pToken: PSecBufferDesc): Integer; stdcall;
function QueryContextAttributesW(phContext: PSecHandle; ulAttribute: Cardinal;
pBuffer: Pointer): Integer; stdcall;
function QuerySecurityContextToken(phContext: PSecHandle; var Token: THandle): Integer; stdcall;
function EncryptMessage(phContext: PSecHandle; fQOP: Cardinal;
pToken: PSecBufferDesc; MessageSeqNo: Cardinal): Integer; stdcall;
function DecryptMessage(phContext: PSecHandle; pToken: PSecBufferDesc;
MessageSeqNo: Cardinal; var fQOP: Cardinal): Integer; stdcall;
function FreeContextBuffer(pvContextBuffer: Pointer): Integer; stdcall;
function DeleteSecurityContext(phContext: PSecHandle): Integer; stdcall;
function FreeCredentialsHandle(phCredential: PSecHandle): Integer; stdcall;
type
HCRYPTPROV = pointer;
HCERTSTORE = Pointer;
PCCERT_CONTEXT = pointer;
ALG_ID = pointer;
_HMAPPER = pointer;
/// SChannel credential information
TSChannel_Cred = record
dwVersion: Cardinal;
cCreds: Cardinal;
paCred: PCCERT_CONTEXT;
hRootStore: HCERTSTORE;
cMappers: Cardinal;
aphMappers: _HMAPPER;
cSupportedAlgs: Cardinal;
palgSupportedAlgs: ALG_ID;
grbitEnabledProtocols: Cardinal;
dwMinimumCipherStrength: Cardinal;
dwMaximumCipherStrength: Cardinal;
dwSessionLifespan: Cardinal;
dwFlags: Cardinal;
dwCredFormat: Cardinal;
end;
/// pointer to SChannel credential information
PSChannel_Cred = ^TSChannel_Cred;
const
UNISP_NAME = 'Microsoft Unified Security Protocol Provider';
SP_PROT_TLS1_0_SERVER = $00000040;
SP_PROT_TLS1_0_CLIENT = $00000080;
SP_PROT_TLS1_0 = SP_PROT_TLS1_0_SERVER + SP_PROT_TLS1_0_CLIENT;
SP_PROT_TLS1_1_SERVER = $00000100;
SP_PROT_TLS1_1_CLIENT = $00000200;
SP_PROT_TLS1_1 = SP_PROT_TLS1_1_SERVER + SP_PROT_TLS1_1_CLIENT;
// TLS 1.2 should be the preferred safe default
SP_PROT_TLS1_2_SERVER = $00000400;
SP_PROT_TLS1_2_CLIENT = $00000800;
SP_PROT_TLS1_2 = SP_PROT_TLS1_2_SERVER + SP_PROT_TLS1_2_CLIENT;
SP_PROT_TLS1_X_SERVER = SP_PROT_TLS1_0_SERVER + SP_PROT_TLS1_1_SERVER + SP_PROT_TLS1_2_SERVER;
SP_PROT_TLS1_X_CLIENT = SP_PROT_TLS1_0_CLIENT + SP_PROT_TLS1_1_CLIENT + SP_PROT_TLS1_2_CLIENT;
SP_PROT_TLS1_X = SP_PROT_TLS1_X_SERVER + SP_PROT_TLS1_X_CLIENT;
function CertOpenStore(lpszStoreProvider: PAnsiChar; dwEncodingType: DWORD;
hCryptProv: HCRYPTPROV; dwFlags: DWORD; pvPara: Pointer): HCERTSTORE; stdcall;
function CertOpenSystemStoreW(hProv: HCRYPTPROV; szSubsystemProtocol: PWideChar): HCERTSTORE; stdcall;
function CertCloseStore(hCertStore: HCERTSTORE; dwFlags: DWORD): BOOL; stdcall;
function CertFindCertificateInStore(hCertStore: HCERTSTORE;
dwCertEncodingType, dwFindFlags, dwFindType: DWORD; pvFindPara: Pointer;
pPrevCertContext: PCCERT_CONTEXT): PCCERT_CONTEXT; stdcall;
(* ========================= High-Level SSPI / SChannel API wrappers ======= *)
/// Sets aSecHandle fields to empty state for a given connection ID
procedure InvalidateSecContext(var aSecContext: TSecContext; aConnectionID: Int64);
/// Free aSecContext on client or server side
procedure FreeSecContext(var aSecContext: TSecContext);
/// Encrypts a message
// - aSecContext must be set e.g. from previous success call to ServerSSPIAuth
// or ClientSSPIAuth
// - aPlain contains data that must be encrypted
// - returns encrypted message
function SecEncrypt(var aSecContext: TSecContext; const aPlain: TSSPIBuffer): TSSPIBuffer;
/// Decrypts a message
// - aSecContext must be set e.g. from previous success call to ServerSSPIAuth
// or ClientSSPIAuth
// - aEncrypted contains data that must be decrypted
// - returns decrypted message
function SecDecrypt(var aSecContext: TSecContext; const aEncrypted: TSSPIBuffer): TSSPIBuffer;
type
/// exception class raised durint SSPI/SChannel process
ESynSSPI = class(Exception)
public
constructor CreateLastOSError(const aContext: TSecContext);
end;
/// the supported TLS modes
// - unsafe deprecated modes (e.g. SSL) are not defined at all
TSynSSPIMode = (tls10, tls11, tls12);
/// set of supported TLS modes
TSynSSPIModes = set of TSynSSPIMode;
/// used for low-level logging
TSynSSPILog = procedure(const Fmt: TSSPIBuffer; const Args: array of const) of object;
/// abstract parent class for SSPI / SChannel process
TSynSSPIAbstract = class
protected
fNewConversation: boolean;
fTLS: TSynSSPIModes;
fContext: TSecContext;
fStreamSizes: TSecPkgContext_StreamSizes;
procedure DeleteContext;
procedure EnsureStreamSizes;
public
/// initialize the process
constructor Create(aConnectionID: Int64); virtual;
/// read-only access to the associated connection ID, as provided to Create
property ConnectionID: Int64 read fContext.ID;
/// the TLS modes supported by this instance
// - only TLS 1.2 is suppported by default, for security reasons
property TLS: TSynSSPIModes read fTLS write fTLS;
end;
TSynSSPIClient = class(TSynSSPIAbstract)
protected
public
end;
implementation
(* ========================= Low-Level SSPI / SChannel API types ====== *)
const
secur32 = 'secur32.dll';
function QuerySecurityPackageInfoW; external secur32;
function AcquireCredentialsHandleW; external secur32;
function InitializeSecurityContextW; external secur32;
function AcceptSecurityContext; external secur32;
function CompleteAuthToken; external secur32;
function QueryContextAttributesW; external secur32;
function QuerySecurityContextToken; external secur32;
function EncryptMessage; external secur32;
function DecryptMessage; external secur32;
function FreeContextBuffer; external secur32;
function DeleteSecurityContext; external secur32;
function FreeCredentialsHandle; external secur32;
const
crypt32 = 'crypt32.dll';
function CertOpenStore; external crypt32;
function CertOpenSystemStoreW; external crypt32;
function CertCloseStore; external crypt32;
function CertFindCertificateInStore; external crypt32;
(* ========================= High-Level SSPI / SChannel API wrappers === *)
{ TSecBuffer }
procedure TSecBuffer.Init(aType: cardinal; aData: pointer;
aSize: cardinal);
begin
BufferType := aType;
pvBuffer := aData;
cbBuffer := aSize;
end;
{ TSecBufferDesc }
procedure TSecBufferDesc.Init(aVersion: cardinal; aBuffers: PSecBuffer;
aBuffersCount: cardinal);
begin
ulVersion := aVersion;
pBuffers := aBuffers;
cBuffers := aBuffersCount;
end;
procedure InvalidateSecContext(var aSecContext: TSecContext; aConnectionID: Int64);
begin
aSecContext.ID := aConnectionID;
aSecContext.CredHandle.dwLower := -1;
aSecContext.CredHandle.dwUpper := -1;
aSecContext.CtxHandle.dwLower := -1;
aSecContext.CtxHandle.dwUpper := -1;
aSecContext.CreatedTick64 := 0;
end;
procedure FreeSecurityContext(var handle: TSecHandle);
begin
if (handle.dwLower <> -1) or (handle.dwUpper <> -1) then begin
DeleteSecurityContext(@handle);
handle.dwLower := -1;
handle.dwUpper := -1;
end;
end;
procedure FreeCredentialsContext(var handle: TSecHandle);
begin
if (handle.dwLower <> -1) or (handle.dwUpper <> -1) then begin
FreeCredentialsHandle(@handle);
handle.dwLower := -1;
handle.dwUpper := -1;
end;
end;
procedure FreeSecContext(var aSecContext: TSecContext);
begin
FreeSecurityContext(aSecContext.CtxHandle);
FreeCredentialsContext(aSecContext.CredHandle);
end;
function SecEncrypt(var aSecContext: TSecContext; const aPlain: TSSPIBuffer): TSSPIBuffer;
var Sizes: TSecPkgContext_Sizes;
SrcLen, EncLen: Cardinal;
EncBuffer: TSSPIBuffer; // TODO: use result as temporary buffer
InBuf: array[0..1] of TSecBuffer;
InDesc: TSecBufferDesc;
Status: Integer;
BufPtr: PByte;
begin
// Sizes.cbSecurityTrailer is size of the trailer (signature + padding) block
if QueryContextAttributesW(@aSecContext.CtxHandle, SECPKG_ATTR_SIZES, @Sizes) <> 0 then
ESynSSPI.CreateLastOSError(aSecContext);
SrcLen := Length(aPlain);
EncLen := SizeOf(Cardinal) + Sizes.cbSecurityTrailer + SrcLen;
SetLength(Result, EncLen);
InBuf[0].Init(SECBUFFER_TOKEN, pointer(LONG_PTR(Result) + SizeOf(Cardinal)),
Sizes.cbSecurityTrailer);
// Encoding done in-place, so we copy the data
SetString(EncBuffer, PAnsiChar(pointer(aPlain)), SrcLen);
InBuf[1].Init(SECBUFFER_DATA, pointer(EncBuffer), SrcLen);
InDesc.Init(SECBUFFER_VERSION, @InBuf, 2);
Status := EncryptMessage(@aSecContext.CtxHandle, 0, @InDesc, 0);
if Status < 0 then
ESynSSPI.CreateLastOSError(aSecContext);
// Encrypted data buffer structure:
//
// 4 bytes SigLen bytes Remaining bytes
// +--------+----------------+-----------------+
// | SigLen | Trailer | Data |
// +--------+----------------+-----------------+
BufPtr := PByte(Result);
PCardinal(BufPtr)^ := InBuf[0].cbBuffer;
Inc(BufPtr, SizeOf(Cardinal));
Inc(BufPtr, InBuf[0].cbBuffer);
Move(PByte(InBuf[1].pvBuffer)^, BufPtr^, SrcLen);
SetLength(Result, SizeOf(Cardinal) + InBuf[0].cbBuffer + SrcLen);
end;
function SecDecrypt(var aSecContext: TSecContext; const aEncrypted: TSSPIBuffer): TSSPIBuffer;
var EncLen, SigLen, SrcLen: Cardinal;
BufPtr: PByte;
InBuf: array [0..1] of TSecBuffer;
InDesc: TSecBufferDesc;
Status: Integer;
QOP: Cardinal;
begin
EncLen := Length(aEncrypted);
BufPtr := PByte(aEncrypted);
if EncLen < SizeOf(Cardinal) then begin
SetLastError(ERROR_INVALID_PARAMETER);
ESynSSPI.CreateLastOSError(aSecContext);
end;
SigLen := PCardinal(BufPtr)^;
Inc(BufPtr, SizeOf(Cardinal));
if EncLen < (SizeOf(Cardinal) + SigLen) then begin
SetLastError(ERROR_INVALID_PARAMETER);
ESynSSPI.CreateLastOSError(aSecContext);
end;
SrcLen := EncLen - SizeOf(Cardinal) - SigLen;
SetLength(Result, SrcLen);
InBuf[0].Init(SECBUFFER_TOKEN, BufPtr, SigLen);
Inc(BufPtr, SigLen);
Move(BufPtr^, PByte(Result)^, SrcLen);
InBuf[1].Init(SECBUFFER_DATA, pointer(result), SrcLen);
InDesc.Init(SECBUFFER_VERSION, @InBuf, 2);
Status := DecryptMessage(@aSecContext.CtxHandle, @InDesc, 0, QOP);
if Status < 0 then
ESynSSPI.CreateLastOSError(aSecContext);
end;
{ ESynSSPI }
constructor ESynSSPI.CreateLastOSError(const aContext: TSecContext);
var error: integer;
begin
error := GetLastError;
CreateFmt('API Error %d [%s] for ConnectionID=%d',
[error,SysErrorMessage(error),aContext.ID]);
end;
{ TSynSSPIAbstract }
constructor TSynSSPIAbstract.Create(aConnectionID: Int64);
begin
inherited Create;
fNewConversation := true;
InvalidateSecContext(fContext, aConnectionID);
fTLS := [tls12];
end;
procedure TSynSSPIAbstract.EnsureStreamSizes;
begin
if fStreamSizes.cbHeader=0 then
if QueryContextAttributesW(@fContext.CtxHandle,SECPKG_ATTR_STREAM_SIZES,@fStreamSizes) <> 0 then
ESynSSPI.CreateLastOSError(fContext);
end;
procedure TSynSSPIAbstract.DeleteContext;
begin
FreeSecurityContext(fContext.CtxHandle);
FreeCredentialsContext(fContext.CredHandle);
end;
end.