-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.ps1
163 lines (132 loc) · 8.36 KB
/
install.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# Run this script as an administrator
Start-Transcript -Path ".\Logs" -NoClobber -Append
# region Include required files
#
$ScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
try {
. ("$ScriptDirectory\functions.ps1")
}
catch {
Write-Host "Error while loading supporting PowerShell Scripts"
}
#endregion
# --- config start
$adminUser = "[email protected]"
$appName = "AzureADGuestLifecycleMgmt" # The Application name bust be a maximum of 32 characters
$adalUrlIdentifier = "https://mindcore.dk/AzureADGuestLifecycleMgmt"
$appReplyUrl = "https://mindcore.dk"
$dnsName = "M365x439370.onmicrosoft.com" # Your DNS name
#$password = "P@ssw0rd1" # Certificate password
$password = StrongPassword
$folderPath = ".\certificate" # Where do you want the files to get saved to? The folder needs to exist.
$fileName = "AzureADGuestLifecycleMgmt" # What do you want to call the cert files? without the file extension
$currentDate = Get-Date # Get todays date
$yearsValid = 10 # Number of years until you need to renew the certificate
$keyVaultName = "guestlifecyclemgmt" # Key Vault Name as specified in ARM Templates.
$rgLocation = "West Europe" # Azure Resource Group Location
# --- config end
$certStoreLocation = 'cert:\LocalMachine\My'
$expirationDate = (Get-Date).AddYears($yearsValid)
$certificateThumb = (New-SelfSignedCertificate -DnsName $dnsName -CertStoreLocation $certStoreLocation -NotAfter $expirationDate -KeyExportPolicy Exportable -KeySpec Signature).Thumbprint
$certificateThumb > $folderPath'\certificate-thumb.txt'
$certificatePath = $certStoreLocation + '\' + $certificateThumb
$filePath = $folderPath + '\' + $fileName
$securePassword = ConvertTo-SecureString -String $password -Force -AsPlainText
Export-Certificate -Cert $certificatePath -FilePath ($filePath + '.cer')
Export-PfxCertificate -Cert $certificatePath -FilePath ($filePath + '.pfx') -Password $securePassword
$path = (Get-Item -Path $folderPath).FullName
$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate("$path\$fileName.pfx", $securePassword)
$keyValue = [System.Convert]::ToBase64String($cert.GetRawCertData())
$keyValue > certificate\pfx-encoded.txt
#Install AzureAD PowerShell Module
Install-Module -Name AzureAD -Force
Import-Module AzureAD
# Connect to Azure AD as an admin account
Connect-AzureAD -AccountId $adminUser
# Store tenantid
$tenant = Get-AzureADTenantDetail
$tenant.ObjectId > $folderPath\tenantid.txt
# Add AuditLog.Read.All access
$svcPrincipal = Get-AzureADServicePrincipal -All $true | ? { $_.DisplayName -eq "Microsoft Graph" }
$appRole = $svcPrincipal.AppRoles | ? { $_.Value -eq "AuditLog.Read.All" }
$appPermission = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "$($appRole.Id)", "Role"
#Add Directory.ReadWrite.All access
$appRole2 = $svcPrincipal.AppRoles | ? { $_.Value -eq "Directory.ReadWrite.All" }
$appPermission2 = New-Object -TypeName "Microsoft.Open.AzureAD.Model.ResourceAccess" -ArgumentList "$($appRole2.Id)", "Role"
$reqGraph = New-Object -TypeName "Microsoft.Open.AzureAD.Model.RequiredResourceAccess"
$reqGraph.ResourceAppId = $svcPrincipal.AppId
$reqGraph.ResourceAccess = $appPermission, $appPermission2
# Create Azure Active Directory Application (ADAL)
$application = New-AzureADApplication -DisplayName $appName -IdentifierUris $adalUrlIdentifier -ReplyUrls $appReplyUrl -RequiredResourceAccess $reqGraph
#Add AzureAD App Key Credential
New-AzureADApplicationKeyCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "$appName" -Type AsymmetricX509Cert -Usage Verify -Value $keyValue -StartDate $currentDate -EndDate $expirationDate.AddDays(-1)
#Add AzureAD App ClientSecret (Not tested)
New-AzureADApplicationPasswordCredential -ObjectId $application.ObjectId -CustomKeyIdentifier "$appName" -StartDate $currentDate -EndDate $expirationDate.AddDays(-1)
Write-Host "A browser window will open shortly, please login and consent to the security popup and then close the browser window." -ForegroundColor Green
Start-Sleep 20 # Give it time to create App Registration
# https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-permissions-and-consent
$consentUri = "https://login.microsoftonline.com/$($tenant.ObjectId)/adminconsent?client_id=$($application.AppId)&state=12345&redirect_uri=$appReplyUrl"
$consentUri | clip
#Write-Host "Please make sure you have consented to the Security popup. If not the URL has been copied to your clipboard - paste it into a browser and consent to the popup." -ForegroundColor Green
Write-Host $consentUri -ForegroundColor Blue
Start-Process "$consentUri"
Write-Warning "Please make sure you have consented to the Security popup. If not the URL has been copied to your clipboard - paste it into a browser and consent to the popup. Have you approved the consent Popup?" -WarningAction Inquire
$appId = $application.AppId
$appId > $folderPath\appid.txt
Start-Sleep 10 # Give it time before connecting
Connect-AzureAD -TenantId $tenant.ObjectId -ApplicationId $Application.AppId -CertificateThumbprint $certificateThumb
[Microsoft.Open.Azure.AD.CommonLibrary.AzureSession]::AccessTokens["AccessToken"]
Disconnect-AzureAD
###################################################################################################################
# Start ARM Template Deployment
Write-Warning "Do you wish to continue the deployment and setup the application in Azure?" -WarningAction Inquire
#Install AZ PowerShell Modules
Import-Module -Name Az -Force
#Clear-AzContext
Connect-AzAccount -Tenant $tenant.ObjectId
# Create a New Resource Group for AzureADGuestLifecycleMgmt
Write-Host "Creating the Azure resource group." -ForegroundColor Green
$resourceGroup = "RG_"+$appName
New-AzResourceGroup -Name $resourceGroup -Location $rgLocation
# Start Azure Resource Manager Template Deployment
Write-Host "Starting ARM template deployment." -ForegroundColor Green
New-AzResourceGroupDeployment -ResourceGroupName $resourceGroup -TemplateUri "https://raw.githubusercontent.com/myatix/AzureADGuestLifecycleMgmt/master/guestLifecycleMgmt.json" -TemplateParameterUri "https://raw.githubusercontent.com/myatix/AzureADGuestLifecycleMgmt/master/guestLifecycleMgmt.parameters.json" -Verbose
#Set Key Vault Access Policies
#$objectID = $application.ObjectId
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -ServicePrincipalName $appId -PermissionsToSecrets get -PermissionsToCertificates get
Set-AzKeyVaultAccessPolicy -VaultName $keyVaultName -UserPrincipalName $adminUser -PermissionsToSecrets all -PermissionsToCertificates all -PermissionsToKeys all
# Add Certificate to Azure Key Vault.
Write-Host "Adding certificate to Azure Key Vault." -ForegroundColor Green
Import-AzKeyVaultCertificate -VaultName $keyVaultName -Name $fileName -FilePath ($filePath + '.pfx') -Password $securePassword
###############################################################################################################################
# Add Log Analytics Workspace
Write-Warning "Do you want to create a new Log Analytics Workspace for $appName" -WarningAction Inquire
$WorkspaceName = "log-analytics-" + $appName # workspace names need to be unique in resource group - Get-Random helps with this for the example code
# Create the resource group if needed
try {
Get-AzResourceGroup -Name $ResourceGroup -ErrorAction Stop
} catch {
New-AzResourceGroup -Name $ResourceGroup -Location $rgLocation
}
# Create the workspace
New-AzOperationalInsightsWorkspace -Location $rgLocation -Name $WorkspaceName -Sku Standard -ResourceGroupName $ResourceGroup
# Saved Searches to import
$ExportedSearches = @"
[
{
"Category": "My Saved Searches",
"DisplayName": "New Guest Invitations",
"Query": "AuditLogs | where OperationName == 'Invite external user' and Result == 'success'",
"Version": 1
}
]
"@
# Import Saved Searches
foreach ($search in $ExportedSearches) {
$id = $search.Category + "|" + $search.DisplayName
New-AzOperationalInsightsSavedSearch -ResourceGroupName $ResourceGroup -WorkspaceName $WorkspaceName -SavedSearchId $id -DisplayName $search.DisplayName -Category $search.Category -Query $search.Query -Version $search.Version
}
# Work in progress
#New-AzScheduledQueryRule -Location $rgLocation -Action $alertingAction -Enabled $true -Description "log alert foo" -Schedule $schedule -Source $source -Name "New Guest Invitations"
Stop-Transcript
Write-Host "Installation Complete" -ForegroundColor Green