Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for transparent proxying on Linux #197

Merged
merged 2 commits into from
Mar 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ PyRDP was [introduced in 2018](https://www.gosecure.net/blog/2018/12/19/rdp-man-
- [Choosing when to resume normal activity](#choosing-when-to-resume-normal-activity)
+ [Other MITM arguments](#other-mitm-arguments)
- [--no-downgrade](#--no-downgrade)
- [--transparent](#--transparent)
* [Using the PyRDP Player](#using-the-pyrdp-player)
+ [Playing a replay file](#playing-a-replay-file)
+ [Listening for live connections](#listening-for-live-connections)
Expand Down Expand Up @@ -332,6 +333,60 @@ to be established. The following are currently not affected by this switch and w
RDP traffic using Wireshark and keep the TLS master secrets. Whenever PyRDP adds support for additional extensions,
it would then become possible to extract a valid RDP replay file from the raw network capture.

##### `--transparent`

Tells PyRDP to attempt to spoof the source IP address of the client so that the server sees the real IP
address instead of the MITM one. This option is only useful in certain scenarios where the MITM is physically
a gateway between clients and the server and sees all traffic. It requires root privileges, only works on
Linux and requires manual firewall configuration to ensure that traffic is router properly. The following is
an example configuration:

```bash
# Additional configuration required on the MITM (example)
# +--------+ +------+ +--------+
# | CLIENT | <-- 1 --> | MITM | <--- 2 ---> | SERVER |
# +--------+ +------+ +--------+
# 10.6.6.6 10.1.1.1 10.2.2.2

# The IP of the RDP server which will receive proxied connections.
SERVER_IP=10.2.2.2

# The mark number to use in iptables (should be fine as-is)
MARK=1

# The routing table ID for custom rules (should be fine as-is)
TABLE_ID=100

# Create a custom routing table for pyrdp traffic
echo "$TABLE_ID pyrdp" >> /etc/iproute2/rt_tables
alxbl marked this conversation as resolved.
Show resolved Hide resolved

# Route RDP traffic intended for the target server to local PyRDP (1)
iptables -t nat \
-A PREROUTING \
-d $SERVER_IP \
-p tcp -m tcp --dport 3389 \
-j REDIRECT --to-port 3389

# Mark RDP traffic intended for clients (2)
iptables -t mangle -A PREROUTING \
-s $SERVER_IP \
-m tcp -p tcp --sport 3389 \
-j MARK --set-mark $MARK

# Set route lookup to the pyrdp table for marked packets.
ip rule add fwmark $MARK lookup $TABLE_ID

# Add a custom route that redirects traffic intended for the outside world to loopback
# So that server-client traffic passes through PyRDP
# This table will only ever be used by RDP so it should not be problematic
ip route add local dev lo table $TABLE_ID
```

This setup is a base example and might be much more complex depending on your environment and constraints.
To cleanup, you should delete the created routes, remove the custom routing table from `rt_tables` and
remove the `ip rule`.


### Using the PyRDP Player
Use `pyrdp-player.py` to run the player.

Expand Down
2 changes: 1 addition & 1 deletion pyrdp/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@
from pyrdp.core.stream import ByteStream, StrictStream
from pyrdp.core.subject import ObservedBy, Subject
from pyrdp.core.timer import Timer
from pyrdp.core.twisted import AwaitableClientFactory
from pyrdp.core.twisted import AwaitableClientFactory, connectTransparent
41 changes: 40 additions & 1 deletion pyrdp/core/twisted.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@

import asyncio
from typing import Callable, Union
import socket
import logging

from twisted.internet.protocol import ClientFactory, Protocol
from twisted.internet import tcp, fdesc, reactor

LOG = logging.getLogger(__name__)


class AwaitableClientFactory(ClientFactory):
Expand All @@ -29,4 +34,38 @@ def buildProtocol(self, addr):
if callable(self.protocol):
return self.protocol()
else:
return self.protocol
return self.protocol


class TransparentClient(tcp.Client):
"""A TCP client that supports transparent proxying."""

def createInternetSocket(self):
"""Overridden"""

err = None
s = socket.socket(self.addressFamily, self.socketType)
s.setblocking(0)
fdesc._setCloseOnExec(s.fileno())

try:
if not s.getsockopt(socket.SOL_IP, socket.IP_TRANSPARENT):
s.setsockopt(socket.SOL_IP, socket.IP_TRANSPARENT, 1)
except Exception as e:
LOG.error('Failed to establish transparent proxy: %s', e)

return s # Maintain non-transparent behavior.


class TransparentConnector(tcp.Connector):
"""A TCP connector which creates TransparentClients."""

def _makeTransport(self):
return TransparentClient(self.host, self.port, self.bindAddress, self, self.reactor)


def connectTransparent(host, port, factory, timeout=30, bindAddress=None):
"""Create a transparent proxy connection managed by Twisted."""
c = TransparentConnector(host, port, factory, timeout, bindAddress, reactor)
c.connect()
return c
8 changes: 6 additions & 2 deletions pyrdp/mitm/RDPMITM.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from twisted.internet import reactor
from twisted.internet.protocol import Protocol

from pyrdp.core import AsyncIOSequencer, AwaitableClientFactory
from pyrdp.core import AsyncIOSequencer, AwaitableClientFactory, connectTransparent
from pyrdp.core.ssl import ClientTLSContext, ServerTLSContext
from pyrdp.enum import MCSChannelName, ParserMode, PlayerPDUType, ScanCode, SegmentationPDUType
from pyrdp.layer import ClipboardLayer, DeviceRedirectionLayer, LayerChainItem, RawLayer, \
Expand Down Expand Up @@ -178,7 +178,11 @@ async def connectToServer(self):
"""

serverFactory = AwaitableClientFactory(self.server.tcp)
reactor.connectTCP(self.config.targetHost, self.config.targetPort, serverFactory)
if self.config.transparent:
src = self.client.tcp.transport.client
connectTransparent(self.config.targetHost, self.config.targetPort, serverFactory, bindAddress=(src[0], 0))
else:
reactor.connectTCP(self.config.targetHost, self.config.targetPort, serverFactory)

await serverFactory.connected.wait()

Expand Down
2 changes: 2 additions & 0 deletions pyrdp/mitm/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ def buildArgParser():
parser.add_argument("--no-replay", help="Disable replay recording", action="store_true")
parser.add_argument("--no-downgrade", help="Disables downgrading of unsupported extensions. This makes PyRDP harder to fingerprint but might impact the player's ability to replay captured traffic.", action="store_true")
parser.add_argument("--no-files", help="Do not extract files transferred between the client and server.", action="store_true")
parser.add_argument("--transparent", help="Spoof source IP for connections to the server (See README)", action="store_true")

return parser

Expand Down Expand Up @@ -197,6 +198,7 @@ def configure(cmdline=None) -> MITMConfig:
config.crawlerIgnoreFileName = args.crawler_ignore_file
config.recordReplays = not args.no_replay
config.downgrade = not args.no_downgrade
config.transparent = args.transparent
config.extractFiles = not args.no_files
config.disableActiveClipboardStealing = args.disable_active_clipboard

Expand Down