Debian Codegraph @

ansible_collections/community/windows/plugins/modules/win_security_policy.ps1

raw
1 #!powershell
2
3 # Copyright: (c) 2017, Jordan Borean <[email protected]>
4 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
5
6 #Requires -Module Ansible.ModuleUtils.Legacy
7
8 $ErrorActionPreference = 'Stop'
9
10 $params = Parse-Args $args -supports_check_mode $true
11 $check_mode = Get-AnsibleParam -obj $params -name "_ansible_check_mode" -type "bool" -default $false
12 $diff_mode = Get-AnsibleParam -obj $Params -name "_ansible_diff" -type "bool" -default $false
13
14 $section = Get-AnsibleParam -obj $params -name "section" -type "str" -failifempty $true
15 $key = Get-AnsibleParam -obj $params -name "key" -type "str" -failifempty $true
16 $value = Get-AnsibleParam -obj $params -name "value" -failifempty $true
17
18 $result = @{
19 changed = $false
20 section = $section
21 key = $key
22 value = $value
23 }
24
25 if ($diff_mode) {
26 $result.diff = @{}
27 }
28
29 Function Invoke-SecEdit($arguments) {
30 $stdout = $null
31 $stderr = $null
32 $log_path = [IO.Path]::GetTempFileName()
33 $arguments = $arguments + @("/log", $log_path)
34
35 try {
36 $stdout = &SecEdit.exe $arguments | Out-String
37 }
38 catch {
39 $stderr = $_.Exception.Message
40 }
41 $log = Get-Content -LiteralPath $log_path
42 Remove-Item -LiteralPath $log_path -Force
43
44 $return = @{
45 log = ($log -join "`n").Trim()
46 stdout = $stdout
47 stderr = $stderr
48 rc = $LASTEXITCODE
49 }
50
51 return $return
52 }
53
54 Function Export-SecEdit() {
55 # GetTempFileName() will create a file but it doesn't have any content. This is problematic as secedit uses the
56 # encoding of the file at /cfg if it exists and because there is no BOM it will export using the "ANSI" encoding.
57 # By making sure the file exists and has a UTF-16-LE BOM we can be sure our parser reads the bytes as a string
58 # correctly.
59 $secedit_ini_path = [IO.Path]::GetTempFileName()
60 Set-Content -LiteralPath $secedit_ini_path -Value '' -Encoding Unicode
61
62 # while this will technically make a change to the system in check mode by
63 # creating a new file, we need these values to be able to do anything
64 # substantial in check mode
65 $export_result = Invoke-SecEdit -arguments @("/export", "/cfg", $secedit_ini_path, "/quiet")
66
67 # check the return code and if the file has been populated, otherwise error out
68 if (($export_result.rc -ne 0) -or ((Get-Item -LiteralPath $secedit_ini_path).Length -eq 0)) {
69 Remove-Item -LiteralPath $secedit_ini_path -Force
70 $result.rc = $export_result.rc
71 $result.stdout = $export_result.stdout
72 $result.stderr = $export_result.stderr
73 Fail-Json $result "Failed to export secedit.ini file to $($secedit_ini_path)"
74 }
75 $secedit_ini = ConvertFrom-Ini -file_path $secedit_ini_path
76
77 return $secedit_ini
78 }
79
80 Function Import-SecEdit($ini) {
81 $secedit_ini_path = [IO.Path]::GetTempFileName()
82 $secedit_db_path = [IO.Path]::GetTempFileName()
83 Remove-Item -LiteralPath $secedit_db_path -Force # needs to be deleted for SecEdit.exe /import to work
84
85 $ini_contents = ConvertTo-Ini -ini $ini
86
87 # Use Unicode (UTF-16-LE) as that is the same across all PowerShell versions and we don't have to worry about
88 # changing ANSI encodings.
89 Set-Content -LiteralPath $secedit_ini_path -Value $ini_contents -Encoding Unicode
90 $result.changed = $true
91
92 $import_result = Invoke-SecEdit -arguments @("/configure", "/db", $secedit_db_path, "/cfg", $secedit_ini_path, "/quiet")
93 $result.import_log = $import_result.log
94 Remove-Item -LiteralPath $secedit_ini_path -Force
95 if ($import_result.rc -ne 0) {
96 $result.rc = $import_result.rc
97 $result.stdout = $import_result.stdout
98 $result.stderr = $import_result.stderr
99 Fail-Json $result "Failed to import secedit.ini file from $($secedit_ini_path)"
100 }
101
102 # https://github.com/ansible-collections/community.windows/issues/153
103 # The LegalNoticeText entry is stored in the ini with type 7 (REG_MULTI_SZ) where each comma entry is read as a
104 # newline. When secedit imports the value it sets LegalNoticeText in the registry to be a REG_SZ type with the
105 # newlines but it also adds the extra null char at the end that REG_MULTI_SZ uses to denote the end of an entry.
106 # We manually trim off that extra null char so the legal text does not contain the unknown character symbol.
107 $legalPath = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System'
108 $legalName = 'LegalNoticeText'
109 $prop = Get-ItemProperty -LiteralPath $legalPath
110 if ($legalName -in $prop.PSObject.Properties.Name) {
111 $existingText = $prop.LegalNoticeText.TrimEnd("`0")
112 Set-ItemProperty -LiteralPath $legalPath -Name $legalName -Value $existingText
113 }
114 }
115
116 Function ConvertTo-Ini($ini) {
117 $content = @()
118 foreach ($key in $ini.GetEnumerator()) {
119 $section = $key.Name
120 $values = $key.Value
121
122 $content += "[$section]"
123 foreach ($value in $values.GetEnumerator()) {
124 $value_key = $value.Name
125 $value_value = $value.Value
126
127 if ($null -ne $value_value) {
128 $content += "$value_key = $value_value"
129 }
130 }
131 }
132
133 return $content -join "`r`n"
134 }
135
136 Function ConvertFrom-Ini($file_path) {
137 $ini = @{}
138 switch -Regex -File $file_path {
139 "^\[(.+)\]" {
140 $section = $matches[1]
141 $ini.$section = @{}
142 }
143 "(.+?)\s*=(.*)" {
144 $name = $matches[1].Trim()
145 $value = $matches[2].Trim()
146 if ($value -match "^\d+$") {
147 $value = [int]$value
148 }
149 elseif ($value.StartsWith('"') -and $value.EndsWith('"')) {
150 $value = $value.Substring(1, $value.Length - 2)
151 }
152
153 $ini.$section.$name = $value
154 }
155 }
156
157 return $ini
158 }
159
160 if ($section -eq "Privilege Rights") {
161 Add-Warning -obj $result -message "Using this module to edit rights and privileges is error-prone, use the ansible.windows.win_user_right module instead"
162 }
163
164 $will_change = $false
165 $secedit_ini = Export-SecEdit
166 if (-not ($secedit_ini.ContainsKey($section))) {
167 Fail-Json $result "The section '$section' does not exist in SecEdit.exe output ini"
168 }
169
170 if ($secedit_ini.$section.ContainsKey($key)) {
171 $current_value = $secedit_ini.$section.$key
172
173 if ($current_value -cne $value) {
174 if ($diff_mode) {
175 $result.diff.prepared = @"
176 [$section]
177 -$key = $current_value
178 +$key = $value
179 "@
180 }
181
182 $secedit_ini.$section.$key = $value
183 $will_change = $true
184 }
185 }
186 elseif ([string]$value -eq "") {
187 # Value is requested to be removed, and has already been removed, do nothing
188 }
189 else {
190 if ($diff_mode) {
191 $result.diff.prepared = @"
192 [$section]
193 +$key = $value
194 "@
195 }
196 $secedit_ini.$section.$key = $value
197 $will_change = $true
198 }
199
200 if ($will_change -eq $true) {
201 $result.changed = $true
202 if (-not $check_mode) {
203 Import-SecEdit -ini $secedit_ini
204
205 # secedit doesn't error out on improper entries, re-export and verify
206 # the changes occurred
207 $verification_ini = Export-SecEdit
208 $new_section_values = $verification_ini.$section
209 if ($new_section_values.ContainsKey($key)) {
210 $new_value = $new_section_values.$key
211 if ($new_value -cne $value) {
212 Fail-Json $result "Failed to change the value for key '$key' in section '$section', the value is still $new_value"
213 }
214 }
215 elseif ([string]$value -eq "") {
216 # Value was empty, so OK if no longer in the result
217 }
218 else {
219 Fail-Json $result "The key '$key' in section '$section' is not a valid key, cannot set this value"
220 }
221 }
222 }
223
224 Exit-Json $result