1 -- This script may be used with the auth-filter. Be sure to configure it as you wish.
5 -- <http://mkottman.github.io/luacrypto/>
7 -- <https://git.zx2c4.com/lualdap/about/>
9 -- <https://github.com/luaposix/luaposix>
11 local sysstat = require("posix.sys.stat")
12 local unistd = require("posix.unistd")
13 local crypto = require("crypto")
14 local lualdap = require("lualdap")
19 -- Configure these variables for your settings.
23 -- A list of password protected repositories, with which gentooAccess
24 -- group is allowed to access each one.
25 local protected_repos = {
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"
37 -- Authentication functions follow below. Swap these out if you want different authentication semantics.
41 -- Sets HTTP cookie headers based on post and sets up redirection.
42 function authenticate_post()
43 local redirect = validate_value("redirect", post["redirect"])
45 if redirect == nil then
52 local groups = gentoo_ldap_user_groups(post["username"], post["password"])
54 set_cookie("cgitauth", "")
56 -- One week expiration time
57 set_cookie("cgitauth", secure_value("gentoogroups", table.concat(groups, ","), os.time() + 604800))
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.
73 local user_groups = validate_value("gentoogroups", get_cookie(http["cookie"], "cgitauth"))
74 if user_groups == nil or user_groups == "" then
77 for group in string.gmatch(user_groups, "[^,]+") do
78 if group == required_group then
85 -- Prints the html for the login form.
87 html("<h2>Gentoo LDAP Authentication Required</h2>")
88 html("<form method='post' action='")
89 html_attr(cgit["login"])
91 html("<input type='hidden' name='redirect' value='")
92 html_attr(secure_value("redirect", cgit["url"], 0))
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>")
105 -- Gentoo LDAP support.
109 function gentoo_ldap_user_groups(username, password)
110 -- Ensure the user is alphanumeric
111 if username == nil or username:match("%W") then
115 local who = "uid=" .. username .. ",ou=devs,dc=gentoo,dc=org"
117 local ldap, err = lualdap.open_simple {
118 uri = "ldap://ldap1.gentoo.org",
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"
130 local group_suffix = ".group"
131 local group_suffix_len = group_suffix:len()
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
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))
152 -- Wrapper around filter API, exposing the http table, the cgit table, and the post table to the above functions.
157 actions["authenticate-post"] = authenticate_post
158 actions["authenticate-cookie"] = authenticate_cookie
159 actions["body"] = body
161 function filter_open(...)
162 action = actions[select(1, ...)]
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, ...)
174 cgit["repo"] = select(9, ...)
175 cgit["page"] = select(10, ...)
176 cgit["url"] = select(11, ...)
177 cgit["login"] = select(12, ...)
181 function filter_close()
185 function filter_write(str)
192 -- Utility functions based on keplerproject/wsapi.
196 function url_decode(str)
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")
206 function url_encode(str)
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, " ", "+")
216 function parse_qs(qs)
218 for key, val in string.gmatch(qs, "([^&=]+)=([^&=]*)&?") do
219 tab[url_decode(key)] = url_decode(val)
224 function get_cookie(cookies, name)
225 cookies = string.gsub(";" .. cookies .. ";", "%s*;%s*", ";")
226 return string.match(cookies, ";" .. name .. "=(.-);")
232 -- Cookie construction and validation helpers.
238 -- Loads a secret from a file, creates a secret, or returns one from memory.
239 function get_secret()
240 if secret ~= nil then
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
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")
258 if secret_file == nil then
261 secret = secret_file:read()
263 if secret:len() ~= 64 then
269 -- Returns value of cookie if cookie is valid. Otherwise returns nil.
270 function validate_value(expected_field, cookie)
278 if cookie == nil or cookie:len() < 3 or cookie:sub(1, 1) == "|" then
282 for component in string.gmatch(cookie, "[^|]+") do
288 expiration = tonumber(component)
289 if expiration == nil then
302 if hmac == nil or hmac:len() == 0 then
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
311 if expiration == -1 or (expiration ~= 0 and expiration <= os.time()) then
315 if url_decode(field) ~= expected_field then
319 return url_decode(value)
322 function secure_value(field, value, expiration)
323 if value == nil or value:len() <= 0 then
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())
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
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")
351 html("Status: 404 Not Found\n")
352 html("Cache-Control: no-cache, no-store\n\n")