Class: Bolt::Transport::WinRM::Connection

Inherits:
Object
  • Object
show all
Defined in:
lib/bolt/transport/winrm/connection.rb

Constant Summary collapse

HTTP_PORT =
5985
HTTPS_PORT =
5986

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(target, transport_logger) ⇒ Connection

Returns a new instance of Connection.



12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/bolt/transport/winrm/connection.rb', line 12

def initialize(target, transport_logger)
  raise Bolt::ValidationError, "Target #{target.safe_name} does not have a host" unless target.host

  @target = target

  default_port = target.options['ssl'] ? HTTPS_PORT : HTTP_PORT
  @port = @target.port || default_port
  @user = @target.user
  # Build set of extensions from extensions config as well as interpreters

  @logger = Bolt::Logger.logger(@target.safe_name)
  logger.trace("Initializing winrm connection to #{@target.safe_name}")
  @transport_logger = transport_logger
end

Instance Attribute Details

#loggerObject (readonly)

Returns the value of attribute logger.



10
11
12
# File 'lib/bolt/transport/winrm/connection.rb', line 10

def logger
  @logger
end

#targetObject (readonly)

Returns the value of attribute target.



10
11
12
# File 'lib/bolt/transport/winrm/connection.rb', line 10

def target
  @target
end

Instance Method Details

#connectObject



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'lib/bolt/transport/winrm/connection.rb', line 30

def connect
  if target.options['ssl']
    scheme = 'https'
    transport = :ssl
  else
    scheme = 'http'
    transport = :negotiate
  end

  transport = :kerberos if target.options['realm']
  endpoint = "#{scheme}://#{target.host}:#{@port}/wsman"
  cacert = target.options['cacert'] && target.options['ssl'] ? File.expand_path(target.options['cacert']) : nil
  options = { endpoint: endpoint,
              # https://github.com/WinRb/WinRM/issues/270
              user: target.options['realm'] ? 'dummy' : @user,
              password: target.options['realm'] ? 'dummy' : target.password,
              retry_limit: 1,
              transport: transport,
              basic_auth_only: target.options['basic-auth-only'],
              ca_trust_path: cacert,
              realm: target.options['realm'],
              no_ssl_peer_verification: !target.options['ssl-verify'] }

  Timeout.timeout(target.options['connect-timeout']) do
    @connection = ::WinRM::Connection.new(options)
    @connection.logger = @transport_logger

    @connection.shell(:powershell) do |session|
      session.run('$PSVersionTable.PSVersion')
    end

    @logger.trace { "Opened connection" }
  end
rescue Timeout::Error
  # If we're using the default port with SSL, a timeout probably means the
  # host doesn't support SSL.
  if target.options['ssl'] && @port == HTTPS_PORT
    the_problem = "\nVerify that required WinRM ports are open, " \
                  "or use --no-ssl if this host isn't configured to use SSL for WinRM."
  end
  raise Bolt::Node::ConnectError.new(
    "Timeout after #{target.options['connect-timeout']} seconds connecting to #{endpoint}#{the_problem}",
    'CONNECT_ERROR'
  )
rescue ::WinRM::WinRMAuthorizationError
  raise Bolt::Node::ConnectError.new(
    "Authentication failed for #{endpoint}",
    'AUTH_ERROR'
  )
rescue OpenSSL::SSL::SSLError => e
  # If we're using SSL with the default non-SSL port, mention that as a likely problem
  if target.options['ssl'] && @port == HTTP_PORT
    theres_your_problem = "\nAre you using SSL to connect to a non-SSL port?"
  end
  if target.options['ssl-verify'] && e.message.include?('certificate verify failed')
    theres_your_problem = "\nIs the remote host using a self-signed SSL " \
                          "certificate? Use --no-ssl-verify to disable " \
                          "remote host SSL verification."
  end
  raise Bolt::Node::ConnectError.new(
    "Failed to connect to #{endpoint}: #{e.message}#{theres_your_problem}",
    "CONNECT_ERROR"
  )
rescue StandardError => e
  raise Bolt::Node::ConnectError.new(
    "Failed to connect to #{endpoint}: #{e.message}",
    'CONNECT_ERROR'
  )
end

#disconnectObject



100
101
102
103
# File 'lib/bolt/transport/winrm/connection.rb', line 100

def disconnect
  @client&.disconnect!
  @logger.trace { "Closed connection" }
end

#download_file(source, destination, download) ⇒ Object



206
207
208
209
210
211
212
213
# File 'lib/bolt/transport/winrm/connection.rb', line 206

def download_file(source, destination, download)
  @logger.trace { "Downloading #{source} to #{destination}" }
  if target.options['file-protocol'] == 'smb'
    download_file_smb(source, destination)
  else
    download_file_winrm(source, destination, download)
  end
end

#download_file_smb(source, destination) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
# File 'lib/bolt/transport/winrm/connection.rb', line 228

def download_file_smb(source, destination)
  require_ruby_smb

  win_source = source.tr('/', '\\')
  if (md = win_source.match(/^([a-z]):\\(.*)/i))
    # if drive, use admin share for that drive, so path is '\\host\C$'
    path = "\\\\#{@target.host}\\#{md[1]}$"
    src  = md[2]
  elsif (md = win_source.match(/^(\\\\[^\\]+\\[^\\]+)\\(.*)/))
    # if unc, path is '\\host\share'
    path = md[1]
    src  = md[2]
  else
    raise ArgumentError, "Unknown source '#{source}'"
  end

  client = 
  tree = client.tree_connect(path)

  begin
    # Make sure the root download directory for the target exists
    FileUtils.mkdir_p(destination)
    download_file_smb_recursive(tree, src, destination)
  ensure
    tree.disconnect!
  end
rescue ::RubySMB::Error::UnexpectedStatusCode => e
  raise Bolt::Node::FileError.new("SMB Error: #{e.message}", 'DOWNLOAD_ERROR')
rescue StandardError => e
  raise Bolt::Node::FileError.new(e.message, 'DOWNLOAD_ERROR')
end

#download_file_winrm(source, destination, download) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
# File 'lib/bolt/transport/winrm/connection.rb', line 215

def download_file_winrm(source, destination, download)
  # The winrm gem doesn't create the destination directory if it's missing,
  # so create it here
  FileUtils.mkdir_p(destination)
  fs = ::WinRM::FS::FileManager.new(@connection)
  # params: source, destination, chunksize, first
  # first needs to be set to false, otherwise if the source is a directory it
  # will be nested inside a directory with the same name
  fs.download(source, download, 1024 * 1024, false)
rescue StandardError => e
  raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR')
end

#execute(command) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/bolt/transport/winrm/connection.rb', line 105

def execute(command)
  @logger.trace { "Executing command: #{command}" }

  inp = StringIO.new
  # This transport doesn't accept stdin, so close the stream to ensure
  # it will fail if the shell attempts to provide stdin
  inp.close

  out_rd, out_wr = IO.pipe('UTF-8')
  err_rd, err_wr = IO.pipe('UTF-8')
  th = Thread.new do
    # By default, any exception raised in a thread will be reported to
    # stderr as a stacktrace. Since we know these errors are going to
    # propagate to the main thread via the shell, there's no chance
    # they will be unhandled, so the default stack trace is unneeded.
    Thread.current.report_on_exception = false

    # Open a new shell instance for each command executed. PowerShell is
    # unable to unload any DLLs loaded when running a PowerShell script
    # or task from the same shell instance they were loaded in, which
    # prevents Bolt from cleaning up the temp directory successfully.
    # Using a new PowerShell instance avoids this limitation.
    @connection.shell(:powershell) do |session|
      result = session.run(command)
      out_wr << result.stdout
      err_wr << result.stderr
      result.exitcode
    end
  ensure
    # Close the streams to avoid the caller deadlocking
    out_wr.close
    err_wr.close
  end

  [inp, out_rd, err_rd, th]
rescue Errno::EMFILE => e
  msg = "#{e.message}. This might be resolved by increasing your user limit " \
    "with 'ulimit -n 1024'. See https://puppet.com/docs/bolt/latest/bolt_known_issues.html for details."
  raise Bolt::Error.new(msg, 'bolt/too-many-files')
rescue StandardError
  @logger.trace { "Command aborted" }
  raise
end

#max_command_lengthObject



264
265
266
# File 'lib/bolt/transport/winrm/connection.rb', line 264

def max_command_length
  nil
end

#require_ruby_smbObject



165
166
167
168
169
170
171
172
173
174
175
# File 'lib/bolt/transport/winrm/connection.rb', line 165

def require_ruby_smb
  # lazy-load expensive gem code
  # In BinData 2.5.0+, the below commit makes things VERY noisy when loading RubySMB, so
  # we temporarily disable warnings while we load it. If this ever gets fixed, get rid
  # of this function and restore the plain 'require' where this function is called.
  # https://github.com/dmendel/bindata/commit/2c8588a1ae5959080fffa429e07027f2ff20161c
  prev = $VERBOSE
  $VERBOSE = nil
  require 'ruby_smb'
  $VERBOSE = prev
end

#shellObject



260
261
262
# File 'lib/bolt/transport/winrm/connection.rb', line 260

def shell
  @shell ||= Bolt::Shell::Powershell.new(target, self)
end

#upload_file(source, destination) ⇒ Object



149
150
151
152
153
154
155
156
# File 'lib/bolt/transport/winrm/connection.rb', line 149

def upload_file(source, destination)
  @logger.trace { "Uploading #{source} to #{destination}" }
  if target.options['file-protocol'] == 'smb'
    upload_file_smb(source, destination)
  else
    upload_file_winrm(source, destination)
  end
end

#upload_file_smb(source, destination) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/bolt/transport/winrm/connection.rb', line 177

def upload_file_smb(source, destination)
  require_ruby_smb

  win_dest = destination.tr('/', '\\')
  if (md = win_dest.match(/^([a-z]):\\(.*)/i))
    # if drive, use admin share for that drive, so path is '\\host\C$'
    path = "\\\\#{@target.host}\\#{md[1]}$"
    dest = md[2]
  elsif (md = win_dest.match(/^(\\\\[^\\]+\\[^\\]+)\\(.*)/))
    # if unc, path is '\\host\share'
    path = md[1]
    dest = md[2]
  else
    raise ArgumentError, "Unknown destination '#{destination}'"
  end

  client = 
  tree = client.tree_connect(path)
  begin
    upload_file_smb_recursive(tree, source, dest)
  ensure
    tree.disconnect!
  end
rescue ::RubySMB::Error::UnexpectedStatusCode => e
  raise Bolt::Node::FileError.new("SMB Error: #{e.message}", 'WRITE_ERROR')
rescue StandardError => e
  raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR')
end

#upload_file_winrm(source, destination) ⇒ Object



158
159
160
161
162
163
# File 'lib/bolt/transport/winrm/connection.rb', line 158

def upload_file_winrm(source, destination)
  fs = ::WinRM::FS::FileManager.new(@connection)
  fs.upload(source, destination)
rescue StandardError => e
  raise Bolt::Node::FileError.new(e.message, 'WRITE_ERROR')
end