Merge pull request #4358 from plm/remove-rrd-path-triple-escape
[project/luci.git] / modules / luci-mod-system / htdocs / luci-static / resources / view / system / sshkeys.js
1 'use strict';
2 'require baseclass';
3 'require view';
4 'require fs';
5 'require ui';
6
7 var isReadonlyView = !L.hasViewPermission() || null;
8
9 var SSHPubkeyDecoder = baseclass.singleton({
10 lengthDecode: function(s, off)
11 {
12 var l = (s.charCodeAt(off++) << 24) |
13 (s.charCodeAt(off++) << 16) |
14 (s.charCodeAt(off++) << 8) |
15 s.charCodeAt(off++);
16
17 if (l < 0 || (off + l) > s.length)
18 return -1;
19
20 return l;
21 },
22
23 decode: function(s)
24 {
25 var parts = s.trim().match(/^((?:(?:^|,)[^ =,]+(?:=(?:[^ ",]+|"(?:[^"\\]|\\.)*"))?)+ +)?(ssh-dss|ssh-rsa|ssh-ed25519|ecdsa-sha2-nistp[0-9]+) +([^ ]+)( +.*)?$/);
26
27 if (!parts)
28 return null;
29
30 var key = null;
31 try { key = atob(parts[3]); } catch(e) {}
32 if (!key)
33 return null;
34
35 var off, len;
36
37 off = 0;
38 len = this.lengthDecode(key, off);
39
40 if (len <= 0)
41 return null;
42
43 var type = key.substr(off + 4, len);
44 if (type !== parts[2])
45 return null;
46
47 off += 4 + len;
48
49 var len1 = off < key.length ? this.lengthDecode(key, off) : 0;
50 if (len1 <= 0)
51 return null;
52
53 var curve = null;
54 if (type.indexOf('ecdsa-sha2-') === 0) {
55 curve = key.substr(off + 4, len1);
56
57 if (!len1 || type.substr(11) !== curve)
58 return null;
59
60 type = 'ecdsa-sha2';
61 curve = curve.replace(/^nistp(\d+)$/, 'NIST P-$1');
62 }
63
64 off += 4 + len1;
65
66 var len2 = off < key.length ? this.lengthDecode(key, off) : 0;
67 if (len2 < 0)
68 return null;
69
70 if (len1 & 1)
71 len1--;
72
73 if (len2 & 1)
74 len2--;
75
76 var comment = (parts[4] || '').trim(),
77 fprint = parts[3].length > 68 ? parts[3].substr(0, 33) + '…' + parts[3].substr(-34) : parts[3];
78
79 var options = null;
80 (parts[1] || '').trim().replace(/(?:^|,)([^ =,]+)(?:=(?:([^ ",]+)|"((?:[^"\\]|\\.)*)"))?/g, function(m, k, p, q) {
81 options = options || {};
82
83 if (options.hasOwnProperty(k))
84 options[k] += ',' + (q || p || true);
85 else
86 options[k] = (q || p || true);
87 });
88
89 switch (type)
90 {
91 case 'ssh-rsa':
92 return { type: 'RSA', bits: len2 * 8, comment: comment, options: options, fprint: fprint, src: s };
93
94 case 'ssh-dss':
95 return { type: 'DSA', bits: len1 * 8, comment: comment, options: options, fprint: fprint, src: s };
96
97 case 'ssh-ed25519':
98 return { type: 'ECDH', curve: 'Curve25519', comment: comment, options: options, fprint: fprint, src: s };
99
100 case 'ecdsa-sha2':
101 return { type: 'ECDSA', curve: curve, comment: comment, options: options, fprint: fprint, src: s };
102
103 default:
104 return null;
105 }
106 }
107 });
108
109 function renderKeyItem(pubkey) {
110 return E('div', {
111 class: 'item',
112 click: isReadonlyView ? null : removeKey,
113 'data-key': pubkey.src
114 }, [
115 E('strong', pubkey.comment || _('Unnamed key')), E('br'),
116 E('small', [
117 '%s, %s'.format(pubkey.type, pubkey.curve || _('%d Bit').format(pubkey.bits)),
118 pubkey.options ? E([], [
119 ' / ', _('Options:'), ' ',
120 E('code', Object.keys(pubkey.options).sort().join(', '))
121 ]) : '',
122 E('br'), E('code', pubkey.fprint)
123 ])
124 ]);
125 }
126
127 function renderKeys(keys) {
128 var list = document.querySelector('.cbi-dynlist');
129
130 while (!matchesElem(list.firstElementChild, '.add-item'))
131 list.removeChild(list.firstElementChild);
132
133 keys.forEach(function(key) {
134 var pubkey = SSHPubkeyDecoder.decode(key);
135 if (pubkey)
136 list.insertBefore(renderKeyItem(pubkey), list.lastElementChild);
137 });
138
139 if (list.firstElementChild === list.lastElementChild)
140 list.insertBefore(E('p', _('No public keys present yet.')), list.lastElementChild);
141 }
142
143 function saveKeys(keys) {
144 return fs.write('/etc/dropbear/authorized_keys', keys.join('\n') + '\n', 384 /* 0600 */)
145 .then(renderKeys.bind(this, keys))
146 .catch(function(e) { ui.addNotification(null, E('p', e.message)) })
147 .finally(ui.hideModal);
148 }
149
150 function addKey(ev) {
151 var list = findParent(ev.target, '.cbi-dynlist'),
152 input = list.querySelector('input[type="text"]'),
153 key = input.value.trim(),
154 pubkey = SSHPubkeyDecoder.decode(key),
155 keys = [];
156
157 if (!key.length)
158 return;
159
160 list.querySelectorAll('.item').forEach(function(item) {
161 keys.push(item.getAttribute('data-key'));
162 });
163
164 if (keys.indexOf(key) !== -1) {
165 ui.showModal(_('Add key'), [
166 E('div', { class: 'alert-message warning' }, _('The given SSH public key has already been added.')),
167 E('div', { class: 'right' }, E('div', { class: 'btn', click: L.hideModal }, _('Close')))
168 ]);
169 }
170 else if (!pubkey) {
171 ui.showModal(_('Add key'), [
172 E('div', { class: 'alert-message warning' }, _('The given SSH public key is invalid. Please supply proper public RSA or ECDSA keys.')),
173 E('div', { class: 'right' }, E('div', { class: 'btn', click: L.hideModal }, _('Close')))
174 ]);
175 }
176 else {
177 keys.push(key);
178 input.value = '';
179
180 return saveKeys(keys).then(function() {
181 var added = list.querySelector('[data-key="%s"]'.format(key.replace(/["\\]/g, '\\$&')));
182 if (added)
183 added.classList.add('flash');
184 });
185 }
186 }
187
188 function removeKey(ev) {
189 var list = findParent(ev.target, '.cbi-dynlist'),
190 delkey = ev.target.getAttribute('data-key'),
191 keys = [];
192
193 list.querySelectorAll('.item').forEach(function(item) {
194 var key = item.getAttribute('data-key');
195 if (key !== delkey)
196 keys.push(key);
197 });
198
199 L.showModal(_('Delete key'), [
200 E('div', _('Do you really want to delete the following SSH key?')),
201 E('pre', delkey),
202 E('div', { class: 'right' }, [
203 E('div', { class: 'btn', click: L.hideModal }, _('Cancel')),
204 ' ',
205 E('div', { class: 'btn danger', click: ui.createHandlerFn(this, saveKeys, keys) }, _('Delete key')),
206 ])
207 ]);
208 }
209
210 function dragKey(ev) {
211 ev.stopPropagation();
212 ev.preventDefault();
213 ev.dataTransfer.dropEffect = 'copy';
214 }
215
216 function dropKey(ev) {
217 var file = ev.dataTransfer.files[0],
218 input = ev.currentTarget.querySelector('input[type="text"]'),
219 reader = new FileReader();
220
221 if (file) {
222 reader.onload = function(rev) {
223 input.value = rev.target.result.trim();
224 addKey(ev);
225 input.value = '';
226 };
227
228 reader.readAsText(file);
229 }
230
231 ev.stopPropagation();
232 ev.preventDefault();
233 }
234
235 function handleWindowDragDropIgnore(ev) {
236 ev.preventDefault()
237 }
238
239 return view.extend({
240 load: function() {
241 return fs.lines('/etc/dropbear/authorized_keys').then(function(lines) {
242 return lines.map(function(line) {
243 return SSHPubkeyDecoder.decode(line);
244 }).filter(function(line) {
245 return line != null;
246 });
247 });
248 },
249
250 render: function(keys) {
251 var list = E('div', {
252 'class': 'cbi-dynlist',
253 'dragover': isReadonlyView ? null : dragKey,
254 'drop': isReadonlyView ? null : dropKey
255 }, [
256 E('div', { 'class': 'add-item' }, [
257 E('input', {
258 'class': 'cbi-input-text',
259 'type': 'text',
260 'placeholder': _('Paste or drag SSH key file…') ,
261 'keydown': function(ev) { if (ev.keyCode === 13) addKey(ev) },
262 'disabled': isReadonlyView
263 }),
264 E('button', {
265 'class': 'cbi-button',
266 'click': ui.createHandlerFn(this, addKey),
267 'disabled': isReadonlyView
268 }, _('Add key'))
269 ])
270 ]);
271
272 keys.forEach(L.bind(function(pubkey) {
273 list.insertBefore(renderKeyItem(pubkey), list.lastElementChild);
274 }, this));
275
276 if (list.firstElementChild === list.lastElementChild)
277 list.insertBefore(E('p', _('No public keys present yet.')), list.lastElementChild);
278
279 window.addEventListener('dragover', handleWindowDragDropIgnore);
280 window.addEventListener('drop', handleWindowDragDropIgnore);
281
282 return E('div', {}, [
283 E('h2', _('SSH-Keys')),
284 E('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.')),
285 E('div', { 'class': 'cbi-section-node' }, list)
286 ]);
287 },
288
289 handleSaveApply: null,
290 handleSave: null,
291 handleReset: null
292 });