Merge branch '17903-login-sync-centos7'
[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
14 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
15 req_envs.each do |k|
16   unless ENV[k]
17     abort "Fatal: These environment vars must be set: #{req_envs}"
18   end
19 end
20
21 options = {}
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)
28
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"
34
35 keys = ''
36
37 begin
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 })
42
43   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
44
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 }
48
49   # No system users
50   uid_min = 1000
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")
55         base = 16
56       elsif match[1].start_with?("0")
57         base = 8
58       else
59         base = 10
60       end
61       new_uid_min = match[1].to_i(base)
62       uid_min = new_uid_min if (new_uid_min > 0)
63     end
64   end
65
66   pwnam = Hash.new()
67   logins.reject! do |l|
68     if not pwnam[l[:username]]
69       begin
70         pwnam[l[:username]] = Etc.getpwnam(l[:username])
71       rescue
72         if options[:"skip-missing-users"]
73           STDERR.puts "Account #{l[:username]} not found. Skipping"
74           true
75         end
76       else
77         if pwnam[l[:username]].uid < uid_min
78           STDERR.puts "Account #{l[:username]} uid #{pwnam[l[:username]].uid} < uid_min #{uid_min}. Skipping"
79           true
80         end
81       end
82     end
83   end
84   keys = Hash.new()
85
86   # Collect all keys
87   logins.each do |l|
88     keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
89     key = l[:public_key]
90     if !key.nil?
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')
94       key.gsub!(/\n/,'')
95       key.strip
96
97       keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
98     end
99   end
100
101   seen = Hash.new()
102
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
108     end
109   end
110   Etc.endgrent()
111
112   logins.each do |l|
113     next if seen[l[:username]]
114     seen[l[:username]] = true
115
116     username = l[:username]
117
118     unless pwnam[l[:username]]
119       STDERR.puts "Creating account #{l[:username]}"
120       # Create new user
121       unless system("useradd", "-m",
122                 "-c", username,
123                 "-s", "/bin/bash",
124                 username)
125         STDERR.puts "Account creation failed for #{l[:username]}: #{$?}"
126         next
127       end
128       begin
129         pwnam[username] = Etc.getpwnam(username)
130       rescue => e
131         STDERR.puts "Created account but then getpwnam() failed for #{l[:username]}: #{e}"
132         raise
133       end
134     end
135
136     existing_groups = current_user_groups[username] || []
137     groups = l[:groups] || []
138     # Adding users to the FUSE group has long been hardcoded behavior.
139     groups << "fuse"
140     groups << username
141     groups.select! { |g| Etc.getgrnam(g) rescue false }
142
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)
148       end
149     end
150
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)
156       end
157     end
158
159     homedir = pwnam[l[:username]].dir
160     userdotssh = File.join(homedir, ".ssh")
161     Dir.mkdir(userdotssh) if !File.exist?(userdotssh)
162
163     newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
164
165     keysfile = File.join(userdotssh, "authorized_keys")
166
167     if File.exist?(keysfile)
168       oldkeys = IO::read(keysfile)
169     else
170       oldkeys = ""
171     end
172
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]
179     else
180       newkeys = start_banner + newkeys + end_banner + oldkeys
181     end
182
183     if oldkeys != newkeys then
184       f = File.new(keysfile, 'w')
185       f.write(newkeys)
186       f.close()
187     end
188
189     userdotconfig = File.join(homedir, ".config")
190     if !File.exist?(userdotconfig)
191       Dir.mkdir(userdotconfig)
192     end
193
194     configarvados = File.join(userdotconfig, "arvados")
195     Dir.mkdir(configarvados) if !File.exist?(configarvados)
196
197     tokenfile = File.join(configarvados, "settings.conf")
198
199     begin
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"]))
204         end
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")
209         f.close()
210       end
211     rescue => e
212       STDERR.puts "Error setting token for #{l[:username]}: #{e}"
213     end
214
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)
224     end
225   end
226
227 rescue Exception => bang
228   puts "Error: " + bang.to_s
229   puts bang.backtrace.join("\n")
230   exit 1
231 end