=== modified file '.bzrignore' --- .bzrignore 2012-05-17 01:55:58 +0000 +++ .bzrignore 2010-09-30 06:24:20 +0000 @@ -3,7 +3,6 @@ *.8mandos confdir keydir -statedir man plugin-runner plugins.d/askpass-fifo === modified file 'DBUS-API' --- DBUS-API 2012-01-15 20:27:28 +0000 +++ DBUS-API 2011-03-17 18:14:34 +0000 @@ -5,7 +5,7 @@ This file documents the D-Bus interface to the Mandos server. * Bus: System bus - Bus name: "se.recompile.Mandos" + Bus name: "se.bsnet.fukt.Mandos" * Object Paths: @@ -17,7 +17,7 @@ * Mandos Server Interface: - Interface name: "se.recompile.Mandos" + Interface name: "se.bsnet.fukt.Mandos" ** Methods: *** GetAllClients() → (ao: Clients) @@ -44,7 +44,7 @@ * Mandos Client Interface: - Interface name: "se.recompile.Mandos.Client" + Interface name: "se.bsnet.fukt.Mandos.Client" ** Methods *** Approve(b: Approve) → nothing @@ -86,18 +86,15 @@ | CheckerRunning (c) | b | Read/Write | N/A | | Created (d) | s | Read | N/A | | Enabled (e) | b | Read/Write | N/A | - | Expires (f) | s | Read | N/A | - | ExtendedTimeout (a) | t | Read/Write | extended_timeout | | Fingerprint | s | Read | fingerprint | | Host | s | Read/Write | host | | Interval (a) | t | Read/Write | interval | - | LastApprovalRequest (g) | s | Read | N/A | - | LastCheckedOK (h) | s | Read/Write | N/A | - | LastCheckerStatus (i) | n | Read | N/A | - | LastEnabled (j) | s | Read | N/A | + | LastApprovalRequest (f) | s | Read | N/A | + | LastCheckedOK (g) | s | Read/Write | N/A | + | LastEnabled (h) | s | Read | N/A | | Name | s | Read | (Section name) | | ObjectPath | o | Read | N/A | - | Secret (k) | ay | Write | secret (or secfile) | + | Secret (i) | ay | Write | secret (or secfile) | | Timeout (a) | t | Read/Write | timeout | a) Represented as milliseconds. @@ -112,26 +109,20 @@ e) Setting this property is equivalent to calling Enable() or Disable(). - f) The date and time this client will be disabled, as an RFC 3339 - string, or an empty string if this is not scheduled. - - g) The date and time of the last approval request, as an RFC 3339 - string, or an empty string if this has not happened. - - h) The date and time a checker was last successful, as an RFC 3339 - string, or an empty string if this has not happened. Setting - this property is equivalent to calling CheckedOK(), i.e. the - current time is set, regardless of the string sent. Please - always use an empty string when setting this property, to allow - for possible future expansion. - - i) The exit status of the last checker, -1 if it did not exit - cleanly, -2 if a checker has not yet returned. - - j) The date and time this client was last enabled, as an RFC 3339 - string, or an empty string if this has not happened. - - k) A raw byte array, not hexadecimal digits. + f) The time of the last approval request, as an RFC 3339 string, or + an empty string if this has not happened. + + g) The last time a checker was successful, as an RFC 3339 string, + or an empty string if this has not happened. Setting this + property is equivalent to calling CheckedOK(), i.e. the current + time is set, regardless of the string sent. Please always use + an empty string when setting this property, to allow for + possible future expansion. + + h) The last time this client was enabled, as an RFC 3339 string, or + an empty string if this has not happened. + + i) A raw byte array, not hexadecimal digits. ** Signals *** CheckerCompleted(n: Exitcode, x: Waitstatus, s: Command) @@ -158,8 +149,8 @@ * Copyright - Copyright © 2010-2012 Teddy Hogeborn - Copyright © 2010-2012 Björn Påhlsson + Copyright © 2010-2011 Teddy Hogeborn + Copyright © 2010-2011 Björn Påhlsson ** License: === modified file 'INSTALL' --- INSTALL 2013-06-23 15:13:06 +0000 +++ INSTALL 2011-03-08 19:09:03 +0000 @@ -12,7 +12,7 @@ server and client programs themselves *could* be run in other distributions, but they *are* specific to GNU/Linux systems, and are not written with portabillity to other Unixes in mind. - + ** Libraries The following libraries and packages are needed. (It is possible @@ -35,7 +35,7 @@ To build just the documentation, run the command "make doc". Then the manual page "mandos.8", for example, can be read by running "man -l mandos.8". - + *** Mandos Server + GnuTLS 2.4 http://www.gnu.org/software/gnutls/ + Avahi 0.6.16 http://www.avahi.org/ @@ -51,7 +51,7 @@ Package names: python-gnutls avahi-daemon python python-avahi python-dbus python-gobject python-urwid - + *** Mandos Client + initramfs-tools 0.85i http://packages.qa.debian.org/i/initramfs-tools.html === modified file 'Makefile' --- Makefile 2014-01-21 21:04:25 +0000 +++ Makefile 2011-03-08 19:41:59 +0000 @@ -5,7 +5,7 @@ -Wbad-function-cast -Wcast-qual -Wcast-align -Wwrite-strings \ -Wconversion -Wstrict-prototypes -Wold-style-definition \ -Wpacked -Wnested-externs -Winline -Wvolatile-register-var -# -Wunreachable-code +# -Wunreachable-code #DEBUG=-ggdb3 # For info about _FORTIFY_SOURCE, see # @@ -23,20 +23,15 @@ OPTIMIZE=-Os LANGUAGE=-std=gnu99 htmldir=man -version=1.6.3 +version=1.3.0 SED=sed -USER=$(firstword $(subst :, ,$(shell getent passwd _mandos || getent passwd nobody || echo 65534))) -GROUP=$(firstword $(subst :, ,$(shell getent group _mandos || getent group nobody || echo 65534))) - ## Use these settings for a traditional /usr/local install # PREFIX=$(DESTDIR)/usr/local # CONFDIR=$(DESTDIR)/etc/mandos # KEYDIR=$(DESTDIR)/etc/mandos/keys # MANDIR=$(PREFIX)/man # INITRAMFSTOOLS=$(DESTDIR)/etc/initramfs-tools -# STATEDIR=$(DESTDIR)/var/lib/mandos -# LIBDIR=$(PREFIX)/lib ## ## These settings are for a package-type install @@ -45,20 +40,8 @@ KEYDIR=$(DESTDIR)/etc/keys/mandos MANDIR=$(PREFIX)/share/man INITRAMFSTOOLS=$(DESTDIR)/usr/share/initramfs-tools -STATEDIR=$(DESTDIR)/var/lib/mandos -LIBDIR=$(shell \ - for d in \ - "/usr/lib/`dpkg-architecture -qDEB_HOST_MULTIARCH 2>/dev/null`" \ - "`rpm --eval='%{_libdir}' 2>/dev/null`" /usr/lib; do \ - if [ -d "$$d" -a "$$d" = "$${d%/}" ]; then \ - echo "$(DESTDIR)$$d"; \ - break; \ - fi; \ - done) ## -SYSTEMD=$(DESTDIR)$(shell pkg-config systemd --variable=systemdsystemunitdir) - GNUTLS_CFLAGS=$(shell pkg-config --cflags-only-I gnutls) GNUTLS_LIBS=$(shell pkg-config --libs gnutls) AVAHI_CFLAGS=$(shell pkg-config --cflags-only-I avahi-core) @@ -68,10 +51,10 @@ getconf LFS_LDFLAGS) # Do not change these two -CFLAGS+=$(WARN) $(DEBUG) $(FORTIFY) $(COVERAGE) $(OPTIMIZE) \ +CFLAGS=$(WARN) $(DEBUG) $(FORTIFY) $(COVERAGE) $(OPTIMIZE) \ $(LANGUAGE) $(GNUTLS_CFLAGS) $(AVAHI_CFLAGS) $(GPGME_CFLAGS) \ -DVERSION='"$(version)"' -LDFLAGS+=-Xlinker --as-needed $(COVERAGE) $(LINK_FORTIFY) $(foreach flag,$(LINK_FORTIFY_LD),-Xlinker $(flag)) +LDFLAGS=$(COVERAGE) $(LINK_FORTIFY) $(foreach flag,$(LINK_FORTIFY_LD),-Xlinker $(flag)) # Commands to format a DocBook document into a manual page DOCBOOKTOMAN=$(strip cd $(dir $<); xsltproc --nonet --xinclude \ @@ -80,13 +63,9 @@ --param make.single.year.ranges 1 \ --param man.output.quietly 1 \ --param man.authors.section.enabled 0 \ - /usr/share/xml/docbook/stylesheet/nwalsh/manpages/docbook.xsl \ + /usr/share/xml/docbook/stylesheet/nwalsh/manpages/docbook.xsl \ $(notdir $<); \ - $(MANPOST) $(notdir $@);\ - if locale --all 2>/dev/null | grep --regexp='^en_US\.utf8$$' \ - && type man 2>/dev/null; then LANG=en_US.UTF-8 MANWIDTH=80 \ - man --warnings --encoding=UTF-8 --local-file $(notdir $@); \ - fi >/dev/null) + $(MANPOST) $(notdir $@)) # DocBook-to-man post-processing to fix a '\n' escape bug MANPOST=$(SED) --in-place --expression='s,\\\\en,\\en,g;s,\\n,\\en,g' @@ -113,7 +92,7 @@ plugins.d/mandos-client.8mandos \ plugins.d/password-prompt.8mandos plugins.d/usplash.8mandos \ plugins.d/splashy.8mandos plugins.d/askpass-fifo.8mandos \ - plugins.d/plymouth.8mandos intro.8mandos + plugins.d/plymouth.8mandos htmldocs=$(addsuffix .xhtml,$(DOCS)) @@ -140,11 +119,6 @@ %.8mandos.xhtml: %.xml common.ent legalnotice.xml $(DOCBOOKTOHTML) -intro.8mandos: intro.xml common.ent legalnotice.xml - $(DOCBOOKTOMAN) -intro.8mandos.xhtml: intro.xml common.ent legalnotice.xml - $(DOCBOOKTOHTML) - mandos.8: mandos.xml common.ent mandos-options.xml overview.xml \ legalnotice.xml $(DOCBOOKTOMAN) @@ -236,8 +210,8 @@ $@) plugins.d/mandos-client: plugins.d/mandos-client.c - $(LINK.c) $^ -lrt $(GNUTLS_LIBS) $(AVAHI_LIBS) $(strip\ - ) $(GPGME_LIBS) $(LOADLIBES) $(LDLIBS) -o $@ + $(LINK.c) $(GNUTLS_LIBS) $(AVAHI_LIBS) $(GPGME_LIBS) $(strip\ + ) $(COMMON) $^ $(LOADLIBES) $(LDLIBS) -o $@ .PHONY : all doc html clean distclean run-client run-server install \ install-server install-client uninstall uninstall-server \ @@ -249,11 +223,10 @@ distclean: clean mostlyclean: clean maintainer-clean: clean - -rm --force --recursive keydir confdir statedir + -rm --force --recursive keydir confdir check: all ./mandos --check - ./mandos-ctl --check # Run the client with a local config and key run-client: all keydir/seckey.txt keydir/pubkey.txt @@ -270,7 +243,7 @@ @echo "###################################################################" ./plugin-runner --plugin-dir=plugins.d \ --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 \ $(CLIENTARGS) # Used by run-client @@ -279,9 +252,14 @@ ./mandos-keygen --dir keydir --force # Run the server with a local config -run-server: confdir/mandos.conf confdir/clients.conf statedir - ./mandos --debug --no-dbus --configdir=confdir \ - --statedir=statedir $(SERVERARGS) +run-server: confdir/mandos.conf confdir/clients.conf + @echo "#################################################################" + @echo "# NOTE: Please IGNORE the error about \"Could not open file #" + @echo "# u'/var/run/mandos.pid'\" - it is harmless and is caused by #" + @echo "# the server not running as root. Do NOT run \"make run-server\" #" + @echo "# server as root if you didn't also unpack and compile it thus. #" + @echo "#################################################################" + ./mandos --debug --no-dbus --configdir=confdir $(SERVERARGS) # Used by run-server confdir/mandos.conf: mandos.conf @@ -292,8 +270,6 @@ install --mode=u=rw $< $@ # Add a client password ./mandos-keygen --dir keydir --password >> $@ -statedir: - install --directory statedir install: install-server install-client-nokey @@ -304,12 +280,6 @@ install-server: doc install --directory $(CONFDIR) - if install --directory --mode=u=rwx --owner=$(USER) \ - --group=$(GROUP) $(STATEDIR); then \ - :; \ - elif install --directory --mode=u=rwx $(STATEDIR); then \ - chown -- $(USER):$(GROUP) $(STATEDIR) || :; \ - fi install --mode=u=rwx,go=rx mandos $(PREFIX)/sbin/mandos install --mode=u=rwx,go=rx --target-directory=$(PREFIX)/sbin \ mandos-ctl @@ -323,9 +293,6 @@ $(DESTDIR)/etc/dbus-1/system.d/mandos.conf install --mode=u=rwx,go=rx init.d-mandos \ $(DESTDIR)/etc/init.d/mandos - if [ "$(SYSTEMD)" != "$(DESTDIR)" -a -d "$(SYSTEMD)" ]; then \ - install --mode=u=rw,go=r mandos.service $(SYSTEMD); \ - fi install --mode=u=rw,go=r default-mandos \ $(DESTDIR)/etc/default/mandos if [ -z $(DESTDIR) ]; then \ @@ -341,40 +308,36 @@ > $(MANDIR)/man5/mandos.conf.5.gz gzip --best --to-stdout mandos-clients.conf.5 \ > $(MANDIR)/man5/mandos-clients.conf.5.gz - gzip --best --to-stdout intro.8mandos \ - > $(MANDIR)/man8/intro.8mandos.gz install-client-nokey: all doc - install --directory $(LIBDIR)/mandos $(CONFDIR) + install --directory $(PREFIX)/lib/mandos $(CONFDIR) install --directory --mode=u=rwx $(KEYDIR) \ - $(LIBDIR)/mandos/plugins.d - if [ "$(CONFDIR)" != "$(LIBDIR)/mandos" ]; then \ + $(PREFIX)/lib/mandos/plugins.d + if [ "$(CONFDIR)" != "$(PREFIX)/lib/mandos" ]; then \ install --mode=u=rwx \ --directory "$(CONFDIR)/plugins.d"; \ fi - install --mode=u=rwx,go=rx --directory \ - "$(CONFDIR)/network-hooks.d" install --mode=u=rwx,go=rx \ - --target-directory=$(LIBDIR)/mandos plugin-runner + --target-directory=$(PREFIX)/lib/mandos plugin-runner install --mode=u=rwx,go=rx --target-directory=$(PREFIX)/sbin \ mandos-keygen install --mode=u=rwx,go=rx \ - --target-directory=$(LIBDIR)/mandos/plugins.d \ + --target-directory=$(PREFIX)/lib/mandos/plugins.d \ plugins.d/password-prompt install --mode=u=rwxs,go=rx \ - --target-directory=$(LIBDIR)/mandos/plugins.d \ + --target-directory=$(PREFIX)/lib/mandos/plugins.d \ plugins.d/mandos-client install --mode=u=rwxs,go=rx \ - --target-directory=$(LIBDIR)/mandos/plugins.d \ + --target-directory=$(PREFIX)/lib/mandos/plugins.d \ plugins.d/usplash install --mode=u=rwxs,go=rx \ - --target-directory=$(LIBDIR)/mandos/plugins.d \ + --target-directory=$(PREFIX)/lib/mandos/plugins.d \ plugins.d/splashy install --mode=u=rwxs,go=rx \ - --target-directory=$(LIBDIR)/mandos/plugins.d \ + --target-directory=$(PREFIX)/lib/mandos/plugins.d \ plugins.d/askpass-fifo install --mode=u=rwxs,go=rx \ - --target-directory=$(LIBDIR)/mandos/plugins.d \ + --target-directory=$(PREFIX)/lib/mandos/plugins.d \ plugins.d/plymouth install initramfs-tools-hook \ $(INITRAMFSTOOLS)/hooks/mandos @@ -426,13 +389,13 @@ ! grep --regexp='^ *[^ #].*keyscript=[^,=]*/mandos/' \ $(DESTDIR)/etc/crypttab -rm --force $(PREFIX)/sbin/mandos-keygen \ - $(LIBDIR)/mandos/plugin-runner \ - $(LIBDIR)/mandos/plugins.d/password-prompt \ - $(LIBDIR)/mandos/plugins.d/mandos-client \ - $(LIBDIR)/mandos/plugins.d/usplash \ - $(LIBDIR)/mandos/plugins.d/splashy \ - $(LIBDIR)/mandos/plugins.d/askpass-fifo \ - $(LIBDIR)/mandos/plugins.d/plymouth \ + $(PREFIX)/lib/mandos/plugin-runner \ + $(PREFIX)/lib/mandos/plugins.d/password-prompt \ + $(PREFIX)/lib/mandos/plugins.d/mandos-client \ + $(PREFIX)/lib/mandos/plugins.d/usplash \ + $(PREFIX)/lib/mandos/plugins.d/splashy \ + $(PREFIX)/lib/mandos/plugins.d/askpass-fifo \ + $(PREFIX)/lib/mandos/plugins.d/plymouth \ $(INITRAMFSTOOLS)/hooks/mandos \ $(INITRAMFSTOOLS)/conf-hooks.d/mandos \ $(INITRAMFSTOOLS)/scripts/init-premount/mandos \ @@ -444,8 +407,8 @@ $(MANDIR)/man8/splashy.8mandos.gz \ $(MANDIR)/man8/askpass-fifo.8mandos.gz \ $(MANDIR)/man8/plymouth.8mandos.gz \ - -rmdir $(LIBDIR)/mandos/plugins.d $(CONFDIR)/plugins.d \ - $(LIBDIR)/mandos $(CONFDIR) $(KEYDIR) + -rmdir $(PREFIX)/lib/mandos/plugins.d $(CONFDIR)/plugins.d \ + $(PREFIX)/lib/mandos $(CONFDIR) $(KEYDIR) update-initramfs -k all -u purge: purge-server purge-client @@ -455,8 +418,6 @@ $(DESTDIR)/etc/dbus-1/system.d/mandos.conf $(DESTDIR)/etc/default/mandos \ $(DESTDIR)/etc/init.d/mandos \ - $(SYSTEMD)/mandos.service \ - $(DESTDIR)/run/mandos.pid \ $(DESTDIR)/var/run/mandos.pid -rmdir $(CONFDIR) === modified file 'NEWS' --- NEWS 2014-01-21 21:04:25 +0000 +++ NEWS 2011-03-08 19:41:59 +0000 @@ -1,133 +1,6 @@ This NEWS file records noteworthy changes, very tersely. See the manual for detailed information. -Version 1.6.3 (2014-01-21) -* Server -** Add systemd support. -** For PID file, fall back to /var/run if /run does not exist. -* Client -** Moved files from /usr/lib/mandos to whatever the architecture - specifies, like /usr/lib/x86_64-linux-gnu/mandos or - /usr/lib64/mandos. - -Version 1.6.2 (2013-10-24) -* Server -** PID file moved from /var/run to /run. -** Bug fix: Handle long secrets when saving client state. -** Bug fix: Use more magic in the GnuTLS priority string to handle - both old DSA/ELG 2048-bit keys and new RSA/RSA 4096-bit keys. -* Client -** mandos-keygen: Bug fix: now generate RSA keys which GnuTLS can use. - Bug fix: Output passphrase prompts even when - redirecting standard output. - -Version 1.6.1 (2013-10-13) -* Server -** All client options for time intervals now also take an RFC 3339 - duration. The same for all options to mandos-ctl. -** Bug fix: Handle fast checkers (like ":") correctly. -** Bug fix: Don't print output from checkers when running in - foreground. -** Bug fix: Do not fail when client is removed from clients.conf but - saved settings remain. -** Bug fix: mandos-monitor now displays standout (reverse video) again - using new version of Urwid. -** Bug fix: Make boolean options work from the config file again. -** Bug fix: Make --no-ipv6 work again. -** New default priority string to be slightly more compatible with - older versions of GnuTLS. -* Client -** Bug fix: Fix bashism in mandos-keygen. -** Default key and subkey types are now RSA and RSA, respectively. - Also, new default key size is 4096 bits. - -Version 1.6.0 (2012-06-18) -* Server -** Takes new --foreground option -** Init script supports new "status" action. -* Client -** Now uses all interfaces by default; the --interface option can - still be used to restrict it, and the argument to --interface (as - well as the $DEVICE environment variable for the network hooks) is - now a comma-separated list of interfaces to use. - -Version 1.5.5 (2012-06-01) -* Server -** Server takes new --socket option - -Version 1.5.4 (2012-05-20) -* Server -** Bug fix: Regression fix: Make non-zero approval timeout values work. -** Bug fix: Regression fix: Allow changing the Timeout D-Bus property. -** Fall back to not bind to an interface if an invalid interface name - is given. -** Removed support for undocumented feature of using plain "%%s" in - "checker" client option. -** Old D-Bus interface are now marked as deprecated. -** mandos-monitor: Bug fix: show approval timers correctly. -** mandos-ctl: Show "Extended Timeout" correctly, not as milliseconds. - -Version 1.5.3 (2012-01-15) -* Server -** Add D-Bus property se.recompile.Client.LastCheckerStatus and use it - in mandos-monitor. -* Client -** Fix bugs in the example "bridge" network hook. - -Version 1.5.2 (2012-01-08) -* Server -** Removed D-Bus signal se.recompile.Mandos.NewRequest() added in - 1.5.0. It was buggy and was of questionable utility. - -Version 1.5.1 (2012-01-01) -* Server -** Include intro(8mandos) manual page, missing since migration from - README file in version 1.4.0. - -Version 1.5.0 (2012-01-01) -* Client -** Network hooks. The Mandos client can now run custom scripts to take - up a network interface before the client is run. Three example - scripts are provided: "wireless", "openvpn", and "bridge". - To facilitate this, the client now prefers network interfaces which - are up (if any) over all other interfaces. -* Server -** Persistent state. Client state is now saved between server - restarts. -** clients.conf file can now contain "enabled" setting for clients. -** Bug fix: Fix rare crash bug. -** Bug fix: Send corrent D-Bus type in PropertyChanged for - "ApprovalDelay", "ApprovalDuration", "Timeout", and - "ExtendedTimeout". -** mandos-ctl: Bare numbers as arguments are taken to be milliseconds. -** Bug fix: mandos-ctl --secret option now works. -** New D-Bus signal: se.recompile.Mandos.NewRequest(s). - -Version 1.4.1 (2011-10-15) -* Server -** Make D-Bus properties settable again, and handle checkers - for disabled clients correctly. -* Miscellaneous fixes to "pedantic" Lintian warnings - -Version 1.4.0 (2011-10-09) -* README file migrated to manual page intro(8mandos). -* Client: -** Fixed warning about "rmdir: Directory not empty". -* Server: -** Default values changed: timeout 5 minutes, interval 2 minutes. -** Clients gets an expiration extension when receiving a password, - controlled by new "extended_timeout" setting. -** New domain name: "fukt.bsnet.se" changes to "recompile.se". This - also affects the D-Bus bus and interface names (old names still - work). Users should start using the new names immediately. -** New D-Bus Client object properties "Expires" and "ExtendedTimeout"; - see DBUS-API for details. - -Version 1.3.1 (2011-07-27) -* Client: -** Client now retries all Mandos servers periodically. -** Work around Debian bug #633582 - fixes "Permission denied" problem. - Version 1.3.0 (2011-03-08) * Server: ** Updated for Python 2.6. === modified file 'README' --- README 2012-01-01 20:45:53 +0000 +++ README 2011-02-27 17:26:35 +0000 @@ -1,11 +1,182 @@ -Please see: http://www.recompile.se/mandos/man/intro.8mandos - -This information previously in this file has been moved to the -intro(8mandos) manual page. Go to the above URL, or install the -Mandos server and run this command: - - man 8mandos intro - -In short, this is the Mandos system; it allows computers to have -encrypted root file systems and at the same time be capable of remote -and/or unattended reboots. +-*- org -*- + +* Mandos + - Have your cake and eat it too! + + You know how it is. You’ve heard of it happening. The Man comes + and takes away your servers, your friends’ servers, the servers of + everybody in the same hosting facility. The servers of their + neighbors, and their neighbors’ friends. The servers of people who + owe them money. And like *that*, they’re gone. And you doubt + you’ll ever see them again. + + That is why your servers have encrypted root file systems. However, + there’s a downside. There’s no going around it: rebooting is a + pain. Dragging out that rarely-used keyboard and screen and + unraveling cables behind your servers to plug them in to type in + that password is messy, especially if you have many servers. There + are some people who do clever things like using serial line consoles + and daisy-chain it to the next server, and keep all the servers + connected in a ring with serial cables, which will work, if your + servers are physically close enough. There are also other + out-of-band management solutions, but with *all* these, you still + have to be on hand and manually type in the password at boot time. + Otherwise the server just sits there, waiting for a password. + + Wouldn’t it be great if you could have the security of encrypted + root file systems and still have servers that could boot up + automatically if there was a short power outage while you were + asleep? That you could reboot at will, without having someone run + over to the server to type in the password? + + Well, with Mandos, you (almost) can! The gain in convenience will + only be offset by a small loss in security. The setup is as + follows: + + The server will still have its encrypted root file system. The + password to this file system will be stored on another computer + (henceforth known as the Mandos server) on the same local network. + The password will *not* be stored in plaintext, but encrypted with + OpenPGP. To decrypt this password, a key is needed. This key (the + Mandos client key) will not be stored there, but back on the + original server (henceforth known as the Mandos client) in the + initial RAM disk image. Oh, and all network Mandos client/server + communications will be encrypted, using TLS (SSL). + + So, at boot time, the Mandos client will ask for its encrypted data + over the network, decrypt it to get the password, use it to decrypt + the root file, and continue booting. + + Now, of course the initial RAM disk image is not on the encrypted + root file system, so anyone who had physical access could take the + Mandos client computer offline and read the disk with their own + tools to get the authentication keys used by a client. *But*, by + then the Mandos server should notice that the original server has + been offline for too long, and will no longer give out the encrypted + key. The timing here is the only real weak point, and the method, + frequency and timeout of the server’s checking can be adjusted to + any desired level of paranoia + + (The encrypted keys on the Mandos server is on its normal file + system, so those are safe, provided the root file system of *that* + server is encrypted.) + +* FAQ - couldn’t the security be defeated by... + +** Grabbing the Mandos client key from the initrd *really quickly*? + This, as mentioned above, is the only real weak point. But if you + set the timing values tight enough, this will be really difficult + to do. An attacker would have to physically disassemble the client + computer, extract the key from the initial RAM disk image, and then + connect to a *still online* Mandos server to get the encrypted key, + and do all this *before* the Mandos server timeout kicks in and the + Mandos server refuses to give out the key to anyone. + + Now, as the typical procedure seems to be to barge in and turn off + and grab *all* computers, to maybe look at them months later, this + is not likely. If someone does that, the whole system *will* lock + itself up completely, since Mandos servers are no longer running. + + For sophisticated attackers who *could* do the clever thing, *and* + had physical access to the server for enough time, it would be + simpler to get a key for an encrypted file system by using hardware + memory scanners and reading it right off the memory bus. + +** Replay attacks? + Nope, the network stuff is all done over TLS, which provides + protection against that. + +** Man-in-the-middle? + 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. + +** Physically grabbing the Mandos server computer? + You could protect *that* computer the old-fashioned way, with a + must-type-in-the-password-at-boot method. Or you could have two + computers be the Mandos server for each other. + + Multiple Mandos servers can coexist on a network without any + trouble. They do not clash, and clients will try all available + servers. This means that if just one reboots then the other can + bring it back up, but if both reboot at the same time they will + stay down until someone types in the password on one of them. + +** Faking ping replies? + The default for the server is to use "fping", the replies to which + could be faked to eliminate the timeout. But this could easily be + changed to any shell command, with any security measures you like. + It could, for instance, be changed to an SSH command with strict + keychecking, which could not be faked. Or IPsec could be used for + the ping packets, making them secure. + +* Security Summary + So, in summary: The only weakness in the Mandos system is from + people who have: + 1. The power to come in and physically take your servers, *and* + 2. The cunning and patience to do it carefully, one at a time, and + *quickly*, faking Mandos client/server responses for each one + before the timeout. + + While there are some who may be threatened by people who have *both* + these attributes, they do not, probably, constitute the majority. + + If you *do* face such opponents, you must figure that they could + just as well open your servers and read the file system keys right + off the memory by running wires to the memory bus. + + What Mandos is designed to protect against is *not* such determined, + focused, and competent attacks, but against the early morning knock + on your door and the sudden absence of all the servers in your + server room. Which it does nicely. + +* The Plugin System + In the early designs, the mandos-client(8mandos) program (which + retrieves a password from the Mandos server) also prompted for a + password on the terminal, in case a Mandos server could not be + found. Other ways of retrieving a password could easily be + envisoned, but this multiplicity of purpose was seen to be too + complex to be a viable way to continue. Instead, the original + program was separated into mandos-client(8mandos) and + password-prompt(8mandos), and a plugin-runner(8mandos) exist to run + them both in parallel, allowing the first successful plugin to + provide the password. This opened up for any number of additional + plugins to run, all competing to be the first to find a password and + provide it to the plugin runner. + + Four additional plugins are provided: + * plymouth(8mandos) + This prompts for a password when using plymouth(8). + * usplash(8mandos) + This prompts for a password when using usplash(8). + * splashy(8mandos) + This prompts for a password when using splashy(8). + * askpass-fifo(8mandos) + To provide compatibility with the "askpass" program from + cryptsetup, this plugin listens to the same FIFO as askpass would + do. + + More plugins can easily be written and added by the system + administrator; see the section called "WRITING PLUGINS" in + plugin-runner(8mandos) to learn the plugin requirements. + +* Copyright + + Copyright © 2008-2011 Teddy Hogeborn + Copyright © 2008-2011 Björn Påhlsson + +** License: + + This program is free software: you can redistribute it and/or + modify it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see + . === modified file 'TODO' --- TODO 2014-01-20 20:54:47 +0000 +++ TODO 2010-11-16 17:58:49 +0000 @@ -1,52 +1,39 @@ -*- org -*- -* GIT -** General: [[https://www.atlassian.com/git/workflows][Git Workflows]], [[http://gitimmersion.com/][Git Immersion]], [[https://news.ycombinator.com/item?id=7036628][Simple git workflow is simple]] -** Intro: [[http://www.eyrie.org/~eagle/notes/debian/git.html#combine][Using Git for Debian Packaging]] -** Use: [[https://honk.sigxcpu.org/piki/projects/git-buildpackage/][git-buildpackage]] -** Migration - tailor? - Using bzr-fastimport: [[http://www.fusonic.net/en/blog/2013/03/26/migrating-from-bazaar-to-git/][Migrating from Bazaar to Git]] -** Unresolved: [[http://jameswestby.net/bzr/builddeb/user_manual/split.html][bzr builddeb split mode]] - Maybe: [[http://honk.sigxcpu.org/projects/git-buildpackage/manual-html/gbp.import.html#GBP.IMPORT.UPSTREAM.GIT.NOTARBALL][git-buildpackage - No upstream tarballs]] - [[http://www.python.org/dev/peps/pep-0374/][PEP 374 - Choosing a distributed VCS for the Python project]] - [[http://www.emacswiki.org/emacs/GitForEmacsDevs][Git For Emacs Devs]] - -* [[http://www.undeadly.org/cgi?action=article&sid=20110530221728][OpenBSD]] - -* Testing -** python-nemu +* Use _attribute_((nonnull)) wherever possible. * mandos-applet * mandos-client +** TODO [#B] use scandir(3) instead of readdir(3) +** TODO [#B] Prefix all debug output with "Mandos plugin " + program_invocation_short_name +** TODO [#B] Retry a server which has a non-definite reply: +*** A closed connection during the TLS handshake +*** A TCP timeout ** TODO [#B] Use capabilities instead of seteuid(). -** TODO [#B] Use struct sockaddr_storage instead of a union -** TODO [#B] Use getaddrinfo(hints=AI_NUMERICHOST) instead of inet_pton() -** TODO [#B] Use getnameinfo(serv=NULL, NI_NUMERICHOST) instead of inet_ntop() -** TODO [#B] Prefer /run/tmp over /tmp, if it exists -** TODO [#C] Make start_mandos_communication() take "struct server". +** TODO [#A] Retry --connect forever * splashy ** TODO [#B] use scandir(3) instead of readdir(3) +** TODO [#B] Prefix all debug output with "Mandos plugin " + program_invocation_short_name -* usplash (Deprecated) +* usplash ** TODO [#A] Make it work again ** TODO [#B] use scandir(3) instead of readdir(3) +** TODO [#B] Prefix all debug output with "Mandos plugin " + program_invocation_short_name +** TODO Use [[info:libc:Argz%20Functions][argz_extract]] * askpass-fifo +** TODO [#B] Prefix all debug output with "Mandos plugin " + program_invocation_short_name ** TODO [#B] Drop privileges after opening FIFO. * password-prompt +** TODO [#B] Prefix all debug output with "Mandos plugin " + program_invocation_short_name ** TODO [#B] lock stdin (with flock()?) -* plymouth - * TODO [#B] passdev * plugin-runner -** TODO handle printing for errors for plugins -*** Hook up stderr of plugins, buffer them, and prepend "Mandos Plugin [plugin name]" ** TODO [#B] use scandir(3) instead of readdir(3) ** TODO [#C] use same file name rules as run-parts(8) ** kernel command line option for debug info @@ -54,39 +41,50 @@ * mandos (server) ** TODO [#B] Log level :BUGS: +** TODO Persistent state :BUGS: + /var/lib/mandos/* *** TODO /etc/mandos/clients.d/*.conf Watch this directory and add/remove/update clients? ** TODO [#C] config for TXT record -** TODO Log level dbus option - SetLogLevel D-Bus call +** TODO Log level option + syslogger.setLevel(logging.WARNING) + + SetLogLevel D-Bus call +** TODO Implement --foreground :BUGS: + [[info:standards:Option%20Table][Table of Long Options]] +** TODO Implement --socket + [[info:standards:Option%20Table][Table of Long Options]] +** TODO Date+time on console log messages :BUGS: + Is this the default? ** TODO [#C] DBusServiceObjectUsingSuper ** TODO [#B] Global enable/disable flag -** TODO [#B] By-client countdown on number of secrets given -** D-Bus Client method NeedsPassword(50) - Timeout, default disapprove +** TODO [#B] By-client countdown on secrets given +** TODO [#B] Fix problem with fsck taking a really long time + Whenever a client successfully gets a secret it could get a + one-time timeout boost to allow for an fsck-incurred delay +** TODO [#A] Delay before client receives key + This would give an operator opportunity to cancel the request if + desired. +** TODO [#A] Client manual approval mode + A client needs manual approval on the server before it gets the + secret +** TODO [#B] Support RFC 3339 time duration syntax +** More D-Bus methods +*** NeedsApproval(50, True) -> timeout, default approve + Default approval is configurable, but True by default + + Approve(True) -> approve sending saved + + Approve(False) -> Close client connection immediately +*** NeedsPassword(50) - Timeout, default disapprove + SetPass(u"gazonk", True) -> Approval, persistent + Approve(False) -> Close client connection immediately ** TODO [#C] python-parsedatetime +** TODO [#C] systemd/launchd + http://0pointer.de/blog/projects/systemd.html ** TODO Separate logging logic to own object +** TODO make clients to a dict! ** TODO [#A] Limit approval_delay to max gnutls/tls timeout value ** TODO [#B] break the wait on approval_delay if connection dies ** TODO Generate Client.runtime_expansions from client options + extra ** TODO Allow %%(checker)s as a runtime expansion -** TODO Use python-tlslite? -** TODO D-Bus AddClient() method on server object -** TODO Use org.freedesktop.DBus.Method.NoReply annotation on async methods. :2: -** TODO Emit [[http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties][org.freedesktop.DBus.Properties.PropertiesChanged]] signal :2: - TODO Deprecate se.recompile.Mandos.Client.PropertyChanged - annotate! - TODO Can use "invalidates" annotation to also emit on changed secret. -** TODO Support [[http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager][org.freedesktop.DBus.ObjectManager]] interface on server object :2: - Deprecate methods GetAllClients(), GetAllClientsWithProperties() - and signals ClientAdded and ClientRemoved. -** TODO Save state periodically to recover better from hard shutdowns -** TODO CheckerCompleted method, deprecate CheckedOK -** TODO Secret Service API? - http://standards.freedesktop.org/secret-service/ -** TODO Remove D-Bus interfaces with old domain name :2: -** TODO Remove old string_to_delta format :2: -** TODO --no-zeroconf (only valid if port or socket is set) * mandos.xml ** Add mandos contact info in manual pages @@ -94,27 +92,31 @@ * mandos-ctl *** Handle "no D-Bus server" and/or "no Mandos server found" better *** [#B] --dump option -** TODO Remove old string_to_delta format :2: +** TODO Support RFC 3339 time duration syntax * TODO mandos-dispatch Listens for specified D-Bus signals and spawns shell commands with arguments. * mandos-monitor -** TODO help should be toggleable +** TODO help should be toggable ** Urwid client data displayer Better view of client data in the listing *** Properties popup -** Print a nice "We are sorry" message, save stack trace to log. -** Rename module "gobject" to "GObject". +** Nicer crashes. Stack traces Messes up shell. +*** Print a nice "We are sorry" message, save stack trace to log. +** Show timeout countdown for approval * mandos-keygen +** TODO Loop until passwords match when run interactively ** TODO "--secfile" option Using the "secfile" option instead of "secret" ** TODO [#B] "--test" option For testing decryption before rebooting. * Makefile +** TODO Add "--Xlinker --as-needed" + http://udrepper.livejournal.com/19395.html ** TODO [#C] Implement DEB_BUILD_OPTIONS http://www.debian.org/doc/debian-policy/ch-source.html#s-debianrules-options @@ -127,8 +129,8 @@ From XML sources directly? * Side Stuff -** TODO Locate which package moves the other bin/sh when busybox is deactivated -** TODO contact owner of package, and ask them to have that shell static in position regardless of busybox +** TODO Locate which packet move the other bin/sh when busy box is deactivated +** TODO contact owner of packet, and ask them to have that shell static in position regardless of busybox #+STARTUP: showall === modified file 'clients.conf' --- clients.conf 2012-06-23 00:58:49 +0000 +++ clients.conf 2010-09-12 03:00:40 +0000 @@ -4,19 +4,14 @@ # How long until a client is disabled and not be allowed to get the # data this server holds. -;timeout = PT5M +;timeout = 1h # How often to run the checker to confirm that a client is still up. # Note: a new checker will not be started if an old one is still # running. The server will wait for a checker to complete until the # above "timeout" occurs, at which time the client will be disabled, # and any running checker killed. -;interval = PT2M - -# Extended timeout is an added timeout that is given once after a -# password has been sent sucessfully to a client. This allows for -# additional delays caused by file system checks and quota checks. -;extended_timeout = PT15M +;interval = 5m # What command to run as "the checker". ;checker = fping -q -- %%(host)s @@ -25,13 +20,10 @@ ;approved_by_default = True # How long to wait for approval. -;approval_delay = PT0S +;approval_delay = 0s # How long one approval will last. -;approval_duration = PT1S - -# Whether this client is enabled by default -;enabled = True +;approval_duration = 1s ;#### @@ -78,10 +70,10 @@ ;host = 192.0.2.3 ; ;# Parameters from the [DEFAULT] section can be overridden per client. -;interval = PT1M +;interval = 5m ; ;# This client requires manual approval before it receives its secret. ;approved_by_default = False ;# Require approval within 30 seconds. -;approval_delay = PT30S +;approval_delay = 30s ;#### === modified file 'common.ent' --- common.ent 2014-01-21 21:04:25 +0000 +++ common.ent 2011-03-08 19:41:59 +0000 @@ -1,3 +1,3 @@ - + === modified file 'dbus-mandos.conf' --- dbus-mandos.conf 2011-10-02 19:18:24 +0000 +++ dbus-mandos.conf 2009-11-09 07:35:16 +0000 @@ -7,18 +7,12 @@ - - - - - - === modified file 'debian/changelog' --- debian/changelog 2014-01-21 21:04:25 +0000 +++ debian/changelog 2011-03-08 19:41:59 +0000 @@ -1,176 +1,3 @@ -mandos (1.6.3-1) unstable; urgency=low - - * New upstream release. - * debian/control (Build-Depends): Added "systemd". - * debian/mandos.dirs (lib/systemd/system): New. - * debian/mandos-client.README.Debian: Refer to architecture libdir. - * debian/control (mandos/Depends): Add "avahi-daemon (>= 0.6.31-3) | - systemd-sysv". - * debian/mandos.postinst: If avahi-daemon is version 0.6.31-2 or older, - edit /etc/init.d script headers Required-Start - and Required-Stop to have "avahi" instead of - "avahi-daemon", before insserv(8) sees it. - * debian/mandos-client.lintian-overrides: Libdir changes. - * debian/rules (override_dh_fixperms): - '' - - - -- Teddy Hogeborn Tue, 21 Jan 2014 22:01:30 +0100 - -mandos (1.6.2-1) unstable; urgency=low - - * New upstream release. - * debian/compat: Changed to "9". - * debian/control (Build-Depends): Changed debhelper version to (>= 9). - (Standards-Version): Updated to "3.9.4". - (DM-Upload-Allowed): Removed. - (mandos/Depends): Add "initscripts (>= 2.88dsf-13.3)" to be able to - use the "/run" directory (for mandos.pid). - * debian/copyright (Copyright): Update year. - * Fix "Mandos/gnutls fails to establish connection, "an algorithm that - is not enabled was negotiated"" fixed by upstream. (Closes: #702120) - - -- Teddy Hogeborn Thu, 24 Oct 2013 22:33:40 +0200 - -mandos (1.6.1-1) unstable; urgency=low - - * New upstream release. - * debian/control (mandos/Depends): No longer depends on - python-gnupginterface, but does - depend on gnupg (<< 2). - (Build-Depends): Depend on debhelper 8.9.7 for using "override-*-arch" - and "override-*-indep" targets in debian/rules. - * debian/mandos-client.README: Update Linux documentation link. - * debian/rules: Completely rewritten to use debhelper v7. - * initramfs-tools-hook: Bug fix: Make sure the right version of GnuPG is - copied into the initramfs image. Always assume that GPGME is used to - avoid searching for it since the path might not be /usr/lib. Thanks - to Félix Sipma for the initial bug report, - and also thanks to Dick Middleton for some more - debugging. (Closes: #721903) - * Fix "bashism in /bin/sh script" fixed by upstream. (Closes: #690639) - - -- Teddy Hogeborn Sun, 13 Oct 2013 19:03:23 +0200 - -mandos (1.6.0-1) unstable; urgency=low - - * New upstream release. - * debian/copyright (Copyright): Join the two lines to a single line. - * debian/mandos-client.README.Debian: Update to refer to the new - location of the example network hooks, and the new feature of using - all network interfaces. - * debian/mandos-client.docs (network-hooks.d): Removed. - * debian/mandos-client.examples (network-hooks.d): New. - * debian/rules (binary-common): Added "dh_installexamples". - (binary-common/dh_fixperms): Exclude new location of - "network-hooks.d". - - -- Teddy Hogeborn Mon, 18 Jun 2012 00:15:23 +0200 - -mandos (1.5.5-1) unstable; urgency=low - - * New upstream release. - * debian/copyright (Format): Updated to - "http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/". - * debian/control (Build-Depends): Removed "man, locales-all". - - -- Teddy Hogeborn Fri, 01 Jun 2012 20:30:41 +0200 - -mandos (1.5.4-1) unstable; urgency=low - - * New upstream release. - - -- Teddy Hogeborn Sun, 20 May 2012 15:38:34 +0200 - -mandos (1.5.3-1.2) unstable; urgency=low - - * Non-maintainer upload. - * Set Architecture to linux-any. (Closes: #647670) - - -- Robert Millan Sun, 22 Apr 2012 16:22:01 +0200 - -mandos (1.5.3-1.1) unstable; urgency=low - - * Non-maintainer upload. - * Fix "mandos FTBFS on buildds": add build-dependency on locales-all and - pass LC_ALL to dh_auto_build to make sure we have and use the en_US.UTF-8 - locale for manpage creation. - (Closes: #656178) - - -- gregor herrmann Tue, 31 Jan 2012 17:56:05 +0100 - -mandos (1.5.3-1) unstable; urgency=low - - * New upstream release. - - -- Teddy Hogeborn Sun, 15 Jan 2012 22:05:54 +0100 - -mandos (1.5.2-1) unstable; urgency=low - - * New upstream release. - - -- Teddy Hogeborn Sun, 08 Jan 2012 11:17:20 +0100 - -mandos (1.5.1-1) unstable; urgency=low - - * New upstream release. - - -- Teddy Hogeborn Sun, 01 Jan 2012 21:53:31 +0100 - -mandos (1.5.0-1) unstable; urgency=low - - * New upstream release. - * debian/control (mandos-client/Depends): Added "initramfs-tools". - * debian/mandos-client.README.Debian: Corrected mail address and adjust - wording. - * debian/rules (binary-common): Exclude new nework-hooks.d directory - from dh_fixperms. - * debian/mandos-client.README.Debian: Document network hook facility. - * debian/mandos-client.docs (network-hooks.d): Added. - * debian/mandos.dirs (var/lib/mandos): Added. - * debian/mandos.postinst: Fix ownership of /var/lib/mandos. - * debian/control (mandos/Depends): Added "python-gnupginterface". - - -- Teddy Hogeborn Sun, 01 Jan 2012 05:58:11 +0100 - -mandos (1.4.1-1) unstable; urgency=low - - * New upstream release. - * debian/control (Build-Depends): Added "man". - * debian/control (Conflicts): Changed to "Breaks:". - * debian/copyright: Updated format. - * debian/mandos-client.postinst: Use "set -e" instead of "#!/bin/sh -e". - * debian/mandos-client.postrm: - '' - - * debian/mandos.postinst: - '' - - * debian/mandos.prerm: Consistent magic. - - -- Björn Påhlsson Sat, 15 Oct 2011 18:18:52 +0200 - -mandos (1.4.0-1) unstable; urgency=low - - * New upstream release. - * Fix "FTBFS with binutils-gold": Added "-Xlinker --as-needed" to - LDFLAGS in Makefile. (Closes: #632145) - * Fix "/run transition: uses obsolete /dev/.initramfs": Try both old and - new PID file locations. (Closes: #643554) - * debian/source/local-options: New; contains "--single-debian-patch". - * debian/control (Standards-Version): Upgraded to "3.9.2". - (DM-Upload-Allowed): New; set to "yes". - * debian/control: Changed domain from "fukt.bsnet.se" to "recompile.se". - * debian/copyright: - '' - - * debian/mandos-client.README.Debian: - '' - - * debian/mandos.README.Debian: - '' - - * debian/watch: - '' - - * debian/control (mandos/Description): Fix language to placate lintian. - - -- Teddy Hogeborn Sun, 09 Oct 2011 19:15:08 +0200 - -mandos (1.3.1-1) unstable; urgency=low - - * New upstream release. - * Conflict with correct version of dropbear. - * New version uses argparse; depend on python (<=2.7) | python-argparse. - - -- Teddy Hogeborn Wed, 27 Jul 2011 19:47:17 +0200 - mandos (1.3.0-1) unstable; urgency=low * New upstream release. === modified file 'debian/compat' --- debian/compat 2013-10-20 15:25:09 +0000 +++ debian/compat 2008-09-17 00:34:09 +0000 @@ -1,1 +1,1 @@ -9 +7 === modified file 'debian/control' --- debian/control 2014-02-16 02:42:42 +0000 +++ debian/control 2011-03-17 18:13:40 +0000 @@ -1,27 +1,24 @@ Source: mandos Section: admin Priority: extra -Maintainer: Mandos Maintainers -Uploaders: Teddy Hogeborn , - Björn Påhlsson -Build-Depends: debhelper (>= 9), docbook-xml, docbook-xsl, +Maintainer: Mandos Maintainers +Uploaders: Teddy Hogeborn , + Björn Påhlsson +Build-Depends: debhelper (>= 7), docbook-xml, docbook-xsl, libavahi-core-dev, libgpgme11-dev, libgnutls-dev, xsltproc, - pkg-config, systemd, python (>=2.6), python-gnutls, python-dbus, - python-avahi, python-gobject, python (>=2.7) | python-argparse -Standards-Version: 3.9.4 -Vcs-Bzr: http://ftp.recompile.se/pub/mandos/trunk -Vcs-Browser: http://bzr.recompile.se/loggerhead/mandos/trunk/files -Homepage: http://www.recompile.se/mandos + pkg-config +Standards-Version: 3.9.1 +Vcs-Bzr: http://ftp.fukt.bsnet.se/pub/mandos/trunk +Vcs-Browser: http://bzr.fukt.bsnet.se/loggerhead/mandos/trunk/files +Homepage: http://www.fukt.bsnet.se/mandos Package: mandos Architecture: all Depends: ${misc:Depends}, python (>=2.6), python-gnutls, python-dbus, python-avahi, python-gobject, avahi-daemon, adduser, - python-urwid, python (>=2.7) | python-argparse, gnupg (<< 2), - initscripts (>= 2.88dsf-13.3), avahi-daemon (>= 0.6.31-3) - | systemd-sysv + python-urwid, python (>=2.7) | python-argparse Recommends: fping -Description: server giving encrypted passwords to Mandos clients +Description: a 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 same time be capable of remote and/or unattended reboots. @@ -37,10 +34,10 @@ whereupon the computers can continue booting normally. Package: mandos-client -Architecture: linux-any +Architecture: any Depends: ${shlibs:Depends}, ${misc:Depends}, adduser, cryptsetup, - gnupg (<< 2), initramfs-tools -Breaks: dropbear (<= 0.53.1-1) + gnupg (<< 2) +Conflicts: dropbear (<= 0.52-5) Enhances: cryptsetup Description: do unattended reboots with an encrypted root file system This is the client part of the Mandos system, which allows === modified file 'debian/copyright' --- debian/copyright 2014-02-16 02:42:42 +0000 +++ debian/copyright 2011-02-27 17:26:35 +0000 @@ -1,11 +1,12 @@ -Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Format-Specification: + http://wiki.debian.org/Proposals/CopyrightFormat?action=recall&rev=233 Upstream-Name: Mandos -Upstream-Contact: Mandos -Source: +Upstream-Maintainer: Mandos Maintainers +Upstream-Source: Files: * -Copyright: Copyright © 2008-2013 Teddy Hogeborn - Copyright © 2008-2013 Björn Påhlsson +Copyright: Copyright © 2008-2011 Teddy Hogeborn +Copyright: Copyright © 2008-2011 Björn Påhlsson License: GPL-3+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as @@ -22,4 +23,4 @@ . . On Debian systems, the complete text of the GNU General Public - License can be found in "/usr/share/common-licenses/GPL-3". + License can be found in "/usr/share/common-licenses/GPL". === modified file 'debian/mandos-client.README.Debian' --- debian/mandos-client.README.Debian 2013-10-28 10:04:05 +0000 +++ debian/mandos-client.README.Debian 2010-09-27 17:53:53 +0000 @@ -1,3 +1,25 @@ +* Choose the Client Network Interface + + Please make sure that the correct network interface is specified in + the DEVICE setting in the "/etc/initramfs-tools/initramfs.conf" + file. If the setting is empty, the interface will be autodetected + at boot time, which may not be correct. *If* the DEVICE setting is + changed, it will be necessary to update the initrd image by running + the command + + update-initramfs -k all -u + + The device can be overridden at boot time on the Linux kernel + command line using the sixth colon-separated field of the "ip=" + option; for exact syntax, read the documentation in the file + "/usr/share/doc/linux-doc-*/Documentation/filesystems/nfsroot.txt", + available in the "linux-doc-*" package. + + Note that since this network interface is used in the initial RAM + disk environment, the network interface *must* exist at that stage. + Thus, the interface can *not* be a pseudo-interface such as "br0" or + "tun0"; instead, a real interface (such as "eth0") must be used. + * Adding a Client Password to the Server The server must be given a password to give back to the client on @@ -16,8 +38,7 @@ is possible to verify that the correct password will be received by this client by running the command, on the client: - /usr/lib/$(dpkg-architecture -qDEB_HOST_MULTIARCH \ - )/mandos/plugins.d/mandos-client \ + /usr/lib/mandos/plugins.d/mandos-client \ --pubkey=/etc/keys/mandos/pubkey.txt \ --seckey=/etc/keys/mandos/seckey.txt; echo @@ -25,40 +46,6 @@ it, and output it to standard output. There it can be verified to be the correct password, before rebooting. -* Emergency Escape - - If it ever should be necessary, the Mandos client can be temporarily - prevented from running at startup by passing the parameter - "mandos=off" to the kernel. - -* Specifying a Client Network Interface - - At boot time the network interfaces to use will by default be - automatically detected. If this should result in incorrect - interfaces, edit the DEVICE setting in the - "/etc/initramfs-tools/initramfs.conf" file. (The default setting is - empty, meaning it will autodetect the interface.) *If* the DEVICE - setting is changed, it will be necessary to update the initrd image - by running the command - - update-initramfs -k all -u - - The device can also be overridden at boot time on the Linux kernel - command line using the sixth colon-separated field of the "ip=" - option; for exact syntax, read the documentation in the file - "/usr/share/doc/linux-doc-*/Documentation/filesystems/nfs/nfsroot.txt", - available in the "linux-doc-*" package. - - Note that since the network interfaces are used in the initial RAM - disk environment, the network interfaces *must* exist at that stage. - Thus, an interface can *not* be a pseudo-interface such as "br0" or - "tun0"; instead, only real interfaces (such as "eth0") can be used. - This can be overcome by writing a "network hook" program to create - an interface (see mandos-client(8mandos)) and placing it in - "/etc/mandos/network-hooks.d", from where it will be copied into the - initial RAM disk. Example network hook scripts can be found in - "/usr/share/doc/mandos-client/examples/network-hooks.d". - * User-Supplied Plugins Any plugins found in "/etc/mandos/plugins.d" will override and add @@ -75,14 +62,19 @@ Mandos client will be the new default way for getting a password for the root file system when booting. +* Emergency Escape + + If it ever should be necessary, the Mandos client can be temporarily + prevented from running at startup by passing the parameter + "mandos=off" to the kernel. + * Non-local Connection (Not Using ZeroConf) If the "ip=" kernel command line option is used to specify a complete IP address and device name, as noted above, it then becomes possible to specify a specific IP address and port to connect to, instead of using ZeroConf. The syntax for doing this is - "mandos=connect::" on the kernel command - line. + "mandos=connect::". For very advanced users, it it possible to specify simply "mandos=connect" on the kernel command line to make the system only @@ -91,4 +83,4 @@ work, "--options-for=mandos-client:--connect=
:" needs to be manually added to the file "/etc/mandos/plugin-runner.conf". - -- Teddy Hogeborn , Mon, 28 Oct 2013 11:02:26 +0100 + -- Teddy Hogeborn , Mon, 27 Sep 2010 19:53:21 +0200 === removed file 'debian/mandos-client.examples' --- debian/mandos-client.examples 2012-06-01 21:48:12 +0000 +++ debian/mandos-client.examples 1970-01-01 00:00:00 +0000 @@ -1,1 +0,0 @@ -network-hooks.d === modified file 'debian/mandos-client.lintian-overrides' --- debian/mandos-client.lintian-overrides 2014-01-20 21:50:11 +0000 +++ debian/mandos-client.lintian-overrides 2010-10-13 06:12:52 +0000 @@ -2,12 +2,12 @@ # mandos-client binary: non-standard-dir-perm etc/keys/mandos/ 0700 != 0755 -# The directory /usr/lib//mandos/plugins.d contains setuid -# binaries which are not meant to be run outside an initial RAM disk +# The directory /usr/lib/mandos/plugins.d contains setuid binaries +# which are not meant to be run outside an initial RAM disk # environment (except for test purposes). It would be insecure to # allow anyone to run them. # -mandos-client binary: non-standard-dir-perm usr/lib/*/mandos/plugins.d/ 0700 != 0755 +mandos-client binary: non-standard-dir-perm usr/lib/mandos/plugins.d/ 0700 != 0755 # These binaries must be setuid root, since they need root powers, but # are started by plugin-runner(8mandos), which runs all plugins as @@ -15,14 +15,14 @@ # system, but in an initial RAM disk environment. Here they are # protected from non-root access by the directory permissions, above. # -mandos-client binary: setuid-binary usr/lib/*/mandos/plugins.d/mandos-client 4755 root/root -mandos-client binary: setuid-binary usr/lib/*/mandos/plugins.d/askpass-fifo 4755 root/root -mandos-client binary: setuid-binary usr/lib/*/mandos/plugins.d/splashy 4755 root/root -mandos-client binary: setuid-binary usr/lib/*/mandos/plugins.d/usplash 4755 root/root -mandos-client binary: setuid-binary usr/lib/*/mandos/plugins.d/plymouth 4755 root/root +mandos-client binary: setuid-binary usr/lib/mandos/plugins.d/mandos-client 4755 root/root +mandos-client binary: setuid-binary usr/lib/mandos/plugins.d/askpass-fifo 4755 root/root +mandos-client binary: setuid-binary usr/lib/mandos/plugins.d/splashy 4755 root/root +mandos-client binary: setuid-binary usr/lib/mandos/plugins.d/usplash 4755 root/root +mandos-client binary: setuid-binary usr/lib/mandos/plugins.d/plymouth 4755 root/root # The directory /etc/mandos/plugins.d can be used by local system # administrators to place plugins in, overriding and complementing -# /usr/lib//mandos/plugins.d, and must be likewise protected. +# /usr/lib/mandos/plugins.d, and must be likewise protected. # mandos-client binary: non-standard-dir-perm etc/mandos/plugins.d/ 0700 != 0755 === modified file 'debian/mandos-client.postinst' --- debian/mandos-client.postinst 2011-10-10 20:29:58 +0000 +++ debian/mandos-client.postinst 2009-05-24 23:36:15 +0000 @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/sh -e # This script can be called in the following ways: # # After the package was installed: @@ -15,8 +15,6 @@ # If prerm fails during replacement due to conflict: # abort-remove in-favour -set -e - # Update the initial RAM file system image update_initramfs() { === modified file 'debian/mandos-client.postrm' --- debian/mandos-client.postrm 2011-10-10 20:29:58 +0000 +++ debian/mandos-client.postrm 2011-02-27 17:00:41 +0000 @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/sh -e # This script can be called in the following ways: # # After the package was removed: @@ -26,7 +26,6 @@ # If preinst fails during upgrade: # abort-upgrade -set -e # Update the initial RAM file system image update_initramfs() === modified file 'debian/mandos.README.Debian' --- debian/mandos.README.Debian 2011-10-05 16:00:56 +0000 +++ debian/mandos.README.Debian 2009-09-08 06:28:20 +0000 @@ -1,10 +1,10 @@ The Mandos server is useless without at least one configured client in /etc/mandos/clients.conf. To create one, install the "mandos-client" -package on a client computer, and, on the client, run the command +package on a client computer, and run the command # mandos-keygen --password -to get a config file stanza. Append the output of that command to the -file "/etc/mandos/clients.conf" on the Mandos server computer. +there to get a config file stanza. Append the output of that command +to the file "/etc/mandos/clients.conf" on the Mandos server. - -- Teddy Hogeborn , Wed, 5 Oct 2011 17:51:22 +0200 + -- Teddy Hogeborn , Tue, 8 Sep 2009 06:57:45 +0200 === modified file 'debian/mandos.dirs' --- debian/mandos.dirs 2013-10-27 17:42:23 +0000 +++ debian/mandos.dirs 2010-09-15 17:33:14 +0000 @@ -4,5 +4,3 @@ etc/default etc/dbus-1/system.d usr/sbin -var/lib/mandos -lib/systemd/system === modified file 'debian/mandos.postinst' --- debian/mandos.postinst 2014-01-06 17:22:30 +0000 +++ debian/mandos.postinst 2009-05-24 23:28:04 +0000 @@ -1,4 +1,4 @@ -#!/bin/sh +#!/bin/sh -e # This script can be called in the following ways: # # After the package was installed: @@ -15,8 +15,6 @@ # If prerm fails during replacement due to conflict: # abort-remove in-favour -set -e - case "$1" in configure) # Rename old "mandos" user and group @@ -35,28 +33,17 @@ --disabled-password --gecos "Mandos password system" \ _mandos fi - chown _mandos:_mandos /var/lib/mandos ;; - + abort-upgrade|abort-deconfigure|abort-remove) ;; - + *) echo "$0 called with unknown argument '$1'" 1>&2 exit 1 ;; esac -# Avahi version 0.6.31-2 and older provides "avahi" (instead of -# "avahi-daemon") in its /etc/init.d script header. To make -# insserv(8) happy, we edit our /etc/init.d script header to contain -# the correct string before the code added by dh_installinit calls -# update.rd-c, which calls insserv. -avahi_version="`dpkg-query --showformat='${Version}' --show avahi-daemon`" -if dpkg --compare-versions "$avahi_version" le 0.6.31-2; then - sed --in-place --expression='/^### BEGIN INIT INFO$/,/^### END INIT INFO$/s/^\(# Required-\(Stop\|Start\):.*avahi\)-daemon\>/\1/g' /etc/init.d/mandos -fi - #DEBHELPER# exit 0 === modified file 'debian/mandos.prerm' --- debian/mandos.prerm 2011-10-10 20:29:58 +0000 +++ debian/mandos.prerm 2009-01-18 00:16:57 +0000 @@ -1,4 +1,4 @@ -#!/bin/sh +#! /bin/sh # prerm script for mandos # # see: dh_installdeb(1) === modified file 'debian/rules' --- debian/rules 2014-01-20 21:50:11 +0000 +++ debian/rules 2010-09-09 18:16:14 +0000 @@ -1,29 +1,106 @@ #!/usr/bin/make -f -%: - dh $@ - -override_dh_auto_build-arch: - LC_ALL=en_US.utf8 dh_auto_build -- all doc - -override_dh_auto_build-indep: - LC_ALL=en_US.utf8 dh_auto_build -- doc - -override_dh_installinit-indep: +# Sample debian/rules that uses debhelper. +# +# This file was originally written by Joey Hess and Craig Small. +# As a special exception, when this file is copied by dh-make into a +# dh-make output file, you may use that output file without restriction. +# This special exception was added by Craig Small in version 0.37 of dh-make. +# +# Modified to make a template file for a multi-binary package with separated +# build-arch and build-indep targets by Bill Allombert 2001 + +# Uncomment this to turn on verbose mode. +#export DH_VERBOSE=1 + +# This has to be exported to make some magic below work. +export DH_OPTIONS + +# -pie was broken briefly on the mips and mipsel architectures, see +# +BINUTILS_V := $(shell dpkg-query --showformat='$${Version}' \ + --show binutils) +ifeq (yes,$(shell dpkg --compare-versions $(BINUTILS_V) lt 2.20-3 \ + && dpkg --compare-versions $(BINUTILS_V) ge 2.19.1-1 \ + && echo yes)) + ifneq (,$(strip $(findstring :$(DEB_HOST_ARCH):,:mips:mipsel:) \ + $(findstring :$(DEB_BUILD_ARCH):,:mips:mipsel:))) + BROKEN_PIE := yes + export BROKEN_PIE + endif +endif + +configure: configure-stamp +configure-stamp: + dh_testdir + touch configure-stamp + +build: build-arch build-indep + +build-arch: build-arch-stamp +build-arch-stamp: configure-stamp + dh_auto_build -- all doc + touch $@ + +build-indep: build-indep-stamp +build-indep-stamp: configure-stamp + dh_auto_build -- doc + touch $@ + +clean: + dh_testdir + dh_testroot + rm -f build-arch-stamp build-indep-stamp configure-stamp + dh_auto_clean + dh_clean + +install: install-indep install-arch +install-indep: + dh_testdir + dh_testroot + dh_prep + dh_installdirs --indep + $(MAKE) DESTDIR=$(CURDIR)/debian/mandos install-server + dh_lintian dh_installinit --onlyscripts \ --update-rcd-params="defaults 25 15" - -override_dh_auto_install-indep: - $(MAKE) DESTDIR=$(CURDIR)/debian/mandos install-server - -override_dh_auto_install-arch: - $(MAKE) DESTDIR=$(CURDIR)/debian/mandos-client \ - install-client-nokey - -override_dh_fixperms: + dh_install --indep + +install-arch: + dh_testdir + dh_testroot + dh_prep + dh_installdirs --same-arch + $(MAKE) DESTDIR=$(CURDIR)/debian/mandos-client install-client-nokey + dh_lintian + dh_install --same-arch + +binary-common: + dh_testdir + dh_testroot + dh_installchangelogs + dh_installdocs + dh_link + dh_strip + dh_compress dh_fixperms --exclude etc/keys/mandos \ --exclude etc/mandos/clients.conf \ --exclude etc/mandos/plugins.d \ - --exclude usr/lib/$(shell dpkg-architecture -qDEB_HOST_MULTIARCH 2>/dev/null)/mandos/plugins.d \ - --exclude usr/share/doc/mandos-client/examples/network-hooks.d - chmod --recursive g-w -- \ - "$(CURDIR)/debian/mandos-client/usr/share/doc/mandos-client/examples/network-hooks.d" + --exclude usr/lib/mandos/plugins.d + dh_installdeb + dh_shlibdeps + dh_gencontrol + dh_md5sums + dh_builddeb + +# Build architecture independant packages using the common target. +binary-indep: build-indep install-indep + $(MAKE) -f debian/rules DH_OPTIONS=--indep binary-common + +# Build architecture dependant packages using the common target. +binary-arch: build-arch install-arch + $(MAKE) -f debian/rules DH_OPTIONS=--same-arch binary-common + +binary: binary-arch binary-indep + +.PHONY: build clean binary-indep binary-arch binary install \ + install-indep install-arch configure === removed file 'debian/source/local-options' --- debian/source/local-options 2011-10-08 21:13:46 +0000 +++ debian/source/local-options 1970-01-01 00:00:00 +0000 @@ -1,1 +0,0 @@ ---single-debian-patch === modified file 'debian/watch' --- debian/watch 2014-02-16 02:42:42 +0000 +++ debian/watch 2010-09-15 17:17:46 +0000 @@ -1,3 +1,2 @@ version=3 -opts=pgpsigurlmangle=s/$/.asc/ \ - ftp://ftp.recompile.se/pub/mandos/mandos[-_]([^\s]+?)(?:\.orig)?\.tar\.(?:gz|bz2|7z|xz) +ftp://ftp.fukt.bsnet.se/pub/mandos/mandos[-_]([^\s]+?)(?:\.orig)?\.tar\.(?:gz|bz2|7z|xz) === modified file 'init.d-mandos' --- init.d-mandos 2014-01-06 15:56:54 +0000 +++ init.d-mandos 2009-09-16 23:28:39 +0000 @@ -1,16 +1,16 @@ #! /bin/sh ### BEGIN INIT INFO # Provides: mandos -# Required-Start: $remote_fs $syslog avahi-daemon -# Required-Stop: $remote_fs $syslog avahi-daemon +# Required-Start: $remote_fs $syslog avahi +# Required-Stop: $remote_fs $syslog avahi # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Short-Description: Mandos server -# Description: Server of encrypted passwords to Mandos clients +# Description: Gives encrypted passwords to Mandos clients ### END INIT INFO -# Author: Teddy Hogeborn -# Author: Björn Påhlsson +# Author: Teddy Hogeborn +# Author: Björn Påhlsson # # Please remove the "Author" lines above and replace them # with your own name if you copy and modify this script. @@ -23,11 +23,7 @@ NAME=mandos DAEMON=/usr/sbin/$NAME DAEMON_ARGS="" -if [ -d /run/. ]; then - PIDFILE=/run/$NAME.pid -else - PIDFILE=/var/run/$NAME.pid -fi +PIDFILE=/var/run/$NAME.pid SCRIPTNAME=/etc/init.d/$NAME # Exit if the package is not installed @@ -44,8 +40,7 @@ . /lib/init/vars.sh # Define LSB log_* functions. -# Depend on lsb-base (>= 3.2-14) to ensure that this file is present -# and status_of_proc is working. +# Depend on lsb-base (>= 3.0-6) to ensure that this file is present. . /lib/lsb/init-functions # @@ -123,9 +118,6 @@ 2) [ "$VERBOSE" != no ] && log_end_msg 1 ;; esac ;; - status) - status_of_proc "$DAEMON" "$NAME" -p "$PIDFILE" && exit 0 || exit $? - ;; #reload|force-reload) # # If do_reload() is not implemented then leave this commented out @@ -152,14 +144,14 @@ esac ;; *) - # Failed to stop + # Failed to stop log_end_msg 1 ;; esac ;; *) #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2 - echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2 + echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2 exit 3 ;; esac === modified file 'initramfs-tools-hook' --- initramfs-tools-hook 2013-10-28 08:38:47 +0000 +++ initramfs-tools-hook 2010-09-09 18:16:14 +0000 @@ -3,7 +3,7 @@ # This script will be run by 'mkinitramfs' when it creates the image. # Its job is to decide which files to install, then install them into # the staging area, where the initramfs is being created. This -# happens when a new 'linux-image' package is installed, or when an +# happens when a new 'linux-image' package is installed, or when the # administrator runs 'update-initramfs' by hand to update an initramfs # image. @@ -29,15 +29,13 @@ . /usr/share/initramfs-tools/hook-functions -for d in /usr/lib \ - "/usr/lib/`dpkg-architecture -qDEB_HOST_MULTIARCH 2>/dev/null`" \ - "`rpm --eval='%{_libdir}' 2>/dev/null`" /usr/local/lib; do - if [ -d "$d"/mandos ]; then - libdir="$d" +for d in /usr /usr/local; do + if [ -d "$d"/lib/mandos ]; then + prefix="$d" break fi done -if [ -z "$libdir" ]; then +if [ -z "$prefix" ]; then # Mandos not found exit 1 fi @@ -70,21 +68,20 @@ CONFDIR="/conf/conf.d/mandos" MANDOSDIR="/lib/mandos" PLUGINDIR="${MANDOSDIR}/plugins.d" -HOOKDIR="${MANDOSDIR}/network-hooks.d" # Make directories install --directory --mode=u=rwx,go=rx "${DESTDIR}${CONFDIR}" \ - "${DESTDIR}${MANDOSDIR}" "${DESTDIR}${HOOKDIR}" + "${DESTDIR}${MANDOSDIR}" install --owner=${mandos_user} --group=${mandos_group} --directory \ --mode=u=rwx "${DESTDIR}${PLUGINDIR}" # Copy the Mandos plugin runner -copy_exec "$libdir"/mandos/plugin-runner "${MANDOSDIR}" +copy_exec "$prefix"/lib/mandos/plugin-runner "${MANDOSDIR}" # Copy the plugins # Copy the packaged plugins -for file in "$libdir"/mandos/plugins.d/*; do +for file in "$prefix"/lib/mandos/plugins.d/*; do base="`basename \"$file\"`" # Is this plugin overridden? if [ -e "/etc/mandos/plugins.d/$base" ]; then @@ -109,58 +106,12 @@ esac done -# Get DEVICE from initramfs.conf and other files -. /etc/initramfs-tools/initramfs.conf -for conf in /etc/initramfs-tools/conf.d/*; do - if [ -n `basename \"$conf\" | grep '^[[:alnum:]][[:alnum:]\._-]*$' \ - | grep -v '\.dpkg-.*$'` ]; then - [ -f ${conf} ] && . ${conf} - fi -done -export DEVICE - -# Copy network hooks -for hook in /etc/mandos/network-hooks.d/*; do - case "`basename \"$hook\"`" in - "*") continue ;; - *[!A-Za-z0-9_.-]*) continue ;; - *) test -d "$hook" || copy_exec "$hook" "${HOOKDIR}" ;; - esac - if [ -x "$hook" ]; then - # Copy any files needed by the network hook - MANDOSNETHOOKDIR=/etc/mandos/network-hooks.d MODE=files \ - VERBOSITY=0 "$hook" files | while read file target; do - if [ ! -e "${file}" ]; then - echo "WARNING: file ${file} not found, requested by Mandos network hook '${hook##*/}'" >&2 - fi - if [ -z "${target}" ]; then - copy_exec "$file" - else - copy_exec "$file" "$target" - fi - done - # Copy and load any modules needed by the network hook - MANDOSNETHOOKDIR=/etc/mandos/network-hooks.d MODE=modules \ - VERBOSITY=0 "$hook" modules | while read module; do - if [ -z "${target}" ]; then - force_load "$module" - fi - done - fi -done - -# GPGME needs GnuPG -libgpgme11_version="`dpkg-query --showformat='${Version}' --show libgpgme11`" -if dpkg --compare-versions "$libgpgme11_version" ge 1.4.1-0.1; then - gpg=/usr/bin/gpg2 -else - gpg=/usr/bin/gpg -fi -if [ ! -e "${DESTDIR}$gpg" ]; then - copy_exec "$gpg" -fi -unset gpg -unset libgpgme11_version +# GPGME needs /usr/bin/gpg +if [ ! -e "${DESTDIR}/usr/bin/gpg" \ + -a -n "`ls \"${DESTDIR}\"/usr/lib/libgpgme.so* \ + 2>/dev/null`" ]; then + copy_exec /usr/bin/gpg +fi # Config files for file in /etc/mandos/plugin-runner.conf; do @@ -180,7 +131,7 @@ "${DESTDIR}${CONFDIR}/plugin-runner.conf" fi -# Key files +# Key files for file in "$keydir"/*; do if [ -d "$file" ]; then continue === modified file 'initramfs-tools-script' --- initramfs-tools-script 2011-07-16 00:29:19 +0000 +++ initramfs-tools-script 2009-09-16 23:28:39 +0000 @@ -108,7 +108,6 @@ # Our keyscript mandos=/lib/mandos/plugin-runner -test -x "$mandos" # parse /conf/conf.d/cryptroot. Format: # target=sda2_crypt,source=/dev/sda2,key=none,keyscript=/foo/bar/baz === removed file 'initramfs-unpack' --- initramfs-unpack 2013-10-13 15:43:42 +0000 +++ initramfs-unpack 1970-01-01 00:00:00 +0000 @@ -1,67 +0,0 @@ -#!/bin/bash -# -# Initramfs unpacker - unpacks initramfs images into /tmp -# -# Copyright © 2013 Teddy Hogeborn -# Copyright © 2013 Björn Påhlsson -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with this program. If not, see -# . -# -# Contact the authors at . - -cpio="cpio --extract --make-directories --unconditional --preserve-modification-time" - -if [ -z "$*" ]; then - set -- /boot/initrd.img-* -fi - -for imgfile in "$@"; do - if ! [ -f "$imgfile" ]; then - echo "Error: Not an existing file: $imgfile" >&2 - continue - fi - imgdir="${TMPDIR:-/tmp}/${imgfile##*/}" - if [ -d "$imgdir" ]; then - rm --recursive -- "$imgdir" - fi - mkdir --parents "$imgdir" - # Does this image contain microcode? - if $cpio --quiet --list --file="$imgfile" >/dev/null 2>&1; then - # Number of bytes to skip to get to the compressed archive - skip=$(($(LANG=C $cpio --io-size=1 --list --file="$imgfile" 2>&1 \ - | sed --quiet --expression='s/^\([0-9]\+\) blocks$/\1/p')+8)) - catimg="dd if=$imgfile bs=$skip skip=1 status=noxfer" - else - catimg="cat -- $imgfile" - fi - # Determine the compression method - if { $catimg 2>/dev/null | zcat --test >/dev/null 2>&1; - [ ${PIPESTATUS[-1]} -eq 0 ]; }; then - decomp="zcat" - elif { $catimg 2>/dev/null | bzip2 --test >/dev/null 2>&1; - [ ${PIPESTATUS[-1]} -eq 0 ]; }; then - decomp="bzip2 --stdout --decompress" - elif { $catimg 2>/dev/null | lzop --test >/dev/null 2>&1; - [ ${PIPESTATUS[-1]} -eq 0 ]; }; then - decomp="lzop --stdout --decompress" - else - echo "Error: Could not determine type of $imgfile" >&2 - continue - fi - $catimg 2>/dev/null | $decomp | ( cd -- "$imgdir" && $cpio --quiet ) - if [ ${PIPESTATUS[-1]} -eq 0 ]; then - echo "$imgfile unpacked into $imgdir" - fi -done === removed file 'intro.xml' --- intro.xml 2011-12-31 23:05:34 +0000 +++ intro.xml 1970-01-01 00:00:00 +0000 @@ -1,411 +0,0 @@ - - - -%common; -]> - - - - Mandos Manual - - Mandos - &version; - &TIMESTAMP; - - - Björn - Påhlsson -
- belorn@recompile.se -
-
- - Teddy - Hogeborn -
- teddy@recompile.se -
-
-
- - 2011 - 2012 - Teddy Hogeborn - Björn Påhlsson - - -
- - - intro - 8mandos - - - - intro - - Introduction to the Mandos system - - - - - DESCRIPTION - - This is the the Mandos system, which allows computers to have - encrypted root file systems and at the same time be capable of - remote and/or unattended reboots. - - - 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 - 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. - - - - - INTRODUCTION - - You know how it is. You’ve heard of it happening. The Man - comes and takes away your servers, your friends’ servers, the - servers of everybody in the same hosting facility. The servers - of their neighbors, and their neighbors’ friends. The servers - of people who owe them money. And like - that, they’re gone. And you doubt you’ll - ever see them again. - - - That is why your servers have encrypted root file systems. - However, there’s a downside. There’s no going around it: - rebooting is a pain. Dragging out that rarely-used keyboard and - screen and unraveling cables behind your servers to plug them in - to type in that password is messy, especially if you have many - servers. There are some people who do clever things like using - serial line consoles and daisy-chain it to the next server, and - keep all the servers connected in a ring with serial cables, - which will work, if your servers are physically close enough. - There are also other out-of-band management solutions, but with - all these, you still have to be on hand and - manually type in the password at boot time. Otherwise the - server just sits there, waiting for a password. - - - Wouldn’t it be great if you could have the security of encrypted - root file systems and still have servers that could boot up - automatically if there was a short power outage while you were - asleep? That you could reboot at will, without having someone - run over to the server to type in the password? - - - Well, with Mandos, you (almost) can! The gain in convenience - will only be offset by a small loss in security. The setup is - as follows: - - - The server will still have its encrypted root file system. The - password to this file system will be stored on another computer - (henceforth known as the Mandos server) on the same local - network. The password will not be stored - in plaintext, but encrypted with OpenPGP. To decrypt this - password, a key is needed. This key (the Mandos client key) - will not be stored there, but back on the original server - (henceforth known as the Mandos client) in the initial RAM disk - image. Oh, and all network Mandos client/server communications - will be encrypted, using TLS (SSL). - - - So, at boot time, the Mandos client will ask for its encrypted - data over the network, decrypt it to get the password, use it to - decrypt the root file, and continue booting. - - - Now, of course the initial RAM disk image is not on the - encrypted root file system, so anyone who had physical access - could take the Mandos client computer offline and read the disk - with their own tools to get the authentication keys used by a - client. But, by then the Mandos server - should notice that the original server has been offline for too - long, and will no longer give out the encrypted key. The timing - here is the only real weak point, and the method, frequency and - timeout of the server’s checking can be adjusted to any desired - level of paranoia - - - (The encrypted keys on the Mandos server is on its normal file - system, so those are safe, provided the root file system of - that server is encrypted.) - - - - - FREQUENTLY ASKED QUESTIONS - - Couldn’t the security be defeated by… - - - Grabbing the Mandos client key from the - initrd <emphasis>really quickly</emphasis>? - - This, as mentioned above, is the only real weak point. But if - you set the timing values tight enough, this will be really - difficult to do. An attacker would have to physically - disassemble the client computer, extract the key from the - initial RAM disk image, and then connect to a still - online Mandos server to get the encrypted key, and do - all this before the Mandos server timeout - kicks in and the Mandos server refuses to give out the key to - anyone. - - - Now, as the typical procedure seems to be to barge in and turn - off and grab all computers, to maybe look - at them months later, this is not likely. If someone does that, - the whole system will lock itself up - completely, since Mandos servers are no longer running. - - - For sophisticated attackers who could do - the clever thing, and had physical access - to the server for enough time, it would be simpler to get a key - for an encrypted file system by using hardware memory scanners - and reading it right off the memory bus. - - - - - Replay attacks? - - Nope, the network stuff is all done over TLS, which provides - protection against that. - - - - - Man-in-the-middle? - - 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. - - - - - Physically grabbing the Mandos server computer? - - You could protect that computer the - old-fashioned way, with a must-type-in-the-password-at-boot - method. Or you could have two computers be the Mandos server - for each other. - - - Multiple Mandos servers can coexist on a network without any - trouble. They do not clash, and clients will try all - available servers. This means that if just one reboots then - the other can bring it back up, but if both reboot at the same - time they will stay down until someone types in the password - on one of them. - - - - - Faking ping replies? - - The default for the server is to use - fping, the replies to which - could be faked to eliminate the timeout. But this could - easily be changed to any shell command, with any security - measures you like. It could, for instance, be changed to an - SSH command with strict keychecking, which could not be faked. - Or IPsec could be used for the ping packets, making them - secure. - - - - - - SECURITY - - So, in summary: The only weakness in the Mandos system is from - people who have: - - - - - The power to come in and physically take your servers, - and - - - - - The cunning and patience to do it carefully, one at a time, - and quickly, faking Mandos - client/server responses for each one before the timeout. - - - - - While there are some who may be threatened by people who have - both these attributes, they do not, - probably, constitute the majority. - - - If you do face such opponents, you must - figure that they could just as well open your servers and read - the file system keys right off the memory by running wires to - the memory bus. - - - What Mandos is designed to protect against is - not such determined, focused, and competent - attacks, but against the early morning knock on your door and - the sudden absence of all the servers in your server room. - Which it does nicely. - - - - - PLUGINS - - In the early designs, the - mandos-client8mandos program (which - retrieves a password from the Mandos server) also prompted for a - password on the terminal, in case a Mandos server could not be - found. Other ways of retrieving a password could easily be - envisoned, but this multiplicity of purpose was seen to be too - complex to be a viable way to continue. Instead, the original - program was separated into mandos-client8mandos and password-prompt8mandos, and a plugin-runner8mandos exist to run them both in parallel, allowing - the first successful plugin to provide the password. This - opened up for any number of additional plugins to run, all - competing to be the first to find a password and provide it to - the plugin runner. - - - Four additional plugins are provided: - - - - - plymouth - 8mandos - - - - This prompts for a password when using - plymouth8. - - - - - - usplash - 8mandos - - - - This prompts for a password when using - usplash8. - - - - - - splashy - 8mandos - - - - This prompts for a password when using - splashy8. - - - - - - askpass-fifo - 8mandos - - - - To provide compatibility with the "askpass" program from - cryptsetup, this plugin listens to the same FIFO as - askpass would do. - - - - - - More plugins can easily be written and added by the system - administrator; see the section called "WRITING PLUGINS" in - plugin-runner - 8mandos to learn the - plugin requirements. - - - - - SEE ALSO - - mandos - 8, - mandos.conf - 5, - mandos-clients.conf - 5, - mandos-ctl - 8, - mandos-monitor - 8, - plugin-runner - 8mandos, - mandos-client - 8mandos, - password-prompt - 8mandos, - plymouth - 8mandos, - usplash - 8mandos, - splashy - 8mandos, - askpass-fifo - 8mandos, - mandos-keygen - 8 - - - - - Mandos - - - - The Mandos home page. - - - - - -
- - - - - === modified file 'mandos' --- mandos 2014-02-16 02:42:42 +0000 +++ mandos 2011-03-15 19:15:24 +0000 @@ -11,8 +11,8 @@ # "AvahiService" class, and some lines in "main". # # Everything else is -# Copyright © 2008-2014 Teddy Hogeborn -# Copyright © 2008-2014 Björn Påhlsson +# Copyright © 2008-2011 Teddy Hogeborn +# Copyright © 2008-2011 Björn Påhlsson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -28,14 +28,12 @@ # along with this program. If not, see # . # -# Contact the authors at . +# Contact the authors at . # from __future__ import (division, absolute_import, print_function, unicode_literals) -from future_builtins import * - import SocketServer as socketserver import socket import argparse @@ -64,11 +62,6 @@ import functools import cPickle as pickle import multiprocessing -import types -import binascii -import tempfile -import itertools -import collections import dbus import dbus.service @@ -88,135 +81,24 @@ except ImportError: SO_BINDTODEVICE = None -version = "1.6.3" -stored_state_file = "clients.pickle" - -logger = logging.getLogger() + +version = "1.3.0" + +#logger = logging.getLogger('mandos') +logger = logging.Logger('mandos') syslogger = (logging.handlers.SysLogHandler (facility = logging.handlers.SysLogHandler.LOG_DAEMON, address = str("/dev/log"))) - -try: - if_nametoindex = (ctypes.cdll.LoadLibrary - (ctypes.util.find_library("c")) - .if_nametoindex) -except (OSError, AttributeError): - def if_nametoindex(interface): - "Get an interface index the hard way, i.e. using fcntl()" - SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h - with contextlib.closing(socket.socket()) as s: - ifreq = fcntl.ioctl(s, SIOCGIFINDEX, - struct.pack(str("16s16x"), - interface)) - interface_index = struct.unpack(str("I"), - ifreq[16:20])[0] - return interface_index - - -def initlogger(debug, level=logging.WARNING): - """init logger and add loglevel""" - - syslogger.setFormatter(logging.Formatter - ('Mandos [%(process)d]: %(levelname)s:' - ' %(message)s')) - logger.addHandler(syslogger) - - if debug: - console = logging.StreamHandler() - console.setFormatter(logging.Formatter('%(asctime)s %(name)s' - ' [%(process)d]:' - ' %(levelname)s:' - ' %(message)s')) - logger.addHandler(console) - logger.setLevel(level) - - -class PGPError(Exception): - """Exception if encryption/decryption fails""" - pass - - -class PGPEngine(object): - """A simple class for OpenPGP symmetric encryption & decryption""" - def __init__(self): - self.tempdir = tempfile.mkdtemp(prefix="mandos-") - self.gnupgargs = ['--batch', - '--home', self.tempdir, - '--force-mdc', - '--quiet', - '--no-use-agent'] - - def __enter__(self): - return self - - def __exit__(self, exc_type, exc_value, traceback): - self._cleanup() - return False - - def __del__(self): - self._cleanup() - - def _cleanup(self): - if self.tempdir is not None: - # Delete contents of tempdir - for root, dirs, files in os.walk(self.tempdir, - topdown = False): - for filename in files: - os.remove(os.path.join(root, filename)) - for dirname in dirs: - os.rmdir(os.path.join(root, dirname)) - # Remove tempdir - os.rmdir(self.tempdir) - self.tempdir = None - - def password_encode(self, password): - # Passphrase can not be empty and can not contain newlines or - # NUL bytes. So we prefix it and hex encode it. - encoded = b"mandos" + binascii.hexlify(password) - if len(encoded) > 2048: - # GnuPG can't handle long passwords, so encode differently - encoded = (b"mandos" + password.replace(b"\\", b"\\\\") - .replace(b"\n", b"\\n") - .replace(b"\0", b"\\x00")) - return encoded - - def encrypt(self, data, password): - passphrase = self.password_encode(password) - with tempfile.NamedTemporaryFile(dir=self.tempdir - ) as passfile: - passfile.write(passphrase) - passfile.flush() - proc = subprocess.Popen(['gpg', '--symmetric', - '--passphrase-file', - passfile.name] - + self.gnupgargs, - stdin = subprocess.PIPE, - stdout = subprocess.PIPE, - stderr = subprocess.PIPE) - ciphertext, err = proc.communicate(input = data) - if proc.returncode != 0: - raise PGPError(err) - return ciphertext - - def decrypt(self, data, password): - passphrase = self.password_encode(password) - with tempfile.NamedTemporaryFile(dir = self.tempdir - ) as passfile: - passfile.write(passphrase) - passfile.flush() - proc = subprocess.Popen(['gpg', '--decrypt', - '--passphrase-file', - passfile.name] - + self.gnupgargs, - stdin = subprocess.PIPE, - stdout = subprocess.PIPE, - stderr = subprocess.PIPE) - decrypted_plaintext, err = proc.communicate(input - = data) - if proc.returncode != 0: - raise PGPError(err) - return decrypted_plaintext - +syslogger.setFormatter(logging.Formatter + ('Mandos [%(process)d]: %(levelname)s:' + ' %(message)s')) +logger.addHandler(syslogger) + +console = logging.StreamHandler() +console.setFormatter(logging.Formatter('%(name)s [%(process)d]:' + ' %(levelname)s:' + ' %(message)s')) +logger.addHandler(console) class AvahiError(Exception): def __init__(self, value, *args, **kwargs): @@ -240,7 +122,7 @@ Used to optionally bind to the specified interface. name: string; Example: 'Mandos' type: string; Example: '_mandos._tcp'. - See + See port: integer; what port to announce TXT: list of strings; TXT record for the service domain: string; Domain to publish on, default to .local if empty. @@ -252,7 +134,6 @@ server: D-Bus Server bus: dbus.SystemBus() """ - def __init__(self, interface = avahi.IF_UNSPEC, name = None, servicetype = None, port = None, TXT = None, domain = "", host = "", max_renames = 32768, @@ -270,8 +151,6 @@ self.group = None # our entry group self.server = None self.bus = bus - self.entry_group_state_changed_match = None - def rename(self): """Derived from the Avahi example code""" if self.rename_count >= self.max_renames: @@ -279,38 +158,35 @@ " after %i retries, exiting.", self.rename_count) raise AvahiServiceError("Too many renames") - self.name = unicode(self.server - .GetAlternativeServiceName(self.name)) + self.name = unicode(self.server.GetAlternativeServiceName(self.name)) logger.info("Changing Zeroconf service name to %r ...", self.name) + syslogger.setFormatter(logging.Formatter + ('Mandos (%s) [%%(process)d]:' + ' %%(levelname)s: %%(message)s' + % self.name)) self.remove() try: self.add() - except dbus.exceptions.DBusException as error: - logger.critical("D-Bus Exception", exc_info=error) + except dbus.exceptions.DBusException, error: + logger.critical("DBusException: %s", error) self.cleanup() os._exit(1) self.rename_count += 1 - def remove(self): """Derived from the Avahi example code""" - if self.entry_group_state_changed_match is not None: - self.entry_group_state_changed_match.remove() - self.entry_group_state_changed_match = None if self.group is not None: self.group.Reset() - def add(self): """Derived from the Avahi example code""" - self.remove() if self.group is None: self.group = dbus.Interface( self.bus.get_object(avahi.DBUS_NAME, self.server.EntryGroupNew()), avahi.DBUS_INTERFACE_ENTRY_GROUP) - self.entry_group_state_changed_match = ( - self.group.connect_to_signal( - 'StateChanged', self.entry_group_state_changed)) + self.group.connect_to_signal('StateChanged', + self + .entry_group_state_changed) logger.debug("Adding Zeroconf service '%s' of type '%s' ...", self.name, self.type) self.group.AddService( @@ -322,7 +198,6 @@ dbus.UInt16(self.port), avahi.string_array_to_txt_array(self.TXT)) self.group.Commit() - def entry_group_state_changed(self, state, error): """Derived from the Avahi example code""" logger.debug("Avahi entry group state change: %i", state) @@ -335,81 +210,38 @@ elif state == avahi.ENTRY_GROUP_FAILURE: logger.critical("Avahi: Error in group state changed %s", unicode(error)) - raise AvahiGroupError("State changed: {0!s}" - .format(error)) - + raise AvahiGroupError("State changed: %s" + % unicode(error)) def cleanup(self): """Derived from the Avahi example code""" if self.group is not None: - try: - self.group.Free() - except (dbus.exceptions.UnknownMethodException, - dbus.exceptions.DBusException): - pass + self.group.Free() self.group = None - self.remove() - - def server_state_changed(self, state, error=None): + def server_state_changed(self, state): """Derived from the Avahi example code""" logger.debug("Avahi server state change: %i", state) - bad_states = { avahi.SERVER_INVALID: - "Zeroconf server invalid", - avahi.SERVER_REGISTERING: None, - avahi.SERVER_COLLISION: - "Zeroconf server name collision", - avahi.SERVER_FAILURE: - "Zeroconf server failure" } - if state in bad_states: - if bad_states[state] is not None: - if error is None: - logger.error(bad_states[state]) - else: - logger.error(bad_states[state] + ": %r", error) - self.cleanup() + if state == avahi.SERVER_COLLISION: + logger.error("Zeroconf server name collision") + self.remove() elif state == avahi.SERVER_RUNNING: self.add() - else: - if error is None: - logger.debug("Unknown state: %r", state) - else: - logger.debug("Unknown state: %r: %r", state, error) - def activate(self): """Derived from the Avahi example code""" if self.server is None: self.server = dbus.Interface( self.bus.get_object(avahi.DBUS_NAME, - avahi.DBUS_PATH_SERVER, - follow_name_owner_changes=True), + avahi.DBUS_PATH_SERVER), avahi.DBUS_INTERFACE_SERVER) self.server.connect_to_signal("StateChanged", self.server_state_changed) self.server_state_changed(self.server.GetState()) -class AvahiServiceToSyslog(AvahiService): - def rename(self): - """Add the new name to the syslog messages""" - ret = AvahiService.rename(self) - syslogger.setFormatter(logging.Formatter - ('Mandos ({0}) [%(process)d]:' - ' %(levelname)s: %(message)s' - .format(self.name))) - return ret - - -def timedelta_to_milliseconds(td): - "Convert a datetime.timedelta() to milliseconds" - return ((td.days * 24 * 60 * 60 * 1000) - + (td.seconds * 1000) - + (td.microseconds // 1000)) - - class Client(object): """A representation of a client host served by this server. Attributes: - approved: bool(); 'None' if not yet approved/disapproved + _approved: bool(); 'None' if not yet approved/disapproved approval_delay: datetime.timedelta(); Time to wait for approval approval_duration: datetime.timedelta(); Duration of one approval checker: subprocess.Popen(); a running checker process used @@ -422,9 +254,8 @@ instance %(name)s can be used in the command. checker_initiator_tag: a gobject event source tag, or None created: datetime.datetime(); (UTC) object creation - client_structure: Object describing what attributes a client has - and is used for storing the client at exit current_checker_command: string; current running checker_command + disable_hook: If set, called by disable() as disable_hook(self) disable_initiator_tag: a gobject event source tag, or None enabled: bool() fingerprint: string (40 or 32 hexadecimal digits); used to @@ -433,213 +264,145 @@ interval: datetime.timedelta(); How often to start a new checker last_approval_request: datetime.datetime(); (UTC) or None last_checked_ok: datetime.datetime(); (UTC) or None - last_checker_status: integer between 0 and 255 reflecting exit - status of last checker. -1 reflects crashed - checker, -2 means no checker completed yet. - last_enabled: datetime.datetime(); (UTC) or None + last_enabled: datetime.datetime(); (UTC) name: string; from the config file, used in log messages and D-Bus identifiers secret: bytestring; sent verbatim (over TLS) to client timeout: datetime.timedelta(); How long from last_checked_ok until this client is disabled - extended_timeout: extra long timeout when secret has been sent runtime_expansions: Allowed attributes for runtime expansion. - expires: datetime.datetime(); time (UTC) when a client will be - disabled, or None - server_settings: The server_settings dict from main() """ runtime_expansions = ("approval_delay", "approval_duration", - "created", "enabled", "expires", - "fingerprint", "host", "interval", - "last_approval_request", "last_checked_ok", + "created", "enabled", "fingerprint", + "host", "interval", "last_checked_ok", "last_enabled", "name", "timeout") - client_defaults = { "timeout": "PT5M", - "extended_timeout": "PT15M", - "interval": "PT2M", - "checker": "fping -q -- %%(host)s", - "host": "", - "approval_delay": "PT0S", - "approval_duration": "PT1S", - "approved_by_default": "True", - "enabled": "True", - } + + @staticmethod + def _timedelta_to_milliseconds(td): + "Convert a datetime.timedelta() to milliseconds" + return ((td.days * 24 * 60 * 60 * 1000) + + (td.seconds * 1000) + + (td.microseconds // 1000)) def timeout_milliseconds(self): "Return the 'timeout' attribute in milliseconds" - return timedelta_to_milliseconds(self.timeout) - - def extended_timeout_milliseconds(self): - "Return the 'extended_timeout' attribute in milliseconds" - return timedelta_to_milliseconds(self.extended_timeout) + return self._timedelta_to_milliseconds(self.timeout) def interval_milliseconds(self): "Return the 'interval' attribute in milliseconds" - return timedelta_to_milliseconds(self.interval) - + return self._timedelta_to_milliseconds(self.interval) + def approval_delay_milliseconds(self): - return timedelta_to_milliseconds(self.approval_delay) - - @staticmethod - def config_parser(config): - """Construct a new dict of client settings of this form: - { client_name: {setting_name: value, ...}, ...} - with exceptions for any special settings as defined above. - NOTE: Must be a pure function. Must return the same result - value given the same arguments. - """ - settings = {} - for client_name in config.sections(): - section = dict(config.items(client_name)) - client = settings[client_name] = {} - - client["host"] = section["host"] - # Reformat values from string types to Python types - client["approved_by_default"] = config.getboolean( - client_name, "approved_by_default") - client["enabled"] = config.getboolean(client_name, - "enabled") - - client["fingerprint"] = (section["fingerprint"].upper() - .replace(" ", "")) - if "secret" in section: - client["secret"] = section["secret"].decode("base64") - elif "secfile" in section: - with open(os.path.expanduser(os.path.expandvars - (section["secfile"])), - "rb") as secfile: - client["secret"] = secfile.read() - else: - raise TypeError("No secret or secfile for section {0}" - .format(section)) - client["timeout"] = string_to_delta(section["timeout"]) - client["extended_timeout"] = string_to_delta( - section["extended_timeout"]) - client["interval"] = string_to_delta(section["interval"]) - client["approval_delay"] = string_to_delta( - section["approval_delay"]) - client["approval_duration"] = string_to_delta( - section["approval_duration"]) - client["checker_command"] = section["checker"] - client["last_approval_request"] = None - client["last_checked_ok"] = None - client["last_checker_status"] = -2 - - return settings - - def __init__(self, settings, name = None, server_settings=None): + return self._timedelta_to_milliseconds(self.approval_delay) + + def __init__(self, name = None, disable_hook=None, config=None): + """Note: the 'checker' key in 'config' sets the + 'checker_command' attribute and *not* the 'checker' + attribute.""" self.name = name - if server_settings is None: - server_settings = {} - self.server_settings = server_settings - # adding all client settings - for setting, value in settings.iteritems(): - setattr(self, setting, value) - - if self.enabled: - if not hasattr(self, "last_enabled"): - self.last_enabled = datetime.datetime.utcnow() - if not hasattr(self, "expires"): - self.expires = (datetime.datetime.utcnow() - + self.timeout) - else: - self.last_enabled = None - self.expires = None - + if config is None: + config = {} logger.debug("Creating client %r", self.name) # Uppercase and remove spaces from fingerprint for later # comparison purposes with return value from the fingerprint() # function + self.fingerprint = (config["fingerprint"].upper() + .replace(" ", "")) logger.debug(" Fingerprint: %s", self.fingerprint) - self.created = settings.get("created", - datetime.datetime.utcnow()) - - # attributes specific for this server instance + if "secret" in config: + self.secret = config["secret"].decode("base64") + elif "secfile" in config: + with open(os.path.expanduser(os.path.expandvars + (config["secfile"])), + "rb") as secfile: + self.secret = secfile.read() + else: + raise TypeError("No secret or secfile for client %s" + % self.name) + self.host = config.get("host", "") + self.created = datetime.datetime.utcnow() + self.enabled = False + self.last_approval_request = None + self.last_enabled = None + self.last_checked_ok = None + self.timeout = string_to_delta(config["timeout"]) + self.interval = string_to_delta(config["interval"]) + self.disable_hook = disable_hook self.checker = None self.checker_initiator_tag = None self.disable_initiator_tag = None self.checker_callback_tag = None + self.checker_command = config["checker"] self.current_checker_command = None - self.approved = None + self.last_connect = None + self._approved = None + self.approved_by_default = config.get("approved_by_default", + True) self.approvals_pending = 0 - self.changedstate = (multiprocessing_manager - .Condition(multiprocessing_manager - .Lock())) - self.client_structure = [attr for attr in - self.__dict__.iterkeys() - if not attr.startswith("_")] - self.client_structure.append("client_structure") - - for name, t in inspect.getmembers(type(self), - lambda obj: - isinstance(obj, - property)): - if not name.startswith("_"): - self.client_structure.append(name) + self.approval_delay = string_to_delta( + config["approval_delay"]) + self.approval_duration = string_to_delta( + config["approval_duration"]) + self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock()) - # Send notice to process children that client state has changed def send_changedstate(self): - with self.changedstate: - self.changedstate.notify_all() - + self.changedstate.acquire() + self.changedstate.notify_all() + self.changedstate.release() + def enable(self): """Start this client's checker and timeout hooks""" if getattr(self, "enabled", False): # Already enabled return - self.expires = datetime.datetime.utcnow() + self.timeout - self.enabled = True + self.send_changedstate() self.last_enabled = datetime.datetime.utcnow() - self.init_checker() - self.send_changedstate() - - def disable(self, quiet=True): - """Disable this client.""" - if not getattr(self, "enabled", False): - return False - if not quiet: - logger.info("Disabling client %s", self.name) - if getattr(self, "disable_initiator_tag", None) is not None: - gobject.source_remove(self.disable_initiator_tag) - self.disable_initiator_tag = None - self.expires = None - if getattr(self, "checker_initiator_tag", None) is not None: - gobject.source_remove(self.checker_initiator_tag) - self.checker_initiator_tag = None - self.stop_checker() - self.enabled = False - if not quiet: - self.send_changedstate() - # Do not run this again if called by a gobject.timeout_add - return False - - def __del__(self): - self.disable() - - def init_checker(self): # Schedule a new checker to be started an 'interval' from now, # and every interval from then on. - if self.checker_initiator_tag is not None: - gobject.source_remove(self.checker_initiator_tag) self.checker_initiator_tag = (gobject.timeout_add (self.interval_milliseconds(), self.start_checker)) # Schedule a disable() when 'timeout' has passed - if self.disable_initiator_tag is not None: - gobject.source_remove(self.disable_initiator_tag) self.disable_initiator_tag = (gobject.timeout_add (self.timeout_milliseconds(), self.disable)) + self.enabled = True # Also start a new checker *right now*. self.start_checker() + def disable(self, quiet=True): + """Disable this client.""" + if not getattr(self, "enabled", False): + return False + if not quiet: + self.send_changedstate() + if not quiet: + logger.info("Disabling client %s", self.name) + if getattr(self, "disable_initiator_tag", False): + gobject.source_remove(self.disable_initiator_tag) + self.disable_initiator_tag = None + if getattr(self, "checker_initiator_tag", False): + gobject.source_remove(self.checker_initiator_tag) + self.checker_initiator_tag = None + self.stop_checker() + if self.disable_hook: + self.disable_hook(self) + self.enabled = False + # Do not run this again if called by a gobject.timeout_add + return False + + def __del__(self): + self.disable_hook = None + self.disable() + def checker_callback(self, pid, condition, command): """The checker has completed, so take appropriate actions.""" self.checker_callback_tag = None self.checker = None if os.WIFEXITED(condition): - self.last_checker_status = os.WEXITSTATUS(condition) - if self.last_checker_status == 0: + exitstatus = os.WEXITSTATUS(condition) + if exitstatus == 0: logger.info("Checker for %(name)s succeeded", vars(self)) self.checked_ok() @@ -647,28 +410,20 @@ logger.info("Checker for %(name)s failed", vars(self)) else: - self.last_checker_status = -1 logger.warning("Checker for %(name)s crashed?", vars(self)) def checked_ok(self): - """Assert that the client has been seen, alive and well.""" + """Bump up the timeout for this client. + + This should only be called when the client has been seen, + alive and well. + """ self.last_checked_ok = datetime.datetime.utcnow() - self.last_checker_status = 0 - self.bump_timeout() - - def bump_timeout(self, timeout=None): - """Bump up the timeout for this client.""" - if timeout is None: - timeout = self.timeout - if self.disable_initiator_tag is not None: - gobject.source_remove(self.disable_initiator_tag) - self.disable_initiator_tag = None - if getattr(self, "enabled", False): - self.disable_initiator_tag = (gobject.timeout_add - (timedelta_to_milliseconds - (timeout), self.disable)) - self.expires = datetime.datetime.utcnow() + timeout + gobject.source_remove(self.disable_initiator_tag) + self.disable_initiator_tag = (gobject.timeout_add + (self.timeout_milliseconds(), + self.disable)) def need_approval(self): self.last_approval_request = datetime.datetime.utcnow() @@ -679,10 +434,10 @@ If a checker already exists, leave it running and do nothing.""" # The reason for not killing a running checker is that if we - # did that, and if a checker (for some reason) started running - # slowly and taking more than 'interval' time, then the client - # would inevitably timeout, since no checker would get a - # chance to run to completion. If we instead leave running + # did that, then if a checker (for some reason) started + # running slowly and taking more than 'interval' time, the + # client would inevitably timeout, since no checker would get + # a chance to run to completion. If we instead leave running # checkers alone, the checker would have to take more time # than 'timeout' for the client to be disabled, which is as it # should be. @@ -690,11 +445,10 @@ # If a checker exists, make sure it is not a zombie try: pid, status = os.waitpid(self.checker.pid, os.WNOHANG) - except AttributeError: - pass - except OSError as error: - if error.errno != errno.ECHILD: - raise + except (AttributeError, OSError), error: + if (isinstance(error, OSError) + and error.errno != errno.ECHILD): + raise error else: if pid: logger.warning("Checker was a zombie") @@ -703,17 +457,25 @@ self.current_checker_command) # Start a new checker if needed if self.checker is None: - # Escape attributes for the shell - escaped_attrs = dict( - (attr, re.escape(unicode(getattr(self, attr)))) - for attr in - self.runtime_expansions) try: - command = self.checker_command % escaped_attrs - except TypeError as error: - logger.error('Could not format string "%s"', - self.checker_command, exc_info=error) - return True # Try again later + # In case checker_command has exactly one % operator + command = self.checker_command % self.host + except TypeError: + # Escape attributes for the shell + escaped_attrs = dict( + (attr, + re.escape(unicode(str(getattr(self, attr, "")), + errors= + 'replace'))) + for attr in + self.runtime_expansions) + + try: + command = self.checker_command % escaped_attrs + except TypeError, error: + logger.error('Could not format string "%s":' + ' %s', self.checker_command, error) + return True # Try again later self.current_checker_command = command try: logger.info("Starting checker %r for %s", @@ -722,40 +484,22 @@ # in normal mode, that is already done by daemon(), # and in debug mode we don't want to. (Stdin is # always replaced by /dev/null.) - # The exception is when not debugging but nevertheless - # running in the foreground; use the previously - # created wnull. - popen_args = {} - if (not self.server_settings["debug"] - and self.server_settings["foreground"]): - popen_args.update({"stdout": wnull, - "stderr": wnull }) self.checker = subprocess.Popen(command, close_fds=True, - shell=True, cwd="/", - **popen_args) - except OSError as error: - logger.error("Failed to start subprocess", - exc_info=error) - return True - self.checker_callback_tag = (gobject.child_watch_add - (self.checker.pid, - self.checker_callback, - data=command)) - # The checker may have completed before the gobject - # watch was added. Check for this. - try: + shell=True, cwd="/") + self.checker_callback_tag = (gobject.child_watch_add + (self.checker.pid, + self.checker_callback, + data=command)) + # The checker may have completed before the gobject + # watch was added. Check for this. pid, status = os.waitpid(self.checker.pid, os.WNOHANG) - except OSError as error: - if error.errno == errno.ECHILD: - # This should never happen - logger.error("Child process vanished", - exc_info=error) - return True - raise - if pid: - gobject.source_remove(self.checker_callback_tag) - self.checker_callback(pid, status, command) + if pid: + gobject.source_remove(self.checker_callback_tag) + self.checker_callback(pid, status, command) + except OSError, error: + logger.error("Failed to start subprocess: %s", + error) # Re-run this periodically if run by gobject.timeout_add return True @@ -768,16 +512,15 @@ return logger.debug("Stopping checker for %(name)s", vars(self)) try: - self.checker.terminate() + os.kill(self.checker.pid, signal.SIGTERM) #time.sleep(0.5) #if self.checker.poll() is None: - # self.checker.kill() - except OSError as error: + # os.kill(self.checker.pid, signal.SIGKILL) + except OSError, error: if error.errno != errno.ESRCH: # No such process raise self.checker = None - def dbus_service_property(dbus_interface, signature="v", access="readwrite", byte_arrays=False): """Decorators for marking methods of a DBusObjectWithProperties to @@ -794,7 +537,7 @@ # "Set" method, so we fail early here: if byte_arrays and signature != "ay": raise ValueError("Byte arrays not supported for non-'ay'" - " signature {0!r}".format(signature)) + " signature %r" % signature) def decorator(func): func._dbus_is_property = True func._dbus_interface = dbus_interface @@ -808,43 +551,6 @@ return decorator -def dbus_interface_annotations(dbus_interface): - """Decorator for marking functions returning interface annotations - - Usage: - - @dbus_interface_annotations("org.example.Interface") - def _foo(self): # Function name does not matter - return {"org.freedesktop.DBus.Deprecated": "true", - "org.freedesktop.DBus.Property.EmitsChangedSignal": - "false"} - """ - def decorator(func): - func._dbus_is_interface = True - func._dbus_interface = dbus_interface - func._dbus_name = dbus_interface - return func - return decorator - - -def dbus_annotations(annotations): - """Decorator to annotate D-Bus methods, signals or properties - Usage: - - @dbus_service_property("org.example.Interface", signature="b", - access="r") - @dbus_annotations({{"org.freedesktop.DBus.Deprecated": "true", - "org.freedesktop.DBus.Property." - "EmitsChangedSignal": "false"}) - def Property_dbus_property(self): - return dbus.Boolean(False) - """ - def decorator(func): - func._dbus_annotations = annotations - return func - return decorator - - class DBusPropertyException(dbus.exceptions.DBusException): """A base class for D-Bus property-related exceptions """ @@ -866,45 +572,37 @@ class DBusObjectWithProperties(dbus.service.Object): """A D-Bus object with properties. - + Classes inheriting from this can use the dbus_service_property decorator to expose methods as D-Bus properties. It exposes the standard Get(), Set(), and GetAll() methods on the D-Bus. """ @staticmethod - def _is_dbus_thing(thing): - """Returns a function testing if an attribute is a D-Bus thing - - If called like _is_dbus_thing("method") it returns a function - suitable for use as predicate to inspect.getmembers(). - """ - return lambda obj: getattr(obj, "_dbus_is_{0}".format(thing), - False) + def _is_dbus_property(obj): + return getattr(obj, "_dbus_is_property", False) - def _get_all_dbus_things(self, thing): + def _get_all_dbus_properties(self): """Returns a generator of (name, attribute) pairs """ - return ((getattr(athing.__get__(self), "_dbus_name", - name), - athing.__get__(self)) - for cls in self.__class__.__mro__ - for name, athing in - inspect.getmembers(cls, - self._is_dbus_thing(thing))) + return ((prop._dbus_name, prop) + for name, prop in + inspect.getmembers(self, self._is_dbus_property)) def _get_dbus_property(self, interface_name, property_name): """Returns a bound method if one exists which is a D-Bus property with the specified name and interface. """ - for cls in self.__class__.__mro__: - for name, value in (inspect.getmembers - (cls, - self._is_dbus_thing("property"))): - if (value._dbus_name == property_name - and value._dbus_interface == interface_name): - return value.__get__(self) - + for name in (property_name, + property_name + "_dbus_property"): + prop = getattr(self, name, None) + if (prop is None + or not self._is_dbus_property(prop) + or prop._dbus_name != property_name + or (interface_name and prop._dbus_interface + and interface_name != prop._dbus_interface)): + continue + return prop # No such property raise DBusPropertyNotFound(self.dbus_object_path + ":" + interface_name + "." @@ -934,11 +632,9 @@ # The byte_arrays option is not supported yet on # signatures other than "ay". if prop._dbus_signature != "ay": - raise ValueError("Byte arrays not supported for non-" - "'ay' signature {0!r}" - .format(prop._dbus_signature)) - value = dbus.ByteArray(b''.join(chr(byte) - for byte in value)) + raise ValueError + value = dbus.ByteArray(''.join(unichr(byte) + for byte in value)) prop(value) @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s", @@ -946,11 +642,11 @@ def GetAll(self, interface_name): """Standard D-Bus property GetAll() method, see D-Bus standard. - + Note: Will not include properties with access="write". """ - properties = {} - for name, prop in self._get_all_dbus_things("property"): + all = {} + for name, prop in self._get_all_dbus_properties(): if (interface_name and interface_name != prop._dbus_interface): # Interface non-empty but did not match @@ -960,20 +656,18 @@ continue value = prop() if not hasattr(value, "variant_level"): - properties[name] = value + all[name] = value continue - properties[name] = type(value)(value, variant_level= - value.variant_level+1) - return dbus.Dictionary(properties, signature="sv") + all[name] = type(value)(value, variant_level= + value.variant_level+1) + return dbus.Dictionary(all, signature="sv") @dbus.service.method(dbus.INTROSPECTABLE_IFACE, out_signature="s", path_keyword='object_path', connection_keyword='connection') def Introspect(self, object_path, connection): - """Overloading of standard D-Bus method. - - Inserts property tags and interface annotation tags. + """Standard D-Bus method, overloaded to insert property tags. """ xmlstring = dbus.service.Object.Introspect(self, object_path, connection) @@ -986,44 +680,12 @@ e.setAttribute("access", prop._dbus_access) return e for if_tag in document.getElementsByTagName("interface"): - # Add property tags for tag in (make_tag(document, name, prop) for name, prop - in self._get_all_dbus_things("property") + in self._get_all_dbus_properties() if prop._dbus_interface == if_tag.getAttribute("name")): if_tag.appendChild(tag) - # Add annotation tags - for typ in ("method", "signal", "property"): - for tag in if_tag.getElementsByTagName(typ): - annots = dict() - for name, prop in (self. - _get_all_dbus_things(typ)): - if (name == tag.getAttribute("name") - and prop._dbus_interface - == if_tag.getAttribute("name")): - annots.update(getattr - (prop, - "_dbus_annotations", - {})) - for name, value in annots.iteritems(): - ann_tag = document.createElement( - "annotation") - ann_tag.setAttribute("name", name) - ann_tag.setAttribute("value", value) - tag.appendChild(ann_tag) - # Add interface annotation tags - for annotation, value in dict( - itertools.chain.from_iterable( - annotations().iteritems() - for name, annotations in - self._get_all_dbus_things("interface") - if name == if_tag.getAttribute("name") - )).iteritems(): - ann_tag = document.createElement("annotation") - ann_tag.setAttribute("name", annotation) - ann_tag.setAttribute("value", value) - if_tag.appendChild(ann_tag) # Add the names to the return values for the # "org.freedesktop.DBus.Properties" methods if (if_tag.getAttribute("name") @@ -1042,191 +704,12 @@ xmlstring = document.toxml("utf-8") document.unlink() except (AttributeError, xml.dom.DOMException, - xml.parsers.expat.ExpatError) as error: + xml.parsers.expat.ExpatError), error: logger.error("Failed to override Introspection method", - exc_info=error) + error) return xmlstring -def datetime_to_dbus(dt, variant_level=0): - """Convert a UTC datetime.datetime() to a D-Bus type.""" - if dt is None: - return dbus.String("", variant_level = variant_level) - return dbus.String(dt.isoformat(), - variant_level=variant_level) - - -def alternate_dbus_interfaces(alt_interface_names, deprecate=True): - """A class decorator; applied to a subclass of - dbus.service.Object, it will add alternate D-Bus attributes with - interface names according to the "alt_interface_names" mapping. - Usage: - - @alternate_dbus_interfaces({"org.example.Interface": - "net.example.AlternateInterface"}) - class SampleDBusObject(dbus.service.Object): - @dbus.service.method("org.example.Interface") - def SampleDBusMethod(): - pass - - The above "SampleDBusMethod" on "SampleDBusObject" will be - reachable via two interfaces: "org.example.Interface" and - "net.example.AlternateInterface", the latter of which will have - its D-Bus annotation "org.freedesktop.DBus.Deprecated" set to - "true", unless "deprecate" is passed with a False value. - - This works for methods and signals, and also for D-Bus properties - (from DBusObjectWithProperties) and interfaces (from the - dbus_interface_annotations decorator). - """ - def wrapper(cls): - for orig_interface_name, alt_interface_name in ( - alt_interface_names.iteritems()): - attr = {} - interface_names = set() - # Go though all attributes of the class - for attrname, attribute in inspect.getmembers(cls): - # Ignore non-D-Bus attributes, and D-Bus attributes - # with the wrong interface name - if (not hasattr(attribute, "_dbus_interface") - or not attribute._dbus_interface - .startswith(orig_interface_name)): - continue - # Create an alternate D-Bus interface name based on - # the current name - alt_interface = (attribute._dbus_interface - .replace(orig_interface_name, - alt_interface_name)) - interface_names.add(alt_interface) - # Is this a D-Bus signal? - if getattr(attribute, "_dbus_is_signal", False): - # Extract the original non-method undecorated - # function by black magic - nonmethod_func = (dict( - zip(attribute.func_code.co_freevars, - attribute.__closure__))["func"] - .cell_contents) - # Create a new, but exactly alike, function - # object, and decorate it to be a new D-Bus signal - # with the alternate D-Bus interface name - new_function = (dbus.service.signal - (alt_interface, - attribute._dbus_signature) - (types.FunctionType( - nonmethod_func.func_code, - nonmethod_func.func_globals, - nonmethod_func.func_name, - nonmethod_func.func_defaults, - nonmethod_func.func_closure))) - # Copy annotations, if any - try: - new_function._dbus_annotations = ( - dict(attribute._dbus_annotations)) - except AttributeError: - pass - # Define a creator of a function to call both the - # original and alternate functions, so both the - # original and alternate signals gets sent when - # the function is called - def fixscope(func1, func2): - """This function is a scope container to pass - func1 and func2 to the "call_both" function - outside of its arguments""" - def call_both(*args, **kwargs): - """This function will emit two D-Bus - signals by calling func1 and func2""" - func1(*args, **kwargs) - func2(*args, **kwargs) - return call_both - # Create the "call_both" function and add it to - # the class - attr[attrname] = fixscope(attribute, new_function) - # Is this a D-Bus method? - elif getattr(attribute, "_dbus_is_method", False): - # Create a new, but exactly alike, function - # object. Decorate it to be a new D-Bus method - # with the alternate D-Bus interface name. Add it - # to the class. - attr[attrname] = (dbus.service.method - (alt_interface, - attribute._dbus_in_signature, - attribute._dbus_out_signature) - (types.FunctionType - (attribute.func_code, - attribute.func_globals, - attribute.func_name, - attribute.func_defaults, - attribute.func_closure))) - # Copy annotations, if any - try: - attr[attrname]._dbus_annotations = ( - dict(attribute._dbus_annotations)) - except AttributeError: - pass - # Is this a D-Bus property? - elif getattr(attribute, "_dbus_is_property", False): - # Create a new, but exactly alike, function - # object, and decorate it to be a new D-Bus - # property with the alternate D-Bus interface - # name. Add it to the class. - attr[attrname] = (dbus_service_property - (alt_interface, - attribute._dbus_signature, - attribute._dbus_access, - attribute - ._dbus_get_args_options - ["byte_arrays"]) - (types.FunctionType - (attribute.func_code, - attribute.func_globals, - attribute.func_name, - attribute.func_defaults, - attribute.func_closure))) - # Copy annotations, if any - try: - attr[attrname]._dbus_annotations = ( - dict(attribute._dbus_annotations)) - except AttributeError: - pass - # Is this a D-Bus interface? - elif getattr(attribute, "_dbus_is_interface", False): - # Create a new, but exactly alike, function - # object. Decorate it to be a new D-Bus interface - # with the alternate D-Bus interface name. Add it - # to the class. - attr[attrname] = (dbus_interface_annotations - (alt_interface) - (types.FunctionType - (attribute.func_code, - attribute.func_globals, - attribute.func_name, - attribute.func_defaults, - attribute.func_closure))) - if deprecate: - # Deprecate all alternate interfaces - iname="_AlternateDBusNames_interface_annotation{0}" - for interface_name in interface_names: - @dbus_interface_annotations(interface_name) - def func(self): - return { "org.freedesktop.DBus.Deprecated": - "true" } - # Find an unused name - for aname in (iname.format(i) - for i in itertools.count()): - if aname not in attr: - attr[aname] = func - break - if interface_names: - # Replace the class with a new subclass of it with - # methods, signals, etc. as created above. - cls = type(b"{0}Alternate".format(cls.__name__), - (cls,), attr) - return cls - return wrapper - - -@alternate_dbus_interfaces({"se.recompile.Mandos": - "se.bsnet.fukt.Mandos"}) class ClientDBus(Client, DBusObjectWithProperties): """A Client class using D-Bus @@ -1241,6 +724,7 @@ # dbus.service.Object doesn't use super(), so we can't either. def __init__(self, bus = None, *args, **kwargs): + self._approvals_pending = 0 self.bus = bus Client.__init__(self, *args, **kwargs) # Only now, when this client is initialized, can it show up on @@ -1252,74 +736,50 @@ ("/clients/" + client_object_name)) DBusObjectWithProperties.__init__(self, self.bus, self.dbus_object_path) - - def notifychangeproperty(transform_func, - dbus_name, type_func=lambda x: x, - variant_level=1): - """ Modify a variable so that it's a property which announces - its changes to DBus. - - transform_fun: Function that takes a value and a variant_level - and transforms it to a D-Bus type. - dbus_name: D-Bus name of the variable - type_func: Function that transform the value before sending it - to the D-Bus. Default: no transform - variant_level: D-Bus variant level. Default: 1 - """ - attrname = "_{0}".format(dbus_name) - def setter(self, value): - if hasattr(self, "dbus_object_path"): - if (not hasattr(self, attrname) or - type_func(getattr(self, attrname, None)) - != type_func(value)): - dbus_value = transform_func(type_func(value), - variant_level - =variant_level) - self.PropertyChanged(dbus.String(dbus_name), - dbus_value) - setattr(self, attrname, value) - - return property(lambda self: getattr(self, attrname), setter) - - expires = notifychangeproperty(datetime_to_dbus, "Expires") - approvals_pending = notifychangeproperty(dbus.Boolean, - "ApprovalPending", - type_func = bool) - enabled = notifychangeproperty(dbus.Boolean, "Enabled") - last_enabled = notifychangeproperty(datetime_to_dbus, - "LastEnabled") - checker = notifychangeproperty(dbus.Boolean, "CheckerRunning", - type_func = lambda checker: - checker is not None) - last_checked_ok = notifychangeproperty(datetime_to_dbus, - "LastCheckedOK") - last_checker_status = notifychangeproperty(dbus.Int16, - "LastCheckerStatus") - last_approval_request = notifychangeproperty( - datetime_to_dbus, "LastApprovalRequest") - approved_by_default = notifychangeproperty(dbus.Boolean, - "ApprovedByDefault") - approval_delay = notifychangeproperty(dbus.UInt64, - "ApprovalDelay", - type_func = - timedelta_to_milliseconds) - approval_duration = notifychangeproperty( - dbus.UInt64, "ApprovalDuration", - type_func = timedelta_to_milliseconds) - host = notifychangeproperty(dbus.String, "Host") - timeout = notifychangeproperty(dbus.UInt64, "Timeout", - type_func = - timedelta_to_milliseconds) - extended_timeout = notifychangeproperty( - dbus.UInt64, "ExtendedTimeout", - type_func = timedelta_to_milliseconds) - interval = notifychangeproperty(dbus.UInt64, - "Interval", - type_func = - timedelta_to_milliseconds) - checker_command = notifychangeproperty(dbus.String, "Checker") - - del notifychangeproperty + + def _get_approvals_pending(self): + return self._approvals_pending + def _set_approvals_pending(self, value): + old_value = self._approvals_pending + self._approvals_pending = value + bval = bool(value) + if (hasattr(self, "dbus_object_path") + and bval is not bool(old_value)): + dbus_bool = dbus.Boolean(bval, variant_level=1) + self.PropertyChanged(dbus.String("ApprovalPending"), + dbus_bool) + + approvals_pending = property(_get_approvals_pending, + _set_approvals_pending) + del _get_approvals_pending, _set_approvals_pending + + @staticmethod + def _datetime_to_dbus(dt, variant_level=0): + """Convert a UTC datetime.datetime() to a D-Bus type.""" + return dbus.String(dt.isoformat(), + variant_level=variant_level) + + def enable(self): + oldstate = getattr(self, "enabled", False) + r = Client.enable(self) + if oldstate != self.enabled: + # Emit D-Bus signals + self.PropertyChanged(dbus.String("Enabled"), + dbus.Boolean(True, variant_level=1)) + self.PropertyChanged( + dbus.String("LastEnabled"), + self._datetime_to_dbus(self.last_enabled, + variant_level=1)) + return r + + def disable(self, quiet = False): + oldstate = getattr(self, "enabled", False) + r = Client.disable(self, quiet=quiet) + if not quiet and oldstate != self.enabled: + # Emit D-Bus signal + self.PropertyChanged(dbus.String("Enabled"), + dbus.Boolean(False, variant_level=1)) + return r def __del__(self, *args, **kwargs): try: @@ -1334,6 +794,9 @@ *args, **kwargs): self.checker_callback_tag = None self.checker = None + # Emit D-Bus signal + self.PropertyChanged(dbus.String("CheckerRunning"), + dbus.Boolean(False, variant_level=1)) if os.WIFEXITED(condition): exitstatus = os.WEXITSTATUS(condition) # Emit D-Bus signal @@ -1349,6 +812,24 @@ return Client.checker_callback(self, pid, condition, command, *args, **kwargs) + def checked_ok(self, *args, **kwargs): + r = Client.checked_ok(self, *args, **kwargs) + # Emit D-Bus signal + self.PropertyChanged( + dbus.String("LastCheckedOK"), + (self._datetime_to_dbus(self.last_checked_ok, + variant_level=1))) + return r + + def need_approval(self, *args, **kwargs): + r = Client.need_approval(self, *args, **kwargs) + # Emit D-Bus signal + self.PropertyChanged( + dbus.String("LastApprovalRequest"), + (self._datetime_to_dbus(self.last_approval_request, + variant_level=1))) + return r + def start_checker(self, *args, **kwargs): old_checker = self.checker if self.checker is not None: @@ -1361,28 +842,34 @@ and old_checker_pid != self.checker.pid): # Emit D-Bus signal self.CheckerStarted(self.current_checker_command) + self.PropertyChanged( + dbus.String("CheckerRunning"), + dbus.Boolean(True, variant_level=1)) return r + def stop_checker(self, *args, **kwargs): + old_checker = getattr(self, "checker", None) + r = Client.stop_checker(self, *args, **kwargs) + if (old_checker is not None + and getattr(self, "checker", None) is None): + self.PropertyChanged(dbus.String("CheckerRunning"), + dbus.Boolean(False, variant_level=1)) + return r + def _reset_approved(self): - self.approved = None + self._approved = None return False def approve(self, value=True): - self.approved = value - gobject.timeout_add(timedelta_to_milliseconds + self.send_changedstate() + self._approved = value + gobject.timeout_add(self._timedelta_to_milliseconds (self.approval_duration), self._reset_approved) - self.send_changedstate() + ## D-Bus methods, signals & properties - _interface = "se.recompile.Mandos.Client" - - ## Interfaces - - @dbus_interface_annotations(_interface) - def _foo(self): - return { "org.freedesktop.DBus.Property.EmitsChangedSignal": - "false"} + _interface = "se.bsnet.fukt.Mandos.Client" ## Signals @@ -1435,7 +922,7 @@ # CheckedOK - method @dbus.service.method(_interface) def CheckedOK(self): - self.checked_ok() + return self.checked_ok() # Enable - method @dbus.service.method(_interface) @@ -1474,6 +961,9 @@ if value is None: # get return dbus.Boolean(self.approved_by_default) self.approved_by_default = bool(value) + # Emit D-Bus signal + self.PropertyChanged(dbus.String("ApprovedByDefault"), + dbus.Boolean(value, variant_level=1)) # ApprovalDelay - property @dbus_service_property(_interface, signature="t", @@ -1482,15 +972,21 @@ if value is None: # get return dbus.UInt64(self.approval_delay_milliseconds()) self.approval_delay = datetime.timedelta(0, 0, 0, value) + # Emit D-Bus signal + self.PropertyChanged(dbus.String("ApprovalDelay"), + dbus.UInt64(value, variant_level=1)) # ApprovalDuration - property @dbus_service_property(_interface, signature="t", access="readwrite") def ApprovalDuration_dbus_property(self, value=None): if value is None: # get - return dbus.UInt64(timedelta_to_milliseconds( + return dbus.UInt64(self._timedelta_to_milliseconds( self.approval_duration)) self.approval_duration = datetime.timedelta(0, 0, 0, value) + # Emit D-Bus signal + self.PropertyChanged(dbus.String("ApprovalDuration"), + dbus.UInt64(value, variant_level=1)) # Name - property @dbus_service_property(_interface, signature="s", access="read") @@ -1508,17 +1004,22 @@ def Host_dbus_property(self, value=None): if value is None: # get return dbus.String(self.host) - self.host = unicode(value) + self.host = value + # Emit D-Bus signal + self.PropertyChanged(dbus.String("Host"), + dbus.String(value, variant_level=1)) # Created - property @dbus_service_property(_interface, signature="s", access="read") def Created_dbus_property(self): - return datetime_to_dbus(self.created) + return dbus.String(self._datetime_to_dbus(self.created)) # LastEnabled - property @dbus_service_property(_interface, signature="s", access="read") def LastEnabled_dbus_property(self): - return datetime_to_dbus(self.last_enabled) + if self.last_enabled is None: + return dbus.String("") + return dbus.String(self._datetime_to_dbus(self.last_enabled)) # Enabled - property @dbus_service_property(_interface, signature="b", @@ -1538,23 +1039,19 @@ if value is not None: self.checked_ok() return - return datetime_to_dbus(self.last_checked_ok) - - # LastCheckerStatus - property - @dbus_service_property(_interface, signature="n", - access="read") - def LastCheckerStatus_dbus_property(self): - return dbus.Int16(self.last_checker_status) - - # Expires - property - @dbus_service_property(_interface, signature="s", access="read") - def Expires_dbus_property(self): - return datetime_to_dbus(self.expires) + if self.last_checked_ok is None: + return dbus.String("") + return dbus.String(self._datetime_to_dbus(self + .last_checked_ok)) # LastApprovalRequest - property @dbus_service_property(_interface, signature="s", access="read") def LastApprovalRequest_dbus_property(self): - return datetime_to_dbus(self.last_approval_request) + if self.last_approval_request is None: + return dbus.String("") + return dbus.String(self. + _datetime_to_dbus(self + .last_approval_request)) # Timeout - property @dbus_service_property(_interface, signature="t", @@ -1562,32 +1059,27 @@ def Timeout_dbus_property(self, value=None): if value is None: # get return dbus.UInt64(self.timeout_milliseconds()) - old_timeout = self.timeout self.timeout = datetime.timedelta(0, 0, 0, value) - # Reschedule disabling - if self.enabled: - now = datetime.datetime.utcnow() - self.expires += self.timeout - old_timeout - if self.expires <= now: - # The timeout has passed - self.disable() - else: - if (getattr(self, "disable_initiator_tag", None) - is None): - return - gobject.source_remove(self.disable_initiator_tag) - self.disable_initiator_tag = ( - gobject.timeout_add( - timedelta_to_milliseconds(self.expires - now), - self.disable)) - - # ExtendedTimeout - property - @dbus_service_property(_interface, signature="t", - access="readwrite") - def ExtendedTimeout_dbus_property(self, value=None): - if value is None: # get - return dbus.UInt64(self.extended_timeout_milliseconds()) - self.extended_timeout = datetime.timedelta(0, 0, 0, value) + # Emit D-Bus signal + self.PropertyChanged(dbus.String("Timeout"), + dbus.UInt64(value, variant_level=1)) + if getattr(self, "disable_initiator_tag", None) is None: + return + # Reschedule timeout + gobject.source_remove(self.disable_initiator_tag) + self.disable_initiator_tag = None + time_to_die = (self. + _timedelta_to_milliseconds((self + .last_checked_ok + + self.timeout) + - datetime.datetime + .utcnow())) + if time_to_die <= 0: + # The timeout has passed + self.disable() + else: + self.disable_initiator_tag = (gobject.timeout_add + (time_to_die, self.disable)) # Interval - property @dbus_service_property(_interface, signature="t", @@ -1596,22 +1088,28 @@ if value is None: # get return dbus.UInt64(self.interval_milliseconds()) self.interval = datetime.timedelta(0, 0, 0, value) + # Emit D-Bus signal + self.PropertyChanged(dbus.String("Interval"), + dbus.UInt64(value, variant_level=1)) if getattr(self, "checker_initiator_tag", None) is None: return - if self.enabled: - # Reschedule checker run - gobject.source_remove(self.checker_initiator_tag) - self.checker_initiator_tag = (gobject.timeout_add - (value, self.start_checker)) - self.start_checker() # Start one now, too - + # Reschedule checker run + gobject.source_remove(self.checker_initiator_tag) + self.checker_initiator_tag = (gobject.timeout_add + (value, self.start_checker)) + self.start_checker() # Start one now, too + # Checker - property @dbus_service_property(_interface, signature="s", access="readwrite") def Checker_dbus_property(self, value=None): if value is None: # get return dbus.String(self.checker_command) - self.checker_command = unicode(value) + self.checker_command = value + # Emit D-Bus signal + self.PropertyChanged(dbus.String("Checker"), + dbus.String(self.checker_command, + variant_level=1)) # CheckerRunning - property @dbus_service_property(_interface, signature="b", @@ -1644,9 +1142,9 @@ self._pipe.send(('init', fpr, address)) if not self._pipe.recv(): raise KeyError() - + def __getattribute__(self, name): - if name == '_pipe': + if(name == '_pipe'): return super(ProxyClient, self).__getattribute__(name) self._pipe.send(('getattr', name)) data = self._pipe.recv() @@ -1657,9 +1155,9 @@ self._pipe.send(('funcall', name, args, kwargs)) return self._pipe.recv()[1] return func - + def __setattr__(self, name, value): - if name == '_pipe': + if(name == '_pipe'): return super(ProxyClient, self).__setattr__(name, value) self._pipe.send(('setattr', name, value)) @@ -1676,17 +1174,17 @@ unicode(self.client_address)) logger.debug("Pipe FD: %d", self.server.child_pipe.fileno()) - + session = (gnutls.connection .ClientSession(self.request, gnutls.connection .X509Credentials())) - + # Note: gnutls.connection.X509Credentials is really a # generic GnuTLS certificate credentials object so long as # no X.509 keys are added to it. Therefore, we can use it # here despite using OpenPGP certificates. - + #priority = ':'.join(("NONE", "+VERS-TLS1.1", # "+AES-256-CBC", "+SHA1", # "+COMP-NULL", "+CTYPE-OPENPGP", @@ -1698,39 +1196,38 @@ (gnutls.library.functions .gnutls_priority_set_direct(session._c_object, priority, None)) - + # Start communication using the Mandos protocol # Get protocol number line = self.request.makefile().readline() logger.debug("Protocol version: %r", line) try: if int(line.strip().split()[0]) > 1: - raise RuntimeError(line) - except (ValueError, IndexError, RuntimeError) as error: + raise RuntimeError + except (ValueError, IndexError, RuntimeError), error: logger.error("Unknown protocol version: %s", error) return - + # Start GnuTLS connection try: session.handshake() - except gnutls.errors.GNUTLSError as error: + except gnutls.errors.GNUTLSError, error: logger.warning("Handshake failed: %s", error) # Do not run session.bye() here: the session is not # established. Just abandon the request. return logger.debug("Handshake succeeded") - + approval_required = False try: try: fpr = self.fingerprint(self.peer_certificate (session)) - except (TypeError, - gnutls.errors.GNUTLSError) as error: + except (TypeError, gnutls.errors.GNUTLSError), error: logger.warning("Bad certificate: %s", error) return logger.debug("Fingerprint: %s", fpr) - + try: client = ProxyClient(child_pipe, fpr, self.client_address) @@ -1744,17 +1241,17 @@ while True: if not client.enabled: - logger.info("Client %s is disabled", + logger.warning("Client %s is disabled", client.name) if self.server.use_dbus: # Emit D-Bus signal - client.Rejected("Disabled") + client.Rejected("Disabled") return - if client.approved or not client.approval_delay: + if client._approved or not client.approval_delay: #We are approved or approval is disabled break - elif client.approved is None: + elif client._approved is None: logger.info("Client %s needs approval", client.name) if self.server.use_dbus: @@ -1771,11 +1268,10 @@ return #wait until timeout or approved + #x = float(client._timedelta_to_milliseconds(delay)) time = datetime.datetime.now() client.changedstate.acquire() - client.changedstate.wait( - float(timedelta_to_milliseconds(delay) - / 1000)) + client.changedstate.wait(float(client._timedelta_to_milliseconds(delay) / 1000)) client.changedstate.release() time2 = datetime.datetime.now() if (time2 - time) >= delay: @@ -1796,18 +1292,17 @@ while sent_size < len(client.secret): try: sent = session.send(client.secret[sent_size:]) - except gnutls.errors.GNUTLSError as error: - logger.warning("gnutls send failed", - exc_info=error) + except (gnutls.errors.GNUTLSError), error: + logger.warning("gnutls send failed") return logger.debug("Sent: %d, remaining: %d", sent, len(client.secret) - (sent_size + sent)) sent_size += sent - + logger.info("Sending secret to %s", client.name) - # bump the timeout using extended_timeout - client.bump_timeout(client.extended_timeout) + # bump the timeout as if seen + client.checked_ok() if self.server.use_dbus: # Emit D-Bus signal client.GotSecret() @@ -1817,9 +1312,8 @@ client.approvals_pending -= 1 try: session.bye() - except gnutls.errors.GNUTLSError as error: - logger.warning("GnuTLS bye failed", - exc_info=error) + except (gnutls.errors.GNUTLSError), error: + logger.warning("GnuTLS bye failed") @staticmethod def peer_certificate(session): @@ -1881,7 +1375,7 @@ # Convert the buffer to a Python bytestring fpr = ctypes.string_at(buf, buf_len.value) # Convert the bytestring to hexadecimal notation - hex_fpr = binascii.hexlify(fpr).upper() + hex_fpr = ''.join("%02X" % ord(char) for char in fpr) return hex_fpr @@ -1890,17 +1384,14 @@ def sub_process_main(self, request, address): try: self.finish_request(request, address) - except Exception: + except: self.handle_error(request, address) self.close_request(request) - + def process_request(self, request, address): """Start a new process to process the request.""" - proc = multiprocessing.Process(target = self.sub_process_main, - args = (request, address)) - proc.start() - return proc - + multiprocessing.Process(target = self.sub_process_main, + args = (request, address)).start() class MultiprocessingMixInWithPipe(MultiprocessingMixIn, object): """ adds a pipe to the MixIn """ @@ -1910,16 +1401,15 @@ This function creates a new pipe in self.pipe """ parent_pipe, self.child_pipe = multiprocessing.Pipe() - - proc = MultiprocessingMixIn.process_request(self, request, - client_address) + + super(MultiprocessingMixInWithPipe, + self).process_request(request, client_address) self.child_pipe.close() - self.add_pipe(parent_pipe, proc) - - def add_pipe(self, parent_pipe, proc): + self.add_pipe(parent_pipe) + + def add_pipe(self, parent_pipe): """Dummy function; override as necessary""" - raise NotImplementedError() - + raise NotImplementedError class IPv6_TCPServer(MultiprocessingMixInWithPipe, socketserver.TCPServer, object): @@ -1931,42 +1421,12 @@ use_ipv6: Boolean; to use IPv6 or not """ def __init__(self, server_address, RequestHandlerClass, - interface=None, use_ipv6=True, socketfd=None): - """If socketfd is set, use that file descriptor instead of - creating a new one with socket.socket(). - """ + interface=None, use_ipv6=True): self.interface = interface if use_ipv6: self.address_family = socket.AF_INET6 - if socketfd is not None: - # Save the file descriptor - self.socketfd = socketfd - # Save the original socket.socket() function - self.socket_socket = socket.socket - # To implement --socket, we monkey patch socket.socket. - # - # (When socketserver.TCPServer is a new-style class, we - # could make self.socket into a property instead of monkey - # patching socket.socket.) - # - # Create a one-time-only replacement for socket.socket() - @functools.wraps(socket.socket) - def socket_wrapper(*args, **kwargs): - # Restore original function so subsequent calls are - # not affected. - socket.socket = self.socket_socket - del self.socket_socket - # This time only, return a new socket object from the - # saved file descriptor. - return socket.fromfd(self.socketfd, *args, **kwargs) - # Replace socket.socket() function with wrapper - socket.socket = socket_wrapper - # The socketserver.TCPServer.__init__ will call - # socket.socket(), which might be our replacement, - # socket_wrapper(), if socketfd was set. socketserver.TCPServer.__init__(self, server_address, RequestHandlerClass) - def server_bind(self): """This overrides the normal server_bind() function to bind to an interface if one was specified, and also NOT to @@ -1980,18 +1440,17 @@ try: self.socket.setsockopt(socket.SOL_SOCKET, SO_BINDTODEVICE, - str(self.interface + '\0')) - except socket.error as error: - if error.errno == errno.EPERM: - logger.error("No permission to bind to" - " interface %s", self.interface) - elif error.errno == errno.ENOPROTOOPT: + str(self.interface + + '\0')) + except socket.error, error: + if error[0] == errno.EPERM: + logger.error("No permission to" + " bind to interface %s", + self.interface) + elif error[0] == errno.ENOPROTOOPT: logger.error("SO_BINDTODEVICE not available;" " cannot bind to interface %s", self.interface) - elif error.errno == errno.ENODEV: - logger.error("Interface %s does not exist," - " cannot bind", self.interface) else: raise # Only bind(2) the socket if we really need to. @@ -2000,7 +1459,7 @@ if self.address_family == socket.AF_INET6: any_address = "::" # in6addr_any else: - any_address = "0.0.0.0" # INADDR_ANY + any_address = socket.INADDR_ANY self.server_address = (any_address, self.server_address[1]) elif not self.server_address[1]: @@ -2027,40 +1486,47 @@ """ def __init__(self, server_address, RequestHandlerClass, interface=None, use_ipv6=True, clients=None, - gnutls_priority=None, use_dbus=True, socketfd=None): + gnutls_priority=None, use_dbus=True): self.enabled = False self.clients = clients if self.clients is None: - self.clients = {} + self.clients = set() self.use_dbus = use_dbus self.gnutls_priority = gnutls_priority IPv6_TCPServer.__init__(self, server_address, RequestHandlerClass, interface = interface, - use_ipv6 = use_ipv6, - socketfd = socketfd) + use_ipv6 = use_ipv6) def server_activate(self): if self.enabled: return socketserver.TCPServer.server_activate(self) - def enable(self): self.enabled = True - - def add_pipe(self, parent_pipe, proc): + def add_pipe(self, parent_pipe): # Call "handle_ipc" for both data and EOF events gobject.io_add_watch(parent_pipe.fileno(), gobject.IO_IN | gobject.IO_HUP, functools.partial(self.handle_ipc, - parent_pipe = - parent_pipe, - proc = proc)) - + parent_pipe = parent_pipe)) + def handle_ipc(self, source, condition, parent_pipe=None, - proc = None, client_object=None): - # error, or the other end of multiprocessing.Pipe has closed - if condition & (gobject.IO_ERR | gobject.IO_HUP): - # Wait for other process to exit - proc.join() + client_object=None): + condition_names = { + gobject.IO_IN: "IN", # There is data to read. + gobject.IO_OUT: "OUT", # Data can be written (without + # blocking). + gobject.IO_PRI: "PRI", # There is urgent data to read. + gobject.IO_ERR: "ERR", # Error condition. + gobject.IO_HUP: "HUP" # Hung up (the connection has been + # broken, usually for pipes and + # sockets). + } + conditions_string = ' | '.join(name + for cond, name in + condition_names.iteritems() + if cond & condition) + # error or the other end of multiprocessing.Pipe has closed + if condition & (gobject.IO_ERR | condition & gobject.IO_HUP): return False # Read a request from the child @@ -2071,156 +1537,49 @@ fpr = request[1] address = request[2] - for c in self.clients.itervalues(): + for c in self.clients: if c.fingerprint == fpr: client = c break else: - logger.info("Client not found for fingerprint: %s, ad" - "dress: %s", fpr, address) + logger.warning("Client not found for fingerprint: %s, ad" + "dress: %s", fpr, address) if self.use_dbus: # Emit D-Bus signal - mandos_dbus_service.ClientNotFound(fpr, - address[0]) + mandos_dbus_service.ClientNotFound(fpr, address[0]) parent_pipe.send(False) return False gobject.io_add_watch(parent_pipe.fileno(), gobject.IO_IN | gobject.IO_HUP, functools.partial(self.handle_ipc, - parent_pipe = - parent_pipe, - proc = proc, - client_object = - client)) + parent_pipe = parent_pipe, + client_object = client)) parent_pipe.send(True) - # remove the old hook in favor of the new above hook on - # same fileno + # remove the old hook in favor of the new above hook on same fileno return False if command == 'funcall': funcname = request[1] args = request[2] kwargs = request[3] - parent_pipe.send(('data', getattr(client_object, - funcname)(*args, - **kwargs))) - + parent_pipe.send(('data', getattr(client_object, funcname)(*args, **kwargs))) + if command == 'getattr': attrname = request[1] if callable(client_object.__getattribute__(attrname)): parent_pipe.send(('function',)) else: - parent_pipe.send(('data', client_object - .__getattribute__(attrname))) + parent_pipe.send(('data', client_object.__getattribute__(attrname))) if command == 'setattr': attrname = request[1] value = request[2] setattr(client_object, attrname, value) - + return True -def rfc3339_duration_to_delta(duration): - """Parse an RFC 3339 "duration" and return a datetime.timedelta - - >>> rfc3339_duration_to_delta("P7D") - datetime.timedelta(7) - >>> rfc3339_duration_to_delta("PT60S") - datetime.timedelta(0, 60) - >>> rfc3339_duration_to_delta("PT60M") - datetime.timedelta(0, 3600) - >>> rfc3339_duration_to_delta("PT24H") - datetime.timedelta(1) - >>> rfc3339_duration_to_delta("P1W") - datetime.timedelta(7) - >>> rfc3339_duration_to_delta("PT5M30S") - datetime.timedelta(0, 330) - >>> rfc3339_duration_to_delta("P1DT3M20S") - datetime.timedelta(1, 200) - """ - - # Parsing an RFC 3339 duration with regular expressions is not - # possible - there would have to be multiple places for the same - # values, like seconds. The current code, while more esoteric, is - # cleaner without depending on a parsing library. If Python had a - # built-in library for parsing we would use it, but we'd like to - # avoid excessive use of external libraries. - - # New type for defining tokens, syntax, and semantics all-in-one - Token = collections.namedtuple("Token", - ("regexp", # To match token; if - # "value" is not None, - # must have a "group" - # containing digits - "value", # datetime.timedelta or - # None - "followers")) # Tokens valid after - # this token - # RFC 3339 "duration" tokens, syntax, and semantics; taken from - # the "duration" ABNF definition in RFC 3339, Appendix A. - token_end = Token(re.compile(r"$"), None, frozenset()) - token_second = Token(re.compile(r"(\d+)S"), - datetime.timedelta(seconds=1), - frozenset((token_end,))) - token_minute = Token(re.compile(r"(\d+)M"), - datetime.timedelta(minutes=1), - frozenset((token_second, token_end))) - token_hour = Token(re.compile(r"(\d+)H"), - datetime.timedelta(hours=1), - frozenset((token_minute, token_end))) - token_time = Token(re.compile(r"T"), - None, - frozenset((token_hour, token_minute, - token_second))) - token_day = Token(re.compile(r"(\d+)D"), - datetime.timedelta(days=1), - frozenset((token_time, token_end))) - token_month = Token(re.compile(r"(\d+)M"), - datetime.timedelta(weeks=4), - frozenset((token_day, token_end))) - token_year = Token(re.compile(r"(\d+)Y"), - datetime.timedelta(weeks=52), - frozenset((token_month, token_end))) - token_week = Token(re.compile(r"(\d+)W"), - datetime.timedelta(weeks=1), - frozenset((token_end,))) - token_duration = Token(re.compile(r"P"), None, - frozenset((token_year, token_month, - token_day, token_time, - token_week))), - # Define starting values - value = datetime.timedelta() # Value so far - found_token = None - followers = frozenset(token_duration,) # Following valid tokens - s = duration # String left to parse - # Loop until end token is found - while found_token is not token_end: - # Search for any currently valid tokens - for token in followers: - match = token.regexp.match(s) - if match is not None: - # Token found - if token.value is not None: - # Value found, parse digits - factor = int(match.group(1), 10) - # Add to value so far - value += factor * token.value - # Strip token from string - s = token.regexp.sub("", s, 1) - # Go to found token - found_token = token - # Set valid next tokens - followers = found_token.followers - break - else: - # No currently valid tokens were found - raise ValueError("Invalid RFC 3339 duration") - # End token found - return value - - def string_to_delta(interval): """Parse a string and return a datetime.timedelta @@ -2237,12 +1596,6 @@ >>> string_to_delta('5m 30s') datetime.timedelta(0, 330) """ - - try: - return rfc3339_duration_to_delta(interval) - except ValueError: - pass - timevalue = datetime.timedelta(0) for s in interval.split(): try: @@ -2259,14 +1612,37 @@ elif suffix == "w": delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value) else: - raise ValueError("Unknown suffix {0!r}" - .format(suffix)) - except IndexError as e: + raise ValueError("Unknown suffix %r" % suffix) + except (ValueError, IndexError), e: raise ValueError(*(e.args)) timevalue += delta return timevalue +def if_nametoindex(interface): + """Call the C function if_nametoindex(), or equivalent + + Note: This function cannot accept a unicode string.""" + global if_nametoindex + try: + if_nametoindex = (ctypes.cdll.LoadLibrary + (ctypes.util.find_library("c")) + .if_nametoindex) + except (OSError, AttributeError): + logger.warning("Doing if_nametoindex the hard way") + def if_nametoindex(interface): + "Get an interface index the hard way, i.e. using fcntl()" + SIOCGIFINDEX = 0x8933 # From /usr/include/linux/sockios.h + with contextlib.closing(socket.socket()) as s: + ifreq = fcntl.ioctl(s, SIOCGIFINDEX, + struct.pack(str("16s16x"), + interface)) + interface_index = struct.unpack(str("I"), + ifreq[16:20])[0] + return interface_index + return if_nametoindex(interface) + + def daemon(nochdir = False, noclose = False): """See daemon(3). Standard BSD Unix function. @@ -2280,11 +1656,11 @@ sys.exit() if not noclose: # Close all standard open file descriptors - null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR) + null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR) if not stat.S_ISCHR(os.fstat(null).st_mode): raise OSError(errno.ENODEV, - "{0} not a character device" - .format(os.devnull)) + "%s not a character device" + % os.path.devnull) os.dup2(null, sys.stdin.fileno()) os.dup2(null, sys.stdout.fileno()) os.dup2(null, sys.stderr.fileno()) @@ -2299,7 +1675,7 @@ parser = argparse.ArgumentParser() parser.add_argument("-v", "--version", action="version", - version = "%(prog)s {0}".format(version), + version = "%%(prog)s %s" % version, help="show version number and exit") parser.add_argument("-i", "--interface", metavar="IF", help="Bind to interface IF") @@ -2311,7 +1687,7 @@ help="Run self-test") parser.add_argument("--debug", action="store_true", help="Debug mode; run in foreground and log" - " to terminal", default=None) + " to terminal") parser.add_argument("--debuglevel", metavar="LEVEL", help="Debug level for stdout output") parser.add_argument("--priority", help="GnuTLS" @@ -2324,27 +1700,15 @@ " files") parser.add_argument("--no-dbus", action="store_false", dest="use_dbus", help="Do not provide D-Bus" - " system bus interface", default=None) + " system bus interface") parser.add_argument("--no-ipv6", action="store_false", - dest="use_ipv6", help="Do not use IPv6", - default=None) - parser.add_argument("--no-restore", action="store_false", - dest="restore", help="Do not restore stored" - " state", default=None) - parser.add_argument("--socket", type=int, - help="Specify a file descriptor to a network" - " socket to use instead of creating one") - parser.add_argument("--statedir", metavar="DIR", - help="Directory to save/restore state in") - parser.add_argument("--foreground", action="store_true", - help="Run in foreground", default=None) - + dest="use_ipv6", help="Do not use IPv6") options = parser.parse_args() if options.check: import doctest - fail_count, test_count = doctest.testmod() - sys.exit(os.EX_OK if fail_count == 0 else 1) + doctest.testmod() + sys.exit() # Default values for config file for server-global settings server_defaults = { "interface": "", @@ -2352,15 +1716,11 @@ "port": "", "debug": "False", "priority": - "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224:+SIGN-RSA-RMD160", + "SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP", "servicename": "Mandos", "use_dbus": "True", "use_ipv6": "True", "debuglevel": "", - "restore": "True", - "socket": "", - "statedir": "/var/lib/mandos", - "foreground": "False", } # Parse config file for server-global settings @@ -2371,29 +1731,19 @@ # Convert the SafeConfigParser object to a dict server_settings = server_config.defaults() # Use the appropriate methods on the non-string config options - for option in ("debug", "use_dbus", "use_ipv6", "foreground"): + for option in ("debug", "use_dbus", "use_ipv6"): server_settings[option] = server_config.getboolean("DEFAULT", option) if server_settings["port"]: server_settings["port"] = server_config.getint("DEFAULT", "port") - if server_settings["socket"]: - server_settings["socket"] = server_config.getint("DEFAULT", - "socket") - # Later, stdin will, and stdout and stderr might, be dup'ed - # over with an opened os.devnull. But we don't want this to - # happen with a supplied network socket. - if 0 <= server_settings["socket"] <= 2: - server_settings["socket"] = os.dup(server_settings - ["socket"]) del server_config # Override the settings from the config file with command line # options, if set. for option in ("interface", "address", "port", "debug", "priority", "servicename", "configdir", - "use_dbus", "use_ipv6", "debuglevel", "restore", - "statedir", "socket", "foreground"): + "use_dbus", "use_ipv6", "debuglevel"): value = getattr(options, option) if value is not None: server_settings[option] = value @@ -2402,13 +1752,6 @@ for option in server_settings.keys(): if type(server_settings[option]) is str: server_settings[option] = unicode(server_settings[option]) - # Force all boolean options to be boolean - for option in ("debug", "use_dbus", "use_ipv6", "restore", - "foreground"): - server_settings[option] = bool(server_settings[option]) - # Debug implies foreground - if server_settings["debug"]: - server_settings["foreground"] = True # Now we have our good server settings in "server_settings" ################################################################## @@ -2418,29 +1761,22 @@ debuglevel = server_settings["debuglevel"] use_dbus = server_settings["use_dbus"] use_ipv6 = server_settings["use_ipv6"] - stored_state_path = os.path.join(server_settings["statedir"], - stored_state_file) - foreground = server_settings["foreground"] - - if debug: - initlogger(debug, logging.DEBUG) - else: - if not debuglevel: - initlogger(debug) - else: - level = getattr(logging, debuglevel.upper()) - initlogger(debug, level) - + if server_settings["servicename"] != "Mandos": syslogger.setFormatter(logging.Formatter - ('Mandos ({0}) [%(process)d]:' - ' %(levelname)s: %(message)s' - .format(server_settings - ["servicename"]))) + ('Mandos (%s) [%%(process)d]:' + ' %%(levelname)s: %%(message)s' + % server_settings["servicename"])) # Parse config file with clients - client_config = configparser.SafeConfigParser(Client - .client_defaults) + client_defaults = { "timeout": "1h", + "interval": "5m", + "checker": "fping -q -- %%(host)s", + "host": "", + "approval_delay": "0s", + "approval_duration": "1s", + } + client_config = configparser.SafeConfigParser(client_defaults) client_config.read(os.path.join(server_settings["configdir"], "clients.conf")) @@ -2455,37 +1791,43 @@ use_ipv6=use_ipv6, gnutls_priority= server_settings["priority"], - use_dbus=use_dbus, - socketfd=(server_settings["socket"] - or None)) - if not foreground: - pidfilename = "/run/mandos.pid" - if not os.path.isdir("/run/."): - pidfilename = "/var/run/mandos.pid" - pidfile = None + use_dbus=use_dbus) + if not debug: + pidfilename = "/var/run/mandos.pid" try: pidfile = open(pidfilename, "w") - except IOError as e: - logger.error("Could not open file %r", pidfilename, - exc_info=e) + except IOError: + logger.error("Could not open file %r", pidfilename) - for name in ("_mandos", "mandos", "nobody"): + try: + uid = pwd.getpwnam("_mandos").pw_uid + gid = pwd.getpwnam("_mandos").pw_gid + except KeyError: try: - uid = pwd.getpwnam(name).pw_uid - gid = pwd.getpwnam(name).pw_gid - break + uid = pwd.getpwnam("mandos").pw_uid + gid = pwd.getpwnam("mandos").pw_gid except KeyError: - continue - else: - uid = 65534 - gid = 65534 + try: + uid = pwd.getpwnam("nobody").pw_uid + gid = pwd.getpwnam("nobody").pw_gid + except KeyError: + uid = 65534 + gid = 65534 try: os.setgid(gid) os.setuid(uid) - except OSError as error: - if error.errno != errno.EPERM: - raise + except OSError, error: + if error[0] != errno.EPERM: + raise error + if not debug and not debuglevel: + syslogger.setLevel(logging.WARNING) + console.setLevel(logging.WARNING) + if debuglevel: + level = getattr(logging, debuglevel.upper()) + syslogger.setLevel(level) + console.setLevel(level) + if debug: # Enable all possible GnuTLS debugging @@ -2501,43 +1843,38 @@ .gnutls_global_set_log_function(debug_gnutls)) # Redirect stdin so all checkers get /dev/null - null = os.open(os.devnull, os.O_NOCTTY | os.O_RDWR) + null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR) os.dup2(null, sys.stdin.fileno()) if null > 2: os.close(null) + else: + # No console logging + logger.removeHandler(console) # Need to fork before connecting to D-Bus - if not foreground: + if not debug: # Close all input and output, do double fork, etc. daemon() - # multiprocessing will use threads, so before we use gobject we - # need to inform gobject that threads will be used. - gobject.threads_init() - global main_loop # From the Avahi example code - DBusGMainLoop(set_as_default=True) + DBusGMainLoop(set_as_default=True ) main_loop = gobject.MainLoop() bus = dbus.SystemBus() # End of Avahi example code if use_dbus: try: - bus_name = dbus.service.BusName("se.recompile.Mandos", + bus_name = dbus.service.BusName("se.bsnet.fukt.Mandos", bus, do_not_queue=True) - old_bus_name = (dbus.service.BusName - ("se.bsnet.fukt.Mandos", bus, - do_not_queue=True)) - except dbus.exceptions.NameExistsException as e: - logger.error("Disabling D-Bus:", exc_info=e) + except dbus.exceptions.NameExistsException, e: + logger.error(unicode(e) + ", disabling D-Bus") use_dbus = False server_settings["use_dbus"] = False tcp_server.use_dbus = False protocol = avahi.PROTO_INET6 if use_ipv6 else avahi.PROTO_INET - service = AvahiServiceToSyslog(name = - server_settings["servicename"], - servicetype = "_mandos._tcp", - protocol = protocol, bus = bus) + service = AvahiService(name = server_settings["servicename"], + servicetype = "_mandos._tcp", + protocol = protocol, bus = bus) if server_settings["interface"]: service.interface = (if_nametoindex (str(server_settings["interface"]))) @@ -2548,146 +1885,51 @@ client_class = Client if use_dbus: client_class = functools.partial(ClientDBus, bus = bus) - - client_settings = Client.config_parser(client_config) - old_client_settings = {} - clients_data = {} - - # This is used to redirect stdout and stderr for checker processes - global wnull - wnull = open(os.devnull, "w") # A writable /dev/null - # Only used if server is running in foreground but not in debug - # mode - if debug or not foreground: - wnull.close() - - # Get client data and settings from last running state. - if server_settings["restore"]: - try: - with open(stored_state_path, "rb") as stored_state: - clients_data, old_client_settings = (pickle.load - (stored_state)) - os.remove(stored_state_path) - except IOError as e: - if e.errno == errno.ENOENT: - logger.warning("Could not load persistent state: {0}" - .format(os.strerror(e.errno))) - else: - logger.critical("Could not load persistent state:", - exc_info=e) - raise - except EOFError as e: - logger.warning("Could not load persistent state: " - "EOFError:", exc_info=e) - - with PGPEngine() as pgp: - for client_name, client in clients_data.iteritems(): - # Skip removed clients - if client_name not in client_settings: - continue - - # Decide which value to use after restoring saved state. - # We have three different values: Old config file, - # new config file, and saved state. - # New config value takes precedence if it differs from old - # config value, otherwise use saved state. - for name, value in client_settings[client_name].items(): - try: - # For each value in new config, check if it - # differs from the old config value (Except for - # the "secret" attribute) - if (name != "secret" and - value != old_client_settings[client_name] - [name]): - client[name] = value - except KeyError: - pass - - # Clients who has passed its expire date can still be - # enabled if its last checker was successful. Clients - # whose checker succeeded before we stored its state is - # assumed to have successfully run all checkers during - # downtime. - if client["enabled"]: - if datetime.datetime.utcnow() >= client["expires"]: - if not client["last_checked_ok"]: - logger.warning( - "disabling client {0} - Client never " - "performed a successful checker" - .format(client_name)) - client["enabled"] = False - elif client["last_checker_status"] != 0: - logger.warning( - "disabling client {0} - Client " - "last checker failed with error code {1}" - .format(client_name, - client["last_checker_status"])) - client["enabled"] = False - else: - client["expires"] = (datetime.datetime - .utcnow() - + client["timeout"]) - logger.debug("Last checker succeeded," - " keeping {0} enabled" - .format(client_name)) + def client_config_items(config, section): + special_settings = { + "approved_by_default": + lambda: config.getboolean(section, + "approved_by_default"), + } + for name, value in config.items(section): try: - client["secret"] = ( - pgp.decrypt(client["encrypted_secret"], - client_settings[client_name] - ["secret"])) - except PGPError: - # If decryption fails, we use secret from new settings - logger.debug("Failed to decrypt {0} old secret" - .format(client_name)) - client["secret"] = ( - client_settings[client_name]["secret"]) - - # Add/remove clients based on new changes made to config - for client_name in (set(old_client_settings) - - set(client_settings)): - del clients_data[client_name] - for client_name in (set(client_settings) - - set(old_client_settings)): - clients_data[client_name] = client_settings[client_name] - - # Create all client objects - for client_name, client in clients_data.iteritems(): - tcp_server.clients[client_name] = client_class( - name = client_name, settings = client, - server_settings = server_settings) - + yield (name, special_settings[name]()) + except KeyError: + yield (name, value) + + tcp_server.clients.update(set( + client_class(name = section, + config= dict(client_config_items( + client_config, section))) + for section in client_config.sections())) if not tcp_server.clients: logger.warning("No clients defined") - - if not foreground: - if pidfile is not None: - try: - with pidfile: - pid = os.getpid() - pidfile.write(str(pid) + "\n".encode("utf-8")) - except IOError: - logger.error("Could not write to file %r with PID %d", - pidfilename, pid) - del pidfile + + if not debug: + try: + with pidfile: + pid = os.getpid() + pidfile.write(str(pid) + "\n".encode("utf-8")) + del pidfile + except IOError: + logger.error("Could not write to file %r with PID %d", + pidfilename, pid) + except NameError: + # "pidfile" was never created + pass del pidfilename - + + signal.signal(signal.SIGINT, signal.SIG_IGN) + signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit()) signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit()) if use_dbus: - @alternate_dbus_interfaces({"se.recompile.Mandos": - "se.bsnet.fukt.Mandos"}) - class MandosDBusService(DBusObjectWithProperties): + class MandosDBusService(dbus.service.Object): """A D-Bus proxy object""" def __init__(self): dbus.service.Object.__init__(self, bus, "/") - _interface = "se.recompile.Mandos" - - @dbus_interface_annotations(_interface) - def _foo(self): - return { "org.freedesktop.DBus.Property" - ".EmitsChangedSignal": - "false"} + _interface = "se.bsnet.fukt.Mandos" @dbus.service.signal(_interface, signature="o") def ClientAdded(self, objpath): @@ -2708,8 +1950,7 @@ def GetAllClients(self): "D-Bus method" return dbus.Array(c.dbus_object_path - for c in - tcp_server.clients.itervalues()) + for c in tcp_server.clients) @dbus.service.method(_interface, out_signature="a{oa{sv}}") @@ -2717,15 +1958,15 @@ "D-Bus method" return dbus.Dictionary( ((c.dbus_object_path, c.GetAll("")) - for c in tcp_server.clients.itervalues()), + for c in tcp_server.clients), signature="oa{sv}") @dbus.service.method(_interface, in_signature="o") def RemoveClient(self, object_path): "D-Bus method" - for c in tcp_server.clients.itervalues(): + for c in tcp_server.clients: if c.dbus_object_path == object_path: - del tcp_server.clients[c.name] + tcp_server.clients.remove(c) c.remove_from_connection() # Don't signal anything except ClientRemoved c.disable(quiet=True) @@ -2742,84 +1983,25 @@ "Cleanup function; run on exit" service.cleanup() - multiprocessing.active_children() - wnull.close() - if not (tcp_server.clients or client_settings): - return - - # Store client before exiting. Secrets are encrypted with key - # based on what config file has. If config file is - # removed/edited, old secret will thus be unrecovable. - clients = {} - with PGPEngine() as pgp: - for client in tcp_server.clients.itervalues(): - key = client_settings[client.name]["secret"] - client.encrypted_secret = pgp.encrypt(client.secret, - key) - client_dict = {} - - # A list of attributes that can not be pickled - # + secret. - exclude = set(("bus", "changedstate", "secret", - "checker", "server_settings")) - for name, typ in (inspect.getmembers - (dbus.service.Object)): - exclude.add(name) - - client_dict["encrypted_secret"] = (client - .encrypted_secret) - for attr in client.client_structure: - if attr not in exclude: - client_dict[attr] = getattr(client, attr) - - clients[client.name] = client_dict - del client_settings[client.name]["secret"] - - try: - with (tempfile.NamedTemporaryFile - (mode='wb', suffix=".pickle", prefix='clients-', - dir=os.path.dirname(stored_state_path), - delete=False)) as stored_state: - pickle.dump((clients, client_settings), stored_state) - tempname=stored_state.name - os.rename(tempname, stored_state_path) - except (IOError, OSError) as e: - if not debug: - try: - os.remove(tempname) - except NameError: - pass - if e.errno in (errno.ENOENT, errno.EACCES, errno.EEXIST): - logger.warning("Could not save persistent state: {0}" - .format(os.strerror(e.errno))) - else: - logger.warning("Could not save persistent state:", - exc_info=e) - raise - - # Delete all clients, and settings from config while tcp_server.clients: - name, client = tcp_server.clients.popitem() + client = tcp_server.clients.pop() if use_dbus: client.remove_from_connection() + client.disable_hook = None # Don't signal anything except ClientRemoved client.disable(quiet=True) if use_dbus: # Emit D-Bus signal - mandos_dbus_service.ClientRemoved(client - .dbus_object_path, + mandos_dbus_service.ClientRemoved(client.dbus_object_path, client.name) - client_settings.clear() atexit.register(cleanup) - for client in tcp_server.clients.itervalues(): + for client in tcp_server.clients: if use_dbus: # Emit D-Bus signal mandos_dbus_service.ClientAdded(client.dbus_object_path) - # Need to initiate checking of clients - if client.enabled: - client.init_checker() + client.enable() tcp_server.enable() tcp_server.server_activate() @@ -2828,11 +2010,11 @@ service.port = tcp_server.socket.getsockname()[1] if use_ipv6: logger.info("Now listening on address %r, port %d," - " flowinfo %d, scope_id %d", - *tcp_server.socket.getsockname()) + " flowinfo %d, scope_id %d" + % tcp_server.socket.getsockname()) else: # IPv4 - logger.info("Now listening on address %r, port %d", - *tcp_server.socket.getsockname()) + logger.info("Now listening on address %r, port %d" + % tcp_server.socket.getsockname()) #service.interface = tcp_server.socket.getsockname()[3] @@ -2840,8 +2022,8 @@ # From the Avahi example code try: service.activate() - except dbus.exceptions.DBusException as error: - logger.critical("D-Bus Exception", exc_info=error) + except dbus.exceptions.DBusException, error: + logger.critical("DBusException: %s", error) cleanup() sys.exit(1) # End of Avahi example code @@ -2853,8 +2035,8 @@ logger.debug("Starting main loop") main_loop.run() - except AvahiError as error: - logger.critical("Avahi Error", exc_info=error) + except AvahiError, error: + logger.critical("AvahiError: %s", error) cleanup() sys.exit(1) except KeyboardInterrupt: === modified file 'mandos-clients.conf.xml' --- mandos-clients.conf.xml 2013-10-20 15:25:09 +0000 +++ mandos-clients.conf.xml 2011-02-27 17:26:35 +0000 @@ -3,7 +3,7 @@ "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ /etc/mandos/clients.conf"> - + %common; ]> @@ -20,14 +20,14 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
@@ -36,7 +36,6 @@ 2009 2010 2011 - 2012 Teddy Hogeborn Björn Påhlsson @@ -66,13 +65,8 @@ >mandos 8, read by it at startup. The file needs to list all clients that should be able to use - the service. The settings in this file can be overridden by - runtime changes to the server, which it saves across restarts. - (See the section called PERSISTENT STATE in - mandos8.) However, any changes to this file (including adding and removing - clients) will, at startup, override changes done during runtime. + the service. All clients listed will be regarded as enabled, + even if a client was disabled in a previous run of the server. The format starts with a [section @@ -117,7 +111,7 @@ How long to wait for external approval before resorting to use the value. The - default is PT0S, i.e. not to wait. + default is 0s, i.e. not to wait. The format of TIME is the same @@ -167,12 +161,12 @@ This option is optional. - This option overrides the default shell command that the - server will use to check if the client is still up. Any - output of the command will be ignored, only the exit code - is checked: If the exit code of the command is zero, the - client is considered up. The command will be run using - /bin/sh + This option allows you to override the default shell + command that the server will use to check if the client is + still up. Any output of the command will be ignored, only + the exit code is checked: If the exit code of the command + is zero, the client is considered up. The command will be + run using /bin/sh , so PATH will be searched. The default value for the checker command is - - - - This option is optional. - - - Extended timeout is an added timeout that is given once - after a password has been sent successfully to a client. - The timeout is by default longer than the normal timeout, - and is used for handling the extra long downtime while a - machine is booting up. Time to take into consideration - when changing this value is file system checks and quota - checks. The default value is 15 minutes. - - - The format of TIME is the same - as for timeout below. - - - - - @@ -258,7 +229,7 @@ will wait for a checker to complete until the below timeout occurs, at which time the client will be disabled, and any running checker - killed. The default interval is 2 minutes. + killed. The default interval is 5 minutes. The format of TIME is the same @@ -328,33 +299,23 @@ This option is optional. - The timeout is how long the server will wait, after a - successful checker run, until a client is disabled and not - allowed to get the data this server holds. By default - Mandos will use 5 minutes. See also the - option. - - - The TIME is specified as an RFC - 3339 duration; for example - P1Y2M3DT4H5M6S meaning - one year, two months, three days, four hours, five - minutes, and six seconds. Some values can be omitted, see - RFC 3339 Appendix A for details. - - - - - - - - - Whether this client should be enabled by default. The - default is true. + The timeout is how long the server will wait (for either a + successful checker run or a client receiving its secret) + until a client is disabled and not allowed to get the data + this server holds. By default Mandos will use 1 hour. + + + The TIME is specified as a + space-separated number of values, each of which is a + number and a one-character suffix. The suffix must be one + of d, s, m, + h, and w for days, seconds, + minutes, hours, and weeks, respectively. The values are + added together to give the total time value, so all of + 330s, + 110s 110s 110s, and + 5m 30s will give a value + of five minutes and thirty seconds. @@ -404,7 +365,6 @@ approval_duration, created, enabled, - expires, fingerprint, host, interval, @@ -460,8 +420,8 @@ [DEFAULT] -timeout = PT5M -interval = PT2M +timeout = 1h +interval = 5m checker = fping -q -- %%(host)s # Client "foo" @@ -484,15 +444,15 @@ 4T2zw4dxS5NswXWU0sVEXxjs6PYxuIiCTL7vdpx8QjBkrPWDrAbcMyBr2O QlnHIvPzEArRQLo= host = foo.example.org -interval = PT1M +interval = 1m # Client "bar" [bar] fingerprint = 3e393aeaefb84c7e89e2f547b3a107558fca3a27 secfile = /etc/mandos/bar-secret -timeout = PT15M +timeout = 15m approved_by_default = False -approval_delay = PT30S +approval_delay = 30s @@ -500,31 +460,13 @@ SEE ALSO - intro - 8mandos, mandos-keygen 8, mandos.conf 5, mandos - 8, - fping 8 - - - - RFC 3339: Date and Time on the Internet: - Timestamps - - - - The time intervals are in the "duration" format, as - specified in ABNF in Appendix A of RFC 3339. - - - - === modified file 'mandos-ctl' --- mandos-ctl 2014-02-16 02:42:42 +0000 +++ mandos-ctl 2011-03-15 20:13:05 +0000 @@ -3,8 +3,8 @@ # # Mandos Monitor - Control and monitor the Mandos server # -# Copyright © 2008-2012 Teddy Hogeborn -# Copyright © 2008-2012 Björn Påhlsson +# Copyright © 2008-2010 Teddy Hogeborn +# Copyright © 2008-2010 Björn Påhlsson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,27 +17,21 @@ # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License -# along with this program. If not, see -# . +# along with this program. If not, see . # -# Contact the authors at . +# Contact the authors at . # from __future__ import (division, absolute_import, print_function, unicode_literals) -from future_builtins import * - import sys +import dbus import argparse import locale import datetime import re import os -import collections -import doctest - -import dbus locale.setlocale(locale.LC_ALL, "") @@ -58,15 +52,14 @@ "ApprovalDelay": "Approval Delay", "ApprovalDuration": "Approval Duration", "Checker": "Checker", - "ExtendedTimeout" : "Extended Timeout" } defaultkeywords = ("Name", "Enabled", "Timeout", "LastCheckedOK") -domain = "se.recompile" +domain = "se.bsnet.fukt" busname = domain + ".Mandos" server_path = "/" server_interface = domain + ".Mandos" client_interface = domain + ".Mandos.Client" -version = "1.6.3" +version = "1.3.0" def timedelta_to_milliseconds(td): """Convert a datetime.timedelta object to milliseconds""" @@ -76,112 +69,12 @@ def milliseconds_to_string(ms): td = datetime.timedelta(0, 0, 0, ms) - return ("{days}{hours:02}:{minutes:02}:{seconds:02}" - .format(days = "{0}T".format(td.days) if td.days else "", - hours = td.seconds // 3600, - minutes = (td.seconds % 3600) // 60, - seconds = td.seconds % 60, - )) - - -def rfc3339_duration_to_delta(duration): - """Parse an RFC 3339 "duration" and return a datetime.timedelta - - >>> rfc3339_duration_to_delta("P7D") - datetime.timedelta(7) - >>> rfc3339_duration_to_delta("PT60S") - datetime.timedelta(0, 60) - >>> rfc3339_duration_to_delta("PT60M") - datetime.timedelta(0, 3600) - >>> rfc3339_duration_to_delta("PT24H") - datetime.timedelta(1) - >>> rfc3339_duration_to_delta("P1W") - datetime.timedelta(7) - >>> rfc3339_duration_to_delta("PT5M30S") - datetime.timedelta(0, 330) - >>> rfc3339_duration_to_delta("P1DT3M20S") - datetime.timedelta(1, 200) - """ - - # Parsing an RFC 3339 duration with regular expressions is not - # possible - there would have to be multiple places for the same - # values, like seconds. The current code, while more esoteric, is - # cleaner without depending on a parsing library. If Python had a - # built-in library for parsing we would use it, but we'd like to - # avoid excessive use of external libraries. - - # New type for defining tokens, syntax, and semantics all-in-one - Token = collections.namedtuple("Token", - ("regexp", # To match token; if - # "value" is not None, - # must have a "group" - # containing digits - "value", # datetime.timedelta or - # None - "followers")) # Tokens valid after - # this token - # RFC 3339 "duration" tokens, syntax, and semantics; taken from - # the "duration" ABNF definition in RFC 3339, Appendix A. - token_end = Token(re.compile(r"$"), None, frozenset()) - token_second = Token(re.compile(r"(\d+)S"), - datetime.timedelta(seconds=1), - frozenset((token_end,))) - token_minute = Token(re.compile(r"(\d+)M"), - datetime.timedelta(minutes=1), - frozenset((token_second, token_end))) - token_hour = Token(re.compile(r"(\d+)H"), - datetime.timedelta(hours=1), - frozenset((token_minute, token_end))) - token_time = Token(re.compile(r"T"), - None, - frozenset((token_hour, token_minute, - token_second))) - token_day = Token(re.compile(r"(\d+)D"), - datetime.timedelta(days=1), - frozenset((token_time, token_end))) - token_month = Token(re.compile(r"(\d+)M"), - datetime.timedelta(weeks=4), - frozenset((token_day, token_end))) - token_year = Token(re.compile(r"(\d+)Y"), - datetime.timedelta(weeks=52), - frozenset((token_month, token_end))) - token_week = Token(re.compile(r"(\d+)W"), - datetime.timedelta(weeks=1), - frozenset((token_end,))) - token_duration = Token(re.compile(r"P"), None, - frozenset((token_year, token_month, - token_day, token_time, - token_week))), - # Define starting values - value = datetime.timedelta() # Value so far - found_token = None - followers = frozenset(token_duration,) # Following valid tokens - s = duration # String left to parse - # Loop until end token is found - while found_token is not token_end: - # Search for any currently valid tokens - for token in followers: - match = token.regexp.match(s) - if match is not None: - # Token found - if token.value is not None: - # Value found, parse digits - factor = int(match.group(1), 10) - # Add to value so far - value += factor * token.value - # Strip token from string - s = token.regexp.sub("", s, 1) - # Go to found token - found_token = token - # Set valid next tokens - followers = found_token.followers - break - else: - # No currently valid tokens were found - raise ValueError("Invalid RFC 3339 duration") - # End token found - return value - + return ("%(days)s%(hours)02d:%(minutes)02d:%(seconds)02d" + % { "days": "%dT" % td.days if td.days else "", + "hours": td.seconds // 3600, + "minutes": (td.seconds % 3600) // 60, + "seconds": td.seconds % 60, + }) def string_to_delta(interval): """Parse a string and return a datetime.timedelta @@ -199,54 +92,52 @@ >>> string_to_delta("5m 30s") datetime.timedelta(0, 330) """ - - try: - return rfc3339_duration_to_delta(interval) - except ValueError: - pass - - value = datetime.timedelta(0) - regexp = re.compile(r"(\d+)([dsmhw]?)") - - for num, suffix in regexp.findall(interval): - if suffix == "d": - value += datetime.timedelta(int(num)) - elif suffix == "s": - value += datetime.timedelta(0, int(num)) - elif suffix == "m": - value += datetime.timedelta(0, 0, 0, 0, int(num)) - elif suffix == "h": - value += datetime.timedelta(0, 0, 0, 0, 0, int(num)) - elif suffix == "w": - value += datetime.timedelta(0, 0, 0, 0, 0, 0, int(num)) - elif suffix == "": - value += datetime.timedelta(0, 0, 0, int(num)) - return value + timevalue = datetime.timedelta(0) + regexp = re.compile("\d+[dsmhw]") + + for s in regexp.findall(interval): + try: + suffix = unicode(s[-1]) + value = int(s[:-1]) + if suffix == "d": + delta = datetime.timedelta(value) + elif suffix == "s": + delta = datetime.timedelta(0, value) + elif suffix == "m": + delta = datetime.timedelta(0, 0, 0, 0, value) + elif suffix == "h": + delta = datetime.timedelta(0, 0, 0, 0, 0, value) + elif suffix == "w": + delta = datetime.timedelta(0, 0, 0, 0, 0, 0, value) + else: + raise ValueError + except (ValueError, IndexError): + raise ValueError + timevalue += delta + return timevalue 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"): + "ApprovalDuration"): return milliseconds_to_string(value) return unicode(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) + format_string = " ".join("%%-%ds" % + max(len(tablewords[key]), + max(len(valuetostring(client[key], + key)) + for client in + clients)) + for key in keywords) # Print header line - print(format_string.format(**tablewords)) + print(format_string % tuple(tablewords[key] for key in keywords)) for client in clients: - print(format_string.format(**dict((key, - valuetostring(client[key], - key)) - for key in keywords))) + print(format_string % tuple(valuetostring(client[key], key) + for key in keywords)) def has_actions(options): return any((options.enable, @@ -258,7 +149,6 @@ 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, @@ -271,7 +161,7 @@ def main(): parser = argparse.ArgumentParser() parser.add_argument("--version", action="version", - version = "%(prog)s {0}".format(version), + version = "%%prog %s" % version, help="show version number and exit") parser.add_argument("-a", "--all", action="store_true", help="Select all clients") @@ -295,8 +185,6 @@ 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", @@ -316,22 +204,16 @@ 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() - if has_actions(options) and not (options.client or options.all): + if has_actions(options) and not options.client and not options.all: parser.error("Options require clients names or --all.") if options.verbose and has_actions(options): parser.error("--verbose can only be used alone or with" " --all.") if options.all and not has_actions(options): parser.error("--all requires an action.") - - if options.check: - fail_count, test_count = doctest.testmod() - sys.exit(os.EX_OK if fail_count == 0 else 1) try: bus = dbus.SystemBus() @@ -356,7 +238,7 @@ #restore stderr os.dup2(stderrcopy, sys.stderr.fileno()) os.close(stderrcopy) - except dbus.exceptions.DBusException: + except dbus.exceptions.DBusException, e: print("Access denied: Accessing mandos server through dbus.", file=sys.stderr) sys.exit(1) @@ -376,8 +258,8 @@ clients[client_objc] = client break else: - print("Client not found on server: {0!r}" - .format(name), file=sys.stderr) + print("Client not found on server: %r" % name, + file=sys.stderr) sys.exit(1) if not has_actions(options) and clients: @@ -388,8 +270,7 @@ "LastEnabled", "ApprovalPending", "ApprovedByDefault", "LastApprovalRequest", "ApprovalDelay", - "ApprovalDuration", "Checker", - "ExtendedTimeout") + "ApprovalDuration", "Checker") else: keywords = defaultkeywords @@ -397,58 +278,63 @@ 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, - timedelta_to_milliseconds - (string_to_delta(value))) if options.remove: mandos_serv.RemoveClient(client.__dbus_object_path__) if options.enable: - set_client_prop("Enabled", dbus.Boolean(True)) + client.Enable(dbus_interface=client_interface) if options.disable: - set_client_prop("Enabled", dbus.Boolean(False)) + client.Disable(dbus_interface=client_interface) if options.bump_timeout: - set_client_prop("LastCheckedOK", "") + client.CheckedOK(dbus_interface=client_interface) if options.start_checker: - set_client_prop("CheckerRunning", dbus.Boolean(True)) + client.StartChecker(dbus_interface=client_interface) if options.stop_checker: - set_client_prop("CheckerRunning", dbus.Boolean(False)) + client.StopChecker(dbus_interface=client_interface) if options.is_enabled: sys.exit(0 if client.Get(client_interface, "Enabled", dbus_interface= dbus.PROPERTIES_IFACE) else 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.checker: + client.Set(client_interface, "Checker", + options.checker, + dbus_interface=dbus.PROPERTIES_IFACE) + if options.host: + client.Set(client_interface, "Host", options.host, + dbus_interface=dbus.PROPERTIES_IFACE) + if options.interval: + client.Set(client_interface, "Interval", + timedelta_to_milliseconds + (string_to_delta(options.interval)), + dbus_interface=dbus.PROPERTIES_IFACE) + if options.approval_delay: + client.Set(client_interface, "ApprovalDelay", + timedelta_to_milliseconds + (string_to_delta(options. + approval_delay)), + dbus_interface=dbus.PROPERTIES_IFACE) + if options.approval_duration: + client.Set(client_interface, "ApprovalDuration", + timedelta_to_milliseconds + (string_to_delta(options. + approval_duration)), + dbus_interface=dbus.PROPERTIES_IFACE) + if options.timeout: + client.Set(client_interface, "Timeout", + timedelta_to_milliseconds + (string_to_delta(options.timeout)), + dbus_interface=dbus.PROPERTIES_IFACE) + if options.secret: + client.Set(client_interface, "Secret", + dbus.ByteArray(open(options.secret, + "rb").read()), + dbus_interface=dbus.PROPERTIES_IFACE) if options.approved_by_default is not None: - set_client_prop("ApprovedByDefault", - dbus.Boolean(options - .approved_by_default)) + client.Set(client_interface, "ApprovedByDefault", + dbus.Boolean(options + .approved_by_default), + dbus_interface=dbus.PROPERTIES_IFACE) if options.approve: client.Approve(dbus.Boolean(True), dbus_interface=client_interface) === modified file 'mandos-ctl.xml' --- mandos-ctl.xml 2012-06-22 23:33:56 +0000 +++ mandos-ctl.xml 2011-02-27 17:26:35 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,21 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2010 2011 - 2012 Teddy Hogeborn Björn Påhlsson @@ -96,11 +95,6 @@ - - - - - - &COMMANDNAME; - - @@ -328,19 +318,6 @@
- - - - - - Set the extended_timeout option of the - specified client(s); see mandos-clients.conf5. - - - - - - - - Run self-tests. This includes any unit tests, etc. - - - - @@ -586,8 +554,6 @@ SEE ALSO - intro - 8mandos, mandos 8, mandos-clients.conf === modified file 'mandos-keygen' --- mandos-keygen 2014-01-21 21:04:25 +0000 +++ mandos-keygen 2011-03-08 19:41:59 +0000 @@ -2,8 +2,8 @@ # # Mandos key generator - create a new OpenPGP key for a Mandos client # -# Copyright © 2008-2013 Teddy Hogeborn -# Copyright © 2008-2013 Björn Påhlsson +# Copyright © 2008-2011 Teddy Hogeborn +# Copyright © 2008-2011 Björn Påhlsson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -18,19 +18,19 @@ # You should have received a copy of the GNU General Public License # along with this program. If not, see . # -# Contact the authors at . +# Contact the authors at . # -VERSION="1.6.3" +VERSION="1.3.0" KEYDIR="/etc/keys/mandos" -KEYTYPE=RSA -KEYLENGTH=4096 -SUBKEYTYPE=RSA -SUBKEYLENGTH=4096 +KEYTYPE=DSA +KEYLENGTH=2048 +SUBKEYTYPE=ELG-E +SUBKEYLENGTH=2048 KEYNAME="`hostname --fqdn 2>/dev/null || hostname`" KEYEMAIL="" -KEYCOMMENT="" +KEYCOMMENT="Mandos client key" KEYEXPIRE=0 FORCE=no KEYCOMMENT_ORIG="$KEYCOMMENT" @@ -60,18 +60,19 @@ -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 Key type. Default is DSA. -l BITS, --length BITS - Key length in bits. Default is 4096. + Key length in bits. Default is 2048. -s TYPE, --subtype TYPE - Subkey type. Default is RSA. + Subkey type. Default is ELG-E. -L BITS, --sublength BITS - Subkey length in bits. Default is 4096. + Subkey length in bits. Default is 2048. -n NAME, --name NAME Name of key. Default is the FQDN. -e ADDRESS, --email ADDRESS Email address of key. Default is empty. -c TEXT, --comment TEXT - Comment field for key. The default is empty. + Comment field for key. The default value is + "Mandos client key". -x TIME, --expire TIME Key expire time. Default is no expiration. See gpg(1) for syntax. @@ -191,7 +192,7 @@ shred --remove \"$RINGDIR\"/sec*; test -n \"$BATCHFILE\" && rm --force \"$BATCHFILE\"; \ rm --recursive --force \"$RINGDIR\"; -tty --quiet && stty echo; \ +stty echo; \ " EXIT set -e @@ -203,10 +204,10 @@ cat >"$BATCHFILE" <<-EOF Key-Type: $KEYTYPE Key-Length: $KEYLENGTH - Key-Usage: sign,auth + #Key-Usage: encrypt,sign,auth Subkey-Type: $SUBKEYTYPE Subkey-Length: $SUBKEYLENGTH - Subkey-Usage: encrypt + #Subkey-Usage: encrypt,sign,auth Name-Real: $KEYNAME $KEYCOMMENTLINE $KEYEMAILLINE @@ -288,39 +289,31 @@ FILECOMMENT="Encrypted password for a Mandos client" - while [ ! -s "$SECFILE" ]; do - if [ -n "$PASSFILE" ]; then - cat "$PASSFILE" + if [ -n "$PASSFILE" ]; then + cat "$PASSFILE" + else + stty -echo + echo -n "Enter passphrase: " >&2 + first="$(head --lines=1 | tr --delete '\n')" + echo >&2 + echo -n "Repeat passphrase: " >&2 + second="$(head --lines=1 | tr --delete '\n')" + echo >&2 + stty echo + if [ "$first" != "$second" ]; then + echo "Passphrase mismatch" >&2 + touch "$RINGDIR"/mismatch else - tty --quiet && stty -echo - echo -n "Enter passphrase: " >&2 - read first - tty --quiet && echo >&2 - echo -n "Repeat passphrase: " >&2 - read second - if tty --quiet; then - echo >&2 - stty echo - fi - if [ "$first" != "$second" ]; then - echo "Passphrase mismatch" >&2 - touch "$RINGDIR"/mismatch - else - echo -n "$first" - fi - fi | gpg --quiet --batch --no-tty --no-options --enable-dsa2 \ - --homedir "$RINGDIR" --trust-model always --armor \ - --encrypt --sign --recipient "$FINGERPRINT" --comment \ - "$FILECOMMENT" > "$SECFILE" - if [ -e "$RINGDIR"/mismatch ]; then - rm --force "$RINGDIR"/mismatch - if tty --quiet; then - > "$SECFILE" - else - exit 1 - fi + echo -n "$first" fi - done + fi | gpg --quiet --batch --no-tty --no-options --enable-dsa2 \ + --homedir "$RINGDIR" --trust-model always --armor --encrypt \ + --sign --recipient "$FINGERPRINT" --comment "$FILECOMMENT" \ + > "$SECFILE" + if [ -e "$RINGDIR"/mismatch ]; then + rm --force "$RINGDIR"/mismatch + exit 1 + fi cat <<-EOF [$KEYNAME] === modified file 'mandos-keygen.xml' --- mandos-keygen.xml 2013-10-22 19:24:01 +0000 +++ mandos-keygen.xml 2009-01-04 21:54:55 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,22 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2008 2009 - 2011 - 2012 Teddy Hogeborn Björn Påhlsson @@ -215,7 +213,7 @@ Target directory for key files. Default is - /etc/mandos. + /etc/mandos. @@ -227,7 +225,7 @@ TYPE - Key type. Default is RSA. + Key type. Default is DSA. @@ -239,7 +237,7 @@ BITS - Key length in bits. Default is 4096. + Key length in bits. Default is 2048. @@ -251,7 +249,7 @@ KEYTYPE - Subkey type. Default is RSA (Elgamal + Subkey type. Default is ELG-E (Elgamal encryption-only). @@ -264,7 +262,7 @@ BITS - Subkey length in bits. Default is 4096. + Subkey length in bits. Default is 2048. @@ -288,7 +286,8 @@ TEXT - Comment field for key. Default is empty. + Comment field for key. The default value is + Mandos client key. @@ -411,7 +410,7 @@ - /tmp + /tmp Temporary files will be written here if @@ -452,9 +451,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 key in + /etc/mandos and output a section suitable + for clients.conf. &COMMANDNAME; --password @@ -493,8 +492,6 @@ SEE ALSO - intro - 8mandos, gpg 1, mandos-clients.conf === modified file 'mandos-monitor' --- mandos-monitor 2014-01-21 21:04:25 +0000 +++ mandos-monitor 2011-03-08 19:41:59 +0000 @@ -3,8 +3,8 @@ # # Mandos Monitor - Control and monitor the Mandos server # -# Copyright © 2009-2013 Teddy Hogeborn -# Copyright © 2009-2013 Björn Påhlsson +# Copyright © 2009-2011 Teddy Hogeborn +# Copyright © 2009-2011 Björn Påhlsson # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by @@ -17,18 +17,12 @@ # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License -# along with this program. If not, see -# . +# along with this program. If not, see . # -# Contact the authors at . +# Contact the authors at . # -from __future__ import (division, absolute_import, print_function, - unicode_literals) -try: - from future_builtins import * -except ImportError: - pass +from __future__ import division, absolute_import, print_function, unicode_literals import sys import os @@ -40,28 +34,32 @@ import urwid from dbus.mainloop.glib import DBusGMainLoop -try: - import gobject -except ImportError: - from gi.repository import GObject as gobject +import gobject import dbus +import UserList + import locale -if sys.version_info[0] == 2: - str = unicode - locale.setlocale(locale.LC_ALL, '') import logging logging.getLogger('dbus.proxies').setLevel(logging.CRITICAL) # Some useful constants -domain = 'se.recompile' +domain = 'se.bsnet.fukt' server_interface = domain + '.Mandos' client_interface = domain + '.Mandos.Client' -version = "1.6.3" +version = "1.3.0" + +# Always run in monochrome mode +urwid.curses_display.curses.has_colors = lambda : False + +# Urwid doesn't support blinking, but we want it. Since we have no +# use for underline on its own, we make underline also always blink. +urwid.curses_display.curses.A_UNDERLINE |= ( + urwid.curses_display.curses.A_BLINK) def isoformat_to_datetime(iso): "Parse an ISO 8601 date string to a datetime.datetime()" @@ -84,26 +82,22 @@ properties and calls a hook function when any of them are changed. """ - def __init__(self, proxy_object=None, properties=None, **kwargs): + def __init__(self, proxy_object=None, *args, **kwargs): self.proxy = proxy_object # Mandos Client proxy object - self.properties = dict() if properties is None else properties - self.property_changed_match = ( - self.proxy.connect_to_signal("PropertyChanged", - self._property_changed, - client_interface, - byte_arrays=True)) - - if properties is None: - self.properties.update( - self.proxy.GetAll(client_interface, - dbus_interface - = dbus.PROPERTIES_IFACE)) - - super(MandosClientPropertyCache, self).__init__(**kwargs) - - def _property_changed(self, property, value): - """Helper which takes positional arguments""" - return self.property_changed(property=property, value=value) + + self.properties = dict() + self.proxy.connect_to_signal("PropertyChanged", + self.property_changed, + client_interface, + byte_arrays=True) + + self.properties.update( + self.proxy.GetAll(client_interface, + dbus_interface = dbus.PROPERTIES_IFACE)) + + #XXX This break good super behaviour! +# super(MandosClientPropertyCache, self).__init__( +# *args, **kwargs) def property_changed(self, property=None, value=None): """This is called whenever we get a PropertyChanged signal @@ -111,9 +105,6 @@ """ # Update properties dict with new value self.properties[property] = value - - def delete(self): - self.property_changed_match.remove() class MandosClientWidget(urwid.FlowWidget, MandosClientPropertyCache): @@ -121,7 +112,7 @@ """ def __init__(self, server_proxy_object=None, update_hook=None, - delete_hook=None, logger=None, **kwargs): + delete_hook=None, logger=None, *args, **kwargs): # Called on update self.update_hook = update_hook # Called on delete @@ -132,100 +123,136 @@ self.logger = logger self._update_timer_callback_tag = None + self._update_timer_callback_lock = 0 + self.last_checker_failed = False # The widget shown normally self._text_widget = urwid.Text("") # The widget shown when we have focus self._focus_text_widget = urwid.Text("") - super(MandosClientWidget, self).__init__(**kwargs) + super(MandosClientWidget, self).__init__( + update_hook=update_hook, delete_hook=delete_hook, + *args, **kwargs) self.update() self.opened = False - self.match_objects = ( - self.proxy.connect_to_signal("CheckerCompleted", - self.checker_completed, - client_interface, - byte_arrays=True), - self.proxy.connect_to_signal("CheckerStarted", - self.checker_started, - client_interface, - byte_arrays=True), - self.proxy.connect_to_signal("GotSecret", - self.got_secret, - client_interface, - byte_arrays=True), - self.proxy.connect_to_signal("NeedApproval", - self.need_approval, - client_interface, - byte_arrays=True), - self.proxy.connect_to_signal("Rejected", - self.rejected, - client_interface, - byte_arrays=True)) - #self.logger('Created client {0}' - # .format(self.properties["Name"])) + last_checked_ok = isoformat_to_datetime(self.properties + ["LastCheckedOK"]) + if last_checked_ok is None: + self.last_checker_failed = True + else: + self.last_checker_failed = ((datetime.datetime.utcnow() + - last_checked_ok) + > datetime.timedelta + (milliseconds= + self.properties + ["Interval"])) + + if self.last_checker_failed: + self.using_timer(True) + + if self.need_approval: + self.using_timer(True) + + self.proxy.connect_to_signal("CheckerCompleted", + self.checker_completed, + client_interface, + byte_arrays=True) + self.proxy.connect_to_signal("CheckerStarted", + self.checker_started, + client_interface, + byte_arrays=True) + self.proxy.connect_to_signal("GotSecret", + self.got_secret, + client_interface, + byte_arrays=True) + self.proxy.connect_to_signal("NeedApproval", + self.need_approval, + client_interface, + byte_arrays=True) + self.proxy.connect_to_signal("Rejected", + self.rejected, + client_interface, + byte_arrays=True) + def property_changed(self, property=None, value=None): + super(self, MandosClientWidget).property_changed(property, + value) + if property == "ApprovalPending": + using_timer(bool(value)) + def using_timer(self, flag): """Call this method with True or False when timer should be activated or deactivated. """ - if flag and self._update_timer_callback_tag is None: - # Will update the shown timer value every second + old = self._update_timer_callback_lock + if flag: + self._update_timer_callback_lock += 1 + else: + self._update_timer_callback_lock -= 1 + if old == 0 and self._update_timer_callback_lock: self._update_timer_callback_tag = (gobject.timeout_add (1000, self.update_timer)) - elif not (flag or self._update_timer_callback_tag is None): + elif old and self._update_timer_callback_lock == 0: gobject.source_remove(self._update_timer_callback_tag) self._update_timer_callback_tag = None def checker_completed(self, exitstatus, condition, command): if exitstatus == 0: + if self.last_checker_failed: + self.last_checker_failed = False + self.using_timer(False) + #self.logger('Checker for client %s (command "%s")' + # ' was successful' + # % (self.properties["Name"], command)) self.update() return # Checker failed + if not self.last_checker_failed: + self.last_checker_failed = True + self.using_timer(True) if os.WIFEXITED(condition): - self.logger('Checker for client {0} (command "{1}")' - ' failed with exit code {2}' - .format(self.properties["Name"], command, - os.WEXITSTATUS(condition))) + self.logger('Checker for client %s (command "%s")' + ' failed with exit code %s' + % (self.properties["Name"], command, + os.WEXITSTATUS(condition))) elif os.WIFSIGNALED(condition): - self.logger('Checker for client {0} (command "{1}") was' - ' killed by signal {2}' - .format(self.properties["Name"], command, - os.WTERMSIG(condition))) + self.logger('Checker for client %s (command "%s")' + ' was killed by signal %s' + % (self.properties["Name"], command, + os.WTERMSIG(condition))) elif os.WCOREDUMP(condition): - self.logger('Checker for client {0} (command "{1}")' + self.logger('Checker for client %s (command "%s")' ' dumped core' - .format(self.properties["Name"], command)) + % (self.properties["Name"], command)) else: - self.logger('Checker for client {0} completed' - ' mysteriously' - .format(self.properties["Name"])) + self.logger('Checker for client %s completed' + ' mysteriously') self.update() def checker_started(self, command): - """Server signals that a checker started. This could be useful - to log in the future. """ - #self.logger('Client {0} started checker "{1}"' - # .format(self.properties["Name"], - # str(command))) + #self.logger('Client %s started checker "%s"' + # % (self.properties["Name"], unicode(command))) pass def got_secret(self): - self.logger('Client {0} received its secret' - .format(self.properties["Name"])) + self.last_checker_failed = False + self.logger('Client %s received its secret' + % self.properties["Name"]) def need_approval(self, timeout, default): if not default: - message = 'Client {0} needs approval within {1} seconds' + message = 'Client %s needs approval within %s seconds' else: - message = 'Client {0} will get its secret in {1} seconds' - self.logger(message.format(self.properties["Name"], - timeout/1000)) + message = 'Client %s will get its secret in %s seconds' + self.logger(message + % (self.properties["Name"], timeout/1000)) + self.using_timer(True) def rejected(self, reason): - self.logger('Client {0} was rejected; reason: {1}' - .format(self.properties["Name"], reason)) + self.logger('Client %s was rejected; reason: %s' + % (self.properties["Name"], reason)) def selectable(self): """Make this a "selectable" widget. @@ -253,14 +280,14 @@ "bold-underline-blink": "bold-underline-blink-standout", } - + # Rebuild focus and non-focus widgets using current properties - + # Base part of a client. Name! - base = '{name}: '.format(name=self.properties["Name"]) + base = ('%(name)s: ' + % {"name": self.properties["Name"]}) if not self.properties["Enabled"]: message = "DISABLED" - self.using_timer(False) elif self.properties["ApprovalPending"]: timeout = datetime.timedelta(milliseconds = self.properties @@ -268,36 +295,31 @@ last_approval_request = isoformat_to_datetime( self.properties["LastApprovalRequest"]) if last_approval_request is not None: - timer = max(timeout - (datetime.datetime.utcnow() - - last_approval_request), - datetime.timedelta()) + timer = timeout - (datetime.datetime.utcnow() + - last_approval_request) else: timer = datetime.timedelta() if self.properties["ApprovedByDefault"]: - message = "Approval in {0}. (d)eny?" - else: - message = "Denial in {0}. (a)pprove?" - message = message.format(str(timer).rsplit(".", 1)[0]) - self.using_timer(True) - elif self.properties["LastCheckerStatus"] != 0: - # When checker has failed, show timer until client expires - expires = self.properties["Expires"] - if expires == "": - timer = datetime.timedelta(0) - else: - expires = (datetime.datetime.strptime - (expires, '%Y-%m-%dT%H:%M:%S.%f')) - timer = max(expires - datetime.datetime.utcnow(), - datetime.timedelta()) + message = "Approval in %s. (d)eny?" + else: + message = "Denial in %s. (a)pprove?" + message = message % unicode(timer).rsplit(".", 1)[0] + elif self.last_checker_failed: + timeout = datetime.timedelta(milliseconds + = self.properties + ["Timeout"]) + last_ok = isoformat_to_datetime( + max((self.properties["LastCheckedOK"] + or self.properties["Created"]), + self.properties["LastEnabled"])) + timer = timeout - (datetime.datetime.utcnow() - last_ok) message = ('A checker has failed! Time until client' - ' gets disabled: {0}' - .format(str(timer).rsplit(".", 1)[0])) - self.using_timer(True) + ' gets disabled: %s' + % unicode(timer).rsplit(".", 1)[0]) else: message = "enabled" - self.using_timer(False) - self._text = "{0}{1}".format(base, message) - + self._text = "%s%s" % (base, message) + if not urwid.supports_unicode(): self._text = self._text.encode("ascii", "replace") textlist = [("normal", self._text)] @@ -315,21 +337,16 @@ self.update_hook() def update_timer(self): - """called by gobject. Will indefinitely loop until - gobject.source_remove() on tag is called""" + "called by gobject" self.update() return True # Keep calling this - def delete(self, **kwargs): + def delete(self): if self._update_timer_callback_tag is not None: gobject.source_remove(self._update_timer_callback_tag) self._update_timer_callback_tag = None - for match in self.match_objects: - match.remove() - self.match_objects = () if self.delete_hook is not None: self.delete_hook(self) - return super(MandosClientWidget, self).delete(**kwargs) def render(self, maxcolrow, focus=False): """Render differently if we have focus. @@ -341,32 +358,24 @@ """Handle keys. This overrides the method from urwid.FlowWidget""" if key == "+": - self.proxy.Enable(dbus_interface = client_interface, - ignore_reply=True) + self.proxy.Enable(dbus_interface = client_interface) elif key == "-": - self.proxy.Disable(dbus_interface = client_interface, - ignore_reply=True) + self.proxy.Disable(dbus_interface = client_interface) elif key == "a": self.proxy.Approve(dbus.Boolean(True, variant_level=1), - dbus_interface = client_interface, - ignore_reply=True) + dbus_interface = client_interface) elif key == "d": self.proxy.Approve(dbus.Boolean(False, variant_level=1), - dbus_interface = client_interface, - ignore_reply=True) + dbus_interface = client_interface) elif key == "R" or key == "_" or key == "ctrl k": self.server_proxy_object.RemoveClient(self.proxy - .object_path, - ignore_reply=True) + .object_path) elif key == "s": - self.proxy.StartChecker(dbus_interface = client_interface, - ignore_reply=True) + self.proxy.StartChecker(dbus_interface = client_interface) elif key == "S": - self.proxy.StopChecker(dbus_interface = client_interface, - ignore_reply=True) + self.proxy.StopChecker(dbus_interface = client_interface) elif key == "C": - self.proxy.CheckedOK(dbus_interface = client_interface, - ignore_reply=True) + self.proxy.CheckedOK(dbus_interface = client_interface) # xxx # elif key == "p" or key == "=": # self.proxy.pause() @@ -377,13 +386,14 @@ else: return key - def property_changed(self, property=None, **kwargs): + def property_changed(self, property=None, value=None, + *args, **kwargs): """Call self.update() if old value is not new value. This overrides the method from MandosClientPropertyCache""" - property_name = str(property) + property_name = unicode(property) old_value = self.properties.get(property_name) super(MandosClientWidget, self).property_changed( - property=property, **kwargs) + property=property, value=value, *args, **kwargs) if self.properties.get(property_name) != old_value: self.update() @@ -393,8 +403,8 @@ "down" key presses, thus not allowing any containing widgets to use them as an excuse to shift focus away from this widget. """ - def keypress(self, *args, **kwargs): - ret = super(ConstrainedListBox, self).keypress(*args, **kwargs) + def keypress(self, maxcolrow, key): + ret = super(ConstrainedListBox, self).keypress(maxcolrow, key) if ret in ("up", "down"): return return ret @@ -413,21 +423,20 @@ ("normal", "default", "default", None), ("bold", - "bold", "default", "bold"), + "default", "default", "bold"), ("underline-blink", - "underline,blink", "default", "underline,blink"), + "default", "default", "underline"), ("standout", - "standout", "default", "standout"), + "default", "default", "standout"), ("bold-underline-blink", - "bold,underline,blink", "default", "bold,underline,blink"), + "default", "default", ("bold", "underline")), ("bold-standout", - "bold,standout", "default", "bold,standout"), + "default", "default", ("bold", "standout")), ("underline-blink-standout", - "underline,blink,standout", "default", - "underline,blink,standout"), + "default", "default", ("underline", "standout")), ("bold-underline-blink-standout", - "bold,underline,blink,standout", "default", - "bold,underline,blink,standout"), + "default", "default", ("bold", "underline", + "standout")), )) if urwid.supports_unicode(): @@ -465,11 +474,53 @@ self.busname = domain + '.Mandos' self.main_loop = gobject.MainLoop() + self.bus = dbus.SystemBus() + mandos_dbus_objc = self.bus.get_object( + self.busname, "/", follow_name_owner_changes=True) + self.mandos_serv = dbus.Interface(mandos_dbus_objc, + dbus_interface + = server_interface) + try: + mandos_clients = (self.mandos_serv + .GetAllClientsWithProperties()) + except dbus.exceptions.DBusException: + mandos_clients = dbus.Dictionary() + + (self.mandos_serv + .connect_to_signal("ClientRemoved", + self.find_and_remove_client, + dbus_interface=server_interface, + byte_arrays=True)) + (self.mandos_serv + .connect_to_signal("ClientAdded", + self.add_new_client, + dbus_interface=server_interface, + byte_arrays=True)) + (self.mandos_serv + .connect_to_signal("ClientNotFound", + self.client_not_found, + dbus_interface=server_interface, + byte_arrays=True)) + for path, client in mandos_clients.iteritems(): + client_proxy_object = self.bus.get_object(self.busname, + path) + self.add_client(MandosClientWidget(server_proxy_object + =self.mandos_serv, + proxy_object + =client_proxy_object, + properties=client, + update_hook + =self.refresh, + delete_hook + =self.remove_client, + logger + =self.log_message), + path=path) def client_not_found(self, fingerprint, address): - self.log_message("Client with address {0} and fingerprint" - " {1} could not be found" - .format(address, fingerprint)) + self.log_message(("Client with address %s and fingerprint %s" + " could not be found" % (address, + fingerprint))) def rebuild(self): """This rebuilds the User Interface. @@ -485,10 +536,10 @@ self.divider))) if self.log_visible: self.uilist.append(self.logbox) + pass self.topwidget = urwid.Pile(self.uilist) def log_message(self, message): - """Log message formatted with timestamp""" timestamp = datetime.datetime.now().isoformat() self.log_message_raw(timestamp + ": " + message) @@ -507,7 +558,7 @@ self.log_visible = not self.log_visible self.rebuild() #self.log_message("Log visibility changed to: " - # + str(self.log_visible)) + # + unicode(self.log_visible)) def change_log_display(self): """Change type of log display. @@ -521,7 +572,7 @@ #self.log_message("Wrap mode: " + self.log_wrap) def find_and_remove_client(self, path, name): - """Find a client by its object path and remove it. + """Find an client from its object path and remove it. This is connected to the ClientRemoved signal from the Mandos server object.""" @@ -529,10 +580,8 @@ client = self.clients_dict[path] except KeyError: # not found? - self.log_message("Unknown client {0!r} ({1!r}) removed" - .format(name, path)) return - client.delete() + self.remove_client(client, path) def add_new_client(self, path): client_proxy_object = self.bus.get_object(self.busname, path) @@ -553,7 +602,7 @@ if path is None: path = client.proxy.object_path self.clients_dict[path] = client - self.clients.sort(key=lambda c: c.properties["Name"]) + self.clients.sort(None, lambda c: c.properties["Name"]) self.refresh() def remove_client(self, client, path=None): @@ -561,6 +610,11 @@ if path is None: path = client.proxy.object_path del self.clients_dict[path] + if not self.clients_dict: + # Work around bug in Urwid 0.9.8.3 - if a SimpleListWalker + # is completely emptied, we need to recreate it. + self.clients = urwid.SimpleListWalker([]) + self.rebuild() self.refresh() def refresh(self): @@ -570,52 +624,6 @@ def run(self): """Start the main loop and exit when it's done.""" - self.bus = dbus.SystemBus() - mandos_dbus_objc = self.bus.get_object( - self.busname, "/", follow_name_owner_changes=True) - self.mandos_serv = dbus.Interface(mandos_dbus_objc, - dbus_interface - = server_interface) - try: - mandos_clients = (self.mandos_serv - .GetAllClientsWithProperties()) - if not mandos_clients: - self.log_message_raw(("bold", "Note: Server has no clients.")) - except dbus.exceptions.DBusException: - self.log_message_raw(("bold", "Note: No Mandos server running.")) - mandos_clients = dbus.Dictionary() - - (self.mandos_serv - .connect_to_signal("ClientRemoved", - self.find_and_remove_client, - dbus_interface=server_interface, - byte_arrays=True)) - (self.mandos_serv - .connect_to_signal("ClientAdded", - self.add_new_client, - dbus_interface=server_interface, - byte_arrays=True)) - (self.mandos_serv - .connect_to_signal("ClientNotFound", - self.client_not_found, - dbus_interface=server_interface, - byte_arrays=True)) - for path, client in mandos_clients.items(): - client_proxy_object = self.bus.get_object(self.busname, - path) - self.add_client(MandosClientWidget(server_proxy_object - =self.mandos_serv, - proxy_object - =client_proxy_object, - properties=client, - update_hook - =self.refresh, - delete_hook - =self.remove_client, - logger - =self.log_message), - path=path) - self.refresh() self._input_callback_tag = (gobject.io_add_watch (sys.stdin.fileno(), @@ -718,7 +726,7 @@ ui.run() except KeyboardInterrupt: ui.screen.stop() -except Exception as e: - ui.log_message(str(e)) +except Exception, e: + ui.log_message(unicode(e)) ui.screen.stop() raise === modified file 'mandos-monitor.xml' --- mandos-monitor.xml 2011-12-31 23:05:34 +0000 +++ mandos-monitor.xml 2011-02-27 17:26:35 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,21 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2010 2011 - 2012 Teddy Hogeborn Björn Påhlsson @@ -220,8 +219,6 @@ SEE ALSO - intro - 8mandos, mandos 8, mandos-ctl === modified file 'mandos-options.xml' --- mandos-options.xml 2013-10-24 20:21:45 +0000 +++ mandos-options.xml 2009-02-13 05:38:21 +0000 @@ -46,24 +46,11 @@ not run in debug mode. - - GnuTLS priority string for the TLS handshake. - The default is SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224: - +SIGN-RSA-RMD160. - See gnutls_priority_init - 3 for the syntax. - Warning: changing this may make the - TLS handshake fail, making server-client - communication impossible. - - GnuTLS priority string for the TLS handshake. The default is SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP. See - gnutls_priority_init + gnutls_priority_init 3 for the syntax. Warning: changing this may make the TLS handshake fail, making server-client @@ -99,28 +86,4 @@ advanced users should consider changing this option. - - This option controls whether the server will restore its state - from the last time it ran. Default is to restore last state. - - - - Directory to save (and restore) state in. Default is - /var/lib/mandos. - - - - If this option is used, the server will not create a new network - socket, but will instead use the supplied file descriptor. By - default, the server will create a new network socket. - - - - This option will make the server run in the foreground and not - write a PID file. The default is to not run - in the foreground, except in mode, which - implies this option. - - === modified file 'mandos.conf' --- mandos.conf 2013-10-22 19:24:01 +0000 +++ mandos.conf 2009-02-13 05:38:21 +0000 @@ -4,26 +4,32 @@ # These are the default values for the server, uncomment and change # them if needed. + # If "interface" is set, the server will only listen to a specific # network interface. ;interface = + # If "address" is set, the server will only listen to a specific # address. This must currently be an IPv6 address; an IPv4 address # can be specified using the "::FFFF:192.0.2.3" syntax. Also, if this # is a link-local address, an interface should be set above. ;address = + # If "port" is set, the server to bind to that port. By default, the # server will listen to an arbitrary port. ;port = + # If "debug" is true, the server will run in the foreground and print # a lot of debugging information. ;debug = False + # GnuTLS priority for the TLS handshake. See gnutls_priority_init(3). -;priority = SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP:+SIGN-RSA-SHA224:+SIGN-RSA-RMD160 +;priority = SECURE256:!CTYPE-X.509:+CTYPE-OPENPGP + # Zeroconf service name. You need to change this if you for some # reason want to run more than one server on the same *host*. @@ -36,12 +42,3 @@ # Whether to use IPv6. (Changing this is NOT recommended.) ;use_ipv6 = True - -# Whether to restore saved state on startup -;restore = True - -# The directory where state is saved -;statedir = /var/lib/mandos - -# Whether to run in the foreground -;foreground = False === modified file 'mandos.conf.xml' --- mandos.conf.xml 2013-10-24 20:21:45 +0000 +++ mandos.conf.xml 2009-02-25 01:14:29 +0000 @@ -3,7 +3,7 @@ "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [ /etc/mandos/mandos.conf"> - + %common; ]> @@ -20,23 +20,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2008 2009 - 2011 - 2012 - 2013 Teddy Hogeborn Björn Påhlsson @@ -121,8 +118,7 @@ - +
@@ -157,33 +153,6 @@ - - - - - - - - - - - - - - - - - - - - -
@@ -228,8 +197,6 @@ servicename = Daena use_dbus = False use_ipv6 = True -restore = True -statedir = /var/lib/mandos @@ -237,8 +204,6 @@ SEE ALSO - intro - 8mandos, gnutls_priority_init3, mandos === modified file 'mandos.lsm' --- mandos.lsm 2014-01-21 21:04:25 +0000 +++ mandos.lsm 2011-03-08 19:41:59 +0000 @@ -1,21 +1,21 @@ Begin4 Title: Mandos -Version: 1.6.3 -Entered-date: 2014-01-21 +Version: 1.3.0 +Entered-date: 2011-03-08 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. Keywords: boot, encryption, luks, cryptsetup, network, openpgp, tls, dm-crypt -Author: teddy@recompile.se (Teddy Hogeborn), - belorn@recompile.se (Björn Påhlsson) -Maintained-by: teddy@recompile.se (Teddy Hogeborn), - belorn@recompile.se (Björn Påhlsson) -Primary-site: http://www.recompile.se/mandos - 158K mandos_1.6.3.orig.tar.gz -Alternate-site: ftp://ftp.recompile.se/pub/mandos - 158K mandos_1.6.3.orig.tar.gz -Platforms: Requires GCC, GNU libC, Avahi, GnuPG, Python 2.6, and +Author: teddy@fukt.bsnet.se (Teddy Hogeborn), + belorn@fukt.bsnet.se (Björn Påhlsson) +Maintained-by: teddy@fukt.bsnet.se (Teddy Hogeborn), + belorn@fukt.bsnet.se (Björn Påhlsson) +Primary-site: http://www.fukt.bsnet.se/mandos + 133K mandos_1.3.0.orig.tar.gz +Alternate-site: ftp://ftp.fukt.bsnet.se/pub/mandos + 133K mandos_1.3.0.orig.tar.gz +Platforms: Requires GCC, GNU libC, Avahi, GnuPG, Python 2.5, and various other libraries. While made for Debian GNU/Linux, it is probably portable to other distributions, but not other Unixes. Copying-policy: GNU General Public License version 3.0 or later === removed file 'mandos.service' --- mandos.service 2013-12-31 16:02:18 +0000 +++ mandos.service 1970-01-01 00:00:00 +0000 @@ -1,21 +0,0 @@ -[Unit] -Description=Server of encrypted passwords to Mandos clients - -[Service] -Type=simple -## Type=dbus is not appropriate, because Mandos also needs to announce -## its ZeroConf service and be reachable on the network. -#Type=dbus -BusName=se.recompile.Mandos -# If you add --no-dbus, also comment out BusName above, and vice versa -ExecStart=/usr/sbin/mandos --foreground -Restart=always -KillMode=process -## Using socket activation won't work either, because systemd always -## does bind() on the socket, and also won't announce the ZeroConf -## service. -#ExecStart=/usr/sbin/mandos --foreground --socket=0 -#StandardInput=socket - -[Install] -WantedBy=multi-user.target === modified file 'mandos.xml' --- mandos.xml 2013-10-26 19:05:21 +0000 +++ mandos.xml 2011-02-27 17:26:35 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,14 +19,14 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
@@ -35,8 +35,6 @@ 2009 2010 2011 - 2012 - 2013 Teddy Hogeborn Björn Påhlsson @@ -96,16 +94,6 @@ - - - - - - - - &COMMANDNAME; @@ -129,16 +117,14 @@ &COMMANDNAME; is a server daemon which handles incoming request for passwords for a pre-defined list of - client host computers. For an introduction, see - intro - 8mandos. The Mandos server - uses Zeroconf to announce itself on the local network, and uses - TLS to communicate securely with and to authenticate the - clients. The Mandos server uses IPv6 to allow Mandos clients to - use IPv6 link-local addresses, since the clients will probably - not have any other addresses configured (see ). Any authenticated client is then given - the stored pre-encrypted password for that specific client. + client host computers. The Mandos server uses Zeroconf to + announce itself on the local network, and uses TLS to + communicate securely with and to authenticate the clients. The + Mandos server uses IPv6 to allow Mandos clients to use IPv6 + link-local addresses, since the clients will probably not have + any other addresses configured (see ). + Any authenticated client is then given the stored pre-encrypted + password for that specific client.
@@ -234,8 +220,7 @@ - + @@ -288,41 +273,6 @@ - - - - - - - See also . - - - - - - - - - - - - - - - - - - - - - - - - - @@ -402,10 +352,12 @@ for some time, the client is assumed to be compromised and is no longer eligible to receive the encrypted password. (Manual intervention is required to re-enable a client.) The timeout, - extended timeout, checker program, and interval between checks - can be configured both globally and per client; see - mandos-clients.conf - 5. + checker program, and interval between checks can be configured + both globally and per client; see + mandos-clients.conf + 5. A client successfully + receiving its password will also be treated as a successful + checker run. @@ -433,24 +385,12 @@ LOGGING The server will send log message with various severity levels to - /dev/log. With the + /dev/log. With the option, it will log even more messages, and also show them on the console. - - PERSISTENT STATE - - Client settings, initially read from - clients.conf, are persistent across - restarts, and run-time changes will override settings in - clients.conf. However, if a setting is - changed (or a client added, or removed) in - clients.conf, this will take precedence. - - - D-BUS INTERFACE @@ -518,29 +458,11 @@ - /run/mandos.pid + /var/run/mandos.pid The file containing the process id of the &COMMANDNAME; process started last. - Note: If the /run directory does not - exist, /var/run/mandos.pid will be - used instead. - - - - - /dev/log - - - /var/lib/mandos - - - Directory where persistent state will be saved. Change - this with the option. See - also the option. @@ -574,9 +496,20 @@ backtrace. This could be considered a feature. + Currently, if a client is disabled due to having timed out, the + server does not record this fact onto permanent storage. This + has some security implications, see . + + There is no fine-grained control over logging and debug output. + Debug mode is conflated with running in the foreground. + + + The console log messages do not show a time stamp. + + This server does not check the expire time of clients’ OpenPGP keys. @@ -595,9 +528,9 @@ Run the server in debug mode, read configuration files from - the ~/mandos directory, - and use the Zeroconf service name Test to not - collide with any other official Mandos server on this host: + the ~/mandos directory, and use the + Zeroconf service name Test to not collide with + any other official Mandos server on this host: @@ -652,6 +585,21 @@ compromised if they are gone for too long. + If a client is compromised, its downtime should be duly noted + by the server which would therefore disable the client. But + if the server was ever restarted, it would re-read its client + list from its configuration file and again regard all clients + therein as enabled, and hence eligible to receive their + passwords. Therefore, be careful when restarting servers if + it is suspected that a client has, in fact, been compromised + by parties who may now be running a fake Mandos client with + the keys from the non-encrypted initial RAM + image of the client host. What should be done in that case + (if restarting the server program really is necessary) is to + stop the server program, edit the configuration file to omit + any suspect clients, and restart the server program. + + For more details on client-side security, see mandos-client 8mandos. @@ -662,16 +610,15 @@ SEE ALSO - intro - 8mandos, - mandos-clients.conf - 5, - mandos.conf - 5, - mandos-client - 8mandos, - sh - 1 + + mandos-clients.conf + 5, + mandos.conf + 5, + mandos-client + 8mandos, + sh1 + === removed directory 'network-hooks.d' === removed file 'network-hooks.d/bridge' --- network-hooks.d/bridge 2012-06-13 22:06:57 +0000 +++ network-hooks.d/bridge 1970-01-01 00:00:00 +0000 @@ -1,93 +0,0 @@ -#!/bin/sh -# -# This is an example of a Mandos client network hook. This hook -# brings up a bridge interface as specified in a separate -# configuration file. To be used, this file and any needed -# configuration file(s) should be copied into the -# /etc/mandos/network-hooks.d directory. -# -# Copyright © 2012 Teddy Hogeborn -# Copyright © 2012 Björn Påhlsson -# -# Copying and distribution of this file, with or without modification, -# are permitted in any medium without royalty provided the copyright -# notice and this notice are preserved. This file is offered as-is, -# without any warranty. - -set -e - -CONFIG="$MANDOSNETHOOKDIR/bridge.conf" - -addrtoif(){ - grep -liFe "$1" /sys/class/net/*/address \ - | sed -e 's,.*/\([^/]*\)/[^/]*,\1,' -e "/^${BRIDGE}\$/d" -} - -# Read config file, which must set "BRIDGE", "PORT_ADDRESSES", and -# optionally "IPADDRS" and "ROUTES". -if [ -e "$CONFIG" ]; then - . "$CONFIG" -fi - -if [ -z "$BRIDGE" -o -z "$PORT_ADDRESSES" ]; then - exit -fi - -if [ -n "$DEVICE" ]; then - case "$DEVICE" in - *,"$BRIDGE"|*,"$BRIDGE",*|"$BRIDGE",*|"$BRIDGE") :;; - *) exit;; - esac -fi - -brctl="/sbin/brctl" -for b in "$brctl" /usr/sbin/brctl; do - if [ -e "$b" ]; then - brctl="$b" - break - fi -done - -do_start(){ - "$brctl" addbr "$BRIDGE" - for address in $PORT_ADDRESSES; do - interface=`addrtoif "$address"` - "$brctl" addif "$BRIDGE" "$interface" - ip link set dev "$interface" up - done - ip link set dev "$BRIDGE" up - sleep "${DELAY%%.*}" - if [ -n "$IPADDRS" ]; then - for ipaddr in $IPADDRS; do - ip addr add "$ipaddr" dev "$BRIDGE" - done - fi - if [ -n "$ROUTES" ]; then - for route in $ROUTES; do - ip route add "$route" dev "$BRIDGE" - done - fi -} - -do_stop(){ - ip link set dev "$BRIDGE" down - for address in $PORT_ADDRESSES; do - interface=`addrtoif "$address"` - ip link set dev "$interface" down - "$brctl" delif "$BRIDGE" "$interface" - done - "$brctl" delbr "$BRIDGE" -} - -case "${MODE:-$1}" in - start|stop) - do_"${MODE:-$1}" - ;; - files) - echo /bin/ip - echo "$brctl" - ;; - modules) - echo bridge - ;; -esac === removed file 'network-hooks.d/bridge.conf' --- network-hooks.d/bridge.conf 2011-12-31 13:25:58 +0000 +++ network-hooks.d/bridge.conf 1970-01-01 00:00:00 +0000 @@ -1,11 +0,0 @@ -## Required - -#BRIDGE=br0 - -#PORT_ADDRESSES="00:11:22:33:44:55 11:22:33:44:55:66" - -## Optional - -#IPADDRS="192.0.2.3/24 2001:DB8::aede:48ff:fe71:f6f2/32" - -#ROUTES="192.0.2.0/24 2001:DB8::/32" === removed file 'network-hooks.d/openvpn' --- network-hooks.d/openvpn 2012-06-13 22:06:57 +0000 +++ network-hooks.d/openvpn 1970-01-01 00:00:00 +0000 @@ -1,66 +0,0 @@ -#!/bin/sh -# -# This is an example of a Mandos client network hook. This hook -# brings up an OpenVPN interface as specified in a separate -# configuration file. To be used, this file and any needed -# configuration file(s) should be copied into the -# /etc/mandos/network-hooks.d directory. -# -# Copyright © 2012 Teddy Hogeborn -# Copyright © 2012 Björn Påhlsson -# -# Copying and distribution of this file, with or without modification, -# are permitted in any medium without royalty provided the copyright -# notice and this notice are preserved. This file is offered as-is, -# without any warranty. - -set -e - -CONFIG="openvpn.conf" - -# Extract the "dev" setting from the config file -VPNDEVICE=`sed -n -e 's/[[:space:]]#.*//' \ - -e 's/^[[:space:]]*dev[[:space:]]\+//p' \ - "$MANDOSNETHOOKDIR/$CONFIG"` - -PIDFILE=/run/openvpn-mandos.pid - -# Exit if no device set in config -if [ -z "$VPNDEVICE" ]; then - exit -fi - -# Exit if DEVICE is set and it doesn't match the VPN interface -if [ -n "$DEVICE" ]; then - case "$DEVICE" in - *,"$VPNDEVICE"*|"$VPNDEVICE"*) :;; - *) exit;; - esac -fi - -openvpn=/usr/sbin/openvpn - -do_start(){ - "$openvpn" --cd "$MANDOSNETHOOKDIR" --daemon 'openvpn(Mandos)' \ - --writepid "$PIDFILE" --config "$CONFIG" - sleep "$DELAY" -} - -do_stop(){ - PID="`cat \"$PIDFILE\"`" - if [ "$PID" -gt 0 ]; then - kill "$PID" - fi -} - -case "${MODE:-$1}" in - start|stop) - do_"${MODE:-$1}" - ;; - files) - echo "$openvpn" - ;; - modules) - echo tun - ;; -esac === removed file 'network-hooks.d/openvpn.conf' --- network-hooks.d/openvpn.conf 2011-12-02 16:52:50 +0000 +++ network-hooks.d/openvpn.conf 1970-01-01 00:00:00 +0000 @@ -1,19 +0,0 @@ -# Sample OpenVPN configuration file -# Uncomment and change - see openvpn(8) - -# Network device. -#dev tun - -# Our remote peer -#remote 192.0.2.3 -#float 192.0.2.3 -#port 1194 - -# VPN endpoints -#ifconfig 10.1.0.1 10.1.0.2 - -# A pre-shared static key -#secret openvpn.key - -# Cipher -#cipher AES-128-CBC === removed file 'network-hooks.d/wireless' --- network-hooks.d/wireless 2012-06-13 22:06:57 +0000 +++ network-hooks.d/wireless 1970-01-01 00:00:00 +0000 @@ -1,165 +0,0 @@ -#!/bin/sh -# -# This is an example of a Mandos client network hook. This hook -# brings up a wireless interface as specified in a separate -# configuration file. To be used, this file and any needed -# configuration file(s) should be copied into the -# /etc/mandos/network-hooks.d directory. -# -# Copyright © 2012 Teddy Hogeborn -# Copyright © 2012 Björn Påhlsson -# -# Copying and distribution of this file, with or without modification, -# are permitted in any medium without royalty provided the copyright -# notice and this notice are preserved. This file is offered as-is, -# without any warranty. - -set -e - -RUNDIR="/run" -CTRL="$RUNDIR/wpa_supplicant-global" -CTRLDIR="$RUNDIR/wpa_supplicant" -PIDFILE="$RUNDIR/wpa_supplicant-mandos.pid" - -CONFIG="$MANDOSNETHOOKDIR/wireless.conf" - -addrtoif(){ - grep -liFe "$1" /sys/class/net/*/address \ - | sed -e 's,.*/\([^/]*\)/[^/]*,\1,' -} - -# Read config file -if [ -e "$CONFIG" ]; then - . "$CONFIG" -else - exit -fi - -ifkeys=`sed -n -e 's/^ADDRESS_\([^=]*\)=.*/\1/p' "$CONFIG" | sort -u` - -# Exit if DEVICE is set and is not any of the wireless interfaces -if [ -n "$DEVICE" ]; then - while :; do - for KEY in $ifkeys; do - ADDRESS=`eval 'echo "$ADDRESS_'"$KEY"\"` - INTERFACE=`addrtoif "$ADDRESS"` - - case "$DEVICE" in - *,"$INTERFACE"|*,"$INTERFACE",*|"$INTERFACE",*|"$INTERFACE") - break 2;; - esac - done - exit - done -fi - -wpa_supplicant=/sbin/wpa_supplicant -wpa_cli=/sbin/wpa_cli -ip=/bin/ip - -# Used by the wpa_interface_* functions in the wireless.conf file -wpa_cli_set(){ - case "$1" in - ssid|psk) arg="\"$2\"" ;; - *) arg="$2" ;; - esac - "$wpa_cli" -p "$CTRLDIR" -i "$INTERFACE" set_network "$NETWORK" \ - "$1" "$arg" 2>&1 | sed -e '/^OK$/d' -} - -if [ $VERBOSITY -gt 0 ]; then - WPAS_OPTIONS="-d $WPAS_OPTIONS" -fi -if [ -n "$PIDFILE" ]; then - WPAS_OPTIONS="-P$PIDFILE $WPAS_OPTIONS" -fi - -do_start(){ - mkdir -m u=rwx,go= -p "$CTRLDIR" - "$wpa_supplicant" -B -g "$CTRL" -p "$CTRLDIR" $WPAS_OPTIONS - for KEY in $ifkeys; do - ADDRESS=`eval 'echo "$ADDRESS_'"$KEY"\"` - INTERFACE=`addrtoif "$ADDRESS"` - DRIVER=`eval 'echo "$WPA_DRIVER_'"$KEY"\"` - IFDELAY=`eval 'echo "$DELAY_'"$KEY"\"` - "$wpa_cli" -g "$CTRL" interface_add "$INTERFACE" "" \ - "${DRIVER:-wext}" "$CTRLDIR" > /dev/null \ - | sed -e '/^OK$/d' - NETWORK=`"$wpa_cli" -p "$CTRLDIR" -i "$INTERFACE" add_network` - eval wpa_interface_"$KEY" - "$wpa_cli" -p "$CTRLDIR" -i "$INTERFACE" enable_network \ - "$NETWORK" | sed -e '/^OK$/d' - sleep "${IFDELAY:-$DELAY}" & - sleep=$! - while :; do - kill -0 $sleep 2>/dev/null || break - STATE=`"$wpa_cli" -p "$CTRLDIR" -i "$INTERFACE" status \ - | sed -n -e 's/^wpa_state=//p'` - if [ "$STATE" = COMPLETED ]; then - while :; do - kill -0 $sleep 2>/dev/null || break 2 - UP=`cat /sys/class/net/"$INTERFACE"/operstate` - if [ "$UP" = up ]; then - kill $sleep 2>/dev/null - break 2 - fi - sleep 1 - done - fi - sleep 1 - done & - wait $sleep || : - IPADDRS=`eval 'echo "$IPADDRS_'"$KEY"\"` - if [ -n "$IPADDRS" ]; then - if [ "$IPADDRS" = dhcp ]; then - ipconfig -c dhcp -d "$INTERFACE" || : - #dhclient "$INTERFACE" - else - for ipaddr in $IPADDRS; do - "$ip" addr add "$ipaddr" dev "$INTERFACE" - done - fi - fi - ROUTES=`eval 'echo "$ROUTES_'"$KEY"\"` - if [ -n "$ROUTES" ]; then - for route in $ROUTES; do - "$ip" route add "$route" dev "$INTERFACE" - done - fi - done -} - -do_stop(){ - "$wpa_cli" -g "$CTRL" terminate 2>&1 | sed -e '/^OK$/d' - for KEY in $ifkeys; do - ADDRESS=`eval 'echo "$ADDRESS_'"$KEY"\"` - INTERFACE=`addrtoif "$ADDRESS"` - "$ip" addr show scope global permanent dev "$INTERFACE" \ - | while read type addr rest; do - case "$type" in - inet|inet6) - "$ip" addr del "$addr" dev "$INTERFACE" - ;; - esac - done - "$ip" link set dev "$INTERFACE" down - done -} - -case "${MODE:-$1}" in - start|stop) - do_"${MODE:-$1}" - ;; - files) - echo "$wpa_supplicant" - echo "$wpa_cli" - echo "$ip" - ;; - modules) - if [ "$IPADDRS" = dhcp ]; then - echo af_packet - fi - sed -n -e 's/#.*$//' -e 's/[ ]*$//' \ - -e 's/^MODULE_[^=]\+=//p' "$CONFIG" - ;; -esac === removed file 'network-hooks.d/wireless.conf' --- network-hooks.d/wireless.conf 2011-12-31 13:25:58 +0000 +++ network-hooks.d/wireless.conf 1970-01-01 00:00:00 +0000 @@ -1,23 +0,0 @@ -# Extra options for wpa_supplicant, if any -#WPAS_OPTIONS="" - -# wlan0 -ADDRESS_0=00:11:22:33:44:55 -MODULE_0=ath9k -#WPA_DRIVER_0=wext -wpa_interface_0(){ - # Use this format to set simple things: - wpa_cli_set ssid home - wpa_cli_set psk "secret passphrase" - # Use this format to do more complex things with wpa_cli: - #"$wpa_cli" -p "$CTRLDIR" -i "$INTERFACE" bssid "$NETWORK" 00:11:22:33:44:55 - #"$wpa_cli" -g "$CTRL" ping -} -#DELAY_0=10 -IPADDRS_0=dhcp -#IPADDRS_0="192.0.2.3/24 2001:DB8::aede:48ff:fe71:f6f2/32" -#ROUTES_0="192.0.2.0/24 2001:DB8::/32" - -#ADDRESS_1=11:22:33:44:55:66 -#MODULE_1=... -#... === modified file 'plugin-runner.c' --- plugin-runner.c 2013-12-15 22:21:28 +0000 +++ plugin-runner.c 2010-09-26 21:27:28 +0000 @@ -2,8 +2,8 @@ /* * Mandos plugin runner - Run Mandos plugins * - * Copyright © 2008-2013 Teddy Hogeborn - * Copyright © 2008-2013 Björn Påhlsson + * Copyright © 2008-2010 Teddy Hogeborn + * Copyright © 2008-2010 Björn Påhlsson * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -19,7 +19,7 @@ * along with this program. If not, see * . * - * Contact the authors at . + * Contact the authors at . */ #define _GNU_SOURCE /* TEMP_FAILURE_RETRY(), getline(), @@ -79,7 +79,7 @@ #define AFILE "/conf/conf.d/mandos/plugin-runner.conf" const char *argp_program_version = "plugin-runner " VERSION; -const char *argp_program_bug_address = ""; +const char *argp_program_bug_address = ""; typedef struct plugin{ char *name; /* can be NULL or any plugin name */ @@ -171,7 +171,6 @@ } /* Helper function for add_argument and add_environment */ -__attribute__((nonnull)) static bool add_to_char_array(const char *new, char ***array, int *len){ /* Resize the pointed-to array to hold one more pointer */ @@ -200,7 +199,6 @@ } /* Add to a plugin's argument vector */ -__attribute__((nonnull(2))) static bool add_argument(plugin *p, const char *arg){ if(p == NULL){ return false; @@ -209,7 +207,6 @@ } /* Add to a plugin's environment */ -__attribute__((nonnull(2))) static bool add_environment(plugin *p, const char *def, bool replace){ if(p == NULL){ return false; @@ -289,7 +286,6 @@ } /* Prints out a password to stdout */ -__attribute__((nonnull)) static bool print_out_password(const char *buffer, size_t length){ ssize_t ret; for(size_t written = 0; written < length; written += (size_t)ret){ @@ -303,7 +299,6 @@ } /* Removes and free a plugin from the plugin list */ -__attribute__((nonnull)) static void free_plugin(plugin *plugin_node){ for(char **arg = plugin_node->argv; *arg != NULL; arg++){ @@ -421,12 +416,11 @@ { .name = NULL } }; - __attribute__((nonnull(3))) error_t parse_opt(int key, char *arg, struct argp_state *state){ errno = 0; switch(key){ char *tmp; - intmax_t tmp_id; + intmax_t tmpmax; case 'g': /* --global-options */ { char *plugin_option; @@ -505,24 +499,24 @@ /* This is already done by parse_opt_config_file() */ break; case 130: /* --userid */ - tmp_id = strtoimax(arg, &tmp, 10); + tmpmax = strtoimax(arg, &tmp, 10); if(errno != 0 or tmp == arg or *tmp != '\0' - or tmp_id != (uid_t)tmp_id){ + or tmpmax != (uid_t)tmpmax){ argp_error(state, "Bad user ID number: \"%s\", using %" PRIdMAX, arg, (intmax_t)uid); break; } - uid = (uid_t)tmp_id; + uid = (uid_t)tmpmax; break; case 131: /* --groupid */ - tmp_id = strtoimax(arg, &tmp, 10); + tmpmax = strtoimax(arg, &tmp, 10); if(errno != 0 or tmp == arg or *tmp != '\0' - or tmp_id != (gid_t)tmp_id){ + or tmpmax != (gid_t)tmpmax){ argp_error(state, "Bad group ID number: \"%s\", using %" PRIdMAX, arg, (intmax_t)gid); break; } - gid = (gid_t)tmp_id; + gid = (gid_t)tmpmax; break; case 132: /* --debug */ debug = true; @@ -748,30 +742,8 @@ } } - if(getuid() == 0){ - /* Work around Debian bug #633582: - */ - int plugindir_fd = open(/* plugindir or */ PDIR, O_RDONLY); - if(plugindir_fd == -1){ - error(0, errno, "open"); - } else { - ret = (int)TEMP_FAILURE_RETRY(fstat(plugindir_fd, &st)); - if(ret == -1){ - error(0, errno, "fstat"); - } else { - if(S_ISDIR(st.st_mode) and st.st_uid == 0 and st.st_gid == 0){ - ret = fchown(plugindir_fd, uid, gid); - if(ret == -1){ - error(0, errno, "fchown"); - } - } - } - TEMP_FAILURE_RETRY(close(plugindir_fd)); - } - } - - /* Lower permissions */ - ret = setgid(gid); + /* Strip permissions down to nobody */ + setgid(gid); if(ret == -1){ error(0, errno, "setgid"); } @@ -1071,20 +1043,8 @@ goto fallback; } -#if defined (__GNUC__) and defined (__GLIBC__) -#if not __GLIBC_PREREQ(2, 16) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wsign-conversion" -#endif -#endif FD_SET(new_plugin->fd, &rfds_all); /* Spurious warning from - -Wconversion in GNU libc - before 2.16 */ -#if defined (__GNUC__) and defined (__GLIBC__) -#if not __GLIBC_PREREQ(2, 16) -#pragma GCC diagnostic pop -#endif -#endif + -Wconversion */ if(maxfd < new_plugin->fd){ maxfd = new_plugin->fd; @@ -1144,20 +1104,8 @@ } /* Remove the plugin */ -#if defined (__GNUC__) and defined (__GLIBC__) -#if not __GLIBC_PREREQ(2, 16) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wsign-conversion" -#endif -#endif FD_CLR(proc->fd, &rfds_all); /* Spurious warning from - -Wconversion in GNU libc - before 2.16 */ -#if defined (__GNUC__) and defined (__GLIBC__) -#if not __GLIBC_PREREQ(2, 16) -#pragma GCC diagnostic pop -#endif -#endif + -Wconversion */ /* Block signal while modifying process_list */ ret = (int)TEMP_FAILURE_RETRY(sigprocmask @@ -1203,23 +1151,9 @@ } /* This process has not completed. Does it have any output? */ -#if defined (__GNUC__) and defined (__GLIBC__) -#if not __GLIBC_PREREQ(2, 16) -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wsign-conversion" -#endif -#endif if(proc->eof or not FD_ISSET(proc->fd, &rfds)){ /* Spurious warning from - -Wconversion - in GNU libc - before - 2.16 */ -#if defined (__GNUC__) and defined (__GLIBC__) -#if not __GLIBC_PREREQ(2, 16) -#pragma GCC diagnostic pop -#endif -#endif + -Wconversion */ /* This process had nothing to say at this time */ proc = proc->next; continue; === modified file 'plugin-runner.xml' --- plugin-runner.xml 2011-12-31 23:05:34 +0000 +++ plugin-runner.xml 2009-01-18 06:41:57 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,21 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2008 2009 - 2012 Teddy Hogeborn Björn Påhlsson @@ -261,7 +260,7 @@ Disable the plugin named PLUGIN. The plugin will not be started. -
+ @@ -618,8 +617,6 @@ SEE ALSO - intro - 8mandos, cryptsetup 8, crypttab === modified file 'plugins.d/askpass-fifo.c' --- plugins.d/askpass-fifo.c 2011-12-31 23:05:34 +0000 +++ plugins.d/askpass-fifo.c 2011-02-27 17:26:35 +0000 @@ -2,8 +2,8 @@ /* * Askpass-FIFO - Read a password from a FIFO and output it * - * Copyright © 2008-2012 Teddy Hogeborn - * Copyright © 2008-2012 Björn Påhlsson + * Copyright © 2008-2011 Teddy Hogeborn + * Copyright © 2008-2011 Björn Påhlsson * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -19,7 +19,7 @@ * along with this program. If not, see * . * - * Contact the authors at . + * Contact the authors at . */ #define _GNU_SOURCE /* TEMP_FAILURE_RETRY() */ @@ -32,8 +32,6 @@ ENFILE, ENOMEM, EBADF, EINVAL, EIO, EISDIR, EFBIG */ #include /* error() */ -#include /* fprintf(), vfprintf(), - vasprintf() */ #include /* EXIT_FAILURE, NULL, size_t, free(), realloc(), EXIT_SUCCESS */ #include /* open(), O_RDONLY */ @@ -41,33 +39,7 @@ STDOUT_FILENO */ #include /* EX_OSERR, EX_OSFILE, EX_UNAVAILABLE, EX_IOERR */ -#include /* strerror() */ -#include /* va_list, va_start(), ... */ - - -/* Function to use when printing errors */ -__attribute__((format (gnu_printf, 3, 4))) -void error_plus(int status, int errnum, const char *formatstring, - ...){ - va_list ap; - char *text; - int ret; - - va_start(ap, formatstring); - ret = vasprintf(&text, formatstring, ap); - if (ret == -1){ - fprintf(stderr, "Mandos plugin %s: ", - program_invocation_short_name); - vfprintf(stderr, formatstring, ap); - fprintf(stderr, ": "); - fprintf(stderr, "%s\n", strerror(errnum)); - error(status, errno, "vasprintf while printing error"); - return; - } - fprintf(stderr, "Mandos plugin "); - error(status, errnum, "%s", text); - free(text); -} + int main(__attribute__((unused))int argc, __attribute__((unused))char **argv){ @@ -79,19 +51,19 @@ ret = mkfifo(passfifo, S_IRUSR | S_IWUSR); if(ret == -1){ int e = errno; + error(0, errno, "mkfifo"); switch(e){ case EACCES: case ENOTDIR: case ELOOP: - error_plus(EX_OSFILE, errno, "mkfifo"); + return EX_OSFILE; case ENAMETOOLONG: case ENOSPC: case EROFS: default: - error_plus(EX_OSERR, errno, "mkfifo"); + return EX_OSERR; case ENOENT: - /* no "/lib/cryptsetup"? */ - error_plus(EX_UNAVAILABLE, errno, "mkfifo"); + return EX_UNAVAILABLE; /* no "/lib/cryptsetup"? */ case EEXIST: break; /* not an error */ } @@ -101,7 +73,7 @@ int fifo_fd = open(passfifo, O_RDONLY); if(fifo_fd == -1){ int e = errno; - error_plus(0, errno, "open"); + error(0, errno, "open"); switch(e){ case EACCES: case ENOENT: @@ -129,7 +101,7 @@ if(buf_len + blocksize > buf_allocated){ char *tmp = realloc(buf, buf_allocated + blocksize); if(tmp == NULL){ - error_plus(0, errno, "realloc"); + error(0, errno, "realloc"); free(buf); return EX_OSERR; } @@ -141,7 +113,7 @@ int e = errno; free(buf); errno = e; - error_plus(0, errno, "read"); + error(0, errno, "read"); switch(e){ case EBADF: case EFAULT: @@ -169,7 +141,7 @@ int e = errno; free(buf); errno = e; - error_plus(0, errno, "write"); + error(0, errno, "write"); switch(e){ case EBADF: case EFAULT: @@ -189,7 +161,7 @@ ret = close(STDOUT_FILENO); if(ret == -1){ int e = errno; - error_plus(0, errno, "close"); + error(0, errno, "close"); switch(e){ case EBADF: return EX_OSFILE; === modified file 'plugins.d/askpass-fifo.xml' --- plugins.d/askpass-fifo.xml 2011-12-31 23:05:34 +0000 +++ plugins.d/askpass-fifo.xml 2009-01-04 21:54:55 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,22 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2008 2009 - 2011 - 2012 Teddy Hogeborn Björn Påhlsson @@ -150,8 +148,6 @@ SEE ALSO - intro - 8mandos, fifo 7, plugin-runner === modified file 'plugins.d/mandos-client.c' --- plugins.d/mandos-client.c 2013-12-15 22:21:28 +0000 +++ plugins.d/mandos-client.c 2011-02-27 17:26:35 +0000 @@ -9,8 +9,8 @@ * "browse_callback", and parts of "main". * * Everything else is - * Copyright © 2008-2013 Teddy Hogeborn - * Copyright © 2008-2013 Björn Påhlsson + * Copyright © 2008-2011 Teddy Hogeborn + * Copyright © 2008-2011 Björn Påhlsson * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -26,7 +26,7 @@ * along with this program. If not, see * . * - * Contact the authors at . + * Contact the authors at . */ /* Needed by GPGME, specifically gpgme_data_seek() */ @@ -41,7 +41,7 @@ #include /* fprintf(), stderr, fwrite(), stdout, ferror(), remove() */ -#include /* uint16_t, uint32_t, intptr_t */ +#include /* uint16_t, uint32_t */ #include /* NULL, size_t, ssize_t */ #include /* free(), EXIT_SUCCESS, srand(), strtof(), abort() */ @@ -53,7 +53,7 @@ sockaddr_in6, PF_INET6, SOCK_STREAM, uid_t, gid_t, open(), opendir(), DIR */ -#include /* open(), S_ISREG */ +#include /* open() */ #include /* socket(), struct sockaddr_in6, inet_pton(), connect() */ #include /* open() */ @@ -61,8 +61,8 @@ */ #include /* PRIu16, PRIdMAX, intmax_t, strtoimax() */ -#include /* perror(), errno, - program_invocation_short_name */ +#include /* assert() */ +#include /* perror(), errno */ #include /* nanosleep(), time(), sleep() */ #include /* ioctl, ifreq, SIOCGIFFLAGS, IFF_UP, SIOCSIFFLAGS, if_indextoname(), @@ -72,8 +72,8 @@ */ #include /* close(), SEEK_SET, off_t, write(), getuid(), getgid(), seteuid(), - setgid(), pause(), _exit() */ -#include /* inet_pton(), htons, inet_ntop() */ + setgid(), pause() */ +#include /* inet_pton(), htons */ #include /* not, or, and */ #include /* struct argp_option, error_t, struct argp_state, struct argp, @@ -84,13 +84,6 @@ raise() */ #include /* EX_OSERR, EX_USAGE, EX_UNAVAILABLE, EX_NOHOST, EX_IOERR, EX_PROTOCOL */ -#include /* waitpid(), WIFEXITED(), - WEXITSTATUS(), WTERMSIG() */ -#include /* setgroups() */ -#include /* argz_add_sep(), argz_next(), - argz_delete(), argz_append(), - argz_stringify(), argz_add(), - argz_count() */ #ifdef __linux__ #include /* klogctl() */ @@ -114,8 +107,8 @@ init_gnutls_session(), GNUTLS_* */ #include - /* gnutls_certificate_set_openpgp_key_file(), - GNUTLS_OPENPGP_FMT_BASE64 */ + /* gnutls_certificate_set_openpgp_key_file(), + GNUTLS_OPENPGP_FMT_BASE64 */ /* GPGME */ #include /* All GPGME types, constants and @@ -129,74 +122,40 @@ #define PATHDIR "/conf/conf.d/mandos" #define SECKEY "seckey.txt" #define PUBKEY "pubkey.txt" -#define HOOKDIR "/lib/mandos/network-hooks.d" bool debug = false; static const char mandos_protocol_version[] = "1"; const char *argp_program_version = "mandos-client " VERSION; -const char *argp_program_bug_address = ""; +const char *argp_program_bug_address = ""; static const char sys_class_net[] = "/sys/class/net"; char *connect_to = NULL; -const char *hookdir = HOOKDIR; -uid_t uid = 65534; -gid_t gid = 65534; - -/* Doubly linked list that need to be circularly linked when used */ -typedef struct server{ - const char *ip; - in_port_t port; - AvahiIfIndex if_index; - int af; - struct timespec last_seen; - struct server *next; - struct server *prev; -} server; /* Used for passing in values through the Avahi callback functions */ typedef struct { + AvahiSimplePoll *simple_poll; AvahiServer *server; gnutls_certificate_credentials_t cred; unsigned int dh_bits; gnutls_dh_params_t dh_params; const char *priority; gpgme_ctx_t ctx; - server *current_server; - char *interfaces; - size_t interfaces_size; } mandos_context; -/* global so signal handler can reach it*/ -AvahiSimplePoll *simple_poll; +/* global context so signal handler can reach it*/ +mandos_context mc = { .simple_poll = NULL, .server = NULL, + .dh_bits = 1024, .priority = "SECURE256" + ":!CTYPE-X.509:+CTYPE-OPENPGP" }; sig_atomic_t quit_now = 0; int signal_received = 0; -/* Function to use when printing errors */ -void perror_plus(const char *print_text){ - int e = errno; - fprintf(stderr, "Mandos plugin %s: ", - program_invocation_short_name); - errno = e; - perror(print_text); -} - -__attribute__((format (gnu_printf, 2, 3))) -int fprintf_plus(FILE *stream, const char *format, ...){ - va_list ap; - va_start (ap, format); - - TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", - program_invocation_short_name)); - return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap)); -} - /* * Make additional room in "buffer" for at least BUFFER_SIZE more * bytes. "buffer_capacity" is how much is currently allocated, * "buffer_length" is how much is already used. */ size_t incbuffer(char **buffer, size_t buffer_length, - size_t buffer_capacity){ + size_t buffer_capacity){ if(buffer_length + BUFFER_SIZE > buffer_capacity){ *buffer = realloc(*buffer, buffer_capacity + BUFFER_SIZE); if(buffer == NULL){ @@ -207,51 +166,15 @@ return buffer_capacity; } -/* Add server to set of servers to retry periodically */ -bool add_server(const char *ip, in_port_t port, AvahiIfIndex if_index, - int af, server **current_server){ - int ret; - server *new_server = malloc(sizeof(server)); - if(new_server == NULL){ - perror_plus("malloc"); - return false; - } - *new_server = (server){ .ip = strdup(ip), - .port = port, - .if_index = if_index, - .af = af }; - if(new_server->ip == NULL){ - perror_plus("strdup"); - return false; - } - /* Special case of first server */ - if(*current_server == NULL){ - new_server->next = new_server; - new_server->prev = new_server; - *current_server = new_server; - /* Place the new server last in the list */ - } else { - new_server->next = *current_server; - new_server->prev = (*current_server)->prev; - new_server->prev->next = new_server; - (*current_server)->prev = new_server; - } - ret = clock_gettime(CLOCK_MONOTONIC, &(*current_server)->last_seen); - if(ret == -1){ - perror_plus("clock_gettime"); - return false; - } - return true; -} - /* * Initialize GPGME. */ -static bool init_gpgme(const char *seckey, const char *pubkey, - const char *tempdir, mandos_context *mc){ +static bool init_gpgme(const char *seckey, + const char *pubkey, const char *tempdir){ gpgme_error_t rc; gpgme_engine_info_t engine_info; + /* * Helper function to insert pub and seckey to the engine keyring. */ @@ -262,50 +185,50 @@ fd = (int)TEMP_FAILURE_RETRY(open(filename, O_RDONLY)); if(fd == -1){ - perror_plus("open"); + perror("open"); return false; } rc = gpgme_data_new_from_fd(&pgp_data, fd); if(rc != GPG_ERR_NO_ERROR){ - fprintf_plus(stderr, "bad gpgme_data_new_from_fd: %s: %s\n", - gpgme_strsource(rc), gpgme_strerror(rc)); + fprintf(stderr, "bad gpgme_data_new_from_fd: %s: %s\n", + gpgme_strsource(rc), gpgme_strerror(rc)); return false; } - rc = gpgme_op_import(mc->ctx, pgp_data); + rc = gpgme_op_import(mc.ctx, pgp_data); if(rc != GPG_ERR_NO_ERROR){ - fprintf_plus(stderr, "bad gpgme_op_import: %s: %s\n", - gpgme_strsource(rc), gpgme_strerror(rc)); + fprintf(stderr, "bad gpgme_op_import: %s: %s\n", + gpgme_strsource(rc), gpgme_strerror(rc)); return false; } ret = (int)TEMP_FAILURE_RETRY(close(fd)); if(ret == -1){ - perror_plus("close"); + perror("close"); } gpgme_data_release(pgp_data); return true; } if(debug){ - fprintf_plus(stderr, "Initializing GPGME\n"); + fprintf(stderr, "Initializing GPGME\n"); } /* Init GPGME */ gpgme_check_version(NULL); rc = gpgme_engine_check_version(GPGME_PROTOCOL_OpenPGP); if(rc != GPG_ERR_NO_ERROR){ - fprintf_plus(stderr, "bad gpgme_engine_check_version: %s: %s\n", - gpgme_strsource(rc), gpgme_strerror(rc)); + fprintf(stderr, "bad gpgme_engine_check_version: %s: %s\n", + gpgme_strsource(rc), gpgme_strerror(rc)); return false; } - /* Set GPGME home directory for the OpenPGP engine only */ + /* Set GPGME home directory for the OpenPGP engine only */ rc = gpgme_get_engine_info(&engine_info); if(rc != GPG_ERR_NO_ERROR){ - fprintf_plus(stderr, "bad gpgme_get_engine_info: %s: %s\n", - gpgme_strsource(rc), gpgme_strerror(rc)); + fprintf(stderr, "bad gpgme_get_engine_info: %s: %s\n", + gpgme_strsource(rc), gpgme_strerror(rc)); return false; } while(engine_info != NULL){ @@ -317,17 +240,15 @@ engine_info = engine_info->next; } if(engine_info == NULL){ - fprintf_plus(stderr, "Could not set GPGME home dir to %s\n", - tempdir); + fprintf(stderr, "Could not set GPGME home dir to %s\n", tempdir); return false; } /* Create new GPGME "context" */ - rc = gpgme_new(&(mc->ctx)); + rc = gpgme_new(&(mc.ctx)); if(rc != GPG_ERR_NO_ERROR){ - fprintf_plus(stderr, "Mandos plugin mandos-client: " - "bad gpgme_new: %s: %s\n", gpgme_strsource(rc), - gpgme_strerror(rc)); + fprintf(stderr, "bad gpgme_new: %s: %s\n", + gpgme_strsource(rc), gpgme_strerror(rc)); return false; } @@ -344,8 +265,7 @@ */ static ssize_t pgp_packet_decrypt(const char *cryptotext, size_t crypto_size, - char **plaintext, - mandos_context *mc){ + char **plaintext){ gpgme_data_t dh_crypto, dh_plain; gpgme_error_t rc; ssize_t ret; @@ -353,58 +273,56 @@ ssize_t plaintext_length = 0; if(debug){ - fprintf_plus(stderr, "Trying to decrypt OpenPGP data\n"); + fprintf(stderr, "Trying to decrypt OpenPGP data\n"); } /* Create new GPGME data buffer from memory cryptotext */ rc = gpgme_data_new_from_mem(&dh_crypto, cryptotext, crypto_size, 0); if(rc != GPG_ERR_NO_ERROR){ - fprintf_plus(stderr, "bad gpgme_data_new_from_mem: %s: %s\n", - gpgme_strsource(rc), gpgme_strerror(rc)); + fprintf(stderr, "bad gpgme_data_new_from_mem: %s: %s\n", + gpgme_strsource(rc), gpgme_strerror(rc)); return -1; } /* Create new empty GPGME data buffer for the plaintext */ rc = gpgme_data_new(&dh_plain); if(rc != GPG_ERR_NO_ERROR){ - fprintf_plus(stderr, "Mandos plugin mandos-client: " - "bad gpgme_data_new: %s: %s\n", - gpgme_strsource(rc), gpgme_strerror(rc)); + fprintf(stderr, "bad gpgme_data_new: %s: %s\n", + gpgme_strsource(rc), gpgme_strerror(rc)); gpgme_data_release(dh_crypto); return -1; } /* Decrypt data from the cryptotext data buffer to the plaintext data buffer */ - rc = gpgme_op_decrypt(mc->ctx, dh_crypto, dh_plain); + rc = gpgme_op_decrypt(mc.ctx, dh_crypto, dh_plain); if(rc != GPG_ERR_NO_ERROR){ - fprintf_plus(stderr, "bad gpgme_op_decrypt: %s: %s\n", - gpgme_strsource(rc), gpgme_strerror(rc)); + fprintf(stderr, "bad gpgme_op_decrypt: %s: %s\n", + gpgme_strsource(rc), gpgme_strerror(rc)); plaintext_length = -1; if(debug){ gpgme_decrypt_result_t result; - result = gpgme_op_decrypt_result(mc->ctx); + result = gpgme_op_decrypt_result(mc.ctx); if(result == NULL){ - fprintf_plus(stderr, "gpgme_op_decrypt_result failed\n"); + fprintf(stderr, "gpgme_op_decrypt_result failed\n"); } else { - fprintf_plus(stderr, "Unsupported algorithm: %s\n", - result->unsupported_algorithm); - fprintf_plus(stderr, "Wrong key usage: %u\n", - result->wrong_key_usage); + fprintf(stderr, "Unsupported algorithm: %s\n", + result->unsupported_algorithm); + fprintf(stderr, "Wrong key usage: %u\n", + result->wrong_key_usage); if(result->file_name != NULL){ - fprintf_plus(stderr, "File name: %s\n", result->file_name); + fprintf(stderr, "File name: %s\n", result->file_name); } gpgme_recipient_t recipient; recipient = result->recipients; while(recipient != NULL){ - fprintf_plus(stderr, "Public key algorithm: %s\n", - gpgme_pubkey_algo_name - (recipient->pubkey_algo)); - fprintf_plus(stderr, "Key ID: %s\n", recipient->keyid); - fprintf_plus(stderr, "Secret key available: %s\n", - recipient->status == GPG_ERR_NO_SECKEY - ? "No" : "Yes"); + fprintf(stderr, "Public key algorithm: %s\n", + gpgme_pubkey_algo_name(recipient->pubkey_algo)); + fprintf(stderr, "Key ID: %s\n", recipient->keyid); + fprintf(stderr, "Secret key available: %s\n", + recipient->status == GPG_ERR_NO_SECKEY + ? "No" : "Yes"); recipient = recipient->next; } } @@ -413,12 +331,12 @@ } if(debug){ - fprintf_plus(stderr, "Decryption of OpenPGP data succeeded\n"); + fprintf(stderr, "Decryption of OpenPGP data succeeded\n"); } /* Seek back to the beginning of the GPGME plaintext data buffer */ if(gpgme_data_seek(dh_plain, (off_t)0, SEEK_SET) == -1){ - perror_plus("gpgme_data_seek"); + perror("gpgme_data_seek"); plaintext_length = -1; goto decrypt_end; } @@ -426,12 +344,12 @@ *plaintext = NULL; while(true){ plaintext_capacity = incbuffer(plaintext, - (size_t)plaintext_length, - plaintext_capacity); + (size_t)plaintext_length, + plaintext_capacity); if(plaintext_capacity == 0){ - perror_plus("incbuffer"); - plaintext_length = -1; - goto decrypt_end; + perror("incbuffer"); + plaintext_length = -1; + goto decrypt_end; } ret = gpgme_data_read(dh_plain, *plaintext + plaintext_length, @@ -442,7 +360,7 @@ break; } if(ret < 0){ - perror_plus("gpgme_data_read"); + perror("gpgme_data_read"); plaintext_length = -1; goto decrypt_end; } @@ -450,7 +368,7 @@ } if(debug){ - fprintf_plus(stderr, "Decrypted password is: "); + fprintf(stderr, "Decrypted password is: "); for(ssize_t i = 0; i < plaintext_length; i++){ fprintf(stderr, "%02hhX ", (*plaintext)[i]); } @@ -468,7 +386,8 @@ } static const char * safer_gnutls_strerror(int value){ - const char *ret = gnutls_strerror(value); + const char *ret = gnutls_strerror(value); /* Spurious warning from + -Wunreachable-code */ if(ret == NULL) ret = "(unknown)"; return ret; @@ -477,22 +396,21 @@ /* GnuTLS log function callback */ static void debuggnutls(__attribute__((unused)) int level, const char* string){ - fprintf_plus(stderr, "GnuTLS: %s", string); + fprintf(stderr, "GnuTLS: %s", string); } static int init_gnutls_global(const char *pubkeyfilename, - const char *seckeyfilename, - mandos_context *mc){ + const char *seckeyfilename){ int ret; if(debug){ - fprintf_plus(stderr, "Initializing GnuTLS\n"); + fprintf(stderr, "Initializing GnuTLS\n"); } ret = gnutls_global_init(); if(ret != GNUTLS_E_SUCCESS){ - fprintf_plus(stderr, "GnuTLS global_init: %s\n", - safer_gnutls_strerror(ret)); + fprintf(stderr, "GnuTLS global_init: %s\n", + safer_gnutls_strerror(ret)); return -1; } @@ -505,62 +423,62 @@ } /* OpenPGP credentials */ - ret = gnutls_certificate_allocate_credentials(&mc->cred); + gnutls_certificate_allocate_credentials(&mc.cred); if(ret != GNUTLS_E_SUCCESS){ - fprintf_plus(stderr, "GnuTLS memory error: %s\n", - safer_gnutls_strerror(ret)); + fprintf(stderr, "GnuTLS memory error: %s\n", /* Spurious warning + from + -Wunreachable-code + */ + safer_gnutls_strerror(ret)); gnutls_global_deinit(); return -1; } if(debug){ - fprintf_plus(stderr, "Attempting to use OpenPGP public key %s and" - " secret key %s as GnuTLS credentials\n", - pubkeyfilename, - seckeyfilename); + fprintf(stderr, "Attempting to use OpenPGP public key %s and" + " secret key %s as GnuTLS credentials\n", pubkeyfilename, + seckeyfilename); } ret = gnutls_certificate_set_openpgp_key_file - (mc->cred, pubkeyfilename, seckeyfilename, + (mc.cred, pubkeyfilename, seckeyfilename, GNUTLS_OPENPGP_FMT_BASE64); if(ret != GNUTLS_E_SUCCESS){ - fprintf_plus(stderr, - "Error[%d] while reading the OpenPGP key pair ('%s'," - " '%s')\n", ret, pubkeyfilename, seckeyfilename); - fprintf_plus(stderr, "The GnuTLS error is: %s\n", - safer_gnutls_strerror(ret)); + fprintf(stderr, + "Error[%d] while reading the OpenPGP key pair ('%s'," + " '%s')\n", ret, pubkeyfilename, seckeyfilename); + fprintf(stderr, "The GnuTLS error is: %s\n", + safer_gnutls_strerror(ret)); goto globalfail; } /* GnuTLS server initialization */ - ret = gnutls_dh_params_init(&mc->dh_params); + ret = gnutls_dh_params_init(&mc.dh_params); if(ret != GNUTLS_E_SUCCESS){ - fprintf_plus(stderr, "Error in GnuTLS DH parameter" - " initialization: %s\n", - safer_gnutls_strerror(ret)); + fprintf(stderr, "Error in GnuTLS DH parameter initialization:" + " %s\n", safer_gnutls_strerror(ret)); goto globalfail; } - ret = gnutls_dh_params_generate2(mc->dh_params, 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: %s\n", - safer_gnutls_strerror(ret)); + fprintf(stderr, "Error in GnuTLS prime generation: %s\n", + 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; globalfail: - gnutls_certificate_free_credentials(mc->cred); + gnutls_certificate_free_credentials(mc.cred); gnutls_global_deinit(); - gnutls_dh_params_deinit(mc->dh_params); + gnutls_dh_params_deinit(mc.dh_params); return -1; } -static int init_gnutls_session(gnutls_session_t *session, - mandos_context *mc){ +static int init_gnutls_session(gnutls_session_t *session){ int ret; /* GnuTLS session creation */ do { @@ -570,24 +488,23 @@ } } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN); if(ret != GNUTLS_E_SUCCESS){ - fprintf_plus(stderr, - "Error in GnuTLS session initialization: %s\n", - safer_gnutls_strerror(ret)); + fprintf(stderr, "Error in GnuTLS session initialization: %s\n", + safer_gnutls_strerror(ret)); } { const char *err; do { - ret = gnutls_priority_set_direct(*session, mc->priority, &err); + ret = gnutls_priority_set_direct(*session, mc.priority, &err); if(quit_now){ gnutls_deinit(*session); return -1; } } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN); if(ret != GNUTLS_E_SUCCESS){ - fprintf_plus(stderr, "Syntax error at: %s\n", err); - fprintf_plus(stderr, "GnuTLS error: %s\n", - safer_gnutls_strerror(ret)); + fprintf(stderr, "Syntax error at: %s\n", err); + fprintf(stderr, "GnuTLS error: %s\n", + safer_gnutls_strerror(ret)); gnutls_deinit(*session); return -1; } @@ -595,15 +512,15 @@ do { ret = gnutls_credentials_set(*session, GNUTLS_CRD_CERTIFICATE, - mc->cred); + mc.cred); if(quit_now){ gnutls_deinit(*session); return -1; } } while(ret == GNUTLS_E_INTERRUPTED or ret == GNUTLS_E_AGAIN); if(ret != GNUTLS_E_SUCCESS){ - fprintf_plus(stderr, "Error setting GnuTLS credentials: %s\n", - safer_gnutls_strerror(ret)); + fprintf(stderr, "Error setting GnuTLS credentials: %s\n", + safer_gnutls_strerror(ret)); gnutls_deinit(*session); return -1; } @@ -611,7 +528,7 @@ /* ignore client certificate if any. */ gnutls_certificate_server_set_request(*session, GNUTLS_CERT_IGNORE); - gnutls_dh_set_prime_bits(*session, mc->dh_bits); + gnutls_dh_set_prime_bits(*session, mc.dh_bits); return 0; } @@ -621,9 +538,9 @@ __attribute__((unused)) const char *txt){} /* Called when a Mandos server is found */ -static int start_mandos_communication(const char *ip, in_port_t port, +static int start_mandos_communication(const char *ip, uint16_t port, AvahiIfIndex if_index, - int af, mandos_context *mc){ + int af){ int ret, tcp_sd = -1; ssize_t sret; union { @@ -654,57 +571,25 @@ pf = PF_INET; break; default: - fprintf_plus(stderr, "Bad address family: %d\n", af); + fprintf(stderr, "Bad address family: %d\n", af); errno = EINVAL; return -1; } - /* If the interface is specified and we have a list of interfaces */ - if(if_index != AVAHI_IF_UNSPEC and mc->interfaces != NULL){ - /* Check if the interface is one of the interfaces we are using */ - bool match = false; - { - char *interface = NULL; - while((interface=argz_next(mc->interfaces, mc->interfaces_size, - interface))){ - if(if_nametoindex(interface) == (unsigned int)if_index){ - match = true; - break; - } - } - } - if(not match){ - /* This interface does not match any in the list, so we don't - connect to the server */ - if(debug){ - char interface[IF_NAMESIZE]; - if(if_indextoname((unsigned int)if_index, interface) == NULL){ - perror_plus("if_indextoname"); - } else { - fprintf_plus(stderr, "Skipping server on non-used interface" - " \"%s\"\n", - if_indextoname((unsigned int)if_index, - interface)); - } - } - return -1; - } - } - - ret = init_gnutls_session(&session, mc); + ret = init_gnutls_session(&session); if(ret != 0){ return -1; } if(debug){ - fprintf_plus(stderr, "Setting up a TCP connection to %s, port %" - PRIuMAX "\n", ip, (uintmax_t)port); + fprintf(stderr, "Setting up a TCP connection to %s, port %" PRIu16 + "\n", ip, port); } tcp_sd = socket(pf, SOCK_STREAM, 0); if(tcp_sd < 0){ int e = errno; - perror_plus("socket"); + perror("socket"); errno = e; goto mandos_end; } @@ -724,30 +609,27 @@ } if(ret < 0 ){ int e = errno; - perror_plus("inet_pton"); + perror("inet_pton"); errno = e; goto mandos_end; } if(ret == 0){ int e = errno; - fprintf_plus(stderr, "Bad address: %s\n", ip); + fprintf(stderr, "Bad address: %s\n", ip); errno = e; goto mandos_end; } if(af == AF_INET6){ - to.in6.sin6_port = htons(port); -#ifdef __GNUC__ -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wstrict-aliasing" -#endif + to.in6.sin6_port = htons(port); /* Spurious warnings from + -Wconversion and + -Wunreachable-code */ + if(IN6_IS_ADDR_LINKLOCAL /* Spurious warnings from */ - (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower */ -#ifdef __GNUC__ -#pragma GCC diagnostic pop -#endif + (&to.in6.sin6_addr)){ /* -Wstrict-aliasing=2 or lower and + -Wunreachable-code*/ if(if_index == AVAHI_IF_UNSPEC){ - fprintf_plus(stderr, "An IPv6 link-local address is" - " incomplete without a network interface\n"); + fprintf(stderr, "An IPv6 link-local address is incomplete" + " without a network interface\n"); errno = EINVAL; goto mandos_end; } @@ -755,7 +637,9 @@ to.in6.sin6_scope_id = (uint32_t)if_index; } } else { - to.in.sin_port = htons(port); + to.in.sin_port = htons(port); /* Spurious warnings from + -Wconversion and + -Wunreachable-code */ } if(quit_now){ @@ -767,14 +651,14 @@ if(af == AF_INET6 and if_index != AVAHI_IF_UNSPEC){ char interface[IF_NAMESIZE]; if(if_indextoname((unsigned int)if_index, interface) == NULL){ - perror_plus("if_indextoname"); + perror("if_indextoname"); } else { - fprintf_plus(stderr, "Connection to: %s%%%s, port %" PRIuMAX - "\n", ip, interface, (uintmax_t)port); + fprintf(stderr, "Connection to: %s%%%s, port %" PRIu16 "\n", + ip, interface, port); } } else { - fprintf_plus(stderr, "Connection to: %s, port %" PRIuMAX "\n", - ip, (uintmax_t)port); + fprintf(stderr, "Connection to: %s, port %" PRIu16 "\n", ip, + port); } char addrstr[(INET_ADDRSTRLEN > INET6_ADDRSTRLEN) ? INET_ADDRSTRLEN : INET6_ADDRSTRLEN] = ""; @@ -787,10 +671,10 @@ sizeof(addrstr)); } if(pcret == NULL){ - perror_plus("inet_ntop"); + perror("inet_ntop"); } else { if(strcmp(addrstr, ip) != 0){ - fprintf_plus(stderr, "Canonical address form: %s\n", addrstr); + fprintf(stderr, "Canonical address form: %s\n", addrstr); } } } @@ -808,7 +692,7 @@ if(ret < 0){ if ((errno != ECONNREFUSED and errno != ENETUNREACH) or debug){ int e = errno; - perror_plus("connect"); + perror("connect"); errno = e; } goto mandos_end; @@ -824,10 +708,10 @@ while(true){ size_t out_size = strlen(out); ret = (int)TEMP_FAILURE_RETRY(write(tcp_sd, out + written, - out_size - written)); + out_size - written)); if(ret == -1){ int e = errno; - perror_plus("write"); + perror("write"); errno = e; goto mandos_end; } @@ -850,7 +734,7 @@ } if(debug){ - fprintf_plus(stderr, "Establishing TLS session with %s\n", ip); + fprintf(stderr, "Establishing TLS session with %s\n", ip); } if(quit_now){ @@ -858,11 +742,7 @@ goto mandos_end; } - /* This casting via intptr_t is to eliminate warning about casting - an int to a pointer type. This is exactly how the GnuTLS Guile - function "set-session-transport-fd!" does it. */ - gnutls_transport_set_ptr(session, - (gnutls_transport_ptr_t)(intptr_t)tcp_sd); + gnutls_transport_set_ptr(session, (gnutls_transport_ptr_t) tcp_sd); if(quit_now){ errno = EINTR; @@ -879,7 +759,7 @@ if(ret != GNUTLS_E_SUCCESS){ if(debug){ - fprintf_plus(stderr, "*** GnuTLS Handshake failed ***\n"); + fprintf(stderr, "*** GnuTLS Handshake failed ***\n"); gnutls_perror(ret); } errno = EPROTO; @@ -889,8 +769,8 @@ /* Read OpenPGP packet that contains the wanted password */ if(debug){ - fprintf_plus(stderr, "Retrieving OpenPGP encrypted password from" - " %s\n", ip); + fprintf(stderr, "Retrieving OpenPGP encrypted password from %s\n", + ip); } while(true){ @@ -901,10 +781,10 @@ } buffer_capacity = incbuffer(&buffer, buffer_length, - buffer_capacity); + buffer_capacity); if(buffer_capacity == 0){ int e = errno; - perror_plus("incbuffer"); + perror("incbuffer"); errno = e; goto mandos_end; } @@ -934,16 +814,15 @@ } } while(ret == GNUTLS_E_AGAIN or ret == GNUTLS_E_INTERRUPTED); if(ret < 0){ - fprintf_plus(stderr, "*** GnuTLS Re-handshake failed " - "***\n"); + fprintf(stderr, "*** GnuTLS Re-handshake failed ***\n"); gnutls_perror(ret); errno = EPROTO; goto mandos_end; } break; default: - fprintf_plus(stderr, "Unknown error while reading data from" - " encrypted session with Mandos server\n"); + fprintf(stderr, "Unknown error while reading data from" + " encrypted session with Mandos server\n"); gnutls_bye(session, GNUTLS_SHUT_RDWR); errno = EIO; goto mandos_end; @@ -954,7 +833,7 @@ } if(debug){ - fprintf_plus(stderr, "Closing TLS session\n"); + fprintf(stderr, "Closing TLS session\n"); } if(quit_now){ @@ -972,8 +851,9 @@ if(buffer_length > 0){ ssize_t decrypted_buffer_size; - decrypted_buffer_size = pgp_packet_decrypt(buffer, buffer_length, - &decrypted_buffer, mc); + decrypted_buffer_size = pgp_packet_decrypt(buffer, + buffer_length, + &decrypted_buffer); if(decrypted_buffer_size >= 0){ written = 0; @@ -989,8 +869,8 @@ if(ret == 0 and ferror(stdout)){ int e = errno; if(debug){ - fprintf_plus(stderr, "Error writing encrypted data: %s\n", - strerror(errno)); + fprintf(stderr, "Error writing encrypted data: %s\n", + strerror(errno)); } errno = e; goto mandos_end; @@ -1015,14 +895,14 @@ if(e == 0){ e = errno; } - perror_plus("close"); + perror("close"); } gnutls_deinit(session); - errno = e; if(quit_now){ - errno = EINTR; + e = EINTR; retval = -1; } + errno = e; } return retval; } @@ -1040,10 +920,8 @@ AVAHI_GCC_UNUSED AvahiStringList *txt, AVAHI_GCC_UNUSED AvahiLookupResultFlags flags, - void* mc){ - if(r == NULL){ - return; - } + AVAHI_GCC_UNUSED void* userdata){ + assert(r); /* Called whenever a service has been resolved successfully or timed out */ @@ -1055,11 +933,9 @@ switch(event){ default: case AVAHI_RESOLVER_FAILURE: - fprintf_plus(stderr, "(Avahi Resolver) Failed to resolve service " - "'%s' of type '%s' in domain '%s': %s\n", name, type, - domain, - avahi_strerror(avahi_server_errno - (((mandos_context*)mc)->server))); + fprintf(stderr, "(Avahi Resolver) Failed to resolve service '%s'" + " of type '%s' in domain '%s': %s\n", name, type, domain, + avahi_strerror(avahi_server_errno(mc.server))); break; case AVAHI_RESOLVER_FOUND: @@ -1067,23 +943,14 @@ char ip[AVAHI_ADDRESS_STR_MAX]; avahi_address_snprint(ip, sizeof(ip), address); if(debug){ - fprintf_plus(stderr, "Mandos server \"%s\" found on %s (%s, %" - PRIdMAX ") on port %" PRIu16 "\n", name, - host_name, ip, (intmax_t)interface, port); + fprintf(stderr, "Mandos server \"%s\" found on %s (%s, %" + PRIdMAX ") on port %" PRIu16 "\n", name, host_name, + ip, (intmax_t)interface, port); } - int ret = start_mandos_communication(ip, (in_port_t)port, - interface, - avahi_proto_to_af(proto), - mc); + int ret = start_mandos_communication(ip, port, interface, + avahi_proto_to_af(proto)); if(ret == 0){ - avahi_simple_poll_quit(simple_poll); - } else { - if(not add_server(ip, (in_port_t)port, interface, - avahi_proto_to_af(proto), - &((mandos_context*)mc)->current_server)){ - fprintf_plus(stderr, "Failed to add server \"%s\" to server" - " list\n", name); - } + avahi_simple_poll_quit(mc.simple_poll); } } } @@ -1099,10 +966,8 @@ const char *domain, AVAHI_GCC_UNUSED AvahiLookupResultFlags flags, - void* mc){ - if(b == NULL){ - return; - } + AVAHI_GCC_UNUSED void* userdata){ + assert(b); /* Called whenever a new services becomes available on the LAN or is removed from the LAN */ @@ -1115,10 +980,9 @@ default: case AVAHI_BROWSER_FAILURE: - fprintf_plus(stderr, "(Avahi browser) %s\n", - avahi_strerror(avahi_server_errno - (((mandos_context*)mc)->server))); - avahi_simple_poll_quit(simple_poll); + fprintf(stderr, "(Avahi browser) %s\n", + avahi_strerror(avahi_server_errno(mc.server))); + avahi_simple_poll_quit(mc.simple_poll); return; case AVAHI_BROWSER_NEW: @@ -1127,14 +991,11 @@ the callback function is called the Avahi server will free the resolver for us. */ - if(avahi_s_service_resolver_new(((mandos_context*)mc)->server, - interface, protocol, name, type, - domain, protocol, 0, - resolve_callback, mc) == NULL) - fprintf_plus(stderr, "Avahi: Failed to resolve service '%s':" - " %s\n", name, - avahi_strerror(avahi_server_errno - (((mandos_context*)mc)->server))); + if(avahi_s_service_resolver_new(mc.server, interface, protocol, + name, type, domain, protocol, 0, + resolve_callback, NULL) == NULL) + fprintf(stderr, "Avahi: Failed to resolve service '%s': %s\n", + name, avahi_strerror(avahi_server_errno(mc.server))); break; case AVAHI_BROWSER_REMOVE: @@ -1143,14 +1004,13 @@ case AVAHI_BROWSER_ALL_FOR_NOW: case AVAHI_BROWSER_CACHE_EXHAUSTED: if(debug){ - fprintf_plus(stderr, "No Mandos server found, still" - " searching...\n"); + fprintf(stderr, "No Mandos server found, still searching...\n"); } break; } } -/* Signal handler that stops main loop after SIGTERM */ +/* stop main loop after sigterm has been called */ static void handle_sigterm(int sig){ if(quit_now){ return; @@ -1158,664 +1018,129 @@ quit_now = 1; signal_received = sig; int old_errno = errno; - /* set main loop to exit */ - if(simple_poll != NULL){ - avahi_simple_poll_quit(simple_poll); + if(mc.simple_poll != NULL){ + avahi_simple_poll_quit(mc.simple_poll); } errno = old_errno; } -bool get_flags(const char *ifname, struct ifreq *ifr){ - int ret; - error_t ret_errno; - - int s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP); - if(s < 0){ - ret_errno = errno; - perror_plus("socket"); - errno = ret_errno; - return false; - } - strcpy(ifr->ifr_name, ifname); - ret = ioctl(s, SIOCGIFFLAGS, ifr); - if(ret == -1){ - if(debug){ - ret_errno = errno; - perror_plus("ioctl SIOCGIFFLAGS"); - errno = ret_errno; - } - return false; - } - return true; -} - -bool good_flags(const char *ifname, const struct ifreq *ifr){ - - /* Reject the loopback device */ - if(ifr->ifr_flags & IFF_LOOPBACK){ - if(debug){ - fprintf_plus(stderr, "Rejecting loopback interface \"%s\"\n", - ifname); - } - return false; - } - /* Accept point-to-point devices only if connect_to is specified */ - if(connect_to != NULL and (ifr->ifr_flags & IFF_POINTOPOINT)){ - if(debug){ - fprintf_plus(stderr, "Accepting point-to-point interface" - " \"%s\"\n", ifname); - } - return true; - } - /* Otherwise, reject non-broadcast-capable devices */ - if(not (ifr->ifr_flags & IFF_BROADCAST)){ - if(debug){ - fprintf_plus(stderr, "Rejecting non-broadcast interface" - " \"%s\"\n", ifname); - } - return false; - } - /* Reject non-ARP interfaces (including dummy interfaces) */ - if(ifr->ifr_flags & IFF_NOARP){ - if(debug){ - fprintf_plus(stderr, "Rejecting non-ARP interface \"%s\"\n", - ifname); - } - return false; - } - - /* Accept this device */ - if(debug){ - fprintf_plus(stderr, "Interface \"%s\" is good\n", ifname); - } - return true; -} - /* * This function determines if a directory entry in /sys/class/net * corresponds to an acceptable network device. * (This function is passed to scandir(3) as a filter function.) */ int good_interface(const struct dirent *if_entry){ + ssize_t ssret; + char *flagname = NULL; + int ret = asprintf(&flagname, "%s/%s/flags", sys_class_net, + if_entry->d_name); + if(ret < 0){ + perror("asprintf"); + return 0; + } if(if_entry->d_name[0] == '.'){ return 0; } - - struct ifreq ifr; - if(not get_flags(if_entry->d_name, &ifr)){ - if(debug){ - fprintf_plus(stderr, "Failed to get flags for interface " - "\"%s\"\n", if_entry->d_name); - } - return 0; - } - - if(not good_flags(if_entry->d_name, &ifr)){ - return 0; - } - return 1; -} - -/* - * This function determines if a network interface is up. - */ -bool interface_is_up(const char *interface){ - struct ifreq ifr; - if(not get_flags(interface, &ifr)){ - if(debug){ - fprintf_plus(stderr, "Failed to get flags for interface " - "\"%s\"\n", interface); - } - return false; - } - - return (bool)(ifr.ifr_flags & IFF_UP); -} - -/* - * This function determines if a network interface is running - */ -bool interface_is_running(const char *interface){ - struct ifreq ifr; - if(not get_flags(interface, &ifr)){ - if(debug){ - fprintf_plus(stderr, "Failed to get flags for interface " - "\"%s\"\n", interface); - } - return false; - } - - return (bool)(ifr.ifr_flags & IFF_RUNNING); -} - -int notdotentries(const struct dirent *direntry){ - /* Skip "." and ".." */ - if(direntry->d_name[0] == '.' - and (direntry->d_name[1] == '\0' - or (direntry->d_name[1] == '.' - and direntry->d_name[2] == '\0'))){ - return 0; - } - return 1; -} - -/* Is this directory entry a runnable program? */ -int runnable_hook(const struct dirent *direntry){ - int ret; - size_t sret; - struct stat st; - - if((direntry->d_name)[0] == '\0'){ - /* Empty name? */ - return 0; - } - - sret = strspn(direntry->d_name, "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789" - "_-"); - if((direntry->d_name)[sret] != '\0'){ - /* Contains non-allowed characters */ - if(debug){ - fprintf_plus(stderr, "Ignoring hook \"%s\" with bad name\n", - direntry->d_name); - } - return 0; - } - - char *fullname = NULL; - ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name); - if(ret < 0){ - perror_plus("asprintf"); - return 0; - } - - ret = stat(fullname, &st); - if(ret == -1){ - if(debug){ - perror_plus("Could not stat hook"); - } - return 0; - } - if(not (S_ISREG(st.st_mode))){ - /* Not a regular file */ - if(debug){ - fprintf_plus(stderr, "Ignoring hook \"%s\" - not a file\n", - direntry->d_name); - } - return 0; - } - if(not (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))){ - /* Not executable */ - if(debug){ - fprintf_plus(stderr, "Ignoring hook \"%s\" - not executable\n", - direntry->d_name); - } - return 0; - } + int flags_fd = (int)TEMP_FAILURE_RETRY(open(flagname, O_RDONLY)); + if(flags_fd == -1){ + perror("open"); + return 0; + } + typedef short ifreq_flags; /* ifreq.ifr_flags in netdevice(7) */ + /* read line from flags_fd */ + ssize_t to_read = (sizeof(ifreq_flags)*2)+3; /* "0x1003\n" */ + char *flagstring = malloc((size_t)to_read+1); /* +1 for final \0 */ + flagstring[(size_t)to_read] = '\0'; + if(flagstring == NULL){ + perror("malloc"); + close(flags_fd); + return 0; + } + while(to_read > 0){ + ssret = (ssize_t)TEMP_FAILURE_RETRY(read(flags_fd, flagstring, + (size_t)to_read)); + if(ssret == -1){ + perror("read"); + free(flagstring); + close(flags_fd); + return 0; + } + to_read -= ssret; + if(ssret == 0){ + break; + } + } + close(flags_fd); + intmax_t tmpmax; + char *tmp; + errno = 0; + tmpmax = strtoimax(flagstring, &tmp, 0); + if(errno != 0 or tmp == flagstring or (*tmp != '\0' + and not (isspace(*tmp))) + or tmpmax != (ifreq_flags)tmpmax){ + if(debug){ + fprintf(stderr, "Invalid flags \"%s\" for interface \"%s\"\n", + flagstring, if_entry->d_name); + } + free(flagstring); + return 0; + } + free(flagstring); + ifreq_flags flags = (ifreq_flags)tmpmax; + /* Reject the loopback device */ + if(flags & IFF_LOOPBACK){ + if(debug){ + fprintf(stderr, "Rejecting loopback interface \"%s\"\n", + if_entry->d_name); + } + return 0; + } + /* Accept point-to-point devices only if connect_to is specified */ + if(connect_to != NULL and (flags & IFF_POINTOPOINT)){ + if(debug){ + fprintf(stderr, "Accepting point-to-point interface \"%s\"\n", + if_entry->d_name); + } + return 1; + } + /* Otherwise, reject non-broadcast-capable devices */ + if(not (flags & IFF_BROADCAST)){ + if(debug){ + fprintf(stderr, "Rejecting non-broadcast interface \"%s\"\n", + if_entry->d_name); + } + return 0; + } + /* Accept this device */ if(debug){ - fprintf_plus(stderr, "Hook \"%s\" is acceptable\n", - direntry->d_name); + fprintf(stderr, "Interface \"%s\" is acceptable\n", + if_entry->d_name); } return 1; } -int avahi_loop_with_timeout(AvahiSimplePoll *s, int retry_interval, - mandos_context *mc){ - int ret; - struct timespec now; - struct timespec waited_time; - intmax_t block_time; - - while(true){ - if(mc->current_server == NULL){ - if (debug){ - fprintf_plus(stderr, "Wait until first server is found." - " No timeout!\n"); - } - ret = avahi_simple_poll_iterate(s, -1); - } else { - if (debug){ - fprintf_plus(stderr, "Check current_server if we should run" - " it, or wait\n"); - } - /* the current time */ - ret = clock_gettime(CLOCK_MONOTONIC, &now); - if(ret == -1){ - perror_plus("clock_gettime"); - return -1; - } - /* Calculating in ms how long time between now and server - who we visted longest time ago. Now - last seen. */ - waited_time.tv_sec = (now.tv_sec - - mc->current_server->last_seen.tv_sec); - waited_time.tv_nsec = (now.tv_nsec - - mc->current_server->last_seen.tv_nsec); - /* total time is 10s/10,000ms. - Converting to s from ms by dividing by 1,000, - and ns to ms by dividing by 1,000,000. */ - block_time = ((retry_interval - - ((intmax_t)waited_time.tv_sec * 1000)) - - ((intmax_t)waited_time.tv_nsec / 1000000)); - - if (debug){ - fprintf_plus(stderr, "Blocking for %" PRIdMAX " ms\n", - block_time); - } - - if(block_time <= 0){ - ret = start_mandos_communication(mc->current_server->ip, - mc->current_server->port, - mc->current_server->if_index, - mc->current_server->af, mc); - if(ret == 0){ - avahi_simple_poll_quit(s); - return 0; - } - ret = clock_gettime(CLOCK_MONOTONIC, - &mc->current_server->last_seen); - if(ret == -1){ - perror_plus("clock_gettime"); - return -1; - } - mc->current_server = mc->current_server->next; - block_time = 0; /* Call avahi to find new Mandos - servers, but don't block */ - } - - ret = avahi_simple_poll_iterate(s, (int)block_time); - } - if(ret != 0){ - if (ret > 0 or errno != EINTR){ - return (ret != 1) ? ret : 0; - } - } - } -} - -/* Set effective uid to 0, return errno */ -error_t raise_privileges(void){ - error_t old_errno = errno; - error_t ret_errno = 0; - if(seteuid(0) == -1){ - ret_errno = errno; - perror_plus("seteuid"); - } - errno = old_errno; - return ret_errno; -} - -/* Set effective and real user ID to 0. Return errno. */ -error_t raise_privileges_permanently(void){ - error_t old_errno = errno; - error_t ret_errno = raise_privileges(); - if(ret_errno != 0){ - errno = old_errno; - return ret_errno; - } - if(setuid(0) == -1){ - ret_errno = errno; - perror_plus("seteuid"); - } - errno = old_errno; - return ret_errno; -} - -/* Set effective user ID to unprivileged saved user ID */ -error_t lower_privileges(void){ - error_t old_errno = errno; - error_t ret_errno = 0; - if(seteuid(uid) == -1){ - ret_errno = errno; - perror_plus("seteuid"); - } - errno = old_errno; - return ret_errno; -} - -/* Lower privileges permanently */ -error_t lower_privileges_permanently(void){ - error_t old_errno = errno; - error_t ret_errno = 0; - if(setuid(uid) == -1){ - ret_errno = errno; - perror_plus("setuid"); - } - errno = old_errno; - return ret_errno; -} - -bool run_network_hooks(const char *mode, const char *interface, - const float delay){ - struct dirent **direntries; - struct dirent *direntry; - int ret; - int numhooks = scandir(hookdir, &direntries, runnable_hook, - alphasort); - if(numhooks == -1){ - if(errno == ENOENT){ - if(debug){ - fprintf_plus(stderr, "Network hook directory \"%s\" not" - " found\n", hookdir); - } - } else { - perror_plus("scandir"); - } - } else { - int devnull = open("/dev/null", O_RDONLY); - for(int i = 0; i < numhooks; i++){ - direntry = direntries[i]; - char *fullname = NULL; - ret = asprintf(&fullname, "%s/%s", hookdir, direntry->d_name); - if(ret < 0){ - perror_plus("asprintf"); - continue; - } - if(debug){ - fprintf_plus(stderr, "Running network hook \"%s\"\n", - direntry->d_name); - } - pid_t hook_pid = fork(); - if(hook_pid == 0){ - /* Child */ - /* Raise privileges */ - raise_privileges_permanently(); - /* Set group */ - errno = 0; - ret = setgid(0); - if(ret == -1){ - perror_plus("setgid"); - } - /* Reset supplementary groups */ - errno = 0; - ret = setgroups(0, NULL); - if(ret == -1){ - perror_plus("setgroups"); - } - dup2(devnull, STDIN_FILENO); - close(devnull); - dup2(STDERR_FILENO, STDOUT_FILENO); - ret = setenv("MANDOSNETHOOKDIR", hookdir, 1); - if(ret == -1){ - perror_plus("setenv"); - _exit(EX_OSERR); - } - ret = setenv("DEVICE", interface, 1); - if(ret == -1){ - perror_plus("setenv"); - _exit(EX_OSERR); - } - ret = setenv("VERBOSITY", debug ? "1" : "0", 1); - if(ret == -1){ - perror_plus("setenv"); - _exit(EX_OSERR); - } - ret = setenv("MODE", mode, 1); - if(ret == -1){ - perror_plus("setenv"); - _exit(EX_OSERR); - } - char *delaystring; - ret = asprintf(&delaystring, "%f", delay); - if(ret == -1){ - perror_plus("asprintf"); - _exit(EX_OSERR); - } - ret = setenv("DELAY", delaystring, 1); - if(ret == -1){ - free(delaystring); - perror_plus("setenv"); - _exit(EX_OSERR); - } - free(delaystring); - if(connect_to != NULL){ - ret = setenv("CONNECT", connect_to, 1); - if(ret == -1){ - perror_plus("setenv"); - _exit(EX_OSERR); - } - } - if(execl(fullname, direntry->d_name, mode, NULL) == -1){ - perror_plus("execl"); - _exit(EXIT_FAILURE); - } - } else { - int status; - if(TEMP_FAILURE_RETRY(waitpid(hook_pid, &status, 0)) == -1){ - perror_plus("waitpid"); - free(fullname); - continue; - } - if(WIFEXITED(status)){ - if(WEXITSTATUS(status) != 0){ - fprintf_plus(stderr, "Warning: network hook \"%s\" exited" - " with status %d\n", direntry->d_name, - WEXITSTATUS(status)); - free(fullname); - continue; - } - } else if(WIFSIGNALED(status)){ - fprintf_plus(stderr, "Warning: network hook \"%s\" died by" - " signal %d\n", direntry->d_name, - WTERMSIG(status)); - free(fullname); - continue; - } else { - fprintf_plus(stderr, "Warning: network hook \"%s\"" - " crashed\n", direntry->d_name); - free(fullname); - continue; - } - } - free(fullname); - if(debug){ - fprintf_plus(stderr, "Network hook \"%s\" ran successfully\n", - direntry->d_name); - } - } - close(devnull); - } - return true; -} - -error_t bring_up_interface(const char *const interface, - const float delay){ - int sd = -1; - error_t old_errno = errno; - error_t ret_errno = 0; - int ret, ret_setflags; - struct ifreq network; - unsigned int if_index = if_nametoindex(interface); - if(if_index == 0){ - fprintf_plus(stderr, "No such interface: \"%s\"\n", interface); - errno = old_errno; - return ENXIO; - } - - if(quit_now){ - errno = old_errno; - return EINTR; - } - - if(not interface_is_up(interface)){ - if(not get_flags(interface, &network) and debug){ - ret_errno = errno; - fprintf_plus(stderr, "Failed to get flags for interface " - "\"%s\"\n", interface); - return ret_errno; - } - network.ifr_flags |= IFF_UP; - - sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP); - if(sd < 0){ - ret_errno = errno; - perror_plus("socket"); - errno = old_errno; - return ret_errno; - } - - if(quit_now){ - close(sd); - errno = old_errno; - return EINTR; - } - - if(debug){ - fprintf_plus(stderr, "Bringing up interface \"%s\"\n", - interface); - } - - /* Raise priviliges */ - raise_privileges(); - -#ifdef __linux__ - /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO - messages about the network interface to mess up the prompt */ - int ret_linux = klogctl(8, NULL, 5); - bool restore_loglevel = true; - if(ret_linux == -1){ - restore_loglevel = false; - perror_plus("klogctl"); - } -#endif /* __linux__ */ - ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network); - ret_errno = errno; -#ifdef __linux__ - if(restore_loglevel){ - ret_linux = klogctl(7, NULL, 0); - if(ret_linux == -1){ - perror_plus("klogctl"); - } - } -#endif /* __linux__ */ - - /* Lower privileges */ - lower_privileges(); - - /* Close the socket */ - ret = (int)TEMP_FAILURE_RETRY(close(sd)); - if(ret == -1){ - perror_plus("close"); - } - - if(ret_setflags == -1){ - errno = ret_errno; - perror_plus("ioctl SIOCSIFFLAGS +IFF_UP"); - errno = old_errno; - return ret_errno; - } - } else if(debug){ - fprintf_plus(stderr, "Interface \"%s\" is already up; good\n", - interface); - } - - /* Sleep checking until interface is running. - Check every 0.25s, up to total time of delay */ - for(int i=0; i < delay * 4; i++){ - if(interface_is_running(interface)){ - break; - } - struct timespec sleeptime = { .tv_nsec = 250000000 }; - ret = nanosleep(&sleeptime, NULL); - if(ret == -1 and errno != EINTR){ - perror_plus("nanosleep"); - } - } - - errno = old_errno; - return 0; -} - -error_t take_down_interface(const char *const interface){ - int sd = -1; - error_t old_errno = errno; - error_t ret_errno = 0; - int ret, ret_setflags; - struct ifreq network; - unsigned int if_index = if_nametoindex(interface); - if(if_index == 0){ - fprintf_plus(stderr, "No such interface: \"%s\"\n", interface); - errno = old_errno; - return ENXIO; - } - if(interface_is_up(interface)){ - if(not get_flags(interface, &network) and debug){ - ret_errno = errno; - fprintf_plus(stderr, "Failed to get flags for interface " - "\"%s\"\n", interface); - return ret_errno; - } - network.ifr_flags &= ~(short)IFF_UP; /* clear flag */ - - sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP); - if(sd < 0){ - ret_errno = errno; - perror_plus("socket"); - errno = old_errno; - return ret_errno; - } - - if(debug){ - fprintf_plus(stderr, "Taking down interface \"%s\"\n", - interface); - } - - /* Raise priviliges */ - raise_privileges(); - - ret_setflags = ioctl(sd, SIOCSIFFLAGS, &network); - ret_errno = errno; - - /* Lower privileges */ - lower_privileges(); - - /* Close the socket */ - ret = (int)TEMP_FAILURE_RETRY(close(sd)); - if(ret == -1){ - perror_plus("close"); - } - - if(ret_setflags == -1){ - errno = ret_errno; - perror_plus("ioctl SIOCSIFFLAGS -IFF_UP"); - errno = old_errno; - return ret_errno; - } - } else if(debug){ - fprintf_plus(stderr, "Interface \"%s\" is already down; odd\n", - interface); - } - - errno = old_errno; - return 0; -} - int main(int argc, char *argv[]){ - mandos_context mc = { .server = NULL, .dh_bits = 1024, - .priority = "SECURE256:!CTYPE-X.509:" - "+CTYPE-OPENPGP", .current_server = NULL, - .interfaces = NULL, .interfaces_size = 0 }; AvahiSServiceBrowser *sb = NULL; - error_t ret_errno; + int error; int ret; intmax_t tmpmax; char *tmp; int exitcode = EXIT_SUCCESS; - char *interfaces_to_take_down = NULL; - size_t interfaces_to_take_down_size = 0; + const char *interface = ""; + struct ifreq network; + int sd = -1; + bool take_down_interface = false; + uid_t uid; + gid_t gid; char tempdir[] = "/tmp/mandosXXXXXX"; bool tempdir_created = false; AvahiIfIndex if_index = AVAHI_IF_UNSPEC; const char *seckey = PATHDIR "/" SECKEY; const char *pubkey = PATHDIR "/" PUBKEY; - char *interfaces_hooks = NULL; - size_t interfaces_hooks_size = 0; bool gnutls_initialized = false; bool gpgme_initialized = false; float delay = 2.5f; - double retry_interval = 10; /* 10s between trying a server and - retrying the same server again */ struct sigaction old_sigterm_action = { .sa_handler = SIG_DFL }; struct sigaction sigterm_action = { .sa_handler = handle_sigterm }; @@ -1827,14 +1152,14 @@ errno = 0; ret = setgid(gid); if(ret == -1){ - perror_plus("setgid"); + perror("setgid"); } /* Lower user privileges (temporarily) */ errno = 0; ret = seteuid(uid); if(ret == -1){ - perror_plus("seteuid"); + perror("seteuid"); } if(quit_now){ @@ -1875,14 +1200,6 @@ .arg = "SECONDS", .doc = "Maximum delay to wait for interface startup", .group = 2 }, - { .name = "retry", .key = 132, - .arg = "SECONDS", - .doc = "Retry interval used when denied by the Mandos server", - .group = 2 }, - { .name = "network-hook-dir", .key = 133, - .arg = "DIR", - .doc = "Directory where network hooks are located", - .group = 2 }, /* * These reproduce what we would get without ARGP_NO_HELP */ @@ -1906,11 +1223,7 @@ connect_to = arg; break; case 'i': /* --interface */ - ret_errno = argz_add_sep(&mc.interfaces, &mc.interfaces_size, - arg, (int)','); - if(ret_errno != 0){ - argp_error(state, "%s", strerror(ret_errno)); - } + interface = arg; break; case 's': /* --seckey */ seckey = arg; @@ -1936,17 +1249,6 @@ if(errno != 0 or tmp == arg or *tmp != '\0'){ argp_error(state, "Bad delay"); } - case 132: /* --retry */ - errno = 0; - retry_interval = strtod(arg, &tmp); - if(errno != 0 or tmp == arg or *tmp != '\0' - or (retry_interval * 1000) > INT_MAX - or retry_interval < 0){ - argp_error(state, "Bad retry interval"); - } - break; - case 133: /* --network-hook-dir */ - hookdir = arg; break; /* * These reproduce what we would get without ARGP_NO_HELP @@ -1959,7 +1261,7 @@ argp_state_help(state, state->out_stream, ARGP_HELP_USAGE | ARGP_HELP_EXIT_ERR); case 'V': /* --version */ - fprintf_plus(state->out_stream, "%s\n", argp_program_version); + fprintf(state->out_stream, "%s\n", argp_program_version); exit(argp_err_exit_status); break; default: @@ -1980,7 +1282,7 @@ case ENOMEM: default: errno = ret; - perror_plus("argp_parse"); + perror("argp_parse"); exitcode = EX_OSERR; goto end; case EINVAL: @@ -1988,110 +1290,43 @@ goto end; } } - - { - /* Work around Debian bug #633582: - */ - - /* Re-raise priviliges */ - if(raise_privileges() == 0){ - struct stat st; - - if(strcmp(seckey, PATHDIR "/" SECKEY) == 0){ - int seckey_fd = open(seckey, O_RDONLY); - if(seckey_fd == -1){ - perror_plus("open"); - } else { - ret = (int)TEMP_FAILURE_RETRY(fstat(seckey_fd, &st)); - if(ret == -1){ - perror_plus("fstat"); - } else { - if(S_ISREG(st.st_mode) - and st.st_uid == 0 and st.st_gid == 0){ - ret = fchown(seckey_fd, uid, gid); - if(ret == -1){ - perror_plus("fchown"); - } - } - } - TEMP_FAILURE_RETRY(close(seckey_fd)); - } - } - - if(strcmp(pubkey, PATHDIR "/" PUBKEY) == 0){ - int pubkey_fd = open(pubkey, O_RDONLY); - if(pubkey_fd == -1){ - perror_plus("open"); - } else { - ret = (int)TEMP_FAILURE_RETRY(fstat(pubkey_fd, &st)); - if(ret == -1){ - perror_plus("fstat"); - } else { - if(S_ISREG(st.st_mode) - and st.st_uid == 0 and st.st_gid == 0){ - ret = fchown(pubkey_fd, uid, gid); - if(ret == -1){ - perror_plus("fchown"); - } - } - } - TEMP_FAILURE_RETRY(close(pubkey_fd)); - } - } - - /* Lower privileges */ - lower_privileges(); - } - } - - /* Remove invalid interface names (except "none") */ - { - char *interface = NULL; - while((interface = argz_next(mc.interfaces, mc.interfaces_size, - interface))){ - if(strcmp(interface, "none") != 0 - and if_nametoindex(interface) == 0){ - if(interface[0] != '\0'){ - fprintf_plus(stderr, "Not using nonexisting interface" - " \"%s\"\n", interface); - } - argz_delete(&mc.interfaces, &mc.interfaces_size, interface); - interface = NULL; - } - } - } - - /* Run network hooks */ - { - if(mc.interfaces != NULL){ - interfaces_hooks = malloc(mc.interfaces_size); - if(interfaces_hooks == NULL){ - perror_plus("malloc"); - goto end; - } - memcpy(interfaces_hooks, mc.interfaces, mc.interfaces_size); - interfaces_hooks_size = mc.interfaces_size; - argz_stringify(interfaces_hooks, interfaces_hooks_size, - (int)','); - } - if(not run_network_hooks("start", interfaces_hooks != NULL ? - interfaces_hooks : "", delay)){ - goto end; - } - } if(not debug){ avahi_set_log_function(empty_log); } + + if(interface[0] == '\0'){ + struct dirent **direntries; + ret = scandir(sys_class_net, &direntries, good_interface, + alphasort); + if(ret >= 1){ + /* Pick the first good interface */ + interface = strdup(direntries[0]->d_name); + if(debug){ + fprintf(stderr, "Using interface \"%s\"\n", interface); + } + if(interface == NULL){ + perror("malloc"); + free(direntries); + exitcode = EXIT_FAILURE; + goto end; + } + free(direntries); + } else { + free(direntries); + fprintf(stderr, "Could not find a network interface\n"); + exitcode = EXIT_FAILURE; + goto end; + } + } /* Initialize Avahi early so avahi_simple_poll_quit() can be called from the signal handler */ /* Initialize the pseudo-RNG for Avahi */ srand((unsigned int) time(NULL)); - simple_poll = avahi_simple_poll_new(); - if(simple_poll == NULL){ - fprintf_plus(stderr, - "Avahi: Failed to create simple poll object.\n"); + mc.simple_poll = avahi_simple_poll_new(); + if(mc.simple_poll == NULL){ + fprintf(stderr, "Avahi: Failed to create simple poll object.\n"); exitcode = EX_UNAVAILABLE; goto end; } @@ -2099,19 +1334,19 @@ sigemptyset(&sigterm_action.sa_mask); ret = sigaddset(&sigterm_action.sa_mask, SIGINT); if(ret == -1){ - perror_plus("sigaddset"); + perror("sigaddset"); exitcode = EX_OSERR; goto end; } ret = sigaddset(&sigterm_action.sa_mask, SIGHUP); if(ret == -1){ - perror_plus("sigaddset"); + perror("sigaddset"); exitcode = EX_OSERR; goto end; } ret = sigaddset(&sigterm_action.sa_mask, SIGTERM); if(ret == -1){ - perror_plus("sigaddset"); + perror("sigaddset"); exitcode = EX_OSERR; goto end; } @@ -2121,128 +1356,195 @@ */ ret = sigaction(SIGINT, NULL, &old_sigterm_action); if(ret == -1){ - perror_plus("sigaction"); + perror("sigaction"); return EX_OSERR; } if(old_sigterm_action.sa_handler != SIG_IGN){ ret = sigaction(SIGINT, &sigterm_action, NULL); if(ret == -1){ - perror_plus("sigaction"); + perror("sigaction"); exitcode = EX_OSERR; goto end; } } ret = sigaction(SIGHUP, NULL, &old_sigterm_action); if(ret == -1){ - perror_plus("sigaction"); + perror("sigaction"); return EX_OSERR; } if(old_sigterm_action.sa_handler != SIG_IGN){ ret = sigaction(SIGHUP, &sigterm_action, NULL); if(ret == -1){ - perror_plus("sigaction"); + perror("sigaction"); exitcode = EX_OSERR; goto end; } } ret = sigaction(SIGTERM, NULL, &old_sigterm_action); if(ret == -1){ - perror_plus("sigaction"); + perror("sigaction"); return EX_OSERR; } if(old_sigterm_action.sa_handler != SIG_IGN){ ret = sigaction(SIGTERM, &sigterm_action, NULL); if(ret == -1){ - perror_plus("sigaction"); - exitcode = EX_OSERR; - goto end; - } - } - - /* If no interfaces were specified, make a list */ - if(mc.interfaces == NULL){ - struct dirent **direntries; - /* Look for any good interfaces */ - ret = scandir(sys_class_net, &direntries, good_interface, - alphasort); - if(ret >= 1){ - /* Add all found interfaces to interfaces list */ - for(int i = 0; i < ret; ++i){ - ret_errno = argz_add(&mc.interfaces, &mc.interfaces_size, - direntries[i]->d_name); - if(ret_errno != 0){ - perror_plus("argz_add"); - continue; - } - if(debug){ - fprintf_plus(stderr, "Will use interface \"%s\"\n", - direntries[i]->d_name); - } - } - free(direntries); - } else { - free(direntries); - fprintf_plus(stderr, "Could not find a network interface\n"); - exitcode = EXIT_FAILURE; - goto end; - } - } - - /* Bring up interfaces which are down, and remove any "none"s */ - { - char *interface = NULL; - while((interface = argz_next(mc.interfaces, mc.interfaces_size, - interface))){ - /* If interface name is "none", stop bringing up interfaces. - Also remove all instances of "none" from the list */ - if(strcmp(interface, "none") == 0){ - argz_delete(&mc.interfaces, &mc.interfaces_size, - interface); - interface = NULL; - while((interface = argz_next(mc.interfaces, - mc.interfaces_size, interface))){ - if(strcmp(interface, "none") == 0){ - argz_delete(&mc.interfaces, &mc.interfaces_size, - interface); - interface = NULL; + perror("sigaction"); + exitcode = EX_OSERR; + goto end; + } + } + + /* If the interface is down, bring it up */ + if(strcmp(interface, "none") != 0){ + if_index = (AvahiIfIndex) if_nametoindex(interface); + if(if_index == 0){ + fprintf(stderr, "No such interface: \"%s\"\n", interface); + exitcode = EX_UNAVAILABLE; + goto end; + } + + if(quit_now){ + goto end; + } + + /* Re-raise priviliges */ + errno = 0; + ret = seteuid(0); + if(ret == -1){ + perror("seteuid"); + } + +#ifdef __linux__ + /* Lower kernel loglevel to KERN_NOTICE to avoid KERN_INFO + messages about the network interface to mess up the prompt */ + ret = klogctl(8, NULL, 5); + bool restore_loglevel = true; + if(ret == -1){ + restore_loglevel = false; + perror("klogctl"); + } +#endif /* __linux__ */ + + sd = socket(PF_INET6, SOCK_DGRAM, IPPROTO_IP); + if(sd < 0){ + perror("socket"); + exitcode = EX_OSERR; +#ifdef __linux__ + if(restore_loglevel){ + ret = klogctl(7, NULL, 0); + if(ret == -1){ + perror("klogctl"); + } + } +#endif /* __linux__ */ + /* Lower privileges */ + errno = 0; + ret = seteuid(uid); + if(ret == -1){ + perror("seteuid"); + } + goto end; + } + strcpy(network.ifr_name, interface); + ret = ioctl(sd, SIOCGIFFLAGS, &network); + if(ret == -1){ + perror("ioctl SIOCGIFFLAGS"); +#ifdef __linux__ + if(restore_loglevel){ + ret = klogctl(7, NULL, 0); + if(ret == -1){ + perror("klogctl"); + } + } +#endif /* __linux__ */ + exitcode = EX_OSERR; + /* Lower privileges */ + errno = 0; + ret = seteuid(uid); + if(ret == -1){ + perror("seteuid"); + } + goto end; + } + if((network.ifr_flags & IFF_UP) == 0){ + network.ifr_flags |= IFF_UP; + take_down_interface = true; + ret = ioctl(sd, SIOCSIFFLAGS, &network); + if(ret == -1){ + take_down_interface = false; + perror("ioctl SIOCSIFFLAGS +IFF_UP"); + exitcode = EX_OSERR; +#ifdef __linux__ + if(restore_loglevel){ + ret = klogctl(7, NULL, 0); + if(ret == -1){ + perror("klogctl"); } } +#endif /* __linux__ */ + /* Lower privileges */ + errno = 0; + ret = seteuid(uid); + if(ret == -1){ + perror("seteuid"); + } + goto end; + } + } + /* sleep checking until interface is running */ + for(int i=0; i < delay * 4; i++){ + ret = ioctl(sd, SIOCGIFFLAGS, &network); + if(ret == -1){ + perror("ioctl SIOCGIFFLAGS"); + } else if(network.ifr_flags & IFF_RUNNING){ break; } - bool interface_was_up = interface_is_up(interface); - ret = bring_up_interface(interface, delay); - if(not interface_was_up){ - if(ret != 0){ - errno = ret; - perror_plus("Failed to bring up interface"); - } else { - ret_errno = argz_add(&interfaces_to_take_down, - &interfaces_to_take_down_size, - interface); - } - } - } - if(debug and (interfaces_to_take_down == NULL)){ - fprintf_plus(stderr, "No interfaces were brought up\n"); - } - } - - /* If we only got one interface, explicitly use only that one */ - if(argz_count(mc.interfaces, mc.interfaces_size) == 1){ - if(debug){ - fprintf_plus(stderr, "Using only interface \"%s\"\n", - mc.interfaces); - } - if_index = (AvahiIfIndex)if_nametoindex(mc.interfaces); + struct timespec sleeptime = { .tv_nsec = 250000000 }; + ret = nanosleep(&sleeptime, NULL); + if(ret == -1 and errno != EINTR){ + perror("nanosleep"); + } + } + if(not take_down_interface){ + /* We won't need the socket anymore */ + ret = (int)TEMP_FAILURE_RETRY(close(sd)); + if(ret == -1){ + perror("close"); + } + } +#ifdef __linux__ + if(restore_loglevel){ + /* Restores kernel loglevel to default */ + ret = klogctl(7, NULL, 0); + if(ret == -1){ + perror("klogctl"); + } + } +#endif /* __linux__ */ + /* Lower privileges */ + errno = 0; + if(take_down_interface){ + /* Lower privileges */ + ret = seteuid(uid); + if(ret == -1){ + perror("seteuid"); + } + } else { + /* Lower privileges permanently */ + ret = setuid(uid); + if(ret == -1){ + perror("setuid"); + } + } } if(quit_now){ goto end; } - ret = init_gnutls_global(pubkey, seckey, &mc); + ret = init_gnutls_global(pubkey, seckey); if(ret == -1){ - fprintf_plus(stderr, "init_gnutls_global failed\n"); + fprintf(stderr, "init_gnutls_global failed\n"); exitcode = EX_UNAVAILABLE; goto end; } else { @@ -2253,18 +1555,19 @@ goto end; } + tempdir_created = true; if(mkdtemp(tempdir) == NULL){ - perror_plus("mkdtemp"); + tempdir_created = false; + perror("mkdtemp"); goto end; } - tempdir_created = true; if(quit_now){ goto end; } - if(not init_gpgme(pubkey, seckey, tempdir, &mc)){ - fprintf_plus(stderr, "init_gpgme failed\n"); + if(not init_gpgme(pubkey, seckey, tempdir)){ + fprintf(stderr, "init_gpgme failed\n"); exitcode = EX_UNAVAILABLE; goto end; } else { @@ -2279,9 +1582,8 @@ /* Connect directly, do not use Zeroconf */ /* (Mainly meant for debugging) */ char *address = strrchr(connect_to, ':'); - if(address == NULL){ - fprintf_plus(stderr, "No colon in address\n"); + fprintf(stderr, "No colon in address\n"); exitcode = EX_USAGE; goto end; } @@ -2290,58 +1592,47 @@ goto end; } - in_port_t port; + uint16_t port; errno = 0; tmpmax = strtoimax(address+1, &tmp, 10); if(errno != 0 or tmp == address+1 or *tmp != '\0' - or tmpmax != (in_port_t)tmpmax){ - fprintf_plus(stderr, "Bad port number\n"); + or tmpmax != (uint16_t)tmpmax){ + fprintf(stderr, "Bad port number\n"); exitcode = EX_USAGE; goto end; } - + if(quit_now){ goto end; } - port = (in_port_t)tmpmax; + port = (uint16_t)tmpmax; *address = '\0'; + address = connect_to; /* Colon in address indicates IPv6 */ int af; - if(strchr(connect_to, ':') != NULL){ + if(strchr(address, ':') != NULL){ af = AF_INET6; - /* Accept [] around IPv6 address - see RFC 5952 */ - if(connect_to[0] == '[' and address[-1] == ']') - { - connect_to++; - address[-1] = '\0'; - } } else { af = AF_INET; } - address = connect_to; if(quit_now){ goto end; } - + while(not quit_now){ - ret = start_mandos_communication(address, port, if_index, af, - &mc); + ret = start_mandos_communication(address, port, if_index, af); if(quit_now or ret == 0){ break; } - if(debug){ - fprintf_plus(stderr, "Retrying in %d seconds\n", - (int)retry_interval); - } - sleep((unsigned int)retry_interval); - } - + sleep(15); + }; + if (not quit_now){ exitcode = EXIT_SUCCESS; } - + goto end; } @@ -2359,8 +1650,9 @@ config.publish_domain = 0; /* Allocate a new server */ - mc.server = avahi_server_new(avahi_simple_poll_get(simple_poll), - &config, NULL, NULL, &ret_errno); + mc.server = avahi_server_new(avahi_simple_poll_get + (mc.simple_poll), &config, NULL, + NULL, &error); /* Free the Avahi configuration data */ avahi_server_config_free(&config); @@ -2368,8 +1660,8 @@ /* Check if creating the Avahi server object succeeded */ if(mc.server == NULL){ - fprintf_plus(stderr, "Failed to create Avahi server: %s\n", - avahi_strerror(ret_errno)); + fprintf(stderr, "Failed to create Avahi server: %s\n", + avahi_strerror(error)); exitcode = EX_UNAVAILABLE; goto end; } @@ -2381,11 +1673,10 @@ /* Create the Avahi service browser */ sb = avahi_s_service_browser_new(mc.server, if_index, AVAHI_PROTO_UNSPEC, "_mandos._tcp", - NULL, 0, browse_callback, - (void *)&mc); + NULL, 0, browse_callback, NULL); if(sb == NULL){ - fprintf_plus(stderr, "Failed to create service browser: %s\n", - avahi_strerror(avahi_server_errno(mc.server))); + fprintf(stderr, "Failed to create service browser: %s\n", + avahi_strerror(avahi_server_errno(mc.server))); exitcode = EX_UNAVAILABLE; goto end; } @@ -2397,33 +1688,26 @@ /* Run the main loop */ if(debug){ - fprintf_plus(stderr, "Starting Avahi loop search\n"); - } - - ret = avahi_loop_with_timeout(simple_poll, - (int)(retry_interval * 1000), &mc); - if(debug){ - fprintf_plus(stderr, "avahi_loop_with_timeout exited %s\n", - (ret == 0) ? "successfully" : "with error"); - } + fprintf(stderr, "Starting Avahi loop search\n"); + } + + avahi_simple_poll_loop(mc.simple_poll); end: if(debug){ - fprintf_plus(stderr, "%s exiting\n", argv[0]); + fprintf(stderr, "%s exiting\n", argv[0]); } /* Cleanup things */ - free(mc.interfaces); - if(sb != NULL) avahi_s_service_browser_free(sb); if(mc.server != NULL) avahi_server_free(mc.server); - if(simple_poll != NULL) - avahi_simple_poll_free(simple_poll); + if(mc.simple_poll != NULL) + avahi_simple_poll_free(mc.simple_poll); if(gnutls_initialized){ gnutls_certificate_free_credentials(mc.cred); @@ -2435,82 +1719,79 @@ gpgme_release(mc.ctx); } - /* Cleans up the circular linked list of Mandos servers the client - has seen */ - if(mc.current_server != NULL){ - mc.current_server->prev->next = NULL; - while(mc.current_server != NULL){ - server *next = mc.current_server->next; - free(mc.current_server); - mc.current_server = next; + /* Take down the network interface */ + if(take_down_interface){ + /* Re-raise priviliges */ + errno = 0; + ret = seteuid(0); + if(ret == -1){ + perror("seteuid"); } - } - - /* Re-raise priviliges */ - { - raise_privileges(); - - /* Run network hooks */ - run_network_hooks("stop", interfaces_hooks != NULL ? - interfaces_hooks : "", delay); - - /* Take down the network interfaces which were brought up */ - { - char *interface = NULL; - while((interface=argz_next(interfaces_to_take_down, - interfaces_to_take_down_size, - interface))){ - ret_errno = take_down_interface(interface); - if(ret_errno != 0){ - errno = ret_errno; - perror_plus("Failed to take down interface"); + if(geteuid() == 0){ + ret = ioctl(sd, SIOCGIFFLAGS, &network); + if(ret == -1){ + perror("ioctl SIOCGIFFLAGS"); + } else if(network.ifr_flags & IFF_UP) { + network.ifr_flags &= ~(short)IFF_UP; /* clear flag */ + ret = ioctl(sd, SIOCSIFFLAGS, &network); + if(ret == -1){ + perror("ioctl SIOCSIFFLAGS -IFF_UP"); } } - if(debug and (interfaces_to_take_down == NULL)){ - fprintf_plus(stderr, "No interfaces needed to be taken" - " down\n"); + ret = (int)TEMP_FAILURE_RETRY(close(sd)); + if(ret == -1){ + perror("close"); + } + /* Lower privileges permanently */ + errno = 0; + ret = setuid(uid); + if(ret == -1){ + perror("setuid"); } } - - lower_privileges_permanently(); } - free(interfaces_to_take_down); - free(interfaces_hooks); - - /* Removes the GPGME temp directory and all files inside */ + /* Removes the temp directory used by GPGME */ if(tempdir_created){ - struct dirent **direntries = NULL; - struct dirent *direntry = NULL; - int numentries = scandir(tempdir, &direntries, notdotentries, - alphasort); - if (numentries > 0){ - for(int i = 0; i < numentries; i++){ - direntry = direntries[i]; + DIR *d; + struct dirent *direntry; + d = opendir(tempdir); + if(d == NULL){ + if(errno != ENOENT){ + perror("opendir"); + } + } else { + while(true){ + direntry = readdir(d); + if(direntry == NULL){ + break; + } + /* Skip "." and ".." */ + if(direntry->d_name[0] == '.' + and (direntry->d_name[1] == '\0' + or (direntry->d_name[1] == '.' + and direntry->d_name[2] == '\0'))){ + continue; + } char *fullname = NULL; ret = asprintf(&fullname, "%s/%s", tempdir, direntry->d_name); if(ret < 0){ - perror_plus("asprintf"); + perror("asprintf"); continue; } ret = remove(fullname); if(ret == -1){ - fprintf_plus(stderr, "remove(\"%s\"): %s\n", fullname, - strerror(errno)); + fprintf(stderr, "remove(\"%s\"): %s\n", fullname, + strerror(errno)); } free(fullname); } - } - - /* need to clean even if 0 because man page doesn't specify */ - free(direntries); - if (numentries == -1){ - perror_plus("scandir"); + closedir(d); } ret = rmdir(tempdir); if(ret == -1 and errno != ENOENT){ - perror_plus("rmdir"); + perror("rmdir"); } } @@ -2521,13 +1802,13 @@ &old_sigterm_action, NULL)); if(ret == -1){ - perror_plus("sigaction"); + perror("sigaction"); } do { ret = raise(signal_received); } while(ret != 0 and errno == EINTR); if(ret != 0){ - perror_plus("raise"); + perror("raise"); abort(); } TEMP_FAILURE_RETRY(pause()); === modified file 'plugins.d/mandos-client.xml' --- plugins.d/mandos-client.xml 2014-01-20 20:54:47 +0000 +++ plugins.d/mandos-client.xml 2010-09-26 18:32:58 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,22 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2008 2009 - 2012 - 2013 Teddy Hogeborn Björn Påhlsson @@ -65,13 +63,11 @@ >PORT - + - + NAME + @@ -101,15 +97,6 @@ - - - - - - - - @@ -140,33 +127,15 @@ communicates with mandos8 to get a password. In slightly more detail, this client program - 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 + brings up a network interface, uses the interface’s IPv6 + link-local address 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 are periodically retried. If no servers are found it - will wait indefinitely for new servers to appear. -
- - The network interfaces are selected like this: If any interfaces - are specified using the option, - those interface are used. Otherwise, - &COMMANDNAME; will use all interfaces that - are not loopback interfaces, are not point-to-point interfaces, - are capable of broadcasting and do not have the NOARP flag (see - netdevice - 7). (If the - option is used, point-to-point - interfaces and non-broadcast interfaces are accepted.) If any - used interfaces are not up and running, they are first taken up - (and later taken down again on program exit). - - - Before network interfaces are selected, all network - hooks are run; see . + or a TERM signal is received. If no servers are found, or after + all servers have been tried, it waits indefinitely for new + servers to appear. This program is not meant to be run directly; it is really meant @@ -219,51 +188,44 @@ assumed to separate the address from the port number. - Normally, Zeroconf would be used to locate Mandos servers, - in which case this option would only be used when testing - and debugging. + This option is normally only useful for testing and + debugging. + >NAME + NAME - Comma separated list of network interfaces that will be - brought up and scanned for Mandos servers to connect to. - The default is the empty string, which will automatically - use all appropriate interfaces. + Network interface that will be brought up and scanned for + Mandos servers to connect to. The default is the empty + string, which will automatically choose an appropriate + interface. - If the option is used, and - exactly one interface name is specified (except - none), this specifies - the interface to use to connect to the address given. + If the option is used, this + specifies the interface to use to connect to the address + given. Note that since this program will normally run in the initial RAM disk environment, the interface must be an interface which exists at that stage. Thus, the interface - can normally not be a pseudo-interface such as - br0 or tun0; such interfaces - will not exist until much later in the boot process, and - can not be used by this program, unless created by a - network hook — see . + can not be a pseudo-interface such as br0 + or tun0; such interfaces will not exist + until much later in the boot process, and can not be used + by this program. NAME can be the string - none; this will make - &COMMANDNAME; not bring up - any interfaces specified - after this string. This is not - recommended, and only meant for advanced users. + none; this will not use + any specific interface, and will not bring up an interface + on startup. This is not recommended, and only meant for + advanced users. @@ -321,7 +283,7 @@ >SECONDS - After bringing a network interface up, the program waits + After bringing the network interface up, the program waits for the interface to arrive in a running state before proceeding. During this time, the kernel log level will be lowered to reduce clutter on the system @@ -331,31 +293,6 @@ - - - - - - All Mandos servers are tried repeatedly until a password - is received. This value specifies, in seconds, how long - between each successive try for the same - server. The default is 10 seconds. - - - - - - - - - Network hook directory. The default directory is - /lib/mandos/network-hooks.d. - - - @@ -422,10 +359,8 @@ plugin-runner 8mandos
) is used to run both this program and others in in parallel, - one of which ( - password-prompt - 8mandos) will prompt for - passwords on the system console. + one of which will prompt for passwords on + the system console.
@@ -436,9 +371,9 @@ server could be found and the password received from it could be successfully decrypted and output on standard output. The program will exit with a non-zero exit status only if a critical - error occurs. Otherwise, it will forever connect to any - discovered Mandos servers, trying to - get a decryptable password and print it. + error occurs. Otherwise, it will forever connect to new + Mandos servers as they appear, trying + to get a decryptable password and print it.
@@ -452,175 +387,6 @@ - - NETWORK HOOKS - - If a network interface like a bridge or tunnel is required to - find a Mandos server, this requires the interface to be up and - running before &COMMANDNAME; starts looking - for Mandos servers. This can be accomplished by creating a - network hook program, and placing it in a special - directory. - - - Before the network is used (and again before program exit), any - runnable programs found in the network hook directory are run - with the argument start or - stop. This should bring up or - down, respectively, any network interface which - &COMMANDNAME; should use. - - - REQUIREMENTS - - A network hook must be an executable file, and its name must - consist entirely of upper and lower case letters, digits, - underscores, periods, and hyphens. - - - A network hook will receive one argument, which can be one of - the following: - - - - start - - - This should make the network hook create (if necessary) - and bring up a network interface. - - - - - stop - - - This should make the network hook take down a network - interface, and delete it if it did not exist previously. - - - - - files - - - This should make the network hook print, one - file per line, all the files needed for it to - run. (These files will be copied into the initial RAM - filesystem.) Typical use is for a network hook which is - a shell script to print its needed binaries. - - - It is not necessary to print any non-executable files - already in the network hook directory, these will be - copied implicitly if they otherwise satisfy the name - requirements. - - - - - modules - - - This should make the network hook print, on - separate lines, all the kernel modules needed - for it to run. (These modules will be copied into the - initial RAM filesystem.) For instance, a tunnel - interface needs the - tun module. - - - - - - The network hook will be provided with a number of environment - variables: - - - - MANDOSNETHOOKDIR - - - The network hook directory, specified to - &COMMANDNAME; by the - option. Note: this - should always be used by the - network hook to refer to itself or any files in the hook - directory it may require. - - - - - DEVICE - - - The network interfaces, as specified to - &COMMANDNAME; by the - option, combined to one - string and separated by commas. If this is set, and - does not contain the interface a hook will bring up, - there is no reason for a hook to continue. - - - - - MODE - - - This will be the same as the first argument; - i.e. start, - stop, - files, or - modules. - - - - - VERBOSITY - - - This will be the 1 if - the option is passed to - &COMMANDNAME;, otherwise - 0. - - - - - DELAY - - - This will be the same as the - option passed to &COMMANDNAME;. Is - only set if MODE is - start or - stop. - - - - - CONNECT - - - This will be the same as the - option passed to &COMMANDNAME;. Is - only set if is passed and - MODE is - start or - stop. - - - - - - A hook may not read from standard input, and should be - restrictive in printing to standard output or standard error - unless VERBOSITY is - 1. - - - - FILES @@ -638,17 +404,6 @@ - - /lib/mandos/network-hooks.d - - - Directory where network hooks are located. Change this - with the option. See - . - - - @@ -668,8 +423,8 @@ - Normal invocation needs no options, if the network interfaces - can be automatically determined: + Normal invocation needs no options, if the network interface + is eth0: &COMMANDNAME; @@ -677,8 +432,8 @@ - Search for Mandos servers (and connect to them) using one - specific interface: + Search for Mandos servers (and connect to them) using another + interface: @@ -763,8 +518,6 @@ SEE ALSO - intro - 8mandos, cryptsetup 8, crypttab @@ -848,7 +601,7 @@ This client uses IPv6 link-local addresses, which are immediately usable since a link-local addresses is - automatically assigned to a network interface when it + automatically assigned to a network interfaces when it is brought up. === modified file 'plugins.d/password-prompt.c' --- plugins.d/password-prompt.c 2013-10-20 15:25:09 +0000 +++ plugins.d/password-prompt.c 2011-03-08 11:08:35 +0000 @@ -2,8 +2,8 @@ /* * Password-prompt - Read a password from the terminal and print it * - * Copyright © 2008-2013 Teddy Hogeborn - * Copyright © 2008-2013 Björn Påhlsson + * Copyright © 2008-2010 Teddy Hogeborn + * Copyright © 2008-2010 Björn Påhlsson * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -19,7 +19,7 @@ * along with this program. If not, see * . * - * Contact the authors at . + * Contact the authors at . */ #define _GNU_SOURCE /* getline(), asprintf() */ @@ -41,8 +41,8 @@ getenv(), free() */ #include /* scandir(), alphasort() */ #include /* fprintf(), stderr, getline(), - stdin, feof(), fputc(), vfprintf(), - vasprintf() */ + stdin, feof(), fputc() + */ #include /* errno, EBADF, ENOTTY, EINVAL, EFAULT, EFBIG, EIO, ENOSPC, EINTR */ @@ -51,8 +51,7 @@ #include /* bool, false, true */ #include /* strtoumax() */ #include /* struct stat, lstat(), open() */ -#include /* strlen, rindex, memcmp, strerror() - */ +#include /* strlen, rindex, memcmp */ #include /* struct argp_option, struct argp_state, struct argp, argp_parse(), error_t, @@ -61,50 +60,16 @@ #include /* EX_SOFTWARE, EX_OSERR, EX_UNAVAILABLE, EX_IOERR, EX_OK */ #include /* open() */ -#include /* va_list, va_start(), ... */ volatile sig_atomic_t quit_now = 0; int signal_received; bool debug = false; const char *argp_program_version = "password-prompt " VERSION; -const char *argp_program_bug_address = ""; +const char *argp_program_bug_address = ""; /* Needed for conflict resolution */ const char plymouth_name[] = "plymouthd"; -__attribute__((format (gnu_printf, 2, 3), nonnull(1))) -int fprintf_plus(FILE *stream, const char *format, ...){ - va_list ap; - va_start (ap, format); - - TEMP_FAILURE_RETRY(fprintf(stream, "Mandos plugin %s: ", - program_invocation_short_name)); - return (int)TEMP_FAILURE_RETRY(vfprintf(stream, format, ap)); -} - -/* Function to use when printing errors */ -__attribute__((format (gnu_printf, 3, 4))) -void error_plus(int status, int errnum, const char *formatstring, - ...){ - va_list ap; - char *text; - int ret; - - va_start(ap, formatstring); - ret = vasprintf(&text, formatstring, ap); - if (ret == -1){ - fprintf(stderr, "Mandos plugin %s: ", - program_invocation_short_name); - vfprintf(stderr, formatstring, ap); - fprintf(stderr, ": %s\n", strerror(errnum)); - error(status, errno, "vasprintf while printing error"); - return; - } - fprintf(stderr, "Mandos plugin "); - error(status, errnum, "%s", text); - free(text); -} - static void termination_handler(int signum){ if(quit_now){ return; @@ -119,18 +84,17 @@ from the terminal. Password-prompt will exit if it detects plymouth since plymouth performs the same functionality. */ - __attribute__((nonnull)) int is_plymouth(const struct dirent *proc_entry){ int ret; int cl_fd; { - uintmax_t proc_id; + uintmax_t maxvalue; char *tmp; errno = 0; - proc_id = strtoumax(proc_entry->d_name, &tmp, 10); + maxvalue = strtoumax(proc_entry->d_name, &tmp, 10); if(errno != 0 or *tmp != '\0' - or proc_id != (uintmax_t)((pid_t)proc_id)){ + or maxvalue != (uintmax_t)((pid_t)maxvalue)){ return 0; } } @@ -139,7 +103,7 @@ ret = asprintf(&cmdline_filename, "/proc/%s/cmdline", proc_entry->d_name); if(ret == -1){ - error_plus(0, errno, "asprintf"); + error(0, errno, "asprintf"); return 0; } @@ -147,9 +111,7 @@ cl_fd = open(cmdline_filename, O_RDONLY); free(cmdline_filename); if(cl_fd == -1){ - if(errno != ENOENT){ - error_plus(0, errno, "open"); - } + error(0, errno, "open"); return 0; } @@ -165,7 +127,7 @@ if(cmdline_len + blocksize + 1 > cmdline_allocated){ tmp = realloc(cmdline, cmdline_allocated + blocksize + 1); if(tmp == NULL){ - error_plus(0, errno, "realloc"); + error(0, errno, "realloc"); free(cmdline); close(cl_fd); return 0; @@ -178,7 +140,7 @@ sret = read(cl_fd, cmdline + cmdline_len, cmdline_allocated - cmdline_len); if(sret == -1){ - error_plus(0, errno, "read"); + error(0, errno, "read"); free(cmdline); close(cl_fd); return 0; @@ -187,7 +149,7 @@ } while(sret != 0); ret = close(cl_fd); if(ret == -1){ - error_plus(0, errno, "close"); + error(0, errno, "close"); free(cmdline); return 0; } @@ -219,13 +181,12 @@ return 1; } - struct dirent **direntries = NULL; + struct dirent **direntries; int ret; ret = scandir("/proc", &direntries, is_plymouth, alphasort); if (ret == -1){ - error_plus(1, errno, "scandir"); + error(1, errno, "scandir"); } - free(direntries); return ret > 0; } @@ -260,7 +221,6 @@ { .name = NULL } }; - __attribute__((nonnull(3))) error_t parse_opt (int key, char *arg, struct argp_state *state){ errno = 0; switch (key){ @@ -302,7 +262,7 @@ case ENOMEM: default: errno = ret; - error_plus(0, errno, "argp_parse"); + error(0, errno, "argp_parse"); return EX_OSERR; case EINVAL: return EX_USAGE; @@ -326,7 +286,7 @@ if(tcgetattr(STDIN_FILENO, &t_old) != 0){ int e = errno; - error_plus(0, errno, "tcgetattr"); + error(0, errno, "tcgetattr"); switch(e){ case EBADF: case ENOTTY: @@ -339,17 +299,17 @@ sigemptyset(&new_action.sa_mask); ret = sigaddset(&new_action.sa_mask, SIGINT); if(ret == -1){ - error_plus(0, errno, "sigaddset"); + error(0, errno, "sigaddset"); return EX_OSERR; } ret = sigaddset(&new_action.sa_mask, SIGHUP); if(ret == -1){ - error_plus(0, errno, "sigaddset"); + error(0, errno, "sigaddset"); return EX_OSERR; } ret = sigaddset(&new_action.sa_mask, SIGTERM); if(ret == -1){ - error_plus(0, errno, "sigaddset"); + error(0, errno, "sigaddset"); return EX_OSERR; } /* Need to check if the handler is SIG_IGN before handling: @@ -358,37 +318,37 @@ */ ret = sigaction(SIGINT, NULL, &old_action); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); return EX_OSERR; } if(old_action.sa_handler != SIG_IGN){ ret = sigaction(SIGINT, &new_action, NULL); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); return EX_OSERR; } } ret = sigaction(SIGHUP, NULL, &old_action); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); return EX_OSERR; } if(old_action.sa_handler != SIG_IGN){ ret = sigaction(SIGHUP, &new_action, NULL); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); return EX_OSERR; } } ret = sigaction(SIGTERM, NULL, &old_action); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); return EX_OSERR; } if(old_action.sa_handler != SIG_IGN){ ret = sigaction(SIGTERM, &new_action, NULL); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); return EX_OSERR; } } @@ -402,7 +362,7 @@ t_new.c_lflag &= ~(tcflag_t)ECHO; if(tcsetattr(STDIN_FILENO, TCSAFLUSH, &t_new) != 0){ int e = errno; - error_plus(0, errno, "tcsetattr-echo"); + error(0, errno, "tcsetattr-echo"); switch(e){ case EBADF: case ENOTTY: @@ -472,7 +432,7 @@ sret = write(STDOUT_FILENO, buffer + written, n - written); if(sret < 0){ int e = errno; - error_plus(0, errno, "write"); + error(0, errno, "write"); switch(e){ case EBADF: case EFAULT: @@ -494,7 +454,7 @@ sret = close(STDOUT_FILENO); if(sret == -1){ int e = errno; - error_plus(0, errno, "close"); + error(0, errno, "close"); switch(e){ case EBADF: status = EX_OSFILE; @@ -510,11 +470,10 @@ if(sret < 0){ int e = errno; if(errno != EINTR and not feof(stdin)){ - error_plus(0, errno, "getline"); + error(0, errno, "getline"); switch(e){ case EBADF: status = EX_UNAVAILABLE; - break; case EIO: case EINVAL: default: @@ -540,7 +499,7 @@ fprintf(stderr, "Restoring terminal attributes\n"); } if(tcsetattr(STDIN_FILENO, TCSAFLUSH, &t_old) != 0){ - error_plus(0, errno, "tcsetattr+echo"); + error(0, errno, "tcsetattr+echo"); } if(quit_now){ @@ -548,7 +507,7 @@ old_action.sa_handler = SIG_DFL; ret = sigaction(signal_received, &old_action, NULL); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); } raise(signal_received); } === modified file 'plugins.d/password-prompt.xml' --- plugins.d/password-prompt.xml 2011-12-31 23:05:34 +0000 +++ plugins.d/password-prompt.xml 2009-10-30 16:23:43 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,22 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2008 2009 - 2011 - 2012 Teddy Hogeborn Björn Påhlsson @@ -294,8 +292,6 @@ SEE ALSO - intro - 8mandos crypttab 5 mandos-client === modified file 'plugins.d/plymouth.c' --- plugins.d/plymouth.c 2013-10-20 15:25:09 +0000 +++ plugins.d/plymouth.c 2011-02-27 17:26:35 +0000 @@ -2,8 +2,8 @@ /* * Plymouth - Read a password from Plymouth and output it * - * Copyright © 2010-2013 Teddy Hogeborn - * Copyright © 2010-2013 Björn Påhlsson + * Copyright © 2010-2011 Teddy Hogeborn + * Copyright © 2010-2011 Björn Påhlsson * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -19,7 +19,7 @@ * along with this program. If not, see * . * - * Contact the authors at . + * Contact the authors at . */ #define _GNU_SOURCE /* asprintf(), TEMP_FAILURE_RETRY() */ @@ -36,8 +36,7 @@ #include /* NULL */ #include /* strchr(), memcmp() */ #include /* asprintf(), perror(), fopen(), - fscanf(), vasprintf(), fprintf(), - vfprintf() */ + fscanf() */ #include /* close(), readlink(), read(), fork(), setsid(), chdir(), dup2(), STDERR_FILENO, execv(), access() */ @@ -51,20 +50,17 @@ #include /* error() */ #include /* TEMP_FAILURE_RETRY */ #include /* argz_count(), argz_extract() */ -#include /* va_list, va_start(), ... */ sig_atomic_t interrupted_by_signal = 0; - -/* Used by Ubuntu 11.04 (Natty Narwahl) */ -const char plymouth_old_pid[] = "/dev/.initramfs/plymouth.pid"; -/* Used by Ubuntu 11.10 (Oneiric Ocelot) */ -const char plymouth_pid[] = "/run/initramfs/plymouth.pid"; - +const char plymouth_pid[] = "/dev/.initramfs/plymouth.pid"; const char plymouth_path[] = "/bin/plymouth"; const char plymouthd_path[] = "/sbin/plymouthd"; const char *plymouthd_default_argv[] = {"/sbin/plymouthd", "--mode=boot", "--attach-to-session", + "--pid-file=" + "/dev/.initramfs/" + "plymouth.pid", NULL }; static void termination_handler(__attribute__((unused))int signum){ @@ -74,30 +70,6 @@ interrupted_by_signal = 1; } -/* Function to use when printing errors */ -__attribute__((format (gnu_printf, 3, 4))) -void error_plus(int status, int errnum, const char *formatstring, - ...){ - va_list ap; - char *text; - int ret; - - va_start(ap, formatstring); - ret = vasprintf(&text, formatstring, ap); - if (ret == -1){ - fprintf(stderr, "Mandos plugin %s: ", - program_invocation_short_name); - vfprintf(stderr, formatstring, ap); - fprintf(stderr, ": "); - fprintf(stderr, "%s\n", strerror(errnum)); - error(status, errno, "vasprintf while printing error"); - return; - } - fprintf(stderr, "Mandos plugin "); - error(status, errnum, "%s", text); - free(text); -} - /* Create prompt string */ char *makeprompt(void){ int ret = 0; @@ -137,33 +109,32 @@ bool become_a_daemon(void){ int ret = setuid(geteuid()); if(ret == -1){ - error_plus(0, errno, "setuid"); + error(0, errno, "setuid"); } setsid(); ret = chdir("/"); if(ret == -1){ - error_plus(0, errno, "chdir"); + error(0, errno, "chdir"); return false; } ret = dup2(STDERR_FILENO, STDOUT_FILENO); /* replace our stdout */ if(ret == -1){ - error_plus(0, errno, "dup2"); + error(0, errno, "dup2"); return false; } return true; } -__attribute__((nonnull (2, 3))) bool exec_and_wait(pid_t *pid_return, const char *path, - const char * const *argv, bool interruptable, + const char **argv, bool interruptable, bool daemonize){ int status; int ret; pid_t pid; pid = fork(); if(pid == -1){ - error_plus(0, errno, "fork"); + error(0, errno, "fork"); return false; } if(pid == 0){ @@ -180,7 +151,7 @@ for (; argv[i]!=NULL; i++){ tmp = realloc(new_argv, sizeof(const char *) * ((size_t)i + 1)); if (tmp == NULL){ - error_plus(0, errno, "realloc"); + error(0, errno, "realloc"); free(new_argv); _exit(EX_OSERR); } @@ -190,7 +161,7 @@ new_argv[i] = NULL; execv(path, (char *const *)new_argv); - error_plus(0, errno, "execv"); + error(0, errno, "execv"); _exit(EXIT_FAILURE); } if(pid_return != NULL){ @@ -205,7 +176,7 @@ return false; } if(ret == -1){ - error_plus(0, errno, "waitpid"); + error(0, errno, "waitpid"); return false; } if(WIFEXITED(status) and (WEXITSTATUS(status) == 0)){ @@ -214,17 +185,16 @@ return false; } -__attribute__((nonnull)) int is_plymouth(const struct dirent *proc_entry){ int ret; { - uintmax_t proc_id; + uintmax_t maxvalue; char *tmp; errno = 0; - proc_id = strtoumax(proc_entry->d_name, &tmp, 10); + maxvalue = strtoumax(proc_entry->d_name, &tmp, 10); if(errno != 0 or *tmp != '\0' - or proc_id != (uintmax_t)((pid_t)proc_id)){ + or maxvalue != (uintmax_t)((pid_t)maxvalue)){ return 0; } } @@ -232,7 +202,7 @@ char *exe_link; ret = asprintf(&exe_link, "/proc/%s/exe", proc_entry->d_name); if(ret == -1){ - error_plus(0, errno, "asprintf"); + error(0, errno, "asprintf"); return 0; } @@ -241,7 +211,7 @@ if(ret == -1){ free(exe_link); if(errno != ENOENT){ - error_plus(0, errno, "lstat"); + error(0, errno, "lstat"); } return 0; } @@ -265,54 +235,38 @@ pid_t get_pid(void){ int ret; - uintmax_t proc_id = 0; FILE *pidfile = fopen(plymouth_pid, "r"); - /* Try the new pid file location */ + uintmax_t maxvalue = 0; if(pidfile != NULL){ - ret = fscanf(pidfile, "%" SCNuMAX, &proc_id); + ret = fscanf(pidfile, "%" SCNuMAX, &maxvalue); if(ret != 1){ - proc_id = 0; + maxvalue = 0; } fclose(pidfile); } - /* Try the old pid file location */ - if(proc_id == 0){ - pidfile = fopen(plymouth_pid, "r"); - if(pidfile != NULL){ - ret = fscanf(pidfile, "%" SCNuMAX, &proc_id); - if(ret != 1){ - proc_id = 0; - } - fclose(pidfile); - } - } - /* Look for a plymouth process */ - if(proc_id == 0){ - struct dirent **direntries = NULL; + if(maxvalue == 0){ + struct dirent **direntries; ret = scandir("/proc", &direntries, is_plymouth, alphasort); if (ret == -1){ - error_plus(0, errno, "scandir"); + error(0, errno, "scandir"); } if (ret > 0){ - ret = sscanf(direntries[0]->d_name, "%" SCNuMAX, &proc_id); + ret = sscanf(direntries[0]->d_name, "%" SCNuMAX, &maxvalue); if (ret < 0){ - error_plus(0, errno, "sscanf"); + error(0, errno, "sscanf"); } } - /* scandir might preallocate for this variable (man page unclear). - even if ret == 0, therefore we need to free it. */ - free(direntries); } pid_t pid; - pid = (pid_t)proc_id; - if((uintmax_t)pid == proc_id){ + pid = (pid_t)maxvalue; + if((uintmax_t)pid == maxvalue){ return pid; } return 0; } -const char * const * getargv(pid_t pid){ +const char **getargv(pid_t pid){ int cl_fd; char *cmdline_filename; ssize_t sret; @@ -321,7 +275,7 @@ ret = asprintf(&cmdline_filename, "/proc/%" PRIuMAX "/cmdline", (uintmax_t)pid); if(ret == -1){ - error_plus(0, errno, "asprintf"); + error(0, errno, "asprintf"); return NULL; } @@ -329,7 +283,7 @@ cl_fd = open(cmdline_filename, O_RDONLY); free(cmdline_filename); if(cl_fd == -1){ - error_plus(0, errno, "open"); + error(0, errno, "open"); return NULL; } @@ -343,7 +297,7 @@ if(cmdline_len + blocksize > cmdline_allocated){ tmp = realloc(cmdline, cmdline_allocated + blocksize); if(tmp == NULL){ - error_plus(0, errno, "realloc"); + error(0, errno, "realloc"); free(cmdline); close(cl_fd); return NULL; @@ -356,7 +310,7 @@ sret = read(cl_fd, cmdline + cmdline_len, cmdline_allocated - cmdline_len); if(sret == -1){ - error_plus(0, errno, "read"); + error(0, errno, "read"); free(cmdline); close(cl_fd); return NULL; @@ -365,7 +319,7 @@ } while(sret != 0); ret = close(cl_fd); if(ret == -1){ - error_plus(0, errno, "close"); + error(0, errno, "close"); free(cmdline); return NULL; } @@ -374,12 +328,12 @@ char **argv = malloc((argz_count(cmdline, cmdline_len) + 1) * sizeof(char *)); /* Get number of args */ if(argv == NULL){ - error_plus(0, errno, "argv = malloc()"); + error(0, errno, "argv = malloc()"); free(cmdline); return NULL; } argz_extract(cmdline, cmdline_len, argv); /* Create argv */ - return (const char * const *)argv; + return (const char **)argv; } int main(__attribute__((unused))int argc, @@ -407,16 +361,16 @@ *sig != 0; sig++){ ret = sigaddset(&new_action.sa_mask, *sig); if(ret == -1){ - error_plus(EX_OSERR, errno, "sigaddset"); + error(EX_OSERR, errno, "sigaddset"); } ret = sigaction(*sig, NULL, &old_action); if(ret == -1){ - error_plus(EX_OSERR, errno, "sigaction"); + error(EX_OSERR, errno, "sigaction"); } if(old_action.sa_handler != SIG_IGN){ ret = sigaction(*sig, &new_action, NULL); if(ret == -1){ - error_plus(EX_OSERR, errno, "sigaction"); + error(EX_OSERR, errno, "sigaction"); } } } @@ -441,7 +395,7 @@ ret = asprintf(&prompt_arg, "--prompt=%s", prompt); free(prompt); if(ret == -1){ - error_plus(EX_OSERR, errno, "asprintf"); + error(EX_OSERR, errno, "asprintf"); } /* plymouth ask-for-password --prompt="$prompt" */ @@ -460,10 +414,10 @@ } kill_and_wait(plymouth_command_pid); - const char * const *plymouthd_argv; + const char **plymouthd_argv; pid_t pid = get_pid(); if(pid == 0){ - error_plus(0, 0, "plymouthd pid not found"); + error(0, 0, "plymouthd pid not found"); plymouthd_argv = plymouthd_default_argv; } else { plymouthd_argv = getargv(pid); === modified file 'plugins.d/plymouth.xml' --- plugins.d/plymouth.xml 2011-12-31 23:05:34 +0000 +++ plugins.d/plymouth.xml 2011-02-27 17:26:35 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,21 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2010 2011 - 2012 Teddy Hogeborn Björn Påhlsson @@ -162,7 +161,7 @@ - /proc + /proc To find the running SEE ALSO - intro - 8mandos, crypttab 5, plugin-runner === modified file 'plugins.d/splashy.c' --- plugins.d/splashy.c 2011-12-31 23:05:34 +0000 +++ plugins.d/splashy.c 2011-02-27 17:26:35 +0000 @@ -2,8 +2,8 @@ /* * Splashy - Read a password from splashy and output it * - * Copyright © 2008-2012 Teddy Hogeborn - * Copyright © 2008-2012 Björn Påhlsson + * Copyright © 2008-2011 Teddy Hogeborn + * Copyright © 2008-2011 Björn Påhlsson * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -19,7 +19,7 @@ * along with this program. If not, see * . * - * Contact the authors at . + * Contact the authors at . */ #define _GNU_SOURCE /* TEMP_FAILURE_RETRY(), asprintf() */ @@ -29,8 +29,7 @@ SIG_IGN, kill(), SIGKILL */ #include /* NULL */ #include /* getenv() */ -#include /* asprintf(), vasprintf(), vprintf(), - fprintf() */ +#include /* asprintf() */ #include /* EXIT_FAILURE, free(), EXIT_SUCCESS */ #include /* pid_t, DIR, struct dirent, @@ -43,7 +42,7 @@ sleep(), dup2() STDERR_FILENO, STDOUT_FILENO, _exit(), pause() */ -#include /* memcmp(), strerror() */ +#include /* memcmp() */ #include /* errno, EACCES, ENOTDIR, ELOOP, ENOENT, ENAMETOOLONG, EMFILE, ENFILE, ENOMEM, ENOEXEC, EINVAL, @@ -55,36 +54,10 @@ WEXITSTATUS() */ #include /* EX_OSERR, EX_OSFILE, EX_UNAVAILABLE */ -#include /* va_list, va_start(), ... */ sig_atomic_t interrupted_by_signal = 0; int signal_received; -/* Function to use when printing errors */ -__attribute__((format (gnu_printf, 3, 4))) -void error_plus(int status, int errnum, const char *formatstring, - ...){ - va_list ap; - char *text; - int ret; - - va_start(ap, formatstring); - ret = vasprintf(&text, formatstring, ap); - if (ret == -1){ - fprintf(stderr, "Mandos plugin %s: ", - program_invocation_short_name); - vfprintf(stderr, formatstring, ap); - fprintf(stderr, ": "); - fprintf(stderr, "%s\n", strerror(errnum)); - error(status, errno, "vasprintf while printing error"); - return; - } - fprintf(stderr, "Mandos plugin "); - error(status, errnum, "%s", text); - free(text); -} - - static void termination_handler(int signum){ if(interrupted_by_signal){ return; @@ -137,7 +110,7 @@ proc_dir = opendir("/proc"); if(proc_dir == NULL){ int e = errno; - error_plus(0, errno, "opendir"); + error(0, errno, "opendir"); switch(e){ case EACCES: case ENOTDIR: @@ -179,7 +152,7 @@ char *exe_link; ret = asprintf(&exe_link, "/proc/%s/exe", proc_ent->d_name); if(ret == -1){ - error_plus(0, errno, "asprintf"); + error(0, errno, "asprintf"); exitstatus = EX_OSERR; goto failure; } @@ -193,7 +166,7 @@ continue; } int e = errno; - error_plus(0, errno, "lstat"); + error(0, errno, "lstat"); free(exe_link); switch(e){ case EACCES: @@ -241,60 +214,60 @@ sigemptyset(&new_action.sa_mask); ret = sigaddset(&new_action.sa_mask, SIGINT); if(ret == -1){ - error_plus(0, errno, "sigaddset"); + error(0, errno, "sigaddset"); exitstatus = EX_OSERR; goto failure; } ret = sigaddset(&new_action.sa_mask, SIGHUP); if(ret == -1){ - error_plus(0, errno, "sigaddset"); + error(0, errno, "sigaddset"); exitstatus = EX_OSERR; goto failure; } ret = sigaddset(&new_action.sa_mask, SIGTERM); if(ret == -1){ - error_plus(0, errno, "sigaddset"); + error(0, errno, "sigaddset"); exitstatus = EX_OSERR; goto failure; } ret = sigaction(SIGINT, NULL, &old_action); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); exitstatus = EX_OSERR; goto failure; } if(old_action.sa_handler != SIG_IGN){ ret = sigaction(SIGINT, &new_action, NULL); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); exitstatus = EX_OSERR; goto failure; } } ret = sigaction(SIGHUP, NULL, &old_action); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); exitstatus = EX_OSERR; goto failure; } if(old_action.sa_handler != SIG_IGN){ ret = sigaction(SIGHUP, &new_action, NULL); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); exitstatus = EX_OSERR; goto failure; } } ret = sigaction(SIGTERM, NULL, &old_action); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); exitstatus = EX_OSERR; goto failure; } if(old_action.sa_handler != SIG_IGN){ ret = sigaction(SIGTERM, &new_action, NULL); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); exitstatus = EX_OSERR; goto failure; } @@ -311,7 +284,7 @@ goto failure; } if(splashy_command_pid == -1){ - error_plus(0, errno, "fork"); + error(0, errno, "fork"); exitstatus = EX_OSERR; goto failure; } @@ -321,7 +294,7 @@ const char splashy_command[] = "/sbin/splashy_update"; execl(splashy_command, splashy_command, prompt, (char *)NULL); int e = errno; - error_plus(0, errno, "execl"); + error(0, errno, "execl"); switch(e){ case EACCES: case ENOENT: @@ -371,7 +344,7 @@ goto failure; } if(ret == -1){ - error_plus(0, errno, "waitpid"); + error(0, errno, "waitpid"); if(errno == ECHILD){ splashy_command_pid = 0; } @@ -409,27 +382,27 @@ the real user ID (_mandos) */ ret = setuid(geteuid()); if(ret == -1){ - error_plus(0, errno, "setuid"); + error(0, errno, "setuid"); } setsid(); ret = chdir("/"); if(ret == -1){ - error_plus(0, errno, "chdir"); + error(0, errno, "chdir"); } /* if(fork() != 0){ */ /* _exit(EXIT_SUCCESS); */ /* } */ ret = dup2(STDERR_FILENO, STDOUT_FILENO); /* replace stdout */ if(ret == -1){ - error_plus(0, errno, "dup2"); + error(0, errno, "dup2"); _exit(EX_OSERR); } execl("/sbin/splashy", "/sbin/splashy", "boot", (char *)NULL); { int e = errno; - error_plus(0, errno, "execl"); + error(0, errno, "execl"); switch(e){ case EACCES: case ENOENT: @@ -455,13 +428,13 @@ ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received, &signal_action, NULL)); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); } do { ret = raise(signal_received); } while(ret != 0 and errno == EINTR); if(ret != 0){ - error_plus(0, errno, "raise"); + error(0, errno, "raise"); abort(); } TEMP_FAILURE_RETRY(pause()); === modified file 'plugins.d/splashy.xml' --- plugins.d/splashy.xml 2011-12-31 23:05:34 +0000 +++ plugins.d/splashy.xml 2009-01-04 21:54:55 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,21 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2008 2009 - 2012 Teddy Hogeborn Björn Påhlsson @@ -264,8 +263,6 @@ SEE ALSO - intro - 8mandos, crypttab 5, plugin-runner === modified file 'plugins.d/usplash.c' --- plugins.d/usplash.c 2011-12-31 23:05:34 +0000 +++ plugins.d/usplash.c 2011-02-27 17:26:35 +0000 @@ -2,8 +2,8 @@ /* * Usplash - Read a password from usplash and output it * - * Copyright © 2008-2012 Teddy Hogeborn - * Copyright © 2008-2012 Björn Påhlsson + * Copyright © 2008-2011 Teddy Hogeborn + * Copyright © 2008-2011 Björn Påhlsson * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as @@ -19,7 +19,7 @@ * along with this program. If not, see * . * - * Contact the authors at . + * Contact the authors at . */ #define _GNU_SOURCE /* asprintf(), TEMP_FAILURE_RETRY() */ @@ -35,9 +35,8 @@ #include /* size_t, ssize_t, pid_t, DIR, struct dirent */ #include /* NULL */ -#include /* strlen(), memcmp(), strerror() */ -#include /* asprintf(), vasprintf(), vprintf(), - fprintf() */ +#include /* strlen(), memcmp() */ +#include /* asprintf()*/ #include /* close(), write(), readlink(), read(), STDOUT_FILENO, sleep(), fork(), setuid(), geteuid(), @@ -51,36 +50,11 @@ #include /* struct stat, lstat(), S_ISLNK */ #include /* EX_OSERR, EX_UNAVAILABLE */ #include /* argz_count(), argz_extract() */ -#include /* va_list, va_start(), ... */ sig_atomic_t interrupted_by_signal = 0; int signal_received; const char usplash_name[] = "/sbin/usplash"; -/* Function to use when printing errors */ -__attribute__((format (gnu_printf, 3, 4))) -void error_plus(int status, int errnum, const char *formatstring, - ...){ - va_list ap; - char *text; - int ret; - - va_start(ap, formatstring); - ret = vasprintf(&text, formatstring, ap); - if (ret == -1){ - fprintf(stderr, "Mandos plugin %s: ", - program_invocation_short_name); - vfprintf(stderr, formatstring, ap); - fprintf(stderr, ": "); - fprintf(stderr, "%s\n", strerror(errnum)); - error(status, errno, "vasprintf while printing error"); - return; - } - fprintf(stderr, "Mandos plugin "); - error(status, errnum, "%s", text); - free(text); -} - static void termination_handler(int signum){ if(interrupted_by_signal){ return; @@ -181,7 +155,7 @@ size_t cmdline_len = 0; DIR *proc_dir = opendir("/proc"); if(proc_dir == NULL){ - error_plus(0, errno, "opendir"); + error(0, errno, "opendir"); return -1; } errno = 0; @@ -209,7 +183,7 @@ char *exe_link; ret = asprintf(&exe_link, "/proc/%s/exe", proc_ent->d_name); if(ret == -1){ - error_plus(0, errno, "asprintf"); + error(0, errno, "asprintf"); goto fail_find_usplash; } @@ -221,7 +195,7 @@ free(exe_link); continue; } - error_plus(0, errno, "lstat"); + error(0, errno, "lstat"); free(exe_link); goto fail_find_usplash; } @@ -252,13 +226,13 @@ ret = asprintf(&cmdline_filename, "/proc/%s/cmdline", proc_ent->d_name); if(ret == -1){ - error_plus(0, errno, "asprintf"); + error(0, errno, "asprintf"); goto fail_find_usplash; } cl_fd = open(cmdline_filename, O_RDONLY); free(cmdline_filename); if(cl_fd == -1){ - error_plus(0, errno, "open"); + error(0, errno, "open"); goto fail_find_usplash; } } @@ -270,7 +244,7 @@ if(cmdline_len + blocksize > cmdline_allocated){ tmp = realloc(cmdline, cmdline_allocated + blocksize); if(tmp == NULL){ - error_plus(0, errno, "realloc"); + error(0, errno, "realloc"); close(cl_fd); goto fail_find_usplash; } @@ -281,7 +255,7 @@ sret = read(cl_fd, cmdline + cmdline_len, cmdline_allocated - cmdline_len); if(sret == -1){ - error_plus(0, errno, "read"); + error(0, errno, "read"); close(cl_fd); goto fail_find_usplash; } @@ -289,14 +263,14 @@ } while(sret != 0); ret = close(cl_fd); if(ret == -1){ - error_plus(0, errno, "close"); + error(0, errno, "close"); goto fail_find_usplash; } } /* Close directory */ ret = closedir(proc_dir); if(ret == -1){ - error_plus(0, errno, "closedir"); + error(0, errno, "closedir"); goto fail_find_usplash; } /* Success */ @@ -351,26 +325,26 @@ sigemptyset(&new_action.sa_mask); ret = sigaddset(&new_action.sa_mask, SIGINT); if(ret == -1){ - error_plus(0, errno, "sigaddset"); + error(0, errno, "sigaddset"); status = EX_OSERR; goto failure; } ret = sigaddset(&new_action.sa_mask, SIGHUP); if(ret == -1){ - error_plus(0, errno, "sigaddset"); + error(0, errno, "sigaddset"); status = EX_OSERR; goto failure; } ret = sigaddset(&new_action.sa_mask, SIGTERM); if(ret == -1){ - error_plus(0, errno, "sigaddset"); + error(0, errno, "sigaddset"); status = EX_OSERR; goto failure; } ret = sigaction(SIGINT, NULL, &old_action); if(ret == -1){ if(errno != EINTR){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); status = EX_OSERR; } goto failure; @@ -379,7 +353,7 @@ ret = sigaction(SIGINT, &new_action, NULL); if(ret == -1){ if(errno != EINTR){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); status = EX_OSERR; } goto failure; @@ -388,7 +362,7 @@ ret = sigaction(SIGHUP, NULL, &old_action); if(ret == -1){ if(errno != EINTR){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); status = EX_OSERR; } goto failure; @@ -397,7 +371,7 @@ ret = sigaction(SIGHUP, &new_action, NULL); if(ret == -1){ if(errno != EINTR){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); status = EX_OSERR; } goto failure; @@ -406,7 +380,7 @@ ret = sigaction(SIGTERM, NULL, &old_action); if(ret == -1){ if(errno != EINTR){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); status = EX_OSERR; } goto failure; @@ -415,7 +389,7 @@ ret = sigaction(SIGTERM, &new_action, NULL); if(ret == -1){ if(errno != EINTR){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); status = EX_OSERR; } goto failure; @@ -427,7 +401,7 @@ /* Write command to FIFO */ if(not usplash_write(&fifo_fd, "TIMEOUT", "0")){ if(errno != EINTR){ - error_plus(0, errno, "usplash_write"); + error(0, errno, "usplash_write"); status = EX_OSERR; } goto failure; @@ -439,7 +413,7 @@ if(not usplash_write(&fifo_fd, "INPUTQUIET", prompt)){ if(errno != EINTR){ - error_plus(0, errno, "usplash_write"); + error(0, errno, "usplash_write"); status = EX_OSERR; } goto failure; @@ -457,7 +431,7 @@ outfifo_fd = open("/dev/.initramfs/usplash_outfifo", O_RDONLY); if(outfifo_fd == -1){ if(errno != EINTR){ - error_plus(0, errno, "open"); + error(0, errno, "open"); status = EX_OSERR; } goto failure; @@ -476,7 +450,7 @@ char *tmp = realloc(buf, buf_allocated + blocksize); if(tmp == NULL){ if(errno != EINTR){ - error_plus(0, errno, "realloc"); + error(0, errno, "realloc"); status = EX_OSERR; } goto failure; @@ -488,7 +462,7 @@ buf_allocated - buf_len); if(sret == -1){ if(errno != EINTR){ - error_plus(0, errno, "read"); + error(0, errno, "read"); status = EX_OSERR; } TEMP_FAILURE_RETRY(close(outfifo_fd)); @@ -503,7 +477,7 @@ ret = close(outfifo_fd); if(ret == -1){ if(errno != EINTR){ - error_plus(0, errno, "close"); + error(0, errno, "close"); status = EX_OSERR; } goto failure; @@ -516,7 +490,7 @@ if(not usplash_write(&fifo_fd, "TIMEOUT", "15")){ if(errno != EINTR){ - error_plus(0, errno, "usplash_write"); + error(0, errno, "usplash_write"); status = EX_OSERR; } goto failure; @@ -529,7 +503,7 @@ ret = close(fifo_fd); if(ret == -1){ if(errno != EINTR){ - error_plus(0, errno, "close"); + error(0, errno, "close"); status = EX_OSERR; } goto failure; @@ -543,7 +517,7 @@ sret = write(STDOUT_FILENO, buf + written, buf_len - written); if(sret == -1){ if(errno != EINTR){ - error_plus(0, errno, "write"); + error(0, errno, "write"); status = EX_OSERR; } goto failure; @@ -580,7 +554,7 @@ if(fifo_fd != -1){ ret = (int)TEMP_FAILURE_RETRY(close(fifo_fd)); if(ret == -1 and errno != EINTR){ - error_plus(0, errno, "close"); + error(0, errno, "close"); } fifo_fd = -1; } @@ -589,7 +563,7 @@ if(outfifo_fd != -1){ ret = (int)TEMP_FAILURE_RETRY(close(outfifo_fd)); if(ret == -1){ - error_plus(0, errno, "close"); + error(0, errno, "close"); } } @@ -597,7 +571,7 @@ char **cmdline_argv = malloc((argz_count(cmdline, cmdline_len) + 1) * sizeof(char *)); /* Count args */ if(cmdline_argv == NULL){ - error_plus(0, errno, "malloc"); + error(0, errno, "malloc"); return status; } argz_extract(cmdline, cmdline_len, cmdline_argv); /* Create argv */ @@ -618,13 +592,13 @@ the real user ID (_mandos) */ ret = setuid(geteuid()); if(ret == -1){ - error_plus(0, errno, "setuid"); + error(0, errno, "setuid"); } setsid(); ret = chdir("/"); if(ret == -1){ - error_plus(0, errno, "chdir"); + error(0, errno, "chdir"); _exit(EX_OSERR); } /* if(fork() != 0){ */ @@ -632,13 +606,13 @@ /* } */ ret = dup2(STDERR_FILENO, STDOUT_FILENO); /* replace our stdout */ if(ret == -1){ - error_plus(0, errno, "dup2"); + error(0, errno, "dup2"); _exit(EX_OSERR); } execv(usplash_name, cmdline_argv); if(not interrupted_by_signal){ - error_plus(0, errno, "execv"); + error(0, errno, "execv"); } free(cmdline); free(cmdline_argv); @@ -649,7 +623,7 @@ sleep(2); if(not usplash_write(&fifo_fd, "PULSATE", NULL)){ if(errno != EINTR){ - error_plus(0, errno, "usplash_write"); + error(0, errno, "usplash_write"); } } @@ -657,7 +631,7 @@ if(fifo_fd != -1){ ret = (int)TEMP_FAILURE_RETRY(close(fifo_fd)); if(ret == -1 and errno != EINTR){ - error_plus(0, errno, "close"); + error(0, errno, "close"); } fifo_fd = -1; } @@ -668,13 +642,13 @@ ret = (int)TEMP_FAILURE_RETRY(sigaction(signal_received, &signal_action, NULL)); if(ret == -1){ - error_plus(0, errno, "sigaction"); + error(0, errno, "sigaction"); } do { ret = raise(signal_received); } while(ret != 0 and errno == EINTR); if(ret != 0){ - error_plus(0, errno, "raise"); + error(0, errno, "raise"); abort(); } TEMP_FAILURE_RETRY(pause()); === modified file 'plugins.d/usplash.xml' --- plugins.d/usplash.xml 2011-12-31 23:05:34 +0000 +++ plugins.d/usplash.xml 2009-01-04 21:54:55 +0000 @@ -2,7 +2,7 @@ - + %common; ]> @@ -19,22 +19,20 @@ Björn Påhlsson
- belorn@recompile.se + belorn@fukt.bsnet.se
Teddy Hogeborn
- teddy@recompile.se + teddy@fukt.bsnet.se
2008 2009 - 2011 - 2012 Teddy Hogeborn Björn Påhlsson @@ -179,7 +177,7 @@
- /proc + /proc To find the running SEE ALSO - intro - 8mandos, crypttab 5, fifo