10232: dont create user logic was wrong
[arvados.git] / services / login-sync / bin / arvados-login-sync
1 #!/usr/bin/env ruby
2
3 require 'rubygems'
4 require 'pp'
5 require 'arvados'
6 require 'etc'
7 require 'fileutils'
8 require 'yaml'
9
10 req_envs = %w(ARVADOS_API_HOST ARVADOS_API_TOKEN ARVADOS_VIRTUAL_MACHINE_UUID)
11 req_envs.each do |k|
12   unless ENV[k]
13     abort "Fatal: These environment vars must be set: #{req_envs}"
14   end
15 end
16
17 exclusive_mode = ARGV.index("--exclusive")
18 exclusive_banner = "#######################################################################################
19 #  THIS FILE IS MANAGED BY #{$0} -- CHANGES WILL BE OVERWRITTEN  #
20 #######################################################################################\n\n"
21 start_banner = "### BEGIN Arvados-managed keys -- changes between markers will be overwritten\n"
22 end_banner = "### END Arvados-managed keys -- changes between markers will be overwritten\n"
23
24 # some LDAP systems have already the user there
25 # use this falg
26 dont_create_user = ARGV.index("--dont-create-user")
27
28 keys = ''
29
30 seen = Hash.new
31
32 begin
33   uids = Hash[Etc.to_enum(:passwd).map { |ent| [ent.name, ent.uid] }]
34   gids = Hash[Etc.to_enum(:group).map { |ent| [ent.name, ent.gid] }]
35   arv = Arvados.new({ :suppress_ssl_warnings => false })
36
37   vm_uuid = ENV['ARVADOS_VIRTUAL_MACHINE_UUID']
38
39   logins = arv.virtual_machine.logins(:uuid => vm_uuid)[:items]
40   logins = [] if logins.nil?
41   logins = logins.reject { |l| l[:username].nil? or l[:hostname].nil? or l[:public_key].nil? or l[:virtual_machine_uuid] != vm_uuid }
42
43   # No system users
44   uid_min = 1000
45   open("/etc/login.defs", encoding: "utf-8") do |login_defs|
46     login_defs.each_line do |line|
47       next unless match = /^UID_MIN\s+(\S+)$/.match(line)
48       if match[1].start_with?("0x")
49         base = 16
50       elsif match[1].start_with?("0")
51         base = 8
52       else
53         base = 10
54       end
55       new_uid_min = match[1].to_i(base)
56       uid_min = new_uid_min if (new_uid_min > 0)
57     end
58   end
59   logins.reject! { |l| (uids[l[:username]] || 65535) < uid_min }
60
61   keys = Hash.new()
62
63   # Collect all keys
64   logins.each do |l|
65     keys[l[:username]] = Array.new() if not keys.has_key?(l[:username])
66     key = l[:public_key]
67     # Handle putty-style ssh public keys
68     key.sub!(/^(Comment: "r[^\n]*\n)(.*)$/m,'ssh-rsa \2 \1')
69     key.sub!(/^(Comment: "d[^\n]*\n)(.*)$/m,'ssh-dss \2 \1')
70     key.gsub!(/\n/,'')
71     key.strip
72
73     keys[l[:username]].push(key) if not keys[l[:username]].include?(key)
74   end
75
76   seen = Hash.new()
77   devnull = open("/dev/null", "w")
78
79   logins.each do |l|
80     next if seen[l[:username]]
81     seen[l[:username]] = true if not seen.has_key?(l[:username])
82
83     unless uids[l[:username]] or dont_create_user
84       STDERR.puts "Creating account #{l[:username]}"
85       groups = l[:groups] || []
86       # Adding users to the FUSE group has long been hardcoded behavior.
87       groups << "fuse"
88       groups.select! { |name| gids[name] }
89       # Create new user
90       next unless system("useradd", "-m",
91                          "-c", l[:username],
92                          "-s", "/bin/bash",
93                          "-G", groups.join(","),
94                          l[:username],
95                          out: devnull)
96     end
97
98     # If after all this effort isn't listed using Etc.getpwnam()
99     # this means that wont be available in the system
100     # some LDAP configurations will need this
101     begin
102       # Create .ssh directory if necessary
103       Etc.getpwnam(l[:username])
104     rescue ArgumentError
105       STDERR.puts "Account #{l[:username]} not found. Skipping"
106       next
107     end
108       
109     @homedir = Etc.getpwnam(l[:username]).dir
110     userdotssh = File.join(@homedir, ".ssh")
111     Dir.mkdir(userdotssh) if !File.exists?(userdotssh)
112
113     newkeys = "###\n###\n" + keys[l[:username]].join("\n") + "\n###\n###\n"
114
115     keysfile = File.join(userdotssh, "authorized_keys")
116
117     if File.exists?(keysfile)
118       oldkeys = IO::read(keysfile)
119     else
120       oldkeys = ""
121     end
122
123     if exclusive_mode
124       newkeys = exclusive_banner + newkeys
125     elsif oldkeys.start_with?(exclusive_banner)
126       newkeys = start_banner + newkeys + end_banner
127     elsif (m = /^(.*?\n|)#{start_banner}(.*?\n|)#{end_banner}(.*)/m.match(oldkeys))
128       newkeys = m[1] + start_banner + newkeys + end_banner + m[3]
129     else
130       newkeys = start_banner + newkeys + end_banner + oldkeys
131     end
132
133     if oldkeys != newkeys then
134       f = File.new(keysfile, 'w')
135       f.write(newkeys)
136       f.close()
137     end
138     FileUtils.chown_R(l[:username], nil, userdotssh)
139     File.chmod(0700, userdotssh)
140     File.chmod(0750, @homedir)
141     File.chmod(0600, keysfile)
142   end
143
144   devnull.close
145 rescue Exception => bang
146   puts "Error: " + bang.to_s
147   puts bang.backtrace.join("\n")
148   exit 1
149 end