-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConnection.psm1
More file actions
360 lines (306 loc) · 12.7 KB
/
Connection.psm1
File metadata and controls
360 lines (306 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
Using module .\Logging.psm1
Using module .\Scope.psm1
Using module .\Exit.psm1
Using module .\Input.psm1
Using module Microsoft.Graph.Authentication
Using module ExchangeOnlineManagement
$Script:ExchangeSessionId;
$Script:IPPSSessionId;
function Local:Invoke-NonNullParams {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[String]$FunctionName,
[Parameter(Mandatory)]
[Hashtable]$Params
)
begin { Enter-Scope; }
end { Exit-Scope; }
process {
$RemoveKeys = @();
$Params.GetEnumerator() | Where-Object { $null -eq $_.Value } | ForEach-Object {
$RemoveKeys = $RemoveKeys + $_.Key;
}
$RemoveKeys | ForEach-Object { $Params.Remove($_); }
Invoke-Debug "Invoking Expression '$FunctionName $($Params.GetEnumerator() | ForEach-Object { "-$($_.Key):$($_.Value)" })'";
& $FunctionName @Params;
};
}
$Script:Services = @{
ExchangeOnline = @{
Matchable = $True;
Context = {
if ($Script:ExchangeSessionId) {
Get-ConnectionInformation -ConnectionId:$Script:ExchangeSessionId | Select-Object -ExpandProperty UserPrincipalName;
} else {
$null;
}
};
Connect = { param($AccessToken)
Invoke-NonNullParams 'Connect-ExchangeOnline' ($PSBoundParameters + @{ ShowBanner = $False });
$Script:ExchangeSessionId = Get-ConnectionInformation | Select-Object -Last 1 -ExpandProperty ConnectionId;
};
Disconnect = { Disconnect-ExchangeOnline -Confirm:$False };
};
SecurityComplience = @{
Matchable = $True;
Context = {
if ($Script:IPPSSessionId) {
Get-ConnectionInformation -ConnectionId:$Script:IPPSSessionId | Select-Object -ExpandProperty UserPrincipalName;
} else {
$null;
}
};
Connect = {
Connect-IPPSSession -ShowBanner:$False;
$Script:IPPSSessionId = Get-ConnectionInformation | Select-Object -Last 1 -ExpandProperty ConnectionId;
};
Disconnect = { Disconnect-ExchangeOnline -Confirm:$False; };
};
Graph = @{
Matchable = $True;
Context = {
try {
Get-MgContext | Select-Object -ExpandProperty Account;
} catch {
$null;
}
};
Connect = { param($Scopes, $AccessToken)
if ($AccessToken) {
Connect-MgGraph -AccessToken:$AccessToken -NoWelcome -ContextScope Process;
$Local:ContextScopes = Get-MgContext | Select-Object -ExpandProperty Scopes;
if ($Scopes) {
Invoke-Debug "Token Scopes: $($Local:ContextScopes -join ', ')";
$Local:MissingScopes = $Scopes | Where-Object { $Local:ContextScopes -notcontains $_; };
if ($Local:MissingScopes) {
Invoke-Info "Disconnecting from Graph, missing required scope: $($Local:MissingScopes -join ', ')";
Disconnect-MgGraph;
}
}
}
try {
$Local:Context = Get-MgContext;
} catch { }
if (-not $Local:Context) {
Connect-MgGraph -Scopes:$Scopes -NoWelcome -ContextScope Process;
}
};
Disconnect = { Disconnect-MgGraph };
IsValid = {
param([String[]]$Scopes)
try {
$Local:Context = Get-MgContext;
} catch {
return $False;
}
if ($Scopes) {
Invoke-Debug 'Checking if connected to Graph with required scopes...';
Invoke-Debug "Required Scopes: $($Scopes -join ', ')";
Invoke-Debug "Current Scopes: $($Local:Context.Scopes -join ', ')";
[Bool]$Local:HasAllScopes = ($Scopes | Where-Object { $Local:Context.Scopes -notcontains $_; }).Count -eq 0;
} else {
$Local:HasAllScopes = $True;
}
$Local:HasAllScopes;
}
};
}
#startregion - Internal Functions
[Int]$Script:ERROR_CANT_DISCONNECT = Register-ExitCode -Description 'Failed to disconnect from {0}.';
function Local:Disconnect-ServiceInternal {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$Service
)
begin { Enter-Scope; }
end { Exit-Scope; }
process {
Invoke-Info "Disconnecting from $Local:Service...";
try {
if ($PSCmdlet.ShouldProcess("Disconnect from $Local:Service")) {
& $Script:Services[$Local:Service].Disconnect | Out-Null;
};
} catch {
Invoke-FailedExit -ExitCode $Script:ERROR_CANT_DISCONNECT -FormatArgs @($Local:Service) -ErrorRecord $_;
}
}
}
function Local:Connect-ServiceInternal {
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$Service,
[Parameter()]
[String[]]$Scopes,
[Parameter()]
[SecureString]$AccessToken
)
begin { Enter-Scope; }
end { Exit-Scope; }
process {
try {
if ($PSCmdlet.ShouldProcess("Connect to $Local:Service")) {
$null = & $Script:Services[$Local:Service].Connect -Scopes:$Scopes -AccessToken:$AccessToken;
}
} catch {
Invoke-FailedExit -ExitCode $Script:ERROR_COULDNT_CONNECT -FormatArgs @($Local:Service) -ErrorRecord $_;
}
}
}
function Local:Get-ServiceContext {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$Service
)
try {
& $Script:Services[$Service].Context;
} catch {
# If we can't get the context, we're not connected.
$null;
}
}
function Local:Test-HasContext {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$Service
)
$null -ne (Get-ServiceContext -Service $Service);
}
function Local:Test-IsMatchable {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$ServiceA,
[Parameter()]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$ServiceB
)
$Script:Services[$Service].Matchable -and (-not $ServiceB -or $Script:Services[$ServiceB].Matchable);
}
function Local:Test-SameContext {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$ServiceA,
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$ServiceB
)
[String]$Private:ContextA = Get-ServiceContext -Service $ServiceA;
[String]$Private:ContextB = Get-ServiceContext -Service $ServiceB;
$Private:ContextA -and $Private:ContextB -and ($Private:ContextA -eq $Private:ContextB);
}
function Local:Test-NotMatchableOrSameContext {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$ServiceA,
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String]$ServiceB
)
(Test-IsMatchable -ServiceA $ServiceA -ServiceB $ServiceB) -or (Test-SameContext -ServiceA $ServiceA -ServiceB $ServiceB);
}
#endregion
[Int]$Script:ERROR_NOT_CONNECTED = Register-ExitCode -Description 'Not connected to {0}, must be connected to continue.';
[Int]$Script:ERROR_COULDNT_CONNECT = Register-ExitCode -Description 'Failed to connect to {0}.';
[Int]$Script:ERROR_NOT_MATCHING_ACCOUNTS = Register-ExitCode -Description 'Not all services are connected with the same account, please ensure all services are connected with the same account.';
function Connect-Service(
[Parameter(Mandatory)]
[ValidateSet('ExchangeOnline', 'SecurityComplience', 'Graph')]
[String[]]$Services,
[Parameter()]
[String[]]$Scopes,
[Parameter()]
[SecureString]$AccessToken,
# If true don't prompt for confirmation if already connected.
[Switch]$DontConfirm,
# If true only check if connected, don't connect.
[Switch]$CheckOnly
) {
begin { Enter-Scope; }
end { Exit-Scope; }
process {
[String]$Local:LastService;
[String]$Local:Account;
foreach ($Local:Service in $Services) {
try {
[String]$Local:Context = Get-ServiceContext -Service $Local:Service;
} catch {
Invoke-Debug "Failed to get connection information for $Local:Service";
Format-Error -InvocationInfo $_.InvocationInfo;
}
# FIXME
# if ($Local:LastService) {
# if (-not (Test-MatchableAndSameContext -ServiceA:$Local:Service -ServiceB:$Local:LastService)) {
# Invoke-Warn 'Not all services are connected with the same account, please reconnect with the same account.';
# Disconnect-ServiceInternal -Service $Local:Service;
# }
# } else {
# }
if ($Local:LastService -and (Test-NotMatchableOrSameContext -ServiceA:$Local:Service -ServiceB:$Local:LastService)) {
Invoke-Info 'Not all services are connected with the same account, forcing disconnect...';
Disconnect-ServiceInternal -Service:$Local:Service;
} elseif ($Local:Context) {
[ScriptBlock]$Local:ValidCheck = $Script:Services[$Local:Service].IsValid;
if ($Local:ValidCheck -and -not (& $Local:ValidCheck -Scopes:$Scopes)) {
Invoke-Info "Connected to $Local:Service, but missing required scopes. Disconnecting...";
Disconnect-ServiceInternal -Service $Local:Service;
} elseif (!$DontConfirm) {
$Local:Continue = Get-UserConfirmation -Title "Already connected to $Local:Service as [$Local:Context]" -Question 'Do you want to continue?' -DefaultChoice $true;
if ($Local:Continue) {
Invoke-Verbose 'Continuing with current connection...';
$Local:Account = $Local:Context;
$Local:LastService = $Local:Service;
continue;
}
Disconnect-ServiceInternal -Service $Local:Service;
} else {
Invoke-Verbose "Already connected to $Local:Service. Skipping...";
$Local:Account = $Local:Context;
$Local:LastService = $Local:Service;
continue
}
} elseif ($CheckOnly) {
Invoke-FailedExit -ExitCode:$Script:ERROR_NOT_CONNECTED -FormatArgs @($Local:Service) -ErrorRecord $_;
}
while ($True) {
try {
if ($AccessToken) { Invoke-Info "Connecting to $Local:Service with access token..."; }
else { Invoke-Info "Connecting to $Local:Service..."; }
Invoke-Verbose "Scopes: $($Scopes -join ', ')";
Connect-ServiceInternal -Service:$Local:Service -Scopes:$Scopes -AccessToken:$AccessToken;
} catch {
Invoke-FailedExit -ExitCode $Script:ERROR_COULDNT_CONNECT -FormatArgs @($Local:Service) -ErrorRecord $_;
}
if ($Local:LastService) {
Invoke-Info 'Checking if all services are connected with the same account...';
Invoke-Info "Service A: $Local:Service";
Invoke-Info "Service B: $Local:LastService";
if ($Local:Account -and (Test-NotMatchableOrSameContext -ServiceA:$Local:Service -ServiceB:$Local:LastService)) {
Invoke-Warn 'Not all services are connected with the same account, please reconnect with the same account.';
Disconnect-ServiceInternal -Service $Local:Service;
continue;
}
}
if (-not $Local:Account -and (Test-IsMatchable $Local:Service)) {
$Local:Account = Get-ServiceContext -Service $Local:Service;
}
Invoke-Info "Connected to $Local:Service as [$Local:Account].";
break;
};
}
}
}
Export-ModuleMember -Function Connect-Service;