Class: Puppet::Transport::Panos::API Private
- Inherits:
-
Object
- Object
- Puppet::Transport::Panos::API
- Defined in:
- lib/puppet/transport/panos.rb
Overview
This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.
A simple adaptor to expose the basic PAN-OS XML API operations. Having this in a separate class aids with keeping the gnarly HTTP code away from the business logic, and helps with testing, too.
Instance Method Summary collapse
- #apikey ⇒ Object private
- #fetch_apikey(user, password) ⇒ Object private
- #fingerprint_from_hexdigest(hexdigest) ⇒ Object private
- #handle_response_errors(doc) ⇒ Object private
-
#handle_verify_mode(verify_mode) ⇒ Object
private
Returns the OpenSSL verify mode based on the verify_mode arguments.
- #hexdigest_from_cert(cert) ⇒ Object private
- #http ⇒ Object private
-
#initialize(connection_info) ⇒ API
constructor
private
A new instance of API.
- #job_request(type, **options) ⇒ Object private
- #message_from_code(code) ⇒ Object private
- #request(type, **options) ⇒ Object private
- #same_cert_fingerprint?(end_cert) ⇒ Boolean private
- #upload(type, file, **options) ⇒ Object private
-
#verify_callback(preverify_ok, cert_store) ⇒ Object
private
stackoverflow.com/questions/22093042/implementing-https-certificate-pubkey-pinning-with-ruby/22108461#22108461 this method will be called on the OpenSSL connection to allow for additional verification.
Constructor Details
#initialize(connection_info) ⇒ API
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns a new instance of API.
159 160 161 162 163 164 165 166 167 168 169 170 |
# File 'lib/puppet/transport/panos.rb', line 159 def initialize(connection_info) @host = connection_info[:host] || connection_info[:address] @port = connection_info.key?(:port) ? connection_info[:port].to_i : 443 @user = connection_info[:user] || connection_info[:username] @password = connection_info[:password].unwrap unless connection_info[:password].nil? @ssl_verify = connection_info[:ssl].nil? ? true : connection_info[:ssl] @ca_file = connection_info[:ssl_ca_file] if connection_info[:ssl_ca_file] @ssl_version = connection_info[:ssl_version] if connection_info[:ssl_version] @ciphers = connection_info[:ssl_ciphers] if connection_info[:ssl_ciphers] @fingerprint = fingerprint_from_hexdigest(connection_info[:ssl_fingerprint].unwrap) unless connection_info[:ssl_fingerprint].nil? @apikey = connection_info[:apikey].unwrap unless connection_info[:apikey].nil? end |
Instance Method Details
#apikey ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
257 258 259 |
# File 'lib/puppet/transport/panos.rb', line 257 def apikey @apikey ||= fetch_apikey(@user, @password) end |
#fetch_apikey(user, password) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
243 244 245 246 247 248 249 250 251 252 253 254 255 |
# File 'lib/puppet/transport/panos.rb', line 243 def fetch_apikey(user, password) uri = URI::HTTP.build(path: '/api/') params = { type: 'keygen', user: user, password: password } uri.query = URI.encode_www_form(params) res = http.get(uri) unless res.is_a?(Net::HTTPSuccess) raise "Error: #{res}: #{res.}" end doc = REXML::Document.new(res.body) handle_response_errors(doc) doc.elements['/response/result/key'].text end |
#fingerprint_from_hexdigest(hexdigest) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
224 225 226 |
# File 'lib/puppet/transport/panos.rb', line 224 def fingerprint_from_hexdigest(hexdigest) hexdigest.tr(':', '').tr(' ', '').scan(%r{..}).map { |s| s.upcase }.join(':') end |
#handle_response_errors(doc) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
# File 'lib/puppet/transport/panos.rb', line 377 def handle_response_errors(doc) status = doc.elements['/response'].attributes['status'] code = doc.elements['/response'].attributes['code'] = ('Received "%{status}" with code %{code}: %{message}' % { status: status, code: code, message: (code), }) # require 'pry';binding.pry if status == 'success' # Messages without a code require more processing by the caller Puppet.debug() if code else << "\n" doc.write(, 2) raise Puppet::ResourceError, end end |
#handle_verify_mode(verify_mode) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Returns the OpenSSL verify mode based on the verify_mode arguments
179 180 181 182 183 184 185 186 187 188 189 190 191 |
# File 'lib/puppet/transport/panos.rb', line 179 def handle_verify_mode(verify_mode) case verify_mode when true OpenSSL::SSL::VERIFY_PEER when false Puppet.warning("SSL verification turned off in configuration for $#{Puppet[:certname]}") OpenSSL::SSL::VERIFY_NONE else raise Puppet::ResourceError, "\"#{verify_mode}\" is not a valid mode, " \ 'valid modes are: "false" for no client verification, ' \ 'and "true" for validating the certificate' end end |
#hexdigest_from_cert(cert) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
220 221 222 |
# File 'lib/puppet/transport/panos.rb', line 220 def hexdigest_from_cert(cert) OpenSSL::Digest::SHA256.hexdigest(cert.to_der) end |
#http ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
# File 'lib/puppet/transport/panos.rb', line 228 def http @http ||= begin Puppet.debug('Connecting to https://%{host}:%{port}' % { host: @host, port: @port }) Net::HTTP.start(@host, @port, use_ssl: true, verify_mode: handle_verify_mode(@ssl_verify), ca_file: @ca_file, ssl_version: @ssl_version, ciphers: @ciphers ? @ciphers.join(':') : @ciphers, verify_callback: ->(preverify_ok, cert_store) do verify_callback(preverify_ok, cert_store) end) end end |
#job_request(type, **options) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 |
# File 'lib/puppet/transport/panos.rb', line 311 def job_request(type, **) result = request(type, ) = result.elements['/response/msg'] if Puppet.debug('api response (no changes): %{msg}' % { msg: .text }) return end job_id = result.elements['/response/result/job'].text job_msg = [] result.elements['/response/result/msg'].each_element_with_text { |e| job_msg << e.text } Puppet.debug('api response (job queued): %{msg}' % { msg: job_msg.join("\n") }) tries = 0 loop do # https://<firewall>/api/?type=op&cmd=<show><jobs><id>4</id></jobs></show> poll_result = request('op', cmd: "<show><jobs><id>#{job_id}</id></jobs></show>") status = poll_result.elements['/response/result/job/status'].text result = poll_result.elements['/response/result/job/result'].text progress = poll_result.elements['/response/result/job/progress'].text details = [] poll_result.elements['/response/result/job/details'].each_element_with_text { |e| details << e.text } if status == 'FIN' # TODO: go to debug # poll_result.write($stdout, 2) break if result == 'OK' raise Puppet::ResourceError, 'job failed. result="%{result}": %{details}' % { result: result, details: details.join("\n") } end tries += 1 details.unshift("sleeping for #{tries} seconds") Puppet.debug('job still in progress (%{progress}%%). result="%{result}": %{details}' % { result: result, progress: progress, details: details.join("\n") }) sleep tries end Puppet.debug('job was successful') end |
#message_from_code(code) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 |
# File 'lib/puppet/transport/panos.rb', line 349 def (code) ||= begin h = Hash.new { |_hash, key| 'Unknown error code %{code}' % { code: key } } h['1'] = 'Unknown command: The specific config or operational command is not recognized.' h['2'] = "Internal error: Check with Palo Alto's technical support." h['3'] = "Internal error: Check with Palo Alto's technical support." h['4'] = "Internal error: Check with Palo Alto's technical support." h['5'] = "Internal error: Check with Palo Alto's technical support." h['11'] = "Internal error: Check with Palo Alto's technical support." h['21'] = "Internal error: Check with Palo Alto's technical support." h['6'] = 'Bad XPath: The xpath specified in one or more attributes of the command is invalid.' h['7'] = "Object not present: Object specified by the xpath is not present. For example, entry[@name='value'] where no object with name 'value' is present." h['8'] = 'Object not unique: For commands that operate on a single object, the specified object is not unique.' h['10'] = 'Reference count not zero: Object cannot be deleted as there are other objects that refer to it. For example,:addressobject still in use in policy.' h['12'] = 'Invalid object: Xpath or element values provided are not complete.' h['14'] = 'Operation not possible: Operation is allowed but not possible in this case. For example, moving a rule up one position when it is already at the top.' h['15'] = 'Operation denied: Operation is allowed. For example, Admin not allowed to delete own account, Running a command that is not allowed on a passive device.' h['16'] = 'Unauthorized: The API role does not have access rights to run this query.' h['17'] = 'Invalid command: Invalid command or parameters.' h['18'] = 'Malformed command: The XML is malformed.' h['19'] = 'Success: Command completed successfully.' h['20'] = 'Success: Command completed successfully.' h['22'] = 'Session timed out: The session for this query timed out.' h end [code] end |
#request(type, **options) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 |
# File 'lib/puppet/transport/panos.rb', line 261 def request(type, **) params = { type: type, key: apikey } params.merge!() uri = URI::HTTP.build(path: '/api/') uri.query = URI.encode_www_form(params) res = http.get(uri) unless res.is_a?(Net::HTTPSuccess) raise "Error: #{res}: #{res.}" end doc = REXML::Document.new(res.body) handle_response_errors(doc) doc end |
#same_cert_fingerprint?(end_cert) ⇒ Boolean
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
214 215 216 217 218 |
# File 'lib/puppet/transport/panos.rb', line 214 def same_cert_fingerprint?(end_cert) hexdigest = hexdigest_from_cert(end_cert) cert_fingerprint = fingerprint_from_hexdigest(hexdigest) cert_fingerprint == @fingerprint end |
#upload(type, file, **options) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 |
# File 'lib/puppet/transport/panos.rb', line 277 def upload(type, file, **) params = { type: type, key: apikey } params.merge!() uri = URI::HTTP.build(path: '/api/') uri.query = URI.encode_www_form(params) raise Puppet::ResourceError, "File: `#{file}` does not exist" unless File.exist?(file) # from: http://www.rubyinside.com/nethttp-cheat-sheet-2940.html # Token used to terminate the file in the post body. @boundary ||= SecureRandom.hex(25) post_body = [] post_body << "--#{@boundary}\r\n" post_body << "Content-Disposition: form-data; name=\"file\"; filename=\"#{CGI.escape(File.basename(file))}\"\r\n" post_body << "Content-Type: text/plain\r\n" post_body << "\r\n" post_body << File.open(file, 'rb') { |f| f.read } post_body << "\r\n--#{@boundary}--\r\n" request = Net::HTTP::Post.new(uri.request_uri) request.body = post_body.join request.content_type = "multipart/form-data, boundary=#{@boundary}" res = http.request(request) unless res.is_a?(Net::HTTPSuccess) raise "Error: #{res}: #{res.}" end doc = REXML::Document.new(res.body) handle_response_errors(doc) doc end |
#verify_callback(preverify_ok, cert_store) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
stackoverflow.com/questions/22093042/implementing-https-certificate-pubkey-pinning-with-ruby/22108461#22108461 this method will be called on the OpenSSL connection to allow for additional verification.
A return of false means that verification has failed and will cause certificate verification errors.
A return of true is verification has been successful
202 203 204 205 206 207 208 209 210 211 212 |
# File 'lib/puppet/transport/panos.rb', line 202 def verify_callback(preverify_ok, cert_store) # if ssl_fingerprint is specified then do not # depend on the pre-verification checks, # if no ssl_fingerprint and the preverify_checks fail # then certificate verification will fail overall return false unless preverify_ok || @fingerprint end_cert = cert_store.chain[0] return true unless end_cert.to_der == cert_store.current_cert.to_der @fingerprint ? same_cert_fingerprint?(end_cert) : true end |