=== modified file 'DBUS-API' --- DBUS-API 2018-02-08 10:23:55 +0000 +++ DBUS-API 2019-02-10 04:20:26 +0000 @@ -27,9 +27,9 @@ Removes a client ** Signals: -*** ClientNotFound(s: Fingerprint, s: Address) - A client connected from Address using Fingerprint, but was - rejected because it was not found in the server. The fingerprint +*** ClientNotFound(s: KeyID, s: Address) + A client connected from Address using KeyID, but was + rejected because it was not found in the server. The key ID is represented as a string of hexadecimal digits. The address is an IPv4 or IPv6 address in its normal string format. @@ -66,6 +66,7 @@ | Expires (f) | s | Read | N/A | | ExtendedTimeout (a) | t | Read/Write | extended_timeout | | Fingerprint | s | Read | fingerprint | + | KeyID | s | Read | key_id | | Host | s | Read/Write | host | | Interval (a) | t | Read/Write | interval | | LastApprovalRequest (g) | s | Read | N/A | @@ -130,8 +131,8 @@ * Copyright - Copyright © 2010-2018 Teddy Hogeborn - Copyright © 2010-2018 Björn Påhlsson + Copyright © 2010-2019 Teddy Hogeborn + Copyright © 2010-2019 Björn Påhlsson ** License: === modified file 'INSTALL' --- INSTALL 2016-07-03 03:32:28 +0000 +++ INSTALL 2019-02-09 23:23:26 +0000 @@ -39,6 +39,7 @@ *** Mandos Server + GnuTLS 3.3 https://www.gnutls.org/ + (but not 3.6.0 or later, until 3.6.6, which works) + Avahi 0.6.16 http://www.avahi.org/ + Python 2.7 https://www.python.org/ + dbus-python 0.82.4 https://dbus.freedesktop.org/doc/dbus-python/ @@ -60,6 +61,7 @@ + initramfs-tools 0.85i https://tracker.debian.org/pkg/initramfs-tools + GnuTLS 3.3 https://www.gnutls.org/ + (but not 3.6.0 or later, until 3.6.6 which works) + Avahi 0.6.16 http://www.avahi.org/ + GnuPG 1.4.9 https://www.gnupg.org/ + GPGME 1.1.6 https://www.gnupg.org/related_software/gpgme/ @@ -69,7 +71,7 @@ + OpenSSH http://www.openssh.com/ Package names: - initramfs-tools libgnutls-dev libavahi-core-dev gnupg + initramfs-tools libgnutls-dev gnutls-bin libavahi-core-dev gnupg libgpgme11-dev pkg-config ssh * Installing the Mandos server @@ -123,7 +125,9 @@ # /usr/lib/mandos/plugins.d/mandos-client \ --pubkey=/etc/keys/mandos/pubkey.txt \ - --seckey=/etc/keys/mandos/seckey.txt; echo + --seckey=/etc/keys/mandos/seckey.txt \ + --tls-privkey=/etc/keys/mandos/tls-privkey.pem \ + --tls-pubkey=/etc/keys/mandos/tls-pubkey.pem; echo This command should retrieve the password from the server, decrypt it, and output it to standard output. === modified file 'Makefile' --- Makefile 2018-08-19 14:06:55 +0000 +++ Makefile 2019-02-11 06:31:42 +0000 @@ -40,7 +40,7 @@ OPTIMIZE:=-Os -fno-strict-aliasing LANGUAGE:=-std=gnu11 htmldir:=man -version:=1.7.19 +version:=1.8.3 SED:=sed USER:=$(firstword $(subst :, ,$(shell getent passwd _mandos || getent passwd nobody || echo 65534))) @@ -284,7 +284,7 @@ ./mandos-ctl --check # Run the client with a local config and key -run-client: all keydir/seckey.txt keydir/pubkey.txt +run-client: all keydir/seckey.txt keydir/pubkey.txt keydir/tls-privkey.pem keydir/tls-pubkey.pem @echo "###################################################################" @echo "# The following error messages are harmless and can be safely #" @echo "# ignored: #" @@ -303,12 +303,12 @@ ./plugin-runner --plugin-dir=plugins.d \ --plugin-helper-dir=plugin-helpers \ --config-file=plugin-runner.conf \ - --options-for=mandos-client:--seckey=keydir/seckey.txt,--pubkey=keydir/pubkey.txt,--network-hook-dir=network-hooks.d \ + --options-for=mandos-client:--seckey=keydir/seckey.txt,--pubkey=keydir/pubkey.txt,--tls-privkey=keydir/tls-privkey.pem,--tls-pubkey=keydir/tls-pubkey.pem,--network-hook-dir=network-hooks.d \ --env-for=mandos-client:GNOME_KEYRING_CONTROL= \ $(CLIENTARGS) # Used by run-client -keydir/seckey.txt keydir/pubkey.txt: mandos-keygen +keydir/seckey.txt keydir/pubkey.txt keydir/tls-privkey.pem keydir/tls-pubkey.pem: mandos-keygen install --directory keydir ./mandos-keygen --dir keydir --force @@ -321,7 +321,7 @@ confdir/mandos.conf: mandos.conf install --directory confdir install --mode=u=rw,go=r $^ $@ -confdir/clients.conf: clients.conf keydir/seckey.txt +confdir/clients.conf: clients.conf keydir/seckey.txt keydir/tls-pubkey.pem install --directory confdir install --mode=u=rw $< $@ # Add a client password @@ -423,8 +423,6 @@ plugin-helpers/mandos-client-iprouteadddel install initramfs-tools-hook \ $(INITRAMFSTOOLS)/hooks/mandos - install --mode=u=rw,go=r initramfs-tools-hook-conf \ - $(INITRAMFSTOOLS)/conf-hooks.d/mandos install --mode=u=rw,go=r initramfs-tools-conf \ $(INITRAMFSTOOLS)/conf.d/mandos-conf install initramfs-tools-script \ @@ -510,7 +508,8 @@ -rmdir $(CONFDIR) purge-client: uninstall-client - -shred --remove $(KEYDIR)/seckey.txt + -shred --remove $(KEYDIR)/seckey.txt $(KEYDIR)/tls-privkey.pem -rm --force $(CONFDIR)/plugin-runner.conf \ - $(KEYDIR)/pubkey.txt $(KEYDIR)/seckey.txt + $(KEYDIR)/pubkey.txt $(KEYDIR)/seckey.txt \ + $(KEYDIR)/tls-pubkey.txt $(KEYDIR)/tls-privkey.txt -rmdir $(KEYDIR) $(CONFDIR)/plugins.d $(CONFDIR) === modified file 'NEWS' --- NEWS 2018-02-22 18:50:12 +0000 +++ NEWS 2019-02-11 06:31:42 +0000 @@ -1,6 +1,56 @@ This NEWS file records noteworthy changes, very tersely. See the manual for detailed information. +Version 1.8.3 (2019-02-11) +* No user-visible changes. + +Version 1.8.2 (2019-02-10) +* Client +** In mandos-keygen, ignore failures to remove files in some cases. + +Version 1.8.1 (2019-02-10) +* Client +** Only generate TLS keys using GnuTLS' certtool, of sufficient + version. Key generation of TLS keys will not happen until a + version of GnuTLS is installed with support for raw public keys. +** Remove any bad keys created by 1.8.0 and openssl. +* Server +** On installation, edit clients.conf and remove the same bad key ID + which was erroneously reported by all 1.8.0 clients. Also do not + trust this key ID in the server. + +Version 1.8.0 (2019-02-10) +* Client +** Use new TLS keys for server communication and identification. + With GnuTLS 3.6 or later, OpenPGP keys are no longer supported. + The client can now use the new "raw public keys" (RFC 7250) API + instead, using GnuTLS 3.6.6. Please note: This *requires* new key + IDs to be added to server's client.conf file. +** New --tls-privkey and --tls-pubkey options to load TLS key files. + If GnuTLS is too old, these options do nothing. +* Server +** Supports either old or new GnuTLS. + The server now supports using GnuTLS 3.6.6 and clients connecting + with "raw public keys" as identification. The server will read + both fingerprints and key IDs from clients.conf file, and will use + either one or the other, depending on what is supported by GnuTLS + on the system. Please note: both are *not* supported at once; if + one type is supported by GnuTLS, all values of the other type from + clients.conf are ignored. + +Version 1.7.20 (2018-08-19) +* Client +** Fix: Adapt to the Debian cryptsetup package 2.0.3 or later. + Important: in that version or later, the plugins "askpass-fifo", + "password-prompt", and "plymouth" will no longer be run, since they + would conflict with what cryptsetup is doing. Other plugins, such + as mandos-client and any user-supplied plugins, will still run. +** Better error message if failing to decrypt secret data +** Check for (and report) any key import failure from GPGME +** Better error message if self-signature verification fails +** Set system clock if not set; required by GnuPG for key import +** When debugging plugin-runner, it will now show starting plugins + Version 1.7.19 (2018-02-22) * Client ** Do not print "unlink(...): No such file or directory". === modified file 'TODO' --- TODO 2017-02-22 21:45:35 +0000 +++ TODO 2019-02-13 08:45:09 +0000 @@ -14,6 +14,7 @@ ** TODO [#C] Make start_mandos_communication() take "struct server". ** TODO [#C] --interfaces=regex,eth*,noregex (bridge-utils-interfaces(5)) ** TODO [#A] Detect partial writes to stdout and exit with EX_TEMPFAIL +** TODO [#B] Use reallocarray() with GNU LibC 2.29 or later. * splashy ** TODO [#B] use scandir(3) instead of readdir(3) @@ -33,6 +34,7 @@ * plymouth ** TODO [#A] Detect partial writes to stdout and exit with EX_TEMPFAIL +** TODO [#B] Use reallocarray() with GNU LibC 2.29 or later. * TODO [#B] passdev @@ -119,16 +121,5 @@ * [[http://www.undeadly.org/cgi?action=article&sid=20110530221728][OpenBSD]] -* TODO Use raw public keys (RFC 7250) for TLS communications :2: -** Support for this is planned for GnuTLS version 3.6 - https://gitlab.com/gnutls/gnutls/issues/26 -** Rationale -*** The client key is used both for communication and encryption - Using raw keys in GnuTLS instead uses separate keys for - communication and password decryption. -*** GnuTLS 3.5.9 has deprecated the OpenPGP functions - The functions are still available, but deprecated: - https://gitlab.com/gnutls/gnutls/issues/102 - #+STARTUP: showall === modified file 'clients.conf' --- clients.conf 2012-06-23 00:58:49 +0000 +++ clients.conf 2019-02-09 23:34:15 +0000 @@ -38,6 +38,9 @@ ;# Example client ;[foo] ; +;# TLS public key ID +;key_id = f33fcbed11ed5e03073f6a55b86ffe92af0e24c045fb6e3b40547b3dc0c030ed +; ;# OpenPGP key fingerprint ;fingerprint = 7788 2722 5BA7 DE53 9C5A 7CFA 59CF F7CD BD9A 5920 ; @@ -68,11 +71,14 @@ ;#### ;# Another example client, named "bar". ;[bar] +;# The key ID is not space or case sensitive +;key_id = F33FCBED11ED5E03073F6A55B86FFE92 AF0E24C045FB6E3B40547B3DC0C030ED +; ;# The fingerprint is not space or case sensitive ;fingerprint = 3e393aeaefb84c7e89e2f547b3a107558fca3a27 ; ;# If "secret" is not specified, a file can be read for the data. -;secfile = /etc/mandos/bar-secret.bin +;secfile = /etc/keys/mandos/bar-secret.bin ; ;# An IP address for host is also fine, if the checker accepts it. ;host = 192.0.2.3 === modified file 'common.ent' --- common.ent 2018-02-22 18:50:12 +0000 +++ common.ent 2019-02-11 06:31:42 +0000 @@ -1,3 +1,3 @@ - + === modified file 'debian/changelog' --- debian/changelog 2018-02-22 18:50:12 +0000 +++ debian/changelog 2019-02-11 11:52:07 +0000 @@ -1,3 +1,104 @@ +mandos (1.8.3-2) unstable; urgency=medium + + * debian/rules (override_dh_shlibdeps-arch): New; conditionally edit + debian/control before running dh_shlibdeps. + + -- Teddy Hogeborn Mon, 11 Feb 2019 12:49:57 +0100 + +mandos (1.8.3-1) unstable; urgency=medium + + * New upstream release. + * debian/watch: Make the ".orig" file name suffix non-optional; + otherwise uscan thinks that ".orig" is part of the version number. + * debian/control (Build-Depends): Changed GnuTLS dependencies; move + 3.6.6 alternative to first in list, and remove dependencies on the + virtual package "gnutls-dev", since we need the version restrictions. + (Package: mandos/Depends): Remove dependency on libgnutls28-dev + package. + (Package: mandos/Suggests): New; set to "libc6-dev, c-compiler". (Used + to find value of "SO_BINDTODEVICE"). + (Package: mandos-client/Depends): Don't depend on openssl anymore; + instead depend on either a gnutls-bin (>= 3.6.6) (in which case TLS + key generation will work), or on libgnutls30 (<< 3.6.0) (in which case + TLS key generation will not be needed). + + -- Teddy Hogeborn Mon, 11 Feb 2019 07:30:32 +0100 + +mandos (1.8.2-1) unstable; urgency=medium + + * New upstream release. + * debian/mandos-client.postinst (create_keys): Ignore failure to remove + bad keys. + + -- Teddy Hogeborn Sun, 10 Feb 2019 11:44:56 +0100 + +mandos (1.8.1-1) unstable; urgency=high + + * New upstream release. + * debian/mandos-client.postinst (create_keys): Remove any bad keys + created by 1.8.0-1. Only create TLS keys if certtool succeeds. + * debian/mandos.postinst (configure): Remove any bad keys from + clients.conf, and inform the user if any were found. + * debian/mandos.templates (mandos/removed_bad_key_ids): New message. + + -- Teddy Hogeborn Sun, 10 Feb 2019 10:00:21 +0100 + +mandos (1.8.0-1) unstable; urgency=medium + + * New upstream release. + * Fix "(tries to) use GnuTLS OpenPGP support" by using raw public keys + when available (Closes: #879538) + * Fix "mandos : Depends: libgnutls30 (< 3.6.0) but 3.6.5-2 is to be + installed" by now also allowing GnuTLS >= 3.6.6 (Closes: #916673) + * debian/control (Standards-Version): Update to "4.3.0". + (Package: mandos-client/Depends): Change from "cryptsetup" to + "cryptsetup (<< 2:2.0.3-1) | cryptsetup-initramfs". Add "debconf (>= + 1.5.5) | debconf-2.0". + (Source: mandos/Build-Depends): Also allow libgnutls30 (>= 3.6.6). + (Package: mandos/Depends): - '' - and add debconf (>= 1.5.5) | + debconf-2.0". + (Package: mandos/Description): Alter description to match new design. + (Package: mandos-client/Description): - '' - + (Package: mandos-client/Depends): Move "gnutls-bin | openssl" to here + from "Recommends". + * debian/mandos-client.README.Debian: Add --tls-privkey and --tls-pubkey + options to test command. + * debian/mandos-client.postinst (create_key): Renamed to "create_keys" + - all callers changed - and also create TLS key files. Show notice if + new TLS key files were created. + * debian/mandos-client.postrm (purge): Also remove TLS key files. + * debian/mandos-client.lintian-overrides: Override warnings. + * debian/mandos-client.templates: New. + * debian/mandos.lintian-overrides: Override warnings. + * debian/mandos.postinst (configure): If GnuTLS 3.6.6 or later is + detected, show an important notice (once) about the new key_id option + required in clients.conf. + * debian/mandos.templates: New. + * debian/copyright: Update copyright year to 2019. + + -- Teddy Hogeborn Sun, 10 Feb 2019 05:52:49 +0100 + +mandos (1.7.20-1) unstable; urgency=medium + + * New upstream release. + * Fix "[tethys] mandos-client: Mandos client fails while booting but + works from chroot into unpacked initramfs" by setting system clock if + necessary (Closes: #894495) + * Fix "initramfs boot script assumes internal cryptsetup implementation + details and is now broken" by only using documented + interfaces (Closes: #904899) + * debian/mandos-client.dirs: Add + "usr/share/initramfs-tools/scripts/local-premount" and + "usr/share/initramfs-tools/conf.d", and remove + "usr/share/initramfs-tools/conf-hooks.d". + * debian/control (mandos-client/Depends): Add "(>= 0.99)" to dependency + on "initramfs-tools". + * debian/control (Source: mandos/Rules-Requires-Root): New; set to + "binary-targets". + (Standards-Version): Update to "4.2.0". + + -- Teddy Hogeborn Sun, 19 Aug 2018 22:14:04 +0200 + mandos (1.7.19-1) unstable; urgency=medium * New upstream release. === modified file 'debian/control' --- debian/control 2018-02-10 18:47:22 +0000 +++ debian/control 2019-02-11 06:14:29 +0000 @@ -6,24 +6,27 @@ Björn Påhlsson Build-Depends: debhelper (>= 10), docbook-xml, docbook-xsl, libavahi-core-dev, libgpgme-dev | libgpgme11-dev, - libgnutls28-dev (>= 3.3.0) | gnutls-dev (>= 3.3.0), - libgnutls28-dev (<< 3.6.0) | libgnutls30 (<< 3.6.0), + libgnutls28-dev (>= 3.3.0), + libgnutls28-dev (>= 3.6.6) | libgnutls28-dev (<< 3.6.0), xsltproc, pkg-config, libnl-route-3-dev Build-Depends-Indep: systemd, python (>= 2.7), python (<< 3), python-dbus, python-gi -Standards-Version: 4.1.3 +Standards-Version: 4.3.0 Vcs-Bzr: https://ftp.recompile.se/pub/mandos/trunk Vcs-Browser: https://bzr.recompile.se/loggerhead/mandos/trunk/files Homepage: https://www.recompile.se/mandos +Rules-Requires-Root: binary-targets Package: mandos Architecture: all Depends: ${misc:Depends}, python (>= 2.7), python (<< 3), - libgnutls28-dev (>= 3.3.0) | libgnutls30 (>= 3.3.0), - libgnutls28-dev (<< 3.6.0) | libgnutls30 (<< 3.6.0), + libgnutls30 (>= 3.3.0), + libgnutls30 (>= 3.6.6) | libgnutls30 (<< 3.6.0), python-dbus, python-gi, avahi-daemon, adduser, python-urwid, - gnupg2 | gnupg, systemd-sysv | lsb-base (>= 3.0-6) + gnupg2 | gnupg, systemd-sysv | lsb-base (>= 3.0-6), + debconf (>= 1.5.5) | debconf-2.0 Recommends: ssh-client | fping +Suggests: libc6-dev | libc-dev, c-compiler Description: server giving encrypted passwords to Mandos clients This is the server part of the Mandos system, which allows computers to have encrypted root file systems and at the @@ -32,18 +35,21 @@ The computers run a small client program in the initial RAM disk environment which will communicate with a server over a network. All network communication is encrypted using TLS. - The clients are identified by the server using an OpenPGP + The clients are identified by the server using a TLS public key; each client has one unique to it. The server sends the clients an encrypted password. The encrypted password is - decrypted by the clients using the same OpenPGP key, and the + decrypted by the clients using an OpenPGP key, and the password is then used to unlock the root file system, whereupon the computers can continue booting normally. Package: mandos-client Architecture: linux-any -Depends: ${shlibs:Depends}, ${misc:Depends}, adduser, cryptsetup, - initramfs-tools, dpkg-dev (>=1.16.0) -Recommends: ssh, gnutls-bin | openssl +Depends: ${shlibs:Depends}, ${misc:Depends}, adduser, + cryptsetup (<< 2:2.0.3-1) | cryptsetup-initramfs, + initramfs-tools (>= 0.99), dpkg-dev (>=1.16.0), + gnutls-bin (>= 3.6.6) | libgnutls30 (<< 3.6.0), + debconf (>= 1.5.5) | debconf-2.0 +Recommends: ssh Breaks: dropbear (<= 0.53.1-1) Enhances: cryptsetup Description: do unattended reboots with an encrypted root file system @@ -54,9 +60,9 @@ The computers run a small client program in the initial RAM disk environment which will communicate with a server over a network. All network communication is encrypted using TLS. - The clients are identified by the server using an OpenPGP + The clients are identified by the server using a TLS public key; each client has one unique to it. The server sends the clients an encrypted password. The encrypted password is - decrypted by the clients using the same OpenPGP key, and the + decrypted by the clients using an OpenPGP key, and the password is then used to unlock the root file system, whereupon the computers can continue booting normally. === modified file 'debian/copyright' --- debian/copyright 2018-02-08 10:23:55 +0000 +++ debian/copyright 2019-02-10 04:20:26 +0000 @@ -4,8 +4,8 @@ Source: Files: * -Copyright: Copyright © 2008-2018 Teddy Hogeborn - Copyright © 2008-2018 Björn Påhlsson +Copyright: Copyright © 2008-2019 Teddy Hogeborn + Copyright © 2008-2019 Björn Påhlsson License: GPL-3+ This file is part of Mandos. . === modified file 'debian/mandos-client.README.Debian' --- debian/mandos-client.README.Debian 2016-06-21 19:47:08 +0000 +++ debian/mandos-client.README.Debian 2019-02-09 23:23:26 +0000 @@ -25,7 +25,9 @@ /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH \ )/mandos/plugins.d/mandos-client \ --pubkey=/etc/keys/mandos/pubkey.txt \ - --seckey=/etc/keys/mandos/seckey.txt; echo + --seckey=/etc/keys/mandos/seckey.txt \ + --tls-privkey=/etc/keys/mandos/tls-privkey.pem \ + --tls-pubkey=/etc/keys/mandos/tls-pubkey.pem; echo This command should retrieve the password from the server, decrypt it, and output it to standard output. There it can be verified to @@ -106,4 +108,4 @@ policy or other reasons, simply replace the existing dhparams.pem file and update the initital RAM disk image. - -- Teddy Hogeborn , Tue, 21 Jun 2016 21:43:49 +0200 + -- Teddy Hogeborn , Sat, 9 Feb 2019 15:08:04 +0100 === modified file 'debian/mandos-client.dirs' --- debian/mandos-client.dirs 2018-08-19 14:06:55 +0000 +++ debian/mandos-client.dirs 2018-08-19 14:32:00 +0000 @@ -1,7 +1,6 @@ usr/share/man/man8 usr/sbin usr/share/initramfs-tools/hooks -usr/share/initramfs-tools/conf-hooks.d usr/share/initramfs-tools/conf.d usr/share/initramfs-tools/scripts/init-premount usr/share/initramfs-tools/scripts/local-premount === modified file 'debian/mandos-client.lintian-overrides' --- debian/mandos-client.lintian-overrides 2016-03-19 04:21:00 +0000 +++ debian/mandos-client.lintian-overrides 2019-02-10 03:50:20 +0000 @@ -30,3 +30,14 @@ mandos-client binary: non-standard-dir-perm etc/mandos/plugins.d/ 0700 != 0755 # Likewise for plugin-helpers directory mandos-client binary: non-standard-dir-perm etc/mandos/plugin-helpers/ 0700 != 0755 + +# The debconf templates is only used for displaying information +# detected in the postinst, not for saving answers to questions, so we +# don't need a .config file. +mandos-client binary: no-debconf-config + +# The notice displayed from the postinst script really is critical +mandos-client binary: postinst-uses-db-input + +# It is a really long line +mandos-client binary: manpage-has-errors-from-man usr/share/man/man8/plugin-runner.8mandos.gz *: warning *: can't break line === modified file 'debian/mandos-client.postinst' --- debian/mandos-client.postinst 2016-10-09 22:35:41 +0000 +++ debian/mandos-client.postinst 2019-02-10 10:39:26 +0000 @@ -15,6 +15,8 @@ # If prerm fails during replacement due to conflict: # abort-remove in-favour +. /usr/share/debconf/confmodule + set -e # Update the initial RAM file system image @@ -50,14 +52,79 @@ fi } -# Create client key pair -create_key(){ - if [ -r /etc/keys/mandos/pubkey.txt \ - -a -r /etc/keys/mandos/seckey.txt ]; then - return 0 - fi - mandos-keygen - gpg-connect-agent KILLAGENT /bye || : +# Create client key pairs +create_keys(){ + # If the OpenPGP key files do not exist, generate all keys using + # mandos-keygen + if ! [ -r /etc/keys/mandos/pubkey.txt \ + -a -r /etc/keys/mandos/seckey.txt ]; then + mandos-keygen + gpg-connect-agent KILLAGENT /bye || : + return 0 + fi + + # Remove any bad TLS keys by 1.8.0-1 + if dpkg --compare-versions "$2" eq "1.8.0-1" \ + || dpkg --compare-versions "$2" eq "1.8.0-1~bpo9+1"; then + # Is the key bad? + if ! certtool --password='' \ + --load-privkey=/etc/keys/mandos/tls-privkey.pem \ + --outfile=/dev/null --pubkey-info --no-text \ + 2>/dev/null; then + shred --remove -- /etc/keys/mandos/tls-privkey.pem \ + 2>/dev/null || : + rm --force -- /etc/keys/mandos/tls-pubkey.pem + fi + fi + + # If the TLS keys already exists, do nothing + if [ -r /etc/keys/mandos/tls-privkey.pem \ + -a -r /etc/keys/mandos/tls-pubkey.pem ]; then + return 0 + fi + + # Try to create the TLS keys + + TLS_PRIVKEYTMP="`mktemp -t mandos-client-privkey.XXXXXXXXXX`" + + if certtool --generate-privkey --password='' \ + --outfile "$TLS_PRIVKEYTMP" --sec-param ultra \ + --key-type=ed25519 --pkcs8 --no-text 2>/dev/null; then + + local umask=$(umask) + umask 077 + cp --archive "$TLS_PRIVKEYTMP" /etc/keys/mandos/tls-privkey.pem + shred --remove -- "$TLS_PRIVKEYTMP" 2>/dev/null || : + + # First try certtool from GnuTLS + if ! certtool --password='' \ + --load-privkey=/etc/keys/mandos/tls-privkey.pem \ + --outfile=/etc/keys/mandos/tls-pubkey.pem --pubkey-info \ + --no-text 2>/dev/null; then + # Otherwise try OpenSSL + if ! openssl pkey -in /etc/keys/mandos/tls-privkey.pem \ + -out /etc/keys/mandos/tls-pubkey.pem -pubout; then + rm --force /etc/keys/mandos/tls-pubkey.pem + # None of the commands succeded; give up + umask $umask + return 1 + fi + fi + umask $umask + + key_id=$(mandos-keygen --passfile=/dev/null \ + | grep --regexp="^key_id[ =]") + + db_version 2.0 + db_fset mandos-client/key_id seen false + db_reset mandos-client/key_id + db_subst mandos-client/key_id key_id $key_id + db_input critical mandos-client/key_id || true + db_go + db_stop + else + shred --remove -- "$TLS_PRIVKEYTMP" 2>/dev/null || : + fi } create_dh_params(){ @@ -88,7 +155,7 @@ case "$1" in configure) add_mandos_user "$@" - create_key "$@" + create_keys "$@" create_dh_params "$@" || : update_initramfs "$@" if dpkg --compare-versions "$2" lt-nl "1.7.10-1"; then === modified file 'debian/mandos-client.postrm' --- debian/mandos-client.postrm 2015-07-27 09:23:56 +0000 +++ debian/mandos-client.postrm 2019-02-09 23:23:26 +0000 @@ -44,6 +44,8 @@ rm --force /etc/mandos/plugin-runner.conf \ /etc/keys/mandos/pubkey.txt \ /etc/keys/mandos/seckey.txt \ + /etc/keys/mandos/tls-privkey.pem \ + /etc/keys/mandos/tls-pubkey.pem \ /etc/keys/mandos/dhparams.pem 2>/dev/null update_initramfs ;; === added file 'debian/mandos-client.templates' --- debian/mandos-client.templates 1970-01-01 00:00:00 +0000 +++ debian/mandos-client.templates 2019-02-10 03:50:20 +0000 @@ -0,0 +1,10 @@ +Template: mandos-client/key_id +Type: note +Description: New client option "${key_id}" is REQUIRED on server + A new "key_id" client option is REQUIRED in the server's clients.conf file, otherwise this computer most likely will not reboot unattended. This option: + . + ${key_id} + . + must be added (all on one line!) on the Mandos server host, in the file /etc/mandos/clients.conf, right before the "fingerprint" option for this Mandos client. You must edit that file on that server and add this option. + . + With GnuTLS 3.6.6, Mandos has been forced to stop using OpenPGP keys as TLS session keys. A new TLS key pair has been generated and will be used as identification, but the key ID of the public key needs to be added to the server, since this will now be used to identify the client to the server. === modified file 'debian/mandos.lintian-overrides' --- debian/mandos.lintian-overrides 2018-02-10 18:58:32 +0000 +++ debian/mandos.lintian-overrides 2019-02-10 03:50:20 +0000 @@ -3,3 +3,11 @@ # mandos binary: non-standard-file-perm etc/mandos/clients.conf 0600 != 0644 mandos: init.d-script-needs-depends-on-lsb-base etc/init.d/mandos (line 46) + +# The debconf templates is only used for displaying information +# detected in the postinst, not for saving answers to questions, so we +# don't need a .config file. +mandos binary: no-debconf-config + +# The notice displayed from the postinst script really is critical +mandos binary: postinst-uses-db-input === modified file 'debian/mandos.postinst' --- debian/mandos.postinst 2016-03-19 03:48:56 +0000 +++ debian/mandos.postinst 2019-02-10 08:41:14 +0000 @@ -15,6 +15,8 @@ # If prerm fails during replacement due to conflict: # abort-remove in-favour +. /usr/share/debconf/confmodule + set -e case "$1" in @@ -53,6 +55,33 @@ chown _mandos:_mandos /var/lib/mandos chmod u=rwx,go= /var/lib/mandos fi + + if dpkg --compare-versions "$2" eq "1.8.0-1" \ + || dpkg --compare-versions "$2" eq "1.8.0-1~bpo9+1"; then + if grep --quiet --regexp='^[[:space:]]*key_id[[:space:]]*=[[:space:]]*[Ee]3[Bb]0[Cc]44298[Ff][Cc]1[Cc]149[Aa][Ff][Bb][Ff]4[Cc]8996[Ff][Bb]92427[Aa][Ee]41[Ee]4649[Bb]934[Cc][Aa]495991[Bb]7852[Bb]855[[:space:]]*$' /etc/mandos/clients.conf; then + sed --in-place \ + --expression='/^[[:space:]]*key_id[[:space:]]*=[[:space:]]*[Ee]3[Bb]0[Cc]44298[Ff][Cc]1[Cc]149[Aa][Ff][Bb][Ff]4[Cc]8996[Ff][Bb]92427[Aa][Ee]41[Ee]4649[Bb]934[Cc][Aa]495991[Bb]7852[Bb]855[[:space:]]*$/d' \ + /etc/mandos/clients.conf + invoke-rc.d mandos restart + db_version 2.0 + db_fset mandos/removed_bad_key_ids seen false + db_reset mandos/removed_bad_key_ids + db_input critical mandos/removed_bad_key_ids || true + db_go + db_stop + fi + fi + + gnutls_version=$(dpkg-query --showformat='${Version}' \ + --show libgnutls30 \ + 2>/dev/null || :) + if [ -n "$gnutls_version" ] \ + && dpkg --compare-versions $gnutls_version ge 3.6.6; then + db_version 2.0 + db_input critical mandos/key_id || true + db_go + db_stop + fi ;; abort-upgrade|abort-deconfigure|abort-remove) === added file 'debian/mandos.templates' --- debian/mandos.templates 1970-01-01 00:00:00 +0000 +++ debian/mandos.templates 2019-02-10 08:41:14 +0000 @@ -0,0 +1,19 @@ +Template: mandos/key_id +Type: note +Description: New client option "key_id" is REQUIRED on server + A new "key_id" client option is REQUIRED in the clients.conf file, otherwise the client most likely will not reboot unattended. This option: + . + key_id = + . + must be added in the file /etc/mandos/clients.conf, right before the "fingerprint" option, for each Mandos client. You must edit that file and add this option for all clients. To see the correct key ID for each client, run this command (on each client): + . + mandos-keygen -F/dev/null|grep ^key_id + . + Note: the client must all also be using GnuTLS 3.6.6 or later; the server cannot serve passwords for both old and new clients! + . + Rationale: With GnuTLS 3.6.6, Mandos has been forced to stop using OpenPGP keys as TLS session keys. A new TLS key pair will be generated on each client and will be used as identification, but the key ID of the public key needs to be added to this server, since this will now be used to identify the client to the server. + +Template: mandos/removed_bad_key_ids +Type: note +Description: Bad key IDs have been removed from clients.conf + Bad key IDs, which were reported by a bug in Mandos client 1.8.0, have been removed from /etc/mandos/clients.conf === modified file 'debian/rules' --- debian/rules 2018-02-08 12:25:31 +0000 +++ debian/rules 2019-02-13 08:45:09 +0000 @@ -43,3 +43,19 @@ dh_fixperms --exclude etc/mandos/clients.conf override_dh_auto_test-arch: ; + +#bpo## dpkg-shlibdeps sees the "libgnutls28-dev (>= 3.6.6) | +#bpo## libgnutls28-dev (<< 3.6.0)," in the build-dependencies not as two +#bpo## alternatives, but as an absolute dependency on libgnutls30 >= 3.6.6. +#bpo## So we have to do this ugly hack to hide this build dependency if we +#bpo## compiled with libgnutls30 << 3.6.0. +#bpo#override_dh_shlibdeps-arch: +#bpo# -gnutls_version=$$(dpkg-query --showformat='$${Version}' \ +#bpo# --show libgnutls30); \ +#bpo# dpkg --compare-versions $$gnutls_version lt 3.6.0 \ +#bpo# && { cp --archive debian/control debian/control.orig; sed --expression='s/libgnutls28-dev (>= 3\.6\.6) |//' debian/control; } +#bpo# dh_shlibdeps +#bpo# -gnutls_version=$$(dpkg-query --showformat='$${Version}' \ +#bpo# --show libgnutls30); \ +#bpo# dpkg --compare-versions $$gnutls_version lt 3.6.0 \ +#bpo# && mv debian/control.orig debian/control === modified file 'debian/watch' --- debian/watch 2018-02-08 10:02:51 +0000 +++ debian/watch 2019-02-11 05:15:24 +0000 @@ -1,3 +1,3 @@ version=4 opts=pgpmode=auto \ - https://ftp.recompile.se/pub/@PACKAGE@/@PACKAGE@@ANY_VERSION@(?:\.orig)?@ARCHIVE_EXT@ + https://ftp.recompile.se/pub/@PACKAGE@/@PACKAGE@@ANY_VERSION@\.orig@ARCHIVE_EXT@ === removed file 'initramfs-tools-hook-conf' --- initramfs-tools-hook-conf 2018-08-19 14:06:55 +0000 +++ initramfs-tools-hook-conf 1970-01-01 00:00:00 +0000 @@ -1,11 +0,0 @@ -# -*- shell-script -*- - -# if mkinitramfs is started by mkinitramfs-kpkg, mkinitramfs-kpkg has -# already touched the initrd file with umask 022 before we had a -# chance to affect it. We cannot allow a readable initrd file, -# therefore we must fix this now. -if [ -e "${outfile}" ] \ - && [ `stat --format=%s "${outfile}"` -eq 0 ]; then - rm "${outfile}" - (umask 027; touch "${outfile}") -fi === modified file 'initramfs-tools-script-stop' (properties changed: -x to +x) === modified file 'intro.xml' --- intro.xml 2018-02-08 10:23:55 +0000 +++ intro.xml 2019-02-10 04:20:26 +0000 @@ -1,7 +1,7 @@ + %common; ]> @@ -38,6 +38,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson @@ -67,10 +68,10 @@ The computers run a small client program in the initial RAM disk environment which will communicate with a server over a network. All network communication is encrypted using TLS. The clients - are identified by the server using an OpenPGP key; each client + are identified by the server using a TLS public key; each client has one unique to it. The server sends the clients an encrypted password. The encrypted password is decrypted by the clients - using the same OpenPGP key, and the password is then used to + using a separate OpenPGP key, and the password is then used to unlock the root file system, whereupon the computers can continue booting normally. @@ -200,8 +201,8 @@ No. The server only gives out the passwords to clients which have in the TLS handshake proven that - they do indeed hold the OpenPGP private key corresponding to - that client. + they do indeed hold the private key corresponding to that + client. === modified file 'mandos' --- mandos 2018-08-15 09:18:22 +0000 +++ mandos 2019-02-11 06:31:42 +0000 @@ -11,8 +11,8 @@ # "AvahiService" class, and some lines in "main". # # Everything else is -# Copyright © 2008-2018 Teddy Hogeborn -# Copyright © 2008-2018 Björn Påhlsson +# Copyright © 2008-2019 Teddy Hogeborn +# Copyright © 2008-2019 Björn Påhlsson # # This file is part of Mandos. # @@ -115,7 +115,7 @@ if sys.version_info.major == 2: str = unicode -version = "1.7.19" +version = "1.8.3" stored_state_file = "clients.pickle" logger = logging.getLogger() @@ -514,6 +514,7 @@ _library = ctypes.cdll.LoadLibrary(library) del library _need_version = b"3.3.0" + _tls_rawpk_version = b"3.6.6" def __init__(self): # Need to use "self" here, since this method is called before @@ -530,10 +531,16 @@ E_INTERRUPTED = -52 E_AGAIN = -28 CRT_OPENPGP = 2 + CRT_RAWPK = 3 CLIENT = 2 SHUT_RDWR = 0 CRD_CERTIFICATE = 1 E_NO_CERTIFICATE_FOUND = -49 + X509_FMT_DER = 0 + NO_TICKETS = 1<<10 + ENABLE_RAWPK = 1<<18 + CTYPE_PEERS = 3 + KEYID_USE_SHA256 = 1 # gnutls/x509.h OPENPGP_FMT_RAW = 0 # gnutls/openpgp.h # Types @@ -593,7 +600,13 @@ class ClientSession(object): def __init__(self, socket, credentials=None): self._c_object = gnutls.session_t() - gnutls.init(ctypes.byref(self._c_object), gnutls.CLIENT) + gnutls_flags = gnutls.CLIENT + if gnutls.check_version("3.5.6"): + gnutls_flags |= gnutls.NO_TICKETS + if gnutls.has_rawpk: + gnutls_flags |= gnutls.ENABLE_RAWPK + gnutls.init(ctypes.byref(self._c_object), gnutls_flags) + del gnutls_flags gnutls.set_default_priority(self._c_object) gnutls.transport_set_ptr(self._c_object, socket.fileno()) gnutls.handshake_set_private_extensions(self._c_object, @@ -731,34 +744,69 @@ check_version.argtypes = [ctypes.c_char_p] check_version.restype = ctypes.c_char_p - # All the function declarations below are from gnutls/openpgp.h - - openpgp_crt_init = _library.gnutls_openpgp_crt_init - openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)] - openpgp_crt_init.restype = _error_code - - openpgp_crt_import = _library.gnutls_openpgp_crt_import - openpgp_crt_import.argtypes = [openpgp_crt_t, - ctypes.POINTER(datum_t), - openpgp_crt_fmt_t] - openpgp_crt_import.restype = _error_code - - openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self - openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint, - ctypes.POINTER(ctypes.c_uint)] - openpgp_crt_verify_self.restype = _error_code - - openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit - openpgp_crt_deinit.argtypes = [openpgp_crt_t] - openpgp_crt_deinit.restype = None - - openpgp_crt_get_fingerprint = ( - _library.gnutls_openpgp_crt_get_fingerprint) - openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t, - ctypes.c_void_p, - ctypes.POINTER( - ctypes.c_size_t)] - openpgp_crt_get_fingerprint.restype = _error_code + has_rawpk = bool(check_version(_tls_rawpk_version)) + + if has_rawpk: + # Types + class pubkey_st(ctypes.Structure): + _fields = [] + pubkey_t = ctypes.POINTER(pubkey_st) + + x509_crt_fmt_t = ctypes.c_int + + # All the function declarations below are from gnutls/abstract.h + pubkey_init = _library.gnutls_pubkey_init + pubkey_init.argtypes = [ctypes.POINTER(pubkey_t)] + pubkey_init.restype = _error_code + + pubkey_import = _library.gnutls_pubkey_import + pubkey_import.argtypes = [pubkey_t, ctypes.POINTER(datum_t), + x509_crt_fmt_t] + pubkey_import.restype = _error_code + + pubkey_get_key_id = _library.gnutls_pubkey_get_key_id + pubkey_get_key_id.argtypes = [pubkey_t, ctypes.c_int, + ctypes.POINTER(ctypes.c_ubyte), + ctypes.POINTER(ctypes.c_size_t)] + pubkey_get_key_id.restype = _error_code + + pubkey_deinit = _library.gnutls_pubkey_deinit + pubkey_deinit.argtypes = [pubkey_t] + pubkey_deinit.restype = None + else: + # All the function declarations below are from gnutls/openpgp.h + + openpgp_crt_init = _library.gnutls_openpgp_crt_init + openpgp_crt_init.argtypes = [ctypes.POINTER(openpgp_crt_t)] + openpgp_crt_init.restype = _error_code + + openpgp_crt_import = _library.gnutls_openpgp_crt_import + openpgp_crt_import.argtypes = [openpgp_crt_t, + ctypes.POINTER(datum_t), + openpgp_crt_fmt_t] + openpgp_crt_import.restype = _error_code + + openpgp_crt_verify_self = _library.gnutls_openpgp_crt_verify_self + openpgp_crt_verify_self.argtypes = [openpgp_crt_t, ctypes.c_uint, + ctypes.POINTER(ctypes.c_uint)] + openpgp_crt_verify_self.restype = _error_code + + openpgp_crt_deinit = _library.gnutls_openpgp_crt_deinit + openpgp_crt_deinit.argtypes = [openpgp_crt_t] + openpgp_crt_deinit.restype = None + + openpgp_crt_get_fingerprint = ( + _library.gnutls_openpgp_crt_get_fingerprint) + openpgp_crt_get_fingerprint.argtypes = [openpgp_crt_t, + ctypes.c_void_p, + ctypes.POINTER( + ctypes.c_size_t)] + openpgp_crt_get_fingerprint.restype = _error_code + + if check_version("3.6.4"): + certificate_type_get2 = _library.gnutls_certificate_type_get2 + certificate_type_get2.argtypes = [session_t, ctypes.c_int] + certificate_type_get2.restype = _error_code # Remove non-public functions del _error_code, _retry_on_error @@ -800,7 +848,9 @@ disable_initiator_tag: a GLib event source tag, or None enabled: bool() fingerprint: string (40 or 32 hexadecimal digits); used to - uniquely identify the client + uniquely identify an OpenPGP client + key_id: string (64 hexadecimal digits); used to uniquely identify + a client using raw public keys host: string; available for use by the checker command interval: datetime.timedelta(); How often to start a new checker last_approval_request: datetime.datetime(); (UTC) or None @@ -824,7 +874,7 @@ """ runtime_expansions = ("approval_delay", "approval_duration", - "created", "enabled", "expires", + "created", "enabled", "expires", "key_id", "fingerprint", "host", "interval", "last_approval_request", "last_checked_ok", "last_enabled", "name", "timeout") @@ -860,9 +910,11 @@ client["enabled"] = config.getboolean(client_name, "enabled") - # Uppercase and remove spaces from fingerprint for later - # comparison purposes with return value from the - # fingerprint() function + # Uppercase and remove spaces from key_id and fingerprint + # for later comparison purposes with return value from the + # key_id() and fingerprint() functions + client["key_id"] = (section.get("key_id", "").upper() + .replace(" ", "")) client["fingerprint"] = (section["fingerprint"].upper() .replace(" ", "")) if "secret" in section: @@ -912,6 +964,7 @@ self.expires = None logger.debug("Creating client %r", self.name) + logger.debug(" Key ID: %s", self.key_id) logger.debug(" Fingerprint: %s", self.fingerprint) self.created = settings.get("created", datetime.datetime.utcnow()) @@ -1999,6 +2052,13 @@ def Name_dbus_property(self): return dbus.String(self.name) + # KeyID - property + @dbus_annotations( + {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"}) + @dbus_service_property(_interface, signature="s", access="read") + def KeyID_dbus_property(self): + return dbus.String(self.key_id) + # Fingerprint - property @dbus_annotations( {"org.freedesktop.DBus.Property.EmitsChangedSignal": "const"}) @@ -2160,11 +2220,11 @@ class ProxyClient(object): - def __init__(self, child_pipe, fpr, address): + def __init__(self, child_pipe, key_id, fpr, address): self._pipe = child_pipe - self._pipe.send(('init', fpr, address)) + self._pipe.send(('init', key_id, fpr, address)) if not self._pipe.recv(): - raise KeyError(fpr) + raise KeyError(key_id or fpr) def __getattribute__(self, name): if name == '_pipe': @@ -2237,16 +2297,28 @@ approval_required = False try: - try: - fpr = self.fingerprint( - self.peer_certificate(session)) - except (TypeError, gnutls.Error) as error: - logger.warning("Bad certificate: %s", error) - return - logger.debug("Fingerprint: %s", fpr) - - try: - client = ProxyClient(child_pipe, fpr, + if gnutls.has_rawpk: + fpr = "" + try: + key_id = self.key_id( + self.peer_certificate(session)) + except (TypeError, gnutls.Error) as error: + logger.warning("Bad certificate: %s", error) + return + logger.debug("Key ID: %s", key_id) + + else: + key_id = "" + try: + fpr = self.fingerprint( + self.peer_certificate(session)) + except (TypeError, gnutls.Error) as error: + logger.warning("Bad certificate: %s", error) + return + logger.debug("Fingerprint: %s", fpr) + + try: + client = ProxyClient(child_pipe, key_id, fpr, self.client_address) except KeyError: return @@ -2329,10 +2401,20 @@ @staticmethod def peer_certificate(session): - "Return the peer's OpenPGP certificate as a bytestring" - # If not an OpenPGP certificate... - if (gnutls.certificate_type_get(session._c_object) - != gnutls.CRT_OPENPGP): + "Return the peer's certificate as a bytestring" + try: + cert_type = gnutls.certificate_type_get2(session._c_object, + gnutls.CTYPE_PEERS) + except AttributeError: + cert_type = gnutls.certificate_type_get(session._c_object) + if gnutls.has_rawpk: + valid_cert_types = frozenset((gnutls.CRT_RAWPK,)) + else: + valid_cert_types = frozenset((gnutls.CRT_OPENPGP,)) + # If not a valid certificate type... + if cert_type not in valid_cert_types: + logger.info("Cert type %r not in %r", cert_type, + valid_cert_types) # ...return invalid data return b"" list_size = ctypes.c_uint(1) @@ -2346,6 +2428,40 @@ return ctypes.string_at(cert.data, cert.size) @staticmethod + def key_id(certificate): + "Convert a certificate bytestring to a hexdigit key ID" + # New GnuTLS "datum" with the public key + datum = gnutls.datum_t( + ctypes.cast(ctypes.c_char_p(certificate), + ctypes.POINTER(ctypes.c_ubyte)), + ctypes.c_uint(len(certificate))) + # XXX all these need to be created in the gnutls "module" + # New empty GnuTLS certificate + pubkey = gnutls.pubkey_t() + gnutls.pubkey_init(ctypes.byref(pubkey)) + # Import the raw public key into the certificate + gnutls.pubkey_import(pubkey, + ctypes.byref(datum), + gnutls.X509_FMT_DER) + # New buffer for the key ID + buf = ctypes.create_string_buffer(32) + buf_len = ctypes.c_size_t(len(buf)) + # Get the key ID from the raw public key into the buffer + gnutls.pubkey_get_key_id(pubkey, + gnutls.KEYID_USE_SHA256, + ctypes.cast(ctypes.byref(buf), + ctypes.POINTER(ctypes.c_ubyte)), + ctypes.byref(buf_len)) + # Deinit the certificate + gnutls.pubkey_deinit(pubkey) + + # Convert the buffer to a Python bytestring + key_id = ctypes.string_at(buf, buf_len.value) + # Convert the bytestring to hexadecimal notation + hex_key_id = binascii.hexlify(key_id).upper() + return hex_key_id + + @staticmethod def fingerprint(openpgp): "Convert an OpenPGP bytestring to a hexdigit fingerprint" # New GnuTLS "datum" with the OpenPGP public key @@ -2579,19 +2695,25 @@ command = request[0] if command == 'init': - fpr = request[1].decode("ascii") - address = request[2] + key_id = request[1].decode("ascii") + fpr = request[2].decode("ascii") + address = request[3] for c in self.clients.values(): - if c.fingerprint == fpr: + if key_id == "E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855": + continue + if key_id and c.key_id == key_id: + client = c + break + if fpr and c.fingerprint == fpr: client = c break else: - logger.info("Client not found for fingerprint: %s, ad" - "dress: %s", fpr, address) + logger.info("Client not found for key ID: %s, address" + ": %s", key_id or fpr, address) if self.use_dbus: # Emit D-Bus signal - mandos_dbus_service.ClientNotFound(fpr, + mandos_dbus_service.ClientNotFound(key_id or fpr, address[0]) parent_pipe.send(False) return False @@ -2860,13 +2982,17 @@ sys.exit(os.EX_OK if fail_count == 0 else 1) # Default values for config file for server-global settings + if gnutls.has_rawpk: + priority = ("SECURE128:!CTYPE-X.509:+CTYPE-RAWPK:!RSA" + ":!VERS-ALL:+VERS-TLS1.3:%PROFILE_ULTRA") + else: + priority = ("SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA" + ":+SIGN-DSA-SHA256") server_defaults = {"interface": "", "address": "", "port": "", "debug": "False", - "priority": - "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA" - ":+SIGN-DSA-SHA256", + "priority": priority, "servicename": "Mandos", "use_dbus": "True", "use_ipv6": "True", @@ -2877,6 +3003,7 @@ "foreground": "False", "zeroconf": "True", } + del priority # Parse config file for server-global settings server_config = configparser.SafeConfigParser(server_defaults) @@ -3126,6 +3253,10 @@ for k in ("name", "host"): if isinstance(value[k], bytes): value[k] = value[k].decode("utf-8") + if not value.has_key("key_id"): + value["key_id"] = "" + elif not value.has_key("fingerprint"): + value["fingerprint"] = "" # old_client_settings # .keys() old_client_settings = { @@ -3268,7 +3399,7 @@ pass @dbus.service.signal(_interface, signature="ss") - def ClientNotFound(self, fingerprint, address): + def ClientNotFound(self, key_id, address): "D-Bus signal" pass === modified file 'mandos-clients.conf.xml' --- mandos-clients.conf.xml 2018-02-08 10:23:55 +0000 +++ mandos-clients.conf.xml 2019-02-10 04:20:26 +0000 @@ -3,7 +3,7 @@ "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ /etc/mandos/clients.conf"> - + %common; ]> @@ -43,6 +43,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson @@ -186,9 +187,9 @@ >-- %%(host)s. Note that mandos-keygen, when generating output to be inserted into this file, normally looks for an SSH - server on the Mandos client, and, if it find one, outputs + server on the Mandos client, and, if it finds one, outputs a option to check for the - client’s key fingerprint – this is more secure against + client’s SSH key fingerprint – this is more secure against spoofing. @@ -239,6 +240,22 @@ + + + + This option is optional. + + + This option sets the certificate key ID that identifies + the public key that clients authenticate themselves with + through TLS. The string needs to be in hexadecimal form, + but spaces or upper/lower case are not significant. + + + + + @@ -314,9 +331,9 @@ If present, this option must be set to a string of base64-encoded binary data. It will be decoded and sent - to the client matching the above - . This should, of course, be - OpenPGP encrypted data, decryptable only by the client. + to the client matching the above + or . This should, of course, + be OpenPGP encrypted data, decryptable only by the client. The program mandos-keygen8 can, using its @@ -417,6 +434,7 @@ created, enabled, expires, + key_id, fingerprint, host, interval, @@ -479,6 +497,7 @@ # Client "foo" [foo] +key_id = 788cd77115cd0bb7b2d5e0ae8496f6b48149d5e712c652076b1fd2d957ef7c1f fingerprint = 7788 2722 5BA7 DE53 9C5A 7CFA 59CF F7CD BD9A 5920 secret = hQIOA6QdEjBs2L/HEAf/TCyrDe5Xnm9esa+Pb/vWF9CUqfn4srzVgSu234 @@ -501,6 +520,7 @@ # Client "bar" [bar] +key_id = F90C7A81D72D1EA69A51031A91FF8885F36C8B46D155C8C58709A4C99AE9E361 fingerprint = 3e393aeaefb84c7e89e2f547b3a107558fca3a27 secfile = /etc/mandos/bar-secret timeout = PT15M === modified file 'mandos-ctl' --- mandos-ctl 2018-02-22 18:50:12 +0000 +++ mandos-ctl 2019-03-12 20:24:58 +0000 @@ -1,10 +1,10 @@ #!/usr/bin/python -# -*- mode: python; coding: utf-8 -*- +# -*- mode: python; coding: utf-8; after-save-hook: (lambda () (let ((command (if (and (boundp 'tramp-file-name-structure) (string-match (car tramp-file-name-structure) (buffer-file-name))) (tramp-file-name-localname (tramp-dissect-file-name (buffer-file-name))) (buffer-file-name)))) (if (= (shell-command (format "%s --check" (shell-quote-argument command)) "*Test*") 0) (let ((w (get-buffer-window "*Test*"))) (if w (delete-window w)) (kill-buffer "*Test*")) (display-buffer "*Test*")))); -*- # # Mandos Monitor - Control and monitor the Mandos server # -# Copyright © 2008-2018 Teddy Hogeborn -# Copyright © 2008-2018 Björn Påhlsson +# Copyright © 2008-2019 Teddy Hogeborn +# Copyright © 2008-2019 Björn Påhlsson # # This file is part of Mandos. # @@ -40,42 +40,37 @@ import os import collections import json +import unittest +import logging +import io +import tempfile +import contextlib import dbus +# Show warnings by default +if not sys.warnoptions: + import warnings + warnings.simplefilter("default") + +log = logging.getLogger(sys.argv[0]) +logging.basicConfig(level="INFO", # Show info level messages + format="%(message)s") # Show basic log messages + +logging.captureWarnings(True) # Show warnings via the logging system + if sys.version_info.major == 2: str = unicode locale.setlocale(locale.LC_ALL, "") -tablewords = { - "Name": "Name", - "Enabled": "Enabled", - "Timeout": "Timeout", - "LastCheckedOK": "Last Successful Check", - "LastApprovalRequest": "Last Approval Request", - "Created": "Created", - "Interval": "Interval", - "Host": "Host", - "Fingerprint": "Fingerprint", - "CheckerRunning": "Check Is Running", - "LastEnabled": "Last Enabled", - "ApprovalPending": "Approval Is Pending", - "ApprovedByDefault": "Approved By Default", - "ApprovalDelay": "Approval Delay", - "ApprovalDuration": "Approval Duration", - "Checker": "Checker", - "ExtendedTimeout": "Extended Timeout", - "Expires": "Expires", - "LastCheckerStatus": "Last Checker Status", -} -defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK") -domain = "se.recompile" -busname = domain + ".Mandos" -server_path = "/" -server_interface = domain + ".Mandos" -client_interface = domain + ".Mandos.Client" -version = "1.7.19" +dbus_busname_domain = "se.recompile" +dbus_busname = dbus_busname_domain + ".Mandos" +server_dbus_path = "/" +server_dbus_interface = dbus_busname_domain + ".Mandos" +client_dbus_interface = dbus_busname_domain + ".Mandos.Client" +del dbus_busname_domain +version = "1.8.3" try: @@ -84,13 +79,156 @@ dbus.OBJECT_MANAGER_IFACE = "org.freedesktop.DBus.ObjectManager" -def milliseconds_to_string(ms): - td = datetime.timedelta(0, 0, 0, ms) - return ("{days}{hours:02}:{minutes:02}:{seconds:02}" - .format(days="{}T".format(td.days) if td.days else "", - hours=td.seconds // 3600, - minutes=(td.seconds % 3600) // 60, - seconds=td.seconds % 60)) +def main(): + parser = argparse.ArgumentParser() + + add_command_line_options(parser) + + options = parser.parse_args() + + check_option_syntax(parser, options) + + clientnames = options.client + + if options.debug: + log.setLevel(logging.DEBUG) + + try: + bus = dbus.SystemBus() + log.debug("D-Bus: Connect to: (busname=%r, path=%r)", + dbus_busname, server_dbus_path) + mandos_dbus_objc = bus.get_object(dbus_busname, + server_dbus_path) + except dbus.exceptions.DBusException: + log.critical("Could not connect to Mandos server") + sys.exit(1) + + mandos_serv = dbus.Interface(mandos_dbus_objc, + dbus_interface=server_dbus_interface) + mandos_serv_object_manager = dbus.Interface( + mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE) + + # Filter out log message from dbus module + dbus_logger = logging.getLogger("dbus.proxies") + class NullFilter(logging.Filter): + def filter(self, record): + return False + dbus_filter = NullFilter() + try: + dbus_logger.addFilter(dbus_filter) + log.debug("D-Bus: %s:%s:%s.GetManagedObjects()", dbus_busname, + server_dbus_path, dbus.OBJECT_MANAGER_IFACE) + mandos_clients = {path: ifs_and_props[client_dbus_interface] + for path, ifs_and_props in + mandos_serv_object_manager + .GetManagedObjects().items() + if client_dbus_interface in ifs_and_props} + except dbus.exceptions.DBusException as e: + log.critical("Failed to access Mandos server through D-Bus:" + "\n%s", e) + sys.exit(1) + finally: + # restore dbus logger + dbus_logger.removeFilter(dbus_filter) + + # Compile dict of (clients: properties) to process + clients = {} + + if not clientnames: + clients = {objpath: properties + for objpath, properties in mandos_clients.items()} + else: + for name in clientnames: + for objpath, properties in mandos_clients.items(): + if properties["Name"] == name: + clients[objpath] = properties + break + else: + log.critical("Client not found on server: %r", name) + sys.exit(1) + + # Run all commands on clients + commands = commands_from_options(options) + for command in commands: + command.run(clients, bus, mandos_serv) + + +def add_command_line_options(parser): + parser.add_argument("--version", action="version", + version="%(prog)s {}".format(version), + help="show version number and exit") + parser.add_argument("-a", "--all", action="store_true", + help="Select all clients") + parser.add_argument("-v", "--verbose", action="store_true", + help="Print all fields") + parser.add_argument("-j", "--dump-json", action="store_true", + help="Dump client data in JSON format") + enable_disable = parser.add_mutually_exclusive_group() + enable_disable.add_argument("-e", "--enable", action="store_true", + help="Enable client") + enable_disable.add_argument("-d", "--disable", + action="store_true", + help="disable client") + parser.add_argument("-b", "--bump-timeout", action="store_true", + help="Bump timeout for client") + start_stop_checker = parser.add_mutually_exclusive_group() + start_stop_checker.add_argument("--start-checker", + action="store_true", + help="Start checker for client") + start_stop_checker.add_argument("--stop-checker", + action="store_true", + help="Stop checker for client") + parser.add_argument("-V", "--is-enabled", action="store_true", + help="Check if client is enabled") + parser.add_argument("-r", "--remove", action="store_true", + help="Remove client") + parser.add_argument("-c", "--checker", + help="Set checker command for client") + parser.add_argument("-t", "--timeout", type=string_to_delta, + help="Set timeout for client") + parser.add_argument("--extended-timeout", type=string_to_delta, + help="Set extended timeout for client") + parser.add_argument("-i", "--interval", type=string_to_delta, + help="Set checker interval for client") + approve_deny_default = parser.add_mutually_exclusive_group() + approve_deny_default.add_argument( + "--approve-by-default", action="store_true", + default=None, dest="approved_by_default", + help="Set client to be approved by default") + approve_deny_default.add_argument( + "--deny-by-default", action="store_false", + dest="approved_by_default", + help="Set client to be denied by default") + parser.add_argument("--approval-delay", type=string_to_delta, + help="Set delay before client approve/deny") + parser.add_argument("--approval-duration", type=string_to_delta, + help="Set duration of one client approval") + parser.add_argument("-H", "--host", help="Set host for client") + parser.add_argument("-s", "--secret", + type=argparse.FileType(mode="rb"), + help="Set password blob (file) for client") + approve_deny = parser.add_mutually_exclusive_group() + approve_deny.add_argument( + "-A", "--approve", action="store_true", + help="Approve any current client request") + approve_deny.add_argument("-D", "--deny", action="store_true", + help="Deny any current client request") + parser.add_argument("--debug", action="store_true", + help="Debug mode (show D-Bus commands)") + parser.add_argument("--check", action="store_true", + help="Run self-test") + parser.add_argument("client", nargs="*", help="Client name") + + +def string_to_delta(interval): + """Parse a string and return a datetime.timedelta""" + + try: + return rfc3339_duration_to_delta(interval) + except ValueError as e: + log.warning("%s - Parsing as pre-1.6.1 interval instead", + ' '.join(e.args)) + return parse_pre_1_6_1_interval(interval) def rfc3339_duration_to_delta(duration): @@ -102,6 +240,8 @@ datetime.timedelta(0, 60) >>> rfc3339_duration_to_delta("PT60M") datetime.timedelta(0, 3600) + >>> rfc3339_duration_to_delta("P60M") + datetime.timedelta(1680) >>> rfc3339_duration_to_delta("PT24H") datetime.timedelta(1) >>> rfc3339_duration_to_delta("P1W") @@ -110,6 +250,35 @@ datetime.timedelta(0, 330) >>> rfc3339_duration_to_delta("P1DT3M20S") datetime.timedelta(1, 200) + >>> # Can not be empty: + >>> rfc3339_duration_to_delta("") + Traceback (most recent call last): + ... + ValueError: Invalid RFC 3339 duration: u'' + >>> # Must start with "P": + >>> rfc3339_duration_to_delta("1D") + Traceback (most recent call last): + ... + ValueError: Invalid RFC 3339 duration: u'1D' + >>> # Must use correct order + >>> rfc3339_duration_to_delta("PT1S2M") + Traceback (most recent call last): + ... + ValueError: Invalid RFC 3339 duration: u'PT1S2M' + >>> # Time needs time marker + >>> rfc3339_duration_to_delta("P1H2S") + Traceback (most recent call last): + ... + ValueError: Invalid RFC 3339 duration: u'P1H2S' + >>> # Weeks can not be combined with anything else + >>> rfc3339_duration_to_delta("P1D2W") + Traceback (most recent call last): + ... + ValueError: Invalid RFC 3339 duration: u'P1D2W' + >>> rfc3339_duration_to_delta("P2W2H") + Traceback (most recent call last): + ... + ValueError: Invalid RFC 3339 duration: u'P2W2H' """ # Parsing an RFC 3339 duration with regular expressions is not @@ -192,28 +361,30 @@ return value -def string_to_delta(interval): - """Parse a string and return a datetime.timedelta +def parse_pre_1_6_1_interval(interval): + """Parse an interval string as documented by Mandos before 1.6.1, + and return a datetime.timedelta - >>> string_to_delta('7d') + >>> parse_pre_1_6_1_interval('7d') datetime.timedelta(7) - >>> string_to_delta('60s') + >>> parse_pre_1_6_1_interval('60s') datetime.timedelta(0, 60) - >>> string_to_delta('60m') + >>> parse_pre_1_6_1_interval('60m') datetime.timedelta(0, 3600) - >>> string_to_delta('24h') + >>> parse_pre_1_6_1_interval('24h') datetime.timedelta(1) - >>> string_to_delta('1w') + >>> parse_pre_1_6_1_interval('1w') datetime.timedelta(7) - >>> string_to_delta('5m 30s') + >>> parse_pre_1_6_1_interval('5m 30s') datetime.timedelta(0, 330) + >>> parse_pre_1_6_1_interval('') + datetime.timedelta(0) + >>> # Ignore unknown characters, allow any order and repetitions + >>> parse_pre_1_6_1_interval('2dxy7zz11y3m5m') + datetime.timedelta(2, 480, 18000) + """ - try: - return rfc3339_duration_to_delta(interval) - except ValueError: - pass - value = datetime.timedelta(0) regexp = re.compile(r"(\d+)([dsmhw]?)") @@ -233,106 +404,29 @@ return value -def print_clients(clients, keywords): - def valuetostring(value, keyword): - if type(value) is dbus.Boolean: - return "Yes" if value else "No" - if keyword in ("Timeout", "Interval", "ApprovalDelay", - "ApprovalDuration", "ExtendedTimeout"): - return milliseconds_to_string(value) - return str(value) - - # Create format string to print table rows - format_string = " ".join("{{{key}:{width}}}".format( - width=max(len(tablewords[key]), - max(len(valuetostring(client[key], key)) - for client in clients)), - key=key) - for key in keywords) - # Print header line - print(format_string.format(**tablewords)) - for client in clients: - print(format_string - .format(**{key: valuetostring(client[key], key) - for key in keywords})) - - -def has_actions(options): - return any((options.enable, - options.disable, - options.bump_timeout, - options.start_checker, - options.stop_checker, - options.is_enabled, - options.remove, - options.checker is not None, - options.timeout is not None, - options.extended_timeout is not None, - options.interval is not None, - options.approved_by_default is not None, - options.approval_delay is not None, - options.approval_duration is not None, - options.host is not None, - options.secret is not None, - options.approve, - options.deny)) - - -def main(): - parser = argparse.ArgumentParser() - parser.add_argument("--version", action="version", - version="%(prog)s {}".format(version), - help="show version number and exit") - parser.add_argument("-a", "--all", action="store_true", - help="Select all clients") - parser.add_argument("-v", "--verbose", action="store_true", - help="Print all fields") - parser.add_argument("-j", "--dump-json", action="store_true", - help="Dump client data in JSON format") - parser.add_argument("-e", "--enable", action="store_true", - help="Enable client") - parser.add_argument("-d", "--disable", action="store_true", - help="disable client") - parser.add_argument("-b", "--bump-timeout", action="store_true", - help="Bump timeout for client") - parser.add_argument("--start-checker", action="store_true", - help="Start checker for client") - parser.add_argument("--stop-checker", action="store_true", - help="Stop checker for client") - parser.add_argument("-V", "--is-enabled", action="store_true", - help="Check if client is enabled") - parser.add_argument("-r", "--remove", action="store_true", - help="Remove client") - parser.add_argument("-c", "--checker", - help="Set checker command for client") - parser.add_argument("-t", "--timeout", - help="Set timeout for client") - parser.add_argument("--extended-timeout", - help="Set extended timeout for client") - parser.add_argument("-i", "--interval", - help="Set checker interval for client") - parser.add_argument("--approve-by-default", action="store_true", - default=None, dest="approved_by_default", - help="Set client to be approved by default") - parser.add_argument("--deny-by-default", action="store_false", - dest="approved_by_default", - help="Set client to be denied by default") - parser.add_argument("--approval-delay", - help="Set delay before client approve/deny") - parser.add_argument("--approval-duration", - help="Set duration of one client approval") - parser.add_argument("-H", "--host", help="Set host for client") - parser.add_argument("-s", "--secret", - type=argparse.FileType(mode="rb"), - help="Set password blob (file) for client") - parser.add_argument("-A", "--approve", action="store_true", - help="Approve any current client request") - parser.add_argument("-D", "--deny", action="store_true", - help="Deny any current client request") - parser.add_argument("--check", action="store_true", - help="Run self-test") - parser.add_argument("client", nargs="*", help="Client name") - options = parser.parse_args() +def check_option_syntax(parser, options): + """Apply additional restrictions on options, not expressible in +argparse""" + + def has_actions(options): + return any((options.enable, + options.disable, + options.bump_timeout, + options.start_checker, + options.stop_checker, + options.is_enabled, + options.remove, + options.checker is not None, + options.timeout is not None, + options.extended_timeout is not None, + options.interval is not None, + options.approved_by_default is not None, + options.approval_delay is not None, + options.approval_duration is not None, + options.host is not None, + options.secret is not None, + options.approve, + options.deny)) if has_actions(options) and not (options.client or options.all): parser.error("Options require clients names or --all.") @@ -343,155 +437,1246 @@ parser.error("--dump-json can only be used alone.") if options.all and not has_actions(options): parser.error("--all requires an action.") - - if options.check: - import doctest - fail_count, test_count = doctest.testmod() - sys.exit(os.EX_OK if fail_count == 0 else 1) - - try: - bus = dbus.SystemBus() - mandos_dbus_objc = bus.get_object(busname, server_path) - except dbus.exceptions.DBusException: - print("Could not connect to Mandos server", file=sys.stderr) + if options.is_enabled and len(options.client) > 1: + parser.error("--is-enabled requires exactly one client") + if options.remove: + options.remove = False + if has_actions(options) and not options.deny: + parser.error("--remove can only be combined with --deny") + options.remove = True + + +def commands_from_options(options): + + commands = [] + + if options.is_enabled: + commands.append(IsEnabledCmd()) + + if options.approve: + commands.append(ApproveCmd()) + + if options.deny: + commands.append(DenyCmd()) + + if options.remove: + commands.append(RemoveCmd()) + + if options.dump_json: + commands.append(DumpJSONCmd()) + + if options.enable: + commands.append(EnableCmd()) + + if options.disable: + commands.append(DisableCmd()) + + if options.bump_timeout: + commands.append(BumpTimeoutCmd()) + + if options.start_checker: + commands.append(StartCheckerCmd()) + + if options.stop_checker: + commands.append(StopCheckerCmd()) + + if options.approved_by_default is not None: + if options.approved_by_default: + commands.append(ApproveByDefaultCmd()) + else: + commands.append(DenyByDefaultCmd()) + + if options.checker is not None: + commands.append(SetCheckerCmd(options.checker)) + + if options.host is not None: + commands.append(SetHostCmd(options.host)) + + if options.secret is not None: + commands.append(SetSecretCmd(options.secret)) + + if options.timeout is not None: + commands.append(SetTimeoutCmd(options.timeout)) + + if options.extended_timeout: + commands.append( + SetExtendedTimeoutCmd(options.extended_timeout)) + + if options.interval is not None: + commands.append(SetIntervalCmd(options.interval)) + + if options.approval_delay is not None: + commands.append(SetApprovalDelayCmd(options.approval_delay)) + + if options.approval_duration is not None: + commands.append( + SetApprovalDurationCmd(options.approval_duration)) + + # If no command option has been given, show table of clients, + # optionally verbosely + if not commands: + commands.append(PrintTableCmd(verbose=options.verbose)) + + return commands + + +class Command(object): + """Abstract class for commands""" + def run(self, clients, bus=None, mandos=None): + """Normal commands should implement run_on_one_client(), but + commands which want to operate on all clients at the same time + can override this run() method instead.""" + self.mandos = mandos + for clientpath, properties in clients.items(): + log.debug("D-Bus: Connect to: (busname=%r, path=%r)", + dbus_busname, str(clientpath)) + client = bus.get_object(dbus_busname, clientpath) + self.run_on_one_client(client, properties) + + +class IsEnabledCmd(Command): + def run(self, clients, bus=None, mandos=None): + client, properties = next(iter(clients.items())) + if self.is_enabled(client, properties): + sys.exit(0) sys.exit(1) - - mandos_serv = dbus.Interface(mandos_dbus_objc, - dbus_interface=server_interface) - mandos_serv_object_manager = dbus.Interface( - mandos_dbus_objc, dbus_interface=dbus.OBJECT_MANAGER_IFACE) - - # block stderr since dbus library prints to stderr - null = os.open(os.path.devnull, os.O_RDWR) - stderrcopy = os.dup(sys.stderr.fileno()) - os.dup2(null, sys.stderr.fileno()) - os.close(null) - try: + def is_enabled(self, client, properties): + return properties["Enabled"] + + +class ApproveCmd(Command): + def run_on_one_client(self, client, properties): + log.debug("D-Bus: %s:%s:%s.Approve(True)", dbus_busname, + client.__dbus_object_path__, client_dbus_interface) + client.Approve(dbus.Boolean(True), + dbus_interface=client_dbus_interface) + + +class DenyCmd(Command): + def run_on_one_client(self, client, properties): + log.debug("D-Bus: %s:%s:%s.Approve(False)", dbus_busname, + client.__dbus_object_path__, client_dbus_interface) + client.Approve(dbus.Boolean(False), + dbus_interface=client_dbus_interface) + + +class RemoveCmd(Command): + def run_on_one_client(self, client, properties): + log.debug("D-Bus: %s:%s:%s.RemoveClient(%r)", dbus_busname, + server_dbus_path, server_dbus_interface, + str(client.__dbus_object_path__)) + self.mandos.RemoveClient(client.__dbus_object_path__) + + +class PrintCmd(Command): + """Abstract class for commands printing client details""" + all_keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK", + "Created", "Interval", "Host", "KeyID", + "Fingerprint", "CheckerRunning", "LastEnabled", + "ApprovalPending", "ApprovedByDefault", + "LastApprovalRequest", "ApprovalDelay", + "ApprovalDuration", "Checker", "ExtendedTimeout", + "Expires", "LastCheckerStatus") + def run(self, clients, bus=None, mandos=None): + print(self.output(clients.values())) + def output(self, clients): + raise NotImplementedError() + + +class DumpJSONCmd(PrintCmd): + def output(self, clients): + data = {client["Name"]: + {key: self.dbus_boolean_to_bool(client[key]) + for key in self.all_keywords} + for client in clients.values()} + return json.dumps(data, indent=4, separators=(',', ': ')) + @staticmethod + def dbus_boolean_to_bool(value): + if isinstance(value, dbus.Boolean): + value = bool(value) + return value + + +class PrintTableCmd(PrintCmd): + def __init__(self, verbose=False): + self.verbose = verbose + + def output(self, clients): + default_keywords = ("Name", "Enabled", "Timeout", + "LastCheckedOK") + keywords = default_keywords + if self.verbose: + keywords = self.all_keywords + return str(self.TableOfClients(clients, keywords)) + + class TableOfClients(object): + tableheaders = { + "Name": "Name", + "Enabled": "Enabled", + "Timeout": "Timeout", + "LastCheckedOK": "Last Successful Check", + "LastApprovalRequest": "Last Approval Request", + "Created": "Created", + "Interval": "Interval", + "Host": "Host", + "Fingerprint": "Fingerprint", + "KeyID": "Key ID", + "CheckerRunning": "Check Is Running", + "LastEnabled": "Last Enabled", + "ApprovalPending": "Approval Is Pending", + "ApprovedByDefault": "Approved By Default", + "ApprovalDelay": "Approval Delay", + "ApprovalDuration": "Approval Duration", + "Checker": "Checker", + "ExtendedTimeout": "Extended Timeout", + "Expires": "Expires", + "LastCheckerStatus": "Last Checker Status", + } + + def __init__(self, clients, keywords, tableheaders=None): + self.clients = clients + self.keywords = keywords + if tableheaders is not None: + self.tableheaders = tableheaders + + def __str__(self): + return "\n".join(self.rows()) + + if sys.version_info.major == 2: + __unicode__ = __str__ + def __str__(self): + return str(self).encode(locale.getpreferredencoding()) + + def rows(self): + format_string = self.row_formatting_string() + rows = [self.header_line(format_string)] + rows.extend(self.client_line(client, format_string) + for client in self.clients) + return rows + + def row_formatting_string(self): + "Format string used to format table rows" + return " ".join("{{{key}:{width}}}".format( + width=max(len(self.tableheaders[key]), + *(len(self.string_from_client(client, key)) + for client in self.clients)), + key=key) + for key in self.keywords) + + def string_from_client(self, client, key): + return self.valuetostring(client[key], key) + + @classmethod + def valuetostring(cls, value, keyword): + if isinstance(value, dbus.Boolean): + return "Yes" if value else "No" + if keyword in ("Timeout", "Interval", "ApprovalDelay", + "ApprovalDuration", "ExtendedTimeout"): + return cls.milliseconds_to_string(value) + return str(value) + + def header_line(self, format_string): + return format_string.format(**self.tableheaders) + + def client_line(self, client, format_string): + return format_string.format( + **{key: self.string_from_client(client, key) + for key in self.keywords}) + + @staticmethod + def milliseconds_to_string(ms): + td = datetime.timedelta(0, 0, 0, ms) + return ("{days}{hours:02}:{minutes:02}:{seconds:02}" + .format(days="{}T".format(td.days) + if td.days else "", + hours=td.seconds // 3600, + minutes=(td.seconds % 3600) // 60, + seconds=td.seconds % 60)) + + +class PropertyCmd(Command): + """Abstract class for Actions for setting one client property""" + def run_on_one_client(self, client, properties): + """Set the Client's D-Bus property""" + log.debug("D-Bus: %s:%s:%s.Set(%r, %r, %r)", dbus_busname, + client.__dbus_object_path__, + dbus.PROPERTIES_IFACE, client_dbus_interface, + self.propname, self.value_to_set + if not isinstance(self.value_to_set, dbus.Boolean) + else bool(self.value_to_set)) + client.Set(client_dbus_interface, self.propname, + self.value_to_set, + dbus_interface=dbus.PROPERTIES_IFACE) + @property + def propname(self): + raise NotImplementedError() + + +class EnableCmd(PropertyCmd): + propname = "Enabled" + value_to_set = dbus.Boolean(True) + + +class DisableCmd(PropertyCmd): + propname = "Enabled" + value_to_set = dbus.Boolean(False) + + +class BumpTimeoutCmd(PropertyCmd): + propname = "LastCheckedOK" + value_to_set = "" + + +class StartCheckerCmd(PropertyCmd): + propname = "CheckerRunning" + value_to_set = dbus.Boolean(True) + + +class StopCheckerCmd(PropertyCmd): + propname = "CheckerRunning" + value_to_set = dbus.Boolean(False) + + +class ApproveByDefaultCmd(PropertyCmd): + propname = "ApprovedByDefault" + value_to_set = dbus.Boolean(True) + + +class DenyByDefaultCmd(PropertyCmd): + propname = "ApprovedByDefault" + value_to_set = dbus.Boolean(False) + + +class PropertyValueCmd(PropertyCmd): + """Abstract class for PropertyCmd recieving a value as argument""" + def __init__(self, value): + self.value_to_set = value + + +class SetCheckerCmd(PropertyValueCmd): + propname = "Checker" + + +class SetHostCmd(PropertyValueCmd): + propname = "Host" + + +class SetSecretCmd(PropertyValueCmd): + propname = "Secret" + @property + def value_to_set(self): + return self._vts + @value_to_set.setter + def value_to_set(self, value): + """When setting, read data from supplied file object""" + self._vts = value.read() + value.close() + + +class MillisecondsPropertyValueArgumentCmd(PropertyValueCmd): + """Abstract class for PropertyValueCmd taking a value argument as +a datetime.timedelta() but should store it as milliseconds.""" + @property + def value_to_set(self): + return self._vts + @value_to_set.setter + def value_to_set(self, value): + """When setting, convert value from a datetime.timedelta""" + self._vts = int(round(value.total_seconds() * 1000)) + + +class SetTimeoutCmd(MillisecondsPropertyValueArgumentCmd): + propname = "Timeout" + + +class SetExtendedTimeoutCmd(MillisecondsPropertyValueArgumentCmd): + propname = "ExtendedTimeout" + + +class SetIntervalCmd(MillisecondsPropertyValueArgumentCmd): + propname = "Interval" + + +class SetApprovalDelayCmd(MillisecondsPropertyValueArgumentCmd): + propname = "ApprovalDelay" + + +class SetApprovalDurationCmd(MillisecondsPropertyValueArgumentCmd): + propname = "ApprovalDuration" + + + +class Test_string_to_delta(unittest.TestCase): + def test_handles_basic_rfc3339(self): + self.assertEqual(string_to_delta("PT0S"), + datetime.timedelta()) + self.assertEqual(string_to_delta("P0D"), + datetime.timedelta()) + self.assertEqual(string_to_delta("PT1S"), + datetime.timedelta(0, 1)) + self.assertEqual(string_to_delta("PT2H"), + datetime.timedelta(0, 7200)) + def test_falls_back_to_pre_1_6_1_with_warning(self): + # assertLogs only exists in Python 3.4 + if hasattr(self, "assertLogs"): + with self.assertLogs(log, logging.WARNING): + value = string_to_delta("2h") + else: + class WarningFilter(logging.Filter): + """Don't show, but record the presence of, warnings""" + def filter(self, record): + is_warning = record.levelno >= logging.WARNING + self.found = is_warning or getattr(self, "found", + False) + return not is_warning + warning_filter = WarningFilter() + log.addFilter(warning_filter) + try: + value = string_to_delta("2h") + finally: + log.removeFilter(warning_filter) + self.assertTrue(getattr(warning_filter, "found", False)) + self.assertEqual(value, datetime.timedelta(0, 7200)) + + +class Test_check_option_syntax(unittest.TestCase): + # This mostly corresponds to the definition from has_actions() in + # check_option_syntax() + actions = { + # The actual values set here are not that important, but we do + # at least stick to the correct types, even though they are + # never used + "enable": True, + "disable": True, + "bump_timeout": True, + "start_checker": True, + "stop_checker": True, + "is_enabled": True, + "remove": True, + "checker": "x", + "timeout": datetime.timedelta(), + "extended_timeout": datetime.timedelta(), + "interval": datetime.timedelta(), + "approved_by_default": True, + "approval_delay": datetime.timedelta(), + "approval_duration": datetime.timedelta(), + "host": "x", + "secret": io.BytesIO(b"x"), + "approve": True, + "deny": True, + } + + def setUp(self): + self.parser = argparse.ArgumentParser() + add_command_line_options(self.parser) + + @contextlib.contextmanager + def assertParseError(self): + with self.assertRaises(SystemExit) as e: + with self.temporarily_suppress_stderr(): + yield + # Exit code from argparse is guaranteed to be "2". Reference: + # https://docs.python.org/3/library + # /argparse.html#exiting-methods + self.assertEqual(e.exception.code, 2) + + @staticmethod + @contextlib.contextmanager + def temporarily_suppress_stderr(): + null = os.open(os.path.devnull, os.O_RDWR) + stderrcopy = os.dup(sys.stderr.fileno()) + os.dup2(null, sys.stderr.fileno()) + os.close(null) try: - mandos_clients = {path: ifs_and_props[client_interface] - for path, ifs_and_props in - mandos_serv_object_manager - .GetManagedObjects().items() - if client_interface in ifs_and_props} + yield finally: # restore stderr os.dup2(stderrcopy, sys.stderr.fileno()) os.close(stderrcopy) - except dbus.exceptions.DBusException as e: - print("Access denied: " - "Accessing mandos server through D-Bus: {}".format(e), - file=sys.stderr) - sys.exit(1) - - # Compile dict of (clients: properties) to process - clients = {} - - if options.all or not options.client: - clients = {bus.get_object(busname, path): properties - for path, properties in mandos_clients.items()} - else: - for name in options.client: - for path, client in mandos_clients.items(): - if client["Name"] == name: - client_objc = bus.get_object(busname, path) - clients[client_objc] = client - break - else: - print("Client not found on server: {!r}" - .format(name), file=sys.stderr) - sys.exit(1) - - if not has_actions(options) and clients: - if options.verbose or options.dump_json: - keywords = ("Name", "Enabled", "Timeout", "LastCheckedOK", - "Created", "Interval", "Host", "Fingerprint", - "CheckerRunning", "LastEnabled", - "ApprovalPending", "ApprovedByDefault", - "LastApprovalRequest", "ApprovalDelay", - "ApprovalDuration", "Checker", - "ExtendedTimeout", "Expires", - "LastCheckerStatus") - else: - keywords = defaultkeywords - - if options.dump_json: - json.dump({client["Name"]: {key: - bool(client[key]) - if isinstance(client[key], - dbus.Boolean) - else client[key] - for key in keywords} - for client in clients.values()}, - fp=sys.stdout, indent=4, - separators=(',', ': ')) - print() - else: - print_clients(clients.values(), keywords) - else: - # Process each client in the list by all selected options - for client in clients: - - def set_client_prop(prop, value): - """Set a Client D-Bus property""" - client.Set(client_interface, prop, value, - dbus_interface=dbus.PROPERTIES_IFACE) - - def set_client_prop_ms(prop, value): - """Set a Client D-Bus property, converted - from a string to milliseconds.""" - set_client_prop(prop, - string_to_delta(value).total_seconds() - * 1000) - - if options.remove: - mandos_serv.RemoveClient(client.__dbus_object_path__) - if options.enable: - set_client_prop("Enabled", dbus.Boolean(True)) - if options.disable: - set_client_prop("Enabled", dbus.Boolean(False)) - if options.bump_timeout: - set_client_prop("LastCheckedOK", "") - if options.start_checker: - set_client_prop("CheckerRunning", dbus.Boolean(True)) - if options.stop_checker: - set_client_prop("CheckerRunning", dbus.Boolean(False)) - if options.is_enabled: - if client.Get(client_interface, "Enabled", - dbus_interface=dbus.PROPERTIES_IFACE): - sys.exit(0) - else: - sys.exit(1) - if options.checker is not None: - set_client_prop("Checker", options.checker) - if options.host is not None: - set_client_prop("Host", options.host) - if options.interval is not None: - set_client_prop_ms("Interval", options.interval) - if options.approval_delay is not None: - set_client_prop_ms("ApprovalDelay", - options.approval_delay) - if options.approval_duration is not None: - set_client_prop_ms("ApprovalDuration", - options.approval_duration) - if options.timeout is not None: - set_client_prop_ms("Timeout", options.timeout) - if options.extended_timeout is not None: - set_client_prop_ms("ExtendedTimeout", - options.extended_timeout) - if options.secret is not None: - set_client_prop("Secret", - dbus.ByteArray(options.secret.read())) - if options.approved_by_default is not None: - set_client_prop("ApprovedByDefault", - dbus.Boolean(options - .approved_by_default)) - if options.approve: - client.Approve(dbus.Boolean(True), - dbus_interface=client_interface) - elif options.deny: - client.Approve(dbus.Boolean(False), - dbus_interface=client_interface) - + + def check_option_syntax(self, options): + check_option_syntax(self.parser, options) + + def test_actions_requires_client_or_all(self): + for action, value in self.actions.items(): + options = self.parser.parse_args() + setattr(options, action, value) + with self.assertParseError(): + self.check_option_syntax(options) + + def test_actions_conflicts_with_verbose(self): + for action, value in self.actions.items(): + options = self.parser.parse_args() + setattr(options, action, value) + options.verbose = True + with self.assertParseError(): + self.check_option_syntax(options) + + def test_dump_json_conflicts_with_verbose(self): + options = self.parser.parse_args() + options.dump_json = True + options.verbose = True + with self.assertParseError(): + self.check_option_syntax(options) + + def test_dump_json_conflicts_with_action(self): + for action, value in self.actions.items(): + options = self.parser.parse_args() + setattr(options, action, value) + options.dump_json = True + with self.assertParseError(): + self.check_option_syntax(options) + + def test_all_can_not_be_alone(self): + options = self.parser.parse_args() + options.all = True + with self.assertParseError(): + self.check_option_syntax(options) + + def test_all_is_ok_with_any_action(self): + for action, value in self.actions.items(): + options = self.parser.parse_args() + setattr(options, action, value) + options.all = True + self.check_option_syntax(options) + + def test_is_enabled_fails_without_client(self): + options = self.parser.parse_args() + options.is_enabled = True + with self.assertParseError(): + self.check_option_syntax(options) + + def test_is_enabled_works_with_one_client(self): + options = self.parser.parse_args() + options.is_enabled = True + options.client = ["foo"] + self.check_option_syntax(options) + + def test_is_enabled_fails_with_two_clients(self): + options = self.parser.parse_args() + options.is_enabled = True + options.client = ["foo", "barbar"] + with self.assertParseError(): + self.check_option_syntax(options) + + def test_remove_can_only_be_combined_with_action_deny(self): + for action, value in self.actions.items(): + if action in {"remove", "deny"}: + continue + options = self.parser.parse_args() + setattr(options, action, value) + options.all = True + options.remove = True + with self.assertParseError(): + self.check_option_syntax(options) + + +class Test_command_from_options(unittest.TestCase): + def setUp(self): + self.parser = argparse.ArgumentParser() + add_command_line_options(self.parser) + def assert_command_from_args(self, args, command_cls, + **cmd_attrs): + """Assert that parsing ARGS should result in an instance of +COMMAND_CLS with (optionally) all supplied attributes (CMD_ATTRS).""" + options = self.parser.parse_args(args) + check_option_syntax(self.parser, options) + commands = commands_from_options(options) + self.assertEqual(len(commands), 1) + command = commands[0] + self.assertIsInstance(command, command_cls) + for key, value in cmd_attrs.items(): + self.assertEqual(getattr(command, key), value) + def test_print_table(self): + self.assert_command_from_args([], PrintTableCmd, + verbose=False) + + def test_print_table_verbose(self): + self.assert_command_from_args(["--verbose"], PrintTableCmd, + verbose=True) + + def test_print_table_verbose_short(self): + self.assert_command_from_args(["-v"], PrintTableCmd, + verbose=True) + + def test_enable(self): + self.assert_command_from_args(["--enable", "foo"], EnableCmd) + + def test_enable_short(self): + self.assert_command_from_args(["-e", "foo"], EnableCmd) + + def test_disable(self): + self.assert_command_from_args(["--disable", "foo"], + DisableCmd) + + def test_disable_short(self): + self.assert_command_from_args(["-d", "foo"], DisableCmd) + + def test_bump_timeout(self): + self.assert_command_from_args(["--bump-timeout", "foo"], + BumpTimeoutCmd) + + def test_bump_timeout_short(self): + self.assert_command_from_args(["-b", "foo"], BumpTimeoutCmd) + + def test_start_checker(self): + self.assert_command_from_args(["--start-checker", "foo"], + StartCheckerCmd) + + def test_stop_checker(self): + self.assert_command_from_args(["--stop-checker", "foo"], + StopCheckerCmd) + + def test_remove(self): + self.assert_command_from_args(["--remove", "foo"], + RemoveCmd) + + def test_remove_short(self): + self.assert_command_from_args(["-r", "foo"], RemoveCmd) + + def test_checker(self): + self.assert_command_from_args(["--checker", ":", "foo"], + SetCheckerCmd, value_to_set=":") + + def test_checker_empty(self): + self.assert_command_from_args(["--checker", "", "foo"], + SetCheckerCmd, value_to_set="") + + def test_checker_short(self): + self.assert_command_from_args(["-c", ":", "foo"], + SetCheckerCmd, value_to_set=":") + + def test_timeout(self): + self.assert_command_from_args(["--timeout", "PT5M", "foo"], + SetTimeoutCmd, + value_to_set=300000) + + def test_timeout_short(self): + self.assert_command_from_args(["-t", "PT5M", "foo"], + SetTimeoutCmd, + value_to_set=300000) + + def test_extended_timeout(self): + self.assert_command_from_args(["--extended-timeout", "PT15M", + "foo"], + SetExtendedTimeoutCmd, + value_to_set=900000) + + def test_interval(self): + self.assert_command_from_args(["--interval", "PT2M", "foo"], + SetIntervalCmd, + value_to_set=120000) + + def test_interval_short(self): + self.assert_command_from_args(["-i", "PT2M", "foo"], + SetIntervalCmd, + value_to_set=120000) + + def test_approve_by_default(self): + self.assert_command_from_args(["--approve-by-default", "foo"], + ApproveByDefaultCmd) + + def test_deny_by_default(self): + self.assert_command_from_args(["--deny-by-default", "foo"], + DenyByDefaultCmd) + + def test_approval_delay(self): + self.assert_command_from_args(["--approval-delay", "PT30S", + "foo"], SetApprovalDelayCmd, + value_to_set=30000) + + def test_approval_duration(self): + self.assert_command_from_args(["--approval-duration", "PT1S", + "foo"], SetApprovalDurationCmd, + value_to_set=1000) + + def test_host(self): + self.assert_command_from_args(["--host", "foo.example.org", + "foo"], SetHostCmd, + value_to_set="foo.example.org") + + def test_host_short(self): + self.assert_command_from_args(["-H", "foo.example.org", + "foo"], SetHostCmd, + value_to_set="foo.example.org") + + def test_secret_devnull(self): + self.assert_command_from_args(["--secret", os.path.devnull, + "foo"], SetSecretCmd, + value_to_set=b"") + + def test_secret_tempfile(self): + with tempfile.NamedTemporaryFile(mode="r+b") as f: + value = b"secret\0xyzzy\nbar" + f.write(value) + f.seek(0) + self.assert_command_from_args(["--secret", f.name, + "foo"], SetSecretCmd, + value_to_set=value) + + def test_secret_devnull_short(self): + self.assert_command_from_args(["-s", os.path.devnull, "foo"], + SetSecretCmd, value_to_set=b"") + + def test_secret_tempfile_short(self): + with tempfile.NamedTemporaryFile(mode="r+b") as f: + value = b"secret\0xyzzy\nbar" + f.write(value) + f.seek(0) + self.assert_command_from_args(["-s", f.name, "foo"], + SetSecretCmd, + value_to_set=value) + + def test_approve(self): + self.assert_command_from_args(["--approve", "foo"], + ApproveCmd) + + def test_approve_short(self): + self.assert_command_from_args(["-A", "foo"], ApproveCmd) + + def test_deny(self): + self.assert_command_from_args(["--deny", "foo"], DenyCmd) + + def test_deny_short(self): + self.assert_command_from_args(["-D", "foo"], DenyCmd) + + def test_dump_json(self): + self.assert_command_from_args(["--dump-json"], DumpJSONCmd) + + def test_is_enabled(self): + self.assert_command_from_args(["--is-enabled", "foo"], + IsEnabledCmd) + + def test_is_enabled_short(self): + self.assert_command_from_args(["-V", "foo"], IsEnabledCmd) + + def test_deny_before_remove(self): + options = self.parser.parse_args(["--deny", "--remove", + "foo"]) + check_option_syntax(self.parser, options) + commands = commands_from_options(options) + self.assertEqual(len(commands), 2) + self.assertIsInstance(commands[0], DenyCmd) + self.assertIsInstance(commands[1], RemoveCmd) + + def test_deny_before_remove_reversed(self): + options = self.parser.parse_args(["--remove", "--deny", + "--all"]) + check_option_syntax(self.parser, options) + commands = commands_from_options(options) + self.assertEqual(len(commands), 2) + self.assertIsInstance(commands[0], DenyCmd) + self.assertIsInstance(commands[1], RemoveCmd) + + +class TestCmd(unittest.TestCase): + """Abstract class for tests of command classes""" + def setUp(self): + testcase = self + class MockClient(object): + def __init__(self, name, **attributes): + self.__dbus_object_path__ = "/clients/{}".format(name) + self.attributes = attributes + self.attributes["Name"] = name + self.calls = [] + def Set(self, interface, propname, value, dbus_interface): + testcase.assertEqual(interface, client_dbus_interface) + testcase.assertEqual(dbus_interface, + dbus.PROPERTIES_IFACE) + self.attributes[propname] = value + def Get(self, interface, propname, dbus_interface): + testcase.assertEqual(interface, client_dbus_interface) + testcase.assertEqual(dbus_interface, + dbus.PROPERTIES_IFACE) + return self.attributes[propname] + def Approve(self, approve, dbus_interface): + testcase.assertEqual(dbus_interface, + client_dbus_interface) + self.calls.append(("Approve", (approve, + dbus_interface))) + self.client = MockClient( + "foo", + KeyID=("92ed150794387c03ce684574b1139a65" + "94a34f895daaaf09fd8ea90a27cddb12"), + Secret=b"secret", + Host="foo.example.org", + Enabled=dbus.Boolean(True), + Timeout=300000, + LastCheckedOK="2019-02-03T00:00:00", + Created="2019-01-02T00:00:00", + Interval=120000, + Fingerprint=("778827225BA7DE539C5A" + "7CFA59CFF7CDBD9A5920"), + CheckerRunning=dbus.Boolean(False), + LastEnabled="2019-01-03T00:00:00", + ApprovalPending=dbus.Boolean(False), + ApprovedByDefault=dbus.Boolean(True), + LastApprovalRequest="", + ApprovalDelay=0, + ApprovalDuration=1000, + Checker="fping -q -- %(host)s", + ExtendedTimeout=900000, + Expires="2019-02-04T00:00:00", + LastCheckerStatus=0) + self.other_client = MockClient( + "barbar", + KeyID=("0558568eedd67d622f5c83b35a115f79" + "6ab612cff5ad227247e46c2b020f441c"), + Secret=b"secretbar", + Host="192.0.2.3", + Enabled=dbus.Boolean(True), + Timeout=300000, + LastCheckedOK="2019-02-04T00:00:00", + Created="2019-01-03T00:00:00", + Interval=120000, + Fingerprint=("3E393AEAEFB84C7E89E2" + "F547B3A107558FCA3A27"), + CheckerRunning=dbus.Boolean(True), + LastEnabled="2019-01-04T00:00:00", + ApprovalPending=dbus.Boolean(False), + ApprovedByDefault=dbus.Boolean(False), + LastApprovalRequest="2019-01-03T00:00:00", + ApprovalDelay=30000, + ApprovalDuration=93785000, + Checker=":", + ExtendedTimeout=900000, + Expires="2019-02-05T00:00:00", + LastCheckerStatus=-2) + self.clients = collections.OrderedDict( + [ + ("/clients/foo", self.client.attributes), + ("/clients/barbar", self.other_client.attributes), + ]) + self.one_client = {"/clients/foo": self.client.attributes} + @property + def bus(self): + class Bus(object): + @staticmethod + def get_object(client_bus_name, path): + self.assertEqual(client_bus_name, dbus_busname) + return { + "/clients/foo": self.client, + "/clients/barbar": self.other_client, + }[path] + return Bus() + + +class TestIsEnabledCmd(TestCmd): + def test_is_enabled(self): + self.assertTrue(all(IsEnabledCmd().is_enabled(client, + properties) + for client, properties + in self.clients.items())) + def test_is_enabled_run_exits_successfully(self): + with self.assertRaises(SystemExit) as e: + IsEnabledCmd().run(self.one_client) + if e.exception.code is not None: + self.assertEqual(e.exception.code, 0) + else: + self.assertIsNone(e.exception.code) + def test_is_enabled_run_exits_with_failure(self): + self.client.attributes["Enabled"] = dbus.Boolean(False) + with self.assertRaises(SystemExit) as e: + IsEnabledCmd().run(self.one_client) + if isinstance(e.exception.code, int): + self.assertNotEqual(e.exception.code, 0) + else: + self.assertIsNotNone(e.exception.code) + + +class TestApproveCmd(TestCmd): + def test_approve(self): + ApproveCmd().run(self.clients, self.bus) + for clientpath in self.clients: + client = self.bus.get_object(dbus_busname, clientpath) + self.assertIn(("Approve", (True, client_dbus_interface)), + client.calls) + + +class TestDenyCmd(TestCmd): + def test_deny(self): + DenyCmd().run(self.clients, self.bus) + for clientpath in self.clients: + client = self.bus.get_object(dbus_busname, clientpath) + self.assertIn(("Approve", (False, client_dbus_interface)), + client.calls) + +class TestRemoveCmd(TestCmd): + def test_remove(self): + class MockMandos(object): + def __init__(self): + self.calls = [] + def RemoveClient(self, dbus_path): + self.calls.append(("RemoveClient", (dbus_path,))) + mandos = MockMandos() + super(TestRemoveCmd, self).setUp() + RemoveCmd().run(self.clients, self.bus, mandos) + self.assertEqual(len(mandos.calls), 2) + for clientpath in self.clients: + self.assertIn(("RemoveClient", (clientpath,)), + mandos.calls) + + +class TestDumpJSONCmd(TestCmd): + def setUp(self): + self.expected_json = { + "foo": { + "Name": "foo", + "KeyID": ("92ed150794387c03ce684574b1139a65" + "94a34f895daaaf09fd8ea90a27cddb12"), + "Host": "foo.example.org", + "Enabled": True, + "Timeout": 300000, + "LastCheckedOK": "2019-02-03T00:00:00", + "Created": "2019-01-02T00:00:00", + "Interval": 120000, + "Fingerprint": ("778827225BA7DE539C5A" + "7CFA59CFF7CDBD9A5920"), + "CheckerRunning": False, + "LastEnabled": "2019-01-03T00:00:00", + "ApprovalPending": False, + "ApprovedByDefault": True, + "LastApprovalRequest": "", + "ApprovalDelay": 0, + "ApprovalDuration": 1000, + "Checker": "fping -q -- %(host)s", + "ExtendedTimeout": 900000, + "Expires": "2019-02-04T00:00:00", + "LastCheckerStatus": 0, + }, + "barbar": { + "Name": "barbar", + "KeyID": ("0558568eedd67d622f5c83b35a115f79" + "6ab612cff5ad227247e46c2b020f441c"), + "Host": "192.0.2.3", + "Enabled": True, + "Timeout": 300000, + "LastCheckedOK": "2019-02-04T00:00:00", + "Created": "2019-01-03T00:00:00", + "Interval": 120000, + "Fingerprint": ("3E393AEAEFB84C7E89E2" + "F547B3A107558FCA3A27"), + "CheckerRunning": True, + "LastEnabled": "2019-01-04T00:00:00", + "ApprovalPending": False, + "ApprovedByDefault": False, + "LastApprovalRequest": "2019-01-03T00:00:00", + "ApprovalDelay": 30000, + "ApprovalDuration": 93785000, + "Checker": ":", + "ExtendedTimeout": 900000, + "Expires": "2019-02-05T00:00:00", + "LastCheckerStatus": -2, + }, + } + return super(TestDumpJSONCmd, self).setUp() + def test_normal(self): + json_data = json.loads(DumpJSONCmd().output(self.clients)) + self.assertDictEqual(json_data, self.expected_json) + def test_one_client(self): + clients = self.one_client + json_data = json.loads(DumpJSONCmd().output(clients)) + expected_json = {"foo": self.expected_json["foo"]} + self.assertDictEqual(json_data, expected_json) + + +class TestPrintTableCmd(TestCmd): + def test_normal(self): + output = PrintTableCmd().output(self.clients.values()) + expected_output = "\n".join(( + "Name Enabled Timeout Last Successful Check", + "foo Yes 00:05:00 2019-02-03T00:00:00 ", + "barbar Yes 00:05:00 2019-02-04T00:00:00 ", + )) + self.assertEqual(output, expected_output) + def test_verbose(self): + output = PrintTableCmd(verbose=True).output( + self.clients.values()) + columns = ( + ( + "Name ", + "foo ", + "barbar ", + ),( + "Enabled ", + "Yes ", + "Yes ", + ),( + "Timeout ", + "00:05:00 ", + "00:05:00 ", + ),( + "Last Successful Check ", + "2019-02-03T00:00:00 ", + "2019-02-04T00:00:00 ", + ),( + "Created ", + "2019-01-02T00:00:00 ", + "2019-01-03T00:00:00 ", + ),( + "Interval ", + "00:02:00 ", + "00:02:00 ", + ),( + "Host ", + "foo.example.org ", + "192.0.2.3 ", + ),( + ("Key ID " + " "), + ("92ed150794387c03ce684574b1139a6594a34f895daaaf09fd8" + "ea90a27cddb12 "), + ("0558568eedd67d622f5c83b35a115f796ab612cff5ad227247e" + "46c2b020f441c "), + ),( + "Fingerprint ", + "778827225BA7DE539C5A7CFA59CFF7CDBD9A5920 ", + "3E393AEAEFB84C7E89E2F547B3A107558FCA3A27 ", + ),( + "Check Is Running ", + "No ", + "Yes ", + ),( + "Last Enabled ", + "2019-01-03T00:00:00 ", + "2019-01-04T00:00:00 ", + ),( + "Approval Is Pending ", + "No ", + "No ", + ),( + "Approved By Default ", + "Yes ", + "No ", + ),( + "Last Approval Request ", + " ", + "2019-01-03T00:00:00 ", + ),( + "Approval Delay ", + "00:00:00 ", + "00:00:30 ", + ),( + "Approval Duration ", + "00:00:01 ", + "1T02:03:05 ", + ),( + "Checker ", + "fping -q -- %(host)s ", + ": ", + ),( + "Extended Timeout ", + "00:15:00 ", + "00:15:00 ", + ),( + "Expires ", + "2019-02-04T00:00:00 ", + "2019-02-05T00:00:00 ", + ),( + "Last Checker Status", + "0 ", + "-2 ", + ) + ) + num_lines = max(len(rows) for rows in columns) + expected_output = "\n".join("".join(rows[line] + for rows in columns) + for line in range(num_lines)) + self.assertEqual(output, expected_output) + def test_one_client(self): + output = PrintTableCmd().output(self.one_client.values()) + expected_output = """ +Name Enabled Timeout Last Successful Check +foo Yes 00:05:00 2019-02-03T00:00:00 +"""[1:-1] + self.assertEqual(output, expected_output) + + +class Unique(object): + """Class for objects which exist only to be unique objects, since +unittest.mock.sentinel only exists in Python 3.3""" + + +class TestPropertyCmd(TestCmd): + """Abstract class for tests of PropertyCmd classes""" + def runTest(self): + if not hasattr(self, "command"): + return + values_to_get = getattr(self, "values_to_get", + self.values_to_set) + for value_to_set, value_to_get in zip(self.values_to_set, + values_to_get): + for clientpath in self.clients: + client = self.bus.get_object(dbus_busname, clientpath) + old_value = client.attributes[self.propname] + self.assertNotIsInstance(old_value, Unique) + client.attributes[self.propname] = Unique() + self.run_command(value_to_set, self.clients) + for clientpath in self.clients: + client = self.bus.get_object(dbus_busname, clientpath) + value = client.attributes[self.propname] + self.assertNotIsInstance(value, Unique) + self.assertEqual(value, value_to_get) + def run_command(self, value, clients): + self.command().run(clients, self.bus) + + +class TestEnableCmd(TestCmd): + def test_enable(self): + for clientpath in self.clients: + client = self.bus.get_object(dbus_busname, clientpath) + client.attributes["Enabled"] = False + + EnableCmd().run(self.clients, self.bus) + + for clientpath in self.clients: + client = self.bus.get_object(dbus_busname, clientpath) + self.assertTrue(client.attributes["Enabled"]) + + +class TestDisableCmd(TestCmd): + def test_disable(self): + DisableCmd().run(self.clients, self.bus) + for clientpath in self.clients: + client = self.bus.get_object(dbus_busname, clientpath) + self.assertFalse(client.attributes["Enabled"]) + + +class TestBumpTimeoutCmd(TestPropertyCmd): + command = BumpTimeoutCmd + propname = "LastCheckedOK" + values_to_set = [""] + + +class TestStartCheckerCmd(TestPropertyCmd): + command = StartCheckerCmd + propname = "CheckerRunning" + values_to_set = [dbus.Boolean(True)] + + +class TestStopCheckerCmd(TestPropertyCmd): + command = StopCheckerCmd + propname = "CheckerRunning" + values_to_set = [dbus.Boolean(False)] + + +class TestApproveByDefaultCmd(TestPropertyCmd): + command = ApproveByDefaultCmd + propname = "ApprovedByDefault" + values_to_set = [dbus.Boolean(True)] + + +class TestDenyByDefaultCmd(TestPropertyCmd): + command = DenyByDefaultCmd + propname = "ApprovedByDefault" + values_to_set = [dbus.Boolean(False)] + + +class TestPropertyValueCmd(TestPropertyCmd): + """Abstract class for tests of PropertyValueCmd classes""" + def runTest(self): + if type(self) is TestPropertyValueCmd: + return + return super(TestPropertyValueCmd, self).runTest() + def run_command(self, value, clients): + self.command(value).run(clients, self.bus) + + +class TestSetCheckerCmd(TestPropertyValueCmd): + command = SetCheckerCmd + propname = "Checker" + values_to_set = ["", ":", "fping -q -- %s"] + + +class TestSetHostCmd(TestPropertyValueCmd): + command = SetHostCmd + propname = "Host" + values_to_set = ["192.0.2.3", "foo.example.org"] + + +class TestSetSecretCmd(TestPropertyValueCmd): + command = SetSecretCmd + propname = "Secret" + values_to_set = [io.BytesIO(b""), + io.BytesIO(b"secret\0xyzzy\nbar")] + values_to_get = [b"", b"secret\0xyzzy\nbar"] + + +class TestSetTimeoutCmd(TestPropertyValueCmd): + command = SetTimeoutCmd + propname = "Timeout" + values_to_set = [datetime.timedelta(), + datetime.timedelta(minutes=5), + datetime.timedelta(seconds=1), + datetime.timedelta(weeks=1), + datetime.timedelta(weeks=52)] + values_to_get = [0, 300000, 1000, 604800000, 31449600000] + + +class TestSetExtendedTimeoutCmd(TestPropertyValueCmd): + command = SetExtendedTimeoutCmd + propname = "ExtendedTimeout" + values_to_set = [datetime.timedelta(), + datetime.timedelta(minutes=5), + datetime.timedelta(seconds=1), + datetime.timedelta(weeks=1), + datetime.timedelta(weeks=52)] + values_to_get = [0, 300000, 1000, 604800000, 31449600000] + + +class TestSetIntervalCmd(TestPropertyValueCmd): + command = SetIntervalCmd + propname = "Interval" + values_to_set = [datetime.timedelta(), + datetime.timedelta(minutes=5), + datetime.timedelta(seconds=1), + datetime.timedelta(weeks=1), + datetime.timedelta(weeks=52)] + values_to_get = [0, 300000, 1000, 604800000, 31449600000] + + +class TestSetApprovalDelayCmd(TestPropertyValueCmd): + command = SetApprovalDelayCmd + propname = "ApprovalDelay" + values_to_set = [datetime.timedelta(), + datetime.timedelta(minutes=5), + datetime.timedelta(seconds=1), + datetime.timedelta(weeks=1), + datetime.timedelta(weeks=52)] + values_to_get = [0, 300000, 1000, 604800000, 31449600000] + + +class TestSetApprovalDurationCmd(TestPropertyValueCmd): + command = SetApprovalDurationCmd + propname = "ApprovalDuration" + values_to_set = [datetime.timedelta(), + datetime.timedelta(minutes=5), + datetime.timedelta(seconds=1), + datetime.timedelta(weeks=1), + datetime.timedelta(weeks=52)] + values_to_get = [0, 300000, 1000, 604800000, 31449600000] + + + +def should_only_run_tests(): + parser = argparse.ArgumentParser(add_help=False) + parser.add_argument("--check", action='store_true') + args, unknown_args = parser.parse_known_args() + run_tests = args.check + if run_tests: + # Remove --check argument from sys.argv + sys.argv[1:] = unknown_args + return run_tests + +# Add all tests from doctest strings +def load_tests(loader, tests, none): + import doctest + tests.addTests(doctest.DocTestSuite()) + return tests if __name__ == "__main__": - main() + if should_only_run_tests(): + # Call using ./tdd-python-script --check [--verbose] + unittest.main() + else: + main() === modified file 'mandos-ctl.xml' --- mandos-ctl.xml 2018-02-08 10:23:55 +0000 +++ mandos-ctl.xml 2019-03-08 23:55:34 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -40,6 +40,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson @@ -61,6 +62,22 @@ &COMMANDNAME; + + + + + + + + + + + CLIENT + + + + + &COMMANDNAME; @@ -77,18 +94,10 @@ - - - - - - - - - - - - - + @@ -172,13 +175,18 @@ &COMMANDNAME; - - - - - - - + + + + + + + + + + + + CLIENT @@ -190,6 +198,7 @@ + CLIENT @@ -503,6 +512,15 @@ + + + + Show debug output; currently, this means show D-Bus calls. + + + + + @@ -580,7 +598,7 @@ -&COMMANDNAME; --timeout="5m" --interval="1m" foo1.example.org foo2.example.org +&COMMANDNAME; --timeout="PT5M" --interval="PT1M" foo1.example.org foo2.example.org === modified file 'mandos-keygen' --- mandos-keygen 2018-02-22 18:50:12 +0000 +++ mandos-keygen 2019-02-11 06:31:42 +0000 @@ -1,9 +1,9 @@ #!/bin/sh -e # -# Mandos key generator - create a new OpenPGP key for a Mandos client +# Mandos key generator - create new keys for a Mandos client # -# Copyright © 2008-2018 Teddy Hogeborn -# Copyright © 2008-2018 Björn Påhlsson +# Copyright © 2008-2019 Teddy Hogeborn +# Copyright © 2008-2019 Björn Påhlsson # # This file is part of Mandos. # @@ -23,7 +23,7 @@ # Contact the authors at . # -VERSION="1.7.19" +VERSION="1.8.3" KEYDIR="/etc/keys/mandos" KEYTYPE=RSA @@ -34,6 +34,7 @@ KEYEMAIL="" KEYCOMMENT="" KEYEXPIRE=0 +TLS_KEYTYPE=ed25519 FORCE=no SSH=yes KEYCOMMENT_ORIG="$KEYCOMMENT" @@ -44,8 +45,8 @@ fi # Parse options -TEMP=`getopt --options vhpF:d:t:l:s:L:n:e:c:x:fS \ - --longoptions version,help,password,passfile:,dir:,type:,length:,subtype:,sublength:,name:,email:,comment:,expire:,force,no-ssh \ +TEMP=`getopt --options vhpF:d:t:l:s:L:n:e:c:x:T:fS \ + --longoptions version,help,password,passfile:,dir:,type:,length:,subtype:,sublength:,name:,email:,comment:,expire:,tls-keytype:,force,no-ssh \ --name "$0" -- "$@"` help(){ @@ -63,21 +64,23 @@ -v, --version Show program's version number and exit -h, --help Show this help message and exit -d DIR, --dir DIR Target directory for key files - -t TYPE, --type TYPE Key type. Default is RSA. + -t TYPE, --type TYPE OpenPGP key type. Default is RSA. -l BITS, --length BITS - Key length in bits. Default is 4096. + OpenPGP key length in bits. Default is 4096. -s TYPE, --subtype TYPE - Subkey type. Default is RSA. + OpenPGP subkey type. Default is RSA. -L BITS, --sublength BITS - Subkey length in bits. Default is 4096. + OpenPGP subkey length in bits. Default 4096. -n NAME, --name NAME Name of key. Default is the FQDN. -e ADDRESS, --email ADDRESS - Email address of key. Default is empty. + Email address of OpenPGP key. Default empty. -c TEXT, --comment TEXT - Comment field for key. The default is empty. + Comment field for OpenPGP key. Default empty. -x TIME, --expire TIME - Key expire time. Default is no expiration. + OpenPGP key expire time. Default is none. See gpg(1) for syntax. + -T TYPE, --tls-keytype TYPE + TLS key type. Default is ed25519. -f, --force Force overwriting old key files. Password creation options: @@ -106,6 +109,7 @@ -e|--email) KEYEMAIL="$2"; shift 2;; -c|--comment) KEYCOMMENT="$2"; shift 2;; -x|--expire) KEYEXPIRE="$2"; shift 2;; + -T|--tls-keytype) TLS_KEYTYPE="$2"; shift 2;; -f|--force) FORCE=yes; shift;; -S|--no-ssh) SSH=no; shift;; -v|--version) echo "$0 $VERSION"; exit;; @@ -121,6 +125,8 @@ SECKEYFILE="$KEYDIR/seckey.txt" PUBKEYFILE="$KEYDIR/pubkey.txt" +TLS_PRIVKEYFILE="$KEYDIR/tls-privkey.pem" +TLS_PUBKEYFILE="$KEYDIR/tls-pubkey.pem" # Check for some invalid values if [ ! -d "$KEYDIR" ]; then @@ -163,7 +169,9 @@ [Nn][Oo]|[Ff][Aa][Ll][Ss][Ee]|*) FORCE=0;; esac - if { [ -e "$SECKEYFILE" ] || [ -e "$PUBKEYFILE" ]; } \ + if { [ -e "$SECKEYFILE" ] || [ -e "$PUBKEYFILE" ] \ + || [ -e "$TLS_PRIVKEYFILE" ] \ + || [ -e "$TLS_PUBKEYFILE" ]; } \ && [ "$FORCE" -eq 0 ]; then echo "Refusing to overwrite old key files; use --force" >&2 exit 1 @@ -179,6 +187,7 @@ # Create temporary gpg batch file BATCHFILE="`mktemp -t mandos-keygen-batch.XXXXXXXXXX`" + TLS_PRIVKEYTMP="`mktemp -t mandos-keygen-privkey.XXXXXXXXXX`" fi if [ "$mode" = password ]; then @@ -193,6 +202,7 @@ trap " set +e; \ test -n \"$SECFILE\" && shred --remove \"$SECFILE\"; \ +test -n \"$TLS_PRIVKEYTMP\" && shred --remove \"$TLS_PRIVKEYTMP\"; \ shred --remove \"$RINGDIR\"/sec* 2>/dev/null; test -n \"$BATCHFILE\" && rm --force \"$BATCHFILE\"; \ rm --recursive --force \"$RINGDIR\"; @@ -233,6 +243,39 @@ echo -n "Started: " date fi + + # Generate TLS private key + if certtool --generate-privkey --password='' \ + --outfile "$TLS_PRIVKEYTMP" --sec-param ultra \ + --key-type="$TLS_KEYTYPE" --pkcs8 --no-text 2>/dev/null; then + + # Backup any old key files + if cp --backup=numbered --force "$TLS_PRIVKEYFILE" "$TLS_PRIVKEYFILE" \ + 2>/dev/null; then + shred --remove "$TLS_PRIVKEYFILE" 2>/dev/null || : + fi + if cp --backup=numbered --force "$TLS_PUBKEYFILE" "$TLS_PUBKEYFILE" \ + 2>/dev/null; then + rm --force "$TLS_PUBKEYFILE" + fi + cp --archive "$TLS_PRIVKEYTMP" "$TLS_PRIVKEYFILE" + shred --remove "$TLS_PRIVKEYTMP" 2>/dev/null || : + + ## TLS public key + + # First try certtool from GnuTLS + if ! certtool --password='' --load-privkey="$TLS_PRIVKEYFILE" \ + --outfile="$TLS_PUBKEYFILE" --pubkey-info --no-text \ + 2>/dev/null; then + # Otherwise try OpenSSL + if ! openssl pkey -in "$TLS_PRIVKEYFILE" \ + -out "$TLS_PUBKEYFILE" -pubout; then + rm --force "$TLS_PUBKEYFILE" + # None of the commands succeded; give up + return 1 + fi + fi + fi # Make sure trustdb.gpg exists; # this is a workaround for Debian bug #737128 @@ -253,7 +296,7 @@ # Backup any old key files if cp --backup=numbered --force "$SECKEYFILE" "$SECKEYFILE" \ 2>/dev/null; then - shred --remove "$SECKEYFILE" + shred --remove "$SECKEYFILE" 2>/dev/null || : fi if cp --backup=numbered --force "$PUBKEYFILE" "$PUBKEYFILE" \ 2>/dev/null; then @@ -321,6 +364,19 @@ test -n "$FINGERPRINT" + if [ -r "$TLS_PUBKEYFILE" ]; then + KEY_ID="$(certtool --key-id --hash=sha256 \ + --infile="$TLS_PUBKEYFILE" 2>/dev/null || :)" + + if [ -z "$KEY_ID" ]; then + KEY_ID=$(openssl pkey -pubin -in "$TLS_PUBKEYFILE" \ + -outform der \ + | openssl sha256 \ + | sed --expression='s/^.*[^[:xdigit:]]//') + fi + test -n "$KEY_ID" + fi + FILECOMMENT="Encrypted password for a Mandos client" while [ ! -s "$SECFILE" ]; do @@ -360,6 +416,11 @@ cat <<-EOF [$KEYNAME] host = $KEYNAME + EOF + if [ -n "$KEY_ID" ]; then + echo "key_id = $KEY_ID" + fi + cat <<-EOF fingerprint = $FINGERPRINT secret = EOF @@ -383,7 +444,7 @@ set +e # Remove the password file, if any if [ -n "$SECFILE" ]; then - shred --remove "$SECFILE" + shred --remove "$SECFILE" 2>/dev/null fi # Remove the key rings shred --remove "$RINGDIR"/sec* 2>/dev/null === modified file 'mandos-keygen.xml' --- mandos-keygen.xml 2018-02-08 10:23:55 +0000 +++ mandos-keygen.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -42,6 +42,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson @@ -127,6 +128,13 @@ + + + + + @@ -180,12 +188,12 @@ DESCRIPTION &COMMANDNAME; is a program to generate the - OpenPGP key used by + TLS and OpenPGP keys used by mandos-client - 8mandos. The key is - normally written to /etc/mandos for later installation into the - initrd image, but this, and most other things, can be changed - with command line options. + 8mandos. The keys are + normally written to /etc/keys/mandos for later installation into + the initrd image, but this, and most other things, can be + changed with command line options. This program can also be used with the @@ -228,8 +236,8 @@ DIRECTORY - Target directory for key files. Default is - /etc/mandos. + Target directory for key files. Default is /etc/keys/mandos. @@ -241,7 +249,7 @@ TYPE - Key type. Default is RSA. + OpenPGP key type. Default is RSA. @@ -253,7 +261,7 @@ BITS - Key length in bits. Default is 4096. + OpenPGP key length in bits. Default is 4096. @@ -265,8 +273,7 @@ KEYTYPE - Subkey type. Default is RSA (Elgamal - encryption-only). + OpenPGP subkey type. Default is RSA @@ -278,7 +285,7 @@ BITS - Subkey length in bits. Default is 4096. + OpenPGP subkey length in bits. Default is 4096. @@ -322,6 +329,18 @@ + + + + + TLS key type. Default is ed25519 + + + + + @@ -336,8 +355,8 @@ Prompt for a password and encrypt it with the key already - present in either /etc/mandos or the - directory specified with the + present in either /etc/keys/mandos or + the directory specified with the option. Outputs, on standard output, a section suitable for inclusion in mandos-clients.confOVERVIEW - This program is a small utility to generate new OpenPGP keys for - new Mandos clients, and to generate sections for inclusion in - clients.conf on the server. + This program is a small utility to generate new TLS and OpenPGP + keys for new Mandos clients, and to generate sections for + inclusion in clients.conf on the server. @@ -423,7 +442,7 @@ - /etc/mandos/seckey.txt + /etc/keys/mandos/seckey.txt OpenPGP secret key file which will be created or @@ -432,7 +451,7 @@ - /etc/mandos/pubkey.txt + /etc/keys/mandos/pubkey.txt OpenPGP public key file which will be created or @@ -441,6 +460,22 @@ + /etc/keys/mandos/tls-privkey.pem + + + Private key file which will be created or overwritten. + + + + + /etc/keys/mandos/tls-pubkey.pem + + + Public key file which will be created or overwritten. + + + + /tmp @@ -481,9 +516,9 @@ - Prompt for a password, encrypt it with the key in /etc/mandos and output a section - suitable for clients.conf. + Prompt for a password, encrypt it with the keys in /etc/keys/mandos and output a + section suitable for clients.conf. &COMMANDNAME; --password @@ -491,7 +526,7 @@ - Prompt for a password, encrypt it with the key in the + Prompt for a password, encrypt it with the keys in the client-key directory and output a section suitable for clients.conf. === modified file 'mandos-monitor' --- mandos-monitor 2018-02-22 18:50:12 +0000 +++ mandos-monitor 2019-02-11 06:31:42 +0000 @@ -3,8 +3,8 @@ # # Mandos Monitor - Control and monitor the Mandos server # -# Copyright © 2009-2018 Teddy Hogeborn -# Copyright © 2009-2018 Björn Påhlsson +# Copyright © 2009-2019 Teddy Hogeborn +# Copyright © 2009-2019 Björn Påhlsson # # This file is part of Mandos. # @@ -59,7 +59,7 @@ domain = 'se.recompile' server_interface = domain + '.Mandos' client_interface = domain + '.Mandos.Client' -version = "1.7.19" +version = "1.8.3" try: dbus.OBJECT_MANAGER_IFACE @@ -444,7 +444,7 @@ self.clients_dict = {} # We will add Text widgets to this list - self.log = [] + self.log = urwid.SimpleListWalker([]) self.max_log_length = max_log_length self.log_level = log_level @@ -503,7 +503,7 @@ if self.max_log_length: if len(self.log) > self.max_log_length: del self.log[0:len(self.log)-self.max_log_length-1] - self.logbox.set_focus(len(self.logbox.body.contents), + self.logbox.set_focus(len(self.logbox.body.contents)-1, coming_from="above") self.refresh() === modified file 'mandos-monitor.xml' --- mandos-monitor.xml 2018-02-08 10:23:55 +0000 +++ mandos-monitor.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -40,6 +40,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson === modified file 'mandos-options.xml' --- mandos-options.xml 2015-07-20 03:03:33 +0000 +++ mandos-options.xml 2019-02-09 23:23:26 +0000 @@ -48,10 +48,11 @@ GnuTLS priority string for the TLS handshake. - The default is SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:!RSA - :+SIGN-DSA-SHA256. - See SECURE128​:!CTYPE-X.509​:+CTYPE-RAWPK​:!RSA​:!VERS-ALL​:+VERS-TLS1.3​:%PROFILE_ULTRA + when using raw public keys in TLS, and + SECURE256​:!CTYPE-X.509​:+CTYPE-OPENPGP​:!RSA​:+SIGN-DSA-SHA256 + when using OpenPGP keys in TLS,. See gnutls_priority_init 3 for the syntax. Warning: changing this may make the === modified file 'mandos-to-cryptroot-unlock' (properties changed: -x to +x) === modified file 'mandos.conf.xml' --- mandos.conf.xml 2018-02-08 10:23:55 +0000 +++ mandos.conf.xml 2019-02-10 04:20:26 +0000 @@ -3,7 +3,7 @@ "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ /etc/mandos/mandos.conf"> - + %common; ]> @@ -43,6 +43,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson === modified file 'mandos.lsm' --- mandos.lsm 2018-02-22 18:50:12 +0000 +++ mandos.lsm 2019-02-11 06:31:42 +0000 @@ -1,7 +1,7 @@ Begin4 Title: Mandos -Version: 1.7.19 -Entered-date: 2018-02-22 +Version: 1.8.3 +Entered-date: 2019-02-11 Description: The Mandos system allows computers to have encrypted root file systems and at the same time be capable of remote and/or unattended reboots. @@ -12,9 +12,9 @@ Maintained-by: teddy@recompile.se (Teddy Hogeborn), belorn@recompile.se (Björn Påhlsson) Primary-site: https://www.recompile.se/mandos - 174K mandos_1.7.19.orig.tar.gz + 182K mandos_1.8.3.orig.tar.gz Alternate-site: ftp://ftp.recompile.se/pub/mandos - 174K mandos_1.7.19.orig.tar.gz + 182K mandos_1.8.3.orig.tar.gz Platforms: Requires GCC, GNU libC, Avahi, GnuPG, Python 2.7, and various other libraries. While made for Debian GNU/Linux, it is probably portable to other === modified file 'mandos.xml' --- mandos.xml 2018-02-08 10:23:55 +0000 +++ mandos.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -42,6 +42,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson @@ -361,11 +362,11 @@ start a TLS protocol handshake with a slight quirk: the Mandos server program acts as a TLS client while the connecting Mandos client acts as a TLS server. - The Mandos client must supply an OpenPGP certificate, and the - fingerprint of this certificate is used by the Mandos server to - look up (in a list read from clients.conf - at start time) which binary blob to give the client. No other - authentication or authorization is done by the server. + The Mandos client must supply a TLS public key, and the key ID + of this public key is used by the Mandos server to look up (in a + list read from clients.conf at start time) + which binary blob to give the client. No other authentication + or authorization is done by the server. Mandos Protocol (Version 1) @@ -391,7 +392,7 @@ - OpenPGP public key (part of TLS handshake) + Public key (part of TLS handshake) -> @@ -586,10 +587,6 @@ There is no fine-grained control over logging and debug output. - - This server does not check the expire time of clients’ OpenPGP - keys. - @@ -646,12 +643,12 @@ CLIENTS The server only gives out its stored data to clients which - does have the OpenPGP key of the stored fingerprint. This is - guaranteed by the fact that the client sends its OpenPGP - public key in the TLS handshake; this ensures it to be - genuine. The server computes the fingerprint of the key - itself and looks up the fingerprint in its list of - clients. The clients.conf file (see + does have the correct key ID of the stored key ID. This is + guaranteed by the fact that the client sends its public key in + the TLS handshake; this ensures it to be genuine. The server + computes the key ID of the key itself and looks up the key ID + in its list of clients. The clients.conf + file (see mandos-clients.conf 5) must be made non-readable by anyone @@ -715,7 +712,7 @@ GnuTLS is the library this server uses to implement TLS for communicating securely with the client, and at the same time - confidently get the client’s public OpenPGP key. + confidently get the client’s public key. @@ -774,13 +771,28 @@ + RFC 7250: Using Raw Public Keys in Transport + Layer Security (TLS) and Datagram Transport Layer Security + (DTLS) + + + + This is implemented by GnuTLS version 3.6.6 and is, if + present, used by this server so that raw public keys can be + used. + + + + + RFC 6091: Using OpenPGP Keys for Transport Layer Security (TLS) Authentication - This is implemented by GnuTLS and used by this server so - that OpenPGP keys can be used. + This is implemented by GnuTLS before version 3.6.0 and is, + if present, used by this server so that OpenPGP keys can be + used. === modified file 'overview.xml' --- overview.xml 2008-09-13 15:36:18 +0000 +++ overview.xml 2019-02-09 23:23:26 +0000 @@ -8,10 +8,10 @@ program in the initial RAM disk environment which will communicate with a server over a network. All network communication is encrypted using TLS. The - clients are identified by the server using an OpenPGP key; each - client has one unique to it. The server sends the clients an - encrypted password. The encrypted password is decrypted by the - clients using the same OpenPGP key, and the password is then used to - unlock the root file system, whereupon the computers can continue - booting normally. + clients are identified by the server using a TLS key; each client + has one unique to it. The server sends the clients an encrypted + password. The encrypted password is decrypted by the clients using + a separate OpenPGP key, and the password is then used to unlock the + root file system, whereupon the computers can continue booting + normally. === modified file 'plugin-runner.c' --- plugin-runner.c 2018-08-19 01:03:28 +0000 +++ plugin-runner.c 2019-02-11 05:14:10 +0000 @@ -564,10 +564,12 @@ case '?': /* --help */ state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */ argp_state_help(state, state->out_stream, ARGP_HELP_STD_HELP); + __builtin_unreachable(); case -3: /* --usage */ state->flags &= ~(unsigned int)ARGP_NO_EXIT; /* force exit */ argp_state_help(state, state->out_stream, ARGP_HELP_USAGE | ARGP_HELP_EXIT_OK); + __builtin_unreachable(); case 'V': /* --version */ fprintf(state->out_stream, "%s\n", argp_program_version); exit(EXIT_SUCCESS); === modified file 'plugin-runner.xml' --- plugin-runner.xml 2018-02-08 10:23:55 +0000 +++ plugin-runner.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -42,6 +42,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson @@ -634,7 +635,7 @@ -cd /etc/keys/mandos; &COMMANDNAME; --config-file=/etc/mandos/plugin-runner.conf --plugin-dir /usr/lib/x86_64-linux-gnu/mandos/plugins.d --plugin-helper-dir /usr/lib/x86_64-linux-gnu/mandos/plugin-helpers --options-for=mandos-client:--pubkey=pubkey.txt,--seckey=seckey.txt +cd /etc/keys/mandos; &COMMANDNAME; --config-file=/etc/mandos/plugin-runner.conf --plugin-dir /usr/lib/x86_64-linux-gnu/mandos/plugins.d --plugin-helper-dir /usr/lib/x86_64-linux-gnu/mandos/plugin-helpers --options-for=mandos-client:--pubkey=pubkey.txt,--seckey=seckey.txt,--tls-pubkey=tls-pubkey.pem,--tls-privkey=tls-privkey.pem === modified file 'plugins.d/askpass-fifo.c' --- plugins.d/askpass-fifo.c 2018-02-08 10:23:55 +0000 +++ plugins.d/askpass-fifo.c 2019-02-11 07:06:55 +0000 @@ -2,8 +2,8 @@ /* * Askpass-FIFO - Read a password from a FIFO and output it * - * Copyright © 2008-2018 Teddy Hogeborn - * Copyright © 2008-2018 Björn Påhlsson + * Copyright © 2008-2019 Teddy Hogeborn + * Copyright © 2008-2019 Björn Påhlsson * * This file is part of Mandos. * @@ -65,10 +65,16 @@ fprintf(stderr, ": "); fprintf(stderr, "%s\n", strerror(errnum)); error(status, errno, "vasprintf while printing error"); + if(status){ + __builtin_unreachable(); + } return; } fprintf(stderr, "Mandos plugin "); error(status, errnum, "%s", text); + if(status){ + __builtin_unreachable(); + } free(text); } @@ -90,14 +96,17 @@ case ENOTDIR: case ELOOP: error_plus(EX_OSFILE, errno, "mkfifo"); + __builtin_unreachable(); case ENAMETOOLONG: case ENOSPC: case EROFS: default: error_plus(EX_OSERR, errno, "mkfifo"); + __builtin_unreachable(); case ENOENT: /* no "/lib/cryptsetup"? */ error_plus(EX_UNAVAILABLE, errno, "mkfifo"); + __builtin_unreachable(); case EEXIST: break; /* not an error */ } === modified file 'plugins.d/askpass-fifo.xml' --- plugins.d/askpass-fifo.xml 2018-02-08 10:23:55 +0000 +++ plugins.d/askpass-fifo.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -42,6 +42,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson === modified file 'plugins.d/mandos-client.c' --- plugins.d/mandos-client.c 2018-08-15 09:26:02 +0000 +++ plugins.d/mandos-client.c 2019-02-11 05:14:10 +0000 @@ -9,8 +9,8 @@ * "browse_callback", and parts of "main". * * Everything else is - * Copyright © 2008-2018 Teddy Hogeborn - * Copyright © 2008-2018 Björn Påhlsson + * Copyright © 2008-2019 Teddy Hogeborn + * Copyright © 2008-2019 Björn Påhlsson * * This file is part of Mandos. * @@ -123,9 +123,15 @@ gnutls_* init_gnutls_session(), GNUTLS_* */ +#if GNUTLS_VERSION_NUMBER < 0x030600 #include /* gnutls_certificate_set_openpgp_key_file(), GNUTLS_OPENPGP_FMT_BASE64 */ +#elif GNUTLS_VERSION_NUMBER >= 0x030606 +#include /* gnutls_pkcs_encrypt_flags_t, + GNUTLS_PKCS_PLAIN, + GNUTLS_PKCS_NULL_PASSWORD */ +#endif /* GPGME */ #include /* All GPGME types, constants and @@ -139,6 +145,8 @@ #define PATHDIR "/conf/conf.d/mandos" #define SECKEY "seckey.txt" #define PUBKEY "pubkey.txt" +#define TLS_PRIVKEY "tls-privkey.pem" +#define TLS_PUBKEY "tls-pubkey.pem" #define HOOKDIR "/lib/mandos/network-hooks.d" bool debug = false; @@ -699,7 +707,6 @@ const char *dhparamsfilename, mandos_context *mc){ int ret; - unsigned int uret; if(debug){ fprintf_plus(stderr, "Initializing GnuTLS\n"); @@ -722,18 +729,34 @@ } if(debug){ - fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and" - " secret key %s as GnuTLS credentials\n", + fprintf_plus(stderr, "Attempting to use public key %s and" + " private key %s as GnuTLS credentials\n", pubkeyfilename, seckeyfilename); } +#if GNUTLS_VERSION_NUMBER >= 0x030606 + ret = gnutls_certificate_set_rawpk_key_file + (mc->cred, pubkeyfilename, seckeyfilename, + GNUTLS_X509_FMT_PEM, /* format */ + NULL, /* pass */ + /* key_usage */ + GNUTLS_KEY_DIGITAL_SIGNATURE | GNUTLS_KEY_KEY_ENCIPHERMENT, + NULL, /* names */ + 0, /* names_length */ + /* privkey_flags */ + GNUTLS_PKCS_PLAIN | GNUTLS_PKCS_NULL_PASSWORD, + 0); /* pkcs11_flags */ +#elif GNUTLS_VERSION_NUMBER < 0x030600 ret = gnutls_certificate_set_openpgp_key_file (mc->cred, pubkeyfilename, seckeyfilename, GNUTLS_OPENPGP_FMT_BASE64); +#else +#error "Needs GnuTLS 3.6.6 or later, or before 3.6.0" +#endif if(ret != GNUTLS_E_SUCCESS){ fprintf_plus(stderr, - "Error[%d] while reading the OpenPGP key pair ('%s'," + "Error[%d] while reading the key pair ('%s'," " '%s')\n", ret, pubkeyfilename, seckeyfilename); fprintf_plus(stderr, "The GnuTLS error is: %s\n", safer_gnutls_strerror(ret)); @@ -810,6 +833,7 @@ } if(dhparamsfilename == NULL){ if(mc->dh_bits == 0){ +#if GNUTLS_VERSION_NUMBER < 0x030600 /* Find out the optimal number of DH bits */ /* Try to read the private key file */ gnutls_datum_t buffer = { .data = NULL, .size = 0 }; @@ -895,7 +919,7 @@ } } } - uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param); + unsigned int uret = gnutls_sec_param_to_pk_bits(GNUTLS_PK_DH, sec_param); if(uret != 0){ mc->dh_bits = uret; if(debug){ @@ -913,19 +937,22 @@ safer_gnutls_strerror(ret)); goto globalfail; } - } else if(debug){ - fprintf_plus(stderr, "DH bits explicitly set to %u\n", - mc->dh_bits); - } - ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits); - if(ret != GNUTLS_E_SUCCESS){ - fprintf_plus(stderr, "Error in GnuTLS prime generation (%u" - " bits): %s\n", mc->dh_bits, - safer_gnutls_strerror(ret)); - goto globalfail; +#endif + } else { /* dh_bits != 0 */ + if(debug){ + fprintf_plus(stderr, "DH bits explicitly set to %u\n", + mc->dh_bits); + } + ret = gnutls_dh_params_generate2(mc->dh_params, mc->dh_bits); + if(ret != GNUTLS_E_SUCCESS){ + fprintf_plus(stderr, "Error in GnuTLS prime generation (%u" + " bits): %s\n", mc->dh_bits, + safer_gnutls_strerror(ret)); + goto globalfail; + } + gnutls_certificate_set_dh_params(mc->cred, mc->dh_params); } } - gnutls_certificate_set_dh_params(mc->cred, mc->dh_params); return 0; @@ -942,7 +969,14 @@ int ret; /* GnuTLS session creation */ do { - ret = gnutls_init(session, GNUTLS_SERVER); + ret = gnutls_init(session, (GNUTLS_SERVER +#if GNUTLS_VERSION_NUMBER >= 0x030506 + | GNUTLS_NO_TICKETS +#endif +#if GNUTLS_VERSION_NUMBER >= 0x030606 + | GNUTLS_ENABLE_RAWPK +#endif + )); if(quit_now){ return -1; } @@ -2427,8 +2461,16 @@ int main(int argc, char *argv[]){ mandos_context mc = { .server = NULL, .dh_bits = 0, +#if GNUTLS_VERSION_NUMBER >= 0x030606 + .priority = "SECURE128:!CTYPE-X.509" + ":+CTYPE-RAWPK:!RSA:!VERS-ALL:+VERS-TLS1.3" + ":%PROFILE_ULTRA", +#elif GNUTLS_VERSION_NUMBER < 0x030600 .priority = "SECURE256:!CTYPE-X.509" ":+CTYPE-OPENPGP:!RSA:+SIGN-DSA-SHA256", +#else +#error "Needs GnuTLS 3.6.6 or later, or before 3.6.0" +#endif .current_server = NULL, .interfaces = NULL, .interfaces_size = 0 }; AvahiSServiceBrowser *sb = NULL; @@ -2445,6 +2487,10 @@ AvahiIfIndex if_index = AVAHI_IF_UNSPEC; const char *seckey = PATHDIR "/" SECKEY; const char *pubkey = PATHDIR "/" PUBKEY; +#if GNUTLS_VERSION_NUMBER >= 0x030606 + const char *tls_privkey = PATHDIR "/" TLS_PRIVKEY; + const char *tls_pubkey = PATHDIR "/" TLS_PUBKEY; +#endif const char *dh_params_file = NULL; char *interfaces_hooks = NULL; @@ -2498,7 +2544,23 @@ { .name = "pubkey", .key = 'p', .arg = "FILE", .doc = "OpenPGP public key file base name", - .group = 2 }, + .group = 1 }, + { .name = "tls-privkey", .key = 't', + .arg = "FILE", +#if GNUTLS_VERSION_NUMBER >= 0x030606 + .doc = "TLS private key file base name", +#else + .doc = "Dummy; ignored (requires GnuTLS 3.6.6)", +#endif + .group = 1 }, + { .name = "tls-pubkey", .key = 'T', + .arg = "FILE", +#if GNUTLS_VERSION_NUMBER >= 0x030606 + .doc = "TLS public key file base name", +#else + .doc = "Dummy; ignored (requires GnuTLS 3.6.6)", +#endif + .group = 1 }, { .name = "dh-bits", .key = 129, .arg = "BITS", .doc = "Bit length of the prime number used in the" @@ -2560,6 +2622,16 @@ case 'p': /* --pubkey */ pubkey = arg; break; + case 't': /* --tls-privkey */ +#if GNUTLS_VERSION_NUMBER >= 0x030606 + tls_privkey = arg; +#endif + break; + case 'T': /* --tls-pubkey */ +#if GNUTLS_VERSION_NUMBER >= 0x030606 + tls_pubkey = arg; +#endif + break; case 129: /* --dh-bits */ errno = 0; tmpmax = strtoimax(arg, &tmp, 10); @@ -2600,9 +2672,11 @@ argp_state_help(state, state->out_stream, (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR) & ~(unsigned int)ARGP_HELP_EXIT_OK); + __builtin_unreachable(); case -3: /* --usage */ argp_state_help(state, state->out_stream, ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR); + __builtin_unreachable(); case 'V': /* --version */ fprintf_plus(state->out_stream, "%s\n", argp_program_version); exit(argp_err_exit_status); @@ -2919,7 +2993,13 @@ goto end; } +#if GNUTLS_VERSION_NUMBER >= 0x030606 + ret = init_gnutls_global(tls_pubkey, tls_privkey, dh_params_file, &mc); +#elif GNUTLS_VERSION_NUMBER < 0x030600 ret = init_gnutls_global(pubkey, seckey, dh_params_file, &mc); +#else +#error "Needs GnuTLS 3.6.6 or later, or before 3.6.0" +#endif if(ret == -1){ fprintf_plus(stderr, "init_gnutls_global failed\n"); exitcode = EX_UNAVAILABLE; === modified file 'plugins.d/mandos-client.xml' --- plugins.d/mandos-client.xml 2018-02-08 10:23:55 +0000 +++ plugins.d/mandos-client.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -42,6 +42,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson @@ -95,6 +96,20 @@ FILE + + + + + + + + + + @@ -154,10 +169,10 @@ brings up network interfaces, uses the interfaces’ IPv6 link-local addresses to get network connectivity, uses Zeroconf to find servers on the local network, and communicates with - servers using TLS with an OpenPGP key to ensure authenticity and - confidentiality. This client program keeps running, trying all - servers on the network, until it receives a satisfactory reply - or a TERM signal. After all servers have been tried, all + servers using TLS with a raw public key to ensure authenticity + and confidentiality. This client program keeps running, trying + all servers on the network, until it receives a satisfactory + reply or a TERM signal. After all servers have been tried, all servers are periodically retried. If no servers are found it will wait indefinitely for new servers to appear. @@ -307,6 +322,34 @@ + + + + + TLS raw public key file name. The default name is + /conf/conf.d/mandos/tls-pubkey.pem. + + + + + + + + + + TLS secret key file name. The default name is + /conf/conf.d/mandos/tls-privkey.pem. + + + + + @@ -322,9 +365,10 @@ Sets the number of bits to use for the prime number in the TLS Diffie-Hellman key exchange. The default value is - selected automatically based on the OpenPGP key. Note - that if the option is used, - the values from that file will be used instead. + selected automatically based on the GnuTLS security + profile set in its priority string. Note that if the + option is used, the values + from that file will be used instead. @@ -682,6 +726,20 @@ + /conf/conf.d/mandos/tls-pubkey.pem + /conf/conf.d/mandos/tls-privkey.pem + + + Public and private raw key files, in PEM + format. These are the default file names, they can be + changed with the and + options. + + + + /lib/mandos/network-hooks.d @@ -729,18 +787,18 @@ - Run in debug mode, and use a custom key: + Run in debug mode, and use custom keys: -&COMMANDNAME; --debug --pubkey keydir/pubkey.txt --seckey keydir/seckey.txt +&COMMANDNAME; --debug --pubkey keydir/pubkey.txt --seckey keydir/seckey.txt --tls-pubkey keydir/tls-pubkey.pem --tls-privkey keydir/tls-privkey.pem - Run in debug mode, with a custom key, and do not use Zeroconf + Run in debug mode, with custom keys, and do not use Zeroconf to locate a server; connect directly to the IPv6 link-local address fe80::aede:48ff:fe71:f6f2, port 4711, @@ -749,7 +807,7 @@ -&COMMANDNAME; --debug --pubkey keydir/pubkey.txt --seckey keydir/seckey.txt --connect fe80::aede:48ff:fe71:f6f2:4711 --interface eth2 +&COMMANDNAME; --debug --pubkey keydir/pubkey.txt --seckey keydir/seckey.txt --tls-pubkey keydir/tls-pubkey.pem --tls-privkey keydir/tls-privkey.pem --connect fe80::aede:48ff:fe71:f6f2:4711 --interface eth2 @@ -779,12 +837,12 @@ The only remaining weak point is that someone with physical access to the client hard drive might turn off the client - computer, read the OpenPGP keys directly from the hard drive, - and communicate with the server. To safeguard against this, the - server is supposed to notice the client disappearing and stop - giving out the encrypted data. Therefore, it is important to - set the timeout and checker interval values tightly on the - server. See mandos8. @@ -850,7 +908,7 @@ GnuTLS is the library this client uses to implement TLS for communicating securely with the server, and at the same time - send the public OpenPGP key to the server. + send the public key to the server. @@ -922,13 +980,28 @@ + RFC 7250: Using Raw Public Keys in Transport + Layer Security (TLS) and Datagram Transport Layer Security + (DTLS) + + + + This is implemented by GnuTLS in version 3.6.6 and is, if + present, used by this program so that raw public keys can be + used. + + + + + RFC 6091: Using OpenPGP Keys for Transport Layer Security - This is implemented by GnuTLS and used by this program so - that OpenPGP keys can be used. + This is implemented by GnuTLS before version 3.6.0 and is, + if present, used by this program so that OpenPGP keys can be + used. === modified file 'plugins.d/password-prompt.c' --- plugins.d/password-prompt.c 2018-02-08 10:23:55 +0000 +++ plugins.d/password-prompt.c 2019-02-11 07:06:55 +0000 @@ -2,8 +2,8 @@ /* * Password-prompt - Read a password from the terminal and print it * - * Copyright © 2008-2018 Teddy Hogeborn - * Copyright © 2008-2018 Björn Påhlsson + * Copyright © 2008-2019 Teddy Hogeborn + * Copyright © 2008-2019 Björn Påhlsson * * This file is part of Mandos. * @@ -274,9 +274,11 @@ argp_state_help(state, state->out_stream, (ARGP_HELP_STD_HELP | ARGP_HELP_EXIT_ERR) & ~(unsigned int)ARGP_HELP_EXIT_OK); + __builtin_unreachable(); case -3: /* --usage */ argp_state_help(state, state->out_stream, ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR); + __builtin_unreachable(); case 'V': /* --version */ fprintf(state->out_stream, "%s\n", argp_program_version); exit(argp_err_exit_status); === modified file 'plugins.d/password-prompt.xml' --- plugins.d/password-prompt.xml 2018-02-08 10:23:55 +0000 +++ plugins.d/password-prompt.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -42,6 +42,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson === modified file 'plugins.d/plymouth.xml' --- plugins.d/plymouth.xml 2018-02-08 10:23:55 +0000 +++ plugins.d/plymouth.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -40,6 +40,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson === modified file 'plugins.d/splashy.xml' --- plugins.d/splashy.xml 2018-02-08 10:23:55 +0000 +++ plugins.d/splashy.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -42,6 +42,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson === modified file 'plugins.d/usplash.xml' --- plugins.d/usplash.xml 2018-02-08 10:23:55 +0000 +++ plugins.d/usplash.xml 2019-02-10 04:20:26 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -42,6 +42,7 @@ 2016 2017 2018 + 2019 Teddy Hogeborn Björn Påhlsson