codecraftai-protocol-ssh 1.3.0__tar.gz → 1.4.0__tar.gz
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.
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/PKG-INFO +19 -5
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/README.rst +14 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/pyproject.toml +5 -24
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshagent.py +19 -4
- codecraftai_protocol_ssh-1.4.0/source/packages/ccai/protocols/ssh/sshauth.py +266 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshbase.py +110 -15
- codecraftai_protocol_ssh-1.4.0/source/packages/ccai/protocols/ssh/sshclient.py +498 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshconnection.py +35 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshconstants.py +38 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshhelpers.py +144 -78
- codecraftai_protocol_ssh-1.4.0/source/packages/ccai/protocols/ssh/sshhostkeys.py +368 -0
- codecraftai_protocol_ssh-1.4.0/source/packages/ccai/protocols/ssh/sshkeys.py +291 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshsession.py +65 -12
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshsftp.py +228 -14
- codecraftai_protocol_ssh-1.4.0/source/packages/ccai/protocols/ssh/sshtransport.py +1488 -0
- codecraftai_protocol_ssh-1.3.0/source/packages/ccai/protocols/ssh/sshauth.py +0 -118
- codecraftai_protocol_ssh-1.3.0/source/packages/ccai/protocols/ssh/sshclient.py +0 -170
- codecraftai_protocol_ssh-1.3.0/source/packages/ccai/protocols/ssh/sshkeys.py +0 -197
- codecraftai_protocol_ssh-1.3.0/source/packages/ccai/protocols/ssh/sshtransport.py +0 -756
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/LICENSE.md +0 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/__init__.py +0 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/py.typed +0 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshconst.py +0 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshpacket.py +0 -0
- {codecraftai_protocol_ssh-1.3.0 → codecraftai_protocol_ssh-1.4.0}/source/packages/ccai/protocols/ssh/sshtunnel.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: codecraftai-protocol-ssh
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.4.0
|
|
4
4
|
Summary: Code Craft AI - SSH Protocol
|
|
5
5
|
License-Expression: LicenseRef-CodeCraftAI-Source-Available
|
|
6
6
|
License-File: LICENSE.md
|
|
@@ -10,10 +10,10 @@ Author-email: myron.walker@gmail.com
|
|
|
10
10
|
Requires-Python: >=3.10,<4.0
|
|
11
11
|
Classifier: Programming Language :: Python :: 3
|
|
12
12
|
Classifier: Operating System :: POSIX
|
|
13
|
-
Requires-Dist: codecraftai-credentials (
|
|
14
|
-
Requires-Dist: codecraftai-foundations (
|
|
15
|
-
Requires-Dist: codecraftai-interop (
|
|
16
|
-
Requires-Dist: codecraftai-xmodules (
|
|
13
|
+
Requires-Dist: codecraftai-credentials (>=1.0.0,<2.0.0)
|
|
14
|
+
Requires-Dist: codecraftai-foundations (>=1.0.0,<2.0.0)
|
|
15
|
+
Requires-Dist: codecraftai-interop (>=1.0.0,<2.0.0)
|
|
16
|
+
Requires-Dist: codecraftai-xmodules (>=1.0.0,<2.0.0)
|
|
17
17
|
Requires-Dist: cryptography (>=45.0.5,<51.0.0)
|
|
18
18
|
Project-URL: Issues, https://github.com/code-craft-ai-company/codecraftai-protocol-ssh/issues
|
|
19
19
|
Project-URL: Repository, https://github.com/code-craft-ai-company/codecraftai-protocol-ssh
|
|
@@ -34,6 +34,20 @@ Highlights
|
|
|
34
34
|
- SFTP and tunnel support in ``sshsftp.py`` and ``sshtunnel.py``.
|
|
35
35
|
- RFC-aligned implementations of the SSH transport and user authentication layers.
|
|
36
36
|
|
|
37
|
+
Security Defaults
|
|
38
|
+
=================
|
|
39
|
+
|
|
40
|
+
- Host keys are verified against ``~/.ssh/known_hosts`` (and ``known_hosts_path``); unknown host keys are
|
|
41
|
+
rejected. Pass ``verify_host_keys=False`` to ``SshAgent`` / ``SshSession`` only for ephemeral lab devices.
|
|
42
|
+
- Only SHA-2 based algorithms are offered: ``curve25519-sha256``, ``diffie-hellman-group14-sha256``,
|
|
43
|
+
``ssh-ed25519``, ``rsa-sha2-512`` / ``rsa-sha2-256``, ``aes*-ctr``, ``hmac-sha2-256`` / ``hmac-sha2-512``.
|
|
44
|
+
The legacy SHA-1 based algorithms (``diffie-hellman-group14-sha1``, ``ssh-rsa`` host key and user key
|
|
45
|
+
signatures, ``hmac-sha1``) are not offered by default, and a server that supports nothing else is refused with
|
|
46
|
+
a ``ProtocolError`` that says so. For an old server that cannot be upgraded, opt in explicitly with
|
|
47
|
+
``allow_legacy_algorithms=True`` on ``SshAgent`` / ``SshSession`` / ``SshClient.connect`` (or
|
|
48
|
+
``SshTransport.set_allow_legacy_algorithms(True)``); the legacy algorithms are then offered after every SHA-2
|
|
49
|
+
one, so a server that supports SHA-2 is never downgraded. ``disabled_algorithms`` still applies on top.
|
|
50
|
+
|
|
37
51
|
Repository Structure
|
|
38
52
|
====================
|
|
39
53
|
|
|
@@ -13,6 +13,20 @@ Highlights
|
|
|
13
13
|
- SFTP and tunnel support in ``sshsftp.py`` and ``sshtunnel.py``.
|
|
14
14
|
- RFC-aligned implementations of the SSH transport and user authentication layers.
|
|
15
15
|
|
|
16
|
+
Security Defaults
|
|
17
|
+
=================
|
|
18
|
+
|
|
19
|
+
- Host keys are verified against ``~/.ssh/known_hosts`` (and ``known_hosts_path``); unknown host keys are
|
|
20
|
+
rejected. Pass ``verify_host_keys=False`` to ``SshAgent`` / ``SshSession`` only for ephemeral lab devices.
|
|
21
|
+
- Only SHA-2 based algorithms are offered: ``curve25519-sha256``, ``diffie-hellman-group14-sha256``,
|
|
22
|
+
``ssh-ed25519``, ``rsa-sha2-512`` / ``rsa-sha2-256``, ``aes*-ctr``, ``hmac-sha2-256`` / ``hmac-sha2-512``.
|
|
23
|
+
The legacy SHA-1 based algorithms (``diffie-hellman-group14-sha1``, ``ssh-rsa`` host key and user key
|
|
24
|
+
signatures, ``hmac-sha1``) are not offered by default, and a server that supports nothing else is refused with
|
|
25
|
+
a ``ProtocolError`` that says so. For an old server that cannot be upgraded, opt in explicitly with
|
|
26
|
+
``allow_legacy_algorithms=True`` on ``SshAgent`` / ``SshSession`` / ``SshClient.connect`` (or
|
|
27
|
+
``SshTransport.set_allow_legacy_algorithms(True)``); the legacy algorithms are then offered after every SHA-2
|
|
28
|
+
one, so a server that supports SHA-2 is never downgraded. ``disabled_algorithms`` still applies on top.
|
|
29
|
+
|
|
16
30
|
Repository Structure
|
|
17
31
|
====================
|
|
18
32
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "codecraftai-protocol-ssh"
|
|
3
|
-
version = "1.
|
|
3
|
+
version = "1.4.0"
|
|
4
4
|
description = "Code Craft AI - SSH Protocol"
|
|
5
5
|
readme = "README.rst"
|
|
6
6
|
license = "LicenseRef-CodeCraftAI-Source-Available"
|
|
@@ -15,10 +15,10 @@ classifiers = [
|
|
|
15
15
|
requires-python = ">=3.10,<4.0"
|
|
16
16
|
dependencies = [
|
|
17
17
|
"cryptography>=45.0.5,<51.0.0",
|
|
18
|
-
"codecraftai-foundations
|
|
19
|
-
"codecraftai-credentials
|
|
20
|
-
"codecraftai-interop
|
|
21
|
-
"codecraftai-xmodules
|
|
18
|
+
"codecraftai-foundations>=1.0.0,<2.0.0",
|
|
19
|
+
"codecraftai-credentials>=1.0.0,<2.0.0",
|
|
20
|
+
"codecraftai-interop>=1.0.0,<2.0.0",
|
|
21
|
+
"codecraftai-xmodules>=1.0.0,<2.0.0",
|
|
22
22
|
]
|
|
23
23
|
|
|
24
24
|
[project.urls]
|
|
@@ -32,25 +32,6 @@ dbio = []
|
|
|
32
32
|
[tool.poetry]
|
|
33
33
|
packages = [{include="ccai", from="source/packages"}]
|
|
34
34
|
|
|
35
|
-
[tool.poetry.dependencies]
|
|
36
|
-
codecraftai-foundations = {source = "codecraftai"}
|
|
37
|
-
codecraftai-credentials = {source = "codecraftai"}
|
|
38
|
-
codecraftai-interop = {source = "codecraftai"}
|
|
39
|
-
codecraftai-xmodules = {source = "codecraftai"}
|
|
40
|
-
|
|
41
|
-
[[tool.poetry.source]]
|
|
42
|
-
name = "codecraftai"
|
|
43
|
-
url = "https://code-craft.ai/licensed-repository/simple/"
|
|
44
|
-
priority = "supplemental"
|
|
45
|
-
|
|
46
|
-
[[tool.uv.index]]
|
|
47
|
-
# Same licensed index as [[tool.poetry.source]]. Listed before PyPI so that
|
|
48
|
-
# codecraftai-* packages (direct and transitive) resolve from it; everything
|
|
49
|
-
# else falls through to PyPI. Credentials: UV_INDEX_CODECRAFTAI_USERNAME /
|
|
50
|
-
# UV_INDEX_CODECRAFTAI_PASSWORD, or `uv auth login`.
|
|
51
|
-
name = "codecraftai"
|
|
52
|
-
url = "https://code-craft.ai/licensed-repository/simple/"
|
|
53
|
-
|
|
54
35
|
[tool.ruff.lint]
|
|
55
36
|
# Deliberately narrow. This gate exists for one reason: a bare `except:`
|
|
56
37
|
# swallows ConfigurationError and SemanticError, which derive from
|
|
@@ -42,7 +42,9 @@ class SshAgent(SshBase):
|
|
|
42
42
|
provides run patterning to help eliminate duplication of code associated with running SSH commands in loops.
|
|
43
43
|
"""
|
|
44
44
|
def __init__(self, host: str, primary_credential: SshCredential, users: Optional[Dict[str, SshCredential]] = None, port: int = 22, jump: Union[str, SshJumpParams, None] = None,
|
|
45
|
-
pty_params: Optional[dict] = None, called_id: Optional[str]=None, look_for_keys: bool = False,
|
|
45
|
+
pty_params: Optional[dict] = None, called_id: Optional[str]=None, look_for_keys: bool = False,
|
|
46
|
+
verify_host_keys: bool = True, known_hosts_path: Optional[str] = None,
|
|
47
|
+
allow_legacy_algorithms: bool = False, aspects: AspectsCmd = DEFAULT_CMD_ASPECTS):
|
|
46
48
|
"""
|
|
47
49
|
Initialize an :class:`SshAgent` instance.
|
|
48
50
|
|
|
@@ -54,10 +56,19 @@ class SshAgent(SshBase):
|
|
|
54
56
|
:param pty_params: Parameters used when requesting a PTY.
|
|
55
57
|
:param called_id: Friendly identifier for logging purposes.
|
|
56
58
|
:param look_for_keys: Search for SSH keys in default locations.
|
|
59
|
+
:param verify_host_keys: If ``True`` (default) unknown host keys are rejected; pass ``False``
|
|
60
|
+
to auto-accept them for ephemeral lab devices (no MITM protection).
|
|
61
|
+
:param known_hosts_path: Optional known_hosts file loaded in addition to the user's one.
|
|
62
|
+
:param allow_legacy_algorithms: If ``False`` (default) the legacy SHA-1 based SSH algorithms
|
|
63
|
+
(diffie-hellman-group14-sha1, "ssh-rsa" signatures, hmac-sha1)
|
|
64
|
+
are not offered; pass ``True`` only for an old server that
|
|
65
|
+
supports nothing else.
|
|
57
66
|
:param aspects: Default command aspects for operations.
|
|
58
67
|
"""
|
|
59
68
|
SshBase.__init__(self, host, primary_credential, users=users, port=port, jump=jump,
|
|
60
|
-
pty_params=pty_params, called_id=called_id, look_for_keys=look_for_keys,
|
|
69
|
+
pty_params=pty_params, called_id=called_id, look_for_keys=look_for_keys,
|
|
70
|
+
verify_host_keys=verify_host_keys, known_hosts_path=known_hosts_path,
|
|
71
|
+
allow_legacy_algorithms=allow_legacy_algorithms, aspects=aspects)
|
|
61
72
|
return
|
|
62
73
|
|
|
63
74
|
def open_session(self, user: str = None, primitive: bool = False, pty_params: Optional[dict] = None, interactive=False, basis_session: Optional[SshSession] = None,
|
|
@@ -88,11 +99,15 @@ class SshAgent(SshBase):
|
|
|
88
99
|
bs = basis_session
|
|
89
100
|
session = SshSession(bs._host, session_credential, users=bs._users, port=bs._port,
|
|
90
101
|
jump=bs._jump, pty_params=pty_params, interactive=interactive,
|
|
91
|
-
basis_session=basis_session, look_for_keys=bs._look_for_keys, primitive=primitive,
|
|
102
|
+
basis_session=basis_session, look_for_keys=bs._look_for_keys, primitive=primitive,
|
|
103
|
+
verify_host_keys=bs._verify_host_keys, known_hosts_path=bs._known_hosts_path,
|
|
104
|
+
allow_legacy_algorithms=bs._allow_legacy_algorithms, aspects=aspects)
|
|
92
105
|
else:
|
|
93
106
|
session = SshSession(self._host, session_credential, users=self._users, port=self._port,
|
|
94
107
|
jump=self._jump, pty_params=pty_params, interactive=interactive,
|
|
95
|
-
look_for_keys=self._look_for_keys, primitive=primitive,
|
|
108
|
+
look_for_keys=self._look_for_keys, primitive=primitive,
|
|
109
|
+
verify_host_keys=self._verify_host_keys, known_hosts_path=self._known_hosts_path,
|
|
110
|
+
allow_legacy_algorithms=self._allow_legacy_algorithms, aspects=aspects)
|
|
96
111
|
return session
|
|
97
112
|
|
|
98
113
|
def open_tunnel(self, local_port: int = 0, remote_host: str = 'localhost', remote_port: int = 5432) -> SshTunnel:
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
"""
|
|
2
|
+
SSH Authentication Layer
|
|
3
|
+
"""
|
|
4
|
+
import logging
|
|
5
|
+
import os
|
|
6
|
+
import threading
|
|
7
|
+
import time
|
|
8
|
+
from ccai.protocols.ssh import sshconstants
|
|
9
|
+
from ccai.protocols.ssh.sshpacket import SshPacket
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
# The number of seconds to wait for the server to answer a service or authentication request, unless the
|
|
14
|
+
# caller sets 'timeout' on the agent (SshClient.connect sets it from its 'auth_timeout').
|
|
15
|
+
DEFAULT_AUTH_TIMEOUT = 30
|
|
16
|
+
|
|
17
|
+
# How often, in seconds, a wait for the server's answer checks that the transport is still open.
|
|
18
|
+
AUTH_WAIT_POLL_INTERVAL = 1.0
|
|
19
|
+
|
|
20
|
+
# The signature algorithms tried for an RSA key, in order. The SHA-2 signature (RFC 8332) is what current
|
|
21
|
+
# servers require (OpenSSH 8.8 and later refuse "ssh-rsa" signatures); the SHA-1 "ssh-rsa" signature is only
|
|
22
|
+
# tried afterwards, for servers that predate RFC 8332, and only when the caller opted in to the legacy SHA-1
|
|
23
|
+
# algorithms (allow_legacy_algorithms=True, MYT-221). Every attempt counts against the server's limit of
|
|
24
|
+
# authentication attempts, so the list is kept to two.
|
|
25
|
+
RSA_PUBLICKEY_ALGORITHMS = ("rsa-sha2-256", "ssh-rsa")
|
|
26
|
+
|
|
27
|
+
# The public key signature algorithms that are only used after an opt-in to the legacy SHA-1 algorithms.
|
|
28
|
+
LEGACY_PUBLICKEY_ALGORITHMS = ("ssh-rsa",)
|
|
29
|
+
|
|
30
|
+
class SshAuthError(Exception):
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
class SshAuthAgent:
|
|
34
|
+
"""
|
|
35
|
+
Handles Client-side User Authentication.
|
|
36
|
+
"""
|
|
37
|
+
def __init__(self, transport):
|
|
38
|
+
self.transport = transport
|
|
39
|
+
self.username = None
|
|
40
|
+
self.service = "ssh-connection"
|
|
41
|
+
self.auth_methods = []
|
|
42
|
+
self.authenticated = False
|
|
43
|
+
self.event = threading.Event()
|
|
44
|
+
self.service_accepted = threading.Event()
|
|
45
|
+
self.last_exception = None
|
|
46
|
+
# True when the last SSH_MSG_USERAUTH_FAILURE said the method succeeded but the server requires
|
|
47
|
+
# further methods (RFC 4252 section 5.1 'partial success').
|
|
48
|
+
self.partial_success = False
|
|
49
|
+
# The number of seconds to wait for the server to answer each request.
|
|
50
|
+
self.timeout = DEFAULT_AUTH_TIMEOUT
|
|
51
|
+
# Public key signature algorithms that must not be used (paramiko's disabled_algorithms['pubkeys']).
|
|
52
|
+
self.disabled_pubkey_algorithms = ()
|
|
53
|
+
# True when the caller opted in to the legacy SHA-1 "ssh-rsa" signature for an old server.
|
|
54
|
+
self.allow_legacy_algorithms = False
|
|
55
|
+
|
|
56
|
+
def request_userauth_service(self):
|
|
57
|
+
"""
|
|
58
|
+
Request the 'ssh-userauth' service and block until the server accepts it.
|
|
59
|
+
|
|
60
|
+
RFC 4252 requires the client to send SSH_MSG_SERVICE_REQUEST for
|
|
61
|
+
'ssh-userauth' and receive SSH_MSG_SERVICE_ACCEPT before any
|
|
62
|
+
SSH_MSG_USERAUTH_REQUEST. This is sent once per connection.
|
|
63
|
+
"""
|
|
64
|
+
if self.service_accepted.is_set():
|
|
65
|
+
return
|
|
66
|
+
|
|
67
|
+
pkt = SshPacket(sshconstants.SSH_MSG_SERVICE_REQUEST)
|
|
68
|
+
pkt.add_string("ssh-userauth")
|
|
69
|
+
self.transport.send_packet(pkt)
|
|
70
|
+
|
|
71
|
+
accepted = self._wait_for_event(self.service_accepted)
|
|
72
|
+
if not accepted:
|
|
73
|
+
raise SshAuthError("Timed out waiting for SERVICE_ACCEPT (ssh-userauth)")
|
|
74
|
+
return
|
|
75
|
+
|
|
76
|
+
def _wait_for_event(self, event: threading.Event) -> bool:
|
|
77
|
+
"""
|
|
78
|
+
Waits for the server's answer for up to ``timeout`` seconds, and stops waiting as soon as the
|
|
79
|
+
transport closes: a server that drops the connection instead of answering (for example after too
|
|
80
|
+
many authentication attempts) must not cost the caller the whole timeout.
|
|
81
|
+
|
|
82
|
+
:param event: The event the reader thread sets when the answer arrives.
|
|
83
|
+
|
|
84
|
+
:returns: True if the event was set, False if the timeout expired.
|
|
85
|
+
:raises: ConnectionError if the transport closed while waiting.
|
|
86
|
+
"""
|
|
87
|
+
wait_start = time.monotonic()
|
|
88
|
+
|
|
89
|
+
answered = event.is_set()
|
|
90
|
+
while answered is not True:
|
|
91
|
+
if self.transport.active is False:
|
|
92
|
+
err_msg_lines = [
|
|
93
|
+
"The SSH transport closed while waiting for the server to answer an authentication request.",
|
|
94
|
+
"CAUSE: {}".format(getattr(self.transport, "close_error", None)),
|
|
95
|
+
]
|
|
96
|
+
err_msg = os.linesep.join(err_msg_lines)
|
|
97
|
+
raise ConnectionError(err_msg)
|
|
98
|
+
|
|
99
|
+
remaining = self.timeout - (time.monotonic() - wait_start)
|
|
100
|
+
if remaining <= 0:
|
|
101
|
+
break
|
|
102
|
+
|
|
103
|
+
wait_time = AUTH_WAIT_POLL_INTERVAL
|
|
104
|
+
if remaining < wait_time:
|
|
105
|
+
wait_time = remaining
|
|
106
|
+
|
|
107
|
+
answered = event.wait(timeout=wait_time)
|
|
108
|
+
|
|
109
|
+
return answered
|
|
110
|
+
|
|
111
|
+
def authenticate_none(self, username: str):
|
|
112
|
+
"""
|
|
113
|
+
Attempt 'none' authentication to get list of allowed methods.
|
|
114
|
+
"""
|
|
115
|
+
self.username = username
|
|
116
|
+
self.request_userauth_service()
|
|
117
|
+
self._send_auth_request("none")
|
|
118
|
+
self._wait_for_response()
|
|
119
|
+
return self.auth_methods
|
|
120
|
+
|
|
121
|
+
def authenticate_password(self, username: str, password: str):
|
|
122
|
+
"""
|
|
123
|
+
Attempt password authentication.
|
|
124
|
+
"""
|
|
125
|
+
self.username = username
|
|
126
|
+
self.request_userauth_service()
|
|
127
|
+
self._send_auth_request("password", password=password)
|
|
128
|
+
self._wait_for_response()
|
|
129
|
+
return
|
|
130
|
+
|
|
131
|
+
def authenticate_publickey(self, username: str, key):
|
|
132
|
+
"""
|
|
133
|
+
Attempt public key authentication (RFC 4252 section 7) with a private key.
|
|
134
|
+
|
|
135
|
+
The request carries a signature, made with the private key, over the session identifier followed by
|
|
136
|
+
the request itself, which proves possession of the key for this connection only.
|
|
137
|
+
|
|
138
|
+
:param username: The name of the user to authenticate as.
|
|
139
|
+
:param key: The private key, an :class:`SshRSAKey` or :class:`SshEd25519Key`.
|
|
140
|
+
|
|
141
|
+
:raises: SshAuthError if the server does not accept the key, TimeoutError if it does not answer.
|
|
142
|
+
"""
|
|
143
|
+
self.username = username
|
|
144
|
+
self.request_userauth_service()
|
|
145
|
+
|
|
146
|
+
session_id = self.transport.session_id
|
|
147
|
+
if session_id is None:
|
|
148
|
+
err_msg = "Public key authentication needs the session identifier of a completed key exchange."
|
|
149
|
+
raise SshAuthError(err_msg)
|
|
150
|
+
|
|
151
|
+
key_blob = bytes(key.as_bytes())
|
|
152
|
+
|
|
153
|
+
key_type = key.get_name()
|
|
154
|
+
if key_type == "ssh-rsa":
|
|
155
|
+
candidates = RSA_PUBLICKEY_ALGORITHMS
|
|
156
|
+
else:
|
|
157
|
+
candidates = (key_type,)
|
|
158
|
+
if self.allow_legacy_algorithms is not True:
|
|
159
|
+
candidates = [name for name in candidates if name not in LEGACY_PUBLICKEY_ALGORITHMS]
|
|
160
|
+
algorithms = [name for name in candidates if name not in self.disabled_pubkey_algorithms]
|
|
161
|
+
|
|
162
|
+
if len(algorithms) == 0:
|
|
163
|
+
err_msg = "Every public key signature algorithm of a '{}' key has been disabled.".format(key_type)
|
|
164
|
+
raise SshAuthError(err_msg)
|
|
165
|
+
|
|
166
|
+
last_error = None
|
|
167
|
+
for algorithm in algorithms:
|
|
168
|
+
pkt = SshPacket(sshconstants.SSH_MSG_USERAUTH_REQUEST)
|
|
169
|
+
pkt.add_string(self.username)
|
|
170
|
+
pkt.add_string(self.service)
|
|
171
|
+
pkt.add_string("publickey")
|
|
172
|
+
pkt.add_boolean(True) # A signature follows
|
|
173
|
+
pkt.add_string(algorithm)
|
|
174
|
+
pkt.add_string(key_blob)
|
|
175
|
+
|
|
176
|
+
# The signed data is the session identifier, as a string, followed by the request up to here.
|
|
177
|
+
signed_data = SshPacket()
|
|
178
|
+
signed_data.add_string(session_id)
|
|
179
|
+
signed_data.add_bytes(pkt.to_bytes())
|
|
180
|
+
|
|
181
|
+
signature = key.sign(bytes(signed_data.payload), algorithm=algorithm)
|
|
182
|
+
|
|
183
|
+
signature_blob = SshPacket()
|
|
184
|
+
signature_blob.add_string(algorithm)
|
|
185
|
+
signature_blob.add_string(signature)
|
|
186
|
+
pkt.add_string(bytes(signature_blob.payload))
|
|
187
|
+
|
|
188
|
+
self.event.clear()
|
|
189
|
+
self.transport.send_packet(pkt)
|
|
190
|
+
|
|
191
|
+
answered = self._wait_for_event(self.event)
|
|
192
|
+
if answered is not True:
|
|
193
|
+
raise TimeoutError("Auth request timed out")
|
|
194
|
+
|
|
195
|
+
if self.authenticated is True:
|
|
196
|
+
last_error = None
|
|
197
|
+
break
|
|
198
|
+
|
|
199
|
+
last_error = self.last_exception
|
|
200
|
+
if self.partial_success is True:
|
|
201
|
+
# The key was accepted; a different algorithm would not change what the server still wants.
|
|
202
|
+
break
|
|
203
|
+
|
|
204
|
+
if last_error is not None:
|
|
205
|
+
raise last_error
|
|
206
|
+
|
|
207
|
+
if self.authenticated is not True:
|
|
208
|
+
raise SshAuthError("Authentication failed")
|
|
209
|
+
return
|
|
210
|
+
|
|
211
|
+
def _send_auth_request(self, method: str, password: str = None):
|
|
212
|
+
pkt = SshPacket(sshconstants.SSH_MSG_USERAUTH_REQUEST)
|
|
213
|
+
pkt.add_string(self.username)
|
|
214
|
+
pkt.add_string(self.service)
|
|
215
|
+
pkt.add_string(method)
|
|
216
|
+
|
|
217
|
+
if method == "password":
|
|
218
|
+
pkt.add_boolean(False) # Change password?
|
|
219
|
+
pkt.add_string(password)
|
|
220
|
+
|
|
221
|
+
self.event.clear()
|
|
222
|
+
self.transport.send_packet(pkt)
|
|
223
|
+
return
|
|
224
|
+
|
|
225
|
+
def dispatch_message(self, packet: SshPacket):
|
|
226
|
+
"""
|
|
227
|
+
Called by the transport when an auth-related packet is received.
|
|
228
|
+
"""
|
|
229
|
+
if not packet.payload:
|
|
230
|
+
return
|
|
231
|
+
|
|
232
|
+
msg_id = packet.get_byte()
|
|
233
|
+
if msg_id == sshconstants.SSH_MSG_SERVICE_ACCEPT:
|
|
234
|
+
self.service_accepted.set()
|
|
235
|
+
elif msg_id == sshconstants.SSH_MSG_USERAUTH_SUCCESS:
|
|
236
|
+
self.authenticated = True
|
|
237
|
+
self.event.set()
|
|
238
|
+
elif msg_id == sshconstants.SSH_MSG_USERAUTH_FAILURE:
|
|
239
|
+
# Parse allowed methods
|
|
240
|
+
methods = packet.get_name_list()
|
|
241
|
+
partial_success = packet.get_boolean()
|
|
242
|
+
self.auth_methods = methods
|
|
243
|
+
self.authenticated = False
|
|
244
|
+
self.partial_success = partial_success
|
|
245
|
+
if partial_success is True:
|
|
246
|
+
self.last_exception = SshAuthError(
|
|
247
|
+
f"Authentication succeeded partially; the server requires a further method. Allowed: {methods}")
|
|
248
|
+
else:
|
|
249
|
+
self.last_exception = SshAuthError(f"Authentication failed. Allowed: {methods}")
|
|
250
|
+
self.event.set()
|
|
251
|
+
elif msg_id == sshconstants.SSH_MSG_USERAUTH_BANNER:
|
|
252
|
+
banner = packet.get_string().decode('utf-8')
|
|
253
|
+
logger.info(f"Auth Banner: {banner}")
|
|
254
|
+
else:
|
|
255
|
+
logger.warning(f"Unknown auth packet: {msg_id}")
|
|
256
|
+
return
|
|
257
|
+
|
|
258
|
+
def _wait_for_response(self):
|
|
259
|
+
self._wait_for_event(self.event)
|
|
260
|
+
if not self.event.is_set():
|
|
261
|
+
raise TimeoutError("Auth request timed out")
|
|
262
|
+
if not self.authenticated:
|
|
263
|
+
if self.last_exception:
|
|
264
|
+
raise self.last_exception
|
|
265
|
+
raise SshAuthError("Authentication failed")
|
|
266
|
+
return
|
|
@@ -24,7 +24,7 @@ import time
|
|
|
24
24
|
from datetime import datetime, timedelta
|
|
25
25
|
from io import StringIO
|
|
26
26
|
|
|
27
|
-
from ccai.protocols.ssh.sshclient import SshClient
|
|
27
|
+
from ccai.protocols.ssh.sshclient import SshClient, AutoAddPolicy, RejectPolicy
|
|
28
28
|
from ccai.protocols.ssh.sshkeys import SshRSAKey, SshEd25519Key
|
|
29
29
|
from ccai.protocols.ssh.sshconnection import SshChannel
|
|
30
30
|
|
|
@@ -46,12 +46,14 @@ from ccai.protocols.ssh.sshconst import (
|
|
|
46
46
|
TEMPLATE_COMMAND_SUCCESS
|
|
47
47
|
)
|
|
48
48
|
from ccai.protocols.ssh.sshhelpers import (
|
|
49
|
+
DEFAULT_OUTPUT_DECODE_ERRORS,
|
|
49
50
|
primitive_directory_exists,
|
|
50
51
|
primitive_file_exists,
|
|
51
52
|
primitive_file_pull,
|
|
52
53
|
primitive_file_push,
|
|
53
54
|
primitive_list_directory,
|
|
54
55
|
primitive_list_tree,
|
|
56
|
+
redecode_output,
|
|
55
57
|
sftp_list_directory,
|
|
56
58
|
sftp_list_tree,
|
|
57
59
|
ssh_execute_command
|
|
@@ -68,7 +70,8 @@ class SshBase(ISystemContext):
|
|
|
68
70
|
def __init__(self, host: str, primary_credential: SshCredential, users: Optional[Dict[str, SshCredential]] = None,
|
|
69
71
|
port: int = 22, jump: Union[str, SshJumpParams, None] = None, pty_params: Optional[dict] = None,
|
|
70
72
|
called_id: Optional[str]=None, look_for_keys: bool = False,
|
|
71
|
-
|
|
73
|
+
verify_host_keys: bool = True, known_hosts_path: Optional[str] = None,
|
|
74
|
+
allow_legacy_algorithms: bool = False, aspects: AspectsCmd = DEFAULT_CMD_ASPECTS):
|
|
72
75
|
"""
|
|
73
76
|
Initialize the base SSH helper class.
|
|
74
77
|
|
|
@@ -76,12 +79,40 @@ class SshBase(ISystemContext):
|
|
|
76
79
|
:param primary_credential: Primary credential for authentication.
|
|
77
80
|
:param users: Optional dictionary of additional users.
|
|
78
81
|
:param port: SSH port number.
|
|
79
|
-
:param jump:
|
|
82
|
+
:param jump: Jump hosts are not supported by this SSH client; anything other than ``None``
|
|
83
|
+
raises a :class:`ConfigurationError`.
|
|
80
84
|
:param pty_params: Optional PTY parameters for interactive sessions.
|
|
81
85
|
:param called_id: Identifier used in logs.
|
|
82
86
|
:param look_for_keys: If ``True`` search for SSH keys automatically.
|
|
87
|
+
:param verify_host_keys: If ``True`` (default) the user's known_hosts file (and
|
|
88
|
+
``known_hosts_path`` when given) is loaded and an unknown
|
|
89
|
+
host key is REJECTED (RejectPolicy). Pass ``False`` to
|
|
90
|
+
auto-accept unknown host keys (AutoAddPolicy) for ephemeral
|
|
91
|
+
lab devices; that does not protect against MITM.
|
|
92
|
+
:param known_hosts_path: Optional known_hosts file to load in addition to the user's
|
|
93
|
+
known_hosts when ``verify_host_keys`` is ``True``.
|
|
94
|
+
:param allow_legacy_algorithms: If ``False`` (default) the legacy SHA-1 based SSH algorithms
|
|
95
|
+
(diffie-hellman-group14-sha1, "ssh-rsa" host key and user key
|
|
96
|
+
signatures, hmac-sha1) are not offered, and a server that
|
|
97
|
+
supports nothing else is refused with a ProtocolError. Pass
|
|
98
|
+
``True`` to offer them, after every SHA-2 algorithm, for an old
|
|
99
|
+
server that cannot be upgraded.
|
|
83
100
|
:param aspects: Default command aspects for operations.
|
|
84
101
|
"""
|
|
102
|
+
if jump is not None:
|
|
103
|
+
# Connecting straight to the target while a jump host is configured would silently take a
|
|
104
|
+
# different network path than the one asked for (and usually fail to reach the target).
|
|
105
|
+
errmsg_lines = [
|
|
106
|
+
"A jump host was configured for host '{}', but jump hosts are not supported by the".format(host),
|
|
107
|
+
"'ccai.protocols.ssh' client.",
|
|
108
|
+
"JUMP: {!r}".format(jump),
|
|
109
|
+
"",
|
|
110
|
+
"Use the paramiko based 'ccai.interop.protocols.ssh.sshagent.SshAgent', which supports jump",
|
|
111
|
+
"hosts, or connect without a jump host."
|
|
112
|
+
]
|
|
113
|
+
errmsg = os.linesep.join(errmsg_lines)
|
|
114
|
+
raise ConfigurationError(errmsg) from None
|
|
115
|
+
|
|
85
116
|
self._host = host
|
|
86
117
|
|
|
87
118
|
self._primary_credential = primary_credential
|
|
@@ -114,6 +145,14 @@ class SshBase(ISystemContext):
|
|
|
114
145
|
self._target_tag = "[{}]".format(called_id)
|
|
115
146
|
|
|
116
147
|
self._look_for_keys = look_for_keys
|
|
148
|
+
self._verify_host_keys = verify_host_keys
|
|
149
|
+
self._known_hosts_path = None
|
|
150
|
+
if known_hosts_path is not None:
|
|
151
|
+
self._known_hosts_path = os.path.expanduser(os.path.expandvars(known_hosts_path))
|
|
152
|
+
if not os.path.isfile(self._known_hosts_path):
|
|
153
|
+
errmsg = "The known_hosts file '{}' passed as 'known_hosts_path' does not exist.".format(known_hosts_path)
|
|
154
|
+
raise ConfigurationError(errmsg) from None
|
|
155
|
+
self._allow_legacy_algorithms = allow_legacy_algorithms
|
|
117
156
|
self._aspects = aspects
|
|
118
157
|
|
|
119
158
|
self._ipaddr = socket.gethostbyname(self._host)
|
|
@@ -125,6 +164,13 @@ class SshBase(ISystemContext):
|
|
|
125
164
|
raise ConfigurationError("SshAgent requires either a 'password', an identity 'keyfile', 'keyraw' or allow_agent=True be specified.") from None
|
|
126
165
|
return
|
|
127
166
|
|
|
167
|
+
@property
|
|
168
|
+
def allow_legacy_algorithms(self) -> bool:
|
|
169
|
+
"""
|
|
170
|
+
A value indicating if the legacy SHA-1 based SSH algorithms are offered (``True``) or not (``False``).
|
|
171
|
+
"""
|
|
172
|
+
return self._allow_legacy_algorithms
|
|
173
|
+
|
|
128
174
|
@property
|
|
129
175
|
def aspects(self) -> AspectsCmd:
|
|
130
176
|
"""
|
|
@@ -153,6 +199,13 @@ class SshBase(ISystemContext):
|
|
|
153
199
|
"""
|
|
154
200
|
return self._jump
|
|
155
201
|
|
|
202
|
+
@property
|
|
203
|
+
def known_hosts_path(self) -> Optional[str]:
|
|
204
|
+
"""
|
|
205
|
+
The additional known_hosts file loaded when host keys are verified.
|
|
206
|
+
"""
|
|
207
|
+
return self._known_hosts_path
|
|
208
|
+
|
|
156
209
|
@property
|
|
157
210
|
def look_for_keys(self):
|
|
158
211
|
"""
|
|
@@ -188,6 +241,13 @@ class SshBase(ISystemContext):
|
|
|
188
241
|
"""
|
|
189
242
|
return self._users
|
|
190
243
|
|
|
244
|
+
@property
|
|
245
|
+
def verify_host_keys(self) -> bool:
|
|
246
|
+
"""
|
|
247
|
+
A value indicating if unknown host keys are rejected (``True``) or auto-accepted (``False``).
|
|
248
|
+
"""
|
|
249
|
+
return self._verify_host_keys
|
|
250
|
+
|
|
191
251
|
def lookup_user_by_uid(self, uid: int, update: bool = True) -> Union[str, None]:
|
|
192
252
|
"""
|
|
193
253
|
A helper method used to lookup cached user information by uid.
|
|
@@ -328,18 +388,15 @@ class SshBase(ISystemContext):
|
|
|
328
388
|
pkey = self._load_key(cl_keyraw, cl_keypasswd)
|
|
329
389
|
|
|
330
390
|
ssh_client = SshClient()
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
else:
|
|
341
|
-
ssh_client.connect(self._ipaddr, port=self._port, username=cl_username, password=cl_password,
|
|
342
|
-
pkey=pkey, allow_agent=cl_allow_agent, look_for_keys=self._look_for_keys)
|
|
391
|
+
self._apply_host_key_policy(ssh_client)
|
|
392
|
+
|
|
393
|
+
# A jump host is refused by the constructor, so the connection always goes straight to the
|
|
394
|
+
# target. The host key is looked up under the address connected to and under the configured
|
|
395
|
+
# host name, which is the name a known_hosts file normally records.
|
|
396
|
+
ssh_client.connect(self._ipaddr, port=self._port, username=cl_username, password=cl_password,
|
|
397
|
+
pkey=pkey, allow_agent=cl_allow_agent, look_for_keys=self._look_for_keys,
|
|
398
|
+
host_key_aliases=[self._host],
|
|
399
|
+
allow_legacy_algorithms=self._allow_legacy_algorithms)
|
|
343
400
|
|
|
344
401
|
break
|
|
345
402
|
|
|
@@ -373,6 +430,41 @@ class SshBase(ISystemContext):
|
|
|
373
430
|
|
|
374
431
|
return ssh_client
|
|
375
432
|
|
|
433
|
+
def _apply_host_key_policy(self, ssh_client: SshClient):
|
|
434
|
+
"""
|
|
435
|
+
Applies the host key verification settings of this object to an SshClient.
|
|
436
|
+
|
|
437
|
+
:param ssh_client: The :class:`SshClient` to configure before it connects.
|
|
438
|
+
"""
|
|
439
|
+
if self._verify_host_keys:
|
|
440
|
+
# Verify against the known_hosts files and reject unknown keys.
|
|
441
|
+
ssh_client.load_system_host_keys()
|
|
442
|
+
if self._known_hosts_path is not None:
|
|
443
|
+
ssh_client.load_host_keys(self._known_hosts_path)
|
|
444
|
+
ssh_client.set_missing_host_key_policy(RejectPolicy())
|
|
445
|
+
else:
|
|
446
|
+
# Explicit opt-out: auto-accept unknown host keys (convenient for ephemeral
|
|
447
|
+
# lab devices; does NOT protect against MITM).
|
|
448
|
+
ssh_client.set_missing_host_key_policy(AutoAddPolicy())
|
|
449
|
+
return
|
|
450
|
+
|
|
451
|
+
def _apply_decode_errors(self, stdout: str, stderr: str, aspects: AspectsCmd) -> Tuple[str, str]:
|
|
452
|
+
"""
|
|
453
|
+
Applies the output decode error handler selected by the aspects. The SSH helpers decode
|
|
454
|
+
with 'surrogateescape', which keeps undecodable bytes, so the conversion is lossless.
|
|
455
|
+
|
|
456
|
+
:param stdout: The standard output of the command.
|
|
457
|
+
:param stderr: The error output of the command.
|
|
458
|
+
:param aspects: The aspects of the call; ``aspects.decode_errors`` selects the handler. Aspects
|
|
459
|
+
from an interop release without that setting use the default.
|
|
460
|
+
|
|
461
|
+
:returns: The standard output and error output decoded with the selected handler.
|
|
462
|
+
"""
|
|
463
|
+
decode_errors = getattr(aspects, "decode_errors", DEFAULT_OUTPUT_DECODE_ERRORS)
|
|
464
|
+
stdout = redecode_output(stdout, decode_errors)
|
|
465
|
+
stderr = redecode_output(stderr, decode_errors)
|
|
466
|
+
return stdout, stderr
|
|
467
|
+
|
|
376
468
|
def _directory(self, ssh_client: SshClient, root_dir: str) -> dict:
|
|
377
469
|
"""
|
|
378
470
|
Private method that creates a directory listing for the folder.
|
|
@@ -546,6 +638,7 @@ class SshBase(ISystemContext):
|
|
|
546
638
|
status, stdout, stderr = self._ssh_execute_command(ssh_runner, command, pty_params=pty_params,
|
|
547
639
|
inactivity_timeout=inactivity_timeout, inactivity_interval=inactivity_interval)
|
|
548
640
|
|
|
641
|
+
stdout, stderr = self._apply_decode_errors(stdout, stderr, aspects)
|
|
549
642
|
self._log_command_result(command, status, stdout, stderr, exp_status, logging_pattern)
|
|
550
643
|
|
|
551
644
|
# DO_UNTIL_SUCCESS, run the command until we get a successful expected result or a completion timeout has occured
|
|
@@ -560,6 +653,7 @@ class SshBase(ISystemContext):
|
|
|
560
653
|
status, stdout, stderr = self._ssh_execute_command(ssh_runner, command, pty_params=pty_params,
|
|
561
654
|
inactivity_timeout=inactivity_timeout, inactivity_interval=inactivity_interval)
|
|
562
655
|
|
|
656
|
+
stdout, stderr = self._apply_decode_errors(stdout, stderr, aspects)
|
|
563
657
|
self._log_command_result(command, status, stdout, stderr, exp_status, logging_pattern)
|
|
564
658
|
|
|
565
659
|
if isinstance(exp_status, int):
|
|
@@ -596,6 +690,7 @@ class SshBase(ISystemContext):
|
|
|
596
690
|
status, stdout, stderr = self._ssh_execute_command(ssh_runner, command, pty_params=pty_params,
|
|
597
691
|
inactivity_timeout=inactivity_timeout, inactivity_interval=inactivity_interval)
|
|
598
692
|
|
|
693
|
+
stdout, stderr = self._apply_decode_errors(stdout, stderr, aspects)
|
|
599
694
|
self._log_command_result(command, status, stdout, stderr, exp_status, logging_pattern)
|
|
600
695
|
|
|
601
696
|
if isinstance(exp_status, int):
|