forked from microsoft/activity-log-export-automation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SetupDefaultEventHub.ps1
255 lines (220 loc) · 9.23 KB
/
SetupDefaultEventHub.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
#settings
$AzureSub="MyAzureSub"
$RGName = "MyLoggingRG"
$Location = "South Central US"
$ResourceTags = @{"Owner" = "Corp"}
$splunkConnectorName = "AzureActivityLogs"
#Update the following two variables to use an existing Key Vault, must be in same region and subscription.
#Leave set to $null to create a new Key Vault
$KVRGName = $null
$KVName = $null
#################################################################
# Don't modify anything below unless you know what you're doing.
#################################################################
#variables
$namespace = "$($RGName)Hub"
$AppDisplayName = "$($RGName)App"
$secretName = "EHLoggingCredentials"
if((!$KVRGName) -and (!$KVName)){
$vaultName = "$($RGName)Vault"
$KVRGName = $RGName
}elseif(($KVRGName -and ($KVName))) {
$vaultName = $KVName
}else{
Write-Host -ForegroundColor Red "Please check the values for KVRGName and KVName, must be both populated or left empty"
return
}
Write-Host "Authenticating..."
$ctx=Get-AzureRmContext
if ($ctx.Account -eq $null) {
Login-AzureRmAccount
}
if ($ctx.SubscriptionName -ne $AzureSub) {
Set-AzureRmContext -SubscriptionName $AzureSub
}
$ctx=Get-AzureRmContext -ErrorAction Stop
#force context to grab a token for graph
Get-AzureRmADUser -UserPrincipalName $ctx.Account.Id -ErrorAction Stop
$cache = $ctx.TokenCache
$cacheItems = $cache.ReadItems()
$token = ($cacheItems | where { $_.Resource -eq "https://graph.windows.net/" })
if ($token.ExpiresOn -le [System.DateTime]::UtcNow) {
$ac = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new("$($ctx.Environment.ActiveDirectoryAuthority)$($ctx.Tenant.Id)",$token)
#appId is well-known id of Powershell; reusing token cache from AzureRM login
$token = $ac.AcquireTokenByRefreshToken($token.RefreshToken, "1950a258-227b-4e31-a9cf-717495945fc2", "https://graph.windows.net")
}
$aad = Connect-AzureAD -AadAccessToken $token.AccessToken -AccountId $ctx.Account.Id -TenantId $ctx.Tenant.Id -ErrorAction Stop
$SubscriptionId = $ctx.Subscription.Id
$tenantid = $ctx.Tenant.Id
Write-Host "Setting up Resource Group..."
#create Resource Group for Event Hub
$rg = Get-AzureRmResourceGroup -Name $RGName -ErrorAction SilentlyContinue
if ($rg -eq $null) {
$rg = New-AzureRmResourceGroup `
-Name $RGName `
-Location $Location `
-Tag $ResourceTags `
-ErrorAction Stop
}
Write-Host "Setting up Event Hub..."
$ehn = Get-AzureRmEventHubNamespace -ResourceGroupName $RGName -Name $Namespace -ErrorAction SilentlyContinue
if ($ehn -eq $null) {
#test if event hub namespace exists
$ehntest = Test-AzureRmEventHubName -Namespace $namespace
if ($ehntest.NameAvailable -eq $true) {
#create event hub namespace
$ehn = New-AzureRmEventHubNamespace `
-ResourceGroupName $RGName `
-Name $Namespace `
-Location $Location `
-SkuName Standard `
-SkuCapacity 1 `
-EnableAutoInflate $true `
-Tag $ResourceTags `
-ErrorVariable NSError
} elseif ($ehntest.NameAvailable -eq $false) {
Write-Host -F Red $ehntest.Message
Return
}
}
$ehkey = Get-AzureRmEventHubKey `
-ResourceGroupName $RGName `
-Namespace $Namespace `
-Name "RootManageSharedAccessKey" `
-ErrorAction Stop
#get new namespace authorization rule
$rule = Get-AzureRmEventHubAuthorizationRule -ResourceGroupName $RGName -Namespace $Namespace -ErrorAction Stop
Write-Host "Setting up Key vault..."
$kv = Get-AzureRmKeyVault -VaultName $vaultName -ResourceGroupName $KVRGName
if ($kv) {
#Check location
if ($kv.Location -eq $Location) {
Write-Host ("Using Existing Key Vault {0}" -f $kv.VaultName)
}elseif($kv.Location -ne $Location){
Write-host -F Red ("Unable to use existing Key Vault {0},must be located in {1} region" -f $kv.VaultName, $Location)
Return
}
}
elseif (!$kv) {
#Create Azure Key vault
$kv = New-AzureRmKeyVault `
-VaultName $vaultName `
-ResourceGroupName $KVRGName `
-Location $Location `
-ErrorAction Stop
}
Write-Host "Setting up Service Principal..."
$uri = "http://$($AppDisplayName).$((Get-AzureRmSubscription -SubscriptionName $AzureSub).TenantId)"
#setup access rules for new app
$appResources = [System.Collections.Generic.List[Microsoft.Open.AzureAD.Model.RequiredResourceAccess]]::New()
# get AAD SPN/perms
$aadapp = Get-AzureADServicePrincipal -Filter "DisplayName eq 'Windows Azure Active Directory'" -ErrorAction Stop
if ($aadapp -eq $null) {
throw [System.Exception] "Azure AD Service Principal not found, please check the name"
exit 1
}
$aadSignInPerm = $aadapp | select -expand Oauth2Permissions | ? {$_.value -eq "User.Read"}
try {
# create perm object
$readAndSignInPerm = [Microsoft.Open.AzureAD.Model.ResourceAccess]::New()
$readAndSignInPerm.Id = $aadSignInPerm.Id
$readAndSignInPerm.Type = "Scope"
# Read/Sign-In Perms to AAD
$appAccess = [Microsoft.Open.AzureAD.Model.RequiredResourceAccess]::New()
$appAccess.ResourceAppId = $aadapp.AppId
$appAccess.ResourceAccess = $readAndSignInPerm
$appResources.Add($appAccess)
}
catch {
throw [System.Exception] "Error creating permissions objects. Please ensure you have installed the Microsoft ADAL library from NuGet or https://github.com/AzureAD/microsoft-authentication-library-for-dotnet"
exit 1
}
#hack to work around odata filter using variable
$execstr = "AzureAD\Get-AzureADApplication -Filter `"identifierUris/any(uri:uri eq '$uri')`""
$app = Invoke-Expression $execstr
if ($app -ne $null) {
#start over
AzureAD\Remove-AzureADApplication -ObjectId $app.ObjectId -ErrorAction Stop
Start-Sleep 3
}
#Create AzureAD Application
$app = AzureAD\New-AzureADApplication `
-DisplayName $AppDisplayName `
-IdentifierUris $uri `
-RequiredResourceAccess $appResources `
-ErrorAction Stop
#create Service Principal
$sp = AzureAD\New-AzureADServicePrincipal `
-AppId $app.AppId `
-DisplayName $AppDisplayName `
-Tags {WindowsAzureActiveDirectoryIntegratedApp} `
-ErrorAction Stop
# Generate a client secret
$now = Get-Date
$addYear = $now.AddYears(1)
$cred = New-AzureADApplicationPasswordCredential -ObjectId $app.ObjectId -StartDate $now -EndDate $addYear -CustomKeyIdentifier "Key1"
Write-Host "Pausing 60 seconds to let our new service principal propagate..."
#give AAD 60 seconds to propagate the new SP over to the directory for RBAC assignment
Start-Sleep 60
Write-Host "Adding RBAC role assignment..."
#assign role
New-AzureRmRoleAssignment `
-ObjectId $sp.ObjectId `
-RoleDefinitionName "Reader" `
-Scope "/subscriptions/$($SubscriptionId)" `
-ErrorAction Stop
Write-Host "Adding access to key vault..."
#grant "Get Secrets" access to Key Vault
Set-AzureRmKeyVaultAccessPolicy `
-VaultName $vaultName `
-ObjectId $sp.ObjectId `
-PermissionsToSecrets get `
-ResourceGroupName $KVRGName `
-ErrorAction Stop
Write-Host "Adding secrets to Key vault..."
#get and store key
$ss = ConvertTo-SecureString -String $ehkey.PrimaryKey -AsPlainText -Force
$secret = Set-AzureKeyVaultSecret `
-VaultName $kv.VaultName `
-Name $secretName `
-SecretValue $ss `
-ContentType "RootManageSharedAccessKey" `
-ErrorAction Stop
$output = @{
"Name" = $splunkConnectorName;
"SPNTenantID" = $ctx.Tenant.Id;
"SPNApplicationID" = $sp.AppId;
"SPNApplicationKey" = $cred.Value;
"eventHubNamespace" = $ehn.Name;
"vaultName" = $kv.VaultName;
"secretName" = $secret.Name;
"secretVersion" = $secret.Version;
"ruleid" = $rule.id;
}
Write-Host ""
Write-Host "---"
Write-Host "Configuration complete"
Write-Host ""
Write-Host ""
Write-Host "****************************"
Write-Host "*** RuleID for Profiles ***"
Write-Host "****************************"
Write-Host ""
Write-Host $output.ruleid
Write-Host ""
Write-Host "****************************"
Write-Host "*** SPLUNK CONFIGURATION ***"
Write-Host "****************************"
Write-Host ""
Write-Host "Data Input Settings for configuration as explained at https://github.com/Microsoft/AzureMonitorAddonForSplunk/wiki/Configuration-of-Splunk"
Write-Host ""
Write-Host " AZURE MONITOR ACTIVITY LOG"
Write-Host " ----------------------------"
Write-Host " Name: " $output.Name
Write-Host " SPNTenantID: " $output.SPNTenantID
Write-Host " SPNApplicationId: " $output.SPNApplicationID
Write-Host " SPNApplicationKey: " $output.SPNApplicationKey
Write-Host " eventHubNamespace: " $output.eventHubNamespace
Write-Host " vaultName: " $output.vaultName
Write-Host " secretName: " $output.secretName
Write-Host " secretVersion: " $output.secretVersion