def __init__(self, fileName: str): """ :param fileName: name of the file to read. """ self.viewer = QRemoteDesktop(800, 600) RDPConnectionTab.__init__(self, self.viewer) self.fileName = fileName self.file = open(self.fileName, "rb") self.eventHandler = PlayerMessageHandler(self.widget, self.text) self.thread = ReplayThread(self.file) self.thread.eventReached.connect(self.readEvent) self.thread.timeUpdated.connect(self.onTimeUpdated) self.thread.clearNeeded.connect(self.clear) self.thread.start() self.controlBar = ControlBar(self.thread.getDuration()) self.controlBar.play.connect(self.thread.play) self.controlBar.pause.connect(self.thread.pause) self.controlBar.seek.connect(self.thread.seek) self.controlBar.speedChanged.connect(self.thread.setSpeed) self.layout().insertWidget(0, self.controlBar) self.tpkt = TPKTLayer() self.message = PlayerMessageLayer() self.tpkt.setNext(self.message) self.message.addObserver(self.eventHandler)
def __init__(self, file: BinaryIO): super().__init__(None) self.queue = Queue() self.lastSeekTime = 0 self.requestedSpeed = 1 events = defaultdict(list) startingPosition = file.tell() file.seek(0, os.SEEK_END) size = file.tell() # Take note of the position of each event and its timestamp file.seek(0) currentMessagePosition = 0 tpkt = TPKTLayer() player = PlayerMessageLayer() tpkt.setNext(player) def registerEvent(pdu: PlayerMessagePDU): events[pdu.timestamp].append(currentMessagePosition) player.createObserver(onPDUReceived=registerEvent) while file.tell() < size: data = file.read(4) tpkt.recv(data) data = file.read(tpkt.getDataLengthRequired()) tpkt.recv(data) currentMessagePosition = file.tell() file.seek(startingPosition) # Use relative timestamps to simplify things self.events = {} if len(events) == 0: self.duration = 0 else: timestamps = sorted(events.keys()) startingTime = timestamps[0] for timestamp in timestamps: relative = timestamp - startingTime self.events[relative] = events[timestamp] self.duration = (timestamps[-1] - startingTime) / 1000.0
def __init__(self): RDPConnectionTab.__init__(self, QRemoteDesktop(1024, 768)) self.tcp = AsyncIOTCPLayer() self.tpkt = TPKTLayer() self.message = PlayerMessageLayer() self.eventHandler = PlayerMessageHandler(self.widget, self.text) Layer.chain(self.tcp, self.tpkt, self.message) self.message.addObserver(self.eventHandler)
def __init__(self, reactor: Reactor, log: logging.Logger): self.reactor = reactor self.log = log self.tcp = TCPCertFetchingLayer() self.tpkt = TPKTLayer() self.x224 = X224Layer() Layer.chain(self.tcp, self.tpkt, self.x224) self.tcp.createObserver(onConnection=self.sendConnectionRequest) self.x224.createObserver(onConnectionConfirm=lambda _: self.startTLS())
def __init__(self, _reactor: Reactor, host: str, port: int): self.reactor = _reactor self.host = host self.port = port self.log = logging.getLogger(f"{LOGGER_NAMES.PYRDP}.clonecert") self.tcp = TCPCertFetchingLayer() self.tpkt = TPKTLayer() self.x224 = X224Layer() LayerChainItem.chain(self.tcp, self.tpkt, self.x224) self.tcp.createObserver(onConnection=self.sendConnectionRequest) self.x224.createObserver(onConnectionConfirm=lambda _: self.startTLS())
def __init__(self): self.tcp = TwistedTCPLayer() self.segmentation = SegmentationLayer() self.tpkt = TPKTLayer() self.x224 = X224Layer() self.mcs = MCSLayer() self.security: SecurityLayer = None self.slowPath = SlowPathLayer() self.fastPath: FastPathLayer = None self.tcp.setNext(self.segmentation) self.segmentation.attachLayer(SegmentationPDUType.TPKT, self.tpkt) LayerChainItem.chain(self.tpkt, self.x224, self.mcs)
def __init__(self, friendlyName: str, targetHost: str, targetPort: int, certificateFileName: str, privateKeyFileName: str, recordHost: str, recordPort: int, replacementUsername: str, replacementPassword: str): MCSUserObserver.__init__(self) self.sessionId = f"{friendlyName}{random.randrange(100000,999999)}" self.log = getLoggerPassFilters( f"{LOGGER_NAMES.MITM_CONNECTIONS}.{self.sessionId}.server") self.metadataFilter = ConnectionMetadataFilter(self, self.sessionId) self.log.addFilter(self.metadataFilter) self.replacementPassword = replacementPassword self.replacementUsername = replacementUsername self.targetHost = targetHost self.targetPort = targetPort self.certificateFileName = certificateFileName self.privateKeyFileName = privateKeyFileName self.clipboardObserver = None self.useTLS = False self.client: MITMClient = None self.clientConnector = None self.originalNegotiationPDU = None self.targetNegotiationPDU = None self.serverData = None self.rc4RSAKey = RSA.generate(2048) self.crypter = RC4CrypterProxy() self.socket = None self.fileHandle = open( "out/rdp_replay_{}_{}.pyrdp".format( datetime.datetime.now().strftime('%Y%m%d_%H-%M-%S'), random.randint(0, 1000)), "wb") rc4Log = getLoggerPassFilters(f"{self.log.name}.rc4") self.securitySettings = SecuritySettings(SecuritySettings.Mode.SERVER) self.securitySettings.addObserver(self.crypter) self.securitySettings.addObserver(RC4LoggingObserver(rc4Log)) self.tcp = TwistedTCPLayer() self.tcp.createObserver(onConnection=self.onConnection, onDisconnection=self.onDisconnection) self.segmentation = SegmentationLayer() self.segmentation.createObserver( onUnknownHeader=self.onUnknownTPKTHeader) self.tpkt = TPKTLayer() self.x224 = X224Layer() self.x224.createObserver(onConnectionRequest=self.onConnectionRequest, onDisconnectRequest=self.onDisconnectRequest) self.mcs = MCSLayer() self.router = MITMServerRouter(self.mcs, self) self.mcs.addObserver(self.router) self.router.createObserver( onConnectionReceived=self.onConnectInitial, onDisconnectProviderUltimatum=self.onDisconnectProviderUltimatum, onAttachUserRequest=self.onAttachUserRequest, onChannelJoinRequest=self.onChannelJoinRequest) self.gcc = GCCParser() self.rdpClientInfoParser = ClientInfoParser() self.rdpClientConnectionParser = ClientConnectionParser() self.rdpServerConnectionParser = ServerConnectionParser() self.securityLayer = None self.slowPathLayer = SlowPathLayer() self.fastPathLayer = None self.tcp.setNext(self.segmentation) self.segmentation.attachLayer(SegmentationPDUType.TPKT, self.tpkt) Layer.chain(self.tpkt, self.x224, self.mcs) if recordHost is not None and recordPort is not None: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.connect((recordHost, recordPort)) except socket.error as e: logging.getLogger(LOGGER_NAMES.MITM).error( "Could not connect to liveplayer: %(error)s", {"error": e}) self.socket.close() self.socket = None recordingLayers = [FileLayer(self.fileHandle)] if self.socket is not None: recordingLayers.append(SocketLayer(self.socket)) # Since we're intercepting communications from the original client (so we're a server), # We need to write back the packets as if they came from the client. self.recorder = Recorder(recordingLayers)
def __init__(self, server, fileHandle: BinaryIO, livePlayerSocket: socket, replacementUsername=None, replacementPassword=None): MCSChannelFactory.__init__(self) self.log = getLoggerPassFilters( f"{LOGGER_NAMES.MITM_CONNECTIONS}.{server.getSessionId()}.client") self.log.addFilter(server.metadataFilter) self.replacementUsername = replacementUsername self.replacementPassword = replacementPassword self.server = server self.channelMap: Dict[int, str] = {} self.channelDefinitions = [] self.channelObservers = {} self.deviceRedirectionObserver = None self.useTLS = False self.user = None self.fastPathObserver = None self.conferenceCreateResponse = None self.serverData = None self.crypter = RC4CrypterProxy() rc4Log = getLoggerPassFilters(f"{self.log.name}.rc4") self.securitySettings = SecuritySettings(SecuritySettings.Mode.CLIENT) self.securitySettings.addObserver(self.crypter) self.securitySettings.addObserver(RC4LoggingObserver(rc4Log)) self.tcp = TwistedTCPLayer() self.tcp.createObserver(onConnection=self.startConnection, onDisconnection=self.onDisconnection) self.segmentation = SegmentationLayer() self.segmentation.createObserver( onUnknownHeader=self.onUnknownTPKTHeader) self.tpkt = TPKTLayer() self.x224 = X224Layer() self.x224.createObserver(onConnectionConfirm=self.onConnectionConfirm, onDisconnectRequest=self.onDisconnectRequest) self.mcs = MCSLayer() self.router = MCSClientRouter(self.mcs, self) self.mcs.addObserver(self.router) self.router.createObserver( onConnectResponse=self.onConnectResponse, onDisconnectProviderUltimatum=self.onDisconnectProviderUltimatum) self.mcsConnect = MCSClientConnectionLayer(self.mcs) self.gccConnect = GCCClientConnectionLayer(b"1") self.gccConnect.createObserver( onPDUReceived=self.onConferenceCreateResponse) self.rdpConnect = ClientConnectionLayer() self.rdpConnect.createObserver(onPDUReceived=self.onServerData) self.securityLayer = None self.slowPathLayer = SlowPathLayer() self.fastPathLayer = None self.tcp.setNext(self.segmentation) self.segmentation.attachLayer(SegmentationPDUType.TPKT, self.tpkt) Layer.chain(self.tpkt, self.x224, self.mcs) Layer.chain(self.mcsConnect, self.gccConnect, self.rdpConnect) record_layers = [FileLayer(fileHandle)] if livePlayerSocket is not None: record_layers.append(SocketLayer(livePlayerSocket)) self.recorder = Recorder(record_layers)
class ReplayTab(RDPConnectionTab): """ Tab that displays a RDP Connection that is being replayed from a file. """ def __init__(self, fileName: str): """ :param fileName: name of the file to read. """ self.viewer = QRemoteDesktop(800, 600) RDPConnectionTab.__init__(self, self.viewer) self.fileName = fileName self.file = open(self.fileName, "rb") self.eventHandler = PlayerMessageHandler(self.widget, self.text) self.thread = ReplayThread(self.file) self.thread.eventReached.connect(self.readEvent) self.thread.timeUpdated.connect(self.onTimeUpdated) self.thread.clearNeeded.connect(self.clear) self.thread.start() self.controlBar = ControlBar(self.thread.getDuration()) self.controlBar.play.connect(self.thread.play) self.controlBar.pause.connect(self.thread.pause) self.controlBar.seek.connect(self.thread.seek) self.controlBar.speedChanged.connect(self.thread.setSpeed) self.layout().insertWidget(0, self.controlBar) self.tpkt = TPKTLayer() self.message = PlayerMessageLayer() self.tpkt.setNext(self.message) self.message.addObserver(self.eventHandler) def readEvent(self, position: int): """ Read an event from the file at the given position. :param position: the position of the event in the file. """ self.file.seek(position) data = self.file.read(4) self.tpkt.recv(data) length = self.tpkt.getDataLengthRequired() data = self.file.read(length) self.tpkt.recv(data) def onTimeUpdated(self, currentTime: float): """ Called everytime the thread ticks. :param currentTime: the current time. """ self.controlBar.timeSlider.blockSignals(True) self.controlBar.timeSlider.setValue(int(currentTime * 1000)) self.controlBar.timeSlider.blockSignals(False) def clear(self): """ Clear the UI. """ self.viewer.clear() self.text.setText("") def onClose(self): self.thread.close()
def addTransportLayer(self, transportLayer: Layer): tpktLayer = TPKTLayer() messageLayer = PlayerMessageLayer() Layer.chain(transportLayer, tpktLayer, messageLayer) self.topLayers.append(messageLayer)