Repository: chef-cookbooks/windows
Branch: master
Commit: 5868ac6569f4
Files: 60
Total size: 144.0 KB
Directory structure:
gitextract_io839hx9/
├── .delivery/
│ └── project.toml
├── .editorconfig
├── .gitattributes
├── .github/
│ ├── CODEOWNERS
│ └── workflows/
│ ├── branchcleanup.yml
│ └── delivery.yml
├── .gitignore
├── .rubocop.yml
├── .vscode/
│ └── extensions.json
├── Berksfile
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Gemfile
├── LICENSE
├── README.md
├── TESTING.md
├── appveyor.yml
├── chefignore
├── kitchen.appveyor.yml
├── kitchen.yml
├── libraries/
│ ├── powershell_helper.rb
│ ├── registry_helper.rb
│ ├── version.rb
│ ├── version_helper.rb
│ ├── windows_helper.rb
│ ├── windows_privileged.rb
│ └── wmi_helper.rb
├── metadata.rb
├── providers/
│ └── dns.rb
├── recipes/
│ └── default.rb
├── resources/
│ ├── certificate_binding.rb
│ ├── dns.rb
│ ├── http_acl.rb
│ ├── schannel.rb
│ ├── user_privilege.rb
│ └── zipfile.rb
├── spec/
│ └── spec_helper.rb
└── test/
├── cookbooks/
│ └── test/
│ ├── files/
│ │ ├── Asimov.otf
│ │ ├── CodeNewRoman.otf
│ │ ├── DigiCertAssuredIDCAG2.crt
│ │ ├── GeoTrust_Primary_CA.pem
│ │ ├── GeoTrust_Universal_CA.pem
│ │ ├── ThawteRSACA2018.crt
│ │ ├── base64-cert2.cer
│ │ ├── der-cert1.cer
│ │ ├── test-cert.cer
│ │ ├── test-cert.pfx
│ │ ├── test-cert.pvk
│ │ ├── test-pfx-certificate.pfx
│ │ ├── test_der.der
│ │ └── test_p7b.p7b
│ ├── metadata.rb
│ └── recipes/
│ ├── everything.rb
│ ├── http_acl.rb
│ ├── schannel.rb
│ ├── user_privilege.rb
│ └── zipfile.rb
└── integration/
├── http_acl/
│ └── http_acl_spec.rb
└── schannel/
└── schannel_spec.rb
================================================
FILE CONTENTS
================================================
================================================
FILE: .delivery/project.toml
================================================
remote_file = "https://raw.githubusercontent.com/chef-cookbooks/community_cookbook_tools/master/delivery/project.toml"
================================================
FILE: .editorconfig
================================================
# https://EditorConfig.org
# top-most EditorConfig file
root=true
# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
# 2 space indentation
indent_style = space
indent_size = 2
# Avoid issues parsing cookbook files later
charset = utf-8
# Avoid cookstyle warnings
trim_trailing_whitespace = true
================================================
FILE: .gitattributes
================================================
* text=auto eol=lf
================================================
FILE: .github/CODEOWNERS
================================================
* @chef-cookbooks/windows-team
================================================
FILE: .github/workflows/branchcleanup.yml
================================================
---
name: Branch Cleanup
# This workflow is triggered on all closed pull requests.
# However the script does not do anything if a merge was not performed.
"on":
pull_request:
types: [closed]
env:
NO_BRANCH_DELETED_EXIT_CODE: 0
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: jessfraz/branch-cleanup-action@master
================================================
FILE: .github/workflows/delivery.yml
================================================
name: delivery
on: [push, pull_request]
jobs:
delivery:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@master
- name: Run Chef Delivery
uses: actionshub/chef-delivery@main
env:
CHEF_LICENSE: accept-no-persist
================================================
FILE: .gitignore
================================================
*.rbc
.config
InstalledFiles
lib/bundler/man
pkg
test/tmp
test/version_tmp
tmp
_Store
*~
*#
.#*
\#*#
*.un~
*.tmp
*.bk
*.bkup
# editor temp files
.idea
.*.sw[a-z]
# ruby/bundler files
.ruby-version
.ruby-gemset
.rvmrc
Gemfile.lock
.bundle
*.gem
coverage
spec/reports
# YARD / rdoc artifacts
.yardoc
_yardoc
doc/
rdoc
# chef infra stuff
Berksfile.lock
.kitchen
kitchen.local.yml
vendor/
.coverage/
.zero-knife.rb
Policyfile.lock.json
# vagrant stuff
.vagrant/
.vagrant.d/
================================================
FILE: .rubocop.yml
================================================
ChefModernize/WindowsZipfileUsage:
Enabled: false
Lint/ShadowingOuterLocalVariable:
Exclude:
- 'libraries/registry_helper.rb'
Lint/UselessAssignment:
Exclude:
- 'libraries/registry_helper.rb'
Style/ClassVars:
Exclude:
- 'libraries/registry_helper.rb'
Style/IfInsideElse:
Exclude:
- 'libraries/powershell_helper.rb'
================================================
FILE: .vscode/extensions.json
================================================
{
"recommendations": [
"chef-software.chef",
"rebornix.ruby",
"editorconfig.editorconfig"
]
}
================================================
FILE: Berksfile
================================================
source 'https://supermarket.chef.io'
metadata
group :integration do
cookbook 'test', path: './test/cookbooks/test'
end
================================================
FILE: CHANGELOG.md
================================================
# windows Cookbook CHANGELOG
This file is used to list changes made in each version of the windows cookbook.
## 7.0.2 (2020-09-10)
- Resolve a typo in the user_privilege resource - [@tas50](https://github.com/tas50)
- Don't run delivery in Appveyor - [@tas50](https://github.com/tas50)
## 7.0.1 (2020-09-10)
- Remove testing of Windows 2008 R2 - [@tas50](https://github.com/tas50)
- Cookstyle 6.2.9 Fixes - [@xorimabot](https://github.com/xorimabot)
- Avoid deprcation warnings when using user_privilege resource on Chef >= - [@tas50](https://github.com/tas50)
## Unreleased
- resolved cookstyle error: libraries/registry_helper.rb:69:9 refactor: `ChefCorrectness/ChefApplicationFatal`
- resolved cookstyle error: libraries/registry_helper.rb:232:9 convention: `Style/RedundantReturn`
- resolved cookstyle error: libraries/registry_helper.rb:234:9 convention: `Style/RedundantReturn`
- resolved cookstyle error: libraries/registry_helper.rb:244:9 convention: `Style/RedundantReturn`
- resolved cookstyle error: libraries/registry_helper.rb:245:7 convention: `Style/EmptyElse`
- resolved cookstyle error: libraries/registry_helper.rb:246:9 convention: `Style/RedundantReturn`
- resolved cookstyle error: libraries/registry_helper.rb:272:9 convention: `Style/RedundantReturn`
- resolved cookstyle error: libraries/registry_helper.rb:274:9 convention: `Style/RedundantReturn`
- resolved cookstyle error: libraries/windows_helper.rb:165:14 warning: `Lint/SendWithMixinArgument`
## 7.0.0 (2020-03-26)
### Breaking Changes
- This cookbook now requires Chef Infra Client 14.7 and later as it no longer includes the `windows_share` and `windows_certificate` resources that are now built into Chef Infra Client.
### Other Changes
- Remove list of actions in the dns resource - [@tas50](https://github.com/tas50)
- Don't set the guard_interpreter in powershell_script - [@tas50](https://github.com/tas50)
- Add windows_schannel resource (#619) - [@Xorima](https://github.com/Xorima)
- Remove desired_state: true from resources - [@tas50](https://github.com/tas50)
- The host_name property in the dns resource doesn't need to be a name property - [@tas50](https://github.com/tas50)
- Remove unnecessary include of the powershell mixin - [@tas50](https://github.com/tas50)
## 6.0.1 (2019-10-01)
- Update README.md for Windows cookbook suggesting core dns resources (#616) - [@NAshwini](https://github.com/NAshwini)
- Add a warning when using windows_zipfile resource as users should migrate to archive_file (#617) - [@NAshwini](https://github.com/NAshwini)
## 6.0.0 (2019-04-25)
### Breaking Changes
- This cookbook now requires Chef 14 or later. As of April 2019 Chef 13 is EOL. If you are still running Chef 13 we highly suggest you begin your migration. Chef 14 provides a greatly improved Windows experience with built in resources for Windows clients.
- Resources that are built into Chef 14 and later have been removed from this cookbook:
- windows_auto_run
- windows_feature
- windows_font
- windows_pagefile
- windows_printer_port
- windows_printer
- windows_shortcut
## 5.3.1 (2019-04-25)
- Resolved failures on Chef 14.11 or later
- Removed OS detectio support in the helpers for Windows 2003
## 5.3.0 (2019-03-06)
- Expanded certificate testing to cover more scenarios - [@Xorima](https://github.com/Xorima)
- Updated windows_share to better compare the current and desired path in order to prevent converging on each Chef run - [@Xorima](https://github.com/Xorima)
- Backported all windows_certificate fixes from Chef 14.8 - 14.11 including improvements to importing the types of certificates that can be imported, suppport for nested certs, and support for importing private keys with certs.
## 5.2.4 (2019-02-28)
- Fix http_acl regex to properly capture SDDL - [@Annih](https://github.com/Annih)
- Updated windows_share to create share if the share is deleted, and to sanitize paths using Chef::Util::PathHelper.cleanpath (#607) - [@Xorima](https://github.com/Xorima)
## 5.3.3 (2019-01-30)
- Updated windows_certificate code to match that in Chef 14.10. This increases the requirement of the win32_certstore gem to the latest and resolves multiple issues with the previous implementation.
## 5.2.2 (2018-11-20)
- windows_share: Accounts to be revoked should be provided as an individually quoted string array
## 5.2.1 (2018-11-19)
- windows_share: Fix idempotency by not adding everyone by default
## 5.2.0 (2018-11-14)
- Support installing deleted features in windows_feature_dism
## 5.1.6 (2018-11-13)
- Add a warning to the readme regarding windows_share and windows_certificate now being included in Chef 14.7
- Deprecated win_friendly_path helper in favor of built-in helpers
## 5.1.5 (2018-11-07)
- Avoid deprecation warnings in windows_share and windows_certificate on Chef 14.7+ as these are now included in the chef-client itself.
## 5.1.4 (2018-10-30)
- Note the :verify action for windows_certificate in the readme
- certificate resource: auto set sensitive is passing password
## 5.1.3 (2018-10-11)
- Remove docs and test suite for windows tasks
- Changed variable name in log message for retrieving SMB share access
- Don't load the windows helper in windows_certificate
## 5.1.2 (2018-10-08)
- Fix typo in windows_feature_dism resource name
## 5.1.1 (2018-09-06)
- Require the win32-certstore gem and upgrade the gem as the resource runs so we get the most up to date version
- Remove redundant helper methods from the windows_certificate resource
## 5.1.0 (2018-08-29)
- Add an action to windows_user_privilege to remove a privilege
- Fix failing appveyor tests
- Require win32-certstore 0.1.8 which resolves several issues with the windows_certificate resource
- Avoid deprecation warnings with Chef 14.3+ by not loading resources that are now built into Chef
## 5.0.0 (2018-07-24)
### Breaking Changes
This release removes the windows_task and windows_path resources from this cookbook. This resources shipped in Chef 13.0 and 13.4 This raises the required version of chef-client for this cookbook to 13.4 or later.
## 4.3.4 (2018-07-18)
- Fix error message typo in windows_feature_powershell
- Use win32-certstore 0.1.7 for bugfixes
## 4.3.3 (2018-07-05)
- Fix failures on PS 3.0 in windows_feature_powershell
## 4.3.2 (2018-06-13)
- Don't error in windows_feature_dism when providing a source
## 4.3.1 (2018-06-11)
- Make sure to quote each individual user to grant share access to
## 4.3.0 (2018-06-11)
- Add the windows_user_privilege resource which can grant privileges like Logon As a Service
- Add windows_feature_powershell support for Windows 2008 R2 by not downcasing the feature names there and modifying the shell_out commands to make older output look like the 2012+ output
- windows_certificate resource has been reworked to use the new win32-certstore gem. This gem abstracts away much of the logic and will allow us to better support certificates on Windows, especially on non-english systems.
- Convert pester tests to InSpec for easier testing with ChefDK out of the box
- Added additional tests for better testing in AppVeyor
- Stop importing the servermanager module in windows_feature_powershell since we require PowerShell 3.0 and we don't need to do this there
- Improve the error messages in Windows feature to get the Windows versions right
- Increase readability in version logic with helpers in windows_feature resources
## 4.2.5 (2018-05-28)
- Add quoting to Path when creating new Share
## 4.2.4 (2018-05-14)
- Fix the platform version check in windows_share
## 4.2.3 (2018-05-07)
- Include the helper in the action class to prevent failures with the zipfile resource
## 4.2.2 (2018-04-24)
- Properly fail in windows_share on Windows 2008 R2 since we lack the cmdlets to manipulates shares on those systems.
## 4.2.1 (2018-04-17)
- Make sure shares can have spaces in the share name
## 4.2.0 (2018-04-16)
- Initial rewrite of windows_share to use PowerShell for share creation. This introduces multiple new properties and resolves a good number of longstanding issues. Please be sure to report any issues you see with this so we can stabilize this resource and include it in Chef 15!
- Resolve failures in windows_certificate
## 4.1.4 (2018-03-29)
- Raise in windows_feature_powershell if we're on PS < 3.0
## 4.1.3 (2018-03-28)
- Restore support for Windows 2008 R2 in windows_feature_dism
## 4.1.2 (2018-03-27)
- Improve creation messaging for shares
- Allow feature names to be case insensitive in windows_feature
## 4.1.1 (2018-03-23)
- Simplify delete action slightly in windows_pagefile
- Don't use win_friendly_path helper in windows_pagefile since we already coerce the path value
## 4.1.0 (2018-03-21)
- Adds Caching for WIndows Feature Powershell resource using the same sort of logic we use on windows_feature_dism. This gives us a 3.5X speedup when no features need to be changed (subsequent runs after the change)
- Warn if we're on w2k12 and trying to use source/management properties in windows_feature_powershell since that doesn't work.
- Properly parse features into arrays so installing an array of features works in dism/powershell. This is the preferred way to install a number of features and will be faster than a large number of feature resources
- Fix description of properties for pagefile in the readme
## 4.0.2 (2018-03-20)
- Enable FC016 testing
- Enable FC059 testing
- Properly calculate available packages if source is passed in windows_feature_dism resource
## 4.0.1 (2018-03-07)
Fix the previous update to windows_feature_dism to use 'override' level of attributes not the normal level which persists to the node. Thanks to @Annih for pointing out the mistake here.
## 4.0.0 (2018-03-05)
### WARNING
This release contains a complete rewrite to windows_feature_dism resource and includes several behavior changes to windows_feature resource. Make sure to read the complete list of changes below before deploying this to production systems.
#### DISM feature caching Ohai plugin replacement
In the 3.X cookbook we installed an Ohai plugin that cached the state of features on the node, and we reloaded that plugin anytime we installed/removed a feature from the system. This greatly sped up Chef runs where no features were actually installed/removed (2nd run and later). Without the caching each resource would take about 1 second longer while it queried current feature state. Using Ohai to cache this data was problematic though due to incompatibilities with Chef Solo, the reliance on the ohai cookbook, and the addition of extra node data which had to be stored on the Chef Server.
In the 4.0 release instead of caching data via an Ohai plugin we just write directly to the node within the resource. This avoids the need to load in the ohai plugin and the various issues that come with that. In the end it's basically the exact same thing, but less impacting on end users and faster when the data needs to be updated.
#### Fail when feature is missing in windows_feature_dism
The windows_feature_dism resource had a rather un-Chef behavior in which it just warned you if a feature wasn't available on your platform and then continued on silently. This isn't how we handle missing packages in any of our package resource and because of that it's not going to be what anyone expects out of the box. If someone really wants SNMP installed and we can't install it we should fail instead of continuing on as if we did install it. So we'll now do the following things:
- When installing a feature that doesn't exist: fail
- When removing a feature that doesn't exist: continue since it is technically removed
- When deleting a feature that doesn't exist: continue since it is technically deleted
For some users, particularly those writing community cookbooks, this is going to be a breaking change. I'd highly recommend putting logic within your cookbooks to only install features on supported releases of Windows. If you'd just like it to continue even with a failure you can also use `ignore_failure true` on your resource although this produces a lot of failure messaging in logs.
#### Properly support features as an array in windows_feature_dism
We claimed to support installing features as an array in the windows_feature_dism resource previously, but it didn't actually work. The actual result was a warning that the array of features wasn't available on your platform since we compared the array to available features as if it was a string. We now properly support installation as a array and we do validation on each feature in the array to make sure the features are available on your Windows release.
#### Install as the default action in windows_feature_powershell
Due to some previous refactoring the :install action was not the default action for windows_feature_powershell. For all other package resources in Chef install is the default so this would likely lead to some unexpected behavior in cookbooks. This is technically a breaking change, but I suspect everyone assumed :install was always the default.
#### servermanagercmd.exe Support Removal
This cookbook previously supported servermanagercmd.exe, which was necessary for feature installation on Windows 2003 / 2008 (not R2) systems. Windows 2003 went full EOL in 2015 and 2008 went into extended support in 2015\. Neither releases are supported platforms for Chef or this cookbook so we've chosen to simplify the code and remove support entirely.
#### Remove the undocumented node['windows']['rubyzipversion'] attribute
This attribute was a workaround for a bug in the rubyzip gem YEARS ago that's just not necessary anymore. We also never documented this attribute and a resource shouldn't change behavior based on attributes.
## 3.5.2 (2018-03-01)
- Remove value_for_feature_provider helper which wasn't being used and was using deprecated methods
- Add all the Windows Core editions to the version helper
- Simplify / speedup how we find the font directory in windows_font
- Don't bother enabling why-run mode in the resources since it's enabled by default
- Don't include mixlib-shellout in the resources since it's included by default
- Fix installation messaging for windows_feature_powershell to properly show all features being installed
- Use powershell for the share creation / deletion in windows_share. This speeds up the runs and fixes some of the failures.
## 3.5.1 (2018-02-23)
- Add a new `shortcut_name` property to `windows_shortcut`
- Use Chef's built in registry_key_exists helper in `windows_printer_port`
- Fix the `source` coerce in `windows_font`
## 3.5.0 (2018-02-23)
- Add Windows 2016 to the supported releases in the readme
- Add Windows 10 detection to the version helper
- Remove the Chefspec matchers. These are auto generated by ChefSpec now. If this causes your specs to fail upgrade ChefDK
- In `certificate_binding` support `hostnameport` option if address is a hostname
- Convert several tests to InSpec tests and add additional test scenarios
- Remove `required: true` on the name_properties, which serves no purpose and will be a Foodcritic rule in the next Foodcritic release
- Fix `windows_feature` logging to work when the user provides an array of features
- Don't both coercing a symbol into a symbol in the `windows_auto_run` resource.
- Switch `windows_font` over to the built in path helper in Chef, which a much more robust
- Don't coerce forward slashes to backslashes in the `windows_font` `source` property if the source is a URI
- Add a new `path` property to `windows_pagefile` for properly overriding the resource name
- Coerce backslashes to forward slashes in `windows_pagefile`'s `path` property so we do the right thing even if a user gives bad input
- Add a new `program_name` property in windows_auto_run for overriding the resource name
- Rename `program` property to `path` in windows_auto_run. The legacy name will continue to work, but cookbooks should be updated
- Coerce the `path` property to use backslashes in `windows_auto_run` so it works no matter what format of path the user provides
- Avoid writing out an extra space in `windows_auto_run`'s registry entry when the user doesn't specify an arg
- Added yard comments to many of the helper methods
## 3.4.4 (2018-01-19)
- Fix undefined method for 'ipv4_address' in windows_printer_port
## 3.4.3 (2018-01-04)
- Added missing parentheses around PersistKeySet flag that was preventing PowerShell from creating X509Certificate2 object
## 3.4.2 (2018-01-02)
- Add deprecation warnings for windows_path and windows_task which are now included in Chef 13\. These will be removed from this cookbook in Sept 2018.
## 3.4.1 (2017-12-06)
- Fix long-running filtering by replace LIKE with equality sign in the share resource
- Use logical OR instead of AND when trying to detect share permissions changing in the share resource
- Remove extra new_resource.updated_by_last_action in the windows_task resource that resulted in a Foodcritic warning
## 3.4.0 (2017-11-14)
- Add a root key property for the auto_run resource
- Fix a resource typo where a name_property was still written name_attribute
- Resolve FC108 warnings
## 3.3.0 (2017-11-06)
- Add new dns resource. See readme for examples
- Add BUILTIN\Users to SYSTEM_USERS for windows_task
## 3.2.0 (2017-10-17)
- Add management_tools property to windows_feature powershell provider which installs the various management tools
- Fix deprecations_namespace_collisions
- Add additional certificate store names
- Add the ability to define a timeout on windows_feature
- Multiple improvements to the font resource
- Improved logging, particularly debug logging
- Allow pulling the font from a remote location using remote_file
- Fix some failures in fetching local fonts
- Added a font_name property that allows you specify the local name of the font, which can be different from the name of the chef resource. This allows you to create more friendly resource names for your converge.
- Handle font resources with backslashes in their source
- Remove source property from servermanagercmd provider as it does not support it.
- Remove converge_by around inner powershell_script resource to stop it always reporting as changed
- Change install feature guards to work on Windows 2008r2
- Allow dism feature installs to work on non-English systems
## 3.1.3 (2017-09-18)
### windows_task and windows_path deprecation
s of chef-client 13.0+ and 13.4+ windows_task and windows_path are now included in the Chef client. windows_task underwent a full rewrite that greatly improved the functionality and idempotency of the resource. We highly recommend using these new resources by upgrading to Chef 13.4 or later. If you are running these more recent Chef releases the windows_task and windows_path resources within chef-client will take precedence over those in this cookbook. In September 2018 we will release a new major version of this cookbook that removes windows_task and windows_path.
## 3.1.2 (2017-08-14)
- Revert "Require path in the share resource instead of raising if it's missing" which was causing failures due to a bug in the chef-client
## 3.1.1 (2017-06-13)
- Replace Windows 7 testing with Windows 10 testing
- Expand debug logging in the pagefile resource
- Require path in the share resource instead of raising if it's missing
- Make pagefile properly fail the run if the command fails to run
## 3.1.0 (2017-05-30)
- Updated resource documentation for windows_pagefile
- Declare windows_feature as why-runnable
- Remove action_class.class_eval usage and require 12.7+ as class_eval is causing issues with later versions of Chef
## 3.0.5 (2017-04-07)
- Add support for windows_task resource to run on non-English editions of Windows
- Ensure chef-client 12.6 compatibility with action_class.class_eval
## 3.0.4 (2017-03-29)
- restoring the `cached_file` helper as downstream cookbooks use it.
## 3.0.3 (2017-03-28)
- Correct a typo in a Log message
## 3.0.2 (2017-03-21)
- Fix `windows_zipfile` resource to properly download and cache the zip archives
## 3.0.1 (2017-03-17)
- Fix `windows_share` to be fully idempotent. Fixes #447
## 3.0.0 (2017-03-15)
**Warning** This release includes multiple breaking changes as we refactored all existing resources and resolved many longstanding bugs. We highly recommend exercising caution and fully testing this new version before rolling it out to a production environment.
### Breaking changes
- This cookbook now requires Chef 12.6 or later and we highly recommend even more recent Chef 12 releases as they resolve critical Windows bugs and include new Windows specific functionality.
- The windows_package resource has been removed as it is built into chef-client 12.6+ and the built in version is faster / more robust.
- The powershell out helper has been removed as it is now included in chef-client 12.6+
- The default recipe no longer installs the various Windows rubygems required for non-omnibus chef-client installs. This was a leftover from Chef 10 and is no longer necessary, or desired, as we ship these gems in every Windows chef release.
- windows_feature has been heavily refactored and in doing so the method used to control the underlying providers has changed. You can no longer specify which windows_feature provider to use by setting `node['windows']['feature_provider']` or by setting the `provider` property on the resource itself. Instead you must set `install_method` to specify the correct underlying installation method. You can also now reference the resources directly by using `windows_feature_servermanagercmd`, `windows_feature_powershell` or `windows_feature_dism` instead of `windows_feature`
- Windows_font's `file` property has been renamed to `name` to avoid collisions with the Chef file resource.
### Other Changes
- All LWRPs in this cookbook have been refactored to be custom resources
- windows_path, windows_shortcut, and windows_zipfile have been updated to be idempotent with support for why-run mode and proper notification when the resources actually update
- windows_pagefile now validates the name of the pagefile to avoid cryptic error messages
- A new `share` resource has been added for setting up Windows shares
- TrustedPeople certificate store has been added to the list of allowed store_names in the certificate resources
- version helper constant definitions has been improved
- A new `all` property has been added to the Windows feature resource to install all dependent features. See the windows feature test recipe for usage examples.
- Windows feature now accepts an array of features, which greatly speeds up feature installs and simplifies recipe code
- The path resource now accepts paths with either forward slashes or backslashes and correctly adds the path using Windows style backslash.
- The powershell provider for windows_feature resource has been fixed to properly import ServerManager in the :remove action
- Testing has been switched from a Rakefile to the new Delivery local mode
- Several issues with testing the resources on non-Windows hosts in ChefSpec have been resolved
- A new `source` property has been added to the windows_feature_powershell resource
- Additional test suites have been added to Test Kitchen to cover all resources and those test suites are now being executed in AppVeyer on every PR
- Travis CI testing has been removed and all testing is being performed in AppVeyer
## 2.1.1 (2016-11-23)
- Make sure the ohai plugin is available when installing features
## 2.1.0 (2016-11-22)
- Reduce expensive executions of dism in windows_feature by using a new Ohai plugin
- Add guard around chef_version metadata for Opsworks and older Chef 12 clients
- Update the rakefile to the latest
- Add deprecation dates for the windows_package and powershell functionality that has been moved to core Chef. These will be removed 4/17 when we release Chef 13
- Provide helper method to get windows version info
- Allow defining http acl using SDDL
## 2.0.2 (2016-09-07)
- Added the powershell_out mixin back to allow for Chef 12.1-12.3 compatibility
- Set the dependency back to Chef 12.1
## 2.0.1 (2016-09-07)
- Clarify the platforms we support in the readme
- Require Chef 12.4 which included powershell_out
## 2.0.0 (2016-09-07)
This cookbook now requires Chef 12.1+. Resources (lwrps) that have been moved into the chef-client have been removed from this cookbook. While the functionality in the chef-client is similar, and in many cases improved, the names and properties have changed in some cases. Make sure to check <https://docs.chef.io/resources.html> for full documentation on each of these resources, and as usual carefully test your cookbooks before upgrading to this new release.
### Removed resources and helpers:
- windows_reboot provider
- windows_batch provider
- windows_registry provider
- Powershell out for only_if / not_if statements
- Windows Architecture Helper
- Reboot handler and the dependency on the chef_handler cookbook
#### Changes resource behavior
- For Chef clients 12.6 and later the windows_package provider will no longer be used as windows_package logic is now included in Chef. Chef 12.1 - 12.5.1 clients will continue to default to the windows_package provider in this cookbook for full compatibility.
#### Additional changes
- Updated and expanded testing
- Fixed the windows_feature powershell provider to run on Windows 2008 / 2008 R2
- Added TrustedPublisher as a valid cert store_name
- Updated the certificate_binding resource to respect the app_id property
- Added why-run support to the auto_run resource
## 1.44.3 (2016-08-16)
- Remove support for ChefSpec <4.1 in the matchers
- Add missing Chefspec matchers
## 1.44.2 (2016-08-15)
- Add missing windows_font matcher
- Add chef_version to the metadata
- Switch from Rubocop to Cookstyle and use our improved Rakefile
- Remove test deps from the Gemfile that are in ChefDK
## v1.44.1
- [PR 375](https://github.com/chef-cookbooks/windows/pull/375) - Fix comparison of string to number in platform_version
- [PR 376](https://github.com/chef-cookbooks/windows/pull/376) - Switch to cookstyle, update gem deps and other minor stuff
- [PR 377](https://github.com/chef-cookbooks/windows/pull/377) - add test and check for feature installation through powershell
## v1.44.0
- [PR 372](https://github.com/chef-cookbooks/windows/pull/372) - Support Server 2008 for feature installs via PowerShell
## v1.43.0
- [PR 369](https://github.com/chef-cookbooks/windows/pull/369) - Add a enable_windows_task matcher
## v1.42.0
- [PR 365](https://github.com/chef-cookbooks/windows/pull/365) - Escape command quotes when passing to schtasks
## v1.41.0
- [PR 364](https://github.com/chef-cookbooks/windows/pull/364) - Configurable font source
## v1.40.0
- [PR 357](https://github.com/chef-cookbooks/windows/pull/357) - Fixes for schtasks
- [PR 359](https://github.com/chef-cookbooks/windows/pull/359) - take bundler out of the appveyor build
- [PR 356](https://github.com/chef-cookbooks/windows/pull/356) - Misc fixes and updates
- [PR 355](https://github.com/chef-cookbooks/windows/pull/355) - bump and pin rubocop, fix broken cop
- [PR 348](https://github.com/chef-cookbooks/windows/pull/348) - Make notify work for `windows_task`
## v1.39.2
- [PR 329](https://github.com/chef-cookbooks/windows/pull/329) - Silence `compile_time` warning for `chef_gem`
- [PR 338](https://github.com/chef-cookbooks/windows/pull/338) - ChefSpec matchers for `windows_certificate`
- [PR 341](https://github.com/chef-cookbooks/windows/pull/341) - Updated rubocop and FoodCritic compliance
- [PR 336](https://github.com/chef-cookbooks/windows/pull/336) - Fixed where clause compliance with PS v1/v2
## v1.39.1
- [PR 325](https://github.com/chef-cookbooks/windows/pull/325) - Raise an error if a bogus feature is given to the powershell `windows_feature` provider
- [PR 326](https://github.com/chef-cookbooks/windows/pull/326) - Fix `windows_font` and copy the font file before installation
## v1.39.0
- [PR 305](https://github.com/chef-cookbooks/windows/pull/305) - Added `months` attribute to `windows_task` and allow `frequency_modifier` to accept values 'FIRST', 'SECOND', 'THIRD', 'FOURTH', 'LAST', and 'LASTDAY' for monthly frequency
- [PR 310](https://github.com/chef-cookbooks/windows/pull/310) - Fix `windows_task` breaks when there is a space in the user name
- [PR 314](https://github.com/chef-cookbooks/windows/pull/314) - fixes reboot handling on some chef versions below 11.12
- [PR 317](https://github.com/chef-cookbooks/windows/pull/317) - Adds a `disable_windows_task` matcher
- [PR 311](https://github.com/chef-cookbooks/windows/pull/311) - Implements the `cwd` attribute of `windows_task`
- [PR 318](https://github.com/chef-cookbooks/windows/pull/318) - Use dsl instead of manual resource instanciation
- [PR 303](https://github.com/chef-cookbooks/windows/pull/303) - Fix `http_acl` idempotency when user name contains a space
- [PR 257](https://github.com/chef-cookbooks/windows/pull/257) - Speed up windows_feature dism provider
- [PR 319](https://github.com/chef-cookbooks/windows/pull/319) - Add a `.kitchen.cloud.yml` for kitchen testing on Azure
- [PR 315](https://github.com/chef-cookbooks/windows/pull/315) - Deprecate `windows_package` and forward to `Chef::Provider::Package::Windows` when running 12.6 or higher
## v1.38.4
- [PR 295](https://github.com/chef-cookbooks/windows/pull/295) - Escape `http_acl` username
- [PR 293](https://github.com/chef-cookbooks/windows/pull/293) - Separating assignments to `code_script` and `guard_script` as they should be different scripts and not hold the same reference
- [Issue 298](https://github.com/chef-cookbooks/windows/issues/298) - `windows_certificate_binding` is ignoring `store_name` attribute and always saving to `MY`
- [Issue 296](https://github.com/chef-cookbooks/windows/pull/302) - Fixes `windows_certificate` idempotentcy on chef 11 clients
## v1.38.3
- Make `windows_task` resource idempotent (double quotes need to be single when comparing)
- [Issue 245](https://github.com/chef-cookbooks/windows/issues/256) - Fix `No resource, method, or local variable named`password' for `Chef::Provider::WindowsTask'` when `interactive_enabled` is `true`
## v1.38.2
- Lazy-load windows-pr gem library files. Chef 12.5 no longer includes the windows-pr gem. Earlier versions of this cookbook will not compile on Chef 12.5.
## v1.38.1 (2015-07-28)
- Publishing without extended metadata
## v1.38.0 (2015-07-27)
- Do not set new_resource.password to nil, Fixes #219, Fixes #220
- Add `windows_certificate` resource #212
- Add `windows_http_acl` resource #214
## v1.37.0 (2015-05-14)
- fix `windows_package` `Chef.set_resource_priority_array` warning
- update `windows_task` to support tasks in folders
- fix `windows_task` delete action
- replace `windows_task` name attribute with 'task_name'
- add :end action to 'windows_task'
- Tasks created with the `windows_task` resource default to the SYSTEM account
- The force attribute for `windows_task` makes the :create action update the definition.
- `windows_task` :create action will force an update of the task if the user or command differs from the currently configured setting.
- add default provider for `windows_feature`
- add a helper to make sure `WindowsRebootHandler` works in ChefSpec
- added a source and issues url to the metadata for Supermarket
- updated the Gemfile and .kitchen.yml to reflect the latest test-kitchen windows guest support
- started tests using the kitchen-pester verifier
## v1.36.6 (2014-12-18)
- reverting all chef_gem compile_time work
## v1.36.5 (2014-12-18)
- Fix zipfile provider
## v1.36.4 (2014-12-18)
- Fix Chef chef_gem with Chef::Resource::ChefGem.method_defined?(:compile_time)
## v1.36.3 (2014-12-18)
- Fix Chef chef_gem below 12.1.0
## v1.36.2 (2014-12-17)
- Being explicit about usage of the chef_gem's compile_time property.
- Eliminating future deprecation warnings in Chef 12.1.0
## v1.36.1 (2014-12-17)
- [PR 160](https://github.com/chef-cookbooks/windows/pull/160) - Fix Chef 11.10 / versions without windows_package in core
## v1.36.0 (2014-12-16)
- [PR 145](https://github.com/chef-cookbooks/windows/pull/145) - do not fail on non-existant task
- [PR 144](https://github.com/chef-cookbooks/windows/pull/144) - Add a zip example to the README
- [PR 110](https://github.com/chef-cookbooks/windows/pull/110) - More zip documentation
- [PR 148](https://github.com/chef-cookbooks/windows/pull/148) - Add an LWRP for font installation
- [PR 151](https://github.com/chef-cookbooks/windows/pull/151) - Fix windows_package on Chef 12, add integration tests
- [PR 129](https://github.com/chef-cookbooks/windows/pull/129) - Add enable/disable actions to task LWRP
- [PR 115](https://github.com/chef-cookbooks/windows/pull/115) - require Chef::Mixin::PowershellOut before using it
- [PR 88](https://github.com/chef-cookbooks/windows/pull/88) - Code 1003 from servermanagercmd.exe is valid
## v1.34.8 (2014-10-31)
- [Issue 137](https://github.com/chef-cookbooks/windows/issues/137) - windows_path resource breaks with ruby 2.x
## v1.34.6 (2014-09-22)
- [Chef-2009](https://github.com/chef/chef/issues/2009) - Patch to work around a regression in [Chef](https://github.com/chef/chef)
## v1.34.2 (2014-08-12)
- [Issue 99](https://github.com/chef-cookbooks/windows/issues/99) - Remove rubygems / Internet wmi-lite dependency (PR #108)
## v1.34.0 (2014-08-04)
- [Issue 99](https://github.com/chef-cookbooks/windows/issues/99) - Use wmi-lite to fix Chef 11.14.2 break in rdp-ruby-wmi dependency
## v1.32.1 (2014-07-15)
- Fixes broken cookbook release
## v1.32.0 (2014-07-11)
- Add ChefSpec resource methods to allow notification testing (@sneal)
- Add use_inline_resources to providers (@micgo)
- [COOK-4728] - Allow reboot handler to be used as an exception handler
- [COOK-4620] - Ensure win_friendly_path doesn't error out when ALT_SEPARATOR is nil
## v1.31.0 (2014-05-07)
- [COOK-2934] - Add windows_feature support for 2 new DISM attributes: all, source
## v1.30.2 (2014-04-02)
- [COOK-4414] - Adding ChefSpec matchers
## v1.30.0 (2014-02-14)
- [COOK-3715] - Unable to create a startup task with no login
- [COOK-4188] - Add powershell_version method to return Powershell version
## v1.12.8 (2014-01-21)
- [COOK-3988] Don't unescape URI before constructing it.
## v1.12.6 (2014-01-03)
- [COOK-4168] Circular dep on powershell - moving powershell libraries into windows. removing dependency on powershell
## v1.12.4
Fixing depend/depends typo in metadata.rb
## v1.12.2
### Bug
- **[COOK-4110](https://tickets.chef.io/browse/COOK-4110)** - feature_servermanager installed? method regex bug
## v1.12.0
### Bug
- **[COOK-3793](https://tickets.chef.io/browse/COOK-3793)** - parens inside parens of README.md don't render
### New Feature
- **[COOK-3714](https://tickets.chef.io/browse/COOK-3714)** - Powershell features provider and delete support.
## v1.11.0
### Improvement
- **[COOK-3724](https://tickets.chef.io/browse/COOK-3724)** - Rrecommend built-in resources over cookbook resources
- **[COOK-3515](https://tickets.chef.io/browse/COOK-3515)** - Remove unprofessional comment from library
- **[COOK-3455](https://tickets.chef.io/browse/COOK-3455)** - Add Windows Server 2012R2 to windows cookbook version helper
### Bug
- **[COOK-3542](https://tickets.chef.io/browse/COOK-3542)** - Fix an issue where `windows_zipfile` fails with LoadError
- **[COOK-3447](https://tickets.chef.io/browse/COOK-3447)** - Allow Overriding Of The Default Reboot Timeout In windows_reboot_handler
- **[COOK-3382](https://tickets.chef.io/browse/COOK-3382)** - Allow windows_task to create `on_logon` tasks
- **[COOK-2098](https://tickets.chef.io/browse/COOK-2098)** - Fix and issue where the `windows_reboot` handler is ignoring the reboot time
### New Feature
- **[COOK-3458](https://tickets.chef.io/browse/COOK-3458)** - Add support for `start_date` and `start_time` in `windows_task`
## v1.10.0
### Improvement
- [COOK-3126]: `windows_task` should support the on start frequency
- [COOK-3127]: Support the force option on task create and delete
## v1.9.0
### Bug
- [COOK-2899]: windows_feature fails when a feature install requires a reboot
- [COOK-2914]: Foodcritic failures in Cookbooks
- [COOK-2983]: windows cookbook has foodcritic failures
### Improvement
- [COOK-2686]: Add Windows Server 2012 to version.rb so other depending chef scripts can detect Windows Server 2012
## v1.8.10
When using Windows qualified filepaths (C:/foo), the #absolute? method for URI returns true, because "C" is the scheme.
This change checks that the URI is http or https scheme, so it can be passed off to remote_file appropriately.
- [COOK-2729] - allow only http, https URI schemes
## v1.8.8
- [COOK-2729] - helper should use URI rather than regex and bare string
## v1.8.6
- [COOK-968] - `windows_package` provider should gracefully handle paths with spaces
- [COOK-222] - `windows_task` resource does not declare :change action
- [COOK-241] - Windows cookbook should check for redefined constants
- [COOK-248] - Windows package install type is case sensitive
## v1.8.4
- [COOK-2336] - MSI That requires reboot returns with RC 3010 and causes chef run failure
- [COOK-2368] - `version` attribute of the `windows_package` provider should be documented
## v1.8.2
**Important**: Use powershell in nodes expanded run lists to ensure powershell is downloaded, as powershell has a dependency on this cookbook; v1.8.0 created a circular dependency.
- [COOK-2301] - windows 1.8.0 has circular dependency on powershell
## v1.8.0
- [COOK-2126] - Add checksum attribute to `windows_zipfile`
- [COOK-2142] - Add printer and `printer_port` LWRPs
- [COOK-2149] - Chef::Log.debug Windows Package command line
- [COOK-2155] -`windows_package` does not send checksum to `cached_file` in `installer_type`
## v1.7.0
- [COOK-1745] - allow for newer versions of rubyzip
## v1.6.0
- [COOK-2048] - undefined method for Falseclass on task :change when action is :nothing (and task doesn't exist)
- [COOK-2049] - Add `windows_pagefile` resource
## v1.5.0
- [COOK-1251] - Fix LWRP "NotImplementedError"
- [COOK-1921] - Task LWRP will return true for resource exists when no other scheduled tasks exist
- [COOK-1932] - Include :change functionality to windows task lwrp
## v1.4.0:
- [COOK-1571] - `windows_package` resource (with msi provider) does not accept spaces in filename
- [COOK-1581] - Windows cookbook needs a scheduled tasks LWRP
- [COOK-1584] - `windows_registry` should support all registry types
## v1.3.4
- [COOK-1173] - `windows_registry` throws Win32::Registry::Error for action :remove on a nonexistent key
- [COOK-1182] - windows package sets start window title instead of quoting a path
- [COOK-1476] - zipfile lwrp should support :zip action
- [COOK-1485] - package resource fails to perform install correctly when "source" contains quote
- [COOK-1519] - add action :remove for path lwrp
## v1.3.2
- [COOK-1033] - remove the `libraries/ruby_19_patches.rb` file which causes havoc on non-Windows systems.
- [COOK-811] - add a timeout parameter attribute for `windows_package`
## v1.3.0
- [COOK-1323] - Update for changes in Chef 0.10.10.
- Setting file mode doesn't make sense on Windows (package provider
- and `reboot_handler` recipe)
- Prefix ::Win32 to avoid namespace collision with Chef::Win32
- (`registry_helper` library)
- Use chef_gem instead of gem_package so gems get installed correctly under the Ruby environment Chef runs in (reboot_handler recipe, zipfile provider)
## v1.2.12
- [COOK-1037] - specify version for rubyzip gem
- [COOK-1007] - `windows_feature` does not work to remove features with dism
- [COOK-667] - shortcut resource + provider for Windows platforms
## v1.2.10
- [COOK-939] - add `type` parameter to `windows_registry` to allow binary registry keys.
- [COOK-940] - refactor logic so multiple values get created.
## v1.2.8
- FIX: Older Windows (Windows Server 2003) sometimes return 127 on successful forked commands
- FIX: `windows_package`, ensure we pass the WOW* registry redirection flags into reg.open
## v1.2.6
- patch to fix [CHEF-2684], Open4 is named Open3 in Ruby 1.9
- Ruby 1.9's Open3 returns 0 and 42 for successful commands
- retry keyword can only be used in a rescue block in Ruby 1.9
## v1.2.4
- `windows_package` - catch Win32::Registry::Error that pops up when searching certain keys
## v1.2.2
- combined numerous helper libarires for easier sharing across libaries/LWRPs
- renamed Chef::Provider::WindowsFeature::Base file to the more descriptive `feature_base.rb`
- refactored `windows_path` LWRP
- :add action should MODIFY the the underlying ENV variable (vs CREATE)
- deleted greedy :remove action until it could be made more idempotent
- added a `windows_batch` resource/provider for running batch scripts remotely
## v1.2.0
- [COOK-745] gracefully handle required server restarts on Windows platform
- WindowsRebootHandler for requested and pending reboots
- `windows_reboot` LWRP for requesting (receiving notifies) reboots
- `reboot_handler` recipe for enabling WindowsRebootHandler as a report handler
- [COOK-714] Correct initialize misspelling
- RegistryHelper - new `get_values` method which returns all values for a particular key.
## v1.0.8
- [COOK-719] resource/provider for managing windows features
- [COOK-717] remove `windows_env_vars` resource as env resource exists in core chef
- new `Windows::Version` helper class
- refactored `Windows::Helper` mixin
## v1.0.6
- added `force_modify` action to `windows_registry` resource
- add `win_friendly_path` helper
- re-purpose default recipe to install useful supporting windows related gems
## v1.0.4
- [COOK-700] new resources and improvements to the `windows_registry` provider (thanks Paul Morton!)
- Open the registry in the bitednes of the OS
- Provide convenience methods to check if keys and values exit
- Provide convenience method for reading registry values
- NEW - `windows_auto_run` resource/provider
- NEW - `windows_env_vars` resource/provider
- NEW - `windows_path` resource/provider
- re-write of the `windows_package` logic for determining current installed packages
- new checksum attribute for `windows_package` resource...useful for remote packages
## v1.0.2
- [COOK-647] account for Wow6432Node registry redirecter
- [COOK-656] begin/rescue on win32/registry
## v1.0.0
- [COOK-612] initial release
================================================
FILE: CODE_OF_CONDUCT.md
================================================
Please refer to the Chef Community Code of Conduct at <https://www.chef.io/code-of-conduct/>
================================================
FILE: CONTRIBUTING.md
================================================
Please refer to
https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/CONTRIBUTING.MD
================================================
FILE: Gemfile
================================================
# This gemfile provides additional gems for testing and releasing this cookbook
# It is meant to be installed on top of ChefDK / Chef Workstation which provide the majority
# of the necessary gems for testing this cookbook
#
# Run 'chef exec bundle install' to install these dependencies
source 'https://rubygems.org'
gem 'community_cookbook_releaser'
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.
================================================
FILE: README.md
================================================
# Windows Cookbook
[](https://ci.appveyor.com/project/ChefWindowsCookbooks/windows/branch/master) [](https://supermarket.chef.io/cookbooks/windows)
Provides a set of Windows-specific resources to aid in the creation of cookbooks/recipes targeting the Windows platform.
## EOL Notice
This cookbook is no longer required for managing Windows nodes with Chef Infra. The necessary resources and helpers are now built into Chef Infra Client itself. These built-in resources are more feature rich and execute faster.
## Requirements
### Platforms
- Windows 7 (EOL)
- Windows Server 2008 R2 (EOL)
- Windows 8, 8.1
- Windows Server 2012 (R1, R2)
- Windows Server 2016
### Chef
- Chef 14.7+
## Resources
### windows_certificate_binding
Binds a certificate to an HTTP port to enable TLS communication.
#### Actions
- `:create` - creates or updates a binding.
- `:delete` - deletes a binding.
#### Properties
- `cert_name` - name attribute. The thumbprint(hash) or subject that identifies the certificate to be bound.
- `name_kind` - indicates the type of cert_name. One of :subject (default) or :hash.
- `address` - the address to bind against. Default is 0.0.0.0 (all IP addresses). One of:
- IP v4 address `1.2.3.4`
- IP v6 address `[::1]`
- Host name `www.foo.com`
- `port` - the port to bind against. Default is 443.
- `app_id` - the GUID that defines the application that owns the binding. Default is the values used by IIS.
- `store_name` - the store to locate the certificate in. One of:
- MY (Personal)
- CA (Intermediate Certification Authorities)
- ROOT (Trusted Root Certification Authorities)
- TRUSTEDPUBLISHER (Trusted Publishers)
- CLIENTAUTHISSUER (Client Authentication Issuers)
- REMOTE DESKTOP (Remote Desktop)
- TRUSTEDDEVICES (Trusted Devices)
- WEBHOSTING (Web Hosting)
- AUTHROOT (Third-Party Root Certification Authorities)
- TRUSTEDPEOPLE (Trusted People)
- SMARTCARDROOT (Smart Card Trusted Roots)
- TRUST (Enterprise Trust)
#### Examples
```ruby
# Bind the first certificate matching the subject to the default TLS port
windows_certificate_binding "me.acme.com" do
end
```
```ruby
# Bind a cert from the CA store with the given hash to port 4334
windows_certificate_binding "me.acme.com" do
cert_name "d234567890a23f567c901e345bc8901d34567890"
name_kind :hash
store_name "CA"
port 4334
end
```
### windows_dns
`Note`: This resource is now included in Chef 15 and later. If you are using newer versions of [windows](https://devblogs.microsoft.com/powershell/configuration-in-a-devops-world-windows-powershell-desired-state-configuration/) then should use the core [resource](https://github.com/chef/chef/blob/master/RELEASE_NOTES.md#windows_dns_record-resource) instead of windows_dns.
Configures A and CNAME records in Windows DNS. This requires the DNSCMD to be installed, which is done by adding the DNS role to the server or installing the Remote Server Admin Tools.
#### Actions
- :create: creates/updates the DNS entry
- :delete: deletes the DNS entry
#### Properties
- host_name: name attribute. FQDN of the entry to act on.
- dns_server: the DNS server to update. Default is local machine (.)
- record_type: the type of record to create. One of A (default) or CNAME
- target: for A records an array of IP addresses to associate with the host; for CNAME records the FQDN of the host to alias
- ttl: if > 0 then set the time to live of the record
#### Examples
```ruby
# Create A record linked to 2 addresses with a 10 minute ttl
windows_dns "m1.chef.test" do
target ['10.9.8.7', '1.2.3.4']
ttl 600
end
```
```ruby
# Delete records. target is mandatory although not used
windows_dns "m1.chef.test" do
action :delete
target []
end
```
```ruby
# Set an alias against the node in a role
nodes = search( :node, "role:my_service" )
windows_dns "myservice.chef.test" do
record_type 'CNAME'
target nodes[0]['fqdn']
end
```
### windows_http_acl
Sets the Access Control List for an http URL to grant non-admin accounts permission to open HTTP endpoints.
#### Actions
- `:create` - creates or updates the ACL for a URL.
- `:delete` - deletes the ACL from a URL.
#### Properties
- `url` - the name of the url to be created/deleted.
- `sddl` - the DACL string configuring all permissions to URL. Mandatory for create if user is not provided. Can't be use with `user`.
- `user` - the name (domain\user) of the user or group to be granted permission to the URL. Mandatory for create if sddl is not provided. Can't be use with `sddl`. Only one user or group can be granted permission so this replaces any previously defined entry. If you receive a parameter error your user may not exist.
#### Examples
```ruby
windows_http_acl 'http://+:50051/' do
user 'pc\\fred'
end
```
```ruby
# Grant access to users "NT SERVICE\WinRM" and "NT SERVICE\Wecsvc" via sddl
windows_http_acl 'http://+:5985/' do
sddl 'D:(A;;GX;;;S-1-5-80-569256582-2953403351-2909559716-1301513147-412116970)(A;;GX;;;S-1-5-80-4059739203-877974739-1245631912-527174227-2996563517)'
end
```
```ruby
windows_http_acl 'http://+:50051/' do
action :delete
end
```
### windows_schannel
Used to configure the schannel security settings in windows, this is used by dotnet apps and PowerShell to be able to speak to tls 1.2 endpoints
#### Actions
- `configure`: Configures the setting
#### Properties
property | type | default | description
------------------------ | ---------- | ------------- | -----------------------------------------------------------------------------------------------------------------------------------------------------------
`use_strong_crypto` | True, False | true | Enables or disables the setting
### windows_user_privilege
Adds the `principal` (User/Group) to the specified privileges (such as `Logon as a batch job` or `Logon as a Service`).
#### Actions
- `:add` - add the specified privileges to the `principal`
- `:remove` - remove the specified privilege of the `principal`
#### Properties
- `principal` - Name attribute, Required, String. The user or group to be granted privileges.
- `privilege` - Required, String/Array. The privilege(s) to be granted.
#### Examples
Grant the Administrator user the `Logon as a batch job` and `Logon as a service` privilege.
```ruby
windows_user_privilege 'Administrator' do
privilege %w(SeBatchLogonRight SeServiceLogonRight)
end
```
Remove `Logon as a batch job` privilege of Administrator.
```ruby
windows_user_privilege 'Administrator' do
privilege %w(SeBatchLogonRight)
action :remove
end
```
#### Available Privileges
```
SeTrustedCredManAccessPrivilege Access Credential Manager as a trusted caller
SeNetworkLogonRight Access this computer from the network
SeTcbPrivilege Act as part of the operating system
SeMachineAccountPrivilege Add workstations to domain
SeIncreaseQuotaPrivilege Adjust memory quotas for a process
SeInteractiveLogonRight Allow log on locally
SeRemoteInteractiveLogonRight Allow log on through Remote Desktop Services
SeBackupPrivilege Back up files and directories
SeChangeNotifyPrivilege Bypass traverse checking
SeSystemtimePrivilege Change the system time
SeTimeZonePrivilege Change the time zone
SeCreatePagefilePrivilege Create a pagefile
SeCreateTokenPrivilege Create a token object
SeCreateGlobalPrivilege Create global objects
SeCreatePermanentPrivilege Create permanent shared objects
SeCreateSymbolicLinkPrivilege Create symbolic links
SeDebugPrivilege Debug programs
SeDenyNetworkLogonRight Deny access this computer from the network
SeDenyBatchLogonRight Deny log on as a batch job
SeDenyServiceLogonRight Deny log on as a service
SeDenyInteractiveLogonRight Deny log on locally
SeDenyRemoteInteractiveLogonRight Deny log on through Remote Desktop Services
SeEnableDelegationPrivilege Enable computer and user accounts to be trusted for delegation
SeRemoteShutdownPrivilege Force shutdown from a remote system
SeAuditPrivilege Generate security audits
SeImpersonatePrivilege Impersonate a client after authentication
SeIncreaseWorkingSetPrivilege Increase a process working set
SeIncreaseBasePriorityPrivilege Increase scheduling priority
SeLoadDriverPrivilege Load and unload device drivers
SeLockMemoryPrivilege Lock pages in memory
SeBatchLogonRight Log on as a batch job
SeServiceLogonRight Log on as a service
SeSecurityPrivilege Manage auditing and security log
SeRelabelPrivilege Modify an object label
SeSystemEnvironmentPrivilege Modify firmware environment values
SeManageVolumePrivilege Perform volume maintenance tasks
SeProfileSingleProcessPrivilege Profile single process
SeSystemProfilePrivilege Profile system performance
SeUnsolicitedInputPrivilege "Read unsolicited input from a terminal device"
SeUndockPrivilege Remove computer from docking station
SeAssignPrimaryTokenPrivilege Replace a process level token
SeRestorePrivilege Restore files and directories
SeShutdownPrivilege Shut down the system
SeSyncAgentPrivilege Synchronize directory service data
SeTakeOwnershipPrivilege Take ownership of files or other objects
```
### windows_zipfile
`Note`: This resource has been deprecated as Chef Infra Client 15.0 shipped with a new archive_file resource, which natively handles multiple archive formats. Please update any cookbooks using this resource to instead use the `archive_file` resource: https://docs.chef.io/resource_archive_file.html
Most versions of Windows do not ship with native cli utility for managing compressed files. This resource provides a pure-ruby implementation for managing zip files. Be sure to use the `not_if` or `only_if` meta parameters to guard the resource for idempotence or action will be taken every Chef run.
#### Actions
- `:unzip` - unzip a compressed file
- `:zip` - zip a directory (recursively)
#### Properties
- `path` - name attribute. The path where files will be (un)zipped to.
- `source` - source of the zip file (either a URI or local path) for :unzip, or directory to be zipped for :zip.
- `overwrite` - force an overwrite of the files if they already exist.
- `checksum` - for :unzip, useful if source is remote, if the local file matches the SHA-256 checksum, Chef will not download it.
#### Examples
Unzip a remote zip file locally
```ruby
windows_zipfile 'c:/bin' do
source 'http://download.sysinternals.com/Files/SysinternalsSuite.zip'
action :unzip
not_if {::File.exists?('c:/bin/PsExec.exe')}
end
```
Unzip a local zipfile
```ruby
windows_zipfile 'c:/the_codez' do
source 'c:/foo/baz/the_codez.zip'
action :unzip
end
```
Create a local zipfile
```ruby
windows_zipfile 'c:/foo/baz/the_codez.zip' do
source 'c:/the_codez'
action :zip
end
```
## Libraries
### WindowsHelper
Helper that allows you to use helpful functions in windows
#### installed_packages
Returns a hash of all DisplayNames installed
```ruby
# usage in a recipe
::Chef::DSL::Recipe.send(:include, Windows::Helper)
hash_of_installed_packages = installed_packages
```
#### is_package_installed?
- `package_name` - The name of the package you want to query to see if it is installed
- `returns` - true if the package is installed, false if it the package is not installed
Download a file if a package isn't installed
```ruby
# usage in a recipe to not download a file if package is already installed
::Chef::DSL::Recipe.send(:include, Windows::Helper)
is_win_sdk_installed = is_package_installed?('Windows Software Development Kit')
remote_file 'C:\windows\temp\windows_sdk.zip' do
source 'http://url_to_download/windows_sdk.zip'
action :create_if_missing
not_if {is_win_sdk_installed}
end
```
Do something if a package is installed
```ruby
# usage in a provider
include Windows::Helper
if is_package_installed?('Windows Software Development Kit')
# do something if package is installed
end
```
### Windows::VersionHelper
Helper that allows you to get information on the windows version running on your node. It leverages windows ohai from kernel.os_info, easy to mock and to use even on Linux.
#### core_version?
Determines whether the given node is running on a Windows Core.
```ruby
if ::Windows::VersionHelper.core_version? node
fail 'Windows Core is not supported'
end
```
#### workstation_version?
Determines whether the given node is a windows workstation version (XP, Vista, 7, 8, 8.1, 10)
```ruby
if ::Windows::VersionHelper.workstation_version? node
fail 'Only server version of windows are supported'
end
```
#### server_version?
Determines whether the given node is a windows server version (Server 2003, Server 2008, Server 2012, Server 2016)
```ruby
if ::Windows::VersionHelper.server_version? node
puts 'Server version of windows are cool'
end
```
#### nt_version
Determines NT version of the given node
```ruby
case ::Windows::VersionHelper.nt_version node
when '6.0' then 'Windows vista or Server 2008'
when '6.1' then 'Windows 7 or Server 2008R2'
when '6.2' then 'Windows 8 or Server 2012'
when '6.3' then 'Windows 8.1 or Server 2012R2'
when '10.0' then 'Windows 10'
end
```
## Usage
Place an explicit dependency on this cookbook (using depends in the cookbook's metadata.rb) from any cookbook where you would like to use the Windows-specific resources/providers that ship with this cookbook.
```ruby
depends 'windows'
```
## License & Authors
- Author:: Seth Chisamore ([schisamo@chef.io](mailto:schisamo@chef.io))
- Author:: Doug MacEachern ([dougm@vmware.com](mailto:dougm@vmware.com))
- Author:: Paul Morton ([pmorton@biaprotect.com](mailto:pmorton@biaprotect.com))
- Author:: Doug Ireton ([doug.ireton@nordstrom.com](mailto:doug.ireton@nordstrom.com))
```text
Copyright 2011-2018, Chef Software, Inc.
Copyright 2010, VMware, Inc.
Copyright 2011, Business Intelligence Associates, Inc
Copyright 2012, Nordstrom, 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.
```
================================================
FILE: TESTING.md
================================================
Please refer to
<https://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/TESTING.MD>
================================================
FILE: appveyor.yml
================================================
environment:
machine_user: vagrant
machine_pass: vagrant
KITCHEN_YAML: kitchen.appveyor.yml
CHEF_LICENSE: accept
branches:
only:
- master
# Do not build on tags (GitHub only)
skip_tags: true
#faster cloning
clone_depth: 1
# Install the latest nightly of Chef Workstation
install:
- ps: (& cmd /c); iex (irm https://omnitruck.chef.io/install.ps1); Install-Project -Project chef-workstation -channel current
- ps: 'Get-CimInstance win32_operatingsystem -Property Caption, OSArchitecture, Version | fl Caption, OSArchitecture, Version'
- ps: $PSVersionTable
- c:\opscode\chef-workstation\bin\chef-cli.bat exec ruby --version
- ps: secedit /export /cfg $env:temp/export.cfg
- ps: ((get-content $env:temp/export.cfg) -replace ('PasswordComplexity = 1', 'PasswordComplexity = 0')) | Out-File $env:temp/export.cfg
- ps: ((get-content $env:temp/export.cfg) -replace ('MinimumPasswordLength = 8', 'MinimumPasswordLength = 0')) | Out-File $env:temp/export.cfg
- ps: secedit /configure /db $env:windir/security/new.sdb /cfg $env:temp/export.cfg /areas SECURITYPOLICY
- ps: net user /add $env:machine_user $env:machine_pass
- ps: net localgroup administrators $env:machine_user /add
build_script:
- ps: c:\opscode\chef-workstation\bin\chef-cli.bat shell-init powershell | iex; cmd /c c:\opscode\chef-workstation\bin\chef-cli.bat --version
test_script:
- c:\opscode\chef-workstation\bin\chef-cli.bat exec kitchen verify
deploy: off
================================================
FILE: chefignore
================================================
# Put files/directories that should be ignored in this file when uploading
# to a Chef Infra Server or Supermarket.
# Lines that start with '# ' are comments.
# OS generated files #
######################
.DS_Store
ehthumbs.db
Icon?
nohup.out
Thumbs.db
.envrc
# EDITORS #
###########
.#*
.project
.settings
*_flymake
*_flymake.*
*.bak
*.sw[a-z]
*.tmproj
*~
\#*
REVISION
TAGS*
tmtags
.vscode
.editorconfig
## COMPILED ##
##############
*.class
*.com
*.dll
*.exe
*.o
*.pyc
*.so
*/rdoc/
a.out
mkmf.log
# Testing #
###########
.circleci/*
.codeclimate.yml
.delivery/*
.foodcritic
.kitchen*
.mdlrc
.overcommit.yml
.rspec
.rubocop.yml
.travis.yml
.watchr
.yamllint
azure-pipelines.yml
Dangerfile
examples/*
features/*
Guardfile
kitchen.yml*
mlc_config.json
Procfile
Rakefile
spec/*
test/*
# SCM #
#######
.git
.gitattributes
.gitconfig
.github/*
.gitignore
.gitkeep
.gitmodules
.svn
*/.bzr/*
*/.git
*/.hg/*
*/.svn/*
# Berkshelf #
#############
Berksfile
Berksfile.lock
cookbooks/*
tmp
# Bundler #
###########
vendor/*
Gemfile
Gemfile.lock
# Policyfile #
##############
Policyfile.rb
Policyfile.lock.json
# Documentation #
#############
CODE_OF_CONDUCT*
CONTRIBUTING*
documentation/*
TESTING*
UPGRADING*
# Vagrant #
###########
.vagrant
Vagrantfile
================================================
FILE: kitchen.appveyor.yml
================================================
---
driver:
name: proxy
host: localhost
reset_command: "exit 0"
port: 5985
username: <%= ENV["machine_user"] %>
password: <%= ENV["machine_pass"] %>
transport:
name: winrm
elevated: true
provisioner:
name: chef_zero
deprecations_as_errors: true
product_name: chef
product_version: 14.7
platforms:
- name: windows-2012R2
verifier:
name: inspec
suites:
- name: http_acl
run_list:
- recipe[test::http_acl]
- name: user_privilege
run_list:
- recipe[test::user_privilege]
- name: schannel
run_list:
- recipe[test::schannel]
================================================
FILE: kitchen.yml
================================================
driver:
name: vagrant
customize:
cpus: 2
memory: 4096
transport:
name: winrm
elevated: true
provisioner:
name: chef_zero
deprecations_as_errors: true
product_name: chef
product_version: 14.7
verifier:
name: inspec
platforms:
- name: windows-8.1
driver:
box: chef/windows-8.1-enterprise
- name: windows-10
driver:
box: chef/windows-10-enterprise
- name: windows-2012r2
driver:
box: tas50/windows_2012r2
- name: windows-2016
driver:
box: tas50/windows_2016
- name: windows-2019
driver:
box: tas50/windows_2019
suites:
- name: http_acl
run_list:
- recipe[test::http_acl]
- name: schannel
run_list:
- recipe[test::schannel]
- name: zipfile
run_list:
- recipe[test::zipfile]
- name: user_privilege
run_list:
- recipe[test::user_privilege]
- name: everything
run_list:
- recipe[test::everything]
================================================
FILE: libraries/powershell_helper.rb
================================================
#
# 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
elsif cmd.stdout =~ /^(\d+)/
Regexp.last_match(1).to_i
end
rescue Errno::ENOENT
nil
end
end
end
================================================
FILE: libraries/registry_helper.rb
================================================
#
# 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
raise("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)
true
rescue
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)
get_value(reg_key, 'ProfileImagePath')
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)
key_exists?("#{hive_name}\\#{user_hive}")
else
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
================================================
FILE: libraries/version.rb
================================================
#
# 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
================================================
FILE: libraries/version_helper.rb
================================================
#
# 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
================================================
FILE: libraries/windows_helper.rb
================================================
#
# 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::DSL::Recipe.include Windows::Helper
================================================
FILE: libraries/windows_privileged.rb
================================================
#
# 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
================================================
FILE: libraries/wmi_helper.rb
================================================
#
# 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 unless result.each.count > 0
result
end
def wmi_object_property(wmi_object, wmi_property)
wmi_object.send(wmi_property)
end
end
================================================
FILE: metadata.rb
================================================
name 'windows'
maintainer 'Chef Software, Inc.'
maintainer_email 'cookbooks@chef.io'
license 'Apache-2.0'
description 'Provides a set of useful Windows-specific primitives.'
version '7.0.2'
supports 'windows'
source_url 'https://github.com/chef-cookbooks/windows'
issues_url 'https://github.com/chef-cookbooks/windows/issues'
chef_version '>= 14.7'
================================================
FILE: providers/dns.rb
================================================
#
# Author:: Richard Lavey (richard.lavey@calastone.com)
# Cookbook:: windows
# Provider:: dns
#
# Copyright:: 2015, Calastone Ltd.
#
# 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.
#
# See this for info on DNSCMD
# https://technet.microsoft.com/en-gb/library/cc772069.aspx#BKMK_10
include Windows::Helper
action :create do
if @current_resource.exists
needs_change = (@new_resource.record_type != @current_resource.record_type) ||
(@new_resource.ttl > 0 && @new_resource.ttl != @current_resource.ttl) ||
(@new_resource.target.is_a?(String) && @new_resource.target != @current_resource.target) ||
(@new_resource.target.is_a?(Array) && !(@new_resource.target - @current_resource.target).empty?)
if needs_change
converge_by("Changing #{@new_resource.host_name}") do
update_dns
end
else
Chef::Log.debug("#{@new_resource.host_name} already exists - nothing to do")
end
else
converge_by("Creating #{@new_resource.host_name}") do
update_dns
end
end
end
action :delete do
if @current_resource.exists
converge_by("Deleting #{@current_resource.host_name}") do
execute_command! 'recorddelete', "#{@current_resource.record_type} /f"
end
else
Chef::Log.debug("#{@new_resource.host_name} does not exist - nothing to do")
end
end
def load_current_resource
# validate the new resource params : A records should be an array
if @new_resource.record_type == 'A' && @new_resource.target.is_a?(String)
raise 'target property must be an array for record_type A'
end
@current_resource = Chef::Resource::WindowsDns.new(@new_resource.name)
@current_resource.host_name(@new_resource.host_name)
@current_resource.dns_server(@new_resource.dns_server)
parts = @current_resource.host_name.scan(/(\w+)\.(.*)/)
@host = parts[0][0]
@domain = parts[0][1]
fetch_attributes
end
private
def fetch_attributes
@command = locate_sysnative_cmd('dnscmd.exe')
cmd = shell_out("#{@command} #{@current_resource.dns_server} /enumrecords #{@domain} #{@host}")
Chef::Log.debug "dnscmd reports: #{cmd.stdout}"
# extract values from returned text
if cmd.stdout.include?('DNS_ERROR_NAME_DOES_NOT_EXIST')
@current_resource.exists = false
@current_resource.target([])
elsif cmd.exitstatus == 0
@current_resource.exists = true
m = cmd.stdout.scan(/(\d+)\s(A)\s+(\d+\.\d+\.\d+\.\d+)/)
if m.empty?
m = cmd.stdout.scan(/(\d+)\s(CNAME)\s+((?:\w+\.)+)/)
if m.empty?
@current_resource.exists = false
@current_resource.target([])
else
# We have a cname record
@current_resource.record_type('CNAME')
@current_resource.ttl(m[0][0].to_i)
@current_resource.target(m[0][2].chomp('.'))
end
else
# we have A entries
@current_resource.record_type('A')
@current_resource.ttl(m[0][0].to_i)
addresses = []
m.each do |match|
addresses.push(match[2])
end
@current_resource.target(addresses)
end
else
raise "dnscmd returned error #{cmd.exitstatus} : #{cmd.stderr} #{cmd.stdout}"
end
end
def update_dns
ttl = @new_resource.ttl if @new_resource.ttl > 0
if @current_resource.record_type != @new_resource.record_type
# delete current record(s) as we're changing the type
execute_command! 'recorddelete', "#{@current_resource.record_type} /f"
end
if @new_resource.record_type == 'A'
# delete existing records that are no longer defined
(@current_resource.target - @new_resource.target).each do |address|
Chef::Log.info "Deleting #{address}"
execute_command! 'recorddelete', "A #{address} /f"
end
# add new records that don't exist
# if ttl has changed then update all records
addresses = if @current_resource.ttl == @new_resource.ttl
(@new_resource.target - @current_resource.target)
else
@new_resource.target
end
addresses.each do |address|
Chef::Log.info "Adding/Changing #{address}"
execute_command! 'recordadd', "#{ttl} A #{address}"
end
else
execute_command! 'recordadd', "#{ttl} CNAME #{@new_resource.target}"
end
end
def execute_command!(mode, options)
shell_out!("#{@command} #{@current_resource.dns_server} /#{mode} #{@domain} #{@host} #{options}")
end
================================================
FILE: recipes/default.rb
================================================
#
# Author:: Seth Chisamore (<schisamo@chef.io>)
# Cookbook:: windows
# Recipe:: default
#
# 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.
#
Chef::Log.warn('The windows::default recipe has been deprecated. The gems previously installed in this recipe ship in the Chef MSI.')
================================================
FILE: resources/certificate_binding.rb
================================================
#
# Author:: Richard Lavey (richard.lavey@calastone.com)
# Cookbook:: windows
# Resource:: certificate_binding
#
# 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.
#
unified_mode true if respond_to?(:unified_mode)
property :cert_name, String, name_property: true
property :name_kind, Symbol, equal_to: [:hash, :subject], default: :subject
property :address, String, default: '0.0.0.0'
property :port, Integer, default: 443
property :app_id, String, default: '{4dc3e181-e14b-4a21-b022-59fc669b0914}'
property :store_name, String, default: 'MY', equal_to: ['TRUSTEDPUBLISHER', 'CLIENTAUTHISSUER', 'REMOTE DESKTOP', 'ROOT', 'TRUSTEDDEVICES', 'WEBHOSTING', 'CA', 'AUTHROOT', 'TRUSTEDPEOPLE', 'MY', 'SMARTCARDROOT', 'TRUST']
property :exists, [true, false]
load_current_value do |desired|
cmd = shell_out("#{netsh_command} http show sslcert #{address_mode(desired.address)}=#{desired.address}:#{desired.port}")
Chef::Log.debug "netsh reports: #{cmd.stdout}"
address desired.address
port desired.port
store_name desired.store_name
app_id desired.app_id
if cmd.exitstatus == 0
m = cmd.stdout.scan(/Certificate Hash\s+:\s?([A-Fa-f0-9]{40})/)
raise "Failed to extract hash from command output #{cmd.stdout}" if m.empty?
cert_name m[0][0]
name_kind :hash
exists true
else
exists false
end
end
def address_mode(address)
address.match(/(\d+\.){3}\d+|\[.+\]/).nil? ? 'hostnameport' : 'ipport'
end
def netsh_command
# 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.
if ::File.exist?("#{ENV["WINDIR"]}\\sysnative\\netsh.exe")
"#{ENV["WINDIR"]}\\sysnative\\netsh.exe"
elsif ::File.exist?("#{ENV["WINDIR"]}\\system32\\netsh.exe")
"#{ENV["WINDIR"]}\\system32\\netsh.exe"
else
"netsh.exe"
end
end
action :create do
hash = new_resource.name_kind == :subject ? hash_from_subject : new_resource.cert_name
if current_resource.exists
needs_change = (hash.casecmp(current_resource.cert_name) != 0)
if needs_change
converge_by("Changing #{current_resource.address}:#{current_resource.port}") do
delete_binding
add_binding hash
end
else
Chef::Log.debug("#{new_resource.address}:#{new_resource.port} already bound to #{hash} - nothing to do")
end
else
converge_by("Binding #{new_resource.address}:#{new_resource.port}") do
add_binding hash
end
end
end
action :delete do
if current_resource.exists
converge_by("Deleting #{current_resource.address}:#{current_resource.port}") do
delete_binding
end
else
Chef::Log.debug("#{current_resource.address}:#{current_resource.port} not bound - nothing to do")
end
end
action_class do
def add_binding(hash)
cmd = "#{netsh_command} http add sslcert"
mode = address_mode(current_resource.address)
cmd << " #{mode}=#{current_resource.address}:#{current_resource.port}"
cmd << " certhash=#{hash}"
cmd << " appid=\"#{current_resource.app_id}\""
cmd << " certstorename=#{current_resource.store_name}"
check_hash hash
shell_out!(cmd)
end
def delete_binding
mode = address_mode(current_resource.address)
shell_out!("#{netsh_command} http delete sslcert #{mode}=#{current_resource.address}:#{current_resource.port}")
end
def check_hash(hash)
p = powershell_out!("Test-Path \"cert:\\LocalMachine\\#{current_resource.store_name}\\#{hash}\"")
unless p.stderr.empty? && p.stdout =~ /True/i
raise "A Cert with hash of #{hash} doesn't exist in keystore LocalMachine\\#{current_resource.store_name}"
end
nil
end
def hash_from_subject
# escape wildcard subject name (*.acme.com)
subject = new_resource.cert_name.sub(/\*/, '`*')
ps_script = "& { gci cert:\\localmachine\\#{new_resource.store_name} | where { $_.subject -like '*#{subject}*' } | select -first 1 -expandproperty Thumbprint }"
Chef::Log.debug "Running PS script #{ps_script}"
p = powershell_out!(ps_script)
raise "#{ps_script} failed with #{p.stderr}" if p.error?
raise "Couldn't find thumbprint for subject #{new_resource.cert_name}" if p.stdout.nil? || p.stdout.empty?
# seem to get a UTF-8 string with BOM returned sometimes! Strip any such BOM
hash = p.stdout.strip
hash[0].ord == 239 ? hash.force_encoding('UTF-8').delete!("\xEF\xBB\xBF".force_encoding('UTF-8')) : hash
end
end
================================================
FILE: resources/dns.rb
================================================
#
# Author:: Richard Lavey (richard.lavey@calastone.com)
# Cookbook:: windows
# Resource:: dns
#
# Copyright:: 2015, Calastone Ltd.
#
# 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.
#
unified_mode true if respond_to?(:unified_mode)
default_action :create
attribute :host_name, kind_of: String, required: true
attribute :record_type, kind_of: String, default: 'A', regex: /^(?:A|CNAME)$/
attribute :dns_server, kind_of: String, default: '.'
attribute :target, kind_of: [Array, String], required: true
attribute :ttl, kind_of: Integer, required: false, default: 0
attr_accessor :exists
================================================
FILE: resources/http_acl.rb
================================================
#
# Author:: Richard Lavey (richard.lavey@calastone.com)
# Cookbook:: windows
# Resource:: http_acl
#
# Copyright:: 2015-2017, Calastone Ltd.
#
# 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.
#
unified_mode true if respond_to?(:unified_mode)
include Windows::Helper
property :url, String, name_property: true
property :user, String
property :sddl, String
property :exists, [true, false]
# See https://msdn.microsoft.com/en-us/library/windows/desktop/cc307236%28v=vs.85%29.aspx for netsh info
load_current_value do |desired|
cmd_out = shell_out!("#{locate_sysnative_cmd('netsh.exe')} http show urlacl url=#{desired.url}").stdout
Chef::Log.debug "netsh reports: #{cmd_out}"
if cmd_out.include? desired.url
exists true
url desired.url
# Checks first for sddl, because it generates user(s)
sddl_match = cmd_out.match(/SDDL:\s*(?<sddl>\S+)/)
if sddl_match
sddl sddl_match['sddl']
else
# if no sddl, tries to find a single user
user_match = cmd_out.match(/User:\s*(?<user>.+)/)
user user_match['user']
end
else
exists false
end
end
action :create do
raise '`user` xor `sddl` can\'t be used together' if new_resource.user && new_resource.sddl
raise 'When provided user property can\'t be empty' if new_resource.user && new_resource.user.empty?
raise 'When provided sddl property can\'t be empty' if new_resource.sddl && new_resource.sddl.empty?
if current_resource.exists
sddl_changed = (
new_resource.sddl &&
current_resource.sddl &&
current_resource.sddl.casecmp(new_resource.sddl) != 0
)
user_changed = (
new_resource.user &&
current_resource.user &&
current_resource.user.casecmp(new_resource.user) != 0
)
if sddl_changed || user_changed
converge_by("Changing #{new_resource.url}") do
delete_acl
apply_acl
end
else
Chef::Log.debug("#{new_resource.url} already set - nothing to do")
end
else
converge_by("Setting #{new_resource.url}") do
apply_acl
end
end
end
action :delete do
if current_resource.exists
converge_by("Deleting #{new_resource.url}") do
delete_acl
end
else
Chef::Log.debug("#{new_resource.url} does not exist - nothing to do")
end
end
action_class do
def netsh_command
locate_sysnative_cmd('netsh.exe')
end
def apply_acl
if current_resource.sddl
shell_out!("#{netsh_command} http add urlacl url=#{new_resource.url} sddl=\"#{new_resource.sddl}\"")
else
shell_out!("#{netsh_command} http add urlacl url=#{new_resource.url} user=\"#{new_resource.user}\"")
end
end
def delete_acl
shell_out!("#{netsh_command} http delete urlacl url=#{new_resource.url}")
end
end
================================================
FILE: resources/schannel.rb
================================================
#
# Author:: Jason Field (jason.field@calastone.com)
# Cookbook:: windows
# Resource:: schannel
#
# Copyright:: 2019, Calastone Ltd.
#
# 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.
#
unified_mode true if respond_to?(:unified_mode)
property :use_strong_crypto, [true, false], default: true
action :configure do
registry_key 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\.NETFramework\\v4.0.30319' do
values [{
name: 'SchUseStrongCrypto',
type: :dword,
data: new_resource.use_strong_crypto ? 1 : 0,
}]
end
registry_key 'HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\.NETFramework\\v4.0.30319' do
values [{
name: 'SchUseStrongCrypto',
type: :dword,
data: new_resource.use_strong_crypto ? 1 : 0,
}]
end
end
================================================
FILE: resources/user_privilege.rb
================================================
#
# Author:: Jared Kauppila (<jared@kauppi.la>)
# Cookbook:: windows
# Resource:: user_privilege
#
chef_version_for_provides '< 16.0' if respond_to?(:chef_version_for_provides)
property :principal, String, name_property: true
property :privilege, [Array, String], required: true, coerce: proc { |v| Array(v).sort }
action :add do
new_resource.privilege - Array(current_resource.privilege).each do |user_right|
converge_by("adding user privilege #{user_right}") do
Chef::ReservedNames::Win32::Security.add_account_right(new_resource.principal, user_right)
end
end
end
action :remove do
if Gem::Version.new(Chef::VERSION) < Gem::Version.new('14.4.10')
Chef::Log.warn('Chef 14.4.10 is required to use windows_privilege remove action')
else
curr_res_privilege = current_resource.privilege
new_res_privilege = new_resource.privilege
missing_res_privileges = (new_res_privilege - curr_res_privilege)
if missing_res_privileges
Chef::Log.info("Privilege: #{missing_res_privileges.join(', ')} not present. Unable to delete")
end
(new_res_privilege - missing_res_privileges).each do |user_right|
converge_by("removing user privilege #{user_right}") do
Chef::ReservedNames::Win32::Security.remove_account_right(new_resource.principal, user_right)
end
end
end
end
load_current_value do |desired|
privilege Chef::ReservedNames::Win32::Security.get_account_right(desired.principal)
end
================================================
FILE: resources/zipfile.rb
================================================
#
# Author:: Doug MacEachern (<dougm@vmware.com>)
# Author:: Seth Chisamore (<schisamo@chef.io>)
# Author:: Wade Peacock (<wade.peacock@visioncritical.com>)
# Cookbook:: windows
# Resource:: zipfile
#
# Copyright:: 2010-2017, VMware, Inc.
# 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.
#
unified_mode true if respond_to?(:unified_mode)
require 'chef/util/path_helper'
property :path, String, name_property: true
property :source, String
property :overwrite, [true, false], default: false
property :checksum, String
action :unzip do
ensure_rubyzip_gem_installed
Chef::Log.debug("unzip #{new_resource.source} => #{new_resource.path} (overwrite=#{new_resource.overwrite})")
cache_file_path = if new_resource.source =~ %r{^(file|ftp|http|https):\/\/} # http://rubular.com/r/DGoIWjLfGI
uri = as_uri(new_resource.source)
local_cache_path = "#{Chef::Config[:file_cache_path]}/#{::File.basename(::URI.unescape(uri.path))}"
Chef::Log.debug("Caching a copy of file #{new_resource.source} at #{cache_file_path}")
remote_file local_cache_path do
source new_resource.source
backup false
checksum new_resource.checksum unless new_resource.checksum.nil?
end
local_cache_path
else
new_resource.source
end
cache_file_path = Chef::Util::PathHelper.cleanpath(cache_file_path)
converge_by("unzip #{new_resource.source}") do
ruby_block 'Unzipping' do
block do
Zip::File.open(cache_file_path) do |zip|
zip.each do |entry|
path = ::File.join(new_resource.path, entry.name)
FileUtils.mkdir_p(::File.dirname(path))
if new_resource.overwrite && ::File.exist?(path) && !::File.directory?(path)
FileUtils.rm(path)
end
zip.extract(entry, path) unless ::File.exist?(path)
end
end
end
action :run
end
end
end
action :zip do
ensure_rubyzip_gem_installed
# sanitize paths for windows.
new_resource.source.downcase.gsub!(::File::SEPARATOR, ::File::ALT_SEPARATOR)
new_resource.path.downcase.gsub!(::File::SEPARATOR, ::File::ALT_SEPARATOR)
Chef::Log.debug("zip #{new_resource.source} => #{new_resource.path} (overwrite=#{new_resource.overwrite})")
if new_resource.overwrite == false && ::File.exist?(new_resource.path)
Chef::Log.info("file #{new_resource.path} already exists and overwrite is set to false, exiting")
else
# delete the archive if it already exists, because we are recreating it.
if ::File.exist?(new_resource.path)
converge_by("delete existing file at #{new_resource.path}") do
::File.unlink(new_resource.path)
end
end
# only supporting compression of a single directory (recursively).
if ::File.directory?(new_resource.source)
converge_by("zipping #{new_resource.source} to #{new_resource.path}") do
z = Zip::File.new(new_resource.path, true)
unless new_resource.source =~ /::File::ALT_SEPARATOR$/
new_resource.source << ::File::ALT_SEPARATOR
end
Find.find(new_resource.source) do |f|
f.downcase.gsub!(::File::SEPARATOR, ::File::ALT_SEPARATOR)
# don't add root directory to the zipfile.
next if f == new_resource.source
# strip the root directory from the filename before adding it to the zipfile.
zip_fname = f.sub(new_resource.source, '')
Chef::Log.debug("adding #{zip_fname} to archive, sourcefile is: #{f}")
z.add(zip_fname, f)
end
z.close
end
else
Chef::Log.info("Single directory must be specified for compression, and #{new_resource.source} does not meet that criteria.")
end
end
end
action_class do
include Windows::Helper
require 'find'
def ensure_rubyzip_gem_installed
require 'zip'
Chef::Log.warn('The windows_zipfile resource has been deprecated as Chef Infra Client 15.0 shipped with a new archive_file resource, which natively handles multiple archive formats. Please update any cookbooks using this resource to instead use the `archive_file` resource: https://docs.chef.io/resource_archive_file.html')
rescue LoadError
Chef::Log.info("Missing gem 'rubyzip'...installing now.")
chef_gem 'rubyzip' do
action :install
compile_time true
end
require 'zip'
end
end
================================================
FILE: spec/spec_helper.rb
================================================
require 'chefspec'
require 'chefspec/berkshelf'
require 'win32-certstore'
RSpec.configure do |config|
config.color = true # Use color in STDOUT
config.formatter = :documentation # Use the specified formatter
config.log_level = :error # Avoid deprecation notice SPAM
end
================================================
FILE: test/cookbooks/test/files/GeoTrust_Primary_CA.pem
================================================
-----BEGIN CERTIFICATE-----
MIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBY
MQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjExMC8GA1UEAxMo
R2VvVHJ1c3QgUHJpbWFyeSBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEx
MjcwMDAwMDBaFw0zNjA3MTYyMzU5NTlaMFgxCzAJBgNVBAYTAlVTMRYwFAYDVQQK
Ew1HZW9UcnVzdCBJbmMuMTEwLwYDVQQDEyhHZW9UcnVzdCBQcmltYXJ5IENlcnRp
ZmljYXRpb24gQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
AQEAvrgVe//UfH1nrYNke8hCUy3f9oQIIGHWAVlqnEQRr+92/ZV+zmEwu3qDXwK9
AWbK7hWNb6EwnL2hhZ6UOvNWiAAxz9juapYC2e0DjPt1befquFUWBRaa9OBesYjA
ZIVcFU2Ix7e64HXprQU9nceJSOC7KMgD4TCTZF5SwFlwIjVXiIrxlQqD17wxcwE0
7e9GceBrAqg1cmuXm2bgyxx5X9gaBGgeRwLmnWDiNpcB3841kt++Z8dtd1k7j53W
kBWUvEI0EME5+bEnPn7WinXFsq+W06Lem+SYvn3h6YGttm/81w7a4DSwDRp35+MI
mO9Y+pyEtzavwt+s0vQQBnBxNQIDAQABo0IwQDAPBgNVHRMBAf8EBTADAQH/MA4G
A1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQULNVQQZcVi/CPNmFbSvtr2ZnJM5IwDQYJ
KoZIhvcNAQEFBQADggEBAFpwfyzdtzRP9YZRqSa+S7iq8XEN3GHHoOo0Hnp3DwQ1
6CePbJC/kRYkRj5KTs4rFtULUh38H2eiAkUxT87z+gOneZ1TatnaYzr4gNfTmeGl
4b7UVXGYNTq+k+qurUKykG/g/CFNNWMziUnWm07Kx+dOCQD32sfvmWKZd7aVIl6K
oKv0uHiYyjgZmclynnjNS6yvGaBzEi38wkG6gZHaFloxt/m0cYASSJlyc1pZU8Fj
UjPtp8nSOQJw+uCxQmYpqptR7TBUIhRf2asdweSU8Pj1K/fqynhG1riR/aYNKxoU
AT6A8EKglQdebc3MS6RFjasS6LPeWuWgfOgPIh1a6Vk=
-----END CERTIFICATE-----
================================================
FILE: test/cookbooks/test/files/GeoTrust_Universal_CA.pem
================================================
-----BEGIN CERTIFICATE-----
MIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEW
MBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEeMBwGA1UEAxMVR2VvVHJ1c3QgVW5pdmVy
c2FsIENBMB4XDTA0MDMwNDA1MDAwMFoXDTI5MDMwNDA1MDAwMFowRTELMAkGA1UE
BhMCVVMxFjAUBgNVBAoTDUdlb1RydXN0IEluYy4xHjAcBgNVBAMTFUdlb1RydXN0
IFVuaXZlcnNhbCBDQTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAKYV
VaCjxuAfjJ0hUNfBvitbtaSeodlyWL0AG0y/YckUHUWCq8YdgNY96xCcOq9tJPi8
cQGeBvV8Xx7BDlXKg5pZMK4ZyzBIle0iN430SppyZj6tlcDgFgDgEB8rMQ7XlFTT
QjOgNB0eRXbdT8oYN+yFFXoZCPzVx5zw8qkuEKmS5j1YPakWaDwvdSEYfyh3peFh
F7em6fgemdtzbvQKoiFs7tqqhZJmr/Z6a4LauiIINQ/PQvE1+mrufislzDoR5G2v
c7J2Ha3QsnhnGqQ5HFELZ1aD/ThdDc7d8Lsrlh/eezJS/R27tQahsiFepdaVaH/w
mZ7cRQg+59IJDTWU3YBOU5fXtQlEIGQWFwMCTFMNaN7VqnJNk22CDtucvc+081xd
VHppCZbW2xHBjXWotM85yM48vCR85mLK4b19p71XZQvk/iXttmkQ3CgaRr0BHdCX
teGYO8A3ZNY9lO4L4fUorgtWv3GLIylBjobFS1J72HGrH4oVpjuDWtdYAVHGTEHZ
f9hBZ3KiKN9gg6meyHv8U3NyWfWTehd2Ds735VzZC1U0oqpbtWpU5xPKV+yXbfRe
Bi9Fi1jUIxaS5BZuKGNZMN9QAZxjiRqf2xeUgnA3wySemkfWWspOqGmJch+RbNt+
nhutxx9z3SxPGWX9f5NAEC7S8O08ni4oPmkmM8V7AgMBAAGjYzBhMA8GA1UdEwEB
/wQFMAMBAf8wHQYDVR0OBBYEFNq7LqqwDLiIJlF0XG0D08DYj3rWMB8GA1UdIwQY
MBaAFNq7LqqwDLiIJlF0XG0D08DYj3rWMA4GA1UdDwEB/wQEAwIBhjANBgkqhkiG
9w0BAQUFAAOCAgEAMXjmx7XfuJRAyXHEqDXsRh3ChfMoWIawC/yOsjmPRFWrZIRc
aanQmjg8+uUfNeVE44B5lGiku8SfPeE0zTBGi1QrlaXv9z+ZhP015s8xxtxqv6fX
IwjhmF7DWgh2qaavdy+3YL1ERmrvl/9zlcGO6JP7/TG37FcREUWbMPEaiDnBTzyn
ANXH/KttgCJwpQzgXQQpAvvLoJHRfNbDflDVnVi+QTjruXU8FdmbyUqDWcDaU/0z
uzYYm4UPFd3uLax2k7nZAY1IEKj79TiG8dsKxr2EoyNB3tZ3b4XUhRxQ4K5RirqN
Pnbiucon8l+f725ZDQbYKxek0nxru18UGkiPGkzns0ccjkxFKyDuSN/n3QmOGKja
QI2SJhFTYXNd673nxE0pN2HrrDktZy4W1vUAg4WhzH92xH3kt0tm7wNFYGm2DFKW
koRepqO1pD4r2czYG0eq8kTaT/kD6PAUyz/zg97QwVTjt+gKN02LIFkDMBmhLMi9
ER/frslKxfMnZmaGrGiR/9nmUxwPi1xpZQomyB40w11Re9epnAahNt3ViZS82eQt
DF4JbAiXfKM9fJP/P6EUp8+1Xevb2xzEdt+Iub1FBZUbrvxGakyvSOPOrg/Sfuvm
bJxPgWp6ZKy7PtXny3YuxadIwVyQD8vIP/rmMuGNG2+k5o7Y+SlIis5z/iw=
-----END CERTIFICATE-----
================================================
FILE: test/cookbooks/test/files/base64-cert2.cer
================================================
-----BEGIN CERTIFICATE-----
MIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh
MB8GA1UEChMYVGhlIEdvIERhZGR5IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBE
YWRkeSBDbGFzcyAyIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MB4XDTA0MDYyOTE3
MDYyMFoXDTM0MDYyOTE3MDYyMFowYzELMAkGA1UEBhMCVVMxITAfBgNVBAoTGFRo
ZSBHbyBEYWRkeSBHcm91cCwgSW5jLjExMC8GA1UECxMoR28gRGFkZHkgQ2xhc3Mg
MiBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTCCASAwDQYJKoZIhvcNAQEBBQADggEN
ADCCAQgCggEBAN6d1+pXGEmhW+vXX0iG6r7d/+TvZxz0ZWizV3GgXne77ZtJ6XCA
PVYYYwhv2vLM0D9/AlQiVBDYsoHUwHU9S3/Hd8M+eKsaA7Ugay9qK7HFiH7Eux6w
wdhFJ2+qN1j3hybX2C32qRe3H3I2TqYXP2WYktsqbl2i/ojgC95/5Y0V4evLOtXi
EqITLdiOr18SPaAIBQi2XKVlOARFmR6jYGB0xUGlcmIbYsUfb18aQr4CUWWoriMY
avx4A6lNf4DD+qta/KFApMoZFv6yyO9ecw3ud72a9nmYvLEHZ6IVDd2gWMZEewo+
YihfukEHU1jPEX44dMX4/7VpkI+EdOqXG68CAQOjgcAwgb0wHQYDVR0OBBYEFNLE
sNKR1EwRcbNhyz2h/t2oatTjMIGNBgNVHSMEgYUwgYKAFNLEsNKR1EwRcbNhyz2h
/t2oatTjoWekZTBjMQswCQYDVQQGEwJVUzEhMB8GA1UEChMYVGhlIEdvIERhZGR5
IEdyb3VwLCBJbmMuMTEwLwYDVQQLEyhHbyBEYWRkeSBDbGFzcyAyIENlcnRpZmlj
YXRpb24gQXV0aG9yaXR5ggEAMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQAD
ggEBADJL87LKPpH8EsahB4yOd6AzBhRckB4Y9wimPQoZ+YeAEW5p5JYXMP80kWNy
OO7MHAGjHZQopDH2esRU1/blMVgDoszOYtuURXO1v0XJJLXVggKtI3lpjbi2Tc7P
TMozI+gciKqdi0FuFskg5YmezTvacPd+mSYgFFQlq25zheabIZ0KbIIOqPjCDPoQ
HmyW74cNxA9hi63ugyuV+I6ShHI56yDqg+2DzZduCLzrTia2cyvk0/ZM/iZx4mER
dEr/VxqHD3VILs9RaRegAhJhldXRQLIQTO7ErBBDpqWeCtWVYpoNz4iCxTIM5Cuf
ReYNnyicsbkqWletNw+vHX/bvZ8=
-----END CERTIFICATE-----
================================================
FILE: test/cookbooks/test/files/test_p7b.p7b
================================================
-----BEGIN PKCS7-----
MIIDpgYJKoZIhvcNAQcCoIIDlzCCA5MCAQExADALBgkqhkiG9w0BBwGgggN5MIID
dTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UE
BhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3Qg
Q0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBa
Fw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxT
aWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxTaWdu
IFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZjc6j
40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0S
y6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrj
sok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUO
hugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Q
zns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N89iFo
7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTAD
AQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF
AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1h
TdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38Nf
lNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEV
tQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUadDKqC
5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbMEHMUf
pIBvFSDJ3gyICh3WZlXi/EjJKSZp4KEAMQA=
-----END PKCS7-----
================================================
FILE: test/cookbooks/test/metadata.rb
================================================
name 'test'
version '0.0.1'
depends 'windows'
================================================
FILE: test/cookbooks/test/recipes/everything.rb
================================================
include_recipe '::http_acl'
include_recipe '::user_privilege'
include_recipe '::zipfile'
================================================
FILE: test/cookbooks/test/recipes/http_acl.rb
================================================
user 'space user' do
password 'Pass@word1'
end
windows_http_acl 'http://google.com:80/' do
user "#{ENV['COMPUTERNAME']}\\space user"
end
windows_http_acl 'http://+:50051/' do
user "#{ENV['COMPUTERNAME']}\\space user"
end
# Grant access to users "NT SERVICE\WinRM" and "NT SERVICE\Wecsvc" via sddl
windows_http_acl 'http://+:5985/' do
sddl 'D:(A;;GX;;;S-1-5-80-569256582-2953403351-2909559716-1301513147-412116970)' \
+ '(A;;GX;;;S-1-5-80-4059739203-877974739-1245631912-527174227-2996563517)'
end
windows_http_acl 'http://+:50051/' do
action :delete
end
================================================
FILE: test/cookbooks/test/recipes/schannel.rb
================================================
windows_schannel 'tls 1.2' do
end
================================================
FILE: test/cookbooks/test/recipes/user_privilege.rb
================================================
# Adding 5 Privileges
windows_user_privilege 'vagrant' do
privilege %w(SeIncreaseQuotaPrivilege SeServiceLogonRight SeTimeZonePrivilege SeCreateTokenPrivilege SeBackupPrivilege)
action :add
end
# Removing 3 of them
windows_user_privilege 'vagrant' do
privilege %w(SeIncreaseQuotaPrivilege SeServiceLogonRight SeTimeZonePrivilege)
action :remove
end
# Removing 1 from already removed
windows_user_privilege 'vagrant' do
privilege %w(SeIncreaseQuotaPrivilege)
action :remove
end
# Removing few present & few already removed
windows_user_privilege 'vagrant' do
privilege %w(SeServiceLogonRight SeTimeZonePrivilege SeCreateTokenPrivilege SeBackupPrivilege)
action :remove
end
================================================
FILE: test/cookbooks/test/recipes/zipfile.rb
================================================
directory 'create test dir' do
path 'C:\testdir'
action :create
end
file 'C:\testdir\testfile1' do
content 'test file 1'
action :create
end
file 'C:\testdir\testfile2' do
content 'test file 2'
action :create
end
windows_zipfile 'C:\test.zip' do
source 'C:\testdir'
action :zip
end
directory 'delete test dir' do
path 'C:\testdir'
action :delete
recursive true
end
windows_zipfile 'C:\testdir' do
source 'C:\test.zip'
action :unzip
end
windows_zipfile 'C:\test\windows' do
source 'https://github.com/chef-cookbooks/windows/archive/master.zip'
action :unzip
end
================================================
FILE: test/integration/http_acl/http_acl_spec.rb
================================================
describe command('netsh http show urlacl url=http://google.com:80/') do
its('exit_status') { should eq 0 }
its('stdout') { should_not match /^space user/ }
end
================================================
FILE: test/integration/schannel/schannel_spec.rb
================================================
describe powershell('[Net.ServicePointManager]::SecurityProtocol') do
its('strip') { should match /Tls12/ }
end
gitextract_io839hx9/
├── .delivery/
│ └── project.toml
├── .editorconfig
├── .gitattributes
├── .github/
│ ├── CODEOWNERS
│ └── workflows/
│ ├── branchcleanup.yml
│ └── delivery.yml
├── .gitignore
├── .rubocop.yml
├── .vscode/
│ └── extensions.json
├── Berksfile
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── Gemfile
├── LICENSE
├── README.md
├── TESTING.md
├── appveyor.yml
├── chefignore
├── kitchen.appveyor.yml
├── kitchen.yml
├── libraries/
│ ├── powershell_helper.rb
│ ├── registry_helper.rb
│ ├── version.rb
│ ├── version_helper.rb
│ ├── windows_helper.rb
│ ├── windows_privileged.rb
│ └── wmi_helper.rb
├── metadata.rb
├── providers/
│ └── dns.rb
├── recipes/
│ └── default.rb
├── resources/
│ ├── certificate_binding.rb
│ ├── dns.rb
│ ├── http_acl.rb
│ ├── schannel.rb
│ ├── user_privilege.rb
│ └── zipfile.rb
├── spec/
│ └── spec_helper.rb
└── test/
├── cookbooks/
│ └── test/
│ ├── files/
│ │ ├── Asimov.otf
│ │ ├── CodeNewRoman.otf
│ │ ├── DigiCertAssuredIDCAG2.crt
│ │ ├── GeoTrust_Primary_CA.pem
│ │ ├── GeoTrust_Universal_CA.pem
│ │ ├── ThawteRSACA2018.crt
│ │ ├── base64-cert2.cer
│ │ ├── der-cert1.cer
│ │ ├── test-cert.cer
│ │ ├── test-cert.pfx
│ │ ├── test-cert.pvk
│ │ ├── test-pfx-certificate.pfx
│ │ ├── test_der.der
│ │ └── test_p7b.p7b
│ ├── metadata.rb
│ └── recipes/
│ ├── everything.rb
│ ├── http_acl.rb
│ ├── schannel.rb
│ ├── user_privilege.rb
│ └── zipfile.rb
└── integration/
├── http_acl/
│ └── http_acl_spec.rb
└── schannel/
└── schannel_spec.rb
SYMBOL INDEX (73 symbols across 11 files)
FILE: libraries/powershell_helper.rb
type Powershell (line 23) | module Powershell
type Helper (line 24) | module Helper
function powershell_installed? (line 27) | def powershell_installed?
function interpreter (line 31) | def interpreter
function powershell_version (line 42) | def powershell_version
FILE: libraries/registry_helper.rb
type Windows (line 30) | module Windows
type RegistryHelper (line 31) | module RegistryHelper
function get_hive_name (line 39) | def get_hive_name(path)
function get_hive (line 55) | def get_hive(path)
function unload_hive (line 76) | def unload_hive(path)
function set_value (line 88) | def set_value(mode, path, values, type = nil)
function get_value (line 134) | def get_value(path, value)
function get_values (line 149) | def get_values(path)
function delete_value (line 166) | def delete_value(path, values)
function create_key (line 184) | def create_key(path)
function value_exists? (line 191) | def value_exists?(path, value)
function key_exists? (line 217) | def key_exists?(path, load_hive = false)
function get_user_hive_location (line 240) | def get_user_hive_location(sid)
function resolve_user_to_sid (line 248) | def resolve_user_to_sid(username)
function hive_loaded? (line 263) | def hive_loaded?(path)
function user_hive? (line 276) | def user_hive?(hive)
function get_reg_path_info (line 280) | def get_reg_path_info(path)
function load_user_hive (line 296) | def load_user_hive(hive, reg_path, user_hive)
function ensure_hive_unloaded (line 341) | def ensure_hive_unloaded(hive_loaded = false)
type Registry (line 350) | module Registry
FILE: libraries/version.rb
type Windows (line 25) | module Windows
class Version (line 26) | class Version
method initialize (line 122) | def initialize
method get_os_info (line 177) | def get_os_info
FILE: libraries/version_helper.rb
type Windows (line 20) | module Windows
type VersionHelper (line 22) | module VersionHelper
type CoreSKU (line 26) | module CoreSKU
type ProductType (line 58) | module ProductType
function core_version? (line 65) | def self.core_version?(node)
function workstation_version? (line 72) | def self.workstation_version?(node)
function server_version? (line 78) | def self.server_version?(node)
function nt_version (line 83) | def self.nt_version(node)
function validate_platform (line 89) | def self.validate_platform(node)
FILE: libraries/windows_helper.rb
type Windows (line 27) | module Windows
type Helper (line 28) | module Helper
function win_friendly_path (line 35) | def win_friendly_path(path)
function locate_sysnative_cmd (line 44) | def locate_sysnative_cmd(cmd)
function win_version (line 55) | def win_version
function as_uri (line 60) | def as_uri(source)
function cached_file (line 69) | def cached_file(source, checksum = nil, windows_path = true)
function expand_env_vars (line 90) | def expand_env_vars(path)
function is_package_installed? (line 97) | def is_package_installed?(package_name) # rubocop:disable Naming/Pre...
function installed_packages (line 101) | def installed_packages
function to_array (line 119) | def to_array(var)
function extract_installed_packages_from_key (line 126) | def extract_installed_packages_from_key(hkey = ::Win32::Registry::HK...
FILE: libraries/windows_privileged.rb
class Chef (line 24) | class Chef
class WindowsPrivileged (line 25) | class WindowsPrivileged
method reg_load_key (line 27) | def reg_load_key(name, file)
method reg_unload_key (line 43) | def reg_unload_key(name)
method run (line 52) | def run(*privileges)
method adjust_privilege (line 77) | def adjust_privilege(token, priv, attr = 0)
method load_deps (line 89) | def load_deps
FILE: libraries/wmi_helper.rb
function execute_wmi_query (line 24) | def execute_wmi_query(wmi_query)
function wmi_object_property (line 31) | def wmi_object_property(wmi_object, wmi_property)
FILE: providers/dns.rb
function load_current_resource (line 57) | def load_current_resource
function fetch_attributes (line 76) | def fetch_attributes
function update_dns (line 115) | def update_dns
function execute_command! (line 146) | def execute_command!(mode, options)
FILE: resources/certificate_binding.rb
function address_mode (line 52) | def address_mode(address)
function netsh_command (line 56) | def netsh_command
function add_binding (line 102) | def add_binding(hash)
function delete_binding (line 114) | def delete_binding
function check_hash (line 119) | def check_hash(hash)
function hash_from_subject (line 128) | def hash_from_subject
FILE: resources/http_acl.rb
function netsh_command (line 96) | def netsh_command
function apply_acl (line 100) | def apply_acl
function delete_acl (line 108) | def delete_acl
FILE: resources/zipfile.rb
function ensure_rubyzip_gem_installed (line 119) | def ensure_rubyzip_gem_installed
Condensed preview — 60 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (155K chars).
[
{
"path": ".delivery/project.toml",
"chars": 119,
"preview": "remote_file = \"https://raw.githubusercontent.com/chef-cookbooks/community_cookbook_tools/master/delivery/project.toml\"\n"
},
{
"path": ".editorconfig",
"chars": 353,
"preview": "# https://EditorConfig.org\n\n# top-most EditorConfig file\nroot=true\n\n# Unix-style newlines with a newline ending every fi"
},
{
"path": ".gitattributes",
"chars": 19,
"preview": "* text=auto eol=lf\n"
},
{
"path": ".github/CODEOWNERS",
"chars": 31,
"preview": "* @chef-cookbooks/windows-team\n"
},
{
"path": ".github/workflows/branchcleanup.yml",
"chars": 386,
"preview": "---\nname: Branch Cleanup\n# This workflow is triggered on all closed pull requests.\n# However the script does not do anyt"
},
{
"path": ".github/workflows/delivery.yml",
"chars": 286,
"preview": "name: delivery\n\non: [push, pull_request]\n\njobs:\n delivery:\n\n runs-on: ubuntu-latest\n\n steps:\n - name: Check ou"
},
{
"path": ".gitignore",
"chars": 475,
"preview": "*.rbc\n.config\nInstalledFiles\nlib/bundler/man\npkg\ntest/tmp\ntest/version_tmp\ntmp\n_Store\n*~\n*#\n.#*\n\\#*#\n*.un~\n*.tmp\n*.bk\n*."
},
{
"path": ".rubocop.yml",
"chars": 345,
"preview": "ChefModernize/WindowsZipfileUsage:\n Enabled: false\n\nLint/ShadowingOuterLocalVariable:\n Exclude:\n - 'libraries/regis"
},
{
"path": ".vscode/extensions.json",
"chars": 115,
"preview": "{\n \"recommendations\": [\n \"chef-software.chef\",\n \"rebornix.ruby\",\n \"editorconfig.editorconfig\"\n ]\n}"
},
{
"path": "Berksfile",
"chars": 123,
"preview": "source 'https://supermarket.chef.io'\n\nmetadata\n\ngroup :integration do\n cookbook 'test', path: './test/cookbooks/test'\ne"
},
{
"path": "CHANGELOG.md",
"chars": 42661,
"preview": "# windows Cookbook CHANGELOG\n\nThis file is used to list changes made in each version of the windows cookbook.\n\n## 7.0.2 "
},
{
"path": "CODE_OF_CONDUCT.md",
"chars": 93,
"preview": "Please refer to the Chef Community Code of Conduct at <https://www.chef.io/code-of-conduct/>\n"
},
{
"path": "CONTRIBUTING.md",
"chars": 111,
"preview": "Please refer to\nhttps://github.com/chef-cookbooks/community_cookbook_documentation/blob/master/CONTRIBUTING.MD\n"
},
{
"path": "Gemfile",
"chars": 354,
"preview": "# This gemfile provides additional gems for testing and releasing this cookbook\n# It is meant to be installed on top of "
},
{
"path": "LICENSE",
"chars": 11358,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 15157,
"preview": "# Windows Cookbook\n\n[\n# Cookbook:: windows\n# Library:: powershell_helper\n#\n# Copyright:: 2011"
},
{
"path": "libraries/registry_helper.rb",
"chars": 10883,
"preview": "#\n# Author:: Doug MacEachern (<dougm@vmware.com>)\n# Author:: Seth Chisamore (<schisamo@chef.io>)\n# Author:: Paul Morton "
},
{
"path": "libraries/version.rb",
"chars": 12214,
"preview": "#\n# Author:: Seth Chisamore (<schisamo@chef.io>)\n# Cookbook:: windows\n# Library:: version\n#\n# Copyright:: 2011-2018, Che"
},
{
"path": "libraries/version_helper.rb",
"chars": 3991,
"preview": "#\n# Cookbook:: windows\n# Library:: version_helper\n# Author:: Baptiste Courtois (<b.courtois@criteo.com>)\n#\n# Copyright::"
},
{
"path": "libraries/windows_helper.rb",
"chars": 6613,
"preview": "#\n# Author:: Seth Chisamore (<schisamo@chef.io>)\n# Cookbook:: windows\n# Library:: windows_helper\n#\n# Copyright:: 2011-20"
},
{
"path": "libraries/windows_privileged.rb",
"chars": 2796,
"preview": "#\n# Author:: Doug MacEachern <dougm@vmware.com>\n# Author:: Paul Morton (<pmorton@biaprotect.com>)\n# Cookbook:: windows\n#"
},
{
"path": "libraries/wmi_helper.rb",
"chars": 1022,
"preview": "#\n# Author:: Adam Edwards (<adamed@chef.io>)\n# Cookbook:: windows\n# Library:: wmi_helper\n#\n# Copyright:: 2014-2018, Chef"
},
{
"path": "metadata.rb",
"chars": 414,
"preview": "name 'windows'\nmaintainer 'Chef Software, Inc.'\nmaintainer_email 'cookbooks@chef.io'\nlicense "
},
{
"path": "providers/dns.rb",
"chars": 4883,
"preview": "#\n# Author:: Richard Lavey (richard.lavey@calastone.com)\n# Cookbook:: windows\n# Provider:: dns\n#\n# Copyright:: 2015, Cal"
},
{
"path": "recipes/default.rb",
"chars": 819,
"preview": "#\n# Author:: Seth Chisamore (<schisamo@chef.io>)\n# Cookbook:: windows\n# Recipe:: default\n#\n# Copyright:: 2011-2018, Chef"
},
{
"path": "resources/certificate_binding.rb",
"chars": 5077,
"preview": "#\n# Author:: Richard Lavey (richard.lavey@calastone.com)\n# Cookbook:: windows\n# Resource:: certificate_binding\n#\n# Copyr"
},
{
"path": "resources/dns.rb",
"chars": 1084,
"preview": "#\n# Author:: Richard Lavey (richard.lavey@calastone.com)\n# Cookbook:: windows\n# Resource:: dns\n#\n# Copyright:: 2015, Cal"
},
{
"path": "resources/http_acl.rb",
"chars": 3236,
"preview": "#\n# Author:: Richard Lavey (richard.lavey@calastone.com)\n# Cookbook:: windows\n# Resource:: http_acl\n#\n# Copyright:: 2015"
},
{
"path": "resources/schannel.rb",
"chars": 1269,
"preview": "#\n# Author:: Jason Field (jason.field@calastone.com)\n# Cookbook:: windows\n# Resource:: schannel\n#\n# Copyright:: 2019, Ca"
},
{
"path": "resources/user_privilege.rb",
"chars": 1463,
"preview": "#\n# Author:: Jared Kauppila (<jared@kauppi.la>)\n# Cookbook:: windows\n# Resource:: user_privilege\n#\n\nchef_version_for_pro"
},
{
"path": "resources/zipfile.rb",
"chars": 5087,
"preview": "#\n# Author:: Doug MacEachern (<dougm@vmware.com>)\n# Author:: Seth Chisamore (<schisamo@chef.io>)\n# Author:: Wade Peacock"
},
{
"path": "spec/spec_helper.rb",
"chars": 299,
"preview": "require 'chefspec'\nrequire 'chefspec/berkshelf'\nrequire 'win32-certstore'\n\nRSpec.configure do |config|\n config.color = "
},
{
"path": "test/cookbooks/test/files/GeoTrust_Primary_CA.pem",
"chars": 1269,
"preview": "-----BEGIN CERTIFICATE-----\nMIIDfDCCAmSgAwIBAgIQGKy1av1pthU6Y2yv2vrEoTANBgkqhkiG9w0BAQUFADBY\nMQswCQYDVQQGEwJVUzEWMBQGA1U"
},
{
"path": "test/cookbooks/test/files/GeoTrust_Universal_CA.pem",
"chars": 1935,
"preview": "-----BEGIN CERTIFICATE-----\nMIIFaDCCA1CgAwIBAgIBATANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEW\nMBQGA1UEChMNR2VvVHJ1c3QgSW5"
},
{
"path": "test/cookbooks/test/files/base64-cert2.cer",
"chars": 1472,
"preview": "-----BEGIN CERTIFICATE-----\r\nMIIEADCCAuigAwIBAgIBADANBgkqhkiG9w0BAQUFADBjMQswCQYDVQQGEwJVUzEh\r\nMB8GA1UEChMYVGhlIEdvIERhZ"
},
{
"path": "test/cookbooks/test/files/test_p7b.p7b",
"chars": 1314,
"preview": "-----BEGIN PKCS7-----\nMIIDpgYJKoZIhvcNAQcCoIIDlzCCA5MCAQExADALBgkqhkiG9w0BBwGgggN5MIID\ndTCCAl2gAwIBAgILBAAAAAABFUtaw5QwD"
},
{
"path": "test/cookbooks/test/metadata.rb",
"chars": 49,
"preview": "name 'test'\nversion '0.0.1'\ndepends 'windows'\n"
},
{
"path": "test/cookbooks/test/recipes/everything.rb",
"chars": 89,
"preview": "include_recipe '::http_acl'\ninclude_recipe '::user_privilege'\ninclude_recipe '::zipfile'\n"
},
{
"path": "test/cookbooks/test/recipes/http_acl.rb",
"chars": 575,
"preview": "user 'space user' do\n password 'Pass@word1'\nend\n\nwindows_http_acl 'http://google.com:80/' do\n user \"#{ENV['COMPUTERNAM"
},
{
"path": "test/cookbooks/test/recipes/schannel.rb",
"chars": 34,
"preview": "windows_schannel 'tls 1.2' do\nend\n"
},
{
"path": "test/cookbooks/test/recipes/user_privilege.rb",
"chars": 691,
"preview": "# Adding 5 Privileges\nwindows_user_privilege 'vagrant' do\n privilege %w(SeIncreaseQuotaPrivilege SeServiceLogonRight Se"
},
{
"path": "test/cookbooks/test/recipes/zipfile.rb",
"chars": 596,
"preview": "directory 'create test dir' do\n path 'C:\\testdir'\n action :create\nend\n\nfile 'C:\\testdir\\testfile1' do\n content 'test "
},
{
"path": "test/integration/http_acl/http_acl_spec.rb",
"chars": 164,
"preview": "describe command('netsh http show urlacl url=http://google.com:80/') do\n its('exit_status') { should eq 0 }\n its('stdo"
},
{
"path": "test/integration/schannel/schannel_spec.rb",
"chars": 114,
"preview": "describe powershell('[Net.ServicePointManager]::SecurityProtocol') do\n its('strip') { should match /Tls12/ }\nend\n"
}
]
// ... and 10 more files (download for full content)
About this extraction
This page contains the full source code of the chef-cookbooks/windows GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 60 files (144.0 KB), approximately 41.0k tokens, and a symbol index with 73 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.