DSCResources/Grani_InheritACL/Grani_InheritACL.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
#region Initialize

function Initialize {
    # Enum for Ensure
    try {
        Add-Type -TypeDefinition @"
        public enum EnsureType
        {
            Present,
            Absent
        }
"@

    }
    catch {
    }
}

Initialize

#endregion

#region Message Definition

$debugMessage = DATA {
    ConvertFrom-StringData -StringData "
        CheckingPreserveInheritance = Checking acl is inherited. Access : '{0}', AccessControlType : '{1}', IsInherited : '{2}'.
        SettingAcl = Setting ACL to Path '{0}', IsProtected '{1}', PreserveInheritance '{2}'.
    "

}

$verboseMessage = DATA {
    ConvertFrom-StringData -StringData "
        DetectIsProtected = Path detected as Protected, means not inherited from parent.
        DetectIsNotProtected = Path detected as not Protected, means inherited from parent.
        DetectPreserveInheritance = Path detected as PreserveInheritance.
        GetTargetResourceDetectExeption = GetTargetResource detect exception as '{0}'
        ObtainACL = Path '{0}' found. Obtaining ACL.
        PathNotFound = Path '{0}' not found. Skip other checking.
    "

}

$exceptionMessage = DATA {
    ConvertFrom-StringData -StringData "
        PathNotFoundException = Could not found desired path '{0}' exeption!
        NoAccessRuleLeftException = Invalid Operation detected. there are no access left. You must set any not inherit acess before not preserve Inheritance.
    "

}

#endregion

#region *-TargetResource

function Get-TargetResource {
    [OutputType([System.Collections.Hashtable])]
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Path,

        [parameter(Mandatory = $true)]
        [System.Boolean]$IsProtected,

        [parameter(Mandatory = $false)]
        [System.Boolean]$PreserveInheritance = $true,

        [parameter(Mandatory = $false)]
        [ValidateSet("Present", "Absent")]
        [System.String]$Ensure
    )

    # Set Default value
    $isPathExist = $true;
    $returnValue = @{
        Path                = $Path;
        IsProtected         = $false;
        PreserveInheritance = $true;
    };

    # Path existance Check
    if (!(Test-Path -Path $Path)) {
        Write-Verbose ($verboseMessage.PathNotFound -f $Path);
        $isPathExist = $false;
    }
    else {
        try {
            # Obtain current ACL
            Write-Verbose ($verboseMessage.ObtainACL -f $Path);
            $acl = Get-Acl -Path $Path -ErrorAction Stop;            

            # IsProtected Check
            if ($acl.AreAccessRulesProtected) {
                Write-Verbose ($verboseMessage.DetectIsProtected);
                $returnValue.IsProtected = $true;

                # Could not detect PreserveInheritanceCheck because this information will lost when Protected.
                $returnValue.PreserveInheritance = $PreserveInheritance;
            }
            else {
                Write-Verbose ($verboseMessage.DetectIsNotProtected);
                $returnValue.IsProtected = $false;

                # PreserveInheritanceCheck
                foreach ($access in $acl.Access) {
                    Write-Debug ($debugMessage.CheckingPreserveInheritance -f $access.IdentityReference, $access.AccessControlType, $access.IsInherited);
                    $isInherited = $access.IsInherited;
                    if ($isInherited) {
                        Write-Verbose ($verboseMessage.DetectPreserveInheritance);
                        $returnValue.PreserveInheritance = $true;
                        break; # break is fine when any access was detected inherited.
                    }
                }
            }
        }
        catch {
            Write-Verbose ($verboseMessage.GetTargetResourceDetectExeption -f $_);

        }
    }

    # Ensure Check (Not path detected => Ensure = "Absent")
    if ($isPathExist -and ($IsProtected -eq $returnValue.IsProtected) -and ($PreserveInheritance -eq $returnValue.PreserveInheritance)) {
        $returnValue.Ensure = [EnsureType]::Present.ToString();
    }
    else {
        $returnValue.Ensure = [EnsureType]::Absent.ToString();
    }

    return $returnValue;
}


function Set-TargetResource {
    [OutputType([Void])]
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Path,

        [parameter(Mandatory = $true)]
        [System.Boolean]$IsProtected,

        [parameter(Mandatory = $false)]
        [System.Boolean]$PreserveInheritance = $true,

        [parameter(Mandatory = $false)]
        [ValidateSet("Present", "Absent")]
        [System.String]$Ensure
    )

    # Path existance Check
    if (!(Test-Path -Path $Path)) {
        throw New-Object System.IO.FileNotFoundException ($exceptionMessage.PathNotFoundException -f $Path)
    }

    # Get current
    $acl = Get-Acl -Path $Path;

    # Modify ACL
    Write-Debug -Message ($debugMessage -f $Path, $IsProtected, $PreserveInheritance);
    $acl.SetAccessRuleProtection($IsProtected, $PreserveInheritance);
    if (($acl.Access | sort).Count -eq 0) {
        throw New-Object System.InvalidOperationException ($exceptionMessage.NoAccessRuleLeftException);
    }

    # Write Back to Path
    $acl | Set-Acl -Path $Path
}


function Test-TargetResource {
    [OutputType([System.Boolean])]
    [CmdletBinding()]
    param
    (
        [parameter(Mandatory = $true)]
        [System.String]$Path,

        [parameter(Mandatory = $true)]
        [System.Boolean]$IsProtected,

        [parameter(Mandatory = $false)]
        [System.Boolean]$PreserveInheritance = $true,

        [parameter(Mandatory = $false)]
        [ValidateSet("Present", "Absent")]
        [System.String]$Ensure
    )

    [bool]$result = (Get-TargetResource -Path $Path -IsProtected $IsProtected -PreserveInheritance $PreserveInheritance).Ensure -eq ([EnsureType]::Present.ToString());
    return $result;
}

#endregion

Export-ModuleMember -Function *-TargetResource