git: update to v2.32.0
[cgit.git] / 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 -- luaossl
5 -- <http://25thandclement.com/~william/projects/luaossl.html>
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 lualdap = require("lualdap")
14 local rand = require("openssl.rand")
15 local hmac = require("openssl.hmac")
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 function tohex(b)
230 local x = ""
231 for i = 1, #b do
232 x = x .. string.format("%.2x", string.byte(b, i))
233 end
234 return x
235 end
236
237 --
238 --
239 -- Cookie construction and validation helpers.
240 --
241 --
242
243 local secret = nil
244
245 -- Loads a secret from a file, creates a secret, or returns one from memory.
246 function get_secret()
247 if secret ~= nil then
248 return secret
249 end
250 local secret_file = io.open(secret_filename, "r")
251 if secret_file == nil then
252 local old_umask = sysstat.umask(63)
253 local temporary_filename = secret_filename .. ".tmp." .. tohex(rand.bytes(16))
254 local temporary_file = io.open(temporary_filename, "w")
255 if temporary_file == nil then
256 os.exit(177)
257 end
258 temporary_file:write(tohex(rand.bytes(32)))
259 temporary_file:close()
260 unistd.link(temporary_filename, secret_filename) -- Intentionally fails in the case that another process is doing the same.
261 unistd.unlink(temporary_filename)
262 sysstat.umask(old_umask)
263 secret_file = io.open(secret_filename, "r")
264 end
265 if secret_file == nil then
266 os.exit(177)
267 end
268 secret = secret_file:read()
269 secret_file:close()
270 if secret:len() ~= 64 then
271 os.exit(177)
272 end
273 return secret
274 end
275
276 -- Returns value of cookie if cookie is valid. Otherwise returns nil.
277 function validate_value(expected_field, cookie)
278 local i = 0
279 local value = ""
280 local field = ""
281 local expiration = 0
282 local salt = ""
283 local chmac = ""
284
285 if cookie == nil or cookie:len() < 3 or cookie:sub(1, 1) == "|" then
286 return nil
287 end
288
289 for component in string.gmatch(cookie, "[^|]+") do
290 if i == 0 then
291 field = component
292 elseif i == 1 then
293 value = component
294 elseif i == 2 then
295 expiration = tonumber(component)
296 if expiration == nil then
297 expiration = -1
298 end
299 elseif i == 3 then
300 salt = component
301 elseif i == 4 then
302 chmac = component
303 else
304 break
305 end
306 i = i + 1
307 end
308
309 if chmac == nil or chmac:len() == 0 then
310 return nil
311 end
312
313 -- Lua hashes strings, so these comparisons are time invariant.
314 if chmac ~= tohex(hmac.new(get_secret(), "sha256"):final(field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt)) then
315 return nil
316 end
317
318 if expiration == -1 or (expiration ~= 0 and expiration <= os.time()) then
319 return nil
320 end
321
322 if url_decode(field) ~= expected_field then
323 return nil
324 end
325
326 return url_decode(value)
327 end
328
329 function secure_value(field, value, expiration)
330 if value == nil or value:len() <= 0 then
331 return ""
332 end
333
334 local authstr = ""
335 local salt = tohex(rand.bytes(16))
336 value = url_encode(value)
337 field = url_encode(field)
338 authstr = field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt
339 authstr = authstr .. "|" .. tohex(hmac.new(get_secret(), "sha256"):final(authstr))
340 return authstr
341 end
342
343 function set_cookie(cookie, value)
344 html("Set-Cookie: " .. cookie .. "=" .. value .. "; HttpOnly")
345 if http["https"] == "yes" or http["https"] == "on" or http["https"] == "1" then
346 html("; secure")
347 end
348 html("\n")
349 end
350
351 function redirect_to(url)
352 html("Status: 302 Redirect\n")
353 html("Cache-Control: no-cache, no-store\n")
354 html("Location: " .. url .. "\n")
355 end
356
357 function not_found()
358 html("Status: 404 Not Found\n")
359 html("Cache-Control: no-cache, no-store\n\n")
360 end