libs/web: Add additional sanity checks to session mechanism
[project/luci.git] / libs / web / luasrc / sauth.lua
1 --[[
2
3 Session authentication
4 (c) 2008 Steven Barth <steven@midlink.org>
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 $Id$
13
14 ]]--
15
16 --- LuCI session library.
17 module("luci.sauth", package.seeall)
18 require("luci.fs")
19 require("luci.util")
20 require("luci.config")
21
22
23 luci.config.sauth = luci.config.sauth or {}
24 sessionpath = luci.config.sauth.sessionpath
25 sessiontime = tonumber(luci.config.sauth.sessiontime)
26
27 --- Manually clean up expired sessions.
28 function clean()
29 local now = os.time()
30 local files = luci.fs.dir(sessionpath)
31
32 if not files then
33 return nil
34 end
35
36 for i, file in pairs(files) do
37 local fname = sessionpath .. "/" .. file
38 local stat = luci.fs.stat(fname)
39 if stat and stat.type == "regular" and stat.atime + sessiontime < now then
40 luci.fs.unlink(fname)
41 end
42 end
43 end
44
45 --- Prepare session storage by creating the session directory.
46 function prepare()
47 luci.fs.mkdir(sessionpath)
48 if not luci.fs.chmod(sessionpath, "a-rwx,u+rwx") then
49 error("Security Exception: Session path is not sane!")
50 end
51 end
52
53 --- Read a session and return its content.
54 -- @param id Session identifier
55 -- @return Session data
56 function read(id)
57 if not id or not sane() then
58 return
59 end
60 clean()
61 return luci.fs.readfile(sessionpath .. "/" .. id)
62 end
63
64
65 --- Check whether Session environment is sane.
66 -- @return Boolean status
67 function sane()
68 return luci.fs.stat(sessionpath, "mode") == "rwx------"
69 end
70
71
72 --- Write session data to a session file.
73 -- @param id Session identifier
74 -- @param data Session data
75 function write(id, data)
76 if not sane() then
77 prepare()
78 end
79 luci.fs.writefile(sessionpath .. "/" .. id, data)
80 luci.fs.chmod(sessionpath .. "/" .. id, "a-rwx,u+rw")
81 end