-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy patho365Utils.js
631 lines (546 loc) · 18.9 KB
/
o365Utils.js
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
/**
* getO365PSInitCommands()
*
* Returns an array of Powershell initialization commands suitable
* for setting up shells spawned with StatefulProcessCommandProxy
* to be able to establish a remote PSSession with o365
*
* @see https://github.com/bitsofinfo/powershell-credential-encryption-tools
*
* This function takes the full path to:
* - decryptUtil.ps1 from the project above
* - path the encrypted credentials file generated with decryptUtil.ps1
* - path to the secret key needed to decrypt the credentials
*
* In addition there are parameter to define the PSSessionOption timeouts
*
* Note this is just an example (which works) however you may want to
* replace this with your own set of init command tailored to your specific
* use-case
*
* @see the getO365PSDestroyCommands() below for the corresponding cleanup
* commands for these init commands
*/
module.exports.getO365PSInitCommands = function (pathToDecryptUtilScript,
pathToCredsFile,
pathToKeyFile,
openTimeout,
operationTimeout,
idleTimeout) {
return [
// #0 Encoding UTF8
'chcp 65001',
'$OutputEncoding = [System.Text.Encoding]::GetEncoding(65001)',
// #1 import some basics
'Import-Module MSOnline',
// #2 source the decrypt utils script
// https://github.com/bitsofinfo/powershell-credential-encryption-tools/blob/master/decryptUtil.ps1
('. ' + pathToDecryptUtilScript),
// #3 invoke decrypt2PSCredential to get the PSCredential object
// this function is provided by the sourced file above
('$PSCredential = decrypt2PSCredential ' + pathToCredsFile + ' ' + pathToKeyFile),
// #4+ establish the session to o365
('$sessionOpt = New-PSSessionOption -OpenTimeout ' + openTimeout + ' -OperationTimeout ' + operationTimeout + ' -IdleTimeout ' + idleTimeout),
'$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $PSCredential -Authentication Basic -AllowRedirection -SessionOption $sessionOpt',
// #5 import the relevant cmdlets (TODO: make this configurable)
'Import-PSSession $session -CommandName *DistributionGroup* -AllowClobber',
'Import-PSSession $session -CommandName *Contact* -AllowClobber',
// #6 connect to azure as well
'Connect-MsolService -Credential $PSCredential',
// #7 cleanup
'Remove-Variable -Force -ErrorAction SilentlyContinue $PSCredential'
];
};
/**
* Destroy commands that correspond to the session
* established w/ the initCommands above
*/
module.exports.getO365PSDestroyCommands = function () {
return [
'Get-PSSession | Remove-PSSession -ErrorAction SilentlyContinue',
'Remove-PSSession -Session $session',
'Remove-Module MsOnline'
];
};
/**
* getO365PSKeyInitCommands()
*
* Returns an array of Powershell initialization commands suitable
* for setting up shells spawned with StatefulProcessCommandProxy
* to be able to establish a remote PSSession with o365
*
* @see https://github.com/bitsofinfo/powershell-credential-encryption-tools
* @see https://docs.microsoft.com/en-us/powershell/module/exchange/connect-exchangeonline?view=exchange-ps
* @see https://adamtheautomator.com/exchange-online-powershell-mfa/#Authenticating_Using_Local_PFX_Certificate
*
* This function takes the full path to:
* - decryptUtil.ps1 from the project above
* - path the encrypted credentials file generated with decryptUtil.ps1
* - path to the secret key needed to decrypt the credentials
* - path to the certificate configured for Exchange app authentication
* - certificate password
* - application id created for the Exchange app integration
* - tenant/organizationId for the Exchange
* - comma separatged list of commands to import, widcard supported.
* Everything is imported if empty
*
* In addition there are parameter to define the PSSessionOption timeouts
*
* Note this is just an example (which works) however you may want to
* replace this with your own set of init command tailored to your specific
* use-case
*
* @see the getO365PSKeyDestroyCommandsgetO365PSKeyDestroyCommands() below
for the corresponding cleanup
* commands for these init commands
*/
module.exports.getO365PSKeyInitCommands = function (pathToDecryptUtilScript,
pathToCredsFile,
pathToKeyFile,
pathToAuthCertificate,
authCertificatePassword,
applicationId,
organizationId,
openTimeout,
operationTimeout,
idleTimeout,
commandsToImport = '') {
let psCommandsToImport = '';
if (commandsToImport != '') {
psCommandsToImport = '-CommandName ' + commandsToImport;
}
return [
// #0 Encoding UTF8
'chcp 65001',
'$OutputEncoding = [System.Text.Encoding]::GetEncoding(65001)',
// #1 import some basics
'Import-Module MSOnline',
'Import-Module ExchangeOnlineManagement',
// #2 source the decrypt utils script
// https://github.com/bitsofinfo/powershell-credential-encryption-tools/blob/master/decryptUtil.ps1
('. ' + pathToDecryptUtilScript),
// #3 invoke decrypt2PSCredential to get the PSCredential object
// this function is provided by the sourced file above
('$PSCredential = decrypt2PSCredential ' + pathToCredsFile + ' ' + pathToKeyFile),
// #4 connect to azure as well
'Connect-MsolService -Credential $PSCredential',
// #5 get session options, certificate file and secure password
('$sessionOpt = New-PSSessionOption -OpenTimeout ' + openTimeout + ' -OperationTimeout ' + operationTimeout + ' -IdleTimeout ' + idleTimeout),
'$CertificateFilePath = (Resolve-Path "' + pathToAuthCertificate + '").Path',
'$CertificatePassword = (ConvertTo-SecureString -String "' + authCertificatePassword + '" -AsPlainText -Force)',
// #6 connect to exchange
'Connect-ExchangeOnline -CertificateFilePath $CertificateFilePath -CertificatePassword $CertificatePassword -AppID ' + applicationId + ' -Organization ' + organizationId + ' ' + psCommandsToImport,
// #7 cleanup
'Remove-Variable -Force -ErrorAction SilentlyContinue $PSCredential'
];
};
/**
* Destroy commands that correspond to the session
* established w/ the KeyinitCommands above
*/
module.exports.getO365PSKeyDestroyCommands = function () {
return [
'Get-PSSession | Remove-PSSession -ErrorAction SilentlyContinue',
'Remove-Module MsOnline',
'Remove-Module ExchangeOnlineManagement',
];
};
/**
* getO365PSKeyInitCommands()
*
* Returns an array of Powershell initialization commands suitable
* for setting up shells spawned with StatefulProcessCommandProxy
* to be able to establish a remote PSSession with o365
*
* @see https://github.com/bitsofinfo/powershell-credential-encryption-tools
* @see https://docs.microsoft.com/en-us/powershell/module/exchange/connect-exchangeonline?view=exchange-ps
* @see https://adamtheautomator.com/exchange-online-powershell-mfa/#Authenticating_Using_Certificate_Thumbprint
*
* This function takes the full path to:
* - decryptUtil.ps1 from the project above
* - path the encrypted credentials file generated with decryptUtil.ps1
* - path to the secret key needed to decrypt the credentials
* - certificate thumbprint configured for Exchange app authentication
* - application id created for the Exchange app integration
* - tenant/organizationId for the Exchange
* - comma separatged list of commands to import, widcard supported.
* Everything is imported if empty
*
* In addition there are parameter to define the PSSessionOption timeouts
*
* Note this is just an example (which works) however you may want to
* replace this with your own set of init command tailored to your specific
* use-case
*
* @see the getO365PSKeyDestroyCommandsgetO365PSKeyDestroyCommands() below
for the corresponding cleanup
* commands for these init commands
*/
module.exports.getO365PSThumbprintInitCommands = function (pathToDecryptUtilScript,
pathToCredsFile,
pathToKeyFile,
certificateThumbPrint,
applicationId,
organizationId,
openTimeout,
operationTimeout,
idleTimeout,
commandsToImport = '') {
let psCommandsToImport = '';
if (commandsToImport != '') {
psCommandsToImport = '-CommandName ' + commandsToImport;
}
return [
// #0 Encoding UTF8
'chcp 65001',
'$OutputEncoding = [System.Text.Encoding]::GetEncoding(65001)',
// #1 import some basics
'Import-Module MSOnline',
'Import-Module ExchangeOnlineManagement',
// #2 source the decrypt utils script
// https://github.com/bitsofinfo/powershell-credential-encryption-tools/blob/master/decryptUtil.ps1
('. ' + pathToDecryptUtilScript),
// #3 invoke decrypt2PSCredential to get the PSCredential object
// this function is provided by the sourced file above
('$PSCredential = decrypt2PSCredential ' + pathToCredsFile + ' ' + pathToKeyFile),
// #4 connect to azure as well
'Connect-MsolService -Credential $PSCredential',
// #5 get session options
('$sessionOpt = New-PSSessionOption -OpenTimeout ' + openTimeout + ' -OperationTimeout ' + operationTimeout + ' -IdleTimeout ' + idleTimeout),
// #6 connect to exchange
'Connect-ExchangeOnline -CertificateThumbPrint ' + certificateThumbPrint + ' -AppID ' + applicationId + ' -Organization ' + organizationId + ' ' + psCommandsToImport,
// #7 cleanup
'Remove-Variable -Force -ErrorAction SilentlyContinue $PSCredential'
];
};
/**
* Destroy commands that correspond to the session
* established w/ the KeyinitCommands above
*/
module.exports.getO365PSThumbprintDestroyCommands = function () {
return [
'Get-PSSession | Remove-PSSession -ErrorAction SilentlyContinue',
'Remove-Module MsOnline',
'Remove-Module ExchangeOnlineManagement',
];
};
/**
* Some example blacklisted commands
*/
module.exports.getO365BlacklistedCommands = function () {
return [{
'regex': '.*Invoke-Expression.*',
'flags': 'i'
},
{
'regex': '.*ScriptBlock.*',
'flags': 'i'
},
{
'regex': '.*Get-Acl.*',
'flags': 'i'
},
{
'regex': '.*Set-Acl.*',
'flags': 'i'
},
{
'regex': '.*Get-Content.*',
'flags': 'i'
},
{
'regex': '.*-History.*',
'flags': 'i'
},
{
'regex': '.*Out-File.*',
'flags': 'i'
}
];
};
/**
* Configuration auto invalidation, checking PSSession availability
* @param checkIntervalMS
*/
module.exports.getO365AutoInvalidationConfig = function (checkIntervalMS) {
return {
'checkIntervalMS': checkIntervalMS,
'commands': [
// no remote pssession established? invalid!
{
'command': 'Get-PSSession',
'regexes': {
'stdout': [{
'regex': '.*Opened.*',
'flags': 'i',
'invalidOn': 'noMatch'
}]
}
}
]
};
};
/**
* Defines a registry of Powershell commands
* that can be injected into the PSCommandService
* instance.
*
* Note these are just some example configurations specifically for a few
* o365 functions and limited arguments for each, (they work) however you may want to
* replace this with your own set of init command tailored to your specific
* use-case
*/
var o365CommandRegistry = {
/*******************************
*
* o365 Powershell Command registry
*
* argument properties (optional):
* - quoted: true|false, default true
* - valued: true|false, default true
* - default: optional default value (only if valued..)
*
* return properties:
* type: none, text or json are valid values
*
********************************/
/*******************************
* MsolUser
********************************/
'getMsolUser': {
'command': 'Get-MsolUser {{{arguments}}} | ConvertTo-Json',
'arguments': {
'UserPrincipalName': {}
},
'return': {
type: 'json'
}
},
'newMsolUser': {
'command': 'New-MsolUser {{{arguments}}} | ConvertTo-Json',
'arguments': {
'DisplayName': {},
'UserPrincipalName': {}
},
'return': {
type: 'json'
}
},
'removeMsolUser': {
'command': 'Remove-MsolUser -Force {{{arguments}}} ',
'arguments': {
'UserPrincipalName': {}
},
'return': {
type: 'none'
}
},
/*******************************
* DistributionGroups
********************************/
'getDistributionGroup': {
'command': 'Get-DistributionGroup {{{arguments}}} | ConvertTo-Json',
'arguments': {
'Identity': {}
},
'return': {
type: 'json'
}
},
'newDistributionGroup': {
'command': 'New-DistributionGroup -Confirm:$False {{{arguments}}} | ConvertTo-Json',
'arguments': {
'Name': {},
'DisplayName': {},
'Alias': {},
'PrimarySmtpAddress': {},
'Type': {
'quoted': false,
'default': 'Security'
},
'ManagedBy': {},
'Members': {}, // specifying members on create does not seem to work
'ModerationEnabled': {
'default': '0',
'quoted': false
},
'MemberDepartRestriction': {
'default': 'Closed'
},
'MemberJoinRestriction': {
'default': 'Closed'
},
'SendModerationNotifications': {
'default': 'Never',
'quoted': false
},
},
'return': {
type: 'json'
}
},
'setDistributionGroup': {
'command': 'Set-DistributionGroup -Confirm:$False {{{arguments}}}',
'arguments': {
'Identity': {},
'Name': {},
'DisplayName': {},
'Alias': {},
'PrimarySmtpAddress': {},
'ManagedBy': {},
'Members': {},
'MailTip': {},
'ModerationEnabled': {
'default': '0',
'quoted': false
},
'MemberDepartRestriction': {
'default': 'Closed'
},
'MemberJoinRestriction': {
'default': 'Closed'
},
'SendModerationNotifications': {
'default': 'Never',
'quoted': false
},
'BypassSecurityGroupManagerCheck': {
'valued': false
}
},
'return': {
type: 'none'
}
},
'removeDistributionGroup': {
'command': 'Remove-DistributionGroup {{{arguments}}} -Confirm:$false',
'arguments': {
'Identity': {},
// needed if invoking as global admin who is not explicitly a group admin.. stupid... yes.
'BypassSecurityGroupManagerCheck': {
'valued': false
}
},
'return': {
type: 'none'
}
},
'getDistributionGroupMember': {
'command': 'Get-DistributionGroupMember {{{arguments}}} -ResultSize Unlimited | ConvertTo-Json',
'arguments': {
'Identity': {}
},
'return': {
type: 'json'
}
},
'addDistributionGroupMember': {
'command': 'Add-DistributionGroupMember {{{arguments}}}',
'arguments': {
'Identity': {},
'Member': {},
// needed if invoking as global admin who is not explicitly a group admin.. stupid... yes.
'BypassSecurityGroupManagerCheck': {
'valued': false
}
},
'return': {
type: 'none'
}
},
// members specified w/ this are a full overwrite..
'updateDistributionGroupMembers': {
'command': 'Update-DistributionGroupMember -Confirm:$false {{{arguments}}}',
'arguments': {
'Identity': {},
'Members': {},
// needed if invoking as global admin who is not explicitly a group admin.. stupid... yes.
'BypassSecurityGroupManagerCheck': {
'valued': false
}
},
'return': {
type: 'none'
}
},
'removeDistributionGroupMember': {
'command': 'Remove-DistributionGroupMember {{{arguments}}} -Confirm:$false',
'arguments': {
'Identity': {},
'Member': {},
// needed if invoking as global admin who is not explicitly a group admin.. stupid... yes.
'BypassSecurityGroupManagerCheck': {
'valued': false
}
},
'return': {
type: 'none'
}
},
/*******************************
* MailContacts
********************************/
'getMailContact': {
'command': 'Get-MailContact {{{arguments}}} | ConvertTo-Json',
'arguments': {
'Identity': {}
},
'return': {
type: 'json'
}
},
'newMailContact': {
'command': 'New-MailContact -Confirm:$False {{{arguments}}} | ConvertTo-Json',
'arguments': {
'Name': {},
'ExternalEmailAddress': {}
},
'return': {
type: 'json'
}
},
'setMailContact': {
'command': 'Set-MailContact -Confirm:$False {{{arguments}}}',
'arguments': {
'Identity': {},
'Name': {},
'DisplayName': {},
'ExternalEmailAddress': {}
},
'return': {
type: 'none'
}
},
'removeMailContact': {
'command': 'Remove-MailContact {{{arguments}}} -Confirm:$false',
'arguments': {
'Identity': {}
},
'return': {
type: 'none'
}
},
getStatus: {
command: 'Get-ConnectionInformation | ConvertTo-Json',
return: {
type: 'json'
}
},
};
module.exports.o365CommandRegistry = o365CommandRegistry;
/**
* Some example whitelisted commands
* (only permit) what is in the registry
*/
module.exports.getO365WhitelistedCommands = function () {
var whitelist = [];
for (var cmdName in o365CommandRegistry) {
var config = o365CommandRegistry[cmdName];
var commandStart = config.command.substring(0, config.command.indexOf(' ')).trim();
whitelist.push({
'regex': '^' + commandStart + '\\s+.*',
'flags': 'i'
});
}
return whitelist;
};