Compare commits

...
35 Commits
Author SHA1 Message Date
Joachim Wiberg 8451c4087a Merge pull request #522 from firasuke/master
doc: list libcap as a dependency
2026-11-14 12:14:04 +01:00
Firas Khana e280569941 doc: list libcap as a dependency 2026-11-14 13:44:58 +03:00
Joachim Wiberg f15e95d1cc service: don't take a command named like an option for one
A run/task/service whose command starts like an option without a ':'
lost its command, e.g. the example in finit.conf(5):

    run [2345] @joe:users logger "Hello world"

was registered as the log option, running "Hello world".  Same for
pidof, pidproxy, cgroupfs-mount, and in block format too.

The option parser matches with MATCH_CMD(), a prefix match, also for
the options with no trailing ':' to end the prefix: log, pid, cgroup,
respawn, nowarn, and the rest.

Match these against the whole token, allowing only the separator that
starts a value: "log:", "pid:", "cgroup." and "cgroup:".

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-13 16:00:25 +01:00
Joachim Wiberg 34a0a4b1ff conf: pass -- in a block command to the program
A command that takes -- as an argument lost it, and everything after
it, to the description:

    service name {
        command     = "cmd -- arg"
        description = "a cmd"
    }

ran `cmd` with description `arg`.

The block translator builds a legacy one-liner, appending the
description as "-- text", and service_register() splits that line at
the first "-- ", here the one in the command.

Split the description off only for legacy one-liners.  Blocks now hand
it to the new service_register_desc() as an argument.

Fixes #512

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-13 15:56:30 +01:00
Paweł c03059a9a0 keventd: don't publish whole-disk by-id links for partitions
disk_serial_id() falls back to <disk>/../serial so a partition got a
by-id link named after its parent disk's serial, clobbering the link
created for the whole disk.

(cherry picked from commit 4b2f8c89c5)
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-11-13 15:06:08 +01:00
Joachim Wiberg 297d2de1da Merge pull request #511 from zhangxiaohui1/fix/remain-task-control
service: preserve explicit stop for remain tasks
2026-11-12 21:06:47 +01:00
Joachim Wiberg 3acf1cb7b1 Merge pull request #517 from vazub/hwdb-parse-fix
keventd: fix hwdb lookups that never match
2026-11-12 19:25:38 +01:00
Joachim Wiberg eb9fb83011 Merge pull request #516 from vazub/symlink-fix
keventd: fix dangling and misnamed /dev/input/by-id links
2026-11-12 19:24:02 +01:00
Joachim Wiberg b6f0d5314b Merge pull request #521 from firasuke/firasuke-patch-1
Add conditional include for sm.h based on AUTO_RELOAD
2026-11-12 19:22:53 +01:00
Joachim Wiberg 59a2f69345 Merge pull request #515 from augustebaum/patch-1
docs: Fix nested bulleted list
2026-11-09 17:14:29 +01:00
Firas Khana 90512b07a0 Add conditional include for sm.h based on AUTO_RELOAD 2026-11-06 23:09:13 +03:00
Firas Khana d313b1fd74 Add conditional include for sm.h based on AUTO_RELOAD 2026-11-06 23:04:57 +03:00
Basil Zubko 439cab0558 keventd: fix hwdb parsing issues 2026-10-31 20:42:07 +01:00
Basil Zubko 98b2effb52 keventd: fix dev symlinks 2026-10-30 12:30:40 +01:00
Auguste Baum cbd5f79ffd docs: Fix nested bulleted list 2026-10-30 12:13:23 +01:00
Joachim Wiberg a220e0fa9b Merge pull request #514 from vazub/static-fix
Fix static build dropping all built-in plugins
2026-10-27 12:24:28 +01:00
Basil Zubko 1efd50191c fix static build dropping all built-in plugins 2026-10-24 15:13:10 +02:00
Joachim Wiberg 096e6337c5 Merge pull request #513 from vazub/keventd-input
keventd: fix ENV{} match on unset properties
2026-10-24 12:33:46 +02:00
Basil Zubko 02cd1bac42 keventd: fix ENV{} match on unset properties 2026-10-24 09:06:23 +00:00
zhangxiaohui 3a18ca4a30 service: preserve explicit stop for remain tasks
A completed remain task unconditionally cleared its user stop block
after running its post script.  Since it was still valid in the current
runlevel, it immediately started again, making initctl stop ineffective.

Keep explicit stops blocked, distinguish automatic and requested
restarts, and route initctl restart through teardown before rerunning the
task.  Cover stop, start, restart, reload, and runlevel transitions with
a regression test.

Signed-off-by: zhangxiaohui <xiaohui.zhang@wbstar.com>
2026-10-21 19:03:46 +08:00
Joachim Wiberg 530d6703f1 Merge pull request #509 from anees-r3hman/umount-rc
mount: report unmount failures
2026-10-12 09:38:08 +02:00
Joachim Wiberg cec76f18a3 doc: ChangeLog entry for the lost reload fix
Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-09-27 18:56:03 +02:00
Joachim Wiberg ee6d4a1dae service: keep a pending reload across a second conf reload
A service whose condition goes into flux during a reload is paused
with its reload still pending.  If another reload was requested in
the meantime, re-parsing its unchanged .conf file cleared the pending
mark, so the service was resumed without ever being reloaded.  Seen
with sshd <pid/syslogd> on Infix, where a configuration change that
touched both landed as two reloads in a row and sshd kept its old
listen addresses.

The mark is only ever cleared once the change has been applied, so a
mark that is still set when the file is parsed again means exactly
that: not applied yet.  Leave it alone.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-09-27 18:41:05 +02:00
Joachim Wiberg 0548485be1 doc: update ChangeLog for 5.0
Covers the longer user and group names, the tmpfiles mode and owner
work, the shutdown remount order, and the stop/reload script timeout.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-09-27 18:00:13 +02:00
Joachim Wiberg 1b10c3746e Merge pull request #508 from anees-r3hman/avoid-fstab-on-root-remount
sig: avoid reading fstab during shutdown
2026-09-27 17:58:33 +02:00
Joachim Wiberg 24911ebbc2 Merge pull request #507 from anees-r3hman/master
svc: allow longer user and group names
2026-09-27 17:42:11 +02:00
Joachim Wiberg 88a9e6575b tmpfiles: apply mode and owner of e and f/F entries through an fd
Same treatment as d/D got: e went through fisdir() and a path based
chmod/chown, f/F did the chmod/chown by path after closing the file.
Both now work on the open fd, so the mode and owner end up on the
directory or file that was just checked or written.  f/F use open(2)
directly, which lets a plain f rely on O_EXCL for create-if-missing
instead of the earlier stat().

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
(cherry picked from commit 75739fbeef)
2026-09-27 17:30:16 +02:00
Sam Brkopac 9bfbdc6bac tmpfiles: set mode and owner of d/D directories through an fd
makedir() swallows EEXIST, so the chmod branch for directories that
already existed never ran, while chown() ran every time.  On finix
/var/empty is immutable, which gave a warning on every boot even
though the owner was already correct.

mksubsys() is the original of this code and has the same shape, the
dbus plugin uses it for /tmp/dbus.  Both now go through dirperm(),
which opens the directory and uses fstat/fchmod/fchown on the fd,
changing only what differs.  A failed chown in mksubsys() is a warning
now rather than err(1), PID 1 should not exit over a directory it
cannot adjust.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
(cherry picked from commit 3a72d1263c)
2026-09-27 17:26:08 +02:00
Anees Rehman c016965371 mount: report unmount failures
Return a failure status from unmount_regular() when filesystems remain
mounted, and use it to report the final shutdown unmount result.

Signed-off-by: Anees Rehman <anees.rehman@atlascopco.com>
2026-09-25 21:20:02 +02:00
Anees Rehman 263ea929fd sig: avoid reading fstab during shutdown
Only fall back to the regular mount invocation when both
fstab-independent root remount attempts fail.
This avoids reading an encrypted fstab during a normal shutdown.

Signed-off-by: Anees Rehman <anees.rehman@atlascopco.com>
2026-09-25 19:41:05 +02:00
Anees Rehman cc5e0c5175 svc: allow longer user and group names
Service user and group names are stored in 16-byte buffers, limiting
them to 15 characters. This silently truncates longer names before
getpwnam() and getgrnam(), preventing services configured with valid
longer account names from starting.

Increase the buffers to match the existing maximum configuration
argument length.

Signed-off-by: Anees Rehman <anees.rehman@atlascopco.com>
2026-09-25 16:09:35 +02:00
Joachim Wiberg 417abf9000 Merge pull request #500 from finit-project/pam 2026-09-23 17:52:38 +02:00
Joachim Wiberg 61b0e0f3e6 Fix #420: run services inside a PAM session
Apply a PAM session to run/task/sysv/services Finit starts, pam_limits
above all, so a service running as a given user picks up that user's
limits the way a login does.

Add a new `pam` setting for the new block format (only), like the
per-service directories, naming a file in /etc/pam.d:

    service weston {
        user    = "weston"
        pam     = "weston-autologin"
        command = "/usr/bin/weston --continue-without-input"
    }

pam_close_session() has to be called by a process still holding the
handle, and the handle does not survive exec().  Hence the keeper: it
holds the handle, drops to the service's credentials, and waits for a
parent-death signal before closing the session.  Same shape as
systemd's (sd-pam), for the same reason, and one per fork, so the
script hooks open and close their own.

The keeper closes the descriptors it inherited from Finit and only
those.  Closing everything would also take out what pam_open_session()
opened for itself, a keyring fd or a lock file, and leave the modules
to close a session with those pulled out from under them.  Closing
nothing, as (sd-pam) does, would leave it holding the write end of the
notify pipe for the service's whole lifetime and starve notify = "s6"
services of their ready signal.  So the fds open before pam_start()
are snapshotted and exactly those are closed, while the ones PAM opens
after are marked close-on-exec so the daemon does not inherit them
either.

A refused value, a denied account stack, an uninstalled pam.d file,
and a build without PAM support all keep the service from starting
rather than running it with the stacks skipped: one that quietly loses
pam_limits and its private /tmp, with nothing said.  Capabilities a
module like pam_cap.so granted are merged into the IAB Finit applies
instead of being replaced by it, which only helps a service that also
sets capabilities, the other arm being a plain setuid() with nothing
left to restore once permitted is empty.

The test sysroot gains pam_permit.so, pam_deny.so and pam_limits.so,
which ldd cannot see, libpam dlopen()s them, and the test skips when
the host has none to stage.  The negative cases pin the exit status
rather than only asserting crashed, which serv reports for any early
exit, so a bad command or an unwritable pidfile cannot pass for a
rejected session.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-09-23 16:30:14 +02:00
Joachim Wiberg bad7c5c99a .github: unwrap ChangeLog paragraphs in release notes
The ChangeLog is hard-wrapped at 72 columns, which the GitHub releases
page renders verbatim as a ragged right edge.  Join the continuation
lines of each paragraph and list item, as already done in Infix, and
let the browser do the wrapping.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-08-30 10:12:29 +02:00
Joachim Wiberg 4c16190831 build: drop md5 and sha256 files from releases
GitHub now shows a sha256 digest for every uploaded release asset, so
the sidecar hash files only clutter the asset list.

Signed-off-by: Joachim Wiberg <troglobit@gmail.com>
2026-08-30 10:12:29 +02:00
39 changed files with 1652 additions and 188 deletions

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
#!/bin/sh
#
# Extract the topmost release entry from doc/ChangeLog.md and unwrap
# its paragraphs, so the GitHub releases page can wrap them to the
# browser width instead of showing the hard 72-column breaks.
#
# Usage: .github/scripts/extract-changelog.sh < doc/ChangeLog.md > release.md
#
set -e
# The entry sits between the first two underlines, minus the blank
# line separating it from the next heading.
awk '/^-----*$/{if (x == 1) exit; x=1;next}x' | head -n -1 |
# Blank lines, headings, blockquotes, tables, and list items (at any
# indent) start a new block, everything else continues the current one.
awk '
function flush() { if (buf) print buf; buf = "" }
{
if (/^$/) { flush(); print; blank = 1; next }
if (/^ *([-*] |[0-9]+\. |[>#|])/ || blank || !buf || brk)
{ flush(); buf = $0 }
else
{ sub(/^ +/, ""); buf = buf " " $0 }
blank = 0
brk = / $/
}
END { flush() }
'
+1 -1
View File
@@ -99,7 +99,7 @@ jobs:
- name: Install dependencies
run: |
sudo apt-get -y update
sudo apt-get -y install pkg-config tree jq libcap-dev libconfuse-dev libblkid-dev
sudo apt-get -y install pkg-config tree jq libcap-dev libconfuse-dev libblkid-dev libpam0g-dev
wget https://github.com/troglobit/libuev/releases/download/v2.4.1/libuev-2.4.1.tar.xz
wget https://github.com/troglobit/libite/releases/download/v2.6.2/libite-2.6.2.tar.gz
tar xf libuev-2.4.1.tar.xz
+2 -3
View File
@@ -60,7 +60,7 @@ jobs:
make -j1 release || (cat $dir/test/test-suite.log; false)
ls -lF ../
mkdir -p artifacts/
mv ../*.tar.* artifacts/
mv ../*.tar.gz artifacts/
- name: Upload Test Results
if: always()
uses: actions/upload-artifact@v7
@@ -69,8 +69,7 @@ jobs:
path: finit-*/_build/sub/test/*.log
- name: Extract ChangeLog entry ...
run: |
awk '/-----*/{if (x == 1) exit; x=1;next}x' doc/ChangeLog.md \
|head -n -1 > release.md
.github/scripts/extract-changelog.sh < doc/ChangeLog.md > release.md
cat release.md
- uses: ncipollo/release-action@v1
with:
+1 -11
View File
@@ -49,19 +49,9 @@ distclean-local:
# Target to run when building a release
release: distcheck
@for file in $(DIST_ARCHIVES); do \
md5sum $$file > ../$$file.md5; \
sha256sum $$file > ../$$file.sha256; \
done
@mv $(DIST_ARCHIVES) ../
@echo
@echo "Resulting release files:"
@echo "================================================================="
@for file in $(DIST_ARCHIVES); do \
printf "$$file \tDistribution tarball\n"; \
printf "$$file.md5\t"; cat ../$$file.md5 | cut -f1 -d' '; \
printf "$$file.sha256\t"; cat ../$$file.sha256 | cut -f1 -d' '; \
done
@echo "Resulting release tarball(s): $(DIST_ARCHIVES)"
DISTCHECK_CONFIGURE_FLAGS = --prefix=/usr --sysconfdir=/etc --localstatedir=/var \
--enable-testserv-plugin --enable-x11-common-plugin \
+29 -1
View File
@@ -40,7 +40,7 @@ AC_PROG_MKDIR_P
# Configuration.
AC_CHECK_HEADERS([termios.h sys/ioctl.h mntent.h sys/sysmacros.h])
AC_CHECK_FUNCS([strstr getopt getmntent getmntent_r])
AC_CHECK_FUNCS([strstr getopt getmntent getmntent_r close_range])
# Check for uint[8,16,32]_t
AC_TYPE_UINT8_T
@@ -85,6 +85,11 @@ AC_ARG_ENABLE(libcap,
AS_HELP_STRING([--disable-libcap], [Disable Linux capabilities support]),,[
enable_libcap=yes])
AC_ARG_ENABLE(pam,
AS_HELP_STRING([--disable-pam], [Disable PAM session support for services]),
[pam_explicit=yes],
[enable_pam=yes])
AC_ARG_ENABLE(redirect,
AS_HELP_STRING([--disable-redirect], [Disable redirection of service output to /dev/null]),,[
enable_redirect=yes])
@@ -235,6 +240,26 @@ AS_IF([test "x$enable_libcap" = "xyes"], [
])
])
AS_IF([test "x$enable_pam" = "xyes"], [
AS_IF([test "x$enable_static" = "xyes"], [
AS_IF([test "x$pam_explicit" = "xyes"], [
AC_MSG_ERROR([--enable-pam does not work with --enable-static, PAM dlopen()s its modules])], [
AC_MSG_NOTICE([PAM disabled for static build, PAM dlopen()s its modules])
enable_pam=no])])
])
AS_IF([test "x$enable_pam" = "xyes"], [
AC_CHECK_HEADER([security/pam_appl.h], [], [
AC_MSG_WARN([PAM headers not found, PAM support disabled])
enable_pam=no])
AS_IF([test "x$enable_pam" = "xyes"], [
AC_CHECK_LIB([pam], [pam_start], [
AC_DEFINE(HAVE_LIBPAM, 1, [Have Linux-PAM for per-service session support])
LIBS="$LIBS -lpam"
], [
AC_MSG_WARN([libpam not found, PAM support disabled])
enable_pam=no])])
])
AS_IF([test "x$enable_fastboot" = "xyes"], [
AC_DEFINE(FAST_BOOT, 1, [Skip fsck check on filesystems listed in /etc/fstab])])
@@ -257,6 +282,8 @@ AS_IF([test "x$enable_dbus" = "xyes"], [
AC_DEFINE(HAVE_DBUS, 1, [Build D-Bus support via libink])])
AM_CONDITIONAL(DBUS, [test "x$enable_dbus" = "xyes"])
AM_CONDITIONAL(PAM, [test "x$enable_pam" = "xyes"])
### With features ##############################################################################
AS_IF([test "x$bash_dir" = "xyes"], [
PKG_CHECK_MODULES([BASH_COMPLETION], [bash-completion >= 2.0],
@@ -461,6 +488,7 @@ Optional features:
Replacement libsystemd: $with_libsystemd
Use cgroup v2.........: $enable_cgroup
Use libcap............: $enable_libcap
Use PAM...............: $enable_pam
Parse kernel cmdline..: $enable_kernel_cmdline
Keep kernel logging...: $enable_kernel_logging
Skip fsck check.......: $enable_fastboot
+31
View File
@@ -85,6 +85,10 @@ All relevant changes are documented in this file.
service, `command = { "/lib/systemd/systemd-udevd", "-udevd" }`, and Finit
starts the first one it finds. The line-based format could only express
this by repeating the whole stanza per candidate
- New `pam = "NAME"` setting for run/task/service/sysv blocks, runs the
service inside a PAM session set up from `/etc/pam.d/NAME`, so the `session`
stack applies to the process that becomes the daemon, e.g. limits from
`pam_limits`, which override a per-service `rlimit`. Issue #420
- Finit now ships with a built-in brokerless D-Bus implementation, **libink**,
exposing the running init system as a peer on its own private bus at
`/run/finit/bus`, and -- opportunistically -- registering `org.finit` on the
@@ -136,9 +140,25 @@ All relevant changes are documented in this file.
e.g. `killed by SIGKILL` or `killed by SIGSEGV, core dumped`, in place of
the bare numeric `by signal: N`. Gives operators a much stronger breadcrumb
when a daemon dies unexpectedly
- Service `user:` and `group:` names, including supplementary groups, can
now be up to 63 characters, up from 15. Longer names were silently
truncated before the lookup, so the service never started. By Anees Rehman
- `stop:` and `reload:` scripts take a timeout of their own, `stop:5,/path`,
defaulting to the kill delay as before. Such a line used to crash Finit at
config load
- Shutdown now stops after the first successful remount of `/` read only.
The plain `mount -n -o remount,ro /`, which reads `/etc/fstab`, is only
used when both device-agnostic forms fail, the same order as Debian's
`umountroot`. By Anees Rehman
### Fixes
- Fix #512: `--` in the `command` of a block-format .conf, it was taken as the
start of the description, so `command = "cmd -- arg"` ran `cmd` with
description `arg`. Found by Alexandru Paniș
- Fix a command whose name starts like a service option, e.g. `logger` or
`pidof`. It was taken as the `log` or `pid` option and the next argument
ran as the command, which also broke the `logger` example in finit.conf(5)
- Reject a .conf file that declares the same block title twice. The title is
the service identity and libConfuse merges two sections sharing one, so the
file loaded as a single service holding a mix of both declarations,
@@ -157,6 +177,17 @@ All relevant changes are documented in this file.
- Fix misspelled `SIGUNKOWN` returned by `sig_name()` for unknown signal
numbers, now spelled correctly as `SIGUNKNOWN`. Surfaced by the new restart
log above
- Fix mode of existing `d`/`D` directories in tmpfiles, the chmod branch
never ran because the directory creation swallowed `EEXIST`. Mode and owner
of `d`/`D`, `e`, and `f`/`F` entries, and of the service directories
`mksubsysd()` creates, are now set through an open fd and only when they
differ, so an immutable directory like `/var/empty` no longer warns on every
boot. By Sam Brkopac
- Fix a lost reload for a service paused mid-reload by a condition in
flux. A second reload arriving meanwhile re-parsed the unchanged .conf
and cleared the pending mark, so the service resumed without ever being
reloaded. Seen on Infix, where sshd kept its old listen addresses after
a change that landed as two reloads in a row
[4.17][] - 2026-04-28
---------------------
+24
View File
@@ -15,6 +15,15 @@ and `/dev/disk/by-label/` symlinks after. keventd is enabled by
default, so this is a hard requirement unless you build with
`--without-keventd`.
Linux capabilities support for services is also built by default. It needs
[libcap][] (-lcap); the build falls back to no capabilities support when that
library is missing, or with `--disable-libcap`.
PAM session support for services is built by default. It needs
[Linux-PAM][] (-lpam); the build falls back to no PAM support when that
library is missing. A static build, `--enable-static`, disables PAM
too, since libpam loads its modules with `dlopen()`.
> [!IMPORTANT]
> Most free/open source software packages that use `configure` default
> to install to `/usr/local`. However, some Linux distributions do no
@@ -32,6 +41,7 @@ version of the above mentioned libraries. Currently required versions:
- libuEv v2.2.0, or later
- libConfuse v3.3, or later
- libblkid, any version, when keventd is enabled
- libcap, any version, unless `--disable-libcap` is given
Configure
@@ -54,6 +64,18 @@ Below are a few of the main switches to configure:
built-ins (.o files) and all external libraries, except the C library
will be linked statically.
* `--disable-libcap`: Opt out of Finit's built-in Linux capabilities support,
enabled by default. Needs libcap, and falls back to disabled when it is
missing. See [Linux Capabilities](config/capabilities.md)
* `--disable-pam`: Opt out of Finit's built-in PAM session support,
enabled by default, which lets a service declare `pam = "name"` and
run inside a session set up from `/etc/pam.d/name`. Needs libpam,
falls back to disabled when it is missing, and is also disabled for
`--enable-static` builds. Asking for `--enable-pam` and
`--enable-static` together is an error rather than a fallback. See
[PAM Sessions](config/pam.md)
* `--enable-kernel-cmdline`: Enable Finit pre-4.1 parsing of init args from
`/proc/cmdline`, this is *not recommended* since Finit may be running as the
init for container apps that can see the host's `/proc` filesystem
@@ -285,3 +307,5 @@ it only for debugging start up issues when Finit crashes.
[libite]: https://github.com/troglobit/libite
[libConfuse]: https://github.com/libconfuse/libconfuse
[util-linux]: https://github.com/util-linux/util-linux
[libcap]: https://sites.google.com/site/fullycapable/
[Linux-PAM]: https://github.com/linux-pam/linux-pam
+6 -2
View File
@@ -169,8 +169,9 @@ ps -o user,pid,cmd -p $(pidof nginx)
- Linux kernel 4.3+ (for ambient capabilities support)
- libcap library installed
- Finit built with `--enable-libcap`, otherwise a `capabilities` list is
ignored, with a warning
- Finit built with libcap support (enabled by default unless `--disable-libcap`
is given or libcap was missing at build time), otherwise a `capabilities` list
is ignored, with a warning
## Limitations
@@ -189,6 +190,9 @@ ps -o user,pid,cmd -p $(pidof nginx)
- Services without `capabilities` use standard privilege dropping:
- Services with a non-root `user` have no special capabilities
- Services without `user` run as root with full capabilities
- A capability granted by `pam_cap.so` in a [PAM session](pam.md) is
merged into this set, but only when `capabilities` is also set.
Without it the grant is lost when privileges drop
- Some very old binaries may not work correctly with ambient capabilities
- File system capabilities are not managed by Finit (use `setcap` for that)
+1 -1
View File
@@ -261,7 +261,7 @@ Worth knowing
$SYSLOGD_ARGS"` working with an `envfile`.
* New settings only appear in the block format. The first are the
[per-service directories](service-opts.md#service-directories),
`runtime-dir` and friends.
`runtime-dir` and friends, and [`pam`](pam.md).
For the full description of every key, see the rest of the
[Configuration](index.md) section.
+151
View File
@@ -0,0 +1,151 @@
PAM Sessions
============
`pam = "NAME"` runs a service inside a PAM session set up from
`/etc/pam.d/NAME`. The `session` stack in that file runs for the
process that goes on to become the daemon, so modules like `pam_limits`,
`pam_env`, or `pam_keyinit` see the service the way they see a login.
## Basic Usage
A display server that needs the session a login would have arranged for
it:
```conf
service weston {
user = "weston"
pam = "weston-autologin"
command = "/usr/bin/weston --continue-without-input"
}
```
With `/etc/pam.d/weston-autologin`:
```
auth required pam_permit.so
account required pam_unix.so
session required pam_unix.so
session required pam_limits.so
```
The `auth` line is needed even though nothing is ever authenticated.
Opening the session goes through `pam_setcred()`, which consults the
`auth` stack, and an empty stack comes back as a permission denial, so a
pam.d file with only `account` and `session` lines keeps the service
from starting.
The value names a file in `/etc/pam.d`, it is not a path. A value
holding `/` or `..`, or one too long to fit, is refused, with an error
in the log when the .conf file is read. The service does not start
either, `initctl status` reports it as missing. Like the per-service
directory keys, `pam` exists in the block format only.
## No Authentication
Finit runs the account and session stacks, `pam_acct_mgmt()`,
`pam_setcred()`, and `pam_open_session()`, and never
`pam_authenticate()`. A module that asks a question gets a
conversation error back and its entry in the stack fails.
A service whose account is denied, an expired account say, does not
start, and neither does one naming a pam.d file that is not installed.
The child exits 71 (`EX_OSERR`), `initctl status` shows the service as
crashed, and PAM's own reason is in the log.
## Requirements
PAM support is built by default, see [Building Finit](../build.md).
Without it, e.g. after `--disable-pam`, a service declaring `pam` is
refused rather than started with the stacks skipped:
weston: pam weston-autologin requires Finit built with --enable-pam
## Which Blocks Take It
`service`, `task`, `run`, and `sysv`. Not `tty`: `login` opens a
session of its own there.
Every fork gets its own session, so the `pre:`, `post:`, `ready:`, and
`cleanup:` scripts each open and close one too, as do the stop and
reload scripts and the `stop` call on a `sysv` script.
A refused value stops those too. A `pre:` script forks before the
start-time check runs, so it exits 71 without running instead of the
service being reported missing.
## The User
`user` decides who the session is for. Without it the session is for
root.
systemd documents the opposite for its equivalent. `systemd.exec(5)`
says `PAMName=` is "only useful in conjunction with the `User=`
setting, and is otherwise ignored". That was true of systemd up to and
including v256, v257 changed it to open a session for the manager's own
user, and the man page was never updated. Finit does what v257 does.
A service with a [controlling tty](tty.md#controlling-tty-for-services)
has it passed to PAM as `PAM_TTY`, for the modules that care which
terminal a session is on.
## Precedence
Three places where PAM and a Finit setting cover the same ground:
- `pam_limits` overrides a per-service `rlimit`. A block asking for
`nofile = 4096` under a `limits.conf` that says 512 gets 512.
- `pam_env` overrides Finit's own environment defaults, `PATH`, `USER`,
`LOGNAME`, and `HOME`, and `envfile` in turn overrides `pam_env`. A
`HOME` from the session stack also moves the working directory, which
otherwise is the home directory from `/etc/passwd`.
- The groups from `/etc/group` and `extra-groups` override `pam_group`.
## The Session Keeper
A helper is forked next to the service to close the session when the
service exits, `(finit-pam)`:
```
CGroup : /system/weston cpu 0 [100, max] mem [--.--, max]
|- 312 /usr/bin/weston --continue-without-input
`- 313 (finit-pam)
```
There is one per fork. It runs as the service's user, in the service's
cgroup, and stopping the service takes it along.
A daemon that reaps children in its own `wait()` loop will see a child
it never forked. systemd has the same property, with `(sd-pam)`.
## Limitations
- `type = "forking"` closes the session early. The initial process
exits by design, the keeper's parent-death signal fires with it, and
the session is closed while the real daemon runs on. Finit warns
about the combination when it reads the .conf file, and starts the
service anyway:
/etc/finit.d/foo.conf: foo: pam with type = forking closes the
session when the initial process exits
- A daemon whose initial thread exits while the process lives closes the
session the same way. The parent-death signal follows the thread that
forked the keeper, not the process.
- A capability granted by `pam_cap.so` is only kept when the service
also sets [`capabilities`](capabilities.md).
- The keeper shares the service's cgroup, so an empty cgroup directory
can outlive a stop until the next start reuses it. Cosmetic.
- A module that blocks has no time bound. `pam_open_session()` waits
for as long as the module does, `pam_ldap` against an unreachable
server, say, or `pam_mount` on a hung network mount. The fork has already succeeded by then, so the service
reaches the running state and stays there with no daemon behind it.
Nothing crashes and nothing restarts.
## See Also
- [Service Options](service-opts.md) - the other run/task/service keys
- [Linux Capabilities](capabilities.md) - the key `pam_cap.so` needs
- [Building Finit](../build.md) - `--disable-pam` and its dependency
- [pam(8)](https://man7.org/linux/man-pages/man8/pam.8.html) - the PAM library
- [pam.d(5)](https://man7.org/linux/man-pages/man5/pam.d.5.html) - the file format
- [pam_limits(8)](https://man7.org/linux/man-pages/man8/pam_limits.8.html) - limits from `limits.conf`
+3
View File
@@ -160,6 +160,9 @@ albeit deprecated.
each `/etc/finit.d/*.conf` read. I.e., a set of task/run/service
blocks can share the same rlimits if they are in the same .conf.
For a service with [`pam`](pam.md), `pam_limits` runs after these
limits are applied, so `limits.conf` has the last word.
Miscellaneous Settings
----------------------
+3
View File
@@ -27,6 +27,9 @@ the `ps` command we can see that the process is started with:
foo -n --extra-arg=bar -s -x
> [!NOTE]
For a service with [`pam`](pam.md), the session environment is applied
before `envfile`, so the file overrides anything `pam_env` set.
> The leading `-` on `envfile` determines if Finit should treat a
> missing environment file as blocking the start of the service or not.
> When `-` is used, a missing environment file does *not* block the
+1
View File
@@ -56,6 +56,7 @@ Other run/task/service settings are:
* `log {}` -- see [Redirecting Output](logging.md#redirecting-output)
* `tty` -- see [Controlling TTY](tty.md#controlling-tty-for-services)
* `notify` -- see [Service Synchronization](service-sync.md)
* `pam` -- see the [PAM Sessions](pam.md) section
* `if` -- see [Conditional Execution](services.md#conditional-execution)
* `type = "forking"` -- see description of the [service](services.md) block
* a leading `-` on `command` -- see
+20
View File
@@ -178,6 +178,26 @@ See the [Linux Capabilities](config/capabilities.md) section for detailed
information, examples, and security best practices.
**PAM Sessions**
A service can run inside a PAM session, so the `session` stack in
`/etc/pam.d` applies to it, e.g. limits from `pam_limits`:
```conf
service weston {
user = "weston"
pam = "weston-autologin"
command = "/usr/bin/weston --continue-without-input"
}
```
Without a `user` the session is for root. Requires a build with PAM
support, which is the default; see `--disable-pam`.
See the [PAM Sessions](config/pam.md) section for the pam.d file the
example needs, and for how PAM and Finit settings interact.
**Supplementary Groups**
Finit supports supplementary groups for services, allowing them to access
+6 -6
View File
@@ -3,15 +3,15 @@ Starting & Monitoring
Finit can start and monitor the following types of daemons:
* Forks to background, creates a PID file
* Runs in foreground and signals ready by:
- creating a PID file
- does not create a PID file -- Finit can create it for you (optional)
- [other mechanism][1] (systemd, s6)
* Forks to background, creates a PID file
* Runs in foreground and signals ready by:
- creating a PID file
- does not create a PID file -- Finit can create it for you (optional)
- [other mechanism][1] (systemd, s6)
Finit can *not* start and monitor a daemon that:
* Forks to background and does *not* create a PID file
* Forks to background and does *not* create a PID file
| | Forking | Creates PID File | Finit creates PID File |
|---|---------|------------------|------------------------|
+76 -21
View File
@@ -81,6 +81,13 @@ static int builtin_kmod(struct uevent *ev, int argc, char **argv)
/* ---- hwdb -------------------------------------------------------- */
/*
* Longest lookup key. A key built by the stock name-based evdev rule
* (name, phys, ev and the DMI modalias) is 280 to 300 bytes with typical
* DMI strings, and 250 to 265 bytes for the plain name rule.
*/
#define HWDB_KEY_MAX 1024
/*
* Match a single text hwdb file against the lookup key.
* Text format: match lines at column 0, property lines indented.
@@ -106,7 +113,11 @@ static void hwdb_match_file(const char *path, const char *lookup,
while (fgets(line, sizeof(line), fp)) {
line[strcspn(line, "\n")] = '\0';
if (!line[0] || line[0] == '#') {
/* Comments do not end the record being read */
if (line[0] == '#')
continue;
if (!line[0]) {
matched = 0;
in_props = 0;
continue;
@@ -145,9 +156,11 @@ static void hwdb_match_file(const char *path, const char *lookup,
/*
* Build the hwdb lookup key for input devices.
*
* udev hwdb files use the format:
* evdev:input:b{BUS}v{VENDOR}p{PRODUCT}e{VERSION}*
* where all fields are 4-digit uppercase hex.
* The key is the modalias of the input device, which the rule's
* --lookup-prefix (evdev:, id-input:modalias:) is put in front of:
* input:b{BUS}v{VENDOR}p{PRODUCT}e{VERSION}-e{CAPABILITIES...}
* where the IDs are 4-digit uppercase hex. If the device has no modalias
* attribute, the part up to the version is built from the id/ files.
*
* The id/ files live under the input device directory. For eventN nodes
* (devpath ends in .../inputN/eventN) we strip the last component first.
@@ -156,7 +169,7 @@ static void hwdb_input_key(const struct uevent *ev, char *key, size_t len)
{
char base[PATH_MAX];
char path[PATH_MAX];
char bus_s[8], vendor_s[8], product_s[8], version_s[8];
char bus_s[8] = "", vendor_s[8] = "", product_s[8] = "", version_s[8] = "";
if (!ev->devpath)
return;
@@ -180,11 +193,28 @@ static void hwdb_input_key(const struct uevent *ev, char *key, size_t len)
snprintf(path, sizeof(path), "/sys%s", ev->devpath);
}
snprintf(base, sizeof(base), "%s/id/vendor", path); sysfs_read_file(base, vendor_s, sizeof(vendor_s));
snprintf(base, sizeof(base), "%s/id/product", path); sysfs_read_file(base, product_s, sizeof(product_s));
snprintf(base, sizeof(base), "%s/id/version", path); sysfs_read_file(base, version_s, sizeof(version_s));
/*
* Prefer the modalias of the input device. Unlike the id/ files it
* carries the capability bitmaps (-e0,1,2,4,k110,...) that some
* entries match on.
*/
snprintf(base, sizeof(base), "%s/modalias", path);
if (!sysfs_read_file(base, key, len) && !strncmp(key, "input:", 6))
return;
key[0] = '\0';
snprintf(key, len, "evdev:input:b%04Xv%04Xp%04Xe%04X*",
/* Otherwise build it from the id/ files; without a full set there is no key. */
snprintf(base, sizeof(base), "%s/id/vendor", path);
if (sysfs_read_file(base, vendor_s, sizeof(vendor_s)) < 0)
return;
snprintf(base, sizeof(base), "%s/id/product", path);
if (sysfs_read_file(base, product_s, sizeof(product_s)) < 0)
return;
snprintf(base, sizeof(base), "%s/id/version", path);
if (sysfs_read_file(base, version_s, sizeof(version_s)) < 0)
return;
snprintf(key, len, "input:b%04Xv%04Xp%04Xe%04X*",
(unsigned)strtoul(bus_s, NULL, 16),
(unsigned)strtoul(vendor_s, NULL, 16),
(unsigned)strtoul(product_s, NULL, 16),
@@ -265,24 +295,48 @@ static void hwdb_scan(const char *key, struct uevent *ev)
}
}
/* Insert prefix in front of key, in place; -1 if the result does not fit. */
static int hwdb_prepend(char *key, size_t len, const char *prefix)
{
size_t plen = strlen(prefix), klen = strlen(key);
if (plen + klen >= len)
return -1;
memmove(key + plen, key, klen + 1);
memcpy(key, prefix, plen);
return 0;
}
static int builtin_hwdb(struct uevent *ev, int argc, char **argv)
{
const char *subsys = NULL;
const char *prefix = NULL;
char key[256] = "";
const char *explicit_key = NULL;
char key[HWDB_KEY_MAX] = "";
int i;
/* Parse --subsystem=X and --lookup-prefix=Y */
/*
* Parse --subsystem=X and --lookup-prefix=Y. The first argument
* that is not an option is the lookup key itself, which is how the
* stock udev rules use the builtin:
*
* IMPORT{builtin}="hwdb 'evdev:name:$attr{name}:$attr{[dmi/id]modalias}'"
*/
for (i = 1; i < argc; i++) {
if (!strncmp(argv[i], "--subsystem=", 12))
subsys = argv[i] + 12;
else if (!strncmp(argv[i], "--lookup-prefix=", 16))
prefix = argv[i] + 16;
else if (argv[i][0] != '-' && !explicit_key)
explicit_key = argv[i];
}
if (!subsys)
subsys = ev->subsystem;
if (subsys && !strcmp(subsys, "input")) {
if (explicit_key) {
if (snprintf(key, sizeof(key), "%s", explicit_key) >= (int)sizeof(key))
goto too_long;
} else if (subsys && !strcmp(subsys, "input")) {
hwdb_input_key(ev, key, sizeof(key));
} else if (subsys && (!strcmp(subsys, "usb") ||
!strcmp(subsys, "usb_device"))) {
@@ -290,29 +344,30 @@ static int builtin_hwdb(struct uevent *ev, int argc, char **argv)
}
/* Fall back to MODALIAS / ev->modalias for pci, platform, etc. */
if (!key[0]) {
if (!key[0] && !explicit_key) {
const char *m = uevent_getenv(ev, "MODALIAS");
if (!m)
m = ev->modalias;
if (m)
snprintf(key, sizeof(key), "%s", m);
if (m && snprintf(key, sizeof(key), "%s", m) >= (int)sizeof(key))
goto too_long;
}
if (!key[0])
return 0;
/* --lookup-prefix scopes the match by prepending to the key. */
if (prefix && *prefix) {
char tmp[sizeof(key)];
snprintf(tmp, sizeof(tmp), "%s%s", prefix, key);
snprintf(key, sizeof(key), "%s", tmp);
}
if (prefix && *prefix && hwdb_prepend(key, sizeof(key), prefix))
goto too_long;
logit(LOG_DEBUG, "rules: hwdb lookup: %s", key);
hwdb_scan(key, ev);
return 0;
too_long:
logit(LOG_WARNING, "rules: hwdb key too long (max %d bytes), lookup skipped",
HWDB_KEY_MAX - 1);
return 0;
}
/* ---- path_id ----------------------------------------------------- */
+36 -3
View File
@@ -501,6 +501,33 @@ void rules_free(struct rule_list *list)
/* ----- variable substitution ------------------------------------------- */
/*
* Syspath of the parent device selected by the last successful
* KERNELS/SUBSYSTEMS/DRIVERS/ATTRS== match of the rule being evaluated.
* As in udev, $attr{} and %s{} fall back to this parent when the event
* device has no such attribute itself; the stock rules rely on it:
*
* ATTRS{bInterfaceNumber}=="?*", SYMLINK+="...-if$attr{bInterfaceNumber}-..."
*
* Cleared at the start of every rule and again once it has been applied.
*/
static char matched_parent[PATH_MAX];
/* Read an attribute for $attr{}/%s{}: the event device first, then the matched parent */
static int subst_read_attr(const struct uevent *ev, const char *attr,
char *buf, size_t len)
{
char path[PATH_MAX];
if (ev->devpath && !sysfs_read_attr(ev->devpath, attr, buf, len))
return 0;
if (!matched_parent[0])
return -1;
snprintf(path, sizeof(path), "%s/%s", matched_parent, attr);
return sysfs_read_file(path, buf, len);
}
static void append_str(char *buf, size_t *pos, size_t bufsz, const char *s)
{
size_t l;
@@ -604,8 +631,7 @@ static void subst_value(const char *src, char *buf, size_t bufsz,
al = sizeof(attr) - 1;
memcpy(attr, as, al);
attr[al] = 0;
if (!sysfs_read_attr(ev->devpath, attr,
tmp, sizeof(tmp)))
if (!subst_read_attr(ev, attr, tmp, sizeof(tmp)))
append_str(buf, &pos, bufsz, tmp);
p = ae + 1;
} else {
@@ -681,7 +707,7 @@ static void subst_value(const char *src, char *buf, size_t bufsz,
al = sizeof(attr) - 1;
memcpy(attr, as, al);
attr[al] = 0;
if (!sysfs_read_attr(ev->devpath, attr, tmp, sizeof(tmp)))
if (!subst_read_attr(ev, attr, tmp, sizeof(tmp)))
append_str(buf, &pos, bufsz, tmp);
p = ae + 1;
} else {
@@ -908,6 +934,8 @@ static int parent_cb(const char *syspath, void *data)
if (pattern_match(k->value, subject, k->pat_type)) {
ctx->found = 1;
if (k->op == OP_MATCH_EQ)
snprintf(matched_parent, sizeof(matched_parent), "%s", syspath);
return 0; /* stop walking */
}
return 1; /* keep walking */
@@ -1045,6 +1073,8 @@ static int match_key(const struct rule *r, const struct rule_key *k,
if (!k->attr)
return (k->op == OP_MATCH_NE);
subject = uevent_getenv(ev, k->attr);
if (!subject)
subject = "";
break;
case KEY_CONST: {
if (!k->attr) {
@@ -1099,6 +1129,8 @@ static int rule_matches(const struct rule *r, struct uevent *ev)
{
int i;
matched_parent[0] = 0;
for (i = 0; i < r->nkeys; i++) {
const struct rule_key *k = &r->keys[i];
@@ -1625,6 +1657,7 @@ int rules_apply(struct rule_list *list, struct uevent *ev)
uevent_action_str(ev->action), ev->devpath ?: "");
exec_rule(r, ev);
matched_parent[0] = 0;
/* GOTO takes effect after this rule's assignments are applied */
goto_label = NULL;
+76 -18
View File
@@ -507,6 +507,62 @@ static struct devrule *find_rule(struct uevent *ev)
return &devrules[NELEMS(devrules) - 1];
}
/*
* Build the relative target of a symlink at /dev/<link> that points at the
* device node /dev/<node>, e.g.
*
* link "input/by-id/usb-X-event-kbd", node "input/event17" -> "../event17"
* link "disk/by-id/ata-X", node "sda" -> "../../sda"
*
* Both arguments are relative to /dev. The directory components the link
* and the node have in common are dropped, then one "../" is emitted for
* each directory the link still has to climb out of.
*/
static int symlink_relative_target(const char *link, const char *node,
char *buf, size_t len)
{
const char *l = link, *n = node;
size_t off = 0;
int ret;
while (*l == '/')
l++;
while (*n == '/')
n++;
/* Skip leading directories shared by both paths */
for (;;) {
const char *ls = strchr(l, '/');
const char *ns = strchr(n, '/');
if (!ls || !ns || ls - l != ns - n || strncmp(l, n, ls - l))
break;
l = ls + 1;
n = ns + 1;
while (*l == '/')
l++;
while (*n == '/')
n++;
}
buf[0] = 0;
for (; (l = strchr(l, '/')); l++) {
while (l[1] == '/')
l++;
if (!l[1])
break;
ret = snprintf(buf + off, len - off, "../");
if (ret < 0 || (size_t)ret >= len - off)
return -1;
off += ret;
}
ret = snprintf(buf + off, len - off, "%s", n);
if (ret < 0 || (size_t)ret >= len - off)
return -1;
return 0;
}
/*
* Create device node in /dev.
*/
@@ -792,7 +848,7 @@ static int disk_path_id(struct uevent *ev, char *id, size_t len)
static int symlink_add_disk(struct uevent *ev)
{
char target[PATH_MAX], link[PATH_MAX], id[256];
const char *name;
const char *name, *devtype;
if (!ev->devname)
return -1;
@@ -801,13 +857,22 @@ static int symlink_add_disk(struct uevent *ev)
name = strrchr(ev->devname, '/');
name = name ? name + 1 : ev->devname;
/* by-id: serial-based identifier */
/*
* by-id: serial-based identifier.
* Partitions are skipped, as their serial lives on the parent disk and would
* clobber its by-id link, partitions get theirs from the udev rules instead.
*/
devtype = uevent_getenv(ev, "DEVTYPE");
if (devtype && !strcmp(devtype, "partition"))
goto path;
if (!disk_serial_id(ev, id, sizeof(id))) {
snprintf(target, sizeof(target), "../../%s", name);
snprintf(link, sizeof(link), "/dev/disk/by-id/%s", id);
symlink_create(target, link, ev->devpath);
}
path:
/* by-path: topology-based identifier */
if (!disk_path_id(ev, id, sizeof(id))) {
snprintf(target, sizeof(target), "../../%s", name);
@@ -903,9 +968,6 @@ int symlink_add(struct uevent *ev)
for (i = 0; i < ev->applied.nsymlinks; i++) {
const char *devname, *sl;
char link[PATH_MAX], target[PATH_MAX];
size_t toff = 0;
int depth = 0;
const char *p;
sl = ev->applied.symlinks[i];
if (!sl || !*sl)
@@ -915,19 +977,15 @@ int symlink_add(struct uevent *ev)
if (!devname)
continue;
/* basename of devname for the symlink target */
const char *base = strrchr(devname, '/');
base = base ? base + 1 : devname;
/* Count '/' in symlink path to determine relative depth */
for (p = sl; *p; p++)
if (*p == '/')
depth++;
target[0] = 0;
for (int d = 0; d < depth; d++)
toff += snprintf(target + toff, sizeof(target) - toff, "../");
snprintf(target + toff, sizeof(target) - toff, "%s", base);
/*
* The node lives at /dev/<devname>, which is not necessarily
* directly in /dev (input/event17, dri/card0, ...), so the
* target must be computed relative to the link's directory.
*/
if (symlink_relative_target(sl, devname, target, sizeof(target))) {
logit(LOG_WARNING, "Symlink %s -> %s: path too long", sl, devname);
continue;
}
snprintf(link, sizeof(link), "/dev/%s", sl);
symlink_create(target, link, ev->devpath ?: "");
+1
View File
@@ -39,6 +39,7 @@ nav:
- Logging: config/logging.md
- Cgroups: config/cgroups.md
- Capabilities: config/capabilities.md
- PAM Sessions: config/pam.md
- Templating: config/templating.md
- SysV Compatibility: config/sysv.md
- Rescue Mode: config/rescue.md
+18 -13
View File
@@ -6,51 +6,56 @@ AM_CPPFLAGS += -D_XOPEN_SOURCE=600 -D_BSD_SOURCE -D_GNU_SOURCE -D_DEFAULT
AM_CPPFLAGS += -D__FINIT__ $(lite_CFLAGS) $(uev_CFLAGS)
if STATIC
noinst_LTLIBRARIES = libplug.la
libplug_la_SOURCES = bootmisc.c pidfile.c procps.c sys.c usr.c
noinst_LIBRARIES = libplug.a
libplug_a_SOURCES = bootmisc.c pidfile.c procps.c sys.c usr.c
libplug_a_CFLAGS = $(AM_CFLAGS)
if BUILD_ALSA_UTILS_PLUGIN
libplug_la_SOURCES += alsa-utils.c
libplug_a_SOURCES += alsa-utils.c
endif
if BUILD_DBUS_PLUGIN
libplug_la_SOURCES += dbus.c
libplug_a_SOURCES += dbus.c
endif
if BUILD_HOOK_SCRIPTS_PLUGIN
libplug_a_SOURCES += hook-scripts.c
endif
if BUILD_MODULES_LOAD_PLUGIN
libplug_la_SOURCES += modules-load.c
libplug_a_SOURCES += modules-load.c
endif
if BUILD_MODPROBE_PLUGIN
libplug_la_SOURCES += modprobe.c
libplug_a_SOURCES += modprobe.c
endif
if BUILD_NETLINK_PLUGIN
libplug_la_SOURCES += netlink.c
libplug_a_SOURCES += netlink.c
endif
if BUILD_PLYMOUTH_PLUGIN
libplug_la_SOURCES += plymouth.c
libplug_a_SOURCES += plymouth.c
endif
if BUILD_RESOLVCONF_PLUGIN
libplug_la_SOURCES += resolvconf.c
libplug_a_SOURCES += resolvconf.c
endif
if BUILD_RTC_PLUGIN
libplug_la_SOURCES += rtc.c
libplug_a_SOURCES += rtc.c
endif
if BUILD_TTY_PLUGIN
libplug_la_SOURCES += tty.c
libplug_a_SOURCES += tty.c
endif
if BUILD_URANDOM_PLUGIN
libplug_la_SOURCES += urandom.c
libplug_a_SOURCES += urandom.c
endif
if BUILD_X11_COMMON_PLUGIN
libplug_la_SOURCES += x11-common.c
libplug_a_SOURCES += x11-common.c
endif
else
+6 -1
View File
@@ -76,6 +76,9 @@ endif
if DBUS
finit_SOURCES += dbus.c
endif
if PAM
finit_SOURCES += pam.c pam.h
endif
pkginclude_HEADERS = cgroup.h cond.h conf.h finit.h helpers.h log.h \
plugin.h svc.h service.h
@@ -84,8 +87,10 @@ finit_CPPFLAGS = $(AM_CPPFLAGS) -D__FINIT__
finit_CFLAGS = -W -Wall -Wextra -Wno-unused-parameter -std=gnu99
finit_CFLAGS += $(lite_CFLAGS) $(uev_CFLAGS) $(confuse_CFLAGS)
finit_LDADD = $(lite_LIBS) $(uev_LIBS) $(confuse_LIBS)
finit_LDFLAGS = $(AM_LDFLAGS)
if STATIC
finit_LDADD += ../plugins/libplug.la
finit_LDADD += ../plugins/libplug.a
finit_LDFLAGS += -Wl,--whole-archive,../plugins/libplug.a,--no-whole-archive
else
finit_LDADD += -ldl
endif
+3
View File
@@ -42,6 +42,9 @@
#include "iwatch.h"
#include "conf.h"
#include "service.h"
#ifdef AUTO_RELOAD
#include "sm.h"
#endif
#include "log.h"
#include "util.h"
+45 -7
View File
@@ -67,6 +67,9 @@
#include "legacy.h"
#include "private.h"
#include "service.h"
#ifdef AUTO_RELOAD
#include "sm.h"
#endif
#include "helpers.h"
#include "util.h"
@@ -276,6 +279,7 @@ static cfg_opt_t svc_opts[] = {
CFG_STR_LIST("capabilities", NULL, CFGF_NODEFAULT),
CFG_STR_LIST("caps", NULL, CFGF_NODEFAULT), /* alias */
CFG_STR ("pam", NULL, CFGF_NODEFAULT),
CFG_STR ("runtime-dir", NULL, CFGF_NODEFAULT),
CFG_STR ("state-dir", NULL, CFGF_NODEFAULT),
CFG_STR ("cache-dir", NULL, CFGF_NODEFAULT),
@@ -1122,7 +1126,7 @@ static int sec_getbool(cfg_t *sec, const char *key, const char *alias)
* The line-based format could only spell this as one stanza per
* candidate, relying on nowarn to skip the ones that were not
* installed. A candidate not being there is not an error here, so
* only the winner is looked up again by service_register().
* only the winner is looked up again by service_register_desc().
*
* A leading '-' still says a missing binary is expected, cf. systemd
* ExecStart=-.
@@ -1439,7 +1443,7 @@ static void provides_translate(cfg_t *sec, svc_t *svc, char *file)
/*
* These have no legacy token, they are validated by service_set_dir()
* and stored directly on the registered svc. Empty means unset,
* service_register() has already cleared the fields.
* service_register_desc() has already cleared the fields.
*/
static void dirs_translate(cfg_t *sec, svc_t *svc, char *file)
{
@@ -1485,6 +1489,41 @@ static void dirs_translate(cfg_t *sec, svc_t *svc, char *file)
}
}
/*
* Also block format only. The value names a file in /etc/pam.d, so a
* path is refused rather than followed.
*
* A bad value is stored anyway, or as much of it as fits, and
* service_start() refuses to start the service. Dropping it here
* instead would start the service with no session at all, which is the
* one outcome the service asking for a session cannot live with.
*/
static void pam_translate(cfg_t *sec, svc_t *svc, char *file)
{
const char *str;
str = sec_getstr(sec, "pam", NULL);
if (!str || !str[0])
return;
if (strlcpy(svc->pam, str, sizeof(svc->pam)) >= sizeof(svc->pam)) {
logit(LOG_ERR, "%s: %s: pam '%s' is too long, not starting",
file, cfg_title(sec), str);
return;
}
if (strchr(str, '/') || strstr(str, "..")) {
logit(LOG_ERR, "%s: %s: pam '%s' names a file in /etc/pam.d,"
" not a path, not starting", file, cfg_title(sec), str);
return;
}
if (svc->forking)
logit(LOG_WARNING, "%s: %s: pam with type = forking closes the"
" session when the initial process exits",
file, cfg_title(sec));
}
static void svc_translate(cfg_t *sec, int type, struct rlimit rlimit[], char *file)
{
struct rlimit local_rlimit[RLIMIT_NLIMITS];
@@ -1689,16 +1728,15 @@ static void svc_translate(cfg_t *sec, int type, struct rlimit rlimit[], char *fi
/* the command and its arguments, verbatim */
addtok(line, sizeof(line), "%s", cmd);
if ((str = sec_getstr(sec, "description", "desc")))
addtok(line, sizeof(line), "-- %s", str);
str = sec_getstr(sec, "description", "desc");
dbg("translated: %s", line);
svc = service_register(type, line, rlimit, file);
svc = service_register_desc(type, line, str, rlimit, file);
if (!svc)
return;
dirs_translate(sec, svc, file);
provides_translate(sec, svc, file);
pam_translate(sec, svc, file);
}
/*
@@ -1767,7 +1805,7 @@ static void tty_translate(cfg_t *sec, struct rlimit rlimit[], char *file)
addtok(line, sizeof(line), "%s", str);
dbg("translated: tty %s", line);
service_register(SVC_TYPE_TTY, line, rlimit, file);
service_register_desc(SVC_TYPE_TTY, line, NULL, rlimit, file);
}
/*
+6 -2
View File
@@ -121,15 +121,19 @@ void unmount_tmpfs(void)
}
}
void unmount_regular(void)
int unmount_regular(void)
{
const struct mntent *mnt;
FILE *fp = NULL;
int rc = 0;
while ((mnt = iterator("/proc/mounts", &fp))) {
if (!unmount(mnt->mnt_dir))
rc = unmount(mnt->mnt_dir);
if (!rc)
iterator_end(&fp); /* Restart iteration */
}
return !!rc;
}
/**
+398
View File
@@ -0,0 +1,398 @@
/* Finit PAM session support
*
* Copyright (c) 2026 Joachim Wiberg <troglobit@gmail.com>
*
* 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.
*/
#include "config.h" /* Generated by configure script */
#include <dirent.h> /* opendir(), readdir(), dirfd() */
#include <errno.h>
#include <fcntl.h> /* fcntl(), FD_CLOEXEC */
#include <grp.h> /* setgroups() */
#include <security/pam_appl.h>
#include <signal.h>
#include <stdlib.h> /* malloc(), free(), strtol() */
#include <string.h>
#include <sys/prctl.h>
#include <unistd.h>
#include "helpers.h"
#include "log.h"
#include "pam.h"
#include "svc.h"
/*
* A service has no terminal to prompt on and this path never
* authenticates, so a module that asks a question gets an error and its
* stack entry fails. For a non-interactive service that is the answer
* we want.
*/
static int pam_dialog(int num_msg, const struct pam_message **msg,
struct pam_response **resp, void *appdata)
{
return PAM_CONV_ERR;
}
static const struct pam_conv conv = {
.conv = pam_dialog,
.appdata_ptr = NULL,
};
/*
* The keeper never exec()s, so O_CLOEXEC does nothing for it, and it
* must not sit on Finit's event loop, api socket, inotify and
* notify-pipe descriptors for as long as the service lives. But PAM
* and its modules may have opened descriptors of their own while
* pam_open_session() ran, e.g. a pam_systemd/pam_elogind bus
* connection, a keyring fd, or a lock file, and those have to survive
* until pam_close_session() runs in the keeper. A blanket close of
* everything >= 3 cannot tell the two kinds apart, so take a snapshot
* of Finit's own fds before pam_start() opens anything of its own, and
* have the keeper close only those.
*
* Returns the number of fds found and sets *fdv to a malloc'd array of
* them, or -1 if /proc/self/fd could not be read, in which case the
* caller falls back to closing everything and PAM's own descriptors
* are lost along with Finit's.
*/
static int fdsnap(int **fdv)
{
struct dirent *d;
int *v;
int n, i;
DIR *dir;
int dfd;
dir = opendir("/proc/self/fd");
if (!dir)
return -1;
dfd = dirfd(dir);
n = 0;
while ((d = readdir(dir))) {
char *end;
int fd;
fd = (int)strtol(d->d_name, &end, 10);
if (*end || fd < 3 || fd == dfd)
continue;
n++;
}
if (!n) {
closedir(dir);
*fdv = NULL;
return 0;
}
v = malloc(n * sizeof(*v));
if (!v) {
closedir(dir);
return -1;
}
rewinddir(dir);
i = 0;
while (i < n && (d = readdir(dir))) {
char *end;
int fd;
fd = (int)strtol(d->d_name, &end, 10);
if (*end || fd < 3 || fd == dfd)
continue;
v[i++] = fd;
}
closedir(dir);
*fdv = v;
return i;
}
/*
* Close exactly the fds fdsnap() found, leaving PAM's own alone. With
* no snapshot (nfd < 0), fall back to closing everything >= 3, PAM's
* descriptors lost along with Finit's.
*/
static void closefds(int *fdv, int nfd)
{
long max;
int i;
if (nfd >= 0) {
for (i = 0; i < nfd; i++)
close(fdv[i]);
return;
}
max = sysconf(_SC_OPEN_MAX);
#ifdef HAVE_CLOSE_RANGE
if (!close_range(3, ~0U, 0))
return;
#endif
if (max < 0)
max = 1024;
for (i = 3; i < max; i++)
close(i);
}
/*
* The descriptors PAM opened have to survive in the keeper, but not in
* the process that goes on to exec() the service: a bus connection, a
* keyring fd or a lock file the stack opened would otherwise be
* inherited by the daemon, and by the logit helper forked next to it,
* for as long as the service lives. Finit's own fds are O_CLOEXEC,
* PAM's are not reliably, so diff a fresh snapshot against the one
* taken before pam_start() and mark everything new close-on-exec. The
* keeper is unaffected, it was forked already and has its own
* descriptor table.
*
* With no snapshot to diff against (nfd < 0) there is nothing to do
* here, telling Finit's fds from PAM's is exactly what the snapshot is
* for.
*/
static void cloexec_pamfds(const char *id, int *fdv, int nfd)
{
int *now = NULL;
int i, j, n;
if (nfd < 0)
return;
n = fdsnap(&now);
if (n < 0)
return;
for (i = 0; i < n; i++) {
int flags, old = 0;
for (j = 0; j < nfd; j++) {
if (now[i] == fdv[j]) {
old = 1;
break;
}
}
if (old)
continue;
flags = fcntl(now[i], F_GETFD);
if (flags == -1 || fcntl(now[i], F_SETFD, flags | FD_CLOEXEC))
logit(LOG_WARNING, "%s: pam: failed FD_CLOEXEC on fd %d,"
" the service inherits it", id, now[i]);
}
free(now);
}
/*
* pam_getenvlist() hands back a NUL-terminated array of malloc'd
* "NAME=value" strings. Free all of it so a failure past that point
* never leaves pamsess_open() returning a dangling *envp.
*/
static void free_envlist(char **envp)
{
char **e;
if (!envp)
return;
for (e = envp; *e; e++)
free(*e);
free(envp);
}
/*
* Holds the PAM handle for the lifetime of the service and closes the
* session when it dies. The handle was created before the fork, so
* pam_end() gets PAM_DATA_SILENT: this process is a copy, the modules
* must not run their full cleanup twice.
*/
static void keeper(pam_handle_t *h, uid_t uid, gid_t gid, pid_t ppid,
sigset_t *mask, const char *id, int *fdv, int nfd)
{
int rc, sig;
/* Finit's syslog socket is one of the fds about to be closed;
* close it here first so syslog(3) knows to reconnect instead
* of writing to a fd pulled out from under it. */
closelog();
closefds(fdv, nfd);
setprocnm("(finit-pam)");
/* No groups are needed to close a session */
if (setgroups(0, NULL))
warn("%s: pam: failed setgroups()", id);
if (setgid(gid))
warn("%s: pam: failed setgid(%d)", id, gid);
if (setuid(uid))
warn("%s: pam: failed setuid(%d)", id, uid);
/* After the credential change, which clears a pending pdeath signal */
if (prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0))
warn("%s: pam: failed PR_SET_PDEATHSIG", id);
/* The service may have exited already, then no signal is coming.
* Anything but success means SIGTERM has not arrived yet, so keep
* waiting: closing the session under a service that is still
* running would leave nobody to close it later. glibc reports
* the error number as the return value and musl returns -1 with
* errno set, hence the test on rc alone. The mask is static, so
* a failure that never clears is not reachable here. */
if (getppid() == ppid) {
do {
rc = sigwait(mask, &sig);
} while (rc);
}
rc = pam_setcred(h, PAM_DELETE_CRED | PAM_SILENT);
if (rc != PAM_SUCCESS)
logit(LOG_WARNING, "%s: pam: failed pam_setcred(DELETE_CRED): %s",
id, pam_strerror(h, rc));
rc = pam_close_session(h, PAM_SILENT);
if (rc != PAM_SUCCESS)
logit(LOG_WARNING, "%s: pam: failed pam_close_session(): %s",
id, pam_strerror(h, rc));
pam_end(h, rc | PAM_DATA_SILENT);
_exit(0);
}
/*
* Open a PAM session for svc, as root, before privileges are dropped.
* On success a keeper process has been forked and *envp holds the
* session environment for the caller to apply. The process that goes
* on to exec() must not call pam_end(), its handle disappears with the
* exec; only the keeper ever closes the session. *envp is only ever
* non-NULL on success.
*/
int pamsess_open(svc_t *svc, uid_t uid, gid_t gid, char ***envp)
{
char *id = svc_ident(svc, NULL, 0);
pam_handle_t *h = NULL;
const char *user;
sigset_t mask, omask;
pid_t pid, ppid;
int *fdv = NULL;
int rc, nfd;
const char *why;
*envp = NULL;
/* Every fork funnels through here, service_start() only guards
* the daemon itself, so this is where a value that must not
* reach pam_start() is stopped. */
why = pam_invalid(svc->pam);
if (why) {
logit(LOG_ERR, "%s: pam '%s' %s", id, svc->pam, why);
return -1;
}
/* Snapshot Finit's own fds before pam_start() opens anything */
nfd = fdsnap(&fdv);
user = svc->username[0] ? svc->username : "root";
rc = pam_start(svc->pam, user, &conv, &h);
if (rc != PAM_SUCCESS) {
logit(LOG_ERR, "%s: failed pam_start(%s, %s): %s", id,
svc->pam, user, pam_strerror(h, rc));
free(fdv);
return -1;
}
if (svc_has_ctty(svc)) {
rc = pam_set_item(h, PAM_TTY, svc->log.ctty);
if (rc != PAM_SUCCESS)
logit(LOG_WARNING, "%s: failed pam_set_item(PAM_TTY, %s): %s",
id, svc->log.ctty, pam_strerror(h, rc));
}
rc = pam_acct_mgmt(h, PAM_SILENT);
if (rc != PAM_SUCCESS) {
logit(LOG_ERR, "%s: account denied by %s: %s", id, svc->pam,
pam_strerror(h, rc));
goto fail;
}
rc = pam_setcred(h, PAM_ESTABLISH_CRED | PAM_SILENT);
if (rc != PAM_SUCCESS) {
logit(LOG_ERR, "%s: failed pam_setcred(%s): %s", id, svc->pam,
pam_strerror(h, rc));
goto fail;
}
rc = pam_open_session(h, PAM_SILENT);
if (rc != PAM_SUCCESS) {
logit(LOG_ERR, "%s: failed pam_open_session(%s): %s", id,
svc->pam, pam_strerror(h, rc));
goto cred;
}
*envp = pam_getenvlist(h);
/* Block SIGTERM before forking, the keeper must not miss it */
sigemptyset(&mask);
sigaddset(&mask, SIGTERM);
sigprocmask(SIG_BLOCK, &mask, &omask);
/* Forked here, before the service child calls setsid(), so the
* keeper stays in Finit's process group. Teardown does
* kill(-svc->pid, SIGKILL) on the service's group, and a keeper
* that had ended up there would be killed with the service,
* before it ever gets to close the session. */
ppid = getpid();
pid = fork();
if (pid < 0) {
err(1, "%s: failed forking off PAM session keeper", id);
sigprocmask(SIG_SETMASK, &omask, NULL);
pam_close_session(h, PAM_SILENT);
free_envlist(*envp);
*envp = NULL;
goto cred;
}
if (!pid)
keeper(h, uid, gid, ppid, &mask, id, fdv, nfd); /* does not return */
sigprocmask(SIG_SETMASK, &omask, NULL);
cloexec_pamfds(id, fdv, nfd);
free(fdv);
dbg("%s: PAM session %s open, keeper is PID %d", id, svc->pam, pid);
return 0;
cred:
pam_setcred(h, PAM_DELETE_CRED | PAM_SILENT);
fail:
free(fdv);
pam_end(h, rc);
return -1;
}
/**
* Local Variables:
* indent-tabs-mode: t
* c-file-style: "linux"
* End:
*/
+60
View File
@@ -0,0 +1,60 @@
/* Finit PAM session support
*
* Copyright (c) 2026 Joachim Wiberg <troglobit@gmail.com>
*
* 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.
*/
#ifndef FINIT_PAM_H_
#define FINIT_PAM_H_
#include <string.h> /* strchr(), strlen(), strstr() */
#include <sys/types.h>
#include "svc.h"
/*
* A pam value names a file in /etc/pam.d, it is not a path, and conf.c
* stores an over-long value truncated, so a value filling the buffer
* must not be passed on as some other, shorter name that happens to
* exist. Both users share this one definition: service_start(), which
* refuses the service outright, log line and a visible state, and
* pamsess_open(), which every fork funnels through, including the pre:,
* post:, ready:, cleanup:, stop and reload scripts that run before
* service_start() ever does.
*
* Returns why the value cannot be used, or NULL when it can.
*/
static inline const char *pam_invalid(const char *pam)
{
if (!pam[0])
return NULL;
if (strlen(pam) >= MAX_ARG_LEN - 1)
return "is too long";
if (strchr(pam, '/') || strstr(pam, ".."))
return "names a file in /etc/pam.d, not a path";
return NULL;
}
int pamsess_open(svc_t *svc, uid_t uid, gid_t gid, char ***envp);
#endif /* FINIT_PAM_H_ */
+200 -42
View File
@@ -54,6 +54,7 @@
#include "devmon.h"
#include "finit.h"
#include "helpers.h"
#include "pam.h"
#include "pid.h"
#include "private.h"
#include "sig.h"
@@ -544,10 +545,22 @@ static void set_uid(uid_t uid, svc_t *svc)
*/
if (svc->capabilities[0]) {
cap_iab_t cap_iab;
#ifdef HAVE_LIBPAM
cap_iab_t pam_iab = NULL;
cap_value_t c;
/*
* A module like pam_cap.so may have granted ambient
* capabilities. Capture them while we are still root,
* cap_setuid() below clears them.
*/
if (svc->pam[0])
pam_iab = cap_iab_get_proc();
#endif
if (cap_setuid(uid)) {
err(1, "%s: failed cap_setuid(%d)", svc_ident(svc, NULL, 0), uid);
return;
goto out;
}
/* After dropping privileges, set the specific capabilities we need */
@@ -555,15 +568,30 @@ static void set_uid(uid_t uid, svc_t *svc)
if (!cap_iab) {
err(1, "%s: failed parsing capabilities '%s'",
svc_ident(svc, NULL, 0), svc->capabilities);
return;
goto out;
}
#ifdef HAVE_LIBPAM
/* Merge, do not overwrite, what PAM granted */
if (pam_iab) {
for (c = 0; c <= CAP_LAST_CAP; c++) {
if (cap_iab_get_vector(pam_iab, CAP_IAB_AMB, c))
cap_iab_set_vector(cap_iab, CAP_IAB_AMB, c, CAP_SET);
}
}
#endif
if (cap_iab_set_proc(cap_iab) != 0) {
cap_free(cap_iab);
err(1, "%s: failed setting capabilities",
svc_ident(svc, NULL, 0));
}
cap_free(cap_iab);
out:
#ifdef HAVE_LIBPAM
cap_free(pam_iab);
#endif
return;
} else
#endif
if (setuid(uid))
@@ -703,6 +731,9 @@ static pid_t service_fork(svc_t *svc)
if (pid == 0) {
char *home = NULL;
#ifdef HAVE_LIBPAM
char **pam_env = NULL;
#endif
#ifdef ENABLE_STATIC
int uid = 0; /* XXX: Fix better warning that dropprivs is disabled. */
int gid = 0;
@@ -735,6 +766,15 @@ static pid_t service_fork(svc_t *svc)
svc_ident(svc, NULL, 0), rlim2str(i));
}
#ifdef HAVE_LIBPAM
/*
* After our own rlimits so pam_limits wins, and before
* any credential change: the session stack needs root.
*/
if (svc->pam[0] && pamsess_open(svc, uid, gid, &pam_env))
_exit(EX_OSERR);
#endif
#ifndef ENABLE_STATIC
/* Set supplementary groups from /etc/group and config */
{
@@ -797,6 +837,28 @@ static pid_t service_fork(svc_t *svc)
}
}
#ifdef HAVE_LIBPAM
/* pam_env after our defaults, before env:file */
if (pam_env) {
const char *pam_home;
for (int i = 0; pam_env[i]; i++)
putenv(pam_env[i]);
/* pam_env has the last word on HOME, so the
* working directory has to follow it, the chdir()
* above used the passwd home. */
pam_home = getenv("HOME");
if (pam_home && (!home || strcmp(pam_home, home))) {
if (chdir(pam_home)) {
if (chdir("/"))
err(1, "%s: failed chdir(%s) and chdir(/)",
svc_ident(svc, NULL, 0), pam_home);
}
}
}
#endif
/* Source any environment from env:/path/to/file */
source_env(svc);
}
@@ -811,6 +873,26 @@ static pid_t service_fork(svc_t *svc)
return pid;
}
/*
* Checked here, next to the other preconditions, and not only in
* conf.c, because a .conf reload rewrites the service and would
* otherwise let a refused value start it after all. Running without
* the session the service asked for costs it pam_limits, its private
* /tmp, and its logind session, with nothing said.
*/
static int pam_refused(svc_t *svc)
{
const char *why = pam_invalid(svc->pam);
if (!why)
return 0;
logit(LOG_ERR, "%s: pam '%s' %s, not starting",
svc_ident(svc, NULL, 0), svc->pam, why);
return 1;
}
/**
* service_start - Start service
* @svc: Service to start
@@ -854,6 +936,20 @@ static int service_start(svc_t *svc)
return 1;
}
if (pam_refused(svc)) {
svc_missing(svc);
return 1;
}
#ifndef HAVE_LIBPAM
if (svc->pam[0]) {
logit(LOG_ERR, "%s: pam %s requires Finit built with --enable-pam",
svc_ident(svc, NULL, 0), svc->pam);
svc_missing(svc);
return 1;
}
#endif
if (svc_is_tty(svc) && !svc->notty) {
char *dev = tty_canonicalize(svc->dev);
@@ -1503,6 +1599,15 @@ int service_restart_now(svc_t *svc)
if (!svc)
return 1;
if (svc_is_runtask(svc) && svc_is_remain(svc) &&
svc->state == SVC_DONE_STATE) {
service_timeout_cancel(svc);
svc_restarting(svc);
service_step(svc);
return 0;
}
if (!svc_is_running(svc))
return service_start_now(svc);
@@ -1707,6 +1812,24 @@ static char *parse_args(char **line)
return NULL;
}
/*
* Match an option that takes a value, @opt on its own or followed by
* one of the characters in @sep, e.g. "log" and "log:/path". Returns
* the value, or NULL, so a command like logger or pidof is not taken
* for an option.
*/
static char *is_opt(char *tok, const char *opt, const char *sep)
{
size_t len = strlen(opt);
if (strncasecmp(tok, opt, len))
return NULL;
if (tok[len] && !strchr(sep, tok[len]))
return NULL;
return &tok[len];
}
/*
* log:/path/to/logfile,priority:facility.level,tag:ident
*/
@@ -2051,9 +2174,10 @@ static void parse_cmdline_args(svc_t *svc, char *cmd, char **args)
}
/**
* service_register - Register service, task or run commands
* service_register_desc - Register service, task or run commands
* @type: %SVC_TYPE_SERVICE(0), %SVC_TYPE_TASK(1), %SVC_TYPE_RUN(2)
* @cfg: Configuration, complete command, with -- for description text
* @cfg: Configuration, complete command, without description text
* @desc: Description text, or %NULL
* @rlimit: Limits for this service/task/run, may be global limits
* @file: The file name service was loaded from
*
@@ -2111,9 +2235,10 @@ static void parse_cmdline_args(svc_t *svc, char *cmd, char **args)
* skipped on purpose -- conditional loading, bootstrap over, nowarn --
* also returns %NULL, with @errno zero.
*/
svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
svc_t *service_register_desc(int type, char *cfg, const char *desc,
struct rlimit rlimit[], char *file)
{
char *cmd, *desc, *runlevels = NULL, *cond = NULL;
char *cmd, *runlevels = NULL, *cond = NULL;
char *username = NULL, *log = NULL, *pid = NULL;
char *name = NULL, *halt = NULL, *delay = NULL;
char *id = NULL, *env = NULL, *cgroup = NULL;
@@ -2149,24 +2274,6 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
return NULL;
}
desc = strstr(line, "-- ");
if (desc) {
*desc = 0;
desc += 3;
while (*desc && isblank(*desc))
desc++;
} else {
int pos;
/* Find "--\n" to denote empty/no description */
pos = (int)strlen(line) - 2;
if (pos > 0 && !strcmp(&line[pos], "--")) {
line[pos] = 0;
desc = &line[pos];
}
}
args = line;
cmd = parse_args(&args);
if (!cmd) {
@@ -2176,6 +2283,10 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
return NULL;
}
/*
* Options ending in ':' can be prefix matched, the rest must match
* the whole token or a command like logger is taken for one.
*/
while (cmd) {
char *arg;
@@ -2190,19 +2301,19 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
cond = &cmd[1];
else if (cmd[0] == ':') /* :ID */
id = &cmd[1];
else if (MATCH_CMD(cmd, "log", arg))
else if (is_opt(cmd, "log", ":"))
log = cmd;
else if (MATCH_CMD(cmd, "pid", arg))
else if (is_opt(cmd, "pid", ":"))
pid = cmd;
else if (MATCH_CMD(cmd, "name:", arg))
name = cmd;
else if (MATCH_CMD(cmd, "notify:", arg))
notify = arg;
else if (MATCH_CMD(cmd, "type:forking", arg))
else if (!strcasecmp(cmd, "type:forking"))
forking = 1;
else if (MATCH_CMD(cmd, "manual:yes", arg))
else if (!strcasecmp(cmd, "manual:yes"))
manual = 1;
else if (MATCH_CMD(cmd, "remain:yes", arg))
else if (!strcasecmp(cmd, "remain:yes"))
remain = 1;
else if (MATCH_CMD(cmd, "restart:", arg)) {
if (MATCH_CMD(arg, "always", arg))
@@ -2214,9 +2325,9 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
restart_tmo = atoi(arg) * 1000;
else if (MATCH_CMD(cmd, "restart_sec:", arg))
restart_tmo = atoi(arg) * 1000;
else if (MATCH_CMD(cmd, "norestart", arg))
else if (!strcasecmp(cmd, "norestart"))
restart_max = 0;
else if (MATCH_CMD(cmd, "nowarn", arg))
else if (!strcasecmp(cmd, "nowarn"))
nowarn = 1;
else if (MATCH_CMD(cmd, "oncrash:", arg)) {
if (MATCH_CMD(arg, "reboot", arg))
@@ -2224,7 +2335,7 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
if (MATCH_CMD(arg, "script", arg))
oncrash_action = SVC_ONCRASH_SCRIPT;
}
else if (MATCH_CMD(cmd, "respawn", arg))
else if (!strcasecmp(cmd, "respawn"))
respawn = 1;
else if (MATCH_CMD(cmd, "halt:", arg))
halt = arg;
@@ -2249,7 +2360,7 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
else if (MATCH_CMD(cmd, "tty:", arg))
ctty = arg;
/* catch both cgroup: and cgroup. handled in parse_cgroup() */
else if (MATCH_CMD(cmd, "cgroup", arg))
else if ((arg = is_opt(cmd, "cgroup", ".:")))
cgroup = arg;
else if (MATCH_CMD(cmd, "conflict:", arg))
conflict = arg;
@@ -2505,6 +2616,7 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
memset(svc->capabilities, 0, sizeof(svc->capabilities));
/* block format only, set by conf.c after registration */
memset(svc->pam, 0, sizeof(svc->pam));
for (int i = 0; i < NUM_SVCDIRS; i++) {
memset((char *)svc + svcdirs[i].off, 0, MAX_ARG_LEN);
svc->dir_mode[i] = 0755;
@@ -2606,11 +2718,14 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
if (cgroup)
parse_cgroup(svc, cgroup);
/* New, recently modified or unchanged ... used on reload. */
/*
* New or modified since the last reload. The mark is cleared when
* the change has been applied, on start or reload, so one that is
* still set here is a change that has not been applied yet, e.g.
* the service is paused waiting for a condition. Leave it.
*/
if ((file && conf_changed(file)) || conf_changed(svc_getenv(svc)) || svc->args_dirty)
svc_mark_dirty(svc);
else
svc_mark_clean(svc);
svc_enable(svc);
@@ -2630,6 +2745,45 @@ svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
return svc;
}
/**
* service_register - Register from a legacy one-liner
* @type: %SVC_TYPE_SERVICE(0), %SVC_TYPE_TASK(1), %SVC_TYPE_RUN(2)
* @cfg: Configuration, complete command, with -- for description text
* @rlimit: Limits for this service/task/run, may be global limits
* @file: The file name service was loaded from
*
* The first "-- " in @cfg starts the description, the rest is handed
* to service_register_desc().
*/
svc_t *service_register(int type, char *cfg, struct rlimit rlimit[], char *file)
{
char *line, *desc;
if (!cfg)
return service_register_desc(type, cfg, NULL, rlimit, file);
line = strdupa(cfg);
desc = strstr(line, "-- ");
if (desc) {
*desc = 0;
desc += 3;
while (*desc && isblank(*desc))
desc++;
} else {
int pos;
/* Find "--\n" to denote empty/no description */
pos = (int)strlen(line) - 2;
if (pos > 0 && !strcmp(&line[pos], "--")) {
line[pos] = 0;
desc = &line[pos];
}
}
return service_register_desc(type, line, desc, rlimit, file);
}
/*
* This function is called at the end of a runlevel change or reload
* command to delete all remnants of removed services.
@@ -3278,8 +3432,8 @@ restart:
svc_set_state(svc, SVC_CLEANUP_STATE);
service_cleanup_script(svc);
} else {
/* Unblock remain tasks after post script so they can restart */
if (svc_is_remain(svc))
/* Restart remain tasks after runlevel/reload/restart teardown. */
if (svc_is_remain(svc) && svc_is_restart(svc))
svc_unblock(svc);
svc_set_state(svc, SVC_HALTED_STATE);
}
@@ -3298,13 +3452,17 @@ restart:
break;
case SVC_DONE_STATE:
/* Remain tasks: always run post script when stopped, even if config changed */
if (svc_is_runtask(svc) && svc_is_remain(svc) && svc_is_stopped(svc)) {
/* Remain tasks run post script before stopping or restarting. */
if (svc_is_runtask(svc) && svc_is_remain(svc) &&
(svc_is_stopped(svc) || svc_is_restart(svc))) {
if (svc_has_post(svc)) {
svc_set_state(svc, SVC_TEARDOWN_STATE);
service_post_script(svc);
} else
} else {
if (svc_is_restart(svc))
svc_unblock(svc);
svc_set_state(svc, SVC_HALTED_STATE);
}
} else if (svc_is_changed(svc))
svc_set_state(svc, SVC_HALTED_STATE);
else if (svc_is_runtask(svc) && svc_is_manual(svc) && enabled)
@@ -3627,7 +3785,7 @@ void service_runtask_clean(void)
/* Config changed or leaving runlevel: stop, run post, restart */
svc->once = 0;
svc_stop(svc);
svc_restarting(svc);
service_step(svc);
continue;
}
+2
View File
@@ -44,6 +44,8 @@ extern const struct svcdir svcdirs[NUM_SVCDIRS];
int service_set_dir (svc_t *svc, const struct svcdir *sd, const char *name);
svc_t *service_register (int type, char *line, struct rlimit rlimit[], char *file);
svc_t *service_register_desc (int type, char *line, const char *desc,
struct rlimit rlimit[], char *file);
void service_unregister (svc_t *svc);
void service_runtask_clean (void);
+8 -6
View File
@@ -170,7 +170,7 @@ static struct sigmap {
void mdadm_wait(void);
void unmount_tmpfs(void);
void unmount_regular(void);
int unmount_regular(void);
static void fs_swapoff(void)
{
@@ -302,6 +302,7 @@ void do_shutdown(shutop_t op)
struct sched_param sched_param = { .sched_priority = 99 };
int in_cont = in_container();
int signo = SIGTERM;
int rc;
if (SHUTDOWN_DEBUG) cprintf("do_shutdown: entered, op=%d\n", op);
@@ -377,12 +378,13 @@ void do_shutdown(shutop_t op)
}
/* Unmount any tmpfs before unmounting swap ... */
print(0, "Unmounting filesystems ...");
print(-1, "Unmounting filesystems ...");
unmount_tmpfs();
fs_swapoff();
/* ... unmount remaining regular file systems. */
unmount_regular();
rc = unmount_regular();
print(rc, NULL);
/*
* We sit on / so we must remount it ro, try all the things!
@@ -391,9 +393,9 @@ void do_shutdown(shutop_t op)
* - https://bugs.launchpad.net/ubuntu/+source/util-linux/+bug/29187
*/
sync();
run("mount -n -o remount,ro -t dummytype dummydev /", NULL);
run("mount -n -o remount,ro dummydev /", NULL);
run("mount -n -o remount,ro /", "mount");
if (run("mount -n -o remount,ro -t dummytype dummydev /", NULL) &&
run("mount -n -o remount,ro dummydev /", NULL))
run("mount -n -o remount,ro /", "mount");
/* Call mdadm to mark any RAID array(s) as clean before halting. */
mdadm_wait();
+2 -1
View File
@@ -100,7 +100,7 @@ typedef enum {
#define MAX_IDENT_LEN (MAX_ARG_LEN + MAX_ID_LEN + 1)
#define MAX_STR_LEN 64
#define MAX_COND_LEN (MAX_ARG_LEN * 3)
#define MAX_USER_LEN 16
#define MAX_USER_LEN MAX_ARG_LEN
#define MAX_NUM_SUPGROUPS 4
#define MAX_NUM_PROVIDES 4
#define MAX_NUM_FDS 64 /* Max number of I/O plugins */
@@ -203,6 +203,7 @@ typedef struct svc {
char supgroups[MAX_NUM_SUPGROUPS][MAX_USER_LEN];
int num_supgroups;
char capabilities[MAX_CMD_LEN];
char pam[MAX_ARG_LEN]; /* /etc/pam.d/NAME, block format only */
/* Directories set up for the service, block format only, the
* name is resolved under a fixed base, e.g. /run/NAME */
+50 -42
View File
@@ -24,6 +24,7 @@
#include "config.h" /* Generated by configure script */
#include <dirent.h>
#include <fcntl.h>
#include <ftw.h>
#include <getopt.h>
#include <glob.h>
@@ -557,67 +558,74 @@ static void tmpfiles(char *line)
if (gid < 0)
gid = 0;
rc = makedir(path, mode ?: 0755);
if (rc && errno == EEXIST)
rc = chmod(path, mode ?: 0755);
if (chown(path, uid, gid))
warn("Failed chown(%s, %d, %d)", path, uid, gid);
if (!mode)
mode = 0755;
rc = makedir(path, mode);
if (!rc && dirperm(path, mode, uid, gid))
warn("Failed setting mode/owner on %s", path);
}
umask(omask);
break;
}
case 'e':
case 'e': {
int uid, gid;
if (glob(path, GLOB_NOESCAPE, NULL, &gl))
break;
uid = parse_uid(user);
gid = parse_gid(group);
if (gid < 0)
gid = 0;
for (size_t i = 0; i < gl.gl_pathc; i++) {
char *p = gl.gl_pathv[i];
int uid, gid;
/* e only adjusts existing directories */
if (!fisdir(p))
continue;
uid = parse_uid(user);
gid = parse_gid(group);
if (gid < 0)
gid = 0;
if (mode)
chmod(p, mode);
if (uid >= 0 && chown(p, uid, gid))
warn("Failed chown(%s, %d, %d)", p, uid, gid);
/* skip non-directories */
if (dirperm(p, mode, uid, gid) && errno != ENOTDIR)
warn("Failed setting mode/owner on %s", p);
}
break;
}
case 'f':
case 'F':
mkparent(path, 0755);
case 'F': {
int flags = O_WRONLY | O_CREAT | O_NOFOLLOW | O_CLOEXEC;
int fd, uid, gid;
if (type[1] == '+' || type[0] == 'F') {
/* f+/F will create or truncate the file */
fp = fopen(path, "w+");
flags |= O_TRUNC; /* create or truncate */
} else {
/* f will create the file if it doesn't exist */
if (strc)
fp = fopen(path, "w");
if (!strc)
break; /* create only if missing */
flags |= O_EXCL;
}
if (fp) {
int uid, gid;
write_arg(fp, arg);
rc = fclose(fp);
/* Apply mode and ownership */
if (mode)
chmod(path, mode);
uid = parse_uid(user);
gid = parse_gid(group);
if (gid < 0)
gid = 0;
if (uid >= 0 && chown(path, uid, gid))
warn("Failed chown(%s, %d, %d)", path, uid, gid);
mkparent(path, 0755);
fd = open(path, flags, 0666);
if (fd < 0) {
if (errno != EEXIST)
warn("Failed creating %s", path);
break;
}
fp = fdopen(fd, "w");
if (!fp) {
close(fd);
break;
}
write_arg(fp, arg);
uid = parse_uid(user);
gid = parse_gid(group);
if (gid < 0)
gid = 0;
if (fdperm(fd, mode, uid, gid))
warn("Failed setting mode/owner on %s", path);
rc = fclose(fp);
break;
}
case 'l': /* Finit extension, like 'L' but only if target exists */
if (!arg) {
paste(buf, sizeof(buf), "/usr/share/factory", path);
+40 -5
View File
@@ -25,6 +25,7 @@
#include <ctype.h> /* isprint() */
#include <errno.h>
#include <fcntl.h>
#include <grp.h>
#include <pwd.h>
#ifdef HAVE_MNTENT_H
@@ -374,6 +375,43 @@ int rmrf(const char *path)
return 0;
}
/*
* Set mode and owner on an open fd, only what differs is touched, the
* file may be immutable. mode 0 skips the chmod, uid -1 the chown.
*/
int fdperm(int fd, mode_t mode, uid_t uid, gid_t gid)
{
struct stat st;
int rc;
rc = fstat(fd, &st);
if (!rc && mode && (st.st_mode & 07777) != mode)
rc = fchmod(fd, mode);
if (!rc && uid != (uid_t)-1 && (st.st_uid != uid || st.st_gid != gid))
rc = fchown(fd, uid, gid);
return rc;
}
/*
* Same for a directory that may already exist. Opened with
* O_NOFOLLOW | O_DIRECTORY, so the change lands on the directory
* itself and not on whatever a link at @path points to.
*/
int dirperm(const char *path, mode_t mode, uid_t uid, gid_t gid)
{
int fd, rc;
fd = open(path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
if (fd < 0)
return -1;
rc = fdperm(fd, mode, uid, gid);
close(fd);
return rc;
}
/*
* Like mksubsys() but with the ids already resolved, uid -1 skips the
* chown. Parents are created 0755, only the leaf gets @mode.
@@ -386,11 +424,8 @@ int mksubsysd(const char *dir, mode_t mode, uid_t uid, gid_t gid)
omask = umask(0);
rc = mkpath(dir, 0755);
if (!rc) {
rc = chmod(dir, mode);
if (!rc && uid != (uid_t)-1 && chown(dir, uid, gid))
err(1, "Failed chown(%s, %d, %d)", dir, (int)uid, (int)gid);
}
if (!rc && dirperm(dir, mode, uid, gid))
warn("Failed setting mode/owner on %s", dir);
umask(omask);
+2
View File
@@ -71,6 +71,8 @@ int getgroup (const char *group);
int getcuser (char *buf, size_t len);
int getcgroup (char *buf, size_t len);
int fdperm (int fd, mode_t mode, uid_t uid, gid_t gid);
int dirperm (const char *path, mode_t mode, uid_t uid, gid_t gid);
int mksubsys (const char *dir, mode_t mode, char *user, char *group);
int mksubsysd (const char *dir, mode_t mode, uid_t uid, gid_t gid);
int chownr (const char *path, uid_t uid, gid_t gid);
+6
View File
@@ -43,6 +43,7 @@ EXTRA_DIST += conf-template.sh
EXTRA_DIST += script-timeout.sh
EXTRA_DIST += crashing.sh
EXTRA_DIST += dep-chain-reload.sh
EXTRA_DIST += reload-while-paused.sh
EXTRA_DIST += depserv.sh
EXTRA_DIST += devmon.sh
EXTRA_DIST += failing-sysv.sh
@@ -51,6 +52,7 @@ EXTRA_DIST += global-envs.sh
EXTRA_DIST += initctl-status-subset.sh
EXTRA_DIST += keventd.sh
EXTRA_DIST += notify.sh
EXTRA_DIST += pam-session.sh
EXTRA_DIST += pidfile.sh
EXTRA_DIST += stale-pidfile.sh
EXTRA_DIST += pre-post-serv.sh
@@ -58,6 +60,7 @@ EXTRA_DIST += pre-fail.sh
EXTRA_DIST += process-depends.sh
EXTRA_DIST += rclocal.sh
EXTRA_DIST += ready-serv.sh
EXTRA_DIST += remain-task-control.sh
EXTRA_DIST += restart-self.sh
EXTRA_DIST += runlevel.sh
EXTRA_DIST += run-restart-forever.sh
@@ -108,6 +111,7 @@ TESTS += conf-template.sh
TESTS += script-timeout.sh
TESTS += crashing.sh
TESTS += dep-chain-reload.sh
TESTS += reload-while-paused.sh
TESTS += depserv.sh
TESTS += devmon.sh
TESTS += failing-sysv.sh
@@ -118,6 +122,7 @@ if KEVENTD
TESTS += keventd.sh
endif
TESTS += notify.sh
TESTS += pam-session.sh
TESTS += pidfile.sh
TESTS += stale-pidfile.sh
TESTS += pre-post-serv.sh
@@ -125,6 +130,7 @@ TESTS += pre-fail.sh
TESTS += process-depends.sh
TESTS += rclocal.sh
TESTS += ready-serv.sh
TESTS += remain-task-control.sh
TESTS += restart-self.sh
TESTS += runlevel.sh
TESTS += sysvparts.sh
+24 -1
View File
@@ -76,6 +76,29 @@ retry 'assert_cmd pick "serv -np -i pick"'
assert_desc "Single command" pick
assert_num_children 1 serv
# The description has its own setting, so a -- in the command is an
# argument to it, see issue #512.
say 'A -- in the command is passed on to it'
run "echo 'service pick {' > $FINIT_CONF"
run "echo ' description = \"Dashes\"' >> $FINIT_CONF"
run "echo ' command = \"serv -np -i pick -- extra\"' >> $FINIT_CONF"
run "echo '}' >> $FINIT_CONF"
run "initctl reload"
retry 'assert_cmd pick "serv -np -i pick -- extra"'
assert_desc "Dashes" pick
assert_num_children 1 serv
# Options are matched as whole tokens, so a command that merely starts
# like one, pidof vs. pid, is still the command.
say 'A command named like an option is the command'
run "echo 'task lookalike {' > $FINIT_CONF"
run "echo ' command = \"pidof serv\"' >> $FINIT_CONF"
run "echo '}' >> $FINIT_CONF"
run "initctl reload"
retry 'assert_cmd lookalike "pidof serv"'
# A tty block takes the same list, its command is the getty to run.
# Asserting it is loaded is enough here, a getty in the test namespace
# has no terminal to attach to.
@@ -90,7 +113,7 @@ retry 'assert_cmd tty "serv -np -i ttypick"'
# Nothing resolves, so the block is skipped the same way a single
# missing command is. The leading - only decides whether that is
# quiet, service_register() bails before svc_new() either way.
# quiet, service_register_desc() bails before svc_new() either way.
say 'A block whose candidates are all missing is skipped'
run "echo 'service ghost {' > $FINIT_CONF"
run "echo ' command = { \"-/no/such/one\", \"-/no/such/two\" }' >> $FINIT_CONF"
+11 -1
View File
@@ -39,6 +39,15 @@ BBURL ?= $(BBHOME)/$(BBVER)/$(BBBIN)
_libs_nss := $(firstword $(wildcard /lib/$(ARCH)-linux-gnu/libnss_files.so.2 \
/usr/lib/$(ARCH)-linux-gnu/libnss_files.so.2 \
/lib64/libnss_files.so.2 /lib/libnss_files.so.2))
# PAM dlopen()s its modules too, so ldd cannot see them either. Only
# the three the pam-session test needs; absent is fine, it skips. Their
# own dependencies are picked up by the ldd pass below. libpam looks in
# one compiled-in directory, and here /lib and /usr/lib are two real
# directories rather than the host's symlink, so /usr/lib comes first.
_pam_mods := $(foreach m,pam_permit.so pam_deny.so pam_limits.so, \
$(firstword $(wildcard /usr/lib/$(ARCH)-linux-gnu/security/$(m) \
/lib/$(ARCH)-linux-gnu/security/$(m) \
/lib/security/$(m))))
# A real broker and a real client, staged when the host has them, so
# one test can check Finit against dbus-daemon instead of only against
# libink's own client. Absent is fine, dbus-broker.sh skips.
@@ -53,7 +62,8 @@ _bins := $(FINITBIN) $(dbus_bins) \
# The dbus binaries stage exactly like the libraries: same host path,
# same path under DEST, copied by the rule below.
_libs_src := $(foreach bin,$(_bins),$(shell ldd $(bin) 2>/dev/null | grep -Eo '/[^ ]+')) \
$(_libs_nss) $(dbus_bins)
$(foreach mod,$(_pam_mods),$(shell ldd $(mod) 2>/dev/null | grep -Eo '/[^ ]+')) \
$(_libs_nss) $(_pam_mods) $(dbus_bins)
libs := $(foreach path,$(sort $(_libs_src)),$(abspath $(DEST))$(path))
all: $(libs) $(DEST)/bin/$(BBBIN)
+122
View File
@@ -0,0 +1,122 @@
#!/bin/sh
# A service can run inside a PAM session, so the session stack in
# /etc/pam.d applies to the process that becomes the daemon.
#
# The session outlives the setup: a keeper process, (finit-pam), holds
# the PAM handle and closes the session when the service dies. Here we
# check that it appears and disappears with the service, that a denied
# account stack keeps the service from running at all, and that a
# missing pam.d config, or a value that is a path rather than a name,
# does the same.
#
# Skipped unless Finit was built --enable-pam and the host had PAM
# modules for lib/sysroot.mk to stage.
set -eu
TEST_DIR=$(dirname "$0")
test_teardown()
{
say "Running test teardown."
run "rm -f $FINIT_CONF"
run "rm -f /tmp/pre"
run "rm -rf /etc/pam.d"
run "rm -rf /etc/security"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
# shellcheck disable=SC2154 # top_builddir comes from AM_TESTS_ENVIRONMENT
grep -q "define HAVE_LIBPAM" "$top_builddir/config.h" 2>/dev/null \
|| skip "Finit built without --enable-pam"
# Staged by lib/sysroot.mk from the host, when it has them. All three,
# not just pam_permit.so: without pam_deny.so the denied case would fail
# for the wrong reason and still look like a pass.
# shellcheck disable=SC2016 # the globs are for the shell inside texec
PAMDIR=$(texec sh -c 'for d in /lib/*/security /usr/lib/*/security /lib/security; do
test -f "$d/pam_permit.so" || continue
test -f "$d/pam_deny.so" || continue
test -f "$d/pam_limits.so" || continue
echo "$d" && break
done')
[ -n "$PAMDIR" ] || skip "no PAM modules in the test root, need them on the host"
assert_keeper()
{
assert "$1 PAM session keeper(s)" \
"$(texec sh -c 'cat /proc/[0-9]*/comm 2>/dev/null | grep -c "(finit-pam)"' || true)" -eq "$1"
}
# pamsess_open() leaves the child with EX_OSERR, so a service that fails
# for any other reason -- a bad command, a pidfile it cannot write -- is
# a test failure rather than a pass.
denied="crashed (code=exited, status=71/OSERR)"
say 'A permissive PAM config, and one that denies the account stack'
run "mkdir -p /etc/pam.d"
run "printf 'auth required pam_permit.so\naccount required pam_permit.so\nsession required pam_permit.so\n' > /etc/pam.d/finit-ok"
run "printf 'auth required pam_permit.so\naccount required pam_deny.so\nsession required pam_permit.so\n' > /etc/pam.d/finit-no"
say 'A service in a session runs, and a keeper appears alongside it'
run "printf 'service pamok {\n runlevel = \"S12345\"\n user = \"daemon\"\n pam = \"finit-ok\"\n command = \"/sbin/serv -n -i pamok\"\n}\n' > $FINIT_CONF"
run "initctl reload"
retry 'assert_status pamok running'
retry 'assert_keeper 1'
say 'Stopping the service takes the keeper with it'
run "initctl stop pamok"
retry 'assert_status pamok stopped'
retry 'assert_keeper 0'
say 'Starting again opens a fresh session'
run "initctl start pamok"
retry 'assert_status pamok running'
retry 'assert_keeper 1'
run "initctl stop pamok"
retry 'assert_keeper 0'
say 'A denied account stack keeps the service from running'
run "printf 'service pamno {\n runlevel = \"S12345\"\n user = \"daemon\"\n pam = \"finit-no\"\n command = \"/sbin/serv -n -i pamno\"\n}\n' > $FINIT_CONF"
run "initctl reload"
retry "assert_status_full pamno '$denied'" 500
assert_keeper 0
say 'So does a pam.d config that is not there'
run "printf 'service pamgone {\n runlevel = \"S12345\"\n user = \"daemon\"\n pam = \"finit-no-such-config\"\n command = \"/sbin/serv -n -i pamgone\"\n}\n' > $FINIT_CONF"
run "initctl reload"
retry "assert_status_full pamgone '$denied'" 500
assert_keeper 0
say 'A pam value that is a path is refused, the service does not start'
run "printf 'service pampath {\n runlevel = \"S12345\"\n user = \"daemon\"\n pam = \"/etc/pam.d/finit-ok\"\n command = \"/sbin/serv -n -i pampath\"\n}\n' > $FINIT_CONF"
run "initctl reload"
retry 'assert_status pampath missing'
assert_keeper 0
# The pre: script forks from SVC_SETUP_STATE, before service_start()
# runs, so it is pamsess_open() that has to refuse the value here. The
# script exits 71 without ever running, hence no /tmp/pre.
say 'And a pre: script does not get the refused value either'
run "printf 'service pampre {\n runlevel = \"S12345\"\n user = \"daemon\"\n pam = \"/etc/pam.d/finit-ok\"\n exec-start-pre = \"/bin/pre.sh\"\n command = \"/sbin/serv -n -i pampre\"\n}\n' > $FINIT_CONF"
run "initctl reload"
retry "assert_status_full pampre '$denied'" 500
assert "pre: script did not run" "$(texec sh -c 'test -e /tmp/pre && echo yes || echo no')" = "no"
assert_keeper 0
say 'pam_limits wins over the per-service rlimit'
run "mkdir -p /etc/security"
run "printf 'daemon hard nofile 512\ndaemon soft nofile 512\n' > /etc/security/limits.conf"
run "printf 'auth required pam_permit.so\naccount required pam_permit.so\nsession required pam_limits.so\n' > /etc/pam.d/finit-lim"
run "printf 'service pamlim {\n runlevel = \"S12345\"\n user = \"daemon\"\n pam = \"finit-lim\"\n rlimit {\n nofile = 4096\n }\n command = \"/sbin/serv -n -i pamlim\"\n}\n' > $FINIT_CONF"
run "initctl reload"
retry 'assert_status pamlim running'
pamlim_pid=$(texec initctl -j status pamlim | jq -M .pid)
# shellcheck disable=SC2016 # $4 is awk's field reference, not the shell's
assert "nofile is 512, from limits.conf, not 4096 from the block" \
"$(texec awk '/Max open files/ { print $4 }' "/proc/$pamlim_pid/limits")" = "512"
run "initctl stop pamlim"
retry 'assert_keeper 0'
+76
View File
@@ -0,0 +1,76 @@
#!/bin/sh
# A reload must not be lost on a service paused by a condition
#
# svc_s writes its PID file one second after a SIGHUP, so a service
# with <pid/svc_s> is paused for that second whenever svc_s reloads.
# svc_x counts the SIGHUPs it gets. Both .conf files are touched and
# two reloads are requested back to back, so the second one arrives
# while svc_x is paused with its own reload still pending. svc_x must
# get exactly one SIGHUP and keep its PID.
set -eu
TEST_DIR=$(dirname "$0")
test_teardown()
{
say "Running test teardown."
run "rm -f $FINIT_RCSD/svc_s.conf $FINIT_RCSD/svc_x.conf /tmp/hup.sh /tmp/hup.log"
}
pidof()
{
texec initctl -j status "$1" | jq .pid
}
test_setup()
{
run "cat > /tmp/hup.sh" <<EOF
#!/bin/sh
trap 'echo HUP >> /tmp/hup.log' HUP
trap 'exit 0' TERM
while true; do
sleep 1
done
EOF
run "cat > $FINIT_RCSD/svc_s.conf" <<EOF
service log:stdout notify:pid pid:!/run/service.pid name:svc_s service.sh -- Slow to reassert
EOF
run "cat > $FINIT_RCSD/svc_x.conf" <<EOF
service log:stdout <pid/svc_s> name:svc_x /bin/sh /tmp/hup.sh -- Paused while svc_s reloads
EOF
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
sep "Configuration"
run "cat $FINIT_RCSD/svc_s.conf"
run "cat $FINIT_RCSD/svc_x.conf"
say "Reload Finit to start both services"
run "initctl reload"
retry 'assert_status "svc_x" "running"' 10 1
pid_x=$(pidof svc_x)
say "svc_x PID before: $pid_x"
sep "Touch both, reload twice"
run "rm -f /tmp/hup.log"
run "initctl touch svc_s.conf"
run "initctl touch svc_x.conf"
run "initctl reload"
run "initctl reload"
say "Wait for services to settle"
retry 'assert_status "svc_x" "running"' 15 1
run "initctl status"
# shellcheck disable=SC2016
retry 'assert "svc_x got its SIGHUP" "$(texec sh -c "cat /tmp/hup.log 2>/dev/null | wc -l")" -eq 1' 10 1
new_pid_x=$(pidof svc_x)
# shellcheck disable=SC2086
assert "svc_x was not restarted" $new_pid_x -eq $pid_x
return 0
+76
View File
@@ -0,0 +1,76 @@
#!/bin/sh
set -eu
TEST_DIR=$(dirname "$0")
TEST_CONF=/etc/finit.d/remain-task.conf
STATE=/run/remain-task.state
test_teardown()
{
run "rm -f $TEST_CONF $STATE"
}
assert_runs()
{
assert "Remain task has run $1 time(s)" \
"$(texec initctl -j status remain-task | jq -M .restarts)" -eq "$1"
}
# shellcheck source=/dev/null
. "$TEST_DIR/lib/setup.sh"
say 'Add remain task'
run "cat > $TEST_CONF" <<EOF
task remain-task {
description = "Remain task control"
runlevel = "2345"
remain-after-exit = true
command = "/bin/touch $STATE"
exec-stop-post = "/bin/rm -f $STATE"
}
EOF
run "initctl reload"
retry 'assert_status remain-task done'
assert_file_exists "$STATE"
assert_runs 1
say 'Stop remain task'
run "initctl stop remain-task"
retry 'assert_status remain-task stopped'
assert "Post script removed state" \
"$(texec sh -c "[ ! -e '$STATE' ] && echo yes")" = yes
assert_runs 1
say 'Start remain task'
run "initctl start remain-task"
retry 'assert_status remain-task done'
assert_file_exists "$STATE"
assert_runs 2
say 'Restart remain task'
run "initctl restart remain-task"
retry 'assert_runs 3'
retry 'assert_status remain-task done'
assert_file_exists "$STATE"
say 'Reload changed remain task'
run "sed -i 's/Remain task control/Updated remain task control/' $TEST_CONF"
run "initctl reload"
retry 'assert_runs 4'
retry 'assert_status remain-task done'
assert_file_exists "$STATE"
say 'Leave remain task runlevel'
run "initctl runlevel 1"
retry 'assert_status remain-task halted'
assert "Post script removed state" \
"$(texec sh -c "[ ! -e '$STATE' ] && echo yes")" = yes
assert_runs 4
say 'Re-enter remain task runlevel'
run "initctl runlevel 2"
retry 'assert_runs 5'
retry 'assert_status remain-task done'
assert_file_exists "$STATE"