-
Notifications
You must be signed in to change notification settings - Fork 1
/
Disable-PowerShellAccessExoForNonAdmins.ps1
359 lines (290 loc) · 10.7 KB
/
Disable-PowerShellAccessExoForNonAdmins.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
<#
.DESCRIPTION
Disables exchange Online Powershell capabilites for users which are not members of specific groups or Azure AD roles to reduce the attack surface.
The Service Principal(RunAs) of the Azure Automation Workspace requires:
- MSGraph
- Group.Read.All
- GroupMember.ReadWrite.All
- RoleManagement.Read.Directory
- User.ReadWrite.All
- Office 365 Exchange Online
- Exchange.ManageAsApp
Additionally, the service principal needs to get the the "Exchange Administrator" role assigned in Azure AD.
.EXAMPLE
.\Disable-PowerShellAccessExoForNonAdmins.ps1
.NOTES
Author: Thomas Kurth/baseVISION
Date: 29.10.2021
History
001: First Version
ExitCodes:
0: Successfull
#>
[CmdletBinding()]
Param()
## Manual Variable Definition
########################################################
$tenant = "kurcontoso.onmicrosoft.com" # Name of the tenant
$ExceptionGroups = @("b8fe869d-ff0a-4427-80dd-7c141db3d69c") # Id of groups, members of them will be able to use Exchange PowerShell.
$ExceptionRoles = @("Exchange Administrator","Global Administrator","Security Administrator","Security Reader") # Names of Azure AD roles, members of them will be able to use Exchange PowerShell.
$DebugPreference = "Continue"
$ScriptVersion = "001"
$ScriptName = "Disable-PowerShellAccessExoForNonAdmins"
$LogFilePathFolder = "C:\Windows\Logs"
$FallbackScriptPath = "C:\Windows" # This is only used if the filename could not be resolved(IE running in ISE)
# Log Configuration
$DefaultLogOutputMode = "Console-LogFile" # "Console-LogFile","Console-WindowsEvent","LogFile-WindowsEvent","Console","LogFile","WindowsEvent","All"
$DefaultLogWindowsEventSource = $ScriptName
$DefaultLogWindowsEventLog = "CustomPS"
#region Functions
########################################################
function Write-Log {
<#
.DESCRIPTION
Write text to a logfile with the current time.
.PARAMETER Message
Specifies the message to log.
.PARAMETER Type
Type of Message ("Info","Debug","Warn","Error").
.PARAMETER OutputMode
Specifies where the log should be written. Possible values are "Console","LogFile" and "Both".
.PARAMETER Exception
You can write an exception object to the log file if there was an exception.
.EXAMPLE
Write-Log -Message "Start process XY"
.NOTES
This function should be used to log information to console or log file.
#>
param(
[Parameter(Mandatory = $true, Position = 1)]
[String]
$Message
,
[Parameter(Mandatory = $false)]
[ValidateSet("Info", "Debug", "Warn", "Error")]
[String]
$Type = "Debug"
,
[Parameter(Mandatory = $false)]
[ValidateSet("Console-LogFile", "Console-WindowsEvent", "LogFile-WindowsEvent", "Console", "LogFile", "WindowsEvent", "All")]
[String]
$OutputMode = $DefaultLogOutputMode
,
[Parameter(Mandatory = $false)]
[Exception]
$Exception
)
$DateTimeString = Get-Date -Format "yyyy-MM-dd HH:mm:sszz"
$Output = ($DateTimeString + "`t" + $Type.ToUpper() + "`t" + $Message)
if ($Exception) {
$ExceptionString = ("[" + $Exception.GetType().FullName + "] " + $Exception.Message)
$Output = "$Output - $ExceptionString"
}
if ($OutputMode -eq "Console" -OR $OutputMode -eq "Console-LogFile" -OR $OutputMode -eq "Console-WindowsEvent" -OR $OutputMode -eq "All") {
if ($Type -eq "Error") {
Write-Error $output
}
elseif ($Type -eq "Warn") {
Write-Warning $output
}
elseif ($Type -eq "Debug") {
Write-Debug $output
}
else {
Write-Verbose $output -Verbose
}
}
if ($OutputMode -eq "LogFile" -OR $OutputMode -eq "Console-LogFile" -OR $OutputMode -eq "LogFile-WindowsEvent" -OR $OutputMode -eq "All") {
try {
Add-Content $LogFilePath -Value $Output -ErrorAction Stop
}
catch {
exit 99001
}
}
if ($OutputMode -eq "Console-WindowsEvent" -OR $OutputMode -eq "WindowsEvent" -OR $OutputMode -eq "LogFile-WindowsEvent" -OR $OutputMode -eq "All") {
try {
New-EventLog -LogName $DefaultLogWindowsEventLog -Source $DefaultLogWindowsEventSource -ErrorAction SilentlyContinue
switch ($Type) {
"Warn" {
$EventType = "Warning"
break
}
"Error" {
$EventType = "Error"
break
}
default {
$EventType = "Information"
}
}
Write-EventLog -LogName $DefaultLogWindowsEventLog -Source $DefaultLogWindowsEventSource -EntryType $EventType -EventId 1 -Message $Output -ErrorAction Stop
}
catch {
exit 99002
}
}
}
function New-Folder {
<#
.DESCRIPTION
Creates a Folder if it's not existing.
.PARAMETER Path
Specifies the path of the new folder.
.EXAMPLE
CreateFolder "c:\temp"
.NOTES
This function creates a folder if doesn't exist.
#>
param(
[Parameter(Mandatory = $True, Position = 1)]
[string]$Path
)
# Check if the folder Exists
if (Test-Path $Path) {
Write-Log "Folder: $Path Already Exists"
}
else {
New-Item -Path $Path -type directory | Out-Null
Write-Log "Creating $Path"
}
}
function Set-RegValue {
<#
.DESCRIPTION
Set registry value and create parent key if it is not existing.
.PARAMETER Path
Registry Path
.PARAMETER Name
Name of the Value
.PARAMETER Value
Value to set
.PARAMETER Type
Type = Binary, DWord, ExpandString, MultiString, String or QWord
#>
param(
[Parameter(Mandatory = $True)]
[string]$Path,
[Parameter(Mandatory = $True)]
[string]$Name,
[Parameter(Mandatory = $True)]
[AllowEmptyString()]
[string]$Value,
[Parameter(Mandatory = $True)]
[string]$Type
)
try {
$ErrorActionPreference = 'Stop' # convert all errors to terminating errors
Start-Transaction
if (Test-Path $Path -erroraction silentlycontinue) {
}
else {
New-Item -Path $Path -Force
Write-Log "Registry key $Path created"
}
$null = New-ItemProperty -Path $Path -Name $Name -PropertyType $Type -Value $Value -Force
Write-Log "Registry Value $Path, $Name, $Type, $Value set"
Complete-Transaction
}
catch {
Undo-Transaction
Write-Log "Registry value not set $Path, $Name, $Value, $Type" -Type Error -Exception $_.Exception
}
}
#endregion
#region Dynamic Variables and Parameters
########################################################
# Try get actual ScriptName
try {
$CurrentFileNameTemp = $MyInvocation.MyCommand.Name
If ($null -eq $CurrentFileNameTemp -or $CurrentFileNameTemp -eq "") {
$CurrentFileName = "NotExecutedAsScript"
}
else {
$CurrentFileName = $CurrentFileNameTemp
}
}
catch {
$CurrentFileName = $LogFilePathScriptName
}
$LogFilePath = "$LogFilePathFolder\{0}_{1}_{2}.log" -f ($ScriptName -replace ".ps1", ''), $ScriptVersion, (Get-Date -uformat %Y%m%d%H%M)
# Try get actual ScriptPath
try {
try {
$ScriptPathTemp = Split-Path $MyInvocation.MyCommand.Path
}
catch {
}
if ([String]::IsNullOrWhiteSpace($ScriptPathTemp)) {
$ScriptPathTemp = Split-Path $MyInvocation.InvocationName
}
If ([String]::IsNullOrWhiteSpace($ScriptPathTemp)) {
$ScriptPath = $FallbackScriptPath
}
else {
$ScriptPath = $ScriptPathTemp
}
}
catch {
$ScriptPath = $FallbackScriptPath
}
#endregion
#region Initialization
########################################################
if (!(Test-Path $LogFilePathFolder))
{
New-Folder $LogFilePathFolder
}
Write-Log "Start Script $Scriptname"
Write-log -Type Info -message "Check Module"
$Module = Get-Module -Name ExchangeOnlineManagement -ListAvailable
If ($Null -eq $Module){
Write-log -Type Info -message "ExchangeOnlineManagement Module not installed"
} else {
Write-log -Type Info -message "ExchangeOnlineManagement Module found"
}
$connection = Get-AutomationConnection –Name AzureRunAsConnection
Write-log -Type Info -message "Connecting to Exchange Online ..."
Connect-ExchangeOnline –CertificateThumbprint $connection.CertificateThumbprint –AppId $connection.ApplicationID -ShowBanner:$false –Organization $tenant
Write-log -Type Info -message "Connecting to Azure AD ..."
Connect-AzureAD -TenantId $Connection.TenantId -ApplicationId $Connection.ApplicationID -CertificateThumbprint $Connection.CertificateThumbprint
#endregion
#region Main Script
########################################################
Write-log -Type Info -message "Getting users which should be able to use Remote PowerShell ..."
$UserstoIgnore = @()
foreach($ExceptionGroup in $ExceptionGroups){
$UserstoIgnore += Get-AzureADGroupMember -ObjectId $ExceptionGroup
}
foreach($ExceptionRole in $ExceptionRoles){
$role = Get-AzureADDirectoryRole | Where-Object { $ExceptionRole -eq $_.DisplayName }
$UserstoIgnore += Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId | Where-Object { $_.ObjectType -ne "ServicePrincipal" }
}
Write-log -Type Info -message "Getting all Users with PowerShell enabled ..."
$Users = Get-User | Where-Object { $_.RemotePowerShellEnabled -eq $true }
#block users except their are member of designated group
ForEach($User in $Users){
If($UserstoIgnore.UserPrincipalName -notcontains $User.UserPrincipalName){
Write-log -Type Warn -message "Disabling Remote Powershell for $($User.UserPrincipalName) ..."
Set-User -Identity $User.UserPrincipalName -RemotePowerShellEnabled $false
}
}
Write-log -Type Info -message "Getting all Users with PowerShell disabled ..."
$Users = Get-User | Where-Object { $_.RemotePowerShellEnabled -eq $false }
# enable users which are member of designated group
ForEach($User in $Users){
If($UserstoIgnore.UserPrincipalName -contains $User.UserPrincipalName){
Write-log -Type Warn -message "Enable Remote Powershell for $($User.UserPrincipalName) ..."
Set-User -Identity $User.UserPrincipalName -RemotePowerShellEnabled $true
}
}
#endregion
#region Finishing
########################################################
Write-log -Type Info -message "Disconnect form Exchange Online"
Get-PSSession | Remove-PSSession
#Disconnect from Azure AD and Exchange Online
Disconnect-AzureAD -Confirm:$false
Disconnect-ExchangeOnline -Confirm:$false
Write-log -Type Info -message "End Script $scriptname "
#endregion