#include #include #include #include #include #include #include #include #include #include #include #include "log.h" #define EVENT_TIMEOUT 2000 void child(char *runpath) { pid_t pid; if (!(pid = fork())) { dbg("running %s", runpath); if (execlp(runpath, basename(runpath), NULL) < 0) edie("execvp"); exit(0); } if (pid < 0) edie("fork"); waitpid(pid, NULL, 0); } void usage(void) { die("usage: %s [-dku] [-f subsystem] [-r run]\n", argv0); } int main(int argc, char *argv[]) { struct pollfd fds; int r; char *runpath = "/bin/mdev"; char *subsystem = NULL; int showudev, showkernel; showudev = 1; showkernel = 1; ARGBEGIN { case 'd': dodebug = 1; break; case 'k': showudev = 0; break; case 'u': showkernel = 0; break; case 'r': runpath = EARGF(usage()); break; case 'f': subsystem = EARGF(usage()); break; default: usage(); } ARGEND; dbg("runpath=%s\n", runpath); fds.fd = 0; /* stdin */ fds.events = POLLIN; while ((r = poll(&fds, 1, EVENT_TIMEOUT)) > 0) { size_t len; int i, slen; char *key, *value; struct iovec iov; char cbuf[CMSG_SPACE(sizeof(struct ucred))]; char buf[16384]; struct cmsghdr *chdr; struct ucred *cred; struct msghdr hdr; struct sockaddr_nl cnls; clearenv(); setenv("PATH", "/sbin:/bin", 1); if (!(fds.revents & POLLIN)) continue; iov.iov_base = &buf; iov.iov_len = sizeof(buf); memset(&hdr, 0, sizeof(hdr)); hdr.msg_iov = &iov; hdr.msg_iovlen = 1; hdr.msg_control = cbuf; hdr.msg_controllen = sizeof(cbuf); hdr.msg_name = &cnls; hdr.msg_namelen = sizeof(cnls); len = recvmsg(fds.fd, &hdr, 0); if (len < 0) { if (errno == EINTR) continue; edie("recvmsg"); } if (len < 32 || len >= sizeof(buf)) continue; chdr = CMSG_FIRSTHDR(&hdr); if (chdr == NULL || chdr->cmsg_type != SCM_CREDENTIALS) continue; /* * Don't allow anyone but root to send us messages. * * We will allow users to send us messages, when * udev is enabled. Udev is just a toy you should * only use for testing. */ cred = (struct ucred *)CMSG_DATA(chdr); if (cred->uid != 0 && !showudev) continue; if (!memcmp(buf, "libudev", 8)) { /* * Receiving messages from udev is insecure. */ if (!showudev) continue; } else { if (!showkernel) continue; /* * Kernel messages shouldn't come from the * userspace. */ if (cnls.nl_pid > 0) continue; } for (i = 0; i < len; i += slen + 1) { key = buf + i; value = strchr(key, '='); slen = strlen(buf+i); if (!slen || value == NULL) continue; if (subsystem && !strncmp(key, "SUBSYSTEM=", 10) && !strstr(key+10, subsystem)) { dbg("subsystem filter '%s' applied.", subsystem); break; } value[0] = '\0'; value++; /* * We generally trust the kernel. But there * might be some udev flaw. (It's >20k sloc!) */ if (strcmp(key, "PATH")) { setenv(key, value, 1); dbg("%s = \"%s\"", key, value); } } if (getenv("ACTION") != NULL && getenv("DEVPATH") != NULL && getenv("SUBSYSTEM") != NULL && getenv("SEQNUM") != NULL) { child(runpath); } if (fds.revents & POLLHUP) { dbg("parent hung up\n"); return 0; } } if (r == -1) edie("poll"); if (r == 0) dbg("exit due to timeout"); return 0; }