示例#1
0
 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
示例#2
0
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)
示例#3
0
    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()