forked from Gerenios/AADInternals
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMSAppProxy.ps1
More file actions
754 lines (628 loc) · 30.7 KB
/
MSAppProxy.ps1
File metadata and controls
754 lines (628 loc) · 30.7 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
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
# This file contains functions for Microsoft App Proxy
Add-Type -AssemblyName System.Web
# Registers App proxy agent to the Azure AD
# Apr 2nd 2020
# May 5th 2022: Added UpdateTrust
function Register-ProxyAgent
{
<#
.SYNOPSIS
Registers a new MS App Proxy agent to Azure AD
.DESCRIPTION
Registers a new MS App Proxy agent to Azure AD. Currently Sync and PTA agents are supported.
.PARAMETER MachineName
Machine name used to register the proxy agent
.PARAMETER AgentType
Type of the proxy agent. One of "PTA","Sync"
.PARAMETER AgentGroup
The Agent group where to add the new agent.
.PARAMETER UpdateTrust
Instead of register a new agent, updates the trust of existing one. As a result, a new proxy certificate is created.
.PARAMETER Bootstrap
Filename of existing bootstrap configuration file.
.PARAMETER PfxFileName
The name of an existing proxy agent certificate used to update trust.
.PARAMETER PfxPassword
Password of the existing proxy agent certificate.
.Example
$pt=Get-AADIntAccessTokenForPTA
PS C:\>Register-AADIntProxyAgent -AccessToken $pt -MachineName server1.company.com -AgentType PTA -FileName server1-pta.pfx
.Example
$pt=Get-AADIntAccessTokenForPTA
PS C:\>Register-AADIntProxyAgent -AccessToken $pt -MachineName server2.company.com -AgentType Sync -FileName server2-sync.pfx
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$MachineName,
[Parameter(Mandatory=$False)]
[String]$FileName,
[Parameter(Mandatory=$True)]
[Validateset("PTA","Sync")]
[String]$AgentType,
[Parameter(Mandatory=$False)]
$AgentGroup,
[Parameter(Mandatory=$False)]
[bool]$UpdateTrust,
[Parameter(Mandatory=$False)]
[String]$Bootstrap,
[Parameter(Mandatory=$False)]
[String]$PfxFileName,
[Parameter(Mandatory=$False)]
[string]$PfxPassword
)
Begin
{
$AgentInfo=@{
"PTA"= @{
"FeatureString" = "PassthroughAuthentication"
"UserAgent" = "PassthroughAuthenticationConnector/1.5.643.0"
}
"Sync"= @{
"FeatureString" = "SyncFabric"
"UserAgent" = "SyncFabricConnector/1.1.96.0"
}
}
}
Process
{
if($UpdateTrust)
{
# Load the old certificate
$cert = Load-Certificate -FileName $PfxFileName -Password $PfxPassword
$tenantId = $cert.Subject.Split("=")[1]
}
else
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8"
$tenantId = Get-TenantID -AccessToken $AccessToken
}
# Set some variables
$OSLanguage="1033"
$OSLocale="0409"
$OSSku="8"
$OSVersion="10.0.17763"
# Create a private key and do something with it to get it stored
$rsa=[System.Security.Cryptography.RSA]::Create(2048)
# Initialize the Certificate Signing Request object
$CN="" # The name doesn't matter
$req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new($CN, $rsa, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
if($AgentType -eq "PTA")
{
# Key usage
$req.CertificateExtensions.Add([System.Security.Cryptography.X509Certificates.X509KeyUsageExtension]::new([System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::DigitalSignature -bor [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::NonRepudiation -bor [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::KeyEncipherment -bor [System.Security.Cryptography.X509Certificates.X509KeyUsageFlags]::DataEncipherment, $false))
# TLS Web client authentication
$oidCollection = [System.Security.Cryptography.OidCollection]::new()
$oidCollection.Add([System.Security.Cryptography.Oid]::new("1.3.6.1.5.5.7.3.2")) | Out-Null
$req.CertificateExtensions.Add([System.Security.Cryptography.X509Certificates.X509EnhancedKeyUsageExtension]::new($oidCollection, $true))
# Add the public Key to the request
$req.CertificateExtensions.Add([System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension]::new($req.PublicKey,$false))
# Create the signing request
$csr=$req.CreateSigningRequest()
}
elseif($AgentType -eq "Sync")
{
# This must be done this way cause MS CSR classes doesn't support attributes :(
$csr = NewCSRforSync -MachineName $MachineName -PublicKey $req.PublicKey.EncodedKeyValue.RawData
}
$b64Csr=[convert]::ToBase64String($csr)
# Create the request body
if($UpdateTrust)
{
if($Bootstrap -and (Test-Path $Bootstrap))
{
Write-Verbose "Loading bootstrap from $Bootstrap"
[xml]$config=Get-Content -Path $Bootstrap -Encoding UTF8
}
else
{
Write-Verbose "Getting bootstrap using $($cert.Thumbprint) as $MachineName"
[xml]$config=Get-BootstrapConfiguration -Certificate $cert -MachineName $MachineName
}
if(!$config)
{
Write-Error "Could not load bootstrap!"
return
}
$trustEndpoint = $config.BootstrapResponse.TrustRenewEndpoint
$body=@"
<TrustRenewalRequest xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Registration.TrustRenewal" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Base64Csr xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Registration">$b64Csr
</Base64Csr>
<TrustRenewalRequestSettings>
<SystemSettingsInformation i:type="a:SystemSettings" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.RegistrationCommons" xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Utilities.SystemSettings">
<a:MachineName>$machineName</a:MachineName>
<a:OsLanguage>$OSLanguage</a:OsLanguage>
<a:OsLocale>$OSLocale</a:OsLocale>
<a:OsSku>$OSSku</a:OsSku>
<a:OsVersion>$OSVersion</a:OsVersion>
</SystemSettingsInformation>
<ConnectorVersion>1.5.2482.0</ConnectorVersion>
</TrustRenewalRequestSettings>
</TrustRenewalRequest>
"@
# Renew trust and get the certificate
$response = Invoke-RestMethod -UseBasicParsing -Uri "$trustEndPoint/RenewTrustCertificate" -Method Post -Body $body -Headers @{"Content-Type"="application/xml; charset=utf-8"} -Certificate $cert
if($response.TrustRenewalResult.IsSuccessful.'#text' -eq "true")
{
# Get the certificate
$b64Cert = $response.TrustRenewalResult.Certificate.'#text'
}
else
{
# Something went wrong
Write-Error $response.TrustRenewalResult.ErrorMessage.'#text'
}
}
else
{
$body=@"
<RegistrationRequest xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Registration" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Base64Csr>$b64Csr
</Base64Csr>
<AuthenticationToken>$AccessToken</AuthenticationToken>
<Base64Pkcs10Csr i:nil="true"/>
<Feature>ApplicationProxy</Feature>
<FeatureString>$($AgentInfo[$AgentType]["FeatureString"])</FeatureString>
<RegistrationRequestSettings>
<SystemSettingsInformation i:type="a:SystemSettings" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.RegistrationCommons" xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Utilities.SystemSettings">
<a:MachineName>$machineName</a:MachineName>
<a:OsLanguage>$OSLanguage</a:OsLanguage>
<a:OsLocale>$OSLocale</a:OsLocale>
<a:OsSku>$OSSku</a:OsSku>
<a:OsVersion>$OSVersion</a:OsVersion>
</SystemSettingsInformation>
<PSModuleVersion>1.5.643.0</PSModuleVersion>
<SystemSettings i:type="a:SystemSettings" xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Utilities.SystemSettings">
<a:MachineName>$machineName</a:MachineName>
<a:OsLanguage>$OSLanguage</a:OsLanguage>
<a:OsLocale>$OSLocale</a:OsLocale>
<a:OsSku>$OSSku</a:OsSku>
<a:OsVersion>$OSVersion</a:OsVersion>
</SystemSettings>
</RegistrationRequestSettings>
<TenantId>$tenantId</TenantId>
<UserAgent>$($AgentInfo[$AgentType]["UserAgent"])</UserAgent>
</RegistrationRequest>
"@
# Register the app and get the certificate
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://$tenantId.registration.msappproxy.net/register/RegisterConnector" -Method Post -Body $body -Headers @{"Content-Type"="application/xml; charset=utf-8"}
if($response.RegistrationResult.IsSuccessful -eq "true")
{
# Get the certificate
$b64Cert = $response.RegistrationResult.Certificate
}
else
{
# Something went wrong
Write-Error $response.RegistrationResult.ErrorMessage
}
}
if(![string]::IsNullOrEmpty($b64Cert))
{
# Convert certificate to byte array
$binCert = [convert]::FromBase64String($b64Cert)
# Create a new x509certificate
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($binCert,"",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::UserKeySet -band [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
# Get the instance Id (=Agent Id)
foreach($extension in $cert.Extensions)
{
if($extension.Oid.Value -eq "1.3.6.1.4.1.311.82.1")
{
$InstanceID = [guid]$extension.RawData
}
}
if([string]::IsNullOrEmpty($FileName))
{
$FileName = "$($MachineName)_$($tenantId)_$($InstanceID)_$($cert.Thumbprint).pfx"
}
# Store the private key so that it can be exported
$cspParameters = [System.Security.Cryptography.CspParameters]::new()
$cspParameters.ProviderName = "Microsoft Enhanced RSA and AES Cryptographic Provider"
$cspParameters.ProviderType = 24
$cspParameters.KeyContainerName ="AADInternals"
# Set the private key
$privateKey = [System.Security.Cryptography.RSACryptoServiceProvider]::new(2048,$cspParameters)
$privateKey.ImportParameters($rsa.ExportParameters($true))
$cert.PrivateKey = $privateKey
# Export the certificate to pfx
$binCert = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx)
Set-BinaryContent -Path $fileName -Value $binCert
# Remove the private key from the store
$privateKey.PersistKeyInCsp=$false
$privateKey.Clear()
if($UpdateTrust)
{
Write-Host "$AgentType Agent ($InstanceID) certificate renewed for $MachineName"
}
else
{
Write-Host "$AgentType Agent ($InstanceID) registered as $MachineName"
}
Write-Host "Certificate saved to $FileName"
# We need to register the agent to a group
if($AgentType -eq "Sync" -and [string]::IsNullOrEmpty($AgentGroup) -ne $true)
{
Add-ProxyAgentToGroup -AccessToken $AccessToken -Agent $InstanceID -Group $AgentGroup
}
}
}
}
# Gets list of publishing agents
# Apr 3rd 2020
function Get-ProxyAgents
{
<#
.SYNOPSIS
Shows the list of MS App Proxy agents
.DESCRIPTION
Shows the list of MS App Proxy authentication and provisioning agents
.Example
Get-AADIntProxyAgents | ft
id machineName externalIp status supportedPublishingTypes
-- ----------- ---------- ------ ------------------------
51f3afd9-685b-413a-aafa-bab0d556ea4b this.is.a.fake 67.35.155.73 active {authentication}
51a061a0-968d-48b8-951e-5ae9d9a0441f server1.company.com 93.188.31.116 inactive {authentication}
49c9ad46-c067-42f6-a678-dfd938c27789 server2.company.com 102.20.104.213 inactive {provisioning}
.Example
$pt=Get-AADIntAccessTokenForPTA
PS C:\>Get-AADIntProxyAgents -AccessToken $pt | pt
id machineName externalIp status supportedPublishingTypes
-- ----------- ---------- ------ ------------------------
51f3afd9-685b-413a-aafa-bab0d556ea4b this.is.a.fake 67.35.155.73 active {authentication}
51a061a0-968d-48b8-951e-5ae9d9a0441f server1.company.com 93.188.31.116 inactive {authentication}
49c9ad46-c067-42f6-a678-dfd938c27789 server2.company.com 102.20.104.213 inactive {provisioning}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Begin
{
$publishingTypes = @( # Roles that can access the agent
#"appProxy" # ApplicationAdmin, GlobalAdmin
"authentication" # GlobalAdmin
"provisioning" # GlobalAdmin
"exchangeOnline" # GlobalAdmin
#"intunePfx" # GlobalAdmin
#"oflineDomainJoin" # GlobalAdmin
"adAdministration" # DirSyncAdmin, GlobalAdmin
#"unknownFutureValue" #
)
}
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8"
# Get the tenant id and instance id from the certificate
$TenantId = Get-TenantID -AccessToken $AccessToken
$headers = @{
"Authorization" = "Bearer $AccessToken"
"x-ms-gateway-serviceRoot" =""
}
foreach($type in $publishingTypes)
{
$agents = Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('$type')/agents" -Method Get -Headers $headers -ErrorAction SilentlyContinue
# Return
if($agents)
{
$agents.value
}
}
}
}
# Gets list of agent groups
# Apr 6th 2020
function Get-ProxyAgentGroups
{
<#
.SYNOPSIS
Lists MS App Proxy agent groups
.DESCRIPTION
Lists MS App Proxy agent groups
.Example
Get-AADIntAgentProxyGroups
TenantId : ea664074-37dd-4797-a676-b0cf6fdafcd4
ConfigurationDisplayName : company.com
ConfigurationResourceName : company.com
ConfigurationPublishingType : provisioning
id : 4b6ffe82-bfe2-4357-814c-09da95399da7
displayName : Group-company.com-42660f4a-9e66-4a08-ac17-2a2e0d8b993e
publishingType : provisioning
isDefault : False
.Example
$pt=Get-AADIntAccessTokenForPTA
PS C:\>Get-AADIntProxyGroups -AccessToken $pt
TenantId : ea664074-37dd-4797-a676-b0cf6fdafcd4
ConfigurationDisplayName : company.com
ConfigurationResourceName : company.com
ConfigurationPublishingType : provisioning
id : 4b6ffe82-bfe2-4357-814c-09da95399da7
displayName : Group-company.com-42660f4a-9e66-4a08-ac17-2a2e0d8b993e
publishingType : provisioning
isDefault : False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8"
# Get the tenant id and instance id from the certificate
$TenantId = Get-TenantID -AccessToken $AccessToken
$headers = @{
"Authorization" = "Bearer $AccessToken"
"x-ms-gateway-serviceRoot" =""
}
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('provisioning')/agentGroups?`$expand=agents" -Method Get -Headers $headers
# return
$response.value
}
}
# Gets the list of proxy configurations
#function Get-ProxyConfigurations
# Creates a new proxy agent group
# Apr 6th 2020
function New-ProxyAgentGroup
{
<#
.SYNOPSIS
Creates an MS App Proxy agent group
.DESCRIPTION
Creates an MS App Proxy agent group
.Example
Get-AADIntAgentProxyGroups
TenantId : ea664074-37dd-4797-a676-b0cf6fdafcd4
ConfigurationDisplayName : company.com
ConfigurationResourceName : company.com
ConfigurationPublishingType : provisioning
id : 4b6ffe82-bfe2-4357-814c-09da95399da7
displayName : Group-company.com-42660f4a-9e66-4a08-ac17-2a2e0d8b993e
publishingType : provisioning
isDefault : False
.Example
$pt=Get-AADIntAccessTokenForPTA
PS C:\>Get-AADIntProxyGroups -AccessToken $pt
TenantId : ea664074-37dd-4797-a676-b0cf6fdafcd4
ConfigurationDisplayName : company.com
ConfigurationResourceName : company.com
ConfigurationPublishingType : provisioning
id : 4b6ffe82-bfe2-4357-814c-09da95399da7
displayName : Group-company.com-42660f4a-9e66-4a08-ac17-2a2e0d8b993e
publishingType : provisioning
isDefault : False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DisplayName,
[Parameter(Mandatory=$True)]
[String]$ConfigurationDisplayName,
[Parameter(Mandatory=$True)]
[String]$ConfigurationResourceName
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8"
# Get the tenant id and instance id from the certificate
$TenantId = Get-TenantID -AccessToken $AccessToken
$headers = @{
"Authorization" = "Bearer $AccessToken"
"x-ms-gateway-serviceRoot" =""
"Content-Type" = "application/json"
}
# First, create the agent group with the given name
$Body = "{""displayName"":""$DisplayName""}"
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('provisioning')/agentGroups" -Method POST -Headers $headers -Body $Body
$Body = "{""displayName"":""$ConfigurationDisplayName"",""resourceName"":""$ConfigurationResourceName"",""agentGroups"":[{""id"":""$($response.id)""}]}"
$response2 = Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('provisioning')/publishedResources" -Method POST -Headers $headers -Body $Body
# Extract the information and create the return value
$attributes=[ordered]@{}
$attributes["id"]=$response.id
$attributes["displayName"]=$response.displayName
$attributes["publishingType"]=$response.publishingType
$attributes["isDefault"]=$response.isDefault
$attributes["ConfigurationId"]=$response2.id
$attributes["ConfigurationDisplayName"]=$response2.displayName
$attributes["ConfigurationResourceName"]=$response2.resourceName
$attributes["ConfigurationPublishingType"]=$response2.publishingType
# return
New-Object PSObject -Property $attributes
}
}
# Adds the given agent to given group
# Apr 7th 2020
function Add-ProxyAgentToGroup
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[guid]$Agent,
[Parameter(Mandatory=$True)]
[guid]$Group
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://proxy.cloudwebappproxy.net/registerapp" -ClientId "cb1056e2-e479-49de-ae31-7812af012ed8"
# Get the tenant id and instance id from the certificate
$TenantId = Get-TenantID -AccessToken $AccessToken
$body="{""@odata.id"":""https://$TenantId.admin.msappproxy.net:443/onPremisesPublishingProfiles('provisioning')/agentGroups('$($Group.toString())')""}"
$headers = @{
"Authorization" = "Bearer $AccessToken"
"x-ms-gateway-serviceRoot" =""
"Content-Type" = "application/json"
}
Invoke-RestMethod -UseBasicParsing -Uri "https://$TenantId.admin.msappproxy.net/onPremisesPublishingProfiles('provisioning')/agents('$($Agent.toString())')/agentGroups/`$ref" -Method Post -Headers $headers -Body $body
Write-Host "Agent ($($Agent.toString())) added to group ($($Group.toString()))"
}
}
# Export proxy agent certificates from the local computer
# Mar 8th 2022
# Aug 17th 2022: Added support for exporting from NETWORK SERVICE personal store
function Export-ProxyAgentCertificates
{
<#
.SYNOPSIS
Export certificates of all MS App Proxy agents from the local computer.
.DESCRIPTION
Export certificates of all MS App Proxy agents from the local computer.
The filename of the certificate is <server FQDN>_<tenant id>_<agent id>_<cert thumbprint>.pfx
.Example
Export-AADIntProxyAgentCertificates
Certificate saved to: PTA01.company.com_ea664074-37dd-4797-a676-b0cf6fdafcd4_4b6ffe82-bfe2-4357-814c-09da95399da7_A3457AEAE25D4C513BCF37CB138628772BE1B52.pfx
.Example
Export-AADIntProxyAgentCertificates -GetBootstrap
Certificate saved to: PTA01.company.com_ea664074-37dd-4797-a676-b0cf6fdafcd4_4b6ffe82-bfe2-4357-814c-09da95399da7_A3457AEAE25D4C513BCF37CB138628772BE1B52.pfx
Bootstrap saved to: PTA01.company.com_ea664074-37dd-4797-a676-b0cf6fdafcd4_4b6ffe82-bfe2-4357-814c-09da95399da7_A3457AEAE25D4C513BCF37CB138628772BE1B52.xml
#>
[cmdletbinding()]
Param(
[Switch]$GetBootstrap
)
Process
{
# Get all certificates from LocalMachine Personal store
$certificates = @(Get-Item Cert:\LocalMachine\My\*)
# Internal function to parse PTA & Provisioning agent configs
function Parse-ConfigCert
{
[cmdletbinding()]
Param(
[String]$ConfigPath
)
Process
{
# Check if we have a PTA or provisioning agent configuration and get the certificate if stored in NETWORK SERVICE personal store
[xml]$trustConfig = Get-Content "$env:ProgramData\Microsoft\$ConfigPath\Config\TrustSettings.xml" -ErrorAction SilentlyContinue
if($trustConfig)
{
$thumbPrint = $trustConfig.ConnectorTrustSettingsFile.CloudProxyTrust.Thumbprint
# Check where the certificate is stored
if($trustConfig.ConnectorTrustSettingsFile.CloudProxyTrust.IsInUserStore.ToLower().equals("true"))
{
# Certificate is stored in NETWORK SERVICE personal store so we need to parse it from there
Write-Verbose "Parsing certificate: $($thumbPrint)"
Parse-CertBlob -Data (Get-BinaryContent "$env:windir\ServiceProfiles\NetworkService\AppData\Roaming\Microsoft\SystemCertificates\My\Certificates\$thumbPrint")
}
}
}
}
if($PTACert = Parse-ConfigCert -ConfigPath "Azure AD Connect Authentication Agent")
{
$binCert = $PTACert.DER
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$binCert)
$PTAKeyName = $PTACert.KeyName
$certificates += $certificate
}
if($ProvCert = Parse-ConfigCert -ConfigPath "Azure AD Connect Provisioning Agent")
{
$binCert = $ProvCert.DER
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$binCert)
$ProvKeyName = $ProvCert.KeyName
$certificates += $certificate
}
$CurrentUser = "{0}\{1}" -f $env:USERDOMAIN,$env:USERNAME
Write-Warning "Elevating to LOCAL SYSTEM. You MUST restart PowerShell to restore $CurrentUser rights."
foreach($certificate in $certificates)
{
Write-Verbose "Reading certificate: $($certificate.Thumbprint)"
foreach($ext in $Certificate.Extensions)
{
# Check the agent Id OID exist
if($ext.Oid.Value -eq "1.3.6.1.4.1.311.82.1")
{
# Extract agent and tenant IDs
$agentId = [guid] $ext.RawData
$tenantId = [guid] $certificate.Subject.Split("=")[1]
Write-Verbose " Tenant Id: $tenantId, Agent Id: $agentId"
# Get the certificate
$binCert = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
# Get the key blob and decrypt the keys
if($PTACert)
{
# If stored in NETWORK SERVICE store, PTA Agent's key name can't be readed from the certificate
$keyName = $PTAKeyName
}
elseif($ProvCert)
{
# If stored in NETWORK SERVICE store, Provisioning Agent's key name can't be readed from the certificate
$keyName = $ProvKeyName
}
else
{
# Read the key name from the certificate
$keyName = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate).key.uniquename
}
# Discard trailing null, cr, lf
$keyName = $keyName.trimEnd(@(0x00,0x0a,0x0d))
$paths = @(
"$env:ALLUSERSPROFILE\Microsoft\Crypto\RSA\MachineKeys\$keyName"
"$env:ALLUSERSPROFILE\Microsoft\Crypto\Keys\$keyName"
"$env:windir\ServiceProfiles\NetworkService\AppData\Roaming\Microsoft\Crypto\RSA\S-1-5-20\$keyName"
)
foreach($path in $paths)
{
$keyBlob = Get-BinaryContent $path -ErrorAction SilentlyContinue
if($keyBlob)
{
Write-Verbose "Key loaded from $path"
break
}
}
if(!$keyBlob)
{
if($keyName.EndsWith(".PCPKEY"))
{
# This machine has a TPM
Throw "PCP keys are not supported, unable to export private key!"
}
else
{
Throw "Error accessing key. If you are already elevated to LOCAL SYSTEM, restart PowerShell and try again."
}
return
}
$blobType = [System.BitConverter]::ToInt32($keyBlob,0)
switch($blobType)
{
1 { $privateKey = Parse-CngBlob -Data $keyBlob -Decrypt -LocalMachine}
2 { $privateKey = Parse-CapiBlob -Data $keyBlob -Decrypt -LocalMachine}
default { throw "Unsupported key blob type" }
}
# Save to pfx file
$fileName = "$(Get-ComputerName -FQDN)_$($tenantId)_$($agentId)_$($certificate.Thumbprint).pfx"
Set-BinaryContent -Path $fileName -Value (New-PfxFile -RSAParameters ($privateKey.RSAParameters) -X509Certificate $binCert)
Write-Host "Certificate saved to: $fileName"
if($GetBootstrap)
{
try
{
$bootStrap = Get-BootstrapConfiguration -MachineName (Get-ComputerName -FQDN) -Certificate (Load-Certificate -FileName $fileName)
$bootStrapFileName = "$(Get-ComputerName -FQDN)_$($tenantId)_$($agentId)_$($certificate.Thumbprint).xml"
Set-Content $bootStrapFileName -Value $bootStrap
Write-Host "Bootstrap saved to: $bootStrapFileName"
}
catch
{
Write-Warning "Could not get bootstrap using certificate $($certificate.Thumbprint)!"
}
}
break
}
}
}
}
}