-
Notifications
You must be signed in to change notification settings - Fork 584
/
Copy pathapilistener.cpp
1977 lines (1542 loc) · 54.6 KB
/
apilistener.cpp
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
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */
#include "remote/apilistener.hpp"
#include "remote/apilistener-ti.cpp"
#include "remote/jsonrpcconnection.hpp"
#include "remote/endpoint.hpp"
#include "remote/jsonrpc.hpp"
#include "remote/apifunction.hpp"
#include "remote/configpackageutility.hpp"
#include "remote/configobjectutility.hpp"
#include "base/atomic-file.hpp"
#include "base/convert.hpp"
#include "base/defer.hpp"
#include "base/io-engine.hpp"
#include "base/netstring.hpp"
#include "base/json.hpp"
#include "base/configtype.hpp"
#include "base/logger.hpp"
#include "base/objectlock.hpp"
#include "base/stdiostream.hpp"
#include "base/perfdatavalue.hpp"
#include "base/application.hpp"
#include "base/context.hpp"
#include "base/statsfunction.hpp"
#include "base/exception.hpp"
#include "base/tcpsocket.hpp"
#include <boost/asio/buffer.hpp>
#include <boost/asio/io_context_strand.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/ssl/context.hpp>
#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/regex.hpp>
#include <boost/system/error_code.hpp>
#include <boost/thread/locks.hpp>
#include <climits>
#include <cstdint>
#include <fstream>
#include <memory>
#include <openssl/ssl.h>
#include <openssl/tls1.h>
#include <openssl/x509.h>
#include <sstream>
#include <utility>
using namespace icinga;
REGISTER_TYPE(ApiListener);
boost::signals2::signal<void(bool)> ApiListener::OnMasterChanged;
ApiListener::Ptr ApiListener::m_Instance;
REGISTER_STATSFUNCTION(ApiListener, &ApiListener::StatsFunc);
REGISTER_APIFUNCTION(Hello, icinga, &ApiListener::HelloAPIHandler);
ApiListener::ApiListener()
{
m_RelayQueue.SetName("ApiListener, RelayQueue");
m_SyncQueue.SetName("ApiListener, SyncQueue");
}
String ApiListener::GetApiDir()
{
return Configuration::DataDir + "/api/";
}
String ApiListener::GetApiZonesDir()
{
return GetApiDir() + "zones/";
}
String ApiListener::GetApiZonesStageDir()
{
return GetApiDir() + "zones-stage/";
}
String ApiListener::GetCertsDir()
{
return Configuration::DataDir + "/certs/";
}
String ApiListener::GetCaDir()
{
return Configuration::DataDir + "/ca/";
}
String ApiListener::GetCertificateRequestsDir()
{
return Configuration::DataDir + "/certificate-requests/";
}
String ApiListener::GetDefaultCertPath()
{
return GetCertsDir() + "/" + ScriptGlobal::Get("NodeName") + ".crt";
}
String ApiListener::GetDefaultKeyPath()
{
return GetCertsDir() + "/" + ScriptGlobal::Get("NodeName") + ".key";
}
String ApiListener::GetDefaultCaPath()
{
return GetCertsDir() + "/ca.crt";
}
double ApiListener::GetTlsHandshakeTimeout() const
{
return Configuration::TlsHandshakeTimeout;
}
void ApiListener::SetTlsHandshakeTimeout(double value, bool suppress_events, const Value& cookie)
{
Configuration::TlsHandshakeTimeout = value;
}
void ApiListener::CopyCertificateFile(const String& oldCertPath, const String& newCertPath)
{
struct stat st1, st2;
if (!oldCertPath.IsEmpty() && stat(oldCertPath.CStr(), &st1) >= 0 && (stat(newCertPath.CStr(), &st2) < 0 || st1.st_mtime > st2.st_mtime)) {
Log(LogWarning, "ApiListener")
<< "Copying '" << oldCertPath << "' certificate file to '" << newCertPath << "'";
Utility::MkDirP(Utility::DirName(newCertPath), 0700);
Utility::CopyFile(oldCertPath, newCertPath);
}
}
void ApiListener::OnConfigLoaded()
{
if (m_Instance)
BOOST_THROW_EXCEPTION(ScriptError("Only one ApiListener object is allowed.", GetDebugInfo()));
m_Instance = this;
String defaultCertPath = GetDefaultCertPath();
String defaultKeyPath = GetDefaultKeyPath();
String defaultCaPath = GetDefaultCaPath();
/* Migrate certificate location < 2.8 to the new default path. */
String oldCertPath = GetCertPath();
String oldKeyPath = GetKeyPath();
String oldCaPath = GetCaPath();
CopyCertificateFile(oldCertPath, defaultCertPath);
CopyCertificateFile(oldKeyPath, defaultKeyPath);
CopyCertificateFile(oldCaPath, defaultCaPath);
if (!oldCertPath.IsEmpty() && !oldKeyPath.IsEmpty() && !oldCaPath.IsEmpty()) {
Log(LogWarning, "ApiListener", "Please read the upgrading documentation for v2.8: https://icinga.com/docs/icinga2/latest/doc/16-upgrading-icinga-2/");
}
/* Create the internal API object storage. */
ConfigObjectUtility::CreateStorage();
/* Cache API packages and their active stage name. */
UpdateActivePackageStagesCache();
/* set up SSL context */
std::shared_ptr<X509> cert;
try {
cert = GetX509Certificate(defaultCertPath);
} catch (const std::exception&) {
BOOST_THROW_EXCEPTION(ScriptError("Cannot get certificate from cert path: '"
+ defaultCertPath + "'.", GetDebugInfo()));
}
try {
SetIdentity(GetCertificateCN(cert));
} catch (const std::exception&) {
BOOST_THROW_EXCEPTION(ScriptError("Cannot get certificate common name from cert path: '"
+ defaultCertPath + "'.", GetDebugInfo()));
}
Log(LogInformation, "ApiListener")
<< "My API identity: " << GetIdentity();
UpdateSSLContext();
}
std::shared_ptr<X509> ApiListener::RenewCert(const std::shared_ptr<X509>& cert, bool ca)
{
std::shared_ptr<EVP_PKEY> pubkey (X509_get_pubkey(cert.get()), EVP_PKEY_free);
auto subject (X509_get_subject_name(cert.get()));
auto cacert (GetX509Certificate(GetDefaultCaPath()));
auto newcert (CreateCertIcingaCA(pubkey.get(), subject, ca));
/* verify that the new cert matches the CA we're using for the ApiListener;
* this ensures that the CA we have in /var/lib/icinga2/ca matches the one
* we're using for cluster connections (there's no point in sending a client
* a certificate it wouldn't be able to use to connect to us anyway) */
try {
if (!VerifyCertificate(cacert, newcert, GetCrlPath())) {
Log(LogWarning, "ApiListener")
<< "The CA in '" << GetDefaultCaPath() << "' does not match the CA which Icinga uses "
<< "for its own cluster connections. This is most likely a configuration problem.";
return nullptr;
}
} catch (const std::exception&) { } /* Swallow the exception on purpose, cacert will never be a non-CA certificate. */
return newcert;
}
void ApiListener::UpdateSSLContext()
{
auto ctx (SetupSslContext(GetDefaultCertPath(), GetDefaultKeyPath(), GetDefaultCaPath(), GetCrlPath(), GetCipherList(), GetTlsProtocolmin(), GetDebugInfo()));
{
boost::unique_lock<decltype(m_SSLContextMutex)> lock (m_SSLContextMutex);
m_SSLContext = std::move(ctx);
}
for (const Endpoint::Ptr& endpoint : ConfigType::GetObjectsByType<Endpoint>()) {
for (const JsonRpcConnection::Ptr& client : endpoint->GetClients()) {
client->Disconnect();
}
}
for (const JsonRpcConnection::Ptr& client : m_AnonymousClients) {
client->Disconnect();
}
}
void ApiListener::OnAllConfigLoaded()
{
m_LocalEndpoint = Endpoint::GetByName(GetIdentity());
if (!m_LocalEndpoint)
BOOST_THROW_EXCEPTION(ScriptError("Endpoint object for '" + GetIdentity() + "' is missing.", GetDebugInfo()));
}
/**
* Starts the component.
*/
void ApiListener::Start(bool runtimeCreated)
{
Log(LogInformation, "ApiListener")
<< "'" << GetName() << "' started.";
SyncLocalZoneDirs();
m_RenewOwnCertTimer = Timer::Create();
if (Utility::PathExists(GetIcingaCADir() + "/ca.key")) {
RenewOwnCert();
RenewCA();
m_RenewOwnCertTimer->OnTimerExpired.connect([this](const Timer * const&) {
RenewOwnCert();
RenewCA();
});
} else {
m_RenewOwnCertTimer->OnTimerExpired.connect([this](const Timer * const&) {
JsonRpcConnection::SendCertificateRequest(nullptr, nullptr, String());
});
}
m_RenewOwnCertTimer->SetInterval(RENEW_INTERVAL);
m_RenewOwnCertTimer->Start();
ObjectImpl<ApiListener>::Start(runtimeCreated);
{
std::unique_lock<std::mutex> lock(m_LogLock);
OpenLogFile();
}
/* create the primary JSON-RPC listener */
if (!AddListener(GetBindHost(), GetBindPort())) {
Log(LogCritical, "ApiListener")
<< "Cannot add listener on host '" << GetBindHost() << "' for port '" << GetBindPort() << "'.";
Application::Exit(EXIT_FAILURE);
}
m_Timer = Timer::Create();
m_Timer->OnTimerExpired.connect([this](const Timer * const&) { ApiTimerHandler(); });
m_Timer->SetInterval(5);
m_Timer->Start();
m_Timer->Reschedule(0);
m_ReconnectTimer = Timer::Create();
m_ReconnectTimer->OnTimerExpired.connect([this](const Timer * const&) { ApiReconnectTimerHandler(); });
m_ReconnectTimer->SetInterval(10);
m_ReconnectTimer->Start();
m_ReconnectTimer->Reschedule(0);
/* Keep this in relative sync with the cold startup in UpdateObjectAuthority() and the reconnect interval above.
* Previous: 60s reconnect, 30s OA, 60s cold startup.
* Now: 10s reconnect, 10s OA, 30s cold startup.
*/
m_AuthorityTimer = Timer::Create();
m_AuthorityTimer->OnTimerExpired.connect([](const Timer * const&) { UpdateObjectAuthority(); });
m_AuthorityTimer->SetInterval(10);
m_AuthorityTimer->Start();
m_CleanupCertificateRequestsTimer = Timer::Create();
m_CleanupCertificateRequestsTimer->OnTimerExpired.connect([this](const Timer * const&) { CleanupCertificateRequestsTimerHandler(); });
m_CleanupCertificateRequestsTimer->SetInterval(3600);
m_CleanupCertificateRequestsTimer->Start();
m_CleanupCertificateRequestsTimer->Reschedule(0);
m_ApiPackageIntegrityTimer = Timer::Create();
m_ApiPackageIntegrityTimer->OnTimerExpired.connect([this](const Timer * const&) { CheckApiPackageIntegrity(); });
m_ApiPackageIntegrityTimer->SetInterval(300);
m_ApiPackageIntegrityTimer->Start();
OnMasterChanged(true);
}
void ApiListener::RenewOwnCert()
{
auto certPath (GetDefaultCertPath());
auto cert (GetX509Certificate(certPath));
if (IsCertUptodate(cert)) {
return;
}
Log(LogInformation, "ApiListener")
<< "Our certificate will expire soon, but we own the CA. Renewing.";
cert = RenewCert(cert);
if (!cert) {
return;
}
AtomicFile::Write(certPath, 0644, CertificateToString(cert));
UpdateSSLContext();
}
void ApiListener::RenewCA()
{
auto certPath (GetCaDir() + "/ca.crt");
auto cert (GetX509Certificate(certPath));
if (IsCaUptodate(cert.get())) {
return;
}
Log(LogInformation, "ApiListener")
<< "Our CA will expire soon, but we own it. Renewing.";
cert = RenewCert(cert, true);
if (!cert) {
return;
}
auto certStr (CertificateToString(cert));
AtomicFile::Write(GetDefaultCaPath(), 0644, certStr);
AtomicFile::Write(certPath, 0644, certStr);
UpdateSSLContext();
}
void ApiListener::Stop(bool runtimeDeleted)
{
m_ApiPackageIntegrityTimer->Stop(true);
m_CleanupCertificateRequestsTimer->Stop(true);
m_AuthorityTimer->Stop(true);
m_ReconnectTimer->Stop(true);
m_Timer->Stop(true);
m_RenewOwnCertTimer->Stop(true);
ObjectImpl<ApiListener>::Stop(runtimeDeleted);
Log(LogInformation, "ApiListener")
<< "'" << GetName() << "' stopped.";
{
std::unique_lock<std::mutex> lock(m_LogLock);
CloseLogFile();
RotateLogFile();
}
RemoveStatusFile();
}
ApiListener::Ptr ApiListener::GetInstance()
{
return m_Instance;
}
Endpoint::Ptr ApiListener::GetMaster() const
{
Zone::Ptr zone = Zone::GetLocalZone();
if (!zone)
return nullptr;
std::vector<String> names;
for (const Endpoint::Ptr& endpoint : zone->GetEndpoints())
if (endpoint->GetConnected() || endpoint->GetName() == GetIdentity())
names.push_back(endpoint->GetName());
std::sort(names.begin(), names.end());
return Endpoint::GetByName(*names.begin());
}
bool ApiListener::IsMaster() const
{
Endpoint::Ptr master = GetMaster();
if (!master)
return false;
return master == GetLocalEndpoint();
}
/**
* Creates a new JSON-RPC listener on the specified port.
*
* @param node The host the listener should be bound to.
* @param service The port to listen on.
*/
bool ApiListener::AddListener(const String& node, const String& service)
{
namespace asio = boost::asio;
namespace ip = asio::ip;
using ip::tcp;
ObjectLock olock(this);
if (!m_SSLContext) {
Log(LogCritical, "ApiListener", "SSL context is required for AddListener()");
return false;
}
auto& io (IoEngine::Get().GetIoContext());
auto acceptor (Shared<tcp::acceptor>::Make(io));
try {
tcp::resolver resolver (io);
tcp::resolver::query query (node, service, tcp::resolver::query::passive);
auto result (resolver.resolve(query));
auto current (result.begin());
for (;;) {
try {
acceptor->open(current->endpoint().protocol());
{
auto fd (acceptor->native_handle());
const int optFalse = 0;
setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<const char *>(&optFalse), sizeof(optFalse));
const int optTrue = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<const char *>(&optTrue), sizeof(optTrue));
#ifdef SO_REUSEPORT
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<const char *>(&optTrue), sizeof(optTrue));
#endif /* SO_REUSEPORT */
}
acceptor->bind(current->endpoint());
break;
} catch (const std::exception&) {
if (++current == result.end()) {
throw;
}
if (acceptor->is_open()) {
acceptor->close();
}
}
}
} catch (const std::exception& ex) {
Log(LogCritical, "ApiListener")
<< "Cannot bind TCP socket for host '" << node << "' on port '" << service << "': " << ex.what();
return false;
}
acceptor->listen(INT_MAX);
auto localEndpoint (acceptor->local_endpoint());
Log(LogInformation, "ApiListener")
<< "Started new listener on '[" << localEndpoint.address() << "]:" << localEndpoint.port() << "'";
IoEngine::SpawnCoroutine(io, [this, acceptor](asio::yield_context yc) { ListenerCoroutineProc(yc, acceptor); });
UpdateStatusFile(localEndpoint);
return true;
}
void ApiListener::ListenerCoroutineProc(boost::asio::yield_context yc, const Shared<boost::asio::ip::tcp::acceptor>::Ptr& server)
{
namespace asio = boost::asio;
auto& io (IoEngine::Get().GetIoContext());
time_t lastModified = -1;
const String crlPath = GetCrlPath();
if (!crlPath.IsEmpty()) {
lastModified = Utility::GetFileCreationTime(crlPath);
}
for (;;) {
try {
asio::ip::tcp::socket socket (io);
server->async_accept(socket.lowest_layer(), yc);
auto remoteEndpoint (socket.lowest_layer().remote_endpoint());
if (!crlPath.IsEmpty()) {
time_t currentCreationTime = Utility::GetFileCreationTime(crlPath);
if (lastModified != currentCreationTime) {
UpdateSSLContext();
lastModified = currentCreationTime;
}
}
boost::shared_lock<decltype(m_SSLContextMutex)> lock (m_SSLContextMutex);
auto sslConn (Shared<AsioTlsStream>::Make(io, *m_SSLContext));
lock.unlock();
sslConn->lowest_layer() = std::move(socket);
auto strand (Shared<asio::io_context::strand>::Make(io));
IoEngine::SpawnCoroutine(*strand, [this, strand, sslConn, remoteEndpoint](asio::yield_context yc) {
Timeout::Ptr timeout(new Timeout(strand->context(), *strand, boost::posix_time::microseconds(int64_t(GetConnectTimeout() * 1e6)),
[sslConn, remoteEndpoint](asio::yield_context yc) {
Log(LogWarning, "ApiListener")
<< "Timeout while processing incoming connection from " << remoteEndpoint;
boost::system::error_code ec;
sslConn->lowest_layer().cancel(ec);
}
));
Defer cancelTimeout([timeout]() { timeout->Cancel(); });
NewClientHandler(yc, strand, sslConn, String(), RoleServer);
});
} catch (const std::exception& ex) {
Log(LogCritical, "ApiListener")
<< "Cannot accept new connection: " << ex.what();
}
}
}
/**
* Creates a new JSON-RPC client and connects to the specified endpoint.
*
* @param endpoint The endpoint.
*/
void ApiListener::AddConnection(const Endpoint::Ptr& endpoint)
{
namespace asio = boost::asio;
using asio::ip::tcp;
if (!m_SSLContext) {
Log(LogCritical, "ApiListener", "SSL context is required for AddConnection()");
return;
}
auto& io (IoEngine::Get().GetIoContext());
auto strand (Shared<asio::io_context::strand>::Make(io));
IoEngine::SpawnCoroutine(*strand, [this, strand, endpoint, &io](asio::yield_context yc) {
String host = endpoint->GetHost();
String port = endpoint->GetPort();
Log(LogInformation, "ApiListener")
<< "Reconnecting to endpoint '" << endpoint->GetName() << "' via host '" << host << "' and port '" << port << "'";
try {
boost::shared_lock<decltype(m_SSLContextMutex)> lock (m_SSLContextMutex);
auto sslConn (Shared<AsioTlsStream>::Make(io, *m_SSLContext, endpoint->GetName()));
lock.unlock();
Timeout::Ptr timeout(new Timeout(strand->context(), *strand, boost::posix_time::microseconds(int64_t(GetConnectTimeout() * 1e6)),
[sslConn, endpoint, host, port](asio::yield_context yc) {
Log(LogCritical, "ApiListener")
<< "Timeout while reconnecting to endpoint '" << endpoint->GetName() << "' via host '" << host
<< "' and port '" << port << "', cancelling attempt";
boost::system::error_code ec;
sslConn->lowest_layer().cancel(ec);
}
));
Defer cancelTimeout([&timeout]() { timeout->Cancel(); });
Connect(sslConn->lowest_layer(), host, port, yc);
NewClientHandler(yc, strand, sslConn, endpoint->GetName(), RoleClient);
endpoint->SetConnecting(false);
Log(LogInformation, "ApiListener")
<< "Finished reconnecting to endpoint '" << endpoint->GetName() << "' via host '" << host << "' and port '" << port << "'";
} catch (const std::exception& ex) {
endpoint->SetConnecting(false);
Log(LogCritical, "ApiListener")
<< "Cannot connect to host '" << host << "' on port '" << port << "': " << ex.what();
}
});
}
void ApiListener::NewClientHandler(
boost::asio::yield_context yc, const Shared<boost::asio::io_context::strand>::Ptr& strand,
const Shared<AsioTlsStream>::Ptr& client, const String& hostname, ConnectionRole role
)
{
try {
NewClientHandlerInternal(yc, strand, client, hostname, role);
} catch (const std::exception& ex) {
Log(LogCritical, "ApiListener")
<< "Exception while handling new API client connection: " << DiagnosticInformation(ex, false);
Log(LogDebug, "ApiListener")
<< "Exception while handling new API client connection: " << DiagnosticInformation(ex);
}
}
static const auto l_AppVersionInt (([]() -> unsigned long {
auto appVersion (Application::GetAppVersion());
boost::regex rgx (R"EOF(^[rv]?(\d+)\.(\d+)\.(\d+))EOF");
boost::smatch match;
if (!boost::regex_search(appVersion.GetData(), match, rgx)) {
return 0;
}
return 100u * 100u * boost::lexical_cast<unsigned long>(match[1].str())
+ 100u * boost::lexical_cast<unsigned long>(match[2].str())
+ boost::lexical_cast<unsigned long>(match[3].str());
})());
static const auto l_MyCapabilities (
(uint_fast64_t)ApiCapabilities::ExecuteArbitraryCommand | (uint_fast64_t)ApiCapabilities::IfwApiCheckCommand
);
/**
* Processes a new client connection.
*
* @param client The new client.
*/
void ApiListener::NewClientHandlerInternal(
boost::asio::yield_context yc, const Shared<boost::asio::io_context::strand>::Ptr& strand,
const Shared<AsioTlsStream>::Ptr& client, const String& hostname, ConnectionRole role
)
{
namespace asio = boost::asio;
namespace ssl = asio::ssl;
String conninfo;
{
std::ostringstream conninfo_;
if (role == RoleClient) {
conninfo_ << "to";
} else {
conninfo_ << "from";
}
auto endpoint (client->lowest_layer().remote_endpoint());
conninfo_ << " [" << endpoint.address() << "]:" << endpoint.port();
conninfo = conninfo_.str();
}
auto& sslConn (client->next_layer());
boost::system::error_code ec;
{
Timeout::Ptr handshakeTimeout (new Timeout(
strand->context(),
*strand,
boost::posix_time::microseconds(intmax_t(Configuration::TlsHandshakeTimeout * 1000000)),
[strand, client](asio::yield_context yc) {
boost::system::error_code ec;
client->lowest_layer().cancel(ec);
}
));
sslConn.async_handshake(role == RoleClient ? sslConn.client : sslConn.server, yc[ec]);
handshakeTimeout->Cancel();
}
if (ec) {
// https://github.com/boostorg/beast/issues/915
// Google Chrome 73+ seems not close the connection properly, https://stackoverflow.com/questions/56272906/how-to-fix-certificate-unknown-error-from-chrome-v73
if (ec == asio::ssl::error::stream_truncated) {
Log(LogNotice, "ApiListener")
<< "TLS stream was truncated, ignoring connection from " << conninfo;
return;
}
Log(LogCritical, "ApiListener")
<< "Client TLS handshake failed (" << conninfo << "): " << ec.message();
return;
}
bool willBeShutDown = false;
Defer shutDownIfNeeded ([&sslConn, &willBeShutDown, &yc]() {
if (!willBeShutDown) {
// Ignore the error, but do not throw an exception being swallowed at all cost.
// https://github.com/Icinga/icinga2/issues/7351
boost::system::error_code ec;
sslConn.async_shutdown(yc[ec]);
}
});
std::shared_ptr<X509> cert (sslConn.GetPeerCertificate());
bool verify_ok = false;
String identity;
Endpoint::Ptr endpoint;
if (cert) {
verify_ok = sslConn.IsVerifyOK();
String verifyError = sslConn.GetVerifyError();
try {
identity = GetCertificateCN(cert);
} catch (const std::exception&) {
Log(LogCritical, "ApiListener")
<< "Cannot get certificate common name from peer (" << conninfo << ") cert.";
return;
}
if (!hostname.IsEmpty()) {
if (identity != hostname) {
Log(LogWarning, "ApiListener")
<< "Unexpected certificate common name while connecting to endpoint '"
<< hostname << "': got '" << identity << "'";
return;
} else if (!verify_ok) {
Log(LogWarning, "ApiListener")
<< "Certificate validation failed for endpoint '" << hostname
<< "': " << verifyError;
}
}
if (verify_ok) {
endpoint = Endpoint::GetByName(identity);
}
Log log(LogInformation, "ApiListener");
log << "New client connection for identity '" << identity << "' " << conninfo;
if (!verify_ok) {
log << " (certificate validation failed: " << verifyError << ")";
} else if (!endpoint) {
log << " (no Endpoint object found for identity)";
}
} else {
Log(LogInformation, "ApiListener")
<< "New client connection " << conninfo << " (no client certificate)";
}
ClientType ctype;
try {
if (role == RoleClient) {
JsonRpc::SendMessage(client, new Dictionary({
{ "jsonrpc", "2.0" },
{ "method", "icinga::Hello" },
{ "params", new Dictionary({
{ "version", (double)l_AppVersionInt },
{ "capabilities", (double)l_MyCapabilities }
}) }
}), yc);
client->async_flush(yc);
ctype = ClientJsonRpc;
} else {
{
boost::system::error_code ec;
if (client->async_fill(yc[ec]) == 0u) {
if (identity.IsEmpty()) {
Log(LogInformation, "ApiListener")
<< "No data received on new API connection " << conninfo << ". "
<< "Ensure that the remote endpoints are properly configured in a cluster setup.";
} else {
Log(LogWarning, "ApiListener")
<< "No data received on new API connection " << conninfo << " for identity '" << identity << "'. "
<< "Ensure that the remote endpoints are properly configured in a cluster setup.";
}
return;
}
}
char firstByte = 0;
{
asio::mutable_buffer firstByteBuf (&firstByte, 1);
client->peek(firstByteBuf);
}
if (firstByte >= '0' && firstByte <= '9') {
JsonRpc::SendMessage(client, new Dictionary({
{ "jsonrpc", "2.0" },
{ "method", "icinga::Hello" },
{ "params", new Dictionary({
{ "version", (double)l_AppVersionInt },
{ "capabilities", (double)l_MyCapabilities }
}) }
}), yc);
client->async_flush(yc);
ctype = ClientJsonRpc;
} else {
ctype = ClientHttp;
}
}
} catch (const boost::system::system_error& systemError) {
if (systemError.code() == boost::asio::error::operation_aborted) {
shutDownIfNeeded.Cancel();
}
throw;
}
if (ctype == ClientJsonRpc) {
Log(LogNotice, "ApiListener", "New JSON-RPC client");
if (endpoint && endpoint->GetConnected()) {
Log(LogNotice, "ApiListener")
<< "Ignoring JSON-RPC connection " << conninfo
<< ". We're already connected to Endpoint '" << endpoint->GetName() << "'.";
return;
}
JsonRpcConnection::Ptr aclient = new JsonRpcConnection(identity, verify_ok, client, role);
if (endpoint) {
endpoint->AddClient(aclient);
Utility::QueueAsyncCallback([this, aclient, endpoint]() {
SyncClient(aclient, endpoint, true);
});
} else if (!AddAnonymousClient(aclient)) {
Log(LogNotice, "ApiListener")
<< "Ignoring anonymous JSON-RPC connection " << conninfo
<< ". Max connections (" << GetMaxAnonymousClients() << ") exceeded.";
aclient = nullptr;
}
if (aclient) {
aclient->Start();
willBeShutDown = true;
}
} else {
Log(LogNotice, "ApiListener", "New HTTP client");
HttpServerConnection::Ptr aclient = new HttpServerConnection(identity, verify_ok, client);
AddHttpClient(aclient);
aclient->Start();
willBeShutDown = true;
}
}
void ApiListener::SyncClient(const JsonRpcConnection::Ptr& aclient, const Endpoint::Ptr& endpoint, bool needSync)
{
Zone::Ptr eZone = endpoint->GetZone();
try {
{
ObjectLock olock(endpoint);
endpoint->SetSyncing(true);
}
Zone::Ptr myZone = Zone::GetLocalZone();
auto parent (myZone->GetParent());
if (parent == eZone || (!parent && eZone == myZone)) {
JsonRpcConnection::SendCertificateRequest(aclient, nullptr, String());
if (Utility::PathExists(ApiListener::GetCertificateRequestsDir())) {
Utility::Glob(ApiListener::GetCertificateRequestsDir() + "/*.json", [aclient](const String& newPath) {
JsonRpcConnection::SendCertificateRequest(aclient, nullptr, newPath);
}, GlobFile);
}
}
/* Make sure that the config updates are synced
* before the logs are replayed.
*/
Log(LogInformation, "ApiListener")
<< "Sending config updates for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
/* sync zone file config */
SendConfigUpdate(aclient);
Log(LogInformation, "ApiListener")
<< "Finished sending config file updates for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
/* sync runtime config */
SendRuntimeConfigObjects(aclient);
Log(LogInformation, "ApiListener")
<< "Finished sending runtime config updates for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
if (!needSync) {
ObjectLock olock2(endpoint);
endpoint->SetSyncing(false);
return;
}
Log(LogInformation, "ApiListener")
<< "Sending replay log for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
ReplayLog(aclient);
if (eZone == Zone::GetLocalZone())
UpdateObjectAuthority();
Log(LogInformation, "ApiListener")
<< "Finished sending replay log for endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
} catch (const std::exception& ex) {
{
ObjectLock olock2(endpoint);
endpoint->SetSyncing(false);
}
Log(LogCritical, "ApiListener")
<< "Error while syncing endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex, false);
Log(LogDebug, "ApiListener")
<< "Error while syncing endpoint '" << endpoint->GetName() << "': " << DiagnosticInformation(ex);
}
Log(LogInformation, "ApiListener")
<< "Finished syncing endpoint '" << endpoint->GetName() << "' in zone '" << eZone->GetName() << "'.";
}
void ApiListener::ApiTimerHandler()
{
double now = Utility::GetTime();
std::vector<int> files;
Utility::Glob(GetApiDir() + "log/*", [&files](const String& file) { LogGlobHandler(files, file); }, GlobFile);
std::sort(files.begin(), files.end());
for (int ts : files) {
bool need = false;
auto localZone (GetLocalEndpoint()->GetZone());
for (const Endpoint::Ptr& endpoint : ConfigType::GetObjectsByType<Endpoint>()) {
if (endpoint == GetLocalEndpoint())
continue;
auto zone (endpoint->GetZone());
/* only care for endpoints in a) the same zone b) our parent zone c) immediate child zones */
if (!(zone == localZone || zone == localZone->GetParent() || zone->GetParent() == localZone)) {
continue;
}
if (endpoint->GetLogDuration() >= 0 && ts < now - endpoint->GetLogDuration())
continue;
if (ts > endpoint->GetLocalLogPosition()) {
need = true;
break;
}
}
if (!need) {
String path = GetApiDir() + "log/" + Convert::ToString(ts);
Log(LogNotice, "ApiListener")
<< "Removing old log file: " << path;
(void)unlink(path.CStr());
}
}
for (const Endpoint::Ptr& endpoint : ConfigType::GetObjectsByType<Endpoint>()) {