Last active
April 3, 2019 14:42
-
-
Save HerrSpace/ea8cd16aae9aa9d1b55f7b0cad3e9df2 to your computer and use it in GitHub Desktop.
Using paramiko to use and abuse ssh keys for signing and verifying. Load keys from agent or disk.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Example 1: Load priv and pub from file | |
from paramiko import RSAKey | |
# Load key from file, not from agent. | |
key = RSAKey.from_private_key_file('/Users/space/.ssh/tuer') | |
msg = key.sign_ssh_data(b"somestuff") | |
msg.rewind() | |
# This derives the public key.. Obviously. | |
pub = RSAKey(data=key.asbytes()) | |
print(pub.verify_ssh_sig(b"somestuff", msg)) | |
# Example 2: Load priv and pub from agent | |
from paramiko.ssh_exception import SSHException | |
from paramiko import RSAKey, DSSKey, ECDSAKey, Ed25519Key | |
from paramiko.agent import Agent | |
from paramiko.message import Message | |
agent = Agent() | |
for agent_key in agent.get_keys(): | |
# I don't think there is a key type independent way of doing this | |
for key_class in (RSAKey, DSSKey, ECDSAKey, Ed25519Key): | |
try: | |
agent_pub = key_class(data=agent_key.asbytes()) | |
break | |
except SSHException: | |
continue | |
# This doesn't return a Message object but bytes. That's idiotic as it's | |
# not in line with the other key types sign_ssh_data methods. That also | |
# means we don't have to call rewind on it. We can't actually. | |
msg = agent_key.sign_ssh_data(b"somestuff") | |
print(agent_pub.verify_ssh_sig( | |
b"somestuff", | |
# Hence we need to cast it ourselves. | |
Message(msg)) | |
) | |
# Example 3: Load priv from agent, pub from file | |
from paramiko import RSAKey | |
from paramiko.agent import Agent | |
from paramiko.message import Message | |
agent = Agent() | |
# This will raise paramiko.ssh_exception.PasswordRequiredException if a | |
# password is required. | |
key = RSAKey.from_private_key_file('/Users/space/.ssh/id_rsa') | |
pub = RSAKey(data=key.asbytes()) | |
for agent_key in agent.get_keys(): | |
msg = agent_key.sign_ssh_data(b"somestuff") | |
print(pub.verify_ssh_sig(b"somestuff", Message(msg))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment