Compare commits

...
88 Commits
Author SHA1 Message Date
dietrich 70ee27a246 replace println! with trace! 2020-11-30 15:17:24 +01:00
dietrich 1e5a95a9f6 fix warnings 2020-11-30 13:21:22 +01:00
dietrich df2f51a24e add license 2020-11-29 17:35:24 +01:00
dietrich 80a41fc1a2 updating group membership on user deletion
until now groups had members without useraccount after the account has been deleted.

fixes: #5
2020-11-27 17:32:41 +01:00
dietrich e9fbbd91ce Enum to discriminate primary and reg. memberships 2020-11-24 19:20:48 +01:00
dietrich 93e958108b better tests for groups 2020-11-19 09:34:49 +01:00
dietrich 8b42c8c3b2 add group members 2020-11-19 09:14:00 +01:00
dietrich 65542c9b69 make Group a Rc<Inner> type 2020-11-17 07:53:49 +01:00
dietrich 98b1634924 adding new title 2020-11-16 14:35:06 +01:00
dietrich e5583bb378 add summary 2020-11-16 14:21:16 +01:00
dietrich 36f5e51811 updating dependencies 2020-11-16 14:13:25 +01:00
dietrich 0a1bb3bd7e fix clippy warning 2020-11-16 13:08:37 +01:00
dietrich 10d9e3e71e right parameters 2020-11-16 13:04:16 +01:00
dietrich 3583d89697 fix indentation 2020-11-16 12:57:23 +01:00
dietrich c056016d43 add clippy info 2020-11-16 12:52:12 +01:00
dietrich 5a678bc3d5 renaming the project adduser -> umanux 2020-11-16 10:37:18 +01:00
dietrich 05cbd2d139 better 2020-11-16 09:14:40 +00:00
dietrich 425de573d5 update readme 2020-11-16 10:12:51 +01:00
dietrich e13a81f814 use +nightly (#2)
* use +nightly
2020-11-16 08:46:34 +01:00
dietrich 95ce925286 Merge pull request #1 from umanux/enaut-add-rust-workflow
Add rust workflow
2020-11-16 08:11:18 +01:00
dietrich 60e6eb6fa4 Add rust workflow 2020-11-16 08:11:00 +01:00
dietrich 3dae3c4109 modify the shadow file and test the binary 2020-11-15 17:04:31 +01:00
dietrich ed77466bd6 add default shadow entry to default users 2020-11-15 17:02:35 +01:00
dietrich 32d02dcc81 add parameters for files to create_user 2020-11-15 17:01:47 +01:00
dietrich c21ba2fa39 return from main function 2020-11-11 08:20:09 +01:00
dietrich f7fc3229ed optimize release builds for size 2020-11-11 06:58:17 +01:00
dietrich 101dcbb649 first binary test not complete 2020-11-11 06:57:46 +01:00
dietrich de17ff12be first version of create_user 2020-11-10 13:45:21 +01:00
dietrich ed06c58913 remove debug and commented code 2020-11-09 20:25:42 +01:00
dietrich 8fcd32eca2 Fix missing lints - Docs need to be improved still 2020-11-09 13:58:13 +01:00
dietrich 467c8ee007 linting changes 2020-11-09 09:56:24 +01:00
dietrich 647881f022 Adding a first integrationtest for delete_user 2020-11-08 10:41:20 +01:00
dietrich 732893b5d4 first integration test try 2020-11-05 09:01:51 +01:00
dietrich 4062f7a6bb delete the home directory 2020-11-03 13:09:16 +01:00
dietrich f3a18641e0 make delete_user take a struct use derive_builder 2020-11-02 07:55:33 +01:00
dietrich 31fbfbe628 remove from groups 2020-10-31 16:40:26 +01:00
dietrich b72f292891 improve functionlength 2020-10-31 15:55:15 +01:00
dietrich d9fe8b8160 improve error handling 2020-10-31 11:15:29 +01:00
dietrich 6389bb988d actually remove the shadow line and fix a final newline 2020-10-30 19:45:41 +01:00
dietrich bacbfae4d1 delete the shadow entry along with the passwd one 2020-10-30 19:09:56 +01:00
dietrich 4207e1dc0f split Hashes into sepparate module 2020-10-30 16:37:57 +01:00
dietrich 8dd2c53aa9 sepparate Files struct 2020-10-30 16:26:31 +01:00
dietrich 8337c737d9 make userlib module a directory 2020-10-30 16:13:05 +01:00
dietrich 1af8a7cd65 Add better error handling 2020-10-30 08:39:59 +01:00
dietrich bf6908346e first draft of working user deletion
TODO:
  * remove user group
  * remove shadow entry
2020-10-28 09:39:42 +01:00
dietrich b8c1e3989a use env_logger 2020-10-26 14:33:05 +01:00
dietrich 927e7ba4a7 unify locking of a single file to locking of all files 2020-10-26 08:13:24 +01:00
dietrich b8c544a846 first draft of file locking 2020-10-25 11:08:56 +01:00
dietrich 338b4949e4 add must uses 2020-10-24 13:50:33 +02:00
dietrich 91f0453be6 do not use deprecated description 2020-10-24 13:50:20 +02:00
dietrich 56a6679ccb create draft binary for create_users 2020-10-23 19:50:06 +02:00
dietrich 67af4a39cd add getters to User 2020-10-23 19:49:47 +02:00
dietrich 83255390e3 make the structs clonable, add pos and source to the fields 2020-10-23 19:49:21 +02:00
dietrich d81bac5146 add get nth line function 2020-10-23 19:46:20 +02:00
dietrich 932fb2827d comment broken newuser 2020-10-23 19:45:51 +02:00
dietrich f33ba8e767 persistent ordering of the passwd file 2020-10-23 15:21:30 +02:00
dietrich 98d4c72f7f properly do read_all 2020-10-23 15:18:57 +02:00
dietrich 134b97cfec first try implementing userdbwrite 2020-10-23 12:33:34 +02:00
dietrich 70fcd823da adjust and implement more of the api 2020-10-22 12:40:30 +02:00
dietrich f2000c7650 remove erronous warning 2020-10-19 13:04:03 +02:00
dietrich d09f861ab0 add validation for usernames and groupnames 2020-10-19 12:14:00 +02:00
dietrich 7ec3bc3f0c first draft of username and groupname validation 2020-10-18 20:35:53 +02:00
dietrich 403f948c67 implement UserDbRead 2020-10-18 15:22:17 +02:00
dietrich 60bbe1ef1b add some documentation 2020-10-18 08:50:19 +02:00
dietrich abdb704ba0 remove duplicated code 2020-10-18 08:38:23 +02:00
dietrich ffafa7e473 Make the conten of shadow part of the user struct 2020-10-17 20:38:28 +02:00
dietrich 9482e85821 add rough api draft 2020-10-16 13:19:32 +02:00
dietrich 01a76b16a1 explicit types 2020-10-16 08:29:17 +02:00
dietrich f14d4b34ee fix some warnings 2020-10-09 12:11:23 +02:00
dietrich b6eb9972d2 restructuring
Fix (remove) lifetimes and restructure the code

Co-authored-by: Dietrich <dietrich@teilgedanken.de>
Reviewed-on: http://git.teilgedanken.de/Rust/useradd/pulls/2
2020-10-07 15:11:10 +00:00
dietrich 180934b789 Make shadow an entry of the passwd struct 2020-10-03 21:07:47 +02:00
dietrich 4af05c1134 initial parsing and testing for a shadow line 2020-10-03 15:18:45 +02:00
dietrich 4db597c058 initial parsing of shadow file 2020-10-02 18:13:15 +02:00
dietrich c6af13f3af Add is system user 2020-10-02 12:40:03 +02:00
dietrich 9b4956c78a Restructure the passwd file 2020-10-02 11:55:56 +02:00
dietrich 24db3e2579 Add warning on unconventional usernames 2020-10-02 09:50:02 +02:00
dietrich d4d3c0f0cf Merge pull request 'make the username part of the invalid message.' (#1) from local into master
Reviewed-on: http://git.teilgedanken.de/Rust/useradd/pulls/1
2020-10-02 07:46:59 +00:00
dietrich a95fa96d08 Adding a testcase for the ubuntu special user 2020-10-02 09:45:08 +02:00
dietrich b030045355 make the username part of the invalid message. 2020-10-02 09:45:08 +02:00
dietrich 063fb41708 restructure 2020-10-01 09:38:13 +02:00
dietrich 1ab0adbc06 user validation and tests 2020-09-30 20:58:24 +02:00
dietrich 5000fba6e7 doc update for enum Gecos 2020-09-30 18:23:44 +02:00
dietrich 676a5218e6 rename shell_dir -> shell_path 2020-09-30 18:02:02 +02:00
dietrich 2094bb7549 fix switched values 2020-09-30 17:35:39 +02:00
dietrich ee04fa30af Fix failing tests because ubuntu has no comment field 2020-09-30 11:09:43 +02:00
dietrich 0761afa6a0 ignore non ascii characters in tests 2020-09-30 08:40:19 +02:00
dietrich b72449eb88 partially fix clippy warnings regarding umlauts 2020-09-29 20:10:01 +02:00
dietrich 020a95920e Make the other field variable length, it can now be many fields or be missing entirely 2020-09-29 14:19:40 +02:00
32 changed files with 3827 additions and 535 deletions
+45
View File
@@ -0,0 +1,45 @@
name: Rust
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
env:
CARGO_TERM_COLOR: always
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Install latest nightly
uses: actions-rs/toolchain@v1
with:
toolchain: nightly
override: true
components: rustfmt, clippy
# `cargo check` command here will use installed `nightly`
# as it is set as an "override" for current directory
- name: Run cargo check
uses: actions-rs/cargo@v1
with:
command: check
- name: Annotate commit with clippy warnings
uses: actions-rs/clippy-check@v1
with:
token: ${{ secrets.GITHUB_TOKEN }}
args: --all-features -- -Wclippy::all -Wclippy::pedantic -Wclippy::nursery -Wclippy::cargo -Aclippy::non_ascii_literal -Aclippy::missing_errors_doc -Aclippy::multiple_crate_versions
- name: Run cargo Build
uses: actions-rs/cargo@v1
with:
command: build
- name: Run cargo test
uses: actions-rs/cargo@v1
with:
command: test
+1
View File
@@ -1,3 +1,4 @@
/target
.vscode
launch.json
*.orig
Generated
+572 -2
View File
@@ -1,5 +1,575 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
[[package]]
name = "adduser"
version = "0.1.0"
name = "aho-corasick"
version = "0.7.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7404febffaa47dac81aa44dba71523c9d069b1bdc50a77db41195149e17f68e5"
dependencies = [
"memchr",
]
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi",
]
[[package]]
name = "autocfg"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a"
[[package]]
name = "bitflags"
version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf1de2fe8c75bc145a2f577add951f8134889b4795d47466a54a5c846d691693"
[[package]]
name = "cfg-if"
version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822"
[[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 = "clap"
version = "3.0.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bd1061998a501ee7d4b6d449020df3266ca3124b941ec56cf2005c3779ca142"
dependencies = [
"atty",
"bitflags",
"clap_derive",
"indexmap",
"lazy_static",
"os_str_bytes",
"strsim 0.10.0",
"termcolor",
"textwrap",
"unicode-width",
"vec_map",
]
[[package]]
name = "clap_derive"
version = "3.0.0-beta.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "370f715b81112975b1b69db93e0b56ea4cd4e5002ac43b2da8474106a54096a1"
dependencies = [
"heck",
"proc-macro-error",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "darling"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d706e75d87e35569db781a9b5e2416cff1236a47ed380831f959382ccd5f858"
dependencies = [
"darling_core",
"darling_macro",
]
[[package]]
name = "darling_core"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0c960ae2da4de88a91b2d920c2a7233b400bc33cb28453a2987822d8392519b"
dependencies = [
"fnv",
"ident_case",
"proc-macro2",
"quote",
"strsim 0.9.3",
"syn",
]
[[package]]
name = "darling_macro"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b5a2f4ac4969822c62224815d069952656cadc7084fdca9751e6d959189b72"
dependencies = [
"darling_core",
"quote",
"syn",
]
[[package]]
name = "derive_builder"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2658621297f2cf68762a6f7dc0bb7e1ff2cfd6583daef8ee0fed6f7ec468ec0"
dependencies = [
"darling",
"derive_builder_core",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "derive_builder_core"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2791ea3e372c8495c0bc2033991d76b512cd799d07491fbd6890124db9458bef"
dependencies = [
"darling",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "env_logger"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54532e3223c5af90a6a757c90b5c5521564b07e5e7a958681bcd2afad421cdcd"
dependencies = [
"atty",
"humantime",
"log",
"regex",
"termcolor",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "getrandom"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc587bc0ec293155d5bfa6b9891ec18a1e330c234f896ea47fbada4cadbe47e6"
dependencies = [
"cfg-if",
"libc",
"wasi 0.9.0+wasi-snapshot-preview1",
]
[[package]]
name = "hashbrown"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7afe4a420e3fe79967a00898cc1f4db7c8a49a9333a29f8a4bd76a253d5cd04"
[[package]]
name = "heck"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205"
dependencies = [
"unicode-segmentation",
]
[[package]]
name = "hermit-abi"
version = "0.1.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aca5565f760fb5b220e499d72710ed156fdb74e631659e99377d9ebfbd13ae8"
dependencies = [
"libc",
]
[[package]]
name = "humantime"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c1ad908cc71012b7bea4d0c53ba96a8cba9962f048fa68d143376143d863b7a"
[[package]]
name = "ident_case"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
[[package]]
name = "indexmap"
version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "55e2e4c765aa53a0424761bf9f41aa7a6ac1efa87238f59560640e27fca028f2"
dependencies = [
"autocfg",
"hashbrown",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
[[package]]
name = "libc"
version = "0.2.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d58d1b70b004888f764dfbf6a26a3b0342a1632d33968e4a179d8011c760614"
[[package]]
name = "log"
version = "0.4.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fabed175da42fed1fa0746b0ea71f412aa9d35e76e95e59b192c64b9dc2bf8b"
dependencies = [
"cfg-if",
]
[[package]]
name = "memchr"
version = "2.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ee1c47aaa256ecabcaea351eae4a9b01ef39ed810004e298d2511ed284b1525"
[[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 = "os_str_bytes"
version = "2.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afb2e1c3ee07430c2cf76151675e583e0f19985fa6efae47d6848a3e2c824f85"
[[package]]
name = "ppv-lite86"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac74c624d6b2d21f425f752262f42188365d7b8ff1aff74c82e45136510a4857"
[[package]]
name = "proc-macro-error"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2",
"quote",
"version_check",
]
[[package]]
name = "proc-macro2"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e0704ee1a7e00d7bb417d0770ea303c1bccbabf0ef1667dae92b5967f5f8a71"
dependencies = [
"unicode-xid",
]
[[package]]
name = "quote"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa563d17ecb180e500da1cfd2b028310ac758de548efdd203e18f283af693f37"
dependencies = [
"proc-macro2",
]
[[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 = "redox_syscall"
version = "0.1.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41cc0f7e4d5d4544e8861606a285bb08d3e70712ccc7d2b84d7c0ccfaf4b05ce"
[[package]]
name = "regex"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38cf2c13ed4745de91a5eb834e11c00bcc3709e773173b2ce4c56c9fbde04b9c"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
"thread_local",
]
[[package]]
name = "regex-syntax"
version = "0.6.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b181ba2dcf07aaccad5448e8ead58db5b742cf85dfe035e2227f137a539a189"
[[package]]
name = "remove_dir_all"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7"
dependencies = [
"winapi",
]
[[package]]
name = "simplelog"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2b2736f58087298a448859961d3f4a0850b832e72619d75adc69da7993c2cd3c"
dependencies = [
"chrono",
"log",
"termcolor",
]
[[package]]
name = "strsim"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6446ced80d6c486436db5c078dde11a9f73d42b57fb273121e160b84f63d894c"
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "1.0.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc371affeffc477f42a221a1e4297aedcea33d47d19b61455588bd9d8f6b19ac"
dependencies = [
"proc-macro2",
"quote",
"unicode-xid",
]
[[package]]
name = "tempfile"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9"
dependencies = [
"cfg-if",
"libc",
"rand",
"redox_syscall",
"remove_dir_all",
"winapi",
]
[[package]]
name = "termcolor"
version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f"
dependencies = [
"winapi-util",
]
[[package]]
name = "test_bin"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1937bab04b0bd0f2c19628d3408fb6dd78faf5aa60f4bdb03212507a9b7314ba"
[[package]]
name = "textwrap"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "203008d98caf094106cfaba70acfed15e18ed3ddb7d94e49baec153a2b462789"
dependencies = [
"unicode-width",
]
[[package]]
name = "thread_local"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d40c6d1b69745a6ec6fb1ca717914848da4b44ae29d9b3080cbee91d72a69b14"
dependencies = [
"lazy_static",
]
[[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 = "umanux"
version = "0.1.1"
dependencies = [
"chrono",
"clap",
"derive_builder",
"env_logger",
"lazy_static",
"log",
"regex",
"simplelog",
"tempfile",
"test_bin",
]
[[package]]
name = "unicode-segmentation"
version = "1.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db8716a166f290ff49dabc18b44aa407cb7c6dbe1aa0971b44b8a24b0ca35aae"
[[package]]
name = "unicode-width"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9337591893a19b88d8d87f2cec1e73fad5cdfd10e5a6f349f498ad6ea2ffb1e3"
[[package]]
name = "unicode-xid"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7fe0bb3479651439c9112f72b6c505038574c9fbb575ed1bf3b797fa39dd564"
[[package]]
name = "vec_map"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bddf1187be692e79c5ffeab891132dfb0f236ed36a43c7ed39f1165ee20191"
[[package]]
name = "version_check"
version = "0.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5a972e5669d67ba988ce3dc826706fb0a8b01471c088cb0b6110b805cc36aed"
[[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-util"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178"
dependencies = [
"winapi",
]
[[package]]
name = "winapi-x86_64-pc-windows-gnu"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+26 -2
View File
@@ -1,9 +1,33 @@
[package]
name = "adduser"
version = "0.1.0"
name = "umanux"
version = "0.1.1"
description = "Library for managing Linux users and their directories"
authors = ["Dietrich <dietrich@teilgedanken.de>"]
edition = "2018"
license = "MIT OR Apache-2.0"
keywords = ["user", "admin", "linux", "manage", "passwd"]
categories = ["os", "os::linux-apis", "parser-implementations", "command-line-utilities"]
repository = "https://github.com/umanux/umanux"
readme = "README.md"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
regex = "1"
lazy_static = "1.4"
log = "0.4"
simplelog = "0.8"
chrono = "0.4"
env_logger = "0.8"
derive_builder = "0.9"
clap = "3.0.0-beta"
[dev-dependencies]
tempfile = "3.1"
test_bin= "0.3"
# optimize for size at cost of compilation speed.
[profile.release]
lto = true
codegen-units = 1
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2020 Franz Dietrich
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2020 Franz Dietrich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+51
View File
@@ -0,0 +1,51 @@
# **U**ser **MAN**ager for lin**UX**
### A Usermanager written in Rust
> This project is **very much** work in progress. Do **absolutely not** use in production systems!
When done this library intends to provide all the functionality needed to manage users on a linux system.
What is working so far:
* [x] Parsing:
* [x] `/etc/passwd`
* [x] `/etc/shadow` (root permission needed)
* [x] `/etc/group`
* Modifying:
* delete a user
* [x] passwd
* [x] shadow
* [X] group
* [x] own primary group
* [x] membership in other groups
* [x] home dir
* [x] delete
* [x] keep
* [ ] archive
* [ ] mail?
* [ ] multiple entries "Multiple entries named '%s' in %s. Please fix this with pwck or grpck."
* [ ] cancel jobs:
* [ ] cron
* [ ] at
* [ ] print
* create a user
- [x] passwd
- [x] shadow
- [ ] group
- [ ] own group
- [ ] home dir
- [ ] create from skeleton
- [ ] Skip
- [ ] create from directory
- [ ] mail?
- [ ] multiple entries (check uid duplication)
## License
Umanux is licensed under either of the following, at your option:
* Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
* MIT License ([LICENSE-MIT](LICENSE) or http://opensource.org/licenses/MIT)
`SPDX-License-Identifier: Apache-2.0 OR MIT`
+40
View File
@@ -0,0 +1,40 @@
#![allow(clippy::default_trait_access)]
use std::path::PathBuf;
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum CreateHome {
Create,
Skip,
HomeFromDir { path: PathBuf },
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum CreatePrimaryGroup {
Create,
Skip,
CreateIfEmptyOrAdd,
}
#[derive(Debug, Builder, Eq, PartialEq)]
#[builder(public)]
#[builder(default)]
pub struct CreateUserArgs<'a> {
pub username: &'a str,
pub delete_home: CreateHome,
pub delete_primary_group: CreatePrimaryGroup,
}
impl<'a> CreateUserArgs<'a> {
#[must_use]
pub fn builder() -> CreateUserArgsBuilder<'a> {
CreateUserArgsBuilder::default()
}
}
impl Default for CreateUserArgs<'_> {
fn default() -> Self {
Self {
username: "defaultuser",
delete_home: CreateHome::Create,
delete_primary_group: CreatePrimaryGroup::CreateIfEmptyOrAdd,
}
}
}
+40
View File
@@ -0,0 +1,40 @@
#![allow(clippy::default_trait_access)]
use std::path::PathBuf;
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum DeleteHome {
Delete,
Keep,
Archive { path: PathBuf },
}
#[derive(Debug, Clone, Eq, PartialEq)]
pub enum DeletePrimaryGroup {
Delete,
Keep,
DeleteIfEmpty,
}
#[derive(Debug, Builder, Eq, PartialEq)]
#[builder(public)]
#[builder(default)]
pub struct DeleteUserArgs<'a> {
pub username: &'a str,
pub delete_home: DeleteHome,
pub delete_primary_group: DeletePrimaryGroup,
}
impl<'a> DeleteUserArgs<'a> {
#[must_use]
pub fn builder() -> DeleteUserArgsBuilder<'a> {
DeleteUserArgsBuilder::default()
}
}
impl Default for DeleteUserArgs<'_> {
fn default() -> Self {
Self {
username: "defaultuser",
delete_home: DeleteHome::Keep,
delete_primary_group: DeletePrimaryGroup::DeleteIfEmpty,
}
}
}
+72
View File
@@ -0,0 +1,72 @@
pub mod createuser_args;
pub mod deleteuser_args;
pub use createuser_args::{CreateHome, CreatePrimaryGroup, CreateUserArgs};
pub use deleteuser_args::{DeleteHome, DeletePrimaryGroup, DeleteUserArgs};
pub trait UserDBRead {
fn get_all_users(&self) -> Vec<&crate::User>;
fn get_user_by_name(&self, name: &str) -> Option<&crate::User>;
fn get_user_by_id(&self, uid: u32) -> Option<&crate::User>;
fn get_all_groups(&self) -> Vec<crate::Group>;
fn get_group_by_name(&self, name: &str) -> Option<&crate::Group>;
fn get_group_by_id(&self, name: u32) -> Option<&crate::Group>;
}
pub trait UserDBValidation {
fn is_uid_valid_and_free(&self, uid: u32) -> bool;
fn is_username_valid_and_free(&self, name: &str) -> bool;
fn is_gid_valid_and_free(&self, gid: u32) -> bool;
fn is_groupname_valid_and_free(&self, name: &str) -> bool;
}
pub trait UserDBWrite {
fn delete_user(&mut self, params: DeleteUserArgs) -> Result<crate::User, crate::UserLibError>;
fn new_user(&mut self, params: CreateUserArgs) -> Result<&crate::User, crate::UserLibError>;
fn delete_group(&mut self, group: &crate::Group) -> Result<(), crate::UserLibError>;
fn new_group(&mut self) -> Result<&crate::Group, crate::UserLibError>;
}
pub trait UserRead {
fn get_username(&self) -> Option<&str>;
fn get_uid(&self) -> u32;
fn get_gid(&self) -> u32;
fn get_password(&self) -> Option<&str>;
fn get_gecos(&self) -> Option<&crate::Gecos>;
fn get_home_dir(&self) -> Option<&str>;
fn get_shell_path(&self) -> Option<&str>;
fn get_full_name(&self) -> Option<&str>;
fn get_room(&self) -> Option<&str>;
fn get_phone_work(&self) -> Option<&str>;
fn get_phone_home(&self) -> Option<&str>;
fn get_other(&self) -> Option<&Vec<String>>;
}
pub trait UserWrite {
fn set_username(&self, username: String);
fn set_uid(&self, uid: u32);
fn set_gid(&self, gid: u32);
fn set_password(&self, password: String);
fn set_gecos(&self, gecos: crate::Gecos);
fn set_home_dir(&self, home_dir: String);
fn set_shell_path(&self, shell_path: String);
fn set_full_name(&self, full_name: String);
fn set_room(&self, room: String);
fn set_phone_work(&self, phone_work: String);
fn set_phone_home(&self, phone_home: String);
fn set_other(&self, other: Option<Vec<String>>);
}
pub trait GroupRead {
fn get_groupname(&self) -> Option<&str>;
fn get_encrypted_password(&self) -> Option<&str>;
fn get_gid(&self) -> Option<u32>;
fn get_member_names(&self) -> Option<Vec<&str>>;
}
pub trait GroupWrite<T> {
fn set_groupname(&self) -> Option<crate::Group>;
fn set_password(&self) -> Option<crate::Group>;
fn set_gid(&self) -> Option<crate::Group>;
fn add_member(user: T) -> Option<crate::Group>;
fn remove_member(user: T) -> Option<crate::Group>;
}
+69
View File
@@ -0,0 +1,69 @@
use std::path::PathBuf;
extern crate clap;
use clap::{App, Arg};
extern crate umanux;
use umanux::{api::UserDBWrite, UserLibError};
fn main() -> Result<(), UserLibError> {
env_logger::init();
let matches = App::new("Create a new linux user")
.version("0.1.0")
.author("Franz Dietrich <dietrich@teilgedanken.de>")
.about("Create a linux user do not use this in production (yet)")
.arg(
Arg::new("username")
.value_name("USERNAME")
.about("the new users name")
.takes_value(true)
.required(true),
)
.arg(
Arg::new("passwd")
.short('p')
.long("passwd")
.value_name("FILE")
.about("The passwd file")
.default_value("/etc/passwd")
.takes_value(true),
)
.arg(
Arg::new("shadow")
.short('s')
.long("shadow")
.value_name("FILE")
.about("The shadow file")
.default_value("/etc/shadow")
.takes_value(true),
)
.arg(
Arg::new("group")
.short('g')
.long("group")
.value_name("FILE")
.about("The group file")
.default_value("/etc/group")
.takes_value(true),
)
.get_matches();
let mf = umanux::Files {
passwd: Some(PathBuf::from(matches.value_of("passwd").unwrap())),
shadow: Some(PathBuf::from(matches.value_of("shadow").unwrap())),
group: Some(PathBuf::from(matches.value_of("group").unwrap())),
};
let mut db = umanux::UserDBLocal::load_files(mf).unwrap();
match db.new_user(
umanux::api::CreateUserArgs::builder()
.username(matches.value_of("username").unwrap())
// .delete_home(umanux::api::DeleteHome::Delete)
.build()
.unwrap(),
) {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
+37
View File
@@ -0,0 +1,37 @@
use std::path::PathBuf;
extern crate umanux;
use umanux::api::UserDBWrite;
use umanux::api::UserRead;
extern crate env_logger;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
fn main() {
env_logger::init();
let mf = umanux::Files {
passwd: Some(PathBuf::from("./passwd")),
shadow: Some(PathBuf::from("./shadow")),
group: Some(PathBuf::from("./group")),
};
let mut db = umanux::UserDBLocal::load_files(mf).unwrap();
let user_res: Result<umanux::User, umanux::UserLibError> = db.delete_user(
umanux::api::DeleteUserArgs::builder()
.username("teste")
// .delete_home(umanux::api::DeleteHome::Delete)
.build()
.unwrap(),
);
match user_res {
Ok(u) => info!(
"The user <{}> has been deleted! ",
u.get_username().unwrap()
),
Err(e) => error!("Failed to delete the user: {}", e),
}
}
-21
View File
@@ -1,21 +0,0 @@
extern crate adduser;
use adduser::passwd::Passwd;
use std::fs::File;
use std::io::{prelude::*, BufReader};
fn main() {
let file = File::open("/etc/passwd").unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
println!("{}", Passwd::new_from_string(&line.unwrap()).unwrap());
}
// let pwd = Passwd::default();
// let pwd2 =
// Passwd::new_from_string("howdy:notencrypted:1001:1001:not done:/home/test:/bin/bash");
// println!("Test struct: {}", pwd);
// assert_eq!(pwd, pwd2.unwrap())
}
+36
View File
@@ -0,0 +1,36 @@
extern crate umanux;
use umanux::api::GroupRead;
use umanux::api::UserDBRead;
fn main() {
simplelog::CombinedLogger::init(vec![simplelog::TermLogger::new(
simplelog::LevelFilter::Warn,
simplelog::Config::default(),
simplelog::TerminalMode::Mixed,
)])
.unwrap();
let db = umanux::UserDBLocal::load_files(umanux::Files::default()).unwrap();
for u in db.get_all_users() {
println!("{}", u);
println!(
"Groups: {:?}",
u.get_groups()
.iter()
.map(|group| {
(
format!("{:?}", group.0),
group.1.borrow().get_groupname().unwrap().to_owned(),
)
})
.collect::<Vec<(String, String)>>()
);
}
for group in db.get_all_groups() {
let gp = group.borrow();
println!("{}", gp);
println!("{:?}", gp.get_member_names())
}
}
+106
View File
@@ -0,0 +1,106 @@
use std::error::Error;
use std::fmt::{self, Display};
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, PartialEq)]
pub enum ParseError {
Username,
Password,
Uid,
Gid,
Gecos,
HomeDir,
ShellDir,
}
#[allow(clippy::module_name_repetitions)]
#[derive(Debug, PartialEq)]
pub enum UserLibError {
NotFound,
ParseError,
FilesChanged,
FilesRequired,
Message(MyMessage),
}
#[derive(Debug)]
pub enum MyMessage {
Simple(String),
IOError(String, std::io::Error),
}
impl PartialEq for MyMessage {
fn eq(&self, other: &Self) -> bool {
format!("{}", self).eq(&format!("{}", other))
}
}
impl Display for MyMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Simple(m) => write!(f, "{}", m),
Self::IOError(m, e) => write!(f, "{},{}", m, e),
}
}
}
impl Display for UserLibError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::NotFound => write!(f, "not found"),
Self::ParseError => write!(f, "failed to parse"),
Self::FilesRequired => write!(
f,
"File locking is only possible if some files are specified"
),
Self::FilesChanged => write!(
f,
"The files changed. Updating could lead to conflict aborting."
),
Self::Message(message) => write!(f, "{}", message),
}
}
}
impl Error for UserLibError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match *self {
Self::NotFound
| Self::ParseError
| Self::FilesChanged
| Self::FilesRequired
| Self::Message(MyMessage::Simple(_)) => None,
Self::Message(MyMessage::IOError(_, ref e)) => Some(e),
}
}
}
impl From<&str> for UserLibError {
fn from(err: &str) -> Self {
Self::Message(MyMessage::Simple(err.to_owned()))
}
}
impl From<String> for UserLibError {
fn from(err: String) -> Self {
Self::Message(MyMessage::Simple(err))
}
}
impl From<std::io::Error> for UserLibError {
fn from(e: std::io::Error) -> Self {
Self::Message(MyMessage::Simple(e.to_string()))
}
}
impl From<(String, std::io::Error)> for UserLibError {
fn from((m, e): (String, std::io::Error)) -> Self {
Self::Message(MyMessage::IOError(m, e))
}
}
/*
impl From<(String, Error)> for UserLibError {
fn from((m, e): (String, Error)) -> Self {
UserLibError::Message(MyMessage::IOError(m, e))
}
}*/
+208
View File
@@ -0,0 +1,208 @@
#![allow(clippy::non_ascii_literal)]
use crate::userlib::NewFromString;
use log::warn;
use crate::UserLibError;
use std::fmt::{self, Debug, Display};
use std::{cell::RefCell, convert::TryFrom};
use std::{cmp::Eq, rc::Rc};
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum MembershipKind {
Primary,
Member,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Membership {
kind: MembershipKind,
username: crate::Username,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Groupname {
groupname: String,
}
impl Display for Groupname {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.groupname,)
}
}
impl TryFrom<String> for Groupname {
type Error = UserLibError;
fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
if is_groupname_valid(&source) {
Ok(Self { groupname: source })
} else if source == "Debian-exim" {
warn!("username {} is not a valid username. This might cause problems. (It is default in Debian and Ubuntu)", source);
Ok(Self { groupname: source })
} else {
Err(format!("Invalid groupname -{}-", source).into())
}
}
}
pub(crate) fn is_groupname_valid(name: &str) -> bool {
// for now just use the username validation.
crate::user::passwd_fields::is_username_valid(name)
}
pub type Group = Rc<RefCell<Inner>>;
/// A record(line) in the user database `/etc/shadow` found in most linux systems.
#[derive(Debug, PartialEq, Eq)]
pub struct Inner {
pos: u32,
source: String,
groupname: Groupname, /* Username. */
pub(crate) password: crate::Password, /* Usually not used (disabled with x) */
gid: crate::Gid, /* Group ID. */
members: Vec<Membership>, /* Real name. */
}
impl Inner {
#[must_use]
pub fn remove_in(&self, content: &str) -> String {
content
.split(&self.source)
.map(str::trim)
.collect::<Vec<&str>>()
.join("\n")
}
pub(super) fn append_user(&mut self, username: &str) {
self.members.push(Membership {
kind: MembershipKind::Primary,
username: crate::Username {
username: username.to_owned(),
},
})
}
pub(super) fn remove_member(&mut self, kind: MembershipKind, username: &str) {
self.members
.retain(|u| !(u.username.username == username && u.kind == kind))
}
}
use crate::api::GroupRead;
impl GroupRead for Inner {
#[must_use]
fn get_groupname(&self) -> Option<&str> {
Some(&self.groupname.groupname)
}
#[must_use]
fn get_member_names(&self) -> Option<Vec<&str>> {
let mut r: Vec<&str> = Vec::new();
for u in &self.members {
r.push(&u.username.username);
}
Some(r)
}
fn get_gid(&self) -> Option<u32> {
Some(self.gid.get_gid())
}
fn get_encrypted_password(&self) -> Option<&str> {
todo!()
}
}
impl Display for Inner {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
f,
"{}:{}:{}:{}",
self.groupname,
self.password,
self.gid,
self.members
.iter()
.filter_map(|mem| if mem.kind == MembershipKind::Member {
Some(format!("{}", mem.username))
} else {
None
})
.collect::<Vec<String>>()
.join(",")
)
}
}
impl NewFromString for Group {
/// Parse a line formatted like one in `/etc/group` and construct a matching [`Group`] instance
///
/// # Example
/// ```
/// use crate::umanux::api::GroupRead;
/// use umanux::NewFromString;
/// let grp = umanux::Group::new_from_string(
/// "teste:x:1002:test,teste".to_owned(),
/// 0,
/// ).unwrap();
/// assert_eq!(grp.borrow().get_groupname().unwrap(), "teste");
/// ```
///
/// # Errors
/// When parsing fails this function returns a `UserLibError::Message` containing some information as to why the function failed.
fn new_from_string(line: String, position: u32) -> Result<Self, UserLibError> {
let elements: Vec<String> = line.split(':').map(ToString::to_string).collect();
if elements.len() == 4 {
Ok(Self::new(RefCell::new(Inner {
pos: position,
source: line,
groupname: Groupname::try_from(elements.get(0).unwrap().to_string())?,
password: crate::Password::Disabled,
gid: crate::Gid::try_from(elements.get(2).unwrap().to_string())?,
members: parse_members_list(elements.get(3).unwrap()),
})))
} else {
Err(format!(
"Failed to parse: not enough elements ({}): {:?}",
elements.len(),
elements
)
.into())
}
}
}
fn parse_members_list(source: &str) -> Vec<Membership> {
let mut res = vec![];
for mem in source.split(',').filter_map(|x| {
if x.is_empty() {
None
} else {
Some(x.to_string())
}
}) {
res.push(Membership {
kind: MembershipKind::Member,
username: crate::Username::try_from(mem).expect("failed to parse username"),
});
}
res
}
#[test]
fn test_parse_and_back_identity() {
let line = "teste:x:1002:test,teste";
let line2: Group = Group::new_from_string(line.to_owned(), 0).unwrap();
assert_eq!(format!("{}", line2.borrow()), line);
}
#[test]
fn test_groupname() {
let line = "teste:x:1002:test,teste";
let line2 = Group::new_from_string(line.to_owned(), 0).unwrap();
assert_eq!(line2.borrow().get_groupname().unwrap(), "teste");
}
#[test]
fn test_root_group() {
let line = "root:x:0:";
let line2 = Group::new_from_string(line.to_owned(), 0).unwrap();
assert_eq!(line2.borrow().get_groupname().unwrap(), "root");
}
+32 -3
View File
@@ -1,3 +1,32 @@
pub mod passwd;
pub mod userlib_error;
pub use passwd::{Password, Username};
#![warn(
clippy::all,
//clippy::restriction,
clippy::pedantic,
clippy::nursery,
clippy::cargo
)]
//#![allow(clippy::non_ascii_literal)]
#![allow(clippy::missing_errors_doc)]
#![allow(clippy::clippy::multiple_crate_versions)]
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate derive_builder;
extern crate log;
pub mod api;
pub mod error;
pub mod group;
pub mod user;
pub mod userlib;
pub use error::UserLibError;
pub use group::Group;
pub use user::gecos_fields::Gecos;
pub use user::passwd_fields::{
EncryptedPassword, Gid, HomeDir, Password, ShellPath, Uid, Username,
};
pub use user::shadow_fields::Shadow;
pub use user::User;
pub use userlib::{files::Files, NewFromString, UserDBLocal};
-461
View File
@@ -1,461 +0,0 @@
#![warn(
clippy::all,
/* clippy::restriction,*/
clippy::pedantic,
clippy::nursery,
clippy::cargo
)]
use crate::userlib_error::UserLibError;
use std::cmp::Eq;
use std::convert::TryFrom;
use std::fmt::{self, Display};
/// The username of the current user
///
/// When done the validity will automatically be checked in the `trait TryFrom`.
///
/// In the future some extra fields might be added.
#[derive(Debug, PartialEq, Eq)]
pub struct Username<'a> {
/// The username value
username: &'a str,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Password<'a> {
password: &'a str,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Uid {
uid: u32,
}
#[derive(Debug, PartialEq, Eq)]
pub struct Gid {
gid: u32,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Gecos<'a> {
Detail {
full_name: &'a str,
room: &'a str,
phone_work: &'a str,
phone_home: &'a str,
other: &'a str,
},
Simple {
comment: &'a str,
},
}
#[derive(Debug, PartialEq, Eq)]
pub struct HomeDir<'a> {
dir: &'a str,
}
#[derive(Debug, PartialEq, Eq)]
pub struct ShellDir<'a> {
shell: &'a str,
}
/// A record in the user database `/etc/passwd`.
#[derive(Debug, PartialEq, Eq)]
pub struct Passwd<'a> {
username: Username<'a>, /* Username. */
password: Password<'a>, /* Hashed passphrase, if shadow database not in use (see shadow.h). */
uid: Uid, /* User ID. */
gid: Gid, /* Group ID. */
gecos: Gecos<'a>, /* Real name. */
home_dir: HomeDir<'a>, /* Home directory. */
shell_dir: ShellDir<'a>, /* Shell program. */
}
impl<'a> Passwd<'a> {
/// Parse a line formatted like one in `/etc/passwd` and construct a matching `Passwd` instance
///
/// # Example
/// ```
/// let pwd = adduser::passwd::Passwd::new_from_string(
/// "testuser:testpassword:1001:1001:full Name,,,,:/home/test:/bin/test"
/// ).unwrap();
/// assert_eq!(pwd.get_username(), "testuser");
/// ```
///
/// # Errors
/// When parsing fails this function returns a `UserLibError::Message` containing some information as to why the function failed.
pub fn new_from_string(line: &'a str) -> Result<Self, UserLibError> {
let elements: Vec<&str> = line.split(':').collect();
if elements.len() == 7 {
Ok(Passwd {
username: Username::try_from(*elements.get(0).unwrap())?,
password: Password::try_from(*elements.get(1).unwrap())?,
uid: Uid::try_from(*elements.get(2).unwrap())?,
gid: Gid::try_from(*elements.get(3).unwrap())?,
gecos: Gecos::try_from(*elements.get(4).unwrap())?,
home_dir: HomeDir::try_from(*elements.get(5).unwrap())?,
shell_dir: ShellDir::try_from(*elements.get(6).unwrap())?,
})
} else {
Err("Failed to parse: not enough elements".into())
}
}
#[must_use]
pub const fn get_username(&self) -> &'a str {
self.username.username
}
#[must_use]
pub const fn get_password(&self) -> &'a str {
self.password.password
}
#[must_use]
pub const fn get_uid(&self) -> u32 {
self.uid.uid
}
#[must_use]
pub const fn get_gid(&self) -> u32 {
self.gid.gid
}
#[must_use]
pub const fn get_comment(&self) -> &Gecos {
&self.gecos
}
#[must_use]
pub const fn get_home_dir(&self) -> &'a str {
self.home_dir.dir
}
#[must_use]
pub const fn get_shell_dir(&self) -> &'a str {
self.shell_dir.shell
}
}
impl<'a> Gecos<'a> {
#[must_use]
pub const fn get_comment(&'a self) -> Option<&'a str> {
match *self {
Gecos::Simple { comment, .. } => Some(comment),
Gecos::Detail { .. } => None,
}
}
#[must_use]
pub const fn get_full_name(&'a self) -> Option<&'a str> {
match *self {
Gecos::Simple { .. } => None,
Gecos::Detail { full_name, .. } => Some(full_name),
}
}
#[must_use]
pub const fn get_room(&'a self) -> Option<&'a str> {
match *self {
Gecos::Simple { .. } => None,
Gecos::Detail { room, .. } => Some(room),
}
}
#[must_use]
pub const fn get_phone_work(&'a self) -> Option<&'a str> {
match *self {
Gecos::Simple { .. } => None,
Gecos::Detail { phone_work, .. } => Some(phone_work),
}
}
#[must_use]
pub const fn get_phone_home(&'a self) -> Option<&'a str> {
match *self {
Gecos::Simple { .. } => None,
Gecos::Detail { phone_home, .. } => Some(phone_home),
}
}
#[must_use]
pub const fn get_other(&'a self) -> Option<&'a str> {
match *self {
Gecos::Simple { .. } => None,
Gecos::Detail { other, .. } => Some(other),
}
}
}
impl Default for Passwd<'_> {
fn default() -> Self {
Passwd {
username: Username {
username: "defaultuser",
},
password: Password {
password: "notencrypted",
},
uid: Uid { uid: 1001 },
gid: Gid { gid: 1001 },
gecos: Gecos::Simple {
comment: "gecos default comment",
},
home_dir: HomeDir {
dir: "/home/default",
},
shell_dir: ShellDir { shell: "/bin/bash" },
}
}
}
impl Display for Passwd<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}:{}:{}:{}:{}:{}:{}",
self.username,
self.password,
self.uid,
self.gid,
self.gecos,
self.home_dir,
self.shell_dir
)
}
}
impl Display for Username<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.username,)
}
}
impl<'a> TryFrom<&'a str> for Username<'a> {
type Error = UserLibError;
fn try_from(source: &'a str) -> std::result::Result<Self, Self::Error> {
Ok(Self { username: source })
}
}
impl Display for Password<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.password,)
}
}
impl<'a> TryFrom<&'a str> for Password<'a> {
type Error = UserLibError;
fn try_from(source: &'a str) -> std::result::Result<Self, Self::Error> {
Ok(Self { password: source })
}
}
impl Display for Uid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.uid,)
}
}
impl TryFrom<&str> for Uid {
type Error = UserLibError;
fn try_from(source: &str) -> std::result::Result<Self, Self::Error> {
Ok(Self {
uid: source.parse::<u32>().unwrap(),
})
}
}
impl Display for Gid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.gid,)
}
}
impl TryFrom<&str> for Gid {
type Error = UserLibError;
fn try_from(source: &str) -> std::result::Result<Self, Self::Error> {
Ok(Self {
gid: source.parse::<u32>().unwrap(),
})
}
}
impl Display for Gecos<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self {
Gecos::Simple { comment } => write!(f, "{}", comment),
Gecos::Detail {
full_name,
room,
phone_work,
phone_home,
other,
} => write!(
f,
"{},{},{},{},{}",
full_name, room, phone_work, phone_home, other
),
}
}
}
impl<'a> TryFrom<&'a str> for Gecos<'a> {
type Error = UserLibError;
fn try_from(source: &'a str) -> std::result::Result<Self, Self::Error> {
let vals: Vec<&str> = source.split(',').collect();
if vals.len() == 5 {
Ok(Gecos::Detail {
full_name: vals.get(0).unwrap(),
room: vals.get(1).unwrap(),
phone_work: vals.get(2).unwrap(),
phone_home: vals.get(3).unwrap(),
other: vals.get(4).unwrap(),
})
} else if vals.len() == 4 {
Ok(Gecos::Detail {
full_name: vals.get(0).unwrap(),
room: vals.get(1).unwrap(),
phone_work: vals.get(2).unwrap(),
phone_home: vals.get(3).unwrap(),
other: "",
})
} else if vals.len() == 1 {
Ok(Gecos::Simple {
comment: vals.get(0).unwrap(),
})
} else {
panic!(format!("Could not parse this string: {}", source))
}
}
}
impl Display for HomeDir<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.dir,)
}
}
impl<'a> TryFrom<&'a str> for HomeDir<'a> {
type Error = UserLibError;
fn try_from(source: &'a str) -> std::result::Result<Self, Self::Error> {
Ok(Self { dir: source })
}
}
impl Display for ShellDir<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.shell,)
}
}
impl<'a> TryFrom<&'a str> for ShellDir<'a> {
type Error = UserLibError;
fn try_from(source: &'a str) -> std::result::Result<Self, Self::Error> {
Ok(Self { shell: source })
}
}
// Tests ----------------------------------------------------------------------
#[test]
fn test_default_user() {
// Check if a user can be created.
let pwd = Passwd::default();
assert_eq!(pwd.username.username, "defaultuser");
assert_eq!(pwd.home_dir.dir, "/home/default");
assert_eq!(pwd.uid.uid, 1001);
}
#[test]
fn test_parse_gecos() {
// test if the Gecos field can be parsed and the resulting struct is populated correctly.
let gcdetail = "Full Name,504,11345342,ä1-2312,myemail@test.com";
let gcsimple = "A böring comment →";
let gc_no_other: &str = "systemd Network Management,,,";
let res_detail = Gecos::try_from(gcdetail).unwrap();
let res_simple = Gecos::try_from(gcsimple).unwrap();
let res_no_other = Gecos::try_from(gc_no_other).unwrap();
match res_simple {
Gecos::Simple { comment } => assert_eq!(comment, "A böring comment →"),
_ => unreachable!(),
}
match res_detail {
Gecos::Detail {
full_name,
room,
phone_work,
phone_home,
other,
} => {
assert_eq!(full_name, "Full Name");
assert_eq!(room, "504");
assert_eq!(phone_work, "11345342");
assert_eq!(phone_home, "ä1-2312");
assert_eq!(other, "myemail@test.com");
}
_ => unreachable!(),
}
match res_no_other {
Gecos::Detail {
full_name,
room,
phone_work,
phone_home,
other,
} => {
assert_eq!(full_name, "systemd Network Management");
assert_eq!(room, "");
assert_eq!(phone_work, "");
assert_eq!(phone_home, "");
assert_eq!(other, "");
}
_ => unreachable!(),
}
}
#[test]
fn test_new_from_string() {
// Test if a single line can be parsed and if the resulting struct is populated correctly.
let fail = Passwd::new_from_string("").err().unwrap();
assert_eq!(
fail,
UserLibError::Message("Failed to parse: not enough elements".into())
);
let pwd =
Passwd::new_from_string("testuser:testpassword:1001:1001:testcomment:/home/test:/bin/test")
.unwrap();
let pwd2 =
Passwd::new_from_string("testuser:testpassword:1001:1001:full Name,004,000342,001-2312,myemail@test.com:/home/test:/bin/test")
.unwrap();
assert_eq!(pwd.username.username, "testuser");
assert_eq!(pwd.home_dir.dir, "/home/test");
assert_eq!(pwd.uid.uid, 1001);
match pwd.gecos {
Gecos::Simple { comment } => assert_eq!(comment, "testcomment"),
_ => unreachable!(),
}
match pwd2.gecos {
Gecos::Detail {
full_name,
room,
phone_work,
phone_home,
other,
} => {
assert_eq!(full_name, "full Name");
assert_eq!(room, "004");
assert_eq!(phone_work, "000342");
assert_eq!(phone_home, "001-2312");
assert_eq!(other, "myemail@test.com");
}
_ => unreachable!(),
}
}
#[test]
fn test_parse_passwd() {
// Test wether the passwd file can be parsed and recreated without throwing an exception
use std::fs::File;
use std::io::{prelude::*, BufReader};
let file = File::open("/etc/passwd").unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
let lineorig: String = line.unwrap();
assert_eq!(
// ignoring the numbers of `,` since the implementation does not (yet) reproduce a missing comment field.
format!("{}", Passwd::new_from_string(&lineorig.clone()).unwrap()).replace(",", ""),
lineorig.replace(",", "")
);
}
}
+225
View File
@@ -0,0 +1,225 @@
#![allow(clippy::non_ascii_literal)]
use crate::UserLibError;
use std::cmp::Eq;
use std::convert::TryFrom;
use std::fmt::{self, Display};
/// The gecos field of a user.
///
/// In the `/etc/passwd` file this field is a `,` sepparated list of items.
/// The first 4 values are more or less standardised to be full name, room, phone at work and phone at home. After that there can be some extra fields often containing the emailadress and even additional information.
///
/// This enum represents the first 4 values by name and adds the other values to a list of strings [`Gecos::Detail`]. If only one field is found and no `,` at all this value is used as a human readable comment [`Gecos::Simple`].
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Gecos {
Detail {
full_name: String,
room: String,
phone_work: String,
phone_home: String,
other: Option<Vec<String>>,
},
Simple {
comment: String,
},
}
impl Gecos {
#[must_use]
pub fn get_comment(&self) -> Option<&str> {
match &self {
Self::Simple { comment, .. } => Some(comment),
Self::Detail { .. } => None,
}
}
#[must_use]
pub fn get_full_name(&self) -> Option<&str> {
match &self {
Self::Simple { .. } => None,
Self::Detail { full_name, .. } => {
if full_name.is_empty() {
None
} else {
Some(full_name)
}
}
}
}
#[must_use]
pub fn get_room(&self) -> Option<&str> {
match &self {
Self::Simple { .. } => None,
Self::Detail { room, .. } => {
if room.is_empty() {
None
} else {
Some(room)
}
}
}
}
#[must_use]
pub fn get_phone_work(&self) -> Option<&str> {
match &self {
Self::Simple { .. } => None,
Self::Detail { phone_work, .. } => {
if phone_work.is_empty() {
None
} else {
Some(phone_work)
}
}
}
}
#[must_use]
pub fn get_phone_home(&self) -> Option<&str> {
match &self {
Self::Simple { .. } => None,
Self::Detail { phone_home, .. } => {
if phone_home.is_empty() {
None
} else {
Some(phone_home)
}
}
}
}
#[must_use]
pub const fn get_other(&self) -> Option<&Vec<String>> {
match self {
Self::Simple { .. } => None,
Self::Detail { other, .. } => match other {
None => None,
Some(comments) => Some(comments),
},
}
}
}
impl Display for Gecos {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self {
Self::Simple { comment } => write!(f, "{}", comment),
Self::Detail {
full_name,
room,
phone_work,
phone_home,
other,
} => write!(
f,
"{},{},{},{}{}",
full_name,
room,
phone_work,
phone_home,
match other {
None => "".to_string(),
Some(cont) => format!(",{}", cont.join(",")),
}
),
}
}
}
impl TryFrom<String> for Gecos {
type Error = UserLibError;
fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
let vals: Vec<String> = source.split(',').map(ToString::to_string).collect();
if vals.len() > 3 {
Ok(Self::Detail {
full_name: vals[0].clone(),
room: vals[1].clone(),
phone_work: vals[2].clone(),
phone_home: vals[3].clone(),
other: if vals.len() == 4 {
None
} else {
Some(vals[4..].to_vec())
},
})
} else if vals.len() == 1 {
Ok(Self::Simple {
comment: vals.get(0).unwrap().into(),
})
} else {
panic!(format!("Could not parse this string: {}", source))
}
}
}
#[test]
fn test_parse_gecos() {
// test if the Gecos field can be parsed and the resulting struct is populated correctly.
let gcdetail = "Full Name,504,11345342,ä1-2312,myemail@test.com".to_string();
let gcsimple = "A böring comment →".to_string();
let gc_no_other = "systemd Network Management,,,".to_string();
let res_detail = crate::Gecos::try_from(gcdetail).unwrap();
let res_simple = crate::Gecos::try_from(gcsimple).unwrap();
let res_no_other = crate::Gecos::try_from(gc_no_other).unwrap();
match res_simple {
crate::Gecos::Simple { comment } => assert_eq!(comment, "A böring comment →"),
_ => unreachable!(),
}
match res_detail {
crate::Gecos::Detail {
full_name,
room,
phone_work,
phone_home,
other,
} => {
assert_eq!(full_name, "Full Name");
assert_eq!(room, "504");
assert_eq!(phone_work, "11345342");
assert_eq!(phone_home, "ä1-2312");
assert_eq!(other.unwrap()[0], "myemail@test.com");
}
_ => unreachable!(),
}
match res_no_other {
crate::Gecos::Detail {
full_name,
room,
phone_work,
phone_home,
other,
} => {
assert_eq!(full_name, "systemd Network Management");
assert_eq!(room, "");
assert_eq!(phone_work, "");
assert_eq!(phone_home, "");
assert_eq!(other, None);
}
_ => unreachable!(),
}
}
#[test]
fn test_gecos_getters() {
// test if the Gecos field can be parsed and the resulting struct is populated correctly.
let gcdetail = "Full Name,504,11345342,ä1-2312,myemail@test.com".to_string();
let gcsimple = "A böring comment →".to_string();
let gc_no_other = "systemd Network Management,,,".to_string();
let res_detail = crate::Gecos::try_from(gcdetail).unwrap();
let res_simple = crate::Gecos::try_from(gcsimple).unwrap();
let res_no_other = crate::Gecos::try_from(gc_no_other).unwrap();
assert_eq!(res_simple.get_comment(), Some("A böring comment →"));
assert_eq!(res_detail.get_comment(), None);
assert_eq!(res_detail.get_full_name(), Some("Full Name"));
assert_eq!(res_detail.get_room(), Some("504"));
assert_eq!(res_detail.get_phone_work(), Some("11345342"));
assert_eq!(res_detail.get_phone_home(), Some("ä1-2312"));
assert_eq!(
res_detail.get_other(),
Some(&vec!["myemail@test.com".to_string()])
);
assert_eq!(
res_no_other.get_full_name(),
Some("systemd Network Management")
);
assert_eq!(res_no_other.get_room(), None);
assert_eq!(res_no_other.get_phone_work(), None);
assert_eq!(res_no_other.get_phone_home(), None);
assert_eq!(res_no_other.get_other(), None);
}
+312
View File
@@ -0,0 +1,312 @@
pub mod gecos_fields;
pub mod passwd_fields;
pub mod shadow_fields;
use crate::userlib::NewFromString;
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use std::convert::TryFrom;
use std::fmt::{self, Display};
/// A record(line) in the user database `/etc/passwd` found in most linux systems.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct User {
source: String,
pos: u32,
username: crate::Username, /* Username. */
pub(crate) password: crate::Password, /* Hashed passphrase, if shadow database not in use (see shadow.h). */
uid: crate::Uid, /* User ID. */
gid: crate::Gid, /* Group ID. */
gecos: crate::Gecos, /* Real name. */
home_dir: crate::HomeDir, /* Home directory. */
shell_path: crate::ShellPath, /* Shell program. */
groups: Vec<(crate::group::MembershipKind, crate::Group)>,
}
impl User {
#[must_use]
pub const fn get_shadow(&self) -> Option<&crate::Shadow> {
match self.password {
crate::Password::Encrypted(_) | crate::Password::Disabled => None,
crate::Password::Shadow(ref s) => Some(s),
}
}
#[must_use]
pub fn remove_in(&self, content: &str) -> String {
content
.split(&self.source)
.map(str::trim)
.collect::<Vec<&str>>()
.join("\n")
}
pub fn username(&mut self, name: String) -> &mut Self {
self.username = crate::Username { username: name };
if let crate::Password::Shadow(ref mut s) = self.password {
s.set_username(self.username.clone());
}
self
}
pub fn disable_password(&mut self) -> &mut Self {
self.password = crate::Password::Disabled;
self
}
pub fn uid(&mut self, uid: u32) -> &mut Self {
self.uid = crate::Uid { uid };
self
}
pub fn gid(&mut self, gid: u32) -> &mut Self {
self.gid = crate::Gid { gid };
self
}
pub fn home_dir(&mut self, path: String) -> &mut Self {
self.home_dir = crate::HomeDir { dir: path };
self
}
pub fn shell_path(&mut self, path: String) -> &mut Self {
self.shell_path = crate::ShellPath { shell: path };
self
}
pub fn add_group(
&mut self,
group_type: crate::group::MembershipKind,
group: crate::Group,
) -> &mut Self {
self.groups.push((group_type, group));
self
}
#[must_use]
pub const fn get_groups(&self) -> &Vec<(crate::group::MembershipKind, crate::Group)> {
&self.groups
}
}
impl NewFromString for User {
/// Parse a line formatted like one in `/etc/passwd` and construct a matching [`User`] instance
///
/// # Example
/// ```
/// use crate::umanux::api::UserRead;
/// use umanux::NewFromString;
/// let pwd = umanux::User::new_from_string(
/// "testuser:testpassword:1001:1001:full Name,,,,:/home/test:/bin/test".to_string(), 0).unwrap();
/// assert_eq!(pwd.get_username().unwrap(), "testuser");
/// ```
///
/// # Errors
/// When parsing fails this function returns a [`UserLibError::Message`](crate::userlib_error::UserLibError::Message) containing some information as to why the function failed.
fn new_from_string(line: String, position: u32) -> Result<Self, crate::UserLibError>
where
Self: Sized,
{
let elements: Vec<String> = line.split(':').map(ToString::to_string).collect();
if elements.len() == 7 {
Ok(Self {
source: line,
pos: position,
username: crate::Username::try_from(elements.get(0).unwrap().to_string())?,
password: crate::Password::Encrypted(crate::EncryptedPassword::try_from(
elements.get(1).unwrap().to_string(),
)?),
uid: crate::Uid::try_from(elements.get(2).unwrap().to_string())?,
gid: crate::Gid::try_from(elements.get(3).unwrap().to_string())?,
gecos: crate::Gecos::try_from(elements.get(4).unwrap().to_string())?,
home_dir: crate::HomeDir::try_from(elements.get(5).unwrap().to_string())?,
shell_path: crate::ShellPath::try_from(elements.get(6).unwrap().to_string())?,
groups: Vec::new(),
})
} else {
Err("Failed to parse: not enough elements".into())
}
}
}
impl crate::api::UserRead for User {
#[must_use]
fn get_username(&self) -> Option<&str> {
Some(&self.username.username)
}
#[must_use]
fn get_password(&self) -> Option<&str> {
match &self.password {
crate::Password::Encrypted(crate::EncryptedPassword { password }) => Some(password),
crate::Password::Shadow(crate::Shadow { ref password, .. }) => Some(&password.password),
crate::Password::Disabled => None,
}
}
#[must_use]
fn get_uid(&self) -> u32 {
self.uid.uid
}
#[must_use]
fn get_gid(&self) -> u32 {
self.gid.gid
}
#[must_use]
fn get_gecos(&self) -> Option<&crate::Gecos> {
Some(&self.gecos)
}
#[must_use]
fn get_home_dir(&self) -> Option<&str> {
Some(&self.home_dir.dir)
}
#[must_use]
fn get_shell_path(&self) -> Option<&str> {
Some(&self.shell_path.shell)
}
#[must_use]
fn get_full_name(&self) -> Option<&str> {
self.gecos.get_full_name()
}
#[must_use]
fn get_room(&self) -> Option<&str> {
self.gecos.get_room()
}
#[must_use]
fn get_phone_work(&self) -> Option<&str> {
self.gecos.get_phone_work()
}
#[must_use]
fn get_phone_home(&self) -> Option<&str> {
self.gecos.get_phone_home()
}
#[must_use]
fn get_other(&self) -> Option<&Vec<String>> {
self.gecos.get_other()
}
}
impl PartialOrd for User {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.pos.cmp(&other.pos))
}
}
impl Ord for User {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.pos.cmp(&other.pos)
}
}
impl Default for User {
fn default() -> Self {
let username = passwd_fields::Username {
username: "defaultusername".to_owned(),
};
let line = "defaultusername:!!:0:0:99999:7:::";
let password = passwd_fields::Password::Shadow(
shadow_fields::Shadow::new_from_string(line.to_owned(), u32::MAX).unwrap(),
);
Self {
source: "".to_owned(),
pos: u32::MAX,
username,
password,
uid: crate::Uid { uid: 1001 },
gid: crate::Gid { gid: 1001 },
gecos: crate::Gecos::Simple {
comment: "".to_string(),
},
home_dir: crate::HomeDir {
dir: "/".to_owned(),
},
shell_path: crate::ShellPath {
shell: "/bin/nologin".to_owned(),
},
groups: Vec::new(),
}
}
}
impl Display for User {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}:{}:{}:{}:{}:{}:{}",
self.username,
self.password,
self.uid,
self.gid,
self.gecos,
self.home_dir,
self.shell_path
)
}
}
#[test]
fn test_default_user() {
// Check if a user can be created.
let mut pwd = User::default();
assert_eq!(pwd.username.username, "defaultusername");
assert_eq!(pwd.home_dir.dir, "/");
assert_eq!(pwd.uid.uid, 1001);
let npw = pwd.username("test".to_owned()).clone();
assert_eq!(npw.username.username, "test");
}
#[test]
fn test_new_from_string() {
// Test if a single line can be parsed and if the resulting struct is populated correctly.
let fail = User::new_from_string("".into(), 0).err().unwrap();
assert_eq!(fail, "Failed to parse: not enough elements".into());
let pwd = User::new_from_string(
"testuser:testpassword:1001:1001:testcomment:/home/test:/bin/test".into(),
0,
)
.unwrap();
let pwd2 =
User::new_from_string("testuser:testpassword:1001:1001:full Name,004,000342,001-2312,myemail@test.com:/home/test:/bin/test".into(),0)
.unwrap();
assert_eq!(pwd.username.username, "testuser");
assert_eq!(pwd.home_dir.dir, "/home/test");
assert_eq!(pwd.uid.uid, 1001);
match pwd.gecos {
crate::Gecos::Simple { comment } => assert_eq!(comment, "testcomment"),
_ => unreachable!(),
}
match pwd2.gecos {
crate::Gecos::Detail {
full_name,
room,
phone_work,
phone_home,
other,
} => {
assert_eq!(full_name, "full Name");
assert_eq!(room, "004");
assert_eq!(phone_work, "000342");
assert_eq!(phone_home, "001-2312");
assert_eq!(other.unwrap()[0], "myemail@test.com");
}
_ => unreachable!(),
}
}
#[test]
fn test_parse_passwd() {
// Test wether the passwd file can be parsed and recreated without throwing an exception
use std::convert::TryInto;
use std::fs::File;
use std::io::{prelude::*, BufReader};
let file = File::open("/etc/passwd").unwrap();
let reader = BufReader::new(file);
for (n, line) in reader.lines().enumerate() {
let lineorig: String = line.unwrap();
let linecopy = lineorig.clone();
let pass_struc = User::new_from_string(linecopy, n.try_into().unwrap()).unwrap();
assert_eq!(
// ignoring the numbers of `,` since the implementation does not (yet) reproduce a missing comment field.
lineorig,
format!("{}", pass_struc)
);
}
}
+229
View File
@@ -0,0 +1,229 @@
#![allow(clippy::non_ascii_literal)]
use log::warn;
use regex::Regex;
use crate::UserLibError;
use std::cmp::Eq;
use std::convert::TryFrom;
use std::fmt::{self, Display};
/// The username of the current user
///
/// When done the validity will automatically be checked in the `trait TryFrom`.
///
/// In the future some extra fields might be added.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Username {
/// The username value
pub(crate) username: String,
}
impl Display for Username {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.username,)
}
}
impl TryFrom<String> for Username {
type Error = UserLibError;
fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
if is_username_valid(&source) {
Ok(Self { username: source })
} else if source == "Debian-exim" {
warn!("username {} is not a valid username. This might cause problems. (It is default in Debian and Ubuntu)", source);
Ok(Self { username: source })
} else {
Err(format!("Invalid username {}", source).into())
}
}
}
pub(crate) fn is_username_valid(name: &str) -> bool {
lazy_static! {
static ref USERVALIDATION: Regex =
Regex::new("^[a-z_]([a-z0-9_\\-]{0,31}|[a-z0-9_\\-]{0,30}\\$)$").unwrap();
}
USERVALIDATION.is_match(name)
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub enum Password {
Encrypted(crate::EncryptedPassword),
Shadow(crate::Shadow),
Disabled,
}
impl Display for Password {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Encrypted(EncryptedPassword { password }) => write!(f, "{}", password,),
Self::Shadow(_) | Self::Disabled => write!(f, "x"),
}
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct EncryptedPassword {
pub(in crate::user) password: String,
}
impl Display for EncryptedPassword {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.password,)
}
}
impl TryFrom<String> for EncryptedPassword {
type Error = UserLibError;
fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
/*if source == "x" {
//warn!("password from shadow not loaded!")
} else {
//warn!("Password field has an unexpected value")
};*/
Ok(Self { password: source })
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Uid {
pub(in crate::user) uid: u32,
}
impl Display for Uid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.uid,)
}
}
impl TryFrom<String> for Uid {
type Error = UserLibError;
fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
Ok(Self {
uid: source.parse::<u32>().unwrap(),
})
}
}
impl Uid {
#[must_use]
pub const fn is_system_uid(&self) -> bool {
// since it is a u32 it cannot be smaller than 0
self.uid < 1000
}
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Gid {
pub(in crate::user) gid: u32,
}
impl Display for Gid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.gid,)
}
}
impl TryFrom<String> for Gid {
type Error = UserLibError;
fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
Ok(Self {
gid: source.parse::<u32>().unwrap(),
})
}
}
impl Gid {
#[must_use]
pub const fn is_system_gid(&self) -> bool {
// since it is a u32 it cannot be smaller than 0
self.gid < 1000
}
#[must_use]
pub const fn get_gid(&self) -> u32 {
self.gid
}
}
/// The home directory of a user
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct HomeDir {
pub(in crate::user) dir: String,
}
impl Display for HomeDir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.dir,)
}
}
impl TryFrom<String> for HomeDir {
type Error = UserLibError;
fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
Ok(Self { dir: source })
}
}
/// The path to the Shell binary
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct ShellPath {
pub(in crate::user) shell: String,
}
impl Display for ShellPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.shell,)
}
}
impl TryFrom<String> for ShellPath {
type Error = UserLibError;
fn try_from(source: String) -> std::result::Result<Self, Self::Error> {
Ok(Self { shell: source })
}
}
// Tests ----------------------------------------------------------------------
#[test]
fn test_username_validation() {
// Failing tests
let umlauts: Result<Username, UserLibError> = Username::try_from("täst".to_owned()); // umlauts
assert_eq!(Err("Invalid username täst".into()), umlauts);
let number_first = Username::try_from("11elf".to_owned()); // numbers first
assert_eq!(Err("Invalid username 11elf".into()), number_first);
let slashes = Username::try_from("test/name".to_owned()); // slashes in the name
assert_eq!(Err("Invalid username test/name".into()), slashes);
let long = Username::try_from("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".to_owned()); // maximum size 32 letters
assert_eq!(
Err("Invalid username aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into()),
long
);
// Working tests
let ubuntu_exception = Username::try_from("Debian-exim".to_owned()); // for some reason ubuntu and debian have a capital user.
assert_eq!(ubuntu_exception.unwrap().username, "Debian-exim");
let single = Username::try_from("t".to_owned()); // single characters are ok
assert_eq!(single.unwrap().username, "t");
let normal = Username::try_from("superman".to_owned()); // regular username
assert_eq!(normal.unwrap().username, "superman");
let normal = Username::try_from("anna3pete".to_owned()); // regular username containing a number
assert_eq!(normal.unwrap().username, "anna3pete");
let normal = Username::try_from("enya$".to_owned()); // regular username ending in a $
assert_eq!(normal.unwrap().username, "enya$");
}
#[test]
fn test_guid_system_user() {
// Check uids of system users.
let values = vec![
("999".to_owned(), true),
("0".to_owned(), true),
("1000".to_owned(), false),
];
for val in values {
assert_eq!(Uid::try_from(val.0.clone()).unwrap().is_system_uid(), val.1);
assert_eq!(Gid::try_from(val.0.clone()).unwrap().is_system_gid(), val.1);
}
}
+158
View File
@@ -0,0 +1,158 @@
use crate::userlib::NewFromString;
use crate::UserLibError;
use std::cmp::Eq;
use std::convert::TryFrom;
use std::fmt::{self, Debug, Display};
/// A record(line) in the user database `/etc/shadow` found in most linux systems.
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct Shadow {
pos: u32,
source: String,
username: crate::Username, /* Username. */
pub(crate) password: crate::EncryptedPassword, /* Hashed passphrase */
last_change: Option<chrono::NaiveDateTime>, /* User ID. */
earliest_change: Option<chrono::NaiveDateTime>, /* Group ID. */
latest_change: Option<chrono::NaiveDateTime>, /* Real name. */
warn_period: Option<chrono::Duration>, /* Home directory. */
deactivated: Option<chrono::Duration>, /* Shell program. */
deactivated_since: Option<chrono::Duration>, /* Shell program. */
extensions: Option<u64>, /* Shell program. */
}
impl Shadow {
#[must_use]
pub fn get_username(&self) -> &str {
&self.username.username
}
pub fn set_username(&mut self, username: crate::Username) {
self.username = username;
}
#[must_use]
pub fn get_password(&self) -> &str {
&self.password.password
}
#[must_use]
pub fn remove_in(&self, content: &str) -> String {
content
.split(&self.source)
.map(str::trim)
.collect::<Vec<&str>>()
.join("\n")
}
}
impl Display for Shadow {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
write!(
f,
"{}:{}:{}:{}:{}:{}:{}:{}:{}",
self.username,
self.password,
show_option_date(self.last_change),
show_option_date(self.earliest_change),
show_option_date(self.latest_change),
show_option_duration(self.warn_period),
show_option_duration(self.deactivated),
show_option_duration(self.deactivated_since),
if self.extensions.is_none() {
"".to_string()
} else {
self.extensions.unwrap().to_string()
}
)
}
}
fn show_option_date(input: Option<chrono::NaiveDateTime>) -> String {
if input.is_none() {
"".into()
} else {
format!("{}", input.unwrap().timestamp() / SECONDS_PER_DAY)
}
}
fn show_option_duration(input: Option<chrono::Duration>) -> String {
if input.is_none() {
"".into()
} else {
format!("{}", input.unwrap().num_days())
}
}
impl NewFromString for Shadow {
/// Parse a line formatted like one in `/etc/shadow` and construct a matching `Shadow` instance
///
/// # Example
/// ```
/// use umanux::NewFromString;
/// let shad = umanux::Shadow::new_from_string(
/// "test:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18260:0:99999:7:::".to_string(),
/// 0,
/// ).unwrap();
/// assert_eq!(shad.get_username(), "test");
/// ```
///
/// # Errors
/// When parsing fails this function returns a `UserLibError::Message` containing some information as to why the function failed.
fn new_from_string(line: String, position: u32) -> Result<Self, UserLibError> {
let elements: Vec<String> = line.split(':').map(ToString::to_string).collect();
if elements.len() == 9 {
let extra = elements.get(8).unwrap();
Ok(Self {
pos: position,
source: line,
username: crate::Username::try_from(elements.get(0).unwrap().to_string())?,
password: crate::EncryptedPassword::try_from(elements.get(1).unwrap().to_string())?,
last_change: date_since_epoch(elements.get(2).unwrap()),
earliest_change: date_since_epoch(elements.get(3).unwrap()),
latest_change: date_since_epoch(elements.get(4).unwrap()),
warn_period: duration_for_days(elements.get(5).unwrap()),
deactivated: duration_for_days(elements.get(6).unwrap()),
deactivated_since: duration_for_days(elements.get(7).unwrap()),
extensions: if extra.is_empty() {
None
} else {
Some(extra.parse::<u64>().unwrap())
},
})
} else {
Err(format!(
"Failed to parse: not enough elements ({}): {:?}",
elements.len(),
elements
)
.into())
}
}
}
const SECONDS_PER_DAY: i64 = 86400;
fn date_since_epoch(days_since_epoch: &str) -> Option<chrono::NaiveDateTime> {
if days_since_epoch.is_empty() {
None
} else {
let days: i64 = days_since_epoch.parse::<i64>().unwrap();
let seconds = days * SECONDS_PER_DAY;
Some(chrono::NaiveDateTime::from_timestamp(seconds, 0))
}
}
fn duration_for_days(days_source: &str) -> Option<chrono::Duration> {
if days_source.is_empty() {
None
} else {
let days: i64 = days_source.parse::<i64>().unwrap();
Some(chrono::Duration::days(days))
}
}
#[test]
fn test_parse_and_back_identity() {
let line = "test:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18260:0:99999:7:::";
let line2 = Shadow::new_from_string(line.to_owned(), 0).unwrap();
assert_eq!(format!("{}", line2), line);
}
+275
View File
@@ -0,0 +1,275 @@
use std::{io::Seek, io::SeekFrom, path::PathBuf};
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use std::fs::{File, OpenOptions};
use std::io::Read;
use std::io::Write;
use std::ops::Deref;
#[derive(Debug)]
pub struct Files {
pub passwd: Option<PathBuf>,
pub shadow: Option<PathBuf>,
pub group: Option<PathBuf>,
}
impl Default for Files {
/// use the default Linux `/etc/` paths
fn default() -> Self {
Self {
passwd: Some(PathBuf::from("/etc/passwd")),
shadow: Some(PathBuf::from("/etc/shadow")),
group: Some(PathBuf::from("/etc/group")),
}
}
}
impl Files {
/// Check if all the files are defined. Because some operations require the files to be present
#[must_use]
pub const fn is_virtual(&self) -> bool {
!(self.group.is_some() & self.passwd.is_some() & self.shadow.is_some())
}
pub fn lock_and_get_passwd(&self) -> Result<LockedFileGuard, crate::UserLibError> {
let path = self.passwd.as_ref();
match path {
Some(p) => LockedFileGuard::new(p),
None => Err(crate::UserLibError::FilesRequired),
}
}
pub fn lock_and_get_shadow(&self) -> Result<LockedFileGuard, crate::UserLibError> {
let path = self.shadow.as_ref();
match path {
Some(p) => LockedFileGuard::new(p),
None => Err(crate::UserLibError::FilesRequired),
}
}
pub fn lock_and_get_group(&self) -> Result<LockedFileGuard, crate::UserLibError> {
let path = self.group.as_ref();
match path {
Some(p) => LockedFileGuard::new(p),
None => Err(crate::UserLibError::FilesRequired),
}
}
pub fn lock_all_get(
&self,
) -> Result<(LockedFileGuard, LockedFileGuard, LockedFileGuard), crate::UserLibError> {
let pwd = self.lock_and_get_passwd()?;
let shd = self.lock_and_get_shadow()?;
let grp = self.lock_and_get_group()?;
Ok((pwd, shd, grp))
}
}
#[derive(Debug)]
pub struct LockedFileGuard {
lockfile: PathBuf,
path: PathBuf,
pub(crate) file: File,
}
#[derive(Debug)]
struct TempLockFile {
tlf: PathBuf,
}
impl Drop for TempLockFile {
fn drop(&mut self) {
info!("removing temporary lockfile {}", self.tlf.to_str().unwrap());
std::fs::remove_file(&self.tlf).unwrap();
}
}
impl Deref for TempLockFile {
type Target = PathBuf;
fn deref(&self) -> &PathBuf {
&self.tlf
}
}
impl LockedFileGuard {
pub fn new(path: &PathBuf) -> Result<Self, crate::UserLibError> {
let locked = Self::try_to_lock_file(path);
match locked {
Ok((lockfile, file)) => Ok(Self {
lockfile,
path: path.to_owned(),
file,
}),
Err(e) => Err(e),
}
}
pub fn replace_contents(&mut self, new_content: String) -> Result<(), crate::UserLibError> {
self.file = match File::create(&self.path) {
Ok(file) => file,
Err(e) => return Err(("Failed to truncate file.".to_owned(), e).into()),
};
match self.file.write_all(&new_content.into_bytes()) {
Ok(_) => (),
Err(e) => return Err(("Could not write (all) users. ".to_owned(), e).into()),
};
let _ = self.file.write(b"\n");
Ok(())
}
pub fn append(&mut self, appendee: String) -> Result<(), crate::UserLibError> {
// Seek to the last character.
self.file.seek(SeekFrom::End(-1)).map_or_else(
|e| Err(format!("Failed to append to file {}", e)),
|_| Ok(()),
)?;
// Read the last character
let mut b = [0_u8; 1];
self.file.read_exact(&mut b)?;
// Verify it is '\n' else append '\n' so in any case the file ends with with a newline now
if &b != b"\n" {
//self.file.write_all(&b)?;
self.file.write_all(b"\n")?;
}
// write the new line.
self.file.write_all(&appendee.into_bytes()).map_or_else(
|e| Err(("Failed to append to file".to_owned(), e).into()),
Ok,
)
}
/// This function tries to lock a file in the way other passwd locking mechanisms work.
///
/// * get the pid
/// * create the temporary lockfilepath "/etc/passwd.12397"
/// * create the lockfilepath "/etc/passwd.lock"
/// * open the temporary file
/// * write the pid to the tempfile
/// * try to make a link from the temporary file created to the lockfile
/// * ensure that the file has been linked successfully
///
/// when the link could not be created:
///
/// * Open the lockfile
/// * read the contents of the lockfile
/// * check if the lockfile contains a pid if not error out
/// * check if the containing pid is in a valid format. If not create a matching error
///
/// not implemented yet:
///
/// * test if this process could be killed. If so disclose the pid in the error.
/// * try to delete the lockfile as it is apparently not used by the process anmore. (cleanup)
/// * try to lock again now that the old logfile has been safely removed.
/// * remove the original file and only keep the lock hardlink
fn try_to_lock_file(path: &PathBuf) -> Result<(PathBuf, File), crate::UserLibError> {
info!("locking file {}", path.to_string_lossy());
let mut tempfilepath_const = path.clone();
// get the pid
let pid = std::process::id();
debug!("using pid {}", std::process::id());
// get the filename
let filename = tempfilepath_const.file_name().unwrap().to_owned();
// and the base path which is the base for tempfile and lockfile.
tempfilepath_const.pop();
let mut lockfilepath = tempfilepath_const.clone();
// push the filenames to the paths
tempfilepath_const.push(format!("{}.{}", filename.to_str().unwrap(), pid));
let tempfilepath = TempLockFile {
tlf: tempfilepath_const,
};
lockfilepath.push(format!("{}.lock", filename.to_str().unwrap()));
debug!(
"Lockfile paths: {:?} (temporary) {:?} (final)",
*tempfilepath, lockfilepath
);
// write the pid into the tempfile
{
let mut tempfile = File::create(&*tempfilepath).unwrap_or_else(|e| {
panic!("Failed to open {} error: {}", filename.to_str().unwrap(), e)
});
write!(tempfile, "{}", pid).or_else(|e| {
let error_msg = format!(
"could not write to {} error {}",
filename.to_string_lossy(),
e
);
error!("{}", error_msg);
let err: crate::UserLibError = error_msg.into();
Err(err)
})?;
}
// try to make a hardlink from the lockfile to the tempfile
let linkresult = std::fs::hard_link(&*tempfilepath, &lockfilepath);
match linkresult {
Ok(()) => {
debug!("successfully locked");
// open the file
let resfile = OpenOptions::new().read(true).write(true).open(&path);
return match resfile {
Ok(file) => Ok((lockfilepath, file)),
Err(e) => {
// failed to open the file undo the locks
let _ = std::fs::remove_file(&lockfilepath);
let ret: crate::UserLibError = format!(
"Failed to open the file: {}, error: {}",
path.to_str().unwrap(),
e
)
.into();
Err(ret)
}
};
}
Err(e) => match e.kind() {
// analyze the error further
std::io::ErrorKind::AlreadyExists => {
warn!("The file is already locked by another process! testing the validity of the lock");
{
let mut lf = match File::open(&lockfilepath) {
Ok(file) => file,
Err(e) => {
panic!("failed to open the lockfile: {}", e);
}
};
let mut content = String::new();
lf.read_to_string(&mut content)
.unwrap_or_else(|e| panic!("failed to read the lockfile{}", e));
let content = content.trim().trim_matches(char::from(0));
let lock_pid = content.parse::<u32>();
match lock_pid {
Ok(pid) => {
warn!(
"found a pid: {}, checking if this process is still running",
pid
);
error!("The file could not be locked");
todo!("Validate the lock and delete the file if the process does not exist anymore");
/*let sent = nix::sys::signal::kill(
nix::unistd::Pid::from_raw(pid as i32),
nix::sys::signal::Signal::from(0),
);*/
}
Err(e) => error!(
"existing lock file {} with an invalid PID '{}' Error: {}",
lockfilepath.to_str().unwrap(),
content,
e
),
}
}
}
_ => {
panic!("failed to lock the file: {}", e);
}
},
}
Err("was not able to lock!".into())
}
}
impl Drop for LockedFileGuard {
fn drop(&mut self) {
info!("removing lock");
std::fs::remove_file(&self.lockfile).unwrap();
}
}
+40
View File
@@ -0,0 +1,40 @@
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
pub struct SourceHash {
hashvalue: String,
}
impl SourceHash {
#[must_use]
pub fn new(src: &str) -> Self {
Self {
hashvalue: src.to_owned(),
}
}
#[must_use]
pub fn has_changed(&self, new: &str) -> bool {
trace!(
"Old and new lengths: {}, {}",
self.hashvalue.len(),
new.len()
);
!self.hashvalue.eq(new)
}
}
pub struct Hashes {
pub passwd: SourceHash,
pub shadow: SourceHash,
pub group: SourceHash,
}
impl Hashes {
#[must_use]
pub fn new(passwd: &str, shadow: &str, group: &str) -> Self {
Self {
passwd: SourceHash::new(passwd),
shadow: SourceHash::new(shadow),
group: SourceHash::new(group),
}
}
}
+605
View File
@@ -0,0 +1,605 @@
#![allow(clippy::non_ascii_literal)]
pub mod files;
pub mod hashes;
use crate::{
api::{
CreateUserArgs, DeleteHome, DeleteUserArgs, GroupRead, UserDBRead, UserDBWrite, UserRead,
},
group::MembershipKind,
UserLibError,
};
#[allow(unused_imports)]
use log::{debug, error, info, trace, warn};
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufReader, Read};
pub type UserList = HashMap<String, crate::User>;
pub struct UserDBLocal {
source_files: files::Files,
source_hashes: hashes::Hashes, // to detect changes
pub users: UserList,
pub groups: Vec<crate::Group>,
}
impl UserDBLocal {
/// Import the database from strings
#[must_use]
pub fn import_from_strings(
passwd_content: &str,
shadow_content: &str,
group_content: &str,
) -> Self {
let shadow_entries: Vec<crate::Shadow> = string_to(shadow_content);
let mut users = user_vec_to_hashmap(string_to(passwd_content));
let mut groups = string_to(group_content);
shadow_to_users(&mut users, shadow_entries);
groups_to_users(&mut users, &mut groups);
Self {
source_files: files::Files {
passwd: None,
group: None,
shadow: None,
},
users,
groups,
source_hashes: hashes::Hashes::new(passwd_content, shadow_content, group_content),
}
}
/// Import the database from a [`Files`] struct
pub fn load_files(files: files::Files) -> Result<Self, crate::UserLibError> {
// Get the Strings for the files use an inner block to drop references after read.
let (my_passwd_lines, my_shadow_lines, my_group_lines) = {
let opened = files.lock_all_get();
let (locked_p, locked_s, locked_g) = opened.expect("failed to lock files!");
// read the files to strings
let p = file_to_string(&locked_p.file)?;
let s = file_to_string(&locked_s.file)?;
let g = file_to_string(&locked_g.file)?;
// return the strings to the outer scope and release the lock...
(p, s, g)
};
let mut users = user_vec_to_hashmap(string_to(&my_passwd_lines));
let passwds: Vec<crate::Shadow> = string_to(&my_shadow_lines);
let mut groups: Vec<crate::Group> = string_to(&my_group_lines);
shadow_to_users(&mut users, passwds);
groups_to_users(&mut users, &mut groups);
Ok(Self {
source_files: files,
users,
groups,
source_hashes: hashes::Hashes::new(&my_passwd_lines, &my_shadow_lines, &my_group_lines),
})
}
fn delete_from_passwd(
user: &crate::User,
passwd_file_content: &str,
locked_p: &mut files::LockedFileGuard,
) -> Result<(), UserLibError> {
let modified_p = user.remove_in(passwd_file_content);
// write the new content to the file.
let ncont = locked_p.replace_contents(modified_p);
match ncont {
Ok(_) => Ok(()),
Err(e) => Err(format!("Failed to write the passwd database: {}", e).into()),
}
}
fn delete_from_shadow(
user: &crate::User,
shadow_file_content: &str,
locked_s: &mut files::LockedFileGuard,
) -> Result<(), UserLibError> {
let shad = user.get_shadow();
match shad {
Some(shadow) => {
let modified_s = shadow.remove_in(shadow_file_content);
let ncont = locked_s.replace_contents(modified_s);
match ncont {
Ok(_) => Ok(()),
Err(e) => Err(format!(
"Error during write to the database. \
Please doublecheck as the shadowdatabase could be corrupted: {}",
e,
)
.into()),
}
}
None => Ok(()),
}
}
fn delete_from_group(
group: &crate::Group,
group_file_content: &str,
locked_g: &mut files::LockedFileGuard,
) -> Result<(), UserLibError> {
let modified_g = group.borrow().remove_in(group_file_content);
let replace_result = locked_g.replace_contents(modified_g);
match replace_result {
Ok(_) => Ok(()),
Err(e) => Err(format!(
"Error during write to the database. \
Please doublecheck as the groupdatabase could be corrupted: {}",
e,
)
.into()),
}
}
fn write_groups(&self, locked_g: &mut files::LockedFileGuard) -> Result<(), UserLibError> {
let content = self
.groups
.iter()
.map(|g| (g.borrow().to_string()))
.collect::<Vec<String>>()
.join("\n");
let replace_result = locked_g.replace_contents(content);
match replace_result {
Ok(_) => Ok(()),
Err(e) => Err(format!(
"Error during write to the database. \
Please doublecheck as the groupdatabase could be corrupted: {}",
e,
)
.into()),
}
}
fn delete_home(user: &crate::User) -> std::io::Result<()> {
if let Some(dir) = user.get_home_dir() {
std::fs::remove_dir_all(dir)
} else {
let error_msg = "Failed to remove the home directory! As the user did not have one.";
error!("{}", error_msg);
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
error_msg,
))
}
}
fn delete_group_by_id(&mut self, gid: u32) {
self.groups
.retain(|g| g.borrow().get_gid().expect("groups have to have a gid") != gid);
}
}
impl UserDBWrite for UserDBLocal {
fn delete_user(&mut self, args: DeleteUserArgs) -> Result<crate::User, UserLibError> {
// try to get the user from the database
let user_opt = self.get_user_by_name(args.username);
let user = match user_opt {
Some(user) => user,
None => {
return Err(UserLibError::NotFound);
}
};
if self.source_files.is_virtual() {
warn!("There are no associated files working in dummy mode!");
let res = self.users.remove(args.username);
match res {
Some(u) => Ok(u),
None => Err(UserLibError::NotFound), // should not happen anymore as existence is checked.
}
} else {
let opened = self.source_files.lock_all_get();
let (mut locked_p, mut locked_s, mut locked_g) = opened.expect("failed to lock files!");
// read the files to strings
let passwd_file_content = file_to_string(&locked_p.file)?;
let shadow_file_content = file_to_string(&locked_s.file)?;
let group_file_content = file_to_string(&locked_g.file)?;
let src = &self.source_hashes;
if src.passwd.has_changed(&passwd_file_content)
| src.shadow.has_changed(&shadow_file_content)
{
error!("The source files have changed. Deleting the user could corrupt the userdatabase. Aborting!");
Err(format!("The userdatabase has been changed {}", args.username).into())
} else {
Self::delete_from_passwd(user, &passwd_file_content, &mut locked_p)?;
Self::delete_from_shadow(user, &shadow_file_content, &mut locked_s)?;
if args.delete_home == DeleteHome::Delete {
Self::delete_home(user)?;
}
trace!("The users groups: {:#?}", user.get_groups());
// Iterate over the GIDs to avoid borrowing issues
let users_groups: Vec<(MembershipKind, u32)> = user
.get_groups()
.iter()
.map(|(k, g)| (*k, g.borrow().get_gid().unwrap()))
.collect();
for (kind, group) in users_groups {
trace!("Woring on group: {:?} - {}", kind, group);
match kind {
crate::group::MembershipKind::Primary => {
if self
.get_group_by_id(group)
.expect("The group does not exist")
.borrow()
.get_member_names()
.expect("this group allways has a member")
.len()
== 1
{
trace!(
"Deleting group as the user to be deleted is the only member {}", self
.get_group_by_id(group)
.expect("The group does not exist")
.borrow()
.get_groupname().expect("a group has to have a name")
);
Self::delete_from_group(
self.get_group_by_id(group)
.expect("The group does not exist"),
&group_file_content,
&mut locked_g,
)?;
self.delete_group_by_id(group);
} else {
// remove the from the group instead of deleting the group if he was not the only user in its primary group.
if let Some(group) = self.get_group_by_id(group) {
group
.borrow_mut()
.remove_member(MembershipKind::Primary, args.username)
};
self.write_groups(&mut locked_g)?;
warn!(
"The primary group (GID: {}) was not empty and is thus not removed. Only the membership has been removed",
group
);
}
}
crate::group::MembershipKind::Member => {
trace!("delete the membership in the group");
if let Some(group) = self.get_group_by_id(group) {
group
.borrow_mut()
.remove_member(MembershipKind::Member, args.username)
};
self.write_groups(&mut locked_g)?;
}
}
}
// Remove the user from the memory database(HashMap)
let res = self.users.remove(args.username);
match res {
Some(u) => Ok(u),
None => Err("Failed to remove the user from the internal HashMap".into()),
}
}
}
}
fn new_user(&mut self, args: CreateUserArgs) -> Result<&crate::User, crate::UserLibError> {
if self.users.contains_key(args.username) {
Err(format!("The username {} already exists! Aborting!", args.username).into())
} else {
let mut new_user = crate::User::default();
new_user.username(args.username.to_owned());
if self.users.contains_key(args.username) {
Err("Failed to create the user. A user with the same Name already exists".into())
} else {
let opened = self.source_files.lock_all_get();
let (mut locked_p, mut locked_s, mut _locked_g) =
opened.expect("failed to lock files!");
//dbg!(&locked_p);
locked_p.append(format!("{}", new_user))?;
if let Some(shadow) = new_user.get_shadow() {
info!("Adding shadow entry {}", shadow);
locked_s.append(format!("{}", shadow))?;
} else {
warn!("Omitting shadow entry!")
}
assert!(self
.users
.insert(args.username.to_owned(), new_user)
.is_none());
self.users
.get(args.username)
.map_or_else(|| Err("User was not successfully added!".into()), Ok)
}
}
}
fn delete_group(&mut self, _group: &crate::Group) -> Result<(), crate::UserLibError> {
todo!()
}
fn new_group(&mut self) -> Result<&crate::Group, crate::UserLibError> {
todo!()
}
}
impl UserDBRead for UserDBLocal {
fn get_all_users(&self) -> Vec<&crate::User> {
let mut res: Vec<&crate::User> = self.users.iter().map(|(_, x)| x).collect();
res.sort();
res
}
fn get_user_by_name(&self, name: &str) -> Option<&crate::User> {
self.users.get(name)
}
fn get_user_by_id(&self, uid: u32) -> Option<&crate::User> {
// could probably be more efficient - on the other hand its no problem to loop a thousand users.
for user in self.users.values() {
if user.get_uid() == uid {
return Some(user);
}
}
None
}
fn get_all_groups(&self) -> Vec<crate::Group> {
self.groups.iter().map(std::clone::Clone::clone).collect()
}
fn get_group_by_name(&self, name: &str) -> Option<&crate::Group> {
for group in &self.groups {
if group.borrow().get_groupname()? == name {
return Some(group);
}
}
None
}
fn get_group_by_id(&self, id: u32) -> Option<&crate::Group> {
for group in &self.groups {
if group.borrow().get_gid()? == id {
return Some(group);
}
}
None
}
}
use crate::api::UserDBValidation;
impl UserDBValidation for UserDBLocal {
fn is_uid_valid_and_free(&self, uid: u32) -> bool {
warn!("No valid check, only free check");
let free = self.users.iter().all(|(_, u)| u.get_uid() != uid);
free
}
fn is_username_valid_and_free(&self, name: &str) -> bool {
let valid = crate::user::passwd_fields::is_username_valid(name);
let free = self.get_user_by_name(name).is_none();
valid && free
}
fn is_gid_valid_and_free(&self, gid: u32) -> bool {
warn!("No valid check, only free check");
self.groups
.iter()
.all(|x| x.borrow().get_gid().unwrap() != gid)
}
fn is_groupname_valid_and_free(&self, name: &str) -> bool {
let valid = crate::group::is_groupname_valid(name);
let free = self
.groups
.iter()
.all(|x| x.borrow().get_groupname().unwrap() != name);
valid && free
}
}
/// Parse a file to a string
fn file_to_string(file: &File) -> Result<String, crate::UserLibError> {
let mut reader = BufReader::new(file);
let mut lines = String::new();
let res = reader.read_to_string(&mut lines);
match res {
Ok(_) => Ok(lines),
Err(e) => Err(format!("failed to read the file: {:?}", e).into()),
}
}
fn groups_to_users<'a>(
users: &'a mut UserList,
groups: &'a mut [crate::Group],
) -> &'a mut UserList {
// Populate the regular groups
for group in groups.iter() {
match group.borrow().get_member_names() {
Some(usernames) => {
for username in usernames {
if let Some(user) = users.get_mut(username) {
user.add_group(crate::group::MembershipKind::Member, group.clone());
}
}
}
None => continue,
}
}
// Populate the primary membership
for user in users.values_mut() {
let gid = user.get_gid();
let grouplist: Vec<&crate::Group> = groups
.iter()
.filter(|g| g.borrow().get_gid().unwrap() == gid)
.collect();
if grouplist.len() == 1 {
let group = *grouplist.first().unwrap();
group.borrow_mut().append_user(
user.get_username()
.expect("Users without username are not supported"),
);
user.add_group(crate::group::MembershipKind::Primary, group.clone());
} else {
error!(
"Somehow the group with gid {} was found {} times",
gid,
grouplist.len()
);
}
}
users
}
/// Merge the Shadow passwords into the users
fn shadow_to_users(users: &mut UserList, shadow: Vec<crate::Shadow>) -> &mut UserList {
for pass in shadow {
let user = users
.get_mut(pass.get_username())
.unwrap_or_else(|| panic!("the user {} does not exist", pass.get_username()));
user.password = crate::Password::Shadow(pass);
}
users
}
/// Convert a `Vec<crate::User>` to a `UserList` (`HashMap<String, crate::User>`) where the username is used as key
fn user_vec_to_hashmap(users: Vec<crate::User>) -> UserList {
users
.into_iter()
.map(|x| {
(
x.get_username()
.expect("An empty username is not supported")
.to_owned(),
x,
)
})
.collect()
}
/// Try to parse a String into some Object.
///
/// # Errors
/// if the parsing failed a [`UserLibError::Message`](crate::userlib_error::UserLibError::Message) is returned containing a more detailed error message.
pub trait NewFromString {
fn new_from_string(line: String, position: u32) -> Result<Self, crate::UserLibError>
where
Self: Sized;
}
/// A generic function that parses a string line by line and creates the appropriate `Vec<T>` requested by the type system.
fn string_to<T>(source: &str) -> Vec<T>
where
T: NewFromString,
{
use std::convert::TryInto;
source
.lines()
.enumerate()
.filter_map(|(n, line)| {
if line.len() > 5 {
Some(
T::new_from_string(
line.to_owned(),
n.try_into()
.unwrap_or_else(|e| panic!("Failed to convert usize to u32 {}", e)),
)
.expect("failed to read lines"),
)
} else {
None
}
})
.collect()
}
#[test]
fn test_creator_user_db_local() {
let data = UserDBLocal::import_from_strings("test:x:1002:1002:full Name,004,000342,001-2312,myemail@test.com:/home/test:/bin/test", "test:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18260:0:99999:7:::", "teste:x:1002:\nanother:x:1003:test");
assert_eq!(
data.users.get("test").unwrap().get_username().unwrap(),
"test"
);
for user in data.users.values() {
dbg!(user.get_groups());
let (member_group1, group1) = user.get_groups().first().unwrap();
let (member_group2, group2) = user.get_groups().get(1).unwrap();
assert_eq!(*member_group1, crate::group::MembershipKind::Member);
assert_eq!(group1.borrow().get_groupname(), Some("another"));
assert_eq!(*member_group2, crate::group::MembershipKind::Primary);
assert_eq!(group2.borrow().get_groupname(), Some("teste"));
}
}
#[test]
fn test_parsing_local_database() {
use std::path::PathBuf;
// Parse the worldreadable user database ignore the shadow database as this would require root privileges.
let pwdfile = File::open(PathBuf::from("/etc/passwd")).unwrap();
let grpfile = File::open(PathBuf::from("/etc/group")).unwrap();
let my_passwd_lines = file_to_string(&pwdfile).unwrap();
let my_group_lines = file_to_string(&grpfile).unwrap();
let data = UserDBLocal::import_from_strings(&my_passwd_lines, "", &my_group_lines);
assert_eq!(
data.groups
.get(0)
.unwrap()
.borrow()
.get_groupname()
.unwrap(),
"root"
);
}
#[test]
fn test_user_db_read_implementation() {
use std::path::PathBuf;
let pwdfile = File::open(PathBuf::from("/etc/passwd")).unwrap();
let grpfile = File::open(PathBuf::from("/etc/group")).unwrap();
let pass = file_to_string(&pwdfile).unwrap();
let group = file_to_string(&grpfile).unwrap();
let data = UserDBLocal::import_from_strings(&pass, "", &group);
// Usually there are more than 10 users
assert!(data.get_all_users().len() > 10);
assert!(data.get_user_by_name("root").is_some());
assert_eq!(data.get_user_by_name("root").unwrap().get_uid(), 0);
assert_eq!(
data.get_user_by_id(0).unwrap().get_username().unwrap(),
"root"
);
assert!(data.get_all_groups().len() > 10);
assert!(data.get_group_by_name("root").is_some());
assert_eq!(
data.get_group_by_name("root")
.unwrap()
.borrow()
.get_gid()
.unwrap(),
0
);
assert_eq!(
data.get_group_by_id(0)
.unwrap()
.borrow()
.get_groupname()
.unwrap(),
"root"
);
assert!(data.get_user_by_name("norealnameforsure").is_none());
assert!(data.get_group_by_name("norealgroupforsure").is_none());
}
#[test]
fn test_user_db_write_implementation() {
use crate::api::DeleteUserArgs;
let mut data = UserDBLocal::import_from_strings("test:x:1001:1001:full Name,004,000342,001-2312,myemail@test.com:/home/test:/bin/test", "test:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18260:0:99999:7:::", "teste:x:1002:test,test");
let user = "test";
assert_eq!(data.get_all_users().len(), 1);
assert!(data
.delete_user(DeleteUserArgs::builder().username(user).build().unwrap())
.is_ok());
assert!(data
.delete_user(DeleteUserArgs::builder().username(user).build().unwrap())
.is_err());
assert_eq!(data.get_all_users().len(), 0);
}
-46
View File
@@ -1,46 +0,0 @@
use std::error::Error;
use std::fmt::{self, Display};
#[derive(Debug, PartialEq)]
pub enum ParseError {
Username,
Password,
Uid,
Gid,
Gecos,
HomeDir,
ShellDir,
}
#[derive(Debug, PartialEq)]
pub enum UserLibError {
NotFound,
ParseError,
Message(String),
}
impl Display for UserLibError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::NotFound => write!(f, ""),
Self::ParseError => write!(f, "Failed to parse"), // TODO details
Self::Message(message) => write!(f, "{}", message),
}
}
}
impl Error for UserLibError {
fn description(&self) -> &str {
match self {
Self::NotFound => "not found",
Self::ParseError => "failed to parse",
Self::Message(message) => message,
}
}
}
impl From<&str> for UserLibError {
fn from(err: &str) -> Self {
Self::Message(err.to_owned())
}
}
+123
View File
@@ -0,0 +1,123 @@
extern crate test_bin;
extern crate umanux;
mod testfiles;
#[test]
fn test_create_user_function() {
use testfiles::Fixture;
use std::fs;
use umanux::api::UserDBWrite;
use umanux::api::UserRead;
let p = Fixture::copy("passwd");
let s = Fixture::copy("shadow");
let g = Fixture::copy("group");
let pf = fs::read_to_string(&p.path).unwrap();
let mf = umanux::Files {
passwd: Some(p.path.clone()),
shadow: Some(s.path),
group: Some(g.path),
};
let mut db = umanux::UserDBLocal::load_files(mf).unwrap();
let user_res: Result<&umanux::User, umanux::UserLibError> = db.new_user(
umanux::api::CreateUserArgs::builder()
.username("test2")
// .delete_home(umanux::api::DeleteHome::Delete)
.build()
.unwrap(),
);
let password_file_string = fs::read_to_string(&p.path).unwrap();
let shadow_file_string = fs::read_to_string(&p.path).unwrap();
assert_eq!(user_res.unwrap().get_username().unwrap(), "test2");
let pflines = pf.lines();
let pflines2 = password_file_string.lines();
for (l1, l2) in pflines.zip(pflines2) {
dbg!(l1, l2);
assert!(l1 == l2);
}
assert!(password_file_string
.lines()
.last()
.unwrap()
.starts_with("test2"));
assert!(shadow_file_string
.lines()
.last()
.unwrap()
.starts_with("test2"));
}
#[test]
fn test_create_user_binary() {
use testfiles::Fixture;
use std::fs;
let p = Fixture::copy("passwd");
let s = Fixture::copy("shadow");
let g = Fixture::copy("group");
//dbg!(&p, &s, &g);
let passwd_string = fs::read_to_string(&p.path).unwrap();
let passwd_lines = passwd_string.lines();
let shadow_string = fs::read_to_string(&s.path).unwrap();
let shadow_lines = shadow_string.lines();
let out = test_bin::get_test_bin("create_user")
.args(&[
"testuser3",
"-p",
p.path.to_str().unwrap(),
"-s",
s.path.to_str().unwrap(),
"-g",
g.path.to_str().unwrap(),
])
.output()
.expect("Failed to run the command");
println!(
"The output after running: {}",
String::from_utf8_lossy(&out.stdout)
);
println!(
"The error after running: {}",
String::from_utf8_lossy(&out.stderr)
);
assert_eq!(String::from_utf8_lossy(&out.stdout), "");
assert_eq!(String::from_utf8_lossy(&out.stderr), "");
let passwd_string_after = fs::read_to_string(&p.path).unwrap();
let passwd_lines_after = passwd_string_after.lines();
let shadow_string_after = fs::read_to_string(&s.path).unwrap();
let shadow_lines_after = shadow_string_after.lines();
for (l1, l2) in passwd_lines.zip(passwd_lines_after) {
//dbg!(l1, l2);
assert!(l1 == l2);
}
assert_eq!(
passwd_string_after
.lines()
.last()
.unwrap()
.starts_with("testuser3"),
true
);
//dbg!(&shadow_string_after);
for (l1, l2) in shadow_lines.zip(shadow_lines_after) {
//dbg!(l1, l2);
assert!(l1 == l2);
}
assert_eq!(
shadow_string_after
.lines()
.last()
.unwrap()
.starts_with("testuser3"),
true
);
}
+53
View File
@@ -0,0 +1,53 @@
extern crate umanux;
mod testfiles;
#[test]
fn test_delete_user_function() {
use testfiles::Fixture;
use std::fs;
use umanux::api::UserDBWrite;
use umanux::api::UserRead;
let p = Fixture::copy("passwd");
let s = Fixture::copy("shadow");
let g = Fixture::copy("group");
let pf = fs::read_to_string(&p.path).unwrap();
let mf = umanux::Files {
passwd: Some(p.path.clone()),
shadow: Some(s.path),
group: Some(g.path.clone()),
};
let mut db = umanux::UserDBLocal::load_files(mf).unwrap();
let user_res: Result<umanux::User, umanux::UserLibError> = db.delete_user(
umanux::api::DeleteUserArgs::builder()
.username("teste")
// .delete_home(umanux::api::DeleteHome::Delete)
.build()
.unwrap(),
);
let pf2 = fs::read_to_string(&p.path).unwrap();
assert_eq!(user_res.unwrap().get_username().unwrap(), "teste");
let pflines = pf.lines();
let pflines2 = pf2.lines();
for (l1, l2) in pflines.zip(pflines2.clone()) {
if l1 != l2 {
assert!(l1.starts_with("teste"));
assert!(l2.starts_with("bergfried"));
break;
}
}
for line in pflines2 {
assert!(!line.starts_with("teste"))
}
let groupfile2 = fs::read_to_string(&g.path).unwrap();
let groupfilelines2 = groupfile2.lines();
for line in groupfilelines2 {
println!("{}", &line);
assert!(!line.ends_with("teste"))
}
}
+93
View File
@@ -0,0 +1,93 @@
root:x:0:
bin:x:1:
daemon:x:2:
sys:x:3:
adm:x:4:
tty:x:5:
disk:x:6:
lp:x:7:
mem:x:8:
kmem:x:9:
wheel:x:10:dietrich
cdrom:x:11:
mail:x:12:
man:x:15:
dialout:x:18:dietrich
floppy:x:19:
games:x:20:
tape:x:33:
video:x:39:
ftp:x:50:
lock:x:54:dietrich
audio:x:63:
users:x:100:
nobody:x:65534:
utmp:x:22:
utempter:x:35:
input:x:999:
kvm:x:36:qemu
render:x:998:
systemd-journal:x:190:
systemd-coredump:x:997:
systemd-network:x:192:
systemd-resolve:x:193:
dbus:x:81:
systemd-timesync:x:996:
tss:x:59:clevis
dip:x:40:
printadmin:x:995:
gluster:x:994:
qemu:x:107:
nm-openconnect:x:993:
usbmuxd:x:113:
geoclue:x:992:
polkitd:x:991:
rtkit:x:172:
pulse-access:x:990:
pulse-rt:x:989:
pulse:x:171:
chrony:x:988:
avahi:x:70:
pipewire:x:987:
dnsmasq:x:986:
saslauth:x:76:
radvd:x:75:
rpc:x:32:
ssh_keys:x:985:
openvpn:x:984:
nm-openvpn:x:983:
libvirt:x:982:dietrich
unbound:x:981:
brlapi:x:980:
apache:x:48:
colord:x:979:
rpcuser:x:29:
abrt:x:173:
flatpak:x:978:
gdm:x:42:
gnome-initial-setup:x:977:
sshd:x:74:
slocate:x:21:
vboxsf:x:976:
tcpdump:x:72:
wbpriv:x:88:
clevis:x:975:
cockpit-ws:x:974:
libvirtdbus:x:973:
setroubleshoot:x:972:
mysql:x:27:
firebird:x:971:
cockpit-wsinstance:x:970:
pbuilder:x:969:
teste:x:1002:test,teste
testnewgroup:x:1015:teste
hausle:x:1018:dietrich
bergfried:x:1009:
t1:x:1019:
t2:x:1020:
docker:x:968:
jackuser:x:967:
akmods:x:966:
mock:x:135:
rtlsdr:x:965:
Debian-exim:x:128:
+60
View File
@@ -0,0 +1,60 @@
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:65534:65534:Kernel Overflow User:/:/sbin/nologin
systemd-coredump:x:999:997:systemd Core Dumper:/:/sbin/nologin
systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin
systemd-resolve:x:193:193:systemd Resolver:/:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
systemd-timesync:x:998:996:systemd Time Synchronization:/:/sbin/nologin
tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin
gluster:x:997:994:GlusterFS daemons:/run/gluster:/sbin/nologin
qemu:x:107:107:qemu user:/:/sbin/nologin
nm-openconnect:x:996:993:NetworkManager user for OpenConnect:/:/sbin/nologin
usbmuxd:x:113:113:usbmuxd user:/:/sbin/nologin
geoclue:x:995:992:User for geoclue:/var/lib/geoclue:/sbin/nologin
polkitd:x:994:991:User for polkitd:/:/sbin/nologin
rtkit:x:172:172:RealtimeKit:/proc:/sbin/nologin
pulse:x:171:171:PulseAudio System Daemon:/var/run/pulse:/sbin/nologin
chrony:x:993:988::/var/lib/chrony:/sbin/nologin
avahi:x:70:70:Avahi mDNS/DNS-SD Stack:/var/run/avahi-daemon:/sbin/nologin
pipewire:x:992:987:PipeWire System Daemon:/var/run/pipewire:/sbin/nologin
dnsmasq:x:986:986:Dnsmasq DHCP and DNS server:/var/lib/dnsmasq:/sbin/nologin
saslauth:x:985:76:Saslauthd user:/run/saslauthd:/sbin/nologin
radvd:x:75:75:radvd user:/:/sbin/nologin
rpc:x:32:32:Rpcbind Daemon:/var/lib/rpcbind:/sbin/nologin
openvpn:x:984:984:OpenVPN:/etc/openvpn:/sbin/nologin
nm-openvpn:x:983:983:Default user for running openvpn spawned by NetworkManager:/:/sbin/nologin
unbound:x:982:981:Unbound DNS resolver:/etc/unbound:/sbin/nologin
apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin
colord:x:981:979:User for colord:/var/lib/colord:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
abrt:x:173:173::/etc/abrt:/sbin/nologin
flatpak:x:980:978:User for flatpak system helper:/:/sbin/nologin
gdm:x:42:42::/var/lib/gdm:/sbin/nologin
gnome-initial-setup:x:979:977::/run/gnome-initial-setup/:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
vboxadd:x:978:1::/var/run/vboxadd:/sbin/nologin
tcpdump:x:72:72::/:/sbin/nologin
clevis:x:977:975:Clevis Decryption Framework unprivileged user:/var/cache/clevis:/sbin/nologin
cockpit-ws:x:976:974:User for cockpit-ws:/nonexisting:/sbin/nologin
libvirtdbus:x:975:973:Libvirt D-Bus bridge:/:/sbin/nologin
setroubleshoot:x:974:972::/var/lib/setroubleshoot:/sbin/nologin
mysql:x:27:27:MySQL Server:/var/lib/mysql:/sbin/nologin
firebird:x:973:971::/:/bin/nologin
cockpit-wsinstance:x:972:970:User for cockpit-ws instances:/nonexisting:/sbin/nologin
pbuilder:x:971:969:pbuilder:/var/run/pbuilder:/sbin/nologin
test:x:1001:1015:Long,007,1499990,1999201,AKK:/home/test:/bin/bash
teste:x:1002:1002::/home/teste:/bin/bash
bergfried:x:1009:1009:Bergfried Freiberg,,,,:/home/bergfried:/bin/bash
akmods:x:970:966:User is used by akmods to build akmod packages:/var/cache/akmods/:/sbin/nologin
Debian-exim:x:123:128::/var/spool/exim4:/usr/sbin/nologin
+60
View File
@@ -0,0 +1,60 @@
root:$6$I4MRB1rzlIft7qiw$2i0OBungWyGBxXbcxbHNKfeaXKRQBEksxK8o3Zvb8VQKuDOSCaLjh1p6C1yfY.z/BCX0dzozj6l3F67QW1X8b.:18260:0:99999:7:::
bin:*:17995:0:99999:7:::
daemon:*:17995:0:99999:7:::
adm:*:17995:0:99999:7:::
lp:*:17995:0:99999:7:::
sync:*:17995:0:99999:7:::
shutdown:*:17995:0:99999:7:::
halt:*:17995:0:99999:7:::
mail:*:17995:0:99999:7:::
operator:*:17995:0:99999:7:::
games:*:17995:0:99999:7:::
ftp:*:17995:0:99999:7:::
nobody:*:17995:0:99999:7:::
systemd-coredump:!!:18107::::::
systemd-network:!!:18107::::::
systemd-resolve:!!:18107::::::
dbus:!!:18107::::::
systemd-timesync:!!:18107::::::
tss:!!:18107::::::
gluster:!!:18107::::::
qemu:!!:18107::::::
nm-openconnect:!!:18107::::::
usbmuxd:!!:18107::::::
geoclue:!!:18107::::::
polkitd:!!:18107::::::
rtkit:!!:18107::::::
pulse:!!:18107::::::
chrony:!!:18107::::::
avahi:!!:18107::::::
pipewire:!!:18107::::::
dnsmasq:!!:18107::::::
saslauth:!!:18107::::::
radvd:!!:18107::::::
rpc:!!:18107:0:99999:7:::
openvpn:!!:18107::::::
nm-openvpn:!!:18107::::::
unbound:!!:18107::::::
apache:!!:18107::::::
colord:!!:18107::::::
rpcuser:!!:18107::::::
abrt:!!:18107::::::
flatpak:!!:18107::::::
gdm:!!:18107::::::
gnome-initial-setup:!!:18107::::::
sshd:!!:18107::::::
vboxadd:!!:18107::::::
tcpdump:!!:18107::::::
clevis:!!:18113::::::
cockpit-ws:!!:18113::::::
libvirtdbus:!!:18113::::::
setroubleshoot:!!:18113::::::
mysql:!!:18137::::::
firebird:!!:18140::::::
cockpit-wsinstance:!!:18196::::::
pbuilder:!!:18198::::::
test:$6$K3iBIIJwfJjolbIV$AaDjW1kvaeYl8KAqAkvXMTWloQV2VsB8a33PHYItRPdETtYGKP2T2n6HjUUuXUZFPxLdnJyB8cWlpPCl1x/VP0:18574:0:99999:7:::
teste:$6$u0Hh.9WKRF1Aeu4g$XqoDyL6Re/4ZLNQCGAXlNacxCxbdigexEqzFzkOVPV5Z1H23hlenjW8ZLgq6GQtFURYwenIFpo1c.r4aW9l5S/:18574:0:99999:7:::
bergfried:$6$dzc1lAZo7XaWwFx9$MpUJtzD9WFJhgt.5zVtgP6mGjFldNCZ02Pp9S9Y4XTV16fMUuN/0vi5Xs4BH2T0G6EL2gS/gAHRnsyvY4aVi31:18574:0:99999:7:::
akmods:!!:18395::::::
Debian-exim:!:18574:0:99999:7:::
+49
View File
@@ -0,0 +1,49 @@
use std::{env, path::Path};
use std::{fs, path::PathBuf};
use tempfile::TempDir;
use std::ops::Deref;
#[derive(Debug)]
pub struct Fixture {
pub path: PathBuf,
pub source: PathBuf,
_tempdir: TempDir,
}
impl Fixture {
#[must_use]
pub fn blank(fixture_filename: &str) -> Self {
// First, figure out the right file in `tests/fixtures/`:
let root_dir = &env::var("CARGO_MANIFEST_DIR").expect("$CARGO_MANIFEST_DIR");
let mut source = PathBuf::from(root_dir);
source.push("tests/fixtures");
source.push(&fixture_filename);
// The "real" path of the file is going to be under a temporary directory:
let tempdir = tempfile::tempdir().unwrap();
let mut path = PathBuf::from(&tempdir.path());
path.push(&fixture_filename);
Self {
_tempdir: tempdir,
source,
path,
}
}
#[must_use]
pub fn copy(fixture_filename: &str) -> Self {
let fixture = Self::blank(fixture_filename);
fs::copy(&fixture.source, &fixture.path).unwrap();
fixture
}
}
impl Deref for Fixture {
type Target = Path;
fn deref(&self) -> &Self::Target {
&self.path
}
}