Ejemplo n.º 1
0
    def run(self):
        global taskQueue, stopFlag
        while True:
            if stopFlag:
                print("WorkThread Ended")
                break
            try:
                data, addr, recvTimestamp = taskQueue.get(timeout=1)
                recvPacket = NTPPacket()
                recvPacket.from_data(data)

                # Server mode - 4 and SNTP v4
                sendPacket = NTPPacket(version=4, mode=4)
                # According to rfc4330 most fields == 0
                # it is already set in NTPPacket constructor

                # Timestamp Name          ID   When Generated
                # ------------------------------------------------------------
                # Originate Timestamp     T1   time request sent by client
                # Receive Timestamp       T2   time request received by server
                # Transmit Timestamp      T3   time reply sent by server
                # Destination Timestamp   T4   time reply received by client

                timeStamp_high, timeStamp_low = recvPacket.GetTxTimeStamp()
                sendPacket.SetOriginTimeStamp(timeStamp_high, timeStamp_low)
                # Simulate that we have different time on server
                sendPacket.recv_timestamp = recvTimestamp - self.lie_offset
                sendPacket.tx_timestamp = ntp_packet.system_to_ntp_time(
                    time.time() - self.lie_offset)
                # Dummy info to be a correct sntp packet
                sendPacket.stratum = 2
                sendPacket.ref_timestamp = recvTimestamp - 5
                sendPacket.poll = 10
                # sendPacket.precision = 2
                # sendPacket.root_delay = 1
                # sendPacket.root_dispersion = 1
                # sendPacket.ref_id = 1809582983  # ip 107.220.11.135

                # sendPacket = b"\x24\x02\x03\xee\x00\x00\x00\x37\x00\x00\x05\x0f\x6b\xdc\x0b\x87\xd8\xe7\x2f\xa6\x1a\xb4\xc9\x72\xd8\xe7\x30\x27\x66\x15\xdb\x33\xd8\xe7\x30\x26\x02\xe6\xcb\x21\xd8\xe7\x30\x26\x02\xeb\x94\xac"
                self.m_socket.sendto(sendPacket.to_data(), addr)
                print("Sended to {}:{}".format(addr[0], addr[1]))
            except Empty:
                continue
Ejemplo n.º 2
0
    def _internal_send_packet(server, port, version, packet=None):
        if not packet:
            packet = NTPPacket(transmit=time.time() + NTPClient.FORMAT_DIFF)
        answer = NTPPacket(version_number=version)
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
            s.settimeout(NTPClient.WAITING_TIME)
            s.sendto(packet.pack(), (server, port))
            data = s.recv(48)
            arrive_time = time.time() + NTPClient.FORMAT_DIFF
            answer.unpack(data)

        return answer, arrive_time
Ejemplo n.º 3
0
    def request(self, host, version=4, port='ntp', timeout=5):
        """
        Query a SNTP server.

        :param host: server name/address
        :param version: SNTP version to use
        :param port: server port
        :param timeout: timeout on socket operations
        :returns: NTPStats object
        """
        # lookup server address
        addrinfo = socket.getaddrinfo(host, port)[0]
        sockaddr = addrinfo[4]

        # create the socket
        # print(sockaddr)
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        try:
            s.settimeout(timeout)

            # create the request packet - mode 3 is client
            query_packet = NTPPacket(mode=3, version=version,
                                     tx_timestamp=ntp_packet.system_to_ntp_time(time.time()))

            # send the request
            s.sendto(query_packet.to_data(), sockaddr)

            # wait for the response - check the source address
            src_addr = None,
            while src_addr[0] != sockaddr[0]:
                response_packet, src_addr = s.recvfrom(256)

            # build the destination timestamp
            dest_timestamp = ntp_packet.system_to_ntp_time(time.time())
        except socket.timeout:
            raise NTPException("No response received from %s." % host)
        finally:
            s.close()

        # construct corresponding packet
        sntp_packet = NTPPacket()
        sntp_packet.from_data(response_packet)
        sntp_packet.dest_timestamp = dest_timestamp

        print("Offset: ", (((sntp_packet.recv_timestamp - sntp_packet.orig_timestamp) +
                            (sntp_packet.tx_timestamp - sntp_packet.dest_timestamp)) / 2))
        print("Round trip: ", ((sntp_packet.dest_timestamp - sntp_packet.orig_timestamp) -
                               (sntp_packet.tx_timestamp - sntp_packet.recv_timestamp)))

        return sntp_packet
Ejemplo n.º 4
0
def run_server(delay, port):
    with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
        try:
            sock.bind(("127.0.0.1", port))
        except Exception:
            print("Can not create server (sure port is free)")
            return

        while True:
            data, address = sock.recvfrom(1024)

            print("Connected: ", address)

            try:
                packet = NTPPacket().unpack(data)
            except UnpackError:
                print("Wrong packet format")
                sock.sendto(b"Wrong packet format", address)
                continue

            thread = threading.Thread(target=handle_connection,
                                      args=(packet, sock, address, delay))
            thread.start()
Ejemplo n.º 5
0
def fake_server(address):

    s = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind( (address, 123) )

    drift_start = time.time()
    speed = 0.9996

    while True:
        packet, source = s.recvfrom(100)
        print('Received {length} byte packet from {source}'.format(length=len(packet), source=source[0]))
        packet = NTPPacket.from_bytes(packet)

        if packet.version not in (3, 4):
            print('Unsupported NTP version.')
            continue

        if packet.mode != 3:
            print('Not a client request.')
            continue

        try:
            print('Client time:', packet.transmit_timestamp)
        except:
            pass
        time_since_start = time.time() - drift_start
        return_time = drift_start + time_since_start * speed

        response = NTPPacket()
        response.version = packet.version
        response.mode = 4
        response.stratum = 1
        response.reference_identifier = b'XFAK'
        response.origin_timestamp = packet.transmit_timestamp
        response.reference_timestamp = NTPTimestamp.from_unix_timestamp(return_time)
        response.receive_timestamp = NTPTimestamp.from_unix_timestamp(return_time)
        response.transmit_timestamp = NTPTimestamp.from_unix_timestamp(return_time)

        response = response.to_bytes()
        s.sendto(response, source)