]> gitweb.ps.run Git - ps-cgit/blob - filters/simple-authentication.lua
auth: lua string comparisons are time invariant
[ps-cgit] / filters / simple-authentication.lua
1 -- This script may be used with the auth-filter. Be sure to configure it as you wish.
2 --
3 -- Requirements:
4 --      luacrypto >= 0.3
5 --      <http://mkottman.github.io/luacrypto/>
6 --
7
8
9 --
10 --
11 -- Configure these variables for your settings.
12 --
13 --
14
15 local protected_repos = {
16         glouglou        = { laurent = true, jason = true },
17         qt              = { jason = true, bob = true }
18 }
19
20 local users = {
21         jason           = "secretpassword",
22         laurent         = "s3cr3t",
23         bob             = "ilikelua"
24 }
25
26 local secret = "BE SURE TO CUSTOMIZE THIS STRING TO SOMETHING BIG AND RANDOM"
27
28
29
30 --
31 --
32 -- Authentication functions follow below. Swap these out if you want different authentication semantics.
33 --
34 --
35
36 -- Sets HTTP cookie headers based on post and sets up redirection.
37 function authenticate_post()
38         local password = users[post["username"]]
39         local redirect = validate_value(post["redirect"])
40
41         if redirect == nil then
42                 not_found()
43                 return 0
44         end
45
46         redirect_to(redirect)
47
48         -- Lua hashes strings, so these comparisons are time invariant.
49         if password == nil or password ~= post["password"] then
50                 set_cookie("cgitauth", "")
51         else
52                 -- One week expiration time
53                 local username = secure_value(post["username"], os.time() + 604800)
54                 set_cookie("cgitauth", username)
55         end
56
57         html("\n")
58         return 0
59 end
60
61
62 -- Returns 1 if the cookie is valid and 0 if it is not.
63 function authenticate_cookie()
64         accepted_users = protected_repos[cgit["repo"]]
65         if accepted_users == nil then
66                 -- We return as valid if the repo is not protected.
67                 return 1
68         end
69
70         local username = validate_value(get_cookie(http["cookie"], "cgitauth"))
71         if username == nil or not accepted_users[username:lower()] then
72                 return 0
73         else
74                 return 1
75         end
76 end
77
78 -- Prints the html for the login form.
79 function body()
80         html("<h2>Authentication Required</h2>")
81         html("<form method='post' action='")
82         html_attr(cgit["login"])
83         html("'>")
84         html("<input type='hidden' name='redirect' value='")
85         html_attr(secure_value(cgit["url"], 0))
86         html("' />")
87         html("<table>")
88         html("<tr><td><label for='username'>Username:</label></td><td><input id='username' name='username' autofocus /></td></tr>")
89         html("<tr><td><label for='password'>Password:</label></td><td><input id='password' name='password' type='password' /></td></tr>")
90         html("<tr><td colspan='2'><input value='Login' type='submit' /></td></tr>")
91         html("</table></form>")
92
93         return 0
94 end
95
96
97
98 --
99 --
100 -- Wrapper around filter API, exposing the http table, the cgit table, and the post table to the above functions.
101 --
102 --
103
104 local actions = {}
105 actions["authenticate-post"] = authenticate_post
106 actions["authenticate-cookie"] = authenticate_cookie
107 actions["body"] = body
108
109 function filter_open(...)
110         action = actions[select(1, ...)]
111
112         http = {}
113         http["cookie"] = select(2, ...)
114         http["method"] = select(3, ...)
115         http["query"] = select(4, ...)
116         http["referer"] = select(5, ...)
117         http["path"] = select(6, ...)
118         http["host"] = select(7, ...)
119         http["https"] = select(8, ...)
120
121         cgit = {}
122         cgit["repo"] = select(9, ...)
123         cgit["page"] = select(10, ...)
124         cgit["url"] = select(11, ...)
125
126         cgit["login"] = ""
127         for _ in cgit["url"]:gfind("/") do
128                 cgit["login"] = cgit["login"] .. "../"
129         end
130         cgit["login"] = cgit["login"] .. "?p=login"
131
132 end
133
134 function filter_close()
135         return action()
136 end
137
138 function filter_write(str)
139         post = parse_qs(str)
140 end
141
142
143 --
144 --
145 -- Utility functions based on keplerproject/wsapi.
146 --
147 --
148
149 function url_decode(str)
150         if not str then
151                 return ""
152         end
153         str = string.gsub(str, "+", " ")
154         str = string.gsub(str, "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end)
155         str = string.gsub(str, "\r\n", "\n")
156         return str
157 end
158
159 function url_encode(str)
160         if not str then
161                 return ""
162         end
163         str = string.gsub(str, "\n", "\r\n")
164         str = string.gsub(str, "([^%w ])", function (c) return string.format("%%%02X", string.byte(c)) end)
165         str = string.gsub(str, " ", "+")
166         return str
167 end
168
169 function parse_qs(qs)
170         local tab = {}
171         for key, val in string.gmatch(qs, "([^&=]+)=([^&=]*)&?") do
172                 tab[url_decode(key)] = url_decode(val)
173         end
174         return tab
175 end
176
177 function get_cookie(cookies, name)
178         cookies = string.gsub(";" .. cookies .. ";", "%s*;%s*", ";")
179         return url_decode(string.match(cookies, ";" .. name .. "=(.-);"))
180 end
181
182
183 --
184 --
185 -- Cookie construction and validation helpers.
186 --
187 --
188
189 local crypto = require("crypto")
190
191 -- Returns value of cookie if cookie is valid. Otherwise returns nil.
192 function validate_value(cookie)
193         local i = 0
194         local value = ""
195         local expiration = 0
196         local salt = ""
197         local hmac = ""
198
199         if cookie == nil or cookie:len() < 3 or cookie:sub(1, 1) == "|" then
200                 return nil
201         end
202
203         for component in string.gmatch(cookie, "[^|]+") do
204                 if i == 0 then
205                         value = component
206                 elseif i == 1 then
207                         expiration = tonumber(component)
208                         if expiration == nil then
209                                 expiration = 0
210                         end
211                 elseif i == 2 then
212                         salt = component
213                 elseif i == 3 then
214                         hmac = component
215                 else
216                         break
217                 end
218                 i = i + 1
219         end
220
221         if hmac == nil or hmac:len() == 0 then
222                 return nil
223         end
224
225         -- Lua hashes strings, so these comparisons are time invariant.
226         if hmac ~= crypto.hmac.digest("sha1", value .. "|" .. tostring(expiration) .. "|" .. salt, secret) then
227                 return nil
228         end
229
230         if expiration ~= 0 and expiration <= os.time() then
231                 return nil
232         end
233
234         return url_decode(value)
235 end
236
237 function secure_value(value, expiration)
238         if value == nil or value:len() <= 0 then
239                 return ""
240         end
241
242         local authstr = ""
243         local salt = crypto.hex(crypto.rand.bytes(16))
244         value = url_encode(value)
245         authstr = value .. "|" .. tostring(expiration) .. "|" .. salt
246         authstr = authstr .. "|" .. crypto.hmac.digest("sha1", authstr, secret)
247         return authstr
248 end
249
250 function set_cookie(cookie, value)
251         html("Set-Cookie: " .. cookie .. "=" .. value .. "; HttpOnly")
252         if http["https"] == "yes" or http["https"] == "on" or http["https"] == "1" then
253                 html("; secure")
254         end
255         html("\n")
256 end
257
258 function redirect_to(url)
259         html("Status: 302 Redirect\n")
260         html("Cache-Control: no-cache, no-store\n")
261         html("Location: " .. url .. "\n")
262 end
263
264 function not_found()
265         html("Status: 404 Not Found\n")
266         html("Cache-Control: no-cache, no-store\n\n")
267 end