Module: User

Extended by:
User
Included in:
User
Defined in:
lib/nub/user.rb

Overview

Some user related helper methods

Instance Method Summary collapse

Instance Method Details

#drop_privilegesObject

Drop root privileges to original user

Parameters:

  • optional (Proc)

    block to execut in context of user



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
# File 'lib/nub/user.rb', line 53

def drop_privileges
  result = nil
  uid = gid = nil

  # Drop privileges
  if Process.uid.zero?
    uid, gid = Process.uid, Process.gid
    user_uid = ENV['SUDO_UID'].to_i
    user_gid = ENV['SUDO_GID'].to_i
    Process::GID.grant_privilege(user_gid)
    Process::UID.grant_privilege(user_uid)
  end

  # Execute block if given
  begin
    result = Proc.new.call
    self.raise_privileges(uid, gid)
  rescue ArgumentError
    # No block given just return ids
    result = [uid, gid]
  rescue
    self.raise_privileges(uid, gid)
  end

  return result
end

#drop_privileges!Object

Correctly and permanently drops privileges timetobleed.com/5-things-you-dont-know-about-user-ids-that-will-destroy-you/ requires you drop the group before the user and use a safe solution



42
43
44
45
46
47
48
# File 'lib/nub/user.rb', line 42

def drop_privileges!
  if Process.uid.zero?
    nobody = Etc.getpwnam('nobody')
    Process::Sys.setresgid(nobody.gid, nobody.gid, nobody.gid)
    Process::Sys.setresuid(nobody.uid, nobody.uid, nobody.uid)
  end
end

#nameObject

Get the real user taking into account sudo priviledges



35
36
37
# File 'lib/nub/user.rb', line 35

def name
  return Process.uid.zero? ? Etc.getpwuid(ENV['SUDO_UID'].to_i).name : ENV['USER']
end

#raise_privileges(uid, gid) ⇒ Object

Raise privileges if dropped earlier

Parameters:

  • uid (String)

    uid of user to assume

  • gid (String)

    gid of user to assume



83
84
85
86
87
88
# File 'lib/nub/user.rb', line 83

def raise_privileges(uid, gid)
  if uid and gid
    Process::UID.grant_privilege(uid)
    Process::GID.grant_privilege(gid)
  end
end

#root?Boolean

Check if the current user has root privileges

Returns:

  • (Boolean)


30
31
32
# File 'lib/nub/user.rb', line 30

def root?
  return Process.uid.zero?
end