예제 #1
0
def main():
    # parse arguments
    if len(sys.argv) != 5:
        print("usage: python3 %s <host> <port>" % sys.argv[0])
        quit(1)
    host = sys.argv[1]
    port = sys.argv[2]

    # open a socket
    clientfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # connect to server
    clientfd.connect((host, int(port)))

    # message loop
    while (True):

        if sys.argv[4] == 1:
            msg = ktpt()
            clientfd.send(msg.encode())


#        # You don't need to receive for this assignment, but if you wanted to
#        # you would use something like this
#        msg = clientfd.recv(1024).decode()
#        print("Received from server: %s" % msg)

# close connection
    clientfd.close()
def main():
    # parse arguments
    if len(sys.argv) != 2:
        print("usage: python3 %s <port>" % sys.argv[0])
        quit(1)
    port = sys.argv[1]
    
    # TODO 1: open a socket, bind, and listen
    # OPEN SOCKET
    sock_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # BIND SOCKET
    address = ("", int(port))
    sock_fd.bind(address)

    # LISTEN FOR CONNECTION
    sock_fd.listen(5)

    # TODO 2: accept connections from client

    # ACCEPT CONNECTION
    conn, addr = sock_fd.accept()


    # message loop
    while(True):
        # TODO 3: receive a message from client and send response
        data = conn.recv(50)
        print("Received from client: " + str(data.decode()))
        input_data = input("Enter message for client: ")
        bytes = input_data.encode()
        conn.send(bytes)
예제 #3
0
def main():
    # parse arguments
    if len(sys.argv) != 4:
        print("usage: python3 %s <host> <port> <port>" % sys.argv[0])
        quit(1)
    host = sys.argv[1]
    bob_port = sys.argv[2]
    mallory_port = sys.argv[3]

    # connect to bob
    # open a client socket
    clientfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # connect to server
    clientfd.connect((host, int(bob_port)))

    # connect to alice
    # open a listen socket
    listenfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listenfd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # bind socket to ip and port
    listenfd.bind(('', int(mallory_port)))

    # listen to socket
    listenfd.listen(1)

    # accept connection
    (connfd, addr) = listenfd.accept()

    # message loop
    while (True):
        msg = connfd.recv(1024).decode()
        print("Received from client: %s" % msg)

        slct = input(
            "Type 1 to delete message, Type 2 to change message sent or Type 3 to send original message\n"
        )
        if int(slct) == 1:
            break
        elif int(slct) == 2:
            msg = input('type new message \n')
            clientfd.send(msg.encode())
        elif int(slct) == 3:
            clientfd.send(msg.encode())

        #        # You don't need to receive for this assignment, but if you wanted to


#        # you would use something like this
#        msg = clientfd.recv(1024).decode()
#        print("Received from server: %s" % msg)

# close connection
    clientfd.close()
예제 #4
0
    def __init__(self, img_path, label_path):
        self.img_p = img_path
        self.label_p = label_path
        self.img_ids = []

        # use a live loading for training samples later,
        # so the loader class would only save the ids of the
        # training data
        if self._load() <= 0:
            print("No training data found.")
            os.quit()
예제 #5
0
def main():
    # parse arguments
    if len(sys.argv) != 3:
        print("usage: python3 %s <host> <port>" % sys.argv[0])
        quit(1)
    host = sys.argv[1]
    port = sys.argv[2]

    # TODO 1: open a socket and connect to server
    sock_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock_fd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    address = (host, int(port))

    sock_fd.connect(address)

    # message loop
    while (True):
        # TODO 2: send message and receive response
        input_data = input("Enter message for server: ")
        bytes = input_data.encode()
        sock_fd.send(bytes)
        data = sock_fd.recv(50)
        print("Received from server: " + str(data.decode()))
예제 #6
0
 def __sanitycheck(self):
     if self.goth_count > 0 and self.hipster_count > 0:
         print("sync error: bad social mixup! Goths = %d, Hipsters = %d" %  (self.goth_count, self.hipster_count))
         quit(1)
     if self.goth_count>self.capacity or self.hipster_count>self.capacity:
         print("sync error: too many people in the club! Goths = %d, Hipsters = %d" %  (self.goth_count, self.hipster_count))
         quit(1)
     if self.goth_count < 0 or self.hipster_count < 0:
         print("sync error: lost track of people! Goths = %d, Hipsters = %d" %  (self.goth_count, self.hipster_count))
         quit(1)
        if buf.startswith(b'\xff\xd8'):
            # Start of new frame; close the old one (if any) and
            # open a new output
            if self.output:
                self.output.close()
            self.frame_num += 1
            self.output = io.open(self.folder+'/img_%03d.jpg' % self.frame_num, 'wb')
        self.output.write(buf)

folder = sys.argv[-1]

if not os.path.isdir(folder):
    os.mkdir(folder)
else:
    print('Folder already exists!')
    os.quit()

experiment_time = 30 #s

with picamera.PiCamera() as camera:
    camera.resolution = (800,800)
    camera.framerate = 81
    camera.shutter_speed = 2000
    camera.start_preview()
    # Give the camera some warm-up time
    time.sleep(2)
    output = SplitFrames(folder)
    print('start...')
    start = time.time()
    camera.start_recording(output, format='mjpeg')
    camera.wait_recording(experiment_time)
예제 #8
0
def main():

    # Parse arguments
    if len(sys.argv) != 3:
        print("usage: python3 %s <port> <config>" % sys.argv[0])
        quit(1)

    # Setting the port
    port = sys.argv[1]
    config = sys.argv[2]

    # Set up encryption cnfiguration
    if config == "noCrypto":
        enc = False
        mac = False
    elif config == "enc":
        enc = True
        mac = False
    elif config == "mac":
        enc = False
        mac = True
    elif config == "EncThenMac":
        enc = True
        mac = True
    else:
        print("invalid configuration " + config +
              " valid configuration options: noCrypto, enc, mac, EncThenMac")
        quit(1)

    expected_message_num = 0

    # Open a socket
    listenfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    listenfd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Bind socket to ip and port
    listenfd.bind(('', int(port)))

    # Listen to socket
    listenfd.listen(1)

    # Accept connection
    (connfd, addr) = listenfd.accept()

    bob_private_key, bob_public_key, alice_public_key = read_keys()

    # Load crypto tools if needed
    session_key = None
    enc_session_key = None
    mac_key = None
    enc_mac_key = None
    digital_signature = None

    initial_msg = None
    msg_for = None
    time_sent_str = None
    signed_msg = None

    if enc or mac:
        initial_msg = connfd.recv(1024)
        msg_for = initial_msg[:3].decode()
        time_sent_str = initial_msg[3:23].decode()

        signed_msg = msg_for.encode() + time_sent_str.encode()

    if enc and mac:
        enc_session_key = initial_msg[23:279]
        enc_mac_key = initial_msg[279:667].decode()
        digital_signature = initial_msg[667:]

        session_key = decrypt_session_key(enc_session_key, bob_private_key)
        mac_key = decrypt(enc_mac_key, session_key)

        signed_msg += enc_session_key + enc_mac_key.encode()

    elif enc:
        enc_session_key = initial_msg[23:279]
        digital_signature = initial_msg[279:]

        session_key = decrypt_session_key(enc_session_key, bob_private_key)

        signed_msg += enc_session_key

    elif mac:
        mac_key = initial_msg[23:279]
        digital_signature = initial_msg[279:]

        signed_msg = msg_for.encode() + time_sent_str.encode() + mac_key

    if enc or mac:
        if verify_digital_signature(signed_msg, digital_signature,
                                    alice_public_key):
            print("The Signature Is Authentic.\n")
        else:
            print("The Signature Is Not Authentic.\n")
            print("Terminating Connection!")
            exit(1)

        time_sent = datetime.strptime(time_sent_str, "%m/%d/%Y, %H:%M:%S")
        current_time = datetime.now()

        time_delta = current_time - time_sent
        if time_delta.seconds > 120:
            print("Too Much Time Has Elapsed!")
            print("Terminating Connection!")
            exit(1)

        print("Message For: ", msg_for, "\n")
        print("Time Sent: ", time_sent_str, "\n")
        print("Time Recieved: ", current_time, "\n")
        if session_key is not None: print("Session Key: ", session_key, "\n")
        if enc_session_key is not None:
            print("Encrypted Session Key: ", enc_session_key, "\n")
        if mac_key is not None: print("Mac Key: ", mac_key, "\n")
        if enc_mac_key is not None:
            print("Encrypted Mac Key: ", enc_mac_key, "\n")
        if digital_signature is not None:
            print("Digital Signature: ", digital_signature, "\n")

    print('recieving')
    # Message loop
    while (True):
        recieved_msg = connfd.recv(1024).decode()
        print('recieved:' + recieved_msg)
        message = None
        encrypted_message = None
        tag = None
        decrypted_msg = None

        message_number = int.from_bytes(recieved_msg[:4].encode(), "big")

        if enc and mac:
            tag = recieved_msg[4:68]
            encrypted_message = recieved_msg[68:]
            message = decrypt(encrypted_message, session_key)

        elif enc:
            encrypted_message = recieved_msg[4:]
            message = decrypt(encrypted_message, session_key)

        elif mac:
            tag = recieved_msg[4:68]
            message = recieved_msg[68:]

        else:
            message = recieved_msg[4:]

        if not verify_message_num(message_number, expected_message_num):
            print("Messages Numbers Don't Line Up!")
            print("Terminating Connection!")
            exit(1)
        else:
            expected_message_num += 1

        if mac:
            message_to_verify = encrypted_message if enc else message
            if verify_message(message_to_verify, tag, mac_key):
                print("Message Is Authentic")
            else:
                print("Message Has Been Altered")
                print("Terminating Connection!")
                exit(1)

        print("Message Number: ", message_number)
        if encrypted_message is not None:
            print("Encrypted Message: ", encrypted_message)
        if tag is not None: print("Tag: ", tag)
        print("Plain Message: ", message, "\n")

    # Close connection
    connfd.close()
    listenfd.close()
예제 #9
0
파일: punika.py 프로젝트: soneek/romhacking
        graphics = {
            0: {
                'bank': 0x3b,
                'target': 0x8000,
                'vrambank': 0x00,
                'pointer': 0x5218
            },
            1: {
                'bank': 0x3d,
                'target': 0x9000,
                'vrambank': 0x00,
                'pointer': 0x5e94
            },
        }
    else:
        os.quit('Unsupported ROM.')

    if action == 'list':
        for i, g in graphics.items():
            rom.seek(abspointer(g['bank'], g['pointer']))
            compressed = readbyte()
            total = readshort()
            print(
                "{:>4} - bank {:>4} + {:>8} ({:>8}), {} bytes {} read in {:>7}"
                .format(hex(i), hex(g['bank']), hex(g['pointer']),
                        hex(abspointer(g['bank'], g['pointer'])), hex(total),
                        "compressed" if compressed else "not compressed",
                        hex(g['target'])))

    elif action == 'extract':
        for gi, g in graphics.items():
예제 #10
0
def main():

    # Parse arguments
    if len(sys.argv) != 4:
        print("usage: python3 %s <host> <port> <config> % sys.argv[0]")
        quit(1)
    host = sys.argv[1]
    port = sys.argv[2]
    config = sys.argv[3]

    # Set up encryption configuration
    if config == "noCrypto":
        enc = False
        mac = False
    elif config == "enc":
        enc = True
        mac = False
    elif config == "mac":
        enc = False
        mac = True
    elif config == "EncThenMac":
        enc = True
        mac = True
    else:
        print("invalid configuration " + config +
              " valid configuration options: noCrypto, enc, mac, EncThenMac")
        quit(1)

    # Keeps track of the message number
    message_number = 0

    # Open a socket
    clientfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Connect to server
    clientfd.connect((host, int(port)))
    print("Connected to server\n")

    # Read in keys
    alice_private_key, alice_public_key, bob_public_key = read_keys()

    # Load requested tools
    session_key = None
    enc_session_key = None
    mac_key = None
    enc_mac_key = None

    current_time = datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
    message_to_sign = "bob".encode() + current_time.encode()

    if enc and mac:
        session_key, enc_session_key = generate_session_key(bob_public_key)
        mac_key = generate_mac_key()
        enc_mac_key = encrypt(mac_key, session_key)
        message_to_sign += enc_session_key + enc_mac_key.encode()

    elif enc:
        session_key, enc_session_key = generate_session_key(bob_public_key)
        message_to_sign += enc_session_key

    elif mac:
        mac_key = generate_mac_key()
        message_to_sign += mac_key

    if enc or mac:
        digital_signature = generate_digital_signature(message_to_sign,
                                                       alice_private_key)
        set_up_msg = message_to_sign + digital_signature
        print(len(set_up_msg))
        clientfd.send(set_up_msg)

        print("Message For: Bob\n")
        print("Time Sent: ", current_time, "\n")
        if session_key is not None: print("Session Key: ", session_key, "\n")
        if enc_session_key is not None:
            print("Encrypted Session Key: ", enc_session_key, "\n")
        if mac_key is not None: print("Mac Key: ", mac_key, "\n")
        if enc_mac_key is not None:
            print("Encrypted Mac Key: ", enc_mac_key, "\n")
        if digital_signature is not None:
            print("Digital Signature: ", digital_signature, "\n")

    # Message loop
    while (True):
        msg = input("Enter message: ")
        print()

        enc_message = None
        tag = None

        out_going_msg = message_number.to_bytes(4, byteorder='big')

        # Send encrypted message with mac tag
        if enc and mac:
            enc_message = encrypt(msg.encode(), session_key)
            tag = generate_mac(enc_message, mac_key)
            out_going_msg += (tag + enc_message).encode()

        # Send encrypted message with no tags
        elif enc:
            enc_message = encrypt(msg.encode(), session_key)
            out_going_msg += enc_message.encode()

        # Send plaintext with mac tag
        elif mac:
            tag = generate_mac(msg, mac_key)
            out_going_msg += (tag + msg).encode()

        # Send message in plaintext
        else:
            out_going_msg += msg.encode()

        clientfd.send(out_going_msg)

        print("Message Number: ", message_number)
        print("Plain Message: ", msg)
        if enc_message is not None: print("Encrypted Message: ", enc_message)
        if tag is not None: print("Tag: ", tag, "\n")

        message_number += 1

    # Close connection
    clientfd.close()
예제 #11
0
def Quit():
    pygame.quit()
    sys.exit()
    os.quit()
예제 #12
0
파일: punika.py 프로젝트: soneek/romhacking
        rom.seek((0x7b*0x4000)+0x040a)
        for i in range(0xff):
            g = {}
            g['bank'] = readbyte()
            g['pointer'] = readbeshort()
            readbyte()
            readbyte()
            readbyte()
            g['target'] = 0
            graphics[i] = g
    elif game == b'CROC 2\0\0':
        # This game probably sets all offsets manually.  You're on your own here!  Check out RO3F:59F5 for starters.
        graphics = {0:{'bank': 0x3b, 'target': 0x8000, 'vrambank': 0x00, 'pointer': 0x5218},
                    1:{'bank': 0x3d, 'target': 0x9000, 'vrambank': 0x00, 'pointer': 0x5e94},}
    else:
        os.quit('Unsupported ROM.')
    
    if action == 'list':
        for i, g in graphics.items():
            rom.seek(abspointer(g['bank'], g['pointer']))
            compressed = readbyte()
            total = readshort()
            print ("{:>4} - bank {:>4} + {:>8} ({:>8}), {} bytes {} read in {:>7}".format(hex(i),
            hex(g['bank']), 
            hex(g['pointer']), 
            hex(abspointer(g['bank'], g['pointer'])), hex(total), "compressed" if compressed else "not compressed", hex(g['target'])))
    
    elif action == 'extract':
        for gi, g in graphics.items():
            l = abspointer(g['bank'], g['pointer'])
예제 #13
0
def main():

    emailClass = pdfClass.ccePdfAutosendClass()
    outlookConnectLib= \
     SourceFileLoader("module.name", emailClass.credentialsLocation).load_module()

    outlookServerDict = outlookConnectLib.outlookConnect()
    outlookServer = outlookServerDict['serverfile']
    outlookEmailSender = outlookServerDict['senderFriendly']

    #input table import goes here
    inputFileClass = pdfClass.cceEmailListInputClass()
    receipientDF = inputFileClass.importCCESendList()
    print(receipientDF.head())

    #traverse folders
    traverseClass = pdfClass.folderTraverse()
    cceDealerReportsDF = traverseClass.rootDirTraverse()
    print(cceDealerReportsDF.head())

    #as400 query goes here, check update timestamp, dont attempt if current
    #compile input tables here
    #not necessary? ^^ more of a sanity check on list -- 2nd priority

    print(type(receipientDF))
    print(type(cceDealerReportsDF))

    #loop input table here, for each row, send an email
    finalInputClass = pdfClass.iteratedCompleteInputFile()
    finalInputDF = finalInputClass.joinInputs(receipientDF, cceDealerReportsDF,
                                              inputFileClass.inputFileKeys,
                                              traverseClass.folderTraverseKeys)
    print(finalInputDF.head())

    if finalInputDF is not None:
        finalInputDF['test'] = 'FAIL'
        for index, row in finalInputDF.iterrows():
            print('Sending ' + row['subject'])
            try:
                finalInputDF.loc[index, 'test'] = 'SUCCESS'
                emattch.sendEmail(
                    outlookEmailSender,
                    row['Emails'],
                    row['subject'],
                    finalInputClass.textemail(),
                    finalInputClass.htmlemail(),
                    row['filepath'] + row['filename'],
                    row['filename'],
                    outlookServer  #serverConnect=None
                    ,
                    1  #readReceipt
                )
                print('Send Success: ' + row['subject'])
                print('Waiting 10 seconds...')
                time.sleep(10)
            except:
                print('Send Error -- logging error on ' + row['subject'])
                finalInputDF.loc[index, 'test'] = sys.exc_info()[0]
        print(finalInputDF.head())

    else:
        print('finalInputDF is NULL')
        os.quit()

    outlookConnectLib.outlookDisconnect(outlookServer)
예제 #14
0
    if progress >= 16:
        score += 1
        progress = 0
        badspeed += 1
        for i in range(0, len(badguys)): ##--Respawns enemies
            if i < 8:
                badguys[i] = [i*30+45, 0, 6, 0]
            if i >= 8:
                badguys[i] = [i*30-195, 21, 6, 0]

    bullety = bullety - bulletspeed ##-- Bullet movement code

    for event in pygame.event.get():
        if event.type == pygame.QUIT: ##--Qutting when the x button is clicked
            pygame.quit()
            os.quit()

        if event.type == pygame.KEYDOWN:

            if event.key == pygame.K_a: ##--Movement
                axes -= 1
            if event.key == pygame.K_d:
                axes += 1

            if event.key == pygame.K_ESCAPE: ##--Quit
                os.quit()
                pygame.quit()

            if event.key == pygame.K_SPACE: ##--Firing
                if bulletfired == 0:
                    bulletfired = 1
예제 #15
0
def main():

    # Parse arguments
    if len(sys.argv) != 5:
        print(
            "usage: python3 %s <host> <listening_port> <writing_port> <config> % sys.argv[0]"
        )
        quit(1)
    host = sys.argv[1]
    alice_port = sys.argv[2]
    bob_port = sys.argv[3]
    config = sys.argv[4]

    # Set up encryption configuration
    if config == "noCrypto":
        enc = False
        mac = False
    elif config == "enc":
        enc = True
        mac = False
    elif config == "mac":
        enc = False
        mac = True
    elif config == "EncThenMac":
        enc = True
        mac = True
    else:
        print("invalid configuration " + config +
              " valid configuration options: noCrypto, enc, mac, EncThenMac")
        quit(1)

    # Open a socket to listen to alice
    alice_listenfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    alice_listenfd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Bind socket to ip and port
    alice_listenfd.bind(('', int(alice_port)))

    # Listen to socket
    alice_listenfd.listen(1)

    # Accept connection
    (alice_connfd, addr) = alice_listenfd.accept()
    print("Connected to Alice")

    # Open a socket to broadcast to bob
    bob_clientfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # Connect to server
    bob_clientfd.connect((host, int(bob_port)))
    print("Connected to Bob\n")

    alice_public, bob_public = read_keys()

    stored_msg = None
    stored_tag = None
    # Pass on keys
    if enc or mac:
        recieved_msg = alice_connfd.recv(1024)

        init_message_for_bob = None

        valid_behavior = False
        while not valid_behavior:
            valid_behavior = True

            behavior = input("Would you like to alter the init message? (y/n)")

            if behavior == "y":
                init_message_for_bob = alter_init_message(
                    recieved_msg, enc, mac)
            elif behavior == "n":
                init_message_for_bob = recieved_msg
            else:
                print(
                    "please input 'y' to alter the message or 'n' to send the original message"
                )
                valid_behavior = False
                continue

        bob_clientfd.send(init_message_for_bob)

    # message loop
    while (True):
        recieved_msg = alice_connfd.recv(1024).decode()

        # TODO determine what should be printed here in different cases
        message_number = None
        message = None
        tag = None

        if enc and mac:
            message_number = recieved_msg[:4]
            tag = recieved_msg[4:68]
            message = recieved_msg[68:]

        elif enc:
            message_number = recieved_msg[:4]
            message = recieved_msg[4:]

        elif mac:
            message_number = recieved_msg[:4]
            tag = recieved_msg[4:68]
            message = recieved_msg[68:]

        else:
            message_number = recieved_msg[:4]
            message = recieved_msg[4:]

        if message_number is not None:
            print("Message Number: ",
                  int.from_bytes(message_number.encode(), "big"))
        if message is not None: print("Message: " + message)
        if tag is not None: print("Tag: " + tag + "\n")

        message_behavior = 0
        # What are you doing w the message
        while (message_behavior < 1) or (message_behavior > 5):
            message_behavior = int(
                input(
                    "Would you like to: \n 1: Pass this message to Bob without alteration \n 2: Edit this message \n 3: Delete this message? \n 4: Store this message \n 5: Replay the stored message \n"
                ))

            if message_behavior == 1:  # Send message as is
                print("Passing Message Along\n")
                bob_clientfd.send(recieved_msg.encode())

            elif message_behavior == 2:  # Alter message
                altered_message = alter_message(message, tag, enc, mac)
                bob_clientfd.send(message_number.encode() + altered_message)

            elif message_behavior == 3:  # Drop message
                print("Dropping Message\n")

            elif message_behavior == 4:
                print("Current stored message is: " + str(stored_msg) +
                      "\n would you like to overwrite it with " + message)
                behavior = input("replace stored message? y/n \n")
                if behavior == 'y':
                    stored_msg = message
                    if mac:
                        stored_tag = tag
                    print("new stored message is : " + stored_msg)
                elif behavior == 'n':
                    print("keeping " + stored_msg + "stored \n")
                else:
                    print("please enter y(es) or n(o)")
                message_behavior = 0
                print("what would you like to do with message " + message)

            elif message_behavior == 5:
                if stored_msg == None:
                    print("You have no message stored! Try something else")
                    message_behavior = 0
                else:
                    print("Current stored message is " + str(stored_msg) +
                          "\n would you like to send it to Bob?\n")
                    behavior = input("send stored message? y/n \n")
                    if behavior == 'y':
                        print("replaying")
                        if mac:
                            bob_clientfd.send(message_number.encode() +
                                              stored_tag.encode() +
                                              stored_msg.encode())
                        else:
                            bob_clientfd.send(message_number.encode() +
                                              stored_msg.encode())
            else:  # Bad input
                print("Bad input, please enter a number, 1-5")

    # Close connection
    alice_listenfd.close()
    bob_clientfd.close()