Esempio n. 1
0
    def test_fail_with_handshake_on_connect(self):
        """
        Test an invalid CoAP sequence with DTLS encryption. The handshake is triggered from the client
        during the connect call.
        """
        _logger.info("Called test_fail_with_handshake_on_connect ...")

        exchange = self._create_test_sequence(bValidResponse=False)

        # Set up a client side DTLS socket
        _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _sock = wrap_client(_sock,
                            cert_reqs=ssl.CERT_REQUIRED,
                            ca_certs=self.pem['CA_CERT_WRONG'],
                            ciphers="RSA",
                            do_handshake_on_connect=True)

        # Connect the CoAP client to the newly created socket
        client = HelperClient(self.server_address,
                              sock=_sock,
                              cb_ignore_read_exception=self._cb_ignore_read_exception,
                              cb_ignore_write_exception=self._cb_ignore_write_exception)

        # Do the communication
        try:
            self._test_with_client(client, exchange)
        except:
            raise
        # Stop the client (also closes the socket)
        finally:
            client.stop()
Esempio n. 2
0
    def test_fail_with_handshake_on_connect(self):
        """
        Test an invalid CoAP sequence with DTLS encryption. The handshake is triggered from the client
        during the connect call.
        """
        _logger.info("Called test_fail_with_handshake_on_connect ...")

        exchange = self._create_test_sequence(bValidResponse=False)

        # Set up a client side DTLS socket
        _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        _sock = wrap_client(_sock,
                            cert_reqs=ssl.CERT_REQUIRED,
                            ca_certs=self.pem['CA_CERT_WRONG'],
                            ciphers="RSA",
                            do_handshake_on_connect=True)

        # Connect the CoAP client to the newly created socket
        client = HelperClient(self.server_address,
                              sock=_sock,
                              cb_ignore_read_exception=self._cb_ignore_read_exception,
                              cb_ignore_write_exception=self._cb_ignore_write_exception)

        # Do the communication
        try:
            self._test_with_client(client, exchange)
        except:
            raise
        # Stop the client (also closes the socket)
        finally:
            client.stop()
Esempio n. 3
0
    def goConnect(self):
        self.setState(ConnectionState.CONNECTING)

        duration = self.account.keepAlive

        if self.timers is not None:
            self.timers.stopAllTimers()

        option = self.parserOption.encode(CoapOptionType.NODE_ID, self.account.clientID)
        options = []
        options.append(option)
        message = CoapMessage(self.Version, CoapType.CONFIRMABLE, CoapCode.PUT, 0, None, options, None)

        if self.account.isSecure:

            self.loop = asyncio.new_event_loop()

            addr = (self.account.serverHost, self.account.port)
            sock = socket(AF_INET, SOCK_DGRAM)
            sock.settimeout(5)
            sock.setblocking(1)
            if self.account.certificate and len(self.account.certificate) > 0:
                fp = self.get_certificate_file(self.account.certificate, self.account.certPasw)
                self.sock_wrapped = wrapper.wrap_client(sock, keyfile=fp.name, certfile=fp.name, ca_certs=fp.name)
            else:
                self.sock_wrapped = wrapper.wrap_client(sock)

            self.sock_wrapped.connect(addr)

            datagram_endpoint = self.loop.create_datagram_endpoint(lambda: pyDTLSClient(self.account.serverHost, self.account.port, self.account.certificate, self, self.loop), sock=self.sock_wrapped)

            self.transport, protocol = self.loop.run_until_complete(datagram_endpoint)
            self.udpClient = protocol
            self.setState(ConnectionState.CONNECTION_ESTABLISHED)

            self.udpThread = Thread(target=self.init_loop)
            self.udpThread.daemon = True
            self.udpThread.start()
        else:
            self.udpClient = UDPClient(self.account.serverHost, self.account.port, self)
            self.udp_listener = reactor.listenUDP(0, self.udpClient)

        self.timers.goConnectTimer(message)
Esempio n. 4
0
    logger.debug(response)


def cb_request(response):
    logger.debug("dentro callback request")
    logger.debug(response)


try:
    # Set up a client side DTLS socket
    _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    do_patch()
    _sock = wrap_client(_sock,
                        cert_reqs=ssl.CERT_REQUIRED,
                        ca_certs=caminho_server_cert,
                        ciphers="ECDHE+AESGCM",
                        do_handshake_on_connect=False,
                        user_mtu=1200)

    logger.debug(_sock)

    # Connect the CoAP client to the newly created socket
    server = ("127.17.0.1", 5683)
    client = HelperClient(server, sock=_sock)
    logger.debug(client)
    # Do the communication

    #todo: iniciar conexao com ssl
    logger.debug("enviando: TESTE")
    #received_message = client.send_request("teste",cb_request, 10)
    client.put("basic/", "aleatorio_", cb_put, 10)
Esempio n. 5
0
def main():
    global client
    op = None
    payload_path = None
    payload = None
    proxy_uri = None
    try:
        opts, args = getopt.getopt(sys.argv[1:], "ho:p:P:f:", [
            "help", "operation=", "path=", "payload=", "payload_file=",
            "proxy-uri-header="
        ])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ("-o", "--operation"):
            op = a
        elif o in ("-p", "--path"):
            payload_path = a
        elif o in ("-P", "--payload"):
            payload = a
        elif o in ("-f", "--payload-file"):
            with open(a, 'r') as f:
                payload = f.read()
        elif o in ("-u", "--proxy-uri-header"):
            proxy_uri = a
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        else:
            usage()
            sys.exit(2)

    if op is None:
        print "Operation must be specified"
        usage()
        sys.exit(2)

    if payload_path is None:
        print "Path must be specified"
        usage()
        sys.exit(2)

    if not payload_path.startswith("coap://"):
        print "Path must be conform to coap://host[:port]/path"
        usage()
        sys.exit(2)

#if proxy_uri and not proxy_uri.startswith("http://") and not proxy_uri.startswith("https://"):
#    print("Proxy-Uri header must be conform to http[s]://host[:port]/path")
#   usage()
#  sys.exit(2)

    host, port, payload_path = parse_uri(payload_path)
    try:
        tmp = socket.gethostbyname(host)
        host = tmp
    except socket.gaierror:
        pass

    # Setup client side DTLS socket
    _sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    _sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    _sock = wrap_client(
        _sock,
        cert_reqs=ssl.CERT_REQUIRED,
        keyfile=path.join(cert_path, "keycert.pem"),
        certfile=path.join(cert_path, "keycert.pem"),
        ca_certs=path.join(cert_path, "ca-cert.pem"),
        ciphers="RSA",
    )

    client = HelperClient(server=(host, port), sock=_sock)
    if op == "GET":
        if payload_path is None:
            print "Path cannot be empty for a GET request"
            usage()
            sys.exit(2)
        response = client.get(payload_path)
        print response.pretty_print()
        client.stop()
    elif op == "OBSERVE":
        if payload_path is None:
            print "Path cannot be empty for a GET request"
            usage()
            sys.exit(2)
        client.observe(payload_path, client_callback_observe)

    elif op == "DELETE":
        if path is None:
            print "Path cannot be empty for a DELETE request"
            usage()
            sys.exit(2)
        response = client.delete(payload_path)
        print response.pretty_print()
        client.stop()
    elif op == "POST":
        if payload_path is None:
            print "Path cannot be empty for a POST request"
            usage()
            sys.exit(2)
        if payload is None:
            print "Payload cannot be empty for a POST request"
            usage()
            sys.exit(2)
        response = client.post(payload_path, payload)
        print response.pretty_print()
        client.stop()
    elif op == "PUT":
        if payload_path is None:
            print "Path cannot be empty for a PUT request"
            usage()
            sys.exit(2)
        if payload is None:
            print "Payload cannot be empty for a PUT request"
            usage()
            sys.exit(2)
        response = client.put(payload_path, payload)
        print response.pretty_print()
        client.stop()
    elif op == "DISCOVER":
        response = client.discover()
        print response.pretty_print()
        client.stop()
    else:
        print "Operation not recognized"
        usage()
        sys.exit(2)