From 23eb2fc3e45bdc3ec786344d2f95154fa49bf815 Mon Sep 17 00:00:00 2001 From: Eynix Date: Thu, 7 Jun 2018 11:56:34 +0200 Subject: [PATCH] replace hige by lustache --- debian/install | 3 +- debian/install.bak | 7 + helpers.lua | 8 +- helpers.lua.bak | 917 ++++++++++++++++++++++++++++++++++++++++++ hige.lua | 151 ------- init.lua | 2 +- init.lua.bak | 57 +++ lustache.lua | 29 ++ lustache/context.lua | 66 +++ lustache/renderer.lua | 388 ++++++++++++++++++ lustache/scanner.lua | 57 +++ 11 files changed, 1528 insertions(+), 157 deletions(-) create mode 100644 debian/install.bak create mode 100644 helpers.lua.bak delete mode 100644 hige.lua create mode 100644 init.lua.bak create mode 100644 lustache.lua create mode 100644 lustache/context.lua create mode 100644 lustache/renderer.lua create mode 100644 lustache/scanner.lua diff --git a/debian/install b/debian/install index 0f5bf11..1765782 100644 --- a/debian/install +++ b/debian/install @@ -2,6 +2,7 @@ init.lua /usr/share/ssowat access.lua /usr/share/ssowat helpers.lua /usr/share/ssowat config.lua /usr/share/ssowat -hige.lua /usr/share/ssowat +lustache.lua /usr/share/ssowat +lustache /usr/share/ssowat portal /usr/share/ssowat conf.json.example /etc/ssowat diff --git a/debian/install.bak b/debian/install.bak new file mode 100644 index 0000000..0f5bf11 --- /dev/null +++ b/debian/install.bak @@ -0,0 +1,7 @@ +init.lua /usr/share/ssowat +access.lua /usr/share/ssowat +helpers.lua /usr/share/ssowat +config.lua /usr/share/ssowat +hige.lua /usr/share/ssowat +portal /usr/share/ssowat +conf.json.example /etc/ssowat diff --git a/helpers.lua b/helpers.lua index ea7f67b..2d5e690 100644 --- a/helpers.lua +++ b/helpers.lua @@ -469,12 +469,12 @@ function serve(uri) -- Render as mustache if ext == "html" then local data = get_data_for(file) - local rendered = hige.render(read_file(script_path.."portal/header.ms"), data) - rendered = rendered..hige.render(content, data) - content = rendered..hige.render(read_file(script_path.."portal/footer.ms"), data) + local rendered = lustache:render(read_file(script_path.."portal/header.ms"), data) + rendered = rendered..lustache:render(content, data) + content = rendered..lustache:render(read_file(script_path.."portal/footer.ms"), data) elseif ext == "ms" then local data = get_data_for(file) - content = hige.render(content, data) + content = lustache:render(content, data) elseif ext == "json" then local data = get_data_for(file) content = json.encode(data) diff --git a/helpers.lua.bak b/helpers.lua.bak new file mode 100644 index 0000000..ea7f67b --- /dev/null +++ b/helpers.lua.bak @@ -0,0 +1,917 @@ +-- +-- helpers.lua +-- +-- This is a file called at every request by the `access.lua` file. It contains +-- a set of useful functions related to HTTP and LDAP. +-- + +module('helpers', package.seeall) + +local cache = ngx.shared.cache +local conf = config.get_config() + +-- Read a FS stored file +function read_file(file) + local f = io.open(file, "rb") + if not f then return false end + local content = f:read("*all") + f:close() + return content +end + + +-- Lua has no sugar :D +function is_in_table(t, v) + for key, value in ipairs(t) do + if value == v then return key end + end +end + + +-- Get the index of a value in a table +function index_of(t,val) + for k,v in ipairs(t) do + if v == val then return k end + end +end + + +-- Test whether a string starts with another +function string.starts(String, Start) + return string.sub(String, 1, string.len(Start)) == Start +end + + +-- Test whether a string ends with another +function string.ends(String, End) + return End=='' or string.sub(String, -string.len(End)) == End +end + + +-- Find a string by its translate key in the right language +function t(key) + if conf.lang and i18n[conf.lang] and i18n[conf.lang][key] then + return i18n[conf.lang][key] + else + return i18n[conf["default_language"]][key] or "" + end +end + + +-- Store a message in the flash shared table in order to display it at the +-- next response +function flash(wat, message) + if wat == "fail" + or wat == "win" + or wat == "info" + then + flashs[wat] = message + end +end + + +-- Hash a string using hmac_sha512, return a hexa string +function hmac_sha512(key, message) + local cache_key = key..":"..message + + if not cache:get(cache_key) then + -- lua ecosystem is a disaster and it was not possible to find a good + -- easily multiplatform integrable code for this + -- + -- this is really dirty and probably leak the key and the message in the process list + -- but if someone got there I guess we really have other problems so this is acceptable + -- and also this is way better than the previous situation + local pipe = io.popen("echo -n '" ..message:gsub("'", "'\\''").. "' | openssl sha512 -hmac '" ..key:gsub("'", "'\\''").. "'") + + -- openssl returns something like this: + -- root@yunohost:~# echo -n "qsd" | openssl sha512 -hmac "key" + -- (stdin)= f1c2b1658fe64c5a3d16459f2f4eea213e4181905c190235b060ab2a4e7d6a41c15ea2c246828537a1e32ae524b7a7ed309e6d296089194c3e3e3efb98c1fbe3 + -- + -- so we need to remove the "(stdin)= " at the beginning + local hash = pipe:read():sub(string.len("(stdin)= ") + 1) + pipe:close() + + cache:set(cache_key, hash, conf["session_timeout"]) + return hash + else + return cache:get(cache_key) + end +end + + +-- Convert a table of arguments to an URI string +function uri_args_string(args) + if not args then + args = ngx.req.get_uri_args() + end + String = "?" + for k,v in pairs(args) do + String = String..tostring(k).."="..tostring(v).."&" + end + return string.sub(String, 1, string.len(String) - 1) +end + + +-- Set the Cross-Domain-Authentication key for a specific user +function set_cda_key() + local cda_key = random_string() + cache:set("CDA|"..cda_key, authUser, 10) + return cda_key +end + + +-- Compute and set the authentication cookie +-- +-- Sets 3 cookies containing: +-- * The username +-- * The expiration time +-- * A hash of those information along with the client IP address and a unique +-- session key +-- +-- It enables the SSO to quickly retrieve the username and the session +-- expiration time, and to prove their authenticity to avoid session hijacking. +-- +function set_auth_cookie(user, domain) + local maxAge = conf["session_max_timeout"] + local expire = ngx.req.start_time() + maxAge + local session_key = cache:get("session_"..user) + if not session_key then + session_key = random_string() + cache:add("session_"..user, session_key, conf["session_max_timeout"]) + end + local hash = hmac_sha512(srvkey, + user.. + "|"..expire.. + "|"..session_key) + local cookie_str = "; Domain=."..domain.. + "; Path=/".. + "; Expires="..os.date("%a, %d %b %Y %X UTC;", expire).. + "; Secure" + + ngx.header["Set-Cookie"] = { + "SSOwAuthUser="..user..cookie_str, + "SSOwAuthHash="..hash..cookie_str, + "SSOwAuthExpire="..expire..cookie_str + } +end + + +-- Expires the 3 session cookies +function delete_cookie() + conf = config.get_config() + + local expired_time = "Thu, 01 Jan 1970 00:00:00 UTC;" + for _, domain in ipairs(conf["domains"]) do + local cookie_str = "; Domain=."..domain.. + "; Path=/".. + "; Expires="..expired_time.. + "; Secure" + ngx.header["Set-Cookie"] = { + "SSOwAuthUser="..cookie_str, + "SSOwAuthHash="..cookie_str, + "SSOwAuthExpire="..cookie_str + } + end +end + + +-- Expires the redirection cookie +function delete_redirect_cookie() + local expired_time = "Thu, 01 Jan 1970 00:00:00 UTC;" + local cookie_str = "; Path="..conf["portal_path"].. + "; Expires="..expired_time.. + "; Secure" + ngx.header["Set-Cookie"] = "SSOwAuthRedirect=;" ..cookie_str +end + + +-- Validate authentification +-- +-- Check if the session cookies are set, and rehash server + client information +-- to match the session hash. +-- +function is_logged_in() + local expireTime = ngx.var.cookie_SSOwAuthExpire + local user = ngx.var.cookie_SSOwAuthUser + local authHash = ngx.var.cookie_SSOwAuthHash + + if expireTime and expireTime ~= "" + and authHash and authHash ~= "" + and user and user ~= "" + then + -- Check expire time + if (ngx.req.start_time() <= tonumber(expireTime)) then + -- Check hash + local session_key = cache:get("session_"..user) + if session_key and session_key ~= "" then + -- Check cache + if cache:get(user.."-password") then + authUser = user + local hash = hmac_sha512(srvkey, + authUser.. + "|"..expireTime.. + "|"..session_key) + return hash == authHash + end + end + end + end + + return false +end + + +-- Check whether a user is allowed to access a URL using the `users` directive +-- of the configuration file +function has_access(user, url) + user = user or authUser + url = url or ngx.var.host..ngx.var.uri + + if not conf["users"][user] then + conf = config.get_config() + end + + -- If there are no `users` directive, or if the user has no ACL set, he can + -- access the URL by default + if not conf["users"] or not conf["users"][user] then + return true + end + + -- Loop through user's ACLs and return if the URL is authorized. + for u, _ in pairs(conf["users"][user]) do + + -- Replace the original domain by a local one if you are connected from + -- a non-global domain name. + if ngx.var.host == conf["local_portal_domain"] then + u = string.gsub(u, conf["original_portal_domain"], conf["local_portal_domain"]) + end + + if string.starts(url, string.sub(u, 1, -2)) then return true end + end + return false +end + + +-- Authenticate a user against the LDAP database using a username or an email +-- address. +-- Reminder: conf["ldap_identifier"] is "uid" by default +function authenticate(user, password) + conf = config.get_config() + + -- Try to find the username from an email address by openning an anonymous + -- LDAP connection and check if the email address exists + if conf["allow_mail_authentication"] and string.find(user, "@") then + ldap = lualdap.open_simple(conf["ldap_host"]) + for dn, attribs in ldap:search { + base = conf["ldap_group"], + scope = "onelevel", + sizelimit = 1, + filter = "(mail="..user..")", + attrs = {conf["ldap_identifier"]} + } do + if attribs[conf["ldap_identifier"]] then + ngx.log(ngx.NOTICE, "Use email: "..user) + user = attribs[conf["ldap_identifier"]] + else + ngx.log(ngx.ERR, "Unknown email: "..user) + return false + end + end + ldap:close() + end + + -- Now that we have a username, we can try connecting to the LDAP base. + connected = lualdap.open_simple ( + conf["ldap_host"], + conf["ldap_identifier"].."=".. user ..","..conf["ldap_group"], + password + ) + + cache:flush_expired() + + -- If we are connected, we can retrieve the password and put it in the + -- cache shared table in order to eventually reuse it later when updating + -- profile information or just passing credentials to an application. + if connected then + ensure_user_password_uses_strong_hash(connected, user, password) + cache:add(user.."-password", password, conf["session_timeout"]) + ngx.log(ngx.NOTICE, "Connected as: "..user) + return user + + -- Else, the username/email or the password is wrong + else + ngx.log(ngx.ERR, "Connection failed for: "..user) + return false + end +end + +function delete_user_info_cache(user) + cache:delete(user.."-"..conf["ldap_identifier"]) + local i = 2 + while cache:get(user.."-mail|"..i) do + cache:delete(user.."-mail|"..i) + i = i + 1 + end + local i = 2 + while cache:get(user.."-maildrop|"..i) do + cache:delete(user.."-maildrop|"..i) + i = i + 1 + end +end + +-- Set the authentication headers in order to pass credentials to the +-- application underneath. +function set_headers(user) + + -- We definitely don't want to pass credentials on a non-encrypted + -- connection. + if ngx.var.scheme ~= "https" then + return redirect("https://"..ngx.var.host..ngx.var.uri..uri_args_string()) + end + + local user = user or authUser + + -- If the password is not in cache or if the cache has expired, ask for + -- logging. + if not cache:get(user.."-password") then + flash("info", t("please_login")) + local back_url = ngx.var.scheme .. "://" .. ngx.var.host .. ngx.var.uri .. uri_args_string() + return redirect(conf.portal_url.."?r="..ngx.encode_base64(back_url)) + end + + -- If the user information is not in cache, open an LDAP connection and + -- fetch it. + if not cache:get(user.."-"..conf["ldap_identifier"]) then + ldap = lualdap.open_simple( + conf["ldap_host"], + conf["ldap_identifier"].."=".. user ..","..conf["ldap_group"], + cache:get(user.."-password") + ) + ngx.log(ngx.NOTICE, "Reloading LDAP values for: "..user) + for dn, attribs in ldap:search { + base = conf["ldap_identifier"].."=".. user ..","..conf["ldap_group"], + scope = "base", + sizelimit = 1, + attrs = conf["ldap_attributes"] + } do + for k,v in pairs(attribs) do + if type(v) == "table" then + for k2,v2 in ipairs(v) do + if k2 == 1 then cache:set(user.."-"..k, v2, conf["session_timeout"]) end + cache:set(user.."-"..k.."|"..k2, v2, conf["session_max_timeout"]) + end + else + cache:set(user.."-"..k, v, conf["session_timeout"]) + end + end + end + else + -- Else, just revalidate session for another day by default + password = cache:get(user.."-password") + cache:set(user.."-password", password, conf["session_timeout"]) + end + + -- Set `authorization` header to enable HTTP authentification + ngx.req.set_header("Authorization", "Basic "..ngx.encode_base64( + user..":"..cache:get(user.."-password") + )) + + -- Set optionnal additional headers (typically to pass email address) + for k, v in pairs(conf["additional_headers"]) do + ngx.req.set_header(k, cache:get(user.."-"..v)) + end + +end + + +-- Summarize email, aliases and forwards in a table for a specific user +function get_mails(user) + local mails = { mail = "", mailalias = {}, maildrop = {} } + + -- default mail + mails["mail"] = cache:get(user.."-mail") + + -- mail aliases + if cache:get(user.."-mail|2") then + local i = 2 + while cache:get(user.."-mail|"..i) do + table.insert(mails["mailalias"], cache:get(user.."-mail|"..i)) + i = i + 1 + end + end + + -- mail forward + if cache:get(user.."-maildrop|2") then + local i = 2 + while cache:get(user.."-maildrop|"..i) do + table.insert(mails["maildrop"], cache:get(user.."-maildrop|"..i)) + i = i + 1 + end + end + return mails +end + + +-- Yo dawg, this enables SSOwat to serve files in HTTP in an HTTP server +-- Much reliable, very solid. +-- +-- Takes an URI, and returns file content with the proper HTTP headers. +-- It is used to render the SSOwat portal *only*. +function serve(uri) + rel_path = string.gsub(uri, conf["portal_path"], "/") + + -- Load login.html as index + if rel_path == "/" then + if is_logged_in() then + rel_path = "/info.html" + else + rel_path = "/login.html" + end + end + + -- Access to directory root: forbidden + if string.ends(rel_path, "/") then + return ngx.exit(ngx.HTTP_FORBIDDEN) + end + + -- Try to get file content + local content = read_file(script_path.."portal"..rel_path) + if not content then + return ngx.exit(ngx.HTTP_NOT_FOUND) + end + + -- Extract file extension + _, file, ext = string.match(rel_path, "(.-)([^\\/]-%.?([^%.\\/]*))$") + + -- Associate to MIME type + mime_types = { + html = "text/html", + ms = "text/html", + js = "text/javascript", + map = "text/javascript", + css = "text/css", + gif = "image/gif", + jpg = "image/jpeg", + png = "image/png", + svg = "image/svg+xml", + ico = "image/vnd.microsoft.icon", + woff = "application/x-font-woff", + json = "application/json" + } + + -- Set Content-Type + if mime_types[ext] then + ngx.header["Content-Type"] = mime_types[ext] + else + ngx.header["Content-Type"] = "text/plain" + end + + -- Render as mustache + if ext == "html" then + local data = get_data_for(file) + local rendered = hige.render(read_file(script_path.."portal/header.ms"), data) + rendered = rendered..hige.render(content, data) + content = rendered..hige.render(read_file(script_path.."portal/footer.ms"), data) + elseif ext == "ms" then + local data = get_data_for(file) + content = hige.render(content, data) + elseif ext == "json" then + local data = get_data_for(file) + content = json.encode(data) + end + + -- Reset flash messages + flashs["fail"] = nil + flashs["win"] = nil + flashs["info"] = nil + + -- Ain't nobody got time for cache + ngx.header["Cache-Control"] = "no-cache" + + -- Print file content + ngx.say(content) + + -- Return 200 :-) + return ngx.exit(ngx.HTTP_OK) +end + + +-- Simple controller that computes a data table to populate a specific view. +-- The resulting data table typically contains the user information, the page +-- title, the flash notifications' content and the translated strings. +function get_data_for(view) + local user = authUser + conf = config.get_config() + + -- For the login page we only need the page title + if view == "login.html" then + data = { + title = t("login"), + connected = false + } + + -- For those views, we may need user information + elseif view == "info.html" + or view == "edit.html" + or view == "password.html" + or view == "ynhpanel.json" then + + -- Invalidate cache before loading these views. + -- Needed if the LDAP db is changed outside ssowat (from the cli for example). + -- Not doing it for ynhpanel.json only for performance reasons, + -- so the panel could show wrong first name, last name or main email address + if view ~= "ynhpanel.json" then + delete_user_info_cache(user) + end + + -- Be sure cache is loaded + set_headers(user) + + local mails = get_mails(user) + data = { + connected = true, + portal_url = conf.portal_url, + uid = user, + cn = cache:get(user.."-cn"), + sn = cache:get(user.."-sn"), + givenName = cache:get(user.."-givenName"), + mail = mails["mail"], + mailalias = mails["mailalias"], + maildrop = mails["maildrop"], + app = {} + } + + local sorted_apps = {} + + -- Add user's accessible URLs using the ACLs. + -- It is typically used to build the app list. + for url, name in pairs(conf["users"][user]) do + + if ngx.var.host == conf["local_portal_domain"] then + url = string.gsub(url, conf["original_portal_domain"], conf["local_portal_domain"]) + end + table.insert(sorted_apps, name) + table.sort(sorted_apps) + table.insert(data["app"], index_of(sorted_apps, name), { url = url, name = name }) + end + end + + -- Pass all the translated strings to the view (to use with t_) + for k, v in pairs(i18n[conf["default_language"]]) do + data["t_"..k] = (i18n[conf.lang] and i18n[conf.lang][k]) or v + end + + -- Pass flash notification content + data['flash_fail'] = {flashs["fail"]} + data['flash_win'] = {flashs["win"] } + data['flash_info'] = {flashs["info"]} + + return data +end + +-- this function is launched after a successful login +-- it checked if the user password is stored using the most secure hashing +-- algorithm available +-- if it's not the case, it migrates the password to this new hash algorithm +function ensure_user_password_uses_strong_hash(ldap, user, password) + local current_hashed_password = nil + + for dn, attrs in ldap:search { + base = "ou=users,dc=yunohost,dc=org", + scope = "onelevel", + sizelimit = 1, + filter = "(uid="..user..")", + attrs = {"userPassword"} + } do + current_hashed_password = attrs["userPassword"]:sub(0, 10) + end + + -- if the password is not hashed using sha-512, which is the strongest + -- available hash rehash it using that + -- Here "{CRYPT}" means "uses linux auth system" + -- "6" means "uses sha-512", any lower number mean a less strong algo (1 == md5) + if current_hashed_password:sub(0, 10) ~= "{CRYPT}$6$" then + local dn = conf["ldap_identifier"].."="..user..","..conf["ldap_group"] + local hashed_password = hash_password(password) + ldap:modify(dn, {'=', userPassword = hashed_password }) + end +end + +-- Compute the user modification POST request +-- It has to update cached information and edit the LDAP user entry +-- according to the changes detected. +function edit_user() + conf = config.get_config() + + -- We need these calls since we are in a POST request + ngx.req.read_body() + local args = ngx.req.get_post_args() + + -- Ensure that user is logged in and has passed information + -- before continuing. + if is_logged_in() and args + then + + -- Set HTTP status to 201 + ngx.status = ngx.HTTP_CREATED + local user = authUser + + -- In case of a password modification + -- TODO: split this into a new function + if string.ends(ngx.var.uri, "password.html") then + + -- Check current password against the cached one + if args.currentpassword + and args.currentpassword == cache:get(user.."-password") + then + -- and the new password against the confirmation field's content + if args.newpassword == args.confirm then + local dn = conf["ldap_identifier"].."="..user..","..conf["ldap_group"] + + -- Open the LDAP connection + local ldap = lualdap.open_simple(conf["ldap_host"], dn, args.currentpassword) + + local password = hash_password(args.newpassword) + + -- Modify the LDAP information + if ldap:modify(dn, {'=', userPassword = password }) then + flash("win", t("password_changed")) + + -- Reset the password cache + cache:set(user.."-password", args.newpassword, conf["session_timeout"]) + return redirect(conf.portal_url.."info.html") + else + flash("fail", t("password_changed_error")) + end + else + flash("fail", t("password_not_match")) + end + else + flash("fail", t("wrong_current_password")) + end + return redirect(conf.portal_url.."password.html") + + + -- In case of profile modification + -- TODO: split this into a new function + elseif string.ends(ngx.var.uri, "edit.html") then + + -- Check that needed arguments exist + if args.givenName and args.sn and args.mail then + + -- Unstack mailaliases + local mailalias = {} + if args["mailalias[]"] then + if type(args["mailalias[]"]) == "string" then + args["mailalias[]"] = {args["mailalias[]"]} + end + mailalias = args["mailalias[]"] + end + + -- Unstack mail forwards + local maildrop = {} + if args["maildrop[]"] then + if type(args["maildrop[]"]) == "string" then + args["maildrop[]"] = {args["maildrop[]"]} + end + maildrop = args["maildrop[]"] + end + + -- Limit domains per user: + -- This ensures that a user already has an email address or an + -- aliases that ends with a specific domain to claim new aliases + -- on this domain. + -- + -- I.E. You need to have xxx@domain.org to claim a + -- yyy@domain.org alias. + -- + local domains = {} + local ldap = lualdap.open_simple(conf["ldap_host"]) + for dn, attribs in ldap:search { + base = conf["ldap_group"], + scope = "onelevel", + sizelimit = 1, + filter = "(uid="..user..")", + attrs = {"mail"} + } do + -- Construct proper emails array + local mail_list = {} + local mail_attr = attribs["mail"] + if type(mail_attr) == "string" then + mail_list = { mail_attr } + elseif type(mail_attr) == "table" then + mail_list = mail_attr + end + + -- Filter configuration's domain list to keep only + -- "allowed" domains + for _, domain in ipairs(conf["domains"]) do + for k, mail in ipairs(mail_list) do + if string.ends(mail, "@"..domain) then + if not is_in_table(domains, domain) then + table.insert(domains, domain) + end + end + end + end + end + ldap:close() + + local rex = require "rex_pcre" + local rex_flags = rex.flags() + local mail_re = rex.new([[^[\w\.\-+%]+@([^\W_A-Z]+([\-]*[^\W_A-Z]+)*\.)+([^\W\d_]{2,})$]], rex_flags.UTF8 + rex_flags.UCP) + + local mails = {} + + -- Build an LDAP filter so that we can ensure that email + -- addresses are used only once. + local filter = "(|" + table.insert(mailalias, 1, args.mail) + + -- Loop through all the aliases + for k, mail in ipairs(mailalias) do + if mail ~= "" then + -- Check the mail pattern + if not mail_re:match(mail) then + flash("fail", t("invalid_mail")..": "..mail) + return redirect(conf.portal_url.."edit.html") + + -- Check that the domain is known and allowed + else + local domain_valid = false + for _, domain in ipairs(domains) do + if string.ends(mail, "@"..domain) then + domain_valid = true + break + end + end + if domain_valid then + table.insert(mails, mail) + filter = filter.."(mail="..mail..")" + else + flash("fail", t("invalid_domain").." "..mail) + return redirect(conf.portal_url.."edit.html") + end + end + end + end + + -- filter should look like "(|(mail=my@mail.tld)(mail=my@mail2.tld))" + filter = filter..")" + + + -- For email forwards, we only need to check that they look + -- like actual emails + local drops = {} + for k, mail in ipairs(maildrop) do + if mail ~= "" then + if not mail_re:match(mail) then + flash("fail", t("invalid_mailforward")..": "..mail) + return redirect(conf.portal_url.."edit.html") + end + table.insert(drops, mail) + end + end + table.insert(drops, 1, user) + + + -- We now have a list of validated emails and forwards. + -- We need to check if there is a user with a claimed email + -- already before writing modifications to the LDAP. + local dn = conf["ldap_identifier"].."="..user..","..conf["ldap_group"] + local ldap = lualdap.open_simple(conf["ldap_host"], dn, cache:get(user.."-password")) + local cn = args.givenName.." "..args.sn + + for dn, attribs in ldap:search { + base = conf["ldap_group"], + scope = "onelevel", + filter = filter, + attrs = {conf["ldap_identifier"], "mail"} + } do + -- Another user with one of these emails has been found. + if attribs[conf["ldap_identifier"]] and attribs[conf["ldap_identifier"]] ~= user then + -- Construct proper emails array + local mail_list = {} + local mail_attr = attribs["mail"] + if type(mail_attr) == "string" then + mail_list = { mail_attr } + elseif type(mail_attr) == "table" then + mail_list = mail_attr + end + + for _, mail in ipairs(mail_list) do + if is_in_table(mails, mail) then + flash("fail", t("mail_already_used").." "..mail) + end + end + return redirect(conf.portal_url.."edit.html") + end + end + + -- No problem so far, we can write modifications to the LDAP + if ldap:modify(dn, {'=', cn = cn, + givenName = args.givenName, + sn = args.sn, + mail = mails, + maildrop = drops }) + then + delete_user_info_cache(user) + -- Ugly trick to force cache reloading + set_headers(user) + flash("win", t("information_updated")) + return redirect(conf.portal_url.."info.html") + + else + flash("fail", t("user_saving_fail")) + end + else + flash("fail", t("missing_required_fields")) + end + return redirect(conf.portal_url.."edit.html") + end + end +end + +-- hash the user password using sha-512 and using {CRYPT} to uses linux auth system +-- because ldap doesn't support anything stronger than sha1 +function hash_password(password) + -- TODO is the password checked by regex? we don't want to + -- allow shell injection + local mkpasswd = io.popen("mkpasswd --method=sha-512 '" ..password:gsub("'", "'\\''").."'") + local hashed_password = "{CRYPT}"..mkpasswd:read() + mkpasswd:close() + return hashed_password +end + +-- Compute the user login POST request +-- It authenticates the user against the LDAP base then redirects to the portal +function login() + + -- We need these calls since we are in a POST request + ngx.req.read_body() + local args = ngx.req.get_post_args() + local uri_args = ngx.req.get_uri_args() + + args.user = string.lower(args.user) + + local user = authenticate(args.user, args.password) + if user then + ngx.status = ngx.HTTP_CREATED + set_auth_cookie(user, ngx.var.host) + else + ngx.status = ngx.HTTP_UNAUTHORIZED + flash("fail", t("wrong_username_password")) + end + + -- Forward the `r` URI argument if it exists to redirect + -- the user properly after a successful login. + if uri_args.r then + return redirect(conf.portal_url.."?r="..uri_args.r) + else + return redirect(conf.portal_url) + end +end + + +-- Compute the user logout request +-- It deletes session cached information to invalidate client side cookie +-- information. +function logout() + + -- We need this call since we are in a POST request + local args = ngx.req.get_uri_args() + + -- Delete user cookie if logged in (that should always be the case) + if is_logged_in() then + delete_cookie() + cache:delete("session_"..authUser) + cache:delete(authUser.."-"..conf["ldap_identifier"]) -- Ugly trick to reload cache + flash("info", t("logged_out")) + end + + -- Redirect to portal anyway + return redirect(conf.portal_url) +end + + +-- Set cookie and redirect (needed to properly set cookie) +function redirect(url) + ngx.log(ngx.NOTICE, "Redirect to: "..url) + return ngx.redirect(url) +end + + +-- Set cookie and go on with the response (needed to properly set cookie) +function pass() + delete_redirect_cookie() + + -- When we are in the SSOwat portal, we need a default `content-type` + if string.ends(ngx.var.uri, "/") + or string.ends(ngx.var.uri, ".html") + or string.ends(ngx.var.uri, ".htm") + then + ngx.header["Content-Type"] = "text/html" + end + + return +end diff --git a/hige.lua b/hige.lua deleted file mode 100644 index 4bfa40a..0000000 --- a/hige.lua +++ /dev/null @@ -1,151 +0,0 @@ -module('hige', package.seeall) - -local tags = { open = '{{', close = '}}' } -local r = {} - -local function merge_environment(...) - local numargs, out = select('#', ...), {} - for i = 1, numargs do - local t = select(i, ...) - if type(t) == 'table' then - for k, v in pairs(t) do - if (type(v) == 'function') then - out[k] = setfenv(v, setmetatable(out, { - __index = getmetatable(getfenv()).__index - })) - else - out[k] = v - end - end - end - end - return out -end - -local function escape(str) - return str:gsub('[&"<>]', function(c) - if c == '&' then return '&' - elseif c == '"' then return '\"' - elseif c == '\\' then return '\\\\' - elseif c == '<' then return '<' - elseif c == '>' then return '>' - else return c end - end) -end - -local function find(name, context) - local value = context[name] - if value == nil then - return '' - elseif type(value) == 'function' then - return merge_environment(context, value)[name]() - else - return value - end -end - -local operators = { - -- comments - ['!'] = function(state, outer, name, context) - return state.tag_open .. '!' .. outer .. state.tag_close - end, - -- the triple hige is unescaped - ['{'] = function(state, outer, name, context) - return find(name, context) - end, - -- render partial - ['<'] = function(state, outer, name, context) - return r.partial(state, name, context) - end, - -- set new delimiters - ['='] = function(state, outer, name, context) - -- FIXME! - error('setting new delimiters in the template is currently broken') - --[[ - return name:gsub('^(.-)%s+(.-)$', function(open, close) - state.tag_open, state.tag_close = open, close - return '' - end) - ]] - end, -} - -function r.partial(state, name, context) - local target_mt = setmetatable(context, { __index = state.lookup_env }) - local target_name = setfenv(loadstring('return ' .. name), target_mt)() - local target_type = type(target_name) - - if target_type == 'string' then - return r.render(state, target_name, context) - elseif target_type == 'table' then - local target_template = setfenv(loadstring('return '..name..'_template'), target_mt)() - return r.render(state, target_template, merge_environment(target_name, context)) - else - error('unknown partial type "' .. tostring(name) .. '"') - end -end - -function r.tags(state, template, context) - local tag_path = state.tag_open..'([=!<{]?)(%s*([^#/]-)%s*)[=}]?%s*'..state.tag_close - - return template:gsub(tag_path, function(op, outer, name) - if operators[op] ~= nil then - return tostring(operators[op](state, outer, name, context)) - else - return escape(tostring((function() - if name ~= '.' then - return find(name, context) - else - return context - end - end)())) - end - end) -end - -function r.section(state, template, context) - for section_name in template:gmatch(state.tag_open..'#%s*([^#/]-)%s*'..state.tag_close) do - local found, value = context[section_name] ~= nil, find(section_name, context) - local section_path = state.tag_open..'#'..section_name..state.tag_close..'%s*(.*)'..state.tag_open..'/'..section_name..state.tag_close..'%s*' - - template = template:gsub(section_path, function(inner) - if found == false then return '' end - - if value == true then - return r.render(state, inner, context) - elseif type(value) == 'table' then - local output = {} - for _, row in pairs(value) do - local new_context - if type(row) == 'table' then - new_context = merge_environment(context, row) - else - new_context = row - end - table.insert(output, (r.render(state, inner, new_context))) - end - return table.concat(output) - else - return '' - end - end) - end - - return template -end - -function r.render(state, template, context) - return r.tags(state, r.section(state, template, context), context) -end - -function render(template, context, env) - if template:find(tags.open) == nil then return template end - - local state = { - lookup_env = env or _G, - tag_open = tags.open, - tag_close = tags.close, - } - - return r.render(state, template, context or {}) -end diff --git a/init.lua b/init.lua index b0ea838..c9bf90a 100644 --- a/init.lua +++ b/init.lua @@ -18,7 +18,7 @@ package.path = package.path .. ";"..script_path.."?.lua" local json = require "json" local lualdap = require "lualdap" local math = require "math" -local hige = require "hige" +local lustache = require "lustache" local lfs = require "lfs" local socket = require "socket" local config = require "config" diff --git a/init.lua.bak b/init.lua.bak new file mode 100644 index 0000000..b0ea838 --- /dev/null +++ b/init.lua.bak @@ -0,0 +1,57 @@ +-- +-- init.lua +-- +-- This is the initialization file of SSOwat. It is called once at the Nginx +-- server's start. +-- Consequently, all the variables declared (along with libraries and +-- translations) in this file will be *persistent* from one HTTP request to +-- another. +-- + +-- Remove prepending '@' & trailing 'init.lua' +script_path = string.sub(debug.getinfo(1).source, 2, -9) + +-- Include local libs in package.path +package.path = package.path .. ";"..script_path.."?.lua" + +-- Load libraries +local json = require "json" +local lualdap = require "lualdap" +local math = require "math" +local hige = require "hige" +local lfs = require "lfs" +local socket = require "socket" +local config = require "config" + +-- Persistent shared table +flashs = {} +i18n = {} + +-- convert a string to a hex +function tohex(str) + return (str:gsub('.', function (c) + return string.format('%02X', string.byte(c)) + end)) +end + +-- Efficient function to get a random string +function random_string() + local random_bytes = io.open("/dev/urandom"):read(64); + return tohex(random_bytes); +end + +-- Load translations in the "i18n" above table +local locale_dir = script_path.."portal/locales/" +for file in lfs.dir(locale_dir) do + if string.sub(file, -4) == "json" then + local lang = string.sub(file, 1, 2) + local locale_file = io.open(locale_dir..file, "r") + i18n[lang] = json.decode(locale_file:read("*all")) + end +end + +-- Path of the configuration +conf_path = "/etc/ssowat/conf.json" + +-- You should see that in your Nginx error logs by default +ngx.log(ngx.INFO, "SSOwat ready") diff --git a/lustache.lua b/lustache.lua new file mode 100644 index 0000000..94d8a25 --- /dev/null +++ b/lustache.lua @@ -0,0 +1,29 @@ +-- lustache: Lua mustache template parsing. +-- Copyright 2013 Olivine Labs, LLC +-- MIT Licensed. + +module('lustache', package.seeall) + +local string_gmatch = string.gmatch + +function string.split(str, sep) + local out = {} + for m in string_gmatch(str, "[^"..sep.."]+") do out[#out+1] = m end + return out +end + +local lustache = { + name = "lustache", + version = "1.3.1-0", + renderer = require("lustache.renderer"):new(), +} + +return setmetatable(lustache, { + __index = function(self, idx) + if self.renderer[idx] then return self.renderer[idx] end + end, + __newindex = function(self, idx, val) + if idx == "partials" then self.renderer.partials = val end + if idx == "tags" then self.renderer.tags = val end + end +}) diff --git a/lustache/context.lua b/lustache/context.lua new file mode 100644 index 0000000..f8ec1a5 --- /dev/null +++ b/lustache/context.lua @@ -0,0 +1,66 @@ +local string_find, string_split, tostring, type = + string.find, string.split, tostring, type + +local context = {} +context.__index = context + +function context:clear_cache() + self.cache = {} +end + +function context:push(view) + return self:new(view, self) +end + +function context:lookup(name) + local value = self.cache[name] + + if not value then + if name == "." then + value = self.view + else + local context = self + + while context do + if string_find(name, ".") > 0 then + local names = string_split(name, ".") + local i = 0 + + value = context.view + + if(type(value)) == "number" then + value = tostring(value) + end + + while value and i < #names do + i = i + 1 + value = value[names[i]] + end + else + value = context.view[name] + end + + if value then + break + end + + context = context.parent + end + end + + self.cache[name] = value + end + + return value +end + +function context:new(view, parent) + local out = { + view = view, + parent = parent, + cache = {}, + } + return setmetatable(out, context) +end + +return context diff --git a/lustache/renderer.lua b/lustache/renderer.lua new file mode 100644 index 0000000..94e0cfb --- /dev/null +++ b/lustache/renderer.lua @@ -0,0 +1,388 @@ +local Scanner = require "lustache.scanner" +local Context = require "lustache.context" + +local error, ipairs, loadstring, pairs, setmetatable, tostring, type = + error, ipairs, loadstring, pairs, setmetatable, tostring, type +local math_floor, math_max, string_find, string_gsub, string_split, string_sub, table_concat, table_insert, table_remove = + math.floor, math.max, string.find, string.gsub, string.split, string.sub, table.concat, table.insert, table.remove + +local patterns = { + white = "%s*", + space = "%s+", + nonSpace = "%S", + eq = "%s*=", + curly = "%s*}", + tag = "[#\\^/>{&=!]" +} + +local html_escape_characters = { + ["&"] = "&", + ["<"] = "<", + [">"] = ">", + ['"'] = """, + ["'"] = "'", + ["/"] = "/" +} + +local function is_array(array) + if type(array) ~= "table" then return false end + local max, n = 0, 0 + for k, _ in pairs(array) do + if not (type(k) == "number" and k > 0 and math_floor(k) == k) then + return false + end + max = math_max(max, k) + n = n + 1 + end + return n == max +end + +-- Low-level function that compiles the given `tokens` into a +-- function that accepts two arguments: a Context and a +-- Renderer. + +local function compile_tokens(tokens, originalTemplate) + local subs = {} + + local function subrender(i, tokens) + if not subs[i] then + local fn = compile_tokens(tokens, originalTemplate) + subs[i] = function(ctx, rnd) return fn(ctx, rnd) end + end + return subs[i] + end + + local function render(ctx, rnd) + local buf = {} + local token, section + for i, token in ipairs(tokens) do + local t = token.type + buf[#buf+1] = + t == "#" and rnd:_section( + token, ctx, subrender(i, token.tokens), originalTemplate + ) or + t == "^" and rnd:_inverted( + token.value, ctx, subrender(i, token.tokens) + ) or + t == ">" and rnd:_partial(token.value, ctx, originalTemplate) or + (t == "{" or t == "&") and rnd:_name(token.value, ctx, false) or + t == "name" and rnd:_name(token.value, ctx, true) or + t == "text" and token.value or "" + end + return table_concat(buf) + end + return render +end + +local function escape_tags(tags) + + return { + string_gsub(tags[1], "%%", "%%%%").."%s*", + "%s*"..string_gsub(tags[2], "%%", "%%%%"), + } +end + +local function nest_tokens(tokens) + local tree = {} + local collector = tree + local sections = {} + local token, section + + for i,token in ipairs(tokens) do + if token.type == "#" or token.type == "^" then + token.tokens = {} + sections[#sections+1] = token + collector[#collector+1] = token + collector = token.tokens + elseif token.type == "/" then + if #sections == 0 then + error("Unopened section: "..token.value) + end + + -- Make sure there are no open sections when we're done + section = table_remove(sections, #sections) + + if not section.value == token.value then + error("Unclosed section: "..section.value) + end + + section.closingTagIndex = token.startIndex + + if #sections > 0 then + collector = sections[#sections].tokens + else + collector = tree + end + else + collector[#collector+1] = token + end + end + + section = table_remove(sections, #sections) + + if section then + error("Unclosed section: "..section.value) + end + + return tree +end + +-- Combines the values of consecutive text tokens in the given `tokens` array +-- to a single token. +local function squash_tokens(tokens) + local out, txt = {}, {} + local txtStartIndex, txtEndIndex + for _, v in ipairs(tokens) do + if v.type == "text" then + if #txt == 0 then + txtStartIndex = v.startIndex + end + txt[#txt+1] = v.value + txtEndIndex = v.endIndex + else + if #txt > 0 then + out[#out+1] = { type = "text", value = table_concat(txt), startIndex = txtStartIndex, endIndex = txtEndIndex } + txt = {} + end + out[#out+1] = v + end + end + if #txt > 0 then + out[#out+1] = { type = "text", value = table_concat(txt), startIndex = txtStartIndex, endIndex = txtEndIndex } + end + return out +end + +local function make_context(view) + if not view then return view end + return getmetatable(view) == Context and view or Context:new(view) +end + +local renderer = { } + +function renderer:clear_cache() + self.cache = {} + self.partial_cache = {} +end + +function renderer:compile(tokens, tags, originalTemplate) + tags = tags or self.tags + if type(tokens) == "string" then + tokens = self:parse(tokens, tags) + end + + local fn = compile_tokens(tokens, originalTemplate) + + return function(view) + return fn(make_context(view), self) + end +end + +function renderer:render(template, view, partials) + if type(self) == "string" then + error("Call mustache:render, not mustache.render!") + end + + if partials then + -- remember partial table + -- used for runtime lookup & compile later on + self.partials = partials + end + + if not template then + return "" + end + + local fn = self.cache[template] + + if not fn then + fn = self:compile(template, self.tags, template) + self.cache[template] = fn + end + + return fn(view) +end + +function renderer:_section(token, context, callback, originalTemplate) + local value = context:lookup(token.value) + + if type(value) == "table" then + if is_array(value) then + local buffer = "" + + for i,v in ipairs(value) do + buffer = buffer .. callback(context:push(v), self) + end + + return buffer + end + + return callback(context:push(value), self) + elseif type(value) == "function" then + local section_text = string_sub(originalTemplate, token.endIndex+1, token.closingTagIndex - 1) + + local scoped_render = function(template) + return self:render(template, context) + end + + return value(section_text, scoped_render) or "" + else + if value then + return callback(context, self) + end + end + + return "" +end + +function renderer:_inverted(name, context, callback) + local value = context:lookup(name) + + -- From the spec: inverted sections may render text once based on the + -- inverse value of the key. That is, they will be rendered if the key + -- doesn't exist, is false, or is an empty list. + + if value == nil or value == false or (type(value) == "table" and is_array(value) and #value == 0) then + return callback(context, self) + end + + return "" +end + +function renderer:_partial(name, context, originalTemplate) + local fn = self.partial_cache[name] + + -- check if partial cache exists + if (not fn and self.partials) then + + local partial = self.partials[name] + if (not partial) then + return "" + end + + -- compile partial and store result in cache + fn = self:compile(partial, nil, originalTemplate) + self.partial_cache[name] = fn + end + return fn and fn(context, self) or "" +end + +function renderer:_name(name, context, escape) + local value = context:lookup(name) + + if type(value) == "function" then + value = value(context.view) + end + + local str = value == nil and "" or value + str = tostring(str) + + if escape then + return string_gsub(str, '[&<>"\'/]', function(s) return html_escape_characters[s] end) + end + + return str +end + +-- Breaks up the given `template` string into a tree of token objects. If +-- `tags` is given here it must be an array with two string values: the +-- opening and closing tags used in the template (e.g. ["<%", "%>"]). Of +-- course, the default is to use mustaches (i.e. Mustache.tags). +function renderer:parse(template, tags) + tags = tags or self.tags + local tag_patterns = escape_tags(tags) + local scanner = Scanner:new(template) + local tokens = {} -- token buffer + local spaces = {} -- indices of whitespace tokens on the current line + local has_tag = false -- is there a {{tag} on the current line? + local non_space = false -- is there a non-space char on the current line? + + -- Strips all whitespace tokens array for the current line if there was + -- a {{#tag}} on it and otherwise only space + local function strip_space() + if has_tag and not non_space then + while #spaces > 0 do + table_remove(tokens, table_remove(spaces)) + end + else + spaces = {} + end + has_tag = false + non_space = false + end + + local type, value, chr + + while not scanner:eos() do + local start = scanner.pos + + value = scanner:scan_until(tag_patterns[1]) + + if value then + for i = 1, #value do + chr = string_sub(value,i,i) + + if string_find(chr, "%s+") then + spaces[#spaces+1] = #tokens + 1 + else + non_space = true + end + + tokens[#tokens+1] = { type = "text", value = chr, startIndex = start, endIndex = start } + start = start + 1 + if chr == "\n" then + strip_space() + end + end + end + + if not scanner:scan(tag_patterns[1]) then + break + end + + has_tag = true + type = scanner:scan(patterns.tag) or "name" + + scanner:scan(patterns.white) + + if type == "=" then + value = scanner:scan_until(patterns.eq) + scanner:scan(patterns.eq) + scanner:scan_until(tag_patterns[2]) + elseif type == "{" then + local close_pattern = "%s*}"..tags[2] + value = scanner:scan_until(close_pattern) + scanner:scan(patterns.curly) + scanner:scan_until(tag_patterns[2]) + else + value = scanner:scan_until(tag_patterns[2]) + end + + if not scanner:scan(tag_patterns[2]) then + error("Unclosed tag at " .. scanner.pos) + end + + tokens[#tokens+1] = { type = type, value = value, startIndex = start, endIndex = scanner.pos - 1 } + if type == "name" or type == "{" or type == "&" then + non_space = true --> what does this do? + end + + if type == "=" then + tags = string_split(value, patterns.space) + tag_patterns = escape_tags(tags) + end + end + + return nest_tokens(squash_tokens(tokens)) +end + +function renderer:new() + local out = { + cache = {}, + partial_cache = {}, + tags = {"{{", "}}"} + } + return setmetatable(out, { __index = self }) +end + +return renderer diff --git a/lustache/scanner.lua b/lustache/scanner.lua new file mode 100644 index 0000000..0673df1 --- /dev/null +++ b/lustache/scanner.lua @@ -0,0 +1,57 @@ +local string_find, string_match, string_sub = + string.find, string.match, string.sub + +local scanner = {} + +-- Returns `true` if the tail is empty (end of string). +function scanner:eos() + return self.tail == "" +end + +-- Tries to match the given regular expression at the current position. +-- Returns the matched text if it can match, `null` otherwise. +function scanner:scan(pattern) + local match = string_match(self.tail, pattern) + + if match and string_find(self.tail, pattern) == 1 then + self.tail = string_sub(self.tail, #match + 1) + self.pos = self.pos + #match + + return match + end + +end + +-- Skips all text until the given regular expression can be matched. Returns +-- the skipped string, which is the entire tail of this scanner if no match +-- can be made. +function scanner:scan_until(pattern) + + local match + local pos = string_find(self.tail, pattern) + + if pos == nil then + match = self.tail + self.pos = self.pos + #self.tail + self.tail = "" + elseif pos == 1 then + match = nil + else + match = string_sub(self.tail, 1, pos - 1) + self.tail = string_sub(self.tail, pos) + self.pos = self.pos + #match + end + + return match +end + +function scanner:new(str) + local out = { + str = str, + tail = str, + pos = 1 + } + return setmetatable(out, { __index = self } ) +end + +return scanner