-
Notifications
You must be signed in to change notification settings - Fork 4
/
sshecret.py
executable file
·315 lines (247 loc) · 9.03 KB
/
sshecret.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Tyler Cipriani
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
# sshecret is a wrapper around ssh that automatically manages multiple
# ssh-agent(1)s each containing only a single ssh key.
import argparse
import errno
import hashlib
import logging
import os
from shlex import quote
import subprocess
import sys
try:
from paramiko import SSHConfig
except ImportError:
print("[ERROR] sudo apt-get install python3-paramiko")
sys.exit(1)
DESCRIPTION = '''
sshecret is a wrapper around ssh that automatically manages multiple
ssh-agent(1)s each containing only a single ssh key.
EXAMPLE: sshecret -A -L8080:localhost:80 -l johndoe -p2222 example.com
sshecret accepts the same parameters as ssh(1) - fundamentally sshecret uses
execve(2) to wrap ssh, modifying the environment to ensure that each key in
your ssh_config(5) uses its own ssh-agent.
In order to retrieve the path to the socket for a given hostname, use:
sshecret --socket hostname
'''
LOG_FORMAT = '%(asctime)s %(filename)s %(message)s'
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
# Intentionally omit ``-v`` since I want to be able to see debug output
# for this script when passing ``-v`` as well.
SSH_FLAGS = ['-1', '-2', '-4', '-6', '-A', '-a', '-C', '-f', '-g',
'-K', '-k', '-M', '-N', '-n', '-q', '-s', '-T', '-t',
'-V', '-X', '-x', '-Y', '-y']
SSH_ARGS = ['-b', '-c', '-D', '-E', '-e', '-F', '-I', '-i', '-J', '-L',
'-l', '-m', '-O', '-o', '-p', '-Q', '-R', '-S', '-w', '-W']
class SSHSock():
"""
Creates an ssh-agent socket and adds the approriate runtime variables.
"""
def __init__(self, key):
self.key = key
def get_sock_path(self):
"""
Path for SSH socket files
"""
checksum = hashlib.md5()
checksum.update(self.key.file.encode("utf-8"))
hexdigest = checksum.hexdigest()
sock = os.path.join(
os.getenv("XDG_RUNTIME_DIR"), "{}.sock".format(hexdigest))
logging.debug("Sock path is: {}".format(sock))
return sock
def _add_key(self, sock_file):
"""
Add key to existing socket
"""
env = os.environ.copy()
env['SSH_AUTH_SOCK'] = sock_file
if self.key.check_key_exists(env):
logging.debug(
"SSH Key {} already in sock".format(self.key.file))
return
logging.debug(self.key.file)
cmd = ["/usr/bin/ssh-add", self.key.file]
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env)
(stdout, stderr) = proc.communicate()
if proc.returncode:
raise OSError(
1,
"Could not add identityfile sock file",
self.key.file
)
def create(self):
"""
Checksums the identity file and creates a new socket.
New socket will contain *only that one key*.
"""
if self.key.empty:
return
sock_file = self.get_sock_path()
if not os.path.exists(sock_file):
cmd = [
"/usr/bin/ssh-agent",
"-a{}".format(sock_file),
]
error = subprocess.check_call(cmd)
if error:
raise OSError(1, "Could not create sock file", sock_file)
self._add_key(sock_file)
return sock_file
class SSHKey():
"""
Abstract the SSH identity file finding and checksumming.
"""
def __init__(self, host):
"""
Find the identity file based on hostname
"""
config = SSHConfig()
config.parse(open(self._get_ssh_config()))
host_config = config.lookup(host)
id_file = host_config.get("identityfile")
self.id_file = None
self.fingerprint = None
if id_file is not None:
self.id_file = id_file[::-1][0]
logging.debug("SSH identity file is: {}".format(self.id_file))
def _get_ssh_config(self):
"""
Try to find ssh config file at default location
"""
default = os.path.join(os.getenv("HOME"), ".ssh", "config")
path = os.getenv("SSH_CONF_PATH", default)
logging.debug("SSH config path is: {}".format(path))
if not os.path.exists(path) or not os.path.isfile(path):
raise IOError(
errno.ENOENT,
"File not found", path)
return path
def get_fingerprint(self):
"""
Return fingerprint of SSH identity file
"""
if self.id_file is None:
return None
if self.fingerprint is not None:
return self.fingerprint
cmd = [
'/usr/bin/ssh-keygen',
'-l',
'-f',
self.id_file]
out = subprocess.check_output(cmd)
self.fingerprint = out.strip().split()[1]
logging.debug("Key fingerprint is: {}".format(self.fingerprint))
return self.fingerprint
def check_key_exists(self, env):
cmd = ["ssh-add", "-l"]
proc = subprocess.Popen(cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env)
out, err = proc.communicate()
return self.get_fingerprint() in out.split()
@property
def empty(self):
return self.id_file is None
@property
def file(self):
return self.id_file
def parse_known_args(args):
"""Parse commandline arguments."""
parser = argparse.ArgumentParser(
usage='sshecret [--socket] [whatever you want to pass to ssh]',
description=DESCRIPTION,
formatter_class=argparse.RawTextHelpFormatter)
for flagname in SSH_FLAGS:
parser.add_argument(flagname, action='count',
help=argparse.SUPPRESS)
for optionname in SSH_ARGS:
parser.add_argument(optionname, help=argparse.SUPPRESS)
parser.add_argument('-v', action='count', dest="verbose",
help='Increase verbosity of output')
parser.add_argument('--socket', dest="sshecret_print_socket",
action='store_true',
help='print socket path for the given host')
parser.add_argument('hostname', help=argparse.SUPPRESS)
parser.add_argument('command', nargs='?', help=argparse.SUPPRESS)
return parser.parse_known_args(args)
def setup_logging(verbose):
"""
Setup logging level based on passed args.
"""
level = logging.INFO
if verbose > 0:
level = logging.DEBUG
logging.root.handlers = []
logging.basicConfig(level=level, format=LOG_FORMAT)
def get_host(hostname):
"""Extract hostname from ssh-style command line args"""
# Handle the [user]@[hostname] syntax
if '@' in hostname:
hostname = hostname.split('@')[1]
# If for some whacky reason the hostname has a protocol...
if hostname.startswith('ssh://'):
hostname = hostname[len('ssh://'):]
# Handle a port in the hostname
if ':' in hostname:
hostname = hostname.split(':')[0]
logging.debug('Hostname is {}'.format(hostname))
return hostname
def run_ssh(args, sock=None):
"""
Exec ssh in the environemnt
"""
env = {}
if sock is not None:
logging.info('SSH_AUTH_SOCK={}'.format(sock))
env = os.environ.copy()
env["SSH_AUTH_SOCK"] = sock
ssh = ["/usr/bin/ssh"]
ssh.extend(args)
os.execve("/usr/bin/ssh", ssh, env)
def main(args):
"""
Handle the whole deal.
#. Find the host
#. Find the keyfile for the host in the ssh config
#. Create the ssh-agent and socket
#. Exec ssh
"""
args, extra = parse_known_args(args)
verbose = 0
if args.verbose:
verbose = args.verbose
setup_logging(verbose)
host = get_host(args.hostname)
sock = SSHSock(SSHKey(host))
# If other sshecret-specific arguments are added which don't do an early
# return before calling ssh(1), it may be necessary to filter sys.argv.
if args.sshecret_print_socket:
print('SSH_AUTH_SOCK={}'.format(quote(sock.get_sock_path())))
return
run_ssh(sys.argv[1:], sock.create())
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))