]> gitweb.ps.run Git - ps-cgit/blob - filters/gentoo-ldap-authentication.lua
auth-filters: generate secret securely
[ps-cgit] / filters / gentoo-ldap-authentication.lua
1 -- This script may be used with the auth-filter. Be sure to configure it as you wish.
2 --
3 -- Requirements:
4 --      luacrypto >= 0.3
5 --      <http://mkottman.github.io/luacrypto/>
6 --      lualdap >= 1.2
7 --      <https://git.zx2c4.com/lualdap/about/>
8 --      luaposix
9 --      <https://github.com/luaposix/luaposix>
10 --
11 local sysstat = require("posix.sys.stat")
12 local unistd = require("posix.unistd")
13 local crypto = require("crypto")
14 local lualdap = require("lualdap")
15
16
17 --
18 --
19 -- Configure these variables for your settings.
20 --
21 --
22
23 -- A list of password protected repositories, with which gentooAccess
24 -- group is allowed to access each one.
25 local protected_repos = {
26         glouglou = "infra",
27         portage = "dev"
28 }
29
30 -- Set this to a path this script can write to for storing a persistent
31 -- cookie secret, which should be guarded.
32 local secret_filename = "/var/cache/cgit/auth-secret"
33
34
35 --
36 --
37 -- Authentication functions follow below. Swap these out if you want different authentication semantics.
38 --
39 --
40
41 -- Sets HTTP cookie headers based on post and sets up redirection.
42 function authenticate_post()
43         local redirect = validate_value("redirect", post["redirect"])
44
45         if redirect == nil then
46                 not_found()
47                 return 0
48         end
49
50         redirect_to(redirect)
51         
52         local groups = gentoo_ldap_user_groups(post["username"], post["password"])
53         if groups == nil then
54                 set_cookie("cgitauth", "")
55         else
56                 -- One week expiration time
57                 set_cookie("cgitauth", secure_value("gentoogroups", table.concat(groups, ","), os.time() + 604800))
58         end
59
60         html("\n")
61         return 0
62 end
63
64
65 -- Returns 1 if the cookie is valid and 0 if it is not.
66 function authenticate_cookie()
67         local required_group = protected_repos[cgit["repo"]]
68         if required_group == nil then
69                 -- We return as valid if the repo is not protected.
70                 return 1
71         end
72         
73         local user_groups = validate_value("gentoogroups", get_cookie(http["cookie"], "cgitauth"))
74         if user_groups == nil or user_groups == "" then
75                 return 0
76         end
77         for group in string.gmatch(user_groups, "[^,]+") do
78                 if group == required_group then
79                         return 1
80                 end
81         end
82         return 0
83 end
84
85 -- Prints the html for the login form.
86 function body()
87         html("<h2>Gentoo LDAP Authentication Required</h2>")
88         html("<form method='post' action='")
89         html_attr(cgit["login"])
90         html("'>")
91         html("<input type='hidden' name='redirect' value='")
92         html_attr(secure_value("redirect", cgit["url"], 0))
93         html("' />")
94         html("<table>")
95         html("<tr><td><label for='username'>Username:</label></td><td><input id='username' name='username' autofocus /></td></tr>")
96         html("<tr><td><label for='password'>Password:</label></td><td><input id='password' name='password' type='password' /></td></tr>")
97         html("<tr><td colspan='2'><input value='Login' type='submit' /></td></tr>")
98         html("</table></form>")
99
100         return 0
101 end
102
103 --
104 --
105 -- Gentoo LDAP support.
106 --
107 --
108
109 function gentoo_ldap_user_groups(username, password)
110         -- Ensure the user is alphanumeric
111         if username == nil or username:match("%W") then
112                 return nil
113         end
114
115         local who = "uid=" .. username .. ",ou=devs,dc=gentoo,dc=org"
116
117         local ldap, err = lualdap.open_simple {
118                 uri = "ldap://ldap1.gentoo.org",
119                 who = who,
120                 password = password,
121                 starttls = true,
122                 certfile = "/var/www/uwsgi/cgit/gentoo-ldap/star.gentoo.org.crt",
123                 keyfile = "/var/www/uwsgi/cgit/gentoo-ldap/star.gentoo.org.key",
124                 cacertfile = "/var/www/uwsgi/cgit/gentoo-ldap/ca.pem"
125         }
126         if ldap == nil then
127                 return nil
128         end
129
130         local group_suffix = ".group"
131         local group_suffix_len = group_suffix:len()
132         local groups = {}
133         for dn, attribs in ldap:search { base = who, scope = "subtree" } do
134                 local access = attribs["gentooAccess"]
135                 if dn == who and access ~= nil then
136                         for i, v in ipairs(access) do
137                                 local vlen = v:len()
138                                 if vlen > group_suffix_len and v:sub(-group_suffix_len) == group_suffix then
139                                         table.insert(groups, v:sub(1, vlen - group_suffix_len))
140                                 end
141                         end
142                 end
143         end
144
145         ldap:close()
146
147         return groups
148 end
149
150 --
151 --
152 -- Wrapper around filter API, exposing the http table, the cgit table, and the post table to the above functions.
153 --
154 --
155
156 local actions = {}
157 actions["authenticate-post"] = authenticate_post
158 actions["authenticate-cookie"] = authenticate_cookie
159 actions["body"] = body
160
161 function filter_open(...)
162         action = actions[select(1, ...)]
163
164         http = {}
165         http["cookie"] = select(2, ...)
166         http["method"] = select(3, ...)
167         http["query"] = select(4, ...)
168         http["referer"] = select(5, ...)
169         http["path"] = select(6, ...)
170         http["host"] = select(7, ...)
171         http["https"] = select(8, ...)
172
173         cgit = {}
174         cgit["repo"] = select(9, ...)
175         cgit["page"] = select(10, ...)
176         cgit["url"] = select(11, ...)
177         cgit["login"] = select(12, ...)
178
179 end
180
181 function filter_close()
182         return action()
183 end
184
185 function filter_write(str)
186         post = parse_qs(str)
187 end
188
189
190 --
191 --
192 -- Utility functions based on keplerproject/wsapi.
193 --
194 --
195
196 function url_decode(str)
197         if not str then
198                 return ""
199         end
200         str = string.gsub(str, "+", " ")
201         str = string.gsub(str, "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
202         str = string.gsub(str, "\r\n", "\n")
203         return str
204 end
205
206 function url_encode(str)
207         if not str then
208                 return ""
209         end
210         str = string.gsub(str, "\n", "\r\n")
211         str = string.gsub(str, "([^%w ])", function(c) return string.format("%%%02X", string.byte(c)) end)
212         str = string.gsub(str, " ", "+")
213         return str
214 end
215
216 function parse_qs(qs)
217         local tab = {}
218         for key, val in string.gmatch(qs, "([^&=]+)=([^&=]*)&?") do
219                 tab[url_decode(key)] = url_decode(val)
220         end
221         return tab
222 end
223
224 function get_cookie(cookies, name)
225         cookies = string.gsub(";" .. cookies .. ";", "%s*;%s*", ";")
226         return string.match(cookies, ";" .. name .. "=(.-);")
227 end
228
229
230 --
231 --
232 -- Cookie construction and validation helpers.
233 --
234 --
235
236 local secret = nil
237
238 -- Loads a secret from a file, creates a secret, or returns one from memory.
239 function get_secret()
240         if secret ~= nil then
241                 return secret
242         end
243         local secret_file = io.open(secret_filename, "r")
244         if secret_file == nil then
245                 local old_umask = sysstat.umask(63)
246                 local temporary_filename = secret_filename .. ".tmp." .. crypto.hex(crypto.rand.bytes(16))
247                 local temporary_file = io.open(temporary_filename, "w")
248                 if temporary_file == nil then
249                         os.exit(177)
250                 end
251                 temporary_file:write(crypto.hex(crypto.rand.bytes(32)))
252                 temporary_file:close()
253                 unistd.link(temporary_filename, secret_filename) -- Intentionally fails in the case that another process is doing the same.
254                 unistd.unlink(temporary_filename)
255                 sysstat.umask(old_umask)
256                 secret_file = io.open(secret_filename, "r")
257         end
258         if secret_file == nil then
259                 os.exit(177)
260         end
261         secret = secret_file:read()
262         secret_file:close()
263         if secret:len() ~= 64 then
264                 os.exit(177)
265         end
266         return secret
267 end
268
269 -- Returns value of cookie if cookie is valid. Otherwise returns nil.
270 function validate_value(expected_field, cookie)
271         local i = 0
272         local value = ""
273         local field = ""
274         local expiration = 0
275         local salt = ""
276         local hmac = ""
277
278         if cookie == nil or cookie:len() < 3 or cookie:sub(1, 1) == "|" then
279                 return nil
280         end
281
282         for component in string.gmatch(cookie, "[^|]+") do
283                 if i == 0 then
284                         field = component
285                 elseif i == 1 then
286                         value = component
287                 elseif i == 2 then
288                         expiration = tonumber(component)
289                         if expiration == nil then
290                                 expiration = -1
291                         end
292                 elseif i == 3 then
293                         salt = component
294                 elseif i == 4 then
295                         hmac = component
296                 else
297                         break
298                 end
299                 i = i + 1
300         end
301
302         if hmac == nil or hmac:len() == 0 then
303                 return nil
304         end
305
306         -- Lua hashes strings, so these comparisons are time invariant.
307         if hmac ~= crypto.hmac.digest("sha256", field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt, get_secret()) then
308                 return nil
309         end
310
311         if expiration == -1 or (expiration ~= 0 and expiration <= os.time()) then
312                 return nil
313         end
314
315         if url_decode(field) ~= expected_field then
316                 return nil
317         end
318
319         return url_decode(value)
320 end
321
322 function secure_value(field, value, expiration)
323         if value == nil or value:len() <= 0 then
324                 return ""
325         end
326
327         local authstr = ""
328         local salt = crypto.hex(crypto.rand.bytes(16))
329         value = url_encode(value)
330         field = url_encode(field)
331         authstr = field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt
332         authstr = authstr .. "|" .. crypto.hmac.digest("sha256", authstr, get_secret())
333         return authstr
334 end
335
336 function set_cookie(cookie, value)
337         html("Set-Cookie: " .. cookie .. "=" .. value .. "; HttpOnly")
338         if http["https"] == "yes" or http["https"] == "on" or http["https"] == "1" then
339                 html("; secure")
340         end
341         html("\n")
342 end
343
344 function redirect_to(url)
345         html("Status: 302 Redirect\n")
346         html("Cache-Control: no-cache, no-store\n")
347         html("Location: " .. url .. "\n")
348 end
349
350 function not_found()
351         html("Status: 404 Not Found\n")
352         html("Cache-Control: no-cache, no-store\n\n")
353 end