-
Notifications
You must be signed in to change notification settings - Fork 3
/
SMBSecurity.psm1
3027 lines (2514 loc) · 98.1 KB
/
SMBSecurity.psm1
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -RunAsAdministrator
#Requires -Version 5.1
using namespace System.Collections
using namespace System.Collections.Generic
using namespace System.Security.Principal
#using namespace System.Security.Principal.NTAccount
#using namespace System.Security.Principal.SecurityIdentifier
<#
TO-DO:
#>
<#
GENERAL MODULE GUIDELINES AND INFORMATION:
- Err on the side of caution. When in doubt, fail the command and output an error.
- Use ArrayLists for collections. The Classes and Functions will expect them, and it helps a little with performance.
- May switch to [System.Collections.Generic.List[]] in the next version.
- Classes and enums are stored in .\bin\class.ps1 and are used to enforce data structures for the module.
- Classes won't use an enum unless it's in the same file.
- Hashtables are stored in .\bin\hashtable.ps1.
- Enums and hashtables are used for quick lookups of static data. Some consolidation of the two might be needed...
- sddl_flags.json is a constructed list of ACE values based on crawling the SDDL docs: https://docs.microsoft.com/en-us/windows/win32/secauthz/security-descriptor-definition-language
- This currently doesn't do anything.
- Use Write-Verbose and Write-Debug to output optional troubleshooting information.
- Add the function name to output.
- Example:
Write-[Verbose|Debug] "Function-Name - Comment about what's going on. What's in variable: $variable"
- Use Verbose for output that is generally good for troubleshooting.
- Use Debug for loops and when the information only helps with deep troubleshooting.
- Document your code. The documentation can be in the form of a comment or Write-[Verbose|Debug], but make sure you tell others what's going on to ease debugging.
- Do not use the Global variable scope! Local and Script scopes only!
- Export only the functions that are required to perform SMB security work.
- Use "$null = <command>" to prevent unwanted output to the console. Do not use Out-Null whenever possible. Example, when adding an element to an ArrayList: $null = $results.Add(...)
- Test your inputs and outputs! Try-Catch[-Finally] is your friend: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_try_catch_finally
- Avoid using "throw", use 'return (Write-Error "<error>" -EA Stop)' instead. Throw does some weird stuff with classes and layered commands.
- Functions are sorted by verb (Get, Set, Add, New, etc.) regions.
- Use approved PowerShell verbs only: https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands?view=powershell-7.2
#>
################
## LOAD FILES ##
################
# get the module path
[string]$Script:SMBSecModulePath = (Split-Path -Path (Get-Variable -Name myinvocation -Scope script).value.Mycommand.Definition -Parent)
Write-Verbose "ModulePath: $SMBSecModulePath"
Write-Verbose "Importing SDDL flags."
# this seems to be the only consistent way to import the JSON file
try
{
$script:SMBSEC_ACE_TYPE = Get-Content "$Script:SMBSecModulePath\bin\sddl_flags.json" -EA Stop | ConvertFrom-Json
}
catch
{
return (Write-Error "Failed to import the SDDL flags file ($Script:SMBSecModulePath\bin\sddl_flags.json): $_ " -EA Stop)
}
# load files in bin - doing this plus ScriptsToProcess in the module file seems to consistently load all the functions, classes, and enums.
# remove either this or ScriptsToProcess and things start to break, so do them both.
[array]$binFiles = Get-ChildItem "$SMBSecModulePath\bin\*.ps1" -EA SilentlyContinue
foreach ($file in $binFiles)
{
try
{
Write-Debug "Loading $($file.FullName)"
. $file.FullName
}
catch
{
return ( Write-Error "Failed to load file $($file.FullName): $_" -EA Stop )
}
}
###############
## CONSTANTS ##
###############
### Do not use the Global variable scope!
# path to the DefaultSecurity key, where the SMB security details are stored
$script:SMBSecRegPath = "HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\DefaultSecurity"
# location of the auto-backup path (AUTO mode path)
$script:BackupPath = "$ENV:LOCALAPPDATA\SMBSecurity"
# selected backups - this is a generic list on purpose, because ArrayList doesn't work right with the UI for some reason
$script:restoreFileSelection = [List[PSCustomObject]]::new()
# the default share permissions
$Script:SrvsvcDefaultShareInfoSDDL = 'O:SYG:SYD:(A;;0x1200a9;;;WD)'
<#
PURPOSE:
EXPORTED:
#>
###########
## GET ##
###########
#region
<#
PURPOSE: Queries the registry and returns an array containing the current SDDL values.
EXPORTED: YES
#>
function Get-SMBSecurity
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$false)]
[Alias("SDName","Name")]
[string]
$SecurityDescriptorName
)
Write-Verbose "Get-SMBSecurity - Begin"
if (-NOT [string]::IsNullOrEmpty($SecurityDescriptorName) -and $SecurityDescriptorName -notin ([SMBSecurityDescriptor].GetEnumNames()))
{
Write-Error "'$SecurityDescriptorName' is an invalid SecurityDescriptor. The valid names are $((Get-SMBSecurityDescriptorName) -join ', ')"
return $null
}
# stores the enumerated reqults in an ArrayList for performance and consistency
$results = New-Object System.Collections.ArrayList
Write-Verbose "Get-SMBSecurity - Converting binary reg values."
if (-NOT [string]::IsNullOrEmpty($SecurityDescriptorName))
{
Write-Verbose "Get-SMBSecurity - Single descriptor."
Write-Debug "Get-SMBSecurity - Processing: $SecurityDescriptorName"
$null = $results.Add((Read-SMBSecurityDescriptor $SecurityDescriptorName))
}
else
{
Write-Verbose "Get-SMBSecurity - Multiple descriptors."
foreach ($name in [SMBSecurityDescriptor].GetEnumNames())
{
Write-Debug "Get-SMBSecurity - Processing: $SecurityDescriptorName"
$null = $results.Add((Read-SMBSecurityDescriptor $name))
}
}
Write-Verbose "Get-SMBSecurity - Returning $($results.Count) objects:`n`n$($results | Format-Table Name, Owner, RawSDDL | Out-String)`n"
Write-Verbose "Get-SMBSecurity - End"
return $results
}
<#
PURPOSE: Matches an SD value to a readable description
EXPORTED: YES
#>
function Get-SMBSecurityDescription
{
[CmdletBinding()]
param (
[Parameter()]
[Alias("SDName","Name")]
[string]
$SecurityDescriptorName
)
Write-Verbose "Get-SMBSecDesc - Begin"
# test for a valid descriptor name
if (-NOT [string]::IsNullOrEmpty($SecurityDescriptorName) -and $SecurityDescriptorName -notin ([SMBSecurityDescriptor].GetEnumNames()))
{
Write-Error "'$SecurityDescriptorName' is an invalid SecurityDescriptor. The valid names are $((Get-SMBSecurityDescriptorName) -join ', ')"
return $null
}
# return all when no descriptor is passed
if ([string]::IsNullOrEmpty($SecurityDescriptorName))
{
Write-Verbose "Get-SMBSecDesc - Returning all descriptors and descriptions."
$result = [List[PSObject]]::new()
foreach ($element in $Script:SMBSecDescriptorDef.GetEnumerator())
{
Write-Debug "Get-SMBSecDesc - Name: $($element.Key), Description: $($element.Value)"
$tmp = [PSCustomObject]@{
Name = $element.Key
Description = $element.Value
}
# the Add method throws "You cannot call a method on a null-valued expression." in Windows PowerShell
$result.Add($tmp)
Remove-Variable tmp -EA SilentlyContinue
}
return $result
}
else
{
try
{
Write-Verbose "Get-SMBSecDesc - Getting description."
$desc = $Script:SMBSecDescriptorDef."$SecurityDescriptorName"
}
catch
{
# do nothing, just surpressing the error
}
if ($desc)
{
Write-Verbose "Get-SMBSecDesc - returning: $desc"
Write-Verbose "Get-SMBSecDesc - End"
return $desc
}
else
{
Write-Verbose "Get-SMBSecDesc - Unknown reg property found. Returning error."
Write-Verbose "Get-SMBSecDesc - End"
return (Write-Error "Unknown SMB SecurityDescriptor." -EA Stop)
}
}
}
<#
PURPOSE: Matches an well-known SID to a readable account description
EXPORTED: NO
#>
function Get-SMBSecurityAccount
{
[CmdletBinding()]
param (
[Parameter()]
[string]
$SID
)
Write-Verbose "Get-SMBSecurityAccount - Begin"
if (-NOT [string]::IsNullOrEmpty($SID))
{
$accnt = Find-UserAccount $SID
Write-Verbose "Get-SMBSecurityAccount - Returning: $accnt"
Write-Verbose "Get-SMBSecurityAccount - End"
return $accnt
}
Write-Verbose "Get-SMBSecurityAccount - The SID was null or empty. Returning Unknown."
Write-Verbose "Get-SMBSecurityAccount - End"
return "Unknown"
}
<#
PURPOSE: Returns a list of SMB Security Descriptors and their descriptions.
EXPORTED: YES
#>
function Get-SMBSecurityDescriptorName
{
return ([List[string]]( [SMBSecurityDescriptor].GetEnumNames() ))
}
<#
PURPOSE: Returns the available rights for a security descriptor.
EXPORTED: YES
#>
function Get-SMBSecurityDescriptorRight
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
[Alias("SDName","Name")]
[string]
$SecurityDescriptorName
)
# test for a valid descriptor name
if (-NOT [string]::IsNullOrEmpty($SecurityDescriptorName) -and $SecurityDescriptorName -notin ([SMBSecurityDescriptor].GetEnumNames()))
{
Write-Error "'$SecurityDescriptorName' is an invalid SecurityDescriptor. The valid names are $((Get-SMBSecurityDescriptorName) -join ', ')"
return $null
}
# check for FullControl and single permission values
#$hashTable = Invoke-Expression "`$Script:SMBSec$SecurityDescriptorName"
$hashTable = Get-Variable "SMBSec$SecurityDescriptorName" -Scope Script
return ($hashTable.Value)
}
#endregion GET
###########
## SET ##
###########
#region
<#
PURPOSE: Alters the owner of a SecurityDescriptor.
EXPORTED: YES
#>
function Set-SMBSecurityOwner
{
[CmdletBinding()]
param (
## needs to read from pipeline ##
[Parameter( Mandatory=$true,
ValueFromPipeline=$true)]
[PSCustomObject]
$SecurityDescriptor,
$Account,
[switch]
$PassThru
)
begin
{
# Write-Verbose "Set-SMBSecurityOwner - "
Write-Verbose "Set-SMBSecurityOwner - Begin"
}
process
{
Write-Verbose "Set-SMBSecurityOwner - Validating $Account"
try
{
$Owner = New-SMBSecurityOwner -Account $Account -EA Stop
#Write-Verbose "Set-SMBSecurityOwner - Found $($Owner.Account.Value)"
Write-Verbose "Set-SMBSecurityOwner - Setting the Security Descriptor to $Owner."
$SecurityDescriptor.Owner.SetOwner($Owner)
Write-Verbose "Set-SMBSecurityOwner - New owner set"
}
catch
{
return (Write-Error "Failed to validate the Owner account." -EA Stop)
}
}
end
{
Write-Verbose "Set-SMBSecurityOwner - End"
if ($PassThru.IsPresent)
{
return $SecurityDescriptor
}
else
{
return $null
}
}
}
<#
PURPOSE: Alters a SD DACL.
EXPORTED: YES
#>
function Set-SMBSecurityGroup
{
[CmdletBinding()]
param (
## needs to read from pipeline ##
[Parameter( Mandatory=$true,
ValueFromPipeline=$true)]
[PSCustomObject]
$SecurityDescriptor,
[string]
$Account,
[switch]
$PassThru
)
begin
{
# Write-Verbose "Set-SMBSecurityGroup - "
Write-Verbose "Set-SMBSecurityGroup - Begin"
}
process
{
Write-Verbose "Set-SMBSecurityGroup - Setting the Security Descriptor to $Account."
try
{
$Group = New-SMBSecurityGroup -Account $Account -EA Stop
Write-Verbose "Set-SMBSecurityOwner - Setting the Security Descriptor to $Group."
$SecurityDescriptor.Group.SetGroup($Group)
Write-Verbose "Set-SMBSecurityOwner - New Group set"
}
catch
{
return (Write-Error "Failed to set the new Group account: $_" -EA Stop)
}
}
end
{
Write-Verbose "Set-SMBSecurityGroup - End"
if ($PassThru.IsPresent)
{
return $SecurityDescriptor
}
else
{
return $null
}
}
}
<#
PURPOSE: Alters a single DACL. Used in conjunction with Set-SmbSecDescriptor to modify DACLs in an SD.
EXPORTED: YES
#>
function Set-SMBSecurityDACL
{
[CmdletBinding()]
param (
[Parameter( Mandatory=$true )]
[SMBSecDaclAce]
$DACL,
$Account = $null,
[ValidateSet("Allow", "Deny")]
$Access = $null,
[string[]]
$Right = $null,
[switch]
$PassThru
)
Write-Verbose "Set-SMBSecurityDACL - Begin"
# Clone the DACL.
# make changes to the clone and commit only once all changes are successful
Write-Verbose "Set-SMBSecurityDACL - Cloning DACL."
$copyDACL = $DACL
# update the account
if ($Account)
{
Write-Verbose "Set-SMBSecurityDACL - Updating Account from $($copyDACL.Account.ToString()) to $($Account.ToString())."
# Keep it simple, don't bother checking if it's the same as there are too many variables. The user will be trusted on that aspect.
# Let [SMBSecDaclAce].SetAccount() do the work of validation.
try
{
$copyDACL.SetAccount($Account)
Write-Verbose "Set-SMBSecurityDACL - Account update successfully."
}
catch
{
return (Write-Error "Failed to update the DACL account: $_" -EA Stop)
}
}
# update the access
if ($Access)
{
Write-Verbose "Set-SMBSecurityDACL - Updating Access from $($copyDACL.Access) to $($Access.ToString())."
try
{
# Let [SMBSecDaclAce].SetAccess() do the work
$copyDACL.SetAccess($Access)
Write-Verbose "Set-SMBSecurityDACL - Access update successfully."
}
catch
{
return (Write-Error "Failed to update the DACL access: $_" -EA Stop)
}
}
# update rights
if ($Right)
{
Write-Verbose "Set-SMBSecurityDACL - Updating Right(s) from $($copyDACL.Right -join ',') to $($Right -join ',')."
# add rights to the DACL
# SetRights does all the validation work, rely on that rather than duplicating the code here.
try
{
$copyDACL.SetRights($Right)
}
catch
{
return (Write-Error "Failed to update the DACL rights: $_" -EA Stop)
}
}
# return the modified DACL
Write-Verbose "Set-SMBSecurityDACL - End"
#return $copyDACL
}
<#
PURPOSE: Updates a single DACL in a SD. Used in conjunction with Set-SMBSecurityDACL, which modifies the DACL.
EXPORTED: YES
#>
function Set-SmbSecurityDescriptorDACL
{
[CmdletBinding()]
param (
[Parameter( Mandatory=$true)]
[PSCustomObject]
$SecurityDescriptor,
[Parameter( Mandatory=$true )]
[SMBSecDaclAce]
$DACL,
[Parameter( Mandatory=$true )]
[SMBSecDaclAce]
$NewDACL
)
Write-Verbose "Set-SmbSecurityDescriptorDACL - Begin"
# find the index of the DACL in the SD
$index = $SecurityDescriptor.DACL.IndexOf($DACL)
Write-Verbose "Set-SmbSecurityDescriptorDACL - Index of DACL: $index"
if (-NOT $index -or $index -eq -1)
{
return (Write-Error "Could not find a matching DACL in the SecurityDescriptor." -EA Stop)
}
try
{
Write-Verbose "Set-SmbSecurityDescriptorDACL - Removing DACL."
# remove the DACL at the index
$SecurityDescriptor.DACL.RemoveAt($index)
Write-Verbose "Set-SmbSecurityDescriptorDACL - Inserting updated ACL."
# insert the new DACL in the same spot
$SecurityDescriptor.DACL.Insert($index, $NewDACL)
}
catch
{
return (Write-Error "Failed to update the DACL: $_" -EA Stop)
}
}
#endregion SET
###########
## NEW ##
###########
#region
<#
PURPOSE: Creates a [PSCustomObject] containing all the details of an SMB security descriptor.
EXPORTED: YES
#>
<#
TO-DO:
- Create parameter sets.
#>
function New-SMBSecurityDescriptor
{
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)]
#[ValidateScript({ $_ -in ([SMBSecurityDescriptor].GetEnumNames()) })]
[SMBSecurityDescriptor]
$SecurityDescriptorName,
[Parameter(Mandatory=$false)]
[string]
$SDDLString,
[Parameter(Mandatory=$false)]
$Owner,
[Parameter(Mandatory=$false)]
$Group,
[Parameter(Mandatory=$false)]
$DACL
)
Write-Verbose "New-SMBSecurityDescriptor - Begin"
# use the SDDL string over other params
if (-NOT [string]::IsNullOrEmpty($SDDLString))
{
# convert the SDDL to human readable text
$SDDL = ConvertFrom-SddlString $SDDLString
Write-Debug "New-SMBSecurityDescriptor - SecurityDescriptor Name: $SecurityDescriptorName"
Write-Debug "New-SMBSecurityDescriptor - SDDLString: $strSDDL"
Write-Verbose "New-SMBSecurityDescriptor - Creating the DACL ACE object."
$DACL = New-Object System.Collections.ArrayList
# strip out the ACE string(s)
[string[]]$ACEs = $SDDLString.Split(':')[-1].Split(')').Trim('(') | Where-Object { $_ -ne $null -and $_ -ne "" }
Write-Verbose "New-SMBSecurityDescriptor - ACEs: $($ACEs -join ', ')"
# this is really ugly ... :{ ... but it works
$DACL = New-Object System.Collections.ArrayList
try
{
Write-Verbose "New-SMBSecurityDescriptor - First try."
$DACL += Convert-SMBSecString2DACL $SecurityDescriptorName $ACEs
}
catch
{
Write-Verbose "New-SMBSecurityDescriptor - Second try."
$DACL += Convert-SMBSecString2DACL $SecurityDescriptorName $ACEs
#$null = $DACL.AddRange($tmpDACL)
}
Write-Verbose "New-SMBSecurityDescriptor - DACL count: $($DACL.Count)"
if ($DACL)
{
Write-Verbose "New-SMBSecurityDescriptor - DACL:`n$($DACL | Format-Table * | Out-String) "
}
else
{
Write-Error "huh..."
}
}
# need to make sure DACL is an ArrayList or it messes things up later on
if ($DACL -isnot [System.Collections.ArrayList])
{
# convert array and generic lists to ArrayList.
# The next version may switch to generic lists per: https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-arrays?view=powershell-7.2
if ($DACL -is [array] -or $DACL.GetType().Name -Match "List")
{
$tmpDACL = $DACL
$DACL = New-Object System.Collections.ArrayList
$null = $DACL.AddRange($tmpDACL)
}
elseif ($DACL -is [object] -and $DACL.GetType().Name -eq "SMBSecDaclAce")
{
$tmpDACL = $DACL
$DACL = New-Object System.Collections.ArrayList
$null = $DACL.Add($tmpDACL)
}
else
{
return (Write-Error "New-SMBSecurityDescriptor - Unknown DACL type. The DACL must me an Array or ArrayList of, or a single, SMBSecDACL object (New-SMBSecurityDACL).")
}
}
## validate everything... bail on fail ##
# description
try
{
Write-Verbose "New-SMBSecurityDescriptor - Get descriptor description."
$desc = Get-SMBSecurityDescription -SecurityDescriptorName $SecurityDescriptorName -EA Stop
}
catch
{
# the description is not important, but if this fails then something is broken so we terminate anyway.
return (Write-Error "Failed to find a description. Possibly data integrity issue detected. $_" -EA Stop)
}
# owner
try
{
Write-Verbose "New-SMBSecurityDescriptor - Create owner."
if ( -NOT [string]::IsNullOrEmpty($SDDL.Owner) )
{
Write-Debug "New-SMBSecurityDescriptor - Set Owner as part of SDDL: $($SDDL.Owner)"
$OwnAccount = New-SMBSecurityOwner $SDDL.Owner
#$tmpowner = [SMBSecOwner]::New($OwnAccount.Account)
}
elseif ($Owner -is [SMBSecAccount])
{
Write-Debug "New-SMBSecurityDescriptor - Manual set Owner as [SMBSecAccount]: $($Owner.ToString())"
$OwnAccount = New-SMBSecurityOwner $Owner
}
elseif ($Owner -is [SMBSecOwner])
{
Write-Debug "New-SMBSecurityDescriptor - Manual set Owner as [SMBSecAccount]: $($Owner.ToString())"
$OwnAccount = $Owner
}
elseif ( -NOT [string]::IsNullOrEmpty($Owner))
{
Write-Debug "New-SMBSecurityDescriptor - Manual set Owner as something else: $($Owner.ToString())"
$OwnAccount = New-SMBSecurityOwner $Owner
#$tmpowner = [SMBSecOwner]::New($OwnAccount.Account)
}
else
{
return (Write-Error "Failed to find an owner." -EA Stop)
}
}
catch
{
return (Write-Error "Failed to validate owner account: $_" -EA Stop)
}
# group
try
{
Write-Verbose "New-SMBSecurityDescriptor - Create group."
if ( -NOT [string]::IsNullOrEmpty($SDDL.Group) )
{
Write-Debug "New-SMBSecurityDescriptor - Set Group as part of SDDL: $($SDDL.Group)"
$GrpAccount = New-SMBSecurityGroup $SDDL.Group
#$tmpgroup = [SMBSecGroup]::New($GrpAccount.Account)
}
elseif ($Group -is [SMBSecGroup])
{
Write-Debug "New-SMBSecurityDescriptor - Manual set Group as [SMBSecAccount]: $($Group.ToString())"
$GrpAccount = $Group
}
elseif ($Group -is [SMBSecAccount])
{
Write-Debug "New-SMBSecurityDescriptor - Manual set Group as [SMBSecAccount]: $($Group.ToString())"
$GrpAccount = New-SMBSecurityGroup $Group
}
elseif ( -NOT [string]::IsNullOrEmpty($Group))
{
Write-Debug "New-SMBSecurityDescriptor - Manual set Group as something else: $($Group.ToString())"
$GrpAccount = $Group
#$tmpgroup = [SMBSecGroup]::New($GrpAccount.Account)
}
else
{
Write-Error "Failed to find a group." -EA Stop
}
}
catch
{
return (Write-Error "Failed to validate group account: $_" -EA Stop)
}
if ( -NOT $DACL )
{
return (Write-Error "Failed to find or create a DACL." -EA Stop)
}
Write-Verbose "New-SMBSecurityDescriptor - Create SMBSecurityDescriptor object."
# create a results object
$tmpObj = [PSCustomObject]@{
PSTypeName = 'SMBSecurityDescriptor'
DisplayName = 'SMB SecurityDescriptor Object'
Name = $SecurityDescriptorName
Description = $desc
Owner = $OwnAccount
Group = $GrpAccount
DACL = $DACL
}
# I decided to keep the descriptor object simplified so there are fewer things to update.
# One of more of the following can be added back in the future, but will be skipped in the first iteration.
#SDDL = $SDDL
#rawSDDL = $SDDLString
#rawBytes = $rawBytes
<# add ToString method
$sd2Str = @'
Name : {0}
Description : {1}
Owner : {2}
Group : {3}
DACL : {4}
'@
#>
$tmpObj | Add-Member -MemberType ScriptMethod -Name ToString -Value { "Name : {0}`nDescription : {1}`nOwner : {2}`nGroup : {3}`nDACL : {4}" -f $this.Name, `
$this.Description, `
$this.Account.ToString(), `
$this.Account.ToString(), `
$(($this.DACL | ForEach-Object {$_.ToString()}) -join ', ') } -Force
$tmpObj | Add-Member -MemberType ScriptMethod -Name ToBoxString -Value { "`tName : {0}`n`tDescription : {1}`n`tOwner : {2}`n`tGroup : {3}`n`tDACL : `n{4}" -f `
$this.Name, `
$this.Description, `
$this.Account.ToString(), `
$this.Account.ToString(), `
"`n`t`t$(($this.DACL | ForEach-Object {$_.ToString()}) -join "`n`t`t")" } -Force
Write-Verbose "New-SMBSecurityDescriptor - Returning SMBSecurity object:`n $($tmpObj | Format-Table | Out-String)"
Write-Verbose "New-SMBSecurityDescriptor - End"
return $tmpObj
}
<#
PURPOSE: Creates a DACL object which can be added to a SMBSec.Descriptor.
EXPORTED: YES
TO-DO:
- Find a dynamic way of creating the $Rights ValidateSet, possibly with a ValidateScript?
#>
function New-SMBSecurityDACL
{
[CmdletBinding()]
param (
[Parameter( Mandatory=$true,
Position=0)]
[Alias("SDName","Name")]
[string]
$SecurityDescriptorName,
[Parameter( Mandatory=$true,
Position=1)]
#[ValidateSet("Allow","Deny")]
[SMBSecAccess]
$Access,
# Parameter help description
[Parameter( Mandatory=$true,
Position=2)]
#[ValidateSet("AdvancedEnumerate","Change","ChangeServerInfo","ChangeShareInfo","ConnectToPausedServer","ConnectToServer","Delete","Enumerate","EnumerateConnections","EnumerateDisks","EnumerateOpenFiles","ForceFilesClosed","FullControl","Read","ReadAdministrativeServerInfo","ReadAdministrativeSessionInfo","ReadAdministrativeShareInfo","ReadAdminShareUserInfo","ReadAdvancedServerInfo","ReadControl","ReadServerInfo","ReadSessionInfo","ReadShareInfo","ReadShareUserInfo","ReadStatistics","SetInfo","SetShareInfo","WriteDAC","WriteOwner")]
[string[]]
$Rights,
# Parameter help description
[Parameter( Mandatory=$true,
Position=3)]
$Account
)
# Write-Verbose "New-SMBSecurityDACL - "
begin
{
Write-Verbose "New-SMBSecurityDACL - Begin"
# create a DACL object
Write-Verbose "New-SMBSecurityDACL - Create new SMBSecDaclAce."
# tracks failures to ensure partial objects are not returned
$failure = $false
# create the SMBSecDaclAce object
$tmpDACL = [SMBSecDaclAce]::new($SecurityDescriptorName)
}
process
{
Write-Verbose "New-SMBSecurityDACL - Process"
# loop through each parameter and add the value to the [SMBSecDaclAce] object.
:key foreach ($key in $PSBoundParameters.Keys)
{
switch ($key)
{
"Access"
{
Write-Verbose "Set-SMBSecRight - Setting Access."
try
{
$tmpDACL.SetAccess($Access)
}
catch
{
$failure = $true
Write-Error "Failed to set DACL access: $_"
break key
}
break
}
"Rights"
{
Write-Verbose "Set-SMBSecRight - Setting Rights."
try
{
$tmpDACL.SetRights($Rights)
}
catch
{
$failure = $true
Write-Error "Failed to set DACL rights: $_"
break key
}
break
}
"Account"
{
Write-Verbose "Set-SMBSecRight - Setting Account."
try
{
if ($Account -is [SMBSecAccount])
{
$tmpDACL.SetAccount($Account)
break
}
$SMBSecAccount = New-SmbSecurityAccount $Account
$tmpDACL.SetAccount($SMBSecAccount)
}
catch
{
$failure = $true
Write-Error "Failed to set the DACL account: $_" -EA Stop
break key
}
break
}
"SecurityDescriptorName" {break}
default { Write-Error "Unknown parameter: $_`n $($PSBoundParameters | Format-List * | Out-String)" }
}
}
}
end
{
Write-Verbose "New-SMBSecurityDACL - End"
if ($failure)
{
Write-Verbose "New-SMBSecurityDACL - Returning NULL due to failure."
return $null
}
else
{
return $tmpDACL
}
}
}
<#
PURPOSE: Validates the account on the system or domain, then returns a [System.Security.Principal.NTAccount] object.
EXPORTED: YES
#>
function New-SMBSecurityOwner
{
[CmdletBinding()]
param (
## needs to read from pipeline ##
[Parameter( Mandatory=$true,
ValueFromPipeline=$true)]
$Account,
[switch]
$ForceDomain
)
begin
{
# Write-Verbose "Set-SMBSecurityOwner - "
Write-Verbose "New-SMBSecurityOwner - Begin"
$skipCheck = $false
if ($Account -is [System.Security.Principal.SecurityIdentifier] -or $Account -is [System.Security.Principal.NTAccount])
{
$Account = $Account.Value
}
elseif ($Account -is [SMBSecAccount] -or $Account -is [SMBSecOwner])
{
# make sure there is an SID in the object
if ([string]::IsNullOrEmpty($Account.SID.Value))