Imported Upstream version 2.4.3
[platform/upstream/audit.git] / src / auditd-listen.c
1 /* auditd-listen.c -- 
2  * Copyright 2008,2009,2011 Red Hat Inc., Durham, North Carolina.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  *
19  * Authors:
20  *   DJ Delorie <dj@redhat.com>
21  * 
22  */
23
24 #include "config.h"
25 #include <stdio.h>
26 #include <unistd.h>
27 #include <sys/stat.h>
28 #include <errno.h>
29 #include <string.h>
30 #include <dirent.h>
31 #include <ctype.h>
32 #include <stdlib.h>
33 #include <netdb.h>
34 #include <fcntl.h>      /* O_NOFOLLOW needs gnu defined */
35 #include <libgen.h>
36 #include <arpa/inet.h>
37 #include <limits.h>     /* INT_MAX */
38 #include <sys/types.h>
39 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #ifdef HAVE_LIBWRAP
43 #include <tcpd.h>
44 #endif
45 #ifdef USE_GSSAPI
46 #include <gssapi/gssapi.h>
47 #include <gssapi/gssapi_generic.h>
48 #include <krb5.h>
49 #endif
50 #include "libaudit.h"
51 #include "auditd-event.h"
52 #include "auditd-config.h"
53 #include "private.h"
54
55 #include "ev.h"
56
57 extern volatile int stop;
58 extern int send_audit_event(int type, const char *str);
59 #define DEFAULT_BUF_SZ  192
60
61 typedef struct ev_tcp {
62         struct ev_io io;
63         struct sockaddr_in addr;
64         struct ev_tcp *next, *prev;
65         unsigned int bufptr;
66         int client_active;
67 #ifdef USE_GSSAPI
68         /* This holds the negotiated security context for this client.  */
69         gss_ctx_id_t gss_context;
70         char *remote_name;
71         int remote_name_len;
72 #endif
73         unsigned char buffer [MAX_AUDIT_MESSAGE_LENGTH + 17];
74 } ev_tcp;
75
76 static int listen_socket;
77 static struct ev_io tcp_listen_watcher;
78 static struct ev_periodic periodic_watcher;
79 static int min_port, max_port, max_per_addr;
80 static int use_libwrap = 1;
81 #ifdef USE_GSSAPI
82 /* This is used to hold our own private key.  */
83 static gss_cred_id_t server_creds;
84 static char *my_service_name, *my_gss_realm;
85 static int use_gss = 0;
86 static char msgbuf[MAX_AUDIT_MESSAGE_LENGTH + 1];
87 #endif
88
89 static struct ev_tcp *client_chain = NULL;
90
91 static char *sockaddr_to_ipv4(struct sockaddr_in *addr)
92 {
93         unsigned char *uaddr = (unsigned char *)&(addr->sin_addr);
94         static char buf[40];
95
96         snprintf(buf, sizeof(buf), "%u.%u.%u.%u",
97                 uaddr[0], uaddr[1], uaddr[2], uaddr[3]);
98         return buf;
99 }
100
101 static char *sockaddr_to_addr4(struct sockaddr_in *addr)
102 {
103         unsigned char *uaddr = (unsigned char *)&(addr->sin_addr);
104         static char buf[40];
105
106         snprintf(buf, sizeof(buf), "%u.%u.%u.%u:%u",
107                 uaddr[0], uaddr[1], uaddr[2], uaddr[3],
108                 ntohs (addr->sin_port));
109         return buf;
110 }
111
112 static void set_close_on_exec (int fd)
113 {
114         int flags = fcntl (fd, F_GETFD);
115         if (flags == -1)
116                 flags = 0;
117         flags |= FD_CLOEXEC;
118         fcntl (fd, F_SETFD, flags);
119 }
120
121 static void release_client(struct ev_tcp *client)
122 {
123         char emsg[DEFAULT_BUF_SZ];
124
125         snprintf(emsg, sizeof(emsg), "addr=%s port=%d res=success",
126                 sockaddr_to_ipv4(&client->addr), ntohs (client->addr.sin_port));
127         send_audit_event(AUDIT_DAEMON_CLOSE, emsg); 
128 #ifdef USE_GSSAPI
129         if (client->remote_name)
130                 free (client->remote_name);
131 #endif
132         shutdown(client->io.fd, SHUT_RDWR);
133         close(client->io.fd);
134         if (client_chain == client)
135                 client_chain = client->next;
136         if (client->next)
137                 client->next->prev = client->prev;
138         if (client->prev)
139                 client->prev->next = client->next;
140 }
141
142 static void close_client(struct ev_tcp *client)
143 {
144         release_client (client);
145         free (client);
146 }
147
148 static int ar_write (int sock, const void *buf, int len)
149 {
150         int rc = 0, w;
151         while (len > 0) {
152                 do {
153                         w = write(sock, buf, len);
154                 } while (w < 0 && errno == EINTR);
155                 if (w < 0)
156                         return w;
157                 if (w == 0)
158                         break;
159                 rc += w;
160                 len -= w;
161                 buf = (const void *)((const char *)buf + w);
162         }
163         return rc;
164 }
165
166 #ifdef USE_GSSAPI
167 static int ar_read (int sock, void *buf, int len)
168 {
169         int rc = 0, r;
170         while (len > 0) {
171                 do {
172                         r = read(sock, buf, len);
173                 } while (r < 0 && errno == EINTR);
174                 if (r < 0)
175                         return r;
176                 if (r == 0)
177                         break;
178                 rc += r;
179                 len -= r;
180                 buf = (void *)((char *)buf + r);
181         }
182         return rc;
183 }
184
185
186 /* Communications under GSS is done by token exchanges.  Each "token"
187    may contain a message, perhaps signed, perhaps encrypted.  The
188    messages within are what we're interested in, but the network sees
189    the tokens.  The protocol we use for transferring tokens is to send
190    the length first, four bytes MSB first, then the token data.  We
191    return nonzero on error.  */
192 static int recv_token (int s, gss_buffer_t tok)
193 {
194         int ret;
195         unsigned char lenbuf[4];
196         unsigned int len;
197
198         ret = ar_read(s, (char *) lenbuf, 4);
199         if (ret < 0) {
200                 audit_msg(LOG_ERR, "GSS-API error reading token length");
201                 return -1;
202         } else if (!ret) {
203                 return 0;
204         } else if (ret != 4) {
205                 audit_msg(LOG_ERR, "GSS-API error reading token length");
206                 return -1;
207         }
208
209         len = ((lenbuf[0] << 24)
210                | (lenbuf[1] << 16)
211                | (lenbuf[2] << 8)
212                | lenbuf[3]);
213         if (len > MAX_AUDIT_MESSAGE_LENGTH) {
214                 audit_msg(LOG_ERR,
215                         "GSS-API error: event length excedes MAX_AUDIT_LENGTH");
216                 return -1;
217         }
218         tok->length = len;
219
220         tok->value = (char *) malloc(tok->length ? tok->length : 1);
221         if (tok->length && tok->value == NULL) {
222                 audit_msg(LOG_ERR, "Out of memory allocating token data");
223                 return -1;
224         }
225
226         ret = ar_read(s, (char *) tok->value, tok->length);
227         if (ret < 0) {
228                 audit_msg(LOG_ERR, "GSS-API error reading token data");
229                 free(tok->value);
230                 return -1;
231         } else if (ret != (int) tok->length) {
232                 audit_msg(LOG_ERR, "GSS-API error reading token data");
233                 free(tok->value);
234                 return -1;
235         }
236
237         return 1;
238 }
239
240 /* Same here.  */
241 int send_token(int s, gss_buffer_t tok)
242 {
243         int     ret;
244         unsigned char lenbuf[4];
245         unsigned int len;
246
247         if (tok->length > 0xffffffffUL)
248                 return -1;
249         len = tok->length;
250         lenbuf[0] = (len >> 24) & 0xff;
251         lenbuf[1] = (len >> 16) & 0xff;
252         lenbuf[2] = (len >> 8) & 0xff;
253         lenbuf[3] = len & 0xff;
254
255         ret = ar_write(s, (char *) lenbuf, 4);
256         if (ret < 0) {
257                 audit_msg(LOG_ERR, "GSS-API error sending token length");
258                 return -1;
259         } else if (ret != 4) {
260                 audit_msg(LOG_ERR, "GSS-API error sending token length");
261                 return -1;
262         }
263
264         ret = ar_write(s, tok->value, tok->length);
265         if (ret < 0) {
266                 audit_msg(LOG_ERR, "GSS-API error sending token data");
267                 return -1;
268         } else if (ret != (int) tok->length) {
269                 audit_msg(LOG_ERR, "GSS-API error sending token data");
270                 return -1;
271         }
272
273         return 0;
274 }
275
276
277 static void gss_failure_2 (const char *msg, int status, int type)
278 {
279         OM_uint32 message_context = 0;
280         OM_uint32 min_status = 0;
281         gss_buffer_desc status_string;
282
283         do {
284                 gss_display_status (&min_status,
285                                     status,
286                                     type,
287                                     GSS_C_NO_OID,
288                                     &message_context,
289                                     &status_string);
290
291                 audit_msg (LOG_ERR, "GSS error: %s: %s",
292                            msg, (char *)status_string.value);
293
294                 gss_release_buffer(&min_status, &status_string);
295         } while (message_context != 0);
296 }
297
298 static void gss_failure (const char *msg, int major_status, int minor_status)
299 {
300         gss_failure_2 (msg, major_status, GSS_C_GSS_CODE);
301         if (minor_status)
302                 gss_failure_2 (msg, minor_status, GSS_C_MECH_CODE);
303 }
304
305 #define KCHECK(x,f) if (x) { \
306                 const char *kstr = krb5_get_error_message(kcontext, x); \
307                 audit_msg(LOG_ERR, "krb5 error: %s in %s\n", kstr, f); \
308                 krb5_free_error_message(kcontext, kstr); \
309                 return -1; }
310
311 /* These are our private credentials, which come from a key file on
312    our server.  They are aquired once, at program start.  */
313 static int server_acquire_creds(const char *service_name,
314                 gss_cred_id_t *server_creds)
315 {
316         gss_buffer_desc name_buf;
317         gss_name_t server_name;
318         OM_uint32 major_status, minor_status;
319
320         krb5_context kcontext = NULL;
321         int krberr;
322
323         my_service_name = strdup (service_name);
324         name_buf.value = (char *)service_name;
325         name_buf.length = strlen(name_buf.value) + 1;
326         major_status = gss_import_name(&minor_status, &name_buf,
327                                        (gss_OID) gss_nt_service_name,
328                                         &server_name);
329         if (major_status != GSS_S_COMPLETE) {
330                 gss_failure("importing name", major_status, minor_status);
331                 return -1;
332         }
333
334         major_status = gss_acquire_cred(&minor_status,
335                                         server_name, GSS_C_INDEFINITE,
336                                         GSS_C_NULL_OID_SET, GSS_C_ACCEPT,
337                                         server_creds, NULL, NULL);
338         if (major_status != GSS_S_COMPLETE) {
339                 gss_failure("acquiring credentials",
340                                 major_status, minor_status);
341                 return -1;
342         }
343
344         (void) gss_release_name(&minor_status, &server_name);
345
346         krberr = krb5_init_context (&kcontext);
347         KCHECK (krberr, "krb5_init_context");
348         krberr = krb5_get_default_realm (kcontext, &my_gss_realm);
349         KCHECK (krberr, "krb5_get_default_realm");
350
351         audit_msg(LOG_DEBUG, "GSS creds for %s acquired", service_name);
352
353         return 0;
354 }
355
356 /* This is where we negotiate a security context with the client.  In
357    the case of Kerberos, this is where the key exchange happens.
358    FIXME: While everything else is strictly nonblocking, this
359    negotiation blocks.  */
360 static int negotiate_credentials (ev_tcp *io)
361 {
362         gss_buffer_desc send_tok, recv_tok;
363         gss_name_t client;
364         OM_uint32 maj_stat, min_stat, acc_sec_min_stat;
365         gss_ctx_id_t *context;
366         OM_uint32 sess_flags;
367         char *slashptr, *atptr;
368
369         context = & io->gss_context;
370         *context = GSS_C_NO_CONTEXT;
371
372         maj_stat = GSS_S_CONTINUE_NEEDED;
373         do {
374                 /* STEP 1 - get a token from the client.  */
375
376                 if (recv_token(io->io.fd, &recv_tok) <= 0) {
377                         audit_msg(LOG_ERR,
378                         "TCP session from %s will be closed, error ignored",
379                                   sockaddr_to_addr4(&io->addr));
380                         return -1;
381                 }
382                 if (recv_tok.length == 0)
383                         continue;
384
385                 /* STEP 2 - let GSS process that token.  */
386
387                 maj_stat = gss_accept_sec_context(&acc_sec_min_stat,
388                                         context, server_creds,
389                                         &recv_tok,
390                                         GSS_C_NO_CHANNEL_BINDINGS, &client,
391                                         NULL, &send_tok, &sess_flags,
392                                         NULL, NULL);
393                 if (recv_tok.value) {
394                         free(recv_tok.value);
395                         recv_tok.value = NULL;
396                 }
397                 if (maj_stat != GSS_S_COMPLETE
398                     && maj_stat != GSS_S_CONTINUE_NEEDED) {
399                         gss_release_buffer(&min_stat, &send_tok);
400                         if (*context != GSS_C_NO_CONTEXT)
401                                 gss_delete_sec_context(&min_stat, context,
402                                         GSS_C_NO_BUFFER);
403                         gss_failure("accepting context", maj_stat,
404                                     acc_sec_min_stat);
405                         return -1;
406                 }
407
408                 /* STEP 3 - send any tokens to the client that GSS may
409                    ask us to send.  */
410
411                 if (send_tok.length != 0) {
412                         if (send_token(io->io.fd, &send_tok) < 0) {
413                                 gss_release_buffer(&min_stat, &send_tok);
414                                 audit_msg(LOG_ERR,
415                         "TCP session from %s will be closed, error ignored",
416                                           sockaddr_to_addr4(&io->addr));
417                                 if (*context != GSS_C_NO_CONTEXT)
418                                         gss_delete_sec_context(&min_stat,
419                                                 context, GSS_C_NO_BUFFER);
420                                 return -1;
421                         }
422                         gss_release_buffer(&min_stat, &send_tok);
423                 }
424         } while (maj_stat == GSS_S_CONTINUE_NEEDED);
425
426         maj_stat = gss_display_name(&min_stat, client, &recv_tok, NULL);
427         gss_release_name(&min_stat, &client);
428
429         if (maj_stat != GSS_S_COMPLETE) {
430                 gss_failure("displaying name", maj_stat, min_stat);
431                 return -1;
432         }
433
434         audit_msg(LOG_INFO, "GSS-API Accepted connection from: %s",
435                   (char *)recv_tok.value);
436         io->remote_name = strdup (recv_tok.value);
437         io->remote_name_len = strlen (recv_tok.value);
438         gss_release_buffer(&min_stat, &recv_tok);
439
440         slashptr = strchr (io->remote_name, '/');
441         atptr = strchr (io->remote_name, '@');
442
443         if (!slashptr || !atptr) {
444                 audit_msg(LOG_ERR, "Invalid GSS name from remote client: %s",
445                           io->remote_name);
446                 return -1;
447         }
448
449         *slashptr = 0;
450         if (strcmp (io->remote_name, my_service_name)) {
451                 audit_msg(LOG_ERR, "Unauthorized GSS client name: %s (not %s)",
452                           io->remote_name, my_service_name);
453                 return -1;
454         }
455         *slashptr = '/';
456
457         if (strcmp (atptr+1, my_gss_realm)) {
458                 audit_msg(LOG_ERR, "Unauthorized GSS client realm: %s (not %s)",
459                           atptr+1, my_gss_realm);
460                 return -1;
461         }
462
463         return 0;
464 }
465 #endif /* USE_GSSAPI */
466
467 /* This is called from auditd-event after the message has been logged.
468    The header is already filled in.  */
469 static void client_ack (void *ack_data, const unsigned char *header,
470         const char *msg)
471 {
472         ev_tcp *io = (ev_tcp *)ack_data;
473 #ifdef USE_GSSAPI
474         if (use_gss) {
475                 OM_uint32 major_status, minor_status;
476                 gss_buffer_desc utok, etok;
477                 int rc, mlen;
478
479                 mlen = strlen (msg);
480                 utok.length = AUDIT_RMW_HEADER_SIZE + mlen;
481                 utok.value = malloc (utok.length + 1);
482
483                 memcpy (utok.value, header, AUDIT_RMW_HEADER_SIZE);
484                 memcpy (utok.value+AUDIT_RMW_HEADER_SIZE, msg, mlen);
485
486                 /* Wrapping the message creates a token for the
487                    client.  Then we just have to worry about sending
488                    the token.  */
489
490                 major_status = gss_wrap (&minor_status,
491                                          io->gss_context,
492                                          1,
493                                          GSS_C_QOP_DEFAULT,
494                                          &utok,
495                                          NULL,
496                                          &etok);
497                 if (major_status != GSS_S_COMPLETE) {
498                         gss_failure("encrypting message", major_status,
499                                         minor_status);
500                         free (utok.value);
501                         return;
502                 }
503                 // FIXME: What were we going to do with rc?
504                 rc = send_token (io->io.fd, &etok);
505                 free (utok.value);
506                 (void) gss_release_buffer(&minor_status, &etok);
507
508                 return;
509         }
510 #endif
511         // Send the header and a text error message if it exists
512         ar_write (io->io.fd, header, AUDIT_RMW_HEADER_SIZE);
513         if (msg[0])
514                 ar_write (io->io.fd, msg, strlen(msg));
515 }
516
517 static void client_message (struct ev_tcp *io, unsigned int length,
518         unsigned char *header)
519 {
520         unsigned char ch;
521         uint32_t type, mlen, seq;
522         int hver, mver;
523
524         if (AUDIT_RMW_IS_MAGIC (header, length)) {
525                 AUDIT_RMW_UNPACK_HEADER (header, hver, mver, type, mlen, seq)
526
527                 ch = header[length];
528                 header[length] = 0;
529                 if (length > 1 && header[length-1] == '\n')
530                         header[length-1] = 0;
531                 if (type == AUDIT_RMW_TYPE_HEARTBEAT) {
532                         unsigned char ack[AUDIT_RMW_HEADER_SIZE];
533                         AUDIT_RMW_PACK_HEADER (ack, 0, AUDIT_RMW_TYPE_ACK,
534                                 0, seq);
535                         client_ack (io, ack, "");
536                 } else 
537                         enqueue_formatted_event(header+AUDIT_RMW_HEADER_SIZE,
538                                 client_ack, io, seq);
539                 header[length] = ch;
540         } else {
541                 header[length] = 0;
542                 if (length > 1 && header[length-1] == '\n')
543                         header[length-1] = 0;
544                 enqueue_formatted_event (header, NULL, NULL, 0);
545         }
546 }
547
548 static void auditd_tcp_client_handler( struct ev_loop *loop,
549                         struct ev_io *_io, int revents )
550 {
551         struct ev_tcp *io = (struct ev_tcp *) _io;
552         int i, r;
553         int total_this_call = 0;
554
555         io->client_active = 1;
556
557         /* The socket is non-blocking, but we have a limited buffer
558            size.  In the event that we get a packet that's bigger than
559            our buffer, we need to read it in multiple parts.  Thus, we
560            keep reading/parsing/processing until we run out of ready
561            data.  */
562 read_more:
563         r = read (io->io.fd,
564                   io->buffer + io->bufptr,
565                   MAX_AUDIT_MESSAGE_LENGTH - io->bufptr);
566
567         if (r < 0 && errno == EAGAIN)
568                 r = 0;
569
570         /* We need to keep track of the difference between "no data
571          * because it's closed" and "no data because we've read it
572          * all".  */
573         if (r == 0 && total_this_call > 0) {
574                 return;
575         }
576
577         /* If the connection is gracefully closed, the first read we
578            try will return zero.  If the connection times out or
579            otherwise fails, the read will return -1.  */
580         if (r <= 0) {
581                 if (r < 0)
582                         audit_msg (LOG_WARNING,
583                                 "client %s socket closed unexpectedly",
584                                 sockaddr_to_addr4(&io->addr));
585
586                 /* There may have been a final message without a LF.  */
587                 if (io->bufptr) {
588                         client_message (io, io->bufptr, io->buffer);
589
590                 }
591
592                 ev_io_stop (loop, _io);
593                 close_client (io);
594                 return;
595         }
596
597         total_this_call += r;
598
599 more_messages:
600 #ifdef USE_GSSAPI
601         /* If we're using GSS at all, everything will be encrypted,
602            one record per token.  */
603         if (use_gss) {
604                 gss_buffer_desc utok, etok;
605                 io->bufptr += r;
606                 uint32_t len;
607                 OM_uint32 major_status, minor_status;
608
609                 /* We need at least four bytes to test the length.  If
610                    we have more than four bytes, we can tell if we
611                    have a whole token (or more).  */
612
613                 if (io->bufptr < 4)
614                         return;
615
616                 len = (  ((uint32_t)(io->buffer[0] & 0xFF) << 24)
617                        | ((uint32_t)(io->buffer[1] & 0xFF) << 16)
618                        | ((uint32_t)(io->buffer[2] & 0xFF) << 8)
619                        |  (uint32_t)(io->buffer[3] & 0xFF));
620
621                 /* Make sure we got something big enough and not too big */
622                 if (io->bufptr < 4 + len || len > MAX_AUDIT_MESSAGE_LENGTH)
623                         return;
624                 i = len + 4;
625
626                 etok.length = len;
627                 etok.value = io->buffer + 4;
628
629                 /* Unwrapping the token gives us the original message,
630                    which we know is already a single record.  */
631                 major_status = gss_unwrap (&minor_status, io->gss_context,
632                                 &etok, &utok, NULL, NULL);
633
634                 if (major_status != GSS_S_COMPLETE) {
635                         gss_failure("decrypting message", major_status,
636                                 minor_status);
637                 } else {
638                         /* client_message() wants to NUL terminate it,
639                            so copy it to a bigger buffer.  Plus, we
640                            want to add our own tag.  */
641                         memcpy (msgbuf, utok.value, utok.length);
642                         while (utok.length > 0 && msgbuf[utok.length-1] == '\n')
643                                 utok.length --;
644                         snprintf (msgbuf + utok.length,
645                                 MAX_AUDIT_MESSAGE_LENGTH - utok.length,
646                                 " krb5=%s", io->remote_name);
647                         utok.length += 6 + io->remote_name_len;
648                         client_message (io, utok.length, msgbuf);
649                         gss_release_buffer(&minor_status, &utok);
650                 }
651         } else
652 #endif
653         if (AUDIT_RMW_IS_MAGIC (io->buffer, (io->bufptr+r))) {
654                 uint32_t type, len, seq;
655                 int hver, mver;
656                 unsigned char *header = (unsigned char *)io->buffer;
657
658                 io->bufptr += r;
659
660                 if (io->bufptr < AUDIT_RMW_HEADER_SIZE)
661                         return;
662
663                 AUDIT_RMW_UNPACK_HEADER (header, hver, mver, type, len, seq);
664
665                 /* Make sure len is not too big */
666                 if (len > MAX_AUDIT_MESSAGE_LENGTH)
667                         return;
668
669                 i = len;
670                 i += AUDIT_RMW_HEADER_SIZE;
671
672                 /* See if we have enough bytes to extract the whole message.  */
673                 if (io->bufptr < i)
674                         return;
675                 
676                 /* We have an I-byte message in buffer. Send ACK */
677                 client_message (io, i, io->buffer);
678
679         } else {
680                 /* At this point, the buffer has IO->BUFPTR+R bytes in it.
681                    The first IO->BUFPTR bytes do not have a LF in them (we've
682                    already checked), we must check the R new bytes.  */
683
684                 for (i = io->bufptr; i < io->bufptr + r; i ++)
685                         if (io->buffer [i] == '\n')
686                                 break;
687
688                 io->bufptr += r;
689
690                 /* Check for a partial message, with no LF yet.  */
691                 if (i == io->bufptr)
692                         return;
693
694                 i++;
695
696                 /* We have an I-byte message in buffer. Send ACK */
697                 client_message (io, i, io->buffer);
698         }
699
700         /* Now copy any remaining bytes to the beginning of the
701            buffer.  */
702         memmove(io->buffer, io->buffer + i, io->bufptr - i);
703         io->bufptr -= i;
704
705         /* See if this packet had more than one message in it. */
706         if (io->bufptr > 0) {
707                 r = io->bufptr;
708                 io->bufptr = 0;
709                 goto more_messages;
710         }
711
712         /* Go back and see if there's more data to read.  */
713         goto read_more;
714 }
715
716 #ifndef HAVE_LIBWRAP
717 #define auditd_tcpd_check(s) ({ 0; })
718 #else
719 int allow_severity = LOG_INFO, deny_severity = LOG_NOTICE;
720 static int auditd_tcpd_check(int sock)
721 {
722         struct request_info request;
723
724         request_init(&request, RQ_DAEMON, "auditd", RQ_FILE, sock, 0);
725         fromhost(&request);
726         if (! hosts_access(&request))
727                 return 1;
728         return 0;
729 }
730 #endif
731
732 /*
733  * This function counts the number of concurrent connections and returns
734  * a 1 if there are too many and a 0 otherwise. It assumes the incoming
735  * connection has not been added to the linked list yet.
736  */
737 static int check_num_connections(struct sockaddr_in *aaddr)
738 {
739         int num = 0;
740         struct ev_tcp *client = client_chain;
741
742         while (client) {
743                 if (memcmp(&aaddr->sin_addr, &client->addr.sin_addr, 
744                                         sizeof(struct in_addr)) == 0) {
745                         num++;
746                         if (num >= max_per_addr)
747                                 return 1;
748                 }
749                 client = client->next;
750         }
751         return 0;
752 }
753
754 static void auditd_tcp_listen_handler( struct ev_loop *loop,
755         struct ev_io *_io, int revents )
756 {
757         int one=1;
758         int afd;
759         socklen_t aaddrlen;
760         struct sockaddr_in aaddr;
761         struct ev_tcp *client;
762         char emsg[DEFAULT_BUF_SZ];
763
764         /* Accept the connection and see where it's coming from.  */
765         aaddrlen = sizeof(aaddr);
766         afd = accept (listen_socket, (struct sockaddr *)&aaddr, &aaddrlen);
767         if (afd == -1) {
768                 audit_msg(LOG_ERR, "Unable to accept TCP connection");
769                 return;
770         }
771
772         if (use_libwrap) {
773                 if (auditd_tcpd_check(afd)) {
774                         shutdown(afd, SHUT_RDWR);
775                         close(afd);
776                         audit_msg(LOG_ERR, "TCP connection from %s rejected",
777                                         sockaddr_to_addr4(&aaddr));
778                         snprintf(emsg, sizeof(emsg),
779                                 "op=wrap addr=%s port=%d res=no",
780                                 sockaddr_to_ipv4(&aaddr),
781                                 ntohs (aaddr.sin_port));
782                         send_audit_event(AUDIT_DAEMON_ACCEPT, emsg);
783                         return;
784                 }
785         }
786
787         /* Verify it's coming from an authorized port.  We assume the firewall
788          * will block attempts from unauthorized machines.  */
789         if (min_port > ntohs (aaddr.sin_port) ||
790                                         ntohs (aaddr.sin_port) > max_port) {
791                 audit_msg(LOG_ERR, "TCP connection from %s rejected",
792                                 sockaddr_to_addr4(&aaddr));
793                 snprintf(emsg, sizeof(emsg),
794                         "op=port addr=%s port=%d res=no",
795                         sockaddr_to_ipv4(&aaddr),
796                         ntohs (aaddr.sin_port));
797                 send_audit_event(AUDIT_DAEMON_ACCEPT, emsg);
798                 shutdown(afd, SHUT_RDWR);
799                 close(afd);
800                 return;
801         }
802
803         /* Make sure we don't have too many connections */
804         if (check_num_connections(&aaddr)) {
805                 audit_msg(LOG_ERR, "Too many connections from %s - rejected",
806                                 sockaddr_to_addr4(&aaddr));
807                 snprintf(emsg, sizeof(emsg),
808                         "op=dup addr=%s port=%d res=no",
809                         sockaddr_to_ipv4(&aaddr),
810                         ntohs (aaddr.sin_port));
811                 send_audit_event(AUDIT_DAEMON_ACCEPT, emsg);
812                 shutdown(afd, SHUT_RDWR);
813                 close(afd);
814                 return;
815         }
816
817         /* Connection is accepted...start setting it up */
818         setsockopt(afd, SOL_SOCKET, SO_REUSEADDR, (char *)&one, sizeof (int));
819         setsockopt(afd, SOL_SOCKET, SO_KEEPALIVE, (char *)&one, sizeof (int));
820         setsockopt(afd, IPPROTO_TCP, TCP_NODELAY, (char *)&one, sizeof (int));
821         set_close_on_exec (afd);
822
823         /* Make the client data structure */
824         client = (struct ev_tcp *) malloc (sizeof (struct ev_tcp));
825         if (client == NULL) {
826                 audit_msg(LOG_CRIT, "Unable to allocate TCP client data");
827                 snprintf(emsg, sizeof(emsg),
828                         "op=alloc addr=%s port=%d res=no",
829                         sockaddr_to_ipv4(&aaddr),
830                         ntohs (aaddr.sin_port));
831                 send_audit_event(AUDIT_DAEMON_ACCEPT, emsg);
832                 shutdown(afd, SHUT_RDWR);
833                 close(afd);
834                 return;
835         }
836
837         memset (client, 0, sizeof (struct ev_tcp));
838         client->client_active = 1;
839
840         // Was watching for EV_ERROR, but libev 3.48 took it away
841         ev_io_init (&(client->io), auditd_tcp_client_handler, afd, EV_READ);
842
843         memcpy (&client->addr, &aaddr, sizeof (struct sockaddr_in));
844
845 #ifdef USE_GSSAPI
846         if (use_gss && negotiate_credentials (client)) {
847                 shutdown(afd, SHUT_RDWR);
848                 close(afd);
849                 free(client);
850                 return;
851         }
852 #endif
853
854         fcntl(afd, F_SETFL, O_NONBLOCK | O_NDELAY);
855         ev_io_start (loop, &(client->io));
856
857         /* Add the new connection to a linked list of active clients.  */
858         client->next = client_chain;
859         if (client->next)
860                 client->next->prev = client;
861         client_chain = client;
862
863         /* And finally log that we accepted the connection */
864         snprintf(emsg, sizeof(emsg),
865                 "addr=%s port=%d res=success", sockaddr_to_ipv4(&aaddr),
866                 ntohs (aaddr.sin_port));
867         send_audit_event(AUDIT_DAEMON_ACCEPT, emsg);
868 }
869
870 static void auditd_set_ports(int minp, int maxp, int max_p_addr)
871 {
872         min_port = minp;
873         max_port = maxp;
874         max_per_addr = max_p_addr;
875 }
876
877 static void periodic_handler(struct ev_loop *loop, struct ev_periodic *per,
878                         int revents )
879 {
880         struct daemon_conf *config = (struct daemon_conf *) per->data;
881         struct ev_tcp *ev, *next = NULL;
882         int active;
883
884         if (!config->tcp_client_max_idle)
885                 return;
886
887         for (ev = client_chain; ev; ev = next) {
888                 active = ev->client_active;
889                 ev->client_active = 0;
890                 if (active)
891                         continue;
892
893                 audit_msg(LOG_NOTICE,
894                         "client %s idle too long - closing connection\n",
895                         sockaddr_to_addr4(&(ev->addr)));
896                 ev_io_stop (loop, &ev->io);
897                 release_client(ev);
898                 next = ev->next;
899                 free(ev);
900         }
901 }
902
903 int auditd_tcp_listen_init ( struct ev_loop *loop, struct daemon_conf *config )
904 {
905         struct sockaddr_in address;
906         int one = 1;
907
908         ev_periodic_init (&periodic_watcher, periodic_handler,
909                           0, config->tcp_client_max_idle, NULL);
910         periodic_watcher.data = config;
911         if (config->tcp_client_max_idle)
912                 ev_periodic_start (loop, &periodic_watcher);
913
914         /* If the port is not set, that means we aren't going to
915           listen for connections.  */
916         if (config->tcp_listen_port == 0)
917                 return 0;
918
919         listen_socket = socket (AF_INET, SOCK_STREAM, 0);
920         if (listen_socket < 0) {
921                 audit_msg(LOG_ERR, "Cannot create tcp listener socket");
922                 return 1;
923         }
924
925         set_close_on_exec (listen_socket);
926         setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR,
927                         (char *)&one, sizeof (int));
928
929         memset (&address, 0, sizeof(address));
930         address.sin_family = AF_INET;
931         address.sin_port = htons(config->tcp_listen_port);
932         address.sin_addr.s_addr = htonl(INADDR_ANY);
933
934         /* This avoids problems if auditd needs to be restarted.  */
935         setsockopt(listen_socket, SOL_SOCKET, SO_REUSEADDR,
936                         (char *)&one, sizeof (int));
937
938         if (bind(listen_socket, (struct sockaddr *)&address, sizeof(address))){
939                 audit_msg(LOG_ERR,
940                         "Cannot bind tcp listener socket to port %ld",
941                         config->tcp_listen_port);
942                 close(listen_socket);
943                 return 1;
944         }
945
946         listen(listen_socket, config->tcp_listen_queue);
947
948         audit_msg(LOG_DEBUG, "Listening on TCP port %ld",
949                 config->tcp_listen_port);
950
951         ev_io_init (&tcp_listen_watcher, auditd_tcp_listen_handler,
952                         listen_socket, EV_READ);
953         ev_io_start (loop, &tcp_listen_watcher);
954
955         use_libwrap = config->use_libwrap;
956         auditd_set_ports(config->tcp_client_min_port,
957                         config->tcp_client_max_port,
958                         config->tcp_max_per_addr);
959
960 #ifdef USE_GSSAPI
961         if (config->enable_krb5) {
962                 const char *princ = config->krb5_principal;
963                 const char *key_file;
964                 struct stat st;
965
966                 if (!princ)
967                         princ = "auditd";
968                 use_gss = 1;
969                 /* This may fail, but we don't care.  */
970                 unsetenv ("KRB5_KTNAME");
971                 if (config->krb5_key_file)
972                         key_file = config->krb5_key_file;
973                 else
974                         key_file = "/etc/audit/audit.key";
975                 setenv ("KRB5_KTNAME", key_file, 1);
976
977                 if (stat (key_file, &st) == 0) {
978                         if ((st.st_mode & 07777) != 0400) {
979                                 audit_msg (LOG_ERR,
980                          "%s is not mode 0400 (it's %#o) - compromised key?",
981                                            key_file, st.st_mode & 07777);
982                                 return -1;
983                         }
984                         if (st.st_uid != 0) {
985                                 audit_msg (LOG_ERR,
986                          "%s is not owned by root (it's %d) - compromised key?",
987                                            key_file, st.st_uid);
988                                 return -1;
989                         }
990                 }
991
992                 server_acquire_creds(princ, &server_creds);
993         }
994 #endif
995
996         return 0;
997 }
998
999 void auditd_tcp_listen_uninit ( struct ev_loop *loop,
1000                                 struct daemon_conf *config )
1001 {
1002 #ifdef USE_GSSAPI
1003         OM_uint32 status;
1004 #endif
1005
1006         ev_io_stop ( loop, &tcp_listen_watcher );
1007         close ( listen_socket );
1008
1009 #ifdef USE_GSSAPI
1010         if (use_gss) {
1011                 use_gss = 0;
1012                 gss_release_cred(&status, &server_creds);
1013         }
1014 #endif
1015
1016         while (client_chain) {
1017                 unsigned char ack[AUDIT_RMW_HEADER_SIZE];
1018
1019                 AUDIT_RMW_PACK_HEADER (ack, 0, AUDIT_RMW_TYPE_ENDING, 0, 0);
1020                 client_ack (client_chain, ack, "");
1021                 ev_io_stop (loop, &client_chain->io);
1022                 close_client (client_chain);
1023         }
1024
1025         if (config->tcp_client_max_idle)
1026                 ev_periodic_stop (loop, &periodic_watcher);
1027 }
1028
1029 static void periodic_reconfigure(struct daemon_conf *config)
1030 {
1031         struct ev_loop *loop = ev_default_loop (EVFLAG_AUTO);
1032         if (config->tcp_client_max_idle) {
1033                 ev_periodic_set (&periodic_watcher, ev_now (loop),
1034                                  config->tcp_client_max_idle, NULL);
1035                 ev_periodic_start (loop, &periodic_watcher);
1036         } else {
1037                 ev_periodic_stop (loop, &periodic_watcher);
1038         }
1039 }
1040
1041 void auditd_tcp_listen_reconfigure ( struct daemon_conf *nconf,
1042                                      struct daemon_conf *oconf )
1043 {
1044         /* Look at network things that do not need restarting */
1045         if (oconf->tcp_client_min_port != nconf->tcp_client_min_port ||
1046                     oconf->tcp_client_max_port != nconf->tcp_client_max_port ||
1047                     oconf->tcp_max_per_addr != nconf->tcp_max_per_addr) {
1048                 oconf->tcp_client_min_port = nconf->tcp_client_min_port;
1049                 oconf->tcp_client_max_port = nconf->tcp_client_max_port;
1050                 oconf->tcp_max_per_addr = nconf->tcp_max_per_addr;
1051                 auditd_set_ports(oconf->tcp_client_min_port,
1052                                 oconf->tcp_client_max_port,
1053                                 oconf->tcp_max_per_addr);
1054         }
1055         if (oconf->tcp_client_max_idle != nconf->tcp_client_max_idle) {
1056                 oconf->tcp_client_max_idle = nconf->tcp_client_max_idle;
1057                 periodic_reconfigure(oconf);
1058         }
1059         if (oconf->tcp_listen_port != nconf->tcp_listen_port ||
1060                         oconf->tcp_listen_queue != nconf->tcp_listen_queue) {
1061                 oconf->tcp_listen_port = nconf->tcp_listen_port;
1062                 oconf->tcp_listen_queue = nconf->tcp_listen_queue;
1063                 // FIXME: need to restart the network stuff
1064         }
1065 }