libs/web: Added several sanity checks to avoid local privilege escalation
[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)
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 or not sane(sessionpath .. "/" .. id) then
61                 return
62         end
63         clean()
64         return luci.fs.readfile(sessionpath .. "/" .. id)
65 end
66
67
68 --- Check whether Session environment is sane.
69 -- @return Boolean status
70 function sane(file)
71         return luci.sys.process.info("uid")
72                         == luci.fs.stat(file or sessionpath, "uid")
73                 and luci.fs.stat(file or sessionpath, "mode")
74                         == (file and "rw-------" or "rwx------")
75 end
76
77
78 --- Write session data to a session file.
79 -- @param id    Session identifier
80 -- @param data  Session data
81 function write(id, data)
82         if not sane() then
83                 prepare()
84         end
85         luci.fs.writefile(sessionpath .. "/" .. id, data)
86         luci.fs.chmod(sessionpath .. "/" .. id, "a-rwx,u+rw")
87 end