-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathIPCServerPrivate.cpp
1070 lines (919 loc) · 33.7 KB
/
IPCServerPrivate.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
//
// Copyright (C) 2016 Red Hat, Inc.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// Authors: Daniel Kopecek <[email protected]>
//
#ifdef HAVE_BUILD_CONFIG_H
#include <build-config.h>
#endif
#include "IPCServerPrivate.hpp"
#include "IPCPrivate.hpp"
#include "Common/Utility.hpp"
#include "usbguard/Logger.hpp"
#include "usbguard/Exception.hpp"
#include <sys/poll.h>
#include <sys/eventfd.h>
#include <sys/types.h>
#include <pwd.h>
#include <grp.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
namespace usbguard
{
static qb_loop* G_qb_loop = nullptr;
IPCServerPrivate::IPCServerPrivate(IPCServer& p_instance)
: _p_instance(p_instance),
_thread(this, &IPCServerPrivate::thread)
{
if (G_qb_loop != nullptr) {
throw USBGUARD_BUG("Only one instance of IPCServer per process allowed");
}
G_qb_loop = _qb_loop = qb_loop_create();
if (_qb_loop == nullptr) {
throw Exception("IPC server initialization", "main loop", "Failed to create qb_loop object");
}
_wakeup_fd = -1;
try {
initIPC();
USBGUARD_SYSCALL_THROW("IPC server initialization",
(_wakeup_fd = eventfd(0, 0)) < 0);
qb_loop_poll_add(_qb_loop, QB_LOOP_HIGH, _wakeup_fd,
POLLIN, nullptr,
&IPCServerPrivate::qbPollWakeupFn);
}
catch (...) {
qb_loop_destroy(_qb_loop);
G_qb_loop = nullptr;
throw;
}
registerHandler<IPC::appendRule>(&IPCServerPrivate::handleAppendRule, IPCServer::AccessControl::Section::POLICY,
IPCServer::AccessControl::Privilege::MODIFY);
registerHandler<IPC::removeRule>(&IPCServerPrivate::handleRemoveRule, IPCServer::AccessControl::Section::POLICY,
IPCServer::AccessControl::Privilege::MODIFY);
registerHandler<IPC::listRules>(&IPCServerPrivate::handleListRules, IPCServer::AccessControl::Section::POLICY,
IPCServer::AccessControl::Privilege::LIST);
registerHandler<IPC::applyDevicePolicy>(&IPCServerPrivate::handleApplyDevicePolicy, IPCServer::AccessControl::Section::DEVICES,
IPCServer::AccessControl::Privilege::MODIFY);
registerHandler<IPC::listDevices>(&IPCServerPrivate::handleListDevices, IPCServer::AccessControl::Section::DEVICES,
IPCServer::AccessControl::Privilege::LIST);
registerHandler<IPC::setParameter>(&IPCServerPrivate::handleSetParameter, IPCServer::AccessControl::Section::PARAMETERS,
IPCServer::AccessControl::Privilege::MODIFY);
registerHandler<IPC::getParameter>(&IPCServerPrivate::handleGetParameter, IPCServer::AccessControl::Section::PARAMETERS,
IPCServer::AccessControl::Privilege::LIST);
}
void IPCServerPrivate::initIPC()
{
static struct qb_ipcs_service_handlers service_handlers = {
IPCServerPrivate::qbIPCConnectionAcceptFn,
IPCServerPrivate::qbIPCConnectionCreatedFn,
IPCServerPrivate::qbIPCMessageProcessFn,
IPCServerPrivate::qbIPCConnectionClosedFn,
IPCServerPrivate::qbIPCConnectionDestroyedFn
};
_qb_service = qb_ipcs_create("usbguard", 0,
QB_IPC_NATIVE, &service_handlers);
if (_qb_service == nullptr) {
throw Exception("IPC server initialization", "service", "Failed to create qb_service object");
}
qb_ipcs_service_context_set(_qb_service, this);
static struct qb_ipcs_poll_handlers poll_handlers = {
IPCServerPrivate::qbIPCJobAdd,
IPCServerPrivate::qbIPCDispatchAdd,
IPCServerPrivate::qbIPCDispatchMod,
IPCServerPrivate::qbIPCDispatchDel
};
qb_ipcs_poll_handlers_set(_qb_service, &poll_handlers);
const auto rc = qb_ipcs_run(_qb_service);
if (rc != 0) {
throw ErrnoException("IPC server initialization", "service", (int)-rc);
}
}
void IPCServerPrivate::finiIPC()
{
qb_ipcs_destroy(_qb_service);
}
IPCServerPrivate::~IPCServerPrivate()
{
destruct();
}
void IPCServerPrivate::thread()
{
qb_loop_run(_qb_loop);
}
void IPCServerPrivate::wakeup()
{
const uint64_t one = 1;
USBGUARD_SYSCALL_THROW("IPC server",
write(_wakeup_fd, &one, sizeof one) != sizeof one);
}
void IPCServerPrivate::start()
{
if (!_thread.running()) {
_thread.start();
}
}
void IPCServerPrivate::stop()
{
_thread.stop(/*do_wait=*/false);
qb_loop_stop(_qb_loop);
wakeup();
_thread.wait();
}
void IPCServerPrivate::destruct()
{
if (_thread.running()) {
stop();
}
finiIPC();
qb_loop_poll_del(_qb_loop, _wakeup_fd);
qb_loop_destroy(_qb_loop);
USBGUARD_SYSCALL_THROW("IPC server", close(_wakeup_fd) != 0);
}
int32_t IPCServerPrivate::qbPollWakeupFn(int32_t fd, int32_t revents, void* data)
{
USBGUARD_LOG(Trace) << "fd=" << fd
<< " revents=" << revents
<< " data=" << data;
uint64_t one = 0;
if (read(fd, &one, sizeof one) != sizeof one) {
USBGUARD_LOG(Warning) << "IPC server: "
<< "Failed to read wakeup event: "
<< "errno=" << errno;
return -1;
}
else {
return 0;
}
}
void IPCServerPrivate::qbIPCConnectionCreatedFn(qb_ipcs_connection_t* conn)
{
USBGUARD_LOG(Trace) << "conn=" << conn;
USBGUARD_LOG(Info) << "New IPC connection from PID " << qbIPCConnectionClientPID(conn);
}
void IPCServerPrivate::qbIPCConnectionDestroyedFn(qb_ipcs_connection_t* conn)
{
USBGUARD_LOG(Trace) << "Deleting client context: conn=" << conn;
ClientContext* const client_context = \
static_cast<ClientContext*>(qb_ipcs_context_get(conn));
if (client_context != nullptr) {
delete client_context;
}
}
int32_t IPCServerPrivate::qbIPCConnectionClosedFn(qb_ipcs_connection_t* conn)
{
USBGUARD_LOG(Trace) << "conn=" << conn;
USBGUARD_LOG(Info) << "Closed IPC connection to PID " << qbIPCConnectionClientPID(conn);
return 0;
}
int32_t IPCServerPrivate::qbIPCJobAdd(enum qb_loop_priority p, void* data, qb_loop_job_dispatch_fn fn)
{
return qb_loop_job_add(G_qb_loop, p, data, fn);
}
int32_t IPCServerPrivate::qbIPCDispatchAdd(enum qb_loop_priority p, int32_t fd, int32_t evts,
void* data, qb_ipcs_dispatch_fn_t fn)
{
return qb_loop_poll_add(G_qb_loop, p, fd, evts, data, fn);
}
int32_t IPCServerPrivate::qbIPCDispatchMod(enum qb_loop_priority p, int32_t fd, int32_t evts,
void* data, qb_ipcs_dispatch_fn_t fn)
{
return qb_loop_poll_mod(G_qb_loop, p, fd, evts, data, fn);
}
int32_t IPCServerPrivate::qbIPCDispatchDel(int32_t fd)
{
return qb_loop_poll_del(G_qb_loop, fd);
}
int32_t IPCServerPrivate::qbIPCConnectionClientPID(qb_ipcs_connection_t* connection)
{
std::unique_ptr<qb_ipcs_connection_stats_2, FreeDeleter> \
stats(qb_ipcs_connection_stats_get_2(connection, /*clear_after_read=*/0));
if (stats == nullptr) {
throw std::runtime_error("Cannot retrieve qb connection statistics");
}
return stats->client_pid;
}
int32_t IPCServerPrivate::qbIPCConnectionAcceptFn(qb_ipcs_connection_t* conn, uid_t uid, gid_t gid)
{
try {
IPCServerPrivate* server = \
static_cast<IPCServerPrivate*>(qb_ipcs_connection_service_context_get(conn));
std::unique_ptr<ClientContext> client_context(new ClientContext());
const bool auth = server->qbIPCConnectionAllowed(uid, gid, &client_context->access_control);
qb_ipcs_context_set(conn, client_context.release());
if (auth) {
USBGUARD_LOG(Info) << "IPC connection accepted: uid=" << uid
<< " gid=" << gid
<< " pid=" << qbIPCConnectionClientPID(conn);
USBGUARD_LOG(Debug) << "Setting SHM permissions to uid=" << uid
<< " gid=" << 0
<< " mode=0660";
qb_ipcs_connection_auth_set(conn, uid, 0, 0660);
return 0;
}
else {
USBGUARD_LOG(Warning) << "IPC connection denied: uid=" << uid
<< " gid=" << gid
<< " pid=" << qbIPCConnectionClientPID(conn);
return -1;
}
}
catch (const std::exception& exception) {
USBGUARD_LOG(Error) << "IPC connection denied: Exception: " << exception.what();
}
catch (...) {
USBGUARD_LOG(Error) << "IPC connection denied: BUG: unknown exception caught.";
}
return -1;
}
bool IPCServerPrivate::hasACLEntries() const
{
return (!_allowed_uids.empty() \
|| !_allowed_gids.empty() \
|| !_allowed_usernames.empty() \
|| !_allowed_groupnames.empty());
}
bool IPCServerPrivate::qbIPCConnectionAllowed(uid_t uid, gid_t gid, IPCServer::AccessControl* const ac_ptr) const
{
if (hasACLEntries()) {
return authenticateIPCConnectionDAC(uid, gid, ac_ptr);
}
else {
USBGUARD_LOG(Debug) << "IPC ACL is empty."
<< " Allowing connection for uid=" << uid
<< " gid=" << gid;
return true;
}
}
void IPCServerPrivate::qbIPCSendMessage(qb_ipcs_connection_t* qb_conn, const IPC::MessagePointer& message)
{
if (qb_conn == nullptr || message == nullptr) {
throw USBGUARD_BUG("NULL argument(s)");
}
std::string payload;
message->SerializeToString(&payload);
struct qb_ipc_response_header hdr;
struct iovec iov[2];
hdr.id = QB_IPC_MSG_USER_START + IPC::messageTypeNameToNumber(message->GetTypeName());
hdr.size = sizeof hdr + payload.size();
hdr.error = 0;
iov[0].iov_base = &hdr;
iov[0].iov_len = sizeof hdr;
iov[1].iov_base = (void*)payload.data();
iov[1].iov_len = payload.size();
const size_t total_size = hdr.size;
ClientContext* const client_context = \
static_cast<ClientContext*>(qb_ipcs_context_get(qb_conn));
if (client_context == nullptr) {
throw USBGUARD_BUG("NULL client context");
}
std::unique_lock<std::mutex> lock(client_context->mutex);
const ssize_t rc = qb_ipcs_event_sendv(qb_conn, iov, 2);
if (rc < 0 || (size_t)rc != total_size) {
std::unique_ptr<qb_ipcs_connection_stats_2, FreeDeleter> \
stats(qb_ipcs_connection_stats_get_2(qb_conn, /*clear_after_read=*/0));
if (stats == nullptr) {
throw std::runtime_error("Cannot retrieve qb connection statistics");
}
if (rc < 0) {
USBGUARD_LOG(Error) << "An error ocured while sending IPC message to pid=" << qbIPCConnectionClientPID(
qb_conn) << " errno=" << -rc;
/* FALLTHROUGH */
}
else if ((size_t)rc != total_size) {
USBGUARD_LOG(Error) << "Unable to sent complete IPC message to pid=" << qbIPCConnectionClientPID(qb_conn)
<< " sent=" << (size_t)rc
<< " expected=" << total_size;
/* FALLTHROUGH */
}
}
iov[0].iov_base = nullptr;
iov[1].iov_base = nullptr;
}
int32_t IPCServerPrivate::qbIPCMessageProcessFn(qb_ipcs_connection_t* conn, void* data, size_t size)
{
if (conn == nullptr) {
return -1;
}
qb_ipcs_connection_ref(conn);
if (size <= sizeof (struct qb_ipc_request_header)) {
USBGUARD_LOG(Debug) << "IPC message too short";
qb_ipcs_disconnect(conn);
return -1;
}
if (size > 1<<20) {
USBGUARD_LOG(Debug) << "IPC message too large";
qb_ipcs_disconnect(conn);
return -1;
}
const struct qb_ipc_request_header* const hdr = \
reinterpret_cast<const struct qb_ipc_request_header*>(data);
if (size != (size_t)hdr->size) {
USBGUARD_LOG(Debug) << "Invalid IPC header size";
qb_ipcs_disconnect(conn);
return -1;
}
if (hdr->id < QB_IPC_MSG_USER_START) {
USBGUARD_LOG(Debug) << "Invalid IPC header id";
qb_ipcs_disconnect(conn);
return -1;
}
int32_t client_pid = -1;
bool client_disconnect = false;
try {
client_pid = qbIPCConnectionClientPID(conn);
}
catch (...) {
USBGUARD_LOG(Error) << "Unable to get client PID. Disconnecting client.";
qb_ipcs_disconnect(conn);
return -1;
}
try {
IPCServerPrivate* const server = \
reinterpret_cast<IPCServerPrivate*>(qb_ipcs_connection_service_context_get(conn));
const uint32_t payload_type = hdr->id - QB_IPC_MSG_USER_START;
const char* const payload_data = reinterpret_cast<const char*>(data) + sizeof(struct qb_ipc_request_header);
const size_t payload_size = size - sizeof(struct qb_ipc_request_header);
const std::string payload(payload_data, payload_size);
ClientContext* const client_context = \
static_cast<ClientContext*>(qb_ipcs_context_get(conn));
const IPCServer::AccessControl* const access_control = &client_context->access_control;
if (access_control == nullptr) {
throw USBGUARD_BUG("IPC access control not set");
}
USBGUARD_LOG(Debug) << "Handling IPC payload of type=" << payload_type
<< " size=" << payload_size;
auto response = server->handleIPCPayload(payload_type, payload, access_control);
if (response) {
USBGUARD_LOG(Debug) << "Sending response to client_pid=" << client_pid;
qbIPCSendMessage(conn, response);
}
}
catch (const IPCException& ex) {
USBGUARD_LOG(Warning) << "IPC: client_pid=" << client_pid
<< ": IPC exception: " << ex.message();
qbIPCSendMessage(conn, IPC::IPCExceptionToMessage(ex));
/* FALLTHROUGH */
}
catch (const Exception& ex) {
USBGUARD_LOG(Warning) << "IPC: client_pid=" << client_pid
<< ": Exception: " << ex.message();
client_disconnect = true;
/* FALLTHROUGH */
}
catch (const std::exception& ex) {
USBGUARD_LOG(Warning) << "IPC: client_pid=" << client_pid
<< ": Exception: " << ex.what();
client_disconnect = true;
/* FALLTHROUGH */
}
catch (...) {
USBGUARD_LOG(Warning) << "IPC: client_pid=" << client_pid
<< ": Unknown exception.";
client_disconnect = true;
/* FALLTHROUGH */
}
if (client_disconnect) {
USBGUARD_LOG(Warning) << "IPC: client_pid=" << client_pid
<< ": Disconnecting client.";
qb_ipcs_disconnect(conn);
return -1;
}
else {
qb_ipcs_connection_unref(conn);
}
return 0;
}
void IPCServerPrivate::qbIPCBroadcastData(const struct iovec* const iov, const size_t iov_len,
IPCServer::AccessControl::Section section)
{
auto qb_conn = qb_ipcs_connection_first_get(_qb_service);
size_t total_size = 0;
for (size_t i = 0; i < iov_len; ++i) {
total_size += iov[i].iov_len;
}
while (qb_conn != nullptr) {
ClientContext* const client_context = \
static_cast<ClientContext*>(qb_ipcs_context_get(qb_conn));
if (client_context == nullptr) {
throw USBGUARD_BUG("NULL client context");
}
const IPCServer::AccessControl* const access_control = \
&client_context->access_control;
if (access_control->hasPrivilege(section, IPCServer::AccessControl::Privilege::LISTEN)) {
std::unique_lock<std::mutex> lock(client_context->mutex);
/* Send the data */
const ssize_t rc = qb_ipcs_event_sendv(qb_conn, iov, iov_len);
if (rc < 0 || (size_t)rc != total_size) {
std::unique_ptr<qb_ipcs_connection_stats_2, FreeDeleter> \
stats(qb_ipcs_connection_stats_get_2(qb_conn, /*clear_after_read=*/0));
if (stats == nullptr) {
throw std::runtime_error("Cannot retrieve qb connection statistics");
}
if (rc < 0) {
USBGUARD_LOG(Error) << "An error ocured while sending IPC message to pid=" << qbIPCConnectionClientPID(
qb_conn) << " errno=" << -rc;
}
else if ((size_t)rc != total_size) {
USBGUARD_LOG(Error) << "Unable to sent complete IPC message to pid=" << qbIPCConnectionClientPID(qb_conn)
<< " sent=" << (size_t)rc
<< " expected=" << total_size;
}
}
}
else {
USBGUARD_LOG(Info) << "IPC message broadcast: Skipping client at pid=" << qbIPCConnectionClientPID(qb_conn)
<< ": Insufficient privileges to receive the message.";
}
/* Get the next connection */
auto qb_conn_next = qb_ipcs_connection_next_get(_qb_service, qb_conn);
qb_ipcs_connection_unref(qb_conn);
qb_conn = qb_conn_next;
}
}
void IPCServerPrivate::qbIPCBroadcastMessage(const IPC::MessagePointer& message)
{
qbIPCBroadcastMessage(message.get());
}
IPCServer::AccessControl::Section IPCServerPrivate::messageTypeNameToAccessControlSection(const std::string& name)
{
if (name == "usbguard.IPC.DevicePresenceChangedSignal") {
return IPCServer::AccessControl::Section::DEVICES;
}
if (name == "usbguard.IPC.DevicePolicyChangedSignal") {
return IPCServer::AccessControl::Section::DEVICES;
}
if (name == "usbguard.IPC.PropertyParameterChangedSignal") {
return IPCServer::AccessControl::Section::PARAMETERS;
}
if (name == "usbguard.IPC.Exception") {
return IPCServer::AccessControl::Section::EXCEPTIONS;
}
throw Exception("IPC Server", name, "Invalid IPC typename to Access Control section translation request");
}
void IPCServerPrivate::qbIPCBroadcastMessage(const IPC::MessageType* const message)
{
std::string payload;
message->SerializeToString(&payload);
struct qb_ipc_response_header hdr = { };
hdr.id = QB_IPC_MSG_USER_START + IPC::messageTypeNameToNumber(message->GetTypeName());
hdr.size = sizeof hdr + payload.size();
hdr.error = 0;
struct iovec iov[2];
iov[0].iov_base = &hdr;
iov[0].iov_len = sizeof hdr;
iov[1].iov_base = (void*)payload.data();
iov[1].iov_len = payload.size();
qbIPCBroadcastData(iov, 2, messageTypeNameToAccessControlSection(message->GetTypeName()));
iov[0].iov_base = nullptr;
iov[1].iov_base = nullptr;
}
bool IPCServerPrivate::authenticateIPCConnectionDAC(uid_t uid, gid_t gid, IPCServer::AccessControl* const ac_ptr) const
{
USBGUARD_LOG(Trace) << "uid=" << uid << " gid=" << gid << " ac_ptr=" << ac_ptr;
return \
matchACLByUID(uid, ac_ptr) || \
matchACLByGID(gid, ac_ptr) || \
matchACLByName(uid, gid, ac_ptr);
}
bool IPCServerPrivate::matchACLByUID(uid_t uid, IPCServer::AccessControl* const ac_ptr) const
{
USBGUARD_LOG(Trace) << "uid=" << uid << " ac_ptr=" << ac_ptr;
const auto& it = _allowed_uids.find(uid);
if (it == _allowed_uids.cend()) {
return false;
}
if (ac_ptr != nullptr) {
ac_ptr->merge(it->second);
}
USBGUARD_LOG(Trace) << "matched";
return true;
}
bool IPCServerPrivate::matchACLByGID(gid_t gid, IPCServer::AccessControl* const ac_ptr) const
{
USBGUARD_LOG(Trace) << "gid=" << gid << " ac_ptr=" << ac_ptr;
const auto& it = _allowed_gids.find(gid);
if (it == _allowed_gids.cend()) {
return false;
}
if (ac_ptr != nullptr) {
ac_ptr->merge(it->second);
}
USBGUARD_LOG(Trace) << "matched";
return true;
}
bool IPCServerPrivate::matchACLByName(uid_t uid, gid_t gid, IPCServer::AccessControl* const ac_ptr) const
{
USBGUARD_LOG(Trace) << "uid=" << uid << " gid=" << gid << " ac_ptr=" << ac_ptr;
bool matched = false;
const std::string uid_name = getNameFromUID(uid);
const bool check_uid_group_membership = !uid_name.empty();
if (!uid_name.empty()) {
const auto& it = _allowed_usernames.find(uid_name);
if (it != _allowed_usernames.cend()) {
if (ac_ptr != nullptr) {
ac_ptr->merge(it->second);
}
USBGUARD_LOG(Trace) << "username matched: " << uid_name;
matched = true;
}
}
const std::string gid_name = getNameFromGID(gid);
if (!gid_name.empty()) {
const auto& it = _allowed_groupnames.find(gid_name);
if (it != _allowed_groupnames.cend()) {
if (ac_ptr != nullptr) {
ac_ptr->merge(it->second);
}
USBGUARD_LOG(Trace) << "groupname matched: " << gid_name;
matched = true;
}
}
if (check_uid_group_membership) {
USBGUARD_LOG(Trace) << "Checking UID group membership";
/*
* Check against allowed GIDs
*/
for (auto const& allowed_gid_entry : _allowed_gids) {
const auto& allowed_gid = allowed_gid_entry.first;
const std::vector<std::string> group_members = getGroupMemberNames(allowed_gid);
for (const auto& group_member : group_members) {
if (group_member == uid_name) {
if (ac_ptr != nullptr) {
ac_ptr->merge(allowed_gid_entry.second);
}
USBGUARD_LOG(Trace) << "matched member of group with GID: " << allowed_gid;
matched = true;
}
}
}
/*
* Check against allowed groupnames
*/
for (auto const& allowed_groupnames_entry : _allowed_groupnames) {
const auto& allowed_groupname = allowed_groupnames_entry.first;
const std::vector<std::string> group_members = getGroupMemberNames(allowed_groupname);
for (const auto& group_member : group_members) {
if (group_member == uid_name) {
if (ac_ptr != nullptr) {
ac_ptr->merge(allowed_groupnames_entry.second);
}
USBGUARD_LOG(Trace) << "matched member of group with name: " << allowed_groupname;
matched = true;
}
}
}
} /* check_uid_group_membership */
/* TODO:
* Cache final result for some time to prevent DoS.
* IPC ACL doesn't change during runtime. Implement
* cache use limit/expiration to prevent cache time
* stretching.
*/
return matched;
}
std::string IPCServerPrivate::getNameFromUID(uid_t uid)
{
std::string buffer(1024, 0);
struct passwd pw = { };
struct passwd* pwptr = nullptr;
if (getpwuid_r(uid, &pw, &buffer[0], buffer.capacity(), &pwptr) != 0) {
USBGUARD_LOG(Warning) << "Unable to lookup username for uid=" << uid << ": errno=" << errno;
return std::string();
}
if (pwptr == nullptr || pw.pw_name == nullptr) {
USBGUARD_LOG(Info) << "No username associated with uid=" << uid;
return std::string();
}
return std::string(pw.pw_name);
}
std::string IPCServerPrivate::getNameFromGID(gid_t gid)
{
std::string buffer(4096, 0);
struct group gr = { };
struct group* grptr = nullptr;
if (getgrgid_r(gid, &gr, &buffer[0], buffer.capacity(), &grptr) != 0) {
USBGUARD_LOG(Warning) << "Unable to lookup groupname for gid=" << gid << ": errno=" << errno;
return std::string();
}
if (grptr == nullptr || gr.gr_name == nullptr) {
USBGUARD_LOG(Info) << "No groupname associated with gid=" << gid;
return std::string();
}
return std::string(gr.gr_name);
}
std::vector<std::string> IPCServerPrivate::getGroupMemberNames(gid_t gid)
{
std::vector<std::string> names;
std::string buffer(4096, 0);
struct group gr = { };
struct group* grptr = nullptr;
if (getgrgid_r(gid, &gr, &buffer[0], buffer.capacity(), &grptr) != 0) {
USBGUARD_LOG(Warning) << "Unable to fetch group members for gid=" << gid << ": errno=" << errno;
return std::vector<std::string>();
}
if (grptr == nullptr || gr.gr_name == nullptr) {
USBGUARD_LOG(Info) << "No group associated with gid=" << gid;
return std::vector<std::string>();
}
for (size_t i = 0; gr.gr_mem[i] != nullptr; ++i) {
names.emplace_back(std::string(gr.gr_mem[i]));
}
return names;
}
std::vector<std::string> IPCServerPrivate::getGroupMemberNames(const std::string& groupname)
{
std::vector<std::string> names;
std::string buffer(4096, 0);
struct group gr = { };
struct group* grptr = nullptr;
if (getgrnam_r(groupname.c_str(), &gr, &buffer[0], buffer.capacity(), &grptr) != 0) {
USBGUARD_LOG(Warning) << "Unable to fetch group member names for groupname=" << groupname << ": errno=" << errno;
return std::vector<std::string>();
}
if (grptr == nullptr || gr.gr_name == nullptr) {
USBGUARD_LOG(Info) << "Can't find group with name=" << groupname;
return std::vector<std::string>();
}
for (size_t i = 0; gr.gr_mem[i] != nullptr; ++i) {
names.emplace_back(std::string(gr.gr_mem[i]));
}
return names;
}
IPC::MessagePointer IPCServerPrivate::handleIPCPayload(const uint32_t payload_type, const std::string& payload,
const IPCServer::AccessControl* const access_control)
{
const auto& handler_it = _handlers.find(payload_type);
if (handler_it == _handlers.end()) {
throw Exception("IPC connection", "IPC payload data", "Unknown payload type");
}
auto& handler = handler_it->second;
/*
* Try to parse the IPC payload as a message of the
* specified type. If the parsing fails, the client will
* be disconnected.
*/
IPC::MessagePointer message_in;
uint64_t request_id = 0;
try {
message_in = handler.payloadToMessage(payload);
request_id = IPC::getMessageHeaderID(*message_in);
}
catch (...) {
throw Exception("IPC connection", "IPC payload data", "Payload data parsing failed");
}
if (!access_control->hasPrivilege(handler.section(), handler.privilege())) {
throw IPCException("IPC method",
IPC::messageTypeNameFromNumber(payload_type),
"Permission denied",
request_id);
}
/*
* Try to run the handler. Exception thrown from inside the handler
* will be sent to the client.
*/
try {
IPC::MessagePointer response;
handler.run(message_in, response);
return response;
}
catch (IPCException& exception) {
exception.setMessageID(request_id);
throw exception;
}
catch (const Exception& exception) {
throw IPCException(exception, request_id);
}
catch (const std::exception& exception) {
throw IPCException("IPC method",
IPC::messageTypeNameFromNumber(payload_type),
exception.what(),
request_id);
}
catch (...) {
throw IPCException("IPC method",
IPC::messageTypeNameFromNumber(payload_type),
"BUG: Unexpected exception",
request_id);
}
}
void IPCServerPrivate::handleAppendRule(IPC::MessagePointer& request, IPC::MessagePointer& response)
{
/*
* Get request field values.
*/
const IPC::appendRule* const message_in = static_cast<const IPC::appendRule*>(request.get());
const std::string rule = message_in->request().rule();
const uint32_t parent_id = message_in->request().parent_id();
const bool permanent = message_in->request().permanent();
/*
* Execute the method.
*/
const uint32_t id = _p_instance.appendRule(rule, parent_id, permanent);
/*
* Construct the response.
*/
IPC::appendRule* const message_out = message_in->New();
message_out->MergeFrom(*message_in);
message_out->mutable_response()->set_id(id);
response.reset(message_out);
}
void IPCServerPrivate::handleRemoveRule(IPC::MessagePointer& request, IPC::MessagePointer& response)
{
/*
* Get request field values.
*/
const IPC::removeRule* const message_in = static_cast<const IPC::removeRule*>(request.get());
const uint32_t id = message_in->request().id();
/*
* Execute the method.
*/
_p_instance.removeRule(id);
/*
* Construct the response.
*/
IPC::removeRule* const message_out = message_in->New();
message_out->MergeFrom(*message_in);
message_out->mutable_response()->set_id(id);
response.reset(message_out);
}
void IPCServerPrivate::handleListRules(IPC::MessagePointer& request, IPC::MessagePointer& response)
{
/*
* Get request field values.
*/
const IPC::listRules* const message_in = static_cast<const IPC::listRules*>(request.get());
const std::string label = message_in->request().label();
/*
* Execute the method.
*/
auto rules = _p_instance.listRules(label);
/*
* Construct the response.
*/
IPC::listRules* const message_out = message_in->New();
message_out->MergeFrom(*message_in);
for (const auto& rule : rules) {
auto message_rule = message_out->mutable_response()->add_rules();
message_rule->set_id(rule.getRuleID());
message_rule->set_rule(rule.toString());
}
response.reset(message_out);
}
void IPCServerPrivate::handleApplyDevicePolicy(IPC::MessagePointer& request, IPC::MessagePointer& response)
{
/*
* Get request field values.
*/
const IPC::applyDevicePolicy* const message_in = static_cast<const IPC::applyDevicePolicy*>(request.get());
const uint32_t id = message_in->request().id();
const Rule::Target target = Rule::targetFromInteger(message_in->request().target());
const bool permanent = message_in->request().permanent();
/*
* Execute the method.
*/
const uint32_t rule_id = _p_instance.applyDevicePolicy(id, target, permanent);
/*
* Construct the response.
*/
IPC::applyDevicePolicy* const message_out = message_in->New();
IPC::MessagePointer response_local(message_out);
message_out->MergeFrom(*message_in);
message_out->mutable_response()->set_rule_id(rule_id);
response = std::move(response_local);
}
void IPCServerPrivate::handleListDevices(IPC::MessagePointer& request, IPC::MessagePointer& response)
{
/*
* Get request field values.
*/
const IPC::listDevices* const message_in = static_cast<const IPC::listDevices*>(request.get());
const std::string query = message_in->request().query();
/*
* Execute the method.
*/
auto device_rules = _p_instance.listDevices(query);
/*
* Construct the response.
*/
IPC::listDevices* const message_out = message_in->New();
message_out->MergeFrom(*message_in);
message_out->mutable_response()->Clear();
for (const auto& device_rule : device_rules) {
auto message_rule = message_out->mutable_response()->add_devices();
message_rule->set_id(device_rule.getRuleID());
message_rule->set_rule(device_rule.toString());
}
response.reset(message_out);
}
void IPCServerPrivate::handleSetParameter(IPC::MessagePointer& request, IPC::MessagePointer& response)
{
/*
* Get request field values.
*/
const IPC::setParameter* const message_in = static_cast<const IPC::setParameter*>(request.get());
const std::string name = message_in->request().name();
const std::string value = message_in->request().value();
/*
* Execute the method.
*/
auto previous_value = _p_instance.setParameter(name, value);
/*
* Construct the response.
*/
IPC::setParameter* const message_out = message_in->New();
message_out->MergeFrom(*message_in);
message_out->mutable_response()->set_value(previous_value);
response.reset(message_out);
}
void IPCServerPrivate::handleGetParameter(IPC::MessagePointer& request, IPC::MessagePointer& response)
{
const IPC::getParameter* const message_in = static_cast<const IPC::getParameter*>(request.get());
const std::string name = message_in->request().name();
auto value = _p_instance.getParameter(name);
IPC::getParameter* const message_out = message_in->New();
message_out->MergeFrom(*message_in);
message_out->mutable_response()->set_value(value);
response.reset(message_out);
}
void IPCServerPrivate::DevicePresenceChanged(uint32_t id,
DeviceManager::EventType event,
Rule::Target target,
const std::string& device_rule)
{
IPC::DevicePresenceChangedSignal signal;
signal.set_id(id);
signal.set_event(DeviceManager::eventTypeToInteger(event));