Pool Video Switch v2
Software video switch for distributed remote display in a lecture environment
serverconnection.cpp
Go to the documentation of this file.
1 #include "serverconnection.h"
2 
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"
8 
9 #include <QPixmap>
10 #include <QGuiApplication>
11 #include <QCryptographicHash>
12 #include <QElapsedTimer>
13 #include <QHostInfo>
14 #include <QSslCertificate>
15 #include <QSslCipher>
16 #include <QSslKey>
17 #include <QScreen>
18 // For getting logged-in username
19 #include <sys/types.h>
20 #include <pwd.h>
21 #include <unistd.h>
22 
23 #define CHALLENGE_LEN 20
24 
25 ServerConnection::ServerConnection(const QString& host, const quint16 port, const QByteArray& sessionName, const QByteArray& certHash, bool autoConnect) :
26  QObject(nullptr), _timerDelete(0), _jpegQuality(80), _authed(0), _autoConnect(autoConnect), _isLocalConnection(-1), _sessionName(sessionName), _certHash(certHash), _host(host), _port(port)
27 {
28  _socket = new QSslSocket();
29  _blank = new BlankScreen();
30  _connectionTimer.start();
31  connect(_socket, &QSslSocket::encrypted, this, &ServerConnection::sock_connected);
32  connect(_socket, &QSslSocket::readyRead, this, &ServerConnection::sock_dataArrival);
33  connect(_socket, &QSslSocket::disconnected, this, &ServerConnection::sock_closed);
34  connect(_socket, &QSslSocket::stateChanged, this, [this](QAbstractSocket::SocketState state) {
35  qDebug() << diagnosticContext(QStringLiteral("socket state changed to %1").arg(int(state)));
36  });
37  connect(_socket, &QSslSocket::connected, this, [this]() {
38  qDebug() << diagnosticContext(QStringLiteral("TCP connected; local=%1:%2 peer=%3:%4")
39  .arg(_socket->localAddress().toString()).arg(_socket->localPort())
40  .arg(_socket->peerAddress().toString()).arg(_socket->peerPort()));
41  });
42  connect(_socket, QOverload<QAbstractSocket::SocketError>::of(&QSslSocket::errorOccurred),
44  connect(_socket, QOverload<const QList<QSslError> &>::of(&QSslSocket::sslErrors),
46  );
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())));
50  });
51  connect(_socket, &QSslSocket::modeChanged, this, [this](QSslSocket::SslMode mode) {
52  qDebug() << diagnosticContext(QStringLiteral("TLS mode changed to %1").arg(int(mode)));
53  });
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()));
59  _socket->ignoreSslErrors();
60  _socket->connectToHostEncrypted(host, port);
61  _timerId = startTimer(4000);
62  _lastData = QDateTime::currentMSecsSinceEpoch() + PING_TIMEOUT_MS;
63  _timerConnectionCheck = startTimer(5000);
64  // Connect the vnc start/stop signal to this class, so we can tell the server about successful vnc server startup
66 }
67 
68 QString ServerConnection::diagnosticContext(const QString& stage) const
69 {
70  const QString socketState = _socket ? QString::number(int(_socket->state())) : QStringLiteral("deleted");
71  const QString socketError = _socket ? _socket->errorString() : QStringLiteral("no socket");
72  const bool encrypted = _socket && _socket->isEncrypted();
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)
75  .arg(_connectionTimer.elapsed()).arg(socketError);
76 }
77 
79 {
80  this->disconnectFromServer();
81  if (_socket != nullptr) {
82  qCritical("**** SOCKET DELETE IN DESTRUCTOR");
83  _socket->deleteLater();
84  }
85  qDebug("*** Server connection destroyed.");
86  _blank->deleteLater();
87  _blank = nullptr;
88 }
89 
94 {
95  if (_socket == nullptr || _socket->state() != QAbstractSocket::ConnectedState)
96  return;
97  message.writeMessage(_socket);
98  if (!message.writeComplete()) {
99  qCritical() << diagnosticContext(QStringLiteral("message write failed; message ID=%1").arg(message.getFieldString(_ID)))
100  << "writeComplete" << message.writeComplete();
101  }
102 }
103 
105 {
106  NetworkMessage msg;
107  msg.setField(_ID, _ATTENTION);
108  msg.setField(_ENABLE, _BOOL(on));
109  sendMessage(msg);
110 }
111 
118 {
119  if (_timerDelete == 0) {
121  emit closeVnc();
122  emit disconnected(this);
123  _timerDelete = startTimer(500);
124  qDebug() << diagnosticContext(QStringLiteral("closing connection; authentication stage=%1").arg(_authed));
125  if (_socket != nullptr) {
126  _socket->blockSignals(true);
127  _socket->abort();
128  }
129  }
130 }
131 
138 {
139  _lastData = QDateTime::currentMSecsSinceEpoch() + PING_TIMEOUT_MS;
140  const QString &id = _fromServer.getFieldString(_ID);
141 
142  if (id == _ERROR) {
143  qWarning() << diagnosticContext(QStringLiteral("server application error in authentication stage %1: %2")
144  .arg(_authed).arg(_fromServer.getFieldString(_ERROR)));
145  return;
146  }
147 
148  if (_authed == 0) {
149  if (id == _CHALLENGE) {
150  // Initial challenge request by server
152  _myChallenge.resize(CHALLENGE_LEN);
153  for (int i = 0; i < CHALLENGE_LEN; ++i) {
154  _myChallenge[i] = char(slxrand() & 0xff);
155  }
156  QByteArray serverChallenge(_fromServer.getFieldBytes(_CHALLENGE));
157  _toServer.reset();
158  _toServer.setField(_ID, _CHALLENGE);
159  _toServer.setField(_HASH, genSha1(&_sessionName, &serverChallenge));
160  _toServer.setField(_CHALLENGE, _myChallenge);
162  qWarning() << diagnosticContext(QStringLiteral("failed writing challenge response"));
163  qDebug("Received challenge, replying, sending own challenge step <- 1");
164  _authed = 1;
165  } else {
166  qWarning() << diagnosticContext(QStringLiteral("unexpected message ID '%1' while awaiting initial challenge").arg(id));
167  }
168  return;
169  }
170 
171  if (_authed == 1) {
172  if (id == _CHALLENGE) {
173  qDebug("Received challenge reply");
174  if (_timerId != 0) {
175  killTimer(_timerId);
176  _timerId = 0;
177  }
178  // Check challenge response
179  QByteArray serverhash(_fromServer.getFieldBytes(_HASH));
180  const QByteArray expectedServerHash = genSha1(&_sessionName, &_myChallenge);
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.");
186  this->disconnectFromServer();
187  return;
188  }
189  if (serverhash != expectedServerHash && _autoConnect) {
190  qWarning() << diagnosticContext(QStringLiteral("challenge hash mismatch bypassed because this is an auto-connect"));
191  }
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')
199  user = "Hans Affe";
200  _toServer.reset();
201  _toServer.setField(_ID, _LOGIN);
202  _toServer.setField("HOST", QHostInfo::localHostName());
203  _toServer.setField("NAME", QString(user));
204  qDebug() << "logging into manager, exam mode is " << clientApp->isExamMode();
205  _toServer.setField(_EXAMMODE, clientApp->isExamMode() ? __TRUE : __FALSE);
206  /* TODO: (Question) Why is this here not using sendMessage() ? */
207  qDebug("Sending login request!");
209  _authed = 2;
210  qDebug("valid, step <- 2");
211  } else {
212  qWarning() << diagnosticContext(QStringLiteral("failed writing login request; writeComplete=%1").arg(_toServer.writeComplete()));
213  this->disconnectFromServer();
214  }
215  } else {
216  qWarning() << diagnosticContext(QStringLiteral("unexpected message ID '%1' while awaiting challenge response").arg(id));
217  }
218  return;
219  }
220 
221  if (_authed == 2) {
222  if (id == _LOGIN) {
223  qDebug("login accepted, step <- 3");
224  _authed = 3;
226  } else {
227  qWarning() << diagnosticContext(QStringLiteral("unexpected message ID '%1' while awaiting login acceptance").arg(id));
228  }
229  return;
230  }
231 
232  // message THUMB - server requests screenshot as thumbnail
233  if (id == _THUMB) {
234  if (clientApp->isExamMode()) {
235  QByteArray emptyArray;
236  _toServer.setField(_ID, _THUMB);
237  _toServer.setField(_IMG, emptyArray);
239  return;
240  }
241  int x = _fromServer.getFieldString(_X).toInt();
242  int y = _fromServer.getFieldString(_Y).toInt();
243 
244  QRect primaryRect = QGuiApplication::primaryScreen()->geometry();
245  // Limit requested size so it won't easily leak sensitive information
246  if (x < 32) {
247  x = 32;
248  } else if (x > primaryRect.width() / 8) {
249  x = primaryRect.width() / 8;
250  }
251  if (y < 18) {
252  y = 18;
253  } else if (y > primaryRect.height() / 8) {
254  y = primaryRect.height() / 8;
255  }
256 
257  QPixmap desktop(
258  QGuiApplication::primaryScreen()->grabWindow(0,
259  primaryRect.x(), primaryRect.y(), primaryRect.width(), primaryRect.height()
260  ).scaled(x, y, Qt::KeepAspectRatio, Qt::SmoothTransformation
261  ));
262  QByteArray bytes;
263  QBuffer jpgBuffer(&bytes);
264  jpgBuffer.open(QIODevice::WriteOnly);
265  if (desktop.save(&jpgBuffer, "JPG", _jpegQuality)) { // writes pixmap into bytes in JPG format
266  // Try to adjust quality so we stay between 3 and 4.5 KB
267  if (_jpegQuality < 90 && bytes.size() < 3000)
268  _jpegQuality += 7;
269  else if (_jpegQuality > 40 && bytes.size() > 4500)
270  _jpegQuality -= 7;
271  } else {
272  // FALLBACK
273  bytes.clear();
274  QBuffer pngBuffer(&bytes);
275  pngBuffer.open(QIODevice::WriteOnly);
276  if (!desktop.save(&pngBuffer, "PNG")) { // writes pixmap into bytes in PNG format
277  qDebug("Could not convert screenshot to PNG nor JPG");
278  return; // Failed :-(
279  }
280  }
281  _toServer.reset();
282  _toServer.setField(_ID, _THUMB);
283  _toServer.setField(_IMG, bytes);
285  } // message VNCSERVER - start local vncserver
286  else if (id == _VNCSERVER) {
287  if (clientApp->isExamMode()) {
288  qDebug() << "denied request for vnc server (exam mode)";
289  return;
290  }
291  const bool enable = (_fromServer.getFieldString("ENABLE").toInt() != 0);
292  if (enable) {
293  emit closeVnc(); // In case we are watching some other client, stop doing so
295  } else {
297  }
298  } else if (id == _VNCCLIENT) {
299  if (clientApp->isExamMode()) {
300  qDebug() << "denied request for vnc projection (exam mode)";
301  return;
302  }
303  const QString host(_fromServer.getFieldString("HOST"));
304  const int port = _fromServer.getFieldString("PORT").toInt();
305  if (host.isEmpty() || port <= 0) {
306  emit closeVnc();
307  } else {
308  emit openVnc(host, port, _fromServer.getFieldString("ROPASS"), true, true, _fromServer.getFieldString("CAPTION"), _fromServer.getFieldString("CLIENTID").toInt(), _fromServer.getFieldBytes(_THUMB));
309  }
310  } else if (id == _LOCK) {
311  const bool enable = (_fromServer.getFieldString("ENABLE").toInt() != 0);
312  if (enable && !clientApp->isConnectedToLocalManager()) {
313  _blank->lock(_fromServer.getFieldString("MESSAGE"));
314  } else {
315  _blank->unlock();
316  }
317  } else if (id == _ATTENTION) {
319  }
320 }
321 
323 {
324  if (_socket == nullptr) {
325  return;
326  }
327  if (_socket->peerAddress() == _socket->localAddress()) {
328  _isLocalConnection = 1;
329  } else {
330  _isLocalConnection = 0;
331  }
332 }
333 
334 /*
335  * Override
336  */
337 
338 void ServerConnection::timerEvent(QTimerEvent *event)
339 {
340  if (event->timerId() == _timerConnectionCheck) {
341  if (_lastData < QDateTime::currentMSecsSinceEpoch()) {
342  qWarning() << diagnosticContext(QStringLiteral("application ping timeout"));
343  this->disconnectFromServer();
344  killTimer(_timerConnectionCheck);
345  }
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)
349  .arg(_socket && _socket->isEncrypted()));
350  killTimer(_timerId);
351  _timerId = 0;
352  this->disconnectFromServer();
353  } else if (event->timerId() == _timerDelete) {
354  if (_socket == nullptr || _socket->state() == QAbstractSocket::UnconnectedState) {
355  if (_socket != nullptr)
356  _socket->deleteLater();
357  _socket = nullptr;
358  killTimer(_timerDelete);
359  this->deleteLater();
360  return;
361  }
362  _socket->abort();
363  qDebug("A socket is still pending...");
364  } else
365  killTimer(event->timerId());
366 }
367 
368 /*
369  * Slots
370  */
371 
377 void ServerConnection::onVncServerStartStop(int port, const QString &ropass, const QString &rwpass)
378 {
379  _toServer.reset();
380  _toServer.setField(_ID, _VNCSERVER);
381  if (port <= 0) {
382  _toServer.setField("PORT", QByteArray("0"));
383  } else {
384  _toServer.setField("PORT", QString::number(port));
385  _toServer.setField("ROPASS", ropass);
386  _toServer.setField("RWPASS", rwpass);
387  }
389 }
390 
395 void ServerConnection::onVncViewerStartStop(const bool started, const int clientId)
396 {
397  _toServer.reset();
398  _toServer.setField(_ID, _VNCCLIENT);
399  if (started)
400  _toServer.setField("ENABLED", __TRUE);
401  else
402  _toServer.setField("ENABLED", __FALSE);
403  _toServer.setField("CLIENTID", QString::number(clientId));
405 }
406 
411 void ServerConnection::sslErrors(const QList<QSslError> & errors)
412 {
413  _socket->ignoreSslErrors();
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)
425  continue; // We don't pay attention to hostnames for validation
426  if (err.error() == QSslError::SelfSignedCertificate)
427  continue; // Also, this will always be the case; we check the fingerprint later
428  if (err.error() == QSslError::CertificateNotYetValid || err.error() == QSslError::CertificateExpired)
429  continue;
430  // Some other SSL error - do not ignore
431  qWarning() << diagnosticContext(QStringLiteral("non-tolerated TLS error; clearing ignored SSL errors"));
432  _socket->ignoreSslErrors(QList<QSslError>());
433  return;
434  }
435 }
436 
438 {
439  if (_socket == nullptr || _socket->state() != QAbstractSocket::ConnectedState) {
440  qDebug("dataArrival called in bad state");
441  return;
442  }
443 
444  while (_socket->bytesAvailable() > 0) {
445  int retval = _fromServer.readMessage(_socket); // let the message read data from socket
446  if (retval == NM_READ_FAILED) { // error parsing msg, disconnect client!
447  qWarning() << diagnosticContext(QStringLiteral("application message read failed (result=%1)").arg(retval));
448  this->disconnectFromServer();
449  return;
450  }
451  if (retval == NM_READ_INCOMPLETE)
452  return;
453  if (_fromServer.readComplete()) { // message is complete
454  this->handleMsg();
455  if (_socket == nullptr)
456  return;
457  _fromServer.reset();
458  }
459  }
460 }
461 
463 {
464  // should this be unreliable in some way i suggest using the signal "stateChanged()" instead
465  // and check if the state changed to unconnected.
466  qDebug() << diagnosticContext(QStringLiteral("socket closed by peer or transport"));
467  this->disconnectFromServer();
468 }
469 
470 void ServerConnection::sock_error(QAbstractSocket::SocketError errcode)
471 {
472  qWarning() << diagnosticContext(QStringLiteral("socket error code=%1: %2").arg(int(errcode)).arg(_socket ? _socket->errorString() : QStringLiteral("no socket")));
473  this->disconnectFromServer();
474 }
475 
477 {
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())
485  .arg(_socket->peerAddress().toString()).arg(_socket->peerPort())
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())));
492  if (_certHash != cert) {
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())));
496  this->disconnectFromServer();
497  return;
498  }
500 }
static const QByteArray __TRUE("1")
static const QByteArray __FALSE("0")
void stop()
VncServer::stop.
Definition: vncserver.cpp:139
void started(int port, const QString &ropass, const QString &rwpass)
QByteArray _sessionName
#define NM_READ_INCOMPLETE
QSslSocket * _socket
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.
BlankScreen * _blank
NetworkMessage _toServer
#define PING_TIMEOUT_MS
Definition: settings.h:13
QElapsedTimer _connectionTimer
QByteArray genSha1(const QByteArray *a, const QByteArray *b, const QByteArray *c, const QByteArray *d, const QByteArray *e)
Definition: util.cpp:13
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...
#define slxrand()
Definition: util.h:19
#define CHALLENGE_LEN
bool unlock()
Definition: blankscreen.cpp:71
void timerEvent(QTimerEvent *event) override
void start()
VncServer::start.
Definition: vncserver.cpp:77
QByteArray _certHash
bool lock(const QString &message)
Definition: blankscreen.cpp:40
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)
#define clientApp
Definition: clientapp.h:12
void openVnc(const QString &host, int port, const QString &passwd, bool ro, bool fullscreen, const QString &caption, const int clientId, const QByteArray &rawThumb)
#define NM_READ_FAILED
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...
QByteArray _myChallenge
static VncServer * instance()
VncServer::instance.
Definition: vncserver.cpp:25
void sendAttention(bool on)