def init_socket(self):
        """Initalizes listening socket and SSL Connection"""
        if not hasattr(self, 'socket'):
            self.socket = self.get_listener(self.address, self.backlog,
                                            self.family)
            self.address = self.socket.getsockname()

        self._handle = self.handle
        self._socket = self.socket

        self.scn = SSLConnection(self._socket,
                                 keyfile=self.ssl_args["keyfile"],
                                 certfile=self.ssl_args["certfile"],
                                 ca_certs=self.ssl_args["certfile"],
                                 server_side=True,
                                 do_handshake_on_connect=False)
Exemplo n.º 2
0
def dtls(nssfile_path, certs_path, certs_name):
    sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sck.bind(("0.0.0.0", 4433))
    # Windows
    scn = SSLConnection(sck,
                        keyfile="{}{}.key".format(certs_path, certs_name),
                        certfile="{}{}.pem".format(certs_path, certs_name),
                        server_side=True,
                        ca_certs="{}{}.ca".format(certs_path, certs_name),
                        do_handshake_on_connect=False,
                        cb_user_config_ssl_ctx=ssl_ctx_cb)
    while True:
        peer_address = scn.listen()
        act = scn.accept()
        if act:
            conn = act[0]
            z = threading.Thread(target=readdtls, args=[conn, nssfile_path])
            z.start()
    def __init__(self,
                 address_family=socket.AF_INET,
                 socket_type=socket.SOCK_DGRAM,
                 socket_proto=socket.IPPROTO_UDP,
                 ssl_enabled=False, keyfile=None, certfile=None, cacertfile=None, port=constants.COAP_PORT):
        self.__socket = socket.socket(address_family, socket_type,
                                      socket_proto)

        self.ssl = ssl_enabled
        self._sslobj = None
        if self.ssl:
            ssl_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            if not keyfile or not certfile:
                raise Exception("Missing keyfile or certfile")

            # https://github.com/rbit/pydtls/blob/master/dtls/sslconnection.py
            if not cacertfile:
                cacertfile = certfile

            self._sslobj = SSLConnection(
                ssl_sock,
                keyfile=keyfile,
                certfile=certfile,
                server_side=False,
                cert_reqs=ssl.CERT_REQUIRED,
                ssl_version=2,
                ca_certs=cacertfile,
                # ca_certs = "/opt/OpenMTC/openmtc-python/openmtc-gevent/certs/CA_and_certs/pydtls/ca/ca-cert.pem",
                do_handshake_on_connect=True,
                suppress_ragged_eofs=True,
                ciphers=None
            )
            self.processor = MiniProc(sslobj=self._sslobj)
        else:
            # self.__socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.__socket.bind(('', port))
            # processor.add_socket(self.__socket, self._sslobj)
            self.processor = MiniProc(socket=self.__socket)
Exemplo n.º 4
0
def main():
    sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sck.bind(("127.0.0.1", 28000))
    sck.settimeout(30)
    cert_path = path.join(path.abspath(path.dirname(__file__)), "certs")
    scn = SSLConnection(sck,
                        keyfile=path.join(cert_path, "keycert.pem"),
                        certfile=path.join(cert_path, "keycert.pem"),
                        server_side=True,
                        ca_certs=path.join(cert_path, "ca-cert.pem"),
                        do_handshake_on_connect=False)
    cnt = 0

    while True:
        cnt += 1
        print "Listen invocation: %d" % cnt
        peer_address = scn.listen()
        if peer_address:
            print "Completed listening for peer: %s" % str(peer_address)
            break

    print "Accepting..."
    conn = scn.accept()[0]
    sck.settimeout(5)
    conn.get_socket(True).settimeout(5)

    cnt = 0
    while True:
        cnt += 1
        print "Listen invocation: %d" % cnt
        peer_address = scn.listen()
        assert not peer_address
        print "Handshake invocation: %d" % cnt
        try:
            conn.do_handshake()
        except SSLError as err:
            if err.errno == 504:
                continue
            raise
        print "Completed handshaking with peer"
        break

    cnt = 0
    while True:
        cnt += 1
        print "Listen invocation: %d" % cnt
        peer_address = scn.listen()
        assert not peer_address
        print "Read invocation: %d" % cnt
        try:
            message = conn.read()
        except SSLError as err:
            if err.errno == 502:
                continue
            if err.args[0] == SSL_ERROR_ZERO_RETURN:
                break
            raise
        print message
        conn.write("Back to you: " + message)

    cnt = 0
    while True:
        cnt += 1
        print "Listen invocation: %d" % cnt
        peer_address = scn.listen()
        assert not peer_address
        print "Shutdown invocation: %d" % cnt
        try:
            s = conn.shutdown()
            s.shutdown(socket.SHUT_RDWR)
        except SSLError as err:
            if err.errno == 502:
                continue
            raise
        break
Exemplo n.º 5
0
def main():
    sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sck.bind(("127.0.0.1", 28000))
    sck.settimeout(30)
    cert_path = path.join(path.abspath(path.dirname(__file__)), "certs")
    scn = SSLConnection(
        sck,
        keyfile=path.join(cert_path, "keycert.pem"),
        certfile=path.join(cert_path, "keycert.pem"),
        server_side=True,
        ca_certs=path.join(cert_path, "ca-cert.pem"),
        do_handshake_on_connect=False)
    cnt = 0

    while True:
        cnt += 1
        print "Listen invocation: %d" % cnt
        peer_address = scn.listen()
        if peer_address:
            print "Completed listening for peer: %s" % str(peer_address)
            break

    print "Accepting..."
    conn = scn.accept()[0]
    sck.settimeout(5)
    conn.get_socket(True).settimeout(5)

    cnt = 0
    while True:
        cnt += 1
        print "Listen invocation: %d" % cnt
        peer_address = scn.listen()
        assert not peer_address
        print "Handshake invocation: %d" % cnt
        try:
            conn.do_handshake()
        except SSLError as err:
            if err.errno == 504:
                continue
            raise
        print "Completed handshaking with peer"
        break

    cnt = 0
    while True:
        cnt += 1
        print "Listen invocation: %d" % cnt
        peer_address = scn.listen()
        assert not peer_address
        print "Read invocation: %d" % cnt
        try:
            message = conn.read()
        except SSLError as err:
            if err.errno == 502:
                continue
            if err.args[0] == SSL_ERROR_ZERO_RETURN:
                break
            raise
        print message
        conn.write("Back to you: " + message)

    cnt = 0
    while True:
        cnt += 1
        print "Listen invocation: %d" % cnt
        peer_address = scn.listen()
        assert not peer_address
        print "Shutdown invocation: %d" % cnt
        try:
            s = conn.shutdown()
            s.shutdown(socket.SHUT_RDWR)
        except SSLError as err:
            if err.errno == 502:
                continue
            raise
        break
class DtlsServer(DatagramServer):
    """DtlsServer extends the Gevent DatagramServer with DTLS support"""
    def __init__(self,
                 listener,
                 handle=None,
                 backlog=None,
                 spawn='default',
                 **ssl_args):
        """Initializes the Server

        Calls init_socket()

        :param listener: Tuple (address, port) used by the server
        :param handle: function called when application data is recieved
        :param ssl_args: contains two keywords: "keyfile" and "certfile"
                         containing paths to respective files
        """
        DatagramServer.__init__(self, listener, handle=handle, spawn=spawn)
        self.backlog = backlog
        self.ssl_args = ssl_args

    def init_socket(self):
        """Initalizes listening socket and SSL Connection"""
        if not hasattr(self, 'socket'):
            self.socket = self.get_listener(self.address, self.backlog,
                                            self.family)
            self.address = self.socket.getsockname()

        self._handle = self.handle
        self._socket = self.socket

        self.scn = SSLConnection(self._socket,
                                 keyfile=self.ssl_args["keyfile"],
                                 certfile=self.ssl_args["certfile"],
                                 ca_certs=self.ssl_args["certfile"],
                                 server_side=True,
                                 do_handshake_on_connect=False)

    @classmethod
    def get_listener(cls, address, backlog=None, family=None):
        """Creates a datagram socket used to listen to incoming requests"""
        return _udp_socket(address, reuse_addr=cls.reuse_addr, family=family)

    def sendto(self, buff, remote):
        """Overwrites the DatagramServer sendto in order to send an encrypted
         reply

        :param buff: Byte buffer to be encrypted and sent
        :param remote: Unused parameter, since an SSL connection exists
        """
        self.conn.write(buff)

    def do_handshake(self, remote):
        """Performs the DTLS handshake before recieving data.

        Calls the message handler with tuple(data buffer, tuple(client IP,
        client Port))

        :param remote: tuple(client IP, client Port)
        """
        # TODO: Error handling: send something in case of SSL socket timeout
        # Accepting
        self.conn = self.scn.accept()[0]
        self.conn.get_socket(True).settimeout(5)

        # Handshake
        self.conn.do_handshake()

        # Reading the CoAP message
        message = self.conn.read()

        self._handle(message, remote)

    def do_read(self):
        """Overwrites the DatagramServer do_read in order to perform the DTLS
        handshake before receiving data.

        This function is triggered automatically by the DatagramServer when an
        I/O operation is detected.
        """
        peer_address = self.scn.listen()
        if peer_address:
            # FIXME: need to join these on stop()
            Greenlet.spawn(self.do_handshake, peer_address)