From 57623a6933ac2e2c3fc520cfc4caab235aabf8d1 Mon Sep 17 00:00:00 2001 From: Matias Fernandez Date: Tue, 9 Apr 2019 20:34:12 -0400 Subject: [PATCH] Testing for windows service --- ctrlsrv.py | 327 +++++++++++++++++++++++ lib/common.py | 68 +++++ lib/const.py | 29 ++ lib/encodings/common.py | 19 ++ lib/encodings/cursor.py | 20 ++ lib/encodings/raw.py | 32 +++ lib/log.py | 28 ++ pyvncs/__pycache__/server.cpython-36.pyc | Bin 15348 -> 15507 bytes pyvncs/server.py | 101 +++---- requeriments.txt | 4 +- server.py | 40 ++- test.py | 16 ++ test.sh | 6 + winservice.py | 79 ++++++ 14 files changed, 706 insertions(+), 63 deletions(-) create mode 100755 ctrlsrv.py create mode 100644 lib/common.py create mode 100644 lib/const.py create mode 100644 lib/encodings/common.py create mode 100644 lib/encodings/cursor.py create mode 100644 lib/encodings/raw.py create mode 100644 lib/log.py create mode 100644 test.py create mode 100755 test.sh create mode 100644 winservice.py diff --git a/ctrlsrv.py b/ctrlsrv.py new file mode 100755 index 0000000..cd7fcd3 --- /dev/null +++ b/ctrlsrv.py @@ -0,0 +1,327 @@ +#!/usr/bin/env python3 +# coding=utf-8 +# pyvncs +# Copyright (C) 2017-2018 Matias Fernandez +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + +import pyvncs +from lib import log +from lib import common +from argparse import ArgumentParser +from threading import Thread +import time +import sys +import socket +import signal +import readline +import traceback + +#_debug = log.debug +_debug = print + +if common.isWindows(): + _debug("Wintendo...") + import win32ts + import win32security + import win32con + import win32api + import ntsecuritycon + import win32process + import win32event + +def signal_handler(signal, frame): + _debug("Exiting on signal %s..." % signal) + sys.exit(0) + +signal.signal(signal.SIGINT, signal_handler) + +config = { +} + +class ControlThread(Thread): + def __init__(self, threads): + Thread.__init__(self) + self.threads = threads + self.setDaemon(True) + + def run(self): + # elimina los threads muertos + while True: + time.sleep(1) + for t in threads: + if not t.isAlive(): + _debug("ControlThread removing dead", t) + threads.remove(t) + +class VNCThread(Thread): + def __init__(self, port, password): + Thread.__init__(self) + self.ip = None + self.port = port + self.sock = None + self.password = password + self.setDaemon(True) + + def __del__(self): + _debug("VNCThread died") + + + def run(self): + + TCP_IP = '0.0.0.0' + _debug("[+] Listen...") + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + self.sock.bind((TCP_IP, int(self.port))) + self.sock.listen(4) + (conn, (ip,port)) = self.sock.accept() + + _debug("[+] New server socket started for " + ip + ":" + str(port)) + #_debug("Thread", self) + server = pyvncs.server.VncServer(conn, self.password) + #server.CONFIG._8bitdither = CONFIG._8bitdither + status = server.init() + + if not status: + _debug("Error negotiating client init") + return False + server.protocol() + + +class ClientThread(Thread): + def __init__(self, sock, ip, port, config): + Thread.__init__(self) + self.ip = ip + self.port = port + self.sock = sock + self.setDaemon(True) + self.config = config + + def __del__(self): + _debug("ClientThread died") + + def run(self): + #_debug("[+] New server socket thread started for " + self.ip + ":" + str(self.port)) + #_debug("Thread", self) + f = self.sock.makefile('rw') + + f.write("AUTH:>") + f.flush() + passwd = f.readline().strip("\n") + if passwd != config["PASSWORD"]: + time.sleep(1) + f.write("!NO AUTH") + f.flush() + _debug("NO AUTH '%s' != '%s'" % (passwd, config["PASSWORD"])) + self.sock.close() + return + + while True: + f.write("OK:>") + f.flush() + try: + data = f.readline() + cmd = data.strip() + if not data: break + + if cmd == "_DEBUG": + sys.stdout = sys.stderr = f + f.write("OK\n") + + elif cmd == "PING": + f.write("PONG\n") + + elif cmd == "QUIT": + f.write("BYE\n") + self.sock.close() + return + + elif cmd.startswith("STARTVNC"): + params = cmd.split() + if len(params) != 3: + f.write("!NOT_PARAMS\n") + f.flush() + continue + _debug("START VNC !!!") + newthread = VNCThread(params[1], params[2]) + newthread.setDaemon(True) + newthread.start() + + elif cmd == "_WINSESSIONS" and common.isWindows(): + winsessions = win32ts.WTSEnumerateSessions(win32ts.WTS_CURRENT_SERVER_HANDLE) + print(winsessions, file=f) + + elif cmd == "_WINCONSOLE" and common.isWindows(): + winsessions = win32ts.WTSEnumerateSessions(win32ts.WTS_CURRENT_SERVER_HANDLE) + print(winsessions, file=f) + active = win32ts.WTSGetActiveConsoleSessionId() + print(active, file=f) + token = win32ts.WTSQueryUserToken(active) + print(token, file=f) + duplicated = win32security.DuplicateTokenEx(token, win32con.MAXIMUM_ALLOWED, win32con.NULL, win32security.TokenPrimary, win32security.SECURITY_ATTRIBUTES()) + print("duplicated", token, file=f) + + elif cmd == "_TEST" and common.isWindows(): + winsessions = win32ts.WTSEnumerateSessions(win32ts.WTS_CURRENT_SERVER_HANDLE) + print(winsessions, file=f) + active = win32ts.WTSGetActiveConsoleSessionId() + print(active, file=f) + token = win32ts.WTSQueryUserToken(active) + print("token", token, file=f) + ntoken = win32security.DuplicateTokenEx(token, 3 , win32con.MAXIMUM_ALLOWED , win32security.TokenPrimary , win32security.SECURITY_ATTRIBUTES() ) + print("ntoken", ntoken, file=f) + #th = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.MAXIMUM_ALLOWED) + #print("th", th, file=f) + shell_as2(ntoken, True, "cmd") + + elif cmd == "_EVAL": + while True: + f.write("EV:>") + f.flush() + data = f.readline() + cmd = data.strip() + if cmd == "": continue + if cmd == "_QUIT": break + if not data: break + + try: + eval(data) + except: + print("ERROR:", sys.exc_info()[0], file=f) + print(traceback.format_exc(), file=f) + f.flush() + + _debug("eval:", cmd.strip()) + f.flush() + + elif cmd == "_ERROR": + a = 1/0 + + else: + f.write("!NO_CMD %s\n" % cmd) + + _debug("command:", cmd.strip()) + f.flush() + except: + print("ERROR:", sys.exc_info()[0], file=f) + print(traceback.format_exc(), file=f) + f.flush() + +def get_all_privs(th): + # Try to give ourselves some extra privs (only works if we're admin): + # SeBackupPrivilege - so we can read anything + # SeDebugPrivilege - so we can find out about other processes (otherwise OpenProcess will fail for some) + # SeSecurityPrivilege - ??? what does this do? + + # Problem: Vista+ support "Protected" processes, e.g. audiodg.exe. We can't see info about these. + # Interesting post on why Protected Process aren't really secure anyway: http://www.alex-ionescu.com/?p=34 + + privs = win32security.GetTokenInformation(th, ntsecuritycon.TokenPrivileges) + for privtuple in privs: + privs2 = win32security.GetTokenInformation(th, ntsecuritycon.TokenPrivileges) + newprivs = [] + for privtuple2 in privs2: + if privtuple2[0] == privtuple[0]: + newprivs.append((privtuple2[0], 2)) # SE_PRIVILEGE_ENABLED + else: + newprivs.append((privtuple2[0], privtuple2[1])) + + # Adjust privs + privs3 = tuple(newprivs) + win32security.AdjustTokenPrivileges(th, False, privs3) +def shell_as(th, enable_privs = 0): + #t = thread(th) + #print(t.as_text()) + new_tokenh = win32security.DuplicateTokenEx(th, 3 , win32con.MAXIMUM_ALLOWED , win32security.TokenPrimary , win32security.SECURITY_ATTRIBUTES() ) + print("new_tokenh: %s" % new_tokenh) + print("Impersonating...") + if enable_privs: + get_all_privs(new_tokenh) + commandLine = "cmd" + si = win32process.STARTUPINFO() + print("pysecdump: Starting shell with required privileges...") + (hProcess, hThread, dwProcessId, dwThreadId) = win32process.CreateProcessAsUser( + new_tokenh, + None, # AppName + commandLine, # Command line + None, # Process Security + None, # ThreadSecurity + 1, # Inherit Handles? + win32process.NORMAL_PRIORITY_CLASS, + None, # New environment + None, # Current directory + si) # startup info. + win32event.WaitForSingleObject( hProcess, win32event.INFINITE ); + print("pysecdump: Quitting") + +def shell_as2(new_tokenh, enable_privs = 0, commandLine = "cmd"): + print("new_tokenh: %s" % new_tokenh) + print("Impersonating...") + if enable_privs: + get_all_privs(new_tokenh) + si = win32process.STARTUPINFO() + print("pysecdump: Starting shell with required privileges...") + (hProcess, hThread, dwProcessId, dwThreadId) = win32process.CreateProcessAsUser( + new_tokenh, + None, # AppName + commandLine, # Command line + None, # Process Security + None, # ThreadSecurity + 1, # Inherit Handles? + win32process.NORMAL_PRIORITY_CLASS, + None, # New environment + None, # Current directory + si) # startup info. + win32event.WaitForSingleObject( hProcess, win32event.INFINITE ) + print("pysecdump: Quitting") + +def main(argv): + global threads, config + parser = ArgumentParser() + parser.add_argument("-l", "--listen-address", dest="TCP_IP", + help="Listen in this address, default: %s" % ("0.0.0.0"), required=False, default='0.0.0.0') + parser.add_argument("-p", "--port", dest="TCP_PORT", + help="Listen in this port, default: %s" % ("5899"), type=int, required=False, default='5899') + parser.add_argument("-P", "--password", help="Sets password", required=True, dest="PASSWORD") + + args = parser.parse_args() + + config["PASSWORD"] = args.PASSWORD + config["PORT"] = args.TCP_PORT + + sockServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sockServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sockServer.bind((args.TCP_IP, args.TCP_PORT)) + + controlthread = ControlThread(threads) + controlthread.start() + threads.append(controlthread) + + #_debug("Multithreaded Python server : Waiting for connections from TCP clients...") + _debug("Runing on:", sys.platform) + while True: + sockServer.listen(4) + (conn, (ip,port)) = sockServer.accept() + newthread = ClientThread(conn, ip, port, config) + newthread.setDaemon(True) + newthread.start() + threads.append(newthread) + #print(threads) + + + +if __name__ == "__main__": + threads = [] + main(sys.argv) diff --git a/lib/common.py b/lib/common.py new file mode 100644 index 0000000..6af18f8 --- /dev/null +++ b/lib/common.py @@ -0,0 +1,68 @@ +# coding=utf-8 +# pyvncs +# Copyright (C) 2017-2018 Matias Fernandez +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + +import sys +from multiprocessing import Process, Value +import subprocess +import os +import time +import mmap +import psutil + +def isWindows(): + return sys.platform.startswith("win") + +def isOSX(): + return sys.platform.startswith("darwin") + +def isLinux(): + return sys.platform.startswith("linux") + +class proc: + def __init__(self): + self.pid = Value('i', 0) + self._process = None + + def __del__(self): + pass + + def _setpid(self, pid): + self.pid.value = pid + + def getpid(self): + return self.pid.value + + def _newproc(self, cmd): + pr = subprocess.Popen(cmd) + #print("Launched forkproc Process ID:", str(pr.pid)) + self._setpid(pr.pid) + + def run(self, *cmd): + self._process = Process(target=self._newproc, args=(cmd)) + self._process.start() + self._process.join() + return self.pid.value + + def terminate(self): + if psutil.pid_exists(self.pid.value): + p = psutil.Process(self.pid.value) + p.terminate() + self._process.terminate() + + def waitproc(self): + while psutil.pid_exists(self.pid): + time.sleep(.25) diff --git a/lib/const.py b/lib/const.py new file mode 100644 index 0000000..235e4c5 --- /dev/null +++ b/lib/const.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# pyvncs +# Copyright (C) 2017-2018 Matias Fernandez +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + +import sys + +# constants workaround +class _const: + class ConstError(TypeError): pass + def __setattr__(self, name, value): + if name in self.__dict__.keys(): + raise (self.ConstError, "Can't rebind const(%s)" % name) + self.__dict__[name]=value + +sys.modules[__name__]=_const() + diff --git a/lib/encodings/common.py b/lib/encodings/common.py new file mode 100644 index 0000000..948fa94 --- /dev/null +++ b/lib/encodings/common.py @@ -0,0 +1,19 @@ +# coding=utf-8 +# pyvncs +# Copyright (C) 2017-2018 Matias Fernandez +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + +class ENCODINGS: + pass \ No newline at end of file diff --git a/lib/encodings/cursor.py b/lib/encodings/cursor.py new file mode 100644 index 0000000..37cb736 --- /dev/null +++ b/lib/encodings/cursor.py @@ -0,0 +1,20 @@ +# coding=utf-8 +# pyvncs +# Copyright (C) 2017-2018 Matias Fernandez +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + +from . import common + +common.ENCODINGS.cursor = -239 diff --git a/lib/encodings/raw.py b/lib/encodings/raw.py new file mode 100644 index 0000000..85bfcc8 --- /dev/null +++ b/lib/encodings/raw.py @@ -0,0 +1,32 @@ +# coding=utf-8 +# pyvncs +# Copyright (C) 2017-2018 Matias Fernandez +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + +from . import common +from struct import * + +def send_image(x, y, w, h, image): + _buff = bytearray() + rectangles = 1 + _buff.extend(pack("!BxH", 0, rectangles)) + _buff.extend(pack("!HHHH", x, y, w, h)) + _buff.extend(pack(">i", common.ENCODINGS.raw)) + _buff.extend( image.tobytes() ) + + return _buff + +common.ENCODINGS.raw = 0 +common.ENCODINGS.raw_send_image = send_image \ No newline at end of file diff --git a/lib/log.py b/lib/log.py new file mode 100644 index 0000000..5c43b42 --- /dev/null +++ b/lib/log.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# pyvncs +# Copyright (C) 2017-2018 Matias Fernandez +# +# This program is free software: you can redistribute it and/or modify it under +# the terms of the GNU Lesser General Public License as published by the Free +# Software Foundation, either version 3 of the License, or (at your option) any +# later version. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more +# details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + +import logging +logging.basicConfig(level=logging.DEBUG, format='[%(threadName)s] %(message)s') +logger = logging.getLogger('pyvncs') + + +def debug(*args): + str = "" + for s in args: + str = "%s %s" % (str, s) + str = str.strip() + logger.debug(str) diff --git a/pyvncs/__pycache__/server.cpython-36.pyc b/pyvncs/__pycache__/server.cpython-36.pyc index 96d4937f7aa1c789b6849ac1fdd3d1cd5a87e147..a87805a19fc19b9cdcb77213270f390e2b2407b4 100644 GIT binary patch delta 5530 zcmaJ_du$xV8Q)G)p|rGtz*I%h3fdykKMF;a1uX?tl+ymeKNYHk)NLi8RaGIiNR|3fk=pe8X3vge zXl>nZXTJGfGy8or-|XKm@&*4Uzh8gl&A{33U6iCh@DDu^((+_asVY%dE|_mhHW7(x z)O|%thG>*}seXkdo2f(_a^ZX=8OcYJ(R?f!%eN$3h-B#5IQ7lR<<~^ZKPR*Ifj5wA z&9^1n^6klXBJG!GBMn}WXs{+HI|^fhvk5pq1x_{BnO&1yyI&fip%q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kv08y#y1u;jRiHu z_tX@2Zw*QQWLJ0NHJqa^KjnA(Jvb(oT8tai18m=p6^ zZ>Zr<1`Ex?+r>K8&y2mplAl9R z%s+e#V*D?{>2vaDs<=M`Z9^OV*6XN zI5Emb<+~G;DaUYY3wVmQgx)h|IxtL$i}-w)(8_> z$W?3EVg;G**X8&2pSn<_CQ3zHk?H#jZq>_I%E2wNO8B;yuFqs|zHo8wh0B-4eZmHJ z0&!m<@_R(o<#2(n9VfX^%)4bTt8%1#d8sD8MF_eYoc4tkQL6~#^+@Wucm!E1ejVBL zHFv>-tcWLGSiXN?saxec&)!IKaPmt0c~WB8jl@~rpBy`POo>*-I7*QLajfNejyH*8 z^UA&QVllTQ9BO;|-fG!ZQSmAZmEvvrFOwfNVz{?bx`lj4*Kunx+dRbjkSnE7vvrHb zbQ2t9N-?x{>PcemMc#!n$hv|A9(N<^$jFdw5l`5- z+&$Ityv<0`345Ke5R|{YPGd>xpt3l%cAB2l8Ed=0(44!7^nkR?1yQMHqQR9_h{NSF^b*ewJNU<5$+uR;UzIE_ATU-D6L7TC;^?yEePwzg4(7xN-TNo>h^PWCU zT@J@&{>c1Zu8x{NP?+=+g*{Drg$(+Gs6VHYra>>l`@JdoUq{Be4-$4O;JqDtI1K_&%d?Be%{Oc99_p)?9_*gh1wQ@fnvE-vOW`KRW)S z1SP6C%s4_Zb5M`VM<=El`^nY;B9lba0?}_Y;yMv}o~d6QgnF&ft1fs4Hi)B4So}2+ zNeb1H{(jhJD30?2v8RF*$p(BSP&Nb|Et?=T9DJTtZF!IgtlM z{uIQqHXe?Ts1hpU=eSkzed60O@5!y;+fEv3YA~)|ysSJ}Ijb0?h9M$ self.blue_shift: self.primaryOrder = "rgb" else: self.primaryOrder = "bgr" - print("Using order: ", self.primaryOrder) + log.debug("Using order: ", self.primaryOrder) continue if data[0] == 2: # SetEncoding data2 = sock.recv(3) - print("Client Message Type: SetEncoding (2)") + log.debug("Client Message Type: SetEncoding (2)") (nencodings,) = unpack("!xH", data2) - print("SetEncoding: total encodings", repr(nencodings)) + log.debug("SetEncoding: total encodings", repr(nencodings)) data2 = sock.recv(4 * nencodings, socket.MSG_WAITALL) - #print("len", len(data2)) + #log.debug("len", len(data2)) self.client_encodings = unpack("!%si" % nencodings, data2) - #print("data", repr(self.client_encodings), len(self.client_encodings)) + #log.debug("data", repr(self.client_encodings), len(self.client_encodings)) if hasattr(enc.ENCODINGS, "cursor") and enc.ENCODINGS.cursor in self.client_encodings: - print("Remote cursor encoding present") + log.debug("Remote cursor encoding present") self.remotecursor = True self.cursorchanged = True if hasattr(enc.ENCODINGS, "zlib") and enc.ENCODINGS.zlib in self.client_encodings: - print("Using zlib encoding") + log.debug("Using zlib encoding") self.encoding = enc.ENCODINGS.zlib continue @@ -503,10 +504,10 @@ class VncServer(): if data[0] == 3: # FBUpdateRequest data2 = sock.recv(9, socket.MSG_WAITALL) - #print("Client Message Type: FBUpdateRequest (3)") + #log.debug("Client Message Type: FBUpdateRequest (3)") #print(len(data2)) (incremental, x, y, w, h) = unpack("!BHHHH", data2) - #print("RFBU:", incremental, x, y, w, h) + #log.debug("RFBU:", incremental, x, y, w, h) self.SendRectangles(sock, x, y, w, h, incremental) if self.remotecursor and self.cursorchanged: @@ -519,7 +520,7 @@ class VncServer(): data2 = sock.recv(7) # B = U8, L = U32 (downflag, key) = unpack("!BxxL", data2) - print("KeyEvent", downflag, hex(key)) + log.debug("KeyEvent", downflag, hex(key)) # special key if key in kbdmap: @@ -531,9 +532,9 @@ class VncServer(): kbdkey = None try: - print("KEY:", kbdkey) + log.debug("KEY:", kbdkey) except: - print("KEY: (unprintable)") + log.debug("KEY: (unprintable)") try: if downflag: @@ -541,7 +542,7 @@ class VncServer(): else: keyboard.Controller().release(kbdkey) except: - print("Error sending key") + log.debug("Error sending key") continue @@ -557,46 +558,46 @@ class VncServer(): mouse.Controller().position = (x, y) if buttons[0] and not left_pressed: - print("LEFT PRESSED") + log.debug("LEFT PRESSED") mouse.Controller().press(mouse.Button.left) left_pressed = 1 elif not buttons[0] and left_pressed: - print("LEFT RELEASED") + log.debug("LEFT RELEASED") mouse.Controller().release(mouse.Button.left) left_pressed = 0 if buttons[1] and not middle_pressed: - print("MIDDLE PRESSED") + log.debug("MIDDLE PRESSED") mouse.Controller().press(mouse.Button.middle) middle_pressed = 1 elif not buttons[1] and middle_pressed: - print("MIDDLE RELEASED") + log.debug("MIDDLE RELEASED") mouse.Controller().release(mouse.Button.middle) middle_pressed = 0 if buttons[2] and not right_pressed: - print("RIGHT PRESSED") + log.debug("RIGHT PRESSED") mouse.Controller().press(mouse.Button.right) right_pressed = 1 elif not buttons[2] and right_pressed: - print("RIGHT RELEASED") + log.debug("RIGHT RELEASED") mouse.Controller().release(mouse.Button.right) right_pressed = 0 if buttons[3]: - print("SCROLLUP PRESSED") + log.debug("SCROLLUP PRESSED") mouse.Controller().scroll(0, 2) if buttons[4]: - print("SCROLLDOWN PRESSED") + log.debug("SCROLLDOWN PRESSED") mouse.Controller().scroll(0, -2) - #print("PointerEvent", buttonmask, x, y) + #log.debug("PointerEvent", buttonmask, x, y) continue else: data2 = sock.recv(4096) - print("RAW Server received data:", repr(data[0]) , data+data2) + log.debug("RAW Server received data:", repr(data[0]) , data+data2) def GetRectangle(self, x, y, w, h): @@ -621,7 +622,7 @@ class VncServer(): def SendRectangles(self, sock, x, y, w, h, incremental=0): # send FramebufferUpdate to client - #print("start SendRectangles") + #log.debug("start SendRectangles") rectangle = self.GetRectangle(x, y, w, h) if not rectangle: rectangle = Image.new("RGB", [w, h], (0,0,0)) @@ -650,7 +651,7 @@ class VncServer(): (x, y, _, _) = diff.getbbox() w = rectangle.width h = rectangle.height - #print("XYWH:", x,y,w,h, "diff", repr(diff.getbbox())) + #log.debug("XYWH:", x,y,w,h, "diff", repr(diff.getbbox())) stimeout = sock.gettimeout() sock.settimeout(None) @@ -677,7 +678,7 @@ class VncServer(): #redMask = ((1 << redBits) - 1) << self.red_shift #greenMask = ((1 << greenBits) - 1) << self.green_shift #blueMask = ((1 << blueBits) - 1) << self.blue_shift - #print("redMask", redMask, greenMask, blueMask) + #log.debug("redMask", redMask, greenMask, blueMask) if self.primaryOrder == "bgr": self.blue_shift = 0 @@ -757,7 +758,7 @@ class VncServer(): sendbuff.extend(pack("!HHHH", x, y, w, h)) sendbuff.extend(pack(">i", self.encoding)) - print("Compressing...") + log.debug("Compressing...") zlibdata = compress.compress( image.tobytes() ) zlibdata += compress.flush() l = pack("!I", len(zlibdata) ) @@ -769,7 +770,7 @@ class VncServer(): # send with RAW encoding sendbuff.extend(enc.ENCODINGS.raw_send_image(x, y, w, h, image)) else: - print("[!] Unsupported BPP: %s" % self.bpp) + log.debug("[!] Unsupported BPP: %s" % self.bpp) self.framebuffer = lastshot try: @@ -778,4 +779,4 @@ class VncServer(): # connection closed? return False sock.settimeout(stimeout) - #print("end SendRectangles") + #log.debug("end SendRectangles") diff --git a/requeriments.txt b/requeriments.txt index 50504bc..dbfde75 100644 --- a/requeriments.txt +++ b/requeriments.txt @@ -1,2 +1,4 @@ -pyuserinput +pydes +pynput +numpy diff --git a/server.py b/server.py index 0a6afa2..02a9f95 100755 --- a/server.py +++ b/server.py @@ -5,9 +5,19 @@ import pyvncs from argparse import ArgumentParser from threading import Thread from time import sleep - import sys import socket +import signal +from lib import log + +#_debug = log.debug +_debug = print + +def signal_handler(signal, frame): + _debug("Exiting on %s signal..." % signal) + sys.exit(0) + +signal.signal(signal.SIGINT, signal_handler) class ControlThread(Thread): @@ -22,7 +32,7 @@ class ControlThread(Thread): sleep(1) for t in threads: if not t.isAlive(): - print("ControlThread removing dead", t) + _debug("ControlThread removing dead", t) threads.remove(t) class ClientThread(Thread): @@ -34,17 +44,17 @@ class ClientThread(Thread): self.setDaemon(True) def __del__(self): - print("ClientThread died") + _debug("ClientThread died") def run(self): - print("[+] New server socket thread started for " + self.ip + ":" + str(self.port)) - #print("Thread", self) + _debug("[+] New server socket thread started for " + self.ip + ":" + str(self.port)) + #_debug("Thread", self) server = pyvncs.server.VncServer(self.sock, VNC_PASSWORD) server.CONFIG._8bitdither = CONFIG._8bitdither status = server.init() if not status: - print("Error negotiating client init") + _debug("Error negotiating client init") return False server.protocol() @@ -61,11 +71,17 @@ def main(argv): help="Listen in this port, default: %s" % ("5901"), type=int, required=False, default='5901') parser.add_argument("-P", "--password", help="Sets password", required=True, dest="VNC_PASSWORD") parser.add_argument("-8", "--8bitdither", help="Enable 8 bit dithering", required=False, action='store_true', dest="dither") + parser.add_argument("-O", "--output-file", help="Redirects all debug output to file", required=False, dest="OUTFILE") + args = parser.parse_args() - + + if args.OUTFILE is not None: + fsock = open(args.OUTFILE, 'w') + sys.stdout = sys.stderr = fsock + # Multithreaded Python server TCP_IP = '0.0.0.0' if not hasattr(args,"TCP_IP") else args.TCP_IP - TCP_PORT = '0.0.0.0' if not hasattr(args,"TCP_PORT") else args.TCP_PORT + TCP_PORT = '5901' if not hasattr(args,"TCP_PORT") else args.TCP_PORT VNC_PASSWORD = args.VNC_PASSWORD CONFIG._8bitdither = args.dither @@ -77,8 +93,8 @@ def main(argv): controlthread.start() threads.append(controlthread) - print("Multithreaded Python server : Waiting for connections from TCP clients...") - print("Runing on:", sys.platform) + _debug("Multithreaded Python server : Waiting for connections from TCP clients...") + _debug("Runing on:", sys.platform) while True: sockServer.listen(4) (conn, (ip,port)) = sockServer.accept() @@ -95,8 +111,8 @@ if __name__ == "__main__": main(sys.argv) except KeyboardInterrupt: # quit - print("Exiting on ctrl+c...") + _debug("Exiting on ctrl+c...") #for t in threads: - # print("Killing", t) + # _debug("Killing", t) sys.exit() \ No newline at end of file diff --git a/test.py b/test.py new file mode 100644 index 0000000..52c7033 --- /dev/null +++ b/test.py @@ -0,0 +1,16 @@ +from lib import common +import time + +if __name__ == '__main__': + #c = ["/bin/ls", "-alh"] + #c = ["/bin/sleep", "5"] + c = ["./test.sh"] + r = common.proc() + r.run(c) + print("PID", r.getpid()) + #print("Waiting...") + #r.waitproc() + time.sleep(1) + r.terminate() + del r + print("DONE") diff --git a/test.sh b/test.sh new file mode 100755 index 0000000..9c56fd9 --- /dev/null +++ b/test.sh @@ -0,0 +1,6 @@ +#!/bin/bash +for a in $(seq 1 5); do +echo "$a $$" +sleep 1 +done + diff --git a/winservice.py b/winservice.py new file mode 100644 index 0000000..dea87ec --- /dev/null +++ b/winservice.py @@ -0,0 +1,79 @@ +import win32service +import win32serviceutil +import win32api +import win32con +import win32event +import win32evtlogutil +import servicemanager +import os +import sys +from lib import const +from lib import common +from win32api import OutputDebugString as ODS +import traceback + + +const.SERVICENAME = "Test Service" +const.SERVICEDNAME = "Test Service" +const.SERVICEDESC = "Test Service Description" + +const.CHILD = [ + "C:\\Program Files\\Python36\\python.exe", + "C:\\pyvncs\\ctrlsrv.py", + "-P", + "kaka80" +] + +class service(win32serviceutil.ServiceFramework): + + _svc_name_ = const.SERVICENAME + _svc_display_name_ = const.SERVICEDNAME + _svc_description_ = const.SERVICEDESC + + def __init__(self, args): + win32serviceutil.ServiceFramework.__init__(self, args) + self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) + + def SvcStop(self): + self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) + win32event.SetEvent(self.hWaitStop) + + def SvcDoRun(self): + servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,servicemanager.PYS_SERVICE_STARTED,(self._svc_name_, '')) + self.timeout = 3000 + + servicemanager.LogInfoMsg("%s - is running 1" % const.SERVICENAME) + r = common.proc() + try: + r.run(const.CHILD) + except: + servicemanager.LogInfoMsg("ERROR: %s" % sys.exc_info()[0]) + servicemanager.LogInfoMsg(traceback.format_exc()) + sys.exit(1) + + newpid = r.getpid() + servicemanager.LogInfoMsg("%s - started child with pid %s" % (const.SERVICENAME, newpid)) + + while True: + # Wait for service stop signal, if I timeout, loop again + rc = win32event.WaitForSingleObject(self.hWaitStop, self.timeout) + # Check to see if self.hWaitStop happened + if rc == win32event.WAIT_OBJECT_0: + # Stop signal encountered + servicemanager.LogInfoMsg("%s - STOPPED" % const.SERVICENAME) + r.terminate() + break + #else: + # servicemanager.LogInfoMsg("%s - still running" % const.SERVICENAME) + + +def ctrlHandler(ctrlType): + return True + +if __name__ == '__main__': + ODS("__main__\n") + servicemanager.LogInfoMsg("TEST") + appdir = os.path.abspath(os.path.dirname(sys.argv[0])) + os.chdir(appdir) + win32api.SetConsoleCtrlHandler(ctrlHandler, True) + win32serviceutil.HandleCommandLine(service)