-
Notifications
You must be signed in to change notification settings - Fork 1
/
ssh-ad-pubkey.ps1
608 lines (493 loc) · 14.5 KB
/
ssh-ad-pubkey.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
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
<#
.SYNOPSIS
Manage Ssh Public Key in Active Directory.
.DESCRIPTION
Add or remove the SSH Public Key central stored in Active Directory.
The SSH Public Key can be in a File or Console Input.
Listing of the SSH Public Key in a file or in Active Directory for an User
Further the AD can be checked for the desired AD schema extentions.
.NOTES
You need the permission to change the SSH Public Key in AD.
.EXAMPLE
PS C:\>ssh-ad-pubkey -list
List the SSH Public Key(s) for the current user.
.EXAMPLE
PS C:\>ssh-ad-pubkey -list anna
PS C:\>ssh-ad-pubkey -list -sam anna
PS C:\>ssh-ad-pubkey -list -user anna
List the SSH Public Key(s) for the user with SamAccountName Anna.
.EXAMPLE
PS C:\>ssh-ad-pubkey -list -filepath C:\Users\anna\.ssh\id_ed25519.pub
List the SSH Public Key in File
.EXAMPLE
PS C:\>ssh-ad-pubkey -add -filepath C:\Users\anna\.ssh\id_ed25519.pub
Add SSH Public Key in File to AD for current user
PS C:\>ssh-ad-pubkey -add -filepath C:\common\id_ed25519.pub -sam otto
Add SSH Public Key in File to AD for user otto
.EXAMPLE
PS C:\>ssh-ad-pubkey -add -sshpubkey "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC/GnZYLGmAoC95 anna@workshop@windev1"
Add SSH Public Key from Console to AD for current user
PS C:\>ssh-ad-pubkey -add -sshpubkey "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICgixWPrskbEG42 otto@workshop@windev1" -sam otto
Add SSH Public Key from Console to AD for user otto
.EXAMPLE
PS C:\>ssh-ad-pubkey -remove -filepath C:\Users\anna\.ssh\id_ed25519.pub
Remove SSH Public Key in File from AD for current user
PS C:\>ssh-ad-pubkey -remove -filepath C:\common\id_ed25519.pub -sam otto
Remove SSH Public Key in File from AD for user otto
.EXAMPLE
PS C:\>ssh-ad-pubkey -remove -sshpubkey "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIC/GnZYLGmAoC95 anna@workshop@windev1"
Remove SSH Public Key from Console from AD for current user
PS C:\>ssh-ad-pubkey -remove -sshpubkey "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICgixWPrskbEG42 otto@workshop@windev1" -sam otto
Remove SSH Public Key from Console from AD for user otto
.EXAMPLE
PS C:\>ssh-ad-pubkey -clear
Clear all SSH Public Keys from AD for current user
PS C:\>ssh-ad-pubkey -clear -sam otto
Clear all SSH Public Key from AD for user otto
.EXAMPLE
PS C:\> ssh-add-pubkey -check
Check the AD schema for the required extentions for OpenSSH
.EXAMPLE
PS c:\> import-csv .\userlist.csv -Delimiter ',' | % {.\ssh-ad-pubkey.ps1 -list:$true $_.sam}
List the SSH Public Key stored in Active Directory from all Users defined in a comma separated file.
#>
[CmdletBinding(DefaultParameterSetName = 'noaction')]
Param(
[Parameter(ParameterSetName='listfromfile', Mandatory=$true,position=0)]
[Parameter(ParameterSetName='listad', Mandatory=$true, position=0)]
[switch] $list,
[Parameter(ParameterSetName='addstring', Mandatory=$true,position=0)]
[Parameter(ParameterSetName='addfromfile', Mandatory=$true,position=0)]
[switch] $add,
[Parameter(ParameterSetName='removestring', Mandatory=$true,position=0)]
[Parameter(ParameterSetName='removefromfile', Mandatory=$true,position=0)]
[switch] $remove,
[Parameter(ParameterSetName='clear', Mandatory=$true,position=0)]
[switch] $clear,
[Parameter(ParameterSetName='check', Mandatory=$true,position=0)]
[switch] $check,
[Parameter(ParameterSetName='listfromfile', Mandatory=$true)]
[Parameter(ParameterSetName='addfromfile', Mandatory=$true,position=1)]
[Parameter(ParameterSetName='removefromfile', Mandatory=$true,position=1)]
[ValidateNotNullOrEmpty()]
[string] $filepath,
[Parameter(ParameterSetName='addstring', Mandatory=$true,position=1)]
[Parameter(ParameterSetName='removestring', Mandatory=$true,position=1)]
[ValidateNotNullOrEmpty()]
[string] $sshpubkey,
[Parameter(ParameterSetName='listad', Mandatory= $false, position=1)]
[Parameter(ParameterSetName='clear', Mandatory= $false, position=1)]
[Parameter(ParameterSetName='addfromfile', Mandatory=$false,position=2)]
[Parameter(ParameterSetName='removefromfile', Mandatory=$false,position=2)]
[Parameter(ParameterSetName='addstring', Mandatory=$false,position=2)]
[Parameter(ParameterSetName='removestring', Mandatory=$false,position=2)]
[alias("user")]
[ValidateNotNullOrEmpty()]
[String]$sam
)
Set-StrictMode -Version 2.0
[string] $action = "list"
if ($add)
{
$action = "add"
}
elseif ($list)
{
$action = "list"
}
elseif ($remove)
{
$action = "remove"
}
elseif ($check)
{
$action = "check"
}
elseif ($clear)
{
$action = "clear"
}
else
{
write-host "Please use ssh-ad-pubkey one of the following switches:`n-add -list -remove -clear -check`n"
& $MyInvocation.MyCommand.Definition -?
exit
}
# Load the Assemblies for DirectoryServices
# Unfortunately Active Directory Module is currently
# not working with PowerShell Core 6.x
# Find-Module -Name PSCoreWindowsCompat
# Install-Module -Name PSCoreWindowsCompat -Repository PSGallery -Verbose -Force
if ($PSVersionTable.PSEdition -eq "Core")
{
Import-Module PSCoreWindowsCompat
}
else
{
Add-Type -AssemblyName "System.DirectoryServices.AccountManagement"
}
function find-ADProperty
{
Param(
[ValidateNotNullOrEmpty()]
[string] $PropertyName
)
$found = $false
try
{
$RootDSE = [System.DirectoryServices.DirectoryEntry]([System.DirectoryServices.DirectoryEntry]"LDAP://RootDSE")
# Retrieve the Schema naming context, the distinguished name of the Schema container in AD.
$schemaNC = $rootDSE.Properties["schemaNamingContext"][0]
# Create DirectorySearcher object
$ADSearcher = New-Object DirectoryServices.DirectorySearcher
# Filter on the LDAPDisplayName attribute
$ADSearcher.Filter = "(&(LDAPDisplayName=$PropertyName))"
# Search in the Schema
$ADSearcher.SearchRoot = "LDAP://$schemaNC"
# Return only one result
$schemaObj = $ADSearcher.FindOne()
if ($schemaObj)
{
$found = $true
}
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Warning "Something goes wrong"
Write-Warning "$ErrorMessage"
$found = $false
}
return $found
}
function find-CustomObjectinUser
{
$found = $false
try
{
$RootDSE = [System.DirectoryServices.DirectoryEntry]([System.DirectoryServices.DirectoryEntry]"LDAP://RootDSE")
# Retrieve the Schema naming context, the distinguished name of the Schema container in AD.
$schemaNC = $rootDSE.Properties["schemaNamingContext"][0]
# Create DirectorySearcher object
$ADSearcher = New-Object DirectoryServices.DirectorySearcher
# Filter on the LDAPDisplayName attribute
$ADSearcher.Filter = "(&(LDAPDisplayName=user))"
# Search in the Schema
$ADSearcher.SearchRoot = "LDAP://$schemaNC"
# Return only one result
$schemaObj = $ADSearcher.FindOne()
if ($schemaObj)
{
$found = (($schemaObj).Properties.auxiliaryclass)-contains "ldappublickey"
}
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Warning "Something goes wrong"
Write-Warning "$ErrorMessage"
$found = $false
}
return $found
}
function test-CustomizedSchema
{
$a = find-ADProperty "sshPublicKey"
$b = find-ADProperty "ldapPublicKey"
$c = find-CustomObjectinUser
if ( $a -and $b -and $c)
{
write-Host "Customized AD Schema is OK!"
}
else
{
write-Host "Missing AD Schema Extensions!"
if (!$a)
{
"Attribute sshPublicKey is missing!"
}
if (!$b)
{
"Class ldapPublicKey is missing!"
}
if (!$c)
{
"Auxillary class ldapPublicKey is not in user object!"
}
}
}
function show-ADSSHPublicKey
{
Param([System.DirectoryServices.AccountManagement.UserPrincipal] $u)
try
{
$k = ($u.GetUnderlyingObject()).Properties
[bool] $x = $k.Contains("SShPublicKey")
# Entry exists
if ($x)
{
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
$k = ($u.GetUnderlyingObject()).Properties.sshPublicKey
$n = $k.count
write-host "$($u.samAccountName) has $n SSH Public Key(s) in AD:"
for ($i=0; $i -lt $n ; $i++)
{
write-host "$($Utf8NoBomEncoding.GetString($k[$i]))"
}
}
else
{
write-host "$($u.samAccountName) has no SSH Public Key in AD!!!"
}
write-host
}
Catch [System.UnauthorizedAccessException]
{
$ErrorMessage = $_.Exception.Message
Write-Warning "No Access to Object $u"
Write-Warning "$ErrorMessage"
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Warning "Something goes wrong"
Write-Warning "$ErrorMessage"
}
}
function get-ADSSHPublicKey
{
Param([System.DirectoryServices.AccountManagement.UserPrincipal] $u)
try
{
$k = ($u.GetUnderlyingObject()).Properties
[bool] $x = $k.Contains("SShPublicKey")
$s = New-Object System.Collections.Generic.List[String]
# Entry exists
if ($x)
{
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
$k = ($u.GetUnderlyingObject()).Properties.sshPublicKey
$n = $k.count
for ($i=0; $i -lt $n ; $i++)
{
$s.add($Utf8NoBomEncoding.GetString($k[$i]))
}
}
else
{
$s= $null
}
return $s
}
Catch [System.UnauthorizedAccessException]
{
$ErrorMessage = $_.Exception.Message
Write-Warning "No Access to Object $u"
Write-Warning "$ErrorMessage"
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Warning "Something goes wrong"
Write-Warning "$ErrorMessage"
}
}
function get-FileSSHPublicKey
{
Param( [ValidateNotNullOrEmpty()]
[string] $sshpkpath)
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
try
{
if([System.IO.File]::Exists($sshpkpath))
{
$f = [System.IO.File]::ReadAllLines($sshpkpath, $Utf8NoBomEncoding)
return $f
}
else
{
write-warning "Path/file $sshpkpath not found !!!"
return $null
}
}
Catch [System.UnauthorizedAccessException]
{
$ErrorMessage = $_.Exception.Message
Write-Warning "No Access to Object $sshpkpath"
Write-Warning "$ErrorMessage"
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Warning "Something goes wrong"
Write-Warning "$ErrorMessage"
}
}
function show-FileSSHPublicKey
{
Param( [ValidateNotNullOrEmpty()]
[string] $sshpkpath)
$f = get-FileSSHPublicKey $sshpkpath
if ($f)
{
write-Host "Contents of $sshpkpath"
write-host "$f"
}
}
function update-ADSSHPublicKey
{
Param([System.DirectoryServices.AccountManagement.UserPrincipal] $u,
[ValidateNotNullOrEmpty()]
[string] $sshpk,
[ValidateSet("add","remove")]
[string] $act)
$Utf8NoBomEncoding = New-Object System.Text.UTF8Encoding $False
[byte[]] $octets = $Utf8NoBomEncoding.GetBytes($sshpk)
try
{
if ($act -eq "add")
{
($u.GetUnderlyingObject()).Properties["sshpublickey"].Add($octets) | Out-Null
}
else
{
($u.GetUnderlyingObject()).Properties["sshpublickey"].Remove($octets)
}
$u.Save()
}
Catch [System.UnauthorizedAccessException]
{
$ErrorMessage = $_.Exception.Message
Write-Warning "No Access to Object $($u.samaccountname)"
Write-Warning "$ErrorMessage"
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Warning "Something goes wrong"
Write-Warning "$ErrorMessage"
}
}
function clear-ADSSHPublicKey
{
Param([System.DirectoryServices.AccountManagement.UserPrincipal] $u)
try
{
($u.GetUnderlyingObject()).Properties["sshpublickey"].Clear()
$u.Save()
}
Catch [System.UnauthorizedAccessException]
{
$ErrorMessage = $_.Exception.Message
Write-Warning "No Access to Object $($u.samaccountname)"
Write-Warning "$ErrorMessage"
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Warning "Something goes wrong"
Write-Warning "$ErrorMessage"
}
}
function get-UserFromAD
{
[System.DirectoryServices.AccountManagement.UserPrincipal] $user = $null
try
{
if (!$sam)
{
$sam = ([System.DirectoryServices.AccountManagement.UserPrincipal]::Current).samaccountname
}
$ContextType = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$Context = New-Object -TypeName System.DirectoryServices.AccountManagement.PrincipalContext -ArgumentList $ContextType
$user = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($Context,$sam)
}
catch
{
$ErrorMessage = $_.Exception.Message
Write-Warning "Something goes wrong"
Write-Warning "$ErrorMessage"
$user = $null
}
return $user
}
function show-sshkeys
{
if ($filepath)
{
show-FileSSHPublicKey $filepath
}
else
{
$user = get-UserFromAD
if ($user)
{
show-ADSSHPublicKey $user
}
else
{
write-warning "User $sam not found in AD"
}
}
}
function update-sshkey
{
$err = $false
# first get ssh keys from file or console
if ($filepath)
{
$f=get-FileSSHPublicKey $filepath
if (!$f)
{
$err=$true
}
}
elseif ($sshpubkey)
{
$f = $sshpubkey.Trim()
if ([string]::IsNullOrEmpty($f))
{
$err=$true
}
}
else
{
$err =$true
}
# 2. Step
# Get User
if (!$err)
{
$user = get-UserFromAD
if ($user)
{
update-ADSSHPublicKey $user $f $action
}
else
{
write-warning "User $sam not found in AD"
}
}
}
function remove-sshkeys
{
# Get User
$user = get-UserFromAD
if ($user)
{
clear-ADSSHPublicKey $user
}
else
{
write-warning "User $sam not found in AD"
}
}
# Main
switch ($action)
{
"list" { show-sshkeys}
"add" { update-sshkey}
"remove" { update-sshkey}
"clear" { remove-sshkeys}
"check" { test-CustomizedSchema }
}