-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMaxLogic.Windows.Identity.pas
More file actions
618 lines (581 loc) · 14.9 KB
/
Copy pathMaxLogic.Windows.Identity.pas
File metadata and controls
618 lines (581 loc) · 14.9 KB
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
unit MaxLogic.Windows.Identity;
interface
type
TWindowsBootIdentitySource = (
wbisUnavailable,
wbisWindowsRecorded,
wbisApproximate);
TWindowsBootIdentity = record
UtcMilliseconds: Int64;
Source: TWindowsBootIdentitySource;
end;
/// <summary>
/// Returns only an already resolved identity and never starts WMI work.
/// </summary>
function TryGetCachedWindowsBootIdentity(
out aIdentity: TWindowsBootIdentity): Boolean;
/// <summary>
/// Starts at most one background WMI lookup and waits for no more than 1000 ms.
/// The caller must be an owning background workflow, never a VCL event handler.
/// Pass aRetryUnavailable only when that workflow explicitly owns a retry.
/// </summary>
function TryGetWindowsBootIdentity(
const aTimeoutMilliseconds: Cardinal;
const aRetryUnavailable: Boolean;
out aIdentity: TWindowsBootIdentity): Boolean;
/// <summary>
/// Returns process creation time from GetProcessTimes or False when unavailable.
/// </summary>
function TryGetProcessStartedAtUtcMilliseconds(
const aProcessId: Cardinal;
out aStartedAtUtcMilliseconds: Int64): Boolean;
{$IFDEF UNITTESTS}
type
TWindowsBootIdentityQuery = reference to function(
const aTimeoutMilliseconds: Cardinal;
out aIdentity: TWindowsBootIdentity): Boolean;
procedure ResetWindowsBootIdentityCacheForTesting;
procedure SetWindowsBootIdentityQueryForTesting(
const aQuery: TWindowsBootIdentityQuery);
{$ENDIF}
implementation
uses
System.Classes,
System.DateUtils,
System.SyncObjs,
System.SysUtils,
System.Variants
{$IFDEF MSWINDOWS},
Winapi.ActiveX,
Winapi.Wbem,
Winapi.Windows
{$ENDIF};
const
cMaximumLookupMilliseconds = 1000;
cUnavailableCacheMilliseconds = 60000;
cProcessQueryLimitedInformation = $1000;
cRpcAuthnLevelDefault = 0;
cRpcAuthnLevelCall = 3;
cRpcAuthnWinNt = 10;
cRpcAuthzNone = 0;
cRpcImpLevelImpersonate = 3;
cEoacNone = 0;
type
{$IFDEF UNITTESTS}
TBootIdentityQueryMethod = TWindowsBootIdentityQuery;
{$ELSE}
TBootIdentityQueryMethod = reference to function(
const aTimeoutMilliseconds: Cardinal;
out aIdentity: TWindowsBootIdentity): Boolean;
{$ENDIF}
IBootIdentityLookup = interface
['{74B79B06-7161-4AE9-B035-53981A16F8D0}']
function TryGetResult(out aIdentity: TWindowsBootIdentity): Boolean;
function WaitFor(const aTimeoutMilliseconds: Cardinal): TWaitResult;
procedure ExecuteQuery;
end;
TBootIdentityCacheDecision = (
bicdAvailable,
bicdUnavailable,
bicdLookup);
TBootIdentityLookup = class(TInterfacedObject, IBootIdentityLookup)
private
fDone: TEvent;
fIdentity: TWindowsBootIdentity;
fQuery: TBootIdentityQueryMethod;
fSucceeded: Boolean;
fTimeoutMilliseconds: Cardinal;
public
constructor Create(
const aQuery: TBootIdentityQueryMethod;
const aTimeoutMilliseconds: Cardinal);
destructor Destroy; override;
procedure ExecuteQuery;
function TryGetResult(out aIdentity: TWindowsBootIdentity): Boolean;
function WaitFor(const aTimeoutMilliseconds: Cardinal): TWaitResult;
end;
var
gCacheLock: TCriticalSection;
gCachedIdentity: TWindowsBootIdentity;
gFailureCachedAt: UInt64;
gHasCachedIdentity: Boolean;
gHasCachedFailure: Boolean;
gLookup: IBootIdentityLookup;
gQuery: TBootIdentityQueryMethod;
function TryParseDmtfDateTime(
const aValue: string;
out aUtcMilliseconds: Int64): Boolean;
var
lIsoDateTime: string;
lOffsetMinutes: Integer;
lUtcDateTime: TDateTime;
begin
Result := False;
aUtcMilliseconds := 0;
if (Length(aValue) < 25) or
(aValue[15] <> '.') or
not CharInSet(aValue[22], ['+', '-']) or
not TryStrToInt(Copy(aValue, 23, 3), lOffsetMinutes) then
Exit;
lIsoDateTime := Format(
'%s-%s-%sT%s:%s:%s.%s%s%.2d:%.2d',
[
Copy(aValue, 1, 4),
Copy(aValue, 5, 2),
Copy(aValue, 7, 2),
Copy(aValue, 9, 2),
Copy(aValue, 11, 2),
Copy(aValue, 13, 2),
Copy(aValue, 16, 3),
aValue[22],
lOffsetMinutes div 60,
lOffsetMinutes mod 60
]);
if not TryISO8601ToDate(lIsoDateTime, lUtcDateTime, True) then
Exit;
aUtcMilliseconds :=
DateTimeToUnix(lUtcDateTime, True) * 1000 +
MilliSecondOf(lUtcDateTime);
Result := aUtcMilliseconds > 0;
end;
{$IFDEF MSWINDOWS}
function InitializeWmiCom(out aShouldUninitialize: Boolean): Boolean;
var
lHResult: HRESULT;
begin
aShouldUninitialize := False;
lHResult := CoInitializeEx(nil, COINIT_MULTITHREADED);
if lHResult in [S_OK, S_FALSE] then
aShouldUninitialize := True
else if lHResult <> RPC_E_CHANGED_MODE then
Exit(False);
lHResult := CoInitializeSecurity(
nil,
-1,
nil,
nil,
cRpcAuthnLevelDefault,
cRpcImpLevelImpersonate,
nil,
cEoacNone,
nil);
Result := Succeeded(lHResult) or (lHResult = RPC_E_TOO_LATE);
if not Result and aShouldUninitialize then
begin
CoUninitialize;
aShouldUninitialize := False;
end;
end;
function TryConnectWmi(
out aLocator: IWbemLocator;
out aServices: IWbemServices): Boolean;
var
lHResult: HRESULT;
begin
aLocator := nil;
aServices := nil;
lHResult := CoCreateInstance(
CLSID_WbemLocator,
nil,
CLSCTX_INPROC_SERVER,
IID_IWbemLocator,
aLocator);
if Failed(lHResult) then
Exit(False);
lHResult := aLocator.ConnectServer(
'ROOT\CIMV2',
'',
'',
'',
0,
'',
nil,
aServices);
if Failed(lHResult) then
Exit(False);
lHResult := CoSetProxyBlanket(
aServices,
cRpcAuthnWinNt,
cRpcAuthzNone,
nil,
cRpcAuthnLevelCall,
cRpcImpLevelImpersonate,
nil,
cEoacNone);
Result := Succeeded(lHResult);
end;
function TryReadWmiBootDateTime(
const aServices: IWbemServices;
const aTimeoutMilliseconds: Cardinal;
out aValue: string): Boolean;
var
lEnumerator: IEnumWbemClassObject;
lHResult: HRESULT;
lObject: IWbemClassObject;
lPropertyName: WideString;
lReturned: Cardinal;
lValue: OleVariant;
begin
aValue := '';
lHResult := aServices.ExecQuery(
'WQL',
'SELECT LastBootUpTime FROM Win32_OperatingSystem',
WBEM_FLAG_FORWARD_ONLY or WBEM_FLAG_RETURN_IMMEDIATELY,
nil,
lEnumerator);
if Failed(lHResult) then
Exit(False);
lHResult := lEnumerator.Next(
aTimeoutMilliseconds,
1,
lObject,
lReturned);
if Failed(lHResult) or (lReturned <> 1) then
Exit(False);
lPropertyName := 'LastBootUpTime';
lHResult := lObject.Get(
PWideChar(lPropertyName),
0,
lValue,
nil,
nil);
Result :=
Succeeded(lHResult) and
not VarIsNull(lValue) and
not VarIsEmpty(lValue);
if Result then
aValue := VarToWideStr(lValue);
end;
{$ENDIF}
function QueryWindowsRecordedBootIdentity(
const aTimeoutMilliseconds: Cardinal;
out aIdentity: TWindowsBootIdentity): Boolean;
{$IFDEF MSWINDOWS}
var
lBootDateTime: string;
lComInitialized: Boolean;
lLocator: IWbemLocator;
lServices: IWbemServices;
lUtcMilliseconds: Int64;
begin
Result := False;
aIdentity := Default(TWindowsBootIdentity);
if not InitializeWmiCom(lComInitialized) then
Exit;
try
if not TryConnectWmi(lLocator, lServices) then
Exit;
if not TryReadWmiBootDateTime(
lServices,
aTimeoutMilliseconds,
lBootDateTime) then
Exit;
if not TryParseDmtfDateTime(
lBootDateTime,
lUtcMilliseconds) then
Exit;
aIdentity.UtcMilliseconds := lUtcMilliseconds;
aIdentity.Source := wbisWindowsRecorded;
Result := True;
finally
lServices := nil;
lLocator := nil;
if lComInitialized then
CoUninitialize;
end;
end;
{$ELSE}
begin
aIdentity := Default(TWindowsBootIdentity);
Result := False;
end;
{$ENDIF}
function StartBootIdentityLookup(
const aQuery: TBootIdentityQueryMethod;
const aTimeoutMilliseconds: Cardinal): IBootIdentityLookup;
var
lLookup: IBootIdentityLookup;
lThread: TThread;
begin
lLookup := TBootIdentityLookup.Create(aQuery, aTimeoutMilliseconds);
lThread := TThread.CreateAnonymousThread(
procedure
begin
lLookup.ExecuteQuery;
end);
lThread.FreeOnTerminate := True;
lThread.Start;
Result := lLookup;
end;
constructor TBootIdentityLookup.Create(
const aQuery: TBootIdentityQueryMethod;
const aTimeoutMilliseconds: Cardinal);
begin
inherited Create;
fDone := TEvent.Create(nil, True, False, '');
fQuery := aQuery;
fTimeoutMilliseconds := aTimeoutMilliseconds;
end;
destructor TBootIdentityLookup.Destroy;
begin
fDone.Free;
inherited;
end;
procedure TBootIdentityLookup.ExecuteQuery;
begin
try
fSucceeded := fQuery(fTimeoutMilliseconds, fIdentity);
except
// The Try API reports expected WMI/COM lookup failures as unavailable.
fIdentity := Default(TWindowsBootIdentity);
fSucceeded := False;
end;
fDone.SetEvent;
end;
function TBootIdentityLookup.TryGetResult(
out aIdentity: TWindowsBootIdentity): Boolean;
begin
aIdentity := fIdentity;
Result := fSucceeded;
end;
function TBootIdentityLookup.WaitFor(
const aTimeoutMilliseconds: Cardinal): TWaitResult;
begin
Result := fDone.WaitFor(aTimeoutMilliseconds);
end;
function TryGetCachedWindowsBootIdentity(
out aIdentity: TWindowsBootIdentity): Boolean;
begin
aIdentity := Default(TWindowsBootIdentity);
gCacheLock.Acquire;
try
Result := gHasCachedIdentity;
if Result then
aIdentity := gCachedIdentity;
finally
gCacheLock.Release;
end;
end;
function GetBootIdentityCacheDecision(
const aTimeoutMilliseconds: Cardinal;
const aRetryUnavailable: Boolean;
out aIdentity: TWindowsBootIdentity;
out aLookup: IBootIdentityLookup): TBootIdentityCacheDecision;
var
lFailureAge: UInt64;
lNow: UInt64;
lQuery: TBootIdentityQueryMethod;
begin
aIdentity := Default(TWindowsBootIdentity);
aLookup := nil;
gCacheLock.Acquire;
try
if gHasCachedIdentity then
begin
aIdentity := gCachedIdentity;
Exit(bicdAvailable);
end;
lNow := TThread.GetTickCount64;
lFailureAge := lNow - gFailureCachedAt;
if gHasCachedFailure and
(lFailureAge < cUnavailableCacheMilliseconds) and
not aRetryUnavailable then
Exit(bicdUnavailable);
if gLookup = nil then
begin
lQuery := gQuery;
gLookup := StartBootIdentityLookup(lQuery, aTimeoutMilliseconds);
end;
aLookup := gLookup;
Result := bicdLookup;
finally
gCacheLock.Release;
end;
end;
procedure CacheBootIdentityTimeout(const aLookup: IBootIdentityLookup);
begin
gCacheLock.Acquire;
try
if gLookup = aLookup then
begin
gFailureCachedAt := TThread.GetTickCount64;
gHasCachedFailure := True;
end;
finally
gCacheLock.Release;
end;
end;
function PublishBootIdentityResult(
const aLookup: IBootIdentityLookup;
const aLookupIdentity: TWindowsBootIdentity;
const aLookupSucceeded: Boolean;
out aIdentity: TWindowsBootIdentity): Boolean;
begin
aIdentity := Default(TWindowsBootIdentity);
gCacheLock.Acquire;
try
if gLookup <> aLookup then
begin
Result := gHasCachedIdentity;
if Result then
aIdentity := gCachedIdentity;
Exit;
end;
gLookup := nil;
Result := aLookupSucceeded;
if Result then
begin
gCachedIdentity := aLookupIdentity;
gHasCachedIdentity := True;
gFailureCachedAt := 0;
gHasCachedFailure := False;
aIdentity := gCachedIdentity;
end
else
begin
gFailureCachedAt := TThread.GetTickCount64;
gHasCachedFailure := True;
end;
finally
gCacheLock.Release;
end;
end;
function TryGetWindowsBootIdentity(
const aTimeoutMilliseconds: Cardinal;
const aRetryUnavailable: Boolean;
out aIdentity: TWindowsBootIdentity): Boolean;
var
lDecision: TBootIdentityCacheDecision;
lLookup: IBootIdentityLookup;
lLookupIdentity: TWindowsBootIdentity;
lLookupSucceeded: Boolean;
lTimeoutMilliseconds: Cardinal;
begin
aIdentity := Default(TWindowsBootIdentity);
lTimeoutMilliseconds := aTimeoutMilliseconds;
if lTimeoutMilliseconds > cMaximumLookupMilliseconds then
lTimeoutMilliseconds := cMaximumLookupMilliseconds;
lDecision := GetBootIdentityCacheDecision(
lTimeoutMilliseconds,
aRetryUnavailable,
aIdentity,
lLookup);
if lDecision = bicdAvailable then
Exit(True);
if lDecision = bicdUnavailable then
Exit(False);
if lLookup.WaitFor(lTimeoutMilliseconds) <> wrSignaled then
begin
CacheBootIdentityTimeout(lLookup);
Exit(False);
end;
lLookupSucceeded :=
lLookup.TryGetResult(lLookupIdentity) and
(lLookupIdentity.Source <> wbisUnavailable) and
(lLookupIdentity.UtcMilliseconds > 0);
Result := PublishBootIdentityResult(
lLookup,
lLookupIdentity,
lLookupSucceeded,
aIdentity);
end;
{$IFDEF MSWINDOWS}
function TryGetProcessCreationFileTime(
const aProcessId: Cardinal;
out aCreationFileTime: TFileTime): Boolean;
var
lExitFileTime: TFileTime;
lKernelFileTime: TFileTime;
lOwnHandle: Boolean;
lProcess: THandle;
lUserFileTime: TFileTime;
begin
lOwnHandle := aProcessId <> Winapi.Windows.GetCurrentProcessId;
if lOwnHandle then
begin
lProcess := OpenProcess(
cProcessQueryLimitedInformation,
False,
aProcessId);
if lProcess = 0 then
lProcess := OpenProcess(PROCESS_QUERY_INFORMATION, False, aProcessId);
end
else
lProcess := Winapi.Windows.GetCurrentProcess;
if lProcess = 0 then
Exit(False);
try
Result := GetProcessTimes(
lProcess,
aCreationFileTime,
lExitFileTime,
lKernelFileTime,
lUserFileTime);
finally
if lOwnHandle then
CloseHandle(lProcess);
end;
end;
{$ENDIF}
function TryGetProcessStartedAtUtcMilliseconds(
const aProcessId: Cardinal;
out aStartedAtUtcMilliseconds: Int64): Boolean;
{$IFDEF MSWINDOWS}
var
lCreationDateTime: TDateTime;
lCreationFileTime: TFileTime;
lSystemTime: TSystemTime;
begin
aStartedAtUtcMilliseconds := 0;
if not TryGetProcessCreationFileTime(aProcessId, lCreationFileTime) then
Exit(False);
if not FileTimeToSystemTime(lCreationFileTime, lSystemTime) then
Exit(False);
lCreationDateTime := SystemTimeToDateTime(lSystemTime);
aStartedAtUtcMilliseconds :=
DateTimeToUnix(lCreationDateTime, True) * 1000 +
lSystemTime.wMilliseconds;
Result := aStartedAtUtcMilliseconds > 0;
end;
{$ELSE}
begin
aStartedAtUtcMilliseconds := 0;
Result := False;
end;
{$ENDIF}
{$IFDEF UNITTESTS}
procedure ResetWindowsBootIdentityCacheForTesting;
begin
gCacheLock.Acquire;
try
gCachedIdentity := Default(TWindowsBootIdentity);
gFailureCachedAt := 0;
gHasCachedIdentity := False;
gHasCachedFailure := False;
gLookup := nil;
finally
gCacheLock.Release;
end;
end;
procedure SetWindowsBootIdentityQueryForTesting(
const aQuery: TWindowsBootIdentityQuery);
begin
gCacheLock.Acquire;
try
if Assigned(aQuery) then
gQuery := aQuery
else
gQuery := QueryWindowsRecordedBootIdentity;
finally
gCacheLock.Release;
end;
end;
{$ENDIF}
initialization
gCacheLock := TCriticalSection.Create;
gQuery := QueryWindowsRecordedBootIdentity;
finalization
gLookup := nil;
gQuery := nil;
gCacheLock.Free;
end.