From d9124ef9fa7e798b329b1dcfb86bcb6ef48f452b Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Fri, 11 Jan 2013 12:31:01 -0800 Subject: Add process impersonation --- lib/mixlib/shellout.rb | 11 ++++ lib/mixlib/shellout/windows.rb | 5 ++ lib/mixlib/shellout/windows/core_ext.rb | 100 +++++++++++++++++++++++--------- 3 files changed, 89 insertions(+), 27 deletions(-) diff --git a/lib/mixlib/shellout.rb b/lib/mixlib/shellout.rb index 3b2651c047..da58bac08c 100644 --- a/lib/mixlib/shellout.rb +++ b/lib/mixlib/shellout.rb @@ -39,6 +39,10 @@ module Mixlib # User the command will run as. Normally set via options passed to new attr_accessor :user + attr_accessor :domain + attr_accessor :password + attr_accessor :with_logon + attr_accessor :remote_call # Group the command will run as. Normally set via options passed to new attr_accessor :group @@ -261,8 +265,15 @@ module Mixlib case option.to_s when 'cwd' self.cwd = setting + when 'domain' + self.domain = setting + when 'password' + self.password = setting when 'user' self.user = setting + self.with_logon = setting + when 'remote_call' + self.remote_call = setting when 'group' self.group = setting when 'umask' diff --git a/lib/mixlib/shellout/windows.rb b/lib/mixlib/shellout/windows.rb index 7bebb3bfb3..a8511efe77 100644 --- a/lib/mixlib/shellout/windows.rb +++ b/lib/mixlib/shellout/windows.rb @@ -23,6 +23,7 @@ require 'windows/handle' require 'windows/process' require 'windows/synchronize' +require 'mixlib/shellout/windows/localsystem' require 'mixlib/shellout/windows/core_ext' module Mixlib @@ -66,6 +67,10 @@ module Mixlib :close_handles => false } create_process_args[:cwd] = cwd if cwd + create_process_args[:domain] = domain if domain + create_process_args[:with_logon] = with_logon if with_logon + create_process_args[:password] = password if password + create_process_args[:remote_call] = remote_call if remote_call # # Start the process diff --git a/lib/mixlib/shellout/windows/core_ext.rb b/lib/mixlib/shellout/windows/core_ext.rb index be25127d00..ca4a9af464 100644 --- a/lib/mixlib/shellout/windows/core_ext.rb +++ b/lib/mixlib/shellout/windows/core_ext.rb @@ -28,6 +28,7 @@ require 'windows/synchronize' module Windows module Process API.new('CreateProcess', 'SPPPLLLPPP', 'B') + API.new('CreateProcessAsUser', 'PSPPPLLLPPP', 'B', 'advapi32.dll') end end @@ -45,7 +46,7 @@ module Process valid_keys = %w/ app_name command_line inherit creation_flags cwd environment startup_info thread_inherit process_inherit close_handles with_logon - domain password + domain password remote_call / valid_si_keys = %/ @@ -60,6 +61,9 @@ module Process 'close_handles' => true } + #See if running as local service + is_local_service = ENV["USERNAME"].downcase == "local service" + # Validate the keys, and convert symbols and case to lowercase strings. args.each{ |key, val| key = key.to_s.downcase @@ -102,10 +106,11 @@ module Process env = hash['environment'].split(File::PATH_SEPARATOR) end # The argument format is a series of null-terminated strings, with an additional null terminator. - env = env.map { |e| e + "\0" }.join("") + "\0" - if hash['with_logon'] - env = env.multi_to_wide(e) - end + # If calling CreateProcessWithLogonW must put the hash in a wide format + env = env.map do |e| + hash['with_logon'].nil? || is_local_service || hash['remote_call'] ? e + "\0" : multi_to_wide(e) + end.join("") + "\0" + env = [env].pack('p*').unpack('L').first else env = nil @@ -182,28 +187,69 @@ module Process end if hash['with_logon'] - logon = multi_to_wide(hash['with_logon']) - domain = multi_to_wide(hash['domain']) - app = hash['app_name'].nil? ? nil : multi_to_wide(hash['app_name']) - cmd = hash['command_line'].nil? ? nil : multi_to_wide(hash['command_line']) - cwd = multi_to_wide(hash['cwd']) - passwd = multi_to_wide(hash['password']) - - hash['creation_flags'] |= CREATE_UNICODE_ENVIRONMENT - - process_ran = CreateProcessWithLogonW( - logon, # User - domain, # Domain - passwd, # Password - LOGON_WITH_PROFILE, # Logon flags - app, # App name - cmd, # Command line - hash['creation_flags'], # Creation flags - env, # Environment - cwd, # Working directory - startinfo, # Startup Info - procinfo # Process Info - ) + # Need to do a LogonUser and CreateProcessAsUser to work on all windows platforms + + if is_local_service || hash['remote_call'] + include Process::Constants + extend Process::Functions + + Process.is_local_system? + + logon = hash['with_logon'] + domain = hash['domain'] + app = hash['app_name'] + cmd = hash['command_line'] + cwd = hash['cwd'] + passwd = hash['password'] + token = FFI::MemoryPointer.new(:ulong) + + LogonUser( + logon, # User + domain, # Domain + passwd, # Password + LOGON32_LOGON_INTERACTIVE, # Logon Type + LOGON32_PROVIDER_DEFAULT, # Logon Provider + token # User token handle + ) + + token = token.read_ulong + + process_ran = CreateProcessAsUser( + token, # User token handle + app, # App name + cmd, # Command line + process_security, # Process attributes + thread_security, # Thread attributes + hash['inherit'], # Inherit handles + hash['creation_flags'], # Creation Flags + env, # Environment + cwd, # Working directory + startinfo, # Startup Info + procinfo # Process Info + ) + else + logon = multi_to_wide(hash['with_logon']) + domain = multi_to_wide(hash['domain']) + app = hash['app_name'].nil? ? nil : multi_to_wide(hash['app_name']) + cmd = hash['command_line'].nil? ? nil : multi_to_wide(hash['command_line']) + cwd = multi_to_wide(hash['cwd']) + passwd = multi_to_wide(hash['password']) + hash['creation_flags'] |= CREATE_UNICODE_ENVIRONMENT + + process_ran = CreateProcessWithLogonW( + logon, # User + domain, # Domain + passwd, # Password + LOGON_WITH_PROFILE, # Logon flags + app, # App name + cmd, # Command line + hash['creation_flags'], # Creation flags + env, # Environment + cwd, # Working directory + startinfo, # Startup Info + procinfo # Process Info + ) + end else process_ran = CreateProcess( hash['app_name'], # App name -- cgit v1.2.1 From 493218537a11ecf1686741acb8c087bbfa27292d Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Fri, 11 Jan 2013 12:34:21 -0800 Subject: Add local_system file --- lib/mixlib/shellout/windows.rb | 2 +- lib/mixlib/shellout/windows/local_system.rb | 72 +++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 lib/mixlib/shellout/windows/local_system.rb diff --git a/lib/mixlib/shellout/windows.rb b/lib/mixlib/shellout/windows.rb index a8511efe77..4d9c87cad2 100644 --- a/lib/mixlib/shellout/windows.rb +++ b/lib/mixlib/shellout/windows.rb @@ -23,7 +23,7 @@ require 'windows/handle' require 'windows/process' require 'windows/synchronize' -require 'mixlib/shellout/windows/localsystem' +require 'mixlib/shellout/windows/local_system' require 'mixlib/shellout/windows/core_ext' module Mixlib diff --git a/lib/mixlib/shellout/windows/local_system.rb b/lib/mixlib/shellout/windows/local_system.rb new file mode 100644 index 0000000000..ec88ab9335 --- /dev/null +++ b/lib/mixlib/shellout/windows/local_system.rb @@ -0,0 +1,72 @@ +#-- +# Author:: Kevin Moser () +# Copyright:: Copyright (c) 2012, 2013 Nordstrom, Inc. +# License:: Apache License, Version 2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +require 'win32/process' +require 'windows/handle' +require 'windows/process' +require 'windows/synchronize' + +# Add new constants for Logon +module Process::Constants + LOGON32_LOGON_INTERACTIVE = 0x00000002 + LOGON32_PROVIDER_DEFAULT = 0x00000000 + + SID_MAX_SUB_AUTHORITIES = 0x00000015 + SECURITY_NT_AUTHORITY = 0x00000005 + SECURITY_LOCAL_SYSTEM_RID = 0x00000012 +end + +# Define the LogonUser function +module Process::Functions + module FFI::Library + # Wrapper method for attach_function + private + def attach_pfunc(*args) + attach_function(*args) + private args[0] + end + end + + extend FFI::Library + + ffi_lib :advapi32 + + attach_pfunc :LogonUser, :LogonUserA, + [:buffer_in, :buffer_in, :buffer_in, :ulong, :ulong, :pointer], :bool + + attach_pfunc :AllocateAndInitializeSid, + [:pointer, :uint, :ulong, :ulong, :ulong, :ulong, :ulong, :ulong, :ulong, :ulong, :pointer], :bool + attach_pfunc :EqualSid, [:pointer, :pointer], :bool + attach_pfunc :FreeSid, [:pointer], :pointer +end + +module Process + def is_local_system? + token = FFI::MemoryPointer.new(:ulong) + + unless OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, token) + raise SystemCallError, FFI.errno, "OpenProcessToken" + end + + puts("-------------------token pointer: #{token.read_ulong}") + + CloseHandle(token) + + end + + module_function :is_local_system? +end -- cgit v1.2.1 From 7c8ea49051337e98f172ad693e7216732d036f14 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Mon, 14 Jan 2013 08:20:14 -0800 Subject: Update to use win32-process ~> 0.7.0 --- mixlib-shellout-x86-mingw32.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mixlib-shellout-x86-mingw32.gemspec b/mixlib-shellout-x86-mingw32.gemspec index 7244377a38..8cd15c1f48 100644 --- a/mixlib-shellout-x86-mingw32.gemspec +++ b/mixlib-shellout-x86-mingw32.gemspec @@ -3,6 +3,6 @@ gemspec = eval(IO.read(File.expand_path("../mixlib-shellout.gemspec", __FILE__)) gemspec.platform = "x86-mingw32" -gemspec.add_dependency "win32-process", "~> 0.6.5" +gemspec.add_dependency "win32-process", "~> 0.7.0" gemspec -- cgit v1.2.1 From dddf00e96afba47f4a30d187228934ffb397f301 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 15 Jan 2013 09:33:48 -0800 Subject: Remove local_system file --- lib/mixlib/shellout/windows/local_system.rb | 72 ----------------------------- 1 file changed, 72 deletions(-) delete mode 100644 lib/mixlib/shellout/windows/local_system.rb diff --git a/lib/mixlib/shellout/windows/local_system.rb b/lib/mixlib/shellout/windows/local_system.rb deleted file mode 100644 index ec88ab9335..0000000000 --- a/lib/mixlib/shellout/windows/local_system.rb +++ /dev/null @@ -1,72 +0,0 @@ -#-- -# Author:: Kevin Moser () -# Copyright:: Copyright (c) 2012, 2013 Nordstrom, Inc. -# License:: Apache License, Version 2.0 -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -require 'win32/process' -require 'windows/handle' -require 'windows/process' -require 'windows/synchronize' - -# Add new constants for Logon -module Process::Constants - LOGON32_LOGON_INTERACTIVE = 0x00000002 - LOGON32_PROVIDER_DEFAULT = 0x00000000 - - SID_MAX_SUB_AUTHORITIES = 0x00000015 - SECURITY_NT_AUTHORITY = 0x00000005 - SECURITY_LOCAL_SYSTEM_RID = 0x00000012 -end - -# Define the LogonUser function -module Process::Functions - module FFI::Library - # Wrapper method for attach_function + private - def attach_pfunc(*args) - attach_function(*args) - private args[0] - end - end - - extend FFI::Library - - ffi_lib :advapi32 - - attach_pfunc :LogonUser, :LogonUserA, - [:buffer_in, :buffer_in, :buffer_in, :ulong, :ulong, :pointer], :bool - - attach_pfunc :AllocateAndInitializeSid, - [:pointer, :uint, :ulong, :ulong, :ulong, :ulong, :ulong, :ulong, :ulong, :ulong, :pointer], :bool - attach_pfunc :EqualSid, [:pointer, :pointer], :bool - attach_pfunc :FreeSid, [:pointer], :pointer -end - -module Process - def is_local_system? - token = FFI::MemoryPointer.new(:ulong) - - unless OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, token) - raise SystemCallError, FFI.errno, "OpenProcessToken" - end - - puts("-------------------token pointer: #{token.read_ulong}") - - CloseHandle(token) - - end - - module_function :is_local_system? -end -- cgit v1.2.1 From b7c9d33568d96f885d15ae41f683263f57a8abb2 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 15 Jan 2013 09:35:40 -0800 Subject: Remove remote_call option --- lib/mixlib/shellout.rb | 3 --- lib/mixlib/shellout/windows.rb | 2 -- 2 files changed, 5 deletions(-) diff --git a/lib/mixlib/shellout.rb b/lib/mixlib/shellout.rb index da58bac08c..5b50a14b6c 100644 --- a/lib/mixlib/shellout.rb +++ b/lib/mixlib/shellout.rb @@ -42,7 +42,6 @@ module Mixlib attr_accessor :domain attr_accessor :password attr_accessor :with_logon - attr_accessor :remote_call # Group the command will run as. Normally set via options passed to new attr_accessor :group @@ -272,8 +271,6 @@ module Mixlib when 'user' self.user = setting self.with_logon = setting - when 'remote_call' - self.remote_call = setting when 'group' self.group = setting when 'umask' diff --git a/lib/mixlib/shellout/windows.rb b/lib/mixlib/shellout/windows.rb index 4d9c87cad2..5fe9667e2b 100644 --- a/lib/mixlib/shellout/windows.rb +++ b/lib/mixlib/shellout/windows.rb @@ -23,7 +23,6 @@ require 'windows/handle' require 'windows/process' require 'windows/synchronize' -require 'mixlib/shellout/windows/local_system' require 'mixlib/shellout/windows/core_ext' module Mixlib @@ -70,7 +69,6 @@ module Mixlib create_process_args[:domain] = domain if domain create_process_args[:with_logon] = with_logon if with_logon create_process_args[:password] = password if password - create_process_args[:remote_call] = remote_call if remote_call # # Start the process -- cgit v1.2.1 From 79c85e1ee95171776a79278347e65cae4cb95452 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 15 Jan 2013 09:41:08 -0800 Subject: Add check for service window station and do logonuser if so --- lib/mixlib/shellout/windows/core_ext.rb | 462 ++++++++++++++------------------ 1 file changed, 195 insertions(+), 267 deletions(-) diff --git a/lib/mixlib/shellout/windows/core_ext.rb b/lib/mixlib/shellout/windows/core_ext.rb index ca4a9af464..fe3b04760e 100644 --- a/lib/mixlib/shellout/windows/core_ext.rb +++ b/lib/mixlib/shellout/windows/core_ext.rb @@ -1,7 +1,6 @@ #-- -# Author:: Daniel DeLeo () -# Author:: John Keiser () -# Copyright:: Copyright (c) 2011, 2012 Opscode, Inc. +# Author:: Kevin Moser () +# Copyright:: Copyright (c) 2012, 2013 Nordstrom, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -18,41 +17,65 @@ # require 'win32/process' -require 'windows/handle' -require 'windows/process' -require 'windows/synchronize' -# Override module Windows::Process.CreateProcess to fix bug when -# using both app_name and command_line -# -module Windows - module Process - API.new('CreateProcess', 'SPPPLLLPPP', 'B') - API.new('CreateProcessAsUser', 'PSPPPLLLPPP', 'B', 'advapi32.dll') +# Add new constants for Logon +module Process::Constants + LOGON32_LOGON_INTERACTIVE = 0x00000002 + LOGON32_PROVIDER_DEFAULT = 0x00000000 + UOI_NAME = 0x00000002 +end + +# Define the functions needed to check with Service windows station +module Process::Functions + module FFI::Library + # Wrapper method for attach_function + private + def attach_pfunc(*args) + attach_function(*args) + private args[0] + end end + + extend FFI::Library + + ffi_lib :advapi32 + + attach_pfunc :LogonUserW, + [:buffer_in, :buffer_in, :buffer_in, :ulong, :ulong, :pointer], :bool + + attach_pfunc :CreateProcessAsUserW, + [:ulong, :buffer_in, :buffer_in, :pointer, :pointer, :bool, + :ulong, :buffer_in, :buffer_in, :pointer, :pointer], :bool + + ffi_lib :user32 + + attach_pfunc :GetProcessWindowStation, + [], :ulong + + attach_pfunc :GetUserObjectInformationA, + [:ulong, :uint, :buffer_out, :ulong, :pointer], :bool end -# -# Override Win32::Process.create to take a proper environment hash -# so that variables can contain semicolons -# (submitted patch to owner) -# +# Override Process.create to check for running in the Service window station and doing +# a full logon with LogonUser, instead of a CreateProcessWithLogon module Process + include Process::Constants + include Process::Structs + def create(args) unless args.kind_of?(Hash) - raise TypeError, 'Expecting hash-style keyword arguments' + raise TypeError, 'hash keyword arguments expected' end - valid_keys = %w/ + valid_keys = %w[ app_name command_line inherit creation_flags cwd environment startup_info thread_inherit process_inherit close_handles with_logon - domain password remote_call - / + domain password + ] - valid_si_keys = %/ + 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 = { @@ -61,9 +84,6 @@ module Process 'close_handles' => true } - #See if running as local service - is_local_service = ENV["USERNAME"].downcase == "local service" - # Validate the keys, and convert symbols and case to lowercase strings. args.each{ |key, val| key = key.to_s.downcase @@ -97,47 +117,43 @@ module Process end end - # The environment string should be passed as an array of A=B paths, or - # as a string of ';' separated paths. + env = nil + + # The env string should be passed as a string of ';' separated paths. if hash['environment'] env = hash['environment'] - if !env.respond_to?(:join) - # Backwards compat for ; separated paths + + unless env.respond_to?(:join) env = hash['environment'].split(File::PATH_SEPARATOR) end - # The argument format is a series of null-terminated strings, with an additional null terminator. - # If calling CreateProcessWithLogonW must put the hash in a wide format - env = env.map do |e| - hash['with_logon'].nil? || is_local_service || hash['remote_call'] ? e + "\0" : multi_to_wide(e) - end.join("") + "\0" - env = [env].pack('p*').unpack('L').first - else - env = nil + env = env.map{ |e| e + 0.chr }.join('') + 0.chr + env.to_wide_string! if hash['with_logon'] end - startinfo = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] - startinfo = startinfo.pack('LLLLLLLLLLLLSSLLLL') - procinfo = [0,0,0,0].pack('LLLL') - # Process SECURITY_ATTRIBUTE structure - process_security = 0 + process_security = nil + if hash['process_inherit'] - process_security = [0,0,0].pack('LLL') - process_security[0,4] = [12].pack('L') # sizeof(SECURITY_ATTRIBUTE) - process_security[8,4] = [1].pack('L') # TRUE + process_security = SECURITY_ATTRIBUTES.new + process_security[:nLength] = 12 + process_security[:bInheritHandle] = true end # Thread SECURITY_ATTRIBUTE structure - thread_security = 0 + thread_security = nil + if hash['thread_inherit'] - thread_security = [0,0,0].pack('LLL') - thread_security[0,4] = [12].pack('L') # sizeof(SECURITY_ATTRIBUTE) - thread_security[8,4] = [1].pack('L') # TRUE + thread_security = SECURITY_ATTRIBUTES.new + thread_security[:nLength] = 12 + thread_security[:bInheritHandle] = true end # Automatically handle stdin, stdout and stderr as either IO objects - # or file descriptors. This won't work for StringIO, however. + # 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. + # ['stdin', 'stdout', 'stderr'].each{ |io| if si_hash[io] if si_hash[io].respond_to?(:fileno) @@ -147,7 +163,15 @@ module Process end if handle == INVALID_HANDLE_VALUE - raise Error, get_last_error + 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 @@ -158,7 +182,7 @@ module Process HANDLE_FLAG_INHERIT ) - raise Error, get_last_error unless bool + raise SystemCallError.new("SetHandleInformation", FFI.errno) unless bool si_hash[io] = handle si_hash['startf_flags'] ||= 0 @@ -167,43 +191,85 @@ module Process end } - # The bytes not covered here are reserved (null) + procinfo = PROCESS_INFORMATION.new + startinfo = STARTUPINFO.new + unless si_hash.empty? - startinfo[0,4] = [startinfo.size].pack('L') - startinfo[8,4] = [si_hash['desktop']].pack('p*') if si_hash['desktop'] - startinfo[12,4] = [si_hash['title']].pack('p*') if si_hash['title'] - startinfo[16,4] = [si_hash['x']].pack('L') if si_hash['x'] - startinfo[20,4] = [si_hash['y']].pack('L') if si_hash['y'] - startinfo[24,4] = [si_hash['x_size']].pack('L') if si_hash['x_size'] - startinfo[28,4] = [si_hash['y_size']].pack('L') if si_hash['y_size'] - startinfo[32,4] = [si_hash['x_count_chars']].pack('L') if si_hash['x_count_chars'] - startinfo[36,4] = [si_hash['y_count_chars']].pack('L') if si_hash['y_count_chars'] - startinfo[40,4] = [si_hash['fill_attribute']].pack('L') if si_hash['fill_attribute'] - startinfo[44,4] = [si_hash['startf_flags']].pack('L') if si_hash['startf_flags'] - startinfo[48,2] = [si_hash['sw_flags']].pack('S') if si_hash['sw_flags'] - startinfo[56,4] = [si_hash['stdin']].pack('L') if si_hash['stdin'] - startinfo[60,4] = [si_hash['stdout']].pack('L') if si_hash['stdout'] - startinfo[64,4] = [si_hash['stderr']].pack('L') if si_hash['stderr'] + 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'] || false + if hash['with_logon'] - # Need to do a LogonUser and CreateProcessAsUser to work on all windows platforms - - if is_local_service || hash['remote_call'] - include Process::Constants - extend Process::Functions - - Process.is_local_system? - - logon = hash['with_logon'] - domain = hash['domain'] - app = hash['app_name'] - cmd = hash['command_line'] - cwd = hash['cwd'] - passwd = hash['password'] - token = FFI::MemoryPointer.new(:ulong) - - LogonUser( + 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 + + hash['creation_flags'] |= CREATE_UNICODE_ENVIRONMENT + + 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 = winsta_name.read_string(return_size.read_ulong) + + # If running in the service windows station must do a log on to get + # to the interactive desktop. Running process user account must have + # the 'Replace a process level token' permission + if winsta_name =~ /^Service-0x0-.*$/i + token = FFI::MemoryPointer.new(:ulong) + + bool = LogonUserW( logon, # User domain, # Domain passwd, # Password @@ -212,220 +278,82 @@ module Process token # User token handle ) + unless bool + raise SystemCallError.new("LogonUserW", FFI.errno) + end + token = token.read_ulong - process_ran = CreateProcessAsUser( + bool = CreateProcessAsUserW( token, # User token handle app, # App name cmd, # Command line process_security, # Process attributes thread_security, # Thread attributes - hash['inherit'], # Inherit handles + inherit, # Inherit handles hash['creation_flags'], # Creation Flags env, # Environment cwd, # Working directory startinfo, # Startup Info procinfo # Process Info ) + + unless bool + raise SystemCallError.new("CreateProcessAsUserW (You must hold the 'Replace a process level token' permission)", FFI.errno) + end else - logon = multi_to_wide(hash['with_logon']) - domain = multi_to_wide(hash['domain']) - app = hash['app_name'].nil? ? nil : multi_to_wide(hash['app_name']) - cmd = hash['command_line'].nil? ? nil : multi_to_wide(hash['command_line']) - cwd = multi_to_wide(hash['cwd']) - passwd = multi_to_wide(hash['password']) - hash['creation_flags'] |= CREATE_UNICODE_ENVIRONMENT - - process_ran = CreateProcessWithLogonW( - logon, # User - domain, # Domain - passwd, # Password - LOGON_WITH_PROFILE, # Logon flags - app, # App name - cmd, # Command line - hash['creation_flags'], # Creation flags - env, # Environment - cwd, # Working directory - startinfo, # Startup Info - procinfo # Process Info + bool = CreateProcessWithLogonW( + logon, # User + domain, # Domain + passwd, # Password + LOGON_WITH_PROFILE, # Logon flags + app, # App name + cmd, # Command line + hash['creation_flags'], # Creation flags + env, # Environment + cwd, # Working directory + startinfo, # Startup Info + procinfo # Process Info ) - end + end + + unless bool + raise SystemCallError.new("CreateProcessWithLogonW", FFI.errno) + end else - process_ran = CreateProcess( - hash['app_name'], # App name - hash['command_line'], # Command line + bool = CreateProcessW( + app, # App name + cmd, # Command line process_security, # Process attributes thread_security, # Thread attributes - hash['inherit'], # Inherit handles? + inherit, # Inherit handles? hash['creation_flags'], # Creation flags env, # Environment - hash['cwd'], # Working directory + cwd, # Working directory startinfo, # Startup Info procinfo # Process Info ) - end - # TODO: Close stdin, stdout and stderr handles in the si_hash unless - # they're pointing to one of the standard handles already. [Maybe] - if !process_ran - raise_last_error("CreateProcess()") + unless bool + raise SystemCallError.new("CreateProcessW", FFI.errno) + end end # Automatically close the process and thread handles in the # PROCESS_INFORMATION struct unless explicitly told not to. if hash['close_handles'] - CloseHandle(procinfo[0,4].unpack('L').first) - CloseHandle(procinfo[4,4].unpack('L').first) + CloseHandle(procinfo[:hProcess]) + CloseHandle(procinfo[:hThread]) + CloseHandle(token) end ProcessInfo.new( - procinfo[0,4].unpack('L').first, # hProcess - procinfo[4,4].unpack('L').first, # hThread - procinfo[8,4].unpack('L').first, # hProcessId - procinfo[12,4].unpack('L').first # hThreadId + procinfo[:hProcess], + procinfo[:hThread], + procinfo[:dwProcessId], + procinfo[:dwThreadId] ) end - def self.raise_last_error(operation) - error_string = "#{operation} failed: #{get_last_error}" - last_error_code = GetLastError() - if ERROR_CODE_MAP.has_key?(last_error_code) - raise ERROR_CODE_MAP[last_error_code], error_string - else - raise Error, error_string - end - end - - # List from ruby/win32/win32.c - ERROR_CODE_MAP = { - ERROR_INVALID_FUNCTION => Errno::EINVAL, - ERROR_FILE_NOT_FOUND => Errno::ENOENT, - ERROR_PATH_NOT_FOUND => Errno::ENOENT, - ERROR_TOO_MANY_OPEN_FILES => Errno::EMFILE, - ERROR_ACCESS_DENIED => Errno::EACCES, - ERROR_INVALID_HANDLE => Errno::EBADF, - ERROR_ARENA_TRASHED => Errno::ENOMEM, - ERROR_NOT_ENOUGH_MEMORY => Errno::ENOMEM, - ERROR_INVALID_BLOCK => Errno::ENOMEM, - ERROR_BAD_ENVIRONMENT => Errno::E2BIG, - ERROR_BAD_FORMAT => Errno::ENOEXEC, - ERROR_INVALID_ACCESS => Errno::EINVAL, - ERROR_INVALID_DATA => Errno::EINVAL, - ERROR_INVALID_DRIVE => Errno::ENOENT, - ERROR_CURRENT_DIRECTORY => Errno::EACCES, - ERROR_NOT_SAME_DEVICE => Errno::EXDEV, - ERROR_NO_MORE_FILES => Errno::ENOENT, - ERROR_WRITE_PROTECT => Errno::EROFS, - ERROR_BAD_UNIT => Errno::ENODEV, - ERROR_NOT_READY => Errno::ENXIO, - ERROR_BAD_COMMAND => Errno::EACCES, - ERROR_CRC => Errno::EACCES, - ERROR_BAD_LENGTH => Errno::EACCES, - ERROR_SEEK => Errno::EIO, - ERROR_NOT_DOS_DISK => Errno::EACCES, - ERROR_SECTOR_NOT_FOUND => Errno::EACCES, - ERROR_OUT_OF_PAPER => Errno::EACCES, - ERROR_WRITE_FAULT => Errno::EIO, - ERROR_READ_FAULT => Errno::EIO, - ERROR_GEN_FAILURE => Errno::EACCES, - ERROR_LOCK_VIOLATION => Errno::EACCES, - ERROR_SHARING_VIOLATION => Errno::EACCES, - ERROR_WRONG_DISK => Errno::EACCES, - ERROR_SHARING_BUFFER_EXCEEDED => Errno::EACCES, -# ERROR_BAD_NETPATH => Errno::ENOENT, -# ERROR_NETWORK_ACCESS_DENIED => Errno::EACCES, -# ERROR_BAD_NET_NAME => Errno::ENOENT, - ERROR_FILE_EXISTS => Errno::EEXIST, - ERROR_CANNOT_MAKE => Errno::EACCES, - ERROR_FAIL_I24 => Errno::EACCES, - ERROR_INVALID_PARAMETER => Errno::EINVAL, - ERROR_NO_PROC_SLOTS => Errno::EAGAIN, - ERROR_DRIVE_LOCKED => Errno::EACCES, - ERROR_BROKEN_PIPE => Errno::EPIPE, - ERROR_DISK_FULL => Errno::ENOSPC, - ERROR_INVALID_TARGET_HANDLE => Errno::EBADF, - ERROR_INVALID_HANDLE => Errno::EINVAL, - ERROR_WAIT_NO_CHILDREN => Errno::ECHILD, - ERROR_CHILD_NOT_COMPLETE => Errno::ECHILD, - ERROR_DIRECT_ACCESS_HANDLE => Errno::EBADF, - ERROR_NEGATIVE_SEEK => Errno::EINVAL, - ERROR_SEEK_ON_DEVICE => Errno::EACCES, - ERROR_DIR_NOT_EMPTY => Errno::ENOTEMPTY, -# ERROR_DIRECTORY => Errno::ENOTDIR, - ERROR_NOT_LOCKED => Errno::EACCES, - ERROR_BAD_PATHNAME => Errno::ENOENT, - ERROR_MAX_THRDS_REACHED => Errno::EAGAIN, -# ERROR_LOCK_FAILED => Errno::EACCES, - ERROR_ALREADY_EXISTS => Errno::EEXIST, - ERROR_INVALID_STARTING_CODESEG => Errno::ENOEXEC, - ERROR_INVALID_STACKSEG => Errno::ENOEXEC, - ERROR_INVALID_MODULETYPE => Errno::ENOEXEC, - ERROR_INVALID_EXE_SIGNATURE => Errno::ENOEXEC, - ERROR_EXE_MARKED_INVALID => Errno::ENOEXEC, - ERROR_BAD_EXE_FORMAT => Errno::ENOEXEC, - ERROR_ITERATED_DATA_EXCEEDS_64k => Errno::ENOEXEC, - ERROR_INVALID_MINALLOCSIZE => Errno::ENOEXEC, - ERROR_DYNLINK_FROM_INVALID_RING => Errno::ENOEXEC, - ERROR_IOPL_NOT_ENABLED => Errno::ENOEXEC, - ERROR_INVALID_SEGDPL => Errno::ENOEXEC, - ERROR_AUTODATASEG_EXCEEDS_64k => Errno::ENOEXEC, - ERROR_RING2SEG_MUST_BE_MOVABLE => Errno::ENOEXEC, - ERROR_RELOC_CHAIN_XEEDS_SEGLIM => Errno::ENOEXEC, - ERROR_INFLOOP_IN_RELOC_CHAIN => Errno::ENOEXEC, - ERROR_FILENAME_EXCED_RANGE => Errno::ENOENT, - ERROR_NESTING_NOT_ALLOWED => Errno::EAGAIN, -# ERROR_PIPE_LOCAL => Errno::EPIPE, - ERROR_BAD_PIPE => Errno::EPIPE, - ERROR_PIPE_BUSY => Errno::EAGAIN, - ERROR_NO_DATA => Errno::EPIPE, - ERROR_PIPE_NOT_CONNECTED => Errno::EPIPE, - ERROR_OPERATION_ABORTED => Errno::EINTR, -# ERROR_NOT_ENOUGH_QUOTA => Errno::ENOMEM, - ERROR_MOD_NOT_FOUND => Errno::ENOENT, - WSAEINTR => Errno::EINTR, - WSAEBADF => Errno::EBADF, -# WSAEACCES => Errno::EACCES, - WSAEFAULT => Errno::EFAULT, - WSAEINVAL => Errno::EINVAL, - WSAEMFILE => Errno::EMFILE, - WSAEWOULDBLOCK => Errno::EWOULDBLOCK, - WSAEINPROGRESS => Errno::EINPROGRESS, - WSAEALREADY => Errno::EALREADY, - WSAENOTSOCK => Errno::ENOTSOCK, - WSAEDESTADDRREQ => Errno::EDESTADDRREQ, - WSAEMSGSIZE => Errno::EMSGSIZE, - WSAEPROTOTYPE => Errno::EPROTOTYPE, - WSAENOPROTOOPT => Errno::ENOPROTOOPT, - WSAEPROTONOSUPPORT => Errno::EPROTONOSUPPORT, - WSAESOCKTNOSUPPORT => Errno::ESOCKTNOSUPPORT, - WSAEOPNOTSUPP => Errno::EOPNOTSUPP, - WSAEPFNOSUPPORT => Errno::EPFNOSUPPORT, - WSAEAFNOSUPPORT => Errno::EAFNOSUPPORT, - WSAEADDRINUSE => Errno::EADDRINUSE, - WSAEADDRNOTAVAIL => Errno::EADDRNOTAVAIL, - WSAENETDOWN => Errno::ENETDOWN, - WSAENETUNREACH => Errno::ENETUNREACH, - WSAENETRESET => Errno::ENETRESET, - WSAECONNABORTED => Errno::ECONNABORTED, - WSAECONNRESET => Errno::ECONNRESET, - WSAENOBUFS => Errno::ENOBUFS, - WSAEISCONN => Errno::EISCONN, - WSAENOTCONN => Errno::ENOTCONN, - WSAESHUTDOWN => Errno::ESHUTDOWN, - WSAETOOMANYREFS => Errno::ETOOMANYREFS, -# WSAETIMEDOUT => Errno::ETIMEDOUT, - WSAECONNREFUSED => Errno::ECONNREFUSED, - WSAELOOP => Errno::ELOOP, - WSAENAMETOOLONG => Errno::ENAMETOOLONG, - WSAEHOSTDOWN => Errno::EHOSTDOWN, - WSAEHOSTUNREACH => Errno::EHOSTUNREACH, -# WSAEPROCLIM => Errno::EPROCLIM, -# WSAENOTEMPTY => Errno::ENOTEMPTY, - WSAEUSERS => Errno::EUSERS, - WSAEDQUOT => Errno::EDQUOT, - WSAESTALE => Errno::ESTALE, - WSAEREMOTE => Errno::EREMOTE - } - module_function :create end -- cgit v1.2.1 From 8d4efcd52d7a445769aa7e8b58285ac8fade64ed Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 15 Jan 2013 10:00:08 -0800 Subject: Bump version to 1.2.0 to package gem locally --- lib/mixlib/shellout/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/mixlib/shellout/version.rb b/lib/mixlib/shellout/version.rb index e61dbb6ec3..b8086c7c15 100644 --- a/lib/mixlib/shellout/version.rb +++ b/lib/mixlib/shellout/version.rb @@ -1,5 +1,5 @@ module Mixlib class ShellOut - VERSION = "1.1.0" + VERSION = "1.2.0" end end -- cgit v1.2.1 From 9cc97c6708b26642a82e7b39c29027ae9f3c9814 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 15 Jan 2013 10:04:04 -0800 Subject: Revert "Bump version to 1.2.0 to package gem locally" This reverts commit 8d4efcd52d7a445769aa7e8b58285ac8fade64ed. --- lib/mixlib/shellout/version.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/mixlib/shellout/version.rb b/lib/mixlib/shellout/version.rb index b8086c7c15..e61dbb6ec3 100644 --- a/lib/mixlib/shellout/version.rb +++ b/lib/mixlib/shellout/version.rb @@ -1,5 +1,5 @@ module Mixlib class ShellOut - VERSION = "1.2.0" + VERSION = "1.1.0" end end -- cgit v1.2.1 From 491c3e703a4241ceb7fb6aba19a95a201606dcf0 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 15 Jan 2013 10:07:58 -0800 Subject: Fix comments --- lib/mixlib/shellout/windows/core_ext.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/mixlib/shellout/windows/core_ext.rb b/lib/mixlib/shellout/windows/core_ext.rb index fe3b04760e..7062ef73d1 100644 --- a/lib/mixlib/shellout/windows/core_ext.rb +++ b/lib/mixlib/shellout/windows/core_ext.rb @@ -1,6 +1,7 @@ #-- -# Author:: Kevin Moser () -# Copyright:: Copyright (c) 2012, 2013 Nordstrom, Inc. +# Author:: Daniel DeLeo () +# Author:: John Keiser () +# Copyright:: Copyright (c) 2011, 2012 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); -- cgit v1.2.1 From aba52fe10c2ba175bde4ae8d514ab055869d1a55 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 15 Jan 2013 11:25:51 -0800 Subject: Add development dependency for ap --- mixlib-shellout.gemspec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mixlib-shellout.gemspec b/mixlib-shellout.gemspec index c81c3e8f0d..4c59291bf0 100644 --- a/mixlib-shellout.gemspec +++ b/mixlib-shellout.gemspec @@ -14,7 +14,7 @@ Gem::Specification.new do |s| s.homepage = "http://wiki.opscode.com/" - %w(rspec).each { |gem| s.add_development_dependency gem } + %w(rspec ap).each { |gem| s.add_development_dependency gem } s.bindir = "bin" s.executables = [] -- cgit v1.2.1 From 6fd71d85c67f5a8ee5722ee2d8ec83babfd1fb08 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 15 Jan 2013 11:40:25 -0800 Subject: Add default value check for with_logon, domain, & user --- spec/mixlib/shellout_spec.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/spec/mixlib/shellout_spec.rb b/spec/mixlib/shellout_spec.rb index cc59829464..16bef29232 100644 --- a/spec/mixlib/shellout_spec.rb +++ b/spec/mixlib/shellout_spec.rb @@ -31,6 +31,9 @@ describe Mixlib::ShellOut do context 'with default settings' do its(:cwd) { should be_nil } its(:user) { should be_nil } + its(:with_logon) { should be_nil } + its(:domain) { should be_nil } + its(:password) { should be_nil } its(:group) { should be_nil } its(:umask) { should be_nil } its(:timeout) { should eql(600) } -- cgit v1.2.1 From ea9c00c93268e840c3bed0c05db9c2827ece4e90 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 22 Jan 2013 10:25:14 -0800 Subject: Add tests for running as different user in windows --- spec/mixlib/shellout/windows_spec.rb | 2 +- spec/mixlib/shellout_spec.rb | 71 +++++++++++++++++++++++++++++++++++- 2 files changed, 70 insertions(+), 3 deletions(-) diff --git a/spec/mixlib/shellout/windows_spec.rb b/spec/mixlib/shellout/windows_spec.rb index be515be783..4d9359f046 100644 --- a/spec/mixlib/shellout/windows_spec.rb +++ b/spec/mixlib/shellout/windows_spec.rb @@ -1,7 +1,7 @@ require 'spec_helper' describe 'Mixlib::ShellOut::Windows', :windows_only do - + describe 'Utils' do describe '.should_run_under_cmd?' do subject { Mixlib::ShellOut::Windows::Utils.should_run_under_cmd?(command) } diff --git a/spec/mixlib/shellout_spec.rb b/spec/mixlib/shellout_spec.rb index 16bef29232..c44a9c31ac 100644 --- a/spec/mixlib/shellout_spec.rb +++ b/spec/mixlib/shellout_spec.rb @@ -79,7 +79,33 @@ describe Mixlib::ShellOut do shell_cmd.uid.should eql(expected_uid) end end + end + + context 'when setting with_logon' do + let(:accessor) { :with_logon } + let(:value) { 'root' } + + it "should set the with_logon" do + should eql(value) + end + end + context 'when setting domain' do + let(:accessor) { :domain } + let(:value) { 'localhost' } + + it "should set the domain" do + should eql(value) + end + end + + context 'when setting password' do + let(:accessor) { :password } + let(:value) { 'vagrant' } + + it "should set the password" do + should eql(value) + end end context 'when setting group' do @@ -177,12 +203,15 @@ describe Mixlib::ShellOut do context "with options hash" do let(:cmd) { 'brew install couchdb' } - let(:options) { { :cwd => cwd, :user => user, :group => group, :umask => umask, - :timeout => timeout, :environment => environment, :returns => valid_exit_codes, + let(:options) { { :cwd => cwd, :user => user, :domain => domain, :password => password, :group => group, + :umask => umask, :timeout => timeout, :environment => environment, :returns => valid_exit_codes, :live_stream => stream, :input => input } } let(:cwd) { '/tmp' } let(:user) { 'toor' } + let(:with_logon) { user } + let(:domain) { 'localhost' } + let(:password) { 'vagrant' } let(:group) { 'wheel' } let(:umask) { '2222' } let(:timeout) { 5 } @@ -199,6 +228,18 @@ describe Mixlib::ShellOut do shell_cmd.user.should eql(user) end + it "should set the with_logon" do + shell_cmd.with_logon.should eql(with_logon) + end + + it "should set the domain" do + shell_cmd.domain.should eql(domain) + end + + it "should set the password" do + shell_cmd.password.should eql(password) + end + it "should set the group" do shell_cmd.group.should eql(group) end @@ -361,6 +402,32 @@ describe Mixlib::ShellOut do end end + context "when running under Windows", :windows_only do + let(:cmd) { 'whoami.exe' } + let(:running_user) { shell_cmd.run_command.stdout.strip.downcase } + + context "when no user is set" do + # Need to adjust the username and domain if running as local system + # to match how whoami returns the information + local_system = (ENV['USERNAME'].downcase == "x3v7-vagrant$") + let(:domain) { local_system ? 'nt authority' : ENV['COMPUTERNAME'].downcase } + let(:user) { local_system ? 'system' : ENV['USERNAME'].downcase } + it "should run as current user" do + running_user.should eql("#{domain}\\#{user}") + end + end + + context "when user is set to Administrator" do + let(:user) { 'administrator' } + let(:domain) { ENV['COMPUTERNAME'].downcase } + let(:options) { { :domain => domain, :user => user, :password => 'vagrant' } } + + it "should run as Administrator" do + running_user.should eql("#{domain}\\#{user}") + end + end + end + context "with a live stream" do let(:stream) { StringIO.new } let(:ruby_code) { 'puts "hello"' } -- cgit v1.2.1 From 89bdd5f6fd57c3bd6bd7d89b19f5add9e35d0bde Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Tue, 22 Jan 2013 11:47:18 -0800 Subject: Update check for local system use a downcased computer name --- spec/mixlib/shellout_spec.rb | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/spec/mixlib/shellout_spec.rb b/spec/mixlib/shellout_spec.rb index c44a9c31ac..14af6e25d8 100644 --- a/spec/mixlib/shellout_spec.rb +++ b/spec/mixlib/shellout_spec.rb @@ -409,7 +409,8 @@ describe Mixlib::ShellOut do context "when no user is set" do # Need to adjust the username and domain if running as local system # to match how whoami returns the information - local_system = (ENV['USERNAME'].downcase == "x3v7-vagrant$") + + let(:local_system) { (ENV['USERNAME'].downcase == "#{ENV['COMPUTERNAME'].downcase}$") } let(:domain) { local_system ? 'nt authority' : ENV['COMPUTERNAME'].downcase } let(:user) { local_system ? 'system' : ENV['USERNAME'].downcase } it "should run as current user" do -- cgit v1.2.1 From 42592d8c0dcddf82db28dbb74ef648ba91ea2b01 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Fri, 22 Feb 2013 15:11:05 -0800 Subject: Update README.md with windows impersonation example --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 93baa671ca..1f0e46f022 100644 --- a/README.md +++ b/README.md @@ -36,6 +36,12 @@ Invoke crontab to edit user cron: crontab = Mixlib::ShellOut.new("crontab -l -u #{@new_resource.user}", :input => crontab_lines.join("\n")) crontab.run_command +## Windows Impersonation Example +Invoke crontab to edit user cron: + + whomai = Mixlib::ShellOut.new("whoami.exe", :user => "username", :domain => "DOMAIN", :password => "password") + whoami.run_command + ## Platform Support Mixlib::ShellOut does a standard fork/exec on Unix, and uses the Win32 API on Windows. There is not currently support for JRuby. -- cgit v1.2.1 From c98695c6abf3384ae823a991d991151d92d5720f Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Fri, 22 Feb 2013 15:15:08 -0800 Subject: Update comments for why to use LogonUser and CreateProcessAsUser in some cases --- lib/mixlib/shellout/windows/core_ext.rb | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/mixlib/shellout/windows/core_ext.rb b/lib/mixlib/shellout/windows/core_ext.rb index 7062ef73d1..e692c7dfb2 100644 --- a/lib/mixlib/shellout/windows/core_ext.rb +++ b/lib/mixlib/shellout/windows/core_ext.rb @@ -266,7 +266,10 @@ module Process # If running in the service windows station must do a log on to get # to the interactive desktop. Running process user account must have - # the 'Replace a process level token' permission + # 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 cann with the LOGON32_LOGON_INTERACTIVE flag. if winsta_name =~ /^Service-0x0-.*$/i token = FFI::MemoryPointer.new(:ulong) -- cgit v1.2.1 From 9ba15865d7080e423ece5f418c37f512c1118727 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Wed, 13 Mar 2013 12:47:19 -0700 Subject: Add option validation --- lib/mixlib/shellout.rb | 6 +++++- lib/mixlib/shellout/unix.rb | 5 +++++ lib/mixlib/shellout/windows.rb | 9 +++++++++ 3 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/mixlib/shellout.rb b/lib/mixlib/shellout.rb index 5b50a14b6c..63744f1d3d 100644 --- a/lib/mixlib/shellout.rb +++ b/lib/mixlib/shellout.rb @@ -296,8 +296,12 @@ module Mixlib raise InvalidCommandOption, "option '#{option.inspect}' is not a valid option for #{self.class.name}" end end - end + validate_options(opts) + end + def validate_options(opts) + super + end end end diff --git a/lib/mixlib/shellout/unix.rb b/lib/mixlib/shellout/unix.rb index a983e05acd..776169d33f 100644 --- a/lib/mixlib/shellout/unix.rb +++ b/lib/mixlib/shellout/unix.rb @@ -20,6 +20,11 @@ module Mixlib class ShellOut module Unix + # Option validation that is unix specific + def validate_options(opts) + # No options to validate, raise exceptions here if needed + end + # Run the command, writing the command's standard out and standard error # to +stdout+ and +stderr+, and saving its exit status object to +status+ # === Returns diff --git a/lib/mixlib/shellout/windows.rb b/lib/mixlib/shellout/windows.rb index 5fe9667e2b..3251f66602 100644 --- a/lib/mixlib/shellout/windows.rb +++ b/lib/mixlib/shellout/windows.rb @@ -35,6 +35,15 @@ module Mixlib TIME_SLICE = 0.05 + # Option validation that is windows specific + def validate_options(opts) + if opts["user"] + unless opts["password"] && opts["domain"] + raise InvalidCommandOption, "You must supply both a username and password when supplying a user in windows" + end + end + end + #-- # Missing lots of features from the UNIX version, such as # uid, etc. -- cgit v1.2.1 From 85e5bc5f55363e488d20d43d7cff3e519c52c6d2 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Wed, 13 Mar 2013 12:55:43 -0700 Subject: Update hash reference to symbols --- lib/mixlib/shellout/windows.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/mixlib/shellout/windows.rb b/lib/mixlib/shellout/windows.rb index 3251f66602..a513186c72 100644 --- a/lib/mixlib/shellout/windows.rb +++ b/lib/mixlib/shellout/windows.rb @@ -37,8 +37,8 @@ module Mixlib # Option validation that is windows specific def validate_options(opts) - if opts["user"] - unless opts["password"] && opts["domain"] + if opts[:user] + unless opts[:password] && opts[:domain] raise InvalidCommandOption, "You must supply both a username and password when supplying a user in windows" end end -- cgit v1.2.1 From 52a51724a488cba92804a0c180d2c9d61358a882 Mon Sep 17 00:00:00 2001 From: "Moser, Kevin" Date: Wed, 13 Mar 2013 13:40:55 -0700 Subject: Set domain to . if no domain is passed --- lib/mixlib/shellout/windows.rb | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/mixlib/shellout/windows.rb b/lib/mixlib/shellout/windows.rb index a513186c72..ea809b58d7 100644 --- a/lib/mixlib/shellout/windows.rb +++ b/lib/mixlib/shellout/windows.rb @@ -38,7 +38,7 @@ module Mixlib # Option validation that is windows specific def validate_options(opts) if opts[:user] - unless opts[:password] && opts[:domain] + unless opts[:password] raise InvalidCommandOption, "You must supply both a username and password when supplying a user in windows" end end @@ -75,7 +75,8 @@ module Mixlib :close_handles => false } create_process_args[:cwd] = cwd if cwd - create_process_args[:domain] = domain if domain + # default to local account database if domain is not specified + create_process_args[:domain] = domain.nil? ? "." : domain create_process_args[:with_logon] = with_logon if with_logon create_process_args[:password] = password if password -- cgit v1.2.1