Class: Aspera::Ascp::Installation
- Inherits:
-
Object
- Object
- Aspera::Ascp::Installation
- Includes:
- Singleton
- Defined in:
- lib/aspera/ascp/installation.rb
Overview
Singleton that tells where to find ascp and other local resources (keys..) , using the "path(:name)" method.
It is used by object : AgentDirect to find necessary resources
By default it takes the first Aspera product found
The user can specify ascp location by calling: sdk_folder= method
Constant Summary collapse
- CLIENT_SSH_KEY_OPTIONS =
options for SSH client private key
%i{dsa_rsa rsa per_client}.freeze
- USE_PRODUCT_PREFIX =
prefix
'product:'- FIRST_FOUND =
policy for product selection
'FIRST'
Instance Attribute Summary collapse
-
#referer_url ⇒ String?
URL that identifies the application and its version, sent in header
Refererwhen SDK locations are read,nil: not sent. -
#transferd_urls ⇒ Array<String>
URLs of SDK locations, tried in order.
Class Method Summary collapse
-
.instance ⇒ Installation
Returns the singleton instance of Installation.
-
.product_selector?(value) ⇒ Boolean
True if value selects a product instead of a folder.
Instance Method Summary collapse
-
#ascp_info ⇒ Object
information for
ascp info. -
#ascp_info_from_file ⇒ Object
Extract some stings from ascp binary Openssl information.
-
#ascp_info_from_log ⇒ Object
Extract some stings from ascp logs Folder, PVCL, version, license information.
-
#aspera_token_ssh_key_paths(types) ⇒ Array<String>
get paths of SSH keys to use for ascp client.
-
#check_or_create_sdk_file(filename, force: false, &block) ⇒ Object
TODO: if using another product than SDK, should use files from there.
-
#download_sdk(folder:, url: nil, version: nil, backup: true) {|entry_name| ... } ⇒ Object
Downloads and extracts the SDK archive for the current platform into
folder. - #extract_archive_files(url, archive_io) {|entry_name, entry_stream, link_target| ... } ⇒ Object
-
#file_paths ⇒ Hash
With key = file name (String), and value = path to file.
-
#get_ascp_version(exe_path) ⇒ Object
use in plugin
config. -
#get_exe_version(exe_path, vers_arg) ⇒ Object
Check that specified path is ascp and get version.
-
#install_sdk(url: nil, version: nil, folder: nil) ⇒ Array<String>
Downloads, installs and configures the SDK, returns name, version and install folder.
-
#installed_products ⇒ Array<Hash>
The list of installed products in format of product_locations_on_current_os.
-
#installed_sdk_version ⇒ String?
Version of the SDK installed in the SDK folder (from its meta data file), or nil if not installed.
-
#path(file_type) ⇒ String?
Get path of one resource file of currently activated product keys and certs are generated locally...
- #sdk_folder ⇒ Object
-
#sdk_folder=(ascp_location) ⇒ nil
Set
ascpexecutable "location" (optionsdk_folder) It can be: - Full path to folder whereascpexecutable is located, also used as SDK folder (keys, conf) - "product:PRODUCT_NAME" to use ascp from named product, SDK folder stays the default one - "product:FIRST" to use ascp from first found product. -
#sdk_location_for_platform(platform: nil, version: nil) ⇒ Hash
The entry of SDK locations for the given platform and version.
-
#sdk_locations(download: nil) ⇒ Array<Hash>
Loads YAML from cloud with locations of SDK archives for all platforms Tries each URL of option
locations_url(default if empty) in order, until one provides a valid list. -
#sdk_url_for_platform(platform: nil, version: nil) ⇒ String
The url for download of SDK archive for the given platform and version.
-
#ssh_cert_uuid ⇒ String
default bypass key phrase.
Instance Attribute Details
#referer_url ⇒ String?
Returns URL that identifies the application and its version, sent in header Referer when SDK locations are read, nil: not sent.
450 451 452 |
# File 'lib/aspera/ascp/installation.rb', line 450 def referer_url @referer_url end |
#transferd_urls ⇒ Array<String>
Returns URLs of SDK locations, tried in order.
447 448 449 |
# File 'lib/aspera/ascp/installation.rb', line 447 def transferd_urls @transferd_urls end |
Class Method Details
.instance ⇒ Installation
Returns the singleton instance of Installation
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 99 100 101 102 103 104 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 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 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 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 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 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 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 310 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 348 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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
# File 'lib/aspera/ascp/installation.rb', line 37 class Installation include Singleton # options for SSH client private key CLIENT_SSH_KEY_OPTIONS = %i{dsa_rsa rsa per_client}.freeze # prefix USE_PRODUCT_PREFIX = 'product:' # policy for product selection FIRST_FOUND = 'FIRST' class << self # @param value [String, nil] value of option `sdk_folder` # @return [Boolean] true if value selects a product instead of a folder def product_selector?(value) value.is_a?(String) && value.start_with?(USE_PRODUCT_PREFIX) end end # Loads YAML from cloud with locations of SDK archives for all platforms # Tries each URL of option `locations_url` (default if empty) in order, until one provides a valid list. # All but the last URL are read with a short timeout and no retry, so that fallback is quick. # The request tells which application reads the list, and what it downloads (header `Referer`, see `referer_url`): # the default URL counts requests per `Referer` (download statistics). # @param download [Hash, nil] SDK about to be downloaded (`sdk`: version, `platform`), `nil` if the list is only read # @return [Array<Hash>] location structure def sdk_locations(download: nil) Aspera.assert_type(@transferd_urls, Array) { 'locations_url' } location_urls = @transferd_urls.empty? ? TRANSFERD_ARCHIVE_LOCATION_URLS : @transferd_urls return UriReader.read_first(location_urls, what: 'SDK locations', headers: locations_headers(download)) do |content| locations = Yaml.safe_load(content) Aspera.assert_type(locations, Array) { 'SDK locations' } locations end end # Set `ascp` executable "location" (option `sdk_folder`) # It can be: # - Full path to folder where `ascp` executable is located, also used as SDK folder (keys, conf) # - "product:PRODUCT_NAME" to use ascp from named product, SDK folder stays the default one # - "product:FIRST" to use ascp from first found product # @param ascp_location [String] folder or product selector # @return [nil] def sdk_folder=(ascp_location) Aspera.assert_type(ascp_location, String) { 'ascp_location' } Aspera.assert(!ascp_location.empty?, 'ascp location cannot be empty: check your config file', type: ParameterError) @ascp_folder = nil if self.class.product_selector?(ascp_location) # Resolved on first use: product scan requires the SDK folder, which is set later @ascp_product = ascp_location.delete_prefix(USE_PRODUCT_PREFIX) Log.log.debug { "ascp_product=#{@ascp_product}" } else @ascp_product = nil Products::Transferd.sdk_directory = ascp_location.include?('/ascp') ? File.dirname(ascp_location) : ascp_location end nil end def sdk_folder path(:ascp) end # @return [Hash] with key = file name (String), and value = path to file def file_paths return SDK_FILES.to_h do |v| [v.to_s, begin path(v) rescue Errno::ENOENT => e e..gsub(/.*assertion failed: /, '').gsub(/\): .*/, ')') rescue => e e. end] end end # TODO: if using another product than SDK, should use files from there def check_or_create_sdk_file(filename, force: false, &block) FileUtils.mkdir_p(Products::Transferd.sdk_directory) return Environment.write_file_restricted(File.join(Products::Transferd.sdk_directory, filename), force: force, mode: 0o644, &block) end # Get path of one resource file of currently activated product # keys and certs are generated locally... (they are well known values, arch. independent) # @param file_type [Symbol] key of the resource file # @return [String, nil] Full path to the resource file or nil if not found def path(file_type) file_is_required = true case file_type when *EXE_FILES file_is_required = file_type.eql?(:ascp) file = sdk_exe_path(file_type) # transferd always comes from SDK file = File.join(product_ascp_folder, File.basename(file)) unless @ascp_product.nil? || file_type.eql?(:transferd) when :ssh_private_dsa, :ssh_private_rsa # assume last 3 letters are type type = file_type.to_s[-3..].to_sym file = check_or_create_sdk_file("aspera_bypass_#{type}.pem") { DataRepository.instance.item(type) } when :aspera_license file = check_or_create_sdk_file('aspera-license') { DataRepository.instance.item(:license) } when :aspera_conf file = check_or_create_sdk_file('aspera.conf') { DEFAULT_ASPERA_CONF } when :fallback_certificate, :fallback_private_key file_key = File.join(Products::Transferd.sdk_directory, 'aspera_fallback_cert_private_key.pem') file_cert = File.join(Products::Transferd.sdk_directory, 'aspera_fallback_cert.pem') if !File.exist?(file_key) || !File.exist?(file_cert) # create new self signed certificate for http fallback private_key = OpenSSL::PKey::RSA.new(4096) cert = WebServerSimple.self_signed_cert(private_key) check_or_create_sdk_file('aspera_fallback_cert_private_key.pem', force: true) { private_key.to_pem } check_or_create_sdk_file('aspera_fallback_cert.pem', force: true) { cert.to_pem } end file = file_type.eql?(:fallback_certificate) ? file_cert : file_key else Aspera.error_unexpected_value(file_type) end return unless file_is_required || File.exist?(file) Aspera.assert(File.exist?(file), type: Errno::ENOENT) { "#{file_type} not found (#{file})" } return file end # default bypass key phrase # @return [String] UUID used as bypass key phrase for SSH certificate def ssh_cert_uuid return DataRepository.instance.item(:uuid) end # get paths of SSH keys to use for ascp client # @param types [Symbol] types to use (one of CLIENT_SSH_KEY_OPTIONS) # @return [Array<String>] list of private key file paths def aspera_token_ssh_key_paths(types) Aspera.assert_values(types, CLIENT_SSH_KEY_OPTIONS) return case types when :dsa_rsa, :rsa types.to_s.split('_').map { |i| Installation.instance.path("ssh_private_#{i}".to_sym) } when :per_client Aspera.error_not_implemented end end # use in plugin `config` def get_ascp_version(exe_path) return get_exe_version(exe_path, '-A') end # Check that specified path is ascp and get version def get_exe_version(exe_path, vers_arg) Aspera.assert_type(exe_path, String) Aspera.assert_type(vers_arg, String) return unless File.exist?(exe_path) cmd_out, _err, status = Environment.secure_execute(exe_path, vers_arg, mode: :capture, exception: false) raise "An error occurred when testing #{exe_path}: #{cmd_out}" unless status.success? # get version from ascp, only after full extract, as windows requires DLLs (SSL/TLS/etc...) m = cmd_out.match(/ version ([0-9.]+)/) m.nil? ? nil : m[1].gsub(/\.$/, '') end # Extract some stings from ascp logs # Folder, PVCL, version, license information def ascp_info_from_log data = {} _, stderr, status = Environment.secure_execute(path(:ascp), '-DDL-', mode: :capture, exception: false) # read PATHs from ascp directly, and pvcl modules as well last_line = '' stderr.lines do |line| line.chomp! # Skip lines that may have accents next unless line.valid_encoding? last_line = line case line when /^DBG Path ([^ ]+) (dir|file) +: (.*)$/ data[Regexp.last_match(1)] = Regexp.last_match(3) when /^DBG Added module group:"(?<module>[^"]+)" name:"(?<scheme>[^"]+)", version:"(?<version>[^"]+)" interface:"(?<interface>[^"]+)"$/ c = Regexp.last_match.named_captures.symbolize_keys data[c[:interface]] ||= {} data[c[:interface]][c[:module]] ||= [] data[c[:interface]][c[:module]].push("#{c[:scheme]} v#{c[:version]}") when %r{^DBG License result \(/license/(\S+)\): (.+)$} data[Regexp.last_match(1)] = Regexp.last_match(2) when /^LOG (.+) version ([0-9.]+)$/ data['product_name'] = Regexp.last_match(1) data['product_version'] = Regexp.last_match(2) when /^LOG Initializing FASP version ([^,]+),/ data['ascp_version'] = Regexp.last_match(1) end end raise last_line if !status.exitstatus.eql?(1) && !data.key?('root') return data end # Extract some stings from ascp binary # Openssl information def ascp_info_from_file data = {} File.binread(path(:ascp)).scan(/[\x20-\x7E]{10,}/) do |bin_string| if (m = bin_string.match(/OPENSSLDIR.*"(.*)"/)) data['ascp_openssl_dir'] = m[1] elsif (m = bin_string.match(/OpenSSL (\d[^ -]+)/)) data['ascp_openssl_version'] = m[1] end end if File.file?(path(:ascp)) return data end # information for `ascp info` def ascp_info ascp_data = file_paths ascp_data.merge!(ascp_info_from_log) ascp_data.merge!(ascp_info_from_file) # `ascp` is run with `-L-` to read its paths: report where it logs without `-L` if ascp_data['log'].eql?('-') require_relative 'log_locations' ascp_data['log'] = LogLocations.ascp_log_location(path(:ascp), root: ascp_data['root'], conf_file: ascp_data['conf']) end return ascp_data end # @param platform [nil, String] Platform, if nil: current one # @param version [nil, String] Version, if nil: latest # @return [Hash] the entry of SDK locations for the given platform and version def sdk_location_for_platform(platform: nil, version: nil) platform = Environment.instance.architecture if platform.nil? all_locations = sdk_locations(download: {sdk: version || LATEST_VERSION, platform: platform}) locations = all_locations.select { |l| l['platform'].eql?(platform) } Aspera.assert(!locations.empty?, type: ParameterError) { "No SDK for platform: #{platform}, available: #{all_locations.map { |i| i['platform'] }.uniq}" } version = locations.max_by { |entry| Gem::Version.new(entry['version']) }['version'] if version.nil? info = locations.select { |entry| entry['version'].eql?(version) } Aspera.assert(!info.empty?, type: ParameterError) { "No such version: #{version} for #{platform}" } return info.first end # @return [String] the url for download of SDK archive for the given platform and version def sdk_url_for_platform(platform: nil, version: nil) return sdk_location_for_platform(platform: platform, version: version)['url'] end # @return [String, nil] Version of the SDK installed in the SDK folder (from its meta data file), or nil if not installed def installed_sdk_version return unless File.exist?(sdk_exe_path(:transferd)) = File.join(Products::Transferd.sdk_directory, Products::INFO_META_FILE) return unless File.exist?() return File.read().scan(%r{<version>(.*?)</version>}).flatten.first end # @param url [String] URL or filename used to detect archive format # @param archive_io [StringIO] archive content as an in-memory IO stream # @yieldparam entry_name [String] File path in archive # @yieldparam entry_stream [IO, Gem::Package::TarReader::Entry] Data stream # @yieldparam link_target [String, nil] Link target if symlink, nil otherwise def extract_archive_files(url, archive_io) Aspera.assert(block_given?, 'missing block') case url # Windows and Mac use zip when /\.zip$/ require 'zip' Zip::File.open_buffer(archive_io) do |zip_file| zip_file.each do |entry| next if entry.name.end_with?('/') entry.get_input_stream do |io| yield(entry.name, io, nil) end end end # Other Unixes use tar.gz when /\.tar\.gz/ require 'zlib' require 'rubygems/package' Zlib::GzipReader.wrap(archive_io) do |gzip| Gem::Package::TarReader.new(gzip) do |tar| tar.each do |entry| next if entry.directory? yield(entry.full_name, entry, entry.symlink? ? entry.header.linkname : nil) end end end else raise "unknown archive extension: #{url}" end end # Downloads and extracts the SDK archive for the current platform into `folder` # @param folder [String] Destination folder path # @param url [nil, String] URL to SDK archive, if nil: default url for version # @param version [nil, String] Specific version, if nil: latest version # @param backup [Boolean] If destination folder exists, then rename # @yieldparam entry_name [String] File path from archive # @yieldreturn [String, nil] Destination sub folder (end with /) or file, or nil to not extract def download_sdk(folder:, url: nil, version: nil, backup: true) url ||= sdk_url_for_platform(version: version) # Rename old install if backup && Dir.exist?(folder) && !Dir.empty?(folder) Log.log.warn('Previous install exists, renaming folder.') File.rename(folder, "#{folder}.#{Time.now.strftime('%Y%m%d%H%M%S')}") # TODO: cleanup old archives ? end FileUtils.mkdir_p(folder) # Security: Track extracted file paths to detect basename collisions extracted_files = {} # Security: Get canonical path of installation directory for boundary checks install_boundary = File.realpath(folder) archive_io = StringIO.new if UriReader.file?(url) archive_io.write(File.binread(UriReader.file_path(url))) else Rest::Client.new(base_url: url, redirect_max: 3).call(operation: 'GET', save_to: archive_io) end archive_io.rewind extract_archive_files(url, archive_io) do |entry_name, entry_stream, link_target| dest_folder = if block_given? yield(entry_name) else # default files to extract directly to main folder if in selected source folders Products::Transferd::RUNTIME_FOLDERS.any? { |i| entry_name.match?(%r{^[^/]*/#{i}/}) } ? '/' : nil end next if dest_folder.nil? dest_folder = File.join(folder, dest_folder) if dest_folder.end_with?('/') dest_file = File.join(dest_folder, File.basename(entry_name)) else dest_file = dest_folder dest_folder = File.dirname(dest_file) end # Security: Detect basename collisions that could overwrite symlinks file_basename = File.basename(dest_file) if extracted_files.key?(file_basename) Log.log.warn { "Rejecting file with duplicate basename: #{entry_name} (basename: #{file_basename}, previous: #{extracted_files[file_basename]})" } next end extracted_files[file_basename] = entry_name FileUtils.mkdir_p(dest_folder) if link_target.nil? # Security: Check if destination already exists, including a dangling symlink (`exist?` follows links) if File.symlink?(dest_file) || File.exist?(dest_file) Log.log.warn { "Rejecting write to existing file or link: #{dest_file}" } next end # Security: Verify the resolved path stays within installation boundary begin # Create parent directory if needed for realpath check FileUtils.mkdir_p(File.dirname(dest_file)) # Check where the file would resolve to (handles existing symlinks in path) resolved_dest = File.realpath(File.dirname(dest_file)) unless inside_folder?(resolved_dest, install_boundary) Log.log.warn { "Rejecting file outside installation directory: #{dest_file} resolves to #{resolved_dest}" } next end rescue Errno::ENOENT # Directory doesn't exist yet, verify the intended path unless inside_folder?(File.(dest_file), File.(folder)) Log.log.warn { "Rejecting file with path outside installation directory: #{dest_file}" } next end end File.open(dest_file, 'wb') { |output_stream| IO.copy_stream(entry_stream, output_stream) } else # Security: Validate symlink target stays within installation boundary # Resolve the symlink target relative to its location # (real path of the folder, so that links already on disk are resolved) link_dir = File.realpath(File.dirname(dest_file)) resolved_target = if link_target.start_with?('/') # Absolute symlink target link_target else # Relative symlink target File.(link_target, link_dir) end # Check if resolved target would be outside installation directory unless inside_folder?(File.(resolved_target), install_boundary) Log.log.warn { "Rejecting symlink pointing outside installation directory: #{entry_name} -> #{link_target} (resolves to #{resolved_target})" } next end File.symlink(link_target, dest_file) end end end # Downloads, installs and configures the SDK, returns name, version and install folder # @param url [nil, String] URL to SDK archive, if nil: default url for version # @param version [nil, String] Specific version, if nil: latest version # @param folder [nil, String] Install folder, if nil: the SDK folder (option `sdk_folder`), which is unchanged # @return [Array<String>] sdk name, sdk version, install folder def install_sdk(url: nil, version: nil, folder: nil) return with_sdk_directory(folder) { install_sdk(url: url, version: version) } unless folder.nil? folder = Products::Transferd.sdk_directory download_sdk(folder: folder, url: url, version: version) # Ensure necessary files are there, or generate them, restrict file access on SDK executables # (executables of SDK, even if `ascp` of another product is selected) SDK_FILES.each do |file_id_sym| if EXE_FILES.include?(file_id_sym) file_path = sdk_exe_path(file_id_sym) Environment.restrict_file_access(file_path, mode: 0o755) if File.exist?(file_path) else path(file_id_sym) end end # Generate meta data XML file in SDK if needed, based on actual binaries versions = File.join(folder, Products::INFO_META_FILE) if File.exist?() # file is there, read values: = File.read() sdk_name = .scan(%r{<name>(.*?)</name>}).flatten.first || 'unknown' sdk_version = .scan(%r{<version>(.*?)</version>}).flatten.first || 'unknown' else sdk_ascp_version = get_ascp_version(sdk_exe_path(:ascp)) transferd_version = get_exe_version(sdk_exe_path(:transferd), 'version') sdk_name = 'IBM Aspera Transfer SDK' sdk_version = transferd_version || sdk_ascp_version File.write(, "<product><name>#{sdk_name}</name><version>#{sdk_version}</version></product>") end return sdk_name, sdk_version, folder end # @return [Array<String>] URLs of SDK locations, tried in order attr_accessor :transferd_urls # @return [String, nil] URL that identifies the application and its version, sent in header `Referer` when SDK locations are read, `nil`: not sent attr_accessor :referer_url private # @param download [Hash, nil] See `sdk_locations` # @return [Hash] HTTP headers of the request for SDK locations def locations_headers(download) return {} if @referer_url.nil? {'Referer' => download.nil? ? @referer_url : "#{@referer_url}?#{URI.encode_www_form(download)}"} end # Run the block with another SDK folder (files of the SDK are located from it), then set the previous one back # @param folder [String] Temporary SDK folder def with_sdk_directory(folder) previous = Products::Transferd.sdk_directory begin Products::Transferd.sdk_directory = folder return yield ensure Products::Transferd.sdk_directory = previous end end # @param path [String] Path to check # @param boundary [String] Folder that must contain `path` # @return [Boolean] `true` if `path` is `boundary` or is below it (a sibling sharing the name prefix is not) def inside_folder?(path, boundary) path.eql?(boundary) || path.start_with?(boundary.end_with?(File::SEPARATOR) ? boundary : "#{boundary}#{File::SEPARATOR}") end DEFAULT_ASPERA_CONF = <<~END_OF_CONFIG_FILE <?xml version='1.0' encoding='UTF-8'?> <CONF version="2"> <default> <file_system> <resume_suffix>.aspera-ckpt</resume_suffix> <partial_file_suffix>.partial</partial_file_suffix> </file_system> </default> </CONF> END_OF_CONFIG_FILE # all executable files from SDK EXE_FILES = %i[ascp ascp4 async transferd].freeze # IDs of files present in SDK SDK_FILES = (EXE_FILES + %i[ssh_private_dsa ssh_private_rsa aspera_license aspera_conf fallback_certificate fallback_private_key]).freeze # Primary URL (ibm.biz short link) with fallback to the canonical GitHub raw source TRANSFERD_ARCHIVE_LOCATION_URLS = [ 'https://ibm.biz/sdk_location', 'https://raw.githubusercontent.com/IBM/aspera-cli/refs/heads/main/docs/sdk_location.yaml' ].freeze # Version reported in statistics when the latest version is requested (not known before the list is read) LATEST_VERSION = 'latest' # filename for ascp with optional extension (Windows) private_constant :DEFAULT_ASPERA_CONF, :EXE_FILES, :SDK_FILES, :TRANSFERD_ARCHIVE_LOCATION_URLS, :LATEST_VERSION def initialize # cache for installed products found @found_products = nil # URLs of SDK locations, tried in order @transferd_urls = TRANSFERD_ARCHIVE_LOCATION_URLS # set by the application, `nil`: no `Referer` sent @referer_url = nil # product selected with option `sdk_folder`, or nil to use SDK folder @ascp_product = nil # cache for folder of `ascp` of selected product @ascp_folder = nil end # @param file_type [Symbol] one of EXE_FILES # @return [String] path to executable in SDK folder def sdk_exe_path(file_type) file = Products::Transferd.transferd_path file = File.join(File.dirname(file), Environment.instance.exe_file(file_type.to_s)) unless file_type.eql?(:transferd) return file end # @return [String] folder of `ascp` of product selected with option `sdk_folder` def product_ascp_folder if @ascp_folder.nil? if @ascp_product.eql?(FIRST_FOUND) pl = installed_products.first Aspera.assert(!pl.nil?, type: EnvironmentError) { "No Aspera transfer module or SDK found.\nRefer to the manual or install SDK with command:\nascli config ascp install" } else pl = installed_products.find { |i| i[:name].eql?(@ascp_product) } Aspera.assert(!pl.nil?, type: ParameterError) { "No such product installed: #{@ascp_product}" } end @ascp_folder = File.dirname(pl[:ascp_path]) Log.log.debug { "ascp_folder=#{@ascp_folder}" } end return @ascp_folder end public # @return [Array<Hash>] the list of installed products in format of product_locations_on_current_os def installed_products return @found_products unless @found_products.nil? # :expected M app name is taken from the manifest if present, else defaults to this value # :app_root M main folder for the application # :log_root O location of log files (Linux uses syslog) # :run_root O only for Connect Client, location of http port file # :sub_bin O subfolder with executables, default : bin scan_locations = Products::Transferd.locations + Products::Desktop.locations + Products::Connect.locations + Products::CliV3.locations + Products::Hsts.locations + Products::Drive.locations # search installed products: with ascp @found_products = Products.find(scan_locations) end end |
.product_selector?(value) ⇒ Boolean
Returns true if value selects a product instead of a folder.
50 51 52 |
# File 'lib/aspera/ascp/installation.rb', line 50 def product_selector?(value) value.is_a?(String) && value.start_with?(USE_PRODUCT_PREFIX) end |
Instance Method Details
#ascp_info ⇒ Object
information for ascp info
239 240 241 242 243 244 245 246 247 248 249 |
# File 'lib/aspera/ascp/installation.rb', line 239 def ascp_info ascp_data = file_paths ascp_data.merge!(ascp_info_from_log) ascp_data.merge!(ascp_info_from_file) # `ascp` is run with `-L-` to read its paths: report where it logs without `-L` if ascp_data['log'].eql?('-') require_relative 'log_locations' ascp_data['log'] = LogLocations.ascp_log_location(path(:ascp), root: ascp_data['root'], conf_file: ascp_data['conf']) end return ascp_data end |
#ascp_info_from_file ⇒ Object
Extract some stings from ascp binary Openssl information
226 227 228 229 230 231 232 233 234 235 236 |
# File 'lib/aspera/ascp/installation.rb', line 226 def ascp_info_from_file data = {} File.binread(path(:ascp)).scan(/[\x20-\x7E]{10,}/) do |bin_string| if (m = bin_string.match(/OPENSSLDIR.*"(.*)"/)) data['ascp_openssl_dir'] = m[1] elsif (m = bin_string.match(/OpenSSL (\d[^ -]+)/)) data['ascp_openssl_version'] = m[1] end end if File.file?(path(:ascp)) return data end |
#ascp_info_from_log ⇒ Object
Extract some stings from ascp logs Folder, PVCL, version, license information
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 |
# File 'lib/aspera/ascp/installation.rb', line 193 def ascp_info_from_log data = {} _, stderr, status = Environment.secure_execute(path(:ascp), '-DDL-', mode: :capture, exception: false) # read PATHs from ascp directly, and pvcl modules as well last_line = '' stderr.lines do |line| line.chomp! # Skip lines that may have accents next unless line.valid_encoding? last_line = line case line when /^DBG Path ([^ ]+) (dir|file) +: (.*)$/ data[Regexp.last_match(1)] = Regexp.last_match(3) when /^DBG Added module group:"(?<module>[^"]+)" name:"(?<scheme>[^"]+)", version:"(?<version>[^"]+)" interface:"(?<interface>[^"]+)"$/ c = Regexp.last_match.named_captures.symbolize_keys data[c[:interface]] ||= {} data[c[:interface]][c[:module]] ||= [] data[c[:interface]][c[:module]].push("#{c[:scheme]} v#{c[:version]}") when %r{^DBG License result \(/license/(\S+)\): (.+)$} data[Regexp.last_match(1)] = Regexp.last_match(2) when /^LOG (.+) version ([0-9.]+)$/ data['product_name'] = Regexp.last_match(1) data['product_version'] = Regexp.last_match(2) when /^LOG Initializing FASP version ([^,]+),/ data['ascp_version'] = Regexp.last_match(1) end end raise last_line if !status.exitstatus.eql?(1) && !data.key?('root') return data end |
#aspera_token_ssh_key_paths(types) ⇒ Array<String>
get paths of SSH keys to use for ascp client
164 165 166 167 168 169 170 171 172 |
# File 'lib/aspera/ascp/installation.rb', line 164 def aspera_token_ssh_key_paths(types) Aspera.assert_values(types, CLIENT_SSH_KEY_OPTIONS) return case types when :dsa_rsa, :rsa types.to_s.split('_').map { |i| Installation.instance.path("ssh_private_#{i}".to_sym) } when :per_client Aspera.error_not_implemented end end |
#check_or_create_sdk_file(filename, force: false, &block) ⇒ Object
TODO: if using another product than SDK, should use files from there
112 113 114 115 |
# File 'lib/aspera/ascp/installation.rb', line 112 def check_or_create_sdk_file(filename, force: false, &block) FileUtils.mkdir_p(Products::Transferd.sdk_directory) return Environment.write_file_restricted(File.join(Products::Transferd.sdk_directory, filename), force: force, mode: 0o644, &block) end |
#download_sdk(folder:, url: nil, version: nil, backup: true) {|entry_name| ... } ⇒ Object
Downloads and extracts the SDK archive for the current platform into folder
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 348 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 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 |
# File 'lib/aspera/ascp/installation.rb', line 321 def download_sdk(folder:, url: nil, version: nil, backup: true) url ||= sdk_url_for_platform(version: version) # Rename old install if backup && Dir.exist?(folder) && !Dir.empty?(folder) Log.log.warn('Previous install exists, renaming folder.') File.rename(folder, "#{folder}.#{Time.now.strftime('%Y%m%d%H%M%S')}") # TODO: cleanup old archives ? end FileUtils.mkdir_p(folder) # Security: Track extracted file paths to detect basename collisions extracted_files = {} # Security: Get canonical path of installation directory for boundary checks install_boundary = File.realpath(folder) archive_io = StringIO.new if UriReader.file?(url) archive_io.write(File.binread(UriReader.file_path(url))) else Rest::Client.new(base_url: url, redirect_max: 3).call(operation: 'GET', save_to: archive_io) end archive_io.rewind extract_archive_files(url, archive_io) do |entry_name, entry_stream, link_target| dest_folder = if block_given? yield(entry_name) else # default files to extract directly to main folder if in selected source folders Products::Transferd::RUNTIME_FOLDERS.any? { |i| entry_name.match?(%r{^[^/]*/#{i}/}) } ? '/' : nil end next if dest_folder.nil? dest_folder = File.join(folder, dest_folder) if dest_folder.end_with?('/') dest_file = File.join(dest_folder, File.basename(entry_name)) else dest_file = dest_folder dest_folder = File.dirname(dest_file) end # Security: Detect basename collisions that could overwrite symlinks file_basename = File.basename(dest_file) if extracted_files.key?(file_basename) Log.log.warn { "Rejecting file with duplicate basename: #{entry_name} (basename: #{file_basename}, previous: #{extracted_files[file_basename]})" } next end extracted_files[file_basename] = entry_name FileUtils.mkdir_p(dest_folder) if link_target.nil? # Security: Check if destination already exists, including a dangling symlink (`exist?` follows links) if File.symlink?(dest_file) || File.exist?(dest_file) Log.log.warn { "Rejecting write to existing file or link: #{dest_file}" } next end # Security: Verify the resolved path stays within installation boundary begin # Create parent directory if needed for realpath check FileUtils.mkdir_p(File.dirname(dest_file)) # Check where the file would resolve to (handles existing symlinks in path) resolved_dest = File.realpath(File.dirname(dest_file)) unless inside_folder?(resolved_dest, install_boundary) Log.log.warn { "Rejecting file outside installation directory: #{dest_file} resolves to #{resolved_dest}" } next end rescue Errno::ENOENT # Directory doesn't exist yet, verify the intended path unless inside_folder?(File.(dest_file), File.(folder)) Log.log.warn { "Rejecting file with path outside installation directory: #{dest_file}" } next end end File.open(dest_file, 'wb') { |output_stream| IO.copy_stream(entry_stream, output_stream) } else # Security: Validate symlink target stays within installation boundary # Resolve the symlink target relative to its location # (real path of the folder, so that links already on disk are resolved) link_dir = File.realpath(File.dirname(dest_file)) resolved_target = if link_target.start_with?('/') # Absolute symlink target link_target else # Relative symlink target File.(link_target, link_dir) end # Check if resolved target would be outside installation directory unless inside_folder?(File.(resolved_target), install_boundary) Log.log.warn { "Rejecting symlink pointing outside installation directory: #{entry_name} -> #{link_target} (resolves to #{resolved_target})" } next end File.symlink(link_target, dest_file) end end end |
#extract_archive_files(url, archive_io) {|entry_name, entry_stream, link_target| ... } ⇒ Object
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 310 311 312 |
# File 'lib/aspera/ascp/installation.rb', line 283 def extract_archive_files(url, archive_io) Aspera.assert(block_given?, 'missing block') case url # Windows and Mac use zip when /\.zip$/ require 'zip' Zip::File.open_buffer(archive_io) do |zip_file| zip_file.each do |entry| next if entry.name.end_with?('/') entry.get_input_stream do |io| yield(entry.name, io, nil) end end end # Other Unixes use tar.gz when /\.tar\.gz/ require 'zlib' require 'rubygems/package' Zlib::GzipReader.wrap(archive_io) do |gzip| Gem::Package::TarReader.new(gzip) do |tar| tar.each do |entry| next if entry.directory? yield(entry.full_name, entry, entry.symlink? ? entry.header.linkname : nil) end end end else raise "unknown archive extension: #{url}" end end |
#file_paths ⇒ Hash
Returns with key = file name (String), and value = path to file.
99 100 101 102 103 104 105 106 107 108 109 |
# File 'lib/aspera/ascp/installation.rb', line 99 def file_paths return SDK_FILES.to_h do |v| [v.to_s, begin path(v) rescue Errno::ENOENT => e e..gsub(/.*assertion failed: /, '').gsub(/\): .*/, ')') rescue => e e. end] end end |
#get_ascp_version(exe_path) ⇒ Object
use in plugin config
175 176 177 |
# File 'lib/aspera/ascp/installation.rb', line 175 def get_ascp_version(exe_path) return get_exe_version(exe_path, '-A') end |
#get_exe_version(exe_path, vers_arg) ⇒ Object
Check that specified path is ascp and get version
180 181 182 183 184 185 186 187 188 189 |
# File 'lib/aspera/ascp/installation.rb', line 180 def get_exe_version(exe_path, vers_arg) Aspera.assert_type(exe_path, String) Aspera.assert_type(vers_arg, String) return unless File.exist?(exe_path) cmd_out, _err, status = Environment.secure_execute(exe_path, vers_arg, mode: :capture, exception: false) raise "An error occurred when testing #{exe_path}: #{cmd_out}" unless status.success? # get version from ascp, only after full extract, as windows requires DLLs (SSL/TLS/etc...) m = cmd_out.match(/ version ([0-9.]+)/) m.nil? ? nil : m[1].gsub(/\.$/, '') end |
#install_sdk(url: nil, version: nil, folder: nil) ⇒ Array<String>
Downloads, installs and configures the SDK, returns name, version and install folder
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 |
# File 'lib/aspera/ascp/installation.rb', line 415 def install_sdk(url: nil, version: nil, folder: nil) return with_sdk_directory(folder) { install_sdk(url: url, version: version) } unless folder.nil? folder = Products::Transferd.sdk_directory download_sdk(folder: folder, url: url, version: version) # Ensure necessary files are there, or generate them, restrict file access on SDK executables # (executables of SDK, even if `ascp` of another product is selected) SDK_FILES.each do |file_id_sym| if EXE_FILES.include?(file_id_sym) file_path = sdk_exe_path(file_id_sym) Environment.restrict_file_access(file_path, mode: 0o755) if File.exist?(file_path) else path(file_id_sym) end end # Generate meta data XML file in SDK if needed, based on actual binaries versions = File.join(folder, Products::INFO_META_FILE) if File.exist?() # file is there, read values: = File.read() sdk_name = .scan(%r{<name>(.*?)</name>}).flatten.first || 'unknown' sdk_version = .scan(%r{<version>(.*?)</version>}).flatten.first || 'unknown' else sdk_ascp_version = get_ascp_version(sdk_exe_path(:ascp)) transferd_version = get_exe_version(sdk_exe_path(:transferd), 'version') sdk_name = 'IBM Aspera Transfer SDK' sdk_version = transferd_version || sdk_ascp_version File.write(, "<product><name>#{sdk_name}</name><version>#{sdk_version}</version></product>") end return sdk_name, sdk_version, folder end |
#installed_products ⇒ Array<Hash>
Returns the list of installed products in format of product_locations_on_current_os.
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 |
# File 'lib/aspera/ascp/installation.rb', line 545 def installed_products return @found_products unless @found_products.nil? # :expected M app name is taken from the manifest if present, else defaults to this value # :app_root M main folder for the application # :log_root O location of log files (Linux uses syslog) # :run_root O only for Connect Client, location of http port file # :sub_bin O subfolder with executables, default : bin scan_locations = Products::Transferd.locations + Products::Desktop.locations + Products::Connect.locations + Products::CliV3.locations + Products::Hsts.locations + Products::Drive.locations # search installed products: with ascp @found_products = Products.find(scan_locations) end |
#installed_sdk_version ⇒ String?
Returns Version of the SDK installed in the SDK folder (from its meta data file), or nil if not installed.
271 272 273 274 275 276 |
# File 'lib/aspera/ascp/installation.rb', line 271 def installed_sdk_version return unless File.exist?(sdk_exe_path(:transferd)) = File.join(Products::Transferd.sdk_directory, Products::INFO_META_FILE) return unless File.exist?() return File.read().scan(%r{<version>(.*?)</version>}).flatten.first end |
#path(file_type) ⇒ String?
Get path of one resource file of currently activated product keys and certs are generated locally... (they are well known values, arch. independent)
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 148 149 150 151 152 153 |
# File 'lib/aspera/ascp/installation.rb', line 121 def path(file_type) file_is_required = true case file_type when *EXE_FILES file_is_required = file_type.eql?(:ascp) file = sdk_exe_path(file_type) # transferd always comes from SDK file = File.join(product_ascp_folder, File.basename(file)) unless @ascp_product.nil? || file_type.eql?(:transferd) when :ssh_private_dsa, :ssh_private_rsa # assume last 3 letters are type type = file_type.to_s[-3..].to_sym file = check_or_create_sdk_file("aspera_bypass_#{type}.pem") { DataRepository.instance.item(type) } when :aspera_license file = check_or_create_sdk_file('aspera-license') { DataRepository.instance.item(:license) } when :aspera_conf file = check_or_create_sdk_file('aspera.conf') { DEFAULT_ASPERA_CONF } when :fallback_certificate, :fallback_private_key file_key = File.join(Products::Transferd.sdk_directory, 'aspera_fallback_cert_private_key.pem') file_cert = File.join(Products::Transferd.sdk_directory, 'aspera_fallback_cert.pem') if !File.exist?(file_key) || !File.exist?(file_cert) # create new self signed certificate for http fallback private_key = OpenSSL::PKey::RSA.new(4096) cert = WebServerSimple.self_signed_cert(private_key) check_or_create_sdk_file('aspera_fallback_cert_private_key.pem', force: true) { private_key.to_pem } check_or_create_sdk_file('aspera_fallback_cert.pem', force: true) { cert.to_pem } end file = file_type.eql?(:fallback_certificate) ? file_cert : file_key else Aspera.error_unexpected_value(file_type) end return unless file_is_required || File.exist?(file) Aspera.assert(File.exist?(file), type: Errno::ENOENT) { "#{file_type} not found (#{file})" } return file end |
#sdk_folder ⇒ Object
94 95 96 |
# File 'lib/aspera/ascp/installation.rb', line 94 def sdk_folder path(:ascp) end |
#sdk_folder=(ascp_location) ⇒ nil
Set ascp executable "location" (option sdk_folder)
It can be:
- Full path to folder where
ascpexecutable is located, also used as SDK folder (keys, conf) - "product:PRODUCT_NAME" to use ascp from named product, SDK folder stays the default one
- "product:FIRST" to use ascp from first found product
79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/aspera/ascp/installation.rb', line 79 def sdk_folder=(ascp_location) Aspera.assert_type(ascp_location, String) { 'ascp_location' } Aspera.assert(!ascp_location.empty?, 'ascp location cannot be empty: check your config file', type: ParameterError) @ascp_folder = nil if self.class.product_selector?(ascp_location) # Resolved on first use: product scan requires the SDK folder, which is set later @ascp_product = ascp_location.delete_prefix(USE_PRODUCT_PREFIX) Log.log.debug { "ascp_product=#{@ascp_product}" } else @ascp_product = nil Products::Transferd.sdk_directory = ascp_location.include?('/ascp') ? File.dirname(ascp_location) : ascp_location end nil end |
#sdk_location_for_platform(platform: nil, version: nil) ⇒ Hash
Returns the entry of SDK locations for the given platform and version.
254 255 256 257 258 259 260 261 262 263 |
# File 'lib/aspera/ascp/installation.rb', line 254 def sdk_location_for_platform(platform: nil, version: nil) platform = Environment.instance.architecture if platform.nil? all_locations = sdk_locations(download: {sdk: version || LATEST_VERSION, platform: platform}) locations = all_locations.select { |l| l['platform'].eql?(platform) } Aspera.assert(!locations.empty?, type: ParameterError) { "No SDK for platform: #{platform}, available: #{all_locations.map { |i| i['platform'] }.uniq}" } version = locations.max_by { |entry| Gem::Version.new(entry['version']) }['version'] if version.nil? info = locations.select { |entry| entry['version'].eql?(version) } Aspera.assert(!info.empty?, type: ParameterError) { "No such version: #{version} for #{platform}" } return info.first end |
#sdk_locations(download: nil) ⇒ Array<Hash>
Loads YAML from cloud with locations of SDK archives for all platforms
Tries each URL of option locations_url (default if empty) in order, until one provides a valid list.
All but the last URL are read with a short timeout and no retry, so that fallback is quick.
The request tells which application reads the list, and what it downloads (header Referer, see referer_url):
the default URL counts requests per Referer (download statistics).
62 63 64 65 66 67 68 69 70 |
# File 'lib/aspera/ascp/installation.rb', line 62 def sdk_locations(download: nil) Aspera.assert_type(@transferd_urls, Array) { 'locations_url' } location_urls = @transferd_urls.empty? ? TRANSFERD_ARCHIVE_LOCATION_URLS : @transferd_urls return UriReader.read_first(location_urls, what: 'SDK locations', headers: locations_headers(download)) do |content| locations = Yaml.safe_load(content) Aspera.assert_type(locations, Array) { 'SDK locations' } locations end end |
#sdk_url_for_platform(platform: nil, version: nil) ⇒ String
Returns the url for download of SDK archive for the given platform and version.
266 267 268 |
# File 'lib/aspera/ascp/installation.rb', line 266 def sdk_url_for_platform(platform: nil, version: nil) return sdk_location_for_platform(platform: platform, version: version)['url'] end |
#ssh_cert_uuid ⇒ String
default bypass key phrase
157 158 159 |
# File 'lib/aspera/ascp/installation.rb', line 157 def ssh_cert_uuid return DataRepository.instance.item(:uuid) end |