Git Product home page Git Product logo

ssh-mitm's Introduction

SSH-MITM - ssh audits made simple

SSH-MITM intercepting password login

ssh man-in-the-middle (ssh-mitm) server for security audits supporting
publickey authentication, session hijacking and file manipulation

Download as an AppImage     Download on Flathub     Get it from the Snap Store

Contributors

Table of Contents

Introduction

Code style: black CodeFactor Documentation Status PRs Welcome GitHub

SSH-MITM is a man in the middle SSH Server for security audits and malware analysis.

Password and publickey authentication are supported and SSH-MITM is able to detect, if a user is able to login with publickey authentication on the remote server. This allows SSH-MITM to accept the same key as the destination server. If publickey authentication is not possible, the authentication will fall back to password-authentication.

When publickey authentication is possible, a forwarded agent is needed to login to the remote server. In cases, when no agent was forwarded, SSH-MITM can rediredt the session to a honeypot.

(back to top)

Features

  • publickey authentication
  • hijacking and logging of terminal sessions
  • store and replace files during SCP/SFTP file transferes
  • port porwarding
    • SOCKS 4/5 support for dynamic port forwarding
  • intercept MOSH connections
  • audit clients against known vulnerabilities
  • plugin support

(back to top)

Installation

SSH-MITM can be installed as a Flatpak, Ubuntu Snap, AppImage and PIP-Package.

Community-supported options include installations via `Nix and running on Android devices.

Install from Flathub:

flatpak install flathub at.ssh_mitm.server
flatpak run at.ssh_mitm.server

Install from Snap store:

sudo snap install ssh-mitm

Install as AppImage:

wget https://github.com/ssh-mitm/ssh-mitm/releases/latest/download/ssh-mitm-x86_64.AppImage
chmod +x ssh-mitm*.AppImage

Install python package:

python3 -m pip install ssh-mitm

For more installation methods, refer to the SSH-MITM installation guide.

(back to top)

Quickstart

To start SSH-MITM, all you have to do is run this command in your terminal of choice.

ssh-mitm server --remote-host 192.168.0.x

Now let's try to connect. SSH-MITM is listening on port 10022.

ssh -p 10022 testuser@proxyserver

You will see the credentials in the log output.

INFO     Remote authentication succeeded
    Remote Address: 127.0.0.1:22
    Username: testuser
    Password: secret
    Agent: no agent

(back to top)

Session hijacking

Getting the plain text credentials is only half the fun. When a client connects, the ssh-mitm starts a new server, which is used for session hijacking.

INFO     ℹ created mirrorshell on port 34463. connect with: ssh -p 34463 127.0.0.1

To hijack the session, you can use your favorite ssh client.

ssh -p 34463 127.0.0.1

Try to execute somme commands in the hijacked session or in the original session.

The output will be shown in both sessions.

(back to top)

Phishing FIDO Tokens

SSH-MITM is able to phish FIDO2 Tokens which can be used for 2 factor authentication.

The attack is called trivial authentication (CVE-2021-36367, CVE-2021-36368) and can be enabled with the command line argument --enable-trivial-auth.

ssh-mitm server --enable-trivial-auth

Using the trivial authentication attack does not break password authentication, because the attack is only performed when a publickey login is possible.

Video explaining the phishing attack:
Click to view video on vimeo.com
Click to view video on vimeo.com

Downlaod presentation slides

(back to top)

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

See also the list of contributors who participated in this project.

(back to top)

Contact

(back to top)

ssh-mitm's People

Contributors

branchvincent avatar dependabot[bot] avatar fabaff avatar gbyx3 avatar gitter-badger avatar jakobjbauer avatar janbbeck avatar jxhor avatar luan1973 avatar lukebarone avatar manfred-kaiser avatar mlocutus avatar nsauzede avatar schettn avatar the5imon avatar thement avatar yosida95 avatar zoey-fux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ssh-mitm's Issues

Integrate ContainerSSH as Backend Server for Honey Pots

ContainersSSH (https://github.com/ContainerSSH/ContainerSSH) allows connecting SSH sessions to Docker/Kubernetes Containers Shell Sessions instead of a local terminal.

With such an approach, it is possible to create honey pots or endpoints for malware analysis.

ContainerSSH uses an authentication service and a configuration service. This could be integrated as a SSH-MITM authentication plugin.

This allows the same credentials for public key authentication against ssh-mitm and ContainerSSH. Password authentication is not required, because SSH-MITM can reuse password authentication to connect to ContainerSSH.

SSH-MITM authentication Interface:

import paramiko
from ssh_proxy_server.clients.ssh import AuthenticationMethod
from ssh_proxy_server.authentication import Authenticator


class ExampleAuthenticator(Authenticator):

    def get_remote_host_credentials(self, username):
        # returns a tuple with (username, remotehost, remoteport)
        # example:
        # return ("username", '127.0.0.1', 22)
        # call ContainerSSH authentication and config service
        raise NotImplementedError("implement call to ContainerSSH auth and config interface")

    def auth_agent(self, username, host, port):
        return self.connect(username, host, port, AuthenticationMethod.agent)

    def auth_password(self, username, host, port, password):
        return self.connect(username, host, port, AuthenticationMethod.password, password=password)

    def auth_publickey(self, username, host, port, key):
        if key.can_sign():
            return self.connect(username, host, port, AuthenticationMethod.publickey, key=key)
        return paramiko.AUTH_FAILED

GUI for SSH-MITM

The next release of SSH-MITM will include a simple GUI. This gui is intended if you want to quick start with ssh audits. It's still possible to use ssh-mitm from the command line.

The gui will not replace the command line interface and it's still recommended to use the cli version. The reason is, the the command line version supports all features, while the gui supports only the most used features.

ssh-mitm-gui-1

If you want to test the gui, you can checkout the develop branch and install ssh-mitm from the local git repository.

The gui is based on Gooey.

Gooey requires wxPython to be installed. You should check if prebuilt packages for your distribution exists: https://extras.wxpython.org/wxPython4/extras/linux/gtk3/

After installing wxPython, you can install SSH-MITM from your local the develop branch.

pip install /path/to/local/repo[gui]

The gui can be started with the command ssh-mitm-gui

Snap Package:

The Snap Package will be bundled with all packages required to run the gui and will be integrated in the app drawer of your desktop. It's still possible (and recommended) to use SSH-MITM from the command line.

AppImage:
The App will not contain the gui.

CVE-2020-14145- the list of algorithms can be different by different ssh clients.

the list of algorithms can be different by different ssh clients.

On my machine, the DEFAULT_HOST_KEY_ALGOS are:

['[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521', 'ssh-ed25519', 'rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa']

When reconnecting to the ssh-mitm server with another key, I got:

['[email protected]', 'rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa', '[email protected]', '[email protected]', '[email protected]', '[email protected]', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521', 'ssh-ed25519']

I think we should check the client version and/or compare to a list of knows default host key algorithms.

Originally posted by @manfred-kaiser in #34 (comment)

ProxyJump does not work with ssh-mitm

since version 0.4.0 ssh-mitm supports port forwarding.

When ProxyJump is used, ssh-mitm should forward the port with 'channel_direct_tcpip_request', but the client does not connect to the remote server.

Snap interfaces - least privileges for file system access

SSH-MITM needs to read and write files in the filesystem.

At the moment I have only defined network and network-bind which are necessary to accept connections and create new connections (since it's a man in the middle server)

My tool allows to load a private ssh key, which is used as a server key. If I want to use an existing server key, I need access to /etc/ssh.

It's also possible to create a new private key. The default location for new keys is ~/.ssh but can be stored in other locations.

To create a log of an intercepted session, I need to create files. Those files are used to store the session and transferred files.

It's also possible to replace files, which are transferred over scp or sftp, which needs to read files.

I think I need following interfaces:

  • system-files -> read ssh host keys from /etc/ssh
  • ssh-keys -> needed to read private ssh keys, but I'm not sure if this is only needed when reading keys from ~/.ssh or all keys
  • personal-files -> needed to create the session log and read files, which are used for replacing during file transferrs
  • home -> also allowes to access the users home folder -> which is better and what is the difference?

Support for Port Forwarding

Port forwarding should be supported.

To intercept the tcp traffic, plugins should be possible. support for port forwarding will be implemented in the "tcp-proxy-server" project.

Interface for plugnins:

class TcpProxyHandler(Module):

    def process(self, isclient: bool, data: Optional[bytes]) -> Optional[bytes]:
        if not data:
            return None
        try:
            execute_func = self.execute_client if isclient else self.execute_server
            return execute_func(data)
        except NotImplementedError:
            try:
                return self.execute(isclient, data)
            except NotImplementedError:
                return data

    def execute(self, isclient: bool, data: bytes) -> Optional[bytes]:
        raise NotImplementedError()

    def execute_client(self, data: bytes) -> Optional[bytes]:
        raise NotImplementedError()

    def execute_server(self, data: bytes) -> Optional[bytes]:
        raise NotImplementedError()

    def on_close(self) -> None:
        pass

Example Hex Dump Plugin:

class TcpProxyHexDump(TcpProxyHandler):

    @classmethod
    def parser_arguments(cls) -> None:
        cls.PARSER.add_argument(
            '--hexwidth',
            dest='hexwidth',
            type=int,
            default=16,
            help='width of the hexdump in chars'
        )

    def execute(self, isclient: bool, data: bytes) -> Optional[bytes]:
        # this is a pretty hex dumping function directly taken from
        # http://code.activestate.com/recipes/142812-hex-dumper/
        print("{}:".format("Client" if isclient else "Server"))
        result = []

        for i in range(0, len(data), self.args.hexwidth):
            s = data[i:i + self.args.hexwidth]
            hexa = list(map(''.join, zip(*[iter(binascii.hexlify(s).decode('utf-8'))] * 2)))
            while self.args.hexwidth - len(hexa) > 0:
                hexa.append(' ' * 2)
            text = ''.join([chr(x) if 0x20 <= x < 0x7F else '.' for x in s])
            addr = '%04X:    %s    %s' % (i, " ".join(hexa), text)
            result.append(addr)

        print('\n'.join(result))
        return data

set banner to custom string

sometimes, it would be usefull to set the banner to something else then paramikos default banner.

When setting the banner, other server names can be spoofed to trick clients, which checks the banners.

This is described in: https://stackoverflow.com/a/41807052

transport.local_version = 'SSH-2.0-My sshd 1.0'
transport.start_server(...)

Request for docs on specific use case: intercepting proxy traffic

I have a specific use case, and I'm looking for help creating documentation for this use case.

I want to intercept all outgoing SSH connections from the computer I'm running ssh-mitm on. The computer is running a proxy for a lot of web traffic and SSH connections of users I need to pen test, and I want to intercept outgoing connections from the proxy.

How can I set up routing tables to perform this? I'm assuming I need to run ssh-mitm in transparent mode, but I'm having trouble following the rest of the guide.

Any help directly, or by means of creating formal documentation would be quite helpful. I can help create docs for others wishing to do this if someone can help get me started. Thank you!

Just a quick question

yo, everything works great thanks alright uh what I want to know is how would I go about spoofing my ipv4 and being able to connect with ssh-mitm.

i run sudo ifconfig wlan0 my desired phone ipv4 and use termux on another device to connect via ssh desired ipv4 -p 10022 and I'm not able to connect ssh just hangs.

:{

mitm upload error

Describe the bug
All commands from ssh are going well to openssh and dropbearssh both, but uploading it pause all entire process and wait undefined, ssh and scp working together, should forward and continue, i see debug that file upload looks similar but it never end

Redirect commands for inspection

I am not sure if this is possible with ssh-mitm, but I'll give it a try. I am looking at redirecting all commands that the client enters after ssh login is completed. The reason is that i need to automatedly allow certain commands and deny certain commands. The destination server is not within my control, so i am unable to do this there, but i am hoping I could monitor all commands via ssh-mitm. Any ideas?

Exit status not passed between server and client

When executing a command, which returns an exit code > 0, this exit code is not passed to the client

Example code with ssh2-python

import os
import socket

from ssh2.session import Session

host = 'localhost'
user = os.getlogin()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, 22))

session = Session()
session.handshake(sock)
session.agent_auth(user)

channel = session.open_session()
channel.execute('echo me; exit 2')
size, data = channel.read()
while size > 0:
    print(data)
    size, data = channel.read()
channel.close()
print("Exit status: %s" % channel.get_exit_status())

Without ssh-mitm:

b'me\n'
Exit status: 2

With ssh-mitm:

b'me\n'
Exit status: 0

ssh-mitm is not able to intercept traffic from proxifier and sockd (socks5)

I'm trying to intercept SSH connections going from my SOCKS5 server. When I type "ssh 185.163.45.155 -l root" on my SOCKS server everything works fine (log1.txt), but when I connect from another client using my proxy server and type "ssh 185.163.45.155 -l root" it stuck after accepting password (log2.txt). When I disable traffic redirection to ssh-mitm everything works fine.

log2.txt

log1.txt

support for rsync

rsync is a common tool to sync files between a client and a server. It would be interesting to log, which files are synced.

Storing whole files would not be supported, because rsync uses delta sync.

removeing @typechecked decorator will remove development complexity

You have annotated all you classes and functions. While this helps to find bug easier, it add an additional layer of complexity.

Typechecks also reduces the performance of your application and you need to call it with PYTHONOPTIMIZE=1

I think it's better to do it the other way and only add typechecks during development.

typeguard has an importhook, which allows to annotate all functions and classes with the @typechecked-decorator.

You can add in cli.py following code before importing your sshmitm modules:

if os.getenv('TYPECHECKED'):
    from typeguard import importhook
    importhook.install_import_hook('sshmitm')

With those changes, you only need to call your application with: TYPECHECKED=1 ssh-mitm server

TypeError: check_global_request() takes 2 positional arguments but 3 were given

Describe the bug

paramiko.server.ServerInterface requires check_global_request to take 3 positional arguments, but ssh_proxy_server.interfaces.ServerInterface.check_global_request takes only 2 positional arguments.

https://github.com/paramiko/paramiko/blob/a598ca14d6451343c69be97e0e1c65eb15c0e607/paramiko/server.py#L345

def check_global_request(self, msg):

[11/18/21 15:39:36] ERROR    Unknown exception: check_global_request() takes 2 positional arguments but 3 were given
                    ERROR    Traceback (most recent call last):
                    ERROR      File "/snap/ssh-mitm/27/lib/python3.6/site-packages/ssh_proxy_server/workarounds/dropbear.py", line 123, in transport_run
                    ERROR        self._handler_table[ptype](self, m)
                    ERROR      File "/snap/ssh-mitm/27/lib/python3.6/site-packages/paramiko/transport.py", line 2644, in _parse_global_request
                    ERROR        ok = self.server_object.check_global_request(kind, m)
                    ERROR    TypeError: check_global_request() takes 2 positional arguments but 3 were given

To Reproduce

Steps to reproduce the behavior:

  1. Launch ssh-mitm: ssh-mitm --remote-host 127.0.0.1:22
  2. Connect to the ssh-mitm instance: ssh -p 10022 [email protected]
  3. Wait for a while

Expected behavior

The TypeError exception does not happen and the connection keeps alive.

Pyinstaller on this repo misses "Interfaces" and "Forwarders"

Describe the bug
Running pyinstaller on this repo misses "interfaces" like mirrorshell and "forwarders".

To Reproduce
Steps to reproduce the behavior:
pyinstaller --onefile --clean sshmitm/cli.py
./dist/cli server --help

Expected behavior
Doing python3 ./sshmitm/cli.py server --help shows forwarders and interfaces. I'd expect that.

Screenshots
image

Desktop (please complete the following information):

  • Should be irrelevant but it's FreeBSD 12

Packages for Linux Distributins

It would be nice, if ssh-mitm is available through the distributions package management systems.

  • Kali Linux
  • BlackArch
  • Ubuntu
  • Debian
  • ...

Add support for Dropbear client

Dropbear SSH server endpoint on iPhone SE 14.4 is working unstable when SSH-mitm is enabled basically all SFTP requests crash it, some example below:

Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/paramiko/sftp_client.py", line 130, in init
server_version = self._send_version()
File "/usr/local/lib/python3.9/site-packages/paramiko/sftp.py", line 134, in _send_version
t, data = self._read_packet()
File "/usr/local/lib/python3.9/site-packages/paramiko/sftp.py", line 201, in _read_packet
x = self._read_all(4)
File "/usr/local/lib/python3.9/site-packages/paramiko/sftp.py", line 188, in _read_all
raise EOFError()
EOFError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/local/lib/python3.9/site-packages/ssh_proxy_server/clients/sftp.py", line 32, in from_client
sftp._sftp = paramiko.SFTPClient.from_transport(ssh_client.transport)
File "/usr/local/lib/python3.9/site-packages/paramiko/sftp_client.py", line 170, in from_transport
return cls(chan)
File "/usr/local/lib/python3.9/site-packages/paramiko/sftp_client.py", line 132, in init
raise SSHException("EOF during negotiation")
paramiko.ssh_exception.SSHException: EOF during negotiation

Question

in a scenario were the attacker has access to the box is there a way that one could run this to hijack any new ssh conenction incoming to the port 22 would the attacker need sudo ?

Thank you

Only one channel permitted at a time

Describe the bug
ssh-mitm complains about only one channel being able to be opened. It also complains about SFTP.

To Reproduce
Find a device that doesn't support SCP / SFTP / is a rudimentary SSH server.
Run ssh-mitm against it.

Expected behavior
I expected it to work fine.

Screenshots
See [screenshot]([url](url
err
))

Desktop (please complete the following information):

  • OS: Win 10 x64

Additional context
The targeted SSH server is a bit on the rudimentary side.

SCP session stuck after file transfer

Hi,

Not sure if this is an issue with paramiko or this utility, but SCP transfers seem to hang once the files got transferred (requiring a good ol CTRL+C to end). From what I can gather from reading the code of the SCP forwarders is that they have no way to tell how many files are being transfered and so just keep waiting for more once the last file being transfered returned an exit code of 0. This makes it very obvious that a mitm attack is occuring since SCP commands usually exit gracefully (With the client ending the connection with a TCP RST ACK). Here is where it ends (stuck) when transferring to the SSH server of a raspberry pi (with a fresh install) from Windows (that itself runs ssh-mitm):

log

Improve documentation

The documentation of SSH-MITM should be improved.

Please help me to write a better documentation. What can you do:

  • fix spelling errors and improve the english
  • add vulnerabilities for ssh clients and server. At the moment, only openssh, putty and dropbear are documented
  • improve or write tutorials how to use ssh-mitm (supported plugins, arp spoofing, ...)

Connection is dropped with MobaXTerm client

Describe the bug
When connecting to ssh-mitm from MobaXTerm client version 21.5, the connection is dropped.

To Reproduce
Steps to reproduce the behavior:

  1. Go to https://mobaxterm.mobatek.net/download-home-edition.html
  2. Download and run MobaXterm Portable v21.5
  3. Create new session to ssh-mitm and try to connect
  4. Connection is dropped

Expected behavior
SSH client successfully connects to SSH server

ssh-mitm debug output

ssh-mitm-x86_64.AppImage -d server --listen-port XXX --remote-host XXX
──────────────────────────────────────────────────────────────────────────────────────── SSH-MITM - ssh audits made simple ─────────────────────────────────────────────────────────────────────────────────────────
Version: 1.0.0
Documentation: https://docs.ssh-mitm.at
Issues: https://github.com/ssh-mitm/ssh-mitm/issues
────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
[03/21/22 15:26:42] INFO     generated temporary RSAKey key with 2048 bit length and fingerprints:                                                                                                   __init__.py:141
                                 MD5:a8:69:09:66:7f:c4:eb:ea:ba:5c:ad:43:69:42:82:3f                                                                                                                 
                                 SHA256:pZGSmr8/zIQF0T9iOjQoT/Pt9lJd2DtpS0iAiqmVy/U                                                                                                                  
                    INFO     listen interfaces 0.0.0.0 and :: on port XXX                                                                                                                          __init__.py:229
[03/21/22 15:26:49] DEBUG    incoming connection from ('::ffff:XXX', XXX, 0, 0) to ('::ffff:XXX', XXX, 0, 0)                                                                   __init__.py:239
                    INFO     ℹ session b7ad0231-d53d-4038-92ce-092043b42a20 created                                                                                                     session.py:68
                    INFO     ℹ connected client version: SSH-2.0-MoTTY_Release_0.76                                                                                              key_negotiation.py:48
                    DEBUG    cookie: 09e3b442f2c200331a53a4920f634839                                                                                                                          key_negotiation.py:51
                    DEBUG    kex_algorithms: ['diffie-hellman-group-exchange-sha256', 'diffie-hellman-group-exchange-sha1', 'diffie-hellman-group14-sha256', 'diffie-hellman-group14-sha1',    key_negotiation.py:52
                             'diffie-hellman-group1-sha1', 'rsa2048-sha256', 'rsa1024-sha1', 'curve448-sha512', 'curve25519-sha256', '[email protected]', 'ecdh-sha2-nistp256',                          
                             'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', 'ext-info-c']                                                                                                                              
                    DEBUG    server_host_key_algorithms: ['ssh-ed448', 'ssh-ed25519', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', 'ecdsa-sha2-nistp521', 'rsa-sha2-512', 'rsa-sha2-256',     key_negotiation.py:53
                             'ssh-rsa', 'ssh-dss']                                                                                                                                                                  
                    DEBUG    encryption_algorithms_client_to_server: ['aes256-ctr', 'aes256-cbc', '[email protected]', 'aes192-ctr', 'aes192-cbc', 'aes128-ctr', 'aes128-cbc',       key_negotiation.py:54
                             '[email protected]', '3des-ctr', '3des-cbc', 'blowfish-ctr', 'blowfish-cbc', 'arcfour256', 'arcfour128']                                                                   
                    DEBUG    encryption_algorithms_server_to_client: ['aes256-ctr', 'aes256-cbc', '[email protected]', 'aes192-ctr', 'aes192-cbc', 'aes128-ctr', 'aes128-cbc',       key_negotiation.py:55
                             '[email protected]', '3des-ctr', '3des-cbc', 'blowfish-ctr', 'blowfish-cbc', 'arcfour256', 'arcfour128']                                                                   
                    DEBUG    mac_algorithms_client_to_server: ['hmac-sha2-256', 'hmac-sha1', 'hmac-sha1-96', 'hmac-md5', '[email protected]', '[email protected]',         key_negotiation.py:56
                             '[email protected]', '[email protected]']                                                                                                                            
                    DEBUG    mac_algorithms_server_to_client: ['hmac-sha2-256', 'hmac-sha1', 'hmac-sha1-96', 'hmac-md5', '[email protected]', '[email protected]',         key_negotiation.py:57
                             '[email protected]', '[email protected]']                                                                                                                            
                    DEBUG    compression_algorithms_client_to_server: ['zlib', '[email protected]', 'none']                                                                                     key_negotiation.py:58
                    DEBUG    compression_algorithms_server_to_client: ['zlib', '[email protected]', 'none']                                                                                     key_negotiation.py:59
                    DEBUG    languages_client_to_server: ['']                                                                                                                                  key_negotiation.py:60
                    DEBUG    languages_server_to_client: ['']                                                                                                                                  key_negotiation.py:61
                    DEBUG    first_kex_packet_follows: False                                                                                                                                   key_negotiation.py:62

Desktop (please complete the following information):

  • OS: Windows 10
  • MobaXterm Portable v21.5

MITM doesn't work

Client gets "Permission denied, please try again." (correct password entered). ssh-mitm is running in transparent mode on Ubuntu 18
log.txt

Infinite feedback loop

Describe the bug
It appears that an infinite feedback loop is happening when I follow the setup instructions to run a transparent proxy.

To Reproduce
Steps to reproduce the behavior:

  1. Follow the Transparent proxy instructions here: https://docs.ssh-mitm.at/advanced-usage.html, including all iptables and similar setup.
  2. Run ssh-mitm --transparent.
  3. Make an ssh connection like ssh test@localhost.
  4. Observe the output in the Actual Behavior section below.

Expected behavior
I expect the program to function properly and output connection details/instructions for the connection.

Actual Behavior
I get this output:

                   INFO     ℹ connected client version: SSH-2.0-SSHMITM_0.6.3                            
                    INFO     ℹ session 90f8646a-58bc-4c8e-983b-694923e5f9b3 created   

Repeat the above section for different session IDs hundreds of times back-to-back.

Desktop (please complete the following information):

  • OS: Ubuntu 20

Extra Info
I'm not certain I'm doing this entirely correctly. If you could advise what misconfiguration could lead to such a feedback loop, that would be helpful as well.

pyinfra - SSH-MITM closes the connection after the first command

SSH-MITM Version

2.0.1

Platform detail

Ubuntu 22.04

Arguments used to start SSH-MITM

ssh-mitm server

SSH client used

pyinfra

SSH server used

OpenSSH 8.9

What steps will reproduce the bug?

pyinfra output

$ pyinfra 127.0.0.1 --ssh-password PASSWORD --ssh-port 10022 fact server.Date server.Hostname

--> Loading config...

--> Loading inventory...

--> Connecting to hosts...
No host key for [127.0.0.1]:10022 found in known_hosts, do you want to continue [y/n] y
    Added host key for [127.0.0.1]:10022 to known_hosts
    [127.0.0.1] Connected

--> Gathering facts...
    [127.0.0.1] Loaded fact server.Date

SSH-MITM output

DEBUG    check_channel_exec_request: channel=<paramiko.Channel 0 (open) window=2097152 ->
	 <paramiko.Transport at 0xdac207c0 (cipher aes128-ctr, 128 bits) (active; 1 open
         channel(s))>>, command=sh -c 'date +'"'"'%Y-%m-%dT%H:%M:%S%z'"'"''
INFO     got ssh command: sh -c 'date +'"'"'%Y-%m-%dT%H:%M:%S%z'"'"''
INFO     ℹ e7aa398c-0f0c-466a-b484-c9b4e3b69291 - session started
INFO     got remote command: sh -c 'date +'"'"'%Y-%m-%dT%H:%M:%S%z'"'"''
DEBUG    [chan 0] SCP closed
INFO     remote command 'sh -c 'date +'"'"'%Y-%m-%dT%H:%M:%S%z'"'"''' exited with code: 0
DEBUG    (('::ffff:127.0.0.1', 42162, 0, 0)->('::ffff:127.0.0.1', 10022, 0, 0)) session exited
DEBUG    (('::ffff:127.0.0.1', 42162, 0, 0)->('::ffff:127.0.0.1', 10022, 0, 0)) closing ssh client to remote
DEBUG    check_channel_request: kind=session , chanid=1
DEBUG    check_channel_exec_request: channel=<paramiko.Channel 1 (open) window=2097152 -> <paramiko.Transport
         at 0xdac207c0 (cipher aes128-ctr, 128 bits) (active; 1 open  server.py:116 channel(s))>>, 
         command=sh -c 'uname -n'
INFO     got ssh command: sh -c 'uname -n'

Analysis
SSH closes the connection to the remote server, but does not establish a new connection. This is the reason why the client does not reveive a response from SSH-MITM and does not continue with executing the commands.

What should have happened?

SSH-MITM should check if the connection is closed or if the connection is still used.

Additional information

No response

ssh commands get stuck when more than one is issued.

First, thank you very much for ssh-mitm!!

This may be related to #46, multiplexing. But maybe not :P
I have a device for which I update the firmware with a program over the local network. I want to peek into the ssh channel that it opens. This works to some extent:

computer with update program: 192.168.255.126
mitm computer 192.168.255.127
device to update 192.168.255.129

$ sudo  ssh-mitm --listen-port 22 --remote-host 192.168.255.129 --scp-interface debug_traffic
2021-07-15 12:52:11,991 [INFO]  starting SSH-MITM 0.5.11
2021-07-15 12:52:12,022 [INFO]  generated temporary RSAKey key with 2048 bit length and fingerprints:
    MD5:c1:ba:3e:8b:dc:30:7e:58:38:45:0d:2e:75:58:e3:8a
    SHA256:H9m+sx9XQnwD3bJwHncQ2HpeEIhTaOqSr7FEvDSQXp8
2021-07-15 12:52:12,024 [INFO]  listen interfaces 0.0.0.0 and :: on port 22
2021-07-15 12:53:21,078 [INFO]  incoming connection from ('::ffff:192.168.255.126', 1998, 0, 0) to ('::ffff:192.168.255.127', 22, 0, 0)
2021-07-15 12:53:21,080 [INFO]  connected client version: ssh-2.0-paramiko_1.15.1
2021-07-15 12:53:21,239 [INFO]  Client connection established with parameters:
	Remote Address: 192.168.255.129
	Port: 22
	Username: *******
	Password: *******
	Key: None
	Agent: no agent

2021-07-15 12:53:21,430 [INFO]  got ssh command: cat /proc/device-tree/module-identity//product-code
Server data:
0000:    34 37 34 34 30 33 41 2e 31 30 31 00                474403A.101.
2021-07-15 12:53:21,627 [INFO]  got ssh command: cat /proc/device-tree/module-identity//serial-number

The second ssh command never returns a value. The serial-number file does exist and the update program gets stuck right as it grabs the product-code and serial-number.

Is the problem that both ssh commands come in at the same time (wild guess based on #46)? In any case, how can I provide more/better information to track this down?

mypy --strict sshmitm/ does not exit without errors

Running mypy --strict sshmitm/ does not exit without errors:

sshmitm/workarounds/dropbear.py:221: error: Unused "type: ignore" comment
sshmitm/forwarders/scp.py:99: error: Unused "type: ignore" comment
sshmitm/forwarders/scp.py:141: error: Item "None" of "Optional[Any]" has no attribute "send_exit_status"
sshmitm/cli.py:125: error: Unexpected keyword argument "args"
sshmitm/cli.py:135: error: Too many arguments for "run"
sshmitm/cli.py:138: error: Too many arguments for "run"
Found 6 errors in 3 files (checked 55 source files)

Replace or modify files during file transfer

ssh proxy server can intercept scp and sftp. For security audits, it should be interesting, if a file can be modified or replaced.

Use cases:

  • scan a file with an antivirus system an replace infected files with a place holder file
  • modify config files and replace username and password
  • modify executable with metasploit

Intercept MOSH connections

What feature you'd like to see or proposal

The next version of SSH-MITM will be able to intercept MOSH connections.

An initial implementation is available in the develop branch. SSH-MITM is able to intercept the ssh connection from MOSH and get the connection info wich contains the shared-secret and the target port.

SSH-MITM starts a new UDP proxy for this connection and redirects the data to the destination server. With the shared secret, it's possible to decrypt the packets sent by MOSH.

image

Unlike SSH, it's not possible to use the decrypted data to store the terminal session with complete input and output and replay the session because of the state synchonisation protocol (SSP). The problem is, there is no full documentation available how to implement a client which is necessary to implement a feature similar to the mirror shell, which can be used to hijack SSH sessions.

There is an open issue ticket for MOSH to provide documentation for the state synchronisation protocol: mobile-shell/mosh#1087

Another issue ticket is for a Wireshark dissector, which is able to decode the plain text data for SSP: mobile-shell/mosh#778

Without more information, it's hard to create a mosh client to hijack MOSH connections.

Perhaps it's possible to mirror the current session to another client, but I think this requires some changes in the mosh client.

I would be glad if some users can test the MOSH connection and give some feedback on this new feature. 😉

SSH-MITM does not require special arguments, you only need to clone the repo, checkout the development branch and install SSH-MITM.

Install SSH-MITM from the develop-branch:

git clone https://github.com/ssh-mitm/ssh-mitm.git
cd ssh-mitm
git checkout develop
python3 -m venv ~/sshenv
source ~/sshenv/bin/activate
pip install -U pip
pip install -U .

Start SSH-MITM:

# test on localhost
ssh-mitm server

# test with a remote ssh server
ssh-mitm server --remote-host 192.168.x.x

Connect the MOSH client:

mosh --ssh="ssh -p 10022" testuser@localhost

Note:

SSH-MITM create a temporary server key for each start. This can get annoying because you have to clear the known_hosts for each test. So it's better to start ssh without the fingerprint check. Important! Don't use this in production 😉
If you are using public key authentication, you must forward the agent. See https://docs.ssh-mitm.at/user_guide/authentication.html#publickey-authentication-rfc-4252-7

For testing purposes, you can use following command:

mosh --ssh="ssh -p 10022 -A -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" testuser@localhost

CVE-2020-14145 - OpenSSH Client information leak

CVE-2020-14145 describes am method, which allows to detect, if a client already knows the server fingerprint or not.

If the mitm-server is able to detect, if a client would present a mitm attack, the mitm server could redirect the traffic without interception. This makes it harder to detect mitm attacks on ssh.

When used SSH-MITM during security audits a warning should be generated, that the client is affected by CVE-2020-14145

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.