From 552a3276a84610c9f265ffdf072d65f73d3bea50 Mon Sep 17 00:00:00 2001 From: Alex Wilson Date: Tue, 13 Oct 2015 12:12:28 -0700 Subject: [PATCH] Make 'auto' format handle leading whitespace in ssh keys --- lib/formats/auto.js | 22 +++++++++++++++++----- test/pem.js | 6 ++++++ 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/lib/formats/auto.js b/lib/formats/auto.js index 170f4a9..37c3cc8 100644 --- a/lib/formats/auto.js +++ b/lib/formats/auto.js @@ -18,18 +18,16 @@ 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) @@ -37,6 +35,20 @@ function 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 && diff --git a/test/pem.js b/test/pem.js index bfa7300..0edf947 100644 --- a/test/pem.js +++ b/test/pem.js @@ -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, 'mark@foo.local');