Module: Process
- Defined in:
- lib/mixlib/shellout/windows/core_ext.rb
Overview
Override Process.create to check for running in the Service window station and doing a full logon with LogonUser, instead of a CreateProcessWithLogon Cloned from github.com/djberg96/win32-process/blob/ffi/lib/win32/process.rb as of 2015-10-15 from commit cc066e5df25048f9806a610f54bf5f7f253e86f7
Defined Under Namespace
Classes: UnsupportedFeature
Class Method Summary collapse
- .create(args) ⇒ Object
- .create3(args) ⇒ Object
-
.create_environment_block(env_pointer, token) ⇒ Boolean
Retrieves the environment variables for the specified user.
- .create_process(app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo) ⇒ Object
- .create_process_as_user(token, app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo) ⇒ Object
- .create_process_with_logon(logon, domain, passwd, logon_flags, app, cmd, creation_flags, env, cwd, startinfo, procinfo) ⇒ Object
-
.destroy_environment_block(env_pointer) ⇒ Boolean
Frees environment variables created by the CreateEnvironmentBlock function.
-
.environment_list_to_hash(env_var) ⇒ Hash
Convert an array to a hash.
- .format_creds_from_hash(hash) ⇒ Object
- .get_profile_type ⇒ Object
- .get_windows_station_name ⇒ Object
- .load_user_profile(token, profile_ptr) ⇒ Object
-
.logon_has_roaming_profile? ⇒ Boolean
See Process::Constants::WIN32_PROFILETYPE.
- .logon_user(user, domain, passwd, type, provider = LOGON32_PROVIDER_DEFAULT) ⇒ Object
-
.merge_env_variables(fetched_env, current_env) ⇒ Array<String>
Merge environment variables of specified user and current environment variables.
-
.retrieve_environment_variables(token) ⇒ Object
Retrieves the environment variables for the specified user.
- .unload_user_profile(token, profile) ⇒ Object
Class Method Details
.create(args) ⇒ Object
119 120 121 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 119 def create(args) create3(args).first end |
.create3(args) ⇒ Object
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 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 123 def create3(args) unless args.is_a?(Hash) raise TypeError, "hash keyword arguments expected" end valid_keys = %w{ app_name command_line inherit creation_flags cwd environment startup_info thread_inherit process_inherit close_handles with_logon domain password elevated } valid_si_keys = %w{ startf_flags desktop title x y x_size y_size x_count_chars y_count_chars fill_attribute sw_flags stdin stdout stderr } # Set default values hash = { "app_name" => nil, "creation_flags" => 0, "close_handles" => true, } # Validate the keys, and convert symbols and case to lowercase strings. args.each do |key, val| key = key.to_s.downcase unless valid_keys.include?(key) raise ArgumentError, "invalid key '#{key}'" end hash[key] = val end si_hash = {} # If the startup_info key is present, validate its subkeys hash["startup_info"]&.each do |key, val| key = key.to_s.downcase unless valid_si_keys.include?(key) raise ArgumentError, "invalid startup_info key '#{key}'" end si_hash[key] = val end # The +command_line+ key is mandatory unless the +app_name+ key # is specified. unless hash["command_line"] if hash["app_name"] hash["command_line"] = hash["app_name"] hash["app_name"] = nil else raise ArgumentError, "command_line or app_name must be specified" end end env = nil # Retrieve the environment variables for the specified user. if hash["with_logon"] logon, passwd, domain = format_creds_from_hash(hash) logon_type = hash["elevated"] ? LOGON32_LOGON_BATCH : LOGON32_LOGON_INTERACTIVE token = logon_user(logon, domain, passwd, logon_type) logon_ptr = FFI::MemoryPointer.from_string(logon) profile = PROFILEINFO.new.tap do |dat| dat[:dwSize] = dat.size dat[:dwFlags] = 1 dat[:lpUserName] = logon_ptr end load_user_profile(token, profile.pointer) env_list = retrieve_environment_variables(token) end # The env string should be passed as a string of ';' separated paths. if hash["environment"] env = env_list.nil? ? hash["environment"] : merge_env_variables(env_list, hash["environment"]) unless env.respond_to?(:join) env = hash["environment"].split(File::PATH_SEPARATOR) end env = env.map { |e| e + 0.chr }.join("") + 0.chr env.to_wide_string! if hash["with_logon"] end # Process SECURITY_ATTRIBUTE structure process_security = nil if hash["process_inherit"] process_security = SECURITY_ATTRIBUTES.new process_security[:nLength] = 12 process_security[:bInheritHandle] = 1 end # Thread SECURITY_ATTRIBUTE structure thread_security = nil if hash["thread_inherit"] thread_security = SECURITY_ATTRIBUTES.new thread_security[:nLength] = 12 thread_security[:bInheritHandle] = 1 end # Automatically handle stdin, stdout and stderr as either IO objects # or file descriptors. This won't work for StringIO, however. It also # will not work on JRuby because of the way it handles internal file # descriptors. # %w{stdin stdout stderr}.each do |io| if si_hash[io] if si_hash[io].respond_to?(:fileno) handle = get_osfhandle(si_hash[io].fileno) else handle = get_osfhandle(si_hash[io]) end if handle == INVALID_HANDLE_VALUE ptr = FFI::MemoryPointer.new(:int) if windows_version >= 6 && get_errno(ptr) == 0 errno = ptr.read_int else errno = FFI.errno end raise SystemCallError.new("get_osfhandle", errno) end # Most implementations of Ruby on Windows create inheritable # handles by default, but some do not. RF bug #26988. bool = SetHandleInformation( handle, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT ) raise SystemCallError.new("SetHandleInformation", FFI.errno) unless bool si_hash[io] = handle si_hash["startf_flags"] ||= 0 si_hash["startf_flags"] |= STARTF_USESTDHANDLES hash["inherit"] = true end end procinfo = PROCESS_INFORMATION.new startinfo = STARTUPINFO.new unless si_hash.empty? startinfo[:cb] = startinfo.size startinfo[:lpDesktop] = si_hash["desktop"] if si_hash["desktop"] startinfo[:lpTitle] = si_hash["title"] if si_hash["title"] startinfo[:dwX] = si_hash["x"] if si_hash["x"] startinfo[:dwY] = si_hash["y"] if si_hash["y"] startinfo[:dwXSize] = si_hash["x_size"] if si_hash["x_size"] startinfo[:dwYSize] = si_hash["y_size"] if si_hash["y_size"] startinfo[:dwXCountChars] = si_hash["x_count_chars"] if si_hash["x_count_chars"] startinfo[:dwYCountChars] = si_hash["y_count_chars"] if si_hash["y_count_chars"] startinfo[:dwFillAttribute] = si_hash["fill_attribute"] if si_hash["fill_attribute"] startinfo[:dwFlags] = si_hash["startf_flags"] if si_hash["startf_flags"] startinfo[:wShowWindow] = si_hash["sw_flags"] if si_hash["sw_flags"] startinfo[:cbReserved2] = 0 startinfo[:hStdInput] = si_hash["stdin"] if si_hash["stdin"] startinfo[:hStdOutput] = si_hash["stdout"] if si_hash["stdout"] startinfo[:hStdError] = si_hash["stderr"] if si_hash["stderr"] end app = nil cmd = nil # Convert strings to wide character strings if present if hash["app_name"] app = hash["app_name"].to_wide_string end if hash["command_line"] cmd = hash["command_line"].to_wide_string end if hash["cwd"] cwd = hash["cwd"].to_wide_string end inherit = hash["inherit"] ? 1 : 0 if hash["with_logon"] logon, passwd, domain = format_creds_from_hash(hash) hash["creation_flags"] |= CREATE_UNICODE_ENVIRONMENT winsta_name = get_windows_station_name # If running in the service windows station must do a log on to get # to the interactive desktop. The running process user account must have # the 'Replace a process level token' permission. This is necessary as # the logon (which happens with CreateProcessWithLogon) must have an # interactive windows station to attach to, which is created with the # LogonUser call with the LOGON32_LOGON_INTERACTIVE flag. # # User Access Control (UAC) only applies to interactive logons, so we # can simulate running a command 'elevated' by running it under a separate # logon as a batch process. if hash["elevated"] || winsta_name =~ /^Service-0x0-.*$/i logon_type = hash["elevated"] ? LOGON32_LOGON_BATCH : LOGON32_LOGON_INTERACTIVE token = logon_user(logon, domain, passwd, logon_type) logon_ptr = FFI::MemoryPointer.from_string(logon) profile = PROFILEINFO.new.tap do |dat| dat[:dwSize] = dat.size dat[:dwFlags] = 1 dat[:lpUserName] = logon_ptr end if logon_has_roaming_profile? msg = %w{ Mixlib does not currently support executing commands as users configured with Roaming Profiles. [%s] }.join(" ") % logon.encode("UTF-8").unpack("A*") raise UnsupportedFeature.new(msg) end load_user_profile(token, profile.pointer) create_process_as_user(token, app, cmd, process_security, thread_security, inherit, hash["creation_flags"], env, cwd, startinfo, procinfo) else create_process_with_logon(logon, domain, passwd, LOGON_WITH_PROFILE, app, cmd, hash["creation_flags"], env, cwd, startinfo, procinfo) end else create_process(app, cmd, process_security, thread_security, inherit, hash["creation_flags"], env, cwd, startinfo, procinfo) end # Automatically close the process and thread handles in the # PROCESS_INFORMATION struct unless explicitly told not to. if hash["close_handles"] CloseHandle(procinfo[:hProcess]) CloseHandle(procinfo[:hThread]) # Clear these fields so callers don't attempt to close the handle # which can result in the wrong handle being closed or an # exception in some circumstances. procinfo[:hProcess] = 0 procinfo[:hThread] = 0 end process = ProcessInfo.new( procinfo[:hProcess], procinfo[:hThread], procinfo[:dwProcessId], procinfo[:dwThreadId] ) [ process, profile, token ] end |
.create_environment_block(env_pointer, token) ⇒ Boolean
Retrieves the environment variables for the specified user.
427 428 429 430 431 432 433 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 427 def create_environment_block(env_pointer, token) unless CreateEnvironmentBlock(env_pointer, token, false) raise SystemCallError.new("CreateEnvironmentBlock", FFI.errno) end true end |
.create_process(app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo) ⇒ Object
502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 502 def create_process(app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo) bool = CreateProcessW( app, # App name cmd, # Command line process_security, # Process attributes thread_security, # Thread attributes inherit, # Inherit handles? creation_flags, # Creation flags env, # Environment cwd, # Working directory startinfo, # Startup Info procinfo # Process Info ) unless bool raise SystemCallError.new("CreateProcessW", FFI.errno) end end |
.create_process_as_user(token, app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo) ⇒ Object
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 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 448 def create_process_as_user(token, app, cmd, process_security, thread_security, inherit, creation_flags, env, cwd, startinfo, procinfo) bool = CreateProcessAsUserW( token, # User token handle app, # App name cmd, # Command line process_security, # Process attributes thread_security, # Thread attributes inherit, # Inherit handles creation_flags, # Creation Flags env, # Environment cwd, # Working directory startinfo, # Startup Info procinfo # Process Info ) unless bool msg = case FFI.errno when ERROR_PRIVILEGE_NOT_HELD [ %{CreateProcessAsUserW (User '%s' must hold the 'Replace a process}, %{level token' and 'Adjust Memory Quotas for a process' permissions.}, %{Logoff the user after adding this right to make it effective.)}, ].join(" ") % ::ENV["USERNAME"] else "CreateProcessAsUserW failed." end raise SystemCallError.new(msg, FFI.errno) end end |
.create_process_with_logon(logon, domain, passwd, logon_flags, app, cmd, creation_flags, env, cwd, startinfo, procinfo) ⇒ Object
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 480 def create_process_with_logon(logon, domain, passwd, logon_flags, app, cmd, creation_flags, env, cwd, startinfo, procinfo) bool = CreateProcessWithLogonW( logon, # User domain, # Domain passwd, # Password logon_flags, # Logon flags app, # App name cmd, # Command line creation_flags, # Creation flags env, # Environment cwd, # Working directory startinfo, # Startup Info procinfo # Process Info ) unless bool raise SystemCallError.new("CreateProcessWithLogonW", FFI.errno) end end |
.destroy_environment_block(env_pointer) ⇒ Boolean
Frees environment variables created by the CreateEnvironmentBlock function.
440 441 442 443 444 445 446 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 440 def destroy_environment_block(env_pointer) unless DestroyEnvironmentBlock(env_pointer) raise SystemCallError.new("DestroyEnvironmentBlock", FFI.errno) end true end |
.environment_list_to_hash(env_var) ⇒ Hash
Convert an array to a hash.
625 626 627 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 625 def environment_list_to_hash(env_var) Hash[ env_var.map { |pair| pair.split("=", 2) } ] end |
.format_creds_from_hash(hash) ⇒ Object
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 566 def format_creds_from_hash(hash) logon = hash["with_logon"].to_wide_string if hash["password"] passwd = hash["password"].to_wide_string else raise ArgumentError, "password must be specified if with_logon is used" end if hash["domain"] domain = hash["domain"].to_wide_string end [ logon, passwd, domain ] end |
.get_profile_type ⇒ Object
393 394 395 396 397 398 399 400 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 393 def get_profile_type ptr = FFI::MemoryPointer.new(:uint) unless GetProfileType(ptr) raise SystemCallError.new("GetProfileType", FFI.errno) end ptr.read_uint end |
.get_windows_station_name ⇒ Object
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 547 def get_windows_station_name winsta_name = FFI::MemoryPointer.new(:char, 256) return_size = FFI::MemoryPointer.new(:ulong) bool = GetUserObjectInformationA( GetProcessWindowStation(), # Window station handle UOI_NAME, # Information to get winsta_name, # Buffer to receive information winsta_name.size, # Size of buffer return_size # Size filled into buffer ) unless bool raise SystemCallError.new("GetUserObjectInformationA", FFI.errno) end winsta_name.read_string(return_size.read_ulong) end |
.load_user_profile(token, profile_ptr) ⇒ Object
402 403 404 405 406 407 408 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 402 def load_user_profile(token, profile_ptr) unless LoadUserProfileW(token, profile_ptr) raise SystemCallError.new("LoadUserProfileW", FFI.errno) end true end |
.logon_has_roaming_profile? ⇒ Boolean
See Process::Constants::WIN32_PROFILETYPE
389 390 391 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 389 def logon_has_roaming_profile? get_profile_type >= 2 end |
.logon_user(user, domain, passwd, type, provider = LOGON32_PROVIDER_DEFAULT) ⇒ Object
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 523 def logon_user(user, domain, passwd, type, provider = LOGON32_PROVIDER_DEFAULT) token = FFI::MemoryPointer.new(:ulong) bool = LogonUserW( user, # User domain, # Domain passwd, # Password type, # Logon Type provider, # Logon Provider token # User token handle ) unless bool if (FFI.errno == ERROR_LOGON_TYPE_NOT_GRANTED) && (type == LOGON32_LOGON_BATCH) user_utf8 = user.encode( "UTF-8", invalid: :replace, undef: :replace, replace: "" ).delete("\0") raise SystemCallError.new("LogonUserW (User '#{user_utf8}' must hold 'Log on as a batch job' permissions.)", FFI.errno) else raise SystemCallError.new("LogonUserW", FFI.errno) end end token.read_ulong end |
.merge_env_variables(fetched_env, current_env) ⇒ Array<String>
Merge environment variables of specified user and current environment variables.
613 614 615 616 617 618 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 613 def merge_env_variables(fetched_env, current_env) env_hash_1 = environment_list_to_hash(fetched_env) env_hash_2 = environment_list_to_hash(current_env) merged_env = env_hash_2.merge(env_hash_1) merged_env.map { |k, v| "#{k}=#{v}" } end |
.retrieve_environment_variables(token) ⇒ Object
Retrieves the environment variables for the specified user.
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 587 def retrieve_environment_variables(token) env_list = [] env_pointer = FFI::MemoryPointer.new(:pointer) create_environment_block(env_pointer, token) str_ptr = env_pointer.read_pointer offset = 0 loop do new_str_pointer = str_ptr + offset break if new_str_pointer.read_string(2) == ENVIRONMENT_BLOCK_ENDS environment = new_str_pointer.read_wstring env_list << environment offset = offset + environment.length * 2 + 2 end # To free the buffer when we have finished with the environment block destroy_environment_block(str_ptr) env_list end |
.unload_user_profile(token, profile) ⇒ Object
410 411 412 413 414 415 416 417 418 419 |
# File 'lib/mixlib/shellout/windows/core_ext.rb', line 410 def unload_user_profile(token, profile) if profile[:hProfile] == 0 warn "\n\nWARNING: Profile not loaded\n" else unless UnloadUserProfile(token, profile[:hProfile]) raise SystemCallError.new("UnloadUserProfile", FFI.errno) end end true end |