├── units
├── envoy@.socket
└── envoy@.service
├── .gitignore
├── src
├── coverity_model.c
├── socket.h
├── dbus.h
├── gpg-protocol.h
├── socket.c
├── util.h
├── agents.h
├── .ycm_extra_conf.py
├── agents.c
├── util.c
├── dbus.c
├── envoy-exec.c
├── pam_envoy.c
├── gpg-protocol.rl
├── envoy.c
└── envoyd.c
├── zsh-completion
├── dist
└── envoy.spec
├── man
├── envoy-exec.1
├── envoyd.1
└── envoy.1
├── Makefile
├── README.md
└── LICENSE
/units/envoy@.socket:
--------------------------------------------------------------------------------
1 | [Socket]
2 | ListenStream=@/vodik/envoy
3 |
4 | [Install]
5 | WantedBy=sockets.target
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /envoy
2 | /envoyd
3 | /envoy-exec
4 | /pam_envoy.so
5 | src/gpg-protocol.c
6 | *.o
7 | *.pyc
8 | __pycache__/
9 |
--------------------------------------------------------------------------------
/src/coverity_model.c:
--------------------------------------------------------------------------------
1 | void err(int eval, const char *fmt, ...) {
2 | __coverity_panic__();
3 | }
4 |
5 | void errx(int eval, const char *fmt, ...) {
6 | __coverity_panic__();
7 | }
8 |
--------------------------------------------------------------------------------
/units/envoy@.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=Envoy agent monitor for %i
3 | Documentation=man:envoyd(1) man:envoy(1)
4 | After=dbus.service
5 | Requires=dbus.service
6 |
7 | [Service]
8 | ExecStart=/usr/bin/envoyd -t %i
9 | StandardOutput=syslog
10 | StandardError=syslog
11 |
12 | [Install]
13 | WantedBy=multi-user.target
14 | Also=envoy@.socket
15 |
--------------------------------------------------------------------------------
/src/socket.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2012
16 | */
17 |
18 | #pragma once
19 |
20 | #include
21 |
22 | size_t init_envoy_socket(struct sockaddr_un *un);
23 | void unlink_envoy_socket(void);
24 |
25 | // vim: et:sts=4:sw=4:cino=(0
26 |
--------------------------------------------------------------------------------
/src/dbus.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2012
16 | */
17 |
18 | #pragma once
19 |
20 | #include
21 |
22 | void start_transient_unit(sd_bus *bus, const char *name,
23 | const char *slice, const char *desc);
24 | char *get_unit(sd_bus *bus, const char *name);
25 | void stop_unit(sd_bus *bus, const char *path);
26 | char *get_unit_state(sd_bus *bus, const char *path);
27 | sd_bus *get_connection(uid_t uid);
28 |
--------------------------------------------------------------------------------
/zsh-completion:
--------------------------------------------------------------------------------
1 | #compdef envoy envoyd envoy-exec
2 |
3 | zstyle -a ":completion:${curcontext}:" environ environ
4 |
5 | case "$service" in
6 | envoy)
7 | _arguments -s \
8 | {-h,--help}'[display this help]'\
9 | {-v,--version}'[display version]'\
10 | {-d,--defer}'[defer adding keys until the next envoy invocation]'\
11 | {-a,--add}'[add private key identities]':files:_files \
12 | {-x,--expunge}'[remove private key identities]'\
13 | {-k,--kill}'[kill the running agent]'\
14 | {-r,--reload}'[reload the agent (gpg-agent only)]'\
15 | {-l,--list}'[list fingerprints of all loaded identities]'\
16 | {-u,--unlock=-}'[unlock the agent''s keyring (gpg-agent only)]'\
17 | {-p,--print}'[print out environmental arguments]' \
18 | {-s,--sh}'[print sh style commands]' \
19 | {-c,--csh}'[print csh style commands]' \
20 | {-f,--fish}'[print fish style commands]' \
21 | {-t,--agent=-}'[set the preferred agent to start]:agents:(ssh-agent gpg-agent)'
22 | ;;
23 | envoyd)
24 | _arguments -s \
25 | {-h,--help}'[display this help]'\
26 | {-v,--version}'[display version]'\
27 | {-t,--agent=-}'[set the preferred agent to start]:agents:(ssh-agent gpg-agent)'
28 | ;;
29 | envoy-exec)
30 | _arguments -s '*::arguments: _normal'
31 | ;;
32 | esac
33 |
--------------------------------------------------------------------------------
/dist/envoy.spec:
--------------------------------------------------------------------------------
1 | %global commit 1497c9bef81f8b0cafdac518225252380061c2e6
2 | %global shortcommit %(c=%{commit}; echo ${c:0:7})
3 |
4 | %global repo https://github.com/vodik/envoy/archive/%{commit}
5 |
6 | Name: envoy
7 | Version: 0.GIT.%{shortcommit}
8 | Release: 1%{?dist}
9 | Summary: A ssh/gpg-agent wrapper using cgroups and systemd.socket
10 |
11 | License: GPL
12 | URL: https://github.com/vodik/envoy
13 | Source0: %{repo}/envoy-%{version}.tar.gz
14 |
15 | BuildRequires: dbus-devel
16 | BuildRequires: make
17 | BuildRequires: pam-devel
18 | BuildRequires: ragel
19 | BuildRequires: systemd
20 | BuildRequires: systemd-devel
21 |
22 | Requires: dbus
23 | Requires: dbus-libs
24 | Requires: pam
25 | Requires: systemd-libs
26 | Requires: pkgconfig
27 |
28 | %description
29 | Envoy helps you to manage ssh keys in similar fashion to keychain, but done in C, takes advantage of cgroups and systemd.
30 |
31 | %prep
32 | %setup -q -n envoy-%{commit}
33 |
34 |
35 | %build
36 | make %{?_smp_mflags}
37 |
38 |
39 | %install
40 | rm -rf $RPM_BUILD_ROOT
41 | %make_install
42 |
43 |
44 | %files
45 | %{_bindir}/envoyd
46 | %{_bindir}/envoy
47 | %{_bindir}/envoy-exec
48 | %{_libdir}/security/pam_envoy.so
49 | %{_unitdir}/envoy@.service
50 | %{_unitdir}/envoy@.socket
51 | %{_unitdir}/../user/envoy@.service
52 | %{_unitdir}/../user/envoy@.socket
53 | %{_datadir}/zsh/site-functions/_envoy
54 | %doc
55 | %{_mandir}/man1/envoyd.1.gz
56 | %{_mandir}/man1/envoy.1.gz
57 | %{_mandir}/man1/envoy-exec.1.gz
58 |
59 |
60 |
61 | %changelog
62 | * Mon Oct 19 2015 Santiago Saavedra
63 | - Initial specfile
64 |
--------------------------------------------------------------------------------
/src/gpg-protocol.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2012
16 | */
17 |
18 | #pragma once
19 |
20 | struct gpg_t;
21 |
22 | enum keyflags {
23 | KEY_DISABLED = 1,
24 | KEY_SSHCONTROL = 1 << 1,
25 | KEY_CONFIRM = 1 << 2,
26 | };
27 |
28 | struct fingerprint_t {
29 | char *fingerprint;
30 | enum keyflags flags;
31 | struct fingerprint_t *next;
32 | };
33 |
34 | struct gpg_t *gpg_agent_connection(const char *sock, const char *home);
35 | void gpg_close(struct gpg_t *gpg);
36 |
37 | int gpg_reload_agent(struct gpg_t *gpg);
38 | int gpg_update_tty(struct gpg_t *gpg);
39 | int gpg_preset_passphrase(struct gpg_t *gpg, const char *fingerprint, int timeout, const char *password);
40 | struct fingerprint_t *gpg_keyinfo(struct gpg_t *gpg);
41 |
42 | void free_fingerprints(struct fingerprint_t *frpt);
43 |
44 | #define _cleanup_gpg_ __attribute__((cleanup(gpg_closep)))
45 | static inline void gpg_closep(struct gpg_t **p) { if (*p) gpg_close(*p); }
46 |
47 | // vim: et:sts=4:sw=4:cino=(0
48 |
--------------------------------------------------------------------------------
/man/envoy-exec.1:
--------------------------------------------------------------------------------
1 | .TH envoy-exec "1" "July 27" "envoy" "User Commands"
2 | .SH NAME
3 | envoy-exec \- application wrapping tool
4 | .SH SYNOPSIS
5 | \fBenvoy-exec\fP command
6 | .SH DESCRIPTION
7 | \fBenvoy-exec\fP connects to the daemon, gets all the information
8 | associated with the current running agent, updates it with fresh
9 | environmental information and then invokes the provided command. This
10 | ensures that the command runs as seamlessly as possible with the agent
11 | without having to worry about the system's or shell's environment.
12 | .SS Symlinking Against envoy-exec
13 | It is also possible to symlink \fBenvoy-exec\fP to another name to
14 | provide a terser wrapper for that command.
15 | .IP
16 | .nf
17 | export PATH="$HOME/bin:$PATH"
18 | ln -s /usr/bin/envoy-exec ~/bin/ssh
19 | .fi
20 | .SH OPTIONS
21 | .PP
22 | .IP "\fB\-h\fR, \fB\-\-help\fR"
23 | Display help message.
24 | .IP "\fB\-v\fR, \fB\-\-version\fR"
25 | Display version information.
26 | .IP "\fB\-t\fR \fR\fIAGENT\fR\fR, \fB\-\-agent\fR\fB=\fR\fIAGENT\fR"
27 | Set the agent type to fetch. If this isn't set, its up to \fBenvoyd\fR
28 | to decide which agent is launched. \fIssh-agent\fR and \fIgpg-agent\fR
29 | are supported agents (see \fBenvoy\fR(1)).
30 | .SH ENVIRONMENT
31 | .PP
32 | .IP \fBENVOY_SOCKET\fR
33 | Both \fBenvoyd\fP and \fBenvoy\fP use this environment variable for the
34 | location of the unix domain socket for communication. Prefixing the
35 | socket with a @ denotes an abstract namespace. The default socket is
36 | \fI@/vodik/envoy\fR
37 | .PP
38 | .SH AUTHORS
39 | .nf
40 | Simon Gomizelj
41 | .fi
42 | .SH SEE ALSO
43 | \fBenvoyd\fR(1),
44 | \fBenvoy\fR(1),
45 | \fBssh-agent\fR(1),
46 | \fBssh-add\fR(1),
47 | \fBgpg-agent\fR(1)
48 |
--------------------------------------------------------------------------------
/man/envoyd.1:
--------------------------------------------------------------------------------
1 | .TH envoy "1" "July 27" "envoyd" "User Commands"
2 | .SH NAME
3 | envoyd \- process manager for envoy
4 | .SH SYNOPSIS
5 | \fBenvoyd\fP [options] [files]
6 | .SH DESCRIPTION
7 | \fBenvoyd\fP starts the agent of choice in a sanitized environment and
8 | caches the associated environmental variables in memory. The agent is
9 | started on demand and its lifetime is tracked through cgroups for
10 | accuracy.
11 |
12 | This daemon is typically started as root and can thus serve all the
13 | users on the system at once. When started as root, it will check the
14 | credentials of the incoming connection and start the agent under that
15 | uid/guid. If it is started as a user it will only be able to serve that
16 | particular user's requests.
17 |
18 | This effectively allows a user to share a single long-running
19 | authentication agent between all shells and sessions in a clean and
20 | managed fashion that doesn't clutter user login sessions.
21 | .SH OPTIONS
22 | .PP
23 | .IP "\fB\-h\fR, \fB\-\-help\fR"
24 | Display help message.
25 | .IP "\fB\-v\fR, \fB\-\-version\fR"
26 | Display version information.
27 | .IP "\fB\-t\fR \fR\fIAGENT\fR\fR, \fB\-\-agent\fR\fB=\fR\fIAGENT\fR"
28 | Set the default agent type to start. By default this is ssh-agent.
29 | .SH ENVIRONMENT
30 | .PP
31 | .IP \fBENVOY_SOCKET\fR
32 | Both \fBenvoyd\fP and \fBenvoy\fP use this environment variable for the
33 | location of the unix domain socket for communication. Prefixing the
34 | socket with a @ denotes an abstract namespace. The default socket is
35 | \fI@/vodik/envoy\fR
36 | .SH AUTHORS
37 | .nf
38 | Simon Gomizelj
39 | .fi
40 | .SH SEE ALSO
41 | \fBenvoy\fR(1),
42 | \fBenvoy-exec\fR(1),
43 | \fBssh-agent\fR(1),
44 | \fBssh-add\fR(1),
45 | \fBgpg-agent\fR(1)
46 |
--------------------------------------------------------------------------------
/src/socket.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #include "socket.h"
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 |
30 | static const char *get_socket_path(void)
31 | {
32 | const char *socket = getenv("ENVOY_SOCKET");
33 | return socket ? socket : "@/vodik/envoy";
34 | }
35 |
36 | size_t init_envoy_socket(struct sockaddr_un *un)
37 | {
38 | const char *socket = get_socket_path();
39 | off_t off = 0;
40 | size_t len;
41 |
42 | *un = (struct sockaddr_un){ .sun_family = AF_UNIX };
43 |
44 | if (socket[0] == '@')
45 | off = 1;
46 |
47 | len = strlen(socket);
48 | memcpy(&un->sun_path[off], &socket[off], len - off);
49 |
50 | return len + sizeof(un->sun_family);
51 | }
52 |
53 | void unlink_envoy_socket(void)
54 | {
55 | const char *socket = get_socket_path();
56 | if (socket[0] != '@')
57 | unlink(socket);
58 | }
59 |
--------------------------------------------------------------------------------
/src/util.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2013
16 | */
17 |
18 | #pragma once
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 |
26 | #define _unused_ __attribute__((unused))
27 | #define _noreturn_ __attribute__((noreturn))
28 | #define _printf_(a,b) __attribute__((format (printf, a, b)))
29 | #define _sentinel_ __attribute__((sentinel))
30 | #define _cleanup_(x) __attribute__((cleanup(x)))
31 | #define _cleanup_free_ _cleanup_(freep)
32 | #define _cleanup_close_ _cleanup_(closep)
33 |
34 | static inline void freep(void *p) { free(*(void **)p); }
35 | static inline void closep(int *fd) { if (*fd >= 0) close(*fd); }
36 |
37 | static inline bool streq(const char *s1, const char *s2) { return strcmp(s1, s2) == 0; }
38 | static inline bool strneq(const char *s1, const char *s2, size_t n) { return strncmp(s1, s2, n) == 0; }
39 |
40 | char *joinpath(const char *root, ...) _sentinel_;
41 | int putenvf(const char *fmt, ...) _printf_(1, 2);
42 | void safe_asprintf(char **strp, const char *fmt, ...) _printf_(2, 3);
43 |
44 | int unblock_signals(void);
45 | int get_signalfd(int signum, ...) _sentinel_;
46 |
47 | const char *get_home_dir(void);
48 |
49 | // vim: et:sts=4:sw=4:cino=(0
50 |
--------------------------------------------------------------------------------
/src/agents.h:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #pragma once
19 |
20 | #include
21 | #include
22 | #include
23 |
24 | enum agent {
25 | AGENT_DEFAULT = -1,
26 | AGENT_SSH_AGENT = 0,
27 | AGENT_GPG_AGENT,
28 | };
29 |
30 | enum status {
31 | ENVOY_STOPPED = 0,
32 | ENVOY_STARTED,
33 | ENVOY_RUNNING,
34 | ENVOY_FAILED,
35 | ENVOY_BADUSER,
36 | };
37 |
38 | enum options {
39 | AGENT_DEFAULTS = 0,
40 | AGENT_STATUS = 1 << 0,
41 | AGENT_ENVIRON = 1 << 1,
42 | AGENT_KILL = 1 << 2
43 | };
44 |
45 | struct agent_t {
46 | const char *name[2];
47 | char *const *argv;
48 | };
49 |
50 | struct agent_request_t {
51 | enum agent type;
52 | enum options opts;
53 | };
54 |
55 | struct agent_data_t {
56 | enum agent type;
57 | enum status status;
58 | char sock[PATH_MAX];
59 | char gpg[PATH_MAX];
60 | char unit_path[PATH_MAX];
61 | };
62 |
63 | static inline bool agent_running(struct agent_data_t *data)
64 | {
65 | return data->status == ENVOY_STARTED || data->status == ENVOY_RUNNING;
66 | }
67 |
68 | static inline bool agent_started(struct agent_data_t *data)
69 | {
70 | return data->status == ENVOY_STARTED;
71 | }
72 |
73 | extern const struct agent_t Agent[];
74 |
75 | int envoy_get_agent(enum agent type, struct agent_data_t *data, enum options opts);
76 | int envoy_kill_agent(enum agent type);
77 |
78 | enum agent lookup_agent(const char *string);
79 |
80 | // vim: et:sts=4:sw=4:cino=(0
81 |
--------------------------------------------------------------------------------
/src/.ycm_extra_conf.py:
--------------------------------------------------------------------------------
1 | import os
2 | import ycm_core
3 | import subprocess
4 | from clang_helpers import PrepareClangFlags
5 |
6 | database = None
7 |
8 | def pkg_config(pkg):
9 | def not_whitespace(string):
10 | return not (string == '' or string == '\n')
11 | output = subprocess.check_output(['pkg-config', '--cflags', pkg]).strip()
12 | return filter(not_whitespace, output.split(' '))
13 |
14 | flags = [
15 | '-Wall',
16 | '-Wextra',
17 | '-Werror',
18 | '-pedantic',
19 | '-Wshadow', '-Wpointer-arith', '-Wcast-qual', '-Wstrict-prototypes', '-Wmissing-prototypes',
20 | '-DNDEBUG',
21 | '-DUSE_CLANG_COMPLETER',
22 | '-DENVOY_VERSION="ycm"',
23 | '-D_GNU_SOURCE',
24 | '-std=c11',
25 | '-x', 'c'
26 | ]
27 |
28 | flags += pkg_config('dbus-1')
29 | flags += pkg_config('libsystemd-daemon')
30 |
31 | def DirectoryOfThisScript():
32 | return os.path.dirname(os.path.abspath( __file__ ))
33 |
34 | def MakeRelativePathsInFlagsAbsolute( flags, working_directory ):
35 | if not working_directory:
36 | return flags
37 | new_flags = []
38 | make_next_absolute = False
39 | path_flags = [ '-isystem', '-I', '-iquote', '--sysroot=' ]
40 | for flag in flags:
41 | new_flag = flag
42 |
43 | if make_next_absolute:
44 | make_next_absolute = False
45 | if not flag.startswith('/'):
46 | new_flag = os.path.join(working_directory, flag)
47 |
48 | for path_flag in path_flags:
49 | if flag == path_flag:
50 | make_next_absolute = True
51 | break
52 |
53 | if flag.startswith(path_flag):
54 | path = flag[len(path_flag):]
55 | new_flag = path_flag + os.path.join(working_directory, path)
56 | break
57 |
58 | if new_flag:
59 | new_flags.append(new_flag)
60 | return new_flags
61 |
62 | def FlagsForFile(filename):
63 | if database:
64 | # Bear in mind that compilation_info.compiler_flags_ does NOT return a
65 | # python list, but a "list-like" StringVec object
66 | compilation_info = database.GetCompilationInfoForFile(filename)
67 | final_flags = PrepareClangFlags(
68 | MakeRelativePathsInFlagsAbsolute(compilation_info.compiler_flags_,
69 | compilation_info.compiler_working_dir_),
70 | filename)
71 | else:
72 | relative_to = DirectoryOfThisScript()
73 | final_flags = MakeRelativePathsInFlagsAbsolute(flags, relative_to)
74 |
75 | return {
76 | 'flags': final_flags,
77 | 'do_cache': True
78 | }
79 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | RAGEL = ragel
2 | RAGEL_FLAGS := -F0
3 |
4 | COMPILE.rl = $(RAGEL) $(RAGEL_FLAGS)
5 |
6 | %.c: %.rl
7 | $(COMPILE.rl) -C $(OUTPUT_OPTION) $<
8 |
9 | %.so: %.o
10 | $(LINK.o) -shared $^ $(LOADLIBES) $(LDLIBS) -o $@
11 |
12 | VERSION=v14
13 | GIT_DESC=$(shell test -d .git && git describe 2>/dev/null)
14 |
15 | ifneq "$(GIT_DESC)" ""
16 | VERSION=$(GIT_DESC)
17 | endif
18 |
19 | base_CFLAGS = -std=c11 -g \
20 | -Wall -Wextra -pedantic \
21 | -Wshadow -Wpointer-arith -Wcast-qual -Wstrict-prototypes -Wmissing-prototypes \
22 | -D_GNU_SOURCE \
23 | -DENVOY_VERSION=\"$(VERSION)\"
24 |
25 | libsystemd_CFLAGS = $(shell pkg-config --cflags libsystemd)
26 | libsystemd_LDLIBS = $(shell pkg-config --libs libsystemd)
27 |
28 | dbus_CFLAGS = $(shell pkg-config --cflags dbus-1)
29 | dbus_LDLIBS = $(shell pkg-config --libs dbus-1)
30 |
31 | CFLAGS := \
32 | $(base_CFLAGS) \
33 | $(libsystemd_CFLAGS) \
34 | $(dbus_CFLAGS) \
35 | $(CFLAGS)
36 |
37 | LDLIBS := \
38 | $(libsystemd_LDLIBS) \
39 | $(dbus_LDLIBS) \
40 | $(LDLIBS)
41 |
42 | VPATH = src
43 | LIBDIR := $(shell pkg-config --variable=libdir libsystemd)
44 | ENVOYLIBS = gpg-protocol.o agents.o socket.o util.o
45 |
46 | all: envoyd envoy envoy-exec pam_envoy.so
47 |
48 | gpg-protocol.o: $(VPATH)/gpg-protocol.c
49 | $(ENVOYLIBS) pam_envoy.o: private CFLAGS += -fPIC
50 |
51 | envoyd: envoyd.o dbus.o $(ENVOYLIBS)
52 | envoy: envoy.o $(ENVOYLIBS)
53 | envoy-exec: envoy-exec.o $(ENVOYLIBS)
54 | pam_envoy.so: pam_envoy.o $(ENVOYLIBS)
55 |
56 | install: envoyd envoy pam_envoy.so
57 | install -Dm755 envoyd $(DESTDIR)/usr/bin/envoyd
58 | install -Dm755 envoy $(DESTDIR)/usr/bin/envoy
59 | install -Dm755 envoy-exec $(DESTDIR)/usr/bin/envoy-exec
60 | install -Dm755 pam_envoy.so $(DESTDIR)/$(LIBDIR)/security/pam_envoy.so
61 | install -Dm644 man/envoyd.1 $(DESTDIR)/usr/share/man/man1/envoyd.1
62 | install -Dm644 man/envoy.1 $(DESTDIR)/usr/share/man/man1/envoy.1
63 | install -Dm644 man/envoy-exec.1 $(DESTDIR)/usr/share/man/man1/envoy-exec.1
64 | install -Dm644 units/envoy@.service $(DESTDIR)/usr/lib/systemd/system/envoy@.service
65 | install -Dm644 units/envoy@.socket $(DESTDIR)/usr/lib/systemd/system/envoy@.socket
66 | install -Dm644 units/envoy@.service $(DESTDIR)/usr/lib/systemd/user/envoy@.service
67 | install -Dm644 units/envoy@.socket $(DESTDIR)/usr/lib/systemd/user/envoy@.socket
68 | install -Dm644 zsh-completion $(DESTDIR)/usr/share/zsh/site-functions/_envoy
69 |
70 | clean:
71 | $(RM) envoyd envoy envoy-exec pam_envoy.so *.o src/gpg-protocol.c
72 |
73 | .PHONY: all clean install
74 |
--------------------------------------------------------------------------------
/src/agents.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #include "agents.h"
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 |
27 | #include "socket.h"
28 | #include "util.h"
29 |
30 | const struct agent_t Agent[] = {
31 | [AGENT_SSH_AGENT] = {
32 | .name = { "ssh-agent", "ssh" },
33 | .argv = (char *const []){ "/usr/bin/ssh-agent", NULL }
34 | },
35 | [AGENT_GPG_AGENT] = {
36 | .name = { "gpg-agent", "gpg" },
37 | .argv = (char *const []){ "/usr/bin/gpg-agent", "--daemon", "--enable-ssh-support", NULL }
38 | }
39 | };
40 |
41 | static int envoy_connect(void)
42 | {
43 | socklen_t sa_len;
44 | union {
45 | struct sockaddr sa;
46 | struct sockaddr_un un;
47 | } sa;
48 |
49 | int fd = socket(AF_UNIX, SOCK_STREAM, 0);
50 | if (fd < 0)
51 | return -1;
52 |
53 | sa_len = init_envoy_socket(&sa.un);
54 | if (connect(fd, &sa.sa, sa_len) < 0) {
55 | close(fd);
56 | return -1;
57 | }
58 |
59 | return fd;
60 | }
61 |
62 | static ssize_t envoy_request(const struct agent_request_t *req, struct agent_data_t *data)
63 | {
64 | _cleanup_close_ int fd = envoy_connect();
65 | if (fd < 0)
66 | return -1;
67 | if (write(fd, req, sizeof(struct agent_request_t)) < 0)
68 | return -1;
69 | return read(fd, data, sizeof(struct agent_data_t));
70 | }
71 |
72 | int envoy_get_agent(enum agent type, struct agent_data_t *data, enum options opts)
73 | {
74 | const struct agent_request_t req = { .type = type, .opts = opts };
75 | return envoy_request(&req, data) < 0 ? -1 : 0;
76 | }
77 |
78 | int envoy_kill_agent(enum agent type)
79 | {
80 | const struct agent_request_t req = { .type = type, .opts = AGENT_KILL };
81 | struct agent_data_t data;
82 |
83 | if (envoy_request(&req, &data) < 0)
84 | return -1;
85 | return data.status == ENVOY_STOPPED ? 0 : -1;
86 | }
87 |
88 | enum agent lookup_agent(const char *string)
89 | {
90 | size_t i;
91 | for (i = 0; i < sizeof(Agent) / sizeof(Agent[0]); i++) {
92 | const struct agent_t *agent = &Agent[i];
93 |
94 | if (streq(agent->name[0], string) || streq(agent->name[1], string))
95 | return i;
96 | }
97 | return -1;
98 | }
99 |
100 | // vim: et:sts=4:sw=4:cino=(0
101 |
--------------------------------------------------------------------------------
/man/envoy.1:
--------------------------------------------------------------------------------
1 | .TH envoy "1" "July 27" "envoy" "User Commands"
2 | .SH NAME
3 | envoy \- authentication agent controller
4 | .SH SYNOPSIS
5 | \fBenvoy\fP [options] [keys]
6 | .SH DESCRIPTION
7 | \fBenvoy\fP is the client side to \fBenvoyd\fP(1). It connects to the
8 | daemon and gets all the information associated with the current running
9 | agent. It can then do things like add new keys to the agent or output
10 | shell code to inject these variables into a shell.
11 |
12 | This effectively allows a user to share a single long-running
13 | authentication agent between all shells and sessions in a clean and
14 | managed fashion that doesn't clutter user login sessions.
15 | .SS Sourcing Environmental Variables
16 | To connect/source the environmental variables...
17 | .IP
18 | .nf
19 | envoy -t ssh-agent [key ...] # gpg-agent also supported
20 | source <(envoy -p)
21 | .fi
22 | .PP
23 | .SH OPTIONS
24 | .PP
25 | .IP "\fB\-h\fR, \fB\-\-help\fR"
26 | Display help message.
27 | .IP "\fB\-v\fR, \fB\-\-version\fR"
28 | Display version information.
29 | .IP "\fB\-d\fR, \fB\-\-defer\fR"
30 | Defer adding keys until the next envoy call. Useful for using envoy with
31 | ssh-agent in scripts. A useful safety to launch envoy correctly when in
32 | a environment where it can't ask for keys.
33 | .IP "\fB\-a\fR, \fB\-\-add\fR"
34 | Add private key identities to the authentication agent using
35 | \fBssh-add\fR(1). Note that when passing in keys, if they reside in
36 | \fI~/.ssh/\fR, then just providing the filename is sufficient.
37 | .IP "\fB\-k\fR, \fB\-\-kill\fR"
38 | Terminate the running agent. Sends \fISIGTERM\fR to the running agent.
39 | .IP "\fB\-r\fR, \fB\-\-reload\fR"
40 | For gpg-agent only, flush all cached passphrases and, if the program has
41 | been started with a configuration file, reload it. Sends
42 | \fIRELOADAGENT\fR over gpg-agent's socket.
43 | .IP "\fB\-l\fR, \fB\-\-list\fR"
44 | Lists fingerprints of all identities currently represented by the agent.
45 | .IP "\fB\-u\fR[\fIPASSWORD\fR], \fB\-\-unlock\fR\fB=\fR[\fIPASSWORD\fR]
46 | For gpg-agent only, unlock the agent's keyrings. The password will be
47 | prompted for if its not optionally provided. This requires that
48 | \fIallow-preset-passphrase\fR is set in your \fIgpg-agent.conf\fR to
49 | work.
50 | .IP "\fB\-p\fR, \fB\-\-print\fR"
51 | Print out the environmental variables associated with the running agent.
52 | Useful for injecting these variables into the shell.
53 | .IP "\fB\-s\fR, \fB\-\-sh\fR"
54 | Print sh-style commands when outputting environmental variables.
55 | .IP "\fB\-c\fR, \fB\-\-csh\fR"
56 | Print csh-style commands when outputting environmental variables.
57 | .IP "\fB\-f\fR, \fB\-\-fish\fR"
58 | Print fish-style commands when outputting environmental variables.
59 | .IP "\fB\-t\fR \fIAGENT\fR, \fB\-\-agent\fR\fB=\fR\fIAGENT\fR"
60 | Set the agent type to launch. If this isn't set, its up to \fBenvoyd\fR
61 | to decide which agent is launched. \fIssh-agent\fR and \fIgpg-agent\fR
62 | are supported agents.
63 | .SH ENVIRONMENT
64 | .PP
65 | .IP \fBENVOY_SOCKET\fR
66 | Both \fBenvoyd\fP and \fBenvoy\fP use this environment variable for the
67 | location of the unix domain socket for communication. Prefixing the
68 | socket with a @ denotes an abstract namespace. The default socket is
69 | \fI@/vodik/envoy\fR.
70 | .SH AUTHORS
71 | .nf
72 | Simon Gomizelj
73 | .fi
74 | .SH SEE ALSO
75 | \fBenvoyd\fR(1),
76 | \fBenvoy-exec\fR(1),
77 | \fBssh-agent\fR(1),
78 | \fBssh-add\fR(1),
79 | \fBgpg-agent\fR(1)
80 |
--------------------------------------------------------------------------------
/src/util.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #include "util.h"
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 |
29 | static char *home_dir_cache = NULL;
30 |
31 | char *joinpath(const char *root, ...)
32 | {
33 | size_t len;
34 | char *ret, *p;
35 | const char *temp;
36 | va_list ap;
37 |
38 | if (!root)
39 | return NULL;
40 |
41 | len = strlen(root);
42 |
43 | va_start(ap, root);
44 | while ((temp = va_arg(ap, const char *))) {
45 | size_t temp_len = strlen(temp) + 1;
46 | if (temp_len > ((size_t) -1) - len) {
47 | va_end(ap);
48 | return NULL;
49 | }
50 |
51 | len += temp_len;
52 | }
53 | va_end(ap);
54 |
55 | ret = malloc(len + 1);
56 | if (ret) {
57 | p = stpcpy(ret, root);
58 |
59 | va_start(ap, root);
60 | while ((temp = va_arg(ap, const char *))) {
61 | p++[0] = '/';
62 | p = stpcpy(p, temp);
63 | }
64 | va_end(ap);
65 | }
66 |
67 | return ret;
68 | }
69 |
70 | int putenvf(const char *fmt, ...)
71 | {
72 | /* we do not want to free the memory allocated for env because the
73 | * allocated memory literally becomes part of the environ data. */
74 | va_list ap;
75 | char *env;
76 | int ret;
77 |
78 | va_start(ap, fmt);
79 | ret = vasprintf(&env, fmt, ap);
80 | va_end(ap);
81 |
82 | return ret < 0 ? ret : putenv(env);
83 | }
84 |
85 | void safe_asprintf(char **strp, const char *fmt, ...)
86 | {
87 | va_list ap;
88 |
89 | va_start(ap, fmt);
90 | if (vasprintf(strp, fmt, ap) < 0)
91 | err(EXIT_FAILURE, "failed to allocate memory");
92 | va_end(ap);
93 | }
94 |
95 | int unblock_signals(void)
96 | {
97 | sigset_t mask;
98 | sigfillset(&mask);
99 | return sigprocmask(SIG_UNBLOCK, &mask, NULL);
100 | }
101 |
102 | int get_signalfd(int signum, ...)
103 | {
104 | va_list ap;
105 | sigset_t mask;
106 |
107 | sigemptyset(&mask);
108 | sigaddset(&mask, signum);
109 |
110 | va_start(ap, signum);
111 | while ((signum = va_arg(ap, int)))
112 | sigaddset(&mask, signum);
113 | va_end(ap);
114 |
115 | if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0)
116 | return -1;
117 | return signalfd(-1, &mask, SFD_CLOEXEC);
118 | }
119 |
120 | const char *get_home_dir(void)
121 | {
122 | if (!home_dir_cache) {
123 | home_dir_cache = getenv("HOME");
124 |
125 | if (home_dir_cache && home_dir_cache[0])
126 | home_dir_cache = strdup(home_dir_cache);
127 | else {
128 | struct passwd *pwd = getpwuid(getuid());
129 | if (!pwd)
130 | err(EXIT_FAILURE, "failed to get pwd entry for user");
131 | home_dir_cache = strdup(pwd->pw_dir);
132 | }
133 | }
134 |
135 | return home_dir_cache;
136 | }
137 |
138 | // vim: et:sts=4:sw=4:cino=(0
139 |
--------------------------------------------------------------------------------
/src/dbus.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #include "dbus.h"
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include "util.h"
28 |
29 | static void _noreturn_ _printf_(3,4) err2(int ret, int eval, const char *fmt, ...)
30 | {
31 | fprintf(stderr, "%s: ", program_invocation_short_name);
32 | if (fmt) {
33 | va_list ap;
34 |
35 | va_start(ap, fmt);
36 | vfprintf(stderr, fmt, ap);
37 | va_end(ap);
38 | fprintf(stderr, ": ");
39 | }
40 |
41 | fprintf(stderr, "%s\n", strerror(-ret));
42 | exit(eval);
43 | }
44 |
45 | void start_transient_unit(sd_bus *bus, const char *name,
46 | const char *slice, const char *desc)
47 | {
48 | sd_bus_message *msg = NULL;
49 | sd_bus_error error = SD_BUS_ERROR_NULL;
50 |
51 | int ret = sd_bus_message_new_method_call(bus, &msg,
52 | "org.freedesktop.systemd1",
53 | "/org/freedesktop/systemd1",
54 | "org.freedesktop.systemd1.Manager",
55 | "StartTransientUnit");
56 | if (ret < 0)
57 | err2(ret, EXIT_FAILURE, "failed to create new message");
58 |
59 | sd_bus_message_append(msg, "ss", name, "fail");
60 |
61 | sd_bus_message_open_container(msg, 'a', "(sv)");
62 | sd_bus_message_append(msg, "(sv)", "Description", "s", desc);
63 | sd_bus_message_append(msg, "(sv)", "SendSIGHUP", "b", true);
64 | sd_bus_message_append(msg, "(sv)", "PIDs", "au", 1, getpid());
65 | if (slice)
66 | sd_bus_message_append(msg, "(sv)", "Slice", "s", slice);
67 | sd_bus_message_close_container(msg);
68 |
69 | /* Auxiliary units */
70 | sd_bus_message_append(msg, "a(sa(sv))", 0);
71 |
72 | ret = sd_bus_call(bus, msg, 0, &error, NULL);
73 | if (ret < 0) {
74 | if (error.message) {
75 | fprintf(stderr, "%s", error.message);
76 | return;
77 | }
78 | err2(ret, EXIT_FAILURE, "failed to issue StartTransientUnit call");
79 | }
80 |
81 |
82 | sd_bus_message_unref(msg);
83 | sd_bus_error_free(&error);
84 | }
85 |
86 | char *get_unit(sd_bus *bus, const char *name)
87 | {
88 | sd_bus_message *msg = NULL;
89 | sd_bus_error error = SD_BUS_ERROR_NULL;
90 |
91 | int ret = sd_bus_call_method(bus, "org.freedesktop.systemd1",
92 | "/org/freedesktop/systemd1",
93 | "org.freedesktop.systemd1.Manager",
94 | "GetUnit", &error, &msg,
95 | "s", name);
96 | if (ret < 0) {
97 | if (error.message) {
98 | fprintf(stderr, "%s", error.message);
99 | return NULL;
100 | }
101 | err2(ret, EXIT_FAILURE, "failed to issue method call GetUnit %s", name);
102 | }
103 |
104 | char *path;
105 | ret = sd_bus_message_read(msg, "o", &path);
106 | if (ret < 0)
107 | err2(ret, EXIT_FAILURE, "failed to parse response message");
108 |
109 | sd_bus_message_unref(msg);
110 | sd_bus_error_free(&error);
111 | return strdup(path);
112 | }
113 |
114 | void stop_unit(sd_bus *bus, const char *path)
115 | {
116 | sd_bus_message *msg = NULL;
117 | sd_bus_error error = SD_BUS_ERROR_NULL;
118 |
119 | int ret = sd_bus_call_method(bus, "org.freedesktop.systemd1",
120 | path, "org.freedesktop.systemd1.Unit",
121 | "Stop", &error, &msg,
122 | "s", "fail");
123 | if (ret < 0) {
124 | if (error.message) {
125 | fprintf(stderr, "%s", error.message);
126 | return;
127 | }
128 | err2(ret, EXIT_FAILURE, "failed to issue method call Stop %s", path);
129 | }
130 |
131 | sd_bus_message_unref(msg);
132 | sd_bus_error_free(&error);
133 | }
134 |
135 | char *get_unit_state(sd_bus *bus, const char *path)
136 | {
137 | sd_bus_message *msg = NULL;
138 | sd_bus_error error = SD_BUS_ERROR_NULL;
139 |
140 | int ret = sd_bus_get_property(bus, "org.freedesktop.systemd1",
141 | path, "org.freedesktop.systemd1.Unit",
142 | "SubState", &error, &msg, "s");
143 | if (ret < 0) {
144 | if (error.message) {
145 | fprintf(stderr, "%s", error.message);
146 | return NULL;
147 | }
148 | err2(ret, EXIT_FAILURE, "failed to get property SubState");
149 | }
150 |
151 | char *state;
152 | ret = sd_bus_message_read(msg, "s", &state);
153 | if (ret < 0)
154 | err2(ret, EXIT_FAILURE, "failed to get property SubState");
155 |
156 | sd_bus_message_unref(msg);
157 | sd_bus_error_free(&error);
158 | return strdup(state);
159 | }
160 |
161 | sd_bus *get_connection(uid_t uid)
162 | {
163 | sd_bus *bus = NULL;
164 | sd_bus_new(&bus);
165 |
166 | if (uid == 0) {
167 | sd_bus_set_address(bus, "unix:path=/run/systemd/private");
168 | } else {
169 | _cleanup_free_ char *path = NULL;
170 | asprintf(&path, "unix:path=/run/user/%d/systemd/private", uid);
171 | sd_bus_set_address(bus, path);
172 | }
173 |
174 | sd_bus_start(bus);
175 | return bus;
176 | }
177 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ### NOTICE
2 |
3 | I've had a lot of fun developing and supporting this tool and learned
4 | temendously from developing it. However, I won't be dedicating much more
5 | effort into it going foward. Recent changes in `gpg-agent` have weakened
6 | the rational for using `envoyd` around `gpg-agent`.
7 |
8 | Its simpler and better to just wrap gpg-agent in a service now. That
9 | leaves `envoy-exec`, for this configuration, the only useful component.
10 | I've seperated it into a seperate project
11 | [gpg-tools](http://github.com/vodik/gpg-tools) under the name
12 | `gpg-exec`.
13 |
14 | Those using `ssh-agent` can continue to use this project, but since
15 | I primarily use `gpg-agent`, I can't speak for the quality of it. I will
16 | continue to try to support this project and fix bugs.
17 |
18 | ## envoy
19 |
20 |
21 |
23 |
24 |
25 | Envoy helps you to manage SSH keys in a similar fashion to [keychain], but
26 | is implemented in C and takes advantage of cgroups and systemd.
27 |
28 | The daemon, `envoyd`, starts the agent of choice in a sanitized
29 | environment and caches the associated environmental variables in memory.
30 | The agent is started on demand and its lifetime is tracked through
31 | cgroups for accuracy. `envoyd` is typically started as root and can thus
32 | serve all the users on the system at once. It checks the credentials of
33 | the incoming connection and starts the agent under that uid/guid. If it
34 | is started as a user it will only be able to serve that particular user's
35 | requests.
36 |
37 | The `envoy` command connects to the daemon and gets all the information
38 | associated with the current running agent. It can then do things like
39 | add new keys to the agent or output shell code to inject these variables
40 | into a shell.
41 |
42 | This effectively allows a user to share a single long-running
43 | authentication agent between all shells and sessions in a clean and
44 | managed fashion that doesn't clutter user login sessions.
45 |
46 | [keychain]: http://www.funtoo.org/Keychain
47 |
48 | ### Setup
49 |
50 | To setup envoy, first enable the socket:
51 |
52 | # systemctl enable envoy@ssh-agent.socket # to make ssh-agent the default agent
53 | # systemctl enable envoy@gpg-agent.socket # or to make it gpg-agent
54 |
55 | Then add the following to your shell's rc file.
56 |
57 | envoy [key ...]
58 | source <(envoy -p)
59 |
60 | The `-t` flag lets you override the default agent. So `envoy -t
61 | gpg-agent` will launch gpg-agent even if ssh-agent is the system
62 | default.
63 |
64 | The envoyd daemon will also run just fine under a user session, just
65 | note that it won't be able to serve multiple users at once in this
66 | configuration.
67 |
68 | ### Usage
69 |
70 | usage: envoy [options] [key ...]
71 | Options:
72 | -h, --help display this help
73 | -v, --version display version
74 | -d, --defer defer adding keys until the next envoy invocation
75 | -a, --add add private key identities
76 | -x, --expunge remove private key identities
77 | -k, --kill kill the running agent
78 | -r, --reload reload the agent (gpg-agent only)
79 | -l, --list list fingerprints of all loaded identities
80 | -u, --unlock=[PASS] unlock the agent's keyring (gpg-agent only)
81 | -p, --print print out environmental arguments
82 | -s, --sh print sh style commands
83 | -c, --csh print csh style commands
84 | -f, --fish print fish style commands
85 | -t, --agent=AGENT set the preferred agent to start
86 |
87 | Note that when passing in keys, if they reside in `~/.ssh/`, then just
88 | providing the filename is sufficient.
89 |
90 | ### Envoy with ssh-agent
91 |
92 | When invoking `envoy` causes `ssh-agent` to start, on that first run
93 | any keys passed to `envoy` will be added to the agent. The default
94 | behavior is to check for the presence of the files `.ssh/id_rsa`,
95 | `.ssh/id_dsa`, `.ssh/id_ecdsa` and `.ssh/id_ed25519` and load those files
96 | if present.
97 |
98 | ### Envoy with gpg-agent
99 |
100 | Keys are never implicitly added with `gpg-agent`. Instead, keys have to
101 | be explicitly added through either `envoy -a` or `ssh-add`. The agent
102 | will then continue track those identities automatically without having
103 | to be specified in the future.
104 |
105 | The agent will also still respect `~/.gnupg/gpg-agent.conf`. For
106 | example, to disable scdaemon, put `disable-scdaemon` in that file.
107 |
108 | Note that invoking envoy also updates gpg-agent with the current status,
109 | if available, of the tty and X. It is the same effect of running `echo
110 | UPDATESTARTUPTTY | gpg-connect-agent`. This may cause some odd behaviour
111 | with the pinentry. The pinentry may appear in an inappropriate place if
112 | this data becomes stale. This is a limitation of gpg-agent itself.
113 |
114 | ### Envoy's pam integration
115 |
116 | Envoy provides a pam module to load the agent into the environment at
117 | login instead of relying on `envoy -p`. To use it, edit
118 | `/etc/pam.d/login` and add:
119 |
120 | session optional pam_envoy.so
121 |
122 | Its also possible provide an optional argument to choose which agent
123 | type to start:
124 |
125 | session optional pam_envoy.so gpg-agent
126 |
127 | Envoy can also optionally unlock gpg-agent's keyring automatically with
128 | your password, but in order to do so it needs an auth token. To enable
129 | this, add:
130 |
131 | auth optional pam_envoy.so
132 | session optional pam_envoy.so
133 |
134 | Note that this relies on gpg-agent's passphrase presetting support. To
135 | enable this, ensure `allow-preset-passphrase` is also in
136 | `~/.gnupg/gpg-agent.conf`.
137 |
138 | ### Wrappers with envoy
139 |
140 | Envoy has support for wrapping commands through `envoy-exec`. The
141 | utility will connect to the daemon, setup the environment, and launch
142 | the provided command. For example:
143 |
144 | envoy-exec ssh git@github.com
145 |
146 | It is also possible to write an `envoy-exec` "script" to provide a
147 | terser wrapper.
148 |
149 | #!/usr/bin/envoy-exec
150 | /usr/bin/ssh
151 |
152 | This script will behave as if its been invoked as `envoy-exec ssh`.
153 |
154 | ### Cgroups support
155 |
156 | Having been unable to find a simple cgroups library targeted at
157 | embedding, I wrote my own. `cgroups.c` has been borrowed from my own
158 | project [here][cgroups].
159 |
160 | Any bugs with the cgroups support or confusions with terminology (I'm
161 | pretty sure my terminology is way off) should be reported there.
162 |
163 | [cgroups]: https://github.com/vodik/clique
164 |
--------------------------------------------------------------------------------
/src/envoy-exec.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 |
30 | #include "agents.h"
31 | #include "socket.h"
32 | #include "gpg-protocol.h"
33 | #include "util.h"
34 |
35 | static void source_agent_env(enum agent id)
36 | {
37 | struct agent_data_t data;
38 | int ret = envoy_get_agent(id, &data, AGENT_ENVIRON);
39 | if (ret < 0)
40 | warn("failed to fetch envoy agent");
41 |
42 | switch (data.status) {
43 | case ENVOY_STOPPED:
44 | case ENVOY_STARTED:
45 | case ENVOY_RUNNING:
46 | break;
47 | case ENVOY_FAILED:
48 | warnx("agent failed to start, check envoyd's log");
49 | return;
50 | case ENVOY_BADUSER:
51 | warnx("connection rejected, user is unauthorized to use this agent");
52 | return;
53 | }
54 |
55 | if (data.type == AGENT_GPG_AGENT) {
56 | _cleanup_gpg_ struct gpg_t *agent = gpg_agent_connection(data.gpg, NULL);
57 | gpg_update_tty(agent);
58 | }
59 |
60 | if (data.gpg[0])
61 | putenvf("GPG_AGENT_INFO=%s", data.gpg);
62 | putenvf("SSH_AUTH_SOCK=%s", data.sock);
63 | }
64 |
65 | static inline int safe_execv(const char *path, const char *exe_path, char *const argv[])
66 | {
67 | _cleanup_free_ char *real = realpath(path, NULL);
68 | if (real && streq(real, exe_path))
69 | return 0;
70 | return execv(path, argv);
71 | }
72 |
73 | #define WHITESPACE " \t\n\r"
74 |
75 | static char *strstrip(char *s)
76 | {
77 | char *e;
78 | s += strspn(s, WHITESPACE);
79 |
80 | for (e = strchr(s, 0); e > s; --e) {
81 | if (!strchr(WHITESPACE, e[-1]))
82 | break;
83 | }
84 |
85 | *e = 0;
86 | return s;
87 | }
88 |
89 | static char *extract_binary(char *path)
90 | {
91 | struct stat st;
92 | char *memblock, *command = NULL;
93 |
94 | _cleanup_close_ int fd = open(path, O_RDONLY);
95 | if (fd < 0) {
96 | if (errno == ENOENT)
97 | return NULL;
98 | err(EXIT_FAILURE, "failed to open script %s", path);
99 | }
100 |
101 | if (fstat(fd, &st) < 0)
102 | err(EXIT_FAILURE, "failed to stat %s", path);
103 |
104 | memblock = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED | MAP_POPULATE, fd, 0);
105 | madvise(memblock, st.st_size, MADV_WILLNEED | MADV_SEQUENTIAL);
106 |
107 | if (memblock[0] != '#' || memblock[1] != '!')
108 | goto error;
109 |
110 | memblock += strcspn(memblock, "\n");
111 | while (*memblock++ == '\n') {
112 | memblock += strspn(memblock, "#\t ");
113 | if (memblock[0] == '\0')
114 | break;
115 | else if (memblock[0] == '\n')
116 | continue;
117 |
118 | size_t eol = strcspn(memblock, "\n#");
119 | if (memblock[0] == '#') {
120 | memblock += eol;
121 | continue;
122 | } else {
123 | command = strndup(memblock, eol);
124 | goto error;
125 | }
126 | }
127 |
128 | error:
129 | memblock != MAP_FAILED ? munmap(memblock, st.st_size) : 0;
130 | return command ? strstrip(command) : NULL;
131 | }
132 |
133 | static _noreturn_ void exec_from_path(const char *cmd, const char *exe_path, char *argv[])
134 | {
135 | char *path = strdup(getenv("PATH"));
136 | if (!path)
137 | errx(EXIT_FAILURE, "command %s not found", cmd);
138 |
139 | char *saveptr = NULL, *segment = strtok_r(path, ":", &saveptr);
140 | for (; segment; segment = strtok_r(NULL, ":", &saveptr)) {
141 | char *full_path = joinpath(segment, cmd, NULL);
142 | safe_execv(full_path, exe_path, argv);
143 | free(full_path);
144 | }
145 |
146 | errx(EXIT_FAILURE, "command %s not found", cmd);
147 | }
148 |
149 | static _noreturn_ void exec_wrapper(int argc, char *argv[])
150 | {
151 | /* command + NULL + argv */
152 | const char *exe_path;
153 | char *new_argv[argc + 1];
154 | char *cmd = extract_binary(argv[0]);
155 | int i;
156 |
157 | if (cmd) {
158 | exe_path = argv[0];
159 | } else {
160 | cmd = argv[0];
161 | exe_path = realpath("/proc/self/exe", NULL);
162 | if (!exe_path)
163 | err(EXIT_FAILURE, "failed to resolve /proc/self/exe");
164 | }
165 |
166 | new_argv[0] = cmd;
167 | for (i = 1; i < argc; i++)
168 | new_argv[i] = argv[i];
169 | new_argv[argc] = NULL;
170 |
171 | if (cmd[0] == '/' || cmd[0] == '.') {
172 | safe_execv(cmd, exe_path, new_argv);
173 | // If the exec failed, the wrapper was called by its full path
174 | cmd = program_invocation_short_name;
175 | }
176 | exec_from_path(cmd, exe_path, new_argv);
177 | }
178 |
179 | static _noreturn_ void usage(FILE *out)
180 | {
181 | fprintf(out, "usage: %s [options]\n", program_invocation_short_name);
182 | fputs("Options:\n"
183 | " -h, --help display this help and exit\n"
184 | " -v, --version display version\n"
185 | " -t, --agent=AGENT set the agent to start\n", out);
186 |
187 | exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
188 | }
189 |
190 | int main(int argc, char *argv[])
191 | {
192 | enum agent type = AGENT_DEFAULT;
193 |
194 | static const struct option opts[] = {
195 | { "help", no_argument, 0, 'h' },
196 | { "version", no_argument, 0, 'v' },
197 | { "agent", required_argument, 0, 't' },
198 | { 0, 0, 0, 0 }
199 | };
200 |
201 | if (streq(program_invocation_short_name, "envoy-exec")) {
202 | while (true) {
203 | int opt = getopt_long(argc, argv, "+hvt:", opts, NULL);
204 | if (opt == -1)
205 | break;
206 |
207 | switch (opt) {
208 | case 'h':
209 | usage(stdout);
210 | break;
211 | case 'v':
212 | printf("%s %s\n", program_invocation_short_name, ENVOY_VERSION);
213 | return 0;
214 | case 't':
215 | type = lookup_agent(optarg);
216 | if (type < 0)
217 | errx(EXIT_FAILURE, "unknown agent: %s", optarg);
218 | break;
219 | default:
220 | usage(stderr);
221 | }
222 | }
223 |
224 | argc -= optind;
225 | argv += optind;
226 |
227 | if (argc == 0)
228 | usage(stderr);
229 | }
230 |
231 | source_agent_env(type);
232 | exec_wrapper(argc, argv);
233 | }
234 |
235 | // vim: et:sts=4:sw=4:cino=(0
236 |
--------------------------------------------------------------------------------
/src/pam_envoy.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #define PAM_SM_SESSION
19 | #define PAM_SM_AUTH
20 |
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 |
32 | #include
33 | #include
34 |
35 | #include "agents.h"
36 | #include "socket.h"
37 | #include "gpg-protocol.h"
38 | #include "util.h"
39 |
40 | #define PAM_LOG_ERR LOG_AUTHPRIV | LOG_ERR
41 | #define PAM_LOG_WARN LOG_AUTHPRIV | LOG_WARNING
42 |
43 | static _printf_(2, 3) int pam_setenv(pam_handle_t *ph, const char *fmt, ...)
44 | {
45 | va_list ap;
46 | int nbytes;
47 | _cleanup_free_ char *line = NULL;
48 |
49 | va_start(ap, fmt);
50 | nbytes = vasprintf(&line, fmt, ap);
51 | va_end(ap);
52 |
53 | if (nbytes < 0)
54 | return -1;
55 |
56 | pam_putenv(ph, line);
57 | return 0;
58 | }
59 |
60 | static int set_privileges(bool drop, uid_t *uid, gid_t *gid)
61 | {
62 | uid_t tmp_uid = geteuid();
63 | gid_t tmp_gid = getegid();
64 |
65 | if (drop && tmp_uid == *uid)
66 | return false;
67 |
68 | if (setegid(*gid) < 0 || seteuid(*uid) < 0) {
69 | if (drop) {
70 | syslog(PAM_LOG_ERR, "pam-envoy: failed to set privileges to uid=%d gid=%d: %s",
71 | *uid, *gid, strerror(errno));
72 | }
73 | return false;
74 | }
75 |
76 | *uid = tmp_uid;
77 | *gid = tmp_gid;
78 | return true;
79 | }
80 |
81 | static int pam_get_agent(struct agent_data_t *data, enum agent id, uid_t uid, gid_t gid)
82 | {
83 | bool dropped = set_privileges(true, &uid, &gid);
84 |
85 | int ret = envoy_get_agent(id, data, AGENT_ENVIRON);
86 | if (ret < 0)
87 | syslog(PAM_LOG_ERR, "failed to fetch agent: %s", strerror(errno));
88 |
89 | switch (data->status) {
90 | case ENVOY_STOPPED:
91 | case ENVOY_STARTED:
92 | case ENVOY_RUNNING:
93 | break;
94 | case ENVOY_FAILED:
95 | syslog(PAM_LOG_ERR, "agent failed to start, check envoyd's log");
96 | ret = -1;
97 | break;
98 | case ENVOY_BADUSER:
99 | syslog(PAM_LOG_ERR, "connection rejected, user is unauthorized to use this agent");
100 | ret = -1;
101 | break;
102 | }
103 |
104 | if (dropped)
105 | set_privileges(false, &uid, &gid);
106 |
107 | return ret;
108 | }
109 |
110 | /* PAM entry point for session creation */
111 | PAM_EXTERN int pam_sm_open_session(pam_handle_t *ph, int _unused_ flags,
112 | int argc, const char **argv)
113 | {
114 | struct agent_data_t data;
115 | const struct passwd *pwd;
116 | const char *user;
117 | enum agent id = AGENT_DEFAULT;
118 | int ret;
119 |
120 | ret = pam_get_user(ph, &user, NULL);
121 | if (ret != PAM_SUCCESS) {
122 | syslog(PAM_LOG_ERR, "pam-envoy: couldn't get the user name: %s",
123 | pam_strerror(ph, ret));
124 | return PAM_SERVICE_ERR;
125 | }
126 |
127 | pwd = getpwnam(user);
128 | if (!pwd) {
129 | syslog(PAM_LOG_ERR, "pam-envoy: error looking up user information: %s",
130 | strerror(errno));
131 | return PAM_SERVICE_ERR;
132 | }
133 |
134 | if (argc > 1) {
135 | syslog(PAM_LOG_WARN, "pam-envoy: too many arguments");
136 | return PAM_SUCCESS;
137 | } else if (argc == 1) {
138 | id = lookup_agent(argv[0]);
139 | }
140 |
141 | if (pam_get_agent(&data, id, pwd->pw_uid, pwd->pw_gid) < 0) {
142 | syslog(PAM_LOG_WARN, "pam-envoy: failed to get agent for user");
143 | return PAM_SUCCESS;
144 | }
145 |
146 | if (data.type == AGENT_GPG_AGENT) {
147 | _cleanup_gpg_ struct gpg_t *agent = gpg_agent_connection(data.gpg, pwd->pw_dir);
148 | gpg_update_tty(agent);
149 | }
150 |
151 | if (data.gpg[0]) {
152 | pam_setenv(ph, "GPG_AGENT_INFO=%s", data.gpg);
153 | }
154 |
155 | pam_setenv(ph, "SSH_AUTH_SOCK=%s", data.sock);
156 |
157 | return PAM_SUCCESS;
158 | }
159 |
160 | /* PAM entry point for session cleanup */
161 | PAM_EXTERN int pam_sm_close_session(pam_handle_t _unused_ *ph, int _unused_ flags,
162 | int _unused_ argc, const char _unused_ **argv)
163 | {
164 | return PAM_IGNORE;
165 | }
166 |
167 | /* PAM entry point for authentication verification */
168 | PAM_EXTERN int pam_sm_authenticate(pam_handle_t _unused_ *ph, int _unused_ flags,
169 | int _unused_ argc, const char _unused_ **argv)
170 | {
171 | struct agent_data_t data;
172 | const struct passwd *pwd;
173 | const char *user, *password;
174 | enum agent id = AGENT_DEFAULT;
175 | int ret;
176 |
177 | ret = pam_get_user(ph, &user, NULL);
178 | if (ret != PAM_SUCCESS) {
179 | syslog(PAM_LOG_ERR, "pam-envoy: couldn't get the user name: %s",
180 | pam_strerror(ph, ret));
181 | return PAM_SERVICE_ERR;
182 | }
183 |
184 | pwd = getpwnam(user);
185 | if (!pwd) {
186 | syslog(PAM_LOG_ERR, "pam-envoy: error looking up user information: %s",
187 | strerror(errno));
188 | return PAM_SERVICE_ERR;
189 | }
190 |
191 | /* Look up the password */
192 | ret = pam_get_item(ph, PAM_AUTHTOK, (const void**)&password);
193 | if (ret != PAM_SUCCESS || password == NULL) {
194 | if (ret == PAM_SUCCESS)
195 | syslog(PAM_LOG_WARN, "pam-envoy: no password is available for user");
196 | else
197 | syslog(PAM_LOG_WARN, "pam-envoy: no password is available for user: %s",
198 | pam_strerror(ph, ret));
199 | return PAM_SUCCESS;
200 | }
201 |
202 | if (pam_get_agent(&data, id, pwd->pw_uid, pwd->pw_gid) < 0) {
203 | syslog(PAM_LOG_WARN, "pam-envoy: failed to get agent for user");
204 | return PAM_SUCCESS;
205 | }
206 |
207 | if (data.type == AGENT_GPG_AGENT && agent_running(&data)) {
208 | _cleanup_gpg_ struct gpg_t *agent = gpg_agent_connection(data.gpg, pwd->pw_dir);
209 |
210 | if (password) {
211 | const struct fingerprint_t *fpt = gpg_keyinfo(agent);
212 | for (; fpt; fpt = fpt->next) {
213 | if (gpg_preset_passphrase(agent, fpt->fingerprint, -1, password) < 0)
214 | syslog(PAM_LOG_ERR, "failed to unlock '%s'", fpt->fingerprint);
215 | }
216 | }
217 | }
218 |
219 | return PAM_SUCCESS;
220 | }
221 |
222 | /* PAM entry point for setting user credentials (that is, to actually
223 | * establish the authenticated user's credentials to the service
224 | * provider) */
225 | PAM_EXTERN int pam_sm_setcred(pam_handle_t _unused_ *ph, int _unused_ flags,
226 | int _unused_ argc, const char _unused_ **argv)
227 | {
228 | return PAM_IGNORE;
229 | }
230 |
231 | /* PAM entry point for authentication token (password) changes */
232 | PAM_EXTERN int pam_sm_chauthtok(pam_handle_t _unused_ *ph, int _unused_ flags,
233 | int _unused_ argc, const char _unused_ **argv)
234 | {
235 | return PAM_IGNORE;
236 | }
237 |
238 | // vim: et:sts=4:sw=4:cino=(0
239 |
--------------------------------------------------------------------------------
/src/gpg-protocol.rl:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #include "gpg-protocol.h"
19 |
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 |
30 | #include "util.h"
31 |
32 | struct gpg_t {
33 | int fd;
34 | char buf[BUFSIZ];
35 |
36 | /* ragel parser state */
37 | int cs;
38 | char *p;
39 | char *pe;
40 | };
41 |
42 | static int gpg_buffer_refill(struct gpg_t *gpg)
43 | {
44 | ssize_t nbytes_r = read(gpg->fd, gpg->buf, sizeof(gpg->buf) - 1);
45 | if (nbytes_r < 0)
46 | return -1;
47 |
48 | gpg->buf[nbytes_r] = 0;
49 | gpg->p = gpg->buf;
50 | gpg->pe = gpg->buf + nbytes_r;
51 | return nbytes_r;
52 | }
53 |
54 | %%{
55 | machine status;
56 |
57 | action error {
58 | fprintf(stderr, "%s: gpg protocol error: %s", program_invocation_short_name, fpc);
59 | rc = -EIO;
60 | }
61 | action return { return rc; }
62 |
63 | newline = '\n';
64 | main := ( 'OK' | 'ERR' >error ) [^\n]* newline %return;
65 | }%%
66 |
67 | %%write data nofinal;
68 |
69 | static int gpg_check_return(struct gpg_t *gpg)
70 | {
71 | int rc = 0;
72 |
73 | %%access gpg->;
74 | %%variable p gpg->p;
75 | %%variable pe gpg->pe;
76 | %%write init;
77 |
78 | for (;;) {
79 | if (gpg->p == NULL || gpg->p == gpg->pe) {
80 | if (gpg_buffer_refill(gpg) <= 0)
81 | break;
82 | }
83 |
84 | char *eof = gpg->pe;
85 | %%write exec;
86 |
87 | if (gpg->cs == status_error) {
88 | warnx("error parsing gpg protocol");
89 | break;
90 | }
91 | }
92 |
93 | (void)status_en_main;
94 | return rc;
95 | }
96 |
97 | static _printf_(2, 3) int gpg_send_message(struct gpg_t *gpg, const char *fmt, ...)
98 | {
99 | va_list ap;
100 | int nbytes_r, rc;
101 |
102 | va_start(ap, fmt);
103 | nbytes_r = vdprintf(gpg->fd, fmt, ap);
104 | va_end(ap);
105 |
106 | rc = gpg_check_return(gpg);
107 | return rc == 0 ? nbytes_r : rc;
108 | }
109 |
110 | static int get_gpg_agent_socket(char *path, size_t len, const char *home)
111 | {
112 | const char *gnupghome = getenv("GNUPGHOME");
113 | if (gnupghome) {
114 | return snprintf(path, len, "%s/S.gpg-agent", gnupghome);
115 | } else {
116 | return snprintf(path, len, "%s/.gnupg/S.gpg-agent",
117 | home ? home : get_home_dir());
118 | }
119 | }
120 |
121 | struct gpg_t *gpg_agent_connection(const char *sock, const char *home)
122 | {
123 | union {
124 | struct sockaddr sa;
125 | struct sockaddr_un un;
126 | } sa;
127 | size_t len;
128 | socklen_t sa_len;
129 |
130 | int fd = socket(AF_UNIX, SOCK_STREAM, 0);
131 | if (fd < 0)
132 | return NULL;
133 |
134 | sa.un = (struct sockaddr_un){ .sun_family = AF_UNIX };
135 |
136 | if (!sock || !sock[0]) {
137 | len = get_gpg_agent_socket(sa.un.sun_path, sizeof(sa.un.sun_path), home);
138 | } else {
139 | len = strcspn(sock, ":");
140 | memcpy(&sa.un.sun_path, sock, len);
141 | }
142 |
143 | sa_len = len + sizeof(sa.un.sun_family);
144 | if (connect(fd, &sa.sa, sa_len) < 0) {
145 | close(fd);
146 | return NULL;
147 | }
148 |
149 | struct gpg_t *gpg = malloc(sizeof(struct gpg_t));
150 | *gpg = (struct gpg_t) { .fd = fd };
151 |
152 | if (gpg_check_return(gpg) < 0) {
153 | gpg_close(gpg);
154 | return NULL;
155 | }
156 |
157 | return gpg;
158 | }
159 |
160 | int gpg_reload_agent(struct gpg_t *gpg)
161 | {
162 | return gpg_send_message(gpg, "RELOADAGENT\n");
163 | }
164 |
165 | int gpg_update_tty(struct gpg_t *gpg)
166 | {
167 | const char *tty = ttyname(STDIN_FILENO);
168 | const char *term = getenv("TERM");
169 | const char *display = getenv("DISPLAY");
170 | const char *xauthority = getenv("XAUTHORITY");
171 |
172 | /* In this case, there's no information to update, so lets bail to
173 | * avoid clearing what's already there */
174 | if (!tty && !display)
175 | return 0;
176 |
177 | gpg_send_message(gpg, "RESET\n");
178 |
179 | if (tty) {
180 | gpg_send_message(gpg, "OPTION ttyname=%s\n", tty);
181 | gpg_send_message(gpg, "OPTION ttytype=%s\n", term ? term : "dumb");
182 | }
183 |
184 | if (display) {
185 | gpg_send_message(gpg, "OPTION display=%s\n", display);
186 |
187 | if (xauthority)
188 | gpg_send_message(gpg, "OPTION xauthority=%s\n", xauthority);
189 | else
190 | gpg_send_message(gpg, "OPTION xauthority=%s/.Xauthority\n", get_home_dir());
191 | }
192 |
193 | gpg_send_message(gpg, "UPDATESTARTUPTTY\n");
194 | return 0;
195 | }
196 |
197 | %%{
198 | machine keyinfo;
199 |
200 | action clear { keylen = 0; }
201 | action append { keygrip[keylen++] = fc; }
202 | action term {
203 | struct fingerprint_t *next = fpt;
204 | fpt = malloc(sizeof(struct fingerprint_t));
205 | *fpt = (struct fingerprint_t){
206 | .fingerprint = strndup(keygrip, keylen),
207 | .flags = keyflags,
208 | .next = next
209 | };
210 | keyflags = 0;
211 | }
212 |
213 | action flag {
214 | switch (fc) {
215 | case 'D':
216 | keyflags |= KEY_DISABLED;
217 | break;
218 | case 'S':
219 | keyflags |= KEY_SSHCONTROL;
220 | break;
221 | case 'c':
222 | keyflags |= KEY_CONFIRM;
223 | break;
224 | }
225 | }
226 |
227 | action error { fprintf(stderr, "%s: gpg protocol error: %s", program_invocation_short_name, fpc); }
228 | action return { return fpt; }
229 |
230 | newline = '\n';
231 | status = ( 'OK' | 'ERR' >error [^\n]* ) newline %return;
232 |
233 | # KEYGRIP is the keygrip
234 | keygrip = xdigit{40} >clear $append;
235 |
236 | # TYPE describes the type of the key:
237 | # 'D' - Regular key stored on disk,
238 | # 'T' - Key is stored on a smartcard (token),
239 | # 'X' - Unknown type,
240 | # '-' - Key is missing.
241 | type = [DTX\-];
242 |
243 | # SERIALNO is an ASCII string with the serial number of the
244 | # smartcard. If the serial number is not known a single
245 | # dash '-' is used instead.
246 | serialno = alpha+ | '-';
247 |
248 | # IDSTR is the IDSTR used to distinguish keys on a smartcard. If it
249 | # is not known a dash is used instead.
250 | idstr = [^\ ]+ | '-';
251 |
252 | # CACHED is 1 if the passphrase for the key was found in the key cache.
253 | # If not, a '-' is used instead.
254 | cached = [1\-];
255 |
256 | # PROTECTION describes the key protection type:
257 | # 'P' - The key is protected with a passphrase,
258 | # 'C' - The key is not protected,
259 | # '-' - Unknown protection.
260 | protection = [PC\-];
261 |
262 | # FPR returns the formatted ssh-style fingerprint of the key. It is only
263 | # printed if the option --ssh-fpr has been used. It defaults to '-'.
264 | fpr = '-';
265 |
266 | # TTL is the TTL in seconds for that key or '-' if n/a.
267 | ttl = digit+ | '-';
268 |
269 | # FLAGS is a word consisting of one-letter flags:
270 | # 'D' - The key has been disabled,
271 | # 'S' - The key is listed in sshcontrol (requires --with-ssh),
272 | # 'c' - Use of the key needs to be confirmed,
273 | # '-' - No flags given.
274 | flags = [DSc\-]+ >flag;
275 |
276 | # KEYINFO
277 | entry = 'S KEYINFO' space keygrip space type space serialno space idstr space
278 | cached space protection space fpr space ttl space
279 | flags newline
280 | @term;
281 |
282 | main := ( entry | status )*;
283 | }%%
284 |
285 | %%write data nofinal;
286 |
287 | struct fingerprint_t *gpg_keyinfo(struct gpg_t *gpg)
288 | {
289 | static const char message[] = "KEYINFO --list --with-ssh\n";
290 | struct fingerprint_t *fpt = NULL;
291 | char keygrip[40];
292 | size_t keylen = 0;
293 | enum keyflags keyflags = 0;
294 |
295 | ssize_t nbytes_w = write(gpg->fd, message, sizeof(message) - 1);
296 | if (nbytes_w < 0)
297 | return NULL;
298 |
299 | %%access gpg->;
300 | %%variable p gpg->p;
301 | %%variable pe gpg->pe;
302 | %%write init;
303 |
304 | for (;;) {
305 | if (gpg->p == NULL || gpg->p == gpg->pe) {
306 | if (gpg_buffer_refill(gpg) <= 0)
307 | break;
308 | }
309 |
310 | char *eof = gpg->pe;
311 | %%write exec;
312 |
313 | if (gpg->cs == keyinfo_error) {
314 | warnx("error parsing gpg protocol");
315 | break;
316 | }
317 | }
318 |
319 | (void)keyinfo_en_main;
320 | return fpt;
321 | }
322 |
323 | int gpg_preset_passphrase(struct gpg_t *gpg, const char *fingerprint, int timeout, const char *password)
324 | {
325 | static const char *hex_digits = "0123456789ABCDEF";
326 |
327 | if (!fingerprint)
328 | return -EINVAL;
329 |
330 | if (!password)
331 | return gpg_send_message(gpg, "PRESET_PASSPHRASE %s %d\n", fingerprint, timeout);
332 |
333 | size_t i, size = strlen(password);
334 | char bin_password[2 * size + 1];
335 |
336 | for(i = 0; i < size; i++) {
337 | bin_password[2 * i] = hex_digits[password[i] >> 4];
338 | bin_password[2 * i + 1] = hex_digits[password[i] & 0x0f];
339 | }
340 |
341 | bin_password[2 * size] = '\0';
342 | return gpg_send_message(gpg, "PRESET_PASSPHRASE %s %d %s\n", fingerprint, timeout, bin_password);
343 | }
344 |
345 | void free_fingerprints(struct fingerprint_t *fpt)
346 | {
347 | while (fpt) {
348 | struct fingerprint_t *node = fpt;
349 | fpt = fpt->next;
350 |
351 | free(node->fingerprint);
352 | free(node);
353 | }
354 | }
355 |
356 | void gpg_close(struct gpg_t *gpg)
357 | {
358 | close(gpg->fd);
359 | free(gpg);
360 | }
361 |
362 | // vim: et:sts=4:sw=4:cino=(0
363 |
--------------------------------------------------------------------------------
/src/envoy.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 |
32 | #include "agents.h"
33 | #include "socket.h"
34 | #include "gpg-protocol.h"
35 | #include "util.h"
36 |
37 | static struct termios old_termios;
38 |
39 | enum action {
40 | ACTION_PRINT,
41 | ACTION_NONE,
42 | ACTION_FORCE_ADD,
43 | ACTION_FORCE_EXPUNGE,
44 | ACTION_KILL,
45 | ACTION_RELOAD,
46 | ACTION_LIST,
47 | ACTION_UNLOCK,
48 | ACTION_INVALID
49 | };
50 |
51 | static void term_cleanup(void)
52 | {
53 | tcsetattr(STDIN_FILENO, TCSAFLUSH, &old_termios);
54 | }
55 |
56 | static ssize_t read_password(char **password)
57 | {
58 | struct termios new_termios;
59 | size_t len = 0;
60 | ssize_t nbytes_r;
61 |
62 | fputs("Password: ", stdout);
63 | fflush(stdout);
64 |
65 | if (tcgetattr(fileno(stdin), &old_termios) < 0)
66 | err(EXIT_FAILURE, "failed to get terminal attributes");
67 |
68 | atexit(term_cleanup);
69 |
70 | new_termios = old_termios;
71 | new_termios.c_lflag &= ~ECHO;
72 |
73 | if (tcsetattr(fileno(stdin), TCSAFLUSH, &new_termios) < 0)
74 | err(EXIT_FAILURE, "failed to set terminal attributes");
75 |
76 | nbytes_r = getline(password, &len, stdin);
77 | if (nbytes_r < 0)
78 | errx(EXIT_FAILURE, "failed to read password");
79 |
80 | (*password)[--nbytes_r] = 0;
81 | tcsetattr(fileno(stdin), TCSAFLUSH, &old_termios);
82 |
83 | putchar('\n');
84 | return nbytes_r;
85 | }
86 |
87 | static int get_agent(struct agent_data_t *data, enum agent id, bool start, bool env)
88 | {
89 | enum options options = start ? AGENT_DEFAULTS : AGENT_STATUS;
90 | if (env)
91 | options |= AGENT_ENVIRON;
92 |
93 | int ret = envoy_get_agent(id, data, options);
94 | if (ret < 0)
95 | err(EXIT_FAILURE, "failed to fetch agent");
96 |
97 | switch (data->status) {
98 | case ENVOY_STOPPED:
99 | case ENVOY_STARTED:
100 | case ENVOY_RUNNING:
101 | break;
102 | case ENVOY_FAILED:
103 | errx(EXIT_FAILURE, "agent failed to start, check envoyd's log");
104 | case ENVOY_BADUSER:
105 | errx(EXIT_FAILURE, "connection rejected, user is unauthorized to use this agent");
106 | }
107 |
108 | return ret;
109 | }
110 |
111 | static char *get_key_path(const char *home, const char *fragment)
112 | {
113 | /* path exists, add it */
114 | if (fragment[0] == '-' || access(fragment, F_OK) == 0)
115 | return strdup(fragment);
116 |
117 | /* assume it's a key in $HOME/.ssh */
118 | return joinpath(home, ".ssh", fragment, NULL);
119 | }
120 |
121 | static _noreturn_ void add_keys(char **keys, int count)
122 | {
123 | /* command + end-of-opts + NULL + keys */
124 | const char *home_dir = get_home_dir();
125 | char *args[count + 3];
126 | int i;
127 |
128 | args[0] = "/usr/bin/ssh-add";
129 | args[1] = "--";
130 |
131 | for (i = 0; i < count; i++)
132 | args[2 + i] = get_key_path(home_dir, keys[i]);
133 |
134 | args[2 + count] = NULL;
135 |
136 | execv(args[0], args);
137 | err(EXIT_FAILURE, "failed to launch ssh-add");
138 | }
139 |
140 | static _noreturn_ void expunge_keys(char **keys, int count)
141 | {
142 | /* command + -d + end-of-opts + NULL + keys */
143 | const char *home_dir = get_home_dir();
144 | char *args[count + 4];
145 | int i;
146 |
147 | args[0] = "/usr/bin/ssh-add";
148 | args[1] = "-d";
149 | args[2] = "--";
150 |
151 | for (i = 0; i < count; i++)
152 | args[3 + i] = get_key_path(home_dir, keys[i]);
153 |
154 | args[3 + count] = NULL;
155 |
156 | execv(args[0], args);
157 | err(EXIT_FAILURE, "failed to launch ssh-add");
158 | }
159 |
160 | static void print_sh_env(struct agent_data_t *data)
161 | {
162 | if (data->type == AGENT_GPG_AGENT && data->gpg[0])
163 | printf("export GPG_AGENT_INFO='%s'\n", data->gpg);
164 |
165 | printf("export SSH_AUTH_SOCK='%s'\n", data->sock);
166 | }
167 |
168 | static void print_csh_env(struct agent_data_t *data)
169 | {
170 | if (data->type == AGENT_GPG_AGENT && data->gpg[0])
171 | printf("setenv GPG_AGENT_INFO '%s';\n", data->gpg);
172 |
173 | printf("setenv SSH_AUTH_SOCK '%s';\n", data->sock);
174 | }
175 |
176 | static void print_fish_env(struct agent_data_t *data)
177 | {
178 | if (data->type == AGENT_GPG_AGENT && data->gpg[0])
179 | printf("set -x GPG_AGENT_INFO '%s';\n", data->gpg);
180 |
181 | printf("set -x SSH_AUTH_SOCK '%s';\n", data->sock);
182 | }
183 |
184 | static void source_env(struct agent_data_t *data)
185 | {
186 | if (data->type == AGENT_GPG_AGENT) {
187 | _cleanup_gpg_ struct gpg_t *agent = gpg_agent_connection(data->gpg, NULL);
188 | if (!agent)
189 | warn("failed to connect to GPG_AUTH_SOCK");
190 | else
191 | gpg_update_tty(agent);
192 | }
193 |
194 | putenvf("SSH_AUTH_SOCK=%s", data->sock);
195 | }
196 |
197 | static void reload_agent(struct agent_data_t *data)
198 | {
199 | if (data->type != AGENT_GPG_AGENT)
200 | errx(EXIT_FAILURE, "only gpg-agent supports this operation");
201 |
202 | _cleanup_gpg_ struct gpg_t *agent = gpg_agent_connection(data->gpg, NULL);
203 | if (!agent)
204 | err(EXIT_FAILURE, "failed to connect to GPG_AUTH_SOCK");
205 |
206 | gpg_reload_agent(agent);
207 | }
208 |
209 | static int unlock(const struct agent_data_t *data, char *password)
210 | {
211 | if (data->type != AGENT_GPG_AGENT)
212 | errx(EXIT_FAILURE, "only gpg-agent supports this operation");
213 |
214 | _cleanup_gpg_ struct gpg_t *agent = gpg_agent_connection(data->gpg, NULL);
215 | if (!agent)
216 | err(EXIT_FAILURE, "failed to connect to GPG_AUTH_SOCK");
217 |
218 | if (!password)
219 | read_password(&password);
220 |
221 | const struct fingerprint_t *fgpt = gpg_keyinfo(agent);
222 | for (; fgpt; fgpt = fgpt->next) {
223 | if (fgpt->flags & KEY_DISABLED)
224 | continue;
225 |
226 | if (gpg_preset_passphrase(agent, fgpt->fingerprint, -1, password) < 0) {
227 | warnx("failed to unlock key '%s'", fgpt->fingerprint);
228 | return 1;
229 | }
230 | }
231 |
232 | return 0;
233 | }
234 |
235 | static _noreturn_ void usage(FILE *out)
236 | {
237 | fprintf(out, "usage: %s [options] [key ...]\n", program_invocation_short_name);
238 | fputs("Options:\n"
239 | " -h, --help display this help\n"
240 | " -v, --version display version\n"
241 | " -d, --defer defer adding keys until the next envoy invocation\n"
242 | " -a, --add add private key identities\n"
243 | " -x, --expunge remove private key identities\n"
244 | " -k, --kill kill the running agent\n"
245 | " -r, --reload reload the agent (gpg-agent only)\n"
246 | " -l, --list list fingerprints of all loaded identities\n"
247 | " -u, --unlock=[PASS] unlock the agent's keyring (gpg-agent only)\n"
248 | " -p, --print print out environmental arguments\n"
249 | " -s, --sh print sh style commands\n"
250 | " -c, --csh print csh style commands\n"
251 | " -f, --fish print fish style commands\n"
252 | " -t, --agent=AGENT set the preferred agent to start\n", out);
253 |
254 | exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
255 | }
256 |
257 | int main(int argc, char *argv[])
258 | {
259 | bool source = true;
260 | bool defer = false;
261 | struct agent_data_t data;
262 | char *password = NULL;
263 | enum action verb = ACTION_NONE;
264 | enum agent type = AGENT_DEFAULT;
265 | void (*print_env)(struct agent_data_t *data) = print_sh_env;
266 |
267 | static const struct option opts[] = {
268 | { "help", no_argument, 0, 'h' },
269 | { "version", no_argument, 0, 'v' },
270 | { "defer", no_argument, 0, 'd' },
271 | { "add", no_argument, 0, 'a' },
272 | { "expunge", no_argument, 0, 'x' },
273 | { "kill", no_argument, 0, 'k' },
274 | { "reload", no_argument, 0, 'r' },
275 | { "list", no_argument, 0, 'l' },
276 | { "unlock", optional_argument, 0, 'u' },
277 | { "print", no_argument, 0, 'p' },
278 | { "sh", no_argument, 0, 's' },
279 | { "csh", no_argument, 0, 'c' },
280 | { "fish", no_argument, 0, 'f' },
281 | { "agent", required_argument, 0, 't' },
282 | { 0, 0, 0, 0 }
283 | };
284 |
285 | while (true) {
286 | int opt = getopt_long(argc, argv, "hvdaxkrlu::pscft:", opts, NULL);
287 | if (opt == -1)
288 | break;
289 |
290 | switch (opt) {
291 | case 'h':
292 | usage(stdout);
293 | break;
294 | case 'v':
295 | printf("%s %s\n", program_invocation_short_name, ENVOY_VERSION);
296 | return 0;
297 | case 'd':
298 | defer = true;
299 | break;
300 | case 'a':
301 | verb = ACTION_FORCE_ADD;
302 | defer = false;
303 | break;
304 | case 'x':
305 | verb = ACTION_FORCE_EXPUNGE;
306 | defer = false;
307 | break;
308 | case 'k':
309 | verb = ACTION_KILL;
310 | source = false;
311 | break;
312 | case 'r':
313 | verb = ACTION_RELOAD;
314 | source = false;
315 | break;
316 | case 'l':
317 | verb = ACTION_LIST;
318 | break;
319 | case 'u':
320 | verb = ACTION_UNLOCK;
321 | password = optarg;
322 | break;
323 | case 'p':
324 | verb = ACTION_PRINT;
325 | break;
326 | case 's':
327 | print_env = print_sh_env;
328 | break;
329 | case 'c':
330 | print_env = print_csh_env;
331 | break;
332 | case 'f':
333 | print_env = print_fish_env;
334 | break;
335 | case 't':
336 | type = lookup_agent(optarg);
337 | if (type < 0)
338 | errx(EXIT_FAILURE, "unknown agent: %s", optarg);
339 | break;
340 | default:
341 | usage(stderr);
342 | }
343 | }
344 |
345 | if (get_agent(&data, type, source, defer) < 0)
346 | errx(EXIT_FAILURE, "recieved no data, did the agent fail to start?");
347 |
348 | if (data.status == ENVOY_STOPPED)
349 | return 0;
350 |
351 | if (source)
352 | source_env(&data);
353 |
354 | switch (verb) {
355 | case ACTION_PRINT:
356 | print_env(&data);
357 | /* fall through */
358 | case ACTION_NONE:
359 | if (data.type == AGENT_GPG_AGENT || !agent_started(&data))
360 | break;
361 | if (defer)
362 | break;
363 | /* fall through */
364 | case ACTION_FORCE_ADD:
365 | add_keys(&argv[optind], argc - optind);
366 | break;
367 | case ACTION_FORCE_EXPUNGE:
368 | expunge_keys(&argv[optind], argc - optind);
369 | break;
370 | case ACTION_KILL:
371 | if (envoy_kill_agent(type) < 0)
372 | errx(EXIT_FAILURE, "failed to kill agent");
373 | break;
374 | case ACTION_RELOAD:
375 | reload_agent(&data);
376 | break;
377 | case ACTION_LIST:
378 | execlp("ssh-add", "ssh-add", "-l", NULL);
379 | err(EXIT_FAILURE, "failed to launch ssh-add");
380 | case ACTION_UNLOCK:
381 | unlock(&data, password);
382 | break;
383 | default:
384 | break;
385 | }
386 |
387 | return 0;
388 | }
389 |
390 | // vim: et:sts=4:sw=4:cino=(0
391 |
--------------------------------------------------------------------------------
/src/envoyd.c:
--------------------------------------------------------------------------------
1 | /*
2 | * This program is free software; you can redistribute it and/or modify
3 | * it under the terms of the GNU General Public License as published by
4 | * the Free Software Foundation; either version 3 of the License, or
5 | * (at your option) any later version.
6 | *
7 | * This program is distributed in the hope that it will be useful,
8 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
9 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10 | * GNU General Public License for more details.
11 | *
12 | * You should have received a copy of the GNU General Public License
13 | * along with this program. If not, see .
14 | *
15 | * Copyright (C) Simon Gomizelj, 2015
16 | */
17 |
18 | #include
19 | #include
20 | #include
21 | #include
22 | #include
23 | #include
24 | #include
25 | #include
26 | #include
27 | #include
28 | #include
29 | #include
30 | #include
31 | #include
32 | #include
33 | #include
34 | #include
35 | #include
36 |
37 | #include "agents.h"
38 | #include "socket.h"
39 | #include "dbus.h"
40 | #include "util.h"
41 |
42 | struct agent_node_t {
43 | uid_t uid;
44 | char *scope, *slice;
45 | struct agent_data_t d;
46 | struct agent_node_t *next;
47 | };
48 |
49 | static sd_bus *bus = NULL;
50 | static enum agent default_type = AGENT_SSH_AGENT;
51 | static struct agent_node_t *agents = NULL;
52 | static bool sd_activated = false;
53 | static bool multiuser_mode;
54 | static uid_t server_uid;
55 |
56 | static union agent_environ_t {
57 | struct {
58 | char *path;
59 | char *home;
60 | char *gnupghome;
61 | } arg;
62 | char *const env[4];
63 | } agent_env = {
64 | .env = { 0 }
65 | };
66 |
67 | static void cleanup(int fd)
68 | {
69 | struct agent_node_t *node;
70 |
71 | if (!sd_activated) {
72 | close(fd);
73 | unlink_envoy_socket();
74 | }
75 |
76 | for (node = agents; node; node = node->next) {
77 | if (node->d.unit_path[0])
78 | stop_unit(bus, node->d.unit_path);
79 | }
80 | }
81 |
82 | static bool unit_running(struct agent_data_t *data)
83 | {
84 | if (data->unit_path[0]) {
85 | _cleanup_free_ char *state = get_unit_state(bus, data->unit_path);
86 | return streq(state, "running");
87 | }
88 |
89 | return false;
90 | }
91 |
92 | static void init_agent_environ(void)
93 | {
94 | extern char **environ;
95 | char *path = NULL, *gnupghome = NULL;
96 | int i;
97 |
98 | for (i = 0; environ[i]; ++i) {
99 | if (strneq(environ[i], "PATH=", 5))
100 | path = environ[i];
101 | else if (strneq(environ[i], "GNUPGHOME=", 10))
102 | gnupghome = environ[i];
103 | }
104 |
105 | agent_env.arg.path = path ? path : "PATH=/usr/local/bin:/usr/bin/:/bin";
106 |
107 | if (!gnupghome)
108 | return;
109 | if (!multiuser_mode)
110 | agent_env.arg.gnupghome = gnupghome;
111 | else
112 | fprintf(stderr, "warning: running as root and GNUPGHOME is set; ignoring.\n");
113 | }
114 |
115 | static void parse_agentdata_line(char *val, struct agent_data_t *data)
116 | {
117 | val[strcspn(val, ";")] = 0;
118 |
119 | size_t sep = strcspn(val, "=");
120 | if (val[sep] == '\0')
121 | return;
122 |
123 | if (strneq(val, "SSH_AUTH_SOCK", sep))
124 | strncpy(data->sock, &val[sep + 1], sizeof(data->sock) - 1);
125 | else if (strneq(val, "GPG_AGENT_INFO", sep))
126 | strncpy(data->gpg, &val[sep + 1], sizeof(data->gpg) - 1);
127 | }
128 |
129 | static int parse_agentdata(int fd, struct agent_data_t *data)
130 | {
131 | char buf[BUFSIZ];
132 |
133 | ssize_t bytes_r = read(fd, buf, sizeof(buf) - 1);
134 | if (bytes_r <= 0)
135 | return bytes_r;
136 |
137 | buf[bytes_r] = '\0';
138 | char *line = &buf[0];
139 |
140 | while (line < &buf[bytes_r]) {
141 | size_t newline = strcspn(line, "\n");
142 |
143 | line[newline] = 0;
144 | parse_agentdata_line(line, data);
145 | line += newline + 1;
146 | }
147 |
148 | if (data->sock[0] == 0) {
149 | fprintf(stderr, "Did not receive SSH_AUTH_SOCK from agent, bailing...\n");
150 | return -1;
151 | }
152 |
153 | return 0;
154 | }
155 |
156 | static int drop_permissions(uid_t uid, gid_t gid)
157 | {
158 | if (setgroups(0, NULL) < 0)
159 | return -1;
160 |
161 | if (setresgid(gid, gid, gid) < 0 || setresuid(uid, uid, uid) < 0)
162 | return -1;
163 |
164 | return 0;
165 | }
166 |
167 | static _noreturn_ void exec_agent(const struct agent_t *agent, int uid)
168 | {
169 | struct passwd *pwd = getpwuid(uid);
170 | if (pwd == NULL || pwd->pw_dir == NULL)
171 | err(EXIT_FAILURE, "failed to lookup passwd entry");
172 |
173 | /* setup the most minimal environment */
174 | safe_asprintf(&agent_env.arg.home, "HOME=%s", pwd->pw_dir);
175 |
176 | execve(agent->argv[0], agent->argv, agent_env.env);
177 | err(EXIT_FAILURE, "failed to start %s", agent->name[0]);
178 | }
179 |
180 | static int run_agent(struct agent_node_t *node, uid_t uid, gid_t gid)
181 | {
182 | struct agent_data_t *data = &node->d;
183 | const struct agent_t *agent = &Agent[data->type];
184 | int fd[2], stat = 0, rc = 0;
185 | _cleanup_free_ char *path = NULL;
186 |
187 | *data = (struct agent_data_t){
188 | .status = ENVOY_STARTED,
189 | .type = data->type
190 | };
191 |
192 | printf("Starting %s for uid=%u.\n", agent->name[0], uid);
193 | fflush(stdout);
194 |
195 | if (pipe2(fd, O_CLOEXEC) < 0)
196 | err(EXIT_FAILURE, "failed to create pipe");
197 |
198 | pid_t pid = fork();
199 | switch (pid) {
200 | case -1:
201 | err(EXIT_FAILURE, "failed to fork");
202 | break;
203 | case 0:
204 | unblock_signals();
205 | dup2(fd[1], STDOUT_FILENO);
206 |
207 | bus = get_connection(server_uid);
208 | start_transient_unit(bus, node->scope, node->slice,
209 | "Envoy agent monitoring scope");
210 |
211 | if (drop_permissions(uid, gid) < 0) {
212 | err(EXIT_FAILURE, "unable to drop permissions to uid=%u gid=%u\n", uid, gid);
213 | }
214 |
215 | exec_agent(agent, uid);
216 | break;
217 | default:
218 | break;
219 | }
220 |
221 | if (wait(&stat) < 1)
222 | err(EXIT_FAILURE, "failed to get process status");
223 |
224 | if (stat) {
225 | rc = -1;
226 |
227 | if (WIFEXITED(stat))
228 | fprintf(stderr, "%s exited with status %d.\n",
229 | agent->name[0], WEXITSTATUS(stat));
230 | if (WIFSIGNALED(stat))
231 | fprintf(stderr, "%s terminated with signal %d.\n",
232 | agent->name[0], WTERMSIG(stat));
233 |
234 | goto cleanup;
235 | }
236 |
237 | rc = parse_agentdata(fd[0], data);
238 | if (rc < 0) {
239 | fprintf(stderr, "Failed to parse %s output\n", agent->name[0]);
240 | goto cleanup;
241 | }
242 |
243 | path = get_unit(bus, node->scope);
244 | strncpy(data->unit_path, path, sizeof(data->unit_path) - 1);
245 |
246 | cleanup:
247 | close(fd[0]);
248 | close(fd[1]);
249 |
250 | if (rc < 0) {
251 | data->unit_path[0] = '\0';
252 | data->status = ENVOY_FAILED;
253 | }
254 |
255 | return rc;
256 | }
257 |
258 | static int get_socket(void)
259 | {
260 | int fd, n;
261 |
262 | n = sd_listen_fds(0);
263 | if (n > 1)
264 | err(EXIT_FAILURE, "too many file descriptors received");
265 | else if (n == 1) {
266 | fd = SD_LISTEN_FDS_START;
267 | sd_activated = true;
268 | } else {
269 | union {
270 | struct sockaddr sa;
271 | struct sockaddr_un un;
272 | } sa;
273 | socklen_t sa_len;
274 |
275 | fd = socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
276 | if (fd < 0)
277 | err(EXIT_FAILURE, "couldn't create socket");
278 |
279 | sa_len = init_envoy_socket(&sa.un);
280 | if (bind(fd, &sa.sa, sa_len) < 0)
281 | err(EXIT_FAILURE, "failed to bind");
282 |
283 | if (sa.un.sun_path[0] != '\0' && chmod(sa.un.sun_path, multiuser_mode ? 0777 : 0700) < 0)
284 | err(EXIT_FAILURE, "failed to chmod");
285 |
286 | if (listen(fd, SOMAXCONN) < 0)
287 | err(EXIT_FAILURE, "failed to listen");
288 | }
289 |
290 | return fd;
291 | }
292 |
293 | static char *get_scope_name(enum agent type, uid_t uid)
294 | {
295 | char *scope_name;
296 | safe_asprintf(&scope_name, "envoy-%s-monitor-%d.scope", Agent[type].name[0], uid);
297 | return scope_name;
298 | }
299 |
300 | static struct agent_node_t *get_agent_entry(struct agent_node_t **list, enum agent type, uid_t uid)
301 | {
302 | struct agent_node_t *node;
303 |
304 | for (node = *list; node; node = node->next) {
305 | if (node->d.type == type && node->uid == uid)
306 | return node;
307 | }
308 |
309 | node = malloc(sizeof(struct agent_node_t));
310 | *node = (struct agent_node_t){
311 | .uid = uid,
312 | .next = *list,
313 | .d = (struct agent_data_t){ .type = type }
314 | };
315 |
316 | if (sd_activated)
317 | node->slice = multiuser_mode ? "system-envoy.slice" : "envoy.slice";
318 | node->scope = get_scope_name(type, uid);
319 |
320 | *list = node;
321 | return node;
322 | }
323 |
324 | static void send_agent(int fd, struct agent_data_t *agent, bool close_sock)
325 | {
326 | if (write(fd, agent, sizeof(struct agent_data_t)) < 0)
327 | err(EXIT_FAILURE, "failed to write agent data");
328 | if (close_sock)
329 | close(fd);
330 | }
331 |
332 | static void send_message(int fd, enum status status, bool close_sock)
333 | {
334 | struct agent_data_t d = { .status = status };
335 | send_agent(fd, &d, close_sock);
336 | }
337 |
338 | static void accept_conn(int fd)
339 | {
340 | struct ucred cred;
341 | struct agent_request_t req;
342 | socklen_t cred_len = sizeof(struct ucred);
343 |
344 | int cfd = accept4(fd, NULL, NULL, SOCK_CLOEXEC);
345 | if (cfd < 0)
346 | err(EXIT_FAILURE, "failed to accept connection");
347 |
348 | int nbytes_r = read(cfd, &req, sizeof(struct agent_request_t));
349 | if (nbytes_r < 0)
350 | err(EXIT_FAILURE, "couldn't read agent type to start");
351 |
352 | if (getsockopt(cfd, SOL_SOCKET, SO_PEERCRED, &cred, &cred_len) < 0)
353 | err(EXIT_FAILURE, "couldn't obtain credentials from unix domain socket");
354 |
355 | if (server_uid != 0 && server_uid != cred.uid) {
356 | fprintf(stderr, "Connection from uid=%u rejected.\n", cred.uid);
357 | send_message(cfd, ENVOY_BADUSER, true);
358 | return;
359 | }
360 |
361 | enum agent agent = req.type == AGENT_DEFAULT ? default_type : req.type;
362 | struct agent_node_t *node = get_agent_entry(&agents, agent, cred.uid);
363 |
364 | if (unit_running(&node->d)) {
365 | if (req.opts & AGENT_KILL && node->d.unit_path[0]) {
366 | printf("Terminating %s for uid=%u.\n",
367 | Agent[node->d.type].name[0], cred.uid);
368 | fflush(stdout);
369 |
370 | stop_unit(bus, node->d.unit_path);
371 | node->d.unit_path[0] = '\0';
372 | node->d.status = ENVOY_STOPPED;
373 | }
374 | } else {
375 | if (req.opts & AGENT_STATUS) {
376 | send_message(cfd, ENVOY_STOPPED, true);
377 | return;
378 | }
379 |
380 | if (node->d.status != ENVOY_STOPPED) {
381 | printf("Agent %s for uid=%u has terminated. Restarting...\n",
382 | Agent[node->d.type].name[0], cred.uid);
383 | fflush(stdout);
384 | }
385 |
386 | run_agent(node, cred.uid, cred.gid);
387 | }
388 |
389 | send_agent(cfd, &node->d, true);
390 |
391 | if (!(req.opts & AGENT_ENVIRON) && node->d.status == ENVOY_STARTED)
392 | node->d.status = ENVOY_RUNNING;
393 | }
394 |
395 | static int loop(int server_sock)
396 | {
397 | int sfd = get_signalfd(SIGTERM, SIGINT, SIGQUIT, NULL);
398 | if (sfd < 0)
399 | err(EXIT_FAILURE, "failed to create signalfd");
400 |
401 | struct pollfd fds[] = {
402 | { .fd = server_sock, .events = POLLIN },
403 | { .fd = sfd, .events = POLLIN }
404 | };
405 | const size_t fd_count = sizeof(fds) / sizeof(fds[0]);
406 |
407 | while (true) {
408 | int ret = poll(fds, fd_count, -1);
409 |
410 | if (ret == 0) {
411 | continue;
412 | } else if (ret < 0) {
413 | if (errno == EINTR)
414 | continue;
415 | err(EXIT_FAILURE, "failed to poll");
416 | }
417 |
418 | if (fds[0].revents & POLLHUP)
419 | close(fds[0].fd);
420 | else if (fds[0].revents & POLLIN)
421 | accept_conn(server_sock);
422 | else if (fds[1].revents & POLLIN) {
423 | struct signalfd_siginfo si;
424 | ssize_t nbytes_r = read(sfd, &si, sizeof(si));
425 | if (nbytes_r < 0)
426 | err(EXIT_FAILURE, "failed to read signal");
427 |
428 | switch (si.ssi_signo) {
429 | case SIGINT:
430 | case SIGTERM:
431 | case SIGQUIT:
432 | cleanup(server_sock);
433 | exit(EXIT_SUCCESS);
434 | }
435 | }
436 | }
437 |
438 | return 0;
439 | }
440 |
441 | static _noreturn_ void usage(FILE *out)
442 | {
443 | fprintf(out, "usage: %s [options]\n", program_invocation_short_name);
444 | fputs("Options:\n"
445 | " -h, --help display this help and exit\n"
446 | " -v, --version display version\n"
447 | " -t, --agent=AGENT set the agent to start\n", out);
448 |
449 | exit(out == stderr ? EXIT_FAILURE : EXIT_SUCCESS);
450 | }
451 |
452 | int main(int argc, char *argv[])
453 | {
454 | int server_sock;
455 |
456 | static const struct option opts[] = {
457 | { "help", no_argument, 0, 'h' },
458 | { "version", no_argument, 0, 'v' },
459 | { "agent", required_argument, 0, 't' },
460 | { 0, 0, 0, 0 }
461 | };
462 |
463 | while (true) {
464 | int opt = getopt_long(argc, argv, "hvt:", opts, NULL);
465 | if (opt == -1)
466 | break;
467 |
468 | switch (opt) {
469 | case 'h':
470 | usage(stdout);
471 | break;
472 | case 'v':
473 | printf("%s %s\n", program_invocation_short_name, ENVOY_VERSION);
474 | return 0;
475 | case 't':
476 | default_type = lookup_agent(optarg);
477 | if (default_type < 0)
478 | errx(EXIT_FAILURE, "unknown agent: %s", optarg);
479 | break;
480 | default:
481 | usage(stderr);
482 | }
483 | }
484 |
485 | server_uid = geteuid();
486 | multiuser_mode = server_uid == 0;
487 |
488 | init_agent_environ();
489 | server_sock = get_socket();
490 | bus = get_connection(server_uid);
491 |
492 | return loop(server_sock);
493 | }
494 |
495 | // vim: et:sts=4:sw=4:cino=(0
496 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------