Exemple #1
0
 def __init__(self, lowerTransport):
     StackingTransport.__init__(self, lowerTransport)
     #The next sequence number to send data, the field should be
     #updated every time a message is sent.
     self.nextSequenceNumber = int(os.urandom(4).encode('hex'), 16)
     #The current session ID, established in the handshake
     self.sessionID = ""
     #A list of the messages sent that have not yet been acknowledged.
     self.unacknowledgedSent = []
     #The maximum segment size
     self.mss = 4096
     #The current state of the RIP
     self.state = "LISTEN"
     #The timeout period before retransmission
     self.timeout = 4
     #The maximum number of messages sent without an ack
     self.maxSent = 256
     #The buffer to hold any messages sent after the 256th message
     self.sendOverflow = []
     #Timeout for idle/wait in protocol
     self.idleTimeout = None
     #Timeout period for idle/wait
     self.idleTimeoutPeriod = 120
     #The certs for the peer
     self.peerCerts = None
Exemple #2
0
    def data_received(self, buffer):
        logger.debug("{} passthrough received a buffer of size {}".format(
            self._mode, len(buffer)))
        # after handshake successfully, the deserializer should be changed
        # if self.flag == 0:
        #     self.buffer = HandshakePacket.Deserializer()
        #     self.buffer.update(buffer)
        # else:
        #     self.buffer = PacketType.Deserializer()
        #     self.buffer.update(buffer)
        self.buffer = PoopPacketType.Deserializer()
        self.buffer.update(buffer)

        for packet in self.buffer.nextPackets():
            print(packet)
            if self._mode == "server":
                if packet.status == 0:
                    if packet.SYN:
                        # Upon receiving packet, the server sends back a packet with SYN+1, ACK set to 0 and status SUCCESS.
                        new_packet = HandshakePacket()
                        new_packet.SYN = packet.SYN + 1
                        new_packet.ACK = 0
                        new_packet.status = 1
                        self.transport.write(new_packet.__serialize__())
                    else:
                        new_packet = HandshakePacket()
                        new_packet.status = 2
                        self.transport.write(new_packet.__serialize__())

                elif packet.ACK == 1:
                    # Upon receiving the SUCCESS packet, the server checks if ACK is 1. If success, the server
                    # acknowledges this connection. Else, the server sends back a packet to the client with status
                    # ERROR.
                    higher_transport = StackingTransport(self.transport)
                    self.higherProtocol().connection_made(higher_transport)
                    self.flag = 1
                else:
                    new_packet = HandshakePacket()
                    new_packet.status = 2
                    self.transport.write(new_packet.__serialize__())

            elif self._mode == "client":
                # Upon receiving the SUCCESS packet, the client checks if new SYN is old SYN + 1. If it is correct,
                # the client sends back to server a packet with ACK set to 1 and status SUCCESS and acknowledge this
                # connection with server. Else, the client sends back to server a packet with status set to ERROR.
                if packet.SYN == self.SYN + 1:
                    new_packet = HandshakePacket()
                    new_packet.SYN = packet.SYN + 1
                    new_packet.ACK = 1
                    new_packet.status = 1
                    self.flag = 1
                    self.transport.write(new_packet.__serialize__())
                    higher_transport = StackingTransport(self.transport)
                    self.higherProtocol().connection_made(higher_transport)
                else:
                    new_packet = HandshakePacket()
                    new_packet.status = 2
                    self.transport.write(new_packet.__serialize__())
            else:
                self.higherProtocol().data_received(buffer)
 def loseConnection(self):
     print "transport.loseConnection()"
     if protocolStorage.sendBuffer:
         task.deferLater(reactor, 2, self.retransmission)
     self.retransmission()
     closePacket = createMessage("CLOSE", self.SEQ, self.ACK)
     if self.transportOf == "server":
         closePacket.sessionID = protocolStorage.serverSessionID
         closePacket.signature = signMessage(closePacket.__serialize__(), protocolStorage.serverPrivateKey)
     else:
         closePacket.sessionID = protocolStorage.clientSessionID
         closePacket.signature = signMessage(closePacket.__serialize__(), protocolStorage.clientPrivateKey)
     print "Sending Close Request To Peer"
     self.lowerTransport().write(closePacket.__serialize__())
     StackingTransport.loseConnection(self)
Exemple #4
0
 def connection_made(self, transport):
     print(
         "\nConnection made. Once data is received by PassThrough2, will be sent to higher layer"
     )
     self.transport = transport
     higherTransport = StackingTransport(self.transport)
     self.higherProtocol().connection_made(higherTransport)
Exemple #5
0
    def data_received(self, data):
        print("\n===================== PEEP Server Data_Received called =====================\n")
        self.deserializer.update(data)
        print (data)
        for pkt in self.deserializer.nextPackets():
            # Checksum Check
            # SYN from client
            checkvalue = self.checkChecksum(pkt)
            if pkt.Type == 0 and self.serverstate == 0:
                #window_size += 1
                self.serverstate += 1
                self.clientseq = pkt.SequenceNumber
                if checkvalue == True:
                    print("\n===================== SYN Received. Seq= ", pkt.SequenceNumber, " Ackno=", pkt.Acknowledgement)
                    #Sending SYN
                    print("\n", pkt)
                    synack = PEEP()
                    synack.Type = 1
                    self.length = sys.getsizeof(pkt)
                    synack.Acknowledgement = pkt.SequenceNumber +  sys.getsizeof(pkt) + 1
                    synack.SequenceNumber = random.randint(5000, 9999)
                    self.serverseq = synack.SequenceNumber
                    synack.Checksum = self.calculateChecksum(synack)
                    print("\n=========================== Sending SYN-ACK ========================\n")
                    print(synack)
                    packs = synack.__serialize__()
                    self.transport.write(packs)


                else:
                    print("Checksum error. Packet Data corrupt.")
                    self.transport.close()

            elif pkt.Type == 2 and self.serverstate == 1 and pkt.SequenceNumber == self.clientseq + 1 and pkt.Acknowledgement == self.serverseq + 1:
                # Data transmission can start
                print("\n======================= ACK Received. Seq no=", pkt.SequenceNumber, " Ack no=", pkt.Acknowledgement)

                self.serverstate += 1
                if checkvalue == True:
                    print("\n================ TCP Connection successful! Client OK to send the Data now.============= \n")

                    # calling higher connection made since we have received the ACK

                    peeptransport = PeepServerTransport(self, self.transport)
                    higherTransport = StackingTransport(peeptransport)
                    self.higherProtocol().connection_made(higherTransport)

                else:
                    print("================= Corrupt ACK packet. Please check on client end.===============\n")
                    self.transport.close()

            # Reset packet received
            elif pkt.Type == 5:
                 print("================ Server received connection close from client. Closing socket.===============\n")
Exemple #6
0
    def data_received(self, data):
        print(
            "####################SSL layer data received called!#####################"
        )
        self.deserializer.update(data)
        for packet in self.deserializer.nextPackets():
            if isinstance(packet, PlsHello):
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[0]))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[1]))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[2]))
                print("\nReceived Client Hello packet. Beginning Validation.")
                if self.validate(self.incoming_cert):
                    self.nc = packet.Nonce
                    self.m = hashlib.sha1()
                    self.m.update(packet.__serialize__())
                    print("Certificate Validated. Sending Server hello!\n")
                    self.clientnonce = packet.Nonce
                    serverhello = PlsHello()
                    serverhello.Nonce = int.from_bytes(
                        os.urandom(8), byteorder='big')  #12345678
                    self.ns = serverhello.Nonce
                    idcert = getCertsForAddr(self.address)
                    pubkey = getCertsForAddr(self.splitaddr)
                    root = getRootCert()
                    serverhello.Certs = []
                    serverhello.Certs.append(idcert)
                    serverhello.Certs.append(pubkey)
                    serverhello.Certs.append(root)
                    srvhello = serverhello.__serialize__()
                    print("Sent Server Hello!\n")
                    self.m.update(srvhello)
                    self.transport.write(srvhello)

            if isinstance(packet, PlsKeyExchange):
                print("Received Client Key Exchange. Server Server Keys\n\n")
                self.m.update(packet.__serialize__())
                myprivatekey = getPrivateKeyForAddr(self.address)
                serverpriv = CipherUtil.getPrivateKeyFromPemBytes(myprivatekey)
                decrypted = serverpriv.decrypt(
                    packet.PreKey,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                #print("Decrypted Pre-Master Secret: ", decrypted)
                self.pkc = int.from_bytes(decrypted, byteorder='big')
                #====================================
                #Creating Server Pre-Master
                serverkey = PlsKeyExchange()
                randomvalue = os.urandom(16)  #b'1234567887654321'
                self.pks = int.from_bytes(randomvalue, byteorder='big')
                serverkey.NoncePlusOne = self.clientnonce + 1
                pub_key = self.incoming_cert[0].public_key()
                encrypted = pub_key.encrypt(
                    randomvalue,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                #print("Encrypted String is: ", encrypted)
                serverkey.PreKey = encrypted
                skey = serverkey.__serialize__()
                print("Sent the Prekey to Client.\n\n")
                self.m.update(skey)
                self.transport.write(skey)

            if isinstance(packet, PlsHandshakeDone):
                print("Received Client Handshake done message.")
                clientdigest = packet.ValidationHash
                serverdigest = self.m.digest()
                #print("Hash digest is: ", serverdigest)
                hdone = PlsHandshakeDone()
                hdone.ValidationHash = serverdigest
                if (serverdigest == clientdigest):
                    print("Digest verification done!")
                    # calling higher connection made since we have received the ACK
                    self.key_generator()
                    plstransport = PLSStackingTransport(self, self.transport)
                    higherTransport = StackingTransport(plstransport)
                    self.higherProtocol().connection_made(higherTransport)
                hdone_s = hdone.__serialize__()
                self.transport.write(hdone_s)

            if isinstance(packet, PlsData):
                print(
                    "##################Recieved Data Packet from PLSClient###########################"
                )
                self.ctr = 0
                if self.mac_verification_engine(packet.Ciphertext, packet.Mac):
                    DecryptedPacket = self.decryption_engine(packet.Ciphertext)
                    self.higherProtocol().data_received(DecryptedPacket)

                    self.ctr = 0

                else:
                    self.ctr += 1

                    if self.ctr != 5:
                        print("Verification Failed. Try Again. Failed {}"
                              ).format(self.ctr)

                    else:
                        print(
                            "Verification failed 5 times. Killing Connection and Sending PlsClose."
                        )
                        self.ctr = 0
                        #Creating and Sending PlsClose
                        Close = PlsClose()
                        #Close.Error = "Closing Connection due to 5 Verification failures. Aggrresive Close"
                        serializeClose = Close.__serialize__()
                        self.transport.write(serializeClose)
                        self.transport.close()

            if isinstance(packet, PlsClose):
                print(
                    "######################Received PlsClose from Client######################### "
                )
                #self.connection_lost(self)
                self.transport.close()
Exemple #7
0
 def __init__(s, lowerTransport, ripproto):
     StackingTransport.__init__(s, lowerTransport)
     s.ripP = ripproto
Exemple #8
0
 def __init__(self, lowerTransport):
     StackingTransport.__init__(self, lowerTransport)
Exemple #9
0
 def connection_made(self, transport):
     print('pass1 connect')
     self.transport = transport
     self.higherProtocol().connection_made(StackingTransport(
         self.transport))
 def __init__(self, lowerTransport, lowerProtocol):
     StackingTransport.__init__(self, lowerTransport)
     self.lowerProtocol = lowerProtocol
Exemple #11
0
 def __init__(self, lowerTransport, protocol, TCB):
     StackingTransport.__init__(self, lowerTransport)
     self.TCB = protocol.TCB
     self.protocol = protocol
Exemple #12
0
 def __init__(self, srcAddr, srcPort, dstAddr, dstPort, twistedTransport):
     StackingTransport.__init__(self, twistedTransport)
     self.__srcAddr, self.__srcPort = srcAddr, srcPort
     self.__dstAddr, self.__dstPort = dstAddr, dstPort
 def __init__(self, lowerTransport, transportOf):
     StackingTransport.__init__(self, lowerTransport)
     self.SEQ = 0
     self.ACK = 0
     self.transportOf = transportOf
Exemple #14
0
 def __init__(self, lowerTransport, fixedKey):
     StackingTransport.__init__(self, lowerTransport)
     self.FixedKey = fixedKey
Exemple #15
0
    def data_received(self, data):
        print("\n================== PEEP Server Data_Received called ===========================")
        self.deserializer.update(data)
        for pkt in self.deserializer.nextPackets():
            # Checksum Check
            # SYN from client
            checkvalue = self.checkChecksum(pkt)
            if pkt.Type == 0 and self.serverstate == 0:
                self.serverstate += 1
                self.clientseq = pkt.SequenceNumber
                if checkvalue == True:
                    print("\nSYN Received. Seq= ", pkt.SequenceNumber, " Ackno=", pkt.Acknowledgement)
                    synack = PEEPpacket()
                    synack.Type = 1
                    synack.Acknowledgement = pkt.SequenceNumber + 1
                    self.global_number_ack = synack.Acknowledgement
                    synack.SequenceNumber = random.randint(5000, 9999)
                    self.serverseq = synack.SequenceNumber
                    self.global_number_seq = self.serverseq + 1
                    synack.Checksum = self.calculateChecksum(synack)
                    print("\n================== Sending SYN-ACK =============================================")
                    packs = synack.__serialize__()
                    self.transport.write(packs)


                else:
                    print("Checksum error. Packet Data corrupt.")
                    self.transport.close()

            elif pkt.Type == 2 and self.serverstate == 1 and pkt.SequenceNumber == self.clientseq + 1 and pkt.Acknowledgement == self.serverseq + 1:
                # Data transmission can start
                print("\nACK Received. Seq no=", pkt.SequenceNumber, " Ack no=", pkt.Acknowledgement)

                self.serverstate += 1
                if checkvalue == True:
                    print("\n================== TCP Connection successful! Client OK to send the Data now.============= \n")

                    # calling higher connection made since we have received the ACK

                    peeptransport = PeepServerTransport(self, self.transport)
                    higherTransport = StackingTransport(peeptransport)
                    self.higherProtocol().connection_made(higherTransport)

                else:
                    print("================== Corrupted ACK packet. Please check on client end.===============\n")
                    self.transport.close()

            # Reset packet received
            elif pkt.Type == 5 :

                 if checkvalue:
                    print("================== Got Encapasulated Packet and Deserialized==================")
                    self.global_packet_size = asizeof.asizeof(pkt.Data)
                    print("The size of packet is:", self.global_packet_size)
                    print("Seq number of incoming packet", pkt.SequenceNumber)
                    print("Ack Number of incoming packet", pkt.Acknowledgement)
                    self.receive_window(pkt)


                 else:
                     print("================== Corrupted Data packet. Please check on client end.===============\n")
                     self.transport.close()

            elif pkt.Type == 3 and self.serverstate == 2:
                if checkvalue:
                    print("RIP Received from Client. Sending RIP-ACK.")
                    # RIPack
                    ripack = PEEPpacket()
                    self.exc=0
                    self.serverstate += 1
                    ripack.Type = 4
                    ripack.Acknowledgement = pkt.SequenceNumber + 1
                    ripack.SequenceNumber = 5555
                    calcChecksum = PEEPServerProtocol(self.loop)
                    ripack.Checksum = calcChecksum.calculateChecksum(ripack)
                    ripz = ripack.__serialize__()
                    self.transport.write(ripz)
                else:
                    print("Corrupt RIP packet received. Please check on server end.")

            elif pkt.Type == 4 and self.serverstate == 3:
                if checkvalue:
                    self.serverstate += 1
                    print("RIP-ACK Received from Client. Closing down the connection.\n")
                    self.connection_lost(self.exc)
                else:
                    print("Corrupt RIP-ACK packet received. Please check on server end.")
 def __init__(s, lowerTransport, kissproto):
     StackingTransport.__init__(s, lowerTransport)
     s.kissP = kissproto
Exemple #17
0
    def data_received(self, data):
        print(
            "\n================== PEEP Server Data_Received called ==========================="
        )
        self.deserializer.update(data)
        for pkt in self.deserializer.nextPackets():
            # Checksum Check
            # SYN from client
            checkvalue = self.checkChecksum(pkt)
            if pkt.Type == 0 and self.serverstate == 0:
                self.serverstate += 1
                self.clientseq = pkt.SequenceNumber
                if checkvalue == True:
                    print("\nSYN Received. Seq= ", pkt.SequenceNumber,
                          " Ackno=", pkt.Acknowledgement)
                    print(pkt.Data)

                    if pkt.Data == b"Piggy":
                        self.global_pig = 56
                        print(self.global_pig)
                        print("Choosing Piggybacking")
                    else:
                        print("Choosing Selective")

                    synack = PEEPpacket()
                    synack.Type = 1
                    synack.Acknowledgement = pkt.SequenceNumber + 1
                    self.global_number_ack = synack.Acknowledgement
                    synack.SequenceNumber = random.randint(5000, 9999)
                    if self.global_pig == 56:
                        synack.Data = b"Piggy"
                    self.serverseq = synack.SequenceNumber
                    self.global_number_seq = self.serverseq + 1
                    synack.Checksum = self.calculateChecksum(synack)
                    print(
                        "\n================== Sending SYN-ACK ============================================="
                    )
                    self.synackx = synack.__serialize__()
                    self.transport.write(self.synackx)
                    self.ta = Timerx(0.1, self.synackx_timeout, synack)

                else:
                    print("Checksum error. Packet Data corrupt.")
                    self.transport.close()

            elif pkt.Type == 2 and self.serverstate == 1 and pkt.SequenceNumber == self.clientseq + 1 and pkt.Acknowledgement == self.serverseq + 1:
                # Data transmission can start
                print("\nACK Received. Seq no=", pkt.SequenceNumber,
                      " Ack no=", pkt.Acknowledgement)

                self.serverstate += 1
                if checkvalue == True:
                    print(
                        "\n================== TCP Connection successful! Client OK to send the Data now.============= \n"
                    )

                    # calling higher connection made since we have received the ACK

                    peeptransport = PeepServerTransport(self, self.transport)
                    higherTransport = StackingTransport(peeptransport)
                    self.higherProtocol().connection_made(higherTransport)

                else:
                    print(
                        "================== Corrupted ACK packet. Please check on client end.===============\n"
                    )
                    self.transport.close()

            # Reset packet received
            elif pkt.Type == 5:

                if checkvalue:
                    print(
                        "================== Got Encapasulated Packet and Deserialized=================="
                    )
                    self.global_packet_size = len(pkt.Data)
                    print("The size of packet is:", self.global_packet_size)
                    print("Seq number of incoming packet", pkt.SequenceNumber)
                    print("Ack Number of incoming packet", pkt.Acknowledgement)
                    self.global_received_ack = pkt.Acknowledgement
                    self.receive_window(pkt)
                    print("Calling data received of higher protocol from PEEP")
                else:
                    print(
                        "================== Corrupted Data packet. Please check on client end.===============\n"
                    )
                    self.transport.close()

            elif pkt.Type == 2:
                #### NEED A STATE INFO SO THAT Handshake packets are not received here.
                if checkvalue:
                    self.prev_ack_number = pkt.Acknowledgement
                    self.pop_sending_window(pkt.Acknowledgement)
                    print(
                        "ACK Received from the client. Removing data from buffer.",
                        pkt.Acknowledgement)
                    self.global_received_ack = pkt.Acknowledgement

            elif pkt.Type == 3 and self.serverstate == 2:
                if checkvalue:
                    print("RIP Received from Client. Sending RIP-ACK.")
                    # RIPack
                    ripack = PEEPpacket()
                    self.exc = 0
                    self.serverstate += 1
                    ripack.Type = 4
                    ripack.Acknowledgement = pkt.SequenceNumber + 1
                    ripack.SequenceNumber = 5555
                    calcChecksum = PEEPServerProtocol(self.loop)
                    ripack.Checksum = calcChecksum.calculateChecksum(ripack)
                    ripz = ripack.__serialize__()
                    self.transport.write(ripz)
                else:
                    print(
                        "Corrupt RIP packet received. Please check on server end."
                    )

            elif pkt.Type == 4 and self.serverstate == 3:
                if checkvalue:
                    self.serverstate += 1
                    print(
                        "RIP-ACK Received from Client. Closing down the connection.\n"
                    )
                    self.connection_lost(self.exc)
                else:
                    print(
                        "Corrupt RIP-ACK packet received. Please check on server end."
                    )
            else:
                print("Shait happened")
Exemple #18
0
 def loseConnection(self):
     g_logger.info("GateTransport %s to %s lose connection" %
                   (self.getHost(), self.getPeer()))
     return StackingTransport.loseConnection(self)
Exemple #19
0
    def data_received(self, data):
        self.deserializer.update(data)
        for packet in self.deserializer.nextPackets():
            if isinstance(packet, PlsHello):
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[0]))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[1]))
                self.incoming_cert.append(
                    CipherUtil.getCertFromBytes(packet.Certs[2]))
                print("\nReceived Server Hello. Beginning Validation.")
                if self.validate(self.incoming_cert):
                    self.m.update(packet.__serialize__())
                    print(
                        " Server Certificate Validated. Sending Client Key Exchange!\n"
                    )
                    clientkey = PlsKeyExchange()
                    randomvalue = os.urandom(
                        16)  # Example bytes:- b'1234567887654321'
                    self.pkc = int.from_bytes(randomvalue, byteorder='big')
                    clientkey.NoncePlusOne = packet.Nonce + 1
                    self.ns = packet.Nonce
                    pub_key = self.incoming_cert[0].public_key()
                    encrypted1 = pub_key.encrypt(
                        randomvalue,
                        padding.OAEP(
                            mgf=padding.MGF1(algorithm=hashes.SHA256()),
                            algorithm=hashes.SHA256(),
                            label=None))
                    #print ("Encrypted String is: ",encrypted1)
                    clientkey.PreKey = encrypted1
                    clkey = clientkey.__serialize__()
                    print("Sent the Prekey to Server.")
                    self.m.update(clkey)
                    self.transport.write(clkey)

            if isinstance(packet, PlsKeyExchange):
                print("Received Server Key Exchange.")
                self.m.update(packet.__serialize__())
                myprivatekey = getPrivateKeyForAddr(
                    "20174.1.666.46"
                )  #This hardcoded IP address must the peerAddress
                serverpriv = CipherUtil.getPrivateKeyFromPemBytes(myprivatekey)
                decrypted = serverpriv.decrypt(
                    packet.PreKey,
                    padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                                 algorithm=hashes.SHA256(),
                                 label=None))
                #print("Decrypted Pre-Master Secret: ", decrypted)
                self.pks = int.from_bytes(decrypted, byteorder='big')
                #====================================
                #sending digest
                self.clientdigest = self.m.digest()
                #print("Hash digest is: ", self.clientdigest)
                hdone = PlsHandshakeDone()
                hdone.ValidationHash = self.clientdigest
                hdone_s = hdone.__serialize__()
                print("Sent the PLS Handshake Done to server.")
                self.transport.write(hdone_s)

            if isinstance(packet, PlsHandshakeDone):
                print("\n\nReceived Server Handshake done message.")
                if (self.clientdigest == packet.ValidationHash):
                    print("Digest verification done!")
                    self.key_generator()
                    plstransport = PLSStackingTransport(self, self.transport)
                    higherTransport = StackingTransport(plstransport)
                    self.higherProtocol().connection_made(higherTransport)

            if isinstance(packet, PlsData):
                print(
                    "#######################Recieved Data Packet from PLSServer ############################"
                )
                self.ctr = 0
                if self.mac_verification_engine(packet.Ciphertext, packet.Mac):
                    DecryptedPacket = self.decryption_engine(packet.Ciphertext)
                    self.higherProtocol().data_received(DecryptedPacket)

                    self.ctr = 0

                else:
                    self.ctr += 1

                    if self.ctr != 5:
                        print("Verification Failed. Try Again. Failed {}"
                              ).format(self.ctr)

                    else:
                        print(
                            "Verification failed 5 times. Killing Connection and Sending PlsClose."
                        )
                        # Creating and Sending PlsClose
                        self.ctr = 0
                        Close = PlsClose()
                        #Close.Error = "Closing Connection due to 5 Verification failures. Aggressive Close."
                        serializeClose = Close.__serialize__()
                        self.transport.write(serializeClose)
                        self.transport.close()

            if isinstance(packet, PlsClose):
                print(
                    "#####################Received PlsClose from Server###########################"
                )
                self.transport.close()
Exemple #20
0
    def data_received(self, data):
        print("PEEP SERVER Data_Received CALLED")
        self.deserializer.update(data)
        #print (window_size)
        for pkt in self.deserializer.nextPackets():
            # Checksum Check
            # SYN from client
            print("In loop")
            #print (window_size)
            checkvalue = self.checkChecksum(pkt)
            if pkt.Type == 0 and self.serverstate == 0:
                print("pkt.type=0")
                #window_size += 1
                self.serverstate += 1
                self.clientseq = pkt.SequenceNumber
                if checkvalue == True:
                    print("\nSYN Received. Seq=", pkt.SequenceNumber)
                    #Sending SYN
                    synack = PEEP()
                    synack.Type = 1
                    synack.Acknowledgement = pkt.SequenceNumber + 1
                    synack.SequenceNumber = random.randint(5000, 9999)
                    self.serverseq = synack.SequenceNumber
                    synack.Checksum = self.calculateChecksum(synack)
                    print("SYNACK")
                    print(synack)
                    packs = synack.__serialize__()
                    self.transport.write(packs)

                    #self.transport.write(synack.__serialize__())
                else:
                    print("Checksum error. Packet Data corrupt.")
                    self.transport.close()
            elif pkt.Type == 2 and self.serverstate == 1 and pkt.SequenceNumber == self.clientseq + 1 and pkt.Acknowledgement == self.serverseq + 1:
                print("pkt.type==2")
                # Data transmission can start
                print("\nACK Received. Seqno=", pkt.SequenceNumber, " Ackno=",
                      pkt.Acknowledgement)

                self.serverstate += 1
                if checkvalue == True:
                    print(
                        "\nTCP Connection successful. Client OK to send the Data now.\n"
                    )

                    # calling higher connection made since the I have received the ACK

                    peeptransport = PeepServerTransport(self, self.transport)
                    higherTransport = StackingTransport(peeptransport)
                    self.higherProtocol().connection_made(higherTransport)

                    #self.higherProtocol().data_received(data)
                else:
                    print("Corrupt ACK packet. Please check on client end.")
                    self.transport.close()

            # Reset packet received
            elif pkt.Type == 5:
                print(
                    "Server received connection close from client. Closing socket."
                )
Exemple #21
0
 def __init__(self, lowerTransport, protocol):
     StackingTransport.__init__(self, lowerTransport)
     self.protocol = protocol
Exemple #22
0
 def closeConnection(self):
     logger.debug("RIP--%s", self.state)
     self.state = "CLOSED"
     StackingTransport.loseConnection(self)