1 -- This script may be used with the auth-filter. Be sure to configure it as you wish.
5 -- <http://25thandclement.com/~william/projects/luaossl.html>
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 lualdap = require("lualdap")
14 local rand = require("openssl.rand")
15 local hmac = require("openssl.hmac")
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 x = x .. string.format("%.2x", string.byte(b, i))
239 -- Cookie construction and validation helpers.
245 -- Loads a secret from a file, creates a secret, or returns one from memory.
246 function get_secret()
247 if secret ~= nil then
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
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")
265 if secret_file == nil then
268 secret = secret_file:read()
270 if secret:len() ~= 64 then
276 -- Returns value of cookie if cookie is valid. Otherwise returns nil.
277 function validate_value(expected_field, cookie)
285 if cookie == nil or cookie:len() < 3 or cookie:sub(1, 1) == "|" then
289 for component in string.gmatch(cookie, "[^|]+") do
295 expiration = tonumber(component)
296 if expiration == nil then
309 if chmac == nil or chmac:len() == 0 then
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
318 if expiration == -1 or (expiration ~= 0 and expiration <= os.time()) then
322 if url_decode(field) ~= expected_field then
326 return url_decode(value)
329 function secure_value(field, value, expiration)
330 if value == nil or value:len() <= 0 then
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))
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
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")
358 html("Status: 404 Not Found\n")
359 html("Cache-Control: no-cache, no-store\n\n")