forked from Gerenios/AADInternals
-
Notifications
You must be signed in to change notification settings - Fork 1
/
MFA_utils.ps1
589 lines (492 loc) · 16.8 KB
/
MFA_utils.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
# Creates an Oath counter
# Jun 26th 2020
function Get-OathCounter
{
[cmdletbinding()]
Param()
Process
{
$OathCounter = [int](((Get-Date).ToUniversalTime() - $epoch).TotalSeconds / 30)
return $OathCounter
}
}
# Generates a new time-based OTP for MFA
# Jun 26th 2020
function Generate-tOTP
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$SecretKey,
[Parameter(Mandatory=$False)]
[int]$Seconds=0,
[Parameter(Mandatory=$False)]
[int]$TimeShift=0,
[Parameter(Mandatory=$False)]
[int]$TimeStep=30,
[Parameter(Mandatory=$False)]
[int]$Digits=6
)
Process
{
if ($Digits -le 0)
{
$Digits = 6 # Can't be zero so default to six
}
if($Seconds -le 0)
{
# Can't be zero so default to current time
$Seconds = [int]((Get-Date).ToUniversalTime() -$epoch).TotalSeconds
}
if($TimeStep -le 0)
{
$TimeStep = 30 # Can't be zero, so default to 30 seconds
}
$Seconds = ($Seconds + $TimeShift) / $TimeStep
[byte[]]$timeBytes = @( 0,0,0,0, # Integer has only 4 bytes so the first four are zeros
[byte](([int]$Seconds -shr 24) -band 255),
[byte](([int]$Seconds -shr 16) -band 255),
[byte](([int]$Seconds -shr 8) -band 255),
[byte]( [int]$Seconds -band 255)
)
return Generate-hOTP -SecretKey $SecretKey -timeBytes $timeBytes -Digits $Digits
}
}
# Generates a new HMAC based OTP for MFA
# Jun 26th 2020
function Generate-hOTP
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$SecretKey,
[Parameter(Mandatory=$True)]
[byte[]]$TimeBytes,
[Parameter(Mandatory=$True)]
[int]$Digits,
[Parameter(Mandatory=$False)]
[int]$Position = 0
)
Begin
{
$hOtpFullResult = 1073741840
}
Process
{
$divider=0
if ($Digits -ge 1 -and $Digits -le 9)
{
$divider = [Math]::Pow(10, $Digits)
}
elseif ($Digits -eq $hOtpFullResult)
{
$divider = 0
}
else
{
throw "Only 1-9 digits are accepted!"
}
# Calculate the hash using the secret as a key
[byte[]]$decodedSecret = From-Base32String -Secret $SecretKey
$HmacSHA1 = [Security.Cryptography.HMACSHA1]::new($decodedSecret)
$hmacSize = 20
$hash=$HmacSHA1.ComputeHash($TimeBytes)
if ($divider -gt 0)
{
if ($Position -le 0 -or $Position -ge ($hmacSize - 4))
{
$Position = $hash[$hmacSize- 1] -band 15
}
# Generate the OTP from the hash
$retVal = ($hash[$Position] -band 127) -shl 24
$retVal = $retVal -bor ($hash[$Position + 1] -band 255) -shl 16
$retVal = $retVal -bor ($hash[$Position + 2] -band 255) -shl 8
$retVal = $retVal -bor ($hash[$Position + 3] -band 255)
$retVal = $retVal % $divider
return $retVal
}
else
{
return Convert-ByteArrayToHex -Bytes $hash
}
}
}
# Generates a validation code
# Jun 27th 2020
function Generate-ValidationCode
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$SecretKey,
[Parameter(Mandatory=$False)]
[int]$OathCounter=0
)
Process
{
if ($OathCounter -le 0)
{
$OathCounter = Get-OathCounter
}
$validationCode = Generate-tOTP -SecretKey $SecretKey -Digits 1073741840 -Seconds ($OathCounter*30)
return $validationCode.toLower()
}
}
# Converts Base32 string to bytes
# Jun 26th 2020
# Credits: HumanEquivalentUnit
function From-Base32String
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Secret
)
Process
{
$bigInteger = [Numerics.BigInteger]::Zero
foreach ($char in ($secret.ToUpper() -replace '[^A-Z2-7]').GetEnumerator()) {
$bigInteger = ($bigInteger -shl 5) -bor ('ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'.IndexOf($char))
}
[byte[]]$secretAsBytes = $bigInteger.ToByteArray()
# BigInteger sometimes adds a 0 byte to the end,
# if the positive number could be mistaken as a two's complement negative number.
# If it happens, we need to remove it.
if ($secretAsBytes[-1] -eq 0) {
$secretAsBytes = $secretAsBytes[0..($secretAsBytes.Count - 2)]
}
# BigInteger stores bytes in Little-Endian order,
# but we need them in Big-Endian order.
[array]::Reverse($secretAsBytes)
return [byte[]]$secretAsBytes
}
}
# Converts Base32 string to bytes
# Jun 26th 2020
# Credits: HumanEquivalentUnit
function To-Base32String
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Secret
)
Process
{
$byteArrayAsBinaryString = -join $Secret.ForEach{
[Convert]::ToString($_, 2).PadLeft(8, '0')
}
$Base32Secret = [regex]::Replace($byteArrayAsBinaryString, '.{5}', {
param($Match)
'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'[[Convert]::ToInt32($Match.Value, 2)]
})
return $Base32Secret
}
}
# Parses authentication apps data
# Jun 27th 2020
function Parse-AuthApps
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$appDetails
)
Process
{
$apps=@()
foreach($app in $appDetails)
{
$appAtributes = [ordered]@{
"AuthenticationType"=$app.AuthenticationType
"DeviceName"= $app.DeviceName
"DeviceTag"= $app.DeviceTag
"DeviceToken"= $app.DeviceToken
"Id"= $app.Id
"NotificationType"= $app.NotificationType
"OathTokenTimeDrift"=$app.OathTokenTimeDrift
"OathSecretKey"= $app.OathTokenSecretKey
"PhoneAppVersion"= $app.PhoneAppVersion
"TimeInterval"= $app.TimeInterval
"LastAuthTime" = $(if($app.lastAuthenticatedTimestamp){[DateTime]$app.lastAuthenticatedTimestamp}else{$null})
}
$apps+=New-Object psobject -Property $appAtributes
}
return $apps
}
}
# Gets MFA App Registration information (i.e. url, activation code, and session context)
# Jul 1st 2020
function Get-MFAAppRegistrationInfo
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[ValidateSet("APP","OTP")]
[String]$Type="APP"
)
Process
{
# Create the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
"User-Agent" = ""
}
# Registration type
if($Type -eq "APP")
{
$securityInfoType = 2
}
elseif($Type -eq "OTP")
{
$securityInfoType = 3
}
# Get the authorization information
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://account.activedirectory.windowsazure.com/securityinfo/Authorize" -Method POST -Headers $headers
# Strip the carbage from the start and convert to psobject
$response=$response.Substring($response.IndexOf("{")-1) | ConvertFrom-Json
# Extract the session context and update headers
$sessionCtx = $response.sessionCtx
$headers["SessionCtx"] = $sessionCtx
# Get the needed codes
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://account.activedirectory.windowsazure.com/securityinfo/InitializeMobileAppRegistration" -Method POST -Headers $headers -Body "{""securityInfoType"": $securityInfoType}"
# Strip the carbage from the start and convert to psobject
$response=$response.Substring($response.IndexOf("{")-1) | ConvertFrom-Json
# Add the session context to return value
$response | Add-Member -NotePropertyName "SessionCtx" -NotePropertyValue $sessionCtx
Write-Verbose "Registration info:`n$response"
# Return
return $response
}
}
# Sends a new MFA App activation
# Jul 2nd 2020
function Send-MFAAppNewActivation
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
$RegistrationInfo,
[Parameter(Mandatory=$True)]
[String]$DeviceToken,
[Parameter(Mandatory=$False)]
[String]$DeviceName="AADInternals"
)
Process
{
$url = $RegistrationInfo.Url
# Append the PfPaWs.asmx if not included
if(!$Url.EndsWith($PfPaWs))
{
if(!$Url.EndsWith("/"))
{
$Url+="/";
}
$Url+=$PfPaWs;
}
# Create the headers
$headers=@{
"SOAPAction" = "http://www.phonefactor.com/PfPaWs/ActivateNew"
"Content-Type" = "text/xml; charset=utf-8"
"User-Agent" = "Dalvik/2.1.0 (Linux; U; Android 8.1.0; AADInternals)"
}
$body=@"
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns4="http://www.phonefactor.com/PfPaWs">
<soap:Header/>
<soap:Body>
<ns4:ActivateNew>
<ns4:activationParams>
<ns4:ActivationCode>$($RegInfo.ActivationCode)</ns4:ActivationCode>
<ns4:DeviceToken>$DeviceToken</ns4:DeviceToken>
<ns4:DeviceName>$DeviceName</ns4:DeviceName>
<ns4:OathCounter>$(Get-OathCounter)</ns4:OathCounter>
<ns4:Version>$Version</ns4:Version>
</ns4:activationParams>
</ns4:ActivateNew>
</soap:Body>
</soap:Envelope>
"@
# Send the activation request
$response = Invoke-RestMethod -UseBasicParsing -Uri $Url -Method POST -Headers $headers -Body $body
# Extract the activation information
$activationInformation=$response.Envelope.Body.ActivateNewResponse.activationInfo
Write-Verbose "Activation info:`n$activationInformation"
# Return
return $activationInformation
}
}
# Sends a new MFA App activation confirmation
# Jul 2nd 2020
function Send-MFAAppNewActivationConfirmation
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
$RegistrationInfo,
[Parameter(Mandatory=$True)]
$ActivationInfo
)
Process
{
$url = $RegistrationInfo.Url
# Append the PfPaWs.asmx if not included
if(!$Url.EndsWith($PfPaWs))
{
if(!$Url.EndsWith("/"))
{
$Url+="/";
}
$Url+=$PfPaWs;
}
# Create the headers
$headers=@{
"SOAPAction" = "http://www.phonefactor.com/PfPaWs/ConfirmActivation"
"Content-Type" = "text/xml; charset=utf-8"
"User-Agent" = "Dalvik/2.1.0 (Linux; U; Android 8.1.0; AADInternals)"
}
# Create the body
$body=@"
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns4="http://www.phonefactor.com/PfPaWs">
<soap:Header/>
<soap:Body>
<ns4:ConfirmActivation>
<ns4:confirmationCode>$($ActivationInfo.ConfirmationCode)</ns4:confirmationCode>
</ns4:ConfirmActivation>
</soap:Body>
</soap:Envelope>
"@
# Send the activation confirmation
$response = Invoke-RestMethod -UseBasicParsing -Uri $Url -Method POST -Headers $headers -Body $body
Write-Verbose "Confirmation Activation: $($response.Envelope.Body.ConfirmActivationResponse.ConfirmActivationResult)"
# Return
return $response.Envelope.Body.ConfirmActivationResponse.ConfirmActivationResult -eq "true"
}
}
# Adds the new device
# Jul 2nd 2020
function Add-MFAAppAddDevice
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
$RegistrationInfo,
[ValidateSet("APP","OTP")]
[String]$Type="APP"
)
Process
{
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"SessionCtx" = $RegistrationInfo.SessionCtx
#"Access-Control-Request-Method" = "POST"
#"Access-Control-Request-Headers" ="ajaxrequest,authorization,content-type,sessionctx"
"Origin" = "https://mysignins.microsoft.com"
"Sec-Fetch-Site" = "cross-site"
"Sec-Fetch-Mode" = "cors"
"Sec-Fetch-Dest" = "empty"
"Content-Type" = "application/json"
}
if($Type -eq "APP")
{
$securityType = 2
$secretKey = $RegistrationInfo.ActivationCode
}
elseif($Type -eq "OTP")
{
$securityType = 3
$secretKey = $RegistrationInfo.SecretKey
}
$body="{""Type"":$securityType,""Data"":""{\""secretKey\"":\""$secretKey\"",\""affinityRegion\"":\""$($RegistrationInfo.AffinityRegion)\""}""}"
$state=0
$counter=0
# Loop until we get the context or fail for 10 times
while($state -ne 1 -and ($counter++) -lt 11)
{
# Wait
Start-Sleep -Seconds 2
Write-Verbose "Adding MFA application #$counter"
# Send the AddSecurityInfo request
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://account.activedirectory.windowsazure.com/securityinfo/AddSecurityInfo" -Headers $headers -Body $body
# Strip the carbage from the start and convert to psobject
$response=$response.Substring($response.IndexOf("{")-1) | ConvertFrom-Json
# Get the verification state
$state = $response.VerificationState
}
Write-Verbose "Verification context: $($response.VerificationContext)"
# Return
return $response.VerificationContext
}
}
# Sends MFA App verification request
# Jul 2nd 2020
function Verify-MFAAppAddDevice
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
$RegistrationInfo,
[Parameter(Mandatory=$True)]
[String]$VerificationContext,
[ValidateSet("APP","OTP")]
[String]$Type="APP"
)
Process
{
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"SessionCtx" = $RegistrationInfo.SessionCtx
#"Access-Control-Request-Method" = "POST"
#"Access-Control-Request-Headers" ="ajaxrequest,authorization,content-type,sessionctx"
"Origin" = "https://mysignins.microsoft.com"
"Sec-Fetch-Site" = "cross-site"
"Sec-Fetch-Mode" = "cors"
"Sec-Fetch-Dest" = "empty"
"Content-Type" = "application/json"
}
if($Type -eq "APP")
{
$securityType = 2
$verificationData = $null
}
elseif($Type -eq "OTP")
{
$securityType = 3
$verificationData = (New-AADIntOTP -SecretKey $RegistrationInfo.SecretKey).OTP.replace(" ","")
Start-Sleep -Seconds 3
}
# Create the body
$body = "{""Type"":$securityType,""VerificationContext"":""$VerificationContext"",""VerificationData"":$verificationData}"
$state=0
$counter=0
$dataUpdates=""
# Loop until we get the data or fail for 10 times
while([string]::IsNullOrEmpty($dataUpdates) -and ($counter++) -lt 11)
{
# Wait
Start-Sleep -Seconds 2
Write-Verbose "Sending VerifySecurityInfo message #$counter"
# Send the VerifySecurityInfo message
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://account.activedirectory.windowsazure.com/securityinfo/VerifySecurityInfo" -Headers $headers -Body $body
# Strip the carbage from the start and convert to psobject
$responseBody=$response.Substring($response.IndexOf("{")-1) | ConvertFrom-Json
# Get the verification state
$dataUpdates = $responseBody.Dataupdates
}
Write-Verbose "Data Updates: $dataUpdates"
# Return
return $dataUpdates
}
}