1 /*
2  * Copyright 2012, Samsung Telecommunications of America
3  * Copyright (C) 2014 The Android Open Source Project
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * Written by William Roberts <w.roberts@sta.samsung.com>
18  *
19  */
20 
21 #include <errno.h>
22 #include <string.h>
23 #include <unistd.h>
24 
25 #define LOG_TAG "libaudit"
26 #include <log/log.h>
27 
28 #include "libaudit.h"
29 
30 /**
31  * Waits for an ack from the kernel
32  * @param fd
33  *  The netlink socket fd
34  * @param seq
35  *  The current sequence number were acking on
36  * @return
37  *  This function returns 0 on success, else -errno.
38  */
get_ack(int fd,int16_t seq)39 static int get_ack(int fd, int16_t seq)
40 {
41     int rc;
42     struct audit_message rep;
43 
44     /* Sanity check, this is an internal interface this shouldn't happen */
45     if (fd < 0) {
46         return -EINVAL;
47     }
48 
49     rc = audit_get_reply(fd, &rep, GET_REPLY_BLOCKING, MSG_PEEK);
50     if (rc < 0) {
51         return rc;
52     }
53 
54     if (rep.nlh.nlmsg_type == NLMSG_ERROR) {
55         audit_get_reply(fd, &rep, GET_REPLY_BLOCKING, 0);
56         rc = ((struct nlmsgerr *)rep.data)->error;
57         if (rc) {
58             return -rc;
59         }
60     }
61 
62     if ((int16_t)rep.nlh.nlmsg_seq != seq) {
63         SLOGW("Expected sequence number between user space and kernel space is out of skew, "
64           "expected %u got %u", seq, rep.nlh.nlmsg_seq);
65     }
66 
67     return 0;
68 }
69 
70 /**
71  *
72  * @param fd
73  *  The netlink socket fd
74  * @param type
75  *  The type of netlink message
76  * @param data
77  *  The data to send
78  * @param size
79  *  The length of the data in bytes
80  * @return
81  *  This function returns a positive sequence number on success, else -errno.
82  */
audit_send(int fd,int type,const void * data,size_t size)83 static int audit_send(int fd, int type, const void *data, size_t size)
84 {
85     int rc;
86     static int16_t sequence = 0;
87     struct audit_message req;
88     struct sockaddr_nl addr;
89 
90     memset(&req, 0, sizeof(req));
91     memset(&addr, 0, sizeof(addr));
92 
93     /* We always send netlink messaged */
94     addr.nl_family = AF_NETLINK;
95 
96     /* Set up the netlink headers */
97     req.nlh.nlmsg_type = type;
98     req.nlh.nlmsg_len = NLMSG_SPACE(size);
99     req.nlh.nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
100 
101     /*
102      * Check for a valid fd, even though sendto would catch this, its easier
103      * to always blindly increment the sequence number
104      */
105     if (fd < 0) {
106         return -EBADF;
107     }
108 
109     /* Ensure the message is not too big */
110     if (NLMSG_SPACE(size) > MAX_AUDIT_MESSAGE_LENGTH) {
111         SLOGE("netlink message is too large");
112         return -EINVAL;
113     }
114 
115     /* Only memcpy in the data if it was specified */
116     if (size && data) {
117         memcpy(NLMSG_DATA(&req.nlh), data, size);
118     }
119 
120     /*
121      * Only increment the sequence number on a guarantee
122      * you will send it to the kernel.
123      *
124      * Also, the sequence is defined as a u32 in the kernel
125      * struct. Using an int here might not work on 32/64 bit splits. A
126      * signed 64 bit value can overflow a u32..but a u32
127      * might not fit in the response, so we need to use s32.
128      * Which is still kind of hackish since int could be 16 bits
129      * in size. The only safe type to use here is a signed 16
130      * bit value.
131      */
132     req.nlh.nlmsg_seq = ++sequence;
133 
134     /* While failing and its due to interrupts */
135 
136     rc = TEMP_FAILURE_RETRY(sendto(fd, &req, req.nlh.nlmsg_len, 0,
137                                    (struct sockaddr*) &addr, sizeof(addr)));
138 
139     /* Not all the bytes were sent */
140     if (rc < 0) {
141         rc = -errno;
142         SLOGE("Error sending data over the netlink socket: %s", strerror(-errno));
143         goto out;
144     } else if ((uint32_t) rc != req.nlh.nlmsg_len) {
145         rc = -EPROTO;
146         goto out;
147     }
148 
149     /* We sent all the bytes, get the ack */
150     rc = get_ack(fd, sequence);
151 
152     /* If the ack failed, return the error, else return the sequence number */
153     rc = (rc == 0) ? (int) sequence : rc;
154 
155 out:
156     /* Don't let sequence roll to negative */
157     if (sequence < 0) {
158         SLOGW("Auditd to Kernel sequence number has rolled over");
159         sequence = 0;
160     }
161 
162     return rc;
163 }
164 
audit_setup(int fd,uint32_t pid)165 int audit_setup(int fd, uint32_t pid)
166 {
167     int rc;
168     struct audit_message rep;
169     struct audit_status status;
170 
171     memset(&status, 0, sizeof(status));
172 
173     /*
174      * In order to set the auditd PID we send an audit message over the netlink
175      * socket with the pid field of the status struct set to our current pid,
176      * and the the mask set to AUDIT_STATUS_PID
177      */
178     status.pid = pid;
179     status.mask = AUDIT_STATUS_PID | AUDIT_STATUS_RATE_LIMIT;
180     status.rate_limit = 20; // audit entries per second
181 
182     /* Let the kernel know this pid will be registering for audit events */
183     rc = audit_send(fd, AUDIT_SET, &status, sizeof(status));
184     if (rc < 0) {
185         SLOGE("Could net set pid for audit events, error: %s", strerror(-rc));
186         return rc;
187     }
188 
189     /*
190      * In a request where we need to wait for a response, wait for the message
191      * and discard it. This message confirms and sync's us with the kernel.
192      * This daemon is now registered as the audit logger.
193      *
194      * TODO
195      * If the daemon dies and restarts the message didn't come back,
196      * so I went to non-blocking and it seemed to fix the bug.
197      * Need to investigate further.
198      */
199     audit_get_reply(fd, &rep, GET_REPLY_NONBLOCKING, 0);
200 
201     return 0;
202 }
203 
audit_open()204 int audit_open()
205 {
206     return socket(PF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_AUDIT);
207 }
208 
audit_get_reply(int fd,struct audit_message * rep,reply_t block,int peek)209 int audit_get_reply(int fd, struct audit_message *rep, reply_t block, int peek)
210 {
211     ssize_t len;
212     int flags;
213     int rc = 0;
214 
215     struct sockaddr_nl nladdr;
216     socklen_t nladdrlen = sizeof(nladdr);
217 
218     if (fd < 0) {
219         return -EBADF;
220     }
221 
222     /* Set up the flags for recv from */
223     flags = (block == GET_REPLY_NONBLOCKING) ? MSG_DONTWAIT : 0;
224     flags |= peek;
225 
226     /*
227      * Get the data from the netlink socket but on error we need to be carefull,
228      * the interface shows that EINTR can never be returned, other errors,
229      * however, can be returned.
230      */
231     len = TEMP_FAILURE_RETRY(recvfrom(fd, rep, sizeof(*rep), flags,
232                                       (struct sockaddr*) &nladdr, &nladdrlen));
233 
234     /*
235      * EAGAIN should be re-tried until success or another error manifests.
236      */
237     if (len < 0) {
238         rc = -errno;
239         if (block == GET_REPLY_NONBLOCKING && rc == -EAGAIN) {
240             /* If request is non blocking and errno is EAGAIN, just return 0 */
241             return 0;
242         }
243         SLOGE("Error receiving from netlink socket, error: %s", strerror(-rc));
244         return rc;
245     }
246 
247     if (nladdrlen != sizeof(nladdr)) {
248         SLOGE("Protocol fault, error: %s", strerror(EPROTO));
249         return -EPROTO;
250     }
251 
252     /* Make sure the netlink message was not spoof'd */
253     if (nladdr.nl_pid) {
254         SLOGE("Invalid netlink pid received, expected 0 got: %d", nladdr.nl_pid);
255         return -EINVAL;
256     }
257 
258     /* Check if the reply from the kernel was ok */
259     if (!NLMSG_OK(&rep->nlh, (size_t)len)) {
260         rc = (len == sizeof(*rep)) ? -EFBIG : -EBADE;
261         SLOGE("Bad kernel response %s", strerror(-rc));
262     }
263 
264     return rc;
265 }
266 
audit_close(int fd)267 void audit_close(int fd)
268 {
269     int rc = close(fd);
270     if (rc < 0) {
271         SLOGE("Attempting to close invalid fd %d, error: %s", fd, strerror(errno));
272     }
273     return;
274 }
275