-
Notifications
You must be signed in to change notification settings - Fork 17
/
audisp-json.c
1200 lines (1061 loc) · 34.2 KB
/
audisp-json.c
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
/* vim: ts=4:sw=4:noexpandtab
* audisp-json.c --
* Copyright (c) 2014 Mozilla Corporation.
* Portions Copyright 2008 Red Hat Inc., Durham, North Carolina.
* All Rights Reserved.
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Authors:
* Guillaume Destuynder <[email protected]>
* Steve Grubb <[email protected]>
*
*/
#include <stdio.h>
#include <signal.h>
#include <syslog.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <fcntl.h>
#include <pwd.h>
#include <netdb.h>
#include <sys/stat.h>
#include <sys/socket.h>
#include <time.h>
#include <curl/curl.h>
#include "libaudit.h"
#include "auparse.h"
#include "json-config.h"
#define CONFIG_FILE "/etc/audisp/audisp-json.conf"
#define CONFIG_FILE_LOCAL "audisp-json.conf"
/* after this amount of time for any response (connect, http reply, etc.) just give up
* and lose messages.
* don't set this too high as new curl handles will be created and consume memory while
* waiting for the connection to work again.
*/
#define MAX_CURL_GLOBAL_TIMEOUT 5000L
#define MAX_CURL_QUEUE_SIZE 8192
#define MAX_JSON_MSG_SIZE 4096
#define MAX_ARG_LEN 2048
#define MAX_SUMMARY_LEN 256
#define TS_LEN 64
#define MAX_ATTR_SIZE MAX_AUDIT_MESSAGE_LENGTH
#ifdef REORDER_HACK
#define NR_LINES_BUFFERED 64
#endif
#define HTTP_CODE_OK 200
#ifndef PROGRAM_VERSION
#define PROGRAM_VERSION "1"
#endif
#ifndef PROGRAM_NAME
#define PROGRAM_NAME "audisp-json"
#endif
/* transform macro int and str value to ... str - needed for defining USER_AGENT ;)*/
#define _STR(x) #x
#define STR(x) _STR(x)
#define USER_AGENT PROGRAM_NAME"/"STR(PROGRAM_VERSION)
extern int h_errno;
static volatile int sig_stop = 0;
static volatile int sig_hup = 0;
static json_conf_t config;
static char *hostname = NULL;
static auparse_state_t *au = NULL;
static int machine = -1;
static long int curl_timeout = -1;
FILE *curl_logfile;
FILE *file_log;
CURLM *multi_h;
CURL *easy_h;
struct curl_slist *slist1;
int curl_nr_h = -1;
int msg_lost = 0;
typedef struct { char *val; } msg_t;
/* msg attributes list */
typedef struct ll {
char value[MAX_ATTR_SIZE];
struct ll *next;
} attr_t;
struct json_msg_type {
char *category;
char *summary;
char *severity;
char *hostname;
int processid;
char *processname;
char *timestamp;
struct ll *details;
};
/* msgs to send queue/buffer */
typedef struct lq {
char msg[MAX_JSON_MSG_SIZE];
struct lq *next;
} queue_t;
struct lq *msg_queue_list;
unsigned int msg_queue_list_size = 0;
void prepare_curl_handle(char *new_msg)
{
curl_easy_reset(easy_h);
curl_easy_setopt(easy_h, CURLOPT_URL, config.mozdef_url);
curl_easy_setopt(easy_h, CURLOPT_NOPROGRESS, 1L);
curl_easy_setopt(easy_h, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(easy_h, CURLOPT_HTTPHEADER, slist1);
curl_easy_setopt(easy_h, CURLOPT_MAXREDIRS, 10L);
curl_easy_setopt(easy_h, CURLOPT_CUSTOMREQUEST, "POST");
/* keep alive is on by default and only settable in recent libcurl
* keeping this around in case its not actually default in some cases and needs
* to be conditionally enabled
*/
// curl_easy_setopt(easy_h, CURLOPT_TCP_KEEPALIVE, 1L);
/* if logfile is set, log there instead of stderr.
* this is generally useful in combination with the below curl_verbose option,
* since grabbing stderr from a running plugin may be difficult.
*/
if (config.curl_logfile != NULL) {
curl_logfile = fopen(config.curl_logfile, "ab");
if (curl_logfile == NULL) {
syslog(LOG_ERR, "could not open debug curl logfile %s", config.curl_logfile);
} else {
curl_easy_setopt(easy_h, CURLOPT_STDERR, curl_logfile);
}
}
curl_easy_setopt(easy_h, CURLOPT_VERBOSE, config.curl_verbose);
curl_easy_setopt(easy_h, CURLOPT_TIMEOUT_MS, MAX_CURL_GLOBAL_TIMEOUT);
curl_easy_setopt(easy_h, CURLOPT_SSL_VERIFYHOST, config.ssl_verify);
curl_easy_setopt(easy_h, CURLOPT_SSL_VERIFYPEER, config.ssl_verify);
curl_easy_setopt(easy_h, CURLOPT_CAINFO, config.curl_cainfo);
curl_easy_setopt(easy_h, CURLOPT_COPYPOSTFIELDS, new_msg);
}
/* Insert/remove new messages in the queue
*/
int list_check_queue()
{
queue_t *prev;
if (!msg_queue_list) {
return 1;
}
prev = msg_queue_list;
msg_queue_list = msg_queue_list->next;
curl_multi_remove_handle(multi_h, easy_h);
if (prev) {
prepare_curl_handle(prev->msg);
free(prev);
msg_queue_list_size--;
curl_multi_add_handle(multi_h, easy_h);
}
return 0;
}
/* select and fetch urls */
void curl_perform(void)
{
/* Do we have curl enabled?
* If not, just bail here
*/
if (config.file_log != NULL) {
return;
}
int msgs_left;
int maxfd = -1;
long http_code = 0;
struct timeval timeout;
int rc;
CURLMsg *msg;
CURLcode ret;
fd_set r, w, e;
/* Cleanup completed handles */
while ((msg = curl_multi_info_read(multi_h, &msgs_left))) {
if (msg->msg == CURLMSG_DONE) {
ret = curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &http_code);
if (ret != CURLM_OK) {
syslog(LOG_ERR, "Couldn't send JSON message (message is lost): %s.", curl_easy_strerror(ret));
}
if (http_code > HTTP_CODE_OK) {
syslog(LOG_ERR, "Couldn't send JSON message (message is lost): HTTP error code %ld.", http_code);
}
}
}
/* cURL will set this to 0 when there is no transfer left to process,
* signaling we can sent the next message. list_check_queue() will insert the next message from the queue
* into the multi_h.
* If there's no message in the queue, we bail for now.
*/
if (curl_nr_h == 0) {
curl_nr_h = -1;
if (list_check_queue()) {
return;
}
}
FD_ZERO(&r);
FD_ZERO(&w);
FD_ZERO(&e);
/* With cURL you get the timeout you have to wait back from the library, so we use that for the select() call */
ret = curl_multi_timeout(multi_h, &curl_timeout);
if (ret != CURLM_OK) {
syslog(LOG_ERR, "%s", curl_multi_strerror(ret));
}
timeout.tv_sec = 0;
timeout.tv_usec = 100000;
if (curl_timeout >= 0) {
timeout.tv_sec = curl_timeout / 1000;
if (timeout.tv_sec > 1)
timeout.tv_sec = 1;
else
timeout.tv_usec = (curl_timeout % 1000) * 1000;
}
ret = curl_multi_fdset(multi_h, &r, &w, &e, &maxfd);
if (ret != CURLM_OK) {
syslog(LOG_ERR, "%s", curl_multi_strerror(ret));
return;
}
rc = select(maxfd+1, &r, &w, &e, &timeout);
switch(rc) {
case -1:
syslog(LOG_ERR, "%s", strerror(errno));
break;
case 0:
default:
/* This also sets curl_nr_h to exactly 0 if all the handles have been processed. */
while ((ret = curl_multi_perform(multi_h, &curl_nr_h)) && (ret == CURLM_CALL_MULTI_PERFORM)) {
continue;
}
if (ret != CURLM_OK) {
syslog(LOG_ERR, "%s", curl_multi_strerror(ret));
}
break;
}
}
static void handle_event(auparse_state_t *au,
auparse_cb_event_t cb_event_type, void *user_data);
static void int_handler(int sig)
{
if (sig_stop == 1) {
fprintf(stderr, "Repeated keyboard interrupt signal, forcing unclean program termination.\n");
exit(127);
}
sig_stop = 1;
}
static void term_handler(int sig)
{
sig_stop = 1;
}
static void hup_handler(int sig)
{
sig_hup = 1;
}
static void reload_config(void)
{
sig_hup = 0;
}
#ifdef REORDER_HACK
/*
* Hack to reorder input
* libaudit's auparse seems not to correlate messages correctly if event ids are out of sequence, ex (event id are
* 418143181 and 418143182):
* type=EXECVE msg=audit(1418253698.016:418143181): argc=3 a0="sh" a1="-c" a2=[redacted]
* type=EXECVE msg=audit(1418253698.016:418143182): argc=3 a0="sh" a1="-c" a2=[redacted]
* type=CWD msg=audit(1418253698.016:418143181): cwd="/opt/observium"
* type=CWD msg=audit(1418253698.016:418143182): cwd="/opt/observium"
*
* This hack sort them back so that event ids are back to back like this:
* type=EXECVE msg=audit(1418253698.016:418143181): argc=3 a0="sh" a1="-c" a2=[redacted]
* type=CWD msg=audit(1418253698.016:418143181): cwd="/opt/observium"
* type=EXECVE msg=audit(1418253698.016:418143182): argc=3 a0="sh" a1="-c" a2=[redacted]
* type=CWD msg=audit(1418253698.016:418143182): cwd="/opt/observium"
*
* Without the hack, when the event id correlation fails, auparse would only return the parsed event until the point of
* failure (so basically half of the message will be missing from the event/fields will be empty...)
*
* WARNING: The hack relies on properly null terminated strings here and there and doesn't do much bound checking other
* than that. Be careful.
* NOTE: This hack is only necessary when you can't fix libaudit easily, obviously. It's neither nice neither all that fast.
*/
/* count occurences of c in *in */
unsigned int strcharc(char *in, char c)
{
unsigned int i = 0;
for (i = 0; in[i]; in[i] == c ? i++ : *in++);
return i;
}
static int eventcmp(const void *p1, const void *p2)
{
char *s1, *s2;
char *a1, *a2;
int i;
s1 = *(char * const*)p1;
s2 = *(char * const*)p2;
if (!s1 || !s2)
return 0;
a1 = s1;
i = 0;
while (a1[0] != ':' && a1[0] != '\0' && i < MAX_AUDIT_MESSAGE_LENGTH) {
i++;
a1++;
}
a2 = s2;
i = 0;
while (a2[0] != ':' && a2[0] != '\0' && i < MAX_AUDIT_MESSAGE_LENGTH) {
i++;
a2++;
}
return strcmp(a1, a2);
}
size_t reorder_input_hack(char **sorted_tmp, char *tmp)
{
unsigned int lines = 0;
unsigned int llen = 0;
size_t flen = 0;
unsigned int i = 0;
lines = strcharc(tmp, '\n');
char *buf[lines];
char *line;
char *saved;
line = strtok_r(tmp, "\n", &saved);
if (!line) {
syslog(LOG_ERR, "message has no LF, message lost!");
return 0;
}
llen = strnlen(line, MAX_AUDIT_MESSAGE_LENGTH);
buf[i] = malloc(llen + 1);
if (!buf[i]) {
*sorted_tmp = tmp;
syslog(LOG_ERR, "reorder_input_hack() malloc failed won't reorder");
return strnlen(tmp, MAX_AUDIT_MESSAGE_LENGTH);
}
snprintf(buf[i], llen+1, "%s", line);
i++;
for (i; i < lines; i++) {
line = strtok_r(NULL, "\n", &saved);
if (!line) {
continue;
}
llen = strnlen(line, MAX_AUDIT_MESSAGE_LENGTH);
buf[i] = malloc(llen + 1);
if (!buf[i]) {
syslog(LOG_ERR, "reorder_input_hack() malloc failed partially reordering");
continue;
}
snprintf(buf[i], llen+1, "%s", line);
}
qsort(&buf, lines, sizeof(char *), eventcmp);
for (i = 0; i < lines; i++) {
flen += snprintf(*sorted_tmp+flen, MAX_AUDIT_MESSAGE_LENGTH, "%s\n", buf[i]);
if (buf[i]) {
free(buf[i]);
}
}
return flen;
}
#endif
int main(int argc, char *argv[])
{
char tmp[MAX_AUDIT_MESSAGE_LENGTH];
int len=0;
struct sigaction sa;
struct hostent *ht;
char nodename[64];
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sa.sa_handler = term_handler;
if (sigaction(SIGTERM, &sa, NULL) == -1)
return 1;
sa.sa_handler = int_handler;
if (sigaction(SIGINT, &sa, NULL) == -1)
return 1;
sa.sa_handler = hup_handler;
if (sigaction(SIGHUP, &sa, NULL) == -1)
return 1;
if (load_config(&config, CONFIG_FILE))
if (load_config(&config, CONFIG_FILE_LOCAL))
return 1;
openlog(PROGRAM_NAME, LOG_CONS, LOG_DAEMON);
if (gethostname(nodename, sizeof(nodename)-1)) {
snprintf(nodename, 10, "localhost");
}
nodename[sizeof(nodename)] = '\0';
ht = gethostbyname(nodename);
if (ht == NULL) {
hostname = strdup("localhost");
if (hostname == NULL)
return 1;
syslog(LOG_ALERT,
"gethostbyname could not find machine hostname, please fix this. Using %s as fallback. Error: %s",
hostname, hstrerror(h_errno));
} else {
hostname = strdup(ht->h_name);
if (hostname == NULL)
return 1;
}
if (config.file_log != NULL) {
file_log = fopen(config.file_log, "ab");
if (file_log == NULL) {
syslog(LOG_ERR, "failed to open %s", config.file_log);
return -1;
}
}
if (config.prepend_msg == NULL) {
config.prepend_msg = "\0";
}
if (config.postpend_msg == NULL) {
config.postpend_msg = "\0";
}
au = auparse_init(AUSOURCE_FEED, NULL);
if (au == NULL) {
syslog(LOG_ERR, "could not initialize auparse");
return -1;
}
machine = audit_detect_machine();
if (machine < 0) {
return -1;
}
/* libcurl stuff */
if (curl_global_init(CURL_GLOBAL_ALL) != 0) {
syslog(LOG_ERR, "curl_global_init() failed");
return -1;
}
easy_h = curl_easy_init();
multi_h = curl_multi_init();
slist1 = NULL;
slist1 = curl_slist_append(slist1, "Content-Type:application/json");
if (!(easy_h && multi_h && slist1)) {
syslog(LOG_ERR, "cURL handles creation failed, this is fatal");
return -1;
}
#ifdef REORDER_HACK
int start = 0;
int stop = 0;
int i = 0;
char *full_str_tmp = malloc(NR_LINES_BUFFERED*MAX_AUDIT_MESSAGE_LENGTH);
char *sorted_tmp = malloc(NR_LINES_BUFFERED*MAX_AUDIT_MESSAGE_LENGTH);
if (!sorted_tmp || !full_str_tmp) {
syslog(LOG_ERR, "main() malloc failed for sorted_tmp || full_str_tmp, this is fatal");
return -1;
}
sorted_tmp[0] = '\0';
full_str_tmp[0] = '\0';
#endif
auparse_add_callback(au, handle_event, NULL, NULL);
syslog(LOG_INFO, "%s loaded\n", PROGRAM_NAME);
/* At this point we're initialized so we'll read stdin until closed and feed the data to auparse, which in turn will
* call our callback (handle_event) every time it finds a new complete message to parse.
*/
do {
/* NOTE: There's quite a few reasons for auparse_feed() from libaudit to fail parsing silently so we have to be careful here.
* Anything passed to it:
* - must have the same timestamp for a given event id. (kernel takes care of that, if not, you're out of luck).
* - must always be LF+NULL terminated ("\n\0"). (fgets takes care of that even thus it's not nearly as fast as fread).
* - must always have event ids in sequential order. (REORDER_HACK takes care of that, it also buffer lines, since, well, it needs to).
*/
while (fgets_unlocked(tmp, MAX_AUDIT_MESSAGE_LENGTH, stdin)) {
if (sig_hup)
reload_config();
if (sig_stop)
break;
len = strnlen(tmp, MAX_AUDIT_MESSAGE_LENGTH);
#ifdef REORDER_HACK
if (strncmp(tmp, "type=EOE", 8) == 0) {
stop++;
} else if (strncmp(tmp, "type=SYSCALL", 12) == 0) {
start++;
}
if (i > NR_LINES_BUFFERED || start != stop) {
strncat(full_str_tmp, tmp, len);
i++;
} else {
strncat(full_str_tmp, tmp, len);
len = reorder_input_hack(&sorted_tmp, full_str_tmp);
auparse_feed(au, sorted_tmp, len);
i = 0;
start = stop = 0;
sorted_tmp[0] = '\0';
full_str_tmp[0] = '\0';
}
#else
auparse_feed(au, tmp, len);
#endif
curl_perform();
}
if (feof(stdin))
break;
} while (sig_stop == 0);
auparse_flush_feed(au);
while (msg_queue_list)
curl_perform();
auparse_destroy(au);
curl_easy_cleanup(easy_h);
curl_multi_cleanup(multi_h);
curl_global_cleanup();
if (curl_logfile)
fclose(curl_logfile);
if (file_log)
fclose(file_log);
free_config(&config);
free(hostname);
#ifdef REORDER_HACK
free(sorted_tmp);
#endif
syslog(LOG_INFO, "%s unloaded\n", PROGRAM_NAME);
closelog();
return 0;
}
/*
* This function seeks to the specified record returning its type on succees
*/
static int goto_record_type(auparse_state_t *au, int type)
{
int cur_type;
auparse_first_record(au);
do {
cur_type = auparse_get_type(au);
if (cur_type == type) {
auparse_first_field(au);
return type; // Normal exit
}
} while (auparse_next_record(au) > 0);
return -1;
}
/* Removes quotes
* Remove CR and LF
* @const char *in: if NULL, no processing is done.
*/
char *unescape(const char *in)
{
if (in == NULL)
return NULL;
char *dst = (char *)in;
char *s = dst;
char *src = (char *)in;
char c;
while ((c = *src++) != '\0') {
if ((c == '"') || (c == '\n') || (c == '\r') || (c == '\t')
|| (c == '\b') || (c == '\f') || (c == '\\'))
continue;
*dst++ = c;
}
*dst++ = '\0';
return s;
}
/* Add a field to the json msg's details={}
* @attr_t *list: the attribute list to extend
* @const char *st: the attribute name to add
* @const char *val: the attribut value - if NULL, we won't add the field to the json message at all.
*/
attr_t *_json_add_attr(attr_t *list, const char *st, char *val, int freeme)
{
attr_t *new;
if (st == NULL || !strncmp(st, "(null)", 6) || val == NULL || !strncmp(val, "(null)", 6)) {
return list;
}
new = malloc(sizeof(attr_t));
if (!new) {
syslog(LOG_ERR, "json_add_attr() malloc failed attribute will be empty: %s", st);
return list;
}
snprintf(new->value, MAX_ATTR_SIZE, "\"%s\": \"%s\"", st, unescape(val));
new->next = list;
if (freeme) {
free(val);
}
return new;
}
/* Convenience wrappers for _json_add_attr */
attr_t *json_add_attr_free(attr_t *list, const char *st, char *val)
{
return _json_add_attr(list, st, val, 1);
}
attr_t *json_add_attr(attr_t *list, const char *st, const char *val)
{
return _json_add_attr(list, st, (char *)val, 0);
}
void json_del_attrs(attr_t *head)
{
attr_t *prev;
while (head) {
prev = head;
head = head->next;
free(prev);
}
}
/* Resolve uid to username - returns malloc'd value */
char *get_username(int uid)
{
size_t bufsize;
char *buf;
char *name;
struct passwd pwd;
struct passwd *result;
bufsize = sysconf(_SC_GETPW_R_SIZE_MAX);
if (bufsize == -1)
bufsize = 16384;
buf = (char *)alloca(bufsize);
if (!buf) {
return NULL;
}
if (uid == -1) {
return NULL;
}
if (getpwuid_r(uid, &pwd, buf, bufsize, &result) != 0) {
return NULL;
}
if (result == NULL) {
return NULL;
}
name = strdup(pwd.pw_name);
return name;
}
/* Resolve process name from pid */
char *get_proc_name(int pid)
{
char p[1024];
int ret;
static char proc[64];
FILE *fp;
snprintf(p, 512, "/proc/%d/status", pid);
fp = fopen(p, "r");
if (fp) {
ret = fscanf(fp, "Name: %63s", proc);
fclose(fp);
} else
return NULL;
if (ret == 0)
return NULL;
return proc;
}
/* This creates the JSON message we'll send over by deserializing the C struct into a char array
* the function name is rather historical, since this does not send to syslog anymore.
*/
void syslog_json_msg(struct json_msg_type json_msg)
{
attr_t *head = json_msg.details;
attr_t *prev;
queue_t *new_q;
int len;
new_q = malloc(sizeof(queue_t));
if (!new_q) {
syslog(LOG_ERR, "syslog_json_msg() new_q malloc() failed, message lost!");
return;
}
len = snprintf(new_q->msg, MAX_JSON_MSG_SIZE,
"%s{\
\"category\": \"%s\",\
\"summary\": \"%s\",\
\"severity\": \"%s\",\
\"hostname\": \"%s\",\
\"processid\": \"%i\",\
\"processname\": \"%s\",\
\"timestamp\": \"%s\",\
\"tags\": [\
\"%s\",\
\"%s\",\
\"audit\"\
],\
\"details\": {",
config.prepend_msg, json_msg.category, json_msg.summary, json_msg.severity, json_msg.hostname, json_msg.processid,
PROGRAM_NAME, json_msg.timestamp, PROGRAM_NAME, STR(PROGRAM_VERSION));
while (head) {
len += snprintf(new_q->msg+len, MAX_JSON_MSG_SIZE-len, "%s,", head->value);
prev = head;
head = head->next;
free(prev);
if (head == NULL) {
new_q->msg[len-1] = '}';
}
}
len += snprintf(new_q->msg+len, MAX_JSON_MSG_SIZE-len, "}%s\n", config.postpend_msg);
new_q->msg[MAX_JSON_MSG_SIZE-1] = '\0';
/* If using curl, fill up the queue, else just print to file */
if (config.file_log == NULL) {
if (msg_queue_list_size > MAX_CURL_QUEUE_SIZE) {
syslog(LOG_WARNING, "syslog_json_msg() MAX_CURL_QUEUE_SIZE of %u reached, message lost!", MAX_CURL_QUEUE_SIZE);
} else {
new_q->next = msg_queue_list;
msg_queue_list = new_q;
msg_queue_list_size++;
}
} else {
if (fputs(new_q->msg, file_log) < 0) {
/* Retry once (file closed?) */
file_log = fopen(config.file_log, "ab");
if (file_log == NULL || fputs(new_q->msg, file_log) < 0) {
syslog(LOG_ERR, "could not log to file %s", config.file_log);
}
}
free(new_q);
}
}
/* The main event handling, parsing function */
static void handle_event(auparse_state_t *au,
auparse_cb_event_t cb_event_type, void *user_data)
{
int type, num=0;
struct json_msg_type json_msg = {
.category = NULL,
.hostname = hostname,
.processid = 0,
.processname = NULL,
.severity = "INFO",
.summary = NULL,
.timestamp = NULL,
.details = NULL,
};
typedef enum {
CAT_EXECVE,
CAT_READ,
CAT_WRITE,
CAT_PTRACE,
CAT_ATTR,
CAT_APPARMOR,
CAT_CHMOD,
CAT_CHOWN,
CAT_PROMISC,
CAT_TIME,
CAT_SOCKET,
CAT_LISTEN
} category_t;
category_t category;
const char *cwd = NULL, *argc = NULL, *cmd = NULL;
const char *path = NULL;
const char *dev = NULL;
const char *sys;
const char *syscall = NULL;
char fullcmd[MAX_ARG_LEN+1] = "\0";
char serial[64] = "\0";
time_t t;
struct tm *tmp;
char f[8];
int len, tmplen;
int argcount, i;
int promisc;
int havejson = 0;
int haveserial = 0;
int havetypes[128];
/* wait until the lib gives up a full/ready event */
if (cb_event_type != AUPARSE_CB_EVENT_READY) {
return;
}
json_msg.timestamp = (char *)alloca(TS_LEN);
json_msg.summary = (char *)alloca(MAX_SUMMARY_LEN);
if (!json_msg.summary || !json_msg.timestamp) {
syslog(LOG_ERR, "handle_event() alloca failed, message lost!");
return;
}
while (auparse_goto_record_num(au, num) > 0) {
type = auparse_get_type(au);
if (!type)
continue;
havetypes[num] = type;
num++;
/* Don't duplicate msg from types we already have
* Note that this mean we lose certain data msg such as "item=x ..." on purpose
* If you care for these, just know that they are not recorded
* If you wanted them, you need sublists for them and they are not always all that valuable, depending on your
* use case
*/
for (i=0;i<num;i++) {
if (havetypes[i] == type) {
continue;
}
}
if (!auparse_first_field(au))
continue;
if (!haveserial) {
t = auparse_get_time(au);
tmp = localtime(&t);
strftime(json_msg.timestamp, TS_LEN, "%FT%T%z", tmp);
snprintf(serial, TS_LEN-1, "%lu", auparse_get_serial(au));
json_msg.details = json_add_attr(json_msg.details, "auditserial", serial);
haveserial = 1;
}
switch (type) {
case AUDIT_ANOM_PROMISCUOUS:
dev = auparse_find_field(au, "dev");
if (!dev)
return;
category = CAT_PROMISC;
json_msg.details = json_add_attr(json_msg.details, "dev", dev);
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "promiscious", auparse_find_field(au, "prom"));
promisc = auparse_get_field_int(au);
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "old_promicious", auparse_find_field(au, "old_prom"));
goto_record_type(au, type);
if (auparse_find_field(au, "auid")) {
json_msg.details = json_add_attr_free(json_msg.details, "originaluser",
get_username(auparse_get_field_int(au)));
json_msg.details = json_add_attr(json_msg.details, "originaluid", auparse_get_field_str(au));
}
goto_record_type(au, type);
if (auparse_find_field(au, "uid")) {
json_msg.details = json_add_attr_free(json_msg.details, "user", get_username(auparse_get_field_int(au)));
json_msg.details = json_add_attr(json_msg.details, "uid", auparse_get_field_str(au));
}
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "gid", auparse_find_field(au, "gid"));
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "session", auparse_find_field(au, "ses"));
goto_record_type(au, type);
break;
case AUDIT_AVC:
argc = auparse_find_field(au, "apparmor");
if (!argc)
return;
category = CAT_APPARMOR;
json_msg.details = json_add_attr(json_msg.details, "aaresult", auparse_get_field_str(au));
goto_record_type(au, type);
json_msg.summary = unescape(auparse_find_field(au, "info"));
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "aacoperation", auparse_find_field(au, "operation"));
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "aaprofile", auparse_find_field(au, "profile"));
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "aacommand", auparse_find_field(au, "comm"));
goto_record_type(au, type);
if (auparse_find_field(au, "parent"))
json_msg.details = json_add_attr(json_msg.details, "parentprocess",
get_proc_name(auparse_get_field_int(au)));
goto_record_type(au, type);
if (auparse_find_field(au, "pid"))
json_msg.details = json_add_attr(json_msg.details, "processname",
get_proc_name(auparse_get_field_int(au)));
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "aaerror", auparse_find_field(au, "error"));
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "aaname", auparse_find_field(au, "name"));
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "aasrcname", auparse_find_field(au, "srcname"));
goto_record_type(au, type);
json_msg.details = json_add_attr(json_msg.details, "aaflags", auparse_find_field(au, "flags"));
goto_record_type(au, type);
break;
case AUDIT_EXECVE:
argc = auparse_find_field(au, "argc");
if (argc)
argcount = auparse_get_field_int(au);
else
argcount = 0;
fullcmd[0] = '\0';
len = 0;
for (i = 0; i != argcount; i++) {
goto_record_type(au, type);
tmplen = snprintf(f, 7, "a%d", i);
f[tmplen] = '\0';
cmd = auparse_find_field(au, f);
cmd = auparse_interpret_field(au);
if (!cmd)
continue;
if (MAX_ARG_LEN-strlen(fullcmd) > strlen(cmd)) {
if (len == 0)
len += sprintf(fullcmd+len, "%s", cmd);
else
len += sprintf(fullcmd+len, " %s", cmd);
}
}
json_msg.details = json_add_attr(json_msg.details, "command", fullcmd);
break;
case AUDIT_CWD:
cwd = auparse_find_field(au, "cwd");
if (cwd) {
auparse_interpret_field(au);
json_msg.details = json_add_attr(json_msg.details, "cwd", auparse_find_field(au, "cwd"));
}
break;
case AUDIT_PATH:
path = auparse_find_field(au, "name");
json_msg.details = json_add_attr(json_msg.details, "path", path);
goto_record_type(au, type);