Exemple #1
0
class RipClientProtocol(StackingProtocolMixin, Protocol):

    STATE_CLIENT_CLOSE = "RIP CLIENT STATE MACHINE: CLOSE"
    STATE_CLIENT_SNN_SENT = "RIP CLIENT STATE MACHINE: SNN SENT"
    STATE_CLIENT_ESTABLISHED = "RIP CLIENT STATE MACHINE: ESTABLISHED"

    SIGNAL_CLIENT_SEND_SNN = "RIP CLIENT STATE MACHINE: send snn"
    SIGNAL_CLIENT_RCVD_SNNACK = "RIP CLIENT STATE MACHINE: rcvd snn/ack"
    SIGNAL_CLIENT_RIPMESSAGE = "RIP CLIENT STATE MACHINE: general data without flags"

    def __init__(self):
        self.packetStorage = PacketStorage()
        self.nonce = randint(0, 10000)
        self.SM = StateMachine("Rip Client Protocol StateMachine")

        self.SM.addState(self.STATE_CLIENT_CLOSE,
                        # transition
                        (self.SIGNAL_CLIENT_SEND_SNN, self.STATE_CLIENT_SNN_SENT),
                        # no callback for CLOSE
                        )

        self.SM.addState(self.STATE_CLIENT_SNN_SENT,
                        # transition
                        (self.SIGNAL_CLIENT_RCVD_SNNACK, self.STATE_CLIENT_ESTABLISHED),
                        # callbacks for SNN_SENT
                        onEnter = self.snnSend)


        self.SM.addState(self.STATE_CLIENT_ESTABLISHED,
                        # transtion
                        (self.SIGNAL_CLIENT_RIPMESSAGE, self.STATE_CLIENT_ESTABLISHED),
                        (self.SIGNAL_CLIENT_RCVD_SNNACK, self.STATE_CLIENT_ESTABLISHED),
                        # callback
                        onEnter = self.messageHandle)


    def connectionMade(self):
        print "Rip Client Protocol: connection Made"
        self.SM.start(self.STATE_CLIENT_CLOSE)
        print "Rip Client Protocol: start state machine from state -- " + self.SM.currentState()
        self.SM.signal(self.SIGNAL_CLIENT_SEND_SNN, "")
        print "Rip Client Protocol: after snn send current state -- " + self.SM.currentState()


    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_CLIENT_ESTABLISHED:
            return
        ripMsg = RipMessage()
        ripMsg.Data = data
        print "Rip Client Protocol: data send -- SNN = " + str(ripMsg.SNN) + " Data = " + ripMsg.Data
        self.transport.write(Packet.MsgToPacketBytes(ripMsg))

    def msgToSignal(self, msg):
        if (msg.SNN == True and msg.ACK == True):
            signal = self.SIGNAL_CLIENT_RCVD_SNNACK
        elif(msg.SNN == False and msg.ACK == False):
            signal = self.SIGNAL_CLIENT_RIPMESSAGE
        return signal

    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            clientSignal = self.msgToSignal(rcvMsg)
            self.SM.signal(clientSignal, rcvMsg)

    # onEnter callback for STATE_CLIENT_SNN_SENT
    def snnSend(self, signal, msg):
        print "Rip Client Protocol: snnSend received signal -- " + signal
        snnMsg = RipMessage()
        snnMsg.SNN = True
        snnMsg.Certificate = self.generateCertificate()
        snnMsg.Signature = self.generateSignature(snnMsg.__serialize__())
        self.transport.write(Packet.MsgToPacketBytes(snnMsg))

    # not a callback, this function will be called at the first time enter established
    def sendAck(self, nonce2):
        print "Rip Client Protocol: sendAck, current state -- " + self.SM.currentState()
        ackMessage = RipMessage()
        ackMessage.ACK = True
        # ack message certificate chain only have 1 item : [nonce2 + 1]
        ackMessage.Certificate = [int(nonce2) + 1]
        self.transport.write(Packet.MsgToPacketBytes(ackMessage))

    # onEnter callback for STATE_CLIENT_ESTABLISHED
    def messageHandle(self, signal, msg):

        # first time client enter established, must be triggered by signal_receive_snnack
        if signal == self.SIGNAL_CLIENT_RCVD_SNNACK:
            print "Rip Client Protocol: message handle -- signal : " + signal
            # certificate chain from server [nonce2, addrCert, CACert, nonce1 + 1]
            if self.verification(msg) == False:
                print "Rip Client Protocol: verification failed!"
                return
            nonce2 = msg.Certificate[0]
            nonce1Plus1 = msg.Certificate[3]
            print "Rip Client Protocol: message handle -- rcvd snnack: (nonce1 + 1) from server = " + str(nonce1Plus1) + "nonce2 from server = " + str(nonce2)
            self.sendAck(nonce2)
            higherTransport = RipTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_CLIENT_RIPMESSAGE:
            print "Rip Client Protocol: message handle -- receives rip message: ", msg.Data
            self.higherProtocol() and self.higherProtocol().dataReceived(msg.Data)

        else:
            print "Rip Client Protocol: message handle -- undefined signal: ", signal


    def generateCertificate(self):
        #addr = self.transport.getHost().host
        addr = self.transport.getHost()
        chain = [self.nonce]
        chain += getCertsForAddr(addr)
        return chain

    def generateSignature(self, data):
        #addr = self.transport.getHost().host
        addr = self.transport.getHost()
        clientPrivateKeyBytes = getPrivateKeyForAddr(addr)
        clientPrivateKey = RSA.importKey(clientPrivateKeyBytes)
        clientSigner = PKCS1_v1_5.new(clientPrivateKey)
        hasher = SHA256.new()
        hasher.update(data)
        signatureBytes = clientSigner.sign(hasher)
        return signatureBytes

    def verification(self, snnackMsg):
        signatureBytes = snnackMsg.Signature
        certificateChain = snnackMsg.Certificate

        # verify nonce1 + 1
        nonce1Plus1 = certificateChain[3]
        if(int(nonce1Plus1) != int(self.nonce + 1)):
            return False

        # verify server's certificate chain
        serverCert = X509Certificate.loadPEM(certificateChain[1])
        CACert = X509Certificate.loadPEM(certificateChain[2])
        rootCert = X509Certificate.loadPEM(getRootCert())
        if(CACert.getIssuer() != rootCert.getSubject()):
            return False
        if(serverCert.getIssuer() != CACert.getSubject()):
            return False

        # verify signature with server's public key
        serverPublicKeyBlob = serverCert.getPublicKeyBlob()
        serverPublicKey = RSA.importKey(serverPublicKeyBlob)
        rsaVerifier = PKCS1_v1_5.new(serverPublicKey)
        hasher = SHA256.new()
        snnackMsg.Signature = ""
        bytesToBeVerified = snnackMsg.__serialize__()

        hasher.update(bytesToBeVerified)
        result = rsaVerifier.verify(hasher, signatureBytes)
        print "Rip Client verification result: " + str(result)
        return result
class RipClientProtocol(StackingProtocolMixin, Protocol, RipTransport):
    """
            Rip Client State Machine
    """

    STATE_CLIENT_CLOSE = "RIP CLIENT STATE MACHINE: CLOSE"
    STATE_CLIENT_SNN_SENT = "RIP CLIENT STATE MACHINE: SNN SENT"
    STATE_CLIENT_CLS_RCVD = "RIP CLIENT STATE MACHINE: CLS RECEIVED"
    STATE_CLIENT_CLS_SEND = "RIP CLIENT STATE MACHINE: CLS SENT"
    STATE_CLIENT_ESTABLISHED = "RIP CLIENT STATE MACHINE: ESTABLISHED"

    SIGNAL_CLIENT_SEND_SNN = "RIP CLIENT STATE MACHINE: send snn"
    SIGNAL_CLIENT_RCVD_SNNACK = "RIP CLIENT STATE MACHINE: rcvd snn/ack"
    SIGNAL_CLIENT_RIPMESSAGE = "RIP CLIENT STATE MACHINE: general data without flags"
    SIGNAL_CLIENT_RCVD_CLS = "RIP CLIENT STATE MACHINE: rcvd cls"
    SIGNAL_CLIENT_SEND_CLS = "RIP CLIENT STATE MACHINE: send cls"
    SIGNAL_CLIENT_RCVD_CLSACK = "RIP CLIENT STATE MACHINE: rcvd cls/ack from server"
    SIGNAL_CLIENT_SEND_CLSACK = "RIP CLIENT STATE MACHINE: send cls/ack back to server"

    def __init__(self):
        self.packetStorage = PacketStorage()
        self.nonce = randint(0, 10000)
        self.SM = StateMachine("Rip Client Protocol StateMachine")

        self.SM.addState(
            self.STATE_CLIENT_CLOSE,
            (self.SIGNAL_CLIENT_SEND_SNN, self.STATE_CLIENT_SNN_SENT))

        self.SM.addState(
            self.STATE_CLIENT_SNN_SENT,
            (self.SIGNAL_CLIENT_RCVD_SNNACK, self.STATE_CLIENT_ESTABLISHED),
            onEnter=self.sendSnn)

        self.SM.addState(
            self.STATE_CLIENT_ESTABLISHED,
            (self.SIGNAL_CLIENT_RIPMESSAGE, self.STATE_CLIENT_ESTABLISHED),
            (self.SIGNAL_CLIENT_RCVD_SNNACK, self.STATE_CLIENT_ESTABLISHED),
            (self.SIGNAL_CLIENT_RCVD_CLS, self.STATE_CLIENT_CLS_RCVD),
            (self.SIGNAL_CLIENT_SEND_CLS, self.STATE_CLIENT_CLS_SEND),
            onEnter=self.messageHandle)

        self.SM.addState(
            self.STATE_CLIENT_CLS_SEND,
            (self.SIGNAL_CLIENT_RCVD_CLSACK, self.STATE_CLIENT_CLOSE),
            onEnter=self.sendCls)

        self.SM.addState(
            self.STATE_CLIENT_CLS_RCVD,
            (self.SIGNAL_CLIENT_SEND_CLSACK, self.STATE_CLIENT_CLOSE),
            onEnter=self.sendClsAck)

    def connectionMade(self):
        print "Rip Client Protocol: connection Made"
        self.SM.start(self.STATE_CLIENT_CLOSE)
        print "Rip Client Protocol: start state machine from state -- " + self.SM.currentState(
        )
        self.SM.signal(self.SIGNAL_CLIENT_SEND_SNN, "")
        print "Rip Client Protocol: after snn send current state -- " + self.SM.currentState(
        )

    def connectionLost(self, reason=connectionDone):
        self.SM.signal(self.SIGNAL_CLIENT_SEND_CLS, "")
        print "Rip Client Protocol: connection lost"
        self.transport.loseConnection()

    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_CLIENT_ESTABLISHED:
            return
        ripMsg = RipMessage()
        ripMsg.Data = data
        print "Rip Client Protocol: data send -- SNN = " + str(
            ripMsg.SNN) + " Data = " + ripMsg.Data
        self.transport.write(Packet.MsgToPacketBytes(ripMsg))

    def msgToSignal(self, msg):  # only used by dataReceived()
        snn = msg.SNN
        ack = msg.ACK
        cls = msg.CLS
        if (snn and ack):
            signal = self.SIGNAL_CLIENT_RCVD_SNNACK
        elif (not snn and not ack):
            signal = self.SIGNAL_CLIENT_RIPMESSAGE
        elif (cls and not ack):
            signal = self.SIGNAL_CLIENT_RCVD_CLS
        elif (cls and ack):
            signal = self.SIGNAL_CLIENT_RCVD_CLSACK
        return signal

    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            clientSignal = self.msgToSignal(rcvMsg)
            self.SM.signal(clientSignal, rcvMsg)

    """    RipClient OnEnter Callback Functions    """

    # 1. STATE_CLIENT_SNN_SENT
    def sendSnn(self, signal, msg):
        print "Rip Client Protocol: 1. sendSnn -- " + signal
        snnMsg = RipMessage()
        snnMsg.SNN = True
        snnMsg.Certificate = generateClientCertificate(
            self.transport.getHost(), self.nonce)
        snnMsg.Signature = generateSignature(self.transport.getHost(),
                                             snnMsg.__serialize__())
        self.transport.write(Packet.MsgToPacketBytes(snnMsg))

    # 2. STATE_CLIENT_ESTABLISHED
    def messageHandle(self, signal, msg):

        # first time client enter established, must be triggered by signal_receive_snnack
        if signal == self.SIGNAL_CLIENT_RCVD_SNNACK:
            print "Rip Client Protocol: 2. message handle -- signal : " + signal
            # certificate chain from server [nonce2, addrCert, CACert, nonce1 + 1]
            if verification(self.nonce, msg) == False:
                print "Rip Client Protocol: verification failed!"
                return
            nonce2 = msg.Certificate[0]
            nonce1Plus1 = msg.Certificate[3]
            print "Rip Client Protocol: 2. message handle -- rcvd snnack: (nonce1 + 1) from server = " + str(
                nonce1Plus1) + "nonce2 from server = " + str(nonce2)
            self.sendAck(nonce2)
            higherTransport = RipTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_CLIENT_RIPMESSAGE:
            print "Rip Client Protocol: 2. message handle -- receives rip message: ", msg.Data
            self.higherProtocol() and self.higherProtocol().dataReceived(
                msg.Data)

        else:
            print "Rip Client Protocol: 2. message handle -- undefined signal: ", signal

    # 3.1 STATE_CLIENT_CLS_SEND
    def sendCls(self, signal, msg):
        if signal == self.SIGNAL_CLIENT_SEND_CLS:
            print "Rip Client Protocol: 3.1 sendCls -- send CLS"
            msg = RipMessage()
            msg.CLS = True
            self.transport.write(Packet.MsgToPacketBytes(msg))
        else:
            print "Rip Client Protocol: 3.1 sendCls -- undefined signal: ", signal

    # 3.2 STATE_CLIENT_CLS_RCVD
    def sendClsAck(self, signal, msg):
        if signal == self.SIGNAL_CLIENT_RCVD_CLS:
            print "Rip Client Protocol: 3.2 sendClsAck -- send cls/ack back"
            # CLS/ACK package
            msg = RipMessage()
            msg.CLS = True
            msg.ACK = True
            self.transport.write(Packet.MsgToPacketBytes(msg))
            # !! here need to add timer before signal to close
            self.SM.signal(self.SIGNAL_CLIENT_SEND_CLSACK, msg)
            self.transport.loseConnection()
        else:
            print "Rip Client Protocol: 3.2 sendClsAck -- undefined signal: ", signal

    # not a callback, this function will be called at the first time enter established
    def sendAck(self, nonce2):
        print "Rip Client Protocol: sendAck, current state -- " + self.SM.currentState(
        )
        msg = RipMessage()
        msg.ACK = True
        msg.Certificate = [int(nonce2) + 1]
        self.transport.write(Packet.MsgToPacketBytes(msg))
Exemple #3
0
class RipServerProtocol(StackingProtocolMixin, Protocol):

    # States for handshake
    STATE_SERVER_LISTEN = "RIP SERVER STATE MACHINE: LISTEN"
    STATE_SERVER_SNN_RCVD = "RIP SERVER STATE MACHINE: SNN_RCVD"
    STATE_SERVER_ESTABLISHED = "RIP SERVER STATE MACHINE: ESTABLISHED"

    # signal
    SIGNAL_SERVER_RCVD_SNN = "RIP SERVER STATE MACHINE: received snn"
    SIGNAL_SERVER_RCVD_ACK = "RIP SERVER STATE MACHINE: received ack"
    SIGNAL_SERVER_RIPMESSAGE = "RIP SERVER STATE MACHINE: general data without flags"

    def __init__(self):
        self.packetStorage = PacketStorage()
        self.nonce = randint(0, 10000)
        self.SM = StateMachine("Rip Server Protocol StateMachine")

        self.SM.addState(self.STATE_SERVER_LISTEN,
                             # transition
                            (self.SIGNAL_SERVER_RCVD_SNN, self.STATE_SERVER_SNN_RCVD),
                             # no callback for LISTEN
                            )
        self.SM.addState(self.STATE_SERVER_SNN_RCVD,
                             # transition
                            (self.SIGNAL_SERVER_RCVD_ACK, self.STATE_SERVER_ESTABLISHED),
                             # callback
                            onEnter = self.sendSnnAck)

        self.SM.addState(self.STATE_SERVER_ESTABLISHED,
                             # transtion
                             (self.SIGNAL_SERVER_RIPMESSAGE, self.STATE_SERVER_ESTABLISHED),
                             # callback
                             onEnter = self.messageHandle)

    def msgToSignal(self, msg):
        if(msg.SNN == True and msg.ACK == False):
            signal = self.SIGNAL_SERVER_RCVD_SNN
        elif(msg.SNN == False and msg.ACK == True):
            signal = self.SIGNAL_SERVER_RCVD_ACK
        elif(msg.SNN == False and msg.ACK == False):
            signal = self.SIGNAL_SERVER_RIPMESSAGE
        return signal


    def connectionMade(self):
        #print "Gate address: " + str(self.transport.getHost())
        self.SM.start(self.STATE_SERVER_LISTEN)

    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_SERVER_ESTABLISHED:
            return
        ripMsg = RipMessage()
        ripMsg.Data = data
        print "Rip Server Protocol: data send -- Data = " + ripMsg.Data
        self.transport.write(Packet.MsgToPacketBytes(ripMsg))

    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            serverSignal = self.msgToSignal(rcvMsg)
            self.SM.signal(serverSignal, rcvMsg)


    # onEnter callback for STATE_SERVER_SNN_RCVD
    def sendSnnAck(self, signal, rcvMsg):
        if signal == self.SIGNAL_SERVER_RCVD_SNN:
            if self.verifySnnMessage(rcvMsg) == False:
                print "Rip Server Protocol: verification failed!"
                return
            print "Rip Server Protocol: sendSnnAck -- nonce1 from client = " + str(rcvMsg.Certificate[0])
            nonce1 = rcvMsg.Certificate[0]

            snnackMsg = RipMessage()
            snnackMsg.SNN = True
            snnackMsg.ACK = True
            snnackMsg.Certificate = self.generateCertificate(nonce1)
            snnackMsg.Signature = self.generateSignature(snnackMsg.__serialize__())
            self.transport.write(Packet.MsgToPacketBytes(snnackMsg))
        else:
            print "Rip Server Protocol: sendSnnAck -- undefined signal: " + signal

    # onEnter callback for STATE_SERVER_ESTABLISHED
    def messageHandle(self, signal, msg):

        # server first enter established, must be triggered by signal-received-ack
        if signal == self.SIGNAL_SERVER_RCVD_ACK:
            print "Rip Server Protocol: message handle -- received ack: nonce2 + 1 = " + str(msg.Certificate[0]) + " server nonce = " + str(self.nonce)
            nonce2Plus1 = msg.Certificate[0]
            if (int(nonce2Plus1) != (self.nonce + 1)):
                return False
            higherTransport = RipTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_SERVER_RIPMESSAGE:
            print "Rip Server Protocol: message handle -- receives rip message: data -- " + msg.Data
            self.higherProtocol() and self.higherProtocol().dataReceived(msg.Data)

        else:
            print "Rip Server Protocol: message handle -- undefined signal: ", signal

    def verifySnnMessage(self, snnMsg):
        signatureBytes = snnMsg.Signature
        certificate = snnMsg.Certificate

        # verify client's certificate chain
        clientCert = X509Certificate.loadPEM(certificate[1])
        CACert = X509Certificate.loadPEM(certificate[2])
        rootCert = X509Certificate.loadPEM(getRootCert())

        if(CACert.getIssuer() != rootCert.getSubject()):
            return False
        if(clientCert.getIssuer() != CACert.getSubject()):
            return False

        # verify signature with client public key
        clientPublicKeyBlob = clientCert.getPublicKeyBlob()
        clientPublicKey = RSA.importKey(clientPublicKeyBlob)
        rsaVerifier = PKCS1_v1_5.new(clientPublicKey)
        hasher = SHA256.new()
        snnMsg.Signature = ""
        bytesToBeVerified = snnMsg.__serialize__()
        hasher.update(bytesToBeVerified)
        result = rsaVerifier.verify(hasher, signatureBytes)
        print "Server verification result: " + str(result)

        return result

    def generateCertificate(self, nonce1):
        # generate certificate chain for SnnAck message: [nonce2, addrCert, CACert, nonce1 + 1]
        #addr = self.transport.getHost().host
        addr = self.transport.getHost()
        chain = [str(self.nonce)]
        chain += getCertsForAddr(addr)
        chain += [str(int(nonce1) + 1)]
        print "Rip Server Protocol: generateCertificate -- server nonce = "+ chain[0] + " nonce1 + 1 = " + chain[3]
        return chain

    def generateSignature(self, data):
        #addr = self.transport.getHost().host
        addr = self.transport.getHost()
        serverPrivateKeyBytes = getPrivateKeyForAddr(addr)
        serverPrivateKey = RSA.importKey(serverPrivateKeyBytes)
        serverSigner = PKCS1_v1_5.new(serverPrivateKey)
        hasher = SHA256.new()
        hasher.update(data)
        signatureBytes = serverSigner.sign(hasher)
        return signatureBytes
class RipClientProtocol(StackingProtocolMixin, Protocol):

    STATE_CLIENT_CLOSE = "RIP CLIENT STATE MACHINE: CLOSE"
    STATE_CLIENT_SNN_SENT = "RIP CLIENT STATE MACHINE: SNN SENT"
    STATE_CLIENT_ESTABLISHED = "RIP CLIENT STATE MACHINE: ESTABLISHED"

    SIGNAL_CLIENT_SEND_SNN = "RIP CLIENT STATE MACHINE: send snn"
    SIGNAL_CLIENT_RCVD_SNNACK = "RIP CLIENT STATE MACHINE: rcvd snn/ack"
    SIGNAL_CLIENT_RIPMESSAGE = "RIP CLIENT STATE MACHINE: general data without flags"

    def __init__(self):
        self.packetStorage = PacketStorage()
        self.SM = StateMachine("Rip Client Protocol StateMachine")

        self.SM.addState(
            self.STATE_CLIENT_CLOSE,
            # transition
            (self.SIGNAL_CLIENT_SEND_SNN, self.STATE_CLIENT_SNN_SENT),
            # no callback for CLOSE
        )

        self.SM.addState(
            self.STATE_CLIENT_SNN_SENT,
            # transition
            (self.SIGNAL_CLIENT_RCVD_SNNACK, self.STATE_CLIENT_ESTABLISHED),
            # callbacks for SNN_SENT
            onEnter=self.snnSend)

        self.SM.addState(
            self.STATE_CLIENT_ESTABLISHED,
            # transtion
            (self.SIGNAL_CLIENT_RIPMESSAGE, self.STATE_CLIENT_ESTABLISHED),
            (self.SIGNAL_CLIENT_RCVD_SNNACK, self.STATE_CLIENT_ESTABLISHED),
            # callback
            onEnter=self.messageHandle)

    def connectionMade(self):
        print "Rip Client Protocol: connection Made"
        self.SM.start(self.STATE_CLIENT_CLOSE)
        print "Rip Client Protocol: start state machine from state -- " + self.SM.currentState(
        )
        self.SM.signal(self.SIGNAL_CLIENT_SEND_SNN, "")
        print "Rip Client Protocol: after snn send current state -- " + self.SM.currentState(
        )

    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_CLIENT_ESTABLISHED:
            return
        ripMsg = RipMessage()
        ripMsg.Data = data
        print "Rip Client Protocol: data send -- SNN = " + str(
            ripMsg.SNN) + " Data = " + ripMsg.Data
        self.transport.write(Packet.MsgToPacketBytes(ripMsg))

    def msgToSignal(self, msg):
        if (msg.SNN == True and msg.ACK == True):
            signal = self.SIGNAL_CLIENT_RCVD_SNNACK
        elif (msg.SNN == False and msg.ACK == False):
            signal = self.SIGNAL_CLIENT_RIPMESSAGE
        return signal

    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            clientSignal = self.msgToSignal(rcvMsg)
            self.SM.signal(clientSignal, rcvMsg)

    # onEnter callback for STATE_CLIENT_SNN_SENT
    def snnSend(self, signal, msg):
        print "Rip Client Protocol: snnSend received signal -- " + signal
        snnMessage = RipMessage()
        snnMessage.SNN = True
        self.transport.write(Packet.MsgToPacketBytes(snnMessage))

    # not a callback, this function will be called at the first time enter established
    def sendAck(self):
        print "Rip Client Protocol: sendAck, current state -- " + self.SM.currentState(
        )
        ackMessage = RipMessage()
        ackMessage.ACK = True
        self.transport.write(Packet.MsgToPacketBytes(ackMessage))

    # onEnter callback for STATE_CLIENT_ESTABLISHED
    def messageHandle(self, signal, msg):

        # first time client 4enter established, must be triggered by signal_receive_snnack
        if signal == self.SIGNAL_CLIENT_RCVD_SNNACK:
            print "Rip Client Protocol: message handle -- signal : " + signal
            self.sendAck()
            higherTransport = RipTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_CLIENT_RIPMESSAGE:
            print "Rip Client Protocol: message handle -- receives rip message: ", msg.Data
            self.higherProtocol() and self.higherProtocol().dataReceived(
                msg.Data)

        else:
            print "Rip Client Protocol: message handle -- undefined signal: ", signal
Exemple #5
0
class RipProtocol(StackingProtocolMixin, Protocol):
    def __init__(self):

        self.buffer = ""
        self.storage = MessageStorage()
        self.TCB = TransmissionControlBlock()
        self.higherTransport = RipTransport(self.transport, self, self.TCB)
        self.fsm = FSM("RipStateMachine")
        self.fsm.addState("Closed", ("Send_SNN", "SNN-SENT"))
        self.fsm.addState("Listening", ("SNN_Received", "ACK-Sent"))
        self.fsm.addState("SNN-SENT", ("SNN_ACK_Received", "Established"),
                          onEnter=self.sendSyn)
        self.fsm.addState("ACK-Sent", ("ACK_Received", "Established"),
                          onEnter=self.sendSynAck)
        self.fsm.addState("Established", ("CLOSE_Requested", "CLOSE-REQ"),
                          ("CLOSE_Received", "CLOSE-RECV"),
                          onEnter=self.sendAck)
        self.fsm.addState("CLOSE-REQ", ("CLOSE_ACK_Received", "Closed"))
        self.fsm.addState("CLOSE-RECV", ("CLOSE_ACK_Sent", "Listening"),
                          onEnter=self.sendFinAck)

    def connectionMade(self):
        self.higherTransport = RipTransport(self.transport, self, self.TCB)
        if self.factory.State == "CLIENT": self.fsm.start("Closed")
        elif self.factory.State == "SERVER": self.fsm.start("Listening")

        if (self.factory.State == "CLIENT"
                and self.fsm.currentState() == "Closed"):
            self.fsm.signal("Send_SNN", '')

    def dataReceived(self, data):

        self.buffer += data
        self.storage.update(data)

        for msg in self.storage.iterateMessages():
            try:
                message = msg
            except Exception, e:
                print "Error", e
                return

            # If SNN is received
            if (message.sequence_number_notification_flag
                    and self.fsm.currentState() == "Listening"):
                print "%s SNN Received with Sequence No %s" % (
                    self.factory.State, message.sequence_number)
                self.fsm.signal("SNN_Received", message)

            # If SNN-ACK in received
            elif (message.sequence_number_notification_flag
                  and message.acknowledgement_flag and
                  message.acknowledgement_number == self.TCB.sequence_number
                  and self.fsm.currentState() == "SNN-SENT"):
                print "%s: SNN-ACK Received with Sequence No %s" % (
                    self.factory.State, message.sequence_number)
                self.fsm.signal("SNN_ACK_Received", message)
                self.makeHigherConnection(self.higherTransport)

            # If final ACK is received
            elif (not message.sequence_number_notification_flag
                  and message.acknowledgement_flag and
                  message.acknowledgement_number == self.TCB.sequence_number
                  and self.fsm.currentState() == "ACK-Sent"):
                if self.checkMessageIntegrity(message):
                    peerCert = message.certificate
                    signedNonce = peerCert[0]
                    cert = self.TCB.peerCert
                    caCert = self.TCB.peerCaCert

                    if (self.verifySignedNonce(cert, caCert, signedNonce)):
                        self.fsm.signal("ACK_Received", message)
                        print "%s: ACK Received with Sequence No %s" % (
                            self.factory.State, message.sequence_number)
                        self.TCB.next_seq_expected = message.sequence_number + 1
                        self.makeHigherConnection(self.higherTransport)

            # If a message is received by one of the users
            elif (message.data != ""
                  and self.fsm.currentState() == "Established"
                  and message.sessionID
                  == str(self.TCB.peer_nonce) + str(self.TCB.nonce)
                  and not message.acknowledgement_flag
                  and not message.close_flag
                  and message.sequence_number == self.TCB.next_seq_expected):
                if self.checkMessageIntegrity(message):
                    self.TCB.next_seq_expected = message.sequence_number + len(
                        str(message.data))
                    # Add the message to the list of received messages
                    self.TCB.receivedMessages[
                        message.sequence_number] = message
                    self.sendMessageAck(message.data)

            # If ACK for the packet is received
            elif (self.fsm.currentState() == "Established"
                  and message.sessionID
                  == str(self.TCB.peer_nonce) + str(self.TCB.nonce)
                  and message.acknowledgement_flag and not message.close_flag):
                # Remove the acknowledged message from the retransmission buffer
                for key, message in list(
                        self.TCB.retransmissionBuffer.items()):
                    if key <= message.acknowledgement_number:
                        del self.TCB.retransmissionBuffer[key]

            # If CLOSING ACK is received
            elif (message.close_flag and message.acknowledgement_number
                  and self.fsm.currentState() == "CLOSE-REQ"):
                print "%s: CLOSE ACK Received with Sequence Number %s" % (
                    self.factory.State, message.sequence_number)
                if self.TCB.retransmissionBuffer:
                    self.retransmitPackets()
                self.fsm.signal("CLOSE_ACK_Received", message)
                self.closeConnection()

            elif (message.sequence_number_notification_flag
                  and self.fsm.currentState() == "Established"):
                self.closeConnection()
class ChaperoneProtocol(Protocol):
    STATE_DISCONNECTED = "Chaperone Protocol: disconnected"
    STATE_NEGOTIATING = "Chaperone Protocol: negotiating"
    STATE_CONNECTED = "Chaperone Protocol: connected"
    STATE_CLOSED = "Chaperone Protocol: closed"

    SIGNAL_REG_SENT = "Chaperone Protocol: registration sent to chaperone"
    SIGNAL_REG_RECEIVED = "Chaperone Protocol: chaperone sent registration"
    SIGNAL_REG_FAILED = "Chaperone Protocol: chaperone denied registration"
    SIGNAL_UNREG_SENT = "Chaperone Protocol: unregistration sent to chaperone"

    MAX_MSG_SIZE = (2**16)  # This is about the size of a TCP packet
    FRAMING_SIZE = (2**12)
    MAX_FRAG_AGE = 10 * 60  # Ten minute time-out on G2gMessage Frags

    def __init__(self, gateAddress, demuxer):
        self.__packetStorage = PacketStorage()
        self.__gateAddress = gateAddress
        self.__demuxer = demuxer

        self.__fsm = FSM("Chaperone Protocol FSM")
        self.__fsm.addState(
            self.STATE_DISCONNECTED,
            # transitions
            (self.SIGNAL_REG_SENT, self.STATE_NEGOTIATING))

        self.__fsm.addState(
            self.STATE_NEGOTIATING,
            # transitions
            (GateRegistered, self.STATE_NEGOTIATING),
            (self.SIGNAL_REG_RECEIVED, self.STATE_CONNECTED),
            (self.SIGNAL_REG_FAILED, self.STATE_CLOSED),
            # callbacks
            onEnter=self.__checkNegotiation)

        self.__fsm.addState(
            self.STATE_CONNECTED,
            # transitions
            (self.SIGNAL_UNREG_SENT, self.STATE_DISCONNECTED),
            (Gate2GateMessage, self.STATE_CONNECTED),
            # callbacks
            onEnter=self.__handleConnectedMessages)

        self.__fsm.start(self.STATE_DISCONNECTED)

    def gateAddress(self):
        return self.__gateAddress

    def connectionLost(self, reason=connectionDone):
        self.__demuxer.close()

    def connectionMade(self):
        registerGateMessage = RegisterGate()
        registerGateMessage.address = self.__gateAddress

        self.transport.write(Packet.MsgToPacketBytes(registerGateMessage))
        self.__fsm.signal(self.SIGNAL_REG_SENT, registerGateMessage)

    def dataReceived(self, data):
        self.__packetStorage.update(data)
        for msg in IterateMessages(self.__packetStorage, logger, errReporter):
            try:
                self.__fsm.signal(msg.__class__, msg)
            except StateMachineError, e:
                errReporter.error(
                    ("State machine error after receiving %s. Error:\n%s") %
                    (msg, e))
                self.transport.loseConnection()
class RipServerProtocol(StackingProtocolMixin, Protocol):

    # States for handshake
    STATE_SERVER_LISTEN = "RIP SERVER STATE MACHINE: LISTEN"
    STATE_SERVER_SNN_RCVD = "RIP SERVER STATE MACHINE: SNN_RCVD"
    STATE_SERVER_ESTABLISHED = "RIP SERVER STATE MACHINE: ESTABLISHED"

    # signal
    SIGNAL_SERVER_RCVD_SNN = "RIP SERVER STATE MACHINE: received snn"
    SIGNAL_SERVER_RCVD_ACK = "RIP SERVER STATE MACHINE: received ack"
    SIGNAL_SERVER_RIPMESSAGE = "RIP SERVER STATE MACHINE: general data without flags"

    def __init__(self):
        self.packetStorage = PacketStorage()
        self.SM = StateMachine("Rip Server Protocol StateMachine")

        self.SM.addState(
            self.STATE_SERVER_LISTEN,
            # transition
            (self.SIGNAL_SERVER_RCVD_SNN, self.STATE_SERVER_SNN_RCVD),
            # no callback for LISTEN
        )
        self.SM.addState(
            self.STATE_SERVER_SNN_RCVD,
            # transition
            (self.SIGNAL_SERVER_RCVD_ACK, self.STATE_SERVER_ESTABLISHED),
            # callback
            onEnter=self.sendSnnAck)

        self.SM.addState(
            self.STATE_SERVER_ESTABLISHED,
            # transtion
            (self.SIGNAL_SERVER_RIPMESSAGE, self.STATE_SERVER_ESTABLISHED),
            # callback
            onEnter=self.messageHandle)

    def msgToSignal(self, msg):
        if (msg.SNN == True and msg.ACK == False):
            signal = self.SIGNAL_SERVER_RCVD_SNN
        elif (msg.SNN == False and msg.ACK == True):
            signal = self.SIGNAL_SERVER_RCVD_ACK
        elif (msg.SNN == False and msg.ACK == False):
            signal = self.SIGNAL_SERVER_RIPMESSAGE
        return signal

    def connectionMade(self):
        self.SM.start(self.STATE_SERVER_LISTEN)

    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_SERVER_ESTABLISHED:
            return
        ripMsg = RipMessage()
        ripMsg.Data = data
        print "Rip Server Protocol: data send -- Data = " + ripMsg.Data
        self.transport.write(Packet.MsgToPacketBytes(ripMsg))

    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            serverSignal = self.msgToSignal(rcvMsg)
            self.SM.signal(serverSignal, rcvMsg)

    # onEnter callback for STATE_SERVER_SNN_RCVD
    def sendSnnAck(self, signal, data):
        if signal == self.SIGNAL_SERVER_RCVD_SNN:
            print "Rip Server Protocol: sendSnnAck"
            snnackMessage = RipMessage()
            snnackMessage.SNN = True
            snnackMessage.ACK = True
            self.transport.write(Packet.MsgToPacketBytes(snnackMessage))
        else:
            print "Rip Server Protocol: sendSnnAck -- undefined signal: " + signal

    # onEnter callback for STATE_SERVER_ESTABLISHED
    def messageHandle(self, signal, msg):

        # server first enter established, must be triggered by signal-received-ack
        if signal == self.SIGNAL_SERVER_RCVD_ACK:
            print "Rip Server Protocol: message handle -- received ack"
            higherTransport = RipTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_SERVER_RIPMESSAGE:
            print "Rip Server Protocol: message handle -- receives rip message: data -- " + msg.Data
            self.higherProtocol() and self.higherProtocol().dataReceived(
                msg.Data)

        else:
            print "Rip Server Protocol: message handle -- undefined signal: ", signal
class RipServerProtocol(StackingProtocolMixin, Protocol):

    """
            Rip Server State Machine
    """
    STATE_SERVER_LISTEN = "RIP SERVER STATE MACHINE: LISTEN"
    STATE_SERVER_SNN_RCVD = "RIP SERVER STATE MACHINE: SNN_RCVD"
    STATE_SERVER_ESTABLISHED = "RIP SERVER STATE MACHINE: ESTABLISHED"
    STATE_SERVER_CLS_RCVD = "RIP SERVER STATE MACHINE: CLS_RCVD"
    STATE_SERVER_CLS_SEND = "RIP SERVER STATE MACHINE: CLS_SEND"

    SIGNAL_SERVER_RCVD_SNN = "RIP SERVER STATE MACHINE: received snn"
    SIGNAL_SERVER_RCVD_ACK = "RIP SERVER STATE MACHINE: received ack"
    SIGNAL_SERVER_RIPMESSAGE = "RIP SERVER STATE MACHINE: general data without flags"
    SIGNAL_SERVER_RCVD_CLS = "RIP SERVER STATE MACHINE: rcvd cls"
    SIGNAL_SERVER_SEND_CLS = "RIP SERVER STATE MACHINE: send cls"
    SIGNAL_SERVER_RCVD_CLSACK = "RIP SERVER STATE MACHINE: rcvd cls/ack from client"
    SIGNAL_SERVER_SEND_CLSACK = "RIP SERVER STATE MACHINE: send cls/ack back to client"

    def __init__(self):
        self.packetStorage = PacketStorage()
        self.nonce = randint(0, 10000)
        self.SM = StateMachine("Rip Server Protocol StateMachine")

        self.SM.addState(self.STATE_SERVER_LISTEN,
                        (self.SIGNAL_SERVER_RCVD_SNN, self.STATE_SERVER_SNN_RCVD),
                        )
        self.SM.addState(self.STATE_SERVER_SNN_RCVD,
                        (self.SIGNAL_SERVER_RCVD_ACK, self.STATE_SERVER_ESTABLISHED),
                        onEnter = self.sendSnnAck)

        self.SM.addState(self.STATE_SERVER_ESTABLISHED,
                        (self.SIGNAL_SERVER_RIPMESSAGE, self.STATE_SERVER_ESTABLISHED),
                        (self.SIGNAL_SERVER_RCVD_CLS, self.STATE_SERVER_CLS_RCVD),
                        (self.SIGNAL_SERVER_SEND_CLS, self.STATE_SERVER_CLS_SEND),
                        onEnter = self.messageHandle)

        self.SM.addState(self.STATE_SERVER_CLS_SEND,
                         (self.SIGNAL_SERVER_RCVD_CLSACK, self.STATE_SERVER_LISTEN),
                         onEnter = self.sendCls)

        self.SM.addState(self.STATE_SERVER_CLS_RCVD,
                         (self.SIGNAL_SERVER_SEND_CLSACK, self.STATE_SERVER_LISTEN),
                         onEnter = self.sendClsAck)

    def connectionMade(self):
        self.SM.start(self.STATE_SERVER_LISTEN)

    def connectionLost(self, reason=connectionDone):
        self.SM.signal(self.SIGNAL_SERVER_SEND_CLS, "")
        print "Rip Server Protocol: connection lost"
        self.transport.loseConnection()

    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_SERVER_ESTABLISHED:
            return
        ripMsg = RipMessage()
        ripMsg.Data = data
        print "Rip Server Protocol: data send -- Data = " + ripMsg.Data
        self.transport.write(Packet.MsgToPacketBytes(ripMsg))

    def msgToSignal(self, msg): # only used by dataReceived()
        snn = msg.SNN
        ack = msg.ACK
        cls = msg.CLS
        if(snn and not ack):
            signal = self.SIGNAL_SERVER_RCVD_SNN
        elif(not snn and ack):
            signal = self.SIGNAL_SERVER_RCVD_ACK
        elif(not snn and not ack):
            signal = self.SIGNAL_SERVER_RIPMESSAGE
        elif(cls and not ack):
            print "server received cls"
            signal = self.SIGNAL_SERVER_RCVD_CLS
        elif(cls and ack):
            signal = self.SIGNAL_SERVER_RCVD_CLSACK
        return signal


    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            serverSignal = self.msgToSignal(rcvMsg)
            print "server signal" + str(serverSignal)
            self.SM.signal(serverSignal, rcvMsg)

    """     RipServer OnEnter Callback Functions    """

    # 1. STATE_SERVER_SNN_RCVD
    def sendSnnAck(self, signal, rcvMsg):
        if signal == self.SIGNAL_SERVER_RCVD_SNN:
            if verification(0, rcvMsg) == False:
                return
            print "Rip Server Protocol: 1. sendSnnAck -- nonce1 from client = " + str(rcvMsg.Certificate[0])
            nonce1 = rcvMsg.Certificate[0]

            msg = RipMessage()
            msg.SNN = True
            msg.ACK = True
            msg.Certificate = generateServerCertificate(self.transport.getHost(), nonce1, self.nonce)
            msg.Signature = generateSignature(self.transport.getHost(), msg.__serialize__())
            self.transport.write(Packet.MsgToPacketBytes(msg))
        else:
            print "Rip Server Protocol: 1. sendSnnAck -- undefined signal: " + signal

    # 2. STATE_SERVER_ESTABLISHED
    def messageHandle(self, signal, msg):
        if signal == self.SIGNAL_SERVER_RCVD_ACK:
            print "Rip Server Protocol: 2. message handle -- received ack: nonce2 + 1 = " + str(msg.Certificate[0]) + " server nonce = " + str(self.nonce)
            nonce2Plus1 = msg.Certificate[0]
            if (int(nonce2Plus1) != (self.nonce + 1)):
                return False
            higherTransport = RipTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_SERVER_RIPMESSAGE:
            print "Rip Server Protocol: 2. message handle -- receives rip message: data -- " + msg.Data
            self.higherProtocol() and self.higherProtocol().dataReceived(msg.Data)

        else:
            print "Rip Server Protocol: 2. message handle -- undefined signal: ", signal

    # 3.1 STATE_SERVER_CLS_SEND
    def sendCls(self, signal, msg):
        if signal == self.SIGNAL_SERVER_SEND_CLS:
            print "Rip Server Protocol: 3.1 sendCls -- send CLS"
            msg = RipMessage()
            msg.CLS = True
            self.transport.write(Packet.MsgToPacketBytes(msg))
            # timer here
        else:
            print "Rip Server Protocol: 3.1 sendCls -- undefined signal: ", signal

    # 3.2 STATE_CLIENT_CLS_RCVD
    def sendClsAck(self,signal, msg):
        if signal == self.SIGNAL_SERVER_RCVD_CLS:
            print "Rip Server Protocol: 3.2 sendClsAck -- rcvd CLS"
            msg = RipMessage()
            msg.CLS = True
            msg.ACK = True
            self.transport.write(Packet.MsgToPacketBytes(msg))
            self.SM.signal(self.SIGNAL_SERVER_SEND_CLSACK, msg)
            self.transport.loseConnection()
        else:
            print "Rip Server Protocol: 3.2 sendClsAck -- undefined signal: ", signal
class KissClientProtocol(StackingProtocolMixin, Protocol):

    # states for kiss client handshake
    STATE_CLIENT_LOWERTRANSPORT_ESTABLISHED = "KISS CLIENT STATE MACHINE: CLIENT LOWERTRANSPORT ESTABLISHED"
    STATE_CLIENT_KEY_SENT = "KISS CLIENT STATE MACHINE: CLIENT SEND KEY_C"
    STATE_CLIENT_KISS_ESTABLISHED = "KISS CLIENT STATE MACHINE: CLIENT READY TO DATA TRANSMISSION"

    # signal for kiss client handshake
    SIGNAL_CLIENT_SEND_KEY_C = "KISS CLIENT STATE MACHINE: Client send K_c"
    SIGNAL_CLIENT_RCVD_KEY_S = "KISS CLIENT STATE MACHINE: Client received K_s"

    # signal for data transmission
    SIGNAL_CLIENT_RCVD_KISSDATA = "KISS CLIENT STATE MACHINE: Client received enrypted data (kiss data)"

    def __init__(self):
        self.writeIV = clientIV
        self.readIV = ""
        self.writeKey = clientKey
        self.readKey = ""

        self.IV_asCtr1 = Counter.new(128,
                                     initial_value=int(
                                         self.writeIV.encode('hex'), 16))
        #self.IV_asCtr2 = Counter.new(128, initial_value=int(self.readIV.encode('hex'),16))
        self.aesEncrypter = AES.new(self.writeKey,
                                    counter=self.IV_asCtr1,
                                    mode=AES.MODE_CTR)
        #self.aesDecrypter = AES.new(self.readKey, counter=self.IV_asCtr2, mode=AES.MODE_CTR)

        self.packetStorage = PacketStorage()
        self.SM = StateMachine("Kiss Client Protocol StateMachine")

        self.SM.addState(
            self.STATE_CLIENT_LOWERTRANSPORT_ESTABLISHED,
            # transition
            (self.SIGNAL_CLIENT_SEND_KEY_C, self.STATE_CLIENT_KEY_SENT),
            # no callback
        )
        self.SM.addState(
            self.STATE_CLIENT_KEY_SENT,
            # transition
            (self.SIGNAL_CLIENT_RCVD_KEY_S, self.STATE_CLIENT_KISS_ESTABLISHED
             ),
            # callback
            onEnter=self.keySend)
        self.SM.addState(
            self.STATE_CLIENT_KISS_ESTABLISHED,
            # transition
            (self.SIGNAL_CLIENT_RCVD_KISSDATA,
             self.STATE_CLIENT_KISS_ESTABLISHED),
            # callback
            onEnter=self.messageHandle)

    def msgToSignal(self, msg):
        if msg.messageType == "data":
            signal = self.SIGNAL_CLIENT_RCVD_KISSDATA
        elif msg.messageType == "handshake":  # for client it must be the Key_s from server
            signal = self.SIGNAL_CLIENT_RCVD_KEY_S
        return signal

    # initial kiss layer connection
    def connectionMade(self):
        self.SM.start(self.STATE_CLIENT_LOWERTRANSPORT_ESTABLISHED)
        print "Kiss Client Protocol: connectionMade -- start from state: " + self.SM.currentState(
        )
        self.SM.signal(self.SIGNAL_CLIENT_SEND_KEY_C, "")

    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_CLIENT_KISS_ESTABLISHED:
            return
        kissMsg = KissData()
        cipherText = self.aesEncrypter.encrypt(data)
        kissMsg.Data = cipherText
        self.transport.write(Packet.MsgToPacketBytes(kissMsg))

    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            kissSignal = self.msgToSignal(rcvMsg)
            print "Kiss Client Protocol: dataReceived -- kiss signal == " + kissSignal
            self.SM.signal(kissSignal, rcvMsg)

    # onEnter callback for STATE_CLIENT_KEY_SENT
    def keySend(self, signal, data):
        if signal == self.SIGNAL_CLIENT_SEND_KEY_C:
            print "Kiss Client Protocol: keySend -- send client key"
            msg = KissHandshake()
            msg.Key = self.writeKey  # Key_c
            msg.IV = self.writeIV

            print "Kiss Client Protocol: keySend -- send client key: " + msg.Key.encode(
                'hex')
            print "Kiss Client Protocol: keySend -- send client IV: " + msg.IV.encode(
                'hex')

            self.transport.write(Packet.MsgToPacketBytes(msg))
        else:
            print "Kiss Client Protocol: keySend -- undefined signal: " + signal

    # onEnter callback for STATE_CLIENT_KISS_ESTABLISHED
    def messageHandle(self, signal, kissmsg):
        '''
         Client received key and IV from server, it will
         1) setup own read key
         2) makeHigherConnection
         '''
        if signal == self.SIGNAL_CLIENT_RCVD_KEY_S:
            print "Kiss Client Protocol: messageHandle -- received server key: " + kissmsg.Key.encode(
                'hex')
            print "Kiss Client Protocol: messageHandle -- received server IV: " + kissmsg.IV.encode(
                'hex')
            self.readKey = kissmsg.Key
            self.readIV = kissmsg.IV
            higherTransport = KissTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_CLIENT_RCVD_KISSDATA:
            print "Kiss Client Protocol: messageHandle -- received encrypted data from server"
            print "Kiss Client Protocol: messageHandle -- read IV: " + self.readIV
            self.IV_asCtr2 = Counter.new(128,
                                         initial_value=int(
                                             self.readIV.encode('hex'), 16))
            self.aesDecrypter = AES.new(self.readKey,
                                        counter=self.IV_asCtr2,
                                        mode=AES.MODE_CTR)
            decrypttext = self.aesDecrypter.decrypt(kissmsg.Data)
            self.higherProtocol() and self.higherProtocol().dataReceived(
                decrypttext)

        else:
            print "Kiss Client Protocol: messageHandle -- undefined signal: " + signal
class KissServerProtocol(StackingProtocolMixin, Protocol):

    # States for handshake
    STATE_SERVER_LOWERTRANSPORT_ESTABLISHED = "KISS SERVER STATE MACHINE: LOWER TRANSPORT ESTABLISHED"
    STATE_SERVER_KISS_ESTABLISHED = "KISS SERVER STATE MACHINE: SERVER READY TO DATA TRANSMISSION"

    # signal for handshake
    SIGNAL_SERVER_RCVD_KEY_C = "KISS SERVER STATE MACHINE: Server received client key"

    # signal for kiss data transmission
    SIGNAL_SERVER_KISSDATA = "KISS SERVER STATE MACHINE: Server received kiss data"

    def __init__(self):
        self.writeIV = serverIV
        self.readIV = ""
        self.writeKey = serverKey
        self.readKey = ""

        self.IV_asCtr1 = Counter.new(128,
                                     initial_value=int(
                                         self.writeIV.encode('hex'), 16))
        #self.IV_asCtr2 = Counter.new(128, initial_value=int(self.readIV.encode('hex'),16))
        self.aesEncrypter = AES.new(self.writeKey,
                                    counter=self.IV_asCtr1,
                                    mode=AES.MODE_CTR)
        #self.aesDecrypter = AES.new(self.readKey, counter=self.IV_asCtr2, mode=AES.MODE_CTR)

        self.packetStorage = PacketStorage()
        self.SM = StateMachine("Kiss Server Protocol StateMachine")

        self.SM.addState(
            self.STATE_SERVER_LOWERTRANSPORT_ESTABLISHED,
            # transition
            (self.SIGNAL_SERVER_RCVD_KEY_C, self.STATE_SERVER_KISS_ESTABLISHED)
            # no callback
        )
        self.SM.addState(
            self.STATE_SERVER_KISS_ESTABLISHED,
            # transition
            (self.SIGNAL_SERVER_KISSDATA, self.STATE_SERVER_KISS_ESTABLISHED),
            # callback
            onEnter=self.messageHandle)

    def msgToSignal(self, msg):
        if msg.messageType == "handshake":
            signal = self.SIGNAL_SERVER_RCVD_KEY_C
        if msg.messageType == "data":
            signal = self.SIGNAL_SERVER_KISSDATA
        print signal
        return signal

    def connectionMade(self):
        self.SM.start(self.STATE_SERVER_LOWERTRANSPORT_ESTABLISHED)
        print "Kiss Client Protocol: connectionMade -- start from state" + self.SM.currentState(
        )

    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_SERVER_KISS_ESTABLISHED:
            return
        cipherText = self.aesEncrypter.encrypt(data)
        kissMsg = KissData()
        kissMsg.Data = cipherText
        self.transport.write(Packet.MsgToPacketBytes(kissMsg))

    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            kissSignal = self.msgToSignal(rcvMsg)
            print "Kiss Server Protocol: dataReceived -- kiss signal == " + kissSignal
            self.SM.signal(kissSignal, rcvMsg)

    def messageHandle(self, signal, kissmsg):
        '''
         server received client key and IV: it will
         1) set up own read key, IV
         2) send own key back to client
         3) makeHigherConnection
        '''
        if signal == self.SIGNAL_SERVER_RCVD_KEY_C:
            print "Kiss Server Protocol: messageHandle -- received key from client: " + kissmsg.Key.encode(
                'hex')
            self.readKey = kissmsg.Key
            print "Kiss Server Protocol: messageHandle -- received key from client: " + kissmsg.Key.encode(
                'hex')
            self.readIV = kissmsg.IV
            print "Kiss Server Protocol: messageHandle -- received IV from client: " + kissmsg.IV.encode(
                'hex')
            serverKeyMsg = KissHandshake()
            serverKeyMsg.Key = self.writeKey
            serverKeyMsg.IV = self.writeIV

            print "Kiss Server Protocol: messageHandle -- server encrypt key: " + self.writeKey.encode(
                'hex')
            print "Kiss Server Protocol: messageHandle -- server IV: " + self.writeIV.encode(
                'hex')

            self.transport.write(Packet.MsgToPacketBytes(serverKeyMsg))
            print "Kiss Server Protocol: messageHandle -- server send key to client: " + serverKeyMsg.Key.encode(
                'hex')

            higherTransport = KissTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_SERVER_KISSDATA:
            print "Kiss Server Protocol: messageHandle -- received encrypt data: "
            self.IV_asCtr2 = Counter.new(128,
                                         initial_value=int(
                                             self.readIV.encode('hex'), 16))
            self.aesDecrypter = AES.new(self.readKey,
                                        counter=self.IV_asCtr2,
                                        mode=AES.MODE_CTR)
            decryptText = self.aesDecrypter.decrypt(kissmsg.Data)
            print "Kiss Server Protocol: messageHandle -- decrypt data: " + decryptText
            self.higherProtocol() and self.higherProtocol().dataReceived(
                decryptText)
        else:
            print "Kiss Client Protocol: messageHandle -- undefined signal: " + signal
Exemple #11
0
class RipClientProtocol(StackingProtocolMixin, Protocol):

    STATE_CLIENT_CLOSE = "RIP CLIENT STATE MACHINE: CLOSE"
    STATE_CLIENT_ESTABLISHED = "RIP CLIENT STATE MACHINE: ESTABLISHED"

    SIGNAL_CLIENT_SEND_SNN = "RIP CLIENT STATE MACHINE: send snn"
    SIGNAL_CLIENT_RIPMESSAGE = "RIP CLIENT STATE MACHINE: general data without flags"

    def __init__(self):
        self.packetStorage = PacketStorage()
        self.SM = StateMachine("Rip Client Protocol StateMachine")

        self.SM.addState(
            self.STATE_CLIENT_CLOSE,
            # transition
            (self.SIGNAL_CLIENT_SEND_SNN, self.STATE_CLIENT_ESTABLISHED),
            # no callback for CLOSE
        )
        self.SM.addState(
            self.STATE_CLIENT_ESTABLISHED,
            # transtion
            (self.SIGNAL_CLIENT_RIPMESSAGE, self.STATE_CLIENT_ESTABLISHED),
            # callback
            onEnter=self.messageHandle)

    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_CLIENT_ESTABLISHED:
            return
        ripMsg = RipMessage()
        ripMsg.Data = data
        print "Rip Client Protocol: data send -- SNN = " + str(
            ripMsg.SNN) + " Data = " + ripMsg.Data
        self.transport.write(Packet.MsgToPacketBytes(ripMsg))

    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            print "Rip Client Protocol: dataReceived -- rip message received, current state: ", self.SM.currentState(
            )
            dataToUpper = rcvMsg.Data
            self.SM.signal(self.SIGNAL_CLIENT_RIPMESSAGE, dataToUpper)
            print "Rip Client Protocol: dataReceived -- after signal_ripmessage, current state: ", self.SM.currentState(
            )

    def messageHandle(self, signal, dataToUpper):
        if signal == self.SIGNAL_CLIENT_SEND_SNN:
            print "Rip Client Protocol: message handle -- send snn: ", dataToUpper
            higherTransport = RipTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_CLIENT_RIPMESSAGE:
            print "Rip Client Protocol: message handle -- receives rip message: ", dataToUpper
            self.higherProtocol() and self.higherProtocol().dataReceived(
                dataToUpper)

        else:
            print "Rip Client Protocol: message handle -- undefined signal: ", signal

    def connectionMade(self):
        print "Rip Client Protocol: connection Made"
        self.SM.start(self.STATE_CLIENT_CLOSE)
        print "Rip Client Protocol: start state machine from state -- " + self.SM.currentState(
        )
        self.snnSend()
        self.SM.signal(self.SIGNAL_CLIENT_SEND_SNN, "")
        print "Rip Client Protocol: after snn send current state -- " + self.SM.currentState(
        )

    def snnSend(self):
        snnMessage = RipMessage()
        snnMessage.SNN = True
        self.transport.write(Packet.MsgToPacketBytes(snnMessage))
        print "Rip Client Protocol: send snn"
Exemple #12
0
class RipServerProtocol(StackingProtocolMixin, Protocol):

    # States for handshake
    STATE_SERVER_LISTEN = "RIP STATE MACHINE: LISTEN"
    STATE_SERVER_ESTABLISHED = "RIP STATE MACHINE: ESTABLISHED"

    # signal
    SIGNAL_SERVER_RCVD_SNN = "RIP STATE MACHINE: received snn"
    SIGNAL_SERVER_RIPMESSAGE = "RIP STATE MACHINE: general data without flags"

    def __init__(self):
        self.packetStorage = PacketStorage()
        self.SM = StateMachine("Rip Server Protocol StateMachine")

        self.SM.addState(
            self.STATE_SERVER_LISTEN,
            # transition
            (self.SIGNAL_SERVER_RCVD_SNN, self.STATE_SERVER_ESTABLISHED),
            # no callback for LISTEN
        )
        self.SM.addState(
            self.STATE_SERVER_ESTABLISHED,
            # transtion
            (self.SIGNAL_SERVER_RIPMESSAGE, self.STATE_SERVER_ESTABLISHED),
            # callback
            onEnter=self.messageHandle)

    def connectionMade(self):
        self.SM.start(self.STATE_SERVER_LISTEN)

    def dataSend(self, data):
        if not self.SM.currentState() == self.STATE_SERVER_ESTABLISHED:
            return
        ripMsg = RipMessage()
        ripMsg.Data = data
        print "Rip Server Protocol: data send -- SNN = " + str(
            ripMsg.SNN) + " Data = " + ripMsg.Data
        self.transport.write(Packet.MsgToPacketBytes(ripMsg))

    def dataReceived(self, data):
        self.packetStorage.update(data)
        for rcvMsg in IterateMessages(self.packetStorage, logger, errReporter):
            if (rcvMsg.SNN == True):
                print "Rip Protocol: dataReceived -- snn received, current state: ", self.SM.currentState(
                )
                self.SM.signal(self.SIGNAL_SERVER_RCVD_SNN, rcvMsg)
                print "Rip Protocol: dataReceived -- after;l signal_rcvd_snn, current state: ", self.SM.currentState(
                )
            else:
                print "Rip Protocol: dataReceived -- rip message received, current state: ", self.SM.currentState(
                )
                dataToUpper = rcvMsg.Data
                self.SM.signal(self.SIGNAL_SERVER_RIPMESSAGE, dataToUpper)
                print "Rip Protocol: dataReceived -- after signal_ripmessage, current state: ", self.SM.currentState(
                )

    def messageHandle(self, signal, dataToUpper):

        if signal == self.SIGNAL_SERVER_RCVD_SNN:
            print "Rip Server Protocol: message handle -- receives snn: ", dataToUpper
            higherTransport = RipTransport(self.transport, self)
            self.makeHigherConnection(higherTransport)

        elif signal == self.SIGNAL_SERVER_RIPMESSAGE:
            print "Rip Protocol: message handle -- receives rip message: ", dataToUpper
            self.higherProtocol() and self.higherProtocol().dataReceived(
                dataToUpper)

        else:
            print "Rip Protocol: message handle -- undefined signal: ", signal