1 -- This script may be used with the auth-filter.
5 -- <http://25thandclement.com/~william/projects/luaossl.html>
7 -- <https://github.com/luaposix/luaposix>
9 local sysstat = require("posix.sys.stat")
10 local unistd = require("posix.unistd")
11 local rand = require("openssl.rand")
12 local hmac = require("openssl.hmac")
14 -- This file should contain a series of lines in the form of:
19 -- Hashes can be generated using something like `mkpasswd -m sha-512 -R 300000`.
20 -- This file should not be world-readable.
21 local users_filename = "/etc/cgit-auth/users"
23 -- This file should contain a series of lines in the form of:
24 -- groupname1:username1,username2,username3,...
26 local groups_filename = "/etc/cgit-auth/groups"
28 -- This file should contain a series of lines in the form of:
29 -- reponame1:groupname1,groupname2,groupname3,...
31 local repos_filename = "/etc/cgit-auth/repos"
33 -- Set this to a path this script can write to for storing a persistent
34 -- cookie secret, which should not be world-readable.
35 local secret_filename = "/var/cache/cgit/auth-secret"
39 -- Authentication functions follow below. Swap these out if you want different authentication semantics.
43 -- Looks up a hash for a given user.
44 function lookup_hash(user)
46 for line in io.lines(users_filename) do
47 local u, h = string.match(line, "(.-):(.+)")
48 if u:lower() == user:lower() then
55 -- Looks up users for a given repo.
56 function lookup_users(repo)
59 local line, group, user
60 for line in io.lines(repos_filename) do
61 local r, g = string.match(line, "(.-):(.+)")
64 for group in string.gmatch(g, "([^,]+)") do
65 groups[group:lower()] = true
73 for line in io.lines(groups_filename) do
74 local g, u = string.match(line, "(.-):(.+)")
75 if groups[g:lower()] then
79 for user in string.gmatch(u, "([^,]+)") do
80 users[user:lower()] = true
88 -- Sets HTTP cookie headers based on post and sets up redirection.
89 function authenticate_post()
90 local hash = lookup_hash(post["username"])
91 local redirect = validate_value("redirect", post["redirect"])
93 if redirect == nil then
100 if hash == nil or hash ~= unistd.crypt(post["password"], hash) then
101 set_cookie("cgitauth", "")
103 -- One week expiration time
104 local username = secure_value("username", post["username"], os.time() + 604800)
105 set_cookie("cgitauth", username)
113 -- Returns 1 if the cookie is valid and 0 if it is not.
114 function authenticate_cookie()
115 accepted_users = lookup_users(cgit["repo"])
116 if accepted_users == nil then
117 -- We return as valid if the repo is not protected.
121 local username = validate_value("username", get_cookie(http["cookie"], "cgitauth"))
122 if username == nil or not accepted_users[username:lower()] then
129 -- Prints the html for the login form.
131 html("<h2>Authentication Required</h2>")
132 html("<form method='post' action='")
133 html_attr(cgit["login"])
135 html("<input type='hidden' name='redirect' value='")
136 html_attr(secure_value("redirect", cgit["url"], 0))
139 html("<tr><td><label for='username'>Username:</label></td><td><input id='username' name='username' autofocus /></td></tr>")
140 html("<tr><td><label for='password'>Password:</label></td><td><input id='password' name='password' type='password' /></td></tr>")
141 html("<tr><td colspan='2'><input value='Login' type='submit' /></td></tr>")
142 html("</table></form>")
151 -- Wrapper around filter API, exposing the http table, the cgit table, and the post table to the above functions.
156 actions["authenticate-post"] = authenticate_post
157 actions["authenticate-cookie"] = authenticate_cookie
158 actions["body"] = body
160 function filter_open(...)
161 action = actions[select(1, ...)]
164 http["cookie"] = select(2, ...)
165 http["method"] = select(3, ...)
166 http["query"] = select(4, ...)
167 http["referer"] = select(5, ...)
168 http["path"] = select(6, ...)
169 http["host"] = select(7, ...)
170 http["https"] = select(8, ...)
173 cgit["repo"] = select(9, ...)
174 cgit["page"] = select(10, ...)
175 cgit["url"] = select(11, ...)
176 cgit["login"] = select(12, ...)
180 function filter_close()
184 function filter_write(str)
191 -- Utility functions based on keplerproject/wsapi.
195 function url_decode(str)
199 str = string.gsub(str, "+", " ")
200 str = string.gsub(str, "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
201 str = string.gsub(str, "\r\n", "\n")
205 function url_encode(str)
209 str = string.gsub(str, "\n", "\r\n")
210 str = string.gsub(str, "([^%w ])", function(c) return string.format("%%%02X", string.byte(c)) end)
211 str = string.gsub(str, " ", "+")
215 function parse_qs(qs)
217 for key, val in string.gmatch(qs, "([^&=]+)=([^&=]*)&?") do
218 tab[url_decode(key)] = url_decode(val)
223 function get_cookie(cookies, name)
224 cookies = string.gsub(";" .. cookies .. ";", "%s*;%s*", ";")
225 return url_decode(string.match(cookies, ";" .. name .. "=(.-);"))
231 x = x .. string.format("%.2x", string.byte(b, i))
238 -- Cookie construction and validation helpers.
244 -- Loads a secret from a file, creates a secret, or returns one from memory.
245 function get_secret()
246 if secret ~= nil then
249 local secret_file = io.open(secret_filename, "r")
250 if secret_file == nil then
251 local old_umask = sysstat.umask(63)
252 local temporary_filename = secret_filename .. ".tmp." .. tohex(rand.bytes(16))
253 local temporary_file = io.open(temporary_filename, "w")
254 if temporary_file == nil then
257 temporary_file:write(tohex(rand.bytes(32)))
258 temporary_file:close()
259 unistd.link(temporary_filename, secret_filename) -- Intentionally fails in the case that another process is doing the same.
260 unistd.unlink(temporary_filename)
261 sysstat.umask(old_umask)
262 secret_file = io.open(secret_filename, "r")
264 if secret_file == nil then
267 secret = secret_file:read()
269 if secret:len() ~= 64 then
275 -- Returns value of cookie if cookie is valid. Otherwise returns nil.
276 function validate_value(expected_field, cookie)
284 if cookie == nil or cookie:len() < 3 or cookie:sub(1, 1) == "|" then
288 for component in string.gmatch(cookie, "[^|]+") do
294 expiration = tonumber(component)
295 if expiration == nil then
308 if chmac == nil or chmac:len() == 0 then
312 -- Lua hashes strings, so these comparisons are time invariant.
313 if chmac ~= tohex(hmac.new(get_secret(), "sha256"):final(field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt)) then
317 if expiration == -1 or (expiration ~= 0 and expiration <= os.time()) then
321 if url_decode(field) ~= expected_field then
325 return url_decode(value)
328 function secure_value(field, value, expiration)
329 if value == nil or value:len() <= 0 then
334 local salt = tohex(rand.bytes(16))
335 value = url_encode(value)
336 field = url_encode(field)
337 authstr = field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt
338 authstr = authstr .. "|" .. tohex(hmac.new(get_secret(), "sha256"):final(authstr))
342 function set_cookie(cookie, value)
343 html("Set-Cookie: " .. cookie .. "=" .. value .. "; HttpOnly")
344 if http["https"] == "yes" or http["https"] == "on" or http["https"] == "1" then
350 function redirect_to(url)
351 html("Status: 302 Redirect\n")
352 html("Cache-Control: no-cache, no-store\n")
353 html("Location: " .. url .. "\n")
357 html("Status: 404 Not Found\n")
358 html("Cache-Control: no-cache, no-store\n\n")