From 5a6382171da2c941e17d050cd357629f40541cb6 Mon Sep 17 00:00:00 2001 From: Jo-Philipp Wich Date: Tue, 6 Oct 2015 15:53:35 +0200 Subject: [PATCH] luci-base: add support for POST-only actions with CSRF token check Add the dispatcher infrastructure to restrict certain routes to POST requests only in conjunction with verification of CSRF tokens. This is the first step to get rid of the CSRF token in the url in favor to tokens embedded in forms. Signed-off-by: Jo-Philipp Wich --- modules/luci-base/luasrc/dispatcher.lua | 26 ++++++++++++++++++++++++++ modules/luci-base/luasrc/view/csrftoken.htm | 24 ++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 modules/luci-base/luasrc/view/csrftoken.htm diff --git a/modules/luci-base/luasrc/dispatcher.lua b/modules/luci-base/luasrc/dispatcher.lua index 8b8d1fa34..798e3e6ce 100644 --- a/modules/luci-base/luasrc/dispatcher.lua +++ b/modules/luci-base/luasrc/dispatcher.lua @@ -1,4 +1,5 @@ -- Copyright 2008 Steven Barth +-- Copyright 2008-2015 Jo-Philipp Wich -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" @@ -284,6 +285,7 @@ function dispatch(request) resource = luci.config.main.resourcebase; ifattr = function(...) return _ifattr(...) end; attr = function(...) return _ifattr(true, ...) end; + token = ctx.urltoken.stok; }, {__index=function(table, key) if key == "controller" then return build_url() @@ -378,6 +380,20 @@ function dispatch(request) end end + if c and type(c.target) == "table" and c.target.post == true then + if http.getenv("REQUEST_METHOD") ~= "POST" then + http.status(405, "Method Not Allowed") + http.header("Allow", "POST") + return + end + + if http.formvalue("token") ~= ctx.urltoken.stok then + http.status(403, "Forbidden") + luci.template.render("csrftoken") + return + end + end + if track.setgroup then sys.process.setgroup(track.setgroup) end @@ -703,6 +719,16 @@ function call(name, ...) return {type = "call", argv = {...}, name = name, target = _call} end +function post(name, ...) + return { + type = "call", + post = true, + argv = { ... }, + name = name, + target = _call + } +end + local _template = function(self, ...) require "luci.template".render(self.view) diff --git a/modules/luci-base/luasrc/view/csrftoken.htm b/modules/luci-base/luasrc/view/csrftoken.htm new file mode 100644 index 000000000..57ac03f3b --- /dev/null +++ b/modules/luci-base/luasrc/view/csrftoken.htm @@ -0,0 +1,24 @@ +<%# + Copyright 2015 Jo-Philipp Wich + Licensed to the public under the Apache License 2.0. +-%> + +<%+header%> + +

<%:Form token mismatch%>

+
+ +

<%:The submitted security token is invalid or already expired!%>

+ +

<%: + In order to prevent unauthorized access to the system, your request has + been blocked. Click "Continue »" below to return to the previous page. +%>

+ +
+ +

+ Continue » +

+ +<%+footer%> -- 2.11.0