sesscred 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sesscred/__init__.py +153 -0
- sesscred/askpass.py +412 -0
- sesscred/cache/__init__.py +211 -0
- sesscred/cache/keyring.py +420 -0
- sesscred/cache/memory.py +81 -0
- sesscred/cli.py +594 -0
- sesscred/completion.py +248 -0
- sesscred/config.py +773 -0
- sesscred/engine.py +501 -0
- sesscred/errors.py +91 -0
- sesscred/hardening.py +137 -0
- sesscred/policy.py +50 -0
- sesscred/process.py +510 -0
- sesscred/prompt/__init__.py +182 -0
- sesscred/prompt/gui.py +276 -0
- sesscred/prompt/tty.py +198 -0
- sesscred/requester.py +187 -0
- sesscred/runtime.py +240 -0
- sesscred/schema.py +220 -0
- sesscred/sources/__init__.py +276 -0
- sesscred/sources/keepassxc.py +400 -0
- sesscred/sources/kpxc.py +457 -0
- sesscred/values.py +279 -0
- sesscred-0.1.0.dist-info/METADATA +238 -0
- sesscred-0.1.0.dist-info/RECORD +29 -0
- sesscred-0.1.0.dist-info/WHEEL +5 -0
- sesscred-0.1.0.dist-info/entry_points.txt +6 -0
- sesscred-0.1.0.dist-info/licenses/LICENSE +674 -0
- sesscred-0.1.0.dist-info/top_level.txt +1 -0
sesscred/__init__.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2026 Juan D. Martin
|
|
3
|
+
"""sesscred: a session-scoped credential store for Linux.
|
|
4
|
+
|
|
5
|
+
Library use::
|
|
6
|
+
|
|
7
|
+
from sesscred import get_credentials
|
|
8
|
+
|
|
9
|
+
cred = get_credentials("example.com")
|
|
10
|
+
if cred is not None:
|
|
11
|
+
user, password = cred
|
|
12
|
+
|
|
13
|
+
The functions below are the public library interface, provisional during
|
|
14
|
+
0.x (see the manual's API page). They read the configuration, identify
|
|
15
|
+
the calling process as the requester, and may show dialogs or ask
|
|
16
|
+
KeePassXC, exactly as the ``sesscred`` command does. They never print,
|
|
17
|
+
never exit, and never change process settings. Log messages go to the
|
|
18
|
+
``sesscred`` logger, silent unless the application configures logging.
|
|
19
|
+
|
|
20
|
+
Importing the package has no side effects beyond defining names.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
|
|
25
|
+
__version__ = "0.1.0"
|
|
26
|
+
|
|
27
|
+
from .cache import EntryInfo # noqa: E402
|
|
28
|
+
from .engine import Credential # noqa: E402
|
|
29
|
+
from .errors import ( # noqa: E402
|
|
30
|
+
BackendError,
|
|
31
|
+
ConfigError,
|
|
32
|
+
SesscredError,
|
|
33
|
+
SessionError,
|
|
34
|
+
UsageError,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
logging.getLogger("sesscred").addHandler(logging.NullHandler())
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"__version__",
|
|
41
|
+
"get_credentials",
|
|
42
|
+
"list_credentials",
|
|
43
|
+
"forget_credentials",
|
|
44
|
+
"Credential",
|
|
45
|
+
"EntryInfo",
|
|
46
|
+
"SesscredError",
|
|
47
|
+
"ConfigError",
|
|
48
|
+
"SessionError",
|
|
49
|
+
"BackendError",
|
|
50
|
+
"UsageError",
|
|
51
|
+
]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _engine(config, name, start_pid=None):
|
|
55
|
+
"""Create the Engine for a library call; the requester is the
|
|
56
|
+
calling process itself."""
|
|
57
|
+
import os
|
|
58
|
+
|
|
59
|
+
from .config import check_cache_name, load
|
|
60
|
+
from .engine import Engine
|
|
61
|
+
|
|
62
|
+
cfg = load(config)
|
|
63
|
+
if name is not None:
|
|
64
|
+
check_cache_name(name)
|
|
65
|
+
return Engine(cfg, name=name, start_pid=start_pid or os.getpid())
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def get_credentials(
|
|
69
|
+
domain, user=None, *, retry=False, interactive=True, config=None, name=None
|
|
70
|
+
):
|
|
71
|
+
"""Obtain a credential, asking the user at most once per session.
|
|
72
|
+
|
|
73
|
+
Looks in the session cache, then the configured password sources,
|
|
74
|
+
then asks the user, applying the configured policy (confirmation,
|
|
75
|
+
trusted and blocked requesters, caching).
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
domain: What the credential is for (``str`` or UTF-8 ``bytes``),
|
|
79
|
+
e.g. ``"example.com"`` or ``"myhost[sudo]"``.
|
|
80
|
+
user: The user, or None to let the configuration, the source or
|
|
81
|
+
the user choose.
|
|
82
|
+
retry: The credential returned last time was wrong: forget it,
|
|
83
|
+
skip the sources and ask the user to type it.
|
|
84
|
+
interactive: False never asks the user to type it. Confirmations
|
|
85
|
+
the configuration requires are still asked; with no way to
|
|
86
|
+
show one, the answer is no.
|
|
87
|
+
config: Configuration file to use instead of
|
|
88
|
+
``$SESSCRED_CONFIG`` or ``~/.config/sesscred/config.toml``.
|
|
89
|
+
name: Cache name instead of ``session.name``.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
Credential or None: None when there is no credential: not found,
|
|
93
|
+
the user cancelled, or the release was refused.
|
|
94
|
+
|
|
95
|
+
Raises:
|
|
96
|
+
UsageError: Invalid domain, user or cache name.
|
|
97
|
+
ConfigError: The configuration file is invalid or unsafe.
|
|
98
|
+
SessionError: The session cache cannot be used in this process
|
|
99
|
+
(for example, no session keyring of its own).
|
|
100
|
+
"""
|
|
101
|
+
return (
|
|
102
|
+
_engine(config, name)
|
|
103
|
+
.get(domain, user, retry=retry, interactive=interactive)
|
|
104
|
+
.credential
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def list_credentials(*, config=None, name=None):
|
|
109
|
+
"""List the cached entries. Never returns passwords.
|
|
110
|
+
|
|
111
|
+
Args:
|
|
112
|
+
config: Configuration file, as for :func:`get_credentials`.
|
|
113
|
+
name: Cache name instead of ``session.name``.
|
|
114
|
+
|
|
115
|
+
Returns:
|
|
116
|
+
list: :class:`EntryInfo` tuples sorted by domain then user.
|
|
117
|
+
|
|
118
|
+
Raises:
|
|
119
|
+
UsageError: Invalid cache name.
|
|
120
|
+
ConfigError: The configuration file is invalid or unsafe.
|
|
121
|
+
SessionError: The session cache cannot be used here.
|
|
122
|
+
"""
|
|
123
|
+
return _engine(config, name).entries()
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def forget_credentials(
|
|
127
|
+
domain=None, user=None, *, all=False, config=None, name=None
|
|
128
|
+
):
|
|
129
|
+
"""Remove cached entries.
|
|
130
|
+
|
|
131
|
+
Forgets (domain, user), every user of ``domain`` when no user is
|
|
132
|
+
given, or every entry with ``all=True``.
|
|
133
|
+
|
|
134
|
+
Args:
|
|
135
|
+
domain: The domain.
|
|
136
|
+
user: The user, or None for every user of the domain.
|
|
137
|
+
all: Remove every entry of the cache.
|
|
138
|
+
config: Configuration file, as for :func:`get_credentials`.
|
|
139
|
+
name: Cache name instead of ``session.name``.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
int: The number of entries removed.
|
|
143
|
+
|
|
144
|
+
Raises:
|
|
145
|
+
ValueError: Neither a domain nor ``all=True`` was given, or
|
|
146
|
+
both were.
|
|
147
|
+
UsageError: Invalid domain, user or cache name.
|
|
148
|
+
ConfigError: The configuration file is invalid or unsafe.
|
|
149
|
+
SessionError: The session cache cannot be used here.
|
|
150
|
+
"""
|
|
151
|
+
if (domain is None) == (not all):
|
|
152
|
+
raise ValueError("give a domain or all=True, not both")
|
|
153
|
+
return _engine(config, name).forget(domain, user, everything=all)
|
sesscred/askpass.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2026 Juan D. Martin
|
|
3
|
+
"""``sesscred-askpass``: the SUDO_ASKPASS / SSH_ASKPASS helper (DESIGN §13).
|
|
4
|
+
|
|
5
|
+
``sudo -A`` and ``ssh`` run the helper with the prompt text as its only
|
|
6
|
+
argument and read the answer from its standard output. The helper works
|
|
7
|
+
out what is asked (:func:`classify`):
|
|
8
|
+
|
|
9
|
+
- sudo's password prompt, in any language → domain ``HOST[sudo]``;
|
|
10
|
+
- ssh's ``user@host's password:`` → ``host[ssh]``;
|
|
11
|
+
- the key passphrase prompts of ssh and ssh-add → ``/path/to/key[ssh]``;
|
|
12
|
+
- yes/no questions (host keys, agent confirmation) → a yes/no dialog;
|
|
13
|
+
- anything else (including sudo's further PAM questions, such as a
|
|
14
|
+
one-time code) → a plain text dialog, never cached.
|
|
15
|
+
|
|
16
|
+
Passwords go through the normal query flow, with the requester chain
|
|
17
|
+
starting at sudo or ssh. When sudo or ssh runs the helper again for a
|
|
18
|
+
credential it already gave that process, the previous answer was
|
|
19
|
+
wrong, so the query is a retry (:func:`answered`, :func:`remember`).
|
|
20
|
+
|
|
21
|
+
When standard output is a terminal (the helper run by hand: sudo and
|
|
22
|
+
ssh always read it through a pipe), secrets are printed masked.
|
|
23
|
+
|
|
24
|
+
The helper takes no options; ``$SESSCRED_CONFIG`` selects the
|
|
25
|
+
configuration and ``SESSCRED_VERBOSE=1`` explains on stderr.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
import json
|
|
29
|
+
import logging
|
|
30
|
+
import os
|
|
31
|
+
import pwd
|
|
32
|
+
import re
|
|
33
|
+
import socket
|
|
34
|
+
import sys
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
from typing import Optional
|
|
37
|
+
|
|
38
|
+
log = logging.getLogger("sesscred")
|
|
39
|
+
|
|
40
|
+
#: Pattern of ssh's password prompt, ``user@host's password:``. Like
|
|
41
|
+
#: ssh, the host is what follows the last ``@`` (logins may contain one).
|
|
42
|
+
SSH_PASSWORD = re.compile(r"(?P<user>\S+)@(?P<host>[^@'\s]+)'s password:\s*")
|
|
43
|
+
#: Pattern of ssh's keyboard-interactive prompt, ``(user@host) Password:``.
|
|
44
|
+
SSH_KBD = re.compile(
|
|
45
|
+
r"\((?P<user>[^\s()]+)@(?P<host>[^@)\s]+)\)\s*password:\s*",
|
|
46
|
+
re.IGNORECASE,
|
|
47
|
+
)
|
|
48
|
+
#: Pattern of the key passphrase prompts of ssh and ssh-add, including
|
|
49
|
+
#: ssh-add's prompt after a wrong passphrase. A path given without
|
|
50
|
+
#: quotes is absolute, or relative without spaces.
|
|
51
|
+
SSH_KEY = re.compile(
|
|
52
|
+
r"(?:Enter passphrase|(?P<bad>Bad passphrase, try again)) for "
|
|
53
|
+
r"(?:key '(?P<quoted>.+)'|(?P<plain>/.+?|[^\s/']\S*))"
|
|
54
|
+
r"(?: \(will confirm each use\))?:\s*"
|
|
55
|
+
)
|
|
56
|
+
#: Prompts for a user name, whose answer is shown while typed (git asks
|
|
57
|
+
#: ``Username for 'https://host':`` through SSH_ASKPASS).
|
|
58
|
+
USERNAME = re.compile(r"(user\s*name|login)\b", re.IGNORECASE)
|
|
59
|
+
#: Shown instead of a secret when standard output is a terminal.
|
|
60
|
+
MASK = "********"
|
|
61
|
+
#: Pattern of ssh's yes/no questions, for versions without SSH_ASKPASS_PROMPT.
|
|
62
|
+
SSH_YES_NO = re.compile(r"\(yes/no(/\[fingerprint\])?\)\?\s*$")
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass(frozen=True)
|
|
66
|
+
class Kind:
|
|
67
|
+
"""What a prompt asks for."""
|
|
68
|
+
|
|
69
|
+
#: ``"password"``, ``"confirm"``, ``"notify"`` or ``"text"``.
|
|
70
|
+
action: str
|
|
71
|
+
#: Domain of a password, else None.
|
|
72
|
+
domain: Optional[str] = None
|
|
73
|
+
#: User of a password, else None.
|
|
74
|
+
user: Optional[str] = None
|
|
75
|
+
#: True if the prompt itself says the previous answer was wrong
|
|
76
|
+
#: (ssh-add's "Bad passphrase, try again").
|
|
77
|
+
retry: bool = False
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def login_name():
|
|
81
|
+
"""The invoking user's login name (the UID if it has none)."""
|
|
82
|
+
try:
|
|
83
|
+
return pwd.getpwuid(os.getuid()).pw_name
|
|
84
|
+
except KeyError:
|
|
85
|
+
return str(os.getuid())
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def short_hostname():
|
|
89
|
+
"""The host name without its domain part."""
|
|
90
|
+
return socket.gethostname().split(".")[0]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def sudo_user(prompt):
|
|
94
|
+
"""Find the account a sudo prompt asks about, in any language.
|
|
95
|
+
|
|
96
|
+
The last word before the final colon is taken if it is an existing
|
|
97
|
+
account (``[sudo] password for alice:``, ``[sudo] contraseña para
|
|
98
|
+
alice:``); otherwise the invoking user, whose password sudo asks for
|
|
99
|
+
by default.
|
|
100
|
+
|
|
101
|
+
Args:
|
|
102
|
+
prompt: The prompt text.
|
|
103
|
+
|
|
104
|
+
Returns:
|
|
105
|
+
str: The user name.
|
|
106
|
+
"""
|
|
107
|
+
words = prompt.strip().rstrip(":").split()
|
|
108
|
+
if words:
|
|
109
|
+
candidate = words[-1].strip(":")
|
|
110
|
+
try:
|
|
111
|
+
pwd.getpwnam(candidate)
|
|
112
|
+
return candidate
|
|
113
|
+
except KeyError:
|
|
114
|
+
pass
|
|
115
|
+
return login_name()
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def is_sudo(parent):
|
|
119
|
+
"""True if the parent process is sudo.
|
|
120
|
+
|
|
121
|
+
Judged from its command name and ``argv[0]``, since sudo's
|
|
122
|
+
executable cannot be read (it runs as root).
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
parent: The parent :class:`~sesscred.process.Process`, or None.
|
|
126
|
+
"""
|
|
127
|
+
if parent is None:
|
|
128
|
+
return False
|
|
129
|
+
names = {parent.comm, os.path.basename(parent.path)}
|
|
130
|
+
if parent.argv:
|
|
131
|
+
names.add(os.path.basename(parent.argv[0]))
|
|
132
|
+
return "sudo" in names
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def classify(prompt, parent, env):
|
|
136
|
+
"""Decide what a prompt asks for (DESIGN §13.1).
|
|
137
|
+
|
|
138
|
+
``SSH_ASKPASS_PROMPT`` (set by OpenSSH 8.4 and later) decides first:
|
|
139
|
+
``confirm`` is a yes/no question, ``none`` a notification. Then a
|
|
140
|
+
sudo parent means sudo's password, whatever the prompt's language;
|
|
141
|
+
so does a prompt starting with ``[sudo]`` when the parent cannot be
|
|
142
|
+
read (``/proc`` mounted with ``hidepid``). :func:`run` then tells
|
|
143
|
+
the password from further PAM questions. Then ssh's prompts are
|
|
144
|
+
recognised by their (untranslated) text; relative key paths are
|
|
145
|
+
made absolute with the parent's working directory.
|
|
146
|
+
|
|
147
|
+
Args:
|
|
148
|
+
prompt: The prompt text.
|
|
149
|
+
parent: The helper's parent process, or None.
|
|
150
|
+
env: The environment mapping.
|
|
151
|
+
|
|
152
|
+
Returns:
|
|
153
|
+
Kind: The action, and the domain and user of a password.
|
|
154
|
+
"""
|
|
155
|
+
mode = env.get("SSH_ASKPASS_PROMPT", "")
|
|
156
|
+
if mode == "confirm":
|
|
157
|
+
return Kind("confirm")
|
|
158
|
+
if mode == "none":
|
|
159
|
+
return Kind("notify")
|
|
160
|
+
text = prompt.strip()
|
|
161
|
+
if is_sudo(parent) or (parent is None and text.startswith("[sudo]")):
|
|
162
|
+
return Kind("password", f"{short_hostname()}[sudo]", sudo_user(prompt))
|
|
163
|
+
for regex in (SSH_PASSWORD, SSH_KBD):
|
|
164
|
+
m = regex.fullmatch(text)
|
|
165
|
+
if m:
|
|
166
|
+
return Kind("password", f"{m['host']}[ssh]", m["user"])
|
|
167
|
+
m = SSH_KEY.fullmatch(text)
|
|
168
|
+
if m:
|
|
169
|
+
path = m["quoted"] or m["plain"]
|
|
170
|
+
cwd = parent.cwd if parent is not None else None
|
|
171
|
+
if not os.path.isabs(path) and cwd:
|
|
172
|
+
path = os.path.normpath(os.path.join(cwd, path))
|
|
173
|
+
return Kind(
|
|
174
|
+
"password", f"{path}[ssh]", login_name(), retry=bool(m["bad"])
|
|
175
|
+
)
|
|
176
|
+
if SSH_YES_NO.search(text):
|
|
177
|
+
return Kind("confirm")
|
|
178
|
+
return Kind("text")
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# Retry detection --------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _state_path(runtime, parent):
|
|
185
|
+
"""The retry-state file of a parent process (PID and start time)."""
|
|
186
|
+
return runtime / f"askpass-{parent.pid}-{parent.start}.json"
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def cleanup(runtime, alive):
|
|
190
|
+
"""Remove the retry-state files of processes that no longer exist.
|
|
191
|
+
|
|
192
|
+
Args:
|
|
193
|
+
runtime: The runtime directory.
|
|
194
|
+
alive: Function ``(pid, start) -> bool``, normally
|
|
195
|
+
:func:`sesscred.process.is_alive`.
|
|
196
|
+
"""
|
|
197
|
+
for path in runtime.glob("askpass-*-*.json"):
|
|
198
|
+
try:
|
|
199
|
+
_, pid, start = path.stem.split("-")
|
|
200
|
+
if not alive(int(pid), int(start)):
|
|
201
|
+
path.unlink()
|
|
202
|
+
except (ValueError, OSError):
|
|
203
|
+
continue
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def answered(runtime, parent):
|
|
207
|
+
"""Return what the helper already answered for ``parent``.
|
|
208
|
+
|
|
209
|
+
sudo and ssh run the helper again, from the same process, after a
|
|
210
|
+
wrong password. The state file holds only domains, users and prompt
|
|
211
|
+
texts, never passwords, and is keyed by PID and start time so a
|
|
212
|
+
reused PID is not mistaken for the same process.
|
|
213
|
+
|
|
214
|
+
Args:
|
|
215
|
+
runtime: The runtime directory.
|
|
216
|
+
parent: The parent :class:`~sesscred.process.Process`.
|
|
217
|
+
|
|
218
|
+
Returns:
|
|
219
|
+
list: ``(domain, user, prompt)`` tuples, oldest first; empty if
|
|
220
|
+
there is no state file or it cannot be read.
|
|
221
|
+
|
|
222
|
+
Raises:
|
|
223
|
+
sesscred.errors.SessionError: The state file is not private.
|
|
224
|
+
"""
|
|
225
|
+
from .runtime import read_private
|
|
226
|
+
|
|
227
|
+
try:
|
|
228
|
+
raw = read_private(_state_path(runtime, parent))
|
|
229
|
+
records = json.loads(raw) if raw else []
|
|
230
|
+
except (ValueError, OSError):
|
|
231
|
+
return []
|
|
232
|
+
if not isinstance(records, list):
|
|
233
|
+
return []
|
|
234
|
+
return [
|
|
235
|
+
tuple(r)
|
|
236
|
+
for r in records
|
|
237
|
+
if isinstance(r, list)
|
|
238
|
+
and len(r) == 3
|
|
239
|
+
and all(isinstance(x, str) for x in r)
|
|
240
|
+
]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def remember(runtime, parent, domain, user, prompt):
|
|
244
|
+
"""Record that ``parent`` was given a password for (domain, user).
|
|
245
|
+
|
|
246
|
+
Only answered prompts are recorded: a refused or cancelled query
|
|
247
|
+
makes ssh ask again, which must not count as a wrong password.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
runtime: The runtime directory.
|
|
251
|
+
parent: The parent :class:`~sesscred.process.Process`.
|
|
252
|
+
domain: The domain asked for.
|
|
253
|
+
user: The user asked for.
|
|
254
|
+
prompt: The prompt text, stripped.
|
|
255
|
+
|
|
256
|
+
Raises:
|
|
257
|
+
sesscred.errors.SessionError: The state file is not private.
|
|
258
|
+
OSError: The state file cannot be written.
|
|
259
|
+
"""
|
|
260
|
+
from .runtime import write_private
|
|
261
|
+
|
|
262
|
+
records = [list(r) for r in answered(runtime, parent)]
|
|
263
|
+
record = [domain, user, prompt]
|
|
264
|
+
if record not in records:
|
|
265
|
+
records.append(record)
|
|
266
|
+
write_private(
|
|
267
|
+
_state_path(runtime, parent), json.dumps(records).encode()
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def is_sudo_password(prompt, earlier):
|
|
272
|
+
"""Tell sudo's password prompt from further PAM questions.
|
|
273
|
+
|
|
274
|
+
sudo replaces PAM's password prompt with its own, which starts with
|
|
275
|
+
``[sudo]`` unless configured otherwise. Other PAM questions (a
|
|
276
|
+
one-time code, say) come through unchanged, after the password.
|
|
277
|
+
|
|
278
|
+
Args:
|
|
279
|
+
prompt: The prompt text, stripped.
|
|
280
|
+
earlier: :func:`answered` for the sudo process.
|
|
281
|
+
|
|
282
|
+
Returns:
|
|
283
|
+
bool: True for a ``[sudo]`` prompt, the first prompt, or the
|
|
284
|
+
same text as an answered password prompt (a retry).
|
|
285
|
+
"""
|
|
286
|
+
if prompt.startswith("[sudo]"):
|
|
287
|
+
return True
|
|
288
|
+
asked = [p for domain, _, p in earlier if domain.endswith("[sudo]")]
|
|
289
|
+
return not asked or prompt in asked
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
# Entry point ------------------------------------------------------------
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def run(prompt, *, config=None, name=None):
|
|
296
|
+
"""Answer one askpass prompt.
|
|
297
|
+
|
|
298
|
+
Prints the answer and a newline on standard output (secrets are
|
|
299
|
+
masked when it is a terminal). Errors are logged; they never escape.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
prompt: The prompt text given by sudo or ssh.
|
|
303
|
+
config: Configuration file instead of the default.
|
|
304
|
+
name: Cache name instead of ``session.name``.
|
|
305
|
+
|
|
306
|
+
Returns:
|
|
307
|
+
int: 0 with an answer (including "yes"); 1 without one, for a
|
|
308
|
+
refused yes/no question (``no`` is printed too) or on error.
|
|
309
|
+
"""
|
|
310
|
+
from .config import load
|
|
311
|
+
from .engine import TITLE, Engine
|
|
312
|
+
from .errors import SesscredError
|
|
313
|
+
from .process import is_alive, process_chain
|
|
314
|
+
from .prompt import Request
|
|
315
|
+
from .runtime import runtime_dir
|
|
316
|
+
|
|
317
|
+
try:
|
|
318
|
+
cfg = load(config)
|
|
319
|
+
raw = process_chain(os.getppid())
|
|
320
|
+
parent = raw[0] if raw else None
|
|
321
|
+
kind = classify(prompt, parent, os.environ)
|
|
322
|
+
engine = Engine(cfg, name=name, start_pid=os.getppid())
|
|
323
|
+
text = prompt.strip()
|
|
324
|
+
# sudo and ssh read the answer through a pipe: a terminal means
|
|
325
|
+
# the helper was run by hand, which is never a retry.
|
|
326
|
+
by_hand = sys.stdout.isatty()
|
|
327
|
+
runtime = None
|
|
328
|
+
earlier = []
|
|
329
|
+
if kind.action == "password" and parent is not None and not by_hand:
|
|
330
|
+
runtime = runtime_dir()
|
|
331
|
+
cleanup(runtime, is_alive)
|
|
332
|
+
earlier = answered(runtime, parent)
|
|
333
|
+
if is_sudo(parent) and not is_sudo_password(text, earlier):
|
|
334
|
+
kind = Kind("text") # another PAM question: never cached
|
|
335
|
+
log.debug("askpass: %s %s", kind.action, kind.domain or "")
|
|
336
|
+
|
|
337
|
+
if kind.action in ("confirm", "notify", "text"):
|
|
338
|
+
prompter = engine.prompter
|
|
339
|
+
if prompter is None:
|
|
340
|
+
log.warning("no dialog available")
|
|
341
|
+
return 1
|
|
342
|
+
req = Request(
|
|
343
|
+
title=TITLE,
|
|
344
|
+
message=text or "Input requested",
|
|
345
|
+
details=tuple(engine.requester.describe()),
|
|
346
|
+
timeout=cfg.timeout,
|
|
347
|
+
)
|
|
348
|
+
if kind.action == "confirm":
|
|
349
|
+
if prompter.confirm(req):
|
|
350
|
+
sys.stdout.write("yes\n")
|
|
351
|
+
return 0
|
|
352
|
+
sys.stdout.write("no\n")
|
|
353
|
+
return 1 # ssh treats empty output as "yes": fail closed
|
|
354
|
+
if kind.action == "notify":
|
|
355
|
+
prompter.notify(req)
|
|
356
|
+
return 0
|
|
357
|
+
secret = not USERNAME.match(text)
|
|
358
|
+
answer = prompter.ask_text(req, secret=secret)
|
|
359
|
+
if answer is None:
|
|
360
|
+
return 1
|
|
361
|
+
shown = MASK if by_hand and secret else answer
|
|
362
|
+
sys.stdout.write(shown + "\n")
|
|
363
|
+
return 0
|
|
364
|
+
|
|
365
|
+
retry = kind.retry or any(
|
|
366
|
+
(d, u) == (kind.domain, kind.user) for d, u, _ in earlier
|
|
367
|
+
)
|
|
368
|
+
if retry:
|
|
369
|
+
log.debug("askpass: the previous answer was wrong: retry")
|
|
370
|
+
result = engine.get(kind.domain, kind.user, retry=retry)
|
|
371
|
+
if not result.ok:
|
|
372
|
+
log.warning("%s", result.message)
|
|
373
|
+
return 1
|
|
374
|
+
password = result.credential.password
|
|
375
|
+
sys.stdout.write((MASK if by_hand else password) + "\n")
|
|
376
|
+
sys.stdout.flush()
|
|
377
|
+
if runtime is not None:
|
|
378
|
+
try:
|
|
379
|
+
remember(runtime, parent, kind.domain, kind.user, text)
|
|
380
|
+
except OSError as e:
|
|
381
|
+
log.warning("cannot record the answer: %s", e.strerror)
|
|
382
|
+
return 0
|
|
383
|
+
except (SesscredError, OSError) as e:
|
|
384
|
+
log.error("%s", e)
|
|
385
|
+
return 1
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def main(argv=None):
|
|
389
|
+
"""Entry point of ``sesscred-askpass PROMPT``; return the exit status.
|
|
390
|
+
|
|
391
|
+
Hardens the process like the command does (no core dumps, dialog
|
|
392
|
+
children killed when terminated).
|
|
393
|
+
|
|
394
|
+
Args:
|
|
395
|
+
argv: Arguments without the program name; default
|
|
396
|
+
``sys.argv[1:]``.
|
|
397
|
+
"""
|
|
398
|
+
from .cli import env_flag, setup_logging
|
|
399
|
+
from .hardening import Terminated, harden
|
|
400
|
+
|
|
401
|
+
harden()
|
|
402
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
403
|
+
setup_logging(env_flag(os.environ.get("SESSCRED_VERBOSE")))
|
|
404
|
+
prompt = argv[0] if argv else ""
|
|
405
|
+
try:
|
|
406
|
+
return run(prompt)
|
|
407
|
+
except (Terminated, KeyboardInterrupt):
|
|
408
|
+
return 1
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
if __name__ == "__main__":
|
|
412
|
+
sys.exit(main())
|