-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvaultexec.py
More file actions
193 lines (163 loc) · 6.9 KB
/
Copy pathvaultexec.py
File metadata and controls
193 lines (163 loc) · 6.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#!/usr/bin/env python3
"""vaultexec: resolve secret:// references at spawn time, then exec the real command.
Env var values and command arguments may contain secret://SERVICE/ACCOUNT
(keyring:// is an alias) references. Each resolves against the first backend
that knows it; the real command is then exec'd so plaintext exists only in the
child process environment — never in config files, never in a wrapper process.
"""
import getpass
import os
import re
import shutil
import subprocess
import sys
__version__ = "0.2.1"
REF = re.compile(r"(?:secret|keyring)://([A-Za-z0-9._-]+)/([A-Za-z0-9._@-]+)")
USAGE = """\
usage: vaultexec [--] CMD [ARGS...] resolve refs in env + args, then exec CMD
vaultexec get REF resolve one reference and print it
vaultexec set SERVICE ACCOUNT store a secret (stdin or hidden prompt)
vaultexec --version
References look like secret://SERVICE/ACCOUNT; see README for backends."""
def _run(cmd, input=None):
return subprocess.run(cmd, capture_output=True, text=True, input=input)
def keychain_get(service, account):
p = _run(["security", "find-generic-password", "-s", service, "-a", account, "-w"])
return p.stdout.rstrip("\n") if p.returncode == 0 else None
def secretservice_get(service, account):
if not shutil.which("secret-tool"):
return None
p = _run(["secret-tool", "lookup", "service", service, "account", account])
return p.stdout.rstrip("\n") if p.returncode == 0 and p.stdout else None
def systemdcreds_get(service, account):
path = "/etc/credstore.encrypted/%s.%s.cred" % (service, account)
if not shutil.which("systemd-creds") or not os.path.exists(path):
return None
p = _run(["systemd-creds", "decrypt", path, "-"])
return p.stdout.rstrip("\n") if p.returncode == 0 else None
def age_get(service, account):
store = os.environ.get("VAULTEXEC_AGE_FILE",
os.path.expanduser("~/.config/vaultexec/secrets.age"))
ident = os.environ.get("VAULTEXEC_AGE_IDENTITY",
os.path.expanduser("~/.config/vaultexec/identity.txt"))
if not shutil.which("age") or not os.path.exists(store):
return None
p = _run(["age", "-d", "-i", ident, store])
if p.returncode != 0:
return None
for line in p.stdout.splitlines():
key, sep, value = line.partition("=")
if sep and key.strip() == "%s/%s" % (service, account):
return value
return None
def file_get(service, account):
name = "%s.%s" % (service, account)
for d in (os.environ.get("CREDENTIALS_DIRECTORY"), "/run/secrets"):
if not d:
continue
path = os.path.join(d, name)
if os.path.isfile(path):
with open(path) as f:
return f.read().rstrip("\n")
return None
BACKENDS = {
"keychain": keychain_get,
"file": file_get,
"secret-service": secretservice_get,
"systemd-creds": systemdcreds_get,
"age": age_get,
}
def backend_chain():
forced = os.environ.get("VAULTEXEC_BACKEND")
if forced:
names = [n.strip() for n in forced.split(",") if n.strip()]
unknown = [n for n in names if n not in BACKENDS]
if unknown:
raise LookupError("unknown backend in VAULTEXEC_BACKEND: %s (known: %s)"
% (", ".join(unknown), ", ".join(BACKENDS)))
return [(n, BACKENDS[n]) for n in names]
if sys.platform == "darwin":
return [("keychain", keychain_get)]
return [(n, BACKENDS[n]) for n in ("file", "secret-service", "systemd-creds", "age")]
def resolve(text, chain, cache):
def lookup(match):
key = (match.group(1), match.group(2))
if key not in cache:
for _, backend in chain:
value = backend(*key)
if value is not None:
cache[key] = value
break
else:
raise LookupError("could not resolve %s (tried: %s)"
% (match.group(0), ", ".join(n for n, _ in chain)))
return cache[key]
return REF.sub(lookup, text)
def cmd_set(service, account):
if not (re.fullmatch(r"[A-Za-z0-9._-]+", service)
and re.fullmatch(r"[A-Za-z0-9._@-]+", account)):
raise LookupError("service/account may only contain letters, digits, "
". _ - (account may also contain @)")
if sys.stdin.isatty():
value = getpass.getpass("Secret value for %s/%s: " % (service, account))
else:
value = sys.stdin.read().rstrip("\n")
if not value:
raise LookupError("empty secret value")
if sys.platform == "darwin":
# secret goes to `security -i` over stdin so it never appears in any argv
if "\n" in value:
raise LookupError("multi-line values not supported on the keychain backend")
quoted = '"%s"' % value.replace("\\", "\\\\").replace('"', '\\"')
p = _run(["security", "-i"],
input="add-generic-password -U -s %s -a %s -w %s\n"
% (service, account, quoted))
elif shutil.which("secret-tool"):
p = _run(["secret-tool", "store",
"--label", "vaultexec: %s/%s" % (service, account),
"service", service, "account", account], input=value)
else:
raise LookupError("no writable backend here; "
"see README for systemd-creds and age setup")
if p.returncode != 0:
raise LookupError("store failed: %s" % (p.stderr or "").strip())
print("stored secret://%s/%s" % (service, account), file=sys.stderr)
def main(argv=None):
argv = sys.argv[1:] if argv is None else list(argv)
if not argv or argv[0] in ("-h", "--help"):
print(USAGE, file=sys.stderr)
sys.exit(2 if not argv else 0)
if argv[0] == "--version":
print("vaultexec %s" % __version__)
sys.exit(0)
try:
if argv[0] == "get":
if len(argv) != 2 or not REF.search(argv[1]):
print(USAGE, file=sys.stderr)
sys.exit(2)
print(resolve(argv[1], backend_chain(), {}))
sys.exit(0)
if argv[0] == "set":
if len(argv) != 3:
print(USAGE, file=sys.stderr)
sys.exit(2)
cmd_set(argv[1], argv[2])
sys.exit(0)
if argv[0] == "--":
argv = argv[1:]
if not argv:
print(USAGE, file=sys.stderr)
sys.exit(2)
chain, cache = backend_chain(), {}
env = {k: resolve(v, chain, cache) for k, v in os.environ.items()}
args = [resolve(a, chain, cache) for a in argv]
except LookupError as e:
print("vaultexec: %s" % e, file=sys.stderr)
sys.exit(2)
try:
os.execvpe(args[0], args, env)
except FileNotFoundError:
print("vaultexec: command not found: %s" % args[0], file=sys.stderr)
sys.exit(127)
if __name__ == "__main__":
main()