forked from prakhar79/Adaptive-Threat-Prevention-in-POX
-
Notifications
You must be signed in to change notification settings - Fork 0
/
atp_l3_learning.py
345 lines (285 loc) · 12.3 KB
/
atp_l3_learning.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# Copyright 2012-2013 James McCauley
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
A stupid L3 switch
For each switch:
1) Keep a table that maps IP addresses to MAC addresses and switch ports.
Stock this table using information from ARP and IP packets.
2) When you see an ARP query, try to answer it using information in the table
from step 1. If the info in the table is old, just flood the query.
3) Flood all other ARPs.
4) When you see an IP packet, if you know the destination port (because it's
in the table from step 1), install a flow for it.
"""
from pox.core import core
import pox
log = core.getLogger()
from pox.lib.packet.ethernet import ethernet, ETHER_BROADCAST
from pox.lib.packet.ipv4 import ipv4
from pox.lib.packet.arp import arp
from pox.lib.addresses import IPAddr, EthAddr
from pox.lib.util import str_to_bool, dpid_to_str
from pox.lib.recoco import Timer
import pox.openflow.libopenflow_01 as of
from pox.lib.revent import *
import time
# Timeout for flows
FLOW_IDLE_TIMEOUT = 5
FLOW_HARD_TIMEOUT = 60
# Timeout for ARP entries
ARP_TIMEOUT = 60 * 2
# Maximum number of packet to buffer on a switch for an unknown IP
MAX_BUFFERED_PER_IP = 5
# Maximum time to hang on to a buffer for an unknown IP in seconds
MAX_BUFFER_TIME = 5
class Entry (object):
"""
Not strictly an ARP entry.
We use the port to determine which port to forward traffic out of.
We use the MAC to answer ARP replies.
We use the timeout so that if an entry is older than ARP_TIMEOUT, we
flood the ARP request rather than try to answer it ourselves.
"""
def __init__ (self, port, mac):
self.timeout = time.time() + ARP_TIMEOUT
self.port = port
self.mac = mac
def __eq__ (self, other):
if type(other) == tuple:
return (self.port,self.mac)==other
else:
return (self.port,self.mac)==(other.port,other.mac)
def __ne__ (self, other):
return not self.__eq__(other)
def isExpired (self):
if self.port == of.OFPP_NONE: return False
return time.time() > self.timeout
def dpid_to_mac (dpid):
return EthAddr("%012x" % (dpid & 0xffFFffFFffFF,))
class l3_switch (EventMixin):
def __init__ (self, fakeways = [], arp_for_unknowns = False):
# These are "fake gateways" -- we'll answer ARPs for them with MAC
# of the switch they're connected to.
self.fakeways = set(fakeways)
# If this is true and we see a packet for an unknown
# host, we'll ARP for it.
self.arp_for_unknowns = arp_for_unknowns
# (dpid,IP) -> expire_time
# We use this to keep from spamming ARPs
self.outstanding_arps = {}
# (dpid,IP) -> [(expire_time,buffer_id,in_port), ...]
# These are buffers we've gotten at this datapath for this IP which
# we can't deliver because we don't know where they go.
self.lost_buffers = {}
# For each switch, we map IP addresses to Entries
self.arpTable = {}
# This timer handles expiring stuff
self._expire_timer = Timer(5, self._handle_expiration, recurring=True)
self.listenTo(core)
def _handle_expiration (self):
# Called by a timer so that we can remove old items.
empty = []
for k,v in self.lost_buffers.iteritems():
dpid,ip = k
for item in list(v):
expires_at,buffer_id,in_port = item
if expires_at < time.time():
# This packet is old. Tell this switch to drop it.
v.remove(item)
po = of.ofp_packet_out(buffer_id = buffer_id, in_port = in_port)
core.openflow.sendToDPID(dpid, po)
if len(v) == 0: empty.append(k)
# Remove empty buffer bins
for k in empty:
del self.lost_buffers[k]
def _send_lost_buffers (self, dpid, ipaddr, macaddr, port):
"""
We may have "lost" buffers -- packets we got but didn't know
where to send at the time. We may know now. Try and see.
"""
if (dpid,ipaddr) in self.lost_buffers:
# Yup!
bucket = self.lost_buffers[(dpid,ipaddr)]
del self.lost_buffers[(dpid,ipaddr)]
log.debug("Sending %i buffered packets to %s from %s"
% (len(bucket),ipaddr,dpid_to_str(dpid)))
for _,buffer_id,in_port in bucket:
po = of.ofp_packet_out(buffer_id=buffer_id,in_port=in_port)
po.actions.append(of.ofp_action_dl_addr.set_dst(macaddr))
po.actions.append(of.ofp_action_output(port = port))
core.openflow.sendToDPID(dpid, po)
def _handle_GoingUpEvent (self, event):
self.listenTo(core.openflow)
self.listenTo(core.adaptiveThreatPrevention)
self.listenTo(core.atp_events)
log.debug("Up...")
def _handle_addFlowEntry (self,event):
FLOW_IDLE_TIMEOUT = event.idleTimeout
FLOW_HARD_TIMEOUT = event.hardTimeout
event = event.event
dpid = event.connection.dpid
inport = event.port
packet = event.parsed
if not packet.parsed:
log.warning("%i %i ignoring unparsed packet", dpid, inport)
return
if dpid not in self.arpTable:
# New switch -- create an empty table
self.arpTable[dpid] = {}
for fake in self.fakeways:
self.arpTable[dpid][IPAddr(fake)] = Entry(of.OFPP_NONE,
dpid_to_mac(dpid))
if packet.type == ethernet.LLDP_TYPE:
# Ignore LLDP packets
return
if isinstance(packet.next, ipv4):
log.debug("%i %i IP %s => %s", dpid,inport,
packet.next.srcip,packet.next.dstip)
# Send any waiting packets...
self._send_lost_buffers(dpid, packet.next.srcip, packet.src, inport)
# Learn or update port/MAC info
if packet.next.srcip in self.arpTable[dpid]:
if self.arpTable[dpid][packet.next.srcip] != (inport, packet.src):
log.info("%i %i RE-learned %s", dpid,inport,packet.next.srcip)
else:
log.debug("%i %i learned %s", dpid,inport,str(packet.next.srcip))
self.arpTable[dpid][packet.next.srcip] = Entry(inport, packet.src)
# Try to forward
dstaddr = packet.next.dstip
if dstaddr in self.arpTable[dpid]:
# We have info about what port to send it out on...
prt = self.arpTable[dpid][dstaddr].port
mac = self.arpTable[dpid][dstaddr].mac
if prt == inport:
log.warning("%i %i not sending packet for %s back out of the " +
"input port" % (dpid, inport, str(dstaddr)))
else:
log.debug("%i %i installing flow for %s => %s out port %i"
% (dpid, inport, packet.next.srcip, dstaddr, prt))
actions = []
actions.append(of.ofp_action_dl_addr.set_dst(mac))
actions.append(of.ofp_action_output(port = prt))
match = of.ofp_match.from_packet(packet, inport)
match.dl_src = None # Wildcard source MAC
msg = of.ofp_flow_mod(command=of.OFPFC_ADD,
idle_timeout=FLOW_IDLE_TIMEOUT,
hard_timeout=FLOW_HARD_TIMEOUT,
buffer_id=event.ofp.buffer_id,
actions=actions,
flags=of.OFPFF_SEND_FLOW_REM,
match=of.ofp_match.from_packet(packet,
inport))
event.connection.send(msg.pack())
elif self.arp_for_unknowns:
# We don't know this destination.
# First, we track this buffer so that we can try to resend it later
# if we learn the destination, second we ARP for the destination,
# which should ultimately result in it responding and us learning
# where it is
# Add to tracked buffers
if (dpid,dstaddr) not in self.lost_buffers:
self.lost_buffers[(dpid,dstaddr)] = []
bucket = self.lost_buffers[(dpid,dstaddr)]
entry = (time.time() + MAX_BUFFER_TIME,event.ofp.buffer_id,inport)
bucket.append(entry)
while len(bucket) > MAX_BUFFERED_PER_IP: del bucket[0]
# Expire things from our outstanding ARP list...
self.outstanding_arps = {k:v for k,v in
self.outstanding_arps.iteritems() if v > time.time()}
# Check if we've already ARPed recently
if (dpid,dstaddr) in self.outstanding_arps:
# Oop, we've already done this one recently.
return
# And ARP...
self.outstanding_arps[(dpid,dstaddr)] = time.time() + 4
r = arp()
r.hwtype = r.HW_TYPE_ETHERNET
r.prototype = r.PROTO_TYPE_IP
r.hwlen = 6
r.protolen = r.protolen
r.opcode = r.REQUEST
r.hwdst = ETHER_BROADCAST
r.protodst = dstaddr
r.hwsrc = packet.src
r.protosrc = packet.next.srcip
e = ethernet(type=ethernet.ARP_TYPE, src=packet.src,
dst=ETHER_BROADCAST)
e.set_payload(r)
log.debug("%i %i ARPing for %s on behalf of %s" % (dpid, inport,
str(r.protodst), str(r.protosrc)))
msg = of.ofp_packet_out()
msg.data = e.pack()
msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
msg.in_port = inport
event.connection.send(msg)
elif isinstance(packet.next, arp):
a = packet.next
log.debug("%i %i ARP %s %s => %s", dpid, inport,
{arp.REQUEST:"request",arp.REPLY:"reply"}.get(a.opcode,
'op:%i' % (a.opcode,)), str(a.protosrc), str(a.protodst))
if a.prototype == arp.PROTO_TYPE_IP:
if a.hwtype == arp.HW_TYPE_ETHERNET:
if a.protosrc != 0:
# Learn or update port/MAC info
if a.protosrc in self.arpTable[dpid]:
if self.arpTable[dpid][a.protosrc] != (inport, packet.src):
log.info("%i %i RE-learned %s", dpid,inport,str(a.protosrc))
else:
log.debug("%i %i learned %s", dpid,inport,str(a.protosrc))
self.arpTable[dpid][a.protosrc] = Entry(inport, packet.src)
# Send any waiting packets...
self._send_lost_buffers(dpid, a.protosrc, packet.src, inport)
if a.opcode == arp.REQUEST:
# Maybe we can answer
if a.protodst in self.arpTable[dpid]:
# We have an answer...
if not self.arpTable[dpid][a.protodst].isExpired():
# .. and it's relatively current, so we'll reply ourselves
r = arp()
r.hwtype = a.hwtype
r.prototype = a.prototype
r.hwlen = a.hwlen
r.protolen = a.protolen
r.opcode = arp.REPLY
r.hwdst = a.hwsrc
r.protodst = a.protosrc
r.protosrc = a.protodst
r.hwsrc = self.arpTable[dpid][a.protodst].mac
e = ethernet(type=packet.type, src=dpid_to_mac(dpid),
dst=a.hwsrc)
e.set_payload(r)
log.debug("%i %i answering ARP for %s" % (dpid, inport,
str(r.protosrc)))
msg = of.ofp_packet_out()
msg.data = e.pack()
msg.actions.append(of.ofp_action_output(port =
of.OFPP_IN_PORT))
msg.in_port = inport
event.connection.send(msg)
return
# Didn't know how to answer or otherwise handle this ARP, so just flood it
log.debug("%i %i flooding ARP %s %s => %s" % (dpid, inport,
{arp.REQUEST:"request",arp.REPLY:"reply"}.get(a.opcode,
'op:%i' % (a.opcode,)), str(a.protosrc), str(a.protodst)))
msg = of.ofp_packet_out(in_port = inport, data = event.ofp,
action = of.ofp_action_output(port = of.OFPP_FLOOD))
event.connection.send(msg)
def launch (fakeways="", arp_for_unknowns=None):
fakeways = fakeways.replace(","," ").split()
fakeways = [IPAddr(x) for x in fakeways]
if arp_for_unknowns is None:
arp_for_unknowns = len(fakeways) > 0
else:
arp_for_unknowns = str_to_bool(arp_for_unknowns)
core.registerNew(l3_switch, fakeways, arp_for_unknowns)