luci-mod-system: restructure administration pages
authorJo-Philipp Wich <jo@mein.io>
Tue, 20 Nov 2018 09:50:03 +0000 (10:50 +0100)
committerJo-Philipp Wich <jo@mein.io>
Tue, 20 Nov 2018 10:01:50 +0000 (11:01 +0100)
Split password, dropbear and SSH key configuration into separate pages in
order to improve the form layout and to simplify the code.

Signed-off-by: Jo-Philipp Wich <jo@mein.io>
modules/luci-mod-system/luasrc/controller/admin/system.lua
modules/luci-mod-system/luasrc/model/cbi/admin_system/admin.lua [deleted file]
modules/luci-mod-system/luasrc/model/cbi/admin_system/dropbear.lua [new file with mode: 0644]
modules/luci-mod-system/luasrc/view/admin_system/password.htm [new file with mode: 0644]
modules/luci-mod-system/luasrc/view/admin_system/sshkeys.htm [new file with mode: 0644]

index 68ca88b980ca4f81733aad04672e064bc5b19a50..3e58896d63590318ea5a5de7af8bd5914578e926 100644 (file)
@@ -10,7 +10,16 @@ function index()
        entry({"admin", "system", "system"}, cbi("admin_system/system"), _("System"), 1)
        entry({"admin", "system", "clock_status"}, post_on({ set = true }, "action_clock_status"))
 
-       entry({"admin", "system", "admin"}, cbi("admin_system/admin"), _("Administration"), 2)
+       entry({"admin", "system", "admin"}, firstchild(), _("Administration"), 2)
+       entry({"admin", "system", "admin", "password"}, template("admin_system/password"), _("Router Password"), 1)
+       entry({"admin", "system", "admin", "password", "json"}, post("action_password"))
+
+       if fs.access("/etc/config/dropbear") then
+               entry({"admin", "system", "admin", "dropbear"}, cbi("admin_system/dropbear"), _("SSH Access"), 2)
+               entry({"admin", "system", "admin", "sshkeys"}, template("admin_system/sshkeys"), _("SSH-Keys"), 3)
+               entry({"admin", "system", "admin", "sshkeys", "json"}, post_on({ keys = true }, "action_sshkeys"))
+       end
+
        entry({"admin", "system", "startup"}, form("admin_system/startup"), _("Startup"), 45)
        entry({"admin", "system", "crontab"}, form("admin_system/crontab"), _("Scheduled Tasks"), 46)
 
@@ -264,20 +273,65 @@ function action_reset()
        http.redirect(luci.dispatcher.build_url('admin/system/flashops'))
 end
 
-function action_passwd()
-       local p1 = luci.http.formvalue("pwd1")
-       local p2 = luci.http.formvalue("pwd2")
-       local stat = nil
+function action_password()
+       local password = luci.http.formvalue("password")
+       if not password then
+               luci.http.status(400, "Bad Request")
+               return
+       end
 
-       if p1 or p2 then
-               if p1 == p2 then
-                       stat = luci.sys.user.setpasswd("root", p1)
-               else
-                       stat = 10
+       luci.http.prepare_content("application/json")
+       luci.http.write_json({ code = luci.sys.user.setpasswd("root", password) })
+end
+
+function action_sshkeys()
+       local keys = luci.http.formvalue("keys")
+       if keys then
+               keys = luci.jsonc.parse(keys)
+               if not keys or type(keys) ~= "table" then
+                       luci.http.status(400, "Bad Request")
+                       return
                end
+
+               local fd, err = io.open("/etc/dropbear/authorized_keys", "w")
+               if not fd then
+                       luci.http.status(503, err)
+                       return
+               end
+
+               local _, k
+               for _, k in ipairs(keys) do
+                       if type(k) == "string" and k:match("^%w+%-") then
+                               fd:write(k)
+                               fd:write("\n")
+                       end
+               end
+
+               fd:close()
+       end
+
+       local fd, err = io.open("/etc/dropbear/authorized_keys", "r")
+       if not fd then
+               luci.http.status(503, err)
+               return
        end
 
-       luci.template.render("admin_system/passwd", {stat=stat})
+       local rv = {}
+       while true do
+               local ln = fd:read("*l")
+               if not ln then
+                       break
+               elseif ln:match("^[%w%-]+%s+[A-Za-z0-9+/=]+$") or
+                      ln:match("^[%w%-]+%s+[A-Za-z0-9+/=]+%s")
+               then
+                       rv[#rv+1] = ln
+               end
+       end
+
+       fd:close()
+
+       luci.http.prepare_content("application/json")
+       luci.http.write_json(rv)
 end
 
 function action_reboot()
diff --git a/modules/luci-mod-system/luasrc/model/cbi/admin_system/admin.lua b/modules/luci-mod-system/luasrc/model/cbi/admin_system/admin.lua
deleted file mode 100644 (file)
index 3428953..0000000
+++ /dev/null
@@ -1,124 +0,0 @@
--- Copyright 2008 Steven Barth <steven@midlink.org>
--- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
--- Licensed to the public under the Apache License 2.0.
-
-local fs = require "nixio.fs"
-
-m = Map("system", translate("Router Password"),
-       translate("Changes the administrator password for accessing the device"))
-m.apply_on_parse = true
-
-s = m:section(TypedSection, "_dummy", "")
-s.addremove = false
-s.anonymous = true
-
-pw1 = s:option(Value, "pw1", translate("Password"))
-pw1.password = true
-
-pw2 = s:option(Value, "pw2", translate("Confirmation"))
-pw2.password = true
-
-function s.cfgsections()
-       return { "_pass" }
-end
-
-function m.parse(map)
-       local v1 = pw1:formvalue("_pass")
-       local v2 = pw2:formvalue("_pass")
-
-       if v1 and v2 and #v1 > 0 and #v2 > 0 then
-               if v1 == v2 then
-                       if luci.sys.user.setpasswd(luci.dispatcher.context.authuser, v1) == 0 then
-                               m.message = translate("Password successfully changed!")
-                       else
-                               m.message = translate("Unknown Error, password not changed!")
-                       end
-               else
-                       m.message = translate("Given password confirmation did not match, password not changed!")
-               end
-       end
-
-       Map.parse(map)
-end
-
-
-if fs.access("/etc/config/dropbear") then
-
-m2 = Map("dropbear", translate("SSH Access"),
-       translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server"))
-m2.apply_on_parse = true
-
-s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance"))
-s.anonymous = true
-s.addremove = true
-
-
-ni = s:option(Value, "Interface", translate("Interface"),
-       translate("Listen only on the given interface or, if unspecified, on all"))
-
-ni.template    = "cbi/network_netlist"
-ni.nocreate    = true
-ni.unspecified = true
-
-
-pt = s:option(Value, "Port", translate("Port"),
-       translate("Specifies the listening port of this <em>Dropbear</em> instance"))
-
-pt.datatype = "port"
-pt.default  = 22
-
-
-pa = s:option(Flag, "PasswordAuth", translate("Password authentication"),
-       translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication"))
-
-pa.enabled  = "on"
-pa.disabled = "off"
-pa.default  = pa.enabled
-pa.rmempty  = false
-
-
-ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"),
-       translate("Allow the <em>root</em> user to login with password"))
-
-ra.enabled  = "on"
-ra.disabled = "off"
-ra.default  = ra.enabled
-
-
-gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"),
-       translate("Allow remote hosts to connect to local SSH forwarded ports"))
-
-gp.enabled  = "on"
-gp.disabled = "off"
-gp.default  = gp.disabled
-
-
-s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"),
-       translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication."))
-s2.addremove = false
-s2.anonymous = true
-s2.template  = "cbi/tblsection"
-
-function s2.cfgsections()
-       return { "_keys" }
-end
-
-keys = s2:option(TextValue, "_data", "")
-keys.wrap    = "off"
-keys.rows    = 3
-
-function keys.cfgvalue()
-       return fs.readfile("/etc/dropbear/authorized_keys") or ""
-end
-
-function keys.write(self, section, value)
-       return fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n"))
-end
-
-function keys.remove(self, section, value)
-       return fs.writefile("/etc/dropbear/authorized_keys", "")
-end
-
-end
-
-return m, m2
diff --git a/modules/luci-mod-system/luasrc/model/cbi/admin_system/dropbear.lua b/modules/luci-mod-system/luasrc/model/cbi/admin_system/dropbear.lua
new file mode 100644 (file)
index 0000000..1a1695d
--- /dev/null
@@ -0,0 +1,53 @@
+-- Copyright 2008 Steven Barth <steven@midlink.org>
+-- Copyright 2011-2018 Jo-Philipp Wich <jo@mein.io>
+-- Licensed to the public under the Apache License 2.0.
+
+m = Map("dropbear", translate("SSH Access"),
+       translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server"))
+m.apply_on_parse = true
+
+s = m:section(TypedSection, "dropbear", translate("Dropbear Instance"))
+s.anonymous = true
+s.addremove = true
+
+
+ni = s:option(Value, "Interface", translate("Interface"),
+       translate("Listen only on the given interface or, if unspecified, on all"))
+
+ni.template    = "cbi/network_netlist"
+ni.nocreate    = true
+ni.unspecified = true
+
+
+pt = s:option(Value, "Port", translate("Port"),
+       translate("Specifies the listening port of this <em>Dropbear</em> instance"))
+
+pt.datatype = "port"
+pt.default  = 22
+
+
+pa = s:option(Flag, "PasswordAuth", translate("Password authentication"),
+       translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication"))
+
+pa.enabled  = "on"
+pa.disabled = "off"
+pa.default  = pa.enabled
+pa.rmempty  = false
+
+
+ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"),
+       translate("Allow the <em>root</em> user to login with password"))
+
+ra.enabled  = "on"
+ra.disabled = "off"
+ra.default  = ra.enabled
+
+
+gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"),
+       translate("Allow remote hosts to connect to local SSH forwarded ports"))
+
+gp.enabled  = "on"
+gp.disabled = "off"
+gp.default  = gp.disabled
+
+return m
diff --git a/modules/luci-mod-system/luasrc/view/admin_system/password.htm b/modules/luci-mod-system/luasrc/view/admin_system/password.htm
new file mode 100644 (file)
index 0000000..3aff9c9
--- /dev/null
@@ -0,0 +1,70 @@
+<%+header%>
+
+<script type="application/javascript">//<![CDATA[
+       function submitPassword(ev) {
+               var pw1 = document.body.querySelector('[name="pw1"]'),
+                   pw2 = document.body.querySelector('[name="pw2"]');
+
+               if (!pw1.value.length || !pw2.value.length)
+                       return;
+
+               if (pw1.value === pw2.value) {
+                       showModal('<%:Change login password%>',
+                               E('p', { class: 'spinning' }, '<%:Changing password…%>'));
+
+                       (new XHR()).post('<%=url("admin/system/admin/password/json")%>',
+                               { token: '<%=token%>', password: pw1.value },
+                               function() {
+                                       showModal('<%:Change login password%>', [
+                                               E('div', _('The system password has been successfully changed.')),
+                                               E('div', { 'class': 'right' },
+                                                       E('div', { class: 'btn', click: hideModal }, '<%:Dismiss%>'))
+                                       ]);
+
+                                       pw1.value = pw2.value = '';
+                               });
+               }
+               else {
+                       showModal('<%:Change login password%>', [
+                               E('div', { class: 'alert-message warning' },
+                                       _('Given password confirmation did not match, password not changed!')),
+                               E('div', { 'class': 'right' },
+                                       E('div', { class: 'btn', click: hideModal }, '<%:Dismiss%>'))
+                       ]);
+               }
+       }
+//]]></script>
+
+<input type="password" aria-hidden="true" style="position:absolute; left:-10000px" />
+
+<div class="cbi-map">
+       <h2><%:Router Password%></h2>
+
+       <div class="cbi-section-descr">
+               <%:Changes the administrator password for accessing the device%>
+       </div>
+
+       <div class="cbi-section-node">
+               <div class="cbi-value">
+                       <label class="cbi-value-title" for="image"><%:Password%></label>
+                       <div class="cbi-value-field">
+                               <input type="password" name="pw1" /><!--
+                               --><button class="cbi-button cbi-button-neutral" title="<%:Reveal/hide password%>" aria-label="<%:Reveal/hide password%>" onclick="var e = this.previousElementSibling; e.type = (e.type === 'password') ? 'text' : 'password'">∗</button>
+                       </div>
+               </div>
+
+               <div class="cbi-value">
+                       <label class="cbi-value-title" for="image"><%:Confirmation%></label>
+                       <div class="cbi-value-field">
+                               <input type="password" name="pw2" /><!--
+                               --><button class="cbi-button cbi-button-neutral" title="<%:Reveal/hide password%>" aria-label="<%:Reveal/hide password%>" onclick="var e = this.previousElementSibling; e.type = (e.type === 'password') ? 'text' : 'password'">∗</button>
+                       </div>
+               </div>
+       </div>
+</div>
+
+<div class="cbi-page-actions">
+       <button class="btn cbi-button-apply" onclick="submitPassword(event)"><%:Save%></button>
+</div>
+
+<%+footer%>
diff --git a/modules/luci-mod-system/luasrc/view/admin_system/sshkeys.htm b/modules/luci-mod-system/luasrc/view/admin_system/sshkeys.htm
new file mode 100644 (file)
index 0000000..acf008a
--- /dev/null
@@ -0,0 +1,245 @@
+<%+header%>
+
+<style type="text/css">
+       .cbi-dynlist {
+               max-width: 100%;
+       }
+</style>
+
+<script type="application/javascript">//<![CDATA[
+       SSHPubkeyDecoder.prototype = {
+               lengthDecode: function(s, off)
+               {
+                       var l = (s.charCodeAt(off++) << 24) |
+                                       (s.charCodeAt(off++) << 16) |
+                                       (s.charCodeAt(off++) <<  8) |
+                                        s.charCodeAt(off++);
+
+                       if (l < 0 || (off + l) > s.length)
+                               return -1;
+
+                       return l;
+               },
+
+               decode: function(s)
+               {
+                       var parts = s.split(/\s+/);
+                       if (parts.length < 2)
+                               return null;
+
+                       var key = null;
+                       try { key = atob(parts[1]); } catch(e) {}
+                       if (!key)
+                               return null;
+
+                       var off, len;
+
+                       off = 0;
+                       len = this.lengthDecode(key, off);
+
+                       if (len <= 0)
+                               return null;
+
+                       var type = key.substr(off + 4, len);
+                       if (type !== parts[0])
+                               return null;
+
+                       off += 4 + len;
+
+                       var len1 = off < key.length ? this.lengthDecode(key, off) : 0;
+                       if (len1 <= 0)
+                               return null;
+
+                       var curve = null;
+                       if (type.indexOf('ecdsa-sha2-') === 0) {
+                               curve = key.substr(off + 4, len1);
+
+                               if (!len1 || type.substr(11) !== curve)
+                                       return null;
+
+                               type = 'ecdsa-sha2';
+                               curve = curve.replace(/^nistp(\d+)$/, 'NIST P-$1');
+                       }
+
+                       off += 4 + len1;
+
+                       var len2 = off < key.length ? this.lengthDecode(key, off) : 0;
+                       if (len2 < 0)
+                               return null;
+
+                       if (len1 & 1)
+                               len1--;
+
+                       if (len2 & 1)
+                               len2--;
+
+                       var comment = parts.slice(2).join(' '),
+                           fprint = parts[1].length > 68 ? parts[1].substr(0, 33) + '…' + parts[1].substr(-34) : parts[1];
+
+                       switch (type)
+                       {
+                       case 'ssh-rsa':
+                               return { type: 'RSA', bits: len2 * 8, comment: comment, fprint: fprint };
+
+                       case 'ssh-dss':
+                               return { type: 'DSA', bits: len1 * 8, comment: comment, fprint: fprint };
+
+                       case 'ssh-ed25519':
+                               return { type: 'ECDH', curve: 'Curve25519', comment: comment, fprint: fprint };
+
+                       case 'ecdsa-sha2':
+                               return { type: 'ECDSA', curve: curve, comment: comment, fprint: fprint };
+
+                       default:
+                               return null;
+                       }
+               }
+       };
+
+       function SSHPubkeyDecoder() {}
+
+       function renderKeys(keys) {
+               var list = document.querySelector('.cbi-dynlist[name="sshkeys"]'),
+                   decoder = new SSHPubkeyDecoder();
+
+               while (!matchesElem(list.firstElementChild, '.add-item'))
+                       list.removeChild(list.firstElementChild);
+
+               keys.forEach(function(key) {
+                       var pubkey = decoder.decode(key);
+                       if (pubkey)
+                               list.insertBefore(E('div', {
+                                       class: 'item',
+                                       click: removeKey,
+                                       'data-key': key
+                               }, [
+                                       E('strong', pubkey.comment || _('Unnamed key')), E('br'),
+                                       E('small', [
+                                               '%s, %s'.format(pubkey.type, pubkey.curve || _('%d Bit').format(pubkey.bits)),
+                                               E('br'), E('code', pubkey.fprint)
+                                       ])
+                               ]), list.lastElementChild);
+               });
+
+               if (list.firstElementChild === list.lastElementChild)
+                       list.insertBefore(E('p', _('No public keys present yet.')), list.lastElementChild);
+       }
+
+       function saveKeys(keys) {
+               showModal('<%:Add key%>', E('div', { class: 'spinning' }, _('Saving keys…')));
+               (new XHR()).post('<%=url("admin/system/admin/sshkeys/json")%>', { token: '<%=token%>', keys: JSON.stringify(keys) }, function(xhr, keys) {
+                       renderKeys(keys);
+                       hideModal();
+               });
+       }
+
+       function addKey(ev) {
+               var decoder = new SSHPubkeyDecoder(),
+                   list = findParent(ev.target, '.cbi-dynlist'),
+                   input = list.querySelector('input[type="text"]'),
+                   key = input.value.trim(),
+                   pubkey = decoder.decode(key),
+                   keys = [];
+
+               if (!key.length)
+                       return;
+
+               list.querySelectorAll('.item').forEach(function(item) {
+                       keys.push(item.getAttribute('data-key'));
+               });
+
+               if (keys.indexOf(key) !== -1) {
+                       showModal('<%:Add key%>', [
+                               E('div', { class: 'alert-message warning' }, _('The given SSH public key has already been added.')),
+                               E('div', { class: 'right' }, E('div', { class: 'btn', click: hideModal }, _('Close')))
+                       ]);
+               }
+               else if (!pubkey) {
+                       showModal('<%:Add key%>', [
+                               E('div', { class: 'alert-message warning' }, _('The given SSH public key is invalid. Please supply proper public RSA or ECDSA keys.')),
+                               E('div', { class: 'right' }, E('div', { class: 'btn', click: hideModal }, _('Close')))
+                       ]);
+               }
+               else {
+                       keys.push(key);
+                       saveKeys(keys);
+                       input.value = '';
+               }
+       }
+
+       function removeKey(ev) {
+               var list = findParent(ev.target, '.cbi-dynlist'),
+                   delkey = ev.target.getAttribute('data-key'),
+                   keys = [];
+
+               list.querySelectorAll('.item').forEach(function(item) {
+                       var key = item.getAttribute('data-key');
+                       if (key !== delkey)
+                               keys.push(key);
+               });
+
+               showModal('<%:Delete key%>', [
+                       E('div', _('Do you really want to delete the following SSH key?')),
+                       E('pre', delkey),
+                       E('div', { class: 'right' }, [
+                               E('div', { class: 'btn', click: hideModal }, _('Cancel')),
+                               ' ',
+                               E('div', { class: 'btn danger', click: function(ev) { saveKeys(keys) } }, _('Delete key')),
+                       ])
+               ]);
+       }
+
+       function dragKey(ev) {
+               ev.stopPropagation();
+               ev.preventDefault();
+               ev.dataTransfer.dropEffect = 'copy';
+       }
+
+       function dropKey(ev) {
+               var file = ev.dataTransfer.files[0],
+                   input = ev.currentTarget.querySelector('input[type="text"]'),
+                   reader = new FileReader();
+
+               if (file) {
+                       reader.onload = function(rev) {
+                               input.value = rev.target.result.trim();
+                               addKey(ev);
+                               input.value = '';
+                       };
+
+                       reader.readAsText(file);
+               }
+
+               ev.stopPropagation();
+               ev.preventDefault();
+       }
+
+       window.addEventListener('dragover', function(ev) { ev.preventDefault() });
+       window.addEventListener('drop', function(ev) { ev.preventDefault() });
+
+       requestAnimationFrame(function() {
+               XHR.get('<%=url("admin/system/admin/sshkeys/json")%>', null, function(xhr, keys) {
+                       renderKeys(keys);
+               });
+       });
+//]]></script>
+
+<div class="cbi-map">
+       <h2><%:SSH-Keys%></h2>
+
+       <div class="cbi-section-descr">
+               <%_Public keys allow for the passwordless SSH logins with a higher security compared to the use of plain passwords. In order to upload a new key to the device, paste an OpenSSH compatible public key line or drag a <code>.pub</code> file into the input field.%>
+       </div>
+
+       <div class="cbi-section-node">
+               <div class="cbi-dynlist" name="sshkeys">
+                       <p class="spinning"><%:Loading SSH keys…%></p>
+                       <div class="add-item" ondragover="dragKey(event)" ondrop="dropKey(event)">
+                               <input class="cbi-input-text" type="text" placeholder="<%:Paste or drag SSH key file…%>" onkeydown="if (event.keyCode === 13) addKey(event)" /><!--
+                               --><div class="cbi-button" onclick="addKey(event)"><%:Add key%></div>
+                       </div>
+               </div>
+       </div>
+</div>
+
+<%+footer%>