Skip to content

Commit

Permalink
Parse RFC1421 headers in PEM format, error on encrypted private key
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Wilson committed Sep 22, 2015
1 parent 10f4350 commit 4432fa7
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
20 changes: 19 additions & 1 deletion lib/formats/pem.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,26 @@ function read(buf) {
alg = m[1].trim();
}

var headers = {};
while (true) {
lines = lines.slice(1);
m = lines[0].match(/*JSSTYLED*/
/^([A-Za-z0-9-]+): (.+)$/);
if (!m)
break;
headers[m[1].toLowerCase()] = m[2];
}
if (headers['proc-type']) {
var parts = headers['proc-type'].split(',');
if (parts[0] === '4' && parts[1] === 'ENCRYPTED') {
throw (new Error('PEM key is encrypted ' +
'(password-protected). Please use the ' +
'SSH agent or decrypt the key.'));
}
}

/* Chop off the first and last lines */
lines = lines.slice(1, -2).join('');
lines = lines.slice(0, -2).join('');
buf = new Buffer(lines, 'base64');

var der = new asn1.BerReader(buf);
Expand Down
22 changes: 21 additions & 1 deletion test/pem.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,21 @@ var DSA_1024_PEM = '-----BEGIN PUBLIC KEY-----\n' +
'W8SOb2668IL7Vg==\n' +
'-----END PUBLIC KEY-----\n';

var ENC_PRIVATE = '-----BEGIN RSA PRIVATE KEY-----\n' +
'Proc-Type: 4,ENCRYPTED\n' +
'DEK-Info: AES-128-CBC,B3095F1FAF29BE6554540D24F17D14DB\n\n' +
'1OJdgfzsXazrhPZ7pO9Q27Pr97+OsU8FUxiCrDrEP71piJMJrmifue9KfOoAmC1L\n' +
'FhaKXGSmRnP1/odgG7KBJ8ybIkZ5gVMz/dU4hR0SyA3zLMx+sV68oqYYw4s0EjrA\n' +
'KYzQmMc78ouC6yQA4r+psgJ2sgK5VwwB48c0J5lO60HUeyEsno6iGY7VW/Kmt76O\n' +
'Kl8/LwA9qE2U/1u6pRsoaD34CD2E+m/IwCUIyLeri04tiMfyE0RKTL9EacvxExCu\n' +
'ucwBlvtGIcQcChw1JJqGxTXBeCrz8Kb3uWNrZ+MME3OEh4qWFPgT6XqeE/gociym\n' +
'rhyKffZKsnJts0TqxqSuxtpLM5+WaYAGbkEHzuC/chOsynFRKxZomV65ddufmO3N\n' +
'Kb8B3H+2+Fo9x5iucEBhj4MBLHlZ7ZkQ8yEP+E0d0PuPRIFZ3aRcKPuaoZIc/AiQ\n' +
'8w1GGAU1TZWWHs1L4pF7OWyWwuq3NkzWLzL7MkNx++zmxXpIPMKDnFTLuBu24nCk\n' +
'gBx85sgirfSJBwx1mpQzsD1PSE7krAzlA4DRfgPChAWJnlUn89aPJ52uokHneJIK\n' +
'z8/ApT6HCd3EnH9VHEtXp116ZVk4PhRiiOMY/ek2uhFK57wgMxOrRM3OgODrd+5A\n' +
'-----END RSA PRIVATE KEY-----\n';

///--- Tests

test('1024b pem to rsa ssh key', function(t) {
Expand Down Expand Up @@ -168,4 +183,9 @@ test('1024b dsa ssh key', function(t) {
t.end();
});


test('encrypted private key', function(t) {
t.throws(function () {
var k = sshpk.parseKey(ENC_PRIVATE, 'pem');
});
t.end();
});

0 comments on commit 4432fa7

Please sign in to comment.