summaryrefslogtreecommitdiffstats
path: root/lib/puppet/util/suidmanager.rb
blob: 3108fdf5f72ae6e357bc7323455d0de6f58d9513 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
require 'facter'
require 'puppet/util/warnings'
require 'forwardable'

module Puppet::Util::SUIDManager
    include Puppet::Util::Warnings
    extend Forwardable

    to_delegate_to_process = [ :euid=, :euid, :egid=, :egid,
                               :uid=, :uid, :gid=, :gid ]

    to_delegate_to_process.each do |method|
        def_delegator Process, method
        module_function method
    end

    if Facter['kernel'].value == 'Darwin'
        # Cannot change real UID on Darwin so we set euid
        alias :uid :euid
        alias :gid :egid
    end

    # Runs block setting uid and gid if provided then restoring original ids
    def asuser new_uid=nil, new_gid=nil
      # We set both because some programs like to drop privs, i.e. bash.
      old_uid, old_gid = self.uid, self.gid
      old_euid, old_egid = self.euid, self.egid
      begin
          self.uid = convert_xid :uid, new_uid if new_uid
          self.gid = convert_xid :gid, new_gid if new_gid
          self.euid = convert_xid :uid, new_uid if new_uid
          self.egid = convert_xid :gid, new_gid if new_gid

          yield
      ensure
          self.uid, self.gid = old_uid, old_gid
          self.euid, self.egid = old_euid, old_egid
      end
    end
    module_function :asuser
    
    # Make sure the passed argument is a number.
    def convert_xid(type, id)
        map = {:gid => :group, :uid => :user}
        raise ArgumentError, "Invalid id type %s" % type unless map.include?(type)
        ret = Puppet::Util.send(type, id)
        if ret == nil
          raise Puppet::Error, "Invalid %s: %s" % [map[type], id]
        end
        return ret
    end
    module_function :convert_xid


    def run_and_capture(command, new_uid=nil, new_gid=nil)
        output = Puppet::Util.execute(command, :failonfail => false, :uid => new_uid, :gid => new_gid)
        [output, $?.dup]
    end
    module_function :run_and_capture

    def system(command, new_uid=nil, new_gid=nil)
        status = nil
        asuser(new_uid, new_gid) do
            Kernel.system(command)
            status = $?.dup
        end
        status
    end
    module_function :system
end