def connect(self, controllerIP, port): try: self.comm_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.comm_sock.connect((controllerIP, port)) except Exception as e: sdnpwn.message("Problem connecting to " + controllerIP + ":" + str(port), sdnpwn.ERROR) print return sdnpwn.message("Socket connected. Sending OF Hello...", sdnpwn.SUCCESS) ofHello = Hello() header = Header() self.comm_sock.send(ofHello.pack()) #Send Hello replyHeader = self.comm_sock.recv(8) #Get hello response header & body header.unpack(replyHeader) sdnpwn.message("Got " + str(header.message_type), sdnpwn.NORMAL) #sdnpwn.message("Controller base OF version: " + str(header.version), sdnpwn.VERBOSE) replyBody = self.comm_sock.recv(header.length-8) #Get body but ignore sdnpwn.message("Connected to controller", sdnpwn.SUCCESS) if(self.auto_handle_Messages == True): run = True sdnpwn.message("Handling OpenFlow messages automatically", sdnpwn.NORMAL) while(run): #try: #Get feature request reply = self.comm_sock.recv(8) header.unpack(reply) if(header.length == None): sdnpwn.message("Got bad OF message. Closing.", sdnpwn.WARNING) run = False self.comm_sock.close() else: replyBody = self.comm_sock.recv(header.length-8) try: autohandleOFMessage(self, header, replyBody, self.enable_output) except: sdnpwn.message("Error handling OF message", sdnpwn.WARNING) #except Exception as e: #sdnpwn.message("Socket disconnected", sdnpwn.ERROR) #print(e) #self.comm_sock.close() #break else: return True
def sendAndReceiveOF_HELLO_OPENFLOWV1(self): count = 0 # create OF_HEllO message packed_data = Hello().pack() while count < self.numberOfRetransmission: try: # send OF_HEllO message to contoller self.s.send(packed_data) print("Switch ip " + self.switchIp + " Send OF_HELLO message to controller") # receive OF_HELLO message from controller data = self.s.recv(self.buffer_size) data = unpack_message(data) if data.header.message_type.name == "OFPT_HELLO": print("Switch ip " + self.switchIp + " Receive OF_HELLO message from controller") return except Exception as err: count += 1 print(" 322 Switch ip " + self.switchIp + " handling run-time error of socket : " + str(err)) print(" Switch ip " + self.switchIp + " terminate") sys.exit()
def __init__(self, dpid, warmup_time_s, upstream_ip, upstream_port, initial_xid, throughput_mode, enable_tls=False): Thread.__init__(self) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.dpid = dpid self.currentXid = initial_xid self.should_stop = self.getCurrentMicroSeconds() + 5000 * 1000000 self.results = [] self.warmup_time_s = warmup_time_s self.upstream_ip = upstream_ip self.upstream_port = upstream_port self.messageGenerator = MessageGenerator() self.last_packetin_sent = self.getCurrentMicroSeconds() self.throughput_mode = throughput_mode self.enable_tls = enable_tls try: self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except (OSError, NameError): pass self.messages_to_send = [(2, Hello().pack())]
def test_pack_unpack_with_hello(self): """`Hello` message in `data` field after packing and unpacking.""" # packed data p_hello = Hello() self.error_msg.data = p_hello packed = self.error_msg.pack() # unpacked data u_error = ErrorMsg() u_error.unpack(packed) u_hello = u_error.data self.assertEqual(p_hello, u_hello)
def sendAndReceiveOF_HELLO_OPENFLOWV1(self): #init value count = 0 tempBytes = None # create OF_HEllO message packed_data = Hello().pack() while count < self.numberOfRetransmission: try: # send OF_HEllO message to contoller self.s.send(packed_data) print("Switch ip " + self.switchIp + " Send OF_HELLO message to controller") # receive OF_HELLO message from controller data = self.s.recv(self.buffer_size) print("hello message len : " + str(len(data))) # temp for byte data tempBytes = data data = unpack_message(data) if data.header.message_type.name == "OFPT_HELLO": print("Switch ip " + self.switchIp + " Receive OF_HELLO message from controller") if len(tempBytes) == 8: return False, None else: print(tempBytes[8:16]) return True, tempBytes[8:16] except Exception as err: count += 1 print(" 322 Switch ip " + self.switchIp + " handling run-time error of socket : " + str(err)) print(" Switch ip " + self.switchIp + " terminate") sys.exit()
def do_handshake(client): """Get a client (socket) and do the handshake of it. This method receives a client (socket) that simulates a switch on the network and do the OpenFlow handshake process with a running controller on the network. Args: client (socket): a socket object connected on the controller. Returns: The client with the handshake process done. """ # -- STEP 1: Sending Hello message client.send(Hello(xid=3).pack()) # -- STEP 2: Whait for Hello response binary_packet = b'' while len(binary_packet) < 8: binary_packet = client.recv(8) header = Header() header.unpack(binary_packet) # -- STEP 3: Wait for features_request message binary_packet = b'' # len() < 8 here because we just expect a Hello as response while len(binary_packet) < 8: binary_packet = client.recv(8) header = Header() header.unpack(binary_packet) # -- STEP 4: Send features_reply to the controller basedir = os.path.dirname(os.path.abspath(__file__)) raw_dir = os.path.join(basedir, 'raw') message = None with open(os.path.join(raw_dir, 'features_reply.cap'), 'rb') as file: message = file.read() client.send(message) return client
def run(params): targets = None #Full list of targets verbose = False signal.signal(signal.SIGINT, signal_handler) target = sdnpwn.getArg(["--target", "-t"], params) port = sdnpwn.getArg(["--port", "-p"], params) sockTimeout = sdnpwn.getArg(["--socket-timeout", "-s"], params, 2) count = int(sdnpwn.getArg(["--count", "-c"], params, 1)) delay = float(sdnpwn.getArg(["--delay", "-d"], params, 1)) verbose = sdnpwn.checkArg(["--verbose", "-v"], params) if (target == None): print(info()) print(usage()) return else: startIndex = 0 endIndex = 1 if ("/" in target): targets = ip_network(target) startIndex = 1 endIndex = targets.num_addresses - 2 else: targets = ip_network(str(target) + "/32") if (port == None): sdnpwn.message("No ports given, using 6633,6634, and 6653.", sdnpwn.NORMAL) port = "6633,6634,6653" for host in range(startIndex, endIndex): targetHost = targets[host].exploded for p in port.split(","): for c in range(count): sleep(delay) sock = getSocket(targetHost, p, float(sockTimeout)) if (sock != None): targetLabel = str(targetHost) + ":" + str(p) if (verbose == True): sdnpwn.message( "Connected to " + str(targetHost) + ":" + str(p), sdnpwn.NORMAL) #print(params) #for msg in params: #action = { #"--hello":sendHello, #"echo-req":sendEchoRequest #}[msg] #action(sock) #TODO: Remove following items in favour of above if ("--hello" in params): sdnpwn.message( "Sending OF Hello to " + str(targetHost), sdnpwn.NORMAL) ofHello = Hello() sock.send(ofHello.pack()) if ("--echo-request" in params): sdnpwn.message( "Sending OF Echo Request to " + str(targetHost), sdnpwn.NORMAL) echoReq = EchoRequest() sock.send(echoReq.pack()) if ("--packet-in" in params): xid = 13 bufferId = 0 totalLength = -1 inPort = 0 reason = "" data = b'' try: xid = params[params.index("--xid") + 1] # int bufferId = params[params.index("--buffer-id") + 1] # int if ("--total-length" in params): totalLength = params[ params.index("--total-length") + 1] # int Full length of frame inPort = params[params.index("--in-port") + 1] # int reason = params[params.index("--reason") + 1] #match or action if (reason == "match"): reason = 0 #PacketInReason.OFPR_MATCH elif (reason == "action"): reason = 1 #PacketInReason.OFPR_ACTION else: sdnpwn.message( "Invalid 'reason' argument given! Should be 'match' or 'action'", sdnpwn.ERROR) exit(0) dataBin = b'' if ("--data-raw" in params): data = params[params.index("--data-raw") + 1] #Data in bytes dataBin = codecs.decode(data, 'hex_codec') elif ("--data-scapy" in params): try: cmd = params[params.index("--data-scapy") + 1] #Data as scapy code pkt = eval( cmd) #Get packet from scapy objects dataBin = codecs.decode( scapy_packet_to_string(pkt), 'hex_codec') dataBin = bytes(pkt) except Exception as e: sdnpwn.message( "Error building Scapy packet", sdnpwn.ERROR) print(e) except Exception as e: sdnpwn.message( "Missing paramerters for OF Packet In!", sdnpwn.ERROR) print(e) if (totalLength == -1): totalLength = len(dataBin) pktIn = PacketIn(xid=int(xid), buffer_id=int(bufferId), total_len=int(totalLength), in_port=int(inPort), reason=int(reason), data=dataBin) sdnpwn.message( "Sending OF Packet In to " + str(targetHost), sdnpwn.NORMAL) sock.send(pktIn.pack()) if ("--hold-open" not in params): sock.close() else: sdnpwn.message("Holding socket open", sdnpwn.NORMAL) else: sdnpwn.message( "Could not connect to " + targetHost + " on socket " + str(p), sdnpwn.WARNING) if ("--hold-open" in params): sdnpwn.message("Keeping sockets open. Use CTRL+C to stop...", sdnpwn.NORMAL) while (1): sleep(2)
def initConnectionToController(self): count = 0 while count < self.numberOfRetransmission: try: packed_data = Hello().pack() # send OF_HEllO message to contoller self.s.send(packed_data) print("Switch ip " + self.switchIp + " Send OF_HELLO message to controller") # receive OF_HELLO message from controller data = self.s.recv(self.buffer_size) data = unpack_message(data) if data.header.message_type.name == "OFPT_HELLO": print("Switch ip " + self.switchIp + " Receive OF_HELLO message from controller") data = self.s.recv(self.buffer_size) data = unpack_message(data) print( " 428 Switch ip " + self.switchIp + " Receive OF_FEATURE_REQUEST message from controller") if data.header.message_type.name == "OFPT_FEATURES_REQUEST": # get tranID from OF_FEATURE_REQUEST message tranID = data.header.xid #send OF_FEATURE_REPLY message listPort = self.createOFFeatureReplyFromSnmpVersion2C( 1) print("All active port of switch ip " + self.switchIp + " : ") for i in listPort: print("Hw_addr : " + i.hw_addr) print("Hw_desc : " + i.name) # find max value of mac address from list mac address maxPort = "000000000000" maxIndex = 0 for index, item in enumerate(listPort): tempMac = item.hw_addr.replace(":", "") if (int(tempMac, 16) > int(maxPort, 16)): maxPort = tempMac maxIndex = index # create OF_FEATURE_REPLY message packed_data = FeaRes() packed_data.header.xid = tranID # gen datapath_id from hw_addr of first port packed_data.datapath_id = listPort[ maxIndex].hw_addr + ":ff:ff" #packed_data.datapath_id = '00:00:00:00:00:00:00:02' packed_data.n_buffers = 256 packed_data.n_tables = 254 packed_data.capabilities = 199 packed_data.actions = 4095 # create port #port1 = PPort(1, '00:00:00:00:00:02','eth1', 0, 0, 192 ,0,0,0) #packed_data.ports = [port1] packed_data.ports = listPort packed_data = packed_data.pack() # send OF_FEATURE_REPLY message self.s.send(packed_data) print("Send OF_FEATURE_REPLY message to controller") return except Exception as err: count += 1 print(" 322 Switch ip " + self.switchIp + " handling run-time error of socket : " + str(err)) print(" Switch ip " + self.switchIp + " terminate") sys.exit()