From dd29c1d334e35225f9cfc1e60101e424d6359c87 Mon Sep 17 00:00:00 2001 From: Tim Smith Date: Mon, 8 Oct 2018 12:10:27 -0700 Subject: Add windows_certificate and windows_share resources Move two additional resources over from the windows cookbook. With these moved we're pretty close to fully deprecating the windows cookbook. Signed-off-by: Tim Smith --- lib/chef/resource/windows_certificate.rb | 263 ++++++++++++++++++++++++++ lib/chef/resource/windows_share.rb | 315 +++++++++++++++++++++++++++++++ lib/chef/resources.rb | 2 + 3 files changed, 580 insertions(+) create mode 100644 lib/chef/resource/windows_certificate.rb create mode 100644 lib/chef/resource/windows_share.rb (limited to 'lib') diff --git a/lib/chef/resource/windows_certificate.rb b/lib/chef/resource/windows_certificate.rb new file mode 100644 index 0000000000..6c35eb7c96 --- /dev/null +++ b/lib/chef/resource/windows_certificate.rb @@ -0,0 +1,263 @@ +# +# Author:: Richard Lavey (richard.lavey@calastone.com) +# +# Copyright:: 2015-2017, Calastone Ltd. +# Copyright:: 2018, Chef Software, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +require "chef/resource" +require "win32-certstore" if Chef::Platform.windows? +require "openssl" + +class Chef + class Resource + class WindowsCertificate < Chef::Resource + preview_resource true + resource_name :windows_certificate + + description "The the windows_certificate resource to install a certificate into the Windows certificate store from a file. The resource grants read-only access to the private key for designated accounts. Due to current limitations in WinRM, installing certificated remotely may not work if the operation requires a user profile. Operations on the local machine store should still work." + introduced "14.6" + + property :source, String, + description: "The source file (for create and acl_add), thumbprint (for delete and acl_add) or subject (for delete).", + name_property: true + + property :pfx_password, String, + description: "The password to access the source if it is a pfx file." + + property :private_key_acl, Array, + description: "An array of 'domain\account' entries to be granted read-only access to the certificate's private key. Not idempotent." + + property :store_name, String, + description: "The certificate store to manipulate.", + default: "MY", equal_to: ["TRUSTEDPUBLISHER", "TrustedPublisher", "CLIENTAUTHISSUER", "REMOTE DESKTOP", "ROOT", "TRUSTEDDEVICES", "WEBHOSTING", "CA", "AUTHROOT", "TRUSTEDPEOPLE", "MY", "SMARTCARDROOT", "TRUST", "DISALLOWED"] + + property :user_store, [TrueClass, FalseClass], + description: "Use the user store of the local machine store if set to false.", + default: false + + property :cert_path, String, + description: "" + + action :create do + description "Creates or updates a certificate." + + add_cert(OpenSSL::X509::Certificate.new(raw_source)) + end + + # acl_add is a modify-if-exists operation : not idempotent + action :acl_add do + description "Adds read-only entries to a certificate's private key ACL." + + if ::File.exist?(new_resource.source) + hash = "$cert.GetCertHashString()" + code_script = cert_script(false) + guard_script = cert_script(false) + else + # make sure we have no spaces in the hash string + hash = "\"#{new_resource.source.gsub(/\s/, '')}\"" + code_script = "" + guard_script = "" + end + code_script << acl_script(hash) + guard_script << cert_exists_script(hash) + + powershell_script "setting the acls on #{new_resource.source} in #{cert_location}\\#{new_resource.store_name}" do + guard_interpreter :powershell_script + convert_boolean_return true + code code_script + only_if guard_script + end + end + + action :delete do + description "Deletes a certificate." + + delete_cert + end + + action :fetch do + description "Fetches a certificate." + + cert_obj = fetch_cert + if cert_obj + show_or_store_cert(cert_obj) + else + Chef::Log.info("Certificate not found") + end + end + + action :verify do + description "" + + out = verify_cert + if !!out == out + out = out ? "Certificate is valid" : "Certificate not valid" + end + Chef::Log.info(out.to_s) + end + + action_class do + def add_cert(cert_obj) + store = ::Win32::Certstore.open(new_resource.store_name) + store.add(cert_obj) + end + + def delete_cert + store = ::Win32::Certstore.open(new_resource.store_name) + store.delete(new_resource.source) + end + + def fetch_cert + store = ::Win32::Certstore.open(new_resource.store_name) + store.get(new_resource.source) + end + + def verify_cert + store = ::Win32::Certstore.open(new_resource.store_name) + store.valid?(new_resource.source) + end + + def show_or_store_cert(cert_obj) + if new_resource.cert_path + export_cert(cert_obj, new_resource.cert_path) + if ::File.size(new_resource.cert_path) > 0 + Chef::Log.info("Certificate export in #{new_resource.cert_path}") + else + ::File.delete(new_resource.cert_path) + end + else + Chef::Log.info(cert_obj.display) + end + end + + def export_cert(cert_obj, cert_path) + out_file = ::File.new(cert_path, "w+") + case ::File.extname(cert_path) + when ".pem" + out_file.puts(cert_obj.to_pem) + when ".der" + out_file.puts(cert_obj.to_der) + when ".cer" + cert_out = powershell_out("openssl x509 -text -inform DER -in #{cert_obj.to_pem} -outform CER").stdout + out_file.puts(cert_out) + when ".crt" + cert_out = powershell_out("openssl x509 -text -inform DER -in #{cert_obj.to_pem} -outform CRT").stdout + out_file.puts(cert_out) + when ".pfx" + cert_out = powershell_out("openssl pkcs12 -export -nokeys -in #{cert_obj.to_pem} -outform PFX").stdout + out_file.puts(cert_out) + when ".p7b" + cert_out = powershell_out("openssl pkcs7 -export -nokeys -in #{cert_obj.to_pem} -outform P7B").stdout + out_file.puts(cert_out) + else + Chef::Log.info("Supported certificate format .pem, .der, .cer, .crt, .pfx and .p7b") + end + out_file.close + end + + def cert_location + @location ||= new_resource.user_store ? "CurrentUser" : "LocalMachine" + end + + def cert_script(persist) + cert_script = "$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2" + file = win_friendly_path(new_resource.source) + cert_script << " \"#{file}\"" + if ::File.extname(file.downcase) == ".pfx" + cert_script << ", \"#{new_resource.pfx_password}\"" + if persist && new_resource.user_store + cert_script << ", ([System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet)" + elsif persist + cert_script << ", ([System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::PersistKeySet -bor [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::MachineKeyset)" + end + end + cert_script << "\n" + end + + def cert_exists_script(hash) + <<-EOH + $hash = #{hash} + Test-Path "Cert:\\#{cert_location}\\#{new_resource.store_name}\\$hash" + EOH + end + + def within_store_script + inner_script = yield "$store" + <<-EOH + $store = New-Object System.Security.Cryptography.X509Certificates.X509Store "#{new_resource.store_name}", ([System.Security.Cryptography.X509Certificates.StoreLocation]::#{cert_location}) + $store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite) + #{inner_script} + $store.Close() + EOH + end + + def acl_script(hash) + return "" if new_resource.private_key_acl.nil? || new_resource.private_key_acl.empty? + # this PS came from http://blogs.technet.com/b/operationsguy/archive/2010/11/29/provide-access-to-private-keys-commandline-vs-powershell.aspx + # and from https://msdn.microsoft.com/en-us/library/windows/desktop/bb204778(v=vs.85).aspx + set_acl_script = <<-EOH + $hash = #{hash} + $storeCert = Get-ChildItem "cert:\\#{cert_location}\\#{new_resource.store_name}\\$hash" + if ($storeCert -eq $null) { throw 'no key exists.' } + $keyname = $storeCert.PrivateKey.CspKeyContainerInfo.UniqueKeyContainerName + if ($keyname -eq $null) { throw 'no private key exists.' } + if ($storeCert.PrivateKey.CspKeyContainerInfo.MachineKeyStore) + { + $fullpath = "$Env:ProgramData\\Microsoft\\Crypto\\RSA\\MachineKeys\\$keyname" + } + else + { + $currentUser = New-Object System.Security.Principal.NTAccount($Env:UserDomain, $Env:UserName) + $userSID = $currentUser.Translate([System.Security.Principal.SecurityIdentifier]).Value + $fullpath = "$Env:ProgramData\\Microsoft\\Crypto\\RSA\\$userSID\\$keyname" + } + EOH + new_resource.private_key_acl.each do |name| + set_acl_script << "$uname='#{name}'; icacls $fullpath /grant $uname`:RX\n" + end + set_acl_script + end + + def raw_source + ext = ::File.extname(new_resource.source) + convert_pem(ext, new_resource.source) + end + + def convert_pem(ext, source) + out = case ext + when ".crt", ".der" + powershell_out("openssl x509 -text -inform DER -in #{source} -outform PEM").stdout + when ".cer" + powershell_out("openssl x509 -text -inform DER -in #{source} -outform PEM").stdout + when ".pfx" + powershell_out("openssl pkcs12 -in #{source} -nodes -passin pass:#{new_resource.pfx_password}").stdout + when ".p7b" + powershell_out("openssl pkcs7 -print_certs -in #{source} -outform PEM").stdout + end + out = ::File.read(source) if out.nil? || out.empty? + format_raw_out(out) + end + + def format_raw_out(out) + begin_cert = "-----BEGIN CERTIFICATE-----" + end_cert = "-----END CERTIFICATE-----" + begin_cert + out[/#{begin_cert}(.*?)#{end_cert}/m, 1] + end_cert + end + end + + end + end +end diff --git a/lib/chef/resource/windows_share.rb b/lib/chef/resource/windows_share.rb new file mode 100644 index 0000000000..1f39130fbb --- /dev/null +++ b/lib/chef/resource/windows_share.rb @@ -0,0 +1,315 @@ +# +# Author:: Sölvi Páll Ásgeirsson () +# Author:: Richard Lavey (richard.lavey@calastone.com) +# Author:: Tim Smith (tsmith@chef.io) +# +# Copyright:: 2014-2017, Sölvi Páll Ásgeirsson. +# Copyright:: 2018, Chef Software, Inc. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +require "chef/resource" +require "chef/json_compat" + +class Chef + class Resource + class WindowsShare < Chef::Resource + preview_resource true + resource_name :windows_share + + description "Use the windows_share resource to create, modify and remove Windows shares." + introduced "14.6" + + # Specifies a name for the SMB share. The name may be composed of any valid file name characters, but must be less than 80 characters long. The names pipe and mailslot are reserved for use by the computer. + property :share_name, String, + description: "The share to assign to the share.", + name_property: true + + # Specifies the path of the location of the folder to share. The path must be fully qualified. Relative paths or paths that contain wildcard characters are not permitted. + property :path, String, + description: "The path of the location of the folder to share. Required when creating. If the share already exists on a different path then it is deleted and re-created." + + # Specifies an optional description of the SMB share. A description of the share is displayed by running the Get-SmbShare cmdlet. The description may not contain more than 256 characters. + property :description, String, + description: "The description to be applied to the share.", + default: "" + + # Specifies which accounts are granted full permission to access the share. Use a comma-separated list to specify multiple accounts. An account may not be specified more than once in the FullAccess, ChangeAccess, or ReadAccess parameter lists, but may be specified once in the FullAccess, ChangeAccess, or ReadAccess parameter list and once in the NoAccess parameter list. + property :full_users, Array, + description: "The users which should have 'Full control' permissions on the share..", + default: [], coerce: proc { |u| u.sort } + + # Specifies which users are granted modify permission to access the share + property :change_users, Array, + description: "The users which should have 'modify' permission on the share.", + default: [], coerce: proc { |u| u.sort } + + # Specifies which users are granted read permission to access the share. Multiple users can be specified by supplying a comma-separated list. + property :read_users, Array, + description: "The users which should have 'read' permission on the share.", + default: [], coerce: proc { |u| u.sort } + + # Specifies the lifetime of the new SMB share. A temporary share does not persist beyond the next restart of the computer. By default, new SMB shares are persistent, and non-temporary. + property :temporary, [TrueClass, FalseClass], + description: "The lifetime of the new SMB share. A temporary share does not persist beyond the next restart of the computer.", + default: false + + # Specifies the scope name of the share. + property :scope_name, String, + description: "The scope name of the share.", + default: "*" + + # Specifies the continuous availability time-out for the share. + property :ca_timeout, Integer, + description: "The continuous availability time-out for the share.", + default: 0 + + # Indicates that the share is continuously available. + property :continuously_available, [TrueClass, FalseClass], + description: "Indicates that the share is continuously available.", + default: false + + # Specifies the caching mode of the offline files for the SMB share. + # property :caching_mode, String, equal_to: %w(None Manual Documents Programs BranchCache) + + # Specifies the maximum number of concurrently connected users that the new SMB share may accommodate. If this parameter is set to zero (0), then the number of users is unlimited. + property :concurrent_user_limit, Integer, + description: "The maximum number of concurrently connected users the share can accommodate.", + default: 0 + + # Indicates that the share is encrypted. + property :encrypt_data, [TrueClass, FalseClass], + description: "Indicates that the share is encrypted.", + default: false + + # Specifies which files and folders in the SMB share are visible to users. AccessBased: SMB does not the display the files and folders for a share to a user unless that user has rights to access the files and folders. By default, access-based enumeration is disabled for new SMB shares. Unrestricted: SMB displays files and folders to a user even when the user does not have permission to access the items. + # property :folder_enumeration_mode, String, equal_to: %(AccessBased Unrestricted) + + include Chef::Mixin::PowershellOut + + load_current_value do |desired| + # this command selects individual objects because EncryptData & CachingMode have underlying + # types that get converted to their Integer values by ConvertTo-Json & we need to make sure + # those get written out as strings + share_state_cmd = "Get-SmbShare -Name '#{desired.share_name}' | Select-Object Name,Path, Description, Temporary, CATimeout, ContinuouslyAvailable, ConcurrentUserLimit, EncryptData | ConvertTo-Json" + + Chef::Log.debug("Running '#{share_state_cmd}' to determine share state'") + ps_results = powershell_out(share_state_cmd) + + # detect a failure without raising and then set current_resource to nil + if ps_results.error? + Chef::Log.debug("Error fetching share state: #{ps_results.stderr}") + current_value_does_not_exist! + end + + Chef::Log.debug("The Get-SmbShare results were #{ps_results.stdout}") + results = Chef::JSONCompat.from_json(ps_results.stdout) + + path results["Path"] + description results["Description"] + temporary results["Temporary"] + ca_timeout results["CATimeout"] + continuously_available results["ContinuouslyAvailable"] + # caching_mode results['CachingMode'] + concurrent_user_limit results["ConcurrentUserLimit"] + encrypt_data results["EncryptData"] + # folder_enumeration_mode results['FolderEnumerationMode'] + + perm_state_cmd = %{Get-SmbShareAccess -Name "#{desired.share_name}" | Select-Object AccountName,AccessControlType,AccessRight | ConvertTo-Json} + + Chef::Log.debug("Running '#{perm_state_cmd}' to determine share permissions state'") + ps_perm_results = powershell_out(perm_state_cmd) + + # we raise here instead of warning like above because we'd only get here if the above Get-SmbShare + # command was successful and that continuing would leave us with 1/2 known state + raise "Could not determine #{desired.share_name} share permissions by running '#{perm_state_cmd}'" if ps_perm_results.error? + + Chef::Log.debug("The Get-SmbShareAccess results were #{ps_perm_results.stdout}") + + f_users, c_users, r_users = parse_permissions(ps_perm_results.stdout) + + full_users f_users + change_users c_users + read_users r_users + end + + def after_created + raise "The windows_share resource relies on PowerShell cmdlets not present in Windows releases prior to 8/2012. Cannot continue!" if node["platform_version"].to_f < 6.3 + end + +# given the string output of Get-SmbShareAccess parse out +# arrays of full access users, change users, and read only users + def parse_permissions(results_string) + json_results = Chef::JSONCompat.from_json(results_string) + json_results = [json_results] unless json_results.is_a?(Array) # single result is not an array + + f_users = [] + c_users = [] + r_users = [] + + json_results.each do |perm| + next unless perm["AccessControlType"] == 0 # allow + case perm["AccessRight"] + when 0 then f_users << stripped_account(perm["AccountName"]) # 0 full control + when 1 then c_users << stripped_account(perm["AccountName"]) # 1 == change + when 2 then r_users << stripped_account(perm["AccountName"]) # 2 == read + end + end + [f_users, c_users, r_users] + end + +# local names are returned from Get-SmbShareAccess in the full format MACHINE\\NAME +# but users of this resource would simply say NAME so we need to strip the values for comparison + def stripped_account(name) + name.slice!("#{node['hostname']}\\") + name + end + + action :create do + description "Create and modify Windows shares." + + # we do this here instead of requiring the property because :delete doesn't need path set + raise "No path property set" unless new_resource.path + + converge_if_changed do + # you can't actually change the path so you have to delete the old share first + delete_share if different_path? + + # powershell cmdlet for create is different than updates + if current_resource.nil? + Chef::Log.debug("The current resource is nil so we will create a new share") + create_share + else + Chef::Log.debug("The current resource was not nil so we will update an existing share") + update_share + end + + # creating the share does not set permissions so we need to update + update_permissions + end + end + + action :delete do + description "Delete an existing Windows share." + + if current_resource.nil? + Chef::Log.debug("#{new_resource.share_name} does not exist - nothing to do") + else + converge_by("delete #{new_resource.share_name}") do + delete_share + end + end + end + + action_class do + def different_path? + return false if current_resource.nil? # going from nil to something isn't different for our concerns + return false if current_resource.path == new_resource.path + true + end + + def delete_share + delete_command = "Remove-SmbShare -Name '#{new_resource.share_name}' -Force" + + Chef::Log.debug("Running '#{delete_command}' to remove the share") + powershell_out!(delete_command) + end + + def update_share + update_command = "Set-SmbShare -Name '#{new_resource.share_name}' -Description '#{new_resource.description}' -Force" + + Chef::Log.debug("Running '#{update_command}' to update the share") + powershell_out!(update_command) + end + + def create_share + raise "#{new_resource.path} is missing or not a directory. Shares cannot be created if the path doesn't first exist." unless ::File.directory? new_resource.path + + share_cmd = "New-SmbShare -Name '#{new_resource.share_name}' -Path '#{new_resource.path}' -Description '#{new_resource.description}' -ConcurrentUserLimit #{new_resource.concurrent_user_limit} -CATimeout #{new_resource.ca_timeout} -EncryptData:#{bool_string(new_resource.encrypt_data)} -ContinuouslyAvailable:#{bool_string(new_resource.continuously_available)}" + share_cmd << " -ScopeName #{new_resource.scope_name}" unless new_resource.scope_name == "*" # passing * causes the command to fail + share_cmd << " -Temporary:#{bool_string(new_resource.temporary)}" if new_resource.temporary # only set true + + Chef::Log.debug("Running '#{share_cmd}' to create the share") + powershell_out!(share_cmd) + end + + # determine what users in the current state don't exist in the desired state + # users/groups will have their permissions updated with the same command that + # sets it, but removes must be performed with Revoke-SmbShareAccess + def users_to_revoke + @users_to_revoke ||= begin + # if the resource doesn't exist then nothing needs to be revoked + if current_resource.nil? + [] + else # if it exists then calculate the current to new resource diffs + (current_resource.full_users + current_resource.change_users + current_resource.read_users) - (new_resource.full_users + new_resource.change_users + new_resource.read_users) + end + end + end + + # update existing permissions on a share + def update_permissions + # revoke any users that had something, but now has nothing + revoke_user_permissions(users_to_revoke) unless users_to_revoke.empty? + + # set permissions for each of the permission types + %w{full read change}.each do |perm_type| + # set permissions for a brand new share OR + # update permissions if the current state and desired state differ + next unless permissions_need_update?(perm_type) + grant_command = "Grant-SmbShareAccess -Name '#{new_resource.share_name}' -AccountName \"#{new_resource.send("#{perm_type}_users").join('","')}\" -Force -AccessRight #{perm_type}" + + Chef::Log.debug("Running '#{grant_command}' to update the share permissions") + powershell_out!(grant_command) + end + end + + # determine if permissions need to be updated. + # Brand new share with no permissions defined: no + # Brand new share with permissions defined: yes + # Existing share with differing permissions: yes + # + # @param [String] type the permissions type (Full, Read, or Change) + def permissions_need_update?(type) + property_name = "#{type}_users" + + # brand new share, but nothing to set + return false if current_resource.nil? && new_resource.send(property_name).empty? + + # brand new share with new permissions to set + return true if current_resource.nil? && !new_resource.send(property_name).empty? + + # there's a difference between the current and desired state + return true unless (new_resource.send(property_name) - current_resource.send(property_name)).empty? + + # anything else + false + end + + def revoke_user_permissions(users) + revoke_command = "Revoke-SmbShareAccess -Name '#{new_resource.share_name}' -AccountName \"#{users.join(',')}\" -Force" + Chef::Log.debug("Running '#{revoke_command}' to revoke share permissions") + powershell_out!(revoke_command) + end + + # convert True/False into "$True" & "$False" + def bool_string(bool) + # bool ? 1 : 0 + bool ? "$true" : "$false" + end + end + + end + end +end diff --git a/lib/chef/resources.rb b/lib/chef/resources.rb index 6324ce5b66..805d278cc6 100644 --- a/lib/chef/resources.rb +++ b/lib/chef/resources.rb @@ -130,6 +130,7 @@ require "chef/resource/powershell_package" require "chef/resource/msu_package" require "chef/resource/windows_ad_join" require "chef/resource/windows_auto_run" +require "chef/resource/windows_certificate" require "chef/resource/windows_feature" require "chef/resource/windows_feature_dism" require "chef/resource/windows_feature_powershell" @@ -138,6 +139,7 @@ require "chef/resource/windows_pagefile" require "chef/resource/windows_path" require "chef/resource/windows_printer" require "chef/resource/windows_printer_port" +require "chef/resource/windows_share" require "chef/resource/windows_shortcut" require "chef/resource/windows_task" require "chef/resource/windows_workgroup" -- cgit v1.2.1