diff --git a/.github/workflows/coverity.yml b/.github/workflows/coverity.yml index 5f413c5987..b62fd5763a 100644 --- a/.github/workflows/coverity.yml +++ b/.github/workflows/coverity.yml @@ -54,7 +54,7 @@ jobs: run: | sudo apt-get -y update sudo apt-get -y install pkg-config libjansson-dev libev-dev \ - libaugeas-dev libglib2.0-dev libpcre2-dev \ + libcrypt-dev libglib2.0-dev libpcre2-dev \ libuev-dev libite-dev - name: Build dependencies diff --git a/board/common/rootfs/etc/finit.d/10-infix.conf b/board/common/rootfs/etc/finit.d/10-infix.conf index 024848e90d..c7f0f632d7 100644 --- a/board/common/rootfs/etc/finit.d/10-infix.conf +++ b/board/common/rootfs/etc/finit.d/10-infix.conf @@ -1 +1 @@ -task name:ixinit log:tag:ixinit [S] /libexec/finit/runparts -p /libexec/infix/init.d -- Probing system +task name:ixinit log:tag:ixinit [S] /libexec/finit/runparts -bp /libexec/infix/init.d -- Probing system diff --git a/board/common/rootfs/etc/finit.d/available/container@.conf b/board/common/rootfs/etc/finit.d/available/container@.conf index cb648c73ac..20c3570a10 100644 --- a/board/common/rootfs/etc/finit.d/available/container@.conf +++ b/board/common/rootfs/etc/finit.d/available/container@.conf @@ -1,4 +1,4 @@ service :%i pid:!/run/k8s-logger-%i.pid \ [2345] k8s-logger -cni %i -f local1 /run/containers/%i.fifo -- Logger for container %i -sysv :%i pid:!/run/container:%i.pid kill:10 \ +sysv :%i pid:!/run/container:%i.pid log kill:10 \ [2345] container -n %i -- container %i diff --git a/board/common/rootfs/libexec/infix/init.d/05-product b/board/common/rootfs/libexec/infix/init.d/05-product new file mode 100755 index 0000000000..ce46d5fdde --- /dev/null +++ b/board/common/rootfs/libexec/infix/init.d/05-product @@ -0,0 +1,22 @@ +#!/bin/sh +# Find and install any product specific files in /etc before bootstrap +ident=$(basename "$0") + +PREFIXD=/usr/share/product +PRODUCT=$(jq -r '."product-name" | ascii_downcase' /run/system.json) + +note() +{ + logger -k -p user.notice -t "$ident" "$1" +} + +DIR="$PREFIXD/$PRODUCT" +if [ -z "$PRODUCT" ] || [ ! -d "$DIR" ]; then + note "No vendor/product specific directory found, using built-in defaults." + exit 0 +fi + +note "Using vendor/product specific defaults." +for dir in "$DIR"/*; do + [ -d "$dir" ] && cp -a "$dir" / +done diff --git a/board/common/rootfs/libexec/infix/init.d/30-cfg-migrate b/board/common/rootfs/libexec/infix/init.d/30-cfg-migrate new file mode 100755 index 0000000000..520df78c19 --- /dev/null +++ b/board/common/rootfs/libexec/infix/init.d/30-cfg-migrate @@ -0,0 +1,102 @@ +#!/bin/sh +# Run .cfg migration jq scripts to backup and transform older .cfg files +ident=$(basename "$0") + +MIGRATIONS_DIR="/usr/share/confd/migrate" +CONFIG_FILE="/cfg/startup-config.cfg" +BACKUP_DIR="/cfg/backup" + +note() +{ + logger -k -p user.notice -t "$ident" "$1" +} + +err() +{ + logger -k -p user.err -t "$ident" "$1" +} + +file_version() +{ + jq -r ' + if .["infix-meta:meta"] | has("version") then + .["infix-meta:meta"]["version"] + else + "0.0" + end + ' "$1" +} + +atoi() +{ + echo "$1" | awk -F. '{print $1 * 1000 + $2}' +} + +if [ ! -f "$CONFIG_FILE" ]; then + # Nothing to migrate + note "No $(basename "$CONFIG_FILE" .cfg) yet, likely factory reset." + exit 0 +fi + +cfg_version=$(file_version "$CONFIG_FILE") +current_version=$(atoi "$cfg_version") + +# Find the latest version by examining the highest numbered directory +sys_version=$(find "$MIGRATIONS_DIR" -mindepth 1 -maxdepth 1 -type d | sort -V | tail -n1 | xargs -n1 basename) +latest_version=$(atoi "$sys_version") + +# Check for downgrade +if [ "$current_version" -gt "$latest_version" ]; then + err "Configuration file $CONFIG_FILE version ($cfg_version) is newer than the latest supported version ($sys_version). Exiting." + exit 1 +fi + +# If the current version is already the latest, exit the script +if [ "$current_version" -eq "$latest_version" ]; then + note "Configuration is already at the latest version ($sys_version). No migration needed." + exit 0 +fi + +note "Configuration file $CONFIG_FILE is of version $cfg_version, migrating ..." + +# Create the backup directory if it doesn't exist +mkdir -p "$BACKUP_DIR" + +# Create a backup of the current configuration file +nm=$(basename "$CONFIG_FILE" .cfg) +BACKUP_FILE="$BACKUP_DIR/${nm}-${cfg_version}.cfg" +if cp "$CONFIG_FILE" "$BACKUP_FILE"; then + note "Backup created: $BACKUP_FILE" +else + err "Failed creating backup: $BACKUP_FILE" + exit 1 +fi + +# Apply the scripts for each version directory in sequence +for version_dir in $(find "$MIGRATIONS_DIR" -mindepth 1 -maxdepth 1 -type d | sort -V); do + dir=$(basename "$version_dir") + version=$(atoi "$dir") + + # Step by step upgrade file to latest version + if [ "$current_version" -lt "$version" ]; then + note "Applying migrations for version $dir ..." + + # Apply all scripts in the version directory in order + for script in $(find "$version_dir" -type f -name '*.sh' | sort -V); do + note "Calling $script for $CONFIG_FILE ..." + sh "$script" "$CONFIG_FILE" + done + + # File now at $version ... + current_version="$version" + fi +done + +# Update the JSON file to the latest version +if jq --arg version "$sys_version" '.["infix-meta:meta"]["infix-meta:version"] = $version' "$CONFIG_FILE" \ + > "${CONFIG_FILE}.tmp" && mv "${CONFIG_FILE}.tmp" "$CONFIG_FILE"; then + note "Configuration updated to version $sys_version." +else + err "Failed updating configuration to version $sys_version!" + exit 1 +fi diff --git a/board/common/rootfs/libexec/infix/mkkeys b/board/common/rootfs/libexec/infix/mkkeys new file mode 100755 index 0000000000..0eb0b9f844 --- /dev/null +++ b/board/common/rootfs/libexec/infix/mkkeys @@ -0,0 +1,14 @@ +#!/bin/sh +# Generate NETCONF SSH host key pair +set -e + +BIT=2048 +KEY=$1 +PUB=$2 + +mkdir -p "$(dirname "$KEY")" "$(dirname "$PUB")" + +openssl genpkey -quiet -algorithm RSA -pkeyopt rsa_keygen_bits:$BIT -outform PEM > "$KEY" +openssl rsa -RSAPublicKey_out < "$KEY" > "$PUB" + +exit 0 diff --git a/board/common/rootfs/usr/sbin/container b/board/common/rootfs/usr/sbin/container index 920aa6ba9d..5731c62ac6 100755 --- a/board/common/rootfs/usr/sbin/container +++ b/board/common/rootfs/usr/sbin/container @@ -58,6 +58,7 @@ unpack_archive() [ -n "$quiet" ] || log "Extracting OCI archive $file ..." tar xf "$file" || (log "Error: failed unpacking $file in $(pwd)"; exit 1) + remove=true fi dir=$(dirname "$index") @@ -72,6 +73,10 @@ unpack_archive() name=$dir fi + if [ "$remove" = "true" ]; then + rm -rf "$file" + fi + echo "$name" } @@ -575,7 +580,7 @@ case $cmd in stop "$name" timeout=20 while running "$name"; do - _=$((timeoute -= 1)) + _=$((timeout -= 1)) if [ $timeout -le 0 ]; then log "Timeout waiting for container $1 to stop before restarting it." exit 1 diff --git a/board/common/rootfs/usr/share/product/.empty b/board/common/rootfs/usr/share/product/.empty new file mode 100644 index 0000000000..e69de29bb2 diff --git a/configs/aarch64_defconfig b/configs/aarch64_defconfig index f3822f34cb..5d5351d3ee 100644 --- a/configs/aarch64_defconfig +++ b/configs/aarch64_defconfig @@ -58,6 +58,7 @@ BR2_PACKAGE_PYTHON_GUNICORN=y BR2_PACKAGE_LIBSSH_OPENSSL=y BR2_PACKAGE_LIBSSH2=y BR2_PACKAGE_LIBSSH2_OPENSSL=y +BR2_PACKAGE_LIBXCRYPT=y BR2_PACKAGE_LIBOPENSSL_BIN=y BR2_PACKAGE_LIBCURL_CURL=y BR2_PACKAGE_NETOPEER2_CLI=y @@ -95,6 +96,7 @@ BR2_PACKAGE_SOCAT=y BR2_PACKAGE_TCPDUMP=y BR2_PACKAGE_TRACEROUTE=y BR2_PACKAGE_ULOGD=y +BR2_PACKAGE_WHOIS=y BR2_PACKAGE_BASH_COMPLETION=y BR2_PACKAGE_SUDO=y BR2_PACKAGE_TTYD=y diff --git a/configs/r2s_defconfig b/configs/r2s_defconfig index 4ac22a019e..c827362493 100644 --- a/configs/r2s_defconfig +++ b/configs/r2s_defconfig @@ -68,6 +68,7 @@ BR2_PACKAGE_PYTHON_GUNICORN=y BR2_PACKAGE_LIBSSH_OPENSSL=y BR2_PACKAGE_LIBSSH2=y BR2_PACKAGE_LIBSSH2_OPENSSL=y +BR2_PACKAGE_LIBXCRYPT=y BR2_PACKAGE_LIBOPENSSL_BIN=y BR2_PACKAGE_LIBCURL_CURL=y BR2_PACKAGE_NETOPEER2_CLI=y @@ -105,6 +106,7 @@ BR2_PACKAGE_SOCAT=y BR2_PACKAGE_TCPDUMP=y BR2_PACKAGE_TRACEROUTE=y BR2_PACKAGE_ULOGD=y +BR2_PACKAGE_WHOIS=y BR2_PACKAGE_BASH_COMPLETION=y BR2_PACKAGE_SUDO=y BR2_PACKAGE_TTYD=y diff --git a/configs/x86_64_defconfig b/configs/x86_64_defconfig index 51757b6d6b..e37dcaebdd 100644 --- a/configs/x86_64_defconfig +++ b/configs/x86_64_defconfig @@ -53,6 +53,7 @@ BR2_PACKAGE_PYTHON_GUNICORN=y BR2_PACKAGE_LIBSSH_OPENSSL=y BR2_PACKAGE_LIBSSH2=y BR2_PACKAGE_LIBSSH2_OPENSSL=y +BR2_PACKAGE_LIBXCRYPT=y BR2_PACKAGE_LIBOPENSSL_BIN=y BR2_PACKAGE_LIBCURL_CURL=y BR2_PACKAGE_NETOPEER2_CLI=y @@ -90,6 +91,7 @@ BR2_PACKAGE_SOCAT=y BR2_PACKAGE_TCPDUMP=y BR2_PACKAGE_TRACEROUTE=y BR2_PACKAGE_ULOGD=y +BR2_PACKAGE_WHOIS=y BR2_PACKAGE_BASH_COMPLETION=y BR2_PACKAGE_SUDO=y BR2_PACKAGE_TTYD=y diff --git a/doc/ChangeLog.md b/doc/ChangeLog.md index 1bb20f0a9c..e8426bfc21 100644 --- a/doc/ChangeLog.md +++ b/doc/ChangeLog.md @@ -6,9 +6,14 @@ All notable changes to the project are documented in this file. [v24.06.0][UNRELEASED] ---------------------- -> **Note:** After upgrade a factory reset is needed + +> **Note:** this release contains **breaking changes** in YANG models +> that are incompatible with existing configuration files. So, after +> upgrade, but before reboot, a factory reset is required! ### Changes +- Upgrade Buildroot to 2024.02.3 (LTS) +- Upgrade Linux kernel to 6.6.34 (LTS) - Default web landing page refactored into a Buildroot package to make it possible to overload from customer repos. - Enable DCB support in aarch64 kernel (for EtherType prio override) @@ -35,10 +40,30 @@ All notable changes to the project are documented in this file. on egress. - `mv88e6xxx` ports can now use Linux's priority information to select the appropriate egress queue, via the `mqprio` queuing discipline. -- Upgrade Buildroot to 2024.02.3 and Linux kernel to 6.6.34 +- Add logging of output from container start/stop action +- Clean up stale directories after OCI container archive import +- Add support for `show leaf-node` in CLI configure context +- Allow non-admin users to use the CLI. NACM rules still apply +- Ensure filesystem is sync'ed properly after a CLI `copy` command +- Issue #178: add early boot script to migrate configuration files of + older version to new syntax. Initial, rudimentary support, for the + change in shell types +- Issue #308: add `version` field to ietf-system.yang to be able to + detect the configuration file version. +- Issue #435: add support for `$factory$` password hash. This allows + backing up configuration files with device specific passwords. Upon + restore to another device this ensures the replacement's password is + used instead of the originals' +- Issue #435: add support for hostname format specifiers. The default + hostname configuration is now `%h-%m` to encode, `infix-c0-ff-ee` +- Issue #447: add support for [yescrypt][], `$y$` hashes +- Issue #478: add operational support for ietf-system.yang, reading + actual hostname and passwords after issue #435 +- Merge infix-shell-types.yang with infix-system.yang + +[yescrypt]: https://en.wikipedia.org/wiki/Yescrypt) ### Fixes -- Add missing LICENSE hash for factory reset tool - Fix #424: regression, root user can log in without password - Fix build regressions in `cn9130_crb_boot_defconfig` caused by upgrade to Buildroot v2024.02 and recent multi-key support in RAUC and U-Boot @@ -56,6 +81,8 @@ All notable changes to the project are documented in this file. privileges (added to UNIX `wheel` group) - Fix #473: bridge interface with IPv6 SLAAC never get global prefix - Fix locking issue with standard counter groups on `mv88e6xxx` +- Add missing LICENSE hash for factory reset tool +- Fix timeout handling in container restart command - Fix MDB/ATU synchronization issue from IGMPv3/MLDv2 reports on `mv88e6xxx` systems - Fix #476: Custom command for containers not working diff --git a/package/confd/Config.in b/package/confd/Config.in index e1b8dfa195..1b469ce850 100644 --- a/package/confd/Config.in +++ b/package/confd/Config.in @@ -11,3 +11,39 @@ config BR2_PACKAGE_CONFD either the on-system CLI or using NETCONF. https://github.com/kernelkit/infix + +if BR2_PACKAGE_CONFD + +choice + prompt "Default password crypt" + default BR2_PACKAGE_CONFD_YESCRYPT + help + When users set $0$cleartext-password as their password confd + salts and encrypts the "cleartext-password" with this selected + hash algorithm. + + Infix defaults to yescrypt. + +config BR2_PACKAGE_CONFD_MD5CRYPT + bool "md5crypt" + help + +config BR2_PACKAGE_CONFD_SHA256CRYPT + bool "sha256crypt" + +config BR2_PACKAGE_CONFD_SHA512CRYPT + bool "sha512crypt" + +config BR2_PACKAGE_CONFD_YESCRYPT + bool "yescrypt" + +endchoice + +config BR2_PACKAGE_CONFD_DEFAULT_CRYPT + string + default "md5crypt" if BR2_PACKAGE_CONFD_MD5CRYPT + default "sha256crypt" if BR2_PACKAGE_CONFD_SHA256CRYPT + default "sha512crypt" if BR2_PACKAGE_CONFD_SHA512CRYPT + default "yescrypt" if BR2_PACKAGE_CONFD_YESCRYPT + +endif diff --git a/package/confd/confd.mk b/package/confd/confd.mk index c6761a0a9f..c5cecf4824 100644 --- a/package/confd/confd.mk +++ b/package/confd/confd.mk @@ -12,7 +12,7 @@ CONFD_LICENSE_FILES = LICENSE CONFD_REDISTRIBUTE = NO CONFD_DEPENDENCIES = host-sysrepo sysrepo netopeer2 jansson libite sysrepo libsrx libglib2 CONFD_AUTORECONF = YES - +CONFD_CONF_OPTS += --disable-silent-rules --with-crypt=$(BR2_PACKAGE_CONFD_DEFAULT_CRYPT) CONFD_SYSREPO_SHM_PREFIX = sr_buildroot$(subst /,_,$(CONFIG_DIR))_confd define CONFD_CONF_ENV @@ -41,13 +41,13 @@ COMMON_SYSREPO_ENV = \ define CONFD_INSTALL_YANG_MODULES $(COMMON_SYSREPO_ENV) \ - $(BR2_EXTERNAL_INFIX_PATH)/utils/sysrepo-load-modules.sh $(@D)/yang-setup/yang-modules-confd.inc + $(BR2_EXTERNAL_INFIX_PATH)/utils/sysrepo-load-modules.sh $(@D)/yang/confd.inc endef ifeq ($(BR2_PACKAGE_PODMAN),y) define CONFD_INSTALL_YANG_MODULES_CONTAINERS $(COMMON_SYSREPO_ENV) \ - $(BR2_EXTERNAL_INFIX_PATH)/utils/sysrepo-load-modules.sh $(@D)/yang-setup/yang-modules-containers.inc + $(BR2_EXTERNAL_INFIX_PATH)/utils/sysrepo-load-modules.sh $(@D)/yang/containers.inc endef endif diff --git a/package/finit/0012-runparts-add-b-batch-mode-for-syslog-output.patch b/package/finit/0012-runparts-add-b-batch-mode-for-syslog-output.patch new file mode 100644 index 0000000000..a8f4f48f40 --- /dev/null +++ b/package/finit/0012-runparts-add-b-batch-mode-for-syslog-output.patch @@ -0,0 +1,64 @@ +From ab62b5282b0461b14464a4a5de49f3b1fa0604fe Mon Sep 17 00:00:00 2001 +From: Joachim Wiberg +Date: Sat, 25 May 2024 19:33:21 +0200 +Subject: [PATCH 12/12] runparts: add -b (batch) mode for syslog output +Organization: Addiva Elektronik + +Signed-off-by: Joachim Wiberg +--- + src/runparts.c | 24 ++++++++++++++++++------ + 1 file changed, 18 insertions(+), 6 deletions(-) + +diff --git a/src/runparts.c b/src/runparts.c +index 5af2c2d..c4225ce 100644 +--- a/src/runparts.c ++++ b/src/runparts.c +@@ -26,18 +26,27 @@ + #else + #include + ++const char *active_msg = NULL; ++int interactive = 1; + int debug; + + static void print_desc(const char *prefix, const char *msg) + { +- fprintf(stderr, "\e[1m[\e[0m\e[1;33m ⋯ \e[0m\e[1m]\e[0m %s %s", prefix, msg); ++ if (interactive) ++ fprintf(stderr, "\e[1m[\e[0m\e[1;33m ⋯ \e[0m\e[1m]\e[0m %s %s", prefix, msg); ++ else ++ fprintf(stderr, "%s %s ...\n", prefix, msg); ++ active_msg = msg; + } + static void print_result(int rc) + { +- if (rc) +- fputs("\r\e[1m[\e[0m\e[1;31mFAIL\e[0m\e[1m]\e[0m\n", stderr); +- else +- fputs("\r\e[1m[\e[0m\e[1;32m OK \e[0m\e[1m]\e[0m\n", stderr); ++ if (interactive) { ++ if (rc) ++ fputs("\r\e[1m[\e[0m\e[1;31mFAIL\e[0m\e[1m]\e[0m\n", stderr); ++ else ++ fputs("\r\e[1m[\e[0m\e[1;32m OK \e[0m\e[1m]\e[0m\n", stderr); ++ } else ++ fprintf(stderr, "[%s] %s\n", rc ? "FAIL" : " OK ", active_msg ?: ""); + } + + void sig_unblock(void) +@@ -193,8 +202,11 @@ int main(int argc, char *argv[]) + int rc, c, progress = 0, sysv = 0; + char *dir; + +- while ((c = getopt(argc, argv, "dh?ps")) != EOF) { ++ while ((c = getopt(argc, argv, "bdh?ps")) != EOF) { + switch(c) { ++ case 'b': /* batch mode */ ++ interactive = 0; ++ break; + case 'd': + debug = 1; + break; +-- +2.34.1 + diff --git a/package/klish-plugin-sysrepo/klish-plugin-sysrepo.hash b/package/klish-plugin-sysrepo/klish-plugin-sysrepo.hash index a15e69e4ad..8379bd62e7 100644 --- a/package/klish-plugin-sysrepo/klish-plugin-sysrepo.hash +++ b/package/klish-plugin-sysrepo/klish-plugin-sysrepo.hash @@ -1,3 +1,3 @@ # Locally calculated sha256 9d9d33b873917ca5d0bdcc47a36d2fd385971ab0c045d1472fcadf95ee5bcf5b LICENCE -sha256 e18a45b35ade84201d9d59918e0743c0d9b5451cfe89ec1f7f0f6de2dc343a42 klish-plugin-sysrepo-364f7c7b9c61f2cfd51dfd8d94a8c67449ee439f-br1.tar.gz +sha256 e8de6e69d930fcab14b45a0a6e9a2c1b63539d64d65f490d9ba071a676179d0d klish-plugin-sysrepo-bc543fb84294ac791f2ee34573dd11be8c2714cc-br1.tar.gz diff --git a/package/klish-plugin-sysrepo/klish-plugin-sysrepo.mk b/package/klish-plugin-sysrepo/klish-plugin-sysrepo.mk index 5e7576192d..29048e2ba3 100644 --- a/package/klish-plugin-sysrepo/klish-plugin-sysrepo.mk +++ b/package/klish-plugin-sysrepo/klish-plugin-sysrepo.mk @@ -4,7 +4,7 @@ # ################################################################################ -KLISH_PLUGIN_SYSREPO_VERSION = 364f7c7b9c61f2cfd51dfd8d94a8c67449ee439f +KLISH_PLUGIN_SYSREPO_VERSION = bc543fb84294ac791f2ee34573dd11be8c2714cc KLISH_PLUGIN_SYSREPO_SITE = https://github.com/kernelkit/klish-plugin-sysrepo.git #KLISH_PLUGIN_SYSREPO_VERSION = cdd3eb51a7f7ee0ed5bd925fa636061d3b1b85fb #KLISH_PLUGIN_SYSREPO_SITE = https://src.libcode.org/pkun/klish-plugin-sysrepo.git diff --git a/package/klish/klish.hash b/package/klish/klish.hash index 63a9c1ce14..7fad7f0bf7 100644 --- a/package/klish/klish.hash +++ b/package/klish/klish.hash @@ -1,3 +1,3 @@ # Locally calculated sha256 9d9d33b873917ca5d0bdcc47a36d2fd385971ab0c045d1472fcadf95ee5bcf5b LICENCE -sha256 edb7b9a53d57d87756a99fa25c4af3d6219bed9a863541e672580a2d1f6e7052 klish-b898fdd9a128adaad3a5c92d8dd7baac2085df1b-br1.tar.gz +sha256 c80c2b7eee248d80989fd6218068fe89457d034e3da6db8f0f18cad509e8d52d klish-4afbb469613071503f38c21d54efde97dec86109-br1.tar.gz diff --git a/package/klish/klish.mk b/package/klish/klish.mk index 7dfbb70c2b..b16b5014c3 100644 --- a/package/klish/klish.mk +++ b/package/klish/klish.mk @@ -4,7 +4,7 @@ # ################################################################################ -KLISH_VERSION = b898fdd9a128adaad3a5c92d8dd7baac2085df1b +KLISH_VERSION = 4afbb469613071503f38c21d54efde97dec86109 KLISH_SITE = https://github.com/kernelkit/klish.git #KLISH_VERSION = tags/3.0.0 #KLISH_SITE = https://src.libcode.org/pkun/klish.git diff --git a/package/skeleton-init-finit/skeleton/etc/group b/package/skeleton-init-finit/skeleton/etc/group index f20d375cac..2614592d12 100644 --- a/package/skeleton-init-finit/skeleton/etc/group +++ b/package/skeleton-init-finit/skeleton/etc/group @@ -20,6 +20,7 @@ backup:x:34: utmp:x:43: plugdev:x:46: lock:x:54: +sys-cli:x:60: netdev:x:82: users:x:100: nobody:x:65534: diff --git a/package/skeleton-init-finit/skeleton/etc/passwd b/package/skeleton-init-finit/skeleton/etc/passwd index 03092d7551..a2c662ba1e 100644 --- a/package/skeleton-init-finit/skeleton/etc/passwd +++ b/package/skeleton-init-finit/skeleton/etc/passwd @@ -6,4 +6,5 @@ sync:x:4:100:sync:/bin:/bin/sync mail:x:8:8:mail:/var/spool/mail:/bin/false www-data:x:33:33:www-data:/var/www:/bin/false backup:x:34:34:backup:/var/backups:/bin/false +sys-cli:x:60:60:CLI capability:/var:/bin/false nobody:x:65534:65534:nobody:/home:/bin/false diff --git a/package/skeleton-init-finit/skeleton/etc/shadow b/package/skeleton-init-finit/skeleton/etc/shadow index c5b4a870a9..820b8fee3c 100644 --- a/package/skeleton-init-finit/skeleton/etc/shadow +++ b/package/skeleton-init-finit/skeleton/etc/shadow @@ -5,5 +5,6 @@ sys:*::::::: sync:*::::::: mail:*::::::: www-data:*::::::: +sys-cli:*::::::: backup:*::::::: nobody:*::::::: diff --git a/src/confd/README.md b/src/confd/README.md index 02951ac8c1..94ddc022b7 100644 --- a/src/confd/README.md +++ b/src/confd/README.md @@ -6,6 +6,31 @@ between sysrepo and netopeer2 (NETCONF) and the UNIX system under it all. +Factory & Failure Config +------------------------ + +Infix supports both static and dynamically generated factory-config. At +boot the dynamic is always generated to `/run/confd/factory-config.gen`, +which is installed to `/etc/factory-config.cfg` and used by default, if +that file does not already exist. The same applies to the failure mode +configuration. + +The following describes how a vendor/product specific config is found +and installed into `/etc/factory-config.cfg` before the dynamic one is +installed. + + 1. `/etc/factory-config.cfg`: built into the image, e.g., r2s + 2. `/usr/share/product//etc/factory-config.cfg`, where the + `` is determined from the VPD, which is available after + `probe` has run, in `/run/system.json` as `"product-name"`. The + lower case version of the string is used + +In the second option a script running just after `probe` will in fact +`cp` the complete product specific directory to `/`, meaning any file +and directory that is writable at runtime can be overloaded with device +specific versions. + + Origin & References ------------------- diff --git a/src/confd/bin/Makefile.am b/src/confd/bin/Makefile.am index b3bf9ec422..6a87c5e8b8 100644 --- a/src/confd/bin/Makefile.am +++ b/src/confd/bin/Makefile.am @@ -1,3 +1,3 @@ -pkglibexec_SCRIPTS = bootstrap error load gen-service gen-hostkeys gen-admin-auth \ - gen-hostname gen-interfaces gen-motd gen-hardware +pkglibexec_SCRIPTS = bootstrap error load gen-service gen-hostname \ + gen-interfaces gen-motd gen-hardware gen-version sbin_SCRIPTS = dagger diff --git a/src/confd/bin/bootstrap b/src/confd/bin/bootstrap index aa710349e3..7ab39d0471 100755 --- a/src/confd/bin/bootstrap +++ b/src/confd/bin/bootstrap @@ -4,8 +4,8 @@ ######################################################################## # The system factory-config and failure-config are derived from default # settings snippets, from /usr/share/confd/factory.d, and some generated -# snippets, e.g., device unique password, hostname (based on base MAC -# address), and number of interfaces. +# snippets, e.g., hostname (based on base MAC address) and number of +# interfaces. # # The resulting factory-config is used to create the syrepo db (below) # {factory} datastore. Hence, the factory-config file must match the @@ -101,14 +101,7 @@ factory() gen-hardware >"$FACTORY_D/20-hardware.json" # shellcheck disable=SC2086 gen-interfaces $GEN_IFACE_OPTS >"$FACTORY_D/20-interfaces.json" - - # Extract password for admin user from VPD - if ! gen-admin-auth infix-shell-type:bash >"$FACTORY_D/20-authentication.json"; then - console_error "Unable to create factory-config, gen-admin-auth failed" - return - fi - - [ -s "$FACTORY_D/20-hostkey.json" ] || gen-hostkeys >"$FACTORY_D/20-hostkey.json" + gen-version >"$FACTORY_D/20-version.json" # Optional commands (from an overlay) to run for br2-externals [ -x "$(command -v gen-ifs-custom)" ] && gen-ifs-custom >"$FACTORY_D/20-interfaces.json" @@ -126,13 +119,7 @@ failure() gen-hostname "$FAIL_HOSTNAME" >"$FAILURE_D/20-hostname.json" gen-interfaces >"$FAILURE_D/20-interfaces.json" - - # Same password as factory-config, but another login shell - if ! gen-admin-auth infix-shell-type:bash >"$FAILURE_D/20-authentication.json"; then - console_error "Invalid password hash in vital product data, failure-config incomplete!" - fi - - [ -s "$FAILURE_D/20-hostkey.json" ] || gen-hostkeys >"$FAILURE_D/20-hostkey.json" + gen-version >"$FACTORY_D/20-version.json" # Optional failure/error config to generate (or override) for br2-externals [ -x "$(command -v gen-err-custom)" ] && gen-err-custom >"$FAILURE_D/30-error.json" @@ -140,6 +127,8 @@ failure() collate "$FAILURE_GEN" "$FAILURE_CFG" "$FAILURE_D" } +# Both factory-config and failure-config are generated every boot +# regardless if there is a static /etc/factory-config.cfg or not. factory "$FACTORY_GEN" failure "$FAILURE_GEN" @@ -156,24 +145,18 @@ else fi rc=$? -sysrepoctl -z $INIT_DATA -rc=$? -sudo -u root -g wheel sysrepocfg -f json -I"$INIT_DATA" -d running -rc=$? - - -#rm $INIT_DATA - -# On first boot, install factory-config as startup-config. -chgrp wheel /cfg -chmod g+w /cfg -if [ ! -f "$STARTUP_CFG" ]; then - sysrepocfg -f json -X"$STARTUP_CFG" +chgrp wheel "$CFG_PATH_" +chmod g+w "$CFG_PATH_" +if ! sysrepoctl -z "$INIT_DATA"; then + rc=$? + logger -sik -p user.error "Failed loading factory-default datastore" +else + # Clear running-config so we can load/create startup in the next step + temp=$(mktemp) + echo "{}" > "$temp" + sysrepocfg -f json -I"$temp" -d running + rc=$? + rm "$temp" fi -# Clear running-config so we can load startup in the next step -temp=$(mktemp) -echo "{}" > $temp -sysrepocfg -f json -I$temp -d running - exit $rc diff --git a/src/confd/bin/gen-admin-auth b/src/confd/bin/gen-admin-auth deleted file mode 100755 index 825f8c714d..0000000000 --- a/src/confd/bin/gen-admin-auth +++ /dev/null @@ -1,33 +0,0 @@ -#!/bin/sh -# This script extracts the admin user's password hash from VPD - -shell="$1" -pwhash=$(jq -r '."factory-password-hash"' /run/system.json) - -if [ -z "$pwhash" ] || [ "$pwhash" = "null" ]; then - # Do not fail, lock account instead. This way developers can enable - # root account login at build-time to diagnose the system. - password="" - rc=1 -else - password="\"password\": \"$pwhash\"," - rc=0 -fi - -cat < /dev/null - -PUBKEY=$(awk '{print $2}' "${KEYNAME}.pub") - -PRIVPEM=$(openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -outform PEM 2>/dev/null) -# remove header/footer and newlines -PRIVKEY=$(echo "$PRIVPEM" | grep -v -- "-----" | tr -d "\n") - -# generate edit config -cat <= 4.4.27]) PKG_CHECK_MODULES([glib], [glib-2.0 >= 2.50 gio-2.0 gio-unix-2.0]) PKG_CHECK_MODULES([jansson], [jansson >= 2.0.0]) PKG_CHECK_MODULES([libite], [libite >= 2.5.0]) @@ -100,6 +114,7 @@ cat < infix-system:bash + +file=$1 +temp=$1.tmp + +jq '.["ietf-system:system"].authentication.user |= map(.["infix-system:shell"] |= gsub("infix-shell-type:"; ""))' "$file" > "$temp" +mv "$temp" "$file" + diff --git a/src/confd/share/migrate/1.0/Makefile.am b/src/confd/share/migrate/1.0/Makefile.am new file mode 100644 index 0000000000..3a6ac18a14 --- /dev/null +++ b/src/confd/share/migrate/1.0/Makefile.am @@ -0,0 +1,3 @@ +migratedir = $(pkgdatadir)/migrate/1.0 +dist_migrate_DATA = 10-infix-shell-type.sh + diff --git a/src/confd/share/migrate/Makefile.am b/src/confd/share/migrate/Makefile.am new file mode 100644 index 0000000000..d92bf0daf7 --- /dev/null +++ b/src/confd/share/migrate/Makefile.am @@ -0,0 +1,2 @@ +SUBDIRS = 1.0 +migratedir = $(pkgdatadir)/migrate diff --git a/src/confd/src/Makefile.am b/src/confd/src/Makefile.am index 0fdb7b28a9..9999101753 100644 --- a/src/confd/src/Makefile.am +++ b/src/confd/src/Makefile.am @@ -6,6 +6,7 @@ plugin_LTLIBRARIES = confd-plugin.la confd_plugin_la_LDFLAGS = -module -avoid-version -shared confd_plugin_la_CFLAGS = \ + $(crypt_CFLAGS) \ $(glib_CFLAGS) \ $(jansson_CFLAGS) \ $(libite_CFLAGS) \ @@ -14,6 +15,7 @@ confd_plugin_la_CFLAGS = \ $(CFLAGS) confd_plugin_la_LIBADD = \ + $(crypt_LIBS) \ $(glib_LIBS) \ $(jansson_LIBS) \ $(libite_LIBS) \ @@ -25,12 +27,14 @@ confd_plugin_la_SOURCES = \ core.c core.h \ dagger.c dagger.h \ ietf-interfaces.c \ + ietf-keystore.c \ ietf-system.c \ ietf-factory-default.c \ ietf-routing.c \ infix-dhcp.c \ - infix-services.c \ infix-factory.c \ + infix-meta.c \ + infix-services.c \ infix-system-software.c \ ietf-hardware.c diff --git a/src/confd/src/core.c b/src/confd/src/core.c index 2444b29aca..2600aef4e8 100644 --- a/src/confd/src/core.c +++ b/src/confd/src/core.c @@ -122,6 +122,9 @@ int sr_plugin_init_cb(sr_session_ctx_t *session, void **priv) if (!confd.root) goto err; rc = ietf_interfaces_init(&confd); + if (rc) + goto err; + rc = ietf_keystore_init(&confd); if (rc) goto err; rc = ietf_system_init(&confd); @@ -140,6 +143,9 @@ int sr_plugin_init_cb(sr_session_ctx_t *session, void **priv) if (rc) goto err; rc = ietf_routing_init(&confd); + if (rc) + goto err; + rc = infix_meta_init(&confd); if (rc) goto err; rc = infix_system_sw_init(&confd); diff --git a/src/confd/src/core.h b/src/confd/src/core.h index e5997d9495..4361a0394a 100644 --- a/src/confd/src/core.h +++ b/src/confd/src/core.h @@ -191,6 +191,9 @@ int ietf_routing_init(struct confd *confd); /* infix-factory.c */ int infix_factory_init(struct confd *confd); +/* infix-factory.c */ +int infix_meta_init(struct confd *confd); + /* infix-system-software.c */ int infix_system_sw_init(struct confd *confd); @@ -200,4 +203,7 @@ int infix_services_init(struct confd *confd); /* ietf-hardware.c */ int ietf_hardware_init(struct confd *confd); +/* ietf-keystore.c */ +int ietf_keystore_init(struct confd *confd); + #endif /* CONFD_CORE_H_ */ diff --git a/src/confd/src/ietf-interfaces.c b/src/confd/src/ietf-interfaces.c index 3d584b9f7a..4bc4e497e4 100644 --- a/src/confd/src/ietf-interfaces.c +++ b/src/confd/src/ietf-interfaces.c @@ -1798,7 +1798,8 @@ static int ifchange(sr_session_ctx_t *session, uint32_t sub_id, const char *modu int ietf_interfaces_init(struct confd *confd) { - int rc = 0; + int rc; + REGISTER_CHANGE(confd->session, "ietf-interfaces", "/ietf-interfaces:interfaces//.", 0, ifchange, confd, &confd->sub); REGISTER_CHANGE(confd->cand, "ietf-interfaces", "/ietf-interfaces:interfaces//.", diff --git a/src/confd/src/ietf-keystore.c b/src/confd/src/ietf-keystore.c new file mode 100644 index 0000000000..a1937fcb06 --- /dev/null +++ b/src/confd/src/ietf-keystore.c @@ -0,0 +1,138 @@ +/* SPDX-License-Identifier: BSD-3-Clause */ + +#include +#include +#include + +#include + +#include "base64.h" +#include "core.h" + +#define XPATH_KEYSTORE_ "/ietf-keystore:keystore/asymmetric-keys" + +/* return file size */ +static size_t filesz(const char *fn) +{ + struct stat st; + + if (stat(fn, &st)) + st.st_size = BUFSIZ; + return st.st_size; +} + +/* sanity check, must exist and be of non-zero size */ +static bool fileok(const char *fn) +{ + if (!fexist(fn)) + return false; + + /* Minimum size of BEGIN + END markers */ + if (filesz(fn) < 60) + return false; + + return true; +} + +/* read file of max len bytes, return as malloc()'ed buffer */ +static char *filerd(const char *fn, size_t len) +{ + char *buf, *ptr; + FILE *pp; + + ptr = buf = malloc(len + 1); + if (!buf) + return NULL; + + /* strip ---BEGIN//---END markers and concatenate lines */ + pp = popenf("r", "grep -v -- '-----' %s | tr -d '\n'", fn); + if (!pp) { + free(buf); + return NULL; + } + + while (fgets(ptr, len, pp)) { + size_t inc = strlen(chomp(ptr)); + + ptr += inc; + len -= inc; + } + pclose(pp); + + return buf; +} + +static int change_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *module_name, + const char *xpath, sr_event_t event, uint32_t request_id, void *_) +{ + const char *priv_keyfile = "/cfg/ssl/private/netconf.key"; + const char *pub_keyfile = "/cfg/ssl/public/netconf.pub"; + char *pub_key = NULL, *priv_key = NULL; + int rc = SR_ERR_INTERNAL; + + switch (event) { + case SR_EV_UPDATE: + /* Check NETCONF default hostkey pair */ + break; + default: + return SR_ERR_OK; + } + + if (srx_isset(session, XPATH_KEYSTORE_"/asymmetric-key[name='genkey']/cleartext-private-key") && + srx_isset(session, XPATH_KEYSTORE_"/asymmetric-key[name='genkey']/public-key")) { + return SR_ERR_OK; /* already set */ + } + WARN("NETCONF private and public host keys missing in confiugration."); + + if (!fileok(priv_keyfile) || !fileok(pub_keyfile)) { + NOTE("Generating NETCONF SSH host keys ..."); + if (systemf("/libexec/infix/mkkeys %s %s", priv_keyfile, pub_keyfile)) + goto err; + } else { + NOTE("Using existing SSH host keys for NETCONF."); + } + + priv_key = filerd(priv_keyfile, filesz(priv_keyfile)); + if (!priv_key) + goto err; + + pub_key = filerd(pub_keyfile, filesz(pub_keyfile)); + if (!pub_key) + goto err; + + xpath = XPATH_KEYSTORE_"/asymmetric-key[name='genkey']/cleartext-private-key"; + rc = sr_set_item_str(session, xpath, priv_key, NULL, SR_EDIT_NON_RECURSIVE); + if (rc) { + ERROR("Failed setting private key ... rc: %d", rc); + goto err; + } + + xpath = XPATH_KEYSTORE_"/asymmetric-key[name='genkey']/public-key"; + rc = sr_set_item_str(session, xpath, pub_key, NULL, SR_EDIT_NON_RECURSIVE); + if (rc != SR_ERR_OK) { + ERROR("Failed setting public key ... rc: %d", rc); + goto err; + } + +err: + if (pub_key) + free(pub_key); + if (priv_key) + free(priv_key); + + if (rc != SR_ERR_OK) + return rc; + + return SR_ERR_OK; +} + +int ietf_keystore_init(struct confd *confd) +{ + int rc; + + rc = sr_module_change_subscribe(confd->session, "ietf-keystore", "/ietf-keystore:keystore//.", + change_cb, confd, 0, SR_SUBSCR_UPDATE, &confd->sub); + if (rc) + ERROR("%s failed: %s", __func__, sr_strerror(rc)); + return rc; +} diff --git a/src/confd/src/ietf-system.c b/src/confd/src/ietf-system.c index fc72ac8332..233196488d 100644 --- a/src/confd/src/ietf-system.c +++ b/src/confd/src/ietf-system.c @@ -1,11 +1,13 @@ /* SPDX-License-Identifier: BSD-3-Clause */ #include +#include #include #include #include #include #include +#include #include #include @@ -24,6 +26,7 @@ #define XPATH_AUTH_ XPATH_BASE_"/authentication" #define CLOCK_PATH_ "/ietf-system:system-state/clock" #define PLATFORM_PATH_ "/ietf-system:system-state/platform" +#define PASSWORD_PATH "/ietf-system:system/authentication/user/password" #define _PATH_PASSWD "/etc/passwd" #define _PATH_HOSTNAME "/etc/hostname" @@ -39,12 +42,14 @@ static char *ver = NULL; static char *rel = NULL; static char *sys = NULL; static char *os = NULL; +static char *nm = NULL; +static char *id = NULL; static struct { char *name, *shell; bool admin; } shells[] = { - { "infix-shell-type:sh", "/bin/sh", true }, - { "infix-shell-type:bash", "/bin/bash", true }, - { "infix-shell-type:clish", "/bin/clish", false }, - { "infix-shell-type:false", "/bin/false", false }, + { "infix-system:sh", "/bin/sh", true }, + { "infix-system:bash", "/bin/bash", true }, + { "infix-system:clish", "/bin/clish", false }, + { "infix-system:false", "/bin/false", false }, }; static char *strip_quotes(char *str) @@ -65,11 +70,11 @@ static char *strip_quotes(char *str) return str; } -static void setvar(char *line, const char *nm, char **var) +static void setvar(char *line, const char *key, char **var) { char *ptr; - if (!strncmp(line, nm, strlen(nm)) && (ptr = strchr(line, '='))) { + if (!strncmp(line, key, strlen(key)) && (ptr = strchr(line, '='))) { if (*var) free(*var); *var = strdup(strip_quotes(++ptr)); @@ -102,6 +107,8 @@ static void os_init(void) setvar(line, "VERSION_ID", &ver); setvar(line, "BUILD_ID", &rel); setvar(line, "ARCHITECTURE", &sys); + setvar(line, "DEFAULT_HOSTNAME", &nm); + setvar(line, "ID", &id); } fclose(fp); } @@ -126,8 +133,8 @@ static char *fmtime(time_t t, char *buf, size_t len) return buf; } -static sr_error_t _sr_change_iter(sr_session_ctx_t *session, char *xpath, - sr_error_t cb(sr_session_ctx_t *, struct sr_change *)) +static sr_error_t _sr_change_iter(sr_session_ctx_t *session, struct confd *confd, char *xpath, + sr_error_t cb(sr_session_ctx_t *, struct confd *, struct sr_change *)) { struct sr_change change = {}; sr_change_iter_t *iter; @@ -138,7 +145,7 @@ static sr_error_t _sr_change_iter(sr_session_ctx_t *session, char *xpath, return err; while (sr_get_change_next(session, iter, &change.op, &change.old, &change.new) == SR_ERR_OK) { - err = cb(session, &change); + err = cb(session, confd, &change); sr_free_val(change.old); sr_free_val(change.new); if (err) { @@ -583,6 +590,50 @@ static int change_dns(sr_session_ctx_t *session, uint32_t sub_id, const char *mo return rc; } +static bool is_group_member(const char *user, const char *group) +{ + /* Check if user is already in group */ + if (!systemf("grep %s /etc/group |grep %s", group, user)) + return true; + + return false; +} + +static void add_group(const char *user, const char *group) +{ + bool is_already = is_group_member(user, group); + + if (is_already) + return; /* already group member */ + + if (systemf("adduser %s %s", user, group)) + ERROR("Failed giving user %s UNIX %s permissions.", user, group); + else + NOTE("User %s added to UNIX %s group.", user, group); +} + +static void del_group(const char *user, const char *group) +{ + bool is_already = is_group_member(user, group); + + if (!is_already) + return; /* not member of group */ + + if (systemf("delgroup %s %s", user, group)) + ERROR("Failed removing user %s from UNIX %s group.", user, group); + else + NOTE("User %s removed from UNIX %s group.", user, group); +} + +/* Users with a valid shell are also allowed CLI access */ +static void adjust_access(const char *user, const char *shell) +{ + if (strcmp(shell, "/bin/false")) + add_group(user, "sys-cli"); + else + del_group(user, "sys-cli"); +} + /* XXX: Currently Infix only has admin and non-admins as a group */ static bool is_admin_user(sr_session_ctx_t *session, const char *user) { @@ -763,6 +814,8 @@ static int sys_call_adduser(sr_session_ctx_t *sess, char *name, uid_t uid, gid_t * any SSH public keys have been installed. */ err = systemv_silent(args); + if (!err) + adjust_access(name, shell); free(shell); return err; @@ -859,6 +912,8 @@ static int set_shell(const char *user, const char *shell) FILE *fp = NULL; int fd = -1; + adjust_access(user, shell); + setpwent(); fp = fopen(_PATH_PASSWD "+", "w"); @@ -903,12 +958,29 @@ static int set_shell(const char *user, const char *shell) return -1; } -static int set_password(const char *user, const char *hash, bool lock) +static int set_password(struct confd *confd, const char *user, const char *hash, bool lock) { + const char *factory = "$factory$"; struct spwd *sp; FILE *fp = NULL; int fd = -1; + if (!strncmp(hash, factory, strlen(factory))) { + struct json_t *pwd; + + pwd = json_object_get(confd->root, "factory-password-hash"); + if (!json_is_string(pwd)) { + /* + * Do not fail, lock account instead. This way developers can + * enable root account login at build-time to diagnose the system. + */ + ERROR("%s: cannot find factory-default password hash!", user); + lock = true; + } else { + hash = json_string_value(pwd); + } + } + if (lckpwdf()) goto exit; @@ -956,7 +1028,7 @@ static int set_password(const char *user, const char *hash, bool lock) return -1; } -static sr_error_t handle_sr_passwd_update(sr_session_ctx_t *, struct sr_change *change) +static sr_error_t handle_sr_passwd_update(sr_session_ctx_t *, struct confd *confd, struct sr_change *change) { sr_error_t err = SR_ERR_OK; const char *hash; @@ -988,13 +1060,13 @@ static sr_error_t handle_sr_passwd_update(sr_session_ctx_t *, struct sr_change * ERROR("Empty passwords are not allowed, disabling password login."); hash = "*"; } - if (set_password(user, hash, false)) + if (set_password(confd, user, hash, false)) err = SR_ERR_SYS; else NOTE("Password updated for user %s", user); break; case SR_OP_DELETED: - if (set_password(user, "*", true)) + if (set_password(confd, user, "*", true)) err = SR_ERR_SYS; else NOTE("Password deleted for user %s", user); @@ -1007,7 +1079,7 @@ static sr_error_t handle_sr_passwd_update(sr_session_ctx_t *, struct sr_change * return err; } -static sr_error_t handle_sr_shell_update(sr_session_ctx_t *sess, struct sr_change *change) +static sr_error_t handle_sr_shell_update(sr_session_ctx_t *sess, struct confd *confd, struct sr_change *change) { char *shell = NULL; char *user; @@ -1034,7 +1106,7 @@ static sr_error_t handle_sr_shell_update(sr_session_ctx_t *sess, struct sr_chang return err; } -static sr_error_t check_sr_user_update(sr_session_ctx_t *, struct sr_change *change) +static sr_error_t check_sr_user_update(sr_session_ctx_t *, struct confd *, struct sr_change *change) { sr_xpath_ctx_t state; sr_val_t *val; @@ -1053,7 +1125,7 @@ static sr_error_t check_sr_user_update(sr_session_ctx_t *, struct sr_change *cha return SR_ERR_OK; } -static sr_error_t handle_sr_user_update(sr_session_ctx_t *sess, struct sr_change *change) +static sr_error_t handle_sr_user_update(sr_session_ctx_t *sess, struct confd *, struct sr_change *change) { sr_xpath_ctx_t state; char *name; @@ -1148,11 +1220,92 @@ static sr_error_t generate_auth_keys(sr_session_ctx_t *session, const char *xpat return err; } +static const char *ctp_crypt(void) +{ + struct { + const char *crypt; + const char *prefix; + } list[] = { + { "md5crypt", "$1$" }, + { "sha256crypt", "$5$" }, + { "sha512crypt", "$6$" }, + { "yescrypt", "$y$" }, + }; + size_t i; + + for (i = 0; i < NELEMS(list); i++) { + if (strcmp(list[i].crypt, DEFAULT_CRYPT)) + continue; + + return list[i].prefix; + } + + return "$y$"; /* fallback */ +} + +static int ctp_hash_is_cleartext(const char *hash) +{ + if (strlen(hash) < 3) + return 0; + + if (hash[0] == '$' && hash[1] == '0' && hash[2] == '$') + return 1; + + return 0; +} + +static sr_error_t check_user_ctp(sr_session_ctx_t *session, struct confd *_, struct sr_change *change) +{ + const char *prefix = ctp_crypt(); + char *hash, *salt; + sr_val_t *val; + + val = change->new; + if (!val) + return SR_ERR_OK; + + hash = val->data.string_val; + if (!ctp_hash_is_cleartext(hash)) + return SR_ERR_OK; + + if (strlen(hash) < 4) { + sr_session_set_error(session, NULL, SR_ERR_VALIDATION_FAILED, "Too short password."); + return SR_ERR_VALIDATION_FAILED; + } + + salt = crypt_gensalt(prefix, 0, NULL, 0); + if (!salt) { + sr_session_set_error(session, NULL, SR_ERR_INTERNAL, "error %d generating salt, " + "prefix '%s'.", errno, prefix); + return SR_ERR_INTERNAL; + } + + hash = crypt(hash + 3, salt); + if (!hash) { + sr_session_set_error(session, NULL, SR_ERR_INTERNAL, "failed hashing password, " + "error %d.", errno); + return SR_ERR_INTERNAL; + } + + return sr_set_item_str(session, val->xpath, hash, NULL, 0); +} + +static sr_error_t change_auth_ctp(struct confd *confd, sr_session_ctx_t *session) +{ + sr_error_t err; + + err = _sr_change_iter(session, confd, XPATH_AUTH_"/user[*]/password", check_user_ctp); + if (err) + return err; + + return SR_ERR_OK; +} + static sr_error_t change_auth_check(struct confd *confd, sr_session_ctx_t *session) { sr_error_t err; - err = _sr_change_iter(session, XPATH_AUTH_"/user", check_sr_user_update); + err = _sr_change_iter(session, confd, XPATH_AUTH_"/user", check_sr_user_update); if (err) return err; @@ -1163,15 +1316,15 @@ static sr_error_t change_auth_done(struct confd *confd, sr_session_ctx_t *sessio { sr_error_t err; - err = _sr_change_iter(session, XPATH_AUTH_"/user", handle_sr_user_update); + err = _sr_change_iter(session, confd, XPATH_AUTH_"/user", handle_sr_user_update); if (err) return err; - err = _sr_change_iter(session, XPATH_AUTH_"/user[*]/password", handle_sr_passwd_update); + err = _sr_change_iter(session, confd, XPATH_AUTH_"/user[*]/password", handle_sr_passwd_update); if (err) goto cleanup; - err = _sr_change_iter(session, XPATH_AUTH_"/user[*]/shell", handle_sr_shell_update); + err = _sr_change_iter(session, confd, XPATH_AUTH_"/user[*]/shell", handle_sr_shell_update); if (err) goto cleanup; @@ -1191,10 +1344,39 @@ static int change_auth(sr_session_ctx_t *session, uint32_t sub_id, const char *m { struct confd *confd = (struct confd *)priv; - if (event == SR_EV_CHANGE) + switch (event) { + case SR_EV_UPDATE: + return change_auth_ctp(confd, session); + case SR_EV_CHANGE: return change_auth_check(confd, session); - if (event == SR_EV_DONE) + case SR_EV_DONE: return change_auth_done(confd, session); + default: + break; + } + + return SR_ERR_OK; +} + +static int auth_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *module, + const char *path, const char *request_path, uint32_t request_id, + struct lyd_node **parent, void *priv) +{ + struct spwd *spwd; + + ERROR("%s() path %s reqeust_path %s", __func__, path, request_path); + + setspent(); + while ((spwd = getspent())) { + const char *fmt = "/ietf-system:system/authentication/user[name='%s']/password"; + char xpath[256]; + + if (!spwd->sp_pwdp || spwd->sp_pwdp[0] == '*' || spwd->sp_pwdp[0] == '!') + continue; + + snprintf(xpath, sizeof(xpath), fmt, spwd->sp_namp); + lyd_new_path(*parent, NULL, xpath, spwd->sp_pwdp, 0, 0); + } return SR_ERR_OK; } @@ -1219,34 +1401,16 @@ static int change_nacm(sr_session_ctx_t *session, uint32_t sub_id, const char *m for (size_t i = 0; i < user_count; i++) { const char *user = users[i].data.string_val; bool is_admin = is_admin_user(session, user); - bool is_already = false; char *shell; - /* Check if user is already in group */ - if (!systemf("grep wheel /etc/group |grep %s", user)) - is_already = true; - - if (is_admin) { - if (is_already) - continue; /* already admin */ - - if (systemf("adduser %s wheel", user)) - ERROR("Failed giving user %s UNIX sysadmin permissions.", user); - else - NOTE("User %s added to UNIX sysadmin group.", user); - } else { - if (!is_already) - continue; /* not member of wheel */ - - if (systemf("delgroup %s wheel", user)) - ERROR("Failed removing user %s from UNIX sysadmin group.", user); - else - NOTE("User %s removed from UNIX sysadmin group.", user); - } - shell = sys_find_usable_shell(session, (char *)user, is_admin); if (set_shell(user, shell)) ERROR("Failed adjusting shell for user %s", user); + + if (is_admin) + add_group(user, "wheel"); + else + del_group(user, "wheel"); } cleanup: @@ -1375,29 +1539,135 @@ static int change_editor(sr_session_ctx_t *session, uint32_t sub_id, const char return SR_ERR_OK; } +static char *get_mac(struct confd *confd, char *mac, size_t len) +{ + struct json_t *obj; + + obj = json_object_get(confd->root, "mac-address"); + if (!json_is_string(obj)) { + fallback: + ERROR("Unknown or missing base MAC address."); + snprintf(mac, len, "UNKNOWN"); + } else { + const char *ptr = json_string_value(obj); + + if (strlen(ptr) < 17) + goto fallback; + + strlcpy(mac, &ptr[9], len); + mac[2] = '-'; + mac[5] = '-'; + } + + return mac; +} + +#define REPLACE_SPECIFIER(replacement) \ + do { \ + size_t repl_len = strlen(replacement); \ + char *ptr; \ + \ + hostlen += repl_len; \ + ptr = realloc(hostname, hostlen + 1); \ + if (!ptr) { \ + free(hostname); \ + free(*fmt); \ + return -1; \ + } \ + hostname = ptr; \ + strlcat(hostname, replacement, hostlen + 1); \ + j += repl_len; \ + } while (0) + +/* + * Decode hostname format specifiers (non-standard, Infix specifc) + * + * %i: OS ID (from /etc/os-release). infix on vanilla builds, + * %h: Default hostname (DEFAULT_HOSTNAME from /etc/os-release). infix on vanilla builds, + * %m: NIC specific part of base MAC, e.g., c0:ff:ee translated to c0-ff-ee + * %%: Literal % + * + * NOTE: to be forward compatible, any unknown % combination will be silently consumed. + * E.g., "example-%z" will become "example-" + * + * XXX: PLEASE REFACTOR THIS INTO A PYTHON HELPER FOR FUTURE EXTENSIONS, OR BUGS! + */ +static int hostnamefmt(struct confd *confd, char **fmt) +{ + size_t hostlen, fmt_len; + char *hostname; + char mac[10]; + size_t i, j; + + if (!fmt || !*fmt || !strchr(*fmt, '%')) + return 0; + + hostlen = fmt_len = strlen(*fmt); + hostname = calloc(hostlen + 1, sizeof(char)); + if (!hostname) + return -1; + + for (i = 0, j = 0; i < fmt_len; i++) { + if ((*fmt)[i] == '%') { + switch ((*fmt)[++i]) { + case 'i': + REPLACE_SPECIFIER(id); + break; + case 'h': + REPLACE_SPECIFIER(nm); + break; + case 'm': + REPLACE_SPECIFIER(get_mac(confd, mac, sizeof(mac))); + break; + case '%': + if (j < hostlen) { + hostname[j++] = '%'; + hostname[j] = 0; + } + break; + default: + break; /* Unknown, skip */ + } + } else { + if (j < hostlen) { + hostname[j++] = (*fmt)[i]; + hostname[j] = 0; + } + } + } + + free(*fmt); + *fmt = hostname; + + return 0; +} + +#undef REPLACE_SPECIFIER + static int change_hostname(sr_session_ctx_t *session, uint32_t sub_id, const char *module, const char *xpath, sr_event_t event, unsigned request_id, void *priv) { + struct confd *confd = (struct confd *)priv; const char *hostip = "127.0.1.1"; - char *nm, buf[256]; + char *hostnm, buf[256]; FILE *nfp, *fp; int err, fd; if (event != SR_EV_DONE) return SR_ERR_OK; - nm = srx_get_str(session, "%s", xpath); - if (!nm) { - nm = fgetkey("/etc/os-release", "DEFAULT_HOSTNAME"); - if (nm) - nm = strdup(nm); - if (!nm) { + hostnm = srx_get_str(session, "%s", xpath); + if (!hostnm) { + fallback: + hostnm = strdup(nm); + if (!hostnm) { err = SR_ERR_NO_MEMORY; goto err; } - } + } else if (hostnamefmt(confd, &hostnm)) + goto fallback; - err = sethostname(nm, strlen(nm)); + err = sethostname(hostnm, strlen(hostnm)); if (err) { ERROR("failed setting hostname"); err = SR_ERR_SYS; @@ -1410,7 +1680,7 @@ static int change_hostname(sr_session_ctx_t *session, uint32_t sub_id, const cha goto err; } - fprintf(fp, "%s\n", nm); + fprintf(fp, "%s\n", hostnm); fclose(fp); nfp = fopen(_PATH_HOSTS "+", "w"); @@ -1433,7 +1703,7 @@ static int change_hostname(sr_session_ctx_t *session, uint32_t sub_id, const cha while (fgets(buf, sizeof(buf), fp)) { if (!strncmp(buf, hostip, strlen(hostip))) - snprintf(buf, sizeof(buf), "%s\t%s\n", hostip, nm); + snprintf(buf, sizeof(buf), "%s\t%s\n", hostip, hostnm); fputs(buf, nfp); } @@ -1447,12 +1717,12 @@ static int change_hostname(sr_session_ctx_t *session, uint32_t sub_id, const cha goto err; /* Inform any running lldpd and avahi of the change ... */ - systemf("lldpcli configure system hostname %s", nm); - systemf("avahi-set-host-name %s", nm); + systemf("lldpcli configure system hostname %s", hostnm); + systemf("avahi-set-host-name %s", hostnm); system("initctl -nbq touch netbrowse"); err: - if (nm) - free(nm); + if (hostnm) + free(hostnm); if (err) { ERROR("Failed activating changes."); @@ -1465,17 +1735,36 @@ static int change_hostname(sr_session_ctx_t *session, uint32_t sub_id, const cha return SR_ERR_OK; } +static int hostname_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *module, + const char *path, const char *request_path, uint32_t request_id, + struct lyd_node **parent, void *priv) +{ + char hostname[128]; + int rc; + + gethostname(hostname, sizeof(hostname)); + rc = lyd_new_path(*parent, NULL, path, hostname, 0, NULL); + if (rc) { + ERROR("Failed building data tree, libyang error %d", rc); + rc = SR_ERR_INTERNAL; + } + + return rc; +} + int ietf_system_init(struct confd *confd) { - int rc = 0; + int rc; os_init(); - REGISTER_CHANGE(confd->session, "ietf-system", XPATH_AUTH_, 0, change_auth, confd, &confd->sub); + REGISTER_CHANGE(confd->session, "ietf-system", XPATH_AUTH_, SR_SUBSCR_UPDATE, change_auth, confd, &confd->sub); + REGISTER_OPER(confd->session, "ietf-system", PASSWORD_PATH, auth_cb, confd, 0, &confd->sub); REGISTER_MONITOR(confd->session, "ietf-netconf-acm", "/ietf-netconf-acm:nacm//.", 0, change_nacm, confd, &confd->sub); REGISTER_CHANGE(confd->session, "ietf-system", XPATH_BASE_"/hostname", 0, change_hostname, confd, &confd->sub); + REGISTER_OPER(confd->session, "ietf-system", XPATH_BASE_"/hostname", hostname_cb, confd, 0, &confd->sub); REGISTER_CHANGE(confd->session, "ietf-system", XPATH_BASE_"/infix-system:motd", 0, change_motd, confd, &confd->sub); REGISTER_CHANGE(confd->session, "ietf-system", XPATH_BASE_"/infix-system:motd-banner", 0, change_motd_banner, confd, &confd->sub); REGISTER_CHANGE(confd->session, "ietf-system", XPATH_BASE_"/infix-system:text-editor", 0, change_editor, confd, &confd->sub); diff --git a/src/confd/src/infix-meta.c b/src/confd/src/infix-meta.c new file mode 100644 index 0000000000..2936fdc544 --- /dev/null +++ b/src/confd/src/infix-meta.c @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: BSD-3-Clause */ + +#include "core.h" + +#define META_XPATH "/infix-meta:meta/version" + + +static int set_version(sr_session_ctx_t *session) +{ + int rc; + + rc = sr_set_item_str(session, META_XPATH, VERSION, NULL, 0); + if (rc) { + ERROR("Failed setting .cfg version %s: %d", VERSION, rc); + return rc; + } + + return SR_ERR_OK; +} + +static int change_cb(sr_session_ctx_t *session, uint32_t sub_id, const char *module, + const char *xpath, sr_event_t event, unsigned request_id, void *priv) +{ + if (event == SR_EV_UPDATE) + return set_version(session); + + return SR_ERR_OK; +} + +int infix_meta_init(struct confd *confd) +{ + int rc; + + REGISTER_CHANGE(confd->session, "infix-meta", META_XPATH, SR_SUBSCR_UPDATE, + change_cb, confd, &confd->sub); + return SR_ERR_OK; +fail: + ERROR("%s(): failed. %s", __func__, sr_strerror(rc)); + return rc; +} diff --git a/src/confd/yang-setup/yang-modules-containers.inc b/src/confd/yang-setup/yang-modules-containers.inc deleted file mode 100644 index 2b4d453a39..0000000000 --- a/src/confd/yang-setup/yang-modules-containers.inc +++ /dev/null @@ -1,4 +0,0 @@ -MODULES=( - "infix-interfaces@2024-01-15.yang -e vlan-filtering -e containers" - "infix-containers@2024-03-27.yang" -) \ No newline at end of file diff --git a/src/confd/yang-setup/yang-modules-confd.inc b/src/confd/yang/confd.inc similarity index 94% rename from src/confd/yang-setup/yang-modules-confd.inc rename to src/confd/yang/confd.inc index c6675ce55e..b4e19a5805 100644 --- a/src/confd/yang-setup/yang-modules-confd.inc +++ b/src/confd/yang/confd.inc @@ -1,3 +1,5 @@ +# -*- sh -*- +# REMEMBER TO UPDATE infix-interfaces ALSO IN containers.inc MODULES=( "ietf-system@2014-08-06.yang -e authentication -e local-users -e ntp -e ntp-udp-port -e timezone-name" "iana-timezones@2013-11-19.yang" @@ -25,8 +27,8 @@ MODULES=( "ieee802-dot1ab-lldp@2022-03-15.yang" "infix-lldp@2023-08-23.yang" "infix-dhcp-client@2024-04-12.yang" - "infix-shell-type@2023-08-21.yang" - "infix-system@2024-04-12.yang" + "infix-meta@2024-06-19.yang" + "infix-system@2024-06-15.yang" "infix-services@2024-05-30.yang" "ieee802-ethernet-interface@2019-06-21.yang" "infix-ethernet-interface@2024-02-27.yang" @@ -45,4 +47,4 @@ MODULES=( "ietf-tls-server@2023-12-28.yang -e server-ident-raw-public-key -e server-ident-x509-cert" "ietf-restconf@2017-01-26.yang" "infix-interfaces@2024-01-15.yang -e vlan-filtering" -) \ No newline at end of file +) diff --git a/src/confd/yang/containers.inc b/src/confd/yang/containers.inc new file mode 100644 index 0000000000..6ddd91666e --- /dev/null +++ b/src/confd/yang/containers.inc @@ -0,0 +1,6 @@ +# -*- sh -*- +# REMEMBER TO UPDATE infix-interfaces ALSO IN confd.inc +MODULES=( + "infix-interfaces@2024-01-15.yang -e vlan-filtering -e containers" + "infix-containers@2024-03-27.yang" +) diff --git a/src/confd/yang/infix-meta@2024-06-19.yang b/src/confd/yang/infix-meta@2024-06-19.yang new file mode 100644 index 0000000000..e7c2fc1235 --- /dev/null +++ b/src/confd/yang/infix-meta@2024-06-19.yang @@ -0,0 +1,22 @@ +module infix-meta { + yang-version 1.1; + namespace "urn:infix:meta:ns:yang:1.0"; + prefix infix-meta; + + organization "KernelKit"; + contact "kernelkit@googlegroups.com"; + description "Infix metadata."; + + revision 2024-06-19 { + description "Initial revision."; + reference "internal"; + } + + container meta { + leaf version { + status obsolete; // Ensure frontends don't show this, used for migration. + description "Configuration file format version, automatically generated."; + type string; + } + } +} diff --git a/src/confd/yang/infix-shell-type@2023-08-21.yang b/src/confd/yang/infix-shell-type@2023-08-21.yang deleted file mode 100644 index 3a05fdde60..0000000000 --- a/src/confd/yang/infix-shell-type@2023-08-21.yang +++ /dev/null @@ -1,39 +0,0 @@ -module infix-shell-type { - yang-version 1.1; - namespace "urn:ietf:params:xml:ns:yang:infix-shell-type"; - prefix infixsh; - - organization "KernelKit"; - contact "kernelkit@googlegroups.com"; - description "Infix augments and deviations to ietf-system."; - - revision 2023-08-21 { - description "Initial revision."; - reference "internal"; - } - - /* - * Identities - */ - - identity shell-type { - description "Base identity from which specific shell types are derived."; - } - - identity bash { - description "Bourne again shell (BASH), standard UNIX shell."; - base shell-type; - } - identity clish { - description "Dedicated switch/router shell, similar to Cisco/JunOS."; - base shell-type; - } - identity sh { - description "POSIX shell, the original plain UNIX shell."; - base shell-type; - } - identity false { - description "Shell login disabled, both console and SSH."; - base shell-type; - } -} diff --git a/src/confd/yang/infix-system@2024-04-12.yang b/src/confd/yang/infix-system@2024-06-15.yang similarity index 52% rename from src/confd/yang/infix-system@2024-04-12.yang rename to src/confd/yang/infix-system@2024-06-15.yang index 908ff34d1e..020ef7f2bb 100644 --- a/src/confd/yang/infix-system@2024-04-12.yang +++ b/src/confd/yang/infix-system@2024-06-15.yang @@ -9,9 +9,6 @@ module infix-system { import iana-timezones { prefix iana-tz; } - import infix-shell-type { - prefix infixsh; - } include infix-system-software; @@ -19,6 +16,23 @@ module infix-system { contact "kernelkit@googlegroups.com"; description "Infix augments and deviations to ietf-system."; + revision 2024-06-15 { + description "Merge infix-shell-types.yang to add shell-type identities."; + reference "internal"; + } + + revision 2024-06-14 { + description "Add support for format specifiers in hostname: + - %h default hostname from /etc/os-release + - %i value of ID from /etc/os-release + - %m last three octets of base MAC, e.g., c0-ff-ee + + Add support for yescrypt and $factory$ in password. + The latter is a reserved string which is interpreted + as the device default password from the VPD EEPROM."; + reference "internal"; + } + revision 2024-04-12 { description "New type, infix:hostname, for /system/hostname (max 64 chars)."; reference "internal"; @@ -75,10 +89,87 @@ module infix-system { base editor-type; } + identity shell-type { + description "Base identity from which specific shell types are derived."; + } + + identity bash { + description "Bourne again shell (BASH), standard UNIX shell."; + base shell-type; + } + identity clish { + description "Dedicated switch/router shell, similar to Cisco/JunOS."; + base shell-type; + } + identity sh { + description "POSIX shell, the original plain UNIX shell."; + base shell-type; + } + identity false { + description "Shell login disabled, both console and SSH."; + base shell-type; + } + /* * Typedefs */ + typedef crypt-hash { + type string { + pattern + '$0$.*' + + '|$1$[a-zA-Z0-9./]{1,8}$[a-zA-Z0-9./]{22}' + + '|$5$(rounds=\d+$)?[a-zA-Z0-9./]{1,16}$[a-zA-Z0-9./]{43}' + + '|$6$(rounds=\d+$)?[a-zA-Z0-9./]{1,16}$[a-zA-Z0-9./]{86}' + + '|$y$[a-zA-Z0-9./]+$[a-zA-Z0-9./]{1,86}$[a-zA-Z0-9./]{43}' + + '|$factory$.*'; + } + description + "This type is used to store passwords using a hash function. It + extends the IANA crypt-hash type to support yescrypt as well as + a reserved string '$factory$', used for device-specific factory + default hash. It is up to the underlying system to define this + further, one example is to use Vital Product Data (VPD), e.g., + an onboard EEPROM where a device hash is stored for the initial + 'admin' user. + + A value of this type matches one of the forms: + + $0$ + $$$ + $$$$ + + The '$0$' prefix signals that the value is clear text, and even + though it is supported, it is *not* recommended! When such a + value is received it passes through multiple subsystems before + a hash value is calculated and the string '$$$' or + $$$$ is prepended and the result is stored + in the configuration data store. The hash function used depend + on end system requirements. + + When any other '$$' prefix is received, the system store it + 'as is' in the configuration data store. + + When a server needs to verify a password given by a user, it + finds the stored password hash string for that user, extracts + the salt, and calculates the hash with the salt and given + password as input. If the calculated hash value is the same as + the stored value, the password given by the client is accepted. + + This type defines the following supported hash functions: + + id | hash function | feature + ---+---------------+------------------- + 1 | MD5 | crypt-hash-md5 + 5 | SHA-256 | crypt-hash-sha-256 + 6 | SHA-512 | crypt-hash-sha-512 + y | yescrypt | crypt-hash-yescrypt"; + reference + "IEEE Std 1003.1-2008 - crypt() function + RFC 1321: The MD5 Message-Digest Algorithm + FIPS.180-4.2012: Secure Hash Standard (SHS)"; + } + typedef username { type string { pattern "[_a-zA-Z0-9][-._a-zA-Z0-9]*$?"; @@ -89,12 +180,17 @@ module infix-system { typedef hostname { type string { pattern - '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*' - + '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)' - + '|\.'; + '(' + + '(([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*' + + '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?' + + '|%[him]' + + ')' + + '([a-zA-Z0-9\-_\.]|%[him])*'; length "1..64"; } - description "Linux have the same restrictions as IETF, only shorter."; + description "Linux have the same restrictions as IETF, only shorter. + Format specifiers are for, default hostname, ID, and the + last three octets in base MAC, e.g., c0-ff-ee"; } /* @@ -143,9 +239,9 @@ module infix-system { description "Augment of ietf-system to support setting login shell for users."; leaf shell { type identityref { - base infixsh:shell-type; + base shell-type; } - default infixsh:false; + default false; description "Set UNIX login shell for user, default: none (security)"; } } @@ -186,4 +282,11 @@ module infix-system { type infix-sys:username; } } + + deviation "/sys:system/sys:authentication/sys:user/sys:password" { + description "Extended password hash, including missing types, and $factory$."; + deviate replace { + type infix-sys:crypt-hash; + } + } } diff --git a/src/klish-plugin-infix/src/infix.c b/src/klish-plugin-infix/src/infix.c index f2d9265f2c..1b17db1658 100644 --- a/src/klish-plugin-infix/src/infix.c +++ b/src/klish-plugin-infix/src/infix.c @@ -591,6 +591,7 @@ int infix_copy(kcontext_t *ctx) err: if (tmpfn) rc = remove(tmpfn); + sync(); /* ensure command is flushed to disk */ return rc; } diff --git a/src/klish-plugin-infix/xml/infix.xml b/src/klish-plugin-infix/xml/infix.xml index d8d9efbe58..3c1b605824 100644 --- a/src/klish-plugin-infix/xml/infix.xml +++ b/src/klish-plugin-infix/xml/infix.xml @@ -188,11 +188,12 @@ - + - md5 - sha256 - sha512 + md5crypt + sha256crypt + sha512crypt + yescrypt @@ -586,12 +587,12 @@ - + - + diff --git a/src/libsrx/src/srx_val.c b/src/libsrx/src/srx_val.c index 4cf8743466..f2f3d35383 100644 --- a/src/libsrx/src/srx_val.c +++ b/src/libsrx/src/srx_val.c @@ -25,6 +25,37 @@ sr_error_t srx_get_diff(sr_session_ctx_t *session, struct lyd_node **treep) return err; } +/* check if string at xpath (fmt) is set (non-zero length) */ +bool srx_isset(sr_session_ctx_t *session, const char *fmt, ...) +{ + sr_val_t *value = NULL; + bool isset = false; + char *xpath; + va_list ap; + size_t len; + + va_start(ap, fmt); + len = vsnprintf(NULL, 0, fmt, ap) + 1; + va_end(ap); + + xpath = alloca(len); + if (!xpath) + return false; + + va_start(ap, fmt); + vsnprintf(xpath, len, fmt, ap); + va_end(ap); + + if (sr_get_item(session, xpath, 0, &value)) + return false; + + if (value->data.string_val[0] != 0) + isset = true; + sr_free_val(value); + + return isset; +} + int srx_set_item(sr_session_ctx_t *session, const sr_val_t *val, sr_edit_options_t opts, const char *fmt, ...) { diff --git a/src/libsrx/src/srx_val.h b/src/libsrx/src/srx_val.h index 675dea7184..45c95cb09c 100644 --- a/src/libsrx/src/srx_val.h +++ b/src/libsrx/src/srx_val.h @@ -3,12 +3,14 @@ #ifndef CONFD_SRX_VAL_H_ #define CONFD_SRX_VAL_H_ +#include #include "common.h" #define SRX_GET_UINT8(s,v,fmt,...) srx_get_int(s, &v, SR_UINT8_T, fmt, ##__VA_ARGS__) #define SRX_GET_UINT32(s,v,fmt,...) srx_get_int(s, &v, SR_UINT32_T, fmt, ##__VA_ARGS__) sr_error_t srx_get_diff(sr_session_ctx_t *session, struct lyd_node **treep); +bool srx_isset(sr_session_ctx_t *session, const char *fmt, ...); int srx_set_item(sr_session_ctx_t *, const sr_val_t *, sr_edit_options_t, const char *, ...) __attribute__ ((format (printf, 4, 5))); diff --git a/test/case/ietf_system/hostname.py b/test/case/ietf_system/hostname.py index 8818266379..df500e1c3f 100755 --- a/test/case/ietf_system/hostname.py +++ b/test/case/ietf_system/hostname.py @@ -1,13 +1,16 @@ #!/usr/bin/env python3 -import random, string - +import random +import string +import re import infamy with infamy.Test() as test: with test.step("Initialize"): env = infamy.Env(infamy.std_topology("1x1")) target = env.attach("target", "mgmt") + tgtssh = env.attach("target", "mgmt", "ssh") + fmt = "%h-%m" with test.step("Set new hostname"): new = "".join((random.choices(string.ascii_lowercase, k=16))) @@ -20,6 +23,30 @@ with test.step(f"Verify new hostname ({new})"): running = target.get_config_dict("/ietf-system:system") - assert(running["system"]["hostname"] == new) + assert running["system"]["hostname"] == new + + with test.step(f"Set hostname format: {fmt}"): + target.put_config_dict("ietf-system", { + "system": { + "hostname": fmt, + } + }) + + with test.step(f"Verify hostname format in running: {fmt}"): + running = target.get_config_dict("/ietf-system:system") + if running["system"]["hostname"] != fmt: + test.fail() + + cmd = tgtssh.runsh("sed -n s/^DEFAULT_HOSTNAME=//p /etc/os-release") + default = cmd.stdout.rstrip() + + with test.step(f"Verify hostname format in operational: {default}-c0-ff-ee"): + + oper = target.get_data("/ietf-system:system") + name = oper["system"]["hostname"] + pattern = rf'^{default}-([0-9a-fA-F]{{2}}-){{2}}[0-9a-fA-F]{{2}}$' + regex = re.compile(pattern) + if not regex.match(name): + test.fail() test.succeed() diff --git a/test/case/ietf_system/user_admin.py b/test/case/ietf_system/user_admin.py index 5f21d8fe47..3454b5469f 100755 --- a/test/case/ietf_system/user_admin.py +++ b/test/case/ietf_system/user_admin.py @@ -1,10 +1,13 @@ #!/usr/bin/env python3 """ - Add a non-admin user and verify they have no privs - Add user to admin group and recheck privileges + - Add a non-admin user and verify they have no privs + - Add user to admin group and recheck privileges + - Test admin user, verify $factory$ password in running + and active password in operational datastore """ import infamy +import infamy.ssh as ssh from passlib.hash import sha256_crypt with infamy.Test() as test: @@ -12,6 +15,8 @@ env = infamy.Env(infamy.std_topology("1x1")) target = env.attach("target", "mgmt") tgtssh = env.attach("target", "mgmt", "ssh") + factory = env.get_password("target") + address = target.address() with test.step("Add new user"): USER = "jacky" @@ -24,7 +29,7 @@ { "name": USER, "password": PASS, - "shell": "infix-shell-type:bash" + "shell": "infix-system:bash" } ] } @@ -53,20 +58,13 @@ test.fail() with test.step(f"Add {USER} user to admin group"): - target.put_config_dict("ietf-netconf-acm", { - "nacm": { - "groups": { - "group": [ - { - "name": "admin", - "user-name": [ - "admin", - "jacky" - ] - } - ] - } - }}) + # Don't presume 'admin' user exists, only group + nacm = target.get_config_dict("/ietf-netconf-acm:nacm") + for group in nacm["nacm"]["groups"]["group"]: + if group["name"] == "admin": + if USER not in group["user-name"]: + group["user-name"].append(USER) + target.put_config_dict("ietf-netconf-acm", nacm) with test.step(f"Verify user {USER} is now in wheel group ..."): if not tgtssh.runsh(f"grep wheel /etc/group | grep '{USER}'"): @@ -77,4 +75,40 @@ if "bash" not in user: test.fail() + with test.step(f"Change user {USER} to $factory$ password ..."): + running = target.get_config_dict("/ietf-system:system") + users = running["system"]["authentication"]["user"] + + for user in users: + if user['name'] == USER: + user['password'] = "$factory$" + break + target.put_config_dict("ietf-system", running) + + with test.step(f"Verify user {USER} exists and has new password ..."): + operational = target.get_data("/ietf-system:system/authentication") + users = operational["system"]["authentication"]["user"] + + found = None + for user in users: + if user['name'] == USER: + found = user + break + + if found is None: + test.fail() + if found['password'] == "$factory$": + test.fail() + if found['password'] == PASS: + test.fail() + + with test.step(f"Verify user {USER} can log in with SSH ..."): + conn = ssh.Device(ssh.Location(address, factory, USER)) + try: + pwd = conn.runsh(f"cat /etc/passwd | grep {USER}").stdout + print(f"Found {pwd.rstrip()}") + except Exception as err: + print(f"Failed connecting to target as {USER}: {err}") + test.fail() + test.succeed() diff --git a/test/infamy/env.py b/test/infamy/env.py index 870b65a220..27563a4ece 100644 --- a/test/infamy/env.py +++ b/test/infamy/env.py @@ -48,7 +48,7 @@ def __init__(self, ltop=None, argv=sys.argv[1::], environ=os.environ): def attr(self, name, default=None): val = self.ptop.get_attr("ix_" + name) - if val == None: + if val is None: return default try: @@ -58,6 +58,12 @@ def attr(self, name, default=None): return val + def get_password(self, node): + password = self.ptop.get_password(node) + if not password: + password = "admin" + return password + def attach(self, node, port, protocol="netconf", factory_default=True): if self.ltop: mapping = self.ltop.mapping[node] @@ -65,10 +71,6 @@ def attach(self, node, port, protocol="netconf", factory_default=True): else: mapping = None - password=self.ptop.get_password(node) - - if not password: - password = "admin" ctrl = self.ptop.get_ctrl() cport, _ = self.ptop.get_mgmt_link(ctrl, node) @@ -77,6 +79,7 @@ def attach(self, node, port, protocol="netconf", factory_default=True): if not mgmtip: raise Exception(f"Failed, cannot find mgmt IP for {node}") + password = self.get_password(node) if protocol == "netconf": return netconf.Device( location=netconf.Location(cport, mgmtip, password), @@ -84,10 +87,12 @@ def attach(self, node, port, protocol="netconf", factory_default=True): yangdir=self.args.yangdir, factory_default=factory_default ) - elif protocol == "ssh": + if protocol == "ssh": return ssh.Device(ssh.Location(mgmtip, password)) - elif protocol == "restconf": - return restconf.Device(location=restconf.Location(cport, mgmtip, password), + if protocol == "restconf": + return restconf.Device(location=restconf.Location(cport, + mgmtip, + password), mapping=mapping, factory_default=factory_default) diff --git a/test/infamy/netconf.py b/test/infamy/netconf.py index b2d51e6b73..991bea1cd6 100644 --- a/test/infamy/netconf.py +++ b/test/infamy/netconf.py @@ -17,6 +17,7 @@ from netconf_client.error import RpcError + def netconf_syn(addr): try: ai = socket.getaddrinfo(addr, 830, 0, 0, socket.SOL_TCP) @@ -25,21 +26,25 @@ def netconf_syn(addr): sock.close() print(f"{addr} answers to TCP connections on port 830 (NETCONF)") return True - except: + except Exception: return False modinfo_fields = ("identifier", "version", "format", "namespace") ModInfoTuple = namedtuple("ModInfoTuple", modinfo_fields) + + class ModInfo(ModInfoTuple): def xmlns(self): return f"xmlns:{self.identifier}=\"{self.namespace}\"" + NS = { "ietf-netconf-monitoring": "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring", "nc": "urn:ietf:params:xml:ns:netconf:base:1.0", } + class Manager(netconf_client.ncclient.Manager): """Wrapper for the real manager @@ -53,9 +58,10 @@ def _fetch_connection_ip(self): self._peer_ip = None try: self._local_ip = self.session.sock.sock.getsockname()[0] - self._peer_ip = self.session.sock.sock.getpeername()[0] - print(f"Connection status\n\tLocal IP: {self._local_ip}\n\tPeer IP: {self._peer_ip}") - except (AttributeError, socket_error) as err: + self._peer_ip = self.session.sock.sock.getpeername()[0] + print(f"Connection status\n\tLocal IP: {self._local_ip}\n" + "\tPeer IP: {self._peer_ip}") + except (AttributeError, socket.error) as err: print(f"Failed connecting, status: {err}") pass @@ -89,15 +95,15 @@ def __init__(self, location: Location, mapping: dict, yangdir: None | str = None, - factory_default = True): + factory_default=True): self.location = location self.mapping = mapping self.location = location self.ly = libyang.Context(yangdir) self._ncc_init(location) - #self.ncc._fetch_connection_ip() - #self.ncc._debug() + # self.ncc._fetch_connection_ip() + # self.ncc._debug() self.modules = {} self._ly_bootstrap(yangdir) @@ -147,7 +153,9 @@ def _ncc_init(self, location): self.ncc = Manager(session) def _ly_bootstrap(self, yangdir): - self.modules["ietf-netconf-monitoring"] = { "name": "ietf-netconf-monitoring" } + self.modules["ietf-netconf-monitoring"] = { + "name": "ietf-netconf-monitoring" + } for val in self.modules.values(): mod = self.ly.load_module(val["name"]) @@ -156,7 +164,8 @@ def _ly_bootstrap(self, yangdir): for schema in schemas: if os.path.exists(yangdir + "/" + schema['filename']) is False: self.get_schema(schema, yangdir) - sys.stdout.write(f"Downloading YANG model {schema['identifier']} ...\r\033[K") + sys.stdout.write("Downloading YANG model " + f"{schema['identifier']} ...\r\033[K") print("YANG models downloaded.") def _ly_init(self, yangdir): @@ -166,14 +175,14 @@ def _ly_init(self, yangdir): ns = libyang.util.c2str(lib.cdata.ns) xml = lxml.etree.tostring(self.ncc.get(filter=f""" - - - """).data_ele[0]) + + + """).data_ele[0]) data = self.ly.parse_data("xml", libyang.IOType.MEMORY, xml, parse_only=True).print_dict() - self.modules = { m["name"] : m for m in data["modules-state"]["module"] } + self.modules = {m["name"]: m for m in data["modules-state"]["module"]} for ms in self.modules.values(): if ms["conformance-type"] != "implement": @@ -217,13 +226,14 @@ def _ncc_get_data_rpc(self, datastore="operational", filter=None, msg_id=None): f'ds:{datastore}' f'') if filter: - xmlns = " ".join([f"xmlns:{m['name']}=\"{m['namespace']}\"" for m in self._modules_in_xpath(filter)]) + xmlns = " ".join([f"xmlns:{m['name']}=\"{m['namespace']}\"" + for m in self._modules_in_xpath(filter)]) pieces.append(f'{filter}') pieces.append("") return self._ncc_make_rpc("".join(pieces), msg_id=msg_id) def copy(self, source, target): - cmd=f''' + cmd = f''' <{target}/> @@ -234,18 +244,18 @@ def copy(self, source, target): self.ncc._send_rpc(self._ncc_make_rpc(cmd)) def reboot(self): - cmd='' - return self.call_dict("ietf-system", - { - "system-restart" : {} - }) + """""" + return self.call_dict("ietf-system", { + "system-restart": {} + }) def _get(self, xpath, getter, as_xml=False): # Figure out which modules we are referencing mods = self._modules_in_xpath(xpath) # Fetch the data - xmlns = " ".join([f"xmlns:{m['name']}=\"{m['namespace']}\"" for m in mods]) + xmlns = " ".join([f"xmlns:{m['name']}=\"{m['namespace']}\"" + for m in mods]) filt = f"" # pylint: disable=c-extension-no-member data = getter(filter=filt).data_ele[0] @@ -254,7 +264,7 @@ def _get(self, xpath, getter, as_xml=False): cfg = lxml.etree.tostring(data) return self.ly.parse_data_mem(cfg, "xml", parse_only=True) - def _get_data(self, xpath,as_xml=False): + def _get_data(self, xpath, as_xml=False): """Local member wrapper for netconf-client RPC""" # pylint: disable=protected-access (raw, ele) = self.ncc._send_rpc(self._ncc_get_data_rpc(filter=xpath)) @@ -273,7 +283,7 @@ def get(self, xpath, as_xml=False): """RPC (legacy NETCONF) fetches config:false data""" return self._get(xpath, self.ncc.get, as_xml) - def get_dict(self, xpath,as_xml=False): + def get_dict(self, xpath, as_xml=False): """Return Python dictionary of RPC data""" if as_xml: return self.get(xpath, as_xml=True) @@ -287,7 +297,7 @@ def get_dict(self, xpath,as_xml=False): def get_data(self, xpath=None, as_xml=False): """RPC to fetch operational data""" if as_xml: - return self._get_data(xpath,as_xml) + return self._get_data(xpath, as_xml) data = self._get_data(xpath) if not data: @@ -310,15 +320,16 @@ def put_config(self, edit): "delete": "delete", } - xml = f"" + edit + "" + xml = f"" \ + + edit + "" # Translate any edit operations from the yang format generated # by diffing trees with libyang, to their NETCONF equivalents. - for src,dst in yang2nc.items(): + for src, dst in yang2nc.items(): xml = xml.replace(f"yang:operation=\"{src}\"", f"nc:operation=\"{dst}\"" if dst else "") - for _ in range(0,3): + for _ in range(0, 3): try: self.ncc.edit_config(xml, default_operation='merge') except RpcError as _e: @@ -352,7 +363,8 @@ def call_dict(self, modname, call): def call_action(self, action): """Call NETCONF action (contextualized RPC), XML version""" - xml = "" + action + "" + xml = "" \ + + action + "" return self.ncc.dispatch(xml) def call_action_dict(self, modname, action): @@ -362,16 +374,16 @@ def call_action_dict(self, modname, action): return self.call_action(lyd.print_mem("xml", with_siblings=True, pretty=False)) def get_schemas_list(self): - schemas=[] + schemas = [] - data= self.get_dict("/netconf-state") + data = self.get_dict("/netconf-state") for d in data["netconf-state"]["schemas"]["schema"]: - schema={} + schema = {} schema["identifier"] = d['identifier'] schema["format"] = d["format"] if d['version']: schema["version"] = d['version'] - schema["filename"]= f"{d['identifier']}@{d['version']}.yang" + schema["filename"] = f"{d['identifier']}@{d['version']}.yang" else: schema["filename"] = f"{d['identifier']}.yang" schemas.append(schema) diff --git a/test/infamy/ssh.py b/test/infamy/ssh.py index d44735aa7c..af0300eb78 100644 --- a/test/infamy/ssh.py +++ b/test/infamy/ssh.py @@ -2,6 +2,7 @@ from dataclasses import dataclass + @dataclass class Location: host: str @@ -9,13 +10,14 @@ class Location: username: str = "admin" port: int = 22 + class Device(object): def __init__(self, location: Location): self.location = location def _mangle_subprocess_args(self, args, kwargs): if not args: - return + return None args = list(args) if type(args[0]) == str: @@ -25,15 +27,15 @@ def _mangle_subprocess_args(self, args, kwargs): else: args[0] = [args[0]] - args[0] = [ "ssh", - "-oStrictHostKeyChecking no", - "-oUserKnownHostsFile /dev/null", - "-oLogLevel QUIET", - f"-l{self.location.username}", - self.location.host ] + args[0] + args[0] = ["ssh", + "-oStrictHostKeyChecking no", + "-oUserKnownHostsFile /dev/null", + "-oLogLevel QUIET", + f"-l{self.location.username}", + self.location.host] + args[0] if self.location.password: - args[0] = [ "sshpass" , f"-p{self.location.password}" ] + args[0] + args[0] = ["sshpass", f"-p{self.location.password}"] + args[0] return args, kwargs @@ -43,4 +45,5 @@ def run(self, *args, **kwargs): def runsh(self, script, *args, **kwargs): return self.run("/bin/sh", text=True, input=script, - stdout=subprocess.PIPE, stderr=subprocess.STDOUT, *args, **kwargs) + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, *args, **kwargs) diff --git a/utils/sysrepo-load-modules.sh b/utils/sysrepo-load-modules.sh index ab4f898590..a50fae5880 100755 --- a/utils/sysrepo-load-modules.sh +++ b/utils/sysrepo-load-modules.sh @@ -1,29 +1,22 @@ #!/usr/bin/env bash -set -x # This is based on scripts/setup.sh from Netopeer2/libnetconf2 -# env variables NP2_MODULE_DIR, NP2_MODULE_PERMS must be defined and NP2_MODULE_OWNER, NP2_MODULE_GROUP will be used if -# defined when executing this script! -#if [ -z "$NP2_MODULE_DIR" -o -z "$NP2_MODULE_PERMS" ]; then -# echo "Required environment variables not defined!" -# exit 1 -#fi +# +#set -x - -# Source the provided file, which is expected to contain the list of YANG modules and their features. -# This file, specified by the first argument to the script ($1), is sourced to populate the MODULES -# array with the modules and their respective features to be processed by this script. -# The file typically includes definitions in the form of module@revision with optional features to enable, -# e.g., module@revision -e feature1 -e feature2. -source $1 +# Source the include file, which contain the list of YANG models and +# their respective enabled features in a MODULES array. +# Example: +# MODULES=("module@revision -e feature1 -e feature2") +source "$1" # optional env variable override if [ -n "$SYSREPOCTL_EXECUTABLE" ]; then SYSREPOCTL="$SYSREPOCTL_EXECUTABLE" # avoid problems with sudo PATH elif [ `id -u` -eq 0 ] && [ -n "$USER" ] && [ `command -v su` ]; then - SYSREPOCTL=`command -v sysrepoctl -l $USER` + SYSREPOCTL=`command sysrepoctl -l $USER` else - SYSREPOCTL=`command -v sysrepoctl` + SYSREPOCTL=`command sysrepoctl` fi MODDIR=${SEARCH_PATH} @@ -48,8 +41,8 @@ INSTALL_MODULE_CMD() { } UPDATE_MODULE() { - CMD="'$SYSREPOCTL' -U $MODDIR/$1 -s '$MODDIR -v2" - eval $CMD + CMD="'$SYSREPOCTL' -U $MODDIR/$1 -s '$MODDIR' -v2" + eval "$CMD" local rc=$? if [ $rc -ne 0 ]; then exit $rc @@ -87,6 +80,7 @@ for i in "${MODULES[@]}"; do SCTL_MODULE=`echo "$SCTL_MODULES" | grep "^$name \+|[^|]*| I"` if [ -z "$SCTL_MODULE" ]; then # prepare command to install module with all its features + echo "*** Installing YANG model $name ..." INSTALL_MODULE_CMD "$i" continue fi @@ -96,6 +90,7 @@ for i in "${MODULES[@]}"; do if [ "$sctl_revision" \< "$revision" ]; then # update module without any features file=`echo "$i" | cut -d' ' -f 1` + echo "*** Updating YANG model $name ($file) ..." UPDATE_MODULE "$file" fi @@ -104,6 +99,7 @@ for i in "${MODULES[@]}"; do sctl_perms=`echo "$SCTL_MODULE" | sed 's/\([^|]*|\)\{4\} \([^ ]*\).*/\2/'` if [ "$sctl_perms" != "$PERMS" ]; then # change permissions/owner + echo "*** Changing YANG model $name permissions ..." CHANGE_PERMS "$name" fi @@ -128,8 +124,10 @@ for i in "${MODULES[@]}"; do features=`echo "$features" | sed 's/[^[:space:]]* \(.*\)/\1/'` done done + # install all the new modules -if [ ! -z "${CMD_INSTALL}" ]; then +if [ -n "${CMD_INSTALL}" ]; then + printf "*** Installing YANG models ...\n%s" "$CMD_INSTALL" eval $CMD_INSTALL rc=$? if [ $rc -ne 0 ]; then