Пример #1
0
def send_and_get_msg(sock: socket, values):
    """
    Function handles communication between client and server and returns it.
    :param sock: socket for comm
    :param values: values to specify city and api_key used in communication
    :return: server response
    """
    ret = None
    try:
        sock.send(
            bytes(
                broadcast_data.format(values.city, values.api_key, host_name),
                "utf-8"))
    except Exception as err:
        print("Failed to send a request. Details:\n",
              err.__repr__(),
              file=sys.stderr)
        exit(1)

    try:
        ret = str(sock.recv(2048), "utf-8")
    except Exception as err:
        print(
            "An exception during receiving a response has occurred. Details: \n",
            err.__repr__(),
            file=sys.stderr)
        exit(1)
    return ret
Пример #2
0
    def receive_state(self,
                      job_id: str,
                      state: CythonBackend,
                      sock: socket,
                      overwrite: bool = False,
                      chunk_size: int = 2048,
                      max_inflight: int = 4):
        syncaccept = SyncAccept()
        syncaccept.job_id = job_id
        syncaccept.chunk_size = chunk_size
        syncaccept.max_inflight = max_inflight
        # Let the other side know we are ready to receive and how to send info.
        sock.send(syncaccept.SerializeToString())

        running = True
        while running:
            syncstate = SyncState.FromString(sock.recv())
            relstart = syncstate.rel_start_index
            data = pbvec_to_vec(syncstate.data)

            # Break abstraction barrier now
            # TODO: unbreak it
            if overwrite:
                state.overwrite_relative_range(relstart, relstart + len(data),
                                               data)
                # state.state[relstart:relstart+len(data)] = data
            else:
                state.addto_relative_range(relstart, relstart + len(data),
                                           data)
                # state.state[relstart:relstart+len(data)] += data

            sock.send(syncaccept.SerializeToString())
            running = not syncstate.done
Пример #3
0
def ascii_str_by_socket(sock: socket):
    """Messages are received through sock and converted into ascii equivalent strings using str_to_ascii_str, and sent back via sock

        Args:
            sock: socket
                The socket connection by which communication with the
                client is implemented (AF_INET, SOCK_STREAM)
        Returns:
            (none)
        Raises:
            (none)
    """
    msg_out: str = ' '
    msg_in: str = ' '

    while True:
        msg_in = sock.recv(DEFAULT_BUFFER_SIZE)

        if (msg_in.decode(UTF_8) == END_OF_FILE):
            break

        print('[S]: Message received from client: \'{}\''.format(
            msg_in.decode(UTF_8)))

        msg_out = str_to_ascii_str(msg_in.decode(UTF_8), '_')
        print('[S]: Message sending to client: \'{}\''.format(msg_out))
        sock.send(msg_out.encode(UTF_8))
Пример #4
0
def client_send(client_socket: socket):
    while True:
        print(
            '1. register topic, 2. remove topic, 3. keep alive, 4. get match list, 5. publish'
        )
        command = input()
        if command == '1':
            type = input('type:')
            name = input('name:')
            period = input('period:')
            msg = f'register_topic {type} {name} {period}'

        elif command == '2':
            name = input('name:')
            msg = f'remove_topic {name}'

        elif command == '3':
            type = input('type:')
            name = input('name:')
            msg = f'keep_alive {type} {name}'

        elif command == '4':
            msg = f'get_match_list'

        elif command == '5':
            name = input('name:')
            filename = 'text'
            value = input('message:')
            filesize = len(value)
            msg = f'publish {name} {filename} {str(filesize)} {value}'

        else:
            print('Wrong command.')

        client_socket.send(msg.encode('utf-8'))
Пример #5
0
 def handle_outgoing_msgs(self, s: socket):
     if self.server_state == E4ServerState.NEW__:
         # request devices list
         print('Getting list of devices...')
         s.send(msg(E4ServerCommand.DEVICE_LIST__))
         self.server_state = E4ServerState.WAITING__
     elif self.server_state == E4ServerState.NO_DEVICES__:
         print('No devices found!')
         exit(1)
     elif self.server_state == E4ServerState.DEVICES_FOUND__:
         # connect to device
         print('Connecting to device...')
         s.send(
             msg("%s %s" %
                 (E4ServerCommand.DEVICE_CONNECT__, self.device_id)))
         self.server_state = E4ServerState.WAITING__
     elif self.server_state == E4ServerState.CONNECTED_TO_DEVICE__:
         # pause streaming initially
         print('Initializing...')
         s.send(msg("%s ON" % E4ServerCommand.PAUSE__))
         self.server_state = E4ServerState.WAITING__
     elif self.server_state == E4ServerState.READY_TO_SUBSCRIBE__:
         # subscribe to streams
         stream = self.stream_ids[self.sub_streams]
         print('Subscribing to stream: %s' % stream)
         s.send(
             msg("%s %s ON" % (E4ServerCommand.DEVICE_SUBSCRIBE__, stream)))
         self.server_state = E4ServerState.WAITING__
     elif self.server_state == E4ServerState.SUBSCRIBE_COMPLETED__:
         # begin streaming data
         print('Requesting data')
         s.send(msg("%s OFF" % E4ServerCommand.PAUSE__))
         self.server_state = E4ServerState.STREAMING__
Пример #6
0
def handle_to(sock: socket, message: str):
    # get the name of the client who this socket belongs to
    global verbose
    fromname = get_name_by_sock(sock)
    if verbose:
        print("\x1B[1;34mFrom:", fromname)

    # Decode the message from <dest> <mesg> and send it to the dest client
    splitmessage = message.split(" ", maxsplit=1)
    print("Splitmessage:", splitmessage)
    toname = splitmessage[0]
    if (users.get(toname) != None):
        destsock = users.get(toname)[1]
    else:
        edne = "EDNE " + toname + "\r\n\r\n"
        sock.send(edne.encode())
        return 0

    # read the whole mesage and write to the dest
    frommsg = "FROM " + fromname + " " + splitmessage[1]
    while "\r\n\r\n" not in frommsg:
        frommsg = frommsg + (sock.recv(32)).decode("utf-8")
    if verbose:
        print("\x1B[1;34m" + frommsg)
    destsock.send(frommsg.encode())
    return 0
def handle_reply(current_socket: socket, request: str) -> dict:
    """
    Отправляет сообщение на сервер, получает и обрабатывает ответ
    :param current_socket: сокет для общения с сервером
    :param request: сформированный запрос на сервер
    :return: ответ о проверке лабораторной работы
    """
    logger.info("Sending request on server to check the lab...")
    logger.debug("The request is: {request}".format(request=request))
    current_socket.send(request.encode())
    try:
        reply_data: dict = json.loads(current_socket.recv(1024).decode())
        logger.info("Got a reply from server!")
        message_type: int = reply_data.pop('messageType')
        if message_type == MessageType.WRONG_REQUEST.value:
            raise SystemError(
                "We've got problems: an error \n {error} \n occurred with a key '{key}'"
                .format(error=reply_data['text'], key=reply_data['key']))
        elif message_type == MessageType.SERVER_ERROR.value:
            raise SystemError("Server has got a problem: {error}".format(
                error=reply_data['errorMessage']))
        elif message_type == MessageType.DEFAULT_ANSWER.value:
            logger.debug("The lab was successfully checked, moving on..")
            return reply_data
    except TypeError as err:
        raise TypeError(
            "Error reading data from server: {error} \n with traceback {tb}".
            format(error=err, tb=traceback.format_exc()))
def send_file(filename: str, conn: socket) -> None:
    f = open(filename, 'rb')
    l = f.read(1024)
    while(l):
        conn.send(l)
        l = f.read(1024)
    f.close()
Пример #9
0
def send_int(sock: socket, value: int) -> bool:
    message = value.to_bytes(4, byteorder='big')
    message_length = len(message)
    to_send = message_length.to_bytes(4, byteorder='big')

    len_sent = 0
    while len_sent < len(to_send):
        try:
            sent = sock.send(to_send[len_sent:])
        except BrokenPipeError:
            print("Connection has been closed.")
            return False
        if sent == 0:
            print("Connection has been closed.")
            return False
        len_sent += sent

    len_sent = 0
    while len_sent < message_length:
        try:
            sent = sock.send(message[len_sent:])
        except BrokenPipeError:
            print("Connection has been closed.")
            return False
        if sent == 0:
            print("Connection has been closed.")
            return False
        len_sent += sent
Пример #10
0
def send_message(sock: socket, message: str) -> bool:
    send_string = message.encode('utf-8')
    message_length = len(send_string)
    to_send = message_length.to_bytes(4, byteorder='big')

    len_sent = 0
    while len_sent < len(to_send):
        try:
            sent = sock.send(to_send[len_sent:])
        except BrokenPipeError:
            print("Connection has been closed.")
            return False
        if sent == 0:
            print("Connection has been closed.")
            return False
        len_sent += sent

    len_sent = 0
    while len_sent < message_length:
        try:
            sent = sock.send(send_string[len_sent:])
        except BrokenPipeError:
            print("Connection has been closed.")
            return False
        if sent == 0:
            print("Connection has been closed.")
            return False
        len_sent += sent
Пример #11
0
def dictionaryattack(connection: socket) -> None:
    """
    Perform a dictionary attack, reading each line from a list of passwords and then mixes the letters,
    both lowercase and uppercase, for realistic matters, using a generator.\n
    When a password gives the correct response from the servers, it then prints a json string
    with the correct user and password.

    :param connection: Current connection
    :return: None
    """
    with open(
            'C:/Users/intel/PycharmProjects/Password Hacker/Password Hacker/task/hacking/passwords.txt',
            'r') as f:
        user = getuser(connection)
        for raw_pwd in f:
            clean_pwd = raw_pwd.strip()
            mixed_letters = map(
                lambda x: ''.join(x),
                product(*([letter.lower(), letter.upper()]
                          for letter in clean_pwd)))
            for attempt in mixed_letters:
                data = {"login": user, "password": attempt}
                encoder = json.dumps(data)
                start = datetime.now()
                connection.send(encoder.encode())
                if checkresponse(connection, start) == 200:
                    raise TypeError(json.dumps(data))
Пример #12
0
def charloop(user: str,
             charset: list,
             connection: socket,
             charprevious='') -> str:
    """
    Uses time vulnerability.\n
    Will loop through a set of characters until the server takes too long to respond.\n
    (Meaning a character of the password was found.)\n
    Uses recursion to append the characters until the server returns a successful connection.

    :param user: The already found username
    :param charset: Set of characters
    :param connection: Current connection
    :param charprevious: (For recursion purposes) Previous character found
    :return: String with full password if any is found
    """
    for char in charset:
        attempt = charprevious + char
        data = {"login": user, "password": attempt}
        encoder = json.dumps(data)
        start = datetime.now()
        connection.send(encoder.encode())
        status = checkresponse(connection, start)
        if status == 200:
            return attempt
        elif status == 500:
            return charloop(user, charset, connection, charprevious=attempt)
Пример #13
0
def crack_user(sock: socket) -> str:
    # Define a list of common admin usernames.
    common_usernames = [
        'admin', 'Admin', 'admin1', 'admin2', 'admin3', 'user1', 'user2',
        'root', 'default', 'new_user', 'some_user', 'new_admin',
        'administrator', 'Administrator', 'superuser', 'super', 'su', 'alex',
        'suser', 'rootuser', 'adminadmin', 'useruser', 'superadmin',
        'username', 'username'
    ]

    # Attempt to login via the specified socket with each of the common admin usernames.
    for usr in common_usernames:
        # Create a dictionary of the current credentials being tested.
        credentials = {"login": usr, "password": "******"}

        # Create a JSON string from the credentials, encode it and send it to the specified socket.
        sock.send(dumps(credentials).encode())

        # Decode the site's response, load a dictionary from that JSON string and retrieve the value paired with the
        # 'result' key.
        result = loads(sock.recv(1024).decode())['result']

        # If the result is 'Wrong password!', the correct username was found.
        if result == 'Wrong password!':
            return usr

    # If none of the common admin usernames are the correct one, raise an exception.
    raise AssertionError('Unable to determine admin username.')
Пример #14
0
def ascii_list_by_socket(sock: socket, lines: [str]) -> [str]:
    """Sends str from lines: [str] through client socket connection sock: socket and returns a new [str] with equivalent ascii-formatted strings
    from lines, generated by a server program

        Args:
            sock: socket
                The client socket connection by which communication with the
                server is implemented (AF_INET, SOCK_STREAM)

            lines: [str]
                str elements parsed from an input file, using function file_to_list, that will be sent to a server via sock
        Returns:
            A [str] with ascii-formatted strings equivalent to the elements from within lines: [str]
        Raises:
            (none)

    """
    msg_out: str = ' '
    msg_in: str = ' '

    output: [str] = []

    for element in lines:
        msg_out = element

        print('[C]: Message sending to server: \'{}\''.format(msg_out))
        sock.send(msg_out.encode(UTF_8))

        msg_in = sock.recv(DEFAULT_BUFFER_SIZE)
        print('[C]: Message received from server: \'{}\''.format(
            msg_in.decode('utf-8')))

        output.append(msg_in.decode(UTF_8))

    return output
Пример #15
0
def send_recv(sock: socket, command: bytes):
    try:
        sock.send(command)
        data = sock.recv(1024)
    except Exception as e:
        return b"Connection error " + str(e).encode()
    return data
Пример #16
0
def deal_client(newSocket: socket, addr):
    global queue_
    status = False
    while True:
        sleep(1)
        try:
            if status and not queue_.empty():
                submissionId_proId = queue_.get()
                print(submissionId_proId)
                newSocket.send(("judge|%s" % submissionId_proId).encode())
                data = newSocket.recv(1024)
                recv_data = data.decode()
                if recv_data == 'gotten':
                    status = False
                else:
                    queue_.put(submissionId_proId)
            else:
                newSocket.send('get_status'.encode())
                data = newSocket.recv(1024)
                recv_data = data.decode()
                if recv_data == "ok":
                    status = True
                print(addr, status)
        except socket.error:
            newSocket.close()
        except Exception as e_:
            newSocket.close()
            print(e_)
Пример #17
0
    def send_state(self, job_id: str, state: StateType, sock: socket):
        syncaccept = SyncAccept.FromString(sock.recv())
        if syncaccept.job_id != job_id:
            raise Exception("Job ids do not match: {}/{}".format(
                job_id, syncaccept.job_id))
        inflight = 0

        last_index = 0
        total_size = state.get_state_size()
        while last_index < total_size:
            while inflight < syncaccept.max_inflight and last_index < total_size:
                end_index = last_index + min(total_size - last_index,
                                             syncaccept.chunk_size)

                syncstate = SyncState()
                syncstate.job_id = job_id
                syncstate.rel_start_index = last_index
                vec_to_pbvec(state.get_relative_range(last_index, end_index),
                             pbvec=syncstate.data)

                inflight += 1
                last_index = end_index

                syncstate.done = last_index == total_size
                sock.send(syncstate.SerializeToString())

            # Overwrite syncaccept to allow live changes to inflight and chunk_size.
            syncaccept = SyncAccept.FromString(sock.recv())
            inflight -= 1
            if syncaccept.job_id != job_id:
                raise Exception("Job ids do not match: {}/{}".format(
                    job_id, syncaccept.job_id))
Пример #18
0
def client_thread(conn: socket, addr):
    question = json.dumps({
        'hour': time.localtime().tm_hour + 3,
        'minute': time.localtime().tm_min,
        'nick': 'server',
        'message': 'What\'s your name?'
    })
    conn.send(bytes(question, encoding='utf8'))
    username = conn.recv(1024).decode("utf-8")

    if len(username) == 0 or username[0:14] != token:
        remove(curr_connection=conn)
        conn.close()

    greeting_message = "Welcome to the club " + username[14:]
    greeting = json.dumps({
        'hour': time.localtime().tm_hour + 3,
        'minute': time.localtime().tm_min,
        'nick': 'server',
        'message': greeting_message
    })
    try:
        conn.send(bytes(greeting, encoding='utf8'))
    except Exception as e:
        print("User not auth")
        conn.close()
        remove(conn)

    broadcast_meeting(username=username[14:], connection=conn)
    try:
        while True:
            message = conn.recv(1024).decode("utf-8")
            auth(message=message)
            if len(message) > 0:
                message_to_send = json.dumps({
                    'hour':
                    time.localtime().tm_hour - 3,
                    'minute':
                    time.localtime().tm_min,
                    'nick':
                    username[14:],
                    'message':
                    message[14:]
                })
                print("cool")
                broadcast(message_to_send, conn)

            else:
                conn.close()
                remove(conn)
    except ConnectionResetError:
        print("Connection lost")
        conn.close()
        remove(conn)

    except Exception as e:
        print(str(e))
        conn.close()
        remove(conn)
Пример #19
0
def send_greeting(app: str, sock: socket):
    """
    Send greeting message for initial connection

    :app: Which application is sending the data
    :sock: Socket to send greeting on
    """
    sock.send(bytes("-- CONNECTION ESTABLISHED --", "utf-8"))
Пример #20
0
def SavePublicKey(key, csocket: socket):
    csocket.send(server_services['SaveKey'])
    csocket.send(bytes(key, 'utf-8'))
    response = csocket.recv(1024)
    if response == b'OK':
        return True
    else:
        return False
Пример #21
0
def receive_server_response(s: socket, response: HttpRequestInfo) -> list:
    s.send(response.to_byte_array(response.to_http_string()))
    received_data = s.recv(Constants.MAX_RECEIVE)
    server_response = []
    while len(received_data) > 0:
        server_response.append(received_data)
        received_data = s.recv(Constants.MAX_RECEIVE)
    s.close()
    return server_response
Пример #22
0
def write_event(s: socket):
    """写事件处理流程"""
    try:
        # 非阻塞获取该套接字上的任务
        next_msg = message[s].get_nowait()
    except queue.Empty:
        outputs.remove(s)  # 如果该套接字上任务全完成 移出该套接字
    else:
        s.send(next_msg)  # 发送消息
Пример #23
0
 def __tunnelling(self, src: socket, dst: socket):
     try:
         data = src.recv(16384)
         if data:
             dst.send(data)
         else:
             raise NameError("ConnectionClosed")
     except BlockingIOError:
         return
Пример #24
0
def RegisterListener(csocket: socket, port):
    csocket.send(server_services['RegisterListener'])
    resp = csocket.recv(1024)
    if resp == server_services['RegisterListener']:
        csocket.send(bytes(str(port), 'utf-8'))
        response = csocket.recv(1024)
        if response == b'OK':
            return True
        else:
            return False
Пример #25
0
 def _handle_request(self, client: socket, address):
     try:
         data = self._retrieve_request_data(client)
         request = HttpRequest(data)
         response = HttpResponse(request)
         Dispatcher.dispatch(response)
         client.send(response.render())
         client.close()
     except:
         sys.exit()
Пример #26
0
def send_to_client(client_socket: socket, data=str):
    try:
        client_socket.send(bytes.fromhex(data))
        sleep(0.5)
    except ConnectionAbortedError as ce:
        traceback.print_exc()
        print(ce)
    except ConnectionResetError as cr:
        traceback.print_exc()
        print(cr)
Пример #27
0
 def delete(self, sock: socket, port: int):
     """
     """
     delete_cmd = "{vertex}, DELETE, {port}, {ip}".format(
         vertex=self.vertex_id, port=port, ip="0.0.0.0")
     self.logging.debug(
         "Sending DELETE command to controller: [{}]".format(delete_cmd))
     sock.send(bytes(delete_cmd, "utf-8"))
     data = self.recv_data(sock)
     self.parse_fwd_table(data)
Пример #28
0
def send_data_pickle(conn: socket, data: tuple):
    """
    Send data turned into pickle to conn
    :param conn: socket
    :param data: data to send (MessageType Enum, DATA)
    :return: None
    """
    data_pickle = pickle.dumps(data)
    conn.send(make_header(data_pickle))
    conn.sendall(data_pickle)
def get_login(client_socket: socket):
    logins = set()
    with open("C:\\logins.txt", "r") as f:
        for line in f:
            logins.add(line.strip())
    for login in logins:
        request = json.dumps({"login": login, "password": "******"}).encode()
        client_socket.send(request)
        response = client_socket.recv(1024).decode()
        if response == json.dumps({"result": "Wrong password!"}):
            return login
Пример #30
0
    def exit(self, sock: socket):
        """
        Closes a clients connection safely

        :sock: Socket of the connection to close on
        """
        self.logging.debug("Closing sockets and preparing to exit")
        print("\nClosing connections")
        sock.send(bytes("{}, EXIT, 0, 0.0.0.0".format(self.vertex_id),
                        "utf-8"))
        sock.close()
def AI(s: socket, command: str, column_number: int) -> None:
    '''receive actions from server'''
    if command == 'A':
        s.send(str('DROP ' + str(column_number) + '\r\n').encode(encoding = 'utf-8'))
        c = s.recv(4096).decode(encoding = 'utf-8')
        reply_A = s.recv(4096).decode(encoding = 'utf-8')
        return reply_A
    elif command == 'B':
        s.send(str('POP ' + str(column_number) + '\r\n').encode(encoding = 'utf-8'))
        c = s.recv(4096).decode(encoding = 'utf-8')
        reply_B = s.recv(4096).decode(encoding = 'utf-8')
        return reply_B
Пример #32
0
def handleClient(clientSocket:socket):
    received = clientSocket.recv(1024)
    print('Received data', received)
    clientSocket.send('hello')
    clientSocket.close()