blob: 3533c00f6949b1770e83e68b5ec1ccc2b4718861 [file] [log] [blame]
Vernon Tang3f582e92011-04-25 13:08:17 +10001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <cutils/uevent.h>
18
19#include <errno.h>
20#include <strings.h>
21
22#include <linux/netlink.h>
23
24/**
25 * Like recv(), but checks that messages actually originate from the kernel.
26 */
27ssize_t uevent_checked_recv(int socket, void *buffer, size_t length) {
28 struct iovec iov = { buffer, length };
29 struct sockaddr_nl addr;
30 char control[CMSG_SPACE(sizeof(struct ucred))];
31 struct msghdr hdr = {
32 &addr,
33 sizeof(addr),
34 &iov,
35 1,
36 control,
37 sizeof(control),
38 0,
39 };
40
41 ssize_t n = recvmsg(socket, &hdr, 0);
42 if (n <= 0) {
43 return n;
44 }
45
46 if (addr.nl_groups == 0 || addr.nl_pid != 0) {
47 /* ignoring non-kernel or unicast netlink message */
48 goto out;
49 }
50
51 struct cmsghdr *cmsg = CMSG_FIRSTHDR(&hdr);
52 if (cmsg == NULL || cmsg->cmsg_type != SCM_CREDENTIALS) {
53 /* ignoring netlink message with no sender credentials */
54 goto out;
55 }
56
57 struct ucred *cred = (struct ucred *)CMSG_DATA(cmsg);
58 if (cred->uid != 0) {
59 /* ignoring netlink message from non-root user */
60 goto out;
61 }
62
63 return n;
64
65out:
66 /* clear residual potentially malicious data */
67 bzero(buffer, length);
68 errno = EIO;
69 return -1;
70}