Added luci.sauth.kill, sanitize luci.sauth even more
[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.sys")
21 require("luci.config")
22
23
24 luci.config.sauth = luci.config.sauth or {}
25 sessionpath = luci.config.sauth.sessionpath
26 sessiontime = tonumber(luci.config.sauth.sessiontime) or 15 * 60
27
28 --- Manually clean up expired sessions.
29 function clean()
30 local now = os.time()
31 local files = luci.fs.dir(sessionpath)
32
33 if not files then
34 return nil
35 end
36
37 for i, file in pairs(files) do
38 local fname = sessionpath .. "/" .. file
39 local stat = luci.fs.stat(fname)
40 if stat and stat.type == "regular" and stat.atime + sessiontime < now then
41 luci.fs.unlink(fname)
42 end
43 end
44 end
45
46 --- Prepare session storage by creating the session directory.
47 function prepare()
48 luci.fs.mkdir(sessionpath)
49 luci.fs.chmod(sessionpath, "a-rwx,u+rwx")
50
51 if not sane() then
52 error("Security Exception: Session path is not sane!")
53 end
54 end
55
56 --- Read a session and return its content.
57 -- @param id Session identifier
58 -- @return Session data
59 function read(id)
60 if not id then
61 return
62 end
63 if not id:match("^%w+$") then
64 error("Session ID is not sane!")
65 end
66 clean()
67 if not sane(sessionpath .. "/" .. id) then
68 return
69 end
70 return luci.fs.readfile(sessionpath .. "/" .. id)
71 end
72
73
74 --- Check whether Session environment is sane.
75 -- @return Boolean status
76 function sane(file)
77 return luci.sys.process.info("uid")
78 == luci.fs.stat(file or sessionpath, "uid")
79 and luci.fs.stat(file or sessionpath, "mode")
80 == (file and "rw-------" or "rwx------")
81 end
82
83
84 --- Write session data to a session file.
85 -- @param id Session identifier
86 -- @param data Session data
87 function write(id, data)
88 if not sane() then
89 prepare()
90 end
91 if not id:match("^%w+$") then
92 error("Session ID is not sane!")
93 end
94 luci.fs.writefile(sessionpath .. "/" .. id, data)
95 luci.fs.chmod(sessionpath .. "/" .. id, "a-rwx,u+rw")
96 end
97
98
99 --- Kills a session
100 -- @param id Session identifier
101 function kill(id)
102 if not id:match("^%w+$") then
103 error("Session ID is not sane!")
104 end
105 luci.fs.unlink(sessionpath .. "/" .. id)
106 end