Drop WebUI default credentials
[qBittorrent.git] / src / webui / webapplication.cpp
blob49963a7cf2a89bd86dcd2914db922e48f3a5dbcf
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2014, 2022-2023 Vladimir Golovnev <glassez@yandex.ru>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * In addition, as a special exception, the copyright holders give permission to
20 * link this program with the OpenSSL project's "OpenSSL" library (or with
21 * modified versions of it that use the same license as the "OpenSSL" library),
22 * and distribute the linked executables. You must obey the GNU General Public
23 * License in all respects for all of the code used other than "OpenSSL". If you
24 * modify file(s), you may extend this exception to your version of the file(s),
25 * but you are not obligated to do so. If you do not wish to do so, delete this
26 * exception statement from your version.
29 #include "webapplication.h"
31 #include <algorithm>
32 #include <chrono>
34 #include <QDateTime>
35 #include <QDebug>
36 #include <QDir>
37 #include <QFileInfo>
38 #include <QJsonDocument>
39 #include <QMetaObject>
40 #include <QMimeDatabase>
41 #include <QMimeType>
42 #include <QNetworkCookie>
43 #include <QRegularExpression>
44 #include <QThread>
45 #include <QTimer>
46 #include <QUrl>
48 #include "base/algorithm.h"
49 #include "base/http/httperror.h"
50 #include "base/logger.h"
51 #include "base/preferences.h"
52 #include "base/types.h"
53 #include "base/utils/fs.h"
54 #include "base/utils/io.h"
55 #include "base/utils/misc.h"
56 #include "base/utils/random.h"
57 #include "base/utils/string.h"
58 #include "api/apierror.h"
59 #include "api/appcontroller.h"
60 #include "api/authcontroller.h"
61 #include "api/logcontroller.h"
62 #include "api/rsscontroller.h"
63 #include "api/searchcontroller.h"
64 #include "api/synccontroller.h"
65 #include "api/torrentscontroller.h"
66 #include "api/transfercontroller.h"
67 #include "freediskspacechecker.h"
69 const int MAX_ALLOWED_FILESIZE = 10 * 1024 * 1024;
70 const QString DEFAULT_SESSION_COOKIE_NAME = u"SID"_s;
72 const QString WWW_FOLDER = u":/www"_s;
73 const QString PUBLIC_FOLDER = u"/public"_s;
74 const QString PRIVATE_FOLDER = u"/private"_s;
76 using namespace std::chrono_literals;
78 const std::chrono::seconds FREEDISKSPACE_CHECK_TIMEOUT = 30s;
80 namespace
82 QStringMap parseCookie(const QStringView cookieStr)
84 // [rfc6265] 4.2.1. Syntax
85 QStringMap ret;
86 const QList<QStringView> cookies = cookieStr.split(u';', Qt::SkipEmptyParts);
88 for (const auto &cookie : cookies)
90 const int idx = cookie.indexOf(u'=');
91 if (idx < 0)
92 continue;
94 const QString name = cookie.left(idx).trimmed().toString();
95 const QString value = Utils::String::unquote(cookie.mid(idx + 1).trimmed()).toString();
96 ret.insert(name, value);
98 return ret;
101 QUrl urlFromHostHeader(const QString &hostHeader)
103 if (!hostHeader.contains(u"://"))
104 return {u"http://"_s + hostHeader};
105 return hostHeader;
108 QString getCachingInterval(QString contentType)
110 contentType = contentType.toLower();
112 if (contentType.startsWith(u"image/"))
113 return u"private, max-age=604800"_s; // 1 week
115 if ((contentType == Http::CONTENT_TYPE_CSS)
116 || (contentType == Http::CONTENT_TYPE_JS))
118 // short interval in case of program update
119 return u"private, max-age=43200"_s; // 12 hrs
122 return u"no-store"_s;
125 QString createLanguagesOptionsHtml()
127 // List language files
128 const QDir langDir {u":/www/translations"_s};
129 const QStringList langFiles = langDir.entryList(QStringList(u"webui_*.qm"_s), QDir::Files);
130 QStringList languages;
131 for (const QString &langFile : langFiles)
133 const QString localeStr = langFile.section(u"_"_s, 1, -1).section(u"."_s, 0, 0); // remove "webui_" and ".qm"
134 languages << u"<option value=\"%1\">%2</option>"_s.arg(localeStr, Utils::Misc::languageToLocalizedString(localeStr));
135 qDebug() << "Supported locale:" << localeStr;
138 return languages.join(u'\n');
141 bool isValidCookieName(const QString &cookieName)
143 if (cookieName.isEmpty() || (cookieName.size() > 128))
144 return false;
146 const QRegularExpression invalidNameRegex {u"[^a-zA-Z0-9_\\-]"_s};
147 if (invalidNameRegex.match(cookieName).hasMatch())
148 return false;
150 return true;
154 WebApplication::WebApplication(IApplication *app, QObject *parent)
155 : ApplicationComponent(app, parent)
156 , m_cacheID {QString::number(Utils::Random::rand(), 36)}
157 , m_authController {new AuthController(this, app, this)}
158 , m_workerThread {new QThread}
159 , m_freeDiskSpaceChecker {new FreeDiskSpaceChecker}
160 , m_freeDiskSpaceCheckingTimer {new QTimer(this)}
162 declarePublicAPI(u"auth/login"_s);
164 configure();
165 connect(Preferences::instance(), &Preferences::changed, this, &WebApplication::configure);
167 m_sessionCookieName = Preferences::instance()->getWebAPISessionCookieName();
168 if (!isValidCookieName(m_sessionCookieName))
170 if (!m_sessionCookieName.isEmpty())
172 LogMsg(tr("Unacceptable session cookie name is specified: '%1'. Default one is used.")
173 .arg(m_sessionCookieName), Log::WARNING);
175 m_sessionCookieName = DEFAULT_SESSION_COOKIE_NAME;
178 m_freeDiskSpaceChecker->moveToThread(m_workerThread.get());
179 connect(m_workerThread.get(), &QThread::finished, m_freeDiskSpaceChecker, &QObject::deleteLater);
180 m_workerThread->start();
182 m_freeDiskSpaceCheckingTimer->setInterval(FREEDISKSPACE_CHECK_TIMEOUT);
183 m_freeDiskSpaceCheckingTimer->setSingleShot(true);
184 connect(m_freeDiskSpaceCheckingTimer, &QTimer::timeout, m_freeDiskSpaceChecker, &FreeDiskSpaceChecker::check);
185 connect(m_freeDiskSpaceChecker, &FreeDiskSpaceChecker::checked, m_freeDiskSpaceCheckingTimer, qOverload<>(&QTimer::start));
186 QMetaObject::invokeMethod(m_freeDiskSpaceChecker, &FreeDiskSpaceChecker::check);
189 WebApplication::~WebApplication()
191 // cleanup sessions data
192 qDeleteAll(m_sessions);
195 void WebApplication::sendWebUIFile()
197 if (request().path.contains(u'\\'))
198 throw BadRequestHTTPError();
200 if (const QList<QStringView> pathItems = QStringView(request().path).split(u'/', Qt::SkipEmptyParts)
201 ; pathItems.contains(u".") || pathItems.contains(u".."))
203 throw BadRequestHTTPError();
206 const QString path = (request().path != u"/")
207 ? request().path
208 : u"/index.html"_s;
210 Path localPath = m_rootFolder
211 / Path(session() ? PRIVATE_FOLDER : PUBLIC_FOLDER)
212 / Path(path);
213 if (!localPath.exists() && session())
215 // try to send public file if there is no private one
216 localPath = m_rootFolder / Path(PUBLIC_FOLDER) / Path(path);
219 if (m_isAltUIUsed)
221 if (!Utils::Fs::isRegularFile(localPath))
222 throw InternalServerErrorHTTPError(tr("Unacceptable file type, only regular file is allowed."));
224 const QString rootFolder = m_rootFolder.data();
226 QFileInfo fileInfo {localPath.parentPath().data()};
227 while (fileInfo.path() != rootFolder)
229 if (fileInfo.isSymLink())
230 throw InternalServerErrorHTTPError(tr("Symlinks inside alternative UI folder are forbidden."));
232 fileInfo.setFile(fileInfo.path());
236 sendFile(localPath);
239 void WebApplication::translateDocument(QString &data) const
241 const QRegularExpression regex(u"QBT_TR\\((([^\\)]|\\)(?!QBT_TR))+)\\)QBT_TR\\[CONTEXT=([a-zA-Z_][a-zA-Z0-9_]*)\\]"_s);
243 int i = 0;
244 bool found = true;
245 while (i < data.size() && found)
247 QRegularExpressionMatch regexMatch;
248 i = data.indexOf(regex, i, &regexMatch);
249 if (i >= 0)
251 const QString sourceText = regexMatch.captured(1);
252 const QString context = regexMatch.captured(3);
254 const QString loadedText = m_translationFileLoaded
255 ? m_translator.translate(context.toUtf8().constData(), sourceText.toUtf8().constData())
256 : QString();
257 // `loadedText` is empty when translation is not provided
258 // it should fallback to `sourceText`
259 QString translation = loadedText.isEmpty() ? sourceText : loadedText;
261 // Use HTML code for quotes to prevent issues with JS
262 translation.replace(u'\'', u"&#39;"_s);
263 translation.replace(u'\"', u"&#34;"_s);
265 data.replace(i, regexMatch.capturedLength(), translation);
266 i += translation.length();
268 else
270 found = false; // no more translatable strings
273 data.replace(u"${LANG}"_s, m_currentLocale.left(2));
274 data.replace(u"${CACHEID}"_s, m_cacheID);
278 WebSession *WebApplication::session()
280 return m_currentSession;
283 const Http::Request &WebApplication::request() const
285 return m_request;
288 const Http::Environment &WebApplication::env() const
290 return m_env;
293 void WebApplication::setUsername(const QString &username)
295 m_authController->setUsername(username);
298 void WebApplication::setPasswordHash(const QByteArray &passwordHash)
300 m_authController->setPasswordHash(passwordHash);
303 void WebApplication::doProcessRequest()
305 const QRegularExpressionMatch match = m_apiPathPattern.match(request().path);
306 if (!match.hasMatch())
308 sendWebUIFile();
309 return;
312 const QString action = match.captured(u"action"_s);
313 const QString scope = match.captured(u"scope"_s);
315 // Check public/private scope
316 if (!session() && !isPublicAPI(scope, action))
317 throw ForbiddenHTTPError();
319 // Find matching API
320 APIController *controller = nullptr;
321 if (session())
322 controller = session()->getAPIController(scope);
323 if (!controller)
325 if (scope == u"auth")
326 controller = m_authController;
327 else
328 throw NotFoundHTTPError();
331 // Filter HTTP methods
332 const auto allowedMethodIter = m_allowedMethod.find({scope, action});
333 if (allowedMethodIter == m_allowedMethod.end())
335 // by default allow both GET, POST methods
336 if ((m_request.method != Http::METHOD_GET) && (m_request.method != Http::METHOD_POST))
337 throw MethodNotAllowedHTTPError();
339 else
341 if (*allowedMethodIter != m_request.method)
342 throw MethodNotAllowedHTTPError();
345 DataMap data;
346 for (const Http::UploadedFile &torrent : request().files)
347 data[torrent.filename] = torrent.data;
351 const QVariant result = controller->run(action, m_params, data);
352 switch (result.userType())
354 case QMetaType::QJsonDocument:
355 print(result.toJsonDocument().toJson(QJsonDocument::Compact), Http::CONTENT_TYPE_JSON);
356 break;
357 case QMetaType::QByteArray:
358 print(result.toByteArray(), Http::CONTENT_TYPE_TXT);
359 break;
360 case QMetaType::QString:
361 default:
362 print(result.toString(), Http::CONTENT_TYPE_TXT);
363 break;
366 catch (const APIError &error)
368 // re-throw as HTTPError
369 switch (error.type())
371 case APIErrorType::AccessDenied:
372 throw ForbiddenHTTPError(error.message());
373 case APIErrorType::BadData:
374 throw UnsupportedMediaTypeHTTPError(error.message());
375 case APIErrorType::BadParams:
376 throw BadRequestHTTPError(error.message());
377 case APIErrorType::Conflict:
378 throw ConflictHTTPError(error.message());
379 case APIErrorType::NotFound:
380 throw NotFoundHTTPError(error.message());
381 default:
382 Q_ASSERT(false);
387 void WebApplication::configure()
389 const auto *pref = Preferences::instance();
391 const bool isAltUIUsed = pref->isAltWebUIEnabled();
392 const Path rootFolder = (!isAltUIUsed ? Path(WWW_FOLDER) : pref->getWebUIRootFolder());
393 if ((isAltUIUsed != m_isAltUIUsed) || (rootFolder != m_rootFolder))
395 m_isAltUIUsed = isAltUIUsed;
396 m_rootFolder = rootFolder;
397 m_translatedFiles.clear();
398 if (!m_isAltUIUsed)
399 LogMsg(tr("Using built-in WebUI."));
400 else
401 LogMsg(tr("Using custom WebUI. Location: \"%1\".").arg(m_rootFolder.toString()));
404 const QString newLocale = pref->getLocale();
405 if (m_currentLocale != newLocale)
407 m_currentLocale = newLocale;
408 m_translatedFiles.clear();
410 m_translationFileLoaded = m_translator.load((m_rootFolder / Path(u"translations/webui_"_s) + newLocale).data());
411 if (m_translationFileLoaded)
413 LogMsg(tr("WebUI translation for selected locale (%1) has been successfully loaded.")
414 .arg(newLocale));
416 else
418 LogMsg(tr("Couldn't load WebUI translation for selected locale (%1).").arg(newLocale), Log::WARNING);
422 m_isLocalAuthEnabled = pref->isWebUILocalAuthEnabled();
423 m_isAuthSubnetWhitelistEnabled = pref->isWebUIAuthSubnetWhitelistEnabled();
424 m_authSubnetWhitelist = pref->getWebUIAuthSubnetWhitelist();
425 m_sessionTimeout = pref->getWebUISessionTimeout();
427 m_domainList = pref->getServerDomains().split(u';', Qt::SkipEmptyParts);
428 std::for_each(m_domainList.begin(), m_domainList.end(), [](QString &entry) { entry = entry.trimmed(); });
430 m_isCSRFProtectionEnabled = pref->isWebUICSRFProtectionEnabled();
431 m_isSecureCookieEnabled = pref->isWebUISecureCookieEnabled();
432 m_isHostHeaderValidationEnabled = pref->isWebUIHostHeaderValidationEnabled();
433 m_isHttpsEnabled = pref->isWebUIHttpsEnabled();
435 m_prebuiltHeaders.clear();
436 m_prebuiltHeaders.push_back({Http::HEADER_X_XSS_PROTECTION, u"1; mode=block"_s});
437 m_prebuiltHeaders.push_back({Http::HEADER_X_CONTENT_TYPE_OPTIONS, u"nosniff"_s});
439 if (!m_isAltUIUsed)
441 m_prebuiltHeaders.push_back({Http::HEADER_CROSS_ORIGIN_OPENER_POLICY, u"same-origin"_s});
442 m_prebuiltHeaders.push_back({Http::HEADER_REFERRER_POLICY, u"same-origin"_s});
445 const bool isClickjackingProtectionEnabled = pref->isWebUIClickjackingProtectionEnabled();
446 if (isClickjackingProtectionEnabled)
447 m_prebuiltHeaders.push_back({Http::HEADER_X_FRAME_OPTIONS, u"SAMEORIGIN"_s});
449 const QString contentSecurityPolicy =
450 (m_isAltUIUsed
451 ? QString()
452 : u"default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; script-src 'self' 'unsafe-inline'; object-src 'none'; form-action 'self';"_s)
453 + (isClickjackingProtectionEnabled ? u" frame-ancestors 'self';"_s : QString())
454 + (m_isHttpsEnabled ? u" upgrade-insecure-requests;"_s : QString());
455 if (!contentSecurityPolicy.isEmpty())
456 m_prebuiltHeaders.push_back({Http::HEADER_CONTENT_SECURITY_POLICY, contentSecurityPolicy});
458 if (pref->isWebUICustomHTTPHeadersEnabled())
460 const QString customHeaders = pref->getWebUICustomHTTPHeaders();
461 const QList<QStringView> customHeaderLines = QStringView(customHeaders).trimmed().split(u'\n', Qt::SkipEmptyParts);
463 for (const QStringView line : customHeaderLines)
465 const int idx = line.indexOf(u':');
466 if (idx < 0)
468 // require separator `:` to be present even if `value` field can be empty
469 LogMsg(tr("Missing ':' separator in WebUI custom HTTP header: \"%1\"").arg(line.toString()), Log::WARNING);
470 continue;
473 const QString header = line.left(idx).trimmed().toString();
474 const QString value = line.mid(idx + 1).trimmed().toString();
475 m_prebuiltHeaders.push_back({header, value});
479 m_isReverseProxySupportEnabled = pref->isWebUIReverseProxySupportEnabled();
480 if (m_isReverseProxySupportEnabled)
482 const QStringList proxyList = pref->getWebUITrustedReverseProxiesList().split(u';', Qt::SkipEmptyParts);
484 m_trustedReverseProxyList.clear();
485 m_trustedReverseProxyList.reserve(proxyList.size());
487 for (QString proxy : proxyList)
489 if (!proxy.contains(u'/'))
491 const QAbstractSocket::NetworkLayerProtocol protocol = QHostAddress(proxy).protocol();
492 if (protocol == QAbstractSocket::IPv4Protocol)
494 proxy.append(u"/32");
496 else if (protocol == QAbstractSocket::IPv6Protocol)
498 proxy.append(u"/128");
502 const std::optional<Utils::Net::Subnet> subnet = Utils::Net::parseSubnet(proxy);
503 if (subnet)
504 m_trustedReverseProxyList.push_back(subnet.value());
507 if (m_trustedReverseProxyList.isEmpty())
508 m_isReverseProxySupportEnabled = false;
512 void WebApplication::declarePublicAPI(const QString &apiPath)
514 m_publicAPIs << apiPath;
517 void WebApplication::sendFile(const Path &path)
519 const QDateTime lastModified = Utils::Fs::lastModified(path);
521 // find translated file in cache
522 if (!m_isAltUIUsed)
524 if (const auto it = m_translatedFiles.constFind(path);
525 (it != m_translatedFiles.constEnd()) && (lastModified <= it->lastModified))
527 print(it->data, it->mimeType);
528 setHeader({Http::HEADER_CACHE_CONTROL, getCachingInterval(it->mimeType)});
529 return;
533 const auto readResult = Utils::IO::readFile(path, MAX_ALLOWED_FILESIZE);
534 if (!readResult)
536 const QString message = tr("Web server error. %1").arg(readResult.error().message);
538 switch (readResult.error().status)
540 case Utils::IO::ReadError::NotExist:
541 qDebug("%s", qUtf8Printable(message));
542 // don't write log messages here to avoid exhausting the disk space
543 throw NotFoundHTTPError();
545 case Utils::IO::ReadError::ExceedSize:
546 qWarning("%s", qUtf8Printable(message));
547 LogMsg(message, Log::WARNING);
548 throw InternalServerErrorHTTPError(readResult.error().message);
550 case Utils::IO::ReadError::Failed:
551 case Utils::IO::ReadError::SizeMismatch:
552 LogMsg(message, Log::WARNING);
553 throw InternalServerErrorHTTPError(readResult.error().message);
556 throw InternalServerErrorHTTPError(tr("Web server error. Unknown error."));
559 QByteArray data = readResult.value();
560 const QMimeType mimeType = QMimeDatabase().mimeTypeForFileNameAndData(path.data(), data);
561 const bool isTranslatable = !m_isAltUIUsed && mimeType.inherits(u"text/plain"_s);
563 if (isTranslatable)
565 auto dataStr = QString::fromUtf8(data);
566 // Translate the file
567 translateDocument(dataStr);
569 // Add the language options
570 if (path == (m_rootFolder / Path(PRIVATE_FOLDER) / Path(u"views/preferences.html"_s)))
571 dataStr.replace(u"${LANGUAGE_OPTIONS}"_s, createLanguagesOptionsHtml());
573 data = dataStr.toUtf8();
574 m_translatedFiles[path] = {data, mimeType.name(), lastModified}; // caching translated file
577 print(data, mimeType.name());
578 setHeader({Http::HEADER_CACHE_CONTROL, getCachingInterval(mimeType.name())});
581 Http::Response WebApplication::processRequest(const Http::Request &request, const Http::Environment &env)
583 m_currentSession = nullptr;
584 m_request = request;
585 m_env = env;
586 m_params.clear();
588 if (m_request.method == Http::METHOD_GET)
590 for (auto iter = m_request.query.cbegin(); iter != m_request.query.cend(); ++iter)
591 m_params[iter.key()] = QString::fromUtf8(iter.value());
593 else
595 m_params = m_request.posts;
598 // clear response
599 clear();
603 // block suspicious requests
604 if ((m_isCSRFProtectionEnabled && isCrossSiteRequest(m_request))
605 || (m_isHostHeaderValidationEnabled && !validateHostHeader(m_domainList)))
607 throw UnauthorizedHTTPError();
610 // reverse proxy resolve client address
611 m_clientAddress = resolveClientAddress();
613 sessionInitialize();
614 doProcessRequest();
616 catch (const HTTPError &error)
618 status(error.statusCode(), error.statusText());
619 print((!error.message().isEmpty() ? error.message() : error.statusText()), Http::CONTENT_TYPE_TXT);
622 for (const Http::Header &prebuiltHeader : asConst(m_prebuiltHeaders))
623 setHeader(prebuiltHeader);
625 return response();
628 QString WebApplication::clientId() const
630 return m_clientAddress.toString();
633 void WebApplication::sessionInitialize()
635 Q_ASSERT(!m_currentSession);
637 const QString sessionId {parseCookie(m_request.headers.value(u"cookie"_s)).value(m_sessionCookieName)};
639 // TODO: Additional session check
641 if (!sessionId.isEmpty())
643 m_currentSession = m_sessions.value(sessionId);
644 if (m_currentSession)
646 if (m_currentSession->hasExpired(m_sessionTimeout))
648 // session is outdated - removing it
649 delete m_sessions.take(sessionId);
650 m_currentSession = nullptr;
652 else
654 m_currentSession->updateTimestamp();
657 else
659 qDebug() << Q_FUNC_INFO << "session does not exist!";
663 if (!m_currentSession && !isAuthNeeded())
664 sessionStart();
667 QString WebApplication::generateSid() const
669 QString sid;
673 const quint32 tmp[] =
674 {Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand()
675 , Utils::Random::rand(), Utils::Random::rand(), Utils::Random::rand()};
676 sid = QString::fromLatin1(QByteArray::fromRawData(reinterpret_cast<const char *>(tmp), sizeof(tmp)).toBase64());
678 while (m_sessions.contains(sid));
680 return sid;
683 bool WebApplication::isAuthNeeded()
685 if (!m_isLocalAuthEnabled && Utils::Net::isLoopbackAddress(m_clientAddress))
686 return false;
687 if (m_isAuthSubnetWhitelistEnabled && Utils::Net::isIPInSubnets(m_clientAddress, m_authSubnetWhitelist))
688 return false;
689 return true;
692 bool WebApplication::isPublicAPI(const QString &scope, const QString &action) const
694 return m_publicAPIs.contains(u"%1/%2"_s.arg(scope, action));
697 void WebApplication::sessionStart()
699 Q_ASSERT(!m_currentSession);
701 // remove outdated sessions
702 Algorithm::removeIf(m_sessions, [this](const QString &, const WebSession *session)
704 if (session->hasExpired(m_sessionTimeout))
706 delete session;
707 return true;
710 return false;
713 m_currentSession = new WebSession(generateSid(), app());
714 m_sessions[m_currentSession->id()] = m_currentSession;
716 m_currentSession->registerAPIController<AppController>(u"app"_s);
717 m_currentSession->registerAPIController<LogController>(u"log"_s);
718 m_currentSession->registerAPIController<RSSController>(u"rss"_s);
719 m_currentSession->registerAPIController<SearchController>(u"search"_s);
720 m_currentSession->registerAPIController<TorrentsController>(u"torrents"_s);
721 m_currentSession->registerAPIController<TransferController>(u"transfer"_s);
723 auto *syncController = m_currentSession->registerAPIController<SyncController>(u"sync"_s);
724 syncController->updateFreeDiskSpace(m_freeDiskSpaceChecker->lastResult());
725 connect(m_freeDiskSpaceChecker, &FreeDiskSpaceChecker::checked, syncController, &SyncController::updateFreeDiskSpace);
727 QNetworkCookie cookie {m_sessionCookieName.toLatin1(), m_currentSession->id().toUtf8()};
728 cookie.setHttpOnly(true);
729 cookie.setSecure(m_isSecureCookieEnabled && m_isHttpsEnabled);
730 cookie.setPath(u"/"_s);
731 QByteArray cookieRawForm = cookie.toRawForm();
732 if (m_isCSRFProtectionEnabled)
733 cookieRawForm.append("; SameSite=Strict");
734 else if (cookie.isSecure())
735 cookieRawForm.append("; SameSite=None");
736 setHeader({Http::HEADER_SET_COOKIE, QString::fromLatin1(cookieRawForm)});
739 void WebApplication::sessionEnd()
741 Q_ASSERT(m_currentSession);
743 QNetworkCookie cookie {m_sessionCookieName.toLatin1()};
744 cookie.setPath(u"/"_s);
745 cookie.setExpirationDate(QDateTime::currentDateTime().addDays(-1));
747 delete m_sessions.take(m_currentSession->id());
748 m_currentSession = nullptr;
750 setHeader({Http::HEADER_SET_COOKIE, QString::fromLatin1(cookie.toRawForm())});
753 bool WebApplication::isCrossSiteRequest(const Http::Request &request) const
755 // https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF)_Prevention_Cheat_Sheet#Verifying_Same_Origin_with_Standard_Headers
757 const auto isSameOrigin = [](const QUrl &left, const QUrl &right) -> bool
759 // [rfc6454] 5. Comparing Origins
760 return ((left.port() == right.port())
761 // && (left.scheme() == right.scheme()) // not present in this context
762 && (left.host() == right.host()));
765 const QString targetOrigin = request.headers.value(Http::HEADER_X_FORWARDED_HOST, request.headers.value(Http::HEADER_HOST));
766 const QString originValue = request.headers.value(Http::HEADER_ORIGIN);
767 const QString refererValue = request.headers.value(Http::HEADER_REFERER);
769 if (originValue.isEmpty() && refererValue.isEmpty())
771 // owasp.org recommends to block this request, but doing so will inevitably lead Web API users to spoof headers
772 // so lets be permissive here
773 return false;
776 // sent with CORS requests, as well as with POST requests
777 if (!originValue.isEmpty())
779 const bool isInvalid = !isSameOrigin(urlFromHostHeader(targetOrigin), originValue);
780 if (isInvalid)
782 LogMsg(tr("WebUI: Origin header & Target origin mismatch! Source IP: '%1'. Origin header: '%2'. Target origin: '%3'")
783 .arg(m_env.clientAddress.toString(), originValue, targetOrigin)
784 , Log::WARNING);
786 return isInvalid;
789 if (!refererValue.isEmpty())
791 const bool isInvalid = !isSameOrigin(urlFromHostHeader(targetOrigin), refererValue);
792 if (isInvalid)
794 LogMsg(tr("WebUI: Referer header & Target origin mismatch! Source IP: '%1'. Referer header: '%2'. Target origin: '%3'")
795 .arg(m_env.clientAddress.toString(), refererValue, targetOrigin)
796 , Log::WARNING);
798 return isInvalid;
801 return true;
804 bool WebApplication::validateHostHeader(const QStringList &domains) const
806 const QUrl hostHeader = urlFromHostHeader(m_request.headers[Http::HEADER_HOST]);
807 const QString requestHost = hostHeader.host();
809 // (if present) try matching host header's port with local port
810 const int requestPort = hostHeader.port();
811 if ((requestPort != -1) && (m_env.localPort != requestPort))
813 LogMsg(tr("WebUI: Invalid Host header, port mismatch. Request source IP: '%1'. Server port: '%2'. Received Host header: '%3'")
814 .arg(m_env.clientAddress.toString()).arg(m_env.localPort)
815 .arg(m_request.headers[Http::HEADER_HOST])
816 , Log::WARNING);
817 return false;
820 // try matching host header with local address
821 const bool sameAddr = m_env.localAddress.isEqual(QHostAddress(requestHost));
823 if (sameAddr)
824 return true;
826 // try matching host header with domain list
827 for (const auto &domain : domains)
829 const QRegularExpression domainRegex {Utils::String::wildcardToRegexPattern(domain), QRegularExpression::CaseInsensitiveOption};
830 if (requestHost.contains(domainRegex))
831 return true;
834 LogMsg(tr("WebUI: Invalid Host header. Request source IP: '%1'. Received Host header: '%2'")
835 .arg(m_env.clientAddress.toString(), m_request.headers[Http::HEADER_HOST])
836 , Log::WARNING);
837 return false;
840 QHostAddress WebApplication::resolveClientAddress() const
842 if (!m_isReverseProxySupportEnabled)
843 return m_env.clientAddress;
845 // Only reverse proxy can overwrite client address
846 if (!Utils::Net::isIPInSubnets(m_env.clientAddress, m_trustedReverseProxyList))
847 return m_env.clientAddress;
849 const QString forwardedFor = m_request.headers.value(Http::HEADER_X_FORWARDED_FOR);
851 if (!forwardedFor.isEmpty())
853 // client address is the 1st global IP in X-Forwarded-For or, if none available, the 1st IP in the list
854 const QStringList remoteIpList = forwardedFor.split(u',', Qt::SkipEmptyParts);
856 if (!remoteIpList.isEmpty())
858 QHostAddress clientAddress;
860 for (const QString &remoteIp : remoteIpList)
862 if (clientAddress.setAddress(remoteIp) && clientAddress.isGlobal())
863 return clientAddress;
866 if (clientAddress.setAddress(remoteIpList[0]))
867 return clientAddress;
871 return m_env.clientAddress;
874 // WebSession
876 WebSession::WebSession(const QString &sid, IApplication *app)
877 : ApplicationComponent(app)
878 , m_sid {sid}
880 updateTimestamp();
883 QString WebSession::id() const
885 return m_sid;
888 bool WebSession::hasExpired(const qint64 seconds) const
890 if (seconds <= 0)
891 return false;
892 return m_timer.hasExpired(seconds * 1000);
895 void WebSession::updateTimestamp()
897 m_timer.start();
900 APIController *WebSession::getAPIController(const QString &scope) const
902 return m_apiControllers.value(scope);