Skip to content

Commit

Permalink
Make 'auto' format handle leading whitespace in ssh keys
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Wilson committed Oct 13, 2015
1 parent 0a56fe7 commit 552a327
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
22 changes: 17 additions & 5 deletions lib/formats/auto.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,37 @@ function read(buf) {
if (typeof (buf) === 'string') {
if (buf.trim().match(/^[-]+[ ]*BEGIN/))
return (pem.read(buf));
if (buf.match(/^ssh-[a-z]/))
if (buf.match(/^\s*ssh-[a-z]/))
return (ssh.read(buf));
if (buf.match(/^ecdsa-/))
if (buf.match(/^\s*ecdsa-/))
return (ssh.read(buf));
buf = new Buffer(buf, 'binary');
} else {
assert.buffer(buf);
if (findPEMHeader(buf))
return (pem.read(buf));
if (buf.slice(0, 4).toString('ascii') === 'ssh-')
return (ssh.read(buf));
if (buf.slice(0, 6).toString('ascii') === 'ecdsa-')
if (findSSHHeader(buf))
return (ssh.read(buf));
}
if (buf.readUInt32BE(0) < buf.length)
return (rfc4253.read(buf));
throw (new Error('Failed to auto-detect format of key'));
}

function findSSHHeader(buf) {
var offset = 0;
while (offset < buf.length &&
(buf[offset] === 32 || buf[offset] === 10 || buf[offset] === 9))
++offset;
if (offset + 4 <= buf.length &&
buf.slice(offset, offset + 4).toString('ascii') === 'ssh-')
return (true);
if (offset + 6 <= buf.length &&
buf.slice(offset, offset + 6).toString('ascii') === 'ecdsa-')
return (true);
return (false);
}

function findPEMHeader(buf) {
var offset = 0;
while (offset < buf.length &&
Expand Down
6 changes: 6 additions & 0 deletions test/pem.js
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,12 @@ test('1024b rsa ssh key with whitespace', function(t) {
t.end();
});

test('1024b rsa ssh key with whitespace auto', function(t) {
var k = sshpk.parseKey('\n\t \n' + SSH_1024 + '\n', 'auto');
t.equal(k.toString('pem'), PEM_1024);
t.end();
});

test('1024b rsa ssh key with inner whitespace', function(t) {
var k = sshpk.parseKey(SSH_1024_WS, 'ssh');
t.equal(k.comment, '[email protected]');
Expand Down

0 comments on commit 552a327

Please sign in to comment.