2 # Copyright (C) The Arvados Authors. All rights reserved.
4 # SPDX-License-Identifier: AGPL-3.0
14 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
17 abort "Fatal: These environment vars must be set: #{req_envs}"
22 OptionParser.new do |parser|
23 parser.on('--exclusive', 'Manage SSH keys file exclusively.')
24 parser.on('--rotate-tokens', 'Always create new user tokens. Usually needed with --token-lifetime.')
25 parser.on('--skip-missing-users', "Don't try to create any local accounts.")
26 parser.on('--token-lifetime SECONDS', 'Create user tokens that expire after SECONDS.', Integer)
27 end.parse!(into: options)
29 exclusive_banner = "#######################################################################################
30 # THIS FILE IS MANAGED BY #{$0} -- CHANGES WILL BE OVERWRITTEN #
31 #######################################################################################\n\n"
32 start_banner = "### BEGIN Arvados-managed keys -- changes between markers will be overwritten\n"
33 end_banner = "### END Arvados-managed keys -- changes between markers will be overwritten\n"
38 arv = Arvados.new({ :suppress_ssl_warnings => false })
39 logincluster_arv = Arvados.new({ :api_host => (ENV['LOGINCLUSTER_ARVADOS_API_HOST'] || ENV['ARVADOS_API_HOST']),
40 :api_token => (ENV['LOGINCLUSTER_ARVADOS_API_TOKEN'] || ENV['ARVADOS_API_TOKEN']),
41 :suppress_ssl_warnings => false })
43 vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
45 logins = arv.virtual_machine.logins(:uuid => vm_uuid)[:items]
46 logins = [] if logins.nil?
47 logins = logins.reject { |l| l[:username].nil? or l[:hostname].nil? or l[:virtual_machine_uuid] != vm_uuid }
51 open("/etc/login.defs", encoding: "utf-8") do |login_defs|
52 login_defs.each_line do |line|
53 next unless match = /^UID_MIN\s+(\S+)$/.match(line)
54 if match[1].start_with?("0x")
56 elsif match[1].start_with?("0")
61 new_uid_min = match[1].to_i(base)
62 uid_min = new_uid_min if (new_uid_min > 0)
68 if not pwnam[l[:username]]
70 pwnam[l[:username]] = Etc.getpwnam(l[:username])
72 if options[:"skip-missing-users"]
73 STDERR.puts "Account #{l[:username]} not found. Skipping"
77 if pwnam[l[:username]].uid < uid_min
78 STDERR.puts "Account #{l[:username]} uid #{pwnam[l[:username]].uid} < uid_min #{uid_min}. Skipping"
88 keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
91 # Handle putty-style ssh public keys
92 key.sub!(/^(Comment: "r[^\n]*\n)(.*)$/m,'ssh-rsa \2 \1')
93 key.sub!(/^(Comment: "d[^\n]*\n)(.*)$/m,'ssh-dss \2 \1')
97 keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
103 current_user_groups = Hash.new
104 while (ent = Etc.getgrent()) do
105 ent.mem.each do |member|
106 current_user_groups[member] ||= Array.new
107 current_user_groups[member].push ent.name
113 next if seen[l[:username]]
114 seen[l[:username]] = true
116 username = l[:username]
118 unless pwnam[l[:username]]
119 STDERR.puts "Creating account #{l[:username]}"
121 unless system("useradd", "-m",
125 STDERR.puts "Account creation failed for #{l[:username]}: #{$?}"
129 pwnam[username] = Etc.getpwnam(username)
131 STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
136 existing_groups = current_user_groups[username] || []
137 groups = l[:groups] || []
138 # Adding users to the FUSE group has long been hardcoded behavior.
141 groups.select! { |g| Etc.getgrnam(g) rescue false }
143 groups.each do |addgroup|
144 if existing_groups.index(addgroup).nil?
145 # User should be in group, but isn't, so add them.
146 STDERR.puts "Add user #{username} to #{addgroup} group"
147 system("usermod", "-aG", addgroup, username)
151 existing_groups.each do |removegroup|
152 if groups.index(removegroup).nil?
153 # User is in a group, but shouldn't be, so remove them.
154 STDERR.puts "Remove user #{username} from #{removegroup} group"
155 system("gpasswd", "-d", username, removegroup)
159 homedir = pwnam[l[:username]].dir
160 userdotssh = File.join(homedir, ".ssh")
161 Dir.mkdir(userdotssh) if !File.exist?(userdotssh)
163 newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
165 keysfile = File.join(userdotssh, "authorized_keys")
167 if File.exist?(keysfile)
168 oldkeys = IO::read(keysfile)
173 if options[:exclusive]
174 newkeys = exclusive_banner + newkeys
175 elsif oldkeys.start_with?(exclusive_banner)
176 newkeys = start_banner + newkeys + end_banner
177 elsif (m = /^(.*?\n|)#{start_banner}(.*?\n|)#{end_banner}(.*)/m.match(oldkeys))
178 newkeys = m[1] + start_banner + newkeys + end_banner + m[3]
180 newkeys = start_banner + newkeys + end_banner + oldkeys
183 if oldkeys != newkeys then
184 f = File.new(keysfile, 'w')
189 userdotconfig = File.join(homedir, ".config")
190 if !File.exist?(userdotconfig)
191 Dir.mkdir(userdotconfig)
194 configarvados = File.join(userdotconfig, "arvados")
195 Dir.mkdir(configarvados) if !File.exist?(configarvados)
197 tokenfile = File.join(configarvados, "settings.conf")
200 if !File.exist?(tokenfile) || options[:"rotate-tokens"]
201 aca_params = {owner_uuid: l[:user_uuid], api_client_id: 0}
202 if options[:"token-lifetime"] && options[:"token-lifetime"] > 0
203 aca_params.merge!(expires_at: (Time.now + options[:"token-lifetime"]))
205 user_token = logincluster_arv.api_client_authorization.create(api_client_authorization: aca_params)
206 f = File.new(tokenfile, 'w')
207 f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
208 f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
212 STDERR.puts "Error setting token for #{l[:username]}: #{e}"
215 FileUtils.chown_R(l[:username], nil, userdotssh)
216 FileUtils.chown_R(l[:username], nil, userdotconfig)
217 File.chmod(0700, userdotssh)
218 File.chmod(0700, userdotconfig)
219 File.chmod(0700, configarvados)
220 File.chmod(0750, homedir)
221 File.chmod(0600, keysfile)
222 if File.exist?(tokenfile)
223 File.chmod(0600, tokenfile)
227 rescue Exception => bang
228 puts "Error: " + bang.to_s
229 puts bang.backtrace.join("\n")