pax_global_header00006660000000000000000000000064147621173720014524gustar00rootroot0000000000000052 comment=8e9157bbeea1899b7b8b257e7eaa71efef3fffed restorecond-3.8.1/000077500000000000000000000000001476211737200140645ustar00rootroot00000000000000restorecond-3.8.1/.gitignore000066400000000000000000000000141476211737200160470ustar00rootroot00000000000000restorecond restorecond-3.8.1/LICENSE000066400000000000000000000431311476211737200150730ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Library General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Library General Public License instead of this License. restorecond-3.8.1/Makefile000066400000000000000000000044221476211737200155260ustar00rootroot00000000000000PKG_CONFIG ?= pkg-config # Installation directories. LINGUAS ?= PREFIX ?= /usr SBINDIR ?= $(PREFIX)/sbin MANDIR = $(PREFIX)/share/man AUTOSTARTDIR = /etc/xdg/autostart DBUSSERVICEDIR = $(PREFIX)/share/dbus-1/services SYSTEMDSYSTEMUNITDIR ?= $(shell $(PKG_CONFIG) --variable=systemdsystemunitdir systemd) SYSTEMDUSERUNITDIR ?= $(shell $(PKG_CONFIG) --variable=systemduserunitdir systemd) autostart_DATA = sealertauto.desktop INITDIR ?= /etc/rc.d/init.d SELINUXDIR = /etc/selinux GIO_CFLAGS = -DHAVE_DBUS $(shell $(PKG_CONFIG) --cflags gio-2.0) GIO_LIBS = $(shell $(PKG_CONFIG) --libs gio-2.0) CFLAGS ?= -g -Werror -Wall -W override CFLAGS += $(GIO_CFLAGS) override LDLIBS += -lselinux $(GIO_LIBS) all: restorecond restorecond.o utmpwatcher.o stringslist.o user.o watch.o: restorecond.h restorecond: restore.o restorecond.o utmpwatcher.o stringslist.o user.o watch.o $(CC) $(LDFLAGS) -o $@ $^ $(LDLIBS) install: all [ -d $(DESTDIR)$(MANDIR)/man8 ] || mkdir -p $(DESTDIR)$(MANDIR)/man8 -mkdir -p $(DESTDIR)$(SBINDIR) install -m 755 restorecond $(DESTDIR)$(SBINDIR) install -m 644 restorecond.8 $(DESTDIR)$(MANDIR)/man8 for lang in $(LINGUAS) ; do \ if [ -e $${lang} ] ; then \ [ -d $(DESTDIR)$(MANDIR)/$${lang}/man8 ] || mkdir -p $(DESTDIR)$(MANDIR)/$${lang}/man8 ; \ install -m 644 $${lang}/*.8 $(DESTDIR)$(MANDIR)/$${lang}/man8/ ; \ fi ; \ done -mkdir -p $(DESTDIR)$(INITDIR) install -m 755 restorecond.init $(DESTDIR)$(INITDIR)/restorecond -mkdir -p $(DESTDIR)$(SELINUXDIR) install -m 644 restorecond.conf $(DESTDIR)$(SELINUXDIR)/restorecond.conf install -m 644 restorecond_user.conf $(DESTDIR)$(SELINUXDIR)/restorecond_user.conf -mkdir -p $(DESTDIR)$(AUTOSTARTDIR) install -m 644 restorecond.desktop $(DESTDIR)$(AUTOSTARTDIR)/restorecond.desktop -mkdir -p $(DESTDIR)$(DBUSSERVICEDIR) install -m 644 org.selinux.Restorecond.service $(DESTDIR)$(DBUSSERVICEDIR)/org.selinux.Restorecond.service -mkdir -p $(DESTDIR)$(SYSTEMDSYSTEMUNITDIR) install -m 644 restorecond.service $(DESTDIR)$(SYSTEMDSYSTEMUNITDIR) -mkdir -p $(DESTDIR)$(SYSTEMDUSERUNITDIR) install -m 644 restorecond_user.service $(DESTDIR)$(SYSTEMDUSERUNITDIR) relabel: install /sbin/restorecon $(DESTDIR)$(SBINDIR)/restorecond clean: -rm -f restorecond *.o *~ indent: ../../scripts/Lindent $(wildcard *.[ch]) test: restorecond-3.8.1/VERSION000066400000000000000000000000061476211737200151300ustar00rootroot000000000000003.8.1 restorecond-3.8.1/org.selinux.Restorecond.service000066400000000000000000000001631476211737200222110ustar00rootroot00000000000000[D-BUS Service] Name=org.selinux.Restorecond Exec=/usr/sbin/restorecond -u SystemdService=restorecond_user.service restorecond-3.8.1/restore.c000066400000000000000000000055261476211737200157230ustar00rootroot00000000000000#include "restore.h" #include #ifndef GLOB_TILDE #define GLOB_TILDE 0 #endif #ifndef GLOB_BRACE #define GLOB_BRACE 0 #endif char **exclude_list; int exclude_count; void restore_init(struct restore_opts *opts) { int rc; struct selinux_opt selinux_opts[] = { { SELABEL_OPT_VALIDATE, opts->selabel_opt_validate }, { SELABEL_OPT_PATH, opts->selabel_opt_path }, { SELABEL_OPT_DIGEST, opts->selabel_opt_digest } }; opts->hnd = selabel_open(SELABEL_CTX_FILE, selinux_opts, 3); if (!opts->hnd) { perror(opts->selabel_opt_path); exit(1); } opts->restorecon_flags = 0; opts->restorecon_flags = opts->nochange | opts->verbose | opts->progress | opts->set_specctx | opts->add_assoc | opts->ignore_digest | opts->recurse | opts->userealpath | opts->xdev | opts->abort_on_error | opts->syslog_changes | opts->log_matches | opts->ignore_noent | opts->ignore_mounts; /* Use setfiles, restorecon and restorecond own handles */ selinux_restorecon_set_sehandle(opts->hnd); if (opts->rootpath) { rc = selinux_restorecon_set_alt_rootpath(opts->rootpath); if (rc) { fprintf(stderr, "selinux_restorecon_set_alt_rootpath error: %s.\n", strerror(errno)); exit(-1); } } if (exclude_list) selinux_restorecon_set_exclude_list ((const char **)exclude_list); } void restore_finish(void) { int i; if (exclude_list) { for (i = 0; exclude_list[i]; i++) free(exclude_list[i]); free(exclude_list); } } int process_glob(char *name, struct restore_opts *opts) { glob_t globbuf; size_t i = 0; int len, rc, errors; memset(&globbuf, 0, sizeof(globbuf)); errors = glob(name, GLOB_TILDE | GLOB_PERIOD | GLOB_NOCHECK | GLOB_BRACE, NULL, &globbuf); if (errors) return errors; for (i = 0; i < globbuf.gl_pathc; i++) { len = strlen(globbuf.gl_pathv[i]) - 2; if (len > 0 && strcmp(&globbuf.gl_pathv[i][len--], "/.") == 0) continue; if (len > 0 && strcmp(&globbuf.gl_pathv[i][len], "/..") == 0) continue; rc = selinux_restorecon(globbuf.gl_pathv[i], opts->restorecon_flags); if (rc < 0) errors = rc; } globfree(&globbuf); return errors; } void add_exclude(const char *directory) { char **tmp_list; if (directory == NULL || directory[0] != '/') { fprintf(stderr, "Full path required for exclude: %s.\n", directory); exit(-1); } /* Add another two entries, one for directory, and the other to * terminate the list. */ tmp_list = realloc(exclude_list, sizeof(char *) * (exclude_count + 2)); if (!tmp_list) { fprintf(stderr, "realloc failed while excluding %s.\n", directory); exit(-1); } exclude_list = tmp_list; exclude_list[exclude_count] = strdup(directory); if (!exclude_list[exclude_count]) { fprintf(stderr, "strdup failed while excluding %s.\n", directory); exit(-1); } exclude_count++; exclude_list[exclude_count] = NULL; } restorecond-3.8.1/restore.h000066400000000000000000000027411476211737200157240ustar00rootroot00000000000000#ifndef RESTORE_H #define RESTORE_H #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include #include #include #include #include #include #include #include #include #include #include #include #include /* * STAR_COUNT is also defined in libselinux/src/selinux_restorecon.c where it * is used to output "*" for each number of files processed. Defined here for * inclusion in man pages. */ #define STAR_COUNT 1000 /* Things that need to be init'd */ struct restore_opts { unsigned int nochange; unsigned int verbose; unsigned int progress; unsigned int set_specctx; unsigned int add_assoc; unsigned int ignore_digest; unsigned int recurse; unsigned int userealpath; unsigned int xdev; unsigned int abort_on_error; unsigned int syslog_changes; unsigned int log_matches; unsigned int ignore_noent; unsigned int ignore_mounts; /* restorecon_flags holds | of above for restore_init() */ unsigned int restorecon_flags; char *rootpath; char *progname; struct selabel_handle *hnd; const char *selabel_opt_validate; const char *selabel_opt_path; const char *selabel_opt_digest; int debug; FILE *outfile; }; void restore_init(struct restore_opts *opts); void restore_finish(void); void add_exclude(const char *directory); int process_glob(char *name, struct restore_opts *opts); extern char **exclude_list; #endif restorecond-3.8.1/restorecond.8000066400000000000000000000022631476211737200165070ustar00rootroot00000000000000.TH "restorecond" "8" "2002031409" "" "" .SH "NAME" restorecond \- daemon that watches for file creation and then sets the default SELinux file context .SH "SYNOPSIS" .B restorecond [\-d] [-h] [\-f restorecond_file ] [\-u] [\-v] .P .SH "DESCRIPTION" This manual page describes the .BR restorecond program. .P This daemon uses inotify to watch files listed in the /etc/selinux/restorecond.conf, when they are created, this daemon will make sure they have the correct file context associated with the policy. .SH "OPTIONS" .TP .B \-d Turns on debugging mode. Application will stay in the foreground and lots of debugs messages start printing. .TP . B \-h Print usage statement. .TP .B \-f restorecond_file Use alternative restorecond.conf file. .TP .B \-u Turns on user mode. Runs restorecond in the user session and reads /etc/selinux/restorecond_user.conf. Uses dbus to make sure only one restorecond is running per user session. .TP .B \-v Turns on verbose debugging. (Report missing files) .SH "AUTHOR" This man page and program was written by Dan Walsh . .SH "FILES" /etc/selinux/restorecond.conf /etc/selinux/restorecond_user.conf .SH "SEE ALSO" .BR restorecon (8), restorecond-3.8.1/restorecond.c000066400000000000000000000117361476211737200165670ustar00rootroot00000000000000/* * restorecond * * Copyright (C) 2006-2009 Red Hat * see file 'COPYING' for use and warranty information * * 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: * Dan Walsh * */ /* * PURPOSE: * This daemon program watches for the creation of files listed in a config file * and makes sure that there security context matches the systems defaults * * USAGE: * restorecond [-d] [-u] [-v] [-f restorecond_file ] * * -d Run in debug mode * -f Use alternative restorecond_file * -u Run in user mode * -v Run in verbose mode (Report missing files) * * EXAMPLE USAGE: * restorecond * */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include "restore.h" #include #include #include #include #include #include #include #include #include "restorecond.h" #include "utmpwatcher.h" const char *homedir; static int master_fd = -1; static const char *server_watch_file = "/etc/selinux/restorecond.conf"; static const char *user_watch_file = "/etc/selinux/restorecond_user.conf"; static const char *watch_file; struct restore_opts r_opts; #include int debug_mode = 0; int terminate = 0; int master_wd = -1; int run_as_user = 0; static void done(void) { watch_list_free(master_fd); close(master_fd); utmpwatcher_free(); selabel_close(r_opts.hnd); } static const char *pidfile = "/run/restorecond.pid"; static int write_pid_file(void) { int pidfd, len; char val[16]; len = snprintf(val, sizeof(val), "%u\n", getpid()); if (len < 0) { syslog(LOG_ERR, "Pid error (%s)", strerror(errno)); pidfile = 0; return 1; } pidfd = open(pidfile, O_CREAT | O_TRUNC | O_NOFOLLOW | O_WRONLY, 0644); if (pidfd < 0) { syslog(LOG_ERR, "Unable to set pidfile (%s)", strerror(errno)); pidfile = 0; return 1; } if (write(pidfd, val, (unsigned int)len) != len) { syslog(LOG_ERR, "Unable to write to pidfile (%s)", strerror(errno)); close(pidfd); return 1; } close(pidfd); return 0; } /* * SIGTERM handler */ static void term_handler(int s __attribute__ ((unused))) { terminate = 1; /* trigger a failure in the watch */ close(master_fd); } static void usage(char *program) { printf("%s [-d] [-f restorecond_file ] [-u] [-v] \n", program); } void exitApp(const char *msg) { perror(msg); exit(-1); } /* Add a file to the watch list. We are watching for file creation, so we actually put the watch on the directory and then examine all files created in that directory to see if it is one that we are watching. */ int main(int argc, char **argv) { int opt; struct sigaction sa; /* If we are not running SELinux then just exit */ if (is_selinux_enabled() != 1) return 0; watch_file = server_watch_file; /* Set all options to zero/NULL except for ignore_noent & digest. */ memset(&r_opts, 0, sizeof(r_opts)); r_opts.ignore_noent = SELINUX_RESTORECON_IGNORE_NOENTRY; r_opts.ignore_digest = SELINUX_RESTORECON_IGNORE_DIGEST; /* As r_opts.selabel_opt_digest = NULL, no digest will be requested. */ restore_init(&r_opts); /* Register sighandlers */ sa.sa_flags = 0; sa.sa_handler = term_handler; sigemptyset(&sa.sa_mask); sigaction(SIGTERM, &sa, NULL); atexit( done ); while ((opt = getopt(argc, argv, "hdf:uv")) > 0) { switch (opt) { case 'd': debug_mode = 1; break; case 'f': watch_file = optarg; break; case 'u': run_as_user = 1; break; case 'h': usage(argv[0]); exit(0); break; case 'v': r_opts.verbose = SELINUX_RESTORECON_VERBOSE; break; case '?': usage(argv[0]); exit(-1); } } master_fd = inotify_init(); if (master_fd < 0) exitApp("inotify_init"); uid_t uid = getuid(); struct passwd *pwd = getpwuid(uid); if (!pwd) exitApp("getpwuid"); homedir = pwd->pw_dir; if (uid != 0) { if (run_as_user) return server(master_fd, user_watch_file); if (start() != 0) return server(master_fd, user_watch_file); return 0; } read_config(master_fd, watch_file); if (!debug_mode) { if (daemon(0, 0) < 0) exitApp("daemon"); } write_pid_file(); while (watch(master_fd, watch_file) == 0) { } watch_list_free(master_fd); close(master_fd); if (pidfile) unlink(pidfile); return 0; } restorecond-3.8.1/restorecond.conf000066400000000000000000000001661476211737200172650ustar00rootroot00000000000000/etc/services /etc/resolv.conf /etc/samba/secrets.tdb /etc/updatedb.conf /run/utmp /var/log/wtmp /root/* /root/.ssh/* restorecond-3.8.1/restorecond.desktop000066400000000000000000000003361476211737200200100ustar00rootroot00000000000000[Desktop Entry] Name=File Context maintainer Exec=/usr/sbin/restorecond -u Comment=Fix file context in owned by the user Type=Application StartupNotify=false X-GNOME-Autostart-enabled=false X-GNOME-HiddenUnderSystemd=true restorecond-3.8.1/restorecond.h000066400000000000000000000027741476211737200165760ustar00rootroot00000000000000/* restorecond.h -- * Copyright 2006 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: * Dan Walsh * */ #ifndef RESTORED_CONFIG_H #define RESTORED_CONFIG_H extern int debug_mode; extern const char *homedir; extern int terminate; extern int master_wd; extern int run_as_user; extern int start(void); extern int server(int, const char *watch_file); extern void exitApp(const char *msg) __attribute__((__noreturn__)); extern void read_config(int fd, const char *watch_file); extern int watch(int fd, const char *watch_file); extern void watch_list_add(int inotify_fd, const char *path); extern int watch_list_find(int wd, const char *file); extern void watch_list_free(int fd); extern int watch_list_isempty(void); extern struct restore_opts r_opts; #endif restorecond-3.8.1/restorecond.init000066400000000000000000000035151476211737200173040ustar00rootroot00000000000000#!/bin/sh # # restorecond: Daemon used to maintain path file context # # chkconfig: - 12 87 # description: restorecond uses inotify to look for creation of new files \ # listed in the /etc/selinux/restorecond.conf file, and restores the \ # correct security context. # # processname: /usr/sbin/restorecond # config: /etc/selinux/restorecond.conf # pidfile: /run/restorecond.pid # # Return values according to LSB for all commands but status: # 0 - success # 1 - generic or unspecified error # 2 - invalid or excess argument(s) # 3 - unimplemented feature (e.g. "reload") # 4 - insufficient privilege # 5 - program is not installed # 6 - program is not configured # 7 - program is not running PATH=/sbin:/bin:/usr/bin:/usr/sbin # Source function library. . /etc/rc.d/init.d/functions [ -x /usr/sbin/selinuxenabled ] && /usr/sbin/selinuxenabled || exit 7 # Check that we are root ... so non-root users stop here if [ $EUID ]; then test $EUID = 0 || exit 4 else test `id -u` = 0 || exit 4 fi test -x /usr/sbin/restorecond || exit 5 test -f /etc/selinux/restorecond.conf || exit 6 RETVAL=0 start() { echo -n $"Starting restorecond: " unset HOME MAIL USER USERNAME daemon /usr/sbin/restorecond RETVAL=$? touch /var/lock/subsys/restorecond echo return $RETVAL } stop() { echo -n $"Shutting down restorecond: " killproc restorecond RETVAL=$? rm -f /var/lock/subsys/restorecond echo return $RETVAL } restart() { stop start } # See how we were called. case "$1" in start) start ;; stop) stop ;; status) status restorecond RETVAL=$? ;; force-reload|restart|reload) restart ;; condrestart) [ -e /var/lock/subsys/restorecond ] && restart || : ;; *) echo $"Usage: $0 {start|stop|restart|force-reload|status|condrestart}" RETVAL=3 esac exit $RETVAL restorecond-3.8.1/restorecond.service000066400000000000000000000004441476211737200177770ustar00rootroot00000000000000[Unit] Description=Restorecon maintaining path file context Documentation=man:restorecond(8) ConditionPathExists=/etc/selinux/restorecond.conf ConditionSecurity=selinux [Service] Type=forking ExecStart=/usr/sbin/restorecond PIDFile=/run/restorecond.pid [Install] WantedBy=multi-user.target restorecond-3.8.1/restorecond_user.conf000066400000000000000000000001351476211737200203170ustar00rootroot00000000000000~/* ~/public_html/* ~/.gnome2/* ~/local/* ~/.fonts/* ~/.cache/* ~/.config/* ~/.local/share/* restorecond-3.8.1/restorecond_user.service000066400000000000000000000004251476211737200210340ustar00rootroot00000000000000[Unit] Description=Restorecon maintaining path file context (user service) Documentation=man:restorecond(8) ConditionPathExists=/etc/selinux/restorecond_user.conf ConditionSecurity=selinux [Service] Type=dbus BusName=org.selinux.Restorecond ExecStart=/usr/sbin/restorecond -u restorecond-3.8.1/stringslist.c000066400000000000000000000067021476211737200166220ustar00rootroot00000000000000/* * Copyright (C) 2006, 2008 Red Hat * see file 'COPYING' for use and warranty information * * 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: * Dan Walsh * */ #include #include #include #include "stringslist.h" #include "restorecond.h" #include /* Sorted lists */ void strings_list_add(struct stringsList **list, const char *string) { struct stringsList *ptr = *list; struct stringsList *prev = NULL; struct stringsList *newptr = NULL; while (ptr) { int cmp = strcmp(string, ptr->string); if (cmp < 0) break; /* Not on list break out to add */ if (cmp == 0) return; /* Already on list */ prev = ptr; ptr = ptr->next; } newptr = calloc(1, sizeof(struct stringsList)); if (!newptr) exitApp("Out of Memory"); newptr->string = strdup(string); if (!newptr->string) exitApp("Out of Memory"); newptr->next = ptr; if (prev) prev->next = newptr; else *list = newptr; } int strings_list_find(struct stringsList *ptr, const char *string, int *exact) { while (ptr) { *exact = strcmp(ptr->string, string) == 0; int cmp = fnmatch(ptr->string, string, 0); if (cmp == 0) return 0; /* Match found */ ptr = ptr->next; } return -1; } void strings_list_free(struct stringsList *ptr) { struct stringsList *prev = NULL; while (ptr) { free(ptr->string); prev = ptr; ptr = ptr->next; free(prev); } } int strings_list_diff(struct stringsList *from, struct stringsList *to) { while (from != NULL && to != NULL) { if (strcmp(from->string, to->string) != 0) return 1; from = from->next; to = to->next; } if (from != NULL || to != NULL) return 1; return 0; } void strings_list_print(struct stringsList *ptr) { while (ptr) { printf("%s\n", ptr->string); ptr = ptr->next; } } #ifdef TEST void exitApp(const char *msg) { perror(msg); exit(-1); } int main(int argc, char **argv) { struct stringsList *list = NULL; struct stringsList *list1 = NULL; strings_list_add(&list, "/etc/resolv.conf"); strings_list_add(&list, "/etc/walsh"); strings_list_add(&list, "/etc/mtab"); strings_list_add(&list, "/etc/walsh"); if (strings_list_diff(list, list) != 0) printf("strings_list_diff test1 bug\n"); strings_list_add(&list1, "/etc/walsh"); if (strings_list_diff(list, list1) == 0) printf("strings_list_diff test2 bug\n"); strings_list_add(&list1, "/etc/walsh"); strings_list_add(&list1, "/etc/walsh/*"); strings_list_add(&list1, "/etc/resolv.conf"); strings_list_add(&list1, "/etc/mtab1"); if (strings_list_diff(list, list1) == 0) printf("strings_list_diff test3 bug\n"); printf("strings list\n"); strings_list_print(list); printf("strings list1\n"); strings_list_find(list1, "/etc/walsh/dan"); strings_list_print(list1); strings_list_free(list); strings_list_free(list1); } #endif restorecond-3.8.1/stringslist.h000066400000000000000000000024501476211737200166230ustar00rootroot00000000000000/* stringslist.h -- * Copyright 2006 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: * Dan Walsh * */ #ifndef STRINGSLIST_H #define STRINGSLIST_H struct stringsList { struct stringsList *next; char *string; }; void strings_list_free(struct stringsList *list); void strings_list_add(struct stringsList **list, const char *string); void strings_list_print(struct stringsList *list); int strings_list_find(struct stringsList *list, const char *string, int *exact); int strings_list_diff(struct stringsList *from, struct stringsList *to); #endif restorecond-3.8.1/user.c000066400000000000000000000157301476211737200152140ustar00rootroot00000000000000/* * restorecond * * Copyright (C) 2006-2009 Red Hat * Copyright (C) 2020 Nicolas Iooss * see file 'COPYING' for use and warranty information * * 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: * Dan Walsh * Nicolas Iooss */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "restorecond.h" #include "stringslist.h" #include #include static int local_lock_fd = -1; #ifdef HAVE_DBUS #include static const char *DBUS_NAME = "org.selinux.Restorecond"; static void on_name_acquired(GDBusConnection *connection G_GNUC_UNUSED, const gchar *name, gpointer user_data G_GNUC_UNUSED) { if (debug_mode) g_print("D-Bus name acquired: %s\n", name); } static void on_name_lost(GDBusConnection *connection G_GNUC_UNUSED, const gchar *name, gpointer user_data) { /* Exit when the D-Bus connection closes */ GMainLoop *loop = user_data; if (debug_mode) g_print("D-Bus name lost (%s), exiting\n", name); g_main_loop_quit(loop); } /** * Try starting a D-Bus server on the session bus. * Returns -1 if the connection failed, so that a local server can be launched */ static int dbus_server(GMainLoop *loop) { GDBusConnection *bus; guint client_id; bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, NULL); if (!bus) return -1; client_id = g_bus_own_name_on_connection( bus, DBUS_NAME, G_BUS_NAME_OWNER_FLAGS_NONE, on_name_acquired, on_name_lost, loop, NULL); g_object_unref(bus); if (client_id == 0) return -1; return 0; } #endif /* size of the event structure, not counting name */ #define EVENT_SIZE (sizeof (struct inotify_event)) /* reasonable guess as to size of 1024 events */ #define BUF_LEN (1024 * (EVENT_SIZE + 16)) static gboolean io_channel_callback (GIOChannel *source, GIOCondition condition, gpointer data __attribute__((__unused__))) { char buffer[BUF_LEN+1]; gsize bytes_read; unsigned int i = 0; if (condition & G_IO_IN) { /* Data is available. */ g_io_channel_read_chars (source, buffer, sizeof (buffer), &bytes_read, NULL); if (! bytes_read) { /* Session/Terminal Ended */ exit(0); } while (i < bytes_read) { struct inotify_event *event; event = (struct inotify_event *)&buffer[i]; if (debug_mode) printf("wd=%d mask=%u cookie=%u len=%u\n", event->wd, event->mask, event->cookie, event->len); if (event->len) watch_list_find(event->wd, event->name); i += EVENT_SIZE + event->len; } } /* An error happened while reading the file. */ if (condition & G_IO_NVAL) return FALSE; /* We have reached the end of the file. */ if (condition & G_IO_HUP) { g_io_channel_shutdown (source, 0, NULL); exit(0); return FALSE; } /* Returning TRUE will make sure the callback remains associated to the channel. */ return TRUE; } int start(void) { #ifdef HAVE_DBUS GDBusConnection *bus; GError *err = NULL; GVariant *result; /* Get a connection to the session bus */ bus = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &err); if (!bus) { if (debug_mode) g_warning("Failed to connect to the D-BUS daemon: %s", err->message); g_error_free(err); return 1; } /* Start restorecond D-Bus service by pinging its bus name * * https://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-peer */ result = g_dbus_connection_call_sync(bus, DBUS_NAME, /* bus name */ "/", /* object path */ "org.freedesktop.DBus.Peer", /* interface */ "Ping", /* method */ NULL, /* parameters */ NULL, /* reply_type */ G_DBUS_CALL_FLAGS_NONE, -1, /* timeout_msec */ NULL, &err); if (!result) { g_object_unref(bus); if (debug_mode) g_warning("Failed to start %s: %s", DBUS_NAME, err->message); g_error_free(err); return 1; } g_object_unref(bus); #endif /* HAVE_DBUS */ return 0; } static int local_server(void) { // ! dbus, run as local service char *ptr=NULL; if (asprintf(&ptr, "%s/.restorecond", homedir) < 0) { if (debug_mode) perror("asprintf"); return -1; } local_lock_fd = open(ptr, O_CREAT | O_WRONLY | O_NOFOLLOW | O_CLOEXEC, S_IRUSR | S_IWUSR); if (debug_mode) g_warning ("Lock file: %s", ptr); free(ptr); if (local_lock_fd < 0) { if (debug_mode) perror("open"); return -1; } if (flock(local_lock_fd, LOCK_EX | LOCK_NB) < 0) { if (debug_mode) perror("flock"); close(local_lock_fd); local_lock_fd = -1; return -1; } /* watch for stdin/terminal going away */ GIOChannel *in = g_io_channel_unix_new(0); g_io_channel_set_encoding(in, NULL, NULL); g_io_channel_set_flags(in, g_io_channel_get_flags(in) | G_IO_FLAG_NONBLOCK, NULL); g_io_add_watch_full( in, G_PRIORITY_HIGH, G_IO_IN|G_IO_ERR|G_IO_HUP, io_channel_callback, NULL, NULL); return 0; } static void end_local_server(void) { if (local_lock_fd >= 0) close(local_lock_fd); local_lock_fd = -1; } static int sigterm_handler(gpointer user_data) { GMainLoop *loop = user_data; if (debug_mode) g_print("Received SIGTERM, exiting\n"); g_main_loop_quit(loop); return FALSE; } int server(int master_fd, const char *watch_file) { GMainLoop *loop; loop = g_main_loop_new (NULL, FALSE); #ifdef HAVE_DBUS if (dbus_server(loop) != 0) #endif /* HAVE_DBUS */ if (local_server()) goto end; read_config(master_fd, watch_file); if (watch_list_isempty()) goto end; set_matchpathcon_flags(MATCHPATHCON_NOTRANS); GIOChannel *c = g_io_channel_unix_new(master_fd); g_io_channel_set_encoding(c, NULL, NULL); g_io_channel_set_flags(c, g_io_channel_get_flags(c) | G_IO_FLAG_NONBLOCK, NULL); g_io_add_watch_full(c, G_PRIORITY_HIGH, G_IO_IN|G_IO_ERR|G_IO_HUP, io_channel_callback, NULL, NULL); /* Handle SIGTERM */ g_unix_signal_add_full(G_PRIORITY_DEFAULT, SIGTERM, sigterm_handler, loop, NULL); g_main_loop_run (loop); end: end_local_server(); g_main_loop_unref (loop); return 0; } restorecond-3.8.1/utmpwatcher.c000066400000000000000000000053431476211737200166000ustar00rootroot00000000000000/* * utmpwatcher.c * * Copyright (C) 2006 Red Hat * see file 'COPYING' for use and warranty information * * 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: * Dan Walsh * * */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include #include #include "restorecond.h" #include "utmpwatcher.h" #include "stringslist.h" static struct stringsList *utmp_ptr = NULL; static int utmp_wd = -1; unsigned int utmpwatcher_handle(int inotify_fd, int wd) { int changed = 0; struct utmp u; const char *utmp_path = "/run/utmp"; struct stringsList *prev_utmp_ptr = utmp_ptr; if (wd != utmp_wd) return -1; utmp_ptr = NULL; FILE *cfg = fopen(utmp_path, "r"); if (!cfg) exitApp("Error reading utmp file."); while (fread(&u, sizeof(struct utmp), 1, cfg) > 0) { if (u.ut_type == USER_PROCESS) strings_list_add(&utmp_ptr, u.ut_user); } fclose(cfg); if (utmp_wd >= 0) inotify_rm_watch(inotify_fd, utmp_wd); utmp_wd = inotify_add_watch(inotify_fd, utmp_path, IN_MOVED_FROM | IN_MODIFY); if (utmp_wd == -1) exitApp("Error watching utmp file."); changed = strings_list_diff(prev_utmp_ptr, utmp_ptr); if (prev_utmp_ptr) { strings_list_free(prev_utmp_ptr); } return changed; } static void watch_file(int inotify_fd, const char *file) { struct stringsList *ptr = utmp_ptr; while (ptr) { struct passwd *pwd = getpwnam(ptr->string); if (pwd) { char *path = NULL; if (asprintf(&path, "%s%s", pwd->pw_dir, file) < 0) exitApp("Error allocating memory."); watch_list_add(inotify_fd, path); free(path); } ptr = ptr->next; } } void utmpwatcher_add(int inotify_fd, const char *path) { if (utmp_ptr == NULL) { utmpwatcher_handle(inotify_fd, utmp_wd); } watch_file(inotify_fd, path); } void utmpwatcher_free(void) { if (utmp_ptr) strings_list_free(utmp_ptr); } #ifdef TEST int main(int argc, char **argv) { read_utmp(); return 0; } #endif restorecond-3.8.1/utmpwatcher.h000066400000000000000000000020561476211737200166030ustar00rootroot00000000000000/* utmpwatcher.h -- * Copyright 2006 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: * Dan Walsh * */ #ifndef UTMPWATCHER_H #define UTMPWATCHER_H unsigned int utmpwatcher_handle(int inotify_fd, int wd); void utmpwatcher_add(int inotify_fd, const char *path); void utmpwatcher_free(void); #endif restorecond-3.8.1/watch.c000066400000000000000000000134351476211737200153440ustar00rootroot00000000000000#define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include "restore.h" #include #include #include #include #include #include #include #include "restorecond.h" #include "stringslist.h" #include "utmpwatcher.h" #ifndef GLOB_TILDE #define GLOB_TILDE 0 #endif #ifndef GLOB_BRACE #define GLOB_BRACE 0 #endif /* size of the event structure, not counting name */ #define EVENT_SIZE (sizeof (struct inotify_event)) /* reasonable guess as to size of 1024 events */ #define BUF_LEN (1024 * (EVENT_SIZE + 16)) struct watchList { struct watchList *next; int wd; char *dir; struct stringsList *files; }; struct watchList *firstDir = NULL; int watch_list_isempty(void) { return firstDir == NULL; } void watch_list_add(int fd, const char *path) { struct watchList *ptr = NULL; size_t i = 0; struct watchList *prev = NULL; glob_t globbuf; char *x = strdup(path); if (!x) exitApp("Out of Memory"); char *file = basename(x); char *dir = dirname(x); ptr = firstDir; int len; globbuf.gl_offs = 1; if (glob(path, GLOB_TILDE | GLOB_PERIOD, NULL, &globbuf) >= 0) { for (i = 0; i < globbuf.gl_pathc; i++) { len = strlen(globbuf.gl_pathv[i]) - 2; if (len > 0 && strcmp(&globbuf.gl_pathv[i][len--], "/.") == 0) continue; if (len > 0 && strcmp(&globbuf.gl_pathv[i][len], "/..") == 0) continue; selinux_restorecon(globbuf.gl_pathv[i], r_opts.restorecon_flags); } globfree(&globbuf); } while (ptr != NULL) { if (strcmp(dir, ptr->dir) == 0) { strings_list_add(&ptr->files, file); goto end; } prev = ptr; ptr = ptr->next; } ptr = calloc(1, sizeof(struct watchList)); if (!ptr) exitApp("Out of Memory"); ptr->wd = inotify_add_watch(fd, dir, IN_CREATE | IN_MOVED_TO); if (ptr->wd == -1) { free(ptr); if (! run_as_user) syslog(LOG_ERR, "Unable to watch (%s) %s\n", path, strerror(errno)); goto end; } ptr->dir = strdup(dir); if (!ptr->dir) exitApp("Out of Memory"); strings_list_add(&ptr->files, file); if (prev) prev->next = ptr; else firstDir = ptr; if (debug_mode) printf("%d: Dir=%s, File=%s\n", ptr->wd, ptr->dir, file); end: free(x); return; } /* A file was in a direcroty has been created. This function checks to see if it is one that we are watching. */ int watch_list_find(int wd, const char *file) { struct watchList *ptr = NULL; ptr = firstDir; if (debug_mode) printf("%d: File=%s\n", wd, file); while (ptr != NULL) { if (ptr->wd == wd) { int exact=0; if (strings_list_find(ptr->files, file, &exact) == 0) { char *path = NULL; if (asprintf(&path, "%s/%s", ptr->dir, file) < 0) exitApp("Error allocating memory."); selinux_restorecon(path, r_opts.restorecon_flags); free(path); return 0; } if (debug_mode) strings_list_print(ptr->files); /* Not found in this directory */ return -1; } ptr = ptr->next; } /* Did not find a directory */ return -1; } void watch_list_free(int fd) { struct watchList *ptr = NULL; struct watchList *prev = NULL; ptr = firstDir; while (ptr != NULL) { inotify_rm_watch(fd, ptr->wd); strings_list_free(ptr->files); free(ptr->dir); prev = ptr; ptr = ptr->next; free(prev); } firstDir = NULL; } /* Inotify watch loop */ int watch(int fd, const char *watch_file) { char buf[BUF_LEN]; int len, i = 0; if (firstDir == NULL) return 0; len = read(fd, buf, BUF_LEN); if (len < 0) { if (terminate == 0) { syslog(LOG_ERR, "Read error (%s)", strerror(errno)); return 0; } syslog(LOG_INFO, "terminated"); return -1; } else if (!len) /* BUF_LEN too small? */ return -1; while (i < len) { struct inotify_event *event; event = (struct inotify_event *)&buf[i]; if (debug_mode) printf("wd=%d mask=%u cookie=%u len=%u\n", event->wd, event->mask, event->cookie, event->len); if (event->mask & ~IN_IGNORED) { if (event->wd == master_wd) read_config(fd, watch_file); else { switch (utmpwatcher_handle(fd, event->wd)) { case -1: /* Message was not for utmpwatcher */ if (event->len) watch_list_find(event->wd, event->name); break; case 1: /* utmp has changed need to reload */ read_config(fd, watch_file); break; default: /* No users logged in or out */ break; } } } i += EVENT_SIZE + event->len; } return 0; } static void process_config(int fd, FILE * cfg) { char *line_buf = NULL; size_t len = 0; while (getline(&line_buf, &len, cfg) > 0) { char *buffer = line_buf; while (isspace(*buffer)) buffer++; if (buffer[0] == '#') continue; int l = strlen(buffer) - 1; if (l <= 0) continue; buffer[l] = 0; if (buffer[0] == '~') { if (run_as_user) { char *ptr=NULL; if (asprintf(&ptr, "%s%s", homedir, &buffer[1]) < 0) exitApp("Error allocating memory."); watch_list_add(fd, ptr); free(ptr); } else { utmpwatcher_add(fd, &buffer[1]); } } else { watch_list_add(fd, buffer); } } free(line_buf); } /* Read config file ignoring Comment lines Files specified one per line. Files with "~" will be expanded to the logged in users homedirs. */ void read_config(int fd, const char *watch_file_path) { FILE *cfg = NULL; if (debug_mode) printf("Read Config\n"); watch_list_free(fd); cfg = fopen(watch_file_path, "r"); if (!cfg){ perror(watch_file_path); exitApp("Error reading config file"); } process_config(fd, cfg); fclose(cfg); inotify_rm_watch(fd, master_wd); master_wd = inotify_add_watch(fd, watch_file_path, IN_MOVED_FROM | IN_MODIFY); if (master_wd == -1) exitApp("Error watching config file."); }