ssh key format node.js

740 views Asked by At

I've tried using ssh2 and node-ssh libraries to connect, but I always get "Cannot parse privateKey: Unsupported key format" I'm getting the key from AWS secret manager in this format -----BEGIN PRIVATE KEY----- ....---END PRIVATE KEY-----, I tried adding 'BEGIN RSA' or 'BEGIN OPENSSH' (also added them at the end of the file) still getting the same error, I tried using ssh-keygen -m PEM -t rsa and navigate to this file and still I get this error, I managed to workaround with exec a child process but it's not ideal, I'm trying to avoid saving the key as file and use directly the string I'm getting from the secret manager

ssh.connect({
  host: 'my-server.example.com',
  port: 22,
  username: 'my-username',
  privateKey: // string from secret manager in the format mentioned above
});
2

There are 2 answers

0
Prateek Jain On

you can refer below updates using the node-ssh npm package more can be seen here https://www.npmjs.com/package/node-ssh/v/13.1.0

ssh.connect({
  host: 'localhost',
  username: 'steel',
  privateKeyPath: '/home/steel/.ssh/id_rsa'
})

// or with inline privateKey

ssh.connect({
  host: 'localhost',
  username: 'steel',
  privateKey: Buffer.from('...')
})
0
larsks On

A private key that starts with -----BEGIN RSA PRIVATE KEY----- is an encrypted private key. You need to provide an appropriate key passphrase in order to use it.

I'm not familiar with node.js in general (nor node-ssh in particular), but looking at the documentation for node-ssh it looks like there are options for providing the passphrase. The "API" section shows:

declare type Config = ConnectConfig & {
    host?: string;
    port?: number;
    username?: string;
    password?: string;
    privateKeyPath?: string;
    privateKey?: string;
    passphrase?: string;
    tryKeyboard?: boolean;
    onKeyboardInteractive?: (
      name: string,
      instructions: string,
      lang: string,
      prompts: Prompt[],
      finish: (responses: string[]) => void
    ) => void;
};

So you either need:

ssh.connect({
  host: 'my-server.example.com',
  port: 22,
  username: 'my-username',
  privateKey: // string from secret manager in the format mentioned above,
  passphrase: // key passphrase
});

Or you need to store an unencrypted private key in your secrets manager. An unencrypted private key starts with -----BEGIN OPENSSH PRIVATE KEY-----.