knife-windows 0.8.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. checksums.yaml +5 -13
  2. data/.gitignore +1 -0
  3. data/.travis.yml +16 -2
  4. data/CHANGELOG.md +38 -4
  5. data/DOC_CHANGES.md +331 -15
  6. data/Gemfile +2 -1
  7. data/README.md +306 -71
  8. data/RELEASE_NOTES.md +63 -43
  9. data/Rakefile +9 -4
  10. data/appveyor.yml +42 -0
  11. data/ci.gemfile +15 -0
  12. data/knife-windows.gemspec +6 -4
  13. data/lib/chef/knife/bootstrap/windows-chef-client-msi.erb +96 -71
  14. data/lib/chef/knife/bootstrap_windows_base.rb +219 -37
  15. data/lib/chef/knife/bootstrap_windows_ssh.rb +22 -5
  16. data/lib/chef/knife/bootstrap_windows_winrm.rb +24 -24
  17. data/lib/chef/knife/core/windows_bootstrap_context.rb +146 -12
  18. data/lib/chef/knife/knife_windows_base.rb +33 -0
  19. data/lib/chef/knife/windows_cert_generate.rb +155 -0
  20. data/lib/chef/knife/windows_cert_install.rb +68 -0
  21. data/lib/chef/knife/windows_helper.rb +3 -1
  22. data/lib/chef/knife/windows_listener_create.rb +107 -0
  23. data/lib/chef/knife/winrm.rb +103 -206
  24. data/lib/chef/knife/winrm_base.rb +30 -11
  25. data/lib/chef/knife/winrm_knife_base.rb +218 -0
  26. data/lib/chef/knife/winrm_session.rb +81 -0
  27. data/lib/chef/knife/winrm_shared_options.rb +47 -0
  28. data/lib/chef/knife/wsman_endpoint.rb +44 -0
  29. data/lib/chef/knife/wsman_test.rb +96 -0
  30. data/lib/knife-windows/path_helper.rb +234 -0
  31. data/lib/knife-windows/version.rb +1 -1
  32. data/spec/assets/win_template_rendered_with_bootstrap_install_command.txt +217 -0
  33. data/spec/assets/win_template_rendered_without_bootstrap_install_command.txt +329 -0
  34. data/spec/assets/win_template_unrendered.txt +246 -0
  35. data/spec/functional/bootstrap_download_spec.rb +129 -35
  36. data/spec/spec_helper.rb +28 -1
  37. data/spec/unit/knife/bootstrap_options_spec.rb +150 -0
  38. data/spec/unit/knife/bootstrap_template_spec.rb +27 -26
  39. data/spec/unit/knife/bootstrap_windows_winrm_spec.rb +166 -32
  40. data/spec/unit/knife/core/windows_bootstrap_context_spec.rb +151 -0
  41. data/spec/unit/knife/windows_cert_generate_spec.rb +90 -0
  42. data/spec/unit/knife/windows_cert_install_spec.rb +51 -0
  43. data/spec/unit/knife/windows_listener_create_spec.rb +76 -0
  44. data/spec/unit/knife/winrm_session_spec.rb +56 -0
  45. data/spec/unit/knife/winrm_spec.rb +403 -118
  46. data/spec/unit/knife/wsman_test_spec.rb +176 -0
  47. metadata +67 -21
@@ -51,23 +51,39 @@ class Chef
51
51
  :short => "-p PORT",
52
52
  :long => "--ssh-port PORT",
53
53
  :description => "The ssh port",
54
- :default => "22",
55
- :proc => Proc.new { |key| Chef::Config[:knife][:ssh_port] = key }
56
-
54
+ :proc => Proc.new { |key| Chef::Config[:knife][:ssh_port] = key.strip }
55
+
57
56
  option :ssh_gateway,
58
57
  :short => "-G GATEWAY",
59
58
  :long => "--ssh-gateway GATEWAY",
60
59
  :description => "The ssh gateway",
61
60
  :proc => Proc.new { |key| Chef::Config[:knife][:ssh_gateway] = key }
62
61
 
62
+ option :forward_agent,
63
+ :short => "-A",
64
+ :long => "--forward-agent",
65
+ :description => "Enable SSH agent forwarding",
66
+ :boolean => true
67
+
63
68
  option :identity_file,
64
69
  :short => "-i IDENTITY_FILE",
65
70
  :long => "--identity-file IDENTITY_FILE",
66
71
  :description => "The SSH identity file used for authentication"
67
72
 
73
+ # DEPR: Remove this option for the next release.
68
74
  option :host_key_verification,
69
- :long => "--[no-]host-key-verification",
70
- :description => "Disable host key verification",
75
+ :long => "--[no-]host-key-verify",
76
+ :description => "Verify host key, enabled by default. [DEPRECATED] Use --host-key-verify option instead.",
77
+ :boolean => true,
78
+ :default => true,
79
+ :proc => Proc.new { |key|
80
+ Chef::Log.warn("[DEPRECATED] --host-key-verification option is deprecated. Use --host-key-verify option instead.")
81
+ config[:host_key_verify] = key
82
+ }
83
+
84
+ option :host_key_verify,
85
+ :long => "--[no-]host-key-verify",
86
+ :description => "Verify host key, enabled by default.",
71
87
  :boolean => true,
72
88
  :default => true
73
89
 
@@ -83,6 +99,7 @@ class Chef
83
99
  ssh.config[:ssh_port] = locate_config_value(:ssh_port)
84
100
  ssh.config[:ssh_gateway] = locate_config_value(:ssh_gateway)
85
101
  ssh.config[:identity_file] = config[:identity_file]
102
+ ssh.config[:forward_agent] = config[:forward_agent]
86
103
  ssh.config[:manual] = true
87
104
  ssh.config[:host_key_verify] = config[:host_key_verify]
88
105
  ssh.run
@@ -19,7 +19,8 @@
19
19
  require 'chef/knife/bootstrap_windows_base'
20
20
  require 'chef/knife/winrm'
21
21
  require 'chef/knife/winrm_base'
22
- require 'chef/knife/bootstrap'
22
+ require 'chef/knife/winrm_knife_base'
23
+
23
24
 
24
25
  class Chef
25
26
  class Knife
@@ -27,6 +28,7 @@ class Chef
27
28
 
28
29
  include Chef::Knife::BootstrapWindowsBase
29
30
  include Chef::Knife::WinrmBase
31
+ include Chef::Knife::WinrmCommandSharedFunctions
30
32
 
31
33
  deps do
32
34
  require 'chef/knife/core/windows_bootstrap_context'
@@ -35,32 +37,27 @@ class Chef
35
37
  Chef::Knife::Winrm.load_deps
36
38
  end
37
39
 
38
- banner "knife bootstrap windows winrm FQDN (options)"
40
+ banner 'knife bootstrap windows winrm FQDN (options)'
41
+
42
+ def run
43
+ if (Chef::Config[:validation_key] && !File.exist?(File.expand_path(Chef::Config[:validation_key])))
44
+ if !negotiate_auth? && !(locate_config_value(:winrm_transport) == 'ssl')
45
+ ui.error('Validatorless bootstrap over unsecure winrm channels could expose your key to network sniffing')
46
+ exit 1
47
+ end
48
+ end
49
+
50
+ validate_options!
51
+ resolve_session_options
52
+ @session_opts[:host] = server_name
53
+ @session = Chef::Knife::WinrmSession.new(@session_opts)
39
54
 
40
- def run
41
55
  bootstrap
42
56
  end
43
57
 
44
-
45
58
  def run_command(command = '')
46
- winrm = Chef::Knife::Winrm.new
47
- winrm.name_args = [ server_name, command ]
48
- winrm.config[:winrm_user] = locate_config_value(:winrm_user)
49
- winrm.config[:winrm_password] = locate_config_value(:winrm_password)
50
- winrm.config[:winrm_transport] = locate_config_value(:winrm_transport)
51
- winrm.config[:kerberos_keytab_file] = Chef::Config[:knife][:kerberos_keytab_file] if Chef::Config[:knife][:kerberos_keytab_file]
52
- winrm.config[:kerberos_realm] = Chef::Config[:knife][:kerberos_realm] if Chef::Config[:knife][:kerberos_realm]
53
- winrm.config[:kerberos_service] = Chef::Config[:knife][:kerberos_service] if Chef::Config[:knife][:kerberos_service]
54
- winrm.config[:ca_trust_file] = Chef::Config[:knife][:ca_trust_file] if Chef::Config[:knife][:ca_trust_file]
55
- winrm.config[:manual] = true
56
- winrm.config[:winrm_port] = locate_config_value(:winrm_port)
57
- winrm.config[:suppress_auth_failure] = true
58
-
59
- #If you turn off the return flag, then winrm.run won't atually check and
60
- #return the error
61
- #codes. Otherwise, it ignores the return value of the server call.
62
- winrm.config[:returns] = "0"
63
- winrm.run
59
+ @session.relay_command(command)
60
+ return @session.exit_code
64
61
  end
65
62
 
66
63
  protected
@@ -81,10 +78,14 @@ class Chef
81
78
  raise RuntimeError, 'Command execution failed.' if status != 0
82
79
  ui.info(ui.color("Remote node responded after #{elapsed_time_in_minutes(wait_start_time)} minutes.", :magenta))
83
80
  return
84
- rescue
81
+ rescue Errno::ECONNREFUSED => e
82
+ ui.error("Connection refused connecting to #{locate_config_value(:server_name)}:#{locate_config_value(:winrm_port)}.")
83
+ raise
84
+ rescue Exception => e
85
85
  retries_left -= 1
86
86
  if retries_left <= 0 || (elapsed_time_in_minutes(wait_start_time) > wait_max_minutes)
87
87
  ui.error("No response received from remote node after #{elapsed_time_in_minutes(wait_start_time)} minutes, giving up.")
88
+ ui.error("Exception: #{e.message}")
88
89
  raise
89
90
  end
90
91
  print '.'
@@ -99,4 +100,3 @@ class Chef
99
100
  end
100
101
  end
101
102
  end
102
-
@@ -18,6 +18,11 @@
18
18
 
19
19
  require 'chef/knife/core/bootstrap_context'
20
20
 
21
+ # Chef::Util::PathHelper in Chef 11 is a bit juvenile still
22
+ require 'knife-windows/path_helper'
23
+ # require 'chef/util/path_helper'
24
+
25
+
21
26
  class Chef
22
27
  class Knife
23
28
  module Core
@@ -28,20 +33,39 @@ class Chef
28
33
  # * @run_list - the run list for the node to boostrap
29
34
  #
30
35
  class WindowsBootstrapContext < BootstrapContext
36
+ PathHelper = ::Knife::Windows::PathHelper
37
+
38
+ attr_accessor :client_pem
31
39
 
32
- def initialize(config, run_list, chef_config)
40
+ def initialize(config, run_list, chef_config, secret=nil)
33
41
  @config = config
34
42
  @run_list = run_list
35
43
  @chef_config = chef_config
36
- super(config, run_list, chef_config)
44
+ @secret = secret
45
+ # Compatibility with Chef 12 and Chef 11 versions
46
+ begin
47
+ # Pass along the secret parameter for Chef 12
48
+ super(config, run_list, chef_config, secret)
49
+ rescue ArgumentError
50
+ # The Chef 11 base class only has parameters for initialize
51
+ super(config, run_list, chef_config)
52
+ end
37
53
  end
38
54
 
39
55
  def validation_key
40
- escape_and_echo(super)
56
+ if File.exist?(File.expand_path(@chef_config[:validation_key]))
57
+ IO.read(File.expand_path(@chef_config[:validation_key]))
58
+ else
59
+ false
60
+ end
61
+ end
62
+
63
+ def secret
64
+ escape_and_echo(@config[:secret])
41
65
  end
42
66
 
43
- def encrypted_data_bag_secret
44
- escape_and_echo(@config[:encrypted_data_bag_secret])
67
+ def trusted_certs_script
68
+ @trusted_certs_script ||= trusted_certs_content
45
69
  end
46
70
 
47
71
  def config_content
@@ -51,8 +75,6 @@ log_location STDOUT
51
75
 
52
76
  chef_server_url "#{@chef_config[:chef_server_url]}"
53
77
  validation_client_name "#{@chef_config[:validation_client_name]}"
54
- client_key "c:/chef/client.pem"
55
- validation_key "c:/chef/validation.pem"
56
78
 
57
79
  file_cache_path "c:/chef/cache"
58
80
  file_backup_path "c:/chef/backup"
@@ -65,6 +87,36 @@ CONFIG
65
87
  client_rb << "# Using default node name (fqdn)\n"
66
88
  end
67
89
 
90
+ # We configure :verify_api_cert only when it's overridden on the CLI
91
+ # or when specified in the knife config.
92
+ if !@config[:node_verify_api_cert].nil? || knife_config.has_key?(:verify_api_cert)
93
+ value = @config[:node_verify_api_cert].nil? ? knife_config[:verify_api_cert] : @config[:node_verify_api_cert]
94
+ client_rb << %Q{verify_api_cert #{value}\n}
95
+ end
96
+
97
+ # We configure :ssl_verify_mode only when it's overridden on the CLI
98
+ # or when specified in the knife config.
99
+ if @config[:node_ssl_verify_mode] || knife_config.has_key?(:ssl_verify_mode)
100
+ value = case @config[:node_ssl_verify_mode]
101
+ when "peer"
102
+ :verify_peer
103
+ when "none"
104
+ :verify_none
105
+ when nil
106
+ knife_config[:ssl_verify_mode]
107
+ else
108
+ nil
109
+ end
110
+
111
+ if value
112
+ client_rb << %Q{ssl_verify_mode :#{value}\n}
113
+ end
114
+ end
115
+
116
+ if @config[:ssl_verify_mode]
117
+ client_rb << %Q{ssl_verify_mode :#{knife_config[:ssl_verify_mode]}\n}
118
+ end
119
+
68
120
  if knife_config[:bootstrap_proxy]
69
121
  client_rb << "\n"
70
122
  client_rb << %Q{http_proxy "#{knife_config[:bootstrap_proxy]}"\n}
@@ -72,10 +124,18 @@ CONFIG
72
124
  client_rb << %Q{no_proxy "#{knife_config[:bootstrap_no_proxy]}"\n} if knife_config[:bootstrap_no_proxy]
73
125
  end
74
126
 
75
- if @config[:encrypted_data_bag_secret]
127
+ if knife_config[:bootstrap_no_proxy]
128
+ client_rb << %Q{no_proxy "#{knife_config[:bootstrap_no_proxy]}"\n}
129
+ end
130
+
131
+ if @config[:secret]
76
132
  client_rb << %Q{encrypted_data_bag_secret "c:/chef/encrypted_data_bag_secret"\n}
77
133
  end
78
134
 
135
+ unless trusted_certs_script.empty?
136
+ client_rb << %Q{trusted_certs_dir "c:/chef/trusted_certs"\n}
137
+ end
138
+
79
139
  escape_and_echo(client_rb)
80
140
  end
81
141
 
@@ -84,11 +144,53 @@ CONFIG
84
144
  start_chef << "chef-client -c c:/chef/client.rb -j c:/chef/first-boot.json -E #{bootstrap_environment}\n"
85
145
  end
86
146
 
147
+ def latest_current_windows_chef_version_query
148
+ installer_version_string = nil
149
+ if @config[:prerelease]
150
+ installer_version_string = "&prerelease=true"
151
+ else
152
+ chef_version_string = if knife_config[:bootstrap_version]
153
+ knife_config[:bootstrap_version]
154
+ else
155
+ Chef::VERSION.split(".").first
156
+ end
157
+
158
+ installer_version_string = "&v=#{chef_version_string}"
159
+
160
+ # If bootstrapping a pre-release version add the prerelease query string
161
+ if chef_version_string.split(".").length > 3
162
+ installer_version_string << "&prerelease=true"
163
+ end
164
+ end
165
+
166
+ installer_version_string
167
+ end
168
+
87
169
  def win_wget
170
+ # I tried my best to figure out how to properly url decode and switch / to \
171
+ # but this is VBScript - so I don't really care that badly.
88
172
  win_wget = <<-WGET
89
173
  url = WScript.Arguments.Named("url")
90
174
  path = WScript.Arguments.Named("path")
91
175
  proxy = null
176
+ '* Vaguely attempt to handle file:// scheme urls by url unescaping and switching all
177
+ '* / into \. Also assume that file:/// is a local absolute path and that file://<foo>
178
+ '* is possibly a network file path.
179
+ If InStr(url, "file://") = 1 Then
180
+ url = Unescape(url)
181
+ If InStr(url, "file:///") = 1 Then
182
+ sourcePath = Mid(url, Len("file:///") + 1)
183
+ Else
184
+ sourcePath = Mid(url, Len("file:") + 1)
185
+ End If
186
+ sourcePath = Replace(sourcePath, "/", "\\")
187
+
188
+ Set objFSO = CreateObject("Scripting.FileSystemObject")
189
+ If objFSO.Fileexists(path) Then objFSO.DeleteFile path
190
+ objFSO.CopyFile sourcePath, path, true
191
+ Set objFSO = Nothing
192
+
193
+ Else
92
194
  Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
93
195
  Set wshShell = CreateObject( "WScript.Shell" )
94
196
  Set objUserVariables = wshShell.Environment("USER")
@@ -127,8 +229,9 @@ Set objFSO = Nothing
127
229
  objADOStream.SaveToFile path
128
230
  objADOStream.Close
129
231
  Set objADOStream = Nothing
130
- End if
232
+ End If
131
233
  Set objXMLHTTP = Nothing
234
+ End If
132
235
  WGET
133
236
  escape_and_echo(win_wget)
134
237
  end
@@ -162,9 +265,23 @@ WGET_PS
162
265
  local_download_path = "%TEMP%\\chef-client-latest.msi"
163
266
  end
164
267
 
268
+ def msi_url(machine_os=nil, machine_arch=nil, download_context=nil)
269
+ # The default msi path has a number of url query parameters - we attempt to substitute
270
+ # such parameters in as long as they are provided by the template.
271
+
272
+ if @config[:msi_url].nil? || @config[:msi_url].empty?
273
+ url = "https://www.chef.io/chef/download?p=windows"
274
+ url += "&pv=#{machine_os}" unless machine_os.nil?
275
+ url += "&m=#{machine_arch}" unless machine_arch.nil?
276
+ url += "&DownloadContext=#{download_context}" unless download_context.nil?
277
+ url += latest_current_windows_chef_version_query
278
+ else
279
+ @config[:msi_url]
280
+ end
281
+ end
282
+
165
283
  def first_boot
166
- first_boot_attributes_and_run_list = (@config[:first_boot_attributes] || {}).merge(:run_list => @run_list)
167
- escape_and_echo(first_boot_attributes_and_run_list.to_json)
284
+ escape_and_echo(super.to_json)
168
285
  end
169
286
 
170
287
  # escape WIN BATCH special chars
@@ -177,7 +294,24 @@ WGET_PS
177
294
  private
178
295
 
179
296
  def install_command(executor_quote)
180
- "msiexec /qn /log #{executor_quote}%CHEF_CLIENT_MSI_LOG_PATH%#{executor_quote} /i #{executor_quote}%LOCAL_DESTINATION_MSI_PATH%#{executor_quote}"
297
+ if @config[:install_as_service]
298
+ "msiexec /qn /log #{executor_quote}%CHEF_CLIENT_MSI_LOG_PATH%#{executor_quote} /i #{executor_quote}%LOCAL_DESTINATION_MSI_PATH%#{executor_quote} ADDLOCAL=#{executor_quote}ChefClientFeature,ChefServiceFeature#{executor_quote}"
299
+ else
300
+ "msiexec /qn /log #{executor_quote}%CHEF_CLIENT_MSI_LOG_PATH%#{executor_quote} /i #{executor_quote}%LOCAL_DESTINATION_MSI_PATH%#{executor_quote}"
301
+ end
302
+ end
303
+
304
+ # Returns a string for copying the trusted certificates on the workstation to the system being bootstrapped
305
+ # This string should contain both the commands necessary to both create the files, as well as their content
306
+ def trusted_certs_content
307
+ content = ""
308
+ if @chef_config[:trusted_certs_dir]
309
+ Dir.glob(File.join(PathHelper.escape_glob(@chef_config[:trusted_certs_dir]), "*.{crt,pem}")).each do |cert|
310
+ content << "> #{bootstrap_directory}/trusted_certs/#{File.basename(cert)} (\n" +
311
+ escape_and_echo(IO.read(File.expand_path(cert))) + "\n)\n"
312
+ end
313
+ end
314
+ content
181
315
  end
182
316
 
183
317
  def fallback_install_task_command
@@ -0,0 +1,33 @@
1
+ #
2
+ # Author:: Aliasgar Batterywala (<aliasgar.batterywala@clogeny.com>)
3
+ # Copyright:: Copyright (c) 2015 Opscode, Inc.
4
+ # License:: Apache License, Version 2.0
5
+ #
6
+ # Licensed under the Apache License, Version 2.0 (the "License");
7
+ # you may not use this file except in compliance with the License.
8
+ # You may obtain a copy of the License at
9
+ #
10
+ # http://www.apache.org/licenses/LICENSE-2.0
11
+ #
12
+ # Unless required by applicable law or agreed to in writing, software
13
+ # distributed under the License is distributed on an "AS IS" BASIS,
14
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ # See the License for the specific language governing permissions and
16
+ # limitations under the License.
17
+ #
18
+
19
+ class Chef
20
+ class Knife
21
+ module KnifeWindowsBase
22
+
23
+ def locate_config_value(key)
24
+ key = key.to_sym
25
+ value = config[key] || Chef::Config[:knife][key] || default_config[key]
26
+ Chef::Log.debug("Looking for key #{key} and found value #{value}")
27
+ value
28
+ end
29
+
30
+ end
31
+ end
32
+ end
33
+
@@ -0,0 +1,155 @@
1
+ # Author:: Mukta Aphale (<mukta.aphale@clogeny.com>)
2
+ # Copyright:: Copyright (c) 2014 Opscode, Inc.
3
+ # License:: Apache License, Version 2.0
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+
18
+ require 'chef/knife'
19
+ require 'chef/knife/winrm_base'
20
+ require 'openssl'
21
+ require 'socket'
22
+
23
+ class Chef
24
+ class Knife
25
+ class WindowsCertGenerate < Knife
26
+
27
+ attr_accessor :thumbprint, :hostname
28
+
29
+ banner "knife windows cert generate FILE_PATH (options)"
30
+
31
+ option :hostname,
32
+ :short => "-H HOSTNAME",
33
+ :long => "--hostname HOSTNAME",
34
+ :description => "Use to specify the hostname for the listener.
35
+ For example, --hostname something.mydomain.com or *.mydomain.com.",
36
+ :required => true
37
+
38
+ option :output_file,
39
+ :short => "-o PATH",
40
+ :long => "--output-file PATH",
41
+ :description => "Specifies the file path at which to generate the 3 certificate files of type .pfx, .b64, and .pem. The default is './winrmcert'.",
42
+ :default => "winrmcert"
43
+
44
+ option :key_length,
45
+ :short => "-k LENGTH",
46
+ :long => "--key-length LENGTH",
47
+ :description => "Default is 2048",
48
+ :default => "2048"
49
+
50
+ option :cert_validity,
51
+ :short => "-cv MONTHS",
52
+ :long => "--cert-validity MONTHS",
53
+ :description => "Default is 24 months",
54
+ :default => "24"
55
+
56
+ option :cert_passphrase,
57
+ :short => "-cp PASSWORD",
58
+ :long => "--cert-passphrase PASSWORD",
59
+ :description => "Password for certificate."
60
+
61
+ def generate_keypair
62
+ OpenSSL::PKey::RSA.new(config[:key_length].to_i)
63
+ end
64
+
65
+ def prompt_for_passphrase
66
+ passphrase = ""
67
+ begin
68
+ print "Passphrases do not match. Try again.\n" unless passphrase.empty?
69
+ print "Enter certificate passphrase (empty for no passphrase):"
70
+ passphrase = STDIN.gets
71
+ return passphrase.strip if passphrase == "\n"
72
+ print "Enter same passphrase again:"
73
+ confirm_passphrase = STDIN.gets
74
+ end until passphrase == confirm_passphrase
75
+ passphrase.strip
76
+ end
77
+
78
+ def generate_certificate rsa_key
79
+ @hostname = config[:hostname] if config[:hostname]
80
+
81
+ #Create a self-signed X509 certificate from the rsa_key (unencrypted)
82
+ cert = OpenSSL::X509::Certificate.new
83
+ cert.version = 2
84
+ cert.serial = Random.rand(65534) + 1 # 2 digit byte range random number for better security aspect
85
+
86
+ cert.subject = OpenSSL::X509::Name.parse "/CN=#{@hostname}"
87
+ cert.issuer = cert.subject
88
+ cert.public_key = rsa_key.public_key
89
+ cert.not_before = Time.now
90
+ cert.not_after = cert.not_before + 2 * 365 * config[:cert_validity].to_i * 60 * 60 # 2 years validity
91
+ ef = OpenSSL::X509::ExtensionFactory.new
92
+ ef.subject_certificate = cert
93
+ ef.issuer_certificate = cert
94
+ cert.add_extension(ef.create_extension("subjectKeyIdentifier","hash",false))
95
+ cert.add_extension(ef.create_extension("authorityKeyIdentifier","keyid:always",false))
96
+ cert.add_extension(ef.create_extension("extendedKeyUsage", "1.3.6.1.5.5.7.3.1", false))
97
+ cert.sign(rsa_key, OpenSSL::Digest::SHA1.new)
98
+ @thumbprint = OpenSSL::Digest::SHA1.new(cert.to_der)
99
+ cert
100
+ end
101
+
102
+ def write_certificate_to_file(cert, file_path, rsa_key)
103
+ File.open(file_path + ".pem", "wb") { |f| f.print cert.to_pem }
104
+ config[:cert_passphrase] = prompt_for_passphrase unless config[:cert_passphrase]
105
+ pfx = OpenSSL::PKCS12.create("#{config[:cert_passphrase]}", "winrmcert", rsa_key, cert)
106
+ File.open(file_path + ".pfx", "wb") { |f| f.print pfx.to_der }
107
+ File.open(file_path + ".b64", "wb") { |f| f.print Base64.strict_encode64(pfx.to_der) }
108
+ end
109
+
110
+ def certificates_already_exist?(file_path)
111
+ certs_exists = false
112
+ %w{pem pfx b64}.each do |extn|
113
+ if !Dir.glob("#{file_path}.*#{extn}").empty?
114
+ certs_exists = true
115
+ break
116
+ end
117
+ end
118
+
119
+ if certs_exists
120
+ begin
121
+ confirm("Do you really want to overwrite existing certificates")
122
+ rescue SystemExit # Need to handle this as confirming with N/n raises SystemExit exception
123
+ exit!
124
+ end
125
+ end
126
+ end
127
+
128
+ def run
129
+ STDOUT.sync = STDERR.sync = true
130
+
131
+ # takes user specified first cli value as a destination file path for generated cert.
132
+ file_path = @name_args.empty? ? config[:output_file].sub(/\.(\w+)$/,'') : @name_args.first
133
+
134
+ # check if certs already exists at given file path
135
+ certificates_already_exist? file_path
136
+
137
+ begin
138
+ filename = File.basename(file_path)
139
+ rsa_key = generate_keypair
140
+ cert = generate_certificate rsa_key
141
+ write_certificate_to_file cert, file_path, rsa_key
142
+ ui.info "Generated Certificates:"
143
+ ui.info "- #{filename}.pfx - PKCS12 format key pair. Contains public and private keys, can be used with an SSL server."
144
+ ui.info "- #{filename}.b64 - Base64 encoded PKCS12 key pair. Contains public and private keys, used by some cloud provider API's to configure SSL servers."
145
+ ui.info "- #{filename}.pem - Base64 encoded public certificate only. Required by the client to connect to the server."
146
+ ui.info "Certificate Thumbprint: #{@thumbprint.to_s.upcase}"
147
+ rescue => e
148
+ puts "ERROR: + #{e}"
149
+ end
150
+ end
151
+
152
+ end
153
+ end
154
+ end
155
+
@@ -0,0 +1,68 @@
1
+ # Author:: Mukta Aphale (<mukta.aphale@clogeny.com>)
2
+ # Copyright:: Copyright (c) 2014 Opscode, Inc.
3
+ # License:: Apache License, Version 2.0
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ #
17
+
18
+ require 'chef/knife'
19
+ require 'chef/knife/winrm_base'
20
+
21
+ class Chef
22
+ class Knife
23
+ class WindowsCertInstall < Knife
24
+
25
+ banner "knife windows cert install CERT [CERT] (options)"
26
+
27
+ option :cert_passphrase,
28
+ :short => "-cp PASSWORD",
29
+ :long => "--cert-passphrase PASSWORD",
30
+ :description => "Password for certificate."
31
+
32
+ def get_cert_passphrase
33
+ print "Enter given certificate's passphrase (empty for no passphrase):"
34
+ passphrase = STDIN.gets
35
+ passphrase.strip
36
+ end
37
+
38
+ def run
39
+ STDOUT.sync = STDERR.sync = true
40
+
41
+ if Chef::Platform.windows?
42
+ if @name_args.empty?
43
+ ui.error "Please specify the certificate path. e.g- 'knife windows cert install <path>"
44
+ exit 1
45
+ end
46
+ file_path = @name_args.first
47
+ config[:cert_passphrase] = get_cert_passphrase unless config[:cert_passphrase]
48
+
49
+ begin
50
+ ui.info "Adding certificate to the Windows Certificate Store..."
51
+ result = %x{powershell.exe -Command " '#{config[:cert_passphrase]}' | certutil -importPFX '#{file_path}' AT_KEYEXCHANGE"}
52
+ if $?.exitstatus == 0
53
+ ui.info "Certificate added to Certificate Store"
54
+ else
55
+ ui.info "Error adding the certificate. Use -VV option for details"
56
+ end
57
+ Chef::Log.debug "#{result}"
58
+ rescue => e
59
+ puts "ERROR: + #{e}"
60
+ end
61
+ else
62
+ ui.error "Certificate can be installed on Windows system only"
63
+ exit 1
64
+ end
65
+ end
66
+ end
67
+ end
68
+ end
@@ -20,6 +20,7 @@ require 'chef/knife'
20
20
  require 'chef/knife/winrm'
21
21
  require 'chef/knife/bootstrap_windows_ssh'
22
22
  require 'chef/knife/bootstrap_windows_winrm'
23
+ require 'chef/knife/wsman_test'
23
24
 
24
25
  class Chef
25
26
  class Knife
@@ -27,7 +28,8 @@ class Chef
27
28
 
28
29
  banner "#{BootstrapWindowsWinrm.banner}\n" +
29
30
  "#{BootstrapWindowsSsh.banner}\n" +
30
- "#{Winrm.banner}"
31
+ "#{Winrm.banner}\n" +
32
+ "#{WsmanTest.banner}"
31
33
  end
32
34
  end
33
35
  end