3 #include "../vnc/vncserver.h"
4 #include "../../shared/util.h"
5 #include "../../shared/settings.h"
6 #include "../util/platform/blankscreen.h"
7 #include "../clientapp/clientapp.h"
10 #include <QGuiApplication>
11 #include <QCryptographicHash>
12 #include <QElapsedTimer>
14 #include <QSslCertificate>
19 #include <sys/types.h>
23 #define CHALLENGE_LEN 20
26 QObject(nullptr), _timerDelete(0), _jpegQuality(80), _authed(0), _autoConnect(autoConnect), _isLocalConnection(-1), _sessionName(sessionName), _certHash(certHash), _host(host), _port(port)
34 connect(
_socket, &QSslSocket::stateChanged,
this, [
this](QAbstractSocket::SocketState state) {
35 qDebug() <<
diagnosticContext(QStringLiteral(
"socket state changed to %1").arg(
int(state)));
37 connect(
_socket, &QSslSocket::connected,
this, [
this]() {
38 qDebug() <<
diagnosticContext(QStringLiteral(
"TCP connected; local=%1:%2 peer=%3:%4")
42 connect(
_socket, QOverload<QAbstractSocket::SocketError>::of(&QSslSocket::errorOccurred),
44 connect(
_socket, QOverload<
const QList<QSslError> &>::of(&QSslSocket::sslErrors),
47 connect(
_socket, &QSslSocket::peerVerifyError,
this, [
this](
const QSslError& error) {
48 qDebug() <<
diagnosticContext(QStringLiteral(
"TLS peer verification error: %1 (%2)")
49 .arg(error.errorString()).arg(
int(error.error())));
51 connect(
_socket, &QSslSocket::modeChanged,
this, [
this](QSslSocket::SslMode mode) {
52 qDebug() <<
diagnosticContext(QStringLiteral(
"TLS mode changed to %1").arg(
int(mode)));
54 qDebug() <<
diagnosticContext(QStringLiteral(
"starting encrypted connection; expected certificate SHA-1=%1; SSL supported=%2; OpenSSL build=%3 runtime=%4")
55 .arg(QString::fromLatin1(
_certHash.toHex()))
56 .arg(QSslSocket::supportsSsl())
57 .arg(QSslSocket::sslLibraryBuildVersionString())
58 .arg(QSslSocket::sslLibraryVersionString()));
60 _socket->connectToHostEncrypted(host, port);
70 const QString socketState =
_socket ? QString::number(
int(
_socket->state())) : QStringLiteral(
"deleted");
71 const QString socketError =
_socket ?
_socket->errorString() : QStringLiteral(
"no socket");
73 return QStringLiteral(
"[client %1:%2 stage=%3 socketState=%4 encrypted=%5 elapsedMs=%6 error=%7]")
74 .arg(
_host).arg(
_port).arg(stage).arg(socketState).arg(encrypted)
82 qCritical(
"**** SOCKET DELETE IN DESTRUCTOR");
85 qDebug(
"*** Server connection destroyed.");
95 if (
_socket ==
nullptr ||
_socket->state() != QAbstractSocket::ConnectedState)
143 qWarning() <<
diagnosticContext(QStringLiteral(
"server application error in authentication stage %1: %2")
149 if (
id == _CHALLENGE) {
162 qWarning() <<
diagnosticContext(QStringLiteral(
"failed writing challenge response"));
163 qDebug(
"Received challenge, replying, sending own challenge step <- 1");
166 qWarning() <<
diagnosticContext(QStringLiteral(
"unexpected message ID '%1' while awaiting initial challenge").arg(
id));
172 if (
id == _CHALLENGE) {
173 qDebug(
"Received challenge reply");
181 if (serverhash != expectedServerHash && !
_autoConnect) {
182 qWarning() <<
diagnosticContext(QStringLiteral(
"challenge hash mismatch: expected=%1 received=%2")
183 .arg(QString::fromLatin1(expectedServerHash.toHex()), QString::fromLatin1(serverhash.toHex())));
184 qDebug(
"invalid. STOP.");
190 qWarning() <<
diagnosticContext(QStringLiteral(
"challenge hash mismatch bypassed because this is an auto-connect"));
193 const char *user = getpwuid(getuid())->pw_name;
194 if (user ==
nullptr || *user ==
'\0')
195 user = getenv(
"USER");
196 if (user ==
nullptr || *user ==
'\0')
197 user = getenv(
"USERNAME");
198 if (user ==
nullptr || *user ==
'\0')
204 qDebug() <<
"logging into manager, exam mode is " <<
clientApp->isExamMode();
207 qDebug(
"Sending login request!");
210 qDebug(
"valid, step <- 2");
216 qWarning() <<
diagnosticContext(QStringLiteral(
"unexpected message ID '%1' while awaiting challenge response").arg(
id));
223 qDebug(
"login accepted, step <- 3");
227 qWarning() <<
diagnosticContext(QStringLiteral(
"unexpected message ID '%1' while awaiting login acceptance").arg(
id));
235 QByteArray emptyArray;
244 QRect primaryRect = QGuiApplication::primaryScreen()->geometry();
248 }
else if (x > primaryRect.width() / 8) {
249 x = primaryRect.width() / 8;
253 }
else if (y > primaryRect.height() / 8) {
254 y = primaryRect.height() / 8;
258 QGuiApplication::primaryScreen()->grabWindow(0,
259 primaryRect.x(), primaryRect.y(), primaryRect.width(), primaryRect.height()
260 ).scaled(x, y, Qt::KeepAspectRatio, Qt::SmoothTransformation
263 QBuffer jpgBuffer(&bytes);
264 jpgBuffer.open(QIODevice::WriteOnly);
274 QBuffer pngBuffer(&bytes);
275 pngBuffer.open(QIODevice::WriteOnly);
276 if (!desktop.save(&pngBuffer,
"PNG")) {
277 qDebug(
"Could not convert screenshot to PNG nor JPG");
286 else if (
id == _VNCSERVER) {
288 qDebug() <<
"denied request for vnc server (exam mode)";
298 }
else if (
id == _VNCCLIENT) {
300 qDebug() <<
"denied request for vnc projection (exam mode)";
305 if (host.isEmpty() || port <= 0) {
310 }
else if (
id == _LOCK) {
312 if (enable && !
clientApp->isConnectedToLocalManager()) {
317 }
else if (
id == _ATTENTION) {
341 if (
_lastData < QDateTime::currentMSecsSinceEpoch()) {
346 }
else if (event->timerId() ==
_timerId) {
347 qWarning() <<
diagnosticContext(QStringLiteral(
"connection timeout: TCP connected=%1, TLS encrypted=%2")
348 .arg(
_socket &&
_socket->state() == QAbstractSocket::ConnectedState)
354 if (
_socket ==
nullptr ||
_socket->state() == QAbstractSocket::UnconnectedState) {
363 qDebug(
"A socket is still pending...");
365 killTimer(event->timerId());
414 for (
const auto &err : errors) {
415 const bool tolerated = err.error() == QSslError::HostNameMismatch
416 || err.error() == QSslError::SelfSignedCertificate
417 || err.error() == QSslError::CertificateNotYetValid
418 || err.error() == QSslError::CertificateExpired;
419 const QSslCertificate cert = err.certificate();
420 qDebug() <<
diagnosticContext(QStringLiteral(
"TLS error code=%1 tolerated=%2: %3; certificate subject=%4 issuer=%5")
421 .arg(
int(err.error())).arg(tolerated).arg(err.errorString())
422 .arg(cert.subjectInfo(QSslCertificate::CommonName).join(QLatin1Char(
',')))
423 .arg(cert.issuerInfo(QSslCertificate::CommonName).join(QLatin1Char(
','))));
424 if (err.error() == QSslError::HostNameMismatch)
426 if (err.error() == QSslError::SelfSignedCertificate)
428 if (err.error() == QSslError::CertificateNotYetValid || err.error() == QSslError::CertificateExpired)
431 qWarning() <<
diagnosticContext(QStringLiteral(
"non-tolerated TLS error; clearing ignored SSL errors"));
432 _socket->ignoreSslErrors(QList<QSslError>());
439 if (
_socket ==
nullptr ||
_socket->state() != QAbstractSocket::ConnectedState) {
440 qDebug(
"dataArrival called in bad state");
444 while (
_socket->bytesAvailable() > 0) {
447 qWarning() <<
diagnosticContext(QStringLiteral(
"application message read failed (result=%1)").arg(retval));
466 qDebug() <<
diagnosticContext(QStringLiteral(
"socket closed by peer or transport"));
472 qWarning() <<
diagnosticContext(QStringLiteral(
"socket error code=%1: %2").arg(
int(errcode)).arg(
_socket ?
_socket->errorString() : QStringLiteral(
"no socket")));
478 const QSslCertificate peerCert =
_socket->peerCertificate();
479 const QSslCipher cipher =
_socket->sessionCipher();
480 const QByteArray cert(peerCert.digest(QCryptographicHash::Sha1));
481 const QByteArray sha256(peerCert.digest(QCryptographicHash::Sha256));
482 const QSslKey publicKey = peerCert.publicKey();
483 qDebug() <<
diagnosticContext(QStringLiteral(
"TLS encrypted; protocol=%1 cipher=%2; peer=%3:%4; certificate subject=%5 issuer=%6 validFrom=%7 validTo=%8 publicKeyAlgorithm=%9 publicKeyBits=%10 chainLength=%11 SHA1=%12 SHA256=%13")
484 .arg(cipher.protocolString(), cipher.name())
486 .arg(peerCert.subjectInfo(QSslCertificate::CommonName).join(QLatin1Char(
',')))
487 .arg(peerCert.issuerInfo(QSslCertificate::CommonName).join(QLatin1Char(
',')))
488 .arg(peerCert.effectiveDate().toString(Qt::ISODate), peerCert.expiryDate().toString(Qt::ISODate))
489 .arg(
int(publicKey.algorithm())).arg(publicKey.length())
490 .arg(
_socket->peerCertificateChain().size())
491 .arg(QString::fromLatin1(cert.toHex()), QString::fromLatin1(sha256.toHex())));
493 qWarning() <<
diagnosticContext(QStringLiteral(
"certificate fingerprint mismatch; expected SHA1=%1 actual SHA1=%2 actual SHA256=%3; possible TLS interception or unexpected server certificate")
494 .arg(QString::fromLatin1(
_certHash.toHex()), QString::fromLatin1(cert.toHex()), QString::fromLatin1(sha256.toHex())));
static const QByteArray __TRUE("1")
static const QByteArray __FALSE("0")
void checkLocalConnection()
void stop()
VncServer::stop.
void started(int port, const QString &ropass, const QString &rwpass)
#define NM_READ_INCOMPLETE
bool writeMessage(QAbstractSocket *socket)
QString getFieldString(const QByteArray &key) const
~ServerConnection() override
bool readComplete() const
void stateChange(ConnectWindow::ConnectionState state)
void sendMessage(NetworkMessage &message)
Send the given message to the server.
QElapsedTimer _connectionTimer
QByteArray genSha1(const QByteArray *a, const QByteArray *b, const QByteArray *c, const QByteArray *d, const QByteArray *e)
int _timerConnectionCheck
void disconnectFromServer()
Disconnect from current server.
void attentionChanged(bool state)
NetworkMessage _fromServer
void disconnected(ServerConnection *connection)
void onVncServerStartStop(int port, const QString &ropass, const QString &rwpass)
This slot is triggered by the vnc server runner once the external VNC server was succesfully started...
void timerEvent(QTimerEvent *event) override
void start()
VncServer::start.
bool lock(const QString &message)
void sock_error(QAbstractSocket::SocketError errcode)
int readMessage(QAbstractSocket *socket)
void sslErrors(const QList< QSslError > &errors)
An ssl error happened.
bool writeComplete() const
QString diagnosticContext(const QString &stage) const
ServerConnection(const QString &host, quint16 port, const QByteArray &sessionName, const QByteArray &certHash, bool autoConnect)
void openVnc(const QString &host, int port, const QString &passwd, bool ro, bool fullscreen, const QString &caption, const int clientId, const QByteArray &rawThumb)
static const QByteArray & _BOOL(bool val)
void handleMsg()
Handles an incoming message by the server.
QByteArray getFieldBytes(const QByteArray &key) const
void setField(const QByteArray &key, const QByteArray &value)
void onVncViewerStartStop(bool started, int clientId)
This slot is triggered once the internal VNC viewer has started or stopped displaying a VNC stream...
static VncServer * instance()
VncServer::instance.
void sendAttention(bool on)