vagrant and chef install everything

This commit is contained in:
2019-09-02 16:48:23 -04:00
parent 4fb554add5
commit f1809bef83
268 changed files with 16021 additions and 7 deletions

View File

@ -0,0 +1,53 @@
#
# Author:: Seth Chisamore (<schisamo@chef.io>)
# Cookbook:: windows
# Library:: powershell_helper
#
# Copyright:: 2011-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/mixin/shell_out'
module Powershell
module Helper
include Chef::Mixin::ShellOut
def powershell_installed?
!powershell_version.nil?
end
def interpreter
# force 64-bit powershell from 32-bit ruby process
if ::File.exist?("#{ENV['WINDIR']}\\sysnative\\WindowsPowershell\\v1.0\\powershell.exe")
"#{ENV['WINDIR']}\\sysnative\\WindowsPowershell\\v1.0\\powershell.exe"
elsif ::File.exist?("#{ENV['WINDIR']}\\system32\\WindowsPowershell\\v1.0\\powershell.exe")
"#{ENV['WINDIR']}\\system32\\WindowsPowershell\\v1.0\\powershell.exe"
else
'powershell.exe'
end
end
def powershell_version
cmd = shell_out("#{interpreter} -InputFormat none -Command \"& echo $PSVersionTable.psversion.major\"")
if cmd.stdout.empty? # PowerShell 1.0 doesn't have a $PSVersionTable
1
else
Regexp.last_match(1).to_i if cmd.stdout =~ /^(\d+)/
end
rescue Errno::ENOENT
nil
end
end
end

View File

@ -0,0 +1,356 @@
#
# Author:: Doug MacEachern (<dougm@vmware.com>)
# Author:: Seth Chisamore (<schisamo@chef.io>)
# Author:: Paul Morton (<pmorton@biaprotect.com>)
# Cookbook:: windows
# Library:: registry_helper
#
# Copyright:: 2010-2017, VMware, Inc.
# Copyright:: 2011-2018, Chef Software, Inc.
# Copyright:: 2011-2017, Business Intelligence Associates, 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.
#
if RUBY_PLATFORM =~ /mswin|mingw32|windows/
require 'win32/registry'
require_relative 'wmi_helper'
end
module Windows
module RegistryHelper
@@native_registry_constant = if ENV['PROCESSOR_ARCHITECTURE'] == 'AMD64' ||
ENV['PROCESSOR_ARCHITEW6432'] == 'AMD64'
0x0100
else
0x0200
end
def get_hive_name(path)
Chef::Log.debug('Resolving registry shortcuts to full names')
reg_path = path.split('\\')
hive_name = reg_path.shift
hkey = {
'HKLM' => 'HKEY_LOCAL_MACHINE',
'HKCU' => 'HKEY_CURRENT_USER',
'HKU' => 'HKEY_USERS',
}[hive_name] || hive_name
Chef::Log.debug("Hive resolved to #{hkey}")
hkey
end
def get_hive(path)
Chef::Log.debug("Getting hive for #{path}")
reg_path = path.split('\\')
hive_name = reg_path.shift
hkey = get_hive_name(path)
hive = {
'HKEY_LOCAL_MACHINE' => ::Win32::Registry::HKEY_LOCAL_MACHINE,
'HKEY_USERS' => ::Win32::Registry::HKEY_USERS,
'HKEY_CURRENT_USER' => ::Win32::Registry::HKEY_CURRENT_USER,
}[hkey]
unless hive
Chef::Application.fatal!("Unsupported registry hive '#{hive_name}'")
end
Chef::Log.debug("Registry hive resolved to #{hkey}")
hive
end
def unload_hive(path)
hive = get_hive(path)
if hive == ::Win32::Registry::HKEY_USERS
reg_path = path.split('\\')
priv = Chef::WindowsPrivileged.new
begin
priv.reg_unload_key(reg_path[1])
rescue
end
end
end
def set_value(mode, path, values, type = nil)
hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
key_name = reg_path.join('\\')
Chef::Log.debug("Creating #{path}")
create_key(path) unless key_exists?(path, true)
hive.send(mode, key_name, ::Win32::Registry::KEY_ALL_ACCESS | @@native_registry_constant) do |reg|
changed_something = false
values.each do |k, val|
key = k.to_s # wtf. avoid "can't modify frozen string" in win32/registry.rb
cur_val = nil
begin
cur_val = reg[key]
rescue
# subkey does not exist (ok)
end
next unless cur_val != val
Chef::Log.debug("setting #{key}=#{val}")
type = :string if type.nil?
reg_type = {
binary: ::Win32::Registry::REG_BINARY,
string: ::Win32::Registry::REG_SZ,
multi_string: ::Win32::Registry::REG_MULTI_SZ,
expand_string: ::Win32::Registry::REG_EXPAND_SZ,
dword: ::Win32::Registry::REG_DWORD,
dword_big_endian: ::Win32::Registry::REG_DWORD_BIG_ENDIAN,
qword: ::Win32::Registry::REG_QWORD,
}[type]
reg.write(key, reg_type, val)
ensure_hive_unloaded(hive_loaded)
changed_something = true
end
return changed_something
end
false
end
def get_value(path, value)
hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
key = reg_path.join('\\')
hive.open(key, ::Win32::Registry::KEY_ALL_ACCESS | @@native_registry_constant) do |reg|
begin
return reg[value]
rescue
return nil
ensure
ensure_hive_unloaded(hive_loaded)
end
end
end
def get_values(path)
hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
key = reg_path.join('\\')
hive.open(key, ::Win32::Registry::KEY_ALL_ACCESS | @@native_registry_constant) do |reg|
values = []
begin
reg.each_value do |name, type, data|
values << [name, type, data]
end
rescue
ensure
ensure_hive_unloaded(hive_loaded)
end
values
end
end
def delete_value(path, values)
hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
key = reg_path.join('\\')
Chef::Log.debug("Deleting values in #{path}")
hive.open(key, ::Win32::Registry::KEY_ALL_ACCESS | @@native_registry_constant) do |reg|
values.each_key do |key|
name = key.to_s
# Ensure delete operation is idempotent.
if value_exists?(path, key)
Chef::Log.debug("Deleting value #{name} in #{path}")
reg.delete_value(name)
else
Chef::Log.debug("Value #{name} in #{path} does not exist, skipping.")
end
end
end
end
def create_key(path)
hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
key = reg_path.join('\\')
Chef::Log.debug("Creating registry key #{path}")
hive.create(key)
end
def value_exists?(path, value)
if key_exists?(path, true)
hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
key = reg_path.join('\\')
Chef::Log.debug("Attempting to open #{key}")
Chef::Log.debug("Native Constant #{@@native_registry_constant}")
Chef::Log.debug("Hive #{hive}")
hive.open(key, ::Win32::Registry::KEY_READ | @@native_registry_constant) do |reg|
begin
rtn_value = reg[value]
return true
rescue
return false
ensure
ensure_hive_unloaded(hive_loaded)
end
end
end
false
end
# TODO: Does not load user registry...
def key_exists?(path, load_hive = false)
if load_hive
hive, reg_path, hive_name, root_key, hive_loaded = get_reg_path_info(path)
key = reg_path.join('\\')
else
hive = get_hive(path)
reg_path = path.split('\\')
hive_name = reg_path.shift
root_key = reg_path[0]
key = reg_path.join('\\')
hive_loaded = false
end
begin
hive.open(key, ::Win32::Registry::Constants::KEY_READ | @@native_registry_constant)
return true
rescue
return false
ensure
ensure_hive_unloaded(hive_loaded)
end
end
def get_user_hive_location(sid)
reg_key = "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\#{sid}"
Chef::Log.debug("Looking for profile at #{reg_key}")
if key_exists?(reg_key)
return get_value(reg_key, 'ProfileImagePath')
else
return nil
end
end
def resolve_user_to_sid(username)
user_query = execute_wmi_query("select * from Win32_UserAccount where Name='#{username}'")
sid = nil
user_query.each do |user|
sid = wmi_object_property(user, 'sid')
break
end
Chef::Log.debug("Resolved user SID to #{sid}")
sid
rescue
nil
end
def hive_loaded?(path)
hive = get_hive(path)
reg_path = path.split('\\')
hive_name = reg_path.shift
user_hive = path[0]
if user_hive?(hive)
return key_exists?("#{hive_name}\\#{user_hive}")
else
return true
end
end
def user_hive?(hive)
hive == ::Win32::Registry::HKEY_USERS
end
def get_reg_path_info(path)
hive = get_hive(path)
reg_path = path.split('\\')
hive_name = reg_path.shift
root_key = reg_path[0]
hive_loaded = false
if user_hive?(hive) && !key_exists?("#{hive_name}\\#{root_key}")
reg_path, hive_loaded = load_user_hive(hive, reg_path, root_key)
root_key = reg_path[0]
Chef::Log.debug("Resolved user (#{path}) to (#{reg_path.join('/')})")
end
[hive, reg_path, hive_name, root_key, hive_loaded]
end
def load_user_hive(hive, reg_path, user_hive)
Chef::Log.debug("Reg Path #{reg_path}")
# See if the hive is loaded. Logged in users will have a key that is named their SID
# if the user has specified the a path by SID and the user is logged in, this function
# should not be executed.
if user_hive?(hive) && !key_exists?("HKU\\#{user_hive}")
Chef::Log.debug('The user is not logged in and has not been specified by SID')
sid = resolve_user_to_sid(user_hive)
Chef::Log.debug("User SID resolved to (#{sid})")
# Now that the user has been resolved to a SID, check and see if the hive exists.
# If this exists by SID, the user is logged in and we should use that key.
# TODO: Replace the username with the sid and send it back because the username
# does not exist as the key location.
load_reg = false
if key_exists?("HKU\\#{sid}")
reg_path[0] = sid # use the active profile (user is logged on)
Chef::Log.debug("HKEY_USERS Mapped: #{user_hive} -> #{sid}")
else
Chef::Log.debug('User is not logged in')
load_reg = true
end
# The user is not logged in, so we should load the registry from disk
if load_reg
profile_path = get_user_hive_location(sid)
unless profile_path.nil?
ntuser_dat = "#{profile_path}\\NTUSER.DAT"
if ::File.exist?(ntuser_dat)
priv = Chef::WindowsPrivileged.new
if priv.reg_load_key(sid, ntuser_dat)
Chef::Log.debug("RegLoadKey(#{sid}, #{user_hive}, #{ntuser_dat})")
reg_path[0] = sid
else
Chef::Log.debug("Failed RegLoadKey(#{sid}, #{user_hive}, #{ntuser_dat})")
end
end
end
end
end
[reg_path, load_reg]
end
private
def ensure_hive_unloaded(hive_loaded = false)
if hive_loaded
Chef::Log.debug('Hive was loaded, we really should unload it')
unload_hive(path)
end
end
end
end
module Registry
module_function # rubocop: disable Lint/UselessAccessModifier
extend Windows::RegistryHelper
end

View File

@ -0,0 +1,189 @@
#
# Author:: Seth Chisamore (<schisamo@chef.io>)
# Cookbook:: windows
# Library:: version
#
# Copyright:: 2011-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.
#
if RUBY_PLATFORM =~ /mswin|mingw32|windows/
require_relative 'wmi_helper'
end
module Windows
class Version
# http://msdn.microsoft.com/en-us/library/ms724833(v=vs.85).aspx
# Suite Masks
# Microsoft BackOffice components are installed.
VER_SUITE_BACKOFFICE = 0x00000004 unless defined?(VER_SUITE_BACKOFFICE)
# Windows Server 2008 Datacenter, Windows Server 2003, Datacenter Edition, or Windows 2000 Datacenter Server is installed.
VER_SUITE_DATACENTER = 0x00000080 unless defined?(VER_SUITE_DATACENTER)
# Windows Server 2008 Enterprise, Windows Server 2003, Enterprise Edition, or Windows 2000 Advanced Server is installed. Refer to the Remarks section for more information about this bit flag.
VER_SUITE_ENTERPRISE = 0x00000002 unless defined?(VER_SUITE_ENTERPRISE)
# Windows XP Embedded is installed.
VER_SUITE_EMBEDDEDNT = 0x00000040 unless defined?(VER_SUITE_EMBEDDEDNT)
# Windows Vista Home Premium, Windows Vista Home Basic, or Windows XP Home Edition is installed.
VER_SUITE_PERSONAL = 0x00000200 unless defined?(VER_SUITE_PERSONAL)
# Remote Desktop is supported, but only one interactive session is supported. This value is set unless the system is running in application server mode.
VER_SUITE_SINGLEUSERTS = 0x00000100 unless defined?(VER_SUITE_SINGLEUSERTS)
# Microsoft Small Business Server was once installed on the system, but may have been upgraded to another version of Windows. Refer to the Remarks section for more information about this bit flag.
VER_SUITE_SMALLBUSINESS = 0x00000001 unless defined?(VER_SUITE_SMALLBUSINESS)
# Microsoft Small Business Server is installed with the restrictive client license in force. Refer to the Remarks section for more information about this bit flag.
VER_SUITE_SMALLBUSINESS_RESTRICTED = 0x00000020 unless defined?(VER_SUITE_SMALLBUSINESS_RESTRICTED)
# Terminal Services is installed. This value is always set.
# If VER_SUITE_TERMINAL is set but VER_SUITE_SINGLEUSERTS is not set, the system is running in application server mode.
VER_SUITE_TERMINAL = 0x00000010 unless defined?(VER_SUITE_TERMINAL)
# Windows Home Server is installed.
VER_SUITE_WH_SERVER = 0x00008000 unless defined?(VER_SUITE_WH_SERVER)
# Product Type
# The system is a domain controller and the operating system is Windows Server 2012, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, or Windows 2000 Server.
VER_NT_DOMAIN_CONTROLLER = 0x0000002 unless defined?(VER_NT_DOMAIN_CONTROLLER)
# The operating system is Windows Server 2012, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, or Windows 2000 Server.
# Note that a server that is also a domain controller is reported as VER_NT_DOMAIN_CONTROLLER, not VER_NT_SERVER.
VER_NT_SERVER = 0x0000003 unless defined?(VER_NT_SERVER)
# The operating system is Windows 7, Windows Vista, Windows XP Professional, Windows XP Home Edition, or Windows 2000 Professional.
VER_NT_WORKSTATION = 0x0000001 unless defined?(VER_NT_WORKSTATION)
# http://msdn.microsoft.com/en-us/library/ms724358(v=vs.85).aspx
SKU = {
0x00000006 => { ms_const: 'PRODUCT_BUSINESS', name: 'Business' },
0x00000010 => { ms_const: 'PRODUCT_BUSINESS_N', name: 'Business N' },
0x00000012 => { ms_const: 'PRODUCT_CLUSTER_SERVER', name: 'HPC Edition' },
0x00000008 => { ms_const: 'PRODUCT_DATACENTER_SERVER', name: 'Server Datacenter (full installation)' },
0x0000000C => { ms_const: 'PRODUCT_DATACENTER_SERVER_CORE', name: 'Server Datacenter (core installation)' },
0x00000027 => { ms_const: 'PRODUCT_DATACENTER_SERVER_CORE_V', name: 'Server Datacenter without Hyper-V (core installation)' },
0x00000025 => { ms_const: 'PRODUCT_DATACENTER_SERVER_V', name: 'Server Datacenter without Hyper-V (full installation)' },
0x00000004 => { ms_const: 'PRODUCT_ENTERPRISE', name: 'Enterprise' },
0x00000046 => { ms_const: 'PRODUCT_ENTERPRISE_E', name: 'Not supported' },
0x0000001B => { ms_const: 'PRODUCT_ENTERPRISE_N', name: 'Enterprise N' },
0x0000000A => { ms_const: 'PRODUCT_ENTERPRISE_SERVER', name: 'Server Enterprise (full installation)' },
0x0000000E => { ms_const: 'PRODUCT_ENTERPRISE_SERVER_CORE', name: 'Server Enterprise (core installation)' },
0x00000029 => { ms_const: 'PRODUCT_ENTERPRISE_SERVER_CORE_V', name: 'Server Enterprise without Hyper-V (core installation)' },
0x0000000F => { ms_const: 'PRODUCT_ENTERPRISE_SERVER_IA64', name: 'Server Enterprise for Itanium-based Systems' },
0x00000026 => { ms_const: 'PRODUCT_ENTERPRISE_SERVER_V', name: 'Server Enterprise without Hyper-V (full installation)' },
0x00000002 => { ms_const: 'PRODUCT_HOME_BASIC', name: 'Home Basic' },
0x00000043 => { ms_const: 'PRODUCT_HOME_BASIC_E', name: 'Not supported' },
0x00000005 => { ms_const: 'PRODUCT_HOME_BASIC_N', name: 'Home Basic N' },
0x00000003 => { ms_const: 'PRODUCT_HOME_PREMIUM', name: 'Home Premium' },
0x00000044 => { ms_const: 'PRODUCT_HOME_PREMIUM_E', name: 'Not supported' },
0x0000001A => { ms_const: 'PRODUCT_HOME_PREMIUM_N', name: 'Home Premium N' },
0x0000002A => { ms_const: 'PRODUCT_HYPERV', name: 'Microsoft Hyper-V Server' },
0x0000001E => { ms_const: 'PRODUCT_MEDIUMBUSINESS_SERVER_MANAGEMENT', name: 'Windows Essential Business Server Management Server' },
0x00000020 => { ms_const: 'PRODUCT_MEDIUMBUSINESS_SERVER_MESSAGING', name: 'Windows Essential Business Server Messaging Server' },
0x0000001F => { ms_const: 'PRODUCT_MEDIUMBUSINESS_SERVER_SECURITY', name: 'Windows Essential Business Server Security Server' },
0x00000030 => { ms_const: 'PRODUCT_PROFESSIONAL', name: 'Professional' },
0x00000045 => { ms_const: 'PRODUCT_PROFESSIONAL_E', name: 'Not supported' },
0x00000031 => { ms_const: 'PRODUCT_PROFESSIONAL_N', name: 'Professional N' },
0x00000067 => { ms_const: 'PRODUCT_PROFESSIONAL_WMC', name: 'Professional with Media Center' },
0x00000018 => { ms_const: 'PRODUCT_SERVER_FOR_SMALLBUSINESS', name: 'Windows Server 2008 for Windows Essential Server Solutions' },
0x00000023 => { ms_const: 'PRODUCT_SERVER_FOR_SMALLBUSINESS_V', name: 'Windows Server 2008 without Hyper-V for Windows Essential Server Solutions' },
0x00000021 => { ms_const: 'PRODUCT_SERVER_FOUNDATION', name: 'Server Foundation' },
0x00000022 => { ms_const: 'PRODUCT_HOME_PREMIUM_SERVER', name: 'Windows Home Server 2011' },
0x00000032 => { ms_const: 'PRODUCT_SB_SOLUTION_SERVER', name: 'Windows Small Business Server 2011 Essentials' },
0x00000013 => { ms_const: 'PRODUCT_HOME_SERVER', name: 'Windows Storage Server 2008 R2 Essentials' },
0x00000009 => { ms_const: 'PRODUCT_SMALLBUSINESS_SERVER', name: 'Windows Small Business Server' },
0x00000038 => { ms_const: 'PRODUCT_SOLUTION_EMBEDDEDSERVER', name: 'Windows MultiPoint Server' },
0x00000007 => { ms_const: 'PRODUCT_STANDARD_SERVER', name: 'Server Standard (full installation)' },
0x0000000D => { ms_const: 'PRODUCT_STANDARD_SERVER_CORE', name: 'Server Standard (core installation)' },
0x00000028 => { ms_const: 'PRODUCT_STANDARD_SERVER_CORE_V', name: 'Server Standard without Hyper-V (core installation)' },
0x00000024 => { ms_const: 'PRODUCT_STANDARD_SERVER_V', name: 'Server Standard without Hyper-V (full installation)' },
0x0000000B => { ms_const: 'PRODUCT_STARTER', name: 'Starter' },
0x00000042 => { ms_const: 'PRODUCT_STARTER_E', name: 'Not supported' },
0x0000002F => { ms_const: 'PRODUCT_STARTER_N', name: 'Starter N' },
0x00000017 => { ms_const: 'PRODUCT_STORAGE_ENTERPRISE_SERVER', name: 'Storage Server Enterprise' },
0x00000014 => { ms_const: 'PRODUCT_STORAGE_EXPRESS_SERVER', name: 'Storage Server Express' },
0x00000015 => { ms_const: 'PRODUCT_STORAGE_STANDARD_SERVER', name: 'Storage Server Standard' },
0x00000016 => { ms_const: 'PRODUCT_STORAGE_WORKGROUP_SERVER', name: 'Storage Server Workgroup' },
0x00000000 => { ms_const: 'PRODUCT_UNDEFINED', name: 'An unknown product' },
0x00000001 => { ms_const: 'PRODUCT_ULTIMATE', name: 'Ultimate' },
0x00000047 => { ms_const: 'PRODUCT_ULTIMATE_E', name: 'Not supported' },
0x0000001C => { ms_const: 'PRODUCT_ULTIMATE_N', name: 'Ultimate N' },
0x00000011 => { ms_const: 'PRODUCT_WEB_SERVER', name: 'Web Server (full installation)' },
0x0000001D => { ms_const: 'PRODUCT_WEB_SERVER_CORE', name: 'Web Server (core installation)' },
}.freeze unless defined?(SKU)
attr_reader :major_version, :minor_version, :build_number, :service_pack_major_version, :service_pack_minor_version
attr_reader :version, :product_type, :product_suite, :sku
def initialize
unless RUBY_PLATFORM =~ /mswin|mingw32|windows/
raise NotImplementedError, 'only valid on Windows platform'
end
@version, @product_type, @product_suite, @sku, @service_pack_major_version, @service_pack_minor_version = get_os_info
@major_version, @minor_version, @build_number = version.split('.').map(&:to_i)
end
WIN_VERSIONS = {
'Windows 10' => { major: 10, minor: 0, callable: -> { @product_type != VER_NT_WORKSTATION } },
'Windows Server 2012 R2' => { major: 6, minor: 3, callable: -> { @product_type != VER_NT_WORKSTATION } },
'Windows 8' => { major: 6, minor: 2, callable: -> { @product_type == VER_NT_WORKSTATION } },
'Windows Server 2012' => { major: 6, minor: 2, callable: -> { @product_type != VER_NT_WORKSTATION } },
'Windows 7' => { major: 6, minor: 1, callable: -> { @product_type == VER_NT_WORKSTATION } },
'Windows Server 2008 R2' => { major: 6, minor: 1, callable: -> { @product_type != VER_NT_WORKSTATION } },
'Windows Server 2008' => { major: 6, minor: 0, callable: -> { @product_type != VER_NT_WORKSTATION } },
'Windows Vista' => { major: 6, minor: 0, callable: -> { @product_type == VER_NT_WORKSTATION } },
'Windows Home Server' => { major: 5, minor: 2, callable: -> { (@product_suite & VER_SUITE_WH_SERVER) == VER_SUITE_WH_SERVER } },
'Windows XP' => { major: 5, minor: 1 },
'Windows 2000' => { major: 5, minor: 0 },
}.freeze unless defined?(WIN_VERSIONS)
marketing_names = []
# General Windows checks
WIN_VERSIONS.each do |k, v|
method_name = "#{k.gsub(/\s/, '_').downcase}?"
define_method(method_name) do
(@major_version == v[:major]) &&
(@minor_version == v[:minor]) &&
(v[:callable] ? v[:callable].call : true)
end
marketing_names << [k, method_name]
end
define_method(:marketing_name) do
marketing_names.each do |mn|
break mn[0] if send(mn[1])
end
end
# Server Type checks
%w( core full datacenter ).each do |m|
define_method("server_#{m}?") do
if @sku
!(SKU[@sku][:name] =~ /#{m}/i).nil?
else
false
end
end
end
private
# query WMI Win32_OperatingSystem for required OS info
def get_os_info
cols = %w( Version ProductType OSProductSuite OperatingSystemSKU ServicePackMajorVersion ServicePackMinorVersion )
os_info = execute_wmi_query('select * from Win32_OperatingSystem').each.next
cols.map do |c|
begin
wmi_object_property(os_info, c)
rescue # OperatingSystemSKU doesn't exist in all versions of Windows
nil
end
end
end
end
end

View File

@ -0,0 +1,93 @@
#
# Cookbook:: windows
# Library:: version_helper
# Author:: Baptiste Courtois (<b.courtois@criteo.com>)
#
# Copyright:: 2015-2017, Criteo
#
# 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.
#
module Windows
# Module based on windows ohai kernel.cs_info providing version helpers
module VersionHelper
# Module referencing CORE SKU contants from product type
# see. https://msdn.microsoft.com/windows/desktop/ms724358#PRODUCT_DATACENTER_SERVER_CORE
# n.b. Prefix - PRODUCT_ - and suffix - _CORE- have been removed
module CoreSKU
# Server Datacenter Core
DATACENTER_SERVER = 0x0C unless constants.include?(:DATACENTER_SERVER)
# Server Datacenter without Hyper-V Core
DATACENTER_SERVER_V = 0x27 unless constants.include?(:DATACENTER_SERVER_V)
# Server Enterprise Core
ENTERPRISE_SERVER = 0x0E unless constants.include?(:ENTERPRISE_SERVER)
# Server Enterprise without Hyper-V Core
ENTERPRISE_SERVER_V = 0x29 unless constants.include?(:ENTERPRISE_SERVER_V)
# Server Standard Core
STANDARD_SERVER = 0x0D unless constants.include?(:STANDARD_SERVER)
# Server Standard without Hyper-V Core
STANDARD_SERVER_V = 0x28 unless constants.include?(:STANDARD_SERVER_V)
# Small Business Server Premium Core
PRODUCT_SMALLBUSINESS_SERVER_PREMIUM_CORE = 0x3F unless constants.include?(:PRODUCT_SMALLBUSINESS_SERVER_PREMIUM_CORE)
# Server Solutions Premium Core
STANDARD_SERVER_SOLUTIONS = 0x35 unless constants.include?(:STANDARD_SERVER_SOLUTIONS)
# Storage Server Enterprise Core
STORAGE_ENTERPRISE_SERVER = 0x2E unless constants.include?(:STORAGE_ENTERPRISE_SERVER)
# Storage Server Express Core
STORAGE_EXPRESS_SERVER = 0x2B unless constants.include?(:STORAGE_EXPRESS_SERVER)
# Storage Server Standard Core
STORAGE_STANDARD_SERVER = 0x2C unless constants.include?(:STORAGE_STANDARD_SERVER)
# Storage Server Workgroup Core
STORAGE_WORKGROUP_SERVER = 0x2D unless constants.include?(:STORAGE_WORKGROUP_SERVER)
# Web Server Core
WEB_SERVER = 0x1D unless constants.include?(:WEB_SERVER)
end
# Module referencing product type contants
# see. https://msdn.microsoft.com/windows/desktop/ms724833#VER_NT_SERVER
# n.b. Prefix - VER_NT_ - has been removed
module ProductType
WORKSTATION = 0x1 unless constants.include?(:WORKSTATION)
DOMAIN_CONTROLLER = 0x2 unless constants.include?(:DOMAIN_CONTROLLER)
SERVER = 0x3 unless constants.include?(:SERVER)
end
# Determines whether current node is running a windows Core version
def self.core_version?(node)
validate_platform node
CoreSKU.constants.any? { |c| CoreSKU.const_get(c) == node['kernel']['os_info']['operating_system_sku'] }
end
# Determines whether current node is a workstation version
def self.workstation_version?(node)
validate_platform node
node['kernel']['os_info']['product_type'] == ProductType::WORKSTATION
end
# Determines whether current node is a server version
def self.server_version?(node)
!workstation_version?(node)
end
# Determines NT version of the current node
def self.nt_version(node)
validate_platform node
node['platform_version'].to_f
end
def self.validate_platform(node)
raise 'Windows helper are only supported on windows platform!' unless node['platform'] == 'windows'
end
end
end

View File

@ -0,0 +1,165 @@
#
# Author:: Seth Chisamore (<schisamo@chef.io>)
# Cookbook:: windows
# Library:: windows_helper
#
# Copyright:: 2011-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 'uri'
require 'chef/exceptions'
require 'openssl'
require 'chef/mixin/powershell_out'
require 'chef/mixin/windows_env_helper'
require 'chef/util/path_helper'
module Windows
module Helper
AUTO_RUN_KEY = 'HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'.freeze unless defined?(AUTO_RUN_KEY)
ENV_KEY = 'HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment'.freeze unless defined?(ENV_KEY)
include Chef::Mixin::WindowsEnvHelper
# returns windows friendly version of the provided path,
# ensures backslashes are used everywhere
def win_friendly_path(path)
Chef::Log.warn('The win_friendly_path helper has been deprecated and will be removed from the next major release of the windows cookbook. Please update any cookbooks using this helper to instead require `chef/util/path_helper` and then use `Chef::Util::PathHelper.cleanpath`.')
path.gsub(::File::SEPARATOR, ::File::ALT_SEPARATOR || '\\') if path
end
# account for Window's wacky File System Redirector
# http://msdn.microsoft.com/en-us/library/aa384187(v=vs.85).aspx
# especially important for 32-bit processes (like Ruby) on a
# 64-bit instance of Windows.
def locate_sysnative_cmd(cmd)
if ::File.exist?("#{ENV['WINDIR']}\\sysnative\\#{cmd}")
"#{ENV['WINDIR']}\\sysnative\\#{cmd}"
elsif ::File.exist?("#{ENV['WINDIR']}\\system32\\#{cmd}")
"#{ENV['WINDIR']}\\system32\\#{cmd}"
else
cmd
end
end
# singleton instance of the Windows Version checker
def win_version
@win_version ||= Windows::Version.new
end
# Helper function to properly parse a URI
def as_uri(source)
URI.parse(source)
rescue URI::InvalidURIError
Chef::Log.warn("#{source} was an invalid URI. Trying to escape invalid characters")
URI.parse(URI.escape(source))
end
# if a file is local it returns a windows friendly path version
# if a file is remote it caches it locally
def cached_file(source, checksum = nil, windows_path = true)
@installer_file_path ||= begin
if source =~ %r{^(file|ftp|http|https):\/\/}
uri = as_uri(source)
cache_file_path = "#{Chef::Config[:file_cache_path]}/#{::File.basename(::URI.unescape(uri.path))}"
Chef::Log.debug("Caching a copy of file #{source} at #{cache_file_path}")
remote_file cache_file_path do
source source
backup false
checksum checksum unless checksum.nil?
end.run_action(:create)
else
cache_file_path = source
end
windows_path ? Chef::Util::PathHelper.cleanpath(cache_file_path) : cache_file_path
end
end
# Expands the environment variables
def expand_env_vars(path)
# The windows Env provider does not correctly expand variables in
# the PATH environment variable. Ruby expects these to be expanded.
# Using Chef::Mixin::WindowsEnvHelper
expand_path(path)
end
def is_package_installed?(package_name) # rubocop:disable Naming/PredicateName
installed_packages.include?(package_name)
end
def installed_packages
@installed_packages || begin
installed_packages = {}
# Computer\HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_LOCAL_MACHINE)) # rescue nil
# 64-bit registry view
# Computer\HKEY_LOCAL_MACHINE\Software\Wow6464Node\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_LOCAL_MACHINE, (::Win32::Registry::Constants::KEY_READ | 0x0100))) # rescue nil
# 32-bit registry view
# Computer\HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_LOCAL_MACHINE, (::Win32::Registry::Constants::KEY_READ | 0x0200))) # rescue nil
# Computer\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Uninstall
installed_packages.merge!(extract_installed_packages_from_key(::Win32::Registry::HKEY_CURRENT_USER)) # rescue nil
installed_packages
end
end
# Returns an array
def to_array(var)
var = var.is_a?(Array) ? var : [var]
var.reject(&:nil?)
end
private
def extract_installed_packages_from_key(hkey = ::Win32::Registry::HKEY_LOCAL_MACHINE, desired = ::Win32::Registry::Constants::KEY_READ)
uninstall_subkey = 'Software\Microsoft\Windows\CurrentVersion\Uninstall'
packages = {}
begin
::Win32::Registry.open(hkey, uninstall_subkey, desired) do |reg|
reg.each_key do |key, _wtime|
begin
k = reg.open(key, desired)
display_name = begin
k['DisplayName']
rescue
nil
end
version = begin
k['DisplayVersion']
rescue
'NO VERSION'
end
uninstall_string = begin
k['UninstallString']
rescue
nil
end
if display_name
packages[display_name] = { name: display_name,
version: version,
uninstall_string: uninstall_string }
end
rescue ::Win32::Registry::Error
end
end
end
rescue ::Win32::Registry::Error
end
packages
end
end
end
Chef::Recipe.send(:include, Windows::Helper)

View File

@ -0,0 +1,103 @@
#
# Author:: Doug MacEachern <dougm@vmware.com>
# Author:: Paul Morton (<pmorton@biaprotect.com>)
# Cookbook:: windows
# Library:: windows_privileged
#
# Copyright:: 2010-2017, VMware, Inc.
# Copyright:: 2011-2017, Business Intelligence Associates, 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.
#
# helpers for Windows API calls that require privilege adjustments
class Chef
class WindowsPrivileged
# File -> Load Hive... in regedit.exe
def reg_load_key(name, file)
load_deps
run(SE_BACKUP_NAME, SE_RESTORE_NAME) do
rc = RegLoadKey(HKEY_USERS, name.to_s, file)
if rc == ERROR_SUCCESS
return true
elsif rc == ERROR_SHARING_VIOLATION
return false
else
raise get_last_error(rc)
end
end
end
# File -> Unload Hive... in regedit.exe
def reg_unload_key(name)
load_deps
run(SE_BACKUP_NAME, SE_RESTORE_NAME) do
rc = RegUnLoadKey(HKEY_USERS, name.to_s)
raise get_last_error(rc) if rc != ERROR_SUCCESS
end
end
def run(*privileges)
load_deps
token = [0].pack('L')
unless OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, token)
raise get_last_error
end
token = token.unpack1('L')
privileges.each do |name|
unless adjust_privilege(token, name, SE_PRIVILEGE_ENABLED)
raise get_last_error
end
end
begin
yield
ensure # disable privs
privileges.each do |name|
adjust_privilege(token, name, 0)
end
end
end
def adjust_privilege(token, priv, attr = 0)
load_deps
luid = [0, 0].pack('Ll')
if LookupPrivilegeValue(nil, priv, luid)
new_state = [1, luid.unpack('Ll'), attr].flatten.pack('LLlL')
AdjustTokenPrivileges(token, 0, new_state, new_state.size, 0, 0)
end
end
private
def load_deps
if RUBY_PLATFORM =~ /mswin|mingw32|windows/
require 'windows/error'
require 'windows/registry'
require 'windows/process'
require 'windows/security'
include Windows::Error
include Windows::Registry
include Windows::Process
include Windows::Security
end
end
end
end

View File

@ -0,0 +1,34 @@
#
# Author:: Adam Edwards (<adamed@chef.io>)
# Cookbook:: windows
# Library:: wmi_helper
#
# Copyright:: 2014-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.
#
if RUBY_PLATFORM =~ /mswin|mingw32|windows/
require 'win32ole'
def execute_wmi_query(wmi_query)
wmi = ::WIN32OLE.connect('winmgmts://')
result = wmi.ExecQuery(wmi_query)
return nil unless result.each.count > 0
result
end
def wmi_object_property(wmi_object, wmi_property)
wmi_object.send(wmi_property)
end
end