Esempio n. 1
0
        packetData = ''  # Acknowledgment packets contain no data
        urgentPointer = 0  # Not urgent as this is connection setup
        synBit = 1  # Syn bit has to be one since this is connection setup
        finBit = 0  # Not trying to finish connection, therefore 0
        rstBit = 0  # Not trying to reset connection, therefore 0
        terBit = 0  # Not trying to terminate connection, therefore 0

        # Create packet with above data
        responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                acknowledgementNumber,
                                                sequenceNumber, packetData,
                                                urgentPointer, synBit, finBit,
                                                rstBit, terBit)

        # Send packet
        helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

        # Log it
        timeStamp = time.time()
        data = datetime.datetime.fromtimestamp(timeStamp).strftime(
            '%Y-%m-%d %H:%M:%S') + '\n'
        data = data + "Connection setup with Chan started. This is the first step of the threeway handshake.\n\n"
        helper.WriteToLogFile(pathToAnnChanLogFile, 'a', data)

        # Run till connection teardown or termination
        while not exitEvent.isSet():
            pass

        # Wait for nnn's server to finish
        annServer.join()
Esempio n. 2
0
    def handle(self):

        # self.request is the TCP socket connected to the client
        incomingPacket = self.request.recv(4096)
        incomingPacketDecoded = pickle.loads(incomingPacket)

        receivedFrom = helper.GetKeyFromValue(
            incomingPacketDecoded.get('Source ID'))

        global Mission3Counter

        if incomingPacketDecoded.get('Fin Bit') == 1 and Mission3Counter == 7:

            sourceID = portListeningTo  # The port listening to
            destinationID = helper.namesAndPorts.get(
                'Jan'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = incomingPacketDecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting
            # Next byte of data that you want
            acknowledgementNumber = incomingPacketDecoded.get(
                'Sequence Number'
            ) + 1  # Client wanted to disconnect, therefore no data in the original packet, ack # will be one more than client seq #
            packetData = ''  # Second step of three way handshake, therefore no data
            urgentPointer = 0  # Not urgent as this is connection setup
            synBit = 0  # Syn bit is zero
            finBit = 1  # Trying to finish connection
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Mission Complete, Communication with Jan is Finished. This is the second step of the connection teardown.\n\n'
            helper.WriteToLogFile(pathToAnnJanLogFile, 'a', data)
            print('Fin Bit reveived.... sending Fin Bit to Jan....\n')
            print('Ann Ending Connection...')
            # exit Ann's event
            exitEvent.set()

        elif incomingPacketDecoded.get(
                'Urgent Pointer') == 1 and Mission3Counter == 5:

            Mission3Counter = 7
            sourceID = portListeningTo  # The port listening to
            destinationID = helper.namesAndPorts.get(
                'Jan'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = incomingPacketDecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting
            # Next byte of data that you want
            acknowledgementNumber = incomingPacketDecoded.get(
                'Sequence Number') + len(incomingPacketDecoded.get('Data'))
            packetData = 'Meeting Location: 32.76 N, -97.07 W\n'  # Send the coordinates to meet Jan
            urgentPointer = 0  # Not urgent as this is connection setup
            synBit = 0  # Syn bit is zero
            finBit = 0  # Not trying to finish connection, therefore 0
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Received following line.\n'
            data = data + incomingPacketDecoded.get('Data')
            data = data + 'Acknowledgement sent along with below line.\n'
            data = data + packetData + '\n\n'
            helper.WriteToLogFile(pathToAnnJanLogFile, 'a', data)
            print('Urg pointer resived: ' + incomingPacketDecoded.get('Data'))
            print('\nAnnToJan: Meeting Location: 32.76 N, -97.07 W\n')

        elif incomingPacketDecoded.get(
                'Urgent Pointer') == 1 and Mission3Counter == 1:

            # increment the next position
            Mission3Counter = 5

            sourceID = portListeningTo  # The port listening to
            destinationID = helper.namesAndPorts.get(
                'Jan'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = incomingPacketDecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting
            # Next byte of data that you want
            acknowledgementNumber = incomingPacketDecoded.get(
                'Sequence Number') + len(incomingPacketDecoded.get('Data'))
            # authorize to execute and give code
            packetData = 'PEPPER THE PEPPER\n'
            urgentPointer = 0  # Not urgent as this is connection setup
            synBit = 0  # Syn bit is zero
            finBit = 0  # Not trying to finish connection, therefore 0
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Received following line.\n'
            data = data + incomingPacketDecoded.get('Data')
            data = data + 'Acknowledgement sent along with below line.\n'
            data = data + packetData + '\n\n'
            helper.WriteToLogFile(pathToAnnJanLogFile, 'a', data)
            print('Urg pointer resived: ' + incomingPacketDecoded.get('Data'))
            print('\nAnnToJan: Execute\n' +
                  'The authorization code for the Airforce Headquarters:\n' +
                  'PEPPER THE PEPPER\n')

        # When someone else is trying to setup connection with us
        elif Mission3Counter < 0:
            if incomingPacketDecoded.get(
                    'Syn Bit') == 1 and incomingPacketDecoded.get(
                        'Acknowledgement Number') == -1:

                # Send TCP packet with syn bit still one and acknowledgement number as 1 + sequence number. Also, create your own sequence number
                sourceID = portListeningTo  # The port listening to
                destinationID = incomingPacketDecoded.get(
                    'Source ID'
                )  # The destination of the packet about to be sent is where the original packet came from
                sequenceNumber = random.randint(
                    10000, 99999
                )  # First time talking to client, create new sequence number
                acknowledgementNumber = incomingPacketDecoded.get(
                    'Sequence Number'
                ) + 1  # Client wanted to connect, therefore no data in the original packet, ack # will be one more than client seq #
                packetData = ''  # Second step of three way handshake, therefore no data
                urgentPointer = 0  # Not urgent as this is connection setup
                synBit = 1  # Syn bit has to be one for the second step of threeway handshake
                finBit = 0  # Not trying to finish connection, therefore 0
                rstBit = 0  # Not trying to reset connection, therefore 0
                terBit = 0  # Not trying to terminate connection, therefore 0

                # Create packet with above data
                responsePacket = helper.CreateTCPPacket(
                    sourceID, destinationID, acknowledgementNumber,
                    sequenceNumber, packetData, urgentPointer, synBit, finBit,
                    rstBit, terBit)

                # Send packet
                helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

                # Log what happened
                timeStamp = time.time()
                data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                    '%Y-%m-%d %H:%M:%S') + '\n'

                if receivedFrom == 'Jan':
                    data = data + 'Jan as a client attempted to connect. Sent packet with Syn Bit as 1, which is the second step of the threeway handshake.\n\n'
                    helper.WriteToLogFile(pathToAnnJanLogFile, 'a', data)
                elif receivedFrom == 'Chan':
                    data = data + 'Chan as a client attempted to connect. Sent packet with Syn Bit as 1, which is the second step of the threeway handshake.\n\n'
                    helper.WriteToLogFile(pathToAnnChanLogFile, 'a', data)

            # Your attempt to setup connection with someone else has been responded to
            elif incomingPacketDecoded.get('Syn Bit') == 1:

                # Start sending data here and raise the flag to wait for acknowledgement
                sourceID = portListeningTo  # The port listening to
                destinationID = incomingPacketDecoded.get(
                    'Source ID'
                )  # The destination of the packet about to be sent is where the original packet came from
                sequenceNumber = incomingPacketDecoded.get(
                    'Acknowledgement Number'
                )  # The  next byte you should be sending is the byte that the other party is expecting
                acknowledgementNumber = incomingPacketDecoded.get(
                    'Sequence Number'
                ) + 1  # Just one more than the sequence number

                urgentPointer = 0  # Not urgent as this is connection setup
                synBit = 0  # Threeway handshake third step, no need of this bit
                finBit = 0  # Not trying to finish connection, therefore 0
                rstBit = 0  # Not trying to reset connection, therefore 0
                terBit = 0  # Not trying to terminate connection, therefore 0

                # Populate data field depending on who the connection is being established with
                if receivedFrom == 'Jan':
                    try:
                        packetData = contentAnnToJan.pop(
                            0
                        )  # Get the first element from list and delete it from there
                    except IndexError:
                        print('Ann-_Jan.txt is empty.\n\n')

                elif receivedFrom == 'Chan':
                    try:
                        packetData = contentAnnToChan.pop(
                            0
                        )  # Get the first element from list and delete it from there
                    except IndexError:
                        print('Ann-_Chan.txt is empty.\n\n')

                # Create packet with above data
                responsePacket = helper.CreateTCPPacket(
                    sourceID, destinationID, acknowledgementNumber,
                    sequenceNumber, packetData, urgentPointer, synBit, finBit,
                    rstBit, terBit)

                # Send packet
                helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

                # Log what happened
                timeStamp = time.time()
                data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                    '%Y-%m-%d %H:%M:%S') + '\n'

                if receivedFrom == 'Jan':
                    data = data + 'Connection with Jan as the server is successful. This is the third step of the threeway handshake. First line, which is below was sent.\n'
                    data = data + packetData + '\n\n'
                    helper.WriteToLogFile(pathToAnnJanLogFile, 'a', data)
                elif receivedFrom == 'Chan':
                    data = data + 'Connection with Chan as the server is successful. This is the third step of the threeway handshake. First line, which is below was sent.\n'
                    data = data + packetData + '\n\n'
                    helper.WriteToLogFile(pathToAnnChanLogFile, 'a', data)

            # Any other case, is receiving data
            else:
                global Chan_Counter
                # terminate communication with Chan and inform Jan about compromise
                if Chan_Counter == 5:
                    Chan_Counter = Chan_Counter + 1
                    Mission3Counter = 1
                    print(
                        "Terminating Connection With Agent Chan since Chan is compromised.\n"
                    )

                    # send jan a packet with urgbit 1 with Chan being compromised
                    sourceID = portListeningTo  # The port listening to
                    destinationID = helper.namesAndPorts.get(
                        'Jan'
                    )  # The destination of the packet about to be sent is where the original packet came from
                    sequenceNumber = random.randint(
                        10000, 99999
                    )  # First time talking to client, create new that the other party is expecting
                    # Next byte of data that you want
                    acknowledgementNumber = incomingPacketDecoded.get(
                        'Sequence Number') + 1
                    packetData = 'Communication with Chan has been Compromised'  # Termination packet contain no data
                    urgentPointer = 1  # Urgent pointer is 1 to tell Jan that Chan has been compromised
                    synBit = 0  # Syn bit has to be one for the second step of
                    finBit = 0  #
                    rstBit = 0  # Not trying to reset connection, therefore 0
                    terBit = 0
                    responsePacket = helper.CreateTCPPacket(
                        sourceID, destinationID, acknowledgementNumber,
                        sequenceNumber, packetData, urgentPointer, synBit,
                        finBit, rstBit, terBit)
                    # Send packet
                    helper.SerializeAndSendPacket(responsePacket,
                                                  portTalkingTo)
                    # log in the termination
                    timeStamp = time.time()
                    data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                        '%Y-%m-%d %H:%M:%S') + '\n'
                    data = data + 'Communication with Chan has been Terminated.\n\n'
                    helper.WriteToLogFile(pathToAnnJanLogFile, 'a', data)
                    print(
                        'AnnToJan: Urg Pointer On: Communication with Chan has been compromised.'
                    )

                    # send chan a packet with terbit 1
                    sourceID = portListeningTo  # The port listening to
                    destinationID = helper.namesAndPorts.get(
                        'Chan'
                    )  # The destination of the packet about to be sent is where the original packet came from
                    sequenceNumber = incomingPacketDecoded.get(
                        'Acknowledgement Number'
                    )  # The  next byte you should be sending is the byte that the other party is expecting
                    # Next byte of data that you want
                    acknowledgementNumber = incomingPacketDecoded.get(
                        'Sequence Number') + len(
                            incomingPacketDecoded.get('Data'))
                    packetData = ''  # Termination packet contain no data
                    urgentPointer = 0  # Not urgent as this is connection setup
                    synBit = 0  # Syn bit has to be one for the second step of
                    finBit = 0  #
                    rstBit = 1  # reset communication flag on to terminate communication
                    terBit = 1  # make terbit 1 to start termination with chan
                    responsePacket = helper.CreateTCPPacket(
                        sourceID, destinationID, acknowledgementNumber,
                        sequenceNumber, packetData, urgentPointer, synBit,
                        finBit, rstBit, terBit)
                    # Send packet
                    helper.SerializeAndSendPacket(responsePacket,
                                                  portTalkingTo)
                    # log in the termination
                    timeStamp = time.time()
                    data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                        '%Y-%m-%d %H:%M:%S') + '\n'
                    data = data + 'Communication with Chan has been Terminated.\n\n'
                    helper.WriteToLogFile(pathToAnnChanLogFile, 'a', data)

                else:
                    # Send acknowledgement
                    sourceID = portListeningTo  # The port listening to
                    destinationID = incomingPacketDecoded.get(
                        'Source ID'
                    )  # The destination of the packet about to be sent is where the original packet came from
                    sequenceNumber = incomingPacketDecoded.get(
                        'Acknowledgement Number'
                    )  # The  next byte you should be sending is the byte that the other party is expecting

                    # Next byte of data that you want
                    acknowledgementNumber = incomingPacketDecoded.get(
                        'Sequence Number') + len(
                            incomingPacketDecoded.get('Data'))
                    urgentPointer = 0  # Not urgent as this is connection setup
                    synBit = 0  # Syn bit has to be one for the second step of threeway handshake
                    finBit = 0  # Not trying to finish connection, therefore 0
                    rstBit = 0  # Not trying to reset connection, therefore 0
                    terBit = 0  # Not trying to terminate connection, therefore 0

                    # Populate data field depending on who the connection is being established with
                    if receivedFrom == 'Jan':
                        try:
                            packetData = contentAnnToJan.pop(
                                0
                            )  # Get the first element from list and delete it from there
                        except IndexError:
                            # send jan a packet with urgbit 1 with Chan being compromised
                            sourceID = portListeningTo  # The port listening to
                            destinationID = helper.namesAndPorts.get(
                                'Jan'
                            )  # The destination of the packet about to be sent is where the original packet came from
                            sequenceNumber = random.randint(
                                10000, 99999
                            )  # First time talking to client, create new that the other party is expecting
                            # Next byte of data that you want
                            acknowledgementNumber = incomingPacketDecoded.get(
                                'Sequence Number') + 1
                            packetData = 'Communication with Chan has been Compromised'  # Termination packet contain no data
                            urgentPointer = 1  # Urgent pointer is 1 to tell Jan that Chan has been compromised
                            synBit = 0  # Syn bit has to be one for the second step of
                            finBit = 0  #
                            rstBit = 0  # Not trying to reset connection, therefore 0
                            terBit = 0
                            responsePacket = helper.CreateTCPPacket(
                                sourceID, destinationID, acknowledgementNumber,
                                sequenceNumber, packetData, urgentPointer,
                                synBit, finBit, rstBit, terBit)
                            # Send packet
                            helper.SerializeAndSendPacket(
                                responsePacket, portTalkingTo)
                            # log in the termination
                            timeStamp = time.time()
                            data = datetime.datetime.fromtimestamp(
                                timeStamp).strftime('%Y-%m-%d %H:%M:%S') + '\n'
                            data = data + 'Communication with Chan has been Terminated.\n\n'
                            helper.WriteToLogFile(pathToAnnJanLogFile, 'a',
                                                  data)

                    elif receivedFrom == 'Chan':
                        try:
                            packetData = contentAnnToChan.pop(
                                0
                            )  # Get the first element from list and delete it from there
                        except IndexError:
                            # Kick of connection tear down function here
                            pass

                    # Create packet with above data
                    responsePacket = helper.CreateTCPPacket(
                        sourceID, destinationID, acknowledgementNumber,
                        sequenceNumber, packetData, urgentPointer, synBit,
                        finBit, rstBit, terBit)

                    # Send packet
                    helper.SerializeAndSendPacket(responsePacket,
                                                  portTalkingTo)

                    # Log what happened
                    timeStamp = time.time()
                    data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                        '%Y-%m-%d %H:%M:%S') + '\n'
                    data = data + 'Received following line.\n'
                    data = data + incomingPacketDecoded.get('Data')
                    data = data + 'Acknowledgement sent along with below line.\n'
                    data = data + packetData + '\n\n'

                    if receivedFrom == 'Jan':
                        helper.WriteToLogFile(pathToAnnJanLogFile, 'a', data)

                    elif receivedFrom == 'Chan':
                        helper.WriteToLogFile(pathToAnnChanLogFile, 'a', data)
                        Chan_Counter = Chan_Counter + 1

        return
Esempio n. 3
0
    def handle(self):
        incoming_pckt = self.request.recv(4096)
        decoded_pckt = pickle.loads(incoming_pckt)
        receiver = helper.GetKeyFromValue(decoded_pckt.get('Source ID'))

        if decoded_pckt.get('Ter Bit') == 1:
            print('Connection terminated by Ann.\n')
            threading.Event().set()

        elif decoded_pckt.get('Syn Bit') == 1 and decoded_pckt.get(
                'Acknowledgement Number') == -1:
            source_id = listeningport  # The port listening to
            destination_id = decoded_pckt.get('Source ID')
            sequence_num = random.randint(10000, 99999)
            ack_num = decoded_pckt.get('Sequence Number') + 1
            packet_data = ''
            urg_pointer = 0
            syn_bit = 1
            fin_bit = 0
            rst_bit = 0
            ter_bit = 0

            # Create packet with above data
            resp_pckt = helper.CreateTCPPacket(source_id, destination_id,
                                               ack_num, sequence_num,
                                               packet_data, urg_pointer,
                                               syn_bit, fin_bit, rst_bit,
                                               ter_bit)
            # Send packet
            helper.SerializeAndSendPacket(resp_pckt, talkingport)
            # Maintain log
            current_time = time.time()
            shared_data = datetime.datetime.fromtimestamp(
                current_time).strftime('%Y-%m-%d %H:%M:%S') + '\n'

            if receiver == 'Ann':
                shared_data = shared_data + 'Connection request from Ann.\n\n'
                helper.WriteToLogFile(chanannlog_file, 'a', shared_data)
            elif receiver == 'Jan':
                shared_data = shared_data + 'Connection requested from Jan.\n\n'
                helper.WriteToLogFile(chanjanlog_file, 'a', shared_data)

        elif decoded_pckt.get('Syn Bit') == 1:
            # Send data and raise the flag to wait for acknowledgement
            source_id = listeningport
            destination_id = decoded_pckt.get('Source ID')
            sequence_num = decoded_pckt.get('Acknowledgement Number')
            ack_num = decoded_pckt.get('Sequence Number') + 1
            urg_pointer = 0
            syn_bit = 0
            fin_bit = 0
            rst_bit = 0
            ter_bit = 0

            # Populate data field depending on who the connection is being established with
            if receiver == 'Ann':
                try:
                    packet_data = chantoann_comm.pop(
                        0)  # Traverse the text file line by line
                except IndexError:
                    print('Chan-Ann.txt is empty.\n\n')

            elif receiver == 'Jan':
                try:
                    packet_data = chantojan_comm.pop(0)
                except IndexError:
                    print('Chan-Jan.txt is empty.\n\n')

            # Create packet with above data
            resp_pckt = helper.CreateTCPPacket(source_id, destination_id,
                                               ack_num, sequence_num,
                                               packet_data, urg_pointer,
                                               syn_bit, fin_bit, rst_bit,
                                               ter_bit)

            # Send packet
            helper.SerializeAndSendPacket(resp_pckt, talkingport)

            # Log what happened
            current_time = time.time()
            shared_data = datetime.datetime.fromtimestamp(
                current_time).strftime('%Y-%m-%d %H:%M:%S') + '\n'

            if receiver == 'Ann':
                shared_data = shared_data + 'Connection established with Ann.\n'
                shared_data = shared_data + packet_data + '\n\n'
                helper.WriteToLogFile(chanannlog_file, 'a', shared_data)
            elif receiver == 'Jan':
                shared_data = shared_data + 'Connection established with Jan.\n'
                shared_data = shared_data + packet_data + '\n\n'
                helper.WriteToLogFile(chanjanlog_file, 'a', shared_data)

        # Receiving data
        else:
            source_id = listeningport
            destination_id = decoded_pckt.get('Source ID')
            sequence_num = decoded_pckt.get('Acknowledgement Number')
            ack_num = decoded_pckt.get('Sequence Number') + len(
                decoded_pckt.get('Data'))
            urg_pointer = 0
            syn_bit = 0
            fin_bit = 0
            rst_bit = 0
            ter_bit = 0

            if receiver == 'Ann':
                try:
                    packet_data = chantoann_comm.pop(0)
                except IndexError:
                    pass

            elif receiver == 'Jan':
                try:
                    packet_data = chantojan_comm.pop(0)
                except IndexError:
                    pass

            # Create packet with above data
            resp_pckt = helper.CreateTCPPacket(source_id, destination_id,
                                               ack_num, sequence_num,
                                               packet_data, urg_pointer,
                                               syn_bit, fin_bit, rst_bit,
                                               ter_bit)

            # Send packet
            helper.SerializeAndSendPacket(resp_pckt, talkingport)

            current_time = time.time()
            shared_data = datetime.datetime.fromtimestamp(
                current_time).strftime('%Y-%m-%d %H:%M:%S') + '\n'
            shared_data = shared_data + 'Received following line.\n'
            shared_data = shared_data + decoded_pckt.get('Data')
            shared_data = shared_data + 'Acknowledgement sent along with below line.\n'
            shared_data = shared_data + packet_data + '\n\n'

            if receiver == 'Ann':
                helper.WriteToLogFile(chanannlog_file, 'a', shared_data)
            elif receiver == 'Jan':
                helper.WriteToLogFile(chanjanlog_file, 'a', shared_data)
        return
        def handle(self):
        
            # self.request is the TCP socket connected to the client
            packetOnTheWay = self.request.recv(4096)
            packet = pickle.loads(packetOnTheWay)
            print(routerName + '\n' + str(packet) + '\n')
            
            sourceID = packet.get('Source ID')
            destinationID = packet.get('Destination ID')

            # Packet is from Ann to Jan
            if sourceID == helper.namesAndPorts.get('Ann') and destinationID == helper.namesAndPorts.get('Jan'):
                helper.PassPacket(pathAnnToJan, routerName, packetOnTheWay)
            
            # Packet is from Jan to the Airforce
            elif sourceID == helper.namesAndPorts.get('Jan') and destinationID == helper.namesAndPorts.get('H'):
                
                sourceID = helper.namesAndPorts.get('H')
                destinationID = helper.namesAndPorts.get('Jan')                              # The destination of the packet about to be sent is where the original packet came from
                sequenceNumber = random.randint(10000, 99999)                                # First time talking to Jan, create new sequence number                                                                                  
                                                                                             # Next byte of data that you want
                acknowledgementNumber = packet.get('Sequence Number')+ len(packet.get('Data'))    
                packetData = 'Success!'                                                      # Second step of three way handshake, therefore no data
                urgentPointer = 0                                                            # Not urgent as this is connection setup
                synBit = 0                                                                   # Syn bit is zero
                finBit = 0                                                                   # Trying to finish connection
                rstBit = 0                                                                   # Not trying to reset connection, therefore 0
                terBit = 0                                                                   # Not trying to terminate connection, therefore 0

                # Create packet with above data
                responsePacket = helper.CreateTCPPacket(sourceID, destinationID, acknowledgementNumber, sequenceNumber, packetData, urgentPointer, synBit, finBit, rstBit, terBit)

                # Send packet
                helper.SerializeAndSendPacket(responsePacket, destinationID)

                # Log what happened at the airport router
                timeStamp = time.time()
                data = datetime.datetime.fromtimestamp(timeStamp).strftime('%Y-%m-%d %H:%M:%S') + '\n'
                data = data + 'Received following line.\n'
                data = data + packet.get('Data')
                data = data + 'Acknowledgement sent along with below line.\n'
                data = data + packetData + '\n\n'
                helper.WriteToLogFile(pathToAirForceJanLogFile, 'w', data)

                print('Airforce to Jan: Success!')
            
            # Packet is from Jan to Ann
            elif sourceID == helper.namesAndPorts.get('Jan') and destinationID == helper.namesAndPorts.get('Ann'):    
                helper.PassPacket(pathJanToAnn, routerName, packetOnTheWay)
            
            # Packet is from Jan to Chan
            elif sourceID == helper.namesAndPorts.get('Jan') and destinationID == helper.namesAndPorts.get('Chan'):    
                helper.PassPacket(pathJanToChan, routerName, packetOnTheWay)

            # Packet is from Chan to Jan
            elif sourceID == helper.namesAndPorts.get('Chan') and destinationID == helper.namesAndPorts.get('Jan'):    
                helper.PassPacket(pathChanToJan, routerName, packetOnTheWay)

            # Packet is from Ann to Chan
            elif sourceID == helper.namesAndPorts.get('Ann') and destinationID == helper.namesAndPorts.get('Chan'):    
                helper.PassPacket(pathAnnToChan, routerName, packetOnTheWay)
            
            # Packet is from Jan to Ann
            elif sourceID == helper.namesAndPorts.get('Chan') and destinationID == helper.namesAndPorts.get('Ann'):    
                helper.PassPacket(pathChanToAnn, routerName, packetOnTheWay)

            

            # Packet has no right direction
            else:
                print('Packet has no right direction' + '\n\n')

            return
Esempio n. 5
0
        sequence_num = random.randint(1000, 9999)
        ack_num = -1
        packet_data = ''
        urg_pointer = 0
        syn_bit = 1
        fin_bit = 0
        rst_bit = 0
        ter_bit = 0

        # Create packet with above data
        resp_pckt = helper.CreateTCPPacket(source_id, destination_id, ack_num,
                                           sequence_num, packet_data,
                                           urg_pointer, syn_bit, fin_bit,
                                           rst_bit, ter_bit)
        # Send packet
        helper.SerializeAndSendPacket(resp_pckt, talkingport)
        # Log it
        current_time = time.time()
        shared_data = datetime.datetime.fromtimestamp(current_time).strftime(
            '%Y-%m-%d %H:%M:%S') + '\n'
        shared_data = shared_data + "Establishing connection with server Jan initiated.\n\n"
        helper.WriteToLogFile(chanjanlog_file, 'a', shared_data)

        # Execute until connection termination
        while not threading.Event().isSet():
            pass

        # Wait for Chan's server to finish
        chanServer.join()
        sys.exit()
    except KeyboardInterrupt:
Esempio n. 6
0
        sequenceno = random.randint(10000, 99999)  # First time talking to Jan, create new sequence number
        acknumber = -1  # Haven't recevied anything from Jan, hence -1
        packetData = ''  # Acknowledgment packets contain no data
        urgentPointer = 0  # Not urgent as this is connection setup
        synBit = 1  # Syn bit has to be one since this is connection setup
        finBit = 0  # Not trying to finish connection, hence 0
        rstBit = 0  # Not trying to reset connection, hence 0
        terBit = 0  # Not trying to terminate connection, hence 0

        # Create packet with above data
        responsePacket = helper.CreateTCPPacket(sourceid, destinationid, acknumber, sequenceno,
                                                packetData, urgentPointer,
                                                synBit, finBit, rstBit, terBit)

        # Send packet
        helper.SerializeAndSendPacket(responsePacket, talkingport)

        # Log it
        timeStamp = time.time()
        data = datetime.datetime.fromtimestamp(timeStamp).strftime('%Y-%m-%d %H:%M:%S') + '\n'
        data = data + "Connection setup with Chan started. This is the first step of the threeway handshake.\n\n"
        helper.WriteToLogFile(annchan_logfile, 'a', data)

        # Run till connection teardown or termination
        while not threadingEvent.isSet():
            pass

        # Wait for ann's server to finish
        annserver.join()

        sys.exit()
    def handle(self):

        # self.request is the TCP socket connected to the client
        incomingPacket = self.request.recv(4096)
        incomingPacketDecoded = pickle.loads(incomingPacket)

        receivedFrom = helper.GetKeyFromValue(
            incomingPacketDecoded.get('Source ID'))

        if incomingPacketDecoded.get('Ter Bit') == 1:
            print('Ann has ordered the termination of the connection.\n')
            exitEvent.set()

        # When someone else is trying to setup connection with us
        elif incomingPacketDecoded.get(
                'Syn Bit') == 1 and incomingPacketDecoded.get(
                    'Acknowledgement Number') == -1:

            # Send TCP packet with syn bit still one and acknowledgement number as 1 + sequence number. Also, create your own sequence number
            sourceID = portListeningTo  # The port listening to
            destinationID = incomingPacketDecoded.get(
                'Source ID'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = random.randint(
                10000, 99999
            )  # First time talking to client, create new sequence number
            acknowledgementNumber = incomingPacketDecoded.get(
                'Sequence Number'
            ) + 1  # Client wanted to connect, therefore no data in the original packet, ack # will be one more than client seq #
            packetData = ''  # Second step of three way handshake, therefore no data
            urgentPointer = 0  # Not urgent as this is connection setup
            synBit = 1  # Syn bit has to be one for the second step of threeway handshake
            finBit = 0  # Not trying to finish connection, therefore 0
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'

            if receivedFrom == 'Jan':
                data = data + 'Jan as a client attempted to connect. Sent packet with Syn Bit as 1, which is the second step of the threeway handshake.\n\n'
                helper.WriteToLogFile(pathToChanJanLogFile, 'a', data)
            elif receivedFrom == 'Ann':
                data = data + 'Ann as a client attempted to connect. Sent packet with Syn Bit as 1, which is the second step of the threeway handshake.\n\n'
                helper.WriteToLogFile(pathToChanAnnLogFile, 'a', data)

        # Your attempt to setup connection with someone else has been responded to
        elif incomingPacketDecoded.get('Syn Bit') == 1:

            # Start sending data here and raise the flag to wait for acknowledgement
            sourceID = portListeningTo  # The port listening to
            destinationID = incomingPacketDecoded.get(
                'Source ID'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = incomingPacketDecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting
            acknowledgementNumber = incomingPacketDecoded.get(
                'Sequence Number'
            ) + 1  # Just one more than the sequence number
            urgentPointer = 0  # Not urgent as this is connection setup
            synBit = 0  # Threeway handshake third step, no need of this bit
            finBit = 0  # Not trying to finish connection, therefore 0
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Populate data field depending on who the connection is being established with
            if receivedFrom == 'Jan':
                try:
                    packetData = contentChanToJan.pop(
                        0
                    )  # Get the first element from list and delete it from there
                except IndexError:
                    print('Chan-_Jan.txt is empty.\n\n')

            elif receivedFrom == 'Ann':
                try:
                    packetData = contentChanToAnn.pop(
                        0
                    )  # Get the first element from list and delete it from there
                except IndexError:
                    print('Chan-_Ann.txt is empty.\n\n')

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'

            if receivedFrom == 'Jan':
                data = data + 'Connection with Jan as the server is successful. This is the third step of the threeway handshake. First, which is below line was sent.\n'
                data = data + packetData + '\n\n'
                helper.WriteToLogFile(pathToChanJanLogFile, 'a', data)
            elif receivedFrom == 'Ann':
                data = data + 'Connection with Ann as the server is successful. This is the third step of the threeway handshake. First, which is below line was sent.\n'
                data = data + packetData + '\n\n'
                helper.WriteToLogFile(pathToChanAnnLogFile, 'a', data)

        # Any other case, is receiving data
        else:
            # Send acknowledgement
            sourceID = portListeningTo  # The port listening to
            destinationID = incomingPacketDecoded.get(
                'Source ID'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = incomingPacketDecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting

            # Next byte of data that you want
            acknowledgementNumber = incomingPacketDecoded.get(
                'Sequence Number') + len(incomingPacketDecoded.get('Data'))

            urgentPointer = 0  # Not urgent as this is connection setup
            synBit = 0  # Syn bit has to be one for the second step of threeway handshake
            finBit = 0  # Not trying to finish connection, therefore 0
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Populate data field depending on who the connection is being established with
            if receivedFrom == 'Jan':
                try:
                    packetData = contentChanToJan.pop(
                        0
                    )  # Get the first element from list and delete it from there
                except IndexError:
                    # Kick of connection tear down function here
                    pass

            elif receivedFrom == 'Ann':
                try:
                    packetData = contentChanToAnn.pop(
                        0
                    )  # Get the first element from list and delete it from there
                except IndexError:
                    # Kick of connection tear down function here
                    pass

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Received following line.\n'
            data = data + incomingPacketDecoded.get('Data')
            data = data + 'Acknowledgement sent along with below line.\n'
            data = data + packetData + '\n\n'

            if receivedFrom == 'Jan':
                helper.WriteToLogFile(pathToChanJanLogFile, 'a', data)
            elif receivedFrom == 'Ann':
                helper.WriteToLogFile(pathToChanAnnLogFile, 'a', data)

        return
Esempio n. 8
0
    def handle(self):

        # self.request is the TCP socket connected to the client
        incomingPacket = self.request.recv(4096)
        incomingPacketDecoded = pickle.loads(incomingPacket)

        receivedFrom = helper.GetKeyFromValue(
            incomingPacketDecoded.get('Source ID'))
        global Mission3Counter

        if incomingPacketDecoded.get('Fin Bit') == 1 and Mission3Counter == 8:

            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Acknowledgement recieved, Communication with Ann is Finished.This is the third step for the communication teardown.\n\n'
            helper.WriteToLogFile(pathToJanAnnLogFile, 'a', data)
            # exit Jan's event
            print('Fin Bit reveived....\n')
            print('Jan Ending Connection...')
            exitEvent.set()

        elif Mission3Counter == 6:

            # increment the next position
            Mission3Counter = 8

            sourceID = portListeningTo  # The port listening to
            destinationID = helper.namesAndPorts.get(
                'Ann'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = incomingPacketDecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting
            # Next byte of data that you want
            acknowledgementNumber = incomingPacketDecoded.get(
                'Sequence Number') + len(incomingPacketDecoded.get('Data'))
            packetData = 'Request for a finish mission?\n'  # Second step of three way handshake, therefore no data
            urgentPointer = 0  # Not urgent as this is connection setup
            synBit = 0  # Syn bit is zero
            finBit = 1  # Trying to finish connection
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Received following line.\n'
            data = data + incomingPacketDecoded.get('Data')
            data = data + 'Acknowledgement sent along with below line. This is the first step of the connection teardown.\n'
            data = data + packetData + '\n\n'
            helper.WriteToLogFile(pathToJanAnnLogFile, 'a', data)
            print('JanToAnn: sending Fin Bit to ann.\n')

        elif Mission3Counter == 4 and incomingPacketDecoded.get(
                'Data') == 'Success!':

            # increment the next position
            Mission3Counter = 6
            sourceID = portListeningTo  # The port listening to
            destinationID = helper.namesAndPorts.get(
                'Ann'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = incomingPacketDecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting
            # Next byte of data that you want
            acknowledgementNumber = incomingPacketDecoded.get(
                'Sequence Number') + len(incomingPacketDecoded.get('Data'))
            # confirm success by giving the code
            packetData = 'The authorization code:\n' + 'Congratulations we have fried dry green leaves\n'
            urgentPointer = 1  # Message is urgent
            synBit = 0  # Syn bit is zero
            finBit = 0  # Not trying to finish connection, therefore 0
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Received following line.\n'
            data = data + incomingPacketDecoded.get('Data')
            data = data + 'Acknowledgement sent along with below line.\n'
            data = data + packetData + '\n\n'
            helper.WriteToLogFile(pathToJanAnnLogFile, 'a', data)
            print('Recieved Success packet from Head Quarters.\n')
            print('JanToAnn: Urg Pointer On: The authorization code:\n' +
                  'Congratulations we have fried dry green leaves\n')

        elif Mission3Counter == 2 and incomingPacketDecoded.get(
                'Data') == 'PEPPER THE PEPPER\n':

            # increment the next position
            # need to see how to execute to router H

            sourceID = portListeningTo  # The port listening to
            destinationID = helper.namesAndPorts.get(
                'H'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = sequenceNumber = random.randint(
                10000, 99999
            )  # The  next byte you should be sending is the byte that the other party is expecting
            # Next byte of data that you want
            acknowledgementNumber = -1
            # confirm success by giving the code
            packetData = 'Location of target: (32° 43 22.77 N,97° 9 7.53 W)\n' + 'The authorization code for the Airforce Headquarters:\n' + 'PEPPER THE PEPPER\n'
            urgentPointer = 1  # Message is urgent
            synBit = 0  # Syn bit is zero
            finBit = 0  # Not trying to finish connection, therefore 0
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket,
                                          helper.namesAndPorts.get('H'))

            # Log what happened

            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Received following line.\n'
            data = data + incomingPacketDecoded.get('Data')
            data = data + 'Acknowledgement sent along with below line.\n'
            data = data + packetData + '\n\n'
            helper.WriteToLogFile(pathToJanAirForceLogFile, 'a', data)
            Mission3Counter = 4
            print('Recieved Authorization code from Ann.\n')
            print(
                'JanToAirForce: Location of target: (32° 43 22.77 N,97° 9 7.53 W)\n'
                + 'The authorization code for the Airforce Headquarters:\n' +
                'PEPPER THE PEPPER\n')

        elif incomingPacketDecoded.get('Urgent Pointer') == 1:
            # increment the next position
            Mission3Counter = 2
            sourceID = portListeningTo  # The port listening to
            destinationID = helper.namesAndPorts.get(
                'Ann'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceNumber = incomingPacketDecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting
            # Next byte of data that you want
            acknowledgementNumber = incomingPacketDecoded.get(
                'Sequence Number') + len(incomingPacketDecoded.get('Data'))
            # confirm success by giving the code
            packetData = 'Location of target: (32° 43 22.77 N,97° 9 7.53 W)\n' + 'Request for a mission execution?\n'
            urgentPointer = 1  # Message is urgent
            synBit = 0  # Syn bit is zero
            finBit = 0  # Not trying to finish connection, therefore 0
            rstBit = 0  # Not trying to reset connection, therefore 0
            terBit = 0  # Not trying to terminate connection, therefore 0

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceID, destinationID,
                                                    acknowledgementNumber,
                                                    sequenceNumber, packetData,
                                                    urgentPointer, synBit,
                                                    finBit, rstBit, terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Received following line.\n'
            data = data + incomingPacketDecoded.get('Data')
            data = data + 'Acknowledgement sent along with below line.\n'
            data = data + packetData + '\n\n'
            helper.WriteToLogFile(pathToJanAnnLogFile, 'a', data)
            print('Urg pointer resived: ' + incomingPacketDecoded.get('Data'))
            print(
                'JanToAnn: Urg Pointer On: Location of target: (32° 43 22.77 N,97° 9 7.53 W)\n'
                + 'Request for a mission execution?\n')

        elif Mission3Counter < 0:
            # When someone else is trying to setup connection with us
            if incomingPacketDecoded.get(
                    'Syn Bit') == 1 and incomingPacketDecoded.get(
                        'Acknowledgement Number') == -1:

                # Send TCP packet with syn bit still one and acknowledgement number as 1 + sequence number. Also, create your own sequence number
                sourceID = portListeningTo  # The port listening to
                destinationID = incomingPacketDecoded.get(
                    'Source ID'
                )  # The destination of the packet about to be sent is where the original packet came from
                sequenceNumber = random.randint(
                    10000, 99999
                )  # First time talking to client, create new sequence number
                acknowledgementNumber = incomingPacketDecoded.get(
                    'Sequence Number'
                ) + 1  # Client wanted to connect, therefore no data in the original packet, ack # will be one more than client seq #
                packetData = ''  # Second step of three way handshake, therefore no data
                urgentPointer = 0  # Not urgent as this is connection setup
                synBit = 1  # Syn bit has to be one for the second step of threeway handshake
                finBit = 0  # Not trying to finish connection, therefore 0
                rstBit = 0  # Not trying to reset connection, therefore 0
                terBit = 0  # Not trying to terminate connection, therefore 0

                # Create packet with above data
                responsePacket = helper.CreateTCPPacket(
                    sourceID, destinationID, acknowledgementNumber,
                    sequenceNumber, packetData, urgentPointer, synBit, finBit,
                    rstBit, terBit)

                # Send packet
                helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

                # Log what happened
                timeStamp = time.time()
                data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                    '%Y-%m-%d %H:%M:%S') + '\n'

                if receivedFrom == 'Chan':
                    data = data + 'Chan as a client attempted to connect. Sent packet with Syn Bit as 1, which is the second step of the threeway handshake.\n\n'
                    helper.WriteToLogFile(pathToJanChanLogFile, 'a', data)
                elif receivedFrom == 'Ann':
                    data = data + 'Ann as a client attempted to connect. Sent packet with Syn Bit as 1, which is the second step of the threeway handshake.\n\n'
                    helper.WriteToLogFile(pathToJanAnnLogFile, 'a', data)

            # Your attempt to setup connection with someone else has been responded to
            elif incomingPacketDecoded.get('Syn Bit') == 1:

                # Start sending data here and raise the flag to wait for acknowledgement
                sourceID = portListeningTo  # The port listening to
                destinationID = incomingPacketDecoded.get(
                    'Source ID'
                )  # The destination of the packet about to be sent is where the original packet came from
                sequenceNumber = incomingPacketDecoded.get(
                    'Acknowledgement Number'
                )  # The  next byte you should be sending is the byte that the other party is expecting
                acknowledgementNumber = incomingPacketDecoded.get(
                    'Sequence Number'
                ) + 1  # Just one more than the sequence number
                urgentPointer = 0  # Not urgent as this is connection setup
                synBit = 0  # Threeway handshake third step, no need of this bit
                finBit = 0  # Not trying to finish connection, therefore 0
                rstBit = 0  # Not trying to reset connection, therefore 0
                terBit = 0  # Not trying to terminate connection, therefore 0

                # Populate data field depending on who the connection is being established with
                if receivedFrom == 'Chan':
                    try:
                        packetData = contentJanToChan.pop(
                            0
                        )  # Get the first element from list and delete it from there
                    except IndexError:
                        print('Jan-_Chan.txt is empty.\n\n')

                elif receivedFrom == 'Ann':
                    try:
                        packetData = contentJanToAnn.pop(
                            0
                        )  # Get the first element from list and delete it from there
                    except IndexError:
                        print('Jan-_Ann.txt is empty.\n\n')

                # Create packet with above data
                responsePacket = helper.CreateTCPPacket(
                    sourceID, destinationID, acknowledgementNumber,
                    sequenceNumber, packetData, urgentPointer, synBit, finBit,
                    rstBit, terBit)

                # Send packet
                helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

                # Log what happened
                timeStamp = time.time()
                data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                    '%Y-%m-%d %H:%M:%S') + '\n'

                if receivedFrom == 'Chan':
                    data = data + 'Connection with Chan as the server is successful. This is the third step of the threeway handshake. First, which is below line was sent.\n'
                    data = data + packetData + '\n\n'
                    helper.WriteToLogFile(pathToJanChanLogFile, 'a', data)
                elif receivedFrom == 'Ann':
                    data = data + 'Connection with Ann as the server is successful. This is the third step of the threeway handshake. First, which is below line was sent.\n'
                    data = data + packetData + '\n\n'
                    helper.WriteToLogFile(pathToJanAnnLogFile, 'a', data)

            # Any other case, is receiving data
            else:
                # Send acknowledgement
                sourceID = portListeningTo  # The port listening to
                destinationID = incomingPacketDecoded.get(
                    'Source ID'
                )  # The destination of the packet about to be sent is where the original packet came from
                sequenceNumber = incomingPacketDecoded.get(
                    'Acknowledgement Number'
                )  # The  next byte you should be sending is the byte that the other party is expecting

                # Next byte of data that you want
                acknowledgementNumber = incomingPacketDecoded.get(
                    'Sequence Number') + len(incomingPacketDecoded.get('Data'))

                urgentPointer = 0  # Not urgent as this is connection setup
                synBit = 0  # Syn bit has to be one for the second step of threeway handshake
                finBit = 0  # Not trying to finish connection, therefore 0
                rstBit = 0  # Not trying to reset connection, therefore 0
                terBit = 0  # Not trying to terminate connection, therefore 0

                # Populate data field depending on who the connection is being established with
                if receivedFrom == 'Chan':
                    try:
                        packetData = contentJanToChan.pop(
                            0
                        )  # Get the first element from list and delete it from there
                    except IndexError:
                        # Kick of connection tear down function here
                        pass

                elif receivedFrom == 'Ann':
                    try:
                        packetData = contentJanToAnn.pop(
                            0
                        )  # Get the first element from list and delete it from there
                    except IndexError:
                        # Kick of connection tear down function here
                        pass

                # Create packet with above data
                responsePacket = helper.CreateTCPPacket(
                    sourceID, destinationID, acknowledgementNumber,
                    sequenceNumber, packetData, urgentPointer, synBit, finBit,
                    rstBit, terBit)

                # Send packet
                helper.SerializeAndSendPacket(responsePacket, portTalkingTo)

                # Log what happened
                timeStamp = time.time()
                data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                    '%Y-%m-%d %H:%M:%S') + '\n'
                data = data + 'Received following line.\n'
                data = data + incomingPacketDecoded.get('Data')
                data = data + 'Acknowledgement sent along with below line.\n'
                data = data + packetData + '\n\n'

                if receivedFrom == 'Chan':
                    helper.WriteToLogFile(pathToJanChanLogFile, 'a', data)
                elif receivedFrom == 'Ann':
                    helper.WriteToLogFile(pathToJanAnnLogFile, 'a', data)

        return
Esempio n. 9
0
    def handle(self):

        # socket connecting to client here
        packetgoingin = self.request.recv(4096)
        packetgoingindecoded = pickle.loads(packetgoingin)

        messagereceivedfrom = helper.GetKeyFromValue(
            packetgoingindecoded.get('Source ID'))

        if packetgoingindecoded.get('Ter Bit') == 1:
            print('Ann has ordered the termination of the connection.\n')
            exitEvent.set()

        # To check if someone else is trying to corrupt the connection.
        elif packetgoingindecoded.get(
                'Syn Bit') == 1 and packetgoingindecoded.get(
                    'Acknowledgement Number') == -1:

            # ack +1 and creating own sequence number.
            #Three way handshake
            sourceid = listeningport
            destinationid = packetgoingindecoded.get('Source ID')
            sequenceno = random.randint(
                10000, 99999
            )  # First time talking to client, create new sequence number
            acknumber = packetgoingindecoded.get(
                'Sequence Number'
            ) + 1  # Client wanted to connect, hence no data in the original packet, ack # will be one more than client seq #
            packetData = ''
            urgentPointer = 0
            synBit = 1  # Syn bit has to be one for the second step of threeway handshake
            finBit = 0  # Not trying to finish connection, hence 0
            rstBit = 0  # Not trying to reset connection, hence 0
            terBit = 0  # Not trying to terminate connection, hence 0

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceid, destinationid,
                                                    acknumber, sequenceno,
                                                    packetData, urgentPointer,
                                                    synBit, finBit, rstBit,
                                                    terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, talkingport)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'

            if messagereceivedfrom == 'Jan':
                data = data + 'Jan as a client attempted to connect. Sent packet with Syn Bit as 1, which is the second step of the threeway handshake.\n\n'
                helper.WriteToLogFile(chanjan_logfile, 'a', data)
            elif messagereceivedfrom == 'Ann':
                data = data + 'Ann as a client attempted to connect. Sent packet with Syn Bit as 1, which is the second step of the threeway handshake.\n\n'
                helper.WriteToLogFile(chanann_logfile, 'a', data)

                # Connection setup response.
        elif packetgoingindecoded.get('Syn Bit') == 1:

            # Start sending data here and raise the flag to wait for acknowledgement
            sourceid = listeningport  # The port listening to
            destinationid = packetgoingindecoded.get(
                'Source ID'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceno = packetgoingindecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting
            acknumber = packetgoingindecoded.get(
                'Sequence Number') + 1  # One more than the sequence number
            urgentPointer = 0
            synBit = 0  # Threeway handshake third step, no need of this bit
            finBit = 0  # Not trying to finish connection, hence 0
            rstBit = 0  # Not trying to reset connection, hence 0
            terBit = 0  # Not trying to terminate connection, hence 0

            # Populate data field depending on who the connection is being established with
            if messagereceivedfrom == 'Jan':
                try:
                    packetData = chantojan_comm.pop(
                        0
                    )  # Get the first element from list and delete it from there
                except IndexError:
                    print('Chan-_Jan.txt is empty.\n\n')

            elif messagereceivedfrom == 'Ann':
                try:
                    packetData = chantoann_comm.pop(
                        0
                    )  # Get the first element from list and delete it from there
                except IndexError:
                    print('Chan-_Ann.txt is empty.\n\n')

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceid, destinationid,
                                                    acknumber, sequenceno,
                                                    packetData, urgentPointer,
                                                    synBit, finBit, rstBit,
                                                    terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, talkingport)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'

            if messagereceivedfrom == 'Jan':
                data = data + 'Connection with Jan as the server is successful. This is the third step of the threeway handshake. First, which is below line was sent.\n'
                data = data + packetData + '\n\n'
                helper.WriteToLogFile(chanjan_logfile, 'a', data)
            elif messagereceivedfrom == 'Ann':
                data = data + 'Connection with Ann as the server is successful. This is the third step of the threeway handshake. First, which is below line was sent.\n'
                data = data + packetData + '\n\n'
                helper.WriteToLogFile(chanann_logfile, 'a', data)

        # Any other case, is receiving data
        else:
            # Send acknowledgement
            sourceid = listeningport  # The port listening to
            destinationid = packetgoingindecoded.get(
                'Source ID'
            )  # The destination of the packet about to be sent is where the original packet came from
            sequenceno = packetgoingindecoded.get(
                'Acknowledgement Number'
            )  # The  next byte you should be sending is the byte that the other party is expecting

            # Next byte of data that you want
            acknumber = packetgoingindecoded.get('Sequence Number') + len(
                packetgoingindecoded.get('Data'))

            urgentPointer = 0  # Not urgent as this is connection setup
            synBit = 0  # Syn bit has to be one for the second step of threeway handshake
            finBit = 0  # Not trying to finish connection, hence 0
            rstBit = 0  # Not trying to reset connection, hence 0
            terBit = 0  # Not trying to terminate connection, hence 0

            # Populate data field depending on who the connection is being established with
            if messagereceivedfrom == 'Jan':
                try:
                    packetData = chantojan_comm.pop(
                        0
                    )  # Get the first element from list and delete it from there
                except IndexError:
                    # Kick of connection tear down function here
                    pass

            elif messagereceivedfrom == 'Ann':
                try:
                    packetData = chantoann_comm.pop(
                        0
                    )  # Get the first element from list and delete it from there
                except IndexError:
                    # Kick of connection tear down function here
                    pass

            # Create packet with above data
            responsePacket = helper.CreateTCPPacket(sourceid, destinationid,
                                                    acknumber, sequenceno,
                                                    packetData, urgentPointer,
                                                    synBit, finBit, rstBit,
                                                    terBit)

            # Send packet
            helper.SerializeAndSendPacket(responsePacket, talkingport)

            # Log what happened
            timeStamp = time.time()
            data = datetime.datetime.fromtimestamp(timeStamp).strftime(
                '%Y-%m-%d %H:%M:%S') + '\n'
            data = data + 'Received following line.\n'
            data = data + packetgoingindecoded.get('Data')
            data = data + 'Acknowledgement sent along with below line.\n'
            data = data + packetData + '\n\n'

            if messagereceivedfrom == 'Jan':
                helper.WriteToLogFile(chanjan_logfile, 'a', data)
            elif messagereceivedfrom == 'Ann':
                helper.WriteToLogFile(chanann_logfile, 'a', data)

        return