Module: OsCtld::SwitchUser

Extended by:
OsCtl::Lib::Utils::System
Includes:
OsCtl::Lib::Utils::Log
Defined in:
lib/osctld/switch_user.rb

Constant Summary collapse

SYSTEM_PATH =
%w[
  /bin
  /usr/bin
  /sbin
  /usr/sbin
  /run/current-system/sw/bin
  /nix/var/nix/profiles/system/sw/bin
  /run/current-system/profile/bin
  /run/current-system/profile/sbin
  /var/guix/profiles/system/profile/bin
  /var/guix/profiles/system/profile/sbin
].freeze

Class Method Summary collapse

Class Method Details

.apply_prlimits(pid, prlimits) ⇒ Object

Apply process resource limits

Parameters:

  • pid (Integer)
  • prlimits (Hash)


155
156
157
158
159
160
161
162
163
164
# File 'lib/osctld/switch_user.rb', line 155

def self.apply_prlimits(pid, prlimits)
  prlimits.each do |name, limit|
    PrLimits.set(
      pid,
      PrLimits.resource_to_const(name),
      limit[:soft] == 'unlimited' ? PrLimits::INFINITY : limit[:soft],
      limit[:hard] == 'unlimited' ? PrLimits::INFINITY : limit[:hard]
    )
  end
end

.clear_ruby_envObject

Remove Ruby-related environment variables



199
200
201
202
203
# File 'lib/osctld/switch_user.rb', line 199

def self.clear_ruby_env
  ENV.delete_if do |k, _v|
    k.start_with?('RUBY') || k.start_with?('BUNDLE') || k.start_with?('GEM')
  end
end

.close_fds(except: []) ⇒ Object

Close open file descriptors

Parameters:

  • except (Array<IO, Integer>) (defaults to: [])


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/osctld/switch_user.rb', line 168

def self.close_fds(except: [])
  except_filenos = except.map do |v|
    if v.is_a?(::IO)
      v.fileno
    else
      v
    end
  end

  walk_fds do |fd|
    next if except_filenos.include?(fd)

    begin
      IO.new(fd).close
    rescue ArgumentError, Errno::EBADF
      # ignore
    end
  end
end

.fork(**opts, &block) ⇒ Object

Fork into a new process

Parameters:

  • opts (Hash)

Options Hash (**opts):

  • :keep_fds (Array<IO, Integer>)
  • :keep_stdfds (Boolean) — default: true


26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/osctld/switch_user.rb', line 26

def self.fork(**opts, &block)
  keep_fds = (opts[:keep_fds] || []).clone

  if opts.fetch(:keep_stdfds, true)
    keep_fds << 0 << 1 << 2
  end

  Process.fork do
    close_fds(except: keep_fds)
    block.call
  end
end

.fork_and_switch_to(sysuser, ugid, homedir, cgroup_path, **opts, &block) ⇒ Object

Fork a process running as unprivileged user

Parameters:

  • sysuser (String)
  • ugid (Integer)
  • homedir (String)
  • cgroup_path (String)
  • opts (Hash)

    options

Options Hash (**opts):

  • :chown_cgroups (Boolean) — default: true
  • :prlimits (Hash)
  • :oom_score_adj (Integer, nil)
  • :keep_fds (Array<IO, Integer>)
  • :keep_stdfds (Boolean) — default: true
  • :syslogns_tag (String, nil) — default: nil
  • :syslogns_pid (Integer, nil) — default: nil


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
# File 'lib/osctld/switch_user.rb', line 52

def self.fork_and_switch_to(sysuser, ugid, homedir, cgroup_path, **opts, &block)
  chown_cgroups = opts.has_key?(:chown_cgroups) ? opts[:chown_cgroups] : true

  r, w = IO.pipe

  keep_fds = (opts[:keep_fds] || []).clone
  keep_fds << r

  CGroup.mkpath_all(cgroup_path.split('/'), chown: chown_cgroups ? ugid : false)

  pid = self.fork(
    keep_fds:,
    keep_stdfds: opts.fetch(:keep_stdfds, true)
  ) do
    # Closed by self.fork
    # w.close

    if opts[:oom_score_adj]
      File.write('/proc/self/oom_score_adj', opts[:oom_score_adj].to_s)
    end

    switch_to(
      sysuser,
      ugid,
      homedir,
      cgroup_path,
      syslogns_tag: opts.fetch(:syslogns_tag, nil),
      syslogns_pid: opts.fetch(:syslogns_pid, nil)
    )

    msg = r.readline.strip
    r.close

    if msg == 'ready'
      block.call
    else
      exit(false)
    end
  end

  r.close

  apply_prlimits(pid, opts[:prlimits]) if opts[:prlimits]

  w.puts('ready')
  w.close
  pid
end

.switch_to(sysuser, ugid, homedir, cgroup_path, syslogns_tag: nil, syslogns_pid: nil) ⇒ Object

Switch the current process to an unprivileged user



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
# File 'lib/osctld/switch_user.rb', line 102

def self.switch_to(sysuser, ugid, homedir, cgroup_path, syslogns_tag: nil, syslogns_pid: nil)
  if syslogns_tag && syslogns_pid
    raise ArgumentError, 'provide either syslogns_tag or syslogns_pid, not both'
  end

  # Environment
  ENV.delete('XDG_SESSION_ID')

  # LXC places lock files here
  ENV['XDG_RUNTIME_DIR'] = File.join(homedir, '.cache/lxc/run')

  ENV['HOME'] = homedir
  ENV['USER'] = sysuser

  # CGroups
  CGroup.attach_to_all(cgroup_path.split('/'))

  # syslog namespace
  if syslogns_tag
    OsCtl::Lib::Sys.new.create_syslogns(syslogns_tag)
  elsif syslogns_pid
    OsCtl::Lib::Sys.new.attach_syslogns(syslogns_pid)
  end

  # Switch
  Process.groups = [ugid]
  sys = OsCtl::Lib::Sys.new
  sys.setresgid(ugid, ugid, ugid)
  sys.setresuid(ugid, ugid, ugid)
end

.switch_to_system(sysuser, uid, gid, homedir) ⇒ Object

Switch the current process to an unprivileged users, but do not change cgroups.



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/osctld/switch_user.rb', line 135

def self.switch_to_system(sysuser, uid, gid, homedir)
  # Environment
  ENV.delete('XDG_SESSION_ID')

  # LXC places lock files here
  ENV['XDG_RUNTIME_DIR'] = File.join(homedir, '.cache/lxc/run')

  ENV['HOME'] = homedir
  ENV['USER'] = sysuser

  # Switch
  Process.groups = [gid]
  sys = OsCtl::Lib::Sys.new
  sys.setresgid(gid, gid, gid)
  sys.setresuid(uid, uid, uid)
end

.walk_fds {|fd| ... } ⇒ Object

Yield all open file descriptors

Yield Parameters:

  • fd (Integer)


190
191
192
193
194
195
196
# File 'lib/osctld/switch_user.rb', line 190

def self.walk_fds
  Dir.entries('/proc/self/fd').each do |v|
    next if %w[. ..].include?(v)

    yield(v.to_i)
  end
end