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)


192
193
194
195
196
197
198
199
200
201
# File 'lib/osctld/switch_user.rb', line 192

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_env ⇒ Object

Remove Ruby-related environment variables



272
273
274
275
276
# File 'lib/osctld/switch_user.rb', line 272

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: [])


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

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

  # A second IO wrapper can close the descriptor without invalidating its
  # original Ruby owner. Later GC could then close a worker's reused fd.
  # Retain and disarm the old owners until their streams are closed below.
  inherited_ios = ObjectSpace.each_object(IO).to_a.filter_map do |io|
    next if io.closed? || except_filenos.include?(io.fileno)

    io.autoclose = false
    if io.stat.pipe?
      begin
        # Detach a duplex pipe's read side while its fd is still valid.
        # Never do this to sockets: shutdown would affect the parent.
        io.close_read
      rescue IOError, Errno::ECHILD
        # Write-only streams, or popen processes owned by the parent.
      end
      next if io.closed? || except_filenos.include?(io.fileno)

      io.autoclose = false
    end
    io
  rescue IOError
    # An allocated but uninitialized IO has no descriptor to discard.
    nil
  rescue Errno::EBADF
    # An already-invalid owner still needs its Ruby stream closed below.
    io
  end

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

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

  # Close the Ruby streams only after the raw descriptors are gone, so
  # inherited write buffers cannot be flushed into the parent's pipes.
  inherited_ios.each do |io|
    io.close
  rescue IOError, Errno::EBADF, Errno::ECHILD
    # Buffered flushes see closed fds; popen children belong to the parent.
  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


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

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


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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
# 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
  pipes = []
  pid = nil
  handed_off = false

  r, w = IO.pipe
  pipes.push(r, w)
  prepared_r, prepared_w = IO.pipe
  pipes.push(prepared_r, prepared_w)

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

  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)
    )

    # Lowering NOFILE before inherited FDs are closed can prevent even
    # opening /proc/self/fd. Acknowledge preparation before applying limits.
    prepared_w.puts('prepared')
    prepared_w.close

    msg = r.readline.strip
    r.close

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

  r.close
  prepared_w.close

  if prepared_r.readline != "prepared\n"
    raise 'invalid child preparation acknowledgement'
  end

  prepared_r.close

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

  w.puts('ready')
  w.close
  handed_off = true
  pid
ensure
  pipes&.each do |pipe|
    pipe.close unless pipe.closed?
  rescue IOError, SystemCallError
    # Close the remaining ends without hiding the original setup failure.
  end

  reap_failed_fork(pid) if pid && !handed_off
end

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

Switch the current process to an unprivileged user



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

def self.switch_to(sysuser, ugid, homedir, cgroup_path, syslogns_tag: nil)
  # 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('/'))

  sys = OsCtl::Lib::Sys.new

  # syslog namespace
  if syslogns_tag
    create_syslogns(sys, syslogns_tag)
  end

  # Switch
  Process.groups = [ugid]
  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.



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

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)


263
264
265
266
267
268
269
# File 'lib/osctld/switch_user.rb', line 263

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

    yield(v.to_i)
  end
end