带有 QSslSocket 的 Qt 连接不正确

标签 qt ssl qsslsocket

我有一个使用QTcpSocket 的客户端-服务器应用程序。现在我想改用加密的 SSL 连接,因此我尝试切换到 QSslSocket。但是我无法与服务器建立连接。 这是客户端的代码:

ConnectionHandler::ConnectionHandler(QString ip, int port, QObject *parent) : QObject(parent) {
//    connect(this->socket, SIGNAL(connected()), this, SLOT(connected()));
    connect(this->socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    connect(this->socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    connect(this->socket, SIGNAL(encrypted()), this, SLOT(encryptedReady()));
    connect(this->socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(SSLerrorOccured(const QList<QSslError> &)));
    connect(this->socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
    connect(this->socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));

    this->ip = ip;
    this->port = port;
}


void ConnectionHandler::socketStateChanged(QAbstractSocket::SocketState state) {
    qDebug() << state;
}


void ConnectionHandler::socketError(QAbstractSocket::SocketError) {
    qDebug() << this->socket->errorString();
}


void ConnectionHandler::encryptedReady() {
    qDebug() << "READY";

}


void ConnectionHandler::SSLerrorOccured(const QList<QSslError> &) {
    qDebug() << "EEROR";
}


void ConnectionHandler::connectToServer() {
//    this->socket->connectToHost(this->ip, this->port);
    this->socket->connectToHostEncrypted(this->ip, this->port);

    if (!this->socket->waitForConnected(5000)) {
    this->socket->close();
    this->errorMsg = this->socket->errorString();
    }
}


void ConnectionHandler::connected() {
qDebug() << "connected";
    this->connectedHostAddress = this->socket->peerAddress().toString();
    this->connectionEstablished = true;
    this->localIP = this->socket->localAddress().toString();
    this->localPort = this->socket->localPort();
} 

这里是服务器端的:

 ClientHandler::ClientHandler() {
    this->socket->setProtocol(QSsl::SslV3);
    this->socket->setSocketOption(QAbstractSocket::KeepAliveOption, true);
}

void ClientHandler::run() {
    if (!this->fd)
    return;

    connect(this->socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
    connect(this->socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::DirectConnection);
    connect(this->socket, SIGNAL(encrypted()), this, SLOT(encryptedReady()));
    connect(this->socket, SIGNAL(sslErrors(const QList<QSslError> &)), this, SLOT(sslErrorOccured(const QList<QSslError> &)));
    connect(this->socket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(socketError(QAbstractSocket::SocketError)));
    connect(this->socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));

    if (!this->socket->setSocketDescriptor(this->fd)) {
    emit error(socket->error());
    return;
    } else {
    connect(this->socket, SIGNAL(encrypted()), this, SLOT(ready()));
    this->socket->startServerEncryption();
    }

    this->peerIP = socket->peerAddress().toString();
    QString tmp;
    tmp.append(QString("%1").arg(socket->peerPort()));
    this->peerPort = tmp;

    QHostInfo::lookupHost(this->peerIP, this, SLOT(lookedUp(QHostInfo)));
}


void ClientHandler::socketStateChanged(QAbstractSocket::SocketState state) {
    qDebug() << state;
}


void ClientHandler::socketError(QAbstractSocket::SocketError) {
    qDebug() << this->socket->errorString();
}


void ClientHandler::setFileDescriptor(int fd) {
    this->fd = fd;
}

void ClientHandler::ready() {
    qDebug() << "READY";
}

void ClientHandler::sslErrorOccured(const QList<QSslError> &) {
    qDebug() << "EEROR";
}


void ClientHandler::encryptedReady() {
    qDebug() << "READY";

}

我收到的客户端输出是:

  QAbstractSocket::HostLookupState
  QAbstractSocket::ConnectingState
  QAbstractSocket::ConnectedState
  "The remote host closed the connection"
  QAbstractSocket::ClosingState
  QAbstractSocket::UnconnectedState

对于服务器:

  QAbstractSocket::ConnectedState
  "Error during SSL handshake: error:1408A0C1:SSL routines:SSL3_GET_CLIENT_HELLO:no shared cipher"
  QAbstractSocket::UnconnectedState

有人知道如何解决这个问题吗?

最佳答案

我假设使用非加密套接字一切都很好。因此,让我们只关注使用 QSslSocket 进行详细说明的特殊性。如果需要,我可以分享更大的部分或工作代码。还有一个关于 SSL 证书的大故事,我将在这里简要介绍一下。

首先让我们在一些外部 HTTP SSL 服务器上检查您的客户端,例如:

socket->connectToHostEncrypted("gmail.com", 443);

它应该可以立即使用默认的 SSL 协议(protocol)(没有任何 setProtocol())。在 encrypted() 信号上,您可以编写 HTTP GET header ,在 readyRead() 上,将收到回复。

现在尝试为 "gmail.com" 设置 socket->setProtocol(QSsl::SslV3);。预期结果:

sslErrorOccured: ("The host name did not match any of the valid hosts for this certificate")

请注意,它不是 error() 信号,而是 sslErrors() 信号,用于通知客户端可以忽略的证书问题。

因此,为简单起见,让我们使用默认的 SSL 协议(protocol),而不使用 setProtocol()

由于客户端处于工作状态,我们可以转到服务器。您在第一级 SSL 认证挑战中被打扰了。要通过服务器开始初始化 SSL 连接,您必须至少提供私有(private)加密 key 和公共(public)证书。那是你的错误:

"Error during SSL handshake: error:1408A0C1:SSL routines:SSL3_GET_CLIENT_HELLO:no shared cipher"

在完美的情况下,您的证书应该由认证机构公司签署。在这种情况下,任何拥有此类根证书列表的客户端都能够检查您的证书是否有效。然而,该服务是有偿的,可能需要几周时间。我们可以从自签名证书开始。

您可以找到各种生成证书的方法,例如:"How to create a self-signed SSL Certificate which can be used for testing purposes or internal usage"

简短摘录:

#Step 1: Generate a Private Key
openssl genrsa -des3 -out server.key 1024

#Step 2: Generate a CSR (Certificate Signing Request)
#Common Name (eg, your name or your server's hostname) []:example.com
openssl req -new -key server.key -out server.csr

#Step 3: Remove Passphrase from Key
cp server.key server.key.org
openssl rsa -in server.key.org -out server.key

#Step 4: Generating a Self-Signed Certificate
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

现在有server.keyserver.crt 文件。服务器应在 startServerEncryption() 之前将这些文件传递给 QSslSocket:

    socket->setPrivateKey("c:/test/ssl/cert/server.key", QSsl::Rsa);
    socket->setLocalCertificate("c:/test/ssl/cert/server.crt");

现在服务器可以开始SSL连接了。你可以用浏览器测试一下。通常浏览器会发出连接不可信的警报。那是因为证书是自签名的,它不能防止“中间人”攻击。但是,您可以要求浏览器继续该连接。因此,在服务器端,您将在信号 readyRead() 上拥有 HTTP GET header 。

尝试将 Qt 客户端连接到该服务器。现在错误是由客户端引发的:

sslErrorOccured: ("The certificate is self-signed, and untrusted")

服务器在 error() 中说:“远程主机关闭了连接”。客户端引发了 SSL 证书错误,但与浏览器一样,我们可以继续该连接。放socket->ignoreSslErrors()sslErrors() 信号处理程序中:

void Client::sslErrorOccured(const QList<QSslError> & error) {
    qDebug() << "sslErrorOccured:" << error;
    socket->ignoreSslErrors(error);
}

就是这样。当然,您的客户端不应该接受来自所有服务器的所有 SSL 证书错误,因为此类错误意味着连接并不真正安全并且可能被黑客入侵。它仅用于测试。 QSslError 对象包含证书数据,因此您的客户端可能只接受来自服务器的一个特定的自签名证书,而忽略所有其他此类错误。 也可以创建您自己的“权威根证书”,您可以手动将其写入系统。然后该证书可用于签署您的服务器证书。您的客户端会认为这是可信连接,因为它将能够通过系统根证书对其进行验证。

请注意,OpenSSL 库也可能存在一些问题。在 Linux 或 OS X 上,OpenSSL 处于默认设置,但对于 Windows,应手动安装。 Windows 系统 PATH 中可能已经存在一些 OpenSSL 编译,例如 CMake 有一些有限的 OpenSSL 库。但是,一般来说,对于 Windows,您应该将 OpenSSL 与您的应用程序一起部署。

关于带有 QSslSocket 的 Qt 连接不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33198360/

相关文章:

qt - Google OAuth 2.0 使用 Qt 安装应用程序。 "Missing required parameter: code"

security - 关于数字证书的介绍性文本

java - Tomcat 中的 SSL 支持 : Redirect Issue

c++ - QTcpSocket 或 QSslSocket 是否自动创建读/写线程?

qt - 在 Component.onCompleted 之前初始化 QML 信号

c++ - 使用 QTcpSocket 发送字节

c++ - Qt SSl 错误 (QSslSocket : cannot resolve TLSv1_1_client_method)

c++ - QSslSocket::startServerEncryption 失败,返回 "PEM_READ_BIO_PRIVATEKEY:bad password read"

c++ - 为 Visual Studio 2012 编译 Qt 4.8.x

windows - 添加客户端证书后,在使用 Python 和 Postman 的 Windows 上为 "unable to get local issuer certificate"