-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsshfriendfinder.py
221 lines (165 loc) · 6.23 KB
/
sshfriendfinder.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
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
# -----------------------------------------------------------
# Filename : sshfriendfinder.py
# Description : Find ssh keys, and see where you can get with them.
# Requires: : ag/silver searcher, paramiko via pip.
# Created By : Ben Hughes <[email protected]>
# Date Created : 2015-05-30 12:55
#
# License : MIT
#
# (c) Copyright 2015, all rights reserved.
# -----------------------------------------------------------
import argparse
import os
import pwd
import subprocess
import sys
import paramiko
__author__ = "Ben Hughes"
__version__ = "0.1"
class Person(object):
def __init__(self, name):
self.name = name
self.keys = {}
def loadkey(self, keyfile):
"""
populate the keys list with valid loaded passwordless keys
"""
if os.path.isfile(keyfile):
k = loadkeyfile(keyfile)
if k:
self.keys[keyfile] = k
def try_host(self, host):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)
for filename, k in self.keys.iteritems():
idout = ''
try:
ssh.connect(host, username=self.name,
pkey=k, look_for_keys=False, allow_agent=False)
stdin, stdout, stderr = ssh.exec_command('/usr/bin/id')
stdin.close()
idout = stdout.read()
except paramiko.ssh_exception.AuthenticationException, e:
# Didn't authenticate, which is good!
print "Failed to auth with %s using %s, yay." % (e, filename)
continue
except Exception, e:
print "It broke with %s" % e
continue
ssh.close()
if idout != '':
iduser = idout.split(' ')[0]
# print k.get_name() + " " + k.get_base64() + " " + filename
print "'%s' will get you on to %s as %s: %s" % (filename,
host,
self.name,
iduser)
def loadkeyfile(privatekeyfile):
"""
Try to load a key, based on all the types in order of liklihood.
"""
key = False
keytypes = [paramiko.RSAKey.from_private_key_file,
paramiko.DSSKey.from_private_key_file]
# older (or you know, RHEL ones) don't have this, so only import it if we
# have it.
if 'ECDSAKey' in paramiko.__all__:
keytypes.extend(paramiko.ECDSAKey.from_private_key_file)
for keyloader in keytypes:
try:
key = keyloader(privatekeyfile)
except paramiko.ssh_exception.PasswordRequiredException:
continue
except paramiko.ssh_exception.SSHException:
continue
return key
def findkeys(dir):
"""
This requires ag/the silver searcher.
given a dir, find all the keys in it.
"""
cmd = ['ag', '-l', '--nocolor', '--', '-----BEGIN .* PRIVATE KEY-----', dir]
try:
return run_a_command(cmd)
except OSError:
sys.exit("Unable to find 'ag', which this uses.")
def run_a_command(cmd):
"""
Battle against the old versions of python, thanks RHEL.
"""
py_version = sys.version_info
# RHEL is the worst.
if py_version[0] == 2 and py_version[1] < 7:
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
return proc.communicate()[0].rstrip().split("\n")
else:
return subprocess.check_output(cmd).rstrip().split("\n")
def do_directory(somedir, hosts=None, trypattern=None):
for key in findkeys(somedir):
user = getfileowner(key)
p = Person(name=user)
p.loadkey(key)
for host in get_hosts(user, hosts, trypattern):
# XXX need to add a --verbose.
# print "Trying '%s' as %s against %s:" % (key, user, host)
p.try_host(host)
def getfileowner(somefile):
return pwd.getpwuid(os.stat(somefile).st_uid).pw_name
def do_homedir(user, hosts=None, trypattern=None):
p = Person(name=user)
sshdir = os.path.expanduser('~%s/.ssh' % user)
if not os.path.isdir(sshdir):
print "Can't find an SSH dir of '%s'" % sshdir
return
map(lambda x: p.loadkey(x), findkeys(sshdir))
# only bother continuing if we found any.
if not p.keys:
print "Can't find any SSH keys of use in '%s'" % sshdir
return
# hosts = ['127.0.0.1', 'bastion.example.org', 'fw.example.org']
for host in get_hosts(user, hosts, trypattern):
print "Trying against %s:" % host
p.try_host(host)
def get_hosts(user, hosts=[], trypattern=None):
"""
work out all the hosts, defaults to just localhost.
"""
if hosts is []:
if trypattern is None:
return ['127.0.0.1']
else:
return [patternhost(trypattern, user)]
else:
h = [patternhost(trypattern, user)]
hosts.extend(h)
return hosts
def patternhost(pattern, user):
"""
Given a 'something-%s-example.org' format, return that with %s replaced
(once) by the username in question.
"""
return pattern % user
if __name__ == "__main__":
p = argparse.ArgumentParser(description='Find me some SSH keys,\
and play with them')
g = p.add_mutually_exclusive_group()
g.add_argument('--home', '-H', metavar='davedave',
help='Run against user\'s SSH dir')
g.add_argument('--directory', '-d', metavar='/home/',
help='Run against a directory, and use owner of key as user')
p.add_argument('--tryhost', '-t', metavar='host.example.org', nargs='+',
help='add a host to try against')
p.add_argument('--trypattern', '-T', metavar='user-%s.example.org',
help='add a host with a name template to try against')
args = p.parse_args()
if args.home:
do_homedir(args.home, args.tryhost, args.trypattern)
elif args.directory:
do_directory(args.directory, args.tryhost, args.trypattern)
else:
p.print_help()