20663: Improve permissions and ownership handling
[arvados.git] / services / login-sync / bin / arvados-login-sync
1 #!/usr/bin/env ruby
2 # Copyright (C) The Arvados Authors. All rights reserved.
3 #
4 # SPDX-License-Identifier: AGPL-3.0
5
6 require 'rubygems'
7 require 'pp'
8 require 'arvados'
9 require 'etc'
10 require 'fileutils'
11 require 'yaml'
12 require 'optparse'
13 require 'open3'
14
15 def ensure_dir(path, mode, owner, group)
16   begin
17     Dir.mkdir(path, mode)
18   rescue Errno::EEXIST
19     # No change needed
20     false
21   else
22     FileUtils.chown(owner, group, path)
23     true
24   end
25 end
26
27 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
28 req_envs.each do |k|
29   unless ENV[k]
30     abort "Fatal: These environment vars must be set: #{req_envs}"
31   end
32 end
33
34 options = {}
35 OptionParser.new do |parser|
36   parser.on('--exclusive', 'Manage SSH keys file exclusively.')
37   parser.on('--rotate-tokens', 'Force a rotation of all user tokens.')
38   parser.on('--skip-missing-users', "Don't try to create any local accounts.")
39   parser.on('--token-lifetime SECONDS', 'Create user tokens that expire after SECONDS.', Integer)
40   parser.on('--debug', 'Enable debug output')
41 end.parse!(into: options)
42
43 exclusive_banner = "#######################################################################################
44 #  THIS FILE IS MANAGED BY #{$0} -- CHANGES WILL BE OVERWRITTEN  #
45 #######################################################################################\n\n"
46 start_banner = "### BEGIN Arvados-managed keys -- changes between markers will be overwritten\n"
47 end_banner = "### END Arvados-managed keys -- changes between markers will be overwritten\n"
48
49 keys = ''
50
51 begin
52   debug = false
53   if options[:"debug"]
54     debug = true
55   end
56   arv = Arvados.new({ :suppress_ssl_warnings => false })
57   logincluster_host = ENV['ARVADOS_API_HOST']
58   logincluster_name = arv.cluster_config['Login']['LoginCluster'] or ''
59
60   if logincluster_name != '' and logincluster_name != arv.cluster_config['ClusterID']
61     logincluster_host = arv.cluster_config['RemoteClusters'][logincluster_name]['Host']
62   end
63   logincluster_arv = Arvados.new({ :api_host => logincluster_host,
64                                    :suppress_ssl_warnings => false })
65
66   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
67
68   logins = arv.virtual_machine.logins(:uuid => vm_uuid)[:items]
69   logins = [] if logins.nil?
70   logins = logins.reject { |l| l[:username].nil? or l[:hostname].nil? or l[:virtual_machine_uuid] != vm_uuid }
71
72   # No system users
73   uid_min = 1000
74   open("/etc/login.defs", encoding: "utf-8") do |login_defs|
75     login_defs.each_line do |line|
76       next unless match = /^UID_MIN\s+(\S+)$/.match(line)
77       if match[1].start_with?("0x")
78         base = 16
79       elsif match[1].start_with?("0")
80         base = 8
81       else
82         base = 10
83       end
84       new_uid_min = match[1].to_i(base)
85       uid_min = new_uid_min if (new_uid_min > 0)
86     end
87   end
88
89   pwnam = Hash.new()
90   logins.reject! do |l|
91     if not pwnam[l[:username]]
92       begin
93         pwnam[l[:username]] = Etc.getpwnam(l[:username])
94       rescue
95         if options[:"skip-missing-users"]
96           STDERR.puts "Account #{l[:username]} not found. Skipping"
97           true
98         end
99       else
100         if pwnam[l[:username]].uid < uid_min
101           STDERR.puts "Account #{l[:username]} uid #{pwnam[l[:username]].uid} < uid_min #{uid_min}. Skipping" if debug
102           true
103         end
104       end
105     end
106   end
107   keys = Hash.new()
108
109   # Collect all keys
110   logins.each do |l|
111     STDERR.puts("Considering #{l[:username]} ...") if debug
112     keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
113     key = l[:public_key]
114     if !key.nil?
115       # Handle putty-style ssh public keys
116       key.sub!(/^(Comment: "r[^\n]*\n)(.*)$/m,'ssh-rsa \2 \1')
117       key.sub!(/^(Comment: "d[^\n]*\n)(.*)$/m,'ssh-dss \2 \1')
118       key.gsub!(/\n/,'')
119       key.strip
120
121       keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
122     end
123   end
124
125   seen = Hash.new()
126
127   current_user_groups = Hash.new
128   while (ent = Etc.getgrent()) do
129     ent.mem.each do |member|
130       current_user_groups[member] ||= Array.new
131       current_user_groups[member].push ent.name
132     end
133   end
134   Etc.endgrent()
135
136   logins.each do |l|
137     next if seen[l[:username]]
138     seen[l[:username]] = true
139
140     username = l[:username]
141
142     unless pwnam[l[:username]]
143       STDERR.puts "Creating account #{l[:username]}"
144       # Create new user
145       out, st = Open3.capture2e("useradd", "-m",
146                 "-c", username,
147                 "-s", "/bin/bash",
148                 username)
149       if st.exitstatus != 0
150         STDERR.puts "Account creation failed for #{l[:username]}:\n#{out}"
151         next
152       end
153       begin
154         pwnam[username] = Etc.getpwnam(username)
155       rescue => e
156         STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
157         raise
158       end
159     end
160
161     user_gid = pwnam[username].gid
162     homedir = pwnam[l[:username]].dir
163     if !File.exist?(homedir)
164       STDERR.puts "Cannot set up user #{username} because their home directory #{homedir} does not exist. Skipping."
165       next
166     end
167
168     existing_groups = current_user_groups[username] || []
169     groups = l[:groups] || []
170     # Adding users to the FUSE group has long been hardcoded behavior.
171     groups << "fuse"
172     groups << username
173     groups.select! { |g| Etc.getgrnam(g) rescue false }
174
175     groups.each do |addgroup|
176       if existing_groups.index(addgroup).nil?
177         # User should be in group, but isn't, so add them.
178         STDERR.puts "Add user #{username} to #{addgroup} group"
179         out, st = Open3.capture2e("usermod", "-aG", addgroup, username)
180         if st.exitstatus != 0
181           STDERR.puts "Failed to add #{username} to #{addgroup} group:\n#{out}"
182         end
183       end
184     end
185
186     existing_groups.each do |removegroup|
187       if groups.index(removegroup).nil?
188         # User is in a group, but shouldn't be, so remove them.
189         STDERR.puts "Remove user #{username} from #{removegroup} group"
190         out, st = Open3.capture2e("gpasswd", "-d", username, removegroup)
191         if st.exitstatus != 0
192           STDERR.puts "Failed to remove user #{username} from #{removegroup} group:\n#{out}"
193         end
194       end
195     end
196
197     userdotssh = File.join(homedir, ".ssh")
198     ensure_dir(userdotssh, 0700, username, user_gid)
199
200     newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
201
202     keysfile = File.join(userdotssh, "authorized_keys")
203     begin
204       oldkeys = File.read(keysfile)
205     rescue Errno::ENOENT
206       oldkeys = ""
207     end
208
209     if options[:exclusive]
210       newkeys = exclusive_banner + newkeys
211     elsif oldkeys.start_with?(exclusive_banner)
212       newkeys = start_banner + newkeys + end_banner
213     elsif (m = /^(.*?\n|)#{start_banner}(.*?\n|)#{end_banner}(.*)/m.match(oldkeys))
214       newkeys = m[1] + start_banner + newkeys + end_banner + m[3]
215     else
216       newkeys = start_banner + newkeys + end_banner + oldkeys
217     end
218
219     if oldkeys != newkeys then
220       File.open(keysfile, 'w', 0600) do |f|
221         f.write(newkeys)
222       end
223       FileUtils.chown(username, user_gid, keysfile)
224     end
225
226     userdotconfig = File.join(homedir, ".config")
227     ensure_dir(userdotconfig, 0755, username, user_gid)
228     configarvados = File.join(userdotconfig, "arvados")
229     ensure_dir(configarvados, 0700, username, user_gid)
230
231     tokenfile = File.join(configarvados, "settings.conf")
232
233     begin
234       STDERR.puts "Processing #{tokenfile} ..." if debug
235       newToken = false
236       if File.exist?(tokenfile)
237         # check if the token is still valid
238         myToken = ENV["ARVADOS_API_TOKEN"]
239         userEnv = File.read(tokenfile)
240         if (m = /^ARVADOS_API_TOKEN=(.*?\n)/m.match(userEnv))
241           begin
242             tmp_arv = Arvados.new({ :api_host => logincluster_host,
243                                     :api_token => (m[1]),
244                                     :suppress_ssl_warnings => false })
245             tmp_arv.user.current
246           rescue Arvados::TransactionFailedError => e
247             if e.to_s =~ /401 Unauthorized/
248               STDERR.puts "Account #{l[:username]} token not valid, creating new token."
249               newToken = true
250             else
251               raise
252             end
253           end
254         end
255       elsif !File.exist?(tokenfile) || options[:"rotate-tokens"]
256         STDERR.puts "Account #{l[:username]} token file not found, creating new token."
257         newToken = true
258       end
259       if newToken
260         aca_params = {owner_uuid: l[:user_uuid], api_client_id: 0}
261         if options[:"token-lifetime"] && options[:"token-lifetime"] > 0
262           aca_params.merge!(expires_at: (Time.now + options[:"token-lifetime"]))
263         end
264         user_token = logincluster_arv.api_client_authorization.create(api_client_authorization: aca_params)
265         File.open(tokenfile, 'w', 0600) do |f|
266           f.write("ARVADOS_API_HOST=#{ENV['ARVADOS_API_HOST']}\n")
267           f.write("ARVADOS_API_TOKEN=v2/#{user_token[:uuid]}/#{user_token[:api_token]}\n")
268         end
269         FileUtils.chown(username, user_gid, tokenfile)
270       end
271     rescue => e
272       STDERR.puts "Error setting token for #{l[:username]}: #{e}"
273     end
274   end
275
276 rescue Exception => bang
277   puts "Error: " + bang.to_s
278   puts bang.backtrace.join("\n")
279   exit 1
280 end