aboutsummaryrefslogtreecommitdiff
path: root/contrib/exitlist
blob: 86295c7d87aa3fdb12180edf6d5ac3885362885b (plain)
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
#!/usr/bin/python
# Copyright 2005-2006 Nick Mathewson
# See the LICENSE file in the Tor distribution for licensing information.

# Requires Python 2.2 or later.

"""
 exitlist -- Given a Tor directory on stdin, lists the Tor servers
 that accept connections to given addreses.

 example usage (Tor 0.1.0.x and earlier):

    python exitlist 18.244.0.188:80 < ~/.tor/cached-directory

 example usage (Tor 0.1.1.10-alpha and later):

    cat ~/.tor/cached-routers* | python exitlist 18.244.0.188:80

 If you're using Tor 0.1.1.18-rc or later, you should look at
 the "FetchUselessDescriptors" config option in the man page.

 Note that this script won't give you a perfect list of IP addresses
 that might connect to you using Tor, since some Tor servers might exit
 from other addresses than the one they publish.

"""

#
# Change this to True if you want more verbose output.  By default, we
# only print the IPs of the servers that accept any the listed
# addresses, one per line.
#
VERBOSE = False

#
# Change this to True if you want to reverse the output, and list the
# servers that accept *none* of the listed addresses.
#
INVERSE = False

#
# Change this list to contain all of the target services you are interested
# in.  It must contain one entry per line, each consisting of an IPv4 address,
# a colon, and a port number. This default is only used if we don't learn
# about any addresses from the command-line.
#
ADDRESSES_OF_INTEREST = """
    1.2.3.4:80
"""


#
# YOU DO NOT NEED TO EDIT AFTER THIS POINT.
#

import sys
import re
import getopt
import socket
import struct

assert sys.version_info >= (2,2)


def maskIP(ip,mask):
    return "".join([chr(ord(a) & ord(b)) for a,b in zip(ip,mask)])

def maskFromLong(lng):
    return struct.pack("!L", lng)

def maskByBits(n):
    return maskFromLong(0xffffffffl ^ ((1L<<(32-n))-1))

class Pattern:
    """
    >>> import socket
    >>> ip1 = socket.inet_aton("192.169.64.11")
    >>> ip2 = socket.inet_aton("192.168.64.11")
    >>> ip3 = socket.inet_aton("18.244.0.188")

    >>> print Pattern.parse("18.244.0.188")
    18.244.0.188/255.255.255.255:1-65535
    >>> print Pattern.parse("18.244.0.188/16:*")
    18.244.0.0/255.255.0.0:1-65535
    >>> print Pattern.parse("18.244.0.188/2.2.2.2:80")
    2.0.0.0/2.2.2.2:80-80
    >>> print Pattern.parse("192.168.0.1/255.255.00.0:22-25")
    192.168.0.0/255.255.0.0:22-25
    >>> p1 = Pattern.parse("192.168.0.1/255.255.00.0:22-25")
    >>> import socket
    >>> p1.appliesTo(ip1, 22)
    False
    >>> p1.appliesTo(ip2, 22)
    True
    >>> p1.appliesTo(ip2, 25)
    True
    >>> p1.appliesTo(ip2, 26)
    False
    """
    def __init__(self, ip, mask, portMin, portMax):
        self.ip = maskIP(ip,mask)
        self.mask = mask
        self.portMin = portMin
        self.portMax = portMax

    def __str__(self):
        return "%s/%s:%s-%s"%(socket.inet_ntoa(self.ip),
                              socket.inet_ntoa(self.mask),
                              self.portMin,
                              self.portMax)

    def parse(s):
        if ":" in s:
            addrspec, portspec = s.split(":",1)
        else:
            addrspec, portspec = s, "*"

        if addrspec == '*':
            ip,mask = "\x00\x00\x00\x00","\x00\x00\x00\x00"
        elif '/' not in addrspec:
            ip = socket.inet_aton(addrspec)
            mask = "\xff\xff\xff\xff"
        else:
            ip,mask = addrspec.split("/",1)
            ip = socket.inet_aton(ip)
            if "." in mask:
                mask = socket.inet_aton(mask)
            else:
                mask = maskByBits(int(mask))

        if portspec == '*':
            portMin = 1
            portMax = 65535
        elif '-' not in portspec:
            portMin = portMax = int(portspec)
        else:
            portMin, portMax = map(int,portspec.split("-",1))

        return Pattern(ip,mask,portMin,portMax)

    parse = staticmethod(parse)

    def appliesTo(self, ip, port):
        return ((maskIP(ip,self.mask) == self.ip) and
                (self.portMin <= port <= self.portMax))

class Policy:
    """
    >>> import socket
    >>> ip1 = socket.inet_aton("192.169.64.11")
    >>> ip2 = socket.inet_aton("192.168.64.11")
    >>> ip3 = socket.inet_aton("18.244.0.188")

    >>> pol = Policy.parseLines(["reject *:80","accept 18.244.0.188:*"])
    >>> print str(pol).strip()
    reject 0.0.0.0/0.0.0.0:80-80
    accept 18.244.0.188/255.255.255.255:1-65535
    >>> pol.accepts(ip1,80)
    False
    >>> pol.accepts(ip3,80)
    False
    >>> pol.accepts(ip3,81)
    True
    """

    def __init__(self, lst):
        self.lst = lst

    def parseLines(lines):
        r = []
        for item in lines:
            a,p=item.split(" ",1)
            if a == 'accept':
                a = True
            elif a == 'reject':
                a = False
            else:
                raise ValueError("Unrecognized action %r",a)
            p = Pattern.parse(p)
            r.append((p,a))
        return Policy(r)

    parseLines = staticmethod(parseLines)

    def __str__(self):
        r = []
        for pat, accept in self.lst:
            rule = accept and "accept" or "reject"
            r.append("%s %s\n"%(rule,pat))
        return "".join(r)

    def accepts(self, ip, port):
        for pattern,accept in self.lst:
            if pattern.appliesTo(ip,port):
                return accept
        return True

class Server:
    def __init__(self, name, ip, policy):
        self.name = name
        self.ip = ip
        self.policy = policy

def uniq_sort(lst):
    d = {}
    for item in lst: d[item] = 1
    lst = d.keys()
    lst.sort()
    return lst

def run():
    global VERBOSE
    global INVERSE
    global ADDRESSES_OF_INTEREST

    if len(sys.argv) > 1:
        try:
            opts, pargs = getopt.getopt(sys.argv[1:], "vx")
        except getopt.GetoptError, e:
            print """
usage: %s [-v] [-x] [host:port [host:port [...]]]
    -v  verbose output
    -x  invert results
""" % sys.argv[0]
            sys.exit(0)

        for o, a in opts:
            if o == "-v":
                VERBOSE = True
            if o == "-x":
                INVERSE = True
        if len(pargs):
            ADDRESSES_OF_INTEREST = "\n".join(pargs)

    servers = []
    policy = []
    name = ip = None
    for line in sys.stdin.xreadlines():
        if line.startswith('router '):
            if name:
                servers.append(Server(name, ip, Policy.parseLines(policy)))
            _, name, ip, rest = line.split(" ", 3)
            policy = []
        elif line.startswith('accept ') or line.startswith('reject '):
            policy.append(line.strip())

    if name:
        servers.append(Server(name, ip, Policy.parseLines(policy)))

    targets = []
    for line in ADDRESSES_OF_INTEREST.split("\n"):
        line = line.strip()
        if not line: continue
        p = Pattern.parse(line)
        targets.append((p.ip, p.portMin))

    accepters, rejecters = [], []
    for s in servers:
        for ip,port in targets:
            if s.policy.accepts(ip,port):
                accepters.append(s)
                break
        else:
            rejecters.append(s)

    if INVERSE:
        printlist = rejecters
    else:
        printlist = accepters

    ents = []
    if VERBOSE:
        ents = uniq_sort([ "%s\t%s"%(s.ip,s.name) for s in printlist ])
    else:
        ents = uniq_sort([ s.ip for s in printlist ])
    for e in ents:
        print e

def _test():
    import doctest, exitparse
    return doctest.testmod(exitparse)
#_test()

run()