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://github.com/luaposix/luaposix>
9 local sysstat = require("posix.sys.stat")
10 local unistd = require("posix.unistd")
11 local crypto = require("crypto")
16 -- Configure these variables for your settings.
20 -- A list of password protected repositories along with the users who can access them.
21 local protected_repos = {
22 glouglou = { laurent = true, jason = true },
23 qt = { jason = true, bob = true }
26 -- A list of users and hashes, generated with `mkpasswd -m sha-512 -R 300000`.
28 jason = "$6$rounds=300000$YYJct3n/o.ruYK$HhpSeuCuW1fJkpvMZOZzVizeLsBKcGA/aF2UPuV5v60JyH2MVSG6P511UMTj2F3H75.IT2HIlnvXzNb60FcZH1",
29 laurent = "$6$rounds=300000$dP0KNHwYb3JKigT$pN/LG7rWxQ4HniFtx5wKyJXBJUKP7R01zTNZ0qSK/aivw8ywGAOdfYiIQFqFhZFtVGvr11/7an.nesvm8iJUi.",
30 bob = "$6$rounds=300000$jCLCCt6LUpTz$PI1vvd1yaVYcCzqH8QAJFcJ60b6W/6sjcOsU7mAkNo7IE8FRGW1vkjF8I/T5jt/auv5ODLb1L4S2s.CAyZyUC"
33 -- Set this to a path this script can write to for storing a persistent
34 -- cookie secret, which should be guarded.
35 local secret_filename = "/var/cache/cgit/auth-secret"
39 -- Authentication functions follow below. Swap these out if you want different authentication semantics.
43 -- Sets HTTP cookie headers based on post and sets up redirection.
44 function authenticate_post()
45 local hash = users[post["username"]]
46 local redirect = validate_value("redirect", post["redirect"])
48 if redirect == nil then
55 if hash == nil or hash ~= unistd.crypt(post["password"], hash) then
56 set_cookie("cgitauth", "")
58 -- One week expiration time
59 local username = secure_value("username", post["username"], os.time() + 604800)
60 set_cookie("cgitauth", username)
68 -- Returns 1 if the cookie is valid and 0 if it is not.
69 function authenticate_cookie()
70 accepted_users = protected_repos[cgit["repo"]]
71 if accepted_users == nil then
72 -- We return as valid if the repo is not protected.
76 local username = validate_value("username", get_cookie(http["cookie"], "cgitauth"))
77 if username == nil or not accepted_users[username:lower()] then
84 -- Prints the html for the login form.
86 html("<h2>Authentication Required</h2>")
87 html("<form method='post' action='")
88 html_attr(cgit["login"])
90 html("<input type='hidden' name='redirect' value='")
91 html_attr(secure_value("redirect", cgit["url"], 0))
94 html("<tr><td><label for='username'>Username:</label></td><td><input id='username' name='username' autofocus /></td></tr>")
95 html("<tr><td><label for='password'>Password:</label></td><td><input id='password' name='password' type='password' /></td></tr>")
96 html("<tr><td colspan='2'><input value='Login' type='submit' /></td></tr>")
97 html("</table></form>")
106 -- Wrapper around filter API, exposing the http table, the cgit table, and the post table to the above functions.
111 actions["authenticate-post"] = authenticate_post
112 actions["authenticate-cookie"] = authenticate_cookie
113 actions["body"] = body
115 function filter_open(...)
116 action = actions[select(1, ...)]
119 http["cookie"] = select(2, ...)
120 http["method"] = select(3, ...)
121 http["query"] = select(4, ...)
122 http["referer"] = select(5, ...)
123 http["path"] = select(6, ...)
124 http["host"] = select(7, ...)
125 http["https"] = select(8, ...)
128 cgit["repo"] = select(9, ...)
129 cgit["page"] = select(10, ...)
130 cgit["url"] = select(11, ...)
131 cgit["login"] = select(12, ...)
135 function filter_close()
139 function filter_write(str)
146 -- Utility functions based on keplerproject/wsapi.
150 function url_decode(str)
154 str = string.gsub(str, "+", " ")
155 str = string.gsub(str, "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
156 str = string.gsub(str, "\r\n", "\n")
160 function url_encode(str)
164 str = string.gsub(str, "\n", "\r\n")
165 str = string.gsub(str, "([^%w ])", function(c) return string.format("%%%02X", string.byte(c)) end)
166 str = string.gsub(str, " ", "+")
170 function parse_qs(qs)
172 for key, val in string.gmatch(qs, "([^&=]+)=([^&=]*)&?") do
173 tab[url_decode(key)] = url_decode(val)
178 function get_cookie(cookies, name)
179 cookies = string.gsub(";" .. cookies .. ";", "%s*;%s*", ";")
180 return url_decode(string.match(cookies, ";" .. name .. "=(.-);"))
186 -- Cookie construction and validation helpers.
192 -- Loads a secret from a file, creates a secret, or returns one from memory.
193 function get_secret()
194 if secret ~= nil then
197 local secret_file = io.open(secret_filename, "r")
198 if secret_file == nil then
199 local old_umask = sysstat.umask(63)
200 local temporary_filename = secret_filename .. ".tmp." .. crypto.hex(crypto.rand.bytes(16))
201 local temporary_file = io.open(temporary_filename, "w")
202 if temporary_file == nil then
205 temporary_file:write(crypto.hex(crypto.rand.bytes(32)))
206 temporary_file:close()
207 unistd.link(temporary_filename, secret_filename) -- Intentionally fails in the case that another process is doing the same.
208 unistd.unlink(temporary_filename)
209 sysstat.umask(old_umask)
210 secret_file = io.open(secret_filename, "r")
212 if secret_file == nil then
215 secret = secret_file:read()
217 if secret:len() ~= 64 then
223 -- Returns value of cookie if cookie is valid. Otherwise returns nil.
224 function validate_value(expected_field, cookie)
232 if cookie == nil or cookie:len() < 3 or cookie:sub(1, 1) == "|" then
236 for component in string.gmatch(cookie, "[^|]+") do
242 expiration = tonumber(component)
243 if expiration == nil then
256 if hmac == nil or hmac:len() == 0 then
260 -- Lua hashes strings, so these comparisons are time invariant.
261 if hmac ~= crypto.hmac.digest("sha256", field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt, get_secret()) then
265 if expiration == -1 or (expiration ~= 0 and expiration <= os.time()) then
269 if url_decode(field) ~= expected_field then
273 return url_decode(value)
276 function secure_value(field, value, expiration)
277 if value == nil or value:len() <= 0 then
282 local salt = crypto.hex(crypto.rand.bytes(16))
283 value = url_encode(value)
284 field = url_encode(field)
285 authstr = field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt
286 authstr = authstr .. "|" .. crypto.hmac.digest("sha256", authstr, get_secret())
290 function set_cookie(cookie, value)
291 html("Set-Cookie: " .. cookie .. "=" .. value .. "; HttpOnly")
292 if http["https"] == "yes" or http["https"] == "on" or http["https"] == "1" then
298 function redirect_to(url)
299 html("Status: 302 Redirect\n")
300 html("Cache-Control: no-cache, no-store\n")
301 html("Location: " .. url .. "\n")
305 html("Status: 404 Not Found\n")
306 html("Cache-Control: no-cache, no-store\n\n")