-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
Expand file tree
/
Copy pathconfighttp.cpp
More file actions
2267 lines (1961 loc) · 77.4 KB
/
Copy pathconfighttp.cpp
File metadata and controls
2267 lines (1961 loc) · 77.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file src/confighttp.cpp
* @brief Definitions for the Web UI Config HTTP server.
*
* @todo Authentication, better handling of routes common to nvhttp, cleanup
*/
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
// standard includes
#include <algorithm>
#include <charconv>
#include <filesystem>
#include <format>
#include <fstream>
#include <new>
#include <optional>
#include <string_view>
#include <utility>
#include <vector>
// lib includes
#include <boost/algorithm/string.hpp>
#include <boost/asio/ssl/context.hpp>
#include <boost/filesystem.hpp>
#include <lizardbyte/common/env.h>
#include <nlohmann/json.hpp>
#include <Simple-Web-Server/crypto.hpp>
#include <Simple-Web-Server/server_https.hpp>
#ifdef _WIN32
#include "platform/virtualhid_input.h"
#include "platform/windows/misc.h"
#include "platform/windows/utf_utils.h"
#include <Windows.h>
#endif
// local includes
#include "config.h"
#include "confighttp.h"
#include "crypto.h"
#include "display_device.h"
#include "file_handler.h"
#include "globals.h"
#include "httpcommon.h"
#include "input.h"
#include "logging.h"
#include "network.h"
#include "nvhttp.h"
#include "platform/common.h"
#include "process.h"
#include "rtsp.h"
#include "system_tray.h"
#include "utility.h"
#include "uuid.h"
using namespace std::literals;
namespace confighttp {
namespace fs = std::filesystem;
/**
* @brief HTTPS server type used for Sunshine's configuration UI.
*/
using https_server_t = SimpleWeb::Server<SimpleWeb::HTTPS>;
/**
* @brief Case-insensitive map used for HTTP headers and query parameters.
*/
using args_t = SimpleWeb::CaseInsensitiveMultimap;
/**
* @brief Shared HTTPS response object passed to configuration handlers.
*/
using resp_https_t = std::shared_ptr<SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Response>;
/**
* @brief Shared HTTPS request object received by configuration handlers.
*/
using req_https_t = std::shared_ptr<SimpleWeb::ServerBase<SimpleWeb::HTTPS>::Request>;
/**
* @brief Handler signature for configuration UI HTTPS routes.
*/
using https_handler_t = std::function<void(resp_https_t, req_https_t)>;
namespace {
using license_status_provider_t = std::function<lvh::LicenseResult()>; ///< Provider for the current libvirtualhid license status.
/**
* @brief Return the current libvirtualhid license status provider.
*
* Unit-test builds expose a mutable provider so the HTTP fixture can avoid
* contacting an installed Windows broker. Production builds keep the
* provider const and always call libvirtualhid directly.
*
* @return License status provider for the current build.
*/
auto &virtual_input_license_status_provider() {
#ifdef SUNSHINE_TESTS
static license_status_provider_t status_provider = lvh::get_license_status;
#else
static const license_status_provider_t status_provider = lvh::get_license_status;
#endif
return status_provider;
}
} // namespace
/**
* @brief Client certificate operations accepted by the configuration API.
*/
enum class op_e {
ADD, ///< Add client
REMOVE ///< Remove client
};
/**
* @brief Overwrite a request-local sensitive string when leaving scope.
*/
class scoped_sensitive_string_clear_t {
public:
/**
* @brief Register a sensitive string for best-effort clearing.
*
* @param value Mutable sensitive string.
*/
explicit scoped_sensitive_string_clear_t(std::string &value):
value_ {value} {}
scoped_sensitive_string_clear_t(const scoped_sensitive_string_clear_t &) = delete;
scoped_sensitive_string_clear_t &operator=(const scoped_sensitive_string_clear_t &) = delete;
/**
* @brief Overwrite and clear the registered string.
*/
~scoped_sensitive_string_clear_t() {
std::fill(value_.begin(), value_.end(), '\0');
value_.clear();
}
private:
std::string &value_; ///< Sensitive request-local string.
};
#ifdef SUNSHINE_TESTS
void set_virtual_input_license_status_provider_for_testing(virtual_input_license_status_provider_t status_provider) {
virtual_input_license_status_provider() = std::move(status_provider);
}
void reset_virtual_input_license_status_provider_for_testing() {
virtual_input_license_status_provider() = lvh::get_license_status;
}
void clear_sensitive_string_for_testing(std::string &value) {
const scoped_sensitive_string_clear_t clear_value {value};
}
#endif
// CSRF token management
/**
* @brief CSRF token value and its expiration deadline.
*/
struct csrf_token_t {
std::string token; ///< Random token value that must be echoed by the client.
std::chrono::steady_clock::time_point expiration; ///< Monotonic deadline after which the token is rejected.
};
std::map<std::string, csrf_token_t, std::less<>> csrf_tokens; ///< CSRF tokens by client identifier. NOSONAR(cpp:S5421) - intentionally mutable global
std::mutex csrf_tokens_mutex; ///< Mutex protecting CSRF token storage. NOSONAR(cpp:S5421) - intentionally mutable global
// CSRF token configuration
/**
* @brief Number of random bytes used when generating a CSRF token.
*/
constexpr auto CSRF_TOKEN_SIZE = 32; // 32 bytes = 256 bits
/**
* @brief Amount of time a generated CSRF token remains valid.
*/
constexpr auto CSRF_TOKEN_LIFETIME = std::chrono::hours(1); // Tokens valid for 1 hour
constexpr auto LIBVIRTUALHID_MINIMUM_VERSION = "2026.826.2024.22"sv; ///< Minimum supported libvirtualhid driver version. // NOSONAR(cpp:S1313): not an IP address
constexpr auto VIGEMBUS_MINIMUM_VERSION = "1.17.0.0"sv; ///< Minimum supported ViGEmBus fallback driver version. // NOSONAR(cpp:S1313): not an IP address
/**
* @brief Parse one dotted driver-version component.
*
* @param part Version component text.
* @return Parsed component value, or empty when invalid.
*/
std::optional<unsigned int> parse_driver_version_part(std::string_view part) {
if (part.empty()) {
return std::nullopt;
}
unsigned int value = 0;
const auto *begin = part.data();
const auto *end = part.data() + part.size();
const auto [ptr, ec] = std::from_chars(begin, end, value);
if (ec != std::errc {} || ptr != end) {
return std::nullopt;
}
return value;
}
/**
* @brief Parse a dotted driver version into numeric components.
*
* @param version Driver version text.
* @return Parsed version parts, or empty when invalid.
*/
std::optional<std::vector<unsigned int>> parse_driver_version(std::string_view version) {
if (version.empty()) {
return std::nullopt;
}
std::vector<unsigned int> parts;
std::size_t start = 0;
while (start <= version.size()) {
const auto dot = version.find('.', start);
const auto length = dot == std::string_view::npos ? std::string_view::npos : dot - start;
const auto part = parse_driver_version_part(version.substr(start, length));
if (!part.has_value()) {
return std::nullopt;
}
parts.push_back(*part);
if (dot == std::string_view::npos) {
break;
}
start = dot + 1;
}
return parts;
}
bool is_driver_version_supported(std::string_view version, std::string_view minimum_version) {
if (minimum_version.empty()) {
return true;
}
const auto version_parts = parse_driver_version(version);
const auto minimum_parts = parse_driver_version(minimum_version);
if (!version_parts || !minimum_parts) {
return false;
}
if (version_parts->size() >= 3U && (*version_parts)[0] == 0U && (*version_parts)[1] == 0U && (*version_parts)[2] == 0U) {
return true;
}
const auto part_count = std::max(version_parts->size(), minimum_parts->size());
for (std::size_t i = 0; i < part_count; ++i) {
const auto version_part = i < version_parts->size() ? (*version_parts)[i] : 0U;
const auto minimum_part = i < minimum_parts->size() ? (*minimum_parts)[i] : 0U;
if (version_part != minimum_part) {
return version_part > minimum_part;
}
}
return true;
}
nlohmann::json build_driver_status(bool installed, const std::string &version, std::string_view minimum_version) {
const auto minimum_version_text = std::string {minimum_version};
nlohmann::json output_tree;
output_tree["installed"] = installed;
output_tree["version"] = version;
output_tree["minimum_version"] = minimum_version_text;
output_tree["supported_versions"] = minimum_version.empty() ? "Any" : std::format(">= {}", minimum_version_text);
output_tree["version_compatible"] = installed && is_driver_version_supported(version, minimum_version);
return output_tree;
}
/**
* @brief Return a stable Web UI name for a libvirtualhid license state.
*
* @param state License state.
* @return Lowercase state name.
*/
std::string_view virtualhid_license_state_name(lvh::LicenseState state) {
using enum lvh::LicenseState;
switch (state) {
case unlicensed:
return "unlicensed";
case licensed:
return "licensed";
case expired:
return "expired";
case disabled:
return "disabled";
case invalid:
return "invalid";
case unavailable:
default:
return "unavailable";
}
}
nlohmann::json build_virtualhid_license_status(const lvh::LicenseResult &result) {
const auto &license = result.license;
nlohmann::json output_tree;
output_tree["operation_ok"] = result.status.ok();
output_tree["service_available"] = license.service_available;
output_tree["state"] = virtualhid_license_state_name(license.state);
output_tree["licensed"] = license.licensed();
output_tree["active_devices"] = license.active_devices;
output_tree["activation_limit"] = license.activation_limit;
output_tree["activation_usage"] = license.activation_usage;
output_tree["plan_name"] = license.plan_name;
output_tree["customer_email"] = license.customer_email;
output_tree["message"] = license.message;
output_tree["purchase_url"] = license.purchase_url;
output_tree["manage_account_url"] = license.manage_account_url;
output_tree["error"] = result.status.ok() ? "" : result.status.message();
return output_tree;
}
namespace {
/**
* @brief Handle a virtual-input license request using the configured status provider.
*
* @param response HTTP response object.
* @param request Authenticated HTTP request.
*/
void get_virtual_input_license(const resp_https_t &response, const req_https_t &request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
send_response(response, build_virtualhid_license_status(virtual_input_license_status_provider()()));
}
} // namespace
#ifdef _WIN32
/**
* @brief RAII wrapper for a Windows registry key handle.
*/
class registry_key_t {
public:
/**
* @brief Construct an empty registry key wrapper.
*/
registry_key_t() = default;
/**
* @brief Copy construction is disabled because the wrapper owns a handle.
*/
registry_key_t(const registry_key_t &) = delete;
/**
* @brief Copy assignment is disabled because the wrapper owns a handle.
*
* @return This registry key wrapper.
*/
registry_key_t &operator=(const registry_key_t &) = delete;
/**
* @brief Close the owned registry key handle.
*/
~registry_key_t() {
close();
}
/**
* @brief Get the owned registry key handle.
*
* @return Registry key handle.
*/
HKEY get() const {
return handle;
}
/**
* @brief Prepare the wrapper to receive a registry key handle.
*
* @return Address of the wrapped handle.
*/
HKEY *put() {
close();
return &handle;
}
private:
/**
* @brief Close the owned registry key handle if one is open.
*/
void close() {
if (handle) {
RegCloseKey(handle);
handle = nullptr;
}
}
HKEY handle = nullptr; ///< Owned Windows registry key handle.
};
/**
* @brief Read a string value from a Windows registry key.
*
* @param key Registry key to query.
* @param value_name Registry value name.
* @return Registry string value, or empty when unavailable.
*/
std::optional<std::wstring> read_registry_string_value(HKEY key, const wchar_t *value_name) {
DWORD value_type = 0;
DWORD value_size = 0;
if (RegGetValueW(key, nullptr, value_name, RRF_RT_REG_SZ, &value_type, nullptr, &value_size) != ERROR_SUCCESS || value_size == 0) {
return std::nullopt;
}
std::wstring value(value_size / sizeof(wchar_t), L'\0');
if (RegGetValueW(key, nullptr, value_name, RRF_RT_REG_SZ, &value_type, value.data(), &value_size) != ERROR_SUCCESS) {
return std::nullopt;
}
while (!value.empty() && value.back() == L'\0') {
value.pop_back();
}
return value;
}
/**
* @brief Read the installed libvirtualhid driver version from the Windows device registry.
*
* @return Driver version string, or empty when unavailable.
*/
std::string read_libvirtualhid_driver_version() {
registry_key_t root_key;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Enum\\ROOT\\LIBVIRTUALHID", 0, KEY_READ, root_key.put()) != ERROR_SUCCESS) {
return {};
}
for (DWORD index = 0;; ++index) {
std::wstring subkey_name(256, L'\0');
auto subkey_name_size = static_cast<DWORD>(subkey_name.size());
const auto enum_status = RegEnumKeyExW(root_key.get(), index, subkey_name.data(), &subkey_name_size, nullptr, nullptr, nullptr, nullptr);
if (enum_status == ERROR_NO_MORE_ITEMS) {
break;
}
if (enum_status != ERROR_SUCCESS) {
continue;
}
std::wstring device_key_path = L"SYSTEM\\CurrentControlSet\\Enum\\ROOT\\LIBVIRTUALHID\\";
device_key_path.append(subkey_name, 0, subkey_name_size);
registry_key_t device_key;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, device_key_path.c_str(), 0, KEY_READ, device_key.put()) != ERROR_SUCCESS) {
continue;
}
const auto driver_key_suffix = read_registry_string_value(device_key.get(), L"Driver");
if (!driver_key_suffix) {
continue;
}
std::wstring driver_key_path = L"SYSTEM\\CurrentControlSet\\Control\\Class\\";
driver_key_path += *driver_key_suffix;
registry_key_t driver_key;
if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, driver_key_path.c_str(), 0, KEY_READ, driver_key.put()) != ERROR_SUCCESS) {
continue;
}
if (const auto version = read_registry_string_value(driver_key.get(), L"DriverVersion")) {
return utf_utils::to_utf8(*version);
}
}
return {};
}
#endif
/**
* @brief Log the request details.
* @param request The HTTP request object.
*/
void print_req(const req_https_t &request) {
BOOST_LOG(debug) << "METHOD :: "sv << request->method;
BOOST_LOG(debug) << "DESTINATION :: "sv << request->path;
for (auto &[name, val] : request->header) {
BOOST_LOG(debug) << name << " -- " << (name == "Authorization" ? "CREDENTIALS REDACTED" : val);
}
BOOST_LOG(debug) << " [--] "sv;
for (auto &[name, val] : request->parse_query_string()) {
BOOST_LOG(debug) << name << " -- " << val;
}
BOOST_LOG(debug) << " [--] "sv;
}
/**
* @brief Send a response.
* @param response The HTTP response object.
* @param output_tree The JSON tree to send.
*/
void send_response(const resp_https_t &response, const nlohmann::json &output_tree) {
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "application/json");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(output_tree.dump(), headers);
}
/**
* @brief Send a 401 Unauthorized response.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void send_unauthorized(const resp_https_t &response, const req_https_t &request) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(info) << "Web UI: ["sv << address << "] -- not authorized"sv;
constexpr auto code = SimpleWeb::StatusCode::client_error_unauthorized;
nlohmann::json tree;
tree["status_code"] = code;
tree["status"] = false;
tree["error"] = "Unauthorized";
const SimpleWeb::CaseInsensitiveMultimap headers {
{"Content-Type", "application/json"},
{"WWW-Authenticate", R"(Basic realm="Sunshine Gamestream Host", charset="UTF-8")"},
{"X-Frame-Options", "DENY"},
{"Content-Security-Policy", "frame-ancestors 'none';"}
};
response->write(code, tree.dump(), headers);
}
/**
* @brief Send a redirect response.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param path The path to redirect to.
*/
void send_redirect(const resp_https_t &response, const req_https_t &request, const char *path) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(info) << "Web UI: ["sv << address << "] -- not authorized"sv;
const SimpleWeb::CaseInsensitiveMultimap headers {
{"Location", path},
{"X-Frame-Options", "DENY"},
{"Content-Security-Policy", "frame-ancestors 'none';"}
};
response->write(SimpleWeb::StatusCode::redirection_temporary_redirect, headers);
}
/**
* @brief Authenticate the user.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @return True if the user is authenticated, false otherwise.
*/
bool authenticate(const resp_https_t &response, const req_https_t &request) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
if (const auto ip_type = net::from_address(address); ip_type > http::origin_web_ui_allowed) {
BOOST_LOG(info) << "Web UI: ["sv << address << "] -- denied"sv;
response->write(SimpleWeb::StatusCode::client_error_forbidden);
return false;
}
// If credentials are shown, redirect the user to a /welcome page
if (config::sunshine.username.empty()) {
send_redirect(response, request, "/welcome");
return false;
}
auto fg = util::fail_guard([&]() {
send_unauthorized(response, request);
});
const auto auth = request->header.find("authorization");
if (auth == request->header.end()) {
return false;
}
const auto &rawAuth = auth->second;
auto authData = SimpleWeb::Crypto::Base64::decode(rawAuth.substr("Basic "sv.length()));
const auto index = static_cast<int>(authData.find(':'));
if (index >= authData.size() - 1) {
return false;
}
const auto username = authData.substr(0, index);
const auto password = authData.substr(index + 1);
if (const auto hash = util::hex(crypto::hash(password + config::sunshine.salt)).to_string(); !boost::iequals(username, config::sunshine.username) || hash != config::sunshine.password) {
return false;
}
fg.disable();
return true;
}
/**
* @brief Send a 404 Not Found response.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param error_message The error message to include in the response.
*/
void not_found(const resp_https_t &response, [[maybe_unused]] const req_https_t &request, const std::string &error_message) {
constexpr auto code = SimpleWeb::StatusCode::client_error_not_found;
nlohmann::json tree;
tree["status_code"] = code;
tree["error"] = error_message;
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "application/json");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(code, tree.dump(), headers);
}
/**
* @brief Send a 400 Bad Request response.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param error_message The error message to include in the response.
*/
void bad_request(const resp_https_t &response, [[maybe_unused]] const req_https_t &request, const std::string &error_message) {
constexpr auto code = SimpleWeb::StatusCode::client_error_bad_request;
nlohmann::json tree;
tree["status_code"] = code;
tree["status"] = false;
tree["error"] = error_message;
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "application/json");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(code, tree.dump(), headers);
}
/**
* @brief Validate the request content type and send a bad request when mismatched.
*/
bool check_content_type(const resp_https_t &response, const req_https_t &request, const std::string_view &contentType) {
const auto requestContentType = request->header.find("content-type");
if (requestContentType == request->header.end()) {
bad_request(response, request, "Content type not provided");
return false;
}
// Extract the media type part before any parameters (e.g., charset)
std::string actualContentType = requestContentType->second;
if (const size_t semicolonPos = actualContentType.find(';'); semicolonPos != std::string::npos) {
actualContentType = actualContentType.substr(0, semicolonPos);
}
// Trim whitespace and convert to lowercase for case-insensitive comparison
boost::algorithm::trim(actualContentType);
boost::algorithm::to_lower(actualContentType);
std::string expectedContentType(contentType);
boost::algorithm::to_lower(expectedContentType);
if (actualContentType != expectedContentType) {
bad_request(response, request, "Content type mismatch");
return false;
}
return true;
}
/**
* @brief Get a unique client identifier for CSRF token management.
* @param request The HTTP request object.
* @return A unique identifier based on username or IP address.
*/
std::string get_client_id(const req_https_t &request) {
// Try to use the authenticated username as client ID
if (const auto auth = request->header.find("authorization"); !config::sunshine.username.empty() && auth != request->header.end()) {
if (const auto &rawAuth = auth->second; rawAuth.rfind("Basic "sv, 0) == 0) {
auto authData = SimpleWeb::Crypto::Base64::decode(rawAuth.substr("Basic "sv.length()));
if (const auto index = static_cast<int>(authData.find(':')); index < authData.size() - 1) {
return authData.substr(0, index); // Return username
}
}
}
// Fall back to IP address if no username
return net::addr_to_normalized_string(request->remote_endpoint().address());
}
/**
* @brief Generate a new CSRF token for a client.
* @param client_id A unique identifier for the client (e.g., session ID or username).
* @return The generated CSRF token.
*/
std::string generate_csrf_token(const std::string &client_id) {
// Generate a cryptographically secure random token
std::string token = crypto::rand_alphabet(CSRF_TOKEN_SIZE);
std::scoped_lock lock(csrf_tokens_mutex);
// Clean up expired tokens first
const auto now = std::chrono::steady_clock::now();
std::erase_if(csrf_tokens, [&now](const auto &entry) {
return entry.second.expiration < now;
});
// Store the token with expiration
csrf_tokens[client_id] = csrf_token_t {
token,
now + CSRF_TOKEN_LIFETIME
};
return token;
}
/**
* @brief Validate a stored CSRF token for a client against a provided token string.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param client_id A unique identifier for the client.
* @param provided_token The token string to validate.
* @return True if the token is valid, false otherwise.
*/
bool validate_stored_csrf_token(const resp_https_t &response, const req_https_t &request, const std::string_view client_id, const std::string_view provided_token) {
std::scoped_lock lock(csrf_tokens_mutex);
const auto token_it = csrf_tokens.find(client_id);
if (token_it == csrf_tokens.end()) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF token validation failed: no token found for client"sv;
bad_request(response, request, "Invalid CSRF token");
return false;
}
if (const auto now = std::chrono::steady_clock::now(); token_it->second.expiration < now) {
csrf_tokens.erase(token_it);
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF token validation failed: token expired"sv;
bad_request(response, request, "CSRF token expired");
return false;
}
if (token_it->second.token != provided_token) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF token validation failed: token mismatch"sv;
bad_request(response, request, "Invalid CSRF token");
return false;
}
return true;
}
/**
* @brief Validate CSRF token.
*/
bool validate_csrf_token(const resp_https_t &response, const req_https_t &request, const std::string &client_id) {
// Helper function to check if a URL starts with any allowed origin
auto is_allowed_origin = [](const std::string_view url) {
return std::ranges::any_of(config::sunshine.csrf_allowed_origins, [&url](const std::string &allowed_origin) {
// Ensure exact prefix match (with ":" or "/" after to prevent malicious.com matching allowed.com)
if (url.rfind(allowed_origin, 0) != 0) { // rfind with pos=0 checks if the url starts with allowed_origin
return false;
}
// Check that it's followed by ":" (port) or "/" (path) or is an exact match
const size_t len = allowed_origin.length();
return url.length() == len || url[len] == ':' || url[len] == '/';
});
};
// Check if the request is from the same origin (Origin or Referer header matches configured allowed origins)
const auto origin_it = request->header.find("Origin");
if (origin_it != request->header.end() && is_allowed_origin(origin_it->second)) {
// Same origin request - allow without CSRF token
return true;
}
// If we have a Referer header, check if it's same-origin
const auto referer_it = request->header.find("Referer");
if (referer_it != request->header.end() && is_allowed_origin(referer_it->second)) {
// Same origin request - allow without CSRF token
return true;
}
// If neither Origin nor Referer is present, this cannot be a browser-initiated CSRF attack.
// Non-browser clients (e.g. curl, scripts) never send these headers, and a malicious web page
// cannot cause a non-browser client to make requests on a user's behalf.
if (origin_it == request->header.end() && referer_it == request->header.end()) {
return true;
}
// A browser-like request arrived with an Origin/Referer that doesn't match an allowed origin.
// Require a CSRF token.
const std::string_view blocked_origin = (origin_it != request->header.end()) ? origin_it->second : referer_it->second;
// Extract token from X-CSRF-Token header
const auto header_it = request->header.find("X-CSRF-Token");
if (header_it == request->header.end()) {
// Also check query parameters as fallback
auto query_params = request->parse_query_string();
const auto query_it = query_params.find("csrf_token");
if (query_it == query_params.end()) {
auto address = net::addr_to_normalized_string(request->remote_endpoint().address());
BOOST_LOG(error) << "Web UI: ["sv << address << "] -- CSRF protection blocked request from origin: "sv << blocked_origin;
BOOST_LOG(error) << "Web UI: To allow this origin, add it to the 'csrf_allowed_origins' option in your Sunshine configuration"sv;
bad_request(response, request, "Missing CSRF token");
return false;
}
return validate_stored_csrf_token(response, request, client_id, query_it->second);
}
// Validate token from header
return validate_stored_csrf_token(response, request, client_id, header_it->second);
}
/**
* @brief Validates the application index and sends an error response if invalid.
*/
bool check_app_index(const resp_https_t &response, const req_https_t &request, int index) {
std::string file = file_handler::read_file(config::stream.file_apps.c_str());
nlohmann::json file_tree = nlohmann::json::parse(file);
if (const auto &apps = file_tree["apps"]; index < 0 || index >= static_cast<int>(apps.size())) {
std::string error;
if (const int max_index = static_cast<int>(apps.size()) - 1; max_index < 0) {
error = "No applications found";
} else {
error = std::format("'index' {} out of range, max index is {}", index, max_index);
}
bad_request(response, request, error);
return false;
}
return true;
}
/**
* @brief Get an HTML page.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @param html_file The HTML file to serve (relative to WEB_DIR).
* @param require_auth Whether to require authentication (default: true).
* @param redirect_if_username If true, redirect to "/" when the username is set (for welcome page).
*/
void getPage(const resp_https_t &response, const req_https_t &request, const char *html_file, const bool require_auth, const bool redirect_if_username) {
// Special handling for welcome page: redirect if the username is already set
if (redirect_if_username && !config::sunshine.username.empty()) {
send_redirect(response, request, "/");
return;
}
if (require_auth && !authenticate(response, request)) {
return;
}
print_req(request);
const std::string content = file_handler::read_file((std::string(WEB_DIR) + html_file).c_str());
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "text/html; charset=utf-8");
// prevent click jacking
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(content, headers);
}
/**
* @brief Get the favicon image.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @todo combine function with getSunshineLogoImage and possibly getNodeModules
* @todo use mime_types map
*/
void getFaviconImage(const resp_https_t &response, const req_https_t &request) {
print_req(request);
std::ifstream in(WEB_DIR "images/sunshine.ico", std::ios::binary);
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "image/x-icon");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(SimpleWeb::StatusCode::success_ok, in, headers);
}
/**
* @brief Get the Sunshine logo image.
* @param response The HTTP response object.
* @param request The HTTP request object.
* @todo combine function with getFaviconImage and possibly getNodeModules
* @todo use mime_types map
*/
void getSunshineLogoImage(const resp_https_t &response, const req_https_t &request) {
print_req(request);
std::ifstream in(WEB_DIR "images/logo-sunshine-45.png", std::ios::binary);
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", "image/png");
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
response->write(SimpleWeb::StatusCode::success_ok, in, headers);
}
/**
* @brief Check if a path is a child of another path.
* @param base The base path.
* @param query The path to check.
* @return True if the path is a child of the base path, false otherwise.
*/
bool isChildPath(fs::path const &base, fs::path const &query) {
auto relPath = fs::relative(base, query);
return *(relPath.begin()) != fs::path("..");
}
/**
* @brief Get an asset.
* @param response The HTTP response object.
* @param request The HTTP request object.
*/
void getAsset(const resp_https_t &response, const req_https_t &request) {
print_req(request);
fs::path webDirPath(WEB_DIR);
fs::path nodeModulesPath(webDirPath / "assets");
// .relative_path is needed to shed any leading slash that might exist in the request path
auto filePath = fs::weakly_canonical(webDirPath / fs::path(request->path).relative_path());
// Don't do anything if the file does not exist or is outside the assets directory
if (!isChildPath(filePath, nodeModulesPath)) {
BOOST_LOG(warning) << "Someone requested a path " << filePath << " that is outside the assets folder";
bad_request(response, request);
return;
}
if (!fs::exists(filePath)) {
not_found(response, request);
return;
}
auto relPath = fs::relative(filePath, webDirPath);
// get the mime type from the file extension mime_types map
// remove the leading period from the extension
auto mimeType = mime_types.find(relPath.extension().string().substr(1));
// check if the extension is in the map at the x position
if (mimeType == mime_types.end()) {
bad_request(response, request);
return;
}
// if it is, set the content type to the mime type
SimpleWeb::CaseInsensitiveMultimap headers;
headers.emplace("Content-Type", mimeType->second);
headers.emplace("X-Frame-Options", "DENY");
headers.emplace("Content-Security-Policy", "frame-ancestors 'none';");
std::ifstream in(filePath.string(), std::ios::binary);
response->write(SimpleWeb::StatusCode::success_ok, in, headers);
}
/**
* @brief Get a CSRF token for the authenticated user.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/csrf-token| GET| null}
*/
void getCSRFToken(const resp_https_t &response, const req_https_t &request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
std::string client_id = get_client_id(request);
std::string token = generate_csrf_token(client_id);
nlohmann::json output_tree;
output_tree["csrf_token"] = token;
send_response(response, output_tree);
}
/**
* @brief Get the list of available applications.
* @param response The HTTP response object.
* @param request The HTTP request object.
*
* @api_examples{/api/apps| GET| null}
*/
void getApps(const resp_https_t &response, const req_https_t &request) {
if (!authenticate(response, request)) {
return;
}
print_req(request);
try {
std::string content = file_handler::read_file(config::stream.file_apps.c_str());
nlohmann::json file_tree = nlohmann::json::parse(content);