PySide6.QtNetwork.QDtls¶
- class QDtls¶
- This class provides encryption for UDP sockets. - Details- Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - The - QDtlsclass can be used to establish a secure connection with a network peer using User Datagram Protocol (UDP). DTLS connection over essentially connectionless UDP means that two peers first have to successfully complete a TLS handshake by calling- doHandshake(). After the handshake has completed, encrypted datagrams can be sent to the peer using- writeDatagramEncrypted(). Encrypted datagrams coming from the peer can be decrypted by- decryptDatagram().- QDtlsis designed to work with- QUdpSocket. Since- QUdpSocketcan receive datagrams coming from different peers, an application must implement demultiplexing, forwarding datagrams coming from different peers to their corresponding instances of- QDtls. An association between a network peer and its- QDtlsobject can be established using the peer’s address and port number. Before starting a handshake, the application must set the peer’s address and port number using- setPeer().- QDtlsdoes not read datagrams from- QUdpSocket, this is expected to be done by the application, for example, in a slot attached to the QUdpSocket::readyRead() signal. Then, these datagrams must be processed by- QDtls.- Note - QDtlsdoes not take ownership of the- QUdpSocketobject.- Normally, several datagrams are to be received and sent by both peers during the handshake phase. Upon reading datagrams, server and client must pass these datagrams to - doHandshake()until some error is found or- handshakeState()returns- HandshakeComplete:- # A client initiates a handshake: clientSocket = QUdpSocket() clientDtls = QDtls() clientDtls.setPeer(address, port, peerName) clientDtls.doHandshake(clientSocket) # A server accepting an incoming connection; address, port, clientHello are # read by QUdpSocket::readDatagram(): clientHello = QByteArray(serverSocket.pendingDatagramSize(), Qt.Uninitialized) address = QHostAddress() port = {} serverSocket.readDatagram(clientHello.data(), clientHello.size(), address, port) serverDtls = QDtls() serverDtls.setPeer(address, port) serverDtls.doHandshake(serverSocket, clientHello) # Handshake completion, both for server and client: def continueHandshake(self, datagram): if dtls.doHandshake(udpSocket, datagram): # Check handshake status: if dtls.handshakeStatus() == QDlts.HandshakeComplete: # Secure DTLS connection is now established. else: # Error handling. - For a server, the first call to - doHandshake()requires a non-empty datagram containing a ClientHello message. If the server also deploys- QDtlsClientVerifier, the first ClientHello message is expected to be the one verified by- QDtlsClientVerifier.- In case the peer’s identity cannot be validated during the handshake, the application must inspect errors returned by - peerVerificationErrors()and then either ignore errors by calling- ignoreVerificationErrors()or abort the handshake by calling- abortHandshake(). If errors were ignored, the handshake can be resumed by calling- resumeHandshake().- After the handshake has been completed, datagrams can be sent to and received from the network peer securely: - # Sending an encrypted datagram: dtlsConnection.writeDatagramEncrypted(clientSocket, "Hello DTLS server!") # Decryption: encryptedMessage = QByteArray(dgramSize) socket.readDatagram(encryptedMessage.data(), dgramSize) plainText = dtlsConnection.decryptDatagram(socket, encryptedMessage) - A DTLS connection may be closed using - shutdown().- DtlsClient.~DtlsClient() clientDtls.shutdown(clientSocket) - Warning - It’s recommended to call - shutdown()before destroying the client’s- QDtlsobject if you are planning to re-use the same port number to connect to the server later. Otherwise, the server may drop incoming ClientHello messages, see RFC 6347, section 4.2.8 for more details and implementation hints.- If the server does not use - QDtlsClientVerifier, it must configure its- QDtlsobjects to disable the cookie verification procedure:- config = QSslConfiguration.defaultDtlsConfiguration() config.setDtlsCookieVerificationEnabled(False) # Some other customization ... dtlsConnection.setDtlsConfiguration(config) - A server that uses cookie verification with non-default generator parameters must set the same parameters for its - QDtlsobject before starting the handshake.- Note - The DTLS protocol leaves Path Maximum Transmission Unit (PMTU) discovery to the application. The application may provide - QDtlswith the MTU using- setMtuHint(). This hint affects only the handshake phase, since only handshake messages can be fragmented and reassembled by the DTLS. All other messages sent by the application must fit into a single datagram.- Note - DTLS-specific headers add some overhead to application data further reducing the possible message size. - Warning - A server configured to reply with HelloVerifyRequest will drop all fragmented ClientHello messages, never starting a handshake. - The DTLS server and DTLS client examples illustrate how to use - QDtlsin applications.- See also - QUdpSocket- QDtlsClientVerifier- HandshakeState- QDtlsError- QSslConfiguration- Synopsis¶- Methods¶- def - __init__()
- def - abortHandshake()
- def - doHandshake()
- def - dtlsError()
- def - handleTimeout()
- def - handshakeState()
- def - mtuHint()
- def - peerAddress()
- def - peerPort()
- def - sessionCipher()
- def - setMtuHint()
- def - setPeer()
- def - shutdown()
- def - sslMode()
 - Signals¶
- def - pskRequired()
 - Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - class HandshakeState¶
- Describes the current state of DTLS handshake. - This enum describes the current state of DTLS handshake for a - QDtlsconnection.- Constant - Description - QDtls.HandshakeState.HandshakeNotStarted - Nothing done yet. - QDtls.HandshakeState.HandshakeInProgress - Handshake was initiated and no errors were found so far. - QDtls.HandshakeState.PeerVerificationFailed - The identity of the peer can’t be established. - QDtls.HandshakeState.HandshakeComplete - Handshake completed successfully and encrypted connection was established. - See also 
 - Creates a - QDtlsobject,- parentis passed to the QObject constructor.- modeis- SslServerModefor a server-side DTLS connection or- SslClientModefor a client.- abortHandshake(socket)¶
- Parameters:
- socket – - QUdpSocket
- Return type:
- bool 
 
 - Aborts the ongoing handshake. Returns true if one was on-going on - socket; otherwise, sets a suitable error and returns false.- See also - cookieGeneratorParameters()¶
- Return type:
 
 - Returns the current hash algorithm and secret, either default ones or previously set by a call to - setCookieGeneratorParameters().- The default hash algorithm is QCryptographicHash::Sha256 if Qt was configured to support it, QCryptographicHash::Sha1 otherwise. The default secret is obtained from the backend-specific cryptographically strong pseudorandom number generator. - decryptDatagram(socket, dgram)¶
- Parameters:
- socket – - QUdpSocket
- dgram – - QByteArray
 
- Return type:
 
 - Decrypts - dgramand returns its contents as plain text. The handshake must be completed before datagrams can be decrypted. Depending on the type of the TLS message the connection may write into- socket, which must be a valid pointer.- doHandshake(socket[, dgram={}])¶
- Parameters:
- socket – - QUdpSocket
- dgram – - QByteArray
 
- Return type:
- bool 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Starts or continues a DTLS handshake. - socketmust be a valid pointer. When starting a server-side DTLS handshake,- dgrammust contain the initial ClientHello message read from- QUdpSocket. This function returns- trueif no error was found. Handshake state can be tested using- handshakeState().- falsereturn means some error occurred, use- dtlsError()for more detailed information.- Note - If the identity of the peer can’t be established, the error is set to - PeerVerificationError. If you want to ignore verification errors and continue connecting, you must call- ignoreVerificationErrors()and then- resumeHandshake(). If the errors cannot be ignored, you must call- abortHandshake().- if not dtls.doHandshake(socket, dgram): if dtls.dtlsError() == QDtlsError.PeerVerificationError: dtls.abortAfterError(socket) - dtlsConfiguration()¶
- Return type:
 
 - Returns either the default DTLS configuration or the configuration set by an earlier call to - setDtlsConfiguration().- dtlsError()¶
- Return type:
- QDtlsError
 
 - Returns the last error encountered by the connection or - NoError.- See also - dtlsErrorString()- QDtlsError- dtlsErrorString()¶
- Return type:
- str 
 
 - Returns a textual description for the last error encountered by the connection or empty string. - See also - handleTimeout(socket)¶
- Parameters:
- socket – - QUdpSocket
- Return type:
- bool 
 
 - If a timeout occurs during the handshake, the - handshakeTimeout()signal is emitted. The application must call handleTimeout() to retransmit handshake messages; handleTimeout() returns- trueif a timeout has occurred, false otherwise.- socketmust be a valid pointer.- See also - handshakeState()¶
- Return type:
 
 - Returns the current handshake state for this - QDtls.- See also - handshakeTimeout()¶
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Packet loss can result in timeouts during the handshake phase. In this case - QDtlsemits a handshakeTimeout() signal. Call- handleTimeout()to retransmit the handshake messages:- def __init__(self): # Some initialization code here ... clientDtls.handshakeTimeout.connect(self.handleTimeout) def handleTimeout(self): clientDtls.handleTimeout(clientSocket) - See also - ignoreVerificationErrors(errorsToIgnore)¶
- Parameters:
- errorsToIgnore – .list of QSslError 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This method tells - QDtlsto ignore only the errors given in- errorsToIgnore.- If, for instance, you want to connect to a server that uses a self-signed certificate, consider the following snippet: - cert = QSslCertificate.fromPath("server-certificate.pem") error = QSslError(QSslError.SelfSignedCertificate, cert.at(0)) expectedSslErrors = QList() expectedSslErrors.append(error) dtls = QDtls() dtls.ignoreVerificationErrors(expectedSslErrors) dtls.doHandshake(udpSocket) - You can also call this function after - doHandshake()encountered the- PeerVerificationErrorerror, and then resume the handshake by calling- resumeHandshake().- Later calls to this function will replace the list of errors that were passed in previous calls. You can clear the list of errors you want to ignore by calling this function with an empty list. - See also - isConnectionEncrypted()¶
- Return type:
- bool 
 
 - Returns - trueif DTLS handshake completed successfully.- See also - mtuHint()¶
- Return type:
- int 
 
 - Returns the value previously set by - setMtuHint(). The default value is 0.- See also - peerAddress()¶
- Return type:
 
 - Returns the peer’s address, set by - setPeer(), or- Null.- See also - peerPort()¶
- Return type:
- int 
 
 - Returns the peer’s port number, set by - setPeer(), or 0.- See also - Returns errors found while establishing the identity of the peer. - If you want to continue connecting despite the errors that have occurred, you must call - ignoreVerificationErrors().- peerVerificationName()¶
- Return type:
- str 
 
 - Returns the host name set by - setPeer()or- setPeerVerificationName(). The default value is an empty string.- See also - pskRequired(authenticator)¶
- Parameters:
- authenticator – - QSslPreSharedKeyAuthenticator
 
 - QDtlsemits this signal when it negotiates a PSK ciphersuite, and therefore a PSK authentication is then required.- When using PSK, the client must send to the server a valid identity and a valid pre shared key, in order for the TLS handshake to continue. Applications can provide this information in a slot connected to this signal, by filling in the passed - authenticatorobject according to their needs.- Note - Ignoring this signal, or failing to provide the required credentials, will cause the handshake to fail, and therefore the connection to be aborted. - Note - The - authenticatorobject is owned by- QDtlsand must not be deleted by the application.- See also - resumeHandshake(socket)¶
- Parameters:
- socket – - QUdpSocket
- Return type:
- bool 
 
 - If peer verification errors were ignored during the handshake, resumeHandshake() resumes and completes the handshake and returns - true.- socketmust be a valid pointer. Returns- falseif the handshake could not be resumed.- sessionCipher()¶
- Return type:
 
 - Returns the cryptographic - cipherused by this connection, or a null cipher if the connection isn’t encrypted. The cipher for the session is selected during the handshake phase. The cipher is used to encrypt and decrypt data.- QSslConfigurationprovides functions for setting the ordered list of ciphers from which the handshake phase will eventually select the session cipher. This ordered list must be in place before the handshake phase begins.- sessionProtocol()¶
- Return type:
 
 - Returns the DTLS protocol version used by this connection, or UnknownProtocol if the connection isn’t encrypted yet. The protocol for the connection is selected during the handshake phase. - setDtlsConfiguration()can set the preferred version before the handshake starts.- setCookieGeneratorParameters(params)¶
- Parameters:
- params – - GeneratorParameters
- Return type:
- bool 
 
 - Sets the cryptographic hash algorithm and the secret from - params. This function is only needed for a server-side- QDtlsconnection. Returns- trueif successful.- Note - This function must be called before the handshake starts. - setDtlsConfiguration(configuration)¶
- Parameters:
- configuration – - QSslConfiguration
- Return type:
- bool 
 
 - Sets the connection’s TLS configuration from - configurationand returns- trueif successful.- Note - This function must be called before the handshake starts. - See also - setMtuHint(mtuHint)¶
- Parameters:
- mtuHint – int 
 
 - mtuHintis the maximum transmission unit (MTU), either discovered or guessed by the application. The application is not required to set this value.- See also - setPeer(address, port[, verificationName={}])¶
- Parameters:
- address – - QHostAddress
- port – int 
- verificationName – str 
 
- Return type:
- bool 
 
 - Sets the peer’s address, - port, and host name and returns- trueif successful.- addressmust not be null, multicast, or broadcast.- verificationNameis the host name used for the certificate validation.- setPeerVerificationName(name)¶
- Parameters:
- name – str 
- Return type:
- bool 
 
 - Sets the host - namethat will be used for the certificate validation and returns- trueif successful.- Note - This function must be called before the handshake starts. - See also - shutdown(socket)¶
- Parameters:
- socket – - QUdpSocket
- Return type:
- bool 
 
 - Sends an encrypted shutdown alert message and closes the DTLS connection. Handshake state changes to - HandshakeNotStarted.- socketmust be a valid pointer. This function returns- trueon success.- See also - Returns - SslServerModefor a server-side connection and- SslClientModefor a client.- See also - QDtls()- SslMode- writeDatagramEncrypted(socket, dgram)¶
- Parameters:
- socket – - QUdpSocket
- dgram – - QByteArray
 
- Return type:
- int 
 
 - Encrypts - dgramand writes the encrypted data into- socket. Returns the number of bytes written, or -1 in case of error. The handshake must be completed before writing encrypted data.- socketmust be a valid pointer.