pleaser-0.5.1/.cargo_vcs_info.json0000644000000001121415314266100125250ustar { "git": { "sha1": "ce9627c714e46d9ea1d157ee43c78a7523f45d80" } } pleaser-0.5.1/.gitlab-ci.yml010064400017500001750000000020131415312630000137540ustar 00000000000000# This file is a template, and might need editing before it works on your project. # Official language image. Look for the different tagged releases at: # https://hub.docker.com/r/library/rust/tags/ image: "rust:latest" # Optional: Pick zero or more services to be used on all builds. # Only needed when using a docker container to run your tests in. # Check out: http://docs.gitlab.com/ce/ci/docker/using_docker_images.html#what-is-a-service # services: # - mysql:latest # - redis:latest # - postgres:latest # Optional: Install a C compiler, cmake and git into the container. # You will often need this when you (or any of your dependencies) depends on C code. before_script: - apt-get update -yqq - apt-get install -yqq --no-install-recommends build-essential libpam0g-dev libpam0g # Use cargo to test the project test:cargo: script: - rustc --version && cargo --version # Print version info for debugging - cargo test --workspace --verbose # only on nightly # - cargo bench --workspace --verbose pleaser-0.5.1/CHANGELOG.md010064400017500001750000000040711415313273200131450ustar 000000000000000.5.1 * editmode=keep now default if no other mode is specified * only include files in includedir if they do not start with . * trimmed error when unable to communicate with syslog 0.5.0 * backslashes within arguments now require escaping * editmode=keep to preserve the file permission bits from an existing file * exact_{rule,target,name,hostname,dir} which are literal * nix bump to 0.23.0 * deprecating regex term in favour of rule 0.4.2 * allow environments to pass through * allow some environment variables to be forced * handle tstp from shell to editor 0.4.1 * condensing clock and fixing for 32bit * merging syslog version dependency * pam conversation separation for netbsd 0.4.0 * Changing chmod in pleaseedit to use fd * splitting do_environment into set and clean * umask into set_environment * renaming reset and eprivs to esc and drop * fchown on fd * search_path and do_dir_changes print os errors * use seteuid/setguid * use nofollow * dir should be limited to range, or excluded if not specified * use rand characters in temp file names * limit config processing to 10MB * valid token uses both wall and monotonic clock * pam follows conversation * failed edits are now cleaned upon editor exit Thanks to Matthias Gerstner for these recommendations 0.3.22 [fix] spaces within arguments should be escaped -u should alias -t please and pleaseedit should output help when run without arguments 0.3.21 Cargo.lock for packagers * [fix] don't output unparsed config * [fix] path enumeration reported by @noproto * man page tidy * list error should show "your" 0.3.20 * Add current working directory to the syslo * Fix editor execution if it has arguments 0.3.19 * [fix] group list in pleaseedit 0.3.18 * New syslog bool * exitcmd placeholders 0.3.17 * Man improvements 0.3.16 * Minor optimisations * documentation around repeating regex rules 0.3.15 * Performance improvements 0.3.14 * 'last' option to halt processing on match 0.3.13 * documentation fix for datematch 0.3.12 * setgroup error capture 0.3.11 * crate dependency change to align with debian pleaser-0.5.1/CONTRIBUTING.md010064400017500001750000000026131415312627500135720ustar 00000000000000# Introduction Thank you for your interest in this project. # Licence Currently this project is licensed as GPL-3.0-or-later. At a later date there may be a significant reason to re-licence under new terms. If this is something that you may not wish, please state in a commit that you wish the contribution to be GPL-3.0-or-later. There may be a situation where, for project adoption GPL-3.0-or-later might not be compatible, but as yet I have no reason to think so. # Submissions I prefer commits to be submitted via pull requests at https://gitlab.com/edneville/please. This has the benefit of keeping track of who submitted something (this is important). Please squash/rebase your commits if you know how. Your commit message should be well formatted. Lines should be less than 72 characters long, the first should be a brief description, the second line should be blank, then bullet-point style paragraphs should follow. All submissions must be reviewed. You, at a later date may be the person performing the review or building the changelog. # Security If you have a security concern that you do not wish to report publicly please mail that to ed-please@s5h.net. # Tests Ensure that if you add something new, or change behaviour, it must be testable. Please create new tests and ensure that existing tests are not broken. # Credits If you wish, please add yourself to the credits in `src/util.rs`. pleaser-0.5.1/Cargo.lock0000644000000214771415314266100105210ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. [[package]] name = "aho-corasick" version = "0.7.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7404febffaa47dac81aa44dba71523c9d069b1bdc50a77db41195149e17f68e5" dependencies = [ "memchr", ] [[package]] name = "autocfg" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "cc" version = "1.0.67" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c69b077ad434294d3ce9f1f6143a2a4b89a8a2d54ef813d85003a4fd1137fd" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" version = "0.4.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" dependencies = [ "libc", "num-integer", "num-traits", "time", "winapi", ] [[package]] name = "error-chain" version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d2f06b9cac1506ece98fe3231e3cc9c4410ec3d5b1f24ae1c8946f0742cdefc" dependencies = [ "version_check", ] [[package]] name = "getopts" version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" dependencies = [ "unicode-width", ] [[package]] name = "getrandom" version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" dependencies = [ "cfg-if", "libc", "wasi 0.9.0+wasi-snapshot-preview1", ] [[package]] name = "libc" version = "0.2.103" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd8f7255a17a627354f321ef0055d63b898c6fb27eff628af4d1b66b7331edf6" [[package]] name = "log" version = "0.4.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51b9bbe6c47d51fc3e1a9b945965946b4c44142ab8792c50835a980d362c2710" dependencies = [ "cfg-if", ] [[package]] name = "memchr" version = "2.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525" [[package]] name = "memoffset" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "59accc507f1338036a0477ef61afdae33cde60840f4dfe481319ce3ad116ddf9" dependencies = [ "autocfg", ] [[package]] name = "nix" version = "0.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f305c2c2e4c39a82f7bf0bf65fb557f9070ce06781d4f2454295cc34b1c43188" dependencies = [ "bitflags", "cc", "cfg-if", "libc", "memoffset", ] [[package]] name = "num-integer" version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2cc698a63b549a70bc047073d2949cce27cd1c7b0a4a862d08a8031bc2801db" dependencies = [ "autocfg", "num-traits", ] [[package]] name = "num-traits" version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a64b1ec5cda2586e284722486d802acf1f7dbdc623e2bfc57e65ca1cd099290" dependencies = [ "autocfg", ] [[package]] name = "once_cell" version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ad167a2f54e832b82dbe003a046280dceffe5227b5f79e08e363a29638cfddd" [[package]] name = "pam" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa2bdc959c201c047004a1420a92aaa1dd1a6b64d5ef333aa3a4ac764fb93097" dependencies = [ "libc", "pam-sys", "users 0.8.1", ] [[package]] name = "pam-sys" version = "0.5.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd4858311a097f01a0006ef7d0cd50bca81ec430c949d7bf95cbefd202282434" dependencies = [ "libc", ] [[package]] name = "pleaser" version = "0.5.1" dependencies = [ "chrono", "getopts", "libc", "nix", "pam", "rand", "regex", "rpassword", "syslog", "users 0.10.0", ] [[package]] name = "ppv-lite86" version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857" [[package]] name = "rand" version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" dependencies = [ "getrandom", "libc", "rand_chacha", "rand_core", "rand_hc", ] [[package]] name = "rand_chacha" version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" dependencies = [ "getrandom", ] [[package]] name = "rand_hc" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" dependencies = [ "rand_core", ] [[package]] name = "regex" version = "1.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9251239e129e16308e70d853559389de218ac275b515068abc96829d05b948a" dependencies = [ "aho-corasick", "memchr", "regex-syntax", "thread_local", ] [[package]] name = "regex-syntax" version = "0.6.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5eb417147ba9860a96cfe72a0b93bf88fee1744b5636ec99ab20c1aa9376581" [[package]] name = "rpassword" version = "5.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ffc936cf8a7ea60c58f030fd36a612a48f440610214dc54bc36431f9ea0c3efb" dependencies = [ "libc", "winapi", ] [[package]] name = "syslog" version = "5.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a5d8ef1b679c07976f3ee336a436453760c470f54b5e7237556728b8589515d" dependencies = [ "error-chain", "libc", "log", "time", ] [[package]] name = "thread_local" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8018d24e04c95ac8790716a5987d0fec4f8b27249ffa0f7d33f1369bdfb88cbd" dependencies = [ "once_cell", ] [[package]] name = "time" version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" dependencies = [ "libc", "wasi 0.10.0+wasi-snapshot-preview1", "winapi", ] [[package]] name = "unicode-width" version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3" [[package]] name = "users" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fed7d0912567d35f88010c23dbaf865e9da8b5227295e8dc0f2fdd109155ab7" dependencies = [ "libc", ] [[package]] name = "users" version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aa4227e95324a443c9fcb06e03d4d85e91aabe9a5a02aa818688b6918b6af486" dependencies = [ "libc", "log", ] [[package]] name = "version_check" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fecdca9a5291cc2b8dcf7dc02453fee791a280f3743cb0905f8822ae463b3fe" [[package]] name = "wasi" version = "0.9.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" [[package]] name = "wasi" version = "0.10.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" pleaser-0.5.1/Cargo.toml0000644000000025751415314266100105420ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] edition = "2018" name = "pleaser" version = "0.5.1" authors = ["ed neville "] description = "please, a polite regex-first sudo alternative" homepage = "https://www.usenix.org.uk/content/please.html" documentation = "https://www.usenix.org.uk/content/please.html" readme = "README.md" keywords = ["please", "access", "elevation", "edit", "regex"] categories = ["command-line-utilities"] license = "GPL-3.0-or-later" repository = "https://gitlab.com/edneville/please" [dependencies.chrono] version = "0.4" [dependencies.getopts] version = "0.2" [dependencies.libc] version = "0.2" [dependencies.nix] version = ">= 0.23" [dependencies.pam] version = "0.7" [dependencies.rand] version = "0.7" [dependencies.regex] version = "1.3" [dependencies.rpassword] version = "5.0" [dependencies.syslog] version = ">= 4.0" [dependencies.users] version = ">= 0.10" pleaser-0.5.1/Cargo.toml.orig010064400017500001750000000012211415312630000142070ustar 00000000000000[package] name = "pleaser" version = "0.5.1" authors = ["ed neville "] edition = "2018" description = "please, a polite regex-first sudo alternative" license = "GPL-3.0-or-later" homepage = "https://www.usenix.org.uk/content/please.html" repository = "https://gitlab.com/edneville/please" readme = "README.md" categories = ["command-line-utilities"] documentation = "https://www.usenix.org.uk/content/please.html" keywords = ["please", "access", "elevation", "edit", "regex"] [dependencies] regex = "1.3" chrono = "0.4" getopts = "0.2" nix = ">= 0.23" pam = "0.7" users = ">= 0.10" rpassword = "5.0" syslog= ">= 4.0" libc = "0.2" rand = "0.7" pleaser-0.5.1/LICENSE010064400017500001750000001043161372276612500123560ustar 00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. 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. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey 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; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or co 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "paense" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, yoy covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. 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. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 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. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. 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 whiso, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state 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 3 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, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program 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, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU 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 Lesser General Public License instead of this License. But first, please read . pleaser-0.5.1/README.md010064400017500001750000000306661415312630000126160ustar 00000000000000# Please, a sudo alternative with regex support Great! This is what I need. The aim is to allow admins to delegate accurate least privilege access with ease. There are times when what is intended to be executed can be expressed easily with a regex to expose only what is needed and nothing more. The idea is to help you admin your box without giving users full root shells, just because that is easier. Most admins have experience of regex in one form or another, so lets configure access that way. I saw regex but don't like regex. No problem, you can still use please without regex using `exact_` counterparts, or treat each field/property as plain text, and escape control characters `?(){}[]+` etc. Most of the regex match statements have `exact` counterparts. Please is written with memory safe rust. Traditional C memory unsafety is avoided, logic problems may still exist. Logic problems would exist in both systems, but I choose the smaller problem set. # How do I install it It might already be in the repo that you're using: [![Packaging status](https://repology.org/badge/vertical-allrepos/pleaser.svg)](https://repology.org/project/pleaser/versions) If not, it is a simple install: ``` git clone https://gitlab.com/edneville/please.git cd please cargo test && cargo build --release \ && install -oroot -groot -D -m4755 target/release/please target/release/pleaseedit /usr/local/bin ``` Arch: ``` pacman -Syu git fakeroot devtools binutils gcc rust git clone https://aur@aur.archlinux.org/pleaser.git cd pleaser && makepkg -isr ``` Debian/Ubuntu: ``` apt install pleaser ``` Fedora (35): ``` dnf install pleaser ``` NetBSD: ``` pkgin install pleaser ``` SUSE Tumbleweed: ``` zypper install pleaser ``` RHEL 7 (EPEL): ``` yum install cargo git pam-devel git clone 'https://gitlab.com/edneville/please.git' cd please/ cargo test && cargo build --release && install -oroot -groot -D -m4755 target/release/please target/release/pleaseedit /usr/local/bin ``` Optionally, set `sudo` as an alias of `please`: ``` alias sudo="please" alias sudoedit="pleaseedit" ``` Or, if you like, symlink in local: ``` cd /usr/local/bin && ln -s /usr/local/bin/please sudo && ln -s /usr/local/bin/pleaseedit sudoedit ``` # How do I set it up You may need to configure PAM if you didn't use a distro package in order for `require_pass` to authenticate. Debian-based needs something similar to this in `/etc/pam.d/please` and `/etc/pam.d/pleaseedit`: ``` #%PAM-1.0 @include common-auth @include common-account @include common-session-noninteractive ``` Red Hat based needs something similar to this in the same files: ``` #%PAM-1.0 auth include system-auth account include system-auth password include system-auth session optional pam_keyinit.so revoke session required pam_limits.so session include system-auth ``` Next, configure your `/etc/please.ini`, replace user names with appropriate values. The `ini` is divided into section options, matches and actions. ## Section options | Part | Effect | |-----------------------------|--------------| | [section-name] | Section name, shown in list mode | | include=file | Include file as another ini source, other options will be skipped in this section. | | includedir=dir | Include dir of `.ini` files as other sources, in ascii sort order other options will be skipped in this section. Files not matching `.ini` will be ignored to allow for editor tmp files. | `include` and `includedir` will override mandatory arguments. ## Matches One of the simplest, that does not require password authentication can be defined as follows, assuming the user is `jim`: The options are as follows: | Part | Effect | |-----------------------------|--------------| | name=regex | Mandatory, apply configuration to this entity. | | target=regex | May become these users. | | rule=regex | This is the command regex for the section, default is ^$ | | notbefore=YYYYmmdd | The date, or YYYYmmddHHMMSS when this rule becomes effective. | | notafter=YYYYmmdd | The date, or YYYYmmddHHMMSS when this rule expires. | | datematch=[Day dd Mon HH:MM:SS UTC YYYY] | regex to match against a date string | | type=[edit/run/list] | Set the entry type, run = execution, edit = pleaseedit, list = show user rights | | group=[true/false] | True to signify that name= refers to a group rather than a user. | | hostname=regex | Hosts where this applies, defaults to 'localhost'. | | dir=regex | Permit switching to regex defined directory prior to execution. | | reason=[true/false] | when true, require a reason to be provided by `-r`, defaults to false | | permit_env=regex | when combined with `-a`, permit matching environments keys | Exact counterparts, which must match exactly. When both regex and exact rules are present, the exact rule match will have precedence. | Part | Effect | |-----------------------------|--------------| | exact_name=string | Match this exact name | | exact_hostname=string | Match this exact hostname | | exact_target=string | Match this exact target user | | exact_rule=string | Match this exact rule | | exact_dir=string | Match this exact directory | ## Actions | Part | Effect | |-----------------------------|--------------| | permit=[true/false] | Defaults to true | | require_pass=[true/false] | Defaults to true, mandatory in run and edit, become this user | | last=[true/false] | when true, stop processing when matched, defaults to false | | syslog=[true/false] | log this activity to syslog, default = true | | env_assign.key=value | force environment **key** to be assigned **value** | | exitcmd=[program] | (edit) continue with file replacement if `program` exits 0 | | editmode=[octal mode/keep] | (edit) set destination file mode to `octal mode`, or keep the mode of an existing file. If the file is not present, or mode is not declared, then mode falls back to 0600. If there is a file present, then the mode is read and used just prior to file rename | Using a greedy `.*` for the regex field will be as good as saying the rule should match any command. In previous releases there was no anchor (`^` and `$`) however, it seems more sensible to follow `find`'s approach and insist that there are anchors around the regex. This avoids `/bin/bash` matching `/home/user/bin/bash` unless the rule permits something like `/home/%{USER}/bin/bash`. If a `include` directive is met, no other entries in the section will be processed. The same goes for `includedir`. The ordering of rules matters. The last match will win. Set `permit=false` if you wish to exclude something, but this should be very rare as the permit should be against a regex rather than using a positive and then a negative match. A rule of best practice is to avoid a fail open and then try and exclude most of the universe. For example, using the two entries below: ``` [jim_root_du] name=jim target=root permit=true rule = ^(/usr)?/bin/du (/home/[a-z0-9-]+\s?)+ require_pass=false ``` ``` [jim_postgres] name=jim target=postgres permit=true rule = /bin/bash require_pass=false ``` Would permit running `du`, as `/usr/bin/du` or `/bin/du` as `root`: ``` $ please du /home/* ``` And would also permit running a bash shell as `postgres`: ``` $ please -t postgres /bin/bash postgres$ ``` # Date ranges For large environments it is not unusual for a third party to require access during a short time frame for debugging. To accommodate this there are the `notbefore` and `notafter` time brackets. These can be either `YYYYMMDD` or `YYYYMMDDHHMMSS`. The whole day is considered when using the shorter date form of `YYYYMMDD`. Many enterprises may wish to permit access to a user for a limited time only, even if that individual is in the role permanently. # Date matches Another date type is the `datematch` item, this constrains sections to a regex match against the date string `Day dd Mon HH:MM:SS UTC Year`. You can permit some a group of users to perform some house keeping on a Monday: ``` [l2_housekeeping] name=l2users group=true target=root permit=true rule = /usr/local/housekeeping/tidy_(logs|images|mail) datematch = ^Mon.* ``` # pleaseedit `pleaseedit` enables editing of files as another user. Enable editing rather than execution with `type=edit`. The first argument will be passed to `EDITOR`. By default file permission bits will mirror existing file permissions. This is performed as follows: 1. user runs edit as `pleaseedit -u root /etc/fstab` 2. `/etc/fstab` is copied to `/tmp/pleaseedit.$USER.r8cYph9h._etc_fstab` 3. user's `EDITOR` is executed against `/tmp/pleaseedit.$USER.r8cYph9h._etc_fstab` 4. if `EDITOR` exits 0, and `exitcmd` exits 0, then `/tmp/pleaseedit.$USER.r8cYph9h._etc_fstab` is copied to `/etc/fstab.llD3wRQB.pleaseedit.copy.$USER` 5. `/etc/fstab.llD3wRQB.pleaseedit.copy.$USER` is set as (target) root owned and `renamed` to `/etc/fstab` # exitcmd exitcmd can be used prior to the tmp edit file move to the source location. This can be used to test configuration files are valid prior to renaming in place. For something similar to apache, consider copying the config tree to a tmp directory before running the test to accommodate includes. # Other examples Members of the `audio` group may remove temporary users that an application may not have cleaned up in the form of `username_tmp.<10 random alphanumerics>` using `userdel`: ``` [user_remove_tmp_user] name = audio group = true permit = true require_pass = false rule = /usr/sbin/userdel -f -r %{USER}_tmp\.[a-zA-Z0-9]{10} ``` How about, for the purpose of housekeeping, some users may be permitted to destroy zfs snapshots that look roughly like they're date stamped: ``` [user_remove_snapshots] name = data group = true permit = true require_pass = false rule = /usr/sbin/zfs destroy storage/photos@\d{8}T\d{6} ``` To list what you may or may not do: ``` $ please -l You may run the following: file: /etc/please.ini ed_root_list:root: ^.*$ You may edit the following: file: /etc/please.ini ed_edit_ini:root: ^/etc/please.ini$ ``` The above output shows that I may run anything and may edit the `please.ini` configuration. Or, perhaps any user who's name starts `admin` may execute `useradd` and `userdel`: ``` [admin_users] name = admin_\S+ permit = true require_pass = false rule = /usr/sbin/user(add -m|del) \S+ ``` # Files /etc/please.ini # Big installs For big installs, consider the following: ## Consolidate Where you can use groups when all member least privilege matches the set. It is best here to consider that people often perform the same role, so try and organise the rules that way, so use either a group or list accounts in a single `name` regex match. ## Central configuration considerations To avoid single points of failure in a service, `ini` configuration should be generated in a single location and pushed to installs. `ini` files parse very quickly whilst accessing LDAP is not only slower but also error prone. It could be possible to use caching, but a form of positive (correct match) and negative (incorrect match) would be required. 10,000 computers with hundreds of active users performing lookups against an LDAP server could be problematic. For these reasons I prefer rsync distribution as the protocol is highly efficient and reduces network transfer overall. LDAP may at a later date be reconsidered. # Contributions Should you find anything that you feel is missing, regardless of initial design, please feel free to raise an issue with or without a pull request. Locating bugs and logging issues are very appreciated, and I thank you in advance. I welcome pull requests with open arms. # Locations The source code for this project is currently hosted on [gitlab](https://gitlab.com/edneville/please) and mirrored to [github](https://github.com/edneville/please). There is a [crate on crates.io](https://crates.io/crates/pleaser). It also has a [homepage](https://www.usenix.org.uk/content/please.html) where other project information is kept. # Why pleaser in some circles? This project is named "please". In some places that project name was used by others for other things. Some packages will be named pleaser, some will be named please. The only important thing is if you wish someone to make you a sandwich, just say "please" first. pleaser-0.5.1/examples/pam/debian010064400017500001750000000001371415312630000150650ustar 00000000000000#%PAM-1.0 @include common-auth @include common-account @include common-session-noninteractive pleaser-0.5.1/examples/pam/fedora010064400017500001750000000003561415312630000151060ustar 00000000000000#%PAM-1.0 auth include system-auth account include system-auth password include system-auth session optional pam_keyinit.so revoke session required pam_limits.so session include system-auth pleaser-0.5.1/examples/pam/suse010064400017500001750000000003561415312630000146250ustar 00000000000000#%PAM-1.0 auth include system-auth account include system-auth password include system-auth session optional pam_keyinit.so revoke session required pam_limits.so session include system-auth pleaser-0.5.1/examples/please.ini010064400017500001750000000040351415313273200151240ustar 00000000000000# ## Example rules and edit checkers, other suggestions welcomed ## Consider putting local *.ini configuration files in /etc/please.d # ## include *.ini files from the /etc/please.d directory (create it first) [include_local] includedir = /etc/please.d ## permit user 'jim' to run anything # #[jim_become_root] #name = jim #target = root #rule = .* #require_pass = false # ## permit user jim to modify the hosts file # #[jim_hosts] #name = jim #type = edit #target = root #rule = /etc/hosts #editmode = 644 #require_pass = false # ## permit user jim to modify the /etc/please.ini and run a check on exit # #[jim_please] #name = jim #type = edit #target = root #rule = ^/etc/please(\.d/[\w.-]+)?\.ini$ #editmode = 600 #require_pass = false #exitcmd = /usr/bin/please -c %{NEW} # ## permit all users to view their own ACL # #[list_own] #name=^%{USER}$ #permit=true #type=list #target=^%{USER}$ # ## config checkers # ## check fstab # #[fstab] #name=jim #type=edit #exitcmd=/bin/findmnt --verify --tab-file %{NEW} #target=root #rule=/etc/fstab #editmode=644 # ## check openntpd config # #[edit_ntpd] #name=jim #type=edit #rule=/etc/openntpd/ntpd.conf #editmode=644 #exitcmd=/usr/sbin/ntpd -f %{NEW} -n # ## check squid config # #[squid_check] #name=jim #type=edit #rule=/etc/squid/squid.conf #exitcmd=/usr/sbin/squid -k check -f %{NEW} #editmode=644 # ## sshd # #[sshd] #name=jim #type=edit #exitcmd=/usr/sbin/sshd -t -f %{NEW} #editmode=644 #rule=/etc/ssh/sshd_config # ## bind named.conf # #[named_conf] #name=jim #type=edit #exitcmd=/usr/sbin/named-checkconf %{NEW} #editmode=644 #rule=/etc/bind/named.conf # ## bind zone ## setup /usr/local/bin/my-named-checkzone, like this: ## ## #!/bin/sh ## DOMAIN=`echo "$PLEASE_SOURCE_FILE" | sed -e 's%/etc/bind/db\.%%g'` ## /usr/sbin/named-checkzone "$DOMAIN" "$1" # #[named_zone] #name=jim #type=edit #exitcmd=/usr/local/bin/my-named-checkzone %{NEW} #editmode=644 #rule=/etc/bind/db\.[\w.-]+ # ## nginx config # #[nginx_config] #name=jim #type=edit #exitcmd=/usr/sbin/nginx -t -c %{NEW} #editmode=644 #rule=/etc/nginx/nginx.conf pleaser-0.5.1/man/please.1010064400017500001750000000071011415313273200134370ustar 00000000000000.\" Automatically generated by Pandoc 2.9.2.1 .\" .TH "please" "1" "04 December 2021" "please 0.5.1" "User Manual" .hy .SH NAME .PP please - a tool for access elevation. .SH SYNOPSIS .PP \f[B]please /bin/bash\f[R] .PP \f[B]pleaseedit /etc/fstab\f[R] .PP \f[B]pleaseedit [-r/--reason \[dq]new fs\[dq]] /etc/fstab\f[R] .PP \f[B]please [-a/--allowenv list]\f[R] .PP \f[B]please [-c/--check] /etc/please.ini\f[R] .PP \f[B]please [-d/--dir directory] command\f[R] .PP \f[B]please [-h/--help]\f[R] .PP \f[B]please [-t/--target username] backup tar -cvf - /home/data | \&...\f[R] .PP \f[B]please [-u/--user username] backup tar -cvf - /home/data | \&...\f[R] .PP \f[B]please [-l/--list]\f[R] .PP \f[B]please [-l/--list] [-t/--target username]\f[R] .PP \f[B]please [-l/--list] [-u/--user username]\f[R] .PP \f[B]please [-n/--noprompt] command\f[R] .PP \f[B]please [-r/--reason \[dq]sshd reconfigured, ticket 24365\[dq]] /etc/init.d/ssh restart\f[R] .PP \f[B]please [-p/--purge]\f[R] .PP \f[B]please [-w/--warm]\f[R] .SH DESCRIPTION .PP \f[B]please\f[R] and \f[B]pleaseedit\f[R] are sudo alternatives that have regex support and a simple approach to ACL. .PP The aim is to allow admins to delegate accurate principle of least privilege access with ease. \f[B]please.ini\f[R] allows for very specific and flexible regex defined permissions. .PP \f[B]pleaseedit\f[R] adds a layer of safety to editing files. The file is copied to /tmp, where it can be updated. When \f[B]EDITOR\f[R] exits cleanly the file is copied alongside the target, the file will then be renamed over the original, but if a \f[B]exitcmd\f[R] is configured it must exit cleanly first. .TP \f[B]-a\f[R]/\f[B]--allowenv list\f[R] allow environments separated by \f[B],\f[R] to be passed through .TP \f[B]-c\f[R]/\f[B]--check file\f[R] will check the syntax of a \f[B]please.ini\f[R] config file. Exits non-zero on error .TP \f[B]-d\f[R]/\f[B]--dir\f[R] will change directory to \f[B]dir\f[R] prior to executing the command .TP \f[B]-h\f[R]/\f[B]--help\f[R] print help and exit .TP \f[B]-l\f[R]/\f[B]--list\f[R] to list rules .TP \f[B]-n\f[R]/\f[B]--noprompt\f[R] will not prompt for authentication and exits with a status of 1 .TP \f[B]-p\f[R]/\f[B]--purge\f[R] will purge your current authentication token for the running user .TP \f[B]-r\f[R]/\f[B]--reason\f[R] \f[B][reason]\f[R] will add \f[B]reason\f[R] to the system log .TP \f[B]-t\f[R]/\f[B]--target\f[R] \f[B][username]\f[R] to execute command, or edit as target \f[B]username\f[R] .TP \f[B]-u\f[R]/\f[B]--user\f[R] \f[B][username]\f[R] to execute command, or edit as target \f[B]username\f[R] .TP \f[B]-v\f[R]/\f[B]--version\f[R] print version and exit .TP \f[B]-w\f[R]/\f[B]--warm\f[R] will warm an authentication token and exit .SH EXAMPLE USAGE .TP \f[B]please -t httpd /bin/bash\f[R] run a shell as the httpd user .TP \f[B]please -l\f[R] to list what you may run .TP \f[B]please -t \[dq]username\[dq] -l\f[R] to show what username may run. \f[B]username\f[R] must match the target regex in a \f[B]type=list\f[R] rule .TP \f[B]please -r \[aq]reloading apache2, change #123\[aq] systemctl reload apache2\f[R] to reload apache2 with a reason .TP \f[B]pleaseedit -r \[aq]adding new storage, ticket #24365\[aq] /etc/fstab\f[R] to use pleaseedit to modify \f[B]fstab\f[R] .PP Please see \f[B]please.ini\f[R] for configuration examples. .SH FILES .PP /etc/please.ini .SH CONTRIBUTIONS .PP I welcome pull requests with open arms. New features always considered. .SH BUGS .PP Found a bug? Please either open a ticket or send a pull request/patch. .SH SEE ALSO .PP \f[B]please.ini\f[R](5) .SH AUTHORS Ed Neville (ed-please\[at]s5h.net). pleaser-0.5.1/man/please.ini.5010064400017500001750000000320561415313273200142300ustar 00000000000000.\" Automatically generated by Pandoc 2.9.2.1 .\" .TH "please.ini" "5" "04 December 2021" "please 0.5.1" "User Manual" .hy .SH NAME .PP please.ini - configuration file for access .SH DESCRIPTION .PP The \f[B]please.ini\f[R] file contains one or more \f[B][sections]\f[R] that hold ACL for users of the \f[B]please\f[R] and \f[B]pleaseedit\f[R] programs. .PP \f[C]please.ini\f[R] is an ini file, sections can be named with a short description of what the section provides. You may then find this helpful when listing rights with \f[B]please -l\f[R]. .PP Rules are read and applied in the order they are presented in the configuration file. For example, if the user matches a permit rule to run a command in an early section, but in a later section matches criteria for a deny and no further matches, then the user will not be permitted to run that command. The last match wins. .PP The properties permitted are described below and should appear at most once per section. If a property is used more than once in a section, the last one will be used. .SH SECTION OPTIONS .TP \f[B][section-name]\f[R] section name, shown in list mode .TP \f[B]include=[file]\f[R] read ini file, and continue to next section .TP \f[B]includedir=[directory]\f[R] read .ini files in directory, and continue to next section, if the directory does not exist config parse will fail .SH MATCHES .TP \f[B]name=[regex]\f[R] mandatory, the user or \f[B]group\f[R] (see below) to match against .TP \f[B]target=[regex]\f[R] user to execute or list as, defaults to \f[B]root\f[R] .TP \f[B]rule=[regex]\f[R] the regular expression that the command or edit path matches against, defaults to \[ha]$ .TP \f[B]notbefore=[YYYYmmdd|YYYYmmddHHMMSS]\f[R] will add HHMMSS as 00:00:00 to the date if not given, defaults to never .TP \f[B]notafter=[YYYYmmdd|YYYYmmddHHMMSS]\f[R] will add 23:59:59 to the date if not given, defaults to never .TP \f[B]datematch=[Day dd Mon HH:MM:SS UTC YYYY]\f[R] regex to match a date string with .TP \f[B]type=[edit/run/list]\f[R] this section\[cq]s mode behaviour, defaults to \f[B]run\f[R], edit = \f[B]pleaseedit\f[R] entry, list = user access rights listing .TP \f[B]group=[true|false]\f[R] defaults to false, when true, the \f[B]name\f[R] (above) refers to a group rather than a user .TP \f[B]hostname=[regex]\f[R] permitted hostnames where this may apply. A hostname defined as \f[B]any\f[R] or \f[B]localhost\f[R] will always match. Defaults to localhost .TP \f[B]dir=[regex]\f[R] permitted directories to run within .TP \f[B]permit_env=[regex]\f[R] allow environments that match \f[B]regex\f[R] to optionally pass through .PP \f[B]regex\f[R] is a regular expression, \f[B]%{USER}\f[R] will expand to the user who is currently running \f[C]please\f[R]. This enables a single rule for a group to modify/run something that matches their name. .PP Spaces within arguments will be substituted as \f[B]`\[rs]\ '\f[R] (backslash space). Use \f[B]\[ha]/bin/echo hello\[rs]\[rs] world$\f[R] to match \f[B]/bin/echo \[lq]hello world\[rq]\f[R], note that \f[B]\[rs]\f[R] is a regex escape character so it must be escaped, therefore matching a space becomes \f[B]`\[rs]\[rs]\ '\f[R] (backslash backslash space). .PP To match a \f[B]\[rs]\f[R] (backslash), the hex code \f[B]\[rs]x5c\f[R] can be used. .PP To match the string \f[B]%{USER}\f[R], the sequence \f[B]\[rs]x25\[rs]{USER\[rs]}\f[R] can be used. .PP Rules starting \f[B]exact\f[R] are string matches and not \f[B]regex\f[R] processed and take precedence over \f[B]regex\f[R] matches. .TP \f[B]exact_name=[string]\f[R] only permit a user/group name that matches exactly .TP \f[B]exact_hostname=[string]\f[R] only permit a hostname that matches exactly .TP \f[B]exact_target=[string]\f[R] only permit a target that matches exactly .TP \f[B]exact_rule=[string]\f[R] only permit a command rule that matches exactly .TP \f[B]exact_dir=[string]\f[R] only permit a dir that matches exactly .SH ACTIONS .TP \f[B]permit=[true|false]\f[R] permit or disallow the entry, defaults to true .TP \f[B]require_pass=[true|false]\f[R] if entry matches, require a password, defaults to true .TP \f[B]reason=[true|false]\f[R] require a reason for execution/edit, defaults to false .TP \f[B]last=[true|false]\f[R] if true, stop processing when entry is matched, defaults to false .TP \f[B]syslog=[true|false]\f[R] log this activity to syslog, defaults to true .TP \f[B]env_assign.[key]=[value]\f[R] assign \f[B]value\f[R] to environment \f[B]key\f[R] .TP \f[B]editmode=[octal mode|keep]\f[R] (\f[B]type=edit\f[R]) set the file mode bits on replacement file to octal mode. When set to \f[B]keep\f[R] use the existing file mode. If the file is not present, or mode is not declared, then mode falls back to 0600. If there is a file present, then the mode is read and used just prior to file rename. .TP \f[B]exitcmd=[program]\f[R] (\f[B]type=edit\f[R]) run program after editor exits as the target user, if exit is zero, continue with file replacement. \f[B]%{NEW}\f[R] and \f[B]%{OLD}\f[R] placeholders expand to new and old edit files .SH EXAMPLES .PP To allow all commands, you can use a greedy match (\f[B]\[ha].*$\f[R]). You should reduce this to the set of acceptable commands though. .IP .nf \f[C] [user_jim_root] name=jim target=root rule=\[ha].*$ \f[R] .fi .PP If you wish to permit a user to view another\[cq]s command set, then you may do this using \f[B]type=list\f[R] (\f[B]run\f[R] by default). To list another user, they must match the \f[B]target\f[R] regex. .IP .nf \f[C] [user_jim_list_root] name=jim type=list target=root \f[R] .fi .PP \f[B]type\f[R] may also be \f[B]edit\f[R] if you wish to permit a file edit with \f[B]pleaseedit\f[R]. .IP .nf \f[C] [user_jim_edit_hosts] name=jim type=edit target=root rule=\[ha]/etc/hosts$ editmode=644 \f[R] .fi .PP Naming sections should help later when listing permissions. .PP Below, user \f[B]mandy\f[R] may run \f[B]du\f[R] without needing a password, but must enter her password for a \f[B]bash\f[R] running as root: .IP .nf \f[C] [mandy_du] name = mandy rule = \[ha](/usr)?/bin/du .*$ require_pass = false [mandy_some] name = mandy rule = \[ha](/usr)?/bin/bash$ require_pass = true \f[R] .fi .PP The rule \f[B]regex\f[R] can include repetitions. To permit running \f[B]wc\f[R] to count the lines in the log files (we don\[cq]t know how many there are) in \f[B]/var/log\f[R]. This sort of regex will allow multiple instances of a \f[B]()\f[R] group with \f[B]+\f[R], which is used to define the character class \f[B][a-zA-Z0-9-]+\f[R], the numeric class \f[B]\f[R] and the group near the end of the line. In other words, multiple instances of files in \f[B]/var/log\f[R] that may end in common log rotate forms \f[B]-YYYYMMDD\f[R] or \f[B].N\f[R]. .PP This will permit commands such as the following, note how for efficiency find will combine arguments with \f[B]+\f[R] into fewer invocations. \f[B]xargs\f[R] could have been used in place of \f[B]find\f[R]. .IP .nf \f[C] $ find /var/log -type f -exec please /usr/bin/wc {} \[rs]+ \f[R] .fi .PP Here is a sample for the above scenario: .IP .nf \f[C] [user_jim_root_wc] name=jim target=root permit=true rule=\[ha]/usr/bin/wc (/var/log/[a-zA-Z0-9-]+(\[rs].\[rs]d+)?(\[rs]s)?)+$ \f[R] .fi .PP User jim may only start or stop a docker container: .IP .nf \f[C] [user_jim_root_docker] name=jim target=root permit=true rule=\[ha]/usr/bin/docker (start|stop) \[rs]S+ \f[R] .fi .PP User ben may only edit \f[B]/etc/fstab\f[R], and afterwards check the fstab file: .IP .nf \f[C] [ben_fstab] name=ben target=root permit=true type=edit editmode=644 rule=\[ha]/etc/fstab$ exitcmd=/bin/findmnt --verify --tab-file %{NEW} \f[R] .fi .PP User ben may list only users \f[B]eng\f[R], \f[B]net\f[R] and \f[B]dba\f[R]: .IP .nf \f[C] [ben_ops] name=ben permit=true type=list target=\[ha](eng|net|dba)ops$ \f[R] .fi .PP All users may list their own permissions. You may or may not wish to do this if you consider permitting a view of the rules to be a security risk. .IP .nf \f[C] [list_own] name=\[ha]%{USER}$ permit=true type=list target=\[ha]%{USER}$ \f[R] .fi .SH EXITCMD .PP When the user completes their edit, and the editor exits cleanly, if \f[B]exitcmd\f[R] is included then this program will run as the target user. If the program also exits cleanly then the temporary edit will be copied to the destination. .PP \f[B]%{OLD}\f[R] and \f[B]%{NEW}\f[R] will expand to the old (existing source) file and edit candidate, respectively. To verify a file edit, \f[B]ben\f[R]\[cq]s entry to check \f[B]/etc/hosts\f[R] after clean exit could look like this: .IP .nf \f[C] [ben_ops] name=ben permit=true type=edit editmode=644 rule=\[ha]/etc/hosts$ exitcmd=/usr/local/bin/check_hosts %{OLD} %{NEW} \f[R] .fi .PP \f[B]/usr/local/bin/check_hosts\f[R] takes two arguments, the original file as the first argument and the modify candidate as the second argument. If \f[B]check_hosts\f[R] terminates zero, then the edit is considered clean and the original file is replaced with the candidate. Otherwise the edit file is not copied and is left, \f[B]pleaseedit\f[R] will exit with the return value from \f[B]check_hosts\f[R]. .PP A common \f[B]exitcmd\f[R] is to check the validity of \f[B]please.ini\f[R], shown below. This permits members of the \f[B]admin\f[R] group to edit \f[B]/etc/please.ini\f[R] if they provide a reason (\f[B]-r\f[R]). Upon clean exit from the editor the tmp file will be syntax checked. .IP .nf \f[C] [please_ini] name = admins group = true reason = true rule = /etc/please.ini type = edit editmode = 600 exitcmd = /usr/bin/please -c %{NEW} \f[R] .fi .SH DATED RANGES .PP For large environments it is not unusual for a third party to require access during a short time frame for debugging. To accommodate this there are the \f[B]notbefore\f[R] and \f[B]notafter\f[R] time brackets. These can be either \f[B]YYYYmmdd\f[R] or \f[B]YYYYmmddHHMMSS\f[R]. .PP The whole day is considered when using the shorter date form of \f[B]YYYYmmdd\f[R]. .PP Many enterprises may wish to permit periods of access to a user for a limited time only, even if that individual is considered to have a permanent role. .PP User joker can do what they want as root on 1st April 2021: .IP .nf \f[C] [joker_april_first] name=joker target=root permit=true notbefore=20210401 notafter=20210401 rule=\[ha]/bin/bash \f[R] .fi .SH DATEMATCHES .PP \f[B]datematch\f[R] matches against the date string \f[B]Day dd mon HH:MM:SS UTC Year\f[R]. This enables calendar style date matches. .PP Note that the day of the month (\f[B]dd\f[R]) will be padded with spaces if less than two characters wide. .PP You can permit a group of users to run \f[B]/usr/local/housekeeping/\f[R] scripts every Monday: .IP .nf \f[C] [l2_housekeeping] name=l2users group=true target=root permit=true rule = /usr/local/housekeeping/tidy_(logs|images|mail) datematch = \[ha]Mon\[rs]s+.* \f[R] .fi .SH REASONS .PP When \f[B]reason=true\f[R], a user must pass a reason with the \f[B]-r\f[R] option to \f[B]please\f[R] and \f[B]pleaseedit\f[R]. Some organisations may prefer a reason to be logged when a command is executed. This can be helpful for some situations where something such as \f[B]mkfs\f[R] or \f[B]useradd\f[R] might be preferable to be logged against a ticket. .IP .nf \f[C] [l2_user_admin] name=l2users group=true target=root permit=true reason=true rule = \[ha]/usr/sbin/useradd -m \[rs]w+$ \f[R] .fi .PP Perhaps you want to add a mini mollyguard: .IP .nf \f[C] [user_poweroff] name = l2users group = true rule = (/usr)?/s?bin/(shutdown( -h now)?|poweroff|reboot) require_pass = true reason = true \f[R] .fi .SH DIR .PP In some situations you may only want a command to run within a set of directories. The directory is specified with the \f[B]-d\f[R] argument to \f[B]please\f[R]. For example, a program may output to the current working directory, which may only be desirable in certain locations. .IP .nf \f[C] [eng_build_aliases] name=l2users group=true dir=\[ha]/etc/mail$ rule = \[ha]/usr/local/bin/build_aliases$ \f[R] .fi .SH LAST .PP \f[B]last=true\f[R] stops processing at a match: .IP .nf \f[C] [mkfs] name=l2users group=true target=root permit=true reason=true rule = \[ha]/sbin/mkfs.(ext[234]|xfs) /dev/sd[bcdefg]\[rs]d?$ last=true \f[R] .fi .PP For simplicity, there is no need to process other configured rules if certain that the \f[B]l2users\f[R] group are safe to execute this. \f[B]last\f[R] should only be used in situations where there will never be something that could contradict the match in an undesired way later. .SH SYSLOG .PP By default entries are logged to syslog. If you do not wish an entry to be logged then specify \f[B]syslog=false\f[R]. In this case \f[B]jim\f[R] can run anything in \f[B]/usr/bin/\f[R] as root and it will not be logged. .IP .nf \f[C] [maverick] syslog = false name = jim rule = /usr/bin/.* reason = false \f[R] .fi .SH FILES .PP /etc/please.ini .SH NOTES .PP At a later date repeated properties within the same section may be treated as a match list. .PP At a later date sections with names containing `default' may behave differently to normal sections. .SH CONTRIBUTIONS .PP I welcome pull requests with open arms. New features always considered. .SH BUGS .PP Found a bug? Please either open a ticket or send a pull request/patch. .SH SEE ALSO .PP \f[B]please\f[R](1) .SH AUTHORS Ed Neville (ed-please\[at]s5h.net). pleaser-0.5.1/please.ini.md010064400017500001750000000272261415313273200137140ustar 00000000000000--- title: please.ini section: 5 header: User Manual footer: please 0.5.1 author: Ed Neville (ed-please@s5h.net) date: 04 December 2021 --- # NAME please.ini - configuration file for access # DESCRIPTION The **please.ini** file contains one or more **[sections]** that hold ACL for users of the **please** and **pleaseedit** programs. `please.ini` is an ini file, sections can be named with a short description of what the section provides. You may then find this helpful when listing rights with **please -l**. Rules are read and applied in the order they are presented in the configuration file. For example, if the user matches a permit rule to run a command in an early section, but in a later section matches criteria for a deny and no further matches, then the user will not be permitted to run that command. The last match wins. The properties permitted are described below and should appear at most once per section. If a property is used more than once in a section, the last one will be used. # SECTION OPTIONS **[section-name]** : section name, shown in list mode **include=[file]** : read ini file, and continue to next section **includedir=[directory]** : read .ini files in directory, and continue to next section, if the directory does not exist config parse will fail # MATCHES **name=[regex]** : mandatory, the user or **group** (see below) to match against **target=[regex]** : user to execute or list as, defaults to **root** **rule=[regex]** : the regular expression that the command or edit path matches against, defaults to ^$ **notbefore=[YYYYmmdd|YYYYmmddHHMMSS]** : will add HHMMSS as 00:00:00 to the date if not given, defaults to never **notafter=[YYYYmmdd|YYYYmmddHHMMSS]** : will add 23:59:59 to the date if not given, defaults to never **datematch=[Day dd Mon HH:MM:SS UTC YYYY]** : regex to match a date string with **type=[edit/run/list]** : this section's mode behaviour, defaults to **run**, edit = **pleaseedit** entry, list = user access rights listing **group=[true|false]** : defaults to false, when true, the **name** (above) refers to a group rather than a user **hostname=[regex]** : permitted hostnames where this may apply. A hostname defined as **any** or **localhost** will always match. Defaults to localhost **dir=[regex]** : permitted directories to run within **permit_env=[regex]** : allow environments that match **regex** to optionally pass through **regex** is a regular expression, **%{USER}** will expand to the user who is currently running `please`. This enables a single rule for a group to modify/run something that matches their name. Spaces within arguments will be substituted as **'\\\ '** (backslash space). Use **^/bin/echo hello\\\\ world$** to match **/bin/echo "hello world"**, note that **\\** is a regex escape character so it must be escaped, therefore matching a space becomes **'\\\\\ '** (backslash backslash space). To match a **\\** (backslash), the hex code **\\x5c** can be used. To match the string **%{USER}**, the sequence **\\x25\\{USER\\}** can be used. Rules starting **exact** are string matches and not **regex** processed and take precedence over **regex** matches. **exact_name=[string]** : only permit a user/group name that matches exactly **exact_hostname=[string]** : only permit a hostname that matches exactly **exact_target=[string]** : only permit a target that matches exactly **exact_rule=[string]** : only permit a command rule that matches exactly **exact_dir=[string]** : only permit a dir that matches exactly # ACTIONS **permit=[true|false]** : permit or disallow the entry, defaults to true **require_pass=[true|false]** : if entry matches, require a password, defaults to true **reason=[true|false]** : require a reason for execution/edit, defaults to false **last=[true|false]** : if true, stop processing when entry is matched, defaults to false **syslog=[true|false]** : log this activity to syslog, defaults to true **env_assign.[key]=[value]** : assign **value** to environment **key** **editmode=[octal mode|keep]** : (**type=edit**) set the file mode bits on replacement file to octal mode. When set to **keep** use the existing file mode. If the file is not present, or mode is not declared, then mode falls back to 0600. If there is a file present, then the mode is read and used just prior to file rename. **exitcmd=[program]** : (**type=edit**) run program after editor exits as the target user, if exit is zero, continue with file replacement. **%{NEW}** and **%{OLD}** placeholders expand to new and old edit files # EXAMPLES To allow all commands, you can use a greedy match (**^.\*$**). You should reduce this to the set of acceptable commands though. ``` [user_jim_root] name=jim target=root rule=^.*$ ``` If you wish to permit a user to view another's command set, then you may do this using **type=list** (**run** by default). To list another user, they must match the **target** regex. ``` [user_jim_list_root] name=jim type=list target=root ``` **type** may also be **edit** if you wish to permit a file edit with **pleaseedit**. ``` [user_jim_edit_hosts] name=jim type=edit target=root rule=^/etc/hosts$ editmode=644 ``` Naming sections should help later when listing permissions. Below, user **mandy** may run **du** without needing a password, but must enter her password for a **bash** running as root: ``` [mandy_du] name = mandy rule = ^(/usr)?/bin/du .*$ require_pass = false [mandy_some] name = mandy rule = ^(/usr)?/bin/bash$ require_pass = true ``` The rule **regex** can include repetitions. To permit running **wc** to count the lines in the log files (we don't know how many there are) in **/var/log**. This sort of regex will allow multiple instances of a **()** group with **+**, which is used to define the character class **[a-zA-Z0-9-]+**, the numeric class **\d+** and the group near the end of the line. In other words, multiple instances of files in **/var/log** that may end in common log rotate forms **-YYYYMMDD** or **.N**. This will permit commands such as the following, note how for efficiency find will combine arguments with **\+** into fewer invocations. **xargs** could have been used in place of **find**. ``` $ find /var/log -type f -exec please /usr/bin/wc {} \+ ``` Here is a sample for the above scenario: ``` [user_jim_root_wc] name=jim target=root permit=true rule=^/usr/bin/wc (/var/log/[a-zA-Z0-9-]+(\.\d+)?(\s)?)+$ ``` User jim may only start or stop a docker container: ``` [user_jim_root_docker] name=jim target=root permit=true rule=^/usr/bin/docker (start|stop) \S+ ``` User ben may only edit **/etc/fstab**, and afterwards check the fstab file: ``` [ben_fstab] name=ben target=root permit=true type=edit editmode=644 rule=^/etc/fstab$ exitcmd=/bin/findmnt --verify --tab-file %{NEW} ``` User ben may list only users **eng**, **net** and **dba**: ``` [ben_ops] name=ben permit=true type=list target=^(eng|net|dba)ops$ ``` All users may list their own permissions. You may or may not wish to do this if you consider permitting a view of the rules to be a security risk. ``` [list_own] name=^%{USER}$ permit=true type=list target=^%{USER}$ ``` # EXITCMD When the user completes their edit, and the editor exits cleanly, if **exitcmd** is included then this program will run as the target user. If the program also exits cleanly then the temporary edit will be copied to the destination. **%{OLD}** and **%{NEW}** will expand to the old (existing source) file and edit candidate, respectively. To verify a file edit, **ben**'s entry to check **/etc/hosts** after clean exit could look like this: ``` [ben_ops] name=ben permit=true type=edit editmode=644 rule=^/etc/hosts$ exitcmd=/usr/local/bin/check_hosts %{OLD} %{NEW} ``` **/usr/local/bin/check_hosts** takes two arguments, the original file as the first argument and the modify candidate as the second argument. If **check_hosts** terminates zero, then the edit is considered clean and the original file is replaced with the candidate. Otherwise the edit file is not copied and is left, **pleaseedit** will exit with the return value from **check_hosts**. A common **exitcmd** is to check the validity of **please.ini**, shown below. This permits members of the **admin** group to edit **/etc/please.ini** if they provide a reason (**-r**). Upon clean exit from the editor the tmp file will be syntax checked. ``` [please_ini] name = admins group = true reason = true rule = /etc/please.ini type = edit editmode = 600 exitcmd = /usr/bin/please -c %{NEW} ``` # DATED RANGES For large environments it is not unusual for a third party to require access during a short time frame for debugging. To accommodate this there are the **notbefore** and **notafter** time brackets. These can be either **YYYYmmdd** or **YYYYmmddHHMMSS**. The whole day is considered when using the shorter date form of **YYYYmmdd**. Many enterprises may wish to permit periods of access to a user for a limited time only, even if that individual is considered to have a permanent role. User joker can do what they want as root on 1st April 2021: ``` [joker_april_first] name=joker target=root permit=true notbefore=20210401 notafter=20210401 rule=^/bin/bash ``` # DATEMATCHES **datematch** matches against the date string **Day dd mon HH:MM:SS UTC Year**. This enables calendar style date matches. Note that the day of the month (**dd**) will be padded with spaces if less than two characters wide. You can permit a group of users to run **/usr/local/housekeeping/** scripts every Monday: ``` [l2_housekeeping] name=l2users group=true target=root permit=true rule = /usr/local/housekeeping/tidy_(logs|images|mail) datematch = ^Mon\s+.* ``` # REASONS When **reason=true**, a user must pass a reason with the **-r** option to **please** and **pleaseedit**. Some organisations may prefer a reason to be logged when a command is executed. This can be helpful for some situations where something such as **mkfs** or **useradd** might be preferable to be logged against a ticket. ``` [l2_user_admin] name=l2users group=true target=root permit=true reason=true rule = ^/usr/sbin/useradd -m \w+$ ``` Perhaps you want to add a mini mollyguard: ``` [user_poweroff] name = l2users group = true rule = (/usr)?/s?bin/(shutdown( -h now)?|poweroff|reboot) require_pass = true reason = true ``` # DIR In some situations you may only want a command to run within a set of directories. The directory is specified with the **-d** argument to **please**. For example, a program may output to the current working directory, which may only be desirable in certain locations. ``` [eng_build_aliases] name=l2users group=true dir=^/etc/mail$ rule = ^/usr/local/bin/build_aliases$ ``` # LAST **last=true** stops processing at a match: ``` [mkfs] name=l2users group=true target=root permit=true reason=true rule = ^/sbin/mkfs.(ext[234]|xfs) /dev/sd[bcdefg]\d?$ last=true ``` For simplicity, there is no need to process other configured rules if certain that the **l2users** group are safe to execute this. **last** should only be used in situations where there will never be something that could contradict the match in an undesired way later. # SYSLOG By default entries are logged to syslog. If you do not wish an entry to be logged then specify **syslog=false**. In this case **jim** can run anything in **/usr/bin/** as root and it will not be logged. ``` [maverick] syslog = false name = jim rule = /usr/bin/.* reason = false ``` # FILES /etc/please.ini # NOTES At a later date repeated properties within the same section may be treated as a match list. At a later date sections with names containing 'default' may behave differently to normal sections. # CONTRIBUTIONS I welcome pull requests with open arms. New features always considered. # BUGS Found a bug? Please either open a ticket or send a pull request/patch. # SEE ALSO **please**(1) pleaser-0.5.1/please.md010064400017500001750000000060631415313273200131320ustar 00000000000000--- title: please section: 1 header: User Manual footer: please 0.5.1 author: Ed Neville (ed-please@s5h.net) date: 04 December 2021 --- # NAME please - a tool for access elevation. # SYNOPSIS **please /bin/bash** **pleaseedit /etc/fstab** **pleaseedit [-r/\--reason \"new fs\"] /etc/fstab** **please [-a/\--allowenv list]** **please [-c/\--check] /etc/please.ini** **please [-d/\--dir directory] command** **please [-h/\--help]** **please [-t/\--target username] backup tar -cvf - /home/data | ...** **please [-u/\--user username] backup tar -cvf - /home/data | ...** **please [-l/\--list]** **please [-l/\--list] [-t/\--target username]** **please [-l/\--list] [-u/\--user username]** **please [-n/\--noprompt] command** **please [-r/\--reason \"sshd reconfigured, ticket 24365\"] /etc/init.d/ssh restart** **please [-p/\--purge]** **please [-w/\--warm]** # DESCRIPTION **please** and **pleaseedit** are sudo alternatives that have regex support and a simple approach to ACL. The aim is to allow admins to delegate accurate principle of least privilege access with ease. **please.ini** allows for very specific and flexible regex defined permissions. **pleaseedit** adds a layer of safety to editing files. The file is copied to /tmp, where it can be updated. When **EDITOR** exits cleanly the file is copied alongside the target, the file will then be renamed over the original, but if a **exitcmd** is configured it must exit cleanly first. **-a**/**\--allowenv list** : allow environments separated by **,** to be passed through **-c**/**\--check file** : will check the syntax of a **please.ini** config file. Exits non-zero on error **-d**/**\--dir** : will change directory to **dir** prior to executing the command **-h**/**\--help** : print help and exit **-l**/**\--list** : to list rules **-n**/**\--noprompt** : will not prompt for authentication and exits with a status of 1 **-p**/**\--purge** : will purge your current authentication token for the running user **-r**/**\--reason** **[reason]** : will add **reason** to the system log **-t**/**\--target** **[username]** : to execute command, or edit as target **username** **-u**/**\--user** **[username]** : to execute command, or edit as target **username** **-v**/**\--version** : print version and exit **-w**/**\--warm** : will warm an authentication token and exit # EXAMPLE USAGE **please -t httpd /bin/bash** : run a shell as the httpd user **please -l** : to list what you may run **please -t \"username\" -l** : to show what username may run. **username** must match the target regex in a **type=list** rule **please -r \'reloading apache2, change #123\' systemctl reload apache2** : to reload apache2 with a reason **pleaseedit -r \'adding new storage, ticket #24365\' /etc/fstab** : to use pleaseedit to modify **fstab** Please see **please.ini** for configuration examples. # FILES /etc/please.ini # CONTRIBUTIONS I welcome pull requests with open arms. New features always considered. # BUGS Found a bug? Please either open a ticket or send a pull request/patch. # SEE ALSO **please.ini**(5) pleaser-0.5.1/src/bin/please.rs010064400017500001750000000216651415312630000145140ustar 00000000000000// please // Copyright (C) 2020-2021 ed neville // // 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 3 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, see . //! please.rs a sudo-like clone that implements regex all over the place use pleaser::*; use std::os::unix::process::CommandExt; use std::process::Command; use getopts::Options; use users::*; /// walk through user ACL fn do_list(ro: &mut RunOptions, vec_eo: &[EnvOptions], service: &str) { let name = if ro.target == ro.name || ro.target.is_empty() { "You" } else { &ro.target }; let can_do = can(&vec_eo, &ro); ro.syslog = can_do.syslog; if !can_do.permit { let dest = format!("{}'s", &ro.target); log_action(&service, "deny", &ro, &ro.command); println!( "You may not view {} command list", if ro.target.is_empty() || ro.target == ro.name { "your" } else { &dest } ); std::process::exit(1); } // check if a reason was given if can_do.reason && ro.reason.is_none() { log_action(&service, "no_reason", &ro, &ro.original_command.join(" ")); println!( "Sorry but no reason was given to list on {} as {}", &ro.hostname, &ro.target ); std::process::exit(1); } // check if a password is required if !challenge_password(&ro, &can_do, &service) { log_action(&service, "deny", &ro, &ro.original_command.join(" ")); std::process::exit(1); } log_action(&service, "permit", &ro, &ro.command); println!("{} may run the following:", name); ro.acl_type = Acltype::Run; list(&vec_eo, &ro); println!("{} may edit the following:", name); ro.acl_type = Acltype::Edit; list(&vec_eo, &ro); println!("{} may list the following:", name); ro.acl_type = Acltype::List; list(&vec_eo, &ro); } /// navigate to directory or exit 1 fn do_dir_changes(ro: &RunOptions, service: &str) { if ro.directory.is_some() { if let Err(x) = std::env::set_current_dir(&ro.directory.as_ref().unwrap()) { println!( "[{}] cannot cd into {}: {}", &service, &ro.directory.as_ref().unwrap(), x ); std::process::exit(1); } } } /// setup getopts for argument parsing and help output fn general_options( mut ro: &mut RunOptions, args: Vec, service: &str, mut vec_eo: &mut Vec, ) { let mut opts = Options::new(); opts.parsing_style(getopts::ParsingStyle::StopAtFirstFree); opts.optopt( "a", "allowenv", "allow permitted comma separated envs", "LIST", ); opts.optopt("c", "check", "check config file", "FILE"); opts.optopt("d", "dir", "change to directory prior to execution", "DIR"); opts.optflag("h", "help", "print usage help"); opts.optflag("l", "list", "list effective rules, can combine with -t/-u"); opts.optflag("n", "noprompt", "do nothing if a password is required"); opts.optflag("p", "purge", "purge access token"); opts.optopt("r", "reason", "provide reason for execution", "REASON"); opts.optopt("t", "target", "become target user", "USER"); opts.optopt("u", "user", "become target user", "USER"); opts.optflag("v", "version", "print version and exit"); opts.optflag("w", "warm", "warm access token and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { println!("{}", f.to_string()); std::process::exit(1); } }; if matches.opt_present("c") { let mut bytes = 0; std::process::exit(read_ini_config_file( &matches.opt_str("c").unwrap(), &mut vec_eo, &ro.name, true, &mut bytes, ) as i32); } if matches.opt_present("a") { let mut vec = vec![]; for s in matches.opt_str("a").unwrap().split(',') { vec.push(s.to_string()); } ro.allow_env_list = Some(vec); } if matches.opt_present("d") { ro.directory = Some(matches.opt_str("d").unwrap()); } if matches.opt_present("l") { ro.acl_type = Acltype::List; } let header = format!("{} [arguments] ", &service); common_opt_arguments(&matches, &opts, &mut ro, &service, &header); if ro.new_args.is_empty() && !ro.warm_token && !ro.purge_token && ro.acl_type != Acltype::List { println!("No command given"); print_usage(&opts, &header); print_version(&service); std::process::exit(0); } } /// main entry point fn main() { let args: Vec = std::env::args().collect(); let original_command = args.clone(); let service = String::from("please"); let mut ro = RunOptions::new(); let original_uid = get_current_uid(); let original_user = get_user_by_uid(original_uid).unwrap(); ro.name = original_user.name().to_string_lossy().to_string(); ro.syslog = true; let mut vec_eo: Vec = vec![]; let root_uid = nix::unistd::Uid::from_raw(0); let root_gid = nix::unistd::Gid::from_raw(0); if !set_privs("root", root_uid, root_gid) { std::process::exit(1); } if !drop_privs(&ro) { std::process::exit(1); } general_options(&mut ro, args, &service, &mut vec_eo); clean_environment(&mut ro); ro.groups = group_hash(original_user.groups().unwrap()); if !esc_privs() { std::process::exit(1); } let mut bytes = 0; if read_ini_config_file("/etc/please.ini", &mut vec_eo, &ro.name, true, &mut bytes) { println!("Exiting due to error, cannot fully process /etc/please.ini"); std::process::exit(1); } if !drop_privs(&ro) { std::process::exit(1); } if ro.acl_type == Acltype::List { if ro.target.is_empty() { ro.target = ro.name.to_string(); } do_list(&mut ro, &vec_eo, &service); return; } if ro.target.is_empty() { ro.target = "root".to_string(); } ro.command = replace_new_args(ro.new_args.clone()); match search_path(&ro.new_args[0]) { None => { println!("[{}]: command not found", service); std::process::exit(1); } Some(x) => { ro.new_args[0] = x; ro.command = replace_new_args(ro.new_args.clone()); } } let entry = can(&vec_eo, &ro); ro.syslog = entry.syslog; if !entry.permit { log_action(&service, "deny", &ro, &original_command.join(" ")); print_may_not(&ro); std::process::exit(1); } // check if a reason was given if entry.permit && entry.reason && ro.reason.is_none() { log_action(&service, "no_reason", &ro, &original_command.join(" ")); println!( "Sorry but no reason was given to execute \"{}\" on {} as {}", &ro.command, &ro.hostname, &ro.target ); std::process::exit(1); } if !challenge_password(&ro, &entry, &service) { log_action(&service, "deny", &ro, &original_command.join(" ")); std::process::exit(1); } if !drop_privs(&ro) { std::process::exit(1); } let lookup_name = get_user_by_name(&ro.target); if lookup_name.is_none() { println!("Could not lookup {}", &ro.target); std::process::exit(1); } let lookup_name = lookup_name.unwrap(); let target_uid = nix::unistd::Uid::from_raw(lookup_name.uid()); let target_gid = nix::unistd::Gid::from_raw(lookup_name.primary_group_id()); if !esc_privs() { std::process::exit(1); } if !set_eprivs(target_uid, target_gid) { std::process::exit(1); } do_dir_changes(&ro, &service); if !drop_privs(&ro) { std::process::exit(1); } log_action(&service, "permit", &ro, &original_command.join(" ")); set_environment(&ro, &entry, &original_user, original_uid, &lookup_name); if !esc_privs() { std::process::exit(1); } if !set_privs(&ro.target, target_uid, target_gid) { std::process::exit(1); } nix::sys::stat::umask(ro.old_umask.unwrap()); if ro.new_args.len() > 1 { Command::new(&ro.new_args[0]) .args(ro.new_args.clone().split_off(1)) .exec(); } else { Command::new(&ro.new_args[0]).exec(); } } pleaser-0.5.1/src/bin/pleaseedit.rs010064400017500001750000000406041415312630000153540ustar 00000000000000// pleaseedit // Copyright (C) 2020-2021 ed neville // // 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 3 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, see . //! please.rs a sudo-like clone that implements regex all over the place use pleaser::*; use std::convert::TryFrom; use std::fs::OpenOptions; use std::os::unix::fs::OpenOptionsExt; use std::io::{self, Write}; use std::os::unix::io::AsRawFd; use std::os::unix::process::CommandExt; use std::path::Path; use std::process::{Command, Stdio}; use regex::Regex; use getopts::Options; use nix::sys::signal; use nix::sys::signal::Signal; use nix::sys::stat::fchmod; use nix::sys::wait::WaitStatus::Exited; use nix::unistd::{fchown, fork, ForkResult}; use users::*; /// return a path string to work on in /tmp fn tmp_edit_file_name(source_file: &Path, service: &str, original_user: &str) -> String { format!( "/tmp/{}.{}.{}.{}", service, original_user, prng_alpha_num_string(8), source_file.to_str().unwrap().replace('/', "_"), ) } /// return a path string that exitcmd can use adjacent in the source location fn source_tmp_file_name(source_file: &Path, service: &str, original_user: &str) -> String { format!( "{}.{}.{}.{}", source_file.to_str().unwrap(), prng_alpha_num_string(8), service, original_user, ) } /// copy the contents of source file into the tmp file with original user ownership fn setup_temp_edit_file( service: &str, source_file: &Path, ro: &RunOptions, target_uid: nix::unistd::Uid, target_gid: nix::unistd::Gid, ) -> String { if !drop_privs(&ro) { std::process::exit(1); } let tmp_edit_file = tmp_edit_file_name(&source_file, &service, &ro.name); let tmp_edit_file_path = Path::new(&tmp_edit_file); if tmp_edit_file_path.exists() && std::fs::remove_file(tmp_edit_file_path).is_err() { println!("Could not remove {}", tmp_edit_file_path.to_str().unwrap()); std::process::exit(1); } if !esc_privs() { std::process::exit(1); } if !set_eprivs(target_uid, target_gid) { std::process::exit(1); } let mut file_data: Result = Ok("".to_string()); if source_file.exists() { file_data = std::fs::read_to_string(source_file); if file_data.is_err() { println!( "Could not read source file {}", source_file.to_str().unwrap(), ); std::process::exit(1); } } if !drop_privs(&ro) { std::process::exit(1); } let mut options = OpenOptions::new(); options.write(true).create_new(true); options.custom_flags(libc::O_NOFOLLOW); let file = options.open(tmp_edit_file_path); if file.is_err() { println!("Could not create {}", tmp_edit_file_path.to_str().unwrap()); std::process::exit(1); } if fchown( file.as_ref().unwrap().as_raw_fd(), Some(ro.original_uid), Some(ro.original_gid), ) .is_err() { println!("Could not chown {}", tmp_edit_file_path.to_str().unwrap()); } if fchmod( file.as_ref().unwrap().as_raw_fd(), nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR, ) .is_err() { println!("Could not chmod {}", tmp_edit_file_path.to_str().unwrap()); std::process::exit(1); } if file_data.is_ok() && file .unwrap() .write(file_data.as_ref().unwrap().as_bytes()) .is_err() { println!("Could not write data to {}", &tmp_edit_file); std::process::exit(1); } tmp_edit_file } /// return the exitcmd string with %{OLD} and %{NEW} replaced fn build_exitcmd(entry: &EnvOptions, source_file: &str, edit_file: &str) -> Command { let cmd_re = Regex::new(r"\s+").unwrap(); let cmd_str = &entry.exitcmd.as_ref().unwrap(); let cmd_parts: Vec<&str> = cmd_re.split(&cmd_str).collect(); if cmd_parts.is_empty() { println!("exitcmd has too few arguments"); std::process::exit(1); } let mut cmd = Command::new(cmd_parts[0]); for (pos, j) in cmd_parts.iter().enumerate() { if pos > 0 { cmd.arg( j.replace("%{OLD}", &source_file) .replace("%{NEW}", edit_file), ); } } cmd.stdin(Stdio::inherit()); cmd.stdout(Stdio::inherit()); cmd.stderr(Stdio::inherit()); cmd } /// create options for parsing and --help fn general_options(mut ro: &mut RunOptions, args: Vec, service: &str) { let mut opts = Options::new(); opts.parsing_style(getopts::ParsingStyle::StopAtFirstFree); opts.optflag("h", "help", "print usage help"); opts.optflag("n", "noprompt", "do nothing if a password is required"); opts.optflag("p", "purge", "purge access token"); opts.optopt("r", "reason", "provide reason for edit", "REASON"); opts.optopt("t", "target", "edit as target user", "USER"); opts.optopt("u", "user", "edit as target user", "USER"); opts.optflag("v", "version", "print version and exit"); opts.optflag("w", "warm", "warm access token and exit"); let matches = match opts.parse(&args[1..]) { Ok(m) => m, Err(f) => { println!("{}", f.to_string()); std::process::exit(1); } }; let header = format!("{} [arguments] ", &service); common_opt_arguments(&matches, &opts, &mut ro, &service, &header); if (ro.new_args.is_empty() || ro.new_args.len() > 1) && !ro.warm_token && !ro.purge_token { println!("You must provide one file to edit"); print_usage(&opts, &header); print_version(&service); std::process::exit(1); } } fn write_target_tmp_file( dir_parent_tmp: &str, file_data: &Result, target_uid: nix::unistd::Uid, target_gid: nix::unistd::Gid, ) -> std::fs::File { if !esc_privs() { std::process::exit(1); } if !set_eprivs(target_uid, target_gid) { std::process::exit(1); } let mut options = OpenOptions::new(); options.write(true).create_new(true); options.custom_flags(libc::O_NOFOLLOW); let file = options.open(dir_parent_tmp); if file.is_err() || file .as_ref() .unwrap() .write(&file_data.as_ref().unwrap().as_bytes()) .is_err() { println!("Could not write data to {}", &dir_parent_tmp); std::process::exit(1); } file.unwrap() } fn remove_tmp_edit(ro: &RunOptions, edit_file: &str) { if !drop_privs(&ro) { std::process::exit(1); } if std::fs::remove_file(edit_file).is_err() { println!("Could not remove {}", edit_file); std::process::exit(1); } } /// rename the edit in the source directory, return false if exitcmd failed fn rename_to_source( dir_parent_tmp: &str, source_file: &Path, entry: &EnvOptions, lookup_name: &User, dir_parent_tmp_file: &std::fs::File, target_uid: nix::unistd::Uid, target_gid: nix::unistd::Gid, ) -> bool { if !esc_privs() { std::process::exit(1); } if !set_eprivs(target_uid, target_gid) { std::process::exit(1); } fchown( dir_parent_tmp_file.as_raw_fd(), Some(nix::unistd::Uid::from_raw(lookup_name.uid())), Some(nix::unistd::Gid::from_raw(lookup_name.primary_group_id())), ) .unwrap(); let edit_mode = if entry.edit_mode.is_some() { match entry.edit_mode.as_ref().unwrap() { EditMode::Mode(x) => nix::sys::stat::Mode::from_bits(*x as u32).unwrap(), EditMode::Keep(_x) => match nix::sys::stat::stat(source_file) { Ok(m) => nix::sys::stat::Mode::from_bits_truncate(m.st_mode), _ => nix::sys::stat::Mode::from_bits(0o600).unwrap(), }, } } else { nix::sys::stat::Mode::from_bits(0o600).unwrap() }; fchmod(dir_parent_tmp_file.as_raw_fd(), edit_mode).unwrap(); if entry.exitcmd.is_some() { let mut cmd = build_exitcmd(&entry, &source_file.to_str().unwrap(), &dir_parent_tmp); match cmd.output() { Err(x) => { println!("Aborting as exitcmd was non-zero when executing, removing tmp file:"); println!("{}", x); if nix::unistd::unlink(dir_parent_tmp).is_err() { println!("Could not remove tmp file either, giving up"); } std::process::exit(1); } Ok(out) => { io::stdout().write_all(&out.stdout).unwrap(); io::stderr().write_all(&out.stderr).unwrap(); if !out.status.success() { println!("Aborting as exitcmd was non-zero, removing tmp file"); if nix::unistd::unlink(dir_parent_tmp).is_err() { println!("Could not remove tmp file either, giving up"); } std::process::exit(1); } } } } if std::fs::rename(&dir_parent_tmp, source_file).is_err() { println!( "Could not rename {} to {}", &dir_parent_tmp, source_file.to_str().unwrap() ); std::process::exit(1); } true } /// read edit file into memory or exit 1 fn edit_file_to_memory(source_file: &Path, edit_file: &str) -> Result { let file_data = std::fs::read_to_string(edit_file); if file_data.is_err() { println!( "Could not read {}: {}", source_file.to_str().unwrap(), file_data.err().unwrap() ); std::process::exit(1); } file_data } extern "C" fn handle_sigtstp( child: libc::c_int, info: *mut libc::siginfo_t, _th: *mut libc::c_void, ) { let signal = Signal::try_from(child).unwrap(); unsafe { // don't have a handy definition for "5" SI_MESGQ if signal == Signal::SIGCHLD && (*info).si_code == 5 { signal::kill( nix::unistd::Pid::from_raw(std::process::id() as i32), Signal::SIGTSTP, ) .unwrap(); } } } /// entry point fn main() { let args: Vec = std::env::args().collect(); let original_command = args.clone(); let service = String::from("pleaseedit"); let mut ro = RunOptions::new(); let original_uid = get_current_uid(); let original_user = get_user_by_uid(original_uid).unwrap(); ro.name = original_user.name().to_string_lossy().to_string(); ro.acl_type = Acltype::Edit; ro.syslog = true; let mut vec_eo: Vec = vec![]; let root_uid = nix::unistd::Uid::from_raw(0); let root_gid = nix::unistd::Gid::from_raw(0); clean_environment(&mut ro); if !set_privs("root", root_uid, root_gid) { std::process::exit(1); } if !drop_privs(&ro) { std::process::exit(1); } general_options(&mut ro, args, &service); if ro.target.is_empty() { ro.target = "root".to_string(); } ro.command = ro.new_args.join(" "); ro.groups = group_hash(original_user.groups().unwrap()); if !esc_privs() { std::process::exit(1); } let mut bytes = 0; if read_ini_config_file("/etc/please.ini", &mut vec_eo, &ro.name, true, &mut bytes) { println!("Exiting due to error, cannot fully process /etc/please.ini"); std::process::exit(1); } if !drop_privs(&ro) { std::process::exit(1); } let entry = can(&vec_eo, &ro); ro.syslog = entry.syslog; if !entry.permit { log_action(&service, "deny", &ro, &original_command.join(" ")); println!( "You may not edit \"{}\" on {} as {}", &ro.command, &ro.hostname, &ro.target ); std::process::exit(1); } // check if a reason was given if entry.permit && entry.reason && ro.reason.is_none() { log_action(&service, "no_reason", &ro, &original_command.join(" ")); println!( "Sorry but no reason was given to edit \"{}\" on {} as {}", &ro.command, &ro.hostname, &ro.target ); std::process::exit(1); } if !challenge_password(&ro, &entry, &service) { log_action(&service, "deny", &ro, &original_command.join(" ")); std::process::exit(1); } let lookup_name = get_user_by_name(&ro.target); if lookup_name.is_none() { println!("Could not lookup {}", &ro.target); std::process::exit(1); } let lookup_name = lookup_name.unwrap(); let target_uid = nix::unistd::Uid::from_raw(lookup_name.uid()); let target_gid = nix::unistd::Gid::from_raw(lookup_name.primary_group_id()); let source_file = Path::new(&ro.new_args[0]); if !drop_privs(&ro) { std::process::exit(1); } set_environment(&ro, &entry, &original_user, original_uid, &lookup_name); let edit_file = &setup_temp_edit_file(&service, source_file, &ro, target_uid, target_gid); std::env::set_var("PLEASE_EDIT_FILE", edit_file.to_string()); std::env::set_var("PLEASE_SOURCE_FILE", source_file.to_str().unwrap()); let mut good_edit = false; let sig_action = signal::SigAction::new( signal::SigHandler::SigAction(handle_sigtstp), signal::SaFlags::SA_RESTART, signal::SigSet::all(), ); match unsafe { fork() } { Ok(ForkResult::Parent { .. }) => { unsafe { signal::sigaction(signal::SIGCHLD, &sig_action).unwrap(); }; match nix::sys::wait::wait() { Ok(Exited(_pid, ret)) if ret == 0 => { good_edit = true; } Ok(_) => {} Err(_x) => {} } unsafe { signal::signal(signal::SIGCHLD, signal::SigHandler::SigDfl).unwrap(); }; } Ok(ForkResult::Child) => { if !esc_privs() { std::process::exit(1); } if !set_privs(&ro.name, ro.original_uid, ro.original_gid) { std::process::exit(1); } let editor = get_editor(); nix::sys::stat::umask(ro.old_umask.unwrap()); if ro.old_envs.is_some() { for (key, _) in std::env::vars() { std::env::remove_var(key); } for (key, val) in ro.old_envs.as_ref().unwrap().iter() { std::env::set_var(key, val); } } let args: Vec<&str> = editor.as_str().split(' ').collect(); if args.len() == 1 { Command::new(editor.as_str()).arg(&edit_file).exec(); } else { Command::new(&args[0]) .args(&args[1..]) .arg(&edit_file) .exec(); } println!("Could not execute {}", editor.as_str()); std::process::exit(1); } Err(_) => println!("Fork failed"), } if !good_edit { println!("Exiting as editor or child did not close cleanly."); std::process::exit(1); } // drop privs to original user and read into memory log_action(&service, "permit", &ro, &original_command.join(" ")); let dir_parent_tmp = source_tmp_file_name(&source_file, format!("{}.copy", service).as_str(), &ro.name); let file_data = edit_file_to_memory(&source_file, &edit_file); // become the target user and create file let dir_parent_tmp_file = write_target_tmp_file(&dir_parent_tmp, &file_data, target_uid, target_gid); // original user, remove tmp edit file remove_tmp_edit(&ro, edit_file); // rename file to source if exitcmd is clean rename_to_source( &dir_parent_tmp, &source_file, &entry, &lookup_name, &dir_parent_tmp_file, target_uid, target_gid, ); } pleaser-0.5.1/src/lib.rs010064400017500001750000001455121415312630000132370ustar 00000000000000// please // Copyright (C) 2020-2021 ed neville // // 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 3 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, see . use regex::Regex; use std::collections::HashMap; use std::env; use std::ffi::{CStr, CString}; use std::path::Path; use std::process; use syslog::{Facility, Formatter3164}; use chrono::{NaiveDate, NaiveDateTime, Utc}; use std::fmt; use std::fs; use std::fs::File; use std::io::prelude::*; use std::io::BufReader; use std::os::unix::io::AsRawFd; use std::time::SystemTime; use users::os::unix::UserExt; use users::*; use getopts::{Matches, Options}; use nix::unistd::{gethostname, initgroups, setegid, seteuid, setgid, setuid}; use pam::Authenticator; use rand::distributions::Alphanumeric; use rand::{thread_rng, Rng}; #[derive(PartialEq, Eq, Clone, Debug)] pub enum EditMode { Mode(i32), Keep(bool), } #[derive(Clone)] pub struct EnvOptions { pub name: Option, pub exact_name: Option, pub rule: Option, pub exact_rule: Option, pub notbefore: Option, pub notafter: Option, pub datematch: Option, pub target: Option, pub exact_target: Option, pub hostname: Option, pub exact_hostname: Option, pub permit: bool, pub require_pass: bool, pub acl_type: Acltype, pub file_name: String, pub section: String, pub group: bool, pub configured: bool, pub dir: Option, pub exact_dir: Option, pub exitcmd: Option, pub edit_mode: Option, pub reason: bool, pub last: bool, pub syslog: bool, pub env_permit: Option, pub env_assign: Option>, } impl EnvOptions { pub fn new() -> EnvOptions { EnvOptions { name: None, exact_name: None, rule: Some("^$".to_string()), exact_rule: None, target: Some("root".to_string()), exact_target: None, notbefore: None, notafter: None, datematch: None, hostname: None, exact_hostname: None, file_name: "".to_string(), section: "".to_string(), permit: true, require_pass: true, acl_type: Acltype::Run, group: false, configured: false, dir: None, exact_dir: None, exitcmd: None, edit_mode: Some(EditMode::Keep(true)), reason: false, last: false, syslog: true, env_permit: None, env_assign: None, } } fn new_deny() -> EnvOptions { let mut opt = EnvOptions::new(); opt.permit = false; opt.rule = Some(".".to_string()); opt.target = Some("^$".to_string()); opt.acl_type = Acltype::List; opt } } impl Default for EnvOptions { fn default() -> Self { Self::new() } } #[derive(Clone)] pub struct RunOptions { pub name: String, pub original_uid: nix::unistd::Uid, pub original_gid: nix::unistd::Gid, pub target: String, pub command: String, pub original_command: Vec, pub hostname: String, pub directory: Option, pub groups: HashMap, pub date: NaiveDateTime, pub acl_type: Acltype, pub reason: Option, pub syslog: bool, pub prompt: bool, pub purge_token: bool, pub warm_token: bool, pub new_args: Vec, pub old_umask: Option, pub old_envs: Option>, pub allow_env_list: Option>, } impl RunOptions { pub fn new() -> RunOptions { RunOptions { name: "root".to_string(), original_uid: nix::unistd::Uid::from_raw(get_current_uid()), original_gid: nix::unistd::Gid::from_raw(get_current_gid()), target: "".to_string(), command: "".to_string(), original_command: vec![], hostname: "localhost".to_string(), date: Utc::now().naive_utc(), groups: HashMap::new(), directory: None, acl_type: Acltype::Run, reason: None, syslog: true, prompt: true, purge_token: false, warm_token: false, new_args: vec![], old_umask: None, old_envs: None, allow_env_list: None, } } } impl Default for RunOptions { fn default() -> Self { Self::new() } } struct PamConvo { login: String, passwd: Option, service: String, } impl pam::Converse for PamConvo { fn prompt_echo(&mut self, _msg: &CStr) -> Result { CString::new(self.login.clone()).map_err(|_| ()) } fn prompt_blind(&mut self, _msg: &CStr) -> Result { self.passwd = Some( rpassword::read_password_from_tty(Some(&format!( "[{}] password for {}: ", self.service, self.login ))) .unwrap(), ); CString::new(self.passwd.clone().unwrap()).map_err(|_| ()) } fn info(&mut self, _msg: &CStr) {} fn error(&mut self, msg: &CStr) { println!("[{} pam error] {}", self.service, msg.to_string_lossy()); } fn username(&self) -> &str { &self.login } } #[derive(PartialEq, Eq, Clone, Debug)] pub enum Acltype { Run, List, Edit, } impl fmt::Display for Acltype { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Acltype::Run => write!(f, "run"), Acltype::List => write!(f, "list"), Acltype::Edit => write!(f, "edit"), } } } pub fn print_may_not(ro: &RunOptions) { println!( "You may not {} \"{}\" on {} as {}", if ro.acl_type == Acltype::Run { "execute".to_string() } else { ro.acl_type.to_string() }, &ro.command, &ro.hostname, &ro.target ); } /// build a regex and replace %{USER} with the user str, prefix with ^ and suffix with $ pub fn regex_build( v: &str, user: &str, config_path: &str, section: &str, line: Option, ) -> Option { let rule = Regex::new(&format!("^{}$", &v.replace("%{USER}", &user))); if rule.is_err() { println!( "Error parsing {}{}", config_path, if line.is_some() { format!(": {}:{}", section, line.unwrap()) } else { "".to_string() } ); return None; } Some(rule.unwrap()) } /// return true if the inclusion exists and ends with .ini pub fn can_dir_include(file: &str) -> bool { let p = Path::new(file); if !p.is_file() { return false; } can_include_file_pattern(file) } pub fn can_include_file_pattern(file: &str) -> bool { let dir_pattern = Regex::new(r".*\.ini$").unwrap(); if dir_pattern.is_match(file) { let p = Path::new(file); if p.file_name().is_none() { return false; } match p.file_name().unwrap().to_str() { None => { return false; } Some(f) => { if f.starts_with('.') { return false; } } } return true; } false } /// print the usage pub fn print_usage(opts: &Options, header: &str) { println!("usage:"); println!("{}", opts.usage(header)); } /// added around easter time pub fn credits(service: &str) { let mut contributors = [ "All of the Debian Rust Maintainers, and especially Sylvestre Ledru", "Andy Kluger, for your feedback", "Cyrus Wyett, jim was better than ed", "@unmellow, for your early testing", "noproto, for your detailed report", "pin, for work with pkgsrc", "Stanley Dziegiel, for ini suggestions", "My wife and child, for putting up with me", "The SUSE Security Team, especially Matthias Gerstner", ]; print_version(&service); contributors.sort_unstable(); println!("\nWith thanks to the following teams and people, you got us where we are today.\n"); println!("If your name is missing, or incorrect, please get in contact.\n"); println!("In sort order:\n"); for i in contributors.iter() { println!("\t{}", i); } println!("\nYou too of course, for motivating me."); println!("\nI thank you all for your help.\n\n\t-- Edward Neville"); } /// common opt arguments pub fn common_opt_arguments( matches: &Matches, opts: &Options, ro: &mut RunOptions, service: &str, header: &str, ) { ro.new_args = matches.free.clone(); if matches.opt_present("r") { ro.reason = Some(matches.opt_str("r").unwrap()); } if matches.opt_present("t") { ro.target = matches.opt_str("t").unwrap(); } if matches.opt_present("u") { ro.target = matches.opt_str("u").unwrap(); } if matches.opt_str("u").is_some() && matches.opt_str("t").is_some() && matches.opt_str("t").unwrap() != matches.opt_str("u").unwrap() { println!("Cannot use -t and -u with conflicting values"); print_usage(&opts, &header); std::process::exit(1); } if matches.opt_present("p") { ro.purge_token = true; } if matches.opt_present("v") { print_version(&service); std::process::exit(0); } if matches.opt_present("w") { ro.warm_token = true; } if matches.opt_present("n") { ro.prompt = false; } if matches.opt_present("h") { if ro.new_args == ["credits"] { credits(&service); std::process::exit(0); } print_usage(&opts, &header); print_version(&service); std::process::exit(0); } if ro.purge_token { if !esc_privs() { std::process::exit(1); } remove_token(&ro.name); if !drop_privs(&ro) { std::process::exit(1); } std::process::exit(0); } if ro.warm_token { if ro.prompt { challenge_password(&ro, &EnvOptions::new(), &service); } std::process::exit(0); } let mut buf = [0u8; 64]; ro.hostname = gethostname(&mut buf) .expect("Failed getting hostname") .to_str() .expect("Hostname wasn't valid UTF-8") .to_string(); } /// read an ini file and traverse includes pub fn read_ini( conf: &str, vec_eo: &mut Vec, user: &str, fail_error: bool, config_path: &str, bytes: &mut u64, ) -> bool { let parse_datetime_from_str = NaiveDateTime::parse_from_str; let parse_date_from_str = NaiveDate::parse_from_str; let mut faulty = false; let mut section = String::from("no section defined"); let mut in_section = false; let mut opt = EnvOptions::new(); for (mut line_number, l) in conf.split('\n').enumerate() { line_number += 1; let line = l.trim(); if line.is_empty() || line.starts_with('#') { continue; } if line.starts_with('[') && line.ends_with(']') { in_section = true; section = line[1..line.len() - 1].to_string(); if opt.configured { vec_eo.push(opt); } opt = EnvOptions::new(); opt.section = section.clone(); opt.file_name = String::from(config_path); continue; } let equals_pos = line.find('='); if equals_pos.is_none() { continue; } let key = line[0..equals_pos.unwrap()].trim(); let value = line[equals_pos.unwrap() + 1..].trim(); if !in_section { println!("Error parsing {}:{}", config_path, line_number); faulty = true; continue; } // env_assign is a special case as the key names are not known at compile time so do not fit in the match if key.starts_with("env_assign.") { let period_pos = key.find('.'); let env_name = key[period_pos.unwrap() + 1..].trim(); if !value.is_empty() { if opt.clone().env_assign.is_none() { opt.env_assign = Some(HashMap::new()); } opt.env_assign .as_mut() .unwrap() .entry(env_name.to_string()) .or_insert_with(|| value.to_string()); } continue; } match key { "include" => { if !value.starts_with('/') { println!("Includes should start with /"); return true; } if read_ini_config_file(&value, vec_eo, &user, fail_error, bytes) { println!("Could not include file"); return true; } continue; } "includedir" => { if !value.starts_with('/') { println!("Includes should start with /"); return true; } match fs::read_dir(value) { Err(_x) => { faulty = true; } Ok(inc) => { let mut collect = vec![]; for file in inc { collect.push(file.unwrap().path().to_str().unwrap().to_string()); } collect.sort(); for file in collect { let incf = file; if !can_dir_include(&incf) { continue; } if read_ini_config_file(&incf, vec_eo, &user, fail_error, bytes) { println!("Could not include file"); return true; } } } } continue; } "name" => { opt.name = Some(value.to_string()); opt.configured = true; if fail_error && regex_build(value, user, config_path, §ion, Some(line_number as i32)) .is_none() { faulty = true; } } "exact_name" => { opt.exact_name = Some(value.to_string()); opt.configured = true; } "hostname" => { opt.hostname = Some(value.to_string()); opt.configured = true; if fail_error && regex_build(value, user, config_path, §ion, Some(line_number as i32)) .is_none() { faulty = true; } } "exact_hostname" => { opt.exact_hostname = Some(value.to_string()); opt.configured = true; } "target" => { opt.target = Some(value.to_string()); if fail_error && regex_build(value, user, config_path, §ion, Some(line_number as i32)) .is_none() { faulty = true; } } "exact_target" => { opt.exact_target = Some(value.to_string()); } "permit" => opt.permit = value == "true", "require_pass" => opt.require_pass = value != "false", "type" => match value.to_lowercase().as_str() { "edit" => opt.acl_type = Acltype::Edit, "list" => opt.acl_type = Acltype::List, _ => opt.acl_type = Acltype::Run, }, "group" => opt.group = value == "true", "regex" | "rule" => { opt.rule = Some(value.to_string()); if fail_error && regex_build(value, user, config_path, §ion, Some(line_number as i32)) .is_none() { faulty = true; } } "exact_regex" | "exact_rule" => { opt.exact_rule = Some(value.to_string()); opt.configured = true; } "notbefore" if value.len() == 8 => { opt.notbefore = Some( parse_date_from_str(&value.to_string(), "%Y%m%d") .unwrap() .and_hms(0, 0, 0), ) } "notafter" if value.len() == 8 => { opt.notafter = Some( parse_date_from_str(&value.to_string(), "%Y%m%d") .unwrap() .and_hms(23, 59, 59), ) } "notbefore" if value.len() == 14 => { opt.notbefore = Some(parse_datetime_from_str(&value.to_string(), "%Y%m%d%H%M%S").unwrap()) } "notafter" if value.len() == 14 => { opt.notafter = Some(parse_datetime_from_str(&value.to_string(), "%Y%m%d%H%M%S").unwrap()) } "datematch" => { opt.datematch = Some(value.to_string()); if fail_error && regex_build(value, user, config_path, §ion, Some(line_number as i32)) .is_none() { faulty = true; } } "dir" => { opt.dir = Some(value.to_string()); if fail_error && regex_build(value, user, config_path, §ion, Some(line_number as i32)) .is_none() { faulty = true; } } "exact_dir" => { opt.exact_dir = Some(value.to_string()); if fail_error && regex_build(value, user, config_path, §ion, Some(line_number as i32)) .is_none() { faulty = true; } } "permit_env" => { if !value.is_empty() { opt.env_permit = Some(value.to_string()); } } "exitcmd" => { if !value.is_empty() { opt.exitcmd = Some(value.to_string()); } } "editmode" => { if !value.is_empty() { if value.parse::().is_ok() { opt.edit_mode = Some(EditMode::Mode( i32::from_str_radix(value.trim_start_matches('0'), 8) .expect("unable to parse editmode"), )); } else if value.to_lowercase() == "keep" { opt.edit_mode = Some(EditMode::Keep(true)); } else { println!("Could not convert {} to numerical file mode", value); faulty = true; } } } "reason" => opt.reason = value == "true", "last" => opt.last = value == "true", "syslog" => opt.syslog = value == "true", &_ => { println!("Error parsing {}:{}", config_path, line_number); faulty = true; } } } if opt.configured { vec_eo.push(opt); } fail_error && faulty } /// read through an ini config file, appending EnvOptions to vec_eo /// hardcoded limit of 10M for confs pub fn read_ini_config_file( config_path: &str, vec_eo: &mut Vec, user: &str, fail_error: bool, bytes: &mut u64, ) -> bool { let path = Path::new(config_path); let display = path.display(); let file = match File::open(&path) { Err(why) => { println!("Could not open {}: {}", display, why); return true; } Ok(file) => file, }; match nix::sys::stat::fstat(file.as_raw_fd()) { Err(why) => { println!("Could not stat {}: {}", display, why); return true; } Ok(stat_data) => { if stat_data.st_mode & libc::S_IFREG != libc::S_IFREG { println!("Refusing to open non-regular file"); return true; } if (stat_data.st_mode & !libc::S_IFMT) & (0o022) != 0 { println!("Refusing to parse file as group or other write permission bits are set"); return true; } } } let byte_limit = 1024 * 1024 * 10; if *bytes >= byte_limit { println!("Exiting as too much config has already been read."); std::process::exit(1); } let mut s = String::new(); let reader = BufReader::new(file).take(byte_limit).read_to_string(&mut s); match reader { Ok(n) => { *bytes += s.as_bytes().len() as u64; if n >= byte_limit as usize { println!("Exiting as too much config has already been read."); std::process::exit(1); } } Err(why) => { println!("Could not read {}: {}", display, why); return true; } } read_ini(&s, vec_eo, &user, fail_error, config_path, bytes) } pub fn read_ini_config_str( config: &str, vec_eo: &mut Vec, user: &str, fail_error: bool, bytes: &mut u64, ) -> bool { read_ini(&config, vec_eo, &user, fail_error, "static", bytes) } /// may we execute with this hostname pub fn hostname_ok(item: &EnvOptions, ro: &RunOptions, line: Option) -> bool { if item.exact_hostname.is_some() { let hostname = item.exact_hostname.as_ref().unwrap(); if hostname != &ro.hostname && hostname.ne(&"any".to_string()) && hostname.ne(&"localhost".to_string()) { // println!("{}: hostname mismatch: {}", item.section, hostname); return false; } return true; } if item.hostname.is_some() { let hostname_re = match regex_build( &item.hostname.as_ref().unwrap(), &ro.name, &item.file_name, &item.section, line, ) { Some(check) => check, None => { println!("Could not compile {}", &item.hostname.as_ref().unwrap()); return false; } }; if !hostname_re.is_match(&ro.hostname) && !hostname_re.is_match("any") && !hostname_re.is_match("localhost") { // println!("{}: hostname mismatch", item.section); return false; } } true } pub fn target_ok(item: &EnvOptions, ro: &RunOptions, line: Option) -> bool { if item.exact_target.is_some() { let exact_target = item.exact_target.as_ref().unwrap(); if exact_target == &ro.target { return true; } // println!("{}: target mismatch: {} != {}", item.section, exact_target, ro.target); return false; } if item.target.is_some() { let target_re = match regex_build( &item.target.as_ref().unwrap(), &ro.name, &item.file_name, &item.section, line, ) { Some(check) => check, None => { println!("Could not compile {}", &item.target.as_ref().unwrap()); return false; } }; if target_re.is_match(&ro.target) { return true; } return false; } false } pub fn rule_match(item: &EnvOptions, ro: &RunOptions, line: Option) -> bool { if item.exact_rule.is_some() { let exact_rule = item.exact_rule.as_ref().unwrap(); if exact_rule == &ro.command { return true; } // println!("{}: exact rule mismatch: {} != {}", item.section, exact_rule, ro.command); return false; } if item.rule.is_some() { let rule_re = match regex_build( &item.rule.as_ref().unwrap(), &ro.name, &item.file_name, &item.section, line, ) { Some(check) => check, None => { println!("Could not compile {}", &item.rule.as_ref().unwrap()); return false; } }; if rule_re.is_match(&ro.command) { // println!("{}: item rule is match", item.section); // opt = item.clone(); return true; } return false; } false } /// may we execute with this directory pub fn directory_check_ok(item: &EnvOptions, ro: &RunOptions, line: Option) -> bool { if item.exact_dir.is_some() { if ro.directory.as_ref().is_none() { return false; } let exact_dir = item.exact_dir.as_ref().unwrap(); if (&ro.directory.as_ref()).is_some() && exact_dir != ro.directory.as_ref().unwrap() { return false; } return true; } if item.dir.is_some() { if ro.directory.as_ref().is_none() { return false; } let dir_re = match regex_build( &item.dir.as_ref().unwrap(), &ro.name, &item.file_name, &item.section, line, ) { Some(check) => check, None => { println!("Could not compile {}", &item.dir.as_ref().unwrap()); return false; } }; if (&ro.directory.as_ref()).is_some() && !dir_re.is_match(&ro.directory.as_ref().unwrap()) { // && ro.directory != "." { return false; } return true; } if ro.directory.is_some() { return false; } true } /// may we keep environment data pub fn environment_ok(item: &EnvOptions, ro: &RunOptions, line: Option) -> bool { if ro.allow_env_list.is_none() { // println!("allow_env_list is none"); return true; } if item.env_permit.is_none() && ro.allow_env_list.is_some() { // println!("env_permit is none and allow_env_list is some"); return false; } let env_re = match regex_build( &item.env_permit.as_ref().unwrap(), &ro.name, &item.file_name, &item.section, line, ) { Some(check) => check, None => { println!("Could not compile {}", &item.env_permit.as_ref().unwrap()); return false; } }; for permit_env in ro.allow_env_list.as_ref().unwrap() { // println!("permit_env is {}", permit_env); if !env_re.is_match(&permit_env) { // println!( "{}: skipping as not a permitted env {} vs {}", item.section, item.env_permit.clone().unwrap(), permit_env ); return false; } } true } /// is the RunOption valid for the dates permitted in the EnvOption pub fn permitted_dates_ok(item: &EnvOptions, ro: &RunOptions, line: Option) -> bool { if item.notbefore.is_some() && item.notbefore.unwrap() > ro.date { // println!("{}: now is before date", item.section); return false; } if item.notafter.is_some() && item.notafter.unwrap() < ro.date { // println!("{}: now is after date", item.section); return false; } if item.datematch.is_some() { let datematch_re = match regex_build( &item.datematch.as_ref().unwrap(), &ro.name, &item.file_name, &item.section, line, ) { Some(check) => check, None => { println!("Could not compile {}", &item.datematch.as_ref().unwrap()); return false; } }; if !datematch_re.is_match(&ro.date.format("%a %e %b %T UTC %Y").to_string()) { // println!("{}: skipping as not a datematch {} vs {}", item.section, item.datematch.clone().unwrap(), &ro.date.format( "%a %e %b %T UTC %Y" ).to_string() ); return false; } } true } pub fn name_matches(item: &EnvOptions, ro: &RunOptions, line: Option) -> bool { if item.exact_name.is_some() { let name = item.exact_name.as_ref().unwrap(); if name == &ro.name { return true; } //println!("{}: exact name mismatch: {} != {}", item.section, name, ro.name); return false; } if item.name.is_some() { let name_re = match regex_build( &item.name.as_ref().unwrap(), &ro.name, &item.file_name, &item.section, line, ) { Some(check) => check, None => { println!("Could not compile {}", &item.name.as_ref().unwrap()); return false; } }; if name_re.is_match(&ro.name) { // println!("{}: skipping as not a name match ({}), group={}", item.section, item.name.as_ref().unwrap(), item.group); return true; } return false; } false } pub fn group_matches(item: &EnvOptions, ro: &RunOptions, line: Option) -> bool { if item.exact_name.is_some() { let name = item.exact_name.as_ref().unwrap(); for (k, _) in ro.groups.iter() { if name == k { // println!("{}: {} matches group {}", item.section,item.name.as_ref().unwrap(), k); return true; } } // println!("{}: does not match group", item.section); return false; } if item.name.is_some() { let name_re = match regex_build( &item.name.as_ref().unwrap(), &ro.name, &item.file_name, &item.section, line, ) { Some(check) => check, None => { println!("Could not compile {}", &item.name.as_ref().unwrap()); return false; } }; for (k, _) in ro.groups.iter() { if name_re.is_match(&k.to_string()) { // println!("{}: {} matches group {}", item.section, item.name.as_ref().unwrap(), k); return true; } } return false; } false } /// search the EnvOptions list for matching RunOptions and return the match pub fn can(vec_eo: &[EnvOptions], ro: &RunOptions) -> EnvOptions { let mut opt = EnvOptions::new_deny(); let mut matched; for item in vec_eo { // println!("{}:", item.section); if item.acl_type != ro.acl_type { // println!("{}: not {:?} != {:?}", item.section, item.acl_type, ro.acl_type); continue; } if !permitted_dates_ok(&item, &ro, None) { continue; } if !item.group && !name_matches(&item, &ro, None) { continue; } if item.group && !group_matches(&item, &ro, None) { continue; } if !hostname_ok(&item, &ro, None) { continue; } if !directory_check_ok(&item, &ro, None) { continue; } if !environment_ok(&item, &ro, None) { continue; } if !target_ok(&item, &ro, None) { continue; } if item.acl_type == Acltype::List { // println!("{}: is list", item.section); opt = item.clone(); matched = true; } else { if !rule_match(&item, &ro, None) { continue; } matched = true; opt = item.clone(); // else { println!("{}: item rule ({}) is not a match for {}", item.section, item.rule, ro.command); } } if opt.last && matched { break; } // println!("didn't match"); } opt } /// find editor for user. return /usr/bin/vi if EDITOR and VISUAL are unset pub fn get_editor() -> String { let editor = "/usr/bin/vi"; for prog in [String::from("VISUAL"), String::from("EDITOR")].iter() { if let Ok(val) = std::env::var(prog) { return val; } } editor.to_string() } /// handler.authenticate without the root privs part for linux #[cfg(target_os = "linux")] pub fn handler_shim( _ro: &RunOptions, handler: &mut Authenticator, ) -> Result<(), pam::PamError> { handler.authenticate() } /// handler.authenticate needs esc_privs on netbsd #[cfg(not(target_os = "linux"))] pub fn handler_shim( ro: &RunOptions, handler: &mut Authenticator, ) -> Result<(), pam::PamError> { if !esc_privs() { std::process::exit(1); } let auth = handler.authenticate(); if !drop_privs(&ro) { std::process::exit(1); } auth } /// read password of user via rpassword /// should pam require a password, and it is successful, then we set a token pub fn challenge_password(ro: &RunOptions, entry: &EnvOptions, service: &str) -> bool { if entry.require_pass { if tty_name().is_none() { println!("Cannot read password without tty"); return false; } let mut retry_counter = 0; if !esc_privs() { std::process::exit(1); } if valid_token(&ro.name) { update_token(&ro.name); return true; } if !drop_privs(&ro) { std::process::exit(1); } if !ro.prompt { return false; } let convo = PamConvo { login: ro.name.to_string(), passwd: None, service: service.to_string(), }; let mut handler = Authenticator::with_handler(service, convo).expect("Cannot init PAM"); loop { let auth = handler_shim(&ro, &mut handler); if auth.is_ok() { if handler.get_handler().passwd.is_some() { if !esc_privs() { std::process::exit(1); } update_token(&ro.name); if !drop_privs(&ro) { std::process::exit(1); } } return true; } retry_counter += 1; if retry_counter == 3 { println!("Authentication failed :-("); return false; } } } true } /// return rule or exact_rule pub fn list_rule(eo: &EnvOptions) -> String { if eo.exact_rule.is_some() { return format!("exact({})", eo.exact_rule.as_ref().unwrap()); } if eo.rule.is_some() { return eo.rule.as_ref().unwrap().to_string(); } "".to_string() } /// return target or exact_target pub fn list_target(eo: &EnvOptions) -> String { if eo.exact_target.is_some() { return format!("exact({})", eo.exact_target.as_ref().unwrap()); } if eo.target.is_some() { return eo.target.as_ref().unwrap().to_string(); } "".to_string() } /// return dir or exact_dir pub fn list_dir(eo: &EnvOptions) -> String { if eo.exact_dir.is_some() { return format!("exact({})", eo.exact_dir.as_ref().unwrap()); } if eo.dir.is_some() { return eo.dir.as_ref().unwrap().to_string(); } "".to_string() } /// print output list of acl pub fn list(vec_eo: &[EnvOptions], ro: &RunOptions) { //let mut str_list: vec![]; for s in produce_list(&vec_eo, &ro) { println!("{}", s); } } /// return EnvOptions as a vector of strings pub fn produce_list(vec_eo: &[EnvOptions], ro: &RunOptions) -> Vec { let mut str_list = vec![]; let mut ro = ro.clone(); if !ro.target.is_empty() { ro.name = ro.target.clone(); } let mut last_file = ""; for item in vec_eo { if !item.group && !name_matches(&item, &ro, None) { continue; } if item.group && !group_matches(&item, &ro, None) { continue; } let mut prefixes = vec![]; if item.notbefore.is_some() && item.notbefore.unwrap() > ro.date { prefixes.push(format!("upcomming({})", item.notbefore.unwrap())); } if item.notafter.is_some() && item.notafter.unwrap() < ro.date { prefixes.push(format!("expired({})", item.notafter.unwrap())); } if item.reason { prefixes.push(String::from("reason_required")); } if item.acl_type != ro.acl_type { continue; } if !item.permit { prefixes.push(String::from("not permitted")); } if !hostname_ok(&item, &ro, None) { continue; } if item.last { prefixes.push(String::from("last")); } let mut prefix = prefixes.join(", "); if !prefix.is_empty() { if item.acl_type != Acltype::List { prefix = format!(" {} as ", prefix); } else { prefix = format!(" {} to ", prefix); } } if last_file != item.file_name { str_list.push(format!(" in file: {}", item.file_name)); last_file = &item.file_name; } if item.acl_type == Acltype::List { str_list.push(format!( " {}:{}list: {}", item.section, prefix, item.target.as_ref().unwrap() )); continue; } str_list.push(format!( " {}:{}{} (pass={},dirs={}): {}", item.section, prefix, list_target(&item), item.require_pass, list_dir(&item), list_rule(&item) )); } str_list } /// if binary is not an absolute/relative path, look for it in usual places pub fn search_path(binary: &str) -> Option { let p = Path::new(binary); if binary.starts_with('/') || binary.starts_with("./") { if !p.exists() { return None; } else { return Some(binary.to_string()); } } for dir in "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin".split(':') { let path_name = format!("{}/{}", &dir, &binary); let p = Path::new(&path_name); if !p.exists() { continue; } return Some(path_name); } None } /// clean environment aside from ~half a dozen vars pub fn clean_environment(ro: &mut RunOptions) { ro.old_umask = Some(nix::sys::stat::umask( nix::sys::stat::Mode::from_bits(0o077).unwrap(), )); for (key, val) in std::env::vars() { if ro.acl_type == Acltype::Edit { if ro.old_envs.is_none() { ro.old_envs = Some(HashMap::new()); } ro.old_envs .as_mut() .unwrap() .entry(key.to_string()) .or_insert(val); } if key == "LANGUAGE" || key == "XAUTHORITY" || key == "LANG" || key == "LS_COLORS" || key == "TERM" || key == "DISPLAY" || key == "LOGNAME" { continue; } let mut skip = false; if ro.allow_env_list.is_some() { for env in ro.allow_env_list.as_ref().unwrap() { if key == *env { skip = true; break; } } } if skip { continue; } if ro.acl_type == Acltype::Edit && (key == "EDITOR" || key == "VISUAL") { continue; } std::env::remove_var(key); } } /// set the environment unless it is permitted to be kept and is specified pub fn set_env_if_not_passed_through(ro: &RunOptions, key: &str, value: &str) { if ro.allow_env_list.is_some() { for env in ro.allow_env_list.as_ref().unwrap() { if key == *env { // println!("Returning as {} = {}", key, *env ); return; } } } std::env::set_var(key, value); } /// set environment for helper scripts pub fn set_environment( ro: &RunOptions, entry: &EnvOptions, original_user: &User, original_uid: u32, lookup_name: &User, ) { std::env::set_var("PLEASE_USER", original_user.name()); std::env::set_var("PLEASE_UID", original_uid.to_string()); std::env::set_var("PLEASE_GID", original_user.primary_group_id().to_string()); std::env::set_var("PLEASE_COMMAND", &ro.command); std::env::set_var("SUDO_USER", original_user.name()); std::env::set_var("SUDO_UID", original_uid.to_string()); std::env::set_var("SUDO_GID", original_user.primary_group_id().to_string()); std::env::set_var("SUDO_COMMAND", &ro.command); set_env_if_not_passed_through( &ro, "PATH", "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", ); set_env_if_not_passed_through(&ro, "HOME", lookup_name.home_dir().to_str().unwrap()); set_env_if_not_passed_through(&ro, "MAIL", &format!("/var/mail/{}", ro.target)); set_env_if_not_passed_through(&ro, "SHELL", lookup_name.shell().to_str().unwrap()); set_env_if_not_passed_through(&ro, "USER", &ro.target); set_env_if_not_passed_through(&ro, "LOGNAME", &ro.target); if entry.env_assign.is_some() { for (k, v) in entry.env_assign.as_ref().unwrap() { std::env::set_var(k, v); } } } pub fn bad_priv_msg() { println!("I cannot set privs. Exiting as not installed correctly."); } /// set privs of usr to target_uid and target_gid. return false if fails pub fn set_privs(user: &str, target_uid: nix::unistd::Uid, target_gid: nix::unistd::Gid) -> bool { let user = CString::new(user).unwrap(); if initgroups(&user, target_gid).is_err() { bad_priv_msg(); return false; } if setgid(target_gid).is_err() { bad_priv_msg(); return false; } if setuid(target_uid).is_err() { bad_priv_msg(); return false; } true } /// set privs of usr to target_uid and target_gid. return false if fails pub fn set_eprivs(target_uid: nix::unistd::Uid, target_gid: nix::unistd::Gid) -> bool { if setegid(target_gid).is_err() { bad_priv_msg(); return false; } if seteuid(target_uid).is_err() { bad_priv_msg(); return false; } true } /// set privs (just call eprivs based on ro) pub fn drop_privs(ro: &RunOptions) -> bool { esc_privs() && set_eprivs(ro.original_uid, ro.original_gid) } /// reset privs (just call eprivs based on root) pub fn esc_privs() -> bool { set_eprivs(nix::unistd::Uid::from_raw(0), nix::unistd::Gid::from_raw(0)) } /// return our best guess of what the user's tty is pub fn tty_name() -> Option { let mut ttyname = None; /* sometimes a tty isn't attached for all pipes FIXME: make this testable */ for n in 0..3 { let ptr; unsafe { ptr = libc::ttyname(n); } if ptr.is_null() { continue; } let s; unsafe { s = CStr::from_ptr(ptr).to_str(); } match s { Err(_x) => ttyname = None, Ok(x) => ttyname = Some(x.to_string()), } break; } ttyname } /// add a level of escape to strings when they go to the old as " holds entities pub fn escape_log(message: &str) -> String { message.replace("\"", "\\\"") } /// write to syslog a standard log pub fn log_action(service: &str, result: &str, ro: &RunOptions, command: &str) -> bool { if !ro.syslog { return false; } let formatter = Formatter3164 { facility: Facility::LOG_USER, hostname: None, process: service.into(), pid: process::id() as i32, }; let cwd = match env::current_dir() { Err(_) => "unable to get cwd".to_string(), Ok(x) => x.to_string_lossy().to_string(), }; match syslog::unix(formatter) { Err(_e) => println!("Could not connect to syslog"), Ok(mut writer) => { let tty_name = tty_name(); writer .err(format!( "user=\"{}\" cwd=\"{}\" tty=\"{}\" action=\"{}\" target=\"{}\" type=\"{}\" reason=\"{}\" command=\"{}\"", escape_log( &ro.name ), escape_log( &cwd ), if tty_name.is_none() { "no_tty".to_string() } else { tty_name.unwrap() }, result, escape_log( &ro.target ), ro.acl_type, if ro.reason.as_ref().is_some() { escape_log( &ro.reason.as_ref().unwrap() ) } else { String::from("") }, escape_log( command ) )) .expect("could not write error message"); } } false } /// return the directory that the token should use pub fn token_dir() -> String { "/var/run/please/token".to_string() } /// return the path of the users token pub fn token_path(user: &str) -> Option { let tty_name = tty_name(); tty_name.as_ref()?; let ppid = nix::unistd::getppid(); Some(format!( "{}/{}:{}:{}", token_dir(), user, tty_name.unwrap().replace("/", "_"), ppid )) } pub fn create_token_dir() -> bool { if !Path::new(&token_dir()).is_dir() && fs::create_dir_all(&token_dir()).is_err() { println!("Could not create token directory"); return false; } true } pub fn boot_secs() -> libc::timespec { let mut tp = libc::timespec { tv_sec: 0, tv_nsec: 0, }; #[cfg(target_os = "linux")] unsafe { libc::clock_gettime(libc::CLOCK_BOOTTIME, &mut tp) }; #[cfg(not(target_os = "linux"))] unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut tp) }; tp } /// does the user have a valid token /// return false if time stamp is in the future /// return true if token was set within 600 seconds of wall and boot time pub fn valid_token(user: &str) -> bool { if !create_token_dir() { return false; } let token_path = token_path(user); if token_path.is_none() { return false; } let secs = 600; let token_path = token_path.unwrap(); match fs::metadata(token_path) { Ok(meta) => { match meta.modified() { Ok(t) => { let tp = boot_secs(); match t.duration_since(SystemTime::UNIX_EPOCH) { Ok(s) => { if (tp.tv_sec as u64) < s.as_secs() { // println!("tv_sec lower {} vs {}", tp.tv_sec, s.as_secs()); return false; } if ((tp.tv_sec as u64) - s.as_secs()) < secs { // check the atime isn't older than 600 too match SystemTime::now().duration_since(meta.accessed().unwrap()) { Ok(a) => return a.as_secs() <= secs, Err(_) => return false, } } } Err(_) => { return false; } } false } Err(_e) => false, } } Err(_) => false, } } /// touch the users token on disk pub fn update_token(user: &str) { if !create_token_dir() { return; } let token_path = token_path(user); if token_path.is_none() { return; } let old_mode = nix::sys::stat::umask(nix::sys::stat::Mode::from_bits(0o077).unwrap()); let token_path = token_path.unwrap(); let token_path_tmp = format!("{}.tmp", &token_path); match fs::File::create(&token_path_tmp) { Ok(_x) => {} Err(x) => println!("Error creating token: {}", x), } nix::sys::stat::umask(old_mode); let tp = boot_secs(); let tv_mtime = nix::sys::time::TimeVal::from(libc::timeval { tv_sec: tp.tv_sec, tv_usec: 0, }); // https://github.com/rust-lang/libc/issues/1848 #[cfg_attr(target_env = "musl", allow(deprecated))] let tv_atime = nix::sys::time::TimeVal::from(libc::timeval { tv_sec: SystemTime::now() .duration_since(SystemTime::UNIX_EPOCH) .unwrap() .as_secs() as libc::time_t, tv_usec: 0, }); if nix::sys::stat::utimes(Path::new(&token_path_tmp), &tv_atime, &tv_mtime).is_err() { return; } if std::fs::rename(&token_path_tmp.as_str(), token_path).is_err() { println!("Could not update token"); } } /// remove from disk the users token pub fn remove_token(user: &str) { if !create_token_dir() { return; } let token_location = token_path(&user); if token_location.is_none() { return; } let token_location = token_location.unwrap(); let p = Path::new(&token_location); if p.is_file() { match fs::remove_file(p) { Ok(_x) => {} Err(x) => println!("Error removing token {}: {}", p.to_str().unwrap(), x), } } } /// turn group list into an indexed list pub fn group_hash(groups: Vec) -> HashMap { let mut hm: HashMap = HashMap::new(); for group in groups { hm.entry(String::from(group.name().to_string_lossy())) .or_insert_with(|| group.gid()); } hm } /// escape '\' within an argument /// escape ' ' within an argument pub fn replace_new_args(new_args: Vec) -> String { let mut args = vec![]; for arg in &new_args { args.push(arg.replace("\\", "\\\\").replace(" ", "\\ ")); } args.join(" ") } /// print version string pub fn print_version(program: &str) { println!("{} version {}", &program, env!("CARGO_PKG_VERSION")); } /// return a lump of random alpha numeric characters pub fn prng_alpha_num_string(n: usize) -> String { let rng = thread_rng(); rng.sample_iter(&Alphanumeric).take(n).collect() } pleaser-0.5.1/tests/exact.rs010064400017500001750000000227221415312630000141450ustar 00000000000000use chrono::NaiveDate; #[cfg(test)] mod test { use super::*; use pleaser::*; #[test] fn test_exact_rule() { let config = "[ed] exact_name=ed exact_target=root exact_rule = /bin/bash " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.command = "/bin/bashz".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "/".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_exact_rule_parameters() { let config = "[ed] exact_name=ed exact_target=root exact_rule = /bin/bash " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.command = "/bin/bash file".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); let config = "[ed] exact_name=ed exact_target=root exact_rule = /bin/bash file " .to_string(); let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "/bin/bash file".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); let config = "[ed] exact_name=ed exact_target=root exact_rule = /bin/bash echo\\ hello\\ world " .to_string(); let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "/bin/bash echo\\ hello\\ world".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_exact_name() { let config = "[ed] exact_name=ed exact_target=root exact_rule = /bin/bash " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.name = "jim".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "edd".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_exact_target() { let config = "[ed] exact_name=ed exact_target=root exact_rule = /bin/bash " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.target = "jim".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.target = "edd".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_exact_hostname() { let config = "[ed] exact_name=ed exact_target=root exact_hostname=thing exact_rule = /bin/bash " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); ro.hostname = "thing".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.hostname = "".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.hostname = "web".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.hostname = "localhost".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); let config = "[ed] exact_name=ed exact_target=root exact_hostname=localhost exact_rule = /bin/bash " .to_string(); read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); ro.hostname = "thing".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_exact_dir() { let config = "[ed] exact_name=ed exact_target=root exact_rule = /bin/sh exact_dir = /root " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/sh".to_string(); ro.directory = Some("/root".to_string()); assert_eq!(can(&vec_eo, &ro).permit, true); ro.directory = Some("/home".to_string()); assert_eq!(can(&vec_eo, &ro).permit, false); ro.directory = Some("/".to_string()); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_exact_name_precedence() { let config = "[ed] exact_name=ed name = zz exact_target=root exact_rule = /bin/bash " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.name = "zz".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); let config = "[ed] exact_name= name=zz exact_target=root exact_rule = /bin/bash " .to_string(); read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); ro.name = "zz".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_exact_rule_precedence() { let config = "[ed] exact_name=ed exact_target=root exact_rule = /bin/sh rule = /bin/bash " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/sh".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_exact_target_precedence() { let config = "[ed] exact_name=ed exact_target=root target=bob exact_rule = /bin/sh " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/sh".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.target = "bob".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_exact_dir_precedence() { let config = "[ed] exact_name=ed exact_target=root exact_rule = /bin/sh exact_dir = /root dir = .* " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/sh".to_string(); ro.directory = Some("/root".to_string()); assert_eq!(can(&vec_eo, &ro).permit, true); ro.directory = Some("/home".to_string()); assert_eq!(can(&vec_eo, &ro).permit, false); } } pleaser-0.5.1/tests/tests.rs010064400017500001750000001225131415313273200142100ustar 00000000000000use std::collections::HashMap; use chrono::NaiveDate; #[cfg(test)] mod test { use super::*; use pleaser::*; #[test] fn test_execute_config() { let config = "[ed_all_dated] name=ed target=root notbefore=20200101 notafter=20201225 regex =^.*$ [ed_false_oracle] name=ed target=oracle permit=false regex=^/bin/bash .*$ [ed_root_bash_all] name=ed target=root regex=^/bin/bash .*$ " .to_string(); let mut bytes = 0; let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_user_bash() { let config = " [ed_edn] name = ed type = list target = root regex = (edn?) [ed] name = ed target = root regex = /bin/bash " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_execute_user_does_not_exist() { let config = "[ed_root_all] name=ed target=root notbefore=20200101 notafter=20201225 regex= ^.*$ [ed_oracle_bash] name=ed target=oracle regex=^/bin/bash .*$ [ed_root_bash] name=ed target=root regex=^/bin/bash .*$ [user_all_todo] name=.* target=thingy regex=^/bin/bash" .to_string(); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2019, 12, 31).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, &ro.name, false, &mut bytes); assert_eq!(can(&vec_eo, &ro).permit, false); ro.name = "other".to_string(); ro.target = "thingy".to_string(); let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, &ro.name, false, &mut bytes); assert_eq!(can(&vec_eo, &ro).permit, true); ro.name = "other".to_string(); ro.target = "oracle".to_string(); let mut vec_eo: Vec = vec![]; read_ini_config_str(&config, &mut vec_eo, &ro.name, false, &mut bytes); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_execute_config_too_early() { let config = " [ed] name=ed target=root notbefore=20200101 notafter=20201225 regex =^.*$ [ed_oracle] name=ed target=oracle ^/bin/bash .*$ [ed_dated] name=ed target=root notbefore=20200101 notafter=20200125 regex =^.* [name_all_todo] name=m{} target=^ " .to_string(); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); ro.date = NaiveDate::from_ymd(2019, 12, 31).and_hms(0, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, false); ro.date = NaiveDate::from_ymd(2020, 12, 25).and_hms(0, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, true); ro.date = NaiveDate::from_ymd(2020, 01, 25).and_hms(0, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, true); ro.date = NaiveDate::from_ymd(2020, 03, 25).and_hms(0, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_list_regex() { let config = " [ed_root] name = (floppy) group = true permit = true require_pass = false target = ^.* [ed_list] name = (ed) type = list target = %{USER} require_pass = false " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.acl_type = Acltype::List; ro.target = "ed".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.target = "root".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_execute_config_too_early_long() { let config = " [ed_too_early] name=ed target=root notbefore=20200808 notafter=20200810235959 regex=^.* " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); ro.date = NaiveDate::from_ymd(2020, 8, 8).and_hms(0, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, true); ro.date = NaiveDate::from_ymd(2020, 8, 10).and_hms(0, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, true); ro.date = NaiveDate::from_ymd(2020, 8, 10).and_hms(23, 59, 59); assert_eq!(can(&vec_eo, &ro).permit, true); ro.date = NaiveDate::from_ymd(2020, 8, 11).and_hms(0, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, false); ro.date = NaiveDate::from_ymd(2020, 8, 7).and_hms(0, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_execute_config_oracle() { let config = "[ed_oracle] name=ed target=oracle notbefore=20200101 notafter=20201225 regex=^/bin/bash .*$ [ed_oracle_permit] name=ed target=oracle notbefore=20190101 notafter=20201225 permit=true regex=^/bin/bash .*$ " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "oracle".to_string(); ro.date = NaiveDate::from_ymd(2019, 12, 31).and_hms(0, 0, 0); ro.command = "/bin/bash /usr/local/oracle/backup_script".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.command = "/bin/sh /usr/local/oracle/backup_script".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.hostname = "web1".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.hostname = "".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.hostname = "localhost".to_string(); ro.target = "grid".to_string(); ro.command = "/bin/bash /usr/local/oracle/backup_script".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.target = "root".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_execute_config_hostname_any() { let config = " [ed_config_hostname] name=ed target=oracle hostname=any regex=^/bin/bash.*$ " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "oracle".to_string(); ro.command = "/bin/bash /usr/local/oracle/backup_script".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.command = "/bin/sh /usr/local/oracle/backup_script".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.hostname = "web1".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.hostname = "".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.target = "grid".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_execute_config_hostname_locahost() { let config = " [ed_oralce_web1] name=ed target=oracle hostname=web1 regex=^/bin/bash .*$ [ed_oracle_localhost] name=ed target=oracle hostname=localhost regex=^/bin/sh.*$ " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "oracle".to_string(); ro.command = "/bin/bash /usr/local/oracle/backup_script".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.hostname = "web1".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.hostname = "web2".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.hostname = "localhost".to_string(); ro.command = "/bin/sh /usr/local/oracle/backup_script".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.hostname = "web1".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.hostname = "web2".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_missing_user() { let config = " [missing_user] target=oracle hostname=localhost regex=/bin/sh\\b.* " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "".to_string(); ro.target = "oracle".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_regex_line_anchor() { let config = " [regex_anchor] name=ed target=oracle hostname=localhost regex=.* " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "oracle".to_string(); ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_edit_apache() { let config = " [ed_edit_root] name=ed target=root notbefore=20200101 notafter=20201225 type = edit regex = .* [ed_edit_apache] name=ed target=oracle permit=false type = edit regex = /etc/apache [ed_edit_hosts] name=ed target=root regex = /etc/hosts type = edit [user_all_todo] name=m{} target=^ type = edit regex = ^" .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Edit; ro.command = "/etc/apache/httpd2.conf".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_edit_user_macro() { let config = " [ed] name=ed target=root regex =^/bin/cat /etc/%{USER}" .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/cat /etc/ed".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.name = "ned".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_parse_regex_fail() { let mut vec_eo: Vec = vec![]; let config = " [ed] name=ed target=root regex = ^/bin/cat /etc/(" .to_string(); let mut bytes = 0; assert_eq!( read_ini_config_str(&config, &mut vec_eo, "ed", true, &mut bytes), true ); let mut vec_eo: Vec = vec![]; let config = " [ed] name=ed target=root regex = ^/bin/cat /etc/ " .to_string(); let mut bytes = 0; assert_eq!( read_ini_config_str(&config, &mut vec_eo, "ed", true, &mut bytes), false ); } #[test] fn test_group_assignment() { let config = " [users] name=users group=true target=root notbefore=20200101 notafter=20201225 regex = ^.*$ " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/cat /etc/ed".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.groups.insert(String::from("users"), 1); assert_eq!(can(&vec_eo, &ro).permit, true); ro.groups = HashMap::new(); ro.groups.insert(String::from("wwwadm"), 1); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_list_other_user() { let config = " [ed_all] name=ed notbefore=20200101 notafter=20201225 type = list target = ^.*$ [bob_all] name=bob type=edit target = ^.*$ [bob_all] name=bob type = list permit=false target = ^.*$ [meh_ed] name=meh type =list target=^ed$ [root_all] name=root type=run regex =^.*$ [ben_ops] name=ben permit=true type=list target = ^(eng|dba|net)ops$ " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/cat /etc/ed".to_string(); ro.acl_type = Acltype::List; assert_eq!(can(&vec_eo, &ro).permit, true); ro.name = "meh".to_string(); ro.target = "ed".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.target = "bob".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.target = "root".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.name = "bob".to_string(); ro.target = "ed".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.name = "ben".to_string(); ro.target = "dbaops".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.target = "engops".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.target = "netops".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.target = "wwwops".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_edit_regression() { let config = " [www-data-bio] name = root group = true permit = true type = edit require_pass = false regex = ^/var/www/html/%{USER}.html " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/etc/please.ini".to_string(); ro.acl_type = Acltype::Edit; assert_eq!(can(&vec_eo, &ro).permit, false); ro.groups.insert(String::from("root"), 1); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "/var/www/html/ed.html".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.command = "/var/www/html/%{USER}.html".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.groups = HashMap::new(); ro.groups.insert(String::from("wwwadm"), 1); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_edit_user_expansion() { let config = " [www-data-bio] name = root group = true permit = true type = edit require_pass = false regex = ^/var/www/html/%{USER}.html$ " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/var/www/html/ed.html".to_string(); ro.acl_type = Acltype::Edit; ro.groups.insert(String::from("root"), 1); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_edit_user_expansion_unescaped() { let config = " [www-data-bio] name = root group = true permit = true type = edit require_pass = false regex = ^/var/www/html/%USER.html$" .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Edit; ro.command = "/var/www/html/ed.html".to_string(); ro.groups.insert(String::from("root"), 1); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_edit_user_expansion_escapes() { let config = " [www-data-bio] name = root group = true permit = true type = edit require_pass = false regex = ^/var/www/html/%{USER}.html$" .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Edit; ro.command = "/var/www/html/ed.html".to_string(); ro.groups.insert(String::from("root"), 1); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_target_regex() { let config = " [ed_target_ot] name = .*ot group = true target = .*ot permit = true require_pass = false regex = /bin/bash" .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); assert_eq!( vec_eo .iter() .next() .unwrap() .rule .as_ref() .unwrap() .as_str(), "/bin/bash" ); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.groups.insert(String::from("root"), 1); ro.command = "/bin/sh".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.target = "woot".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_edit_regression_empty() { let mut vec_eo: Vec = vec![]; let config = "".to_string(); let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Edit; ro.command = "/etc/please.ini".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_dir_any() { let config = " [regex_anchor] name=ed target=oracle hostname=localhost regex=.* dir=.* " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "oracle".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.directory = Some("/".to_string()); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_dir_fixed() { let config = " [regex_anchor] name=ed target=oracle hostname=localhost regex=.* dir=/var/www " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "oracle".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false, "no directory given",); ro.directory = Some("/".to_string()); assert_eq!(can(&vec_eo, &ro).permit, false, "change outside permitted",); ro.directory = Some("/var/www".to_string()); assert_eq!(can(&vec_eo, &ro).permit, true, "permitted"); } #[test] fn test_dir_tmp() { let config = " [regex_anchor] name=ed target=root regex=/bin/bash dir=/tmp " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); ro.directory = Some("/tmp".to_string()); assert_eq!(can(&vec_eo, &ro).permit, true, "dir_tmp",); } #[test] fn test_dir_given_but_none_in_match() { let config = " [regex_anchor] name=ed target=oracle hostname=localhost regex=.* " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.date = NaiveDate::from_ymd(2020, 1, 1).and_hms(0, 0, 0); ro.name = "ed".to_string(); ro.target = "oracle".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); ro.directory = Some("/".to_string()); assert_eq!(can(&vec_eo, &ro).permit, false, "directory given",); ro.directory = Some("".to_string()); assert_eq!(can(&vec_eo, &ro).permit, false, "directory given",); } #[test] fn test_date_match() { let config = " [regex_anchor] name=ed target=root hostname=localhost regex=.* datematch=Fri.*UTC.* " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.date = NaiveDate::from_ymd(2020, 10, 02).and_hms(22, 0, 0); ro.target = "root".to_string(); ro.acl_type = Acltype::Run; ro.command = "/bin/bash".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.date = NaiveDate::from_ymd(2020, 10, 01).and_hms(22, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, false); let config = " [regex_anchor] name=ed target=root hostname=localhost regex=.* datematch=Fri.*\\s22:00:00\\s+UTC\\s2020 " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); ro.date = NaiveDate::from_ymd(2020, 10, 02).and_hms(21, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, false); ro.date = NaiveDate::from_ymd(2020, 10, 02).and_hms(23, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, false); ro.date = NaiveDate::from_ymd(2020, 10, 02).and_hms(22, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, true); let config = " [regex_anchor] name=ed target=root hostname=localhost regex=.* datematch=Thu\\s+1\\s+Oct\\s+22:00:00\\s+UTC\\s+2020 " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); ro.date = NaiveDate::from_ymd(2020, 10, 01).and_hms(21, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, false); ro.date = NaiveDate::from_ymd(2020, 10, 01).and_hms(23, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, false); ro.date = NaiveDate::from_ymd(2020, 10, 01).and_hms(22, 0, 0); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_edit_mode() { let config = " [edit_filemode] name=ed target=root regex=/etc/please.ini.* type=edit editmode=0644 " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Edit; ro.command = "/etc/please.ini".to_string(); let entry = can(&vec_eo, &ro); assert!(matches!(entry.edit_mode, Some(EditMode::Mode(420)))); let config = " [edit_filemode] name=ed target=root regex=/etc/please.ini.* type=edit editmode=keep " .to_string(); bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let entry = can(&vec_eo, &ro); assert!(matches!(entry.edit_mode, Some(EditMode::Keep(true)))); } #[test] fn test_read_ini_config_file() { let mut vec_eo: Vec = vec![]; let mut bytes = 0; assert_eq!( read_ini_config_file(".", &mut vec_eo, "ed", true, &mut bytes), true ); assert_eq!( read_ini_config_file("", &mut vec_eo, "ed", true, &mut bytes), true ); assert_eq!( read_ini_config_file("./faulty", &mut vec_eo, "ed", true, &mut bytes), true ); } #[test] fn test_last() { let config = " [first] name=ed target=root regex=/bin/bash permit=false last=true [unreachable] name=ed target=root regex=/bin/bash permit=true " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/bash".to_string(); let entry = can(&vec_eo, &ro); assert_eq!(entry.permit, false); } #[test] fn test_reason() { let config = " [first] name=ed target=root regex=/bin/bash permit=false reason=true " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/bash".to_string(); let entry = can(&vec_eo, &ro); assert_eq!(entry.reason, true); } #[test] fn test_regex_build_user_expansion() { let regex_re = regex_build("/var/www/html/%{USER}/page.html", "ed", "/", "none", None).unwrap(); assert_eq!(regex_re.as_str(), "^/var/www/html/ed/page.html$"); } #[test] fn test_section_name() { let config = " [first] name=ed target=root regex=/bin/bash permit=false reason=true " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/bash".to_string(); let entry = can(&vec_eo, &ro); assert_eq!(entry.section, "first"); } #[test] fn test_multi_log() { let config = " [first] name=ed target=root regex=^/usr/bin/wc (/var/log/[a-zA-Z0-9-]+(\\.\\d+)?(\\s)?)+$ " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/usr/bin/wc /var/log/messages /var/log/syslog /var/log/maillog".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.command = "/usr/bin/wc /var/log/messages /var/log/messages.1".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); ro.command = "/usr/bin/wc /var/log/messages /var/log/syslog /var/log/maillog /var/log/../../shadow" .to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "/usr/bin/wc".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "/usr/bin/wc /etc/shadow".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "/usr/bin/wc".to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); ro.command = "/usr/bin/wc /var/log/messages /var/log/messages.1 /var/log/../../etc/shadow" .to_string(); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_edit_group_regression() { let config = " [please_ini] name = lpadmin group = true regex = /etc/please.ini reason = true type = edit exitcmd = /usr/bin/please -c %{NEW} " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.groups.insert(String::from("lpadmin"), 1); ro.acl_type = Acltype::Edit; ro.command = "/etc/please.ini".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_ini_relative() { let mut vec_eo: Vec = vec![]; let config = " [inc] include = ./some.ini " .to_string(); let mut bytes: u64 = 0; assert_eq!( read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes), true ); let config = " [inc] includedir = ./dir.d/some.ini " .to_string(); assert_eq!( read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes), true ); let config = " [inc] includedir = /dev/null " .to_string(); assert_eq!( read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes), false ); } #[test] fn test_can_include() { assert_eq!(can_dir_include("/etc/please.ini.z"), false); assert_eq!(can_dir_include("/etc/.please.ini"), false); assert_eq!(can_dir_include("/etc/.please.ini."), false); } #[test] fn test_can_include_pattern() { assert_eq!(can_include_file_pattern("/etc/please.ini"), true); assert_eq!(can_include_file_pattern("/etc/please.please.ini"), true); assert_eq!(can_include_file_pattern("/etc/please.d/ini.z"), false); assert_eq!(can_include_file_pattern("/etc/please.d/file.ini"), true); assert_eq!(can_include_file_pattern("/etc/please.d/.file.ini"), false); assert_eq!(can_include_file_pattern("/etc/please.d/.file"), false); } #[test] fn test_argument_replace() { assert_eq!( replace_new_args(vec![ "/bin/bash".to_string(), "-c".to_string(), "/bin/id".to_string(), "you're not the boss of me".to_string() ]), "/bin/bash -c /bin/id you're\\ not\\ the\\ boss\\ of\\ me" ); } #[test] fn test_syslog_format() { assert_eq!( escape_log(&"multiple \"strings\""), "multiple \\\"strings\\\"".to_string() ); } #[test] fn test_prng_alpha_num_string() { assert_eq!(prng_alpha_num_string(2).len(), 2); } #[test] fn test_list_output() { let config = " [list] name = %{USER} reason = false type = list " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "ed".to_string(); ro.acl_type = Acltype::List; ro.command = "".to_string(); let list = produce_list(&vec_eo, &ro); assert_eq!(list, [" in file: static", " list:list: root"]); } #[test] fn test_environment_provided_but_not_allowed() { let config = " [env_nopes] name = %{USER} reason = false " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "".to_string(); ro.allow_env_list = Some(vec!["PATH".to_string()]); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_environment_assign_env_list() { let config = " [ed_part_allowed] name = %{USER} reason = false type = run env_assign.ILIKETO = moveitmoveit env_assign.JOE = 90 regex = .* " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "".to_string(); let entry = can(&vec_eo, &ro); assert_eq!( entry.env_assign.as_ref().unwrap().get("ILIKETO").unwrap(), "moveitmoveit" ); assert_eq!(entry.env_assign.as_ref().unwrap().get("JOE").unwrap(), "90"); } #[test] fn test_environment_provided_and_allowed() { let config = " [ed_part_allowed] name = %{USER} reason = false type = run permit_env = (HOME|PATH) " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "".to_string(); ro.allow_env_list = Some(vec!["PATH".to_string(), "HOME".to_string()]); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_environment_provided_but_some_allowed() { let config = " [ed_part_allowed] name = %{USER} reason = false type = run permit_env = (HOME|PATH) " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "".to_string(); ro.allow_env_list = Some(vec![ "PATH".to_string(), "HOME".to_string(), "DISASTER".to_string(), ]); assert_eq!(can(&vec_eo, &ro).permit, false); } #[test] fn test_environment_not_provided_others_allowed() { let config = " [ed_part_allowed] name = %{USER} type = run permit_env = (HOME|PATH) " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "".to_string(); ro.allow_env_list = None; assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_percent_user() { let config = " [ed] name = ed type = run target = root regex = /bin/echo [%]\\{USER\\} " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/echo %{USER}".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_percent_user_as_hex() { let config = " [ed] name = ed type = run target = root regex = /bin/echo \\x25\\{USER\\} " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/echo %{USER}".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_internal_backslash() { let config = " [ed] name = ed type = run target = root regex = /bin/echo hello\\x5cworld " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/echo hello\\world".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_internal_backslash_as_class() { let config = " [ed] name = ed type = run target = root regex = /bin/echo hello[\\\\]world " .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = "/bin/echo hello\\world".to_string(); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_replace_new_args_spaces_exact_rule() { let config = r#" [ed] name = ed type = run target = root exact_rule = /bin/echo hello\ world "# .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = replace_new_args(vec!["/bin/echo".to_string(), "hello world".to_string()]); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_replace_new_args_spaces_rule() { let config = r#" [ed] name = ed type = run target = root rule = /bin/echo hello\\ world "# .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = replace_new_args(vec!["/bin/echo".to_string(), "hello world".to_string()]); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_replace_new_args_internal_backslash_spaces_rule() { let config = r#" [ed] name = ed type = run target = root rule = /bin/echo hello\\ \\\\\\ world "# .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.command = replace_new_args(vec!["/bin/echo".to_string(), "hello \\ world".to_string()]); assert_eq!(can(&vec_eo, &ro).permit, true); } #[test] fn test_default_edit_file_mode() { let config = r#" [ed] name = ed type = edit target = root rule = /etc/fstab "# .to_string(); let mut vec_eo: Vec = vec![]; let mut bytes = 0; read_ini_config_str(&config, &mut vec_eo, "ed", false, &mut bytes); let mut ro = RunOptions::new(); ro.name = "ed".to_string(); ro.target = "root".to_string(); ro.acl_type = Acltype::Edit; ro.command = replace_new_args(vec!["/etc/fstab".to_string()]); assert_eq!(can(&vec_eo, &ro).edit_mode, Some(EditMode::Keep(true))); } }