-
Notifications
You must be signed in to change notification settings - Fork 65
/
intercept.py
286 lines (229 loc) · 9.84 KB
/
intercept.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
import os
import random
import traceback
from uuid import UUID
from OpenSSL import SSL
from twisted.internet import reactor, ssl, protocol
from twisted.python import log
from icl0ud.push.dispatch import BaseDispatch
from icl0ud.push.parser import APSParser
class MessageProxy(protocol.Protocol, BaseDispatch, object):
peer = None
peer_type = None # device or server
def __init__(self):
self._parser = APSParser()
self._source = None
self._buffer = b''
def setPeer(self, peer):
self.peer = peer
def dataReceived(self, data):
buff = self._buffer + data
while self._parser.isMessageComplete(buff):
message, length = self._parser.parseMessage(buff)
messageData = buff[:length]
buff = buff[length:]
self.handleMessage(message, messageData)
self._buffer = buff
def handleMessage(self, message, data):
forward = self.dispatch(self.peer_type, message)
if forward:
self.sendToPeer(data)
def sendToPeer(self, data):
self.peer.transport.write(data)
def connectionLost(self, reason):
# TODO notify handlers
# FIXME fix this shutdown
if self.peer is not None:
self.peer.transport.loseConnection()
self.peer = None
else:
log.msg("Unable to connect to peer: %s" % (reason,))
class InterceptClient(MessageProxy):
"""Proxy Client, captures iCloud-to-client traffic."""
peer_type = 'server'
def connectionMade(self):
self.peer.connectedToServer(self)
def getDeviceProtocol(self):
return self.factory.deviceProtocol
class InterceptClientFactory(protocol.ClientFactory):
protocol = InterceptClient
def __init__(self, deviceProtocol):
self.deviceProtocol = deviceProtocol
def buildProtocol(self, *args, **kw):
prot = protocol.ClientFactory.buildProtocol(self, *args, **kw)
prot.setPeer(self.deviceProtocol)
prot.addHandlers(self.dispatchHandlers)
return prot
def clientConnectionFailed(self, connector, reason):
self.deviceProtocol.transport.loseConnection()
def setDispatchHandlers(self, handlers):
self.dispatchHandlers = handlers
class InterceptClientContextFactory(ssl.ClientContextFactory):
def __init__(self, cert, chain):
self.cert = cert
self.chain = chain
self.method = SSL.SSLv23_METHOD
def _verifyCallback(self, conn, cert, errno, depth, preverifyOk):
# FIXME we should check the server common name
if not preverifyOk:
log.err("Certificate validation failed.")
return preverifyOk
def getContext(self):
ctx = ssl.ClientContextFactory.getContext(self)
ctx.load_verify_locations(self.chain)
ctx.use_certificate_file(self.cert)
ctx.use_privatekey_file(self.cert)
ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
self._verifyCallback)
return ctx
class InterceptServer(MessageProxy):
"""Proxy Server, captures client-to-iCloud traffic."""
clientProtocolFactory = InterceptClientFactory
peer_type = 'device'
def __init__(self, *args, **kwargs):
super(InterceptServer, self).__init__(*args, **kwargs)
self.clientContextFactory = None
self.deviceCommonName = None
self._peerSendBuffer = b''
def SSLInfoCallback(self, conn, where, ret):
# TODO check why this callback is called two times with HANDSHAKE_DONE
# - do not attempt to connect to server twice
# SSL.SSL_CB_HANDSHAKE_DONE(0x20) is missing in old pyOpenSSL releases
if where & 0x20:
try: # Catch exceptions since this function does not throw them
try:
# Twisted < 11.1
cert = self.transport.socket.get_peer_certificate()
except AttributeError:
# Twisted >= 11.1
cert = self.transport.getPeerCertificate()
subject = dict(cert.get_subject().get_components())
self.deviceCommonName = subject['CN']
self.log('SSL handshake done: Device: %s' %
self.deviceCommonName)
self.connectToServer()
except Exception:
log.err('[#%d] SSLInfoCallback Exception:' %
self.transport.sessionno)
log.err(traceback.format_exc())
def connectionMade(self):
try:
# Twisted < 11.1
sslContext = self.transport.socket.get_context()
except AttributeError:
# Twisted >= 11.1
# TODO Don't use private attribute _tlsConnection
sslContext = self.transport._tlsConnection.get_context()
sslContext.set_info_callback(self.SSLInfoCallback)
peer = self.transport.getPeer()
self.log('New connection from %s:%d' % (peer.host, peer.port))
def connectToServer(self):
# Don't read anything from the connecting client until we have
# somewhere to send it to.
self.transport.pauseProducing()
clientFactory = self.getClientFactory()
host = random.choice(self.factory.hosts)
self.log('Connecting to push server: %s:%d' %
(host, self.factory.port))
reactor.connectSSL(host,
self.factory.port,
clientFactory,
self.getClientContextFactory())
def connectedToServer(self, peer):
self.setPeer(peer)
self.flushSendBuffer()
self.transport.resumeProducing()
def getDeviceProtocol(self):
return self
def sendToPeer(self, data):
# This happens if connectToserver is not called fast enough to stop
# the transport from producing. We send the buffer once the client
# connection is established.
if self.peer is None:
self._peerSendBuffer += data
else:
super(InterceptServer, self).sendToPeer(data)
def flushSendBuffer(self):
self.sendToPeer(self._peerSendBuffer)
self._peerSendBuffer = b''
def getClientFactory(self, ):
f = self.clientProtocolFactory(deviceProtocol=self)
f.setDispatchHandlers(self.factory.dispatchHandlers)
return f
def getClientContextFactory(self):
certDir = self.factory.clientCertDir
# ensure this is a valid UUID, if not this throws an exception
UUID(self.deviceCommonName)
cert = os.path.join(certDir, self.deviceCommonName + '.pem')
if not os.path.isfile(cert):
raise Exception('Device certificate is missing: %s' % cert)
if self.clientContextFactory is None:
self.clientContextFactory = InterceptClientContextFactory(
cert=cert,
chain=self.factory.caCertChain,
)
return self.clientContextFactory
def log(self, msg):
prefix = '[#%d] ' % self.transport.sessionno
log.msg(prefix + msg)
class InterceptServerFactory(protocol.Factory):
protocol = InterceptServer
serverContextFactory = None
def __init__(self, hosts, port, serverCert, clientCertDir, caCertChain,
serverChain, dispatchHandlers=[]):
self.hosts = hosts
self.port = port
# Passing through the complete configuration seems quite ugly. Maybe
# implement a Service?
# The courier.push.apple.com server certificate
self.serverCert = serverCert
# Directory containing device certificates
self.clientCertDir = clientCertDir
# The cert chain for verifying Apple's server certificate
self.caCertChain = caCertChain
# The cert chain for verifying device certificates
self.serverChain = serverChain
self.dispatchHandlers = dispatchHandlers
def buildProtocol(self, *args):
p = protocol.Factory.buildProtocol(self, *args)
p.addHandlers(self.dispatchHandlers)
return p
def getServerContextFactory(self):
if self.serverContextFactory is None:
self.serverContextFactory = InterceptServerContextFactory(
self.serverCert,
self.serverChain
)
return self.serverContextFactory
class InterceptServerContextFactory(ssl.DefaultOpenSSLContextFactory):
def __init__(self, cert, chain):
self.chain = chain
self.cert = cert
ssl.DefaultOpenSSLContextFactory.__init__(self, cert, cert)
def getContext(self):
ctx = ssl.DefaultOpenSSLContextFactory.getContext(self)
ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
self._verifyCallback)
ctx.load_verify_locations(self.chain)
ctx.use_certificate_chain_file(self.cert)
# Disable session cache - we don't want to configure it and
# performance is not important.
# Should fix 'session id context uninitialized' errors.
# Requires pyOpenSSL >= 0.14
ctx.set_session_cache_mode(SSL.SESS_CACHE_OFF)
return ctx
def _verifyCallback(self, conn, cert, errno, depth, preverifyOk):
# The following intermediate certificate expired on Apr 16 22:54:46 2014 GMT
#
# subject=/C=US/O=Apple Inc./OU=Apple iPhone/CN=Apple iPhone Device CA
#
# - skipping verification here. This makes things insecure,
# but let's hope not a lot of people are using pushproxy publicly
# anyway. VERIFY_PEER above is required, otherwise OpenSSL doesn't
# request a client certificate.
#
# If this is a problem, one might implement certificate checking based on
# the push certificates themselves instead of checking the chain.
# It could also be possible to manually check everything here and just
# ignore the expiry date for the specific certificate.
return True