Giter Club home page Giter Club logo

bitwarden-ssh-agent's Introduction

Bitwarden SSH Agent

Requirements

  • You need to have the Bitwarden CLI tool installed and available in the $PATH as bw. See below for detailed instructions.
  • ssh-agent must be running in the current session.

Installation

Just save the file bw_add_sshkeys.py in a folder where it can by found when calling it from the command line. On linux you can see these folders by running echo $PATH from the command line. To install for a single user, you can - for example - save the script under ~/.local/bin/ and make it executable by running chmod +x ~/.local/bin/bw_add_sshkeys.py.

What does it do?

Fetches SSH keys stored in Bitwarden vault and adds them to ssh-agent.

How to use it

  1. Run,
    ./bw_add_sshkeys.py
  2. Enter your Bitwarden credentials, if a Bitwarden vault session is not already set.
  3. (optional) Enter your SSH keys' passphrases if they're not stored in your Bitwarden.

Storing the keys in Bitwarden

  1. Create a folder called ssh-agent (can be overridden on the command line).
  2. Add an new secure note to that folder.
  3. Add the private key to the secure note:
    • Add the private key directly on the notes field

      OR

    • Upload the private key as an attachment (requires Bitwarden Premium)

      • You'll need to add a custom field private containing the file name of the private key attachment.
      • The field name can be overridden on the command line
  4. (optional) If your key is encrypted with passphrase and you want it to decrypt automatically, save passphrase into custom field passphrase (field name can be overriden on the command line). You can create this field as hidden if you don't want the passphrase be displayed by default.
  5. Repeat steps 2-4 for each subsequent key

Command line overrides

  • --debug/-d - Show debug output
  • --foldername/-f - Folder name to use to search for SSH keys (default: ssh-agent)
  • --customfield/-c - Custom field name where private key filename is stored (default: private)
  • --passphrasefield/-p - Custom field name where passphrase for the key is stored (default: passphrase)
  • --session/-s - session key of bitwarden

Setting up the Bitwarden CLI tool

Download the Bitwarden CLI, extract the binary from the zip file, make it executable and add it to your path so that it can be found on the command line.

On linux you will likely want to move the executable to ~/.local/bin and make it executable chmod +x ~/.local/bin/bw. ~/.local/bin is likely already set as a path. You can confirm that by running which bw, which should return the path to the executable. You can use the same approach to turn bw_add_sshkeys.py into an executable.

If you want to build the Bitwarden CLI by yourself, see these instructions on the bitwarden github page.

bitwarden-ssh-agent's People

Contributors

cargocultprogramming avatar charmparticle avatar ggiesen avatar joaojacome avatar modem7 avatar p-hash avatar scottwallacesh avatar weidows avatar yamakaky avatar ymage avatar zodman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bitwarden-ssh-agent's Issues

Generate a new key

It would be nice to be able to generate a new keypair and store it in bitwarden with all the fields created.

Passphrase support?

Hi,

This is a nice and simple piece of kit! Thanks! 👍

Does this support SSH Keys with Passphrases? Like KeeAgent

Kind regards,

Login check via subprocess not working as intended with bw 2023.1.0

The login check in line 71 of bw_add_sshkeys.py has set check=True:

proc_logged = subprocess.run(["bw", "login", "--check", "--quiet"], check=True)

However the latest linux bw cli client (version 2023.1.0) returns a non-zero error code for that call if you are not already logged in, which results in subprocess raising an exception due to check=True. That exception is caught in main (line 312) and results in termination, without ever trying to log in.

[ I'm not logged in ]
$ bw login --check --quiet
$ echo $?
1

Setting check=False for subprocess.run() let's the script run as intended. Not sure if there are any other errors this tends to catch, so I'm not submitting a pull request. On my box it works, when I set check=False for that call.

Error loading key "(stdin)": invalid format

The script does not work in Git bash(MINGW) on Windows.

It complains Error loading key "(stdin)": invalid format
It seems that there's some issues related to line breaks on Windows.

But If I change code starting from line 235 as below, it works.

    subprocess.run(
        ["ssh-add", "-"],
        input=ssh_key.encode("utf-8"),
        # Works even if ssh-askpass is not installed
        env=envdict,
        universal_newlines=False,
        check=True,
    )

Can't find ssh.py

When running:

~/path/to/repo/start.sh

Getting the following error:

python: can't open file 'ssh.py': [Errno 2] No such file or directory

Could it be because I am using ~/ ?

Error

when I exec this script,output error:
python3 bw_add_sshkeys.py

INFO:root:Getting Bitwarden session
Traceback (most recent call last):
  File "bw_add_sshkeys.py", line 313, in <module>
    main()
  File "bw_add_sshkeys.py", line 295, in main
    session = get_session()
  File "bw_add_sshkeys.py", line 86, in get_session
    '--quiet'
  File "/usr/lib64/python3.6/subprocess.py", line 729, in __init__
    restore_signals, start_new_session)
  File "/usr/lib64/python3.6/subprocess.py", line 1364, in _execute_child
    raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'bw': 'bw'

Better login and unlock handling

Currently, the script asks the user for his password for login and unlock. This breaks the TOTP login workflow, and maybe other ones like SSO?

A better way would be to directly expose the bw interface. With --raw, stderr shows ? Master password: [input is hidden] and such, and stdout shows the session key. That way, the script only has to capture stdout, with stdin and stderr set as inherit.

ECONNRESET Error

Hello,

I currently have Vaultwarden installed in a Docker container.

I'm attempting to use this script on my M1 Mac. I installed brew and bitwarden-cli, and openssh (so I can use SK keys because Apples decided to disable them in the version that is shipped in macos)

I've got bw pointed to my domain vault.mydomain.one.

When I run the script I get the following errors:

user@m1-mac ~ % ./bw_add_sshkeys.py --debug                                                            
INFO:root:Getting Bitwarden session
DEBUG:root:Bitwarden vault is locked
? Master password: [hidden]
INFO:root:To re-use this BitWarden session run: export BW_SESSION="REDACTED"
DEBUG:root:Session = REDACTED
INFO:root:Getting folder list
DEBUG:root:Folder name: ssh-agent
INFO:root:Getting folder items
DEBUG:root:Folder ID: REDACTED
INFO:root:Attempting to add keys to ssh-agent
DEBUG:root:Private key file declared
WARNING:root:No "passphrase" field found for item myserver
DEBUG:root:Private key ID found
DEBUG:root:Item ID: REDACTED
DEBUG:root:Key ID: REDACTED

/opt/homebrew/Cellar/bitwarden-cli/2023.7.0/libexec/lib/node_modules/@bitwarden/cli/node_modules/node-fetch/lib/index.js:1505
			reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
			       ^
FetchError: request to https://vault.mydomain.one/attachments/REDACTED failed, reason: socket hang up
    at ClientRequest.<anonymous> (/opt/homebrew/Cellar/bitwarden-cli/2023.7.0/libexec/lib/node_modules/@bitwarden/cli/node_modules/node-fetch/lib/index.js:1505:11)
    at ClientRequest.emit (node:events:514:28)
    at TLSSocket.socketOnEnd (node:_http_client:519:9)
    at TLSSocket.emit (node:events:526:35)
    at endReadableNT (node:internal/streams/readable:1376:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ECONNRESET',
  code: 'ECONNRESET'
}

Node.js v20.5.1
WARNING:root:Could not add key to the SSH agent

I've spent a few hours searching the web and trying somethings but can't get it to work. I got it to work on a Debian VM but that's of now use because I can't use my YubiKey remotely to unlock the ssh key.

Any idea what my issue may be?

Unlock ssh-agent

Right now, the script fails if ssh-agent is locked. I don't find a way to detect if it is locked, and I don't think ssh-add can automatically unlock it.

DeprecationWarning: The `punycode` module is deprecated

Running this on MacOS brings up this deprecation warning multiple times:

(node:2509) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead. (Use `node --trace-deprecation ...` to show where the warning was created)

ssh-add always asks for password

Hi,

Thanks for this useful tool!
The weird thing is, I always get the question from ssh-add to enter the keyphrase:

INFO:root:Getting Bitwarden session
DEBUG:root:Bitwarden vault is locked
? Master password: [hidden]
INFO:root:To re-use this BitWarden session run: export BW_SESSION=“XX”
DEBUG:root:Session = XX
INFO:root:Getting folder list
DEBUG:root:Folder name: ssh-agent
INFO:root:Getting folder items
DEBUG:root:Folder ID: 08a058db-cecc-4c4a-b0f9-111500bf1e7a
INFO:root:Attempting to add keys to ssh-agent
DEBUG:root:Private key file declared
DEBUG:root:Passphrase declared
DEBUG:root:Private key ID found
DEBUG:root:Item ID: 5f799525-4849-4aba-a6a1-1116012d1ad8
DEBUG:root:Key ID: co6dah0ygsimglfcj8087k7x3vu71211
DEBUG:root:Running ssh-add
Enter passphrase for (stdin):
Identity added: (stdin) (KEY)

It also doesn't show the correct name, but instead shows (stdin)

This is my configuration:

image

Any suggestions?

for some reason on nonNixOS the package doesnt work like its using without nix

with a nix package:

bitwarden-ssh-agent
INFO:root:Getting Bitwarden session
INFO:root:Getting folder list
? Master password: [input is hidden] 

it's like not detecting the session when it is active and set in the environment...

executing with Python works like a charm!

ython bw_add_sshkeys.py 
INFO:root:Getting Bitwarden session
INFO:root:Getting folder list
INFO:root:Getting folder items
INFO:root:Attempting to add keys to ssh-agent

Loading Key Invalid Format

Hi guys,

Doing something slightly unconventional - running this on Windows. I already resolved one issue (subprocess.run needs shell=True added or it fails to load files. However, now I'm having issues with key format. I've uploaded my private key and the file name as described, but unfortunately I'm getting this error:

DEBUG:root:Running ssh-add
Error loading key "(stdin)": invalid format
WARNING:root:Could not add key to the SSH agent

It appears it fails somewhere in the subprocess.run for SSH add, maybe the input? I'm not sure the best thing to look for to debug this problem. Any thoughts or direction would be appreciated!

Thanks,
Brandin.

TypeError: __init__() got an unexpected keyword argument 'text'

When running bw_add_sshkeys,py, I get the following error:

$ bw_add_sshkeys.py 
INFO:root:Getting Bitwarden session
Traceback (most recent call last):
  File "/home/ggiesen/bin/bw_add_sshkeys.py", line 254, in <module>
    main()
  File "/home/ggiesen/bin/bw_add_sshkeys.py", line 238, in main
    session = get_session()
  File "/home/ggiesen/bin/bw_add_sshkeys.py", line 82, in get_session
    check=True,
  File "/usr/lib64/python3.6/subprocess.py", line 423, in run
    with Popen(*popenargs, **kwargs) as process:
TypeError: __init__() got an unexpected keyword argument 'text'
$ bw --version
1.19.1
$ cat /etc/redhat-release 
Rocky Linux release 8.4 (Green Obsidian)
$ python3 -V
Python 3.6.8
$ rpm -qa | grep openssh-clients
openssh-clients-8.0p1-6.el8_4.2.x86_64

ECONNREFUSED

After logging the client in to my own vaultwarden server (which functions just fine), I tried running the python script. I am getting the following log back however:

INFO:root:Getting folder list
INFO:root:Getting folder items
INFO:root:Attempting to add keys to ssh-agent

/snapshot/clients/node_modules/node-fetch/lib/index.js:1505
			reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
			       ^
FetchError: request to http://localhost/attachments/<long_string>/<another_long_string> failed, reason: connect ECONNREFUSED ::1:80
    at ClientRequest.<anonymous> (/snapshot/clients/node_modules/node-fetch/lib/index.js:1505:11)
    at ClientRequest.emit (node:events:537:28)
    at Socket.socketErrorListener (node:_http_client:465:9)
    at Socket.emit (node:events:537:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  type: 'system',
  errno: 'ECONNREFUSED',
  code: 'ECONNREFUSED'
}

Node.js v18.5.0
WARNING:root:Could not add key to the SSH agent

When I try and browse the link via a web browser with localhost replaced by my actual server domain, the attachment downloads successfully. Why would it point back to localhost in this scenario?

SSH key format?

It looks like the script is able to find the folder and keyfile fine, but something must be getting messed up in the formatting of the keyfile when its pulled down:

DEBUG:root:Running ssh-add
Error loading key "/tmp/tmpzpvpqgtr": invalid format
WARNING:root:Could not add key to the SSD agent

I just did a regular "ssh-keygen" and uploaded the file. I'm thinking either there's some transform needed of the file when its pulled down, or maybe tempfile is doing something?

I can load (or download from bitwarden and load) the attached keyfile fine.

I'm happy to dig further, but was hoping there might be something I'm doing wrong before going down the rabbit hole.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.