File size: 8,762 Bytes
8c763fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

#if !UNIX

using System;
using System.Collections.Generic;
using System.Management.Automation;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text;

namespace Microsoft.PowerShell.Commands
{
    /// <summary>
    /// Converts a SDDL string into an object-based representation of a security descriptor.
    /// </summary>
    [Cmdlet(VerbsData.ConvertFrom, "SddlString", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=623636", RemotingCapability = RemotingCapability.None)]
    [OutputType(typeof(SecurityDescriptorInfo))]
    public sealed class ConvertFromSddlStringCommand : PSCmdlet
    {
        /// <summary>
        /// Gets and sets the string representing the security descriptor in SDDL syntax.
        /// </summary>
        [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true)]
        public string Sddl { get; set; }

        /// <summary>
        /// Gets and sets type of rights that this SDDL string represents.
        /// </summary>
        [Parameter]
        public AccessRightTypeNames Type
        {
            get
            {
                return _type;
            }

            set
            {
                _isTypeSet = true;
                _type = value;
            }
        }

        private AccessRightTypeNames _type;
        private bool _isTypeSet = false;

        private static string ConvertToNTAccount(SecurityIdentifier securityIdentifier)
        {
            try
            {
                return securityIdentifier?.Translate(typeof(NTAccount)).Value;
            }
            catch
            {
                return null;
            }
        }

        private static List<string> GetApplicableAccessRights(int accessMask, AccessRightTypeNames? typeName)
        {
            List<Type> typesToExamine = new();
            List<string> foundAccessRightNames = new();
            HashSet<int> foundAccessRightValues = new();

            if (typeName != null)
            {
                typesToExamine.Add(GetRealAccessRightType(typeName.Value));
            }
            else
            {
                foreach (AccessRightTypeNames member in Enum.GetValues<AccessRightTypeNames>())
                {
                    typesToExamine.Add(GetRealAccessRightType(member));
                }
            }

            foreach (Type accessRightType in typesToExamine)
            {
                foreach (string memberName in Enum.GetNames(accessRightType))
                {
                    int memberValue = (int)Enum.Parse(accessRightType, memberName);
                    if (foundAccessRightValues.Add(memberValue))
                    {
                        if ((accessMask & memberValue) == memberValue)
                        {
                            foundAccessRightNames.Add(memberName);
                        }
                    }
                }
            }

            foundAccessRightNames.Sort(StringComparer.OrdinalIgnoreCase);
            return foundAccessRightNames;
        }

        private static Type GetRealAccessRightType(AccessRightTypeNames typeName)
        {
            switch (typeName)
            {
                case AccessRightTypeNames.FileSystemRights:
                    return typeof(FileSystemRights);
                case AccessRightTypeNames.RegistryRights:
                    return typeof(RegistryRights);
                case AccessRightTypeNames.ActiveDirectoryRights:
                    return typeof(System.DirectoryServices.ActiveDirectoryRights);
                case AccessRightTypeNames.MutexRights:
                    return typeof(MutexRights);
                case AccessRightTypeNames.SemaphoreRights:
                    return typeof(SemaphoreRights);
                case AccessRightTypeNames.EventWaitHandleRights:
                    return typeof(EventWaitHandleRights);
                default:
                    throw new InvalidOperationException();
            }
        }

        private static string[] ConvertAccessControlListToStrings(CommonAcl acl, AccessRightTypeNames? typeName)
        {
            if (acl == null || acl.Count == 0)
            {
                return Array.Empty<string>();
            }

            List<string> aceStringList = new(acl.Count);
            foreach (CommonAce ace in acl)
            {
                StringBuilder aceString = new();
                string ntAccount = ConvertToNTAccount(ace.SecurityIdentifier);
                aceString.Append($"{ntAccount}: {ace.AceQualifier}");

                if (ace.AceFlags != AceFlags.None)
                {
                    aceString.Append($" {ace.AceFlags}");
                }

                List<string> accessRightList = GetApplicableAccessRights(ace.AccessMask, typeName);
                if (accessRightList.Count > 0)
                {
                    string accessRights = string.Join(", ", accessRightList);
                    aceString.Append($" ({accessRights})");
                }

                aceStringList.Add(aceString.ToString());
            }

            return aceStringList.ToArray();
        }

        /// <summary>
        /// ProcessRecord method.
        /// </summary>
        protected override void ProcessRecord()
        {
            CommonSecurityDescriptor rawSecurityDescriptor = null;
            try
            {
                rawSecurityDescriptor = new CommonSecurityDescriptor(isContainer: false, isDS: false, Sddl);
            }
            catch (Exception e)
            {
                var ioe = PSTraceSource.NewInvalidOperationException(e, UtilityCommonStrings.InvalidSDDL, e.Message);
                ThrowTerminatingError(new ErrorRecord(ioe, "InvalidSDDL", ErrorCategory.InvalidArgument, Sddl));
            }

            string owner = ConvertToNTAccount(rawSecurityDescriptor.Owner);
            string group = ConvertToNTAccount(rawSecurityDescriptor.Group);

            AccessRightTypeNames? typeToUse = _isTypeSet ? _type : (AccessRightTypeNames?)null;
            string[] discretionaryAcl = ConvertAccessControlListToStrings(rawSecurityDescriptor.DiscretionaryAcl, typeToUse);
            string[] systemAcl = ConvertAccessControlListToStrings(rawSecurityDescriptor.SystemAcl, typeToUse);

            var outObj = new SecurityDescriptorInfo(owner, group, discretionaryAcl, systemAcl, rawSecurityDescriptor);
            WriteObject(outObj);
        }

        /// <summary>
        /// AccessRight type names.
        /// </summary>
        public enum AccessRightTypeNames
        {
            /// <summary>
            /// FileSystemRights.
            /// </summary>
            FileSystemRights,

            /// <summary>
            /// RegistryRights.
            /// </summary>
            RegistryRights,

            /// <summary>
            /// ActiveDirectoryRights.
            /// </summary>
            ActiveDirectoryRights,

            /// <summary>
            /// MutexRights.
            /// </summary>
            MutexRights,

            /// <summary>
            /// SemaphoreRights.
            /// </summary>
            SemaphoreRights,

            // We have 'CryptoKeyRights' in the list for Windows PowerShell, but that type is not available in .NET Core.
            // CryptoKeyRights,

            /// <summary>
            /// EventWaitHandleRights.
            /// </summary>
            EventWaitHandleRights
        }
    }

    /// <summary>
    /// Representation of a security descriptor.
    /// </summary>
    public sealed class SecurityDescriptorInfo
    {
        internal SecurityDescriptorInfo(
            string owner,
            string group,
            string[] discretionaryAcl,
            string[] systemAcl,
            CommonSecurityDescriptor rawDescriptor)
        {
            Owner = owner;
            Group = group;
            DiscretionaryAcl = discretionaryAcl;
            SystemAcl = systemAcl;
            RawDescriptor = rawDescriptor;
        }

        /// <summary>
        /// EventWaitHandle rights.
        /// </summary>
        public readonly string Owner;

        /// <summary>
        /// EventWaitHandle rights.
        /// </summary>
        public readonly string Group;

        /// <summary>
        /// EventWaitHandle rights.
        /// </summary>
        public readonly string[] DiscretionaryAcl;

        /// <summary>
        /// EventWaitHandle rights.
        /// </summary>
        public readonly string[] SystemAcl;

        /// <summary>
        /// EventWaitHandle rights.
        /// </summary>
        public readonly CommonSecurityDescriptor RawDescriptor;
    }
}

#endif