Made all pretty-print process handy

This commit is contained in:
Matteo ℱan 2019-10-24 22:32:06 +02:00
parent dddc02530b
commit 19e5abbbbd
No known key found for this signature in database
GPG key ID: 3C30A05BC133D9B6
10 changed files with 149 additions and 122 deletions

View file

@ -13,7 +13,8 @@ from pykms_DB2Dict import kmsDB2Dict
from pykms_PidGenerator import epidGenerator from pykms_PidGenerator import epidGenerator
from pykms_Filetimes import filetime_to_dt from pykms_Filetimes import filetime_to_dt
from pykms_Sql import sql_initialize, sql_update, sql_update_epid from pykms_Sql import sql_initialize, sql_update, sql_update_epid
from pykms_Format import justify, byterize, enco, deco, ShellMessage from pykms_Format import justify, byterize, enco, deco
from pykms_Misc import pretty_printer
#-------------------------------------------------------------------------------------------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------------------------------------------------------------
@ -112,7 +113,7 @@ class kmsBase:
if self.srv_config['sqlite'] and self.srv_config['dbSupport']: if self.srv_config['sqlite'] and self.srv_config['dbSupport']:
self.dbName = sql_initialize() self.dbName = sql_initialize()
ShellMessage.Process(15).run() pretty_printer(None, num_text = 15)
kmsRequest = byterize(kmsRequest) kmsRequest = byterize(kmsRequest)
loggersrv.debug("KMS Request Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(kmsRequest), 'latin-1')), 'latin-1'))) loggersrv.debug("KMS Request Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(kmsRequest), 'latin-1')), 'latin-1')))
loggersrv.debug("KMS Request: \n%s\n" % justify(kmsRequest.dump(print_to_stdout = False))) loggersrv.debug("KMS Request: \n%s\n" % justify(kmsRequest.dump(print_to_stdout = False)))
@ -130,10 +131,12 @@ class kmsBase:
tz = get_localzone() tz = get_localzone()
local_dt = tz.localize(requestDatetime) local_dt = tz.localize(requestDatetime)
except UnknownTimeZoneError: except UnknownTimeZoneError:
loggersrv.warning('Unknown time zone ! Request time not localized.') pretty_printer(loggersrv.warning, get_text = True, log_text = True,
put_text = "{yellow}{bold}Unknown time zone ! Request time not localized.{end}")
local_dt = requestDatetime local_dt = requestDatetime
except ImportError: except ImportError:
loggersrv.warning('Module "tzlocal" not available ! Request time not localized.') pretty_printer(loggersrv.warning, get_text = True, log_text = True,
put_text = "{yellow}{bold}Module 'tzlocal' not available ! Request time not localized.{end}")
local_dt = requestDatetime local_dt = requestDatetime
# Activation threshold. # Activation threshold.

View file

@ -22,7 +22,7 @@ from pykms_RequestV5 import kmsRequestV5
from pykms_RequestV6 import kmsRequestV6 from pykms_RequestV6 import kmsRequestV6
from pykms_RpcBase import rpcBase from pykms_RpcBase import rpcBase
from pykms_DB2Dict import kmsDB2Dict from pykms_DB2Dict import kmsDB2Dict
from pykms_Misc import logger_create, check_logfile from pykms_Misc import logger_create, check_logfile, pretty_printer
from pykms_Format import justify, byterize, enco, deco, ShellMessage from pykms_Format import justify, byterize, enco, deco, ShellMessage
clt_description = 'KMS Client Emulator written in Python' clt_description = 'KMS Client Emulator written in Python'
@ -126,31 +126,30 @@ def client_create():
binder = pykms_RpcBind.handler(None, clt_config) binder = pykms_RpcBind.handler(None, clt_config)
RPC_Bind = enco(str(binder.generateRequest()), 'latin-1') RPC_Bind = enco(str(binder.generateRequest()), 'latin-1')
loggerclt.info("Sending RPC bind request...") loggerclt.info("Sending RPC bind request...")
ShellMessage.Process([-1, 1]).run() pretty_printer(None, num_text = [-1, 1])
s.send(RPC_Bind) s.send(RPC_Bind)
try: try:
ShellMessage.Process([-4, 7]).run()
bindResponse = s.recv(1024) bindResponse = s.recv(1024)
if bindResponse == '' or not bindResponse:
pretty_printer(loggerclt.warning, get_text = True, log_text = True, to_exit = True,
put_text = "{yellow}{bold}No data received.{end}")
pretty_printer(None, num_text = [-4, 7])
except socket.error as e: except socket.error as e:
if e.errno == errno.ECONNRESET: pretty_printer(loggerclt.error, get_text = True, log_text = True, to_exit = True,
loggerclt.error("Connection reset by peer. Exiting...") put_text = "{red}{bold}While receiving: %s{end}" %str(e))
sys.exit()
else:
raise
if bindResponse == '' or not bindResponse:
loggerclt.error("No data received ! Exiting...")
sys.exit()
packetType = MSRPCHeader(bindResponse)['type'] packetType = MSRPCHeader(bindResponse)['type']
if packetType == rpcBase.packetType['bindAck']: if packetType == rpcBase.packetType['bindAck']:
loggerclt.info("RPC bind acknowledged.") loggerclt.info("RPC bind acknowledged.")
ShellMessage.Process(8).run() pretty_printer(None, num_text = 8)
kmsRequest = createKmsRequest() kmsRequest = createKmsRequest()
requester = pykms_RpcRequest.handler(kmsRequest, clt_config) requester = pykms_RpcRequest.handler(kmsRequest, clt_config)
s.send(enco(str(requester.generateRequest()), 'latin-1')) s.send(enco(str(requester.generateRequest()), 'latin-1'))
ShellMessage.Process([-1, 12]).run() pretty_printer(None, num_text = [-1, 12])
response = s.recv(1024) response = s.recv(1024)
loggerclt.debug("Response: \n%s\n" % justify(deco(binascii.b2a_hex(response), 'latin-1'))) loggerclt.debug("Response: \n%s\n" % justify(deco(binascii.b2a_hex(response), 'latin-1')))
ShellMessage.Process([-4, 20]).run() pretty_printer(None, num_text = [-4, 20])
parsed = MSRPCRespHeader(response) parsed = MSRPCRespHeader(response)
kmsData = readKmsResponse(parsed['pduData'], kmsRequest, clt_config) kmsData = readKmsResponse(parsed['pduData'], kmsRequest, clt_config)
kmsResp = kmsData['response'] kmsResp = kmsData['response']
@ -170,15 +169,14 @@ def client_create():
'status' : "Activated", 'status' : "Activated",
'product' : clt_config["mode"]}) 'product' : clt_config["mode"]})
ShellMessage.Process(21).run() pretty_printer(None, num_text = 21)
elif packetType == rpcBase.packetType['bindNak']: elif packetType == rpcBase.packetType['bindNak']:
loggerclt.info(justify(MSRPCBindNak(bindResponse).dump(print_to_stdout = False))) loggerclt.info(justify(MSRPCBindNak(bindResponse).dump(print_to_stdout = False)))
sys.exit() sys.exit(0)
else: else:
loggerclt.critical("Something went wrong.") pretty_printer(loggerclt.warning, get_text = True, log_text = True, to_exit = True,
sys.exit() put_text = "{magenta}{bold}Something went wrong.{end}")
def clt_main(with_gui = False): def clt_main(with_gui = False):
if not with_gui: if not with_gui:
@ -211,7 +209,7 @@ def createKmsRequestBase():
requestDict['mnPad'] = '\0'.encode('utf-16le') * (63 - len(requestDict['machineName'].decode('utf-16le'))) requestDict['mnPad'] = '\0'.encode('utf-16le') * (63 - len(requestDict['machineName'].decode('utf-16le')))
# Debug Stuff # Debug Stuff
ShellMessage.Process(9).run() pretty_printer(None, num_text = 9)
requestDict = byterize(requestDict) requestDict = byterize(requestDict)
loggerclt.debug("Request Base Dictionary: \n%s\n" % justify(requestDict.dump(print_to_stdout = False))) loggerclt.debug("Request Base Dictionary: \n%s\n" % justify(requestDict.dump(print_to_stdout = False)))

View file

@ -118,17 +118,9 @@ MsgMap = {0 : {'text' : "{yellow}\n\t\t\tClient generating RPC Bind Request...{
20 : {'text' : "{white}===============>{end}{blue}\tClient received Response !!!{end}", 'where' : "clt"}, 20 : {'text' : "{white}===============>{end}{blue}\tClient received Response !!!{end}", 'where' : "clt"},
21 : {'text' : "{green}{bold}\t\t\tActivation Done !!!{end}", 'where' : "clt"}, 21 : {'text' : "{green}{bold}\t\t\tActivation Done !!!{end}", 'where' : "clt"},
-1 : {'text' : "{white}Server receiving{end}", 'where' : "clt"}, -1 : {'text' : "{white}Server receiving{end}", 'where' : "clt"},
-2 : {'text' : "{white}\n\n\t\t\t\t\t\t\t\tClient sending{end}", 'where' : "srv"}, -2 : {'text' : "{white}\n\n\n\t\t\t\t\t\t\t\tClient sending{end}", 'where' : "srv"},
-3 : {'text' : "{white}\t\t\t\t\t\t\t\tClient receiving{end}", 'where' : "srv"}, -3 : {'text' : "{white}\t\t\t\t\t\t\t\tClient receiving{end}", 'where' : "srv"},
-4 : {'text' : "{white}\n\nServer sending{end}", 'where' : "clt"}, -4 : {'text' : "{white}\n\nServer sending{end}", 'where' : "clt"},
40 : {'text' : "{red}{bold}Server connection timed out. Exiting...{end}", 'where' : "srv"},
41 : {'text' : "{red}{bold}HWID '{0}' is invalid. Digit {1} non hexadecimal. Exiting...{end}", 'where' : "srv"},
42 : {'text' : "{red}{bold}HWID '{0}' is invalid. Hex string is odd length. Exiting...{end}", 'where' : "srv"},
43 : {'text' : "{red}{bold}HWID '{0}' is invalid. Hex string is too short. Exiting...{end}", 'where' : "srv"},
44 : {'text' : "{red}{bold}HWID '{0}' is invalid. Hex string is too long. Exiting...{end}", 'where' : "srv"},
45 : {'text' : "{red}{bold}Port number '{0}' is invalid. Enter between 1 - 65535. Exiting...{end}", 'where' : "srv"},
46 : {'text' : "{red}{bold}{0}. Exiting...{end}", 'where' : "srv"},
} }
def pick_MsgMap(messagelist): def pick_MsgMap(messagelist):
@ -180,30 +172,25 @@ class ShellMessage(object):
class Process(object): class Process(object):
def __init__(self, nshell, get_text = False, put_text = None): def __init__(self, nshell, get_text = False, put_text = None):
self.nshell = nshell self.nshell = nshell
self.print_queue = Queue.Queue()
self.get_text = get_text self.get_text = get_text
self.put_text = put_text self.put_text = put_text
self.print_queue = Queue.Queue()
self.plaintext = [] self.plaintext = []
if not isinstance(nshell, list): def formatter(self, msgtofrmt):
self.nshell = [nshell] self.msgfrmt = msgtofrmt.format(**ColorExtraMap)
if not isinstance(put_text, list):
self.put_text = [put_text]
def formatter(self, num):
if self.put_text is None:
self.msg = MsgMap[num]['text'].format(**ColorExtraMap)
else:
self.msg = MsgMap[num]['text'].format(*self.put_text, **ColorExtraMap)
if self.get_text: if self.get_text:
self.plaintext.append(unshell_message(self.msg, m = 0)[0]["tag00"]['text']) self.plaintext.append(unshell_message(self.msgfrmt, m = 0)[0]["tag00"]['text'])
def run(self): def run(self):
if not ShellMessage.view: if not ShellMessage.view:
if self.get_text: if self.get_text:
for num in self.nshell: if self.put_text is not None:
self.formatter(num) for mess in self.put_text:
self.formatter(mess)
else:
for num in self.nshell:
self.formatter(MsgMap[num]['text'])
return self.plaintext return self.plaintext
else: else:
return return
@ -234,9 +221,14 @@ class ShellMessage(object):
try: try:
# Print something. # Print something.
for num in self.nshell: if self.put_text is not None:
self.formatter(num) for mess in self.put_text:
print(self.msg, flush = True) self.formatter(mess)
print(self.msgfrmt, end = '\n', flush = True)
else:
for num in self.nshell:
self.formatter(MsgMap[num]['text'])
print(self.msgfrmt, end = '\n', flush = True)
finally: finally:
# Restore stdout and send content. # Restore stdout and send content.
sys.stdout = sys.__stdout__ sys.stdout = sys.__stdout__

View file

@ -132,20 +132,20 @@ def logger_create(log_obj, config, mode = 'a'):
#---------------------------------------------------------------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------------------------------------------
def check_logfile(optionlog, defaultlog, logger): def check_logfile(optionlog, defaultlog, log_obj):
if not isinstance(optionlog, list): if not isinstance(optionlog, list):
optionlog = [optionlog] optionlog = [optionlog]
lenopt = len(optionlog) lenopt = len(optionlog)
msg_long = "argument logfile: too much arguments" msg_long = "{red}{bold}Argument logfile: Too much arguments{end}"
def checkdir(path): def checkdir(path):
msg_path = "argument logfile: No such file or directory: %s" %path
if not os.path.isdir(os.path.dirname(path)): if not os.path.isdir(os.path.dirname(path)):
pretty_errors(46, logger, get_text = False, put_text = msg_path, log_text = False) pretty_printer(log_obj, to_exit = True,
put_text = "{red}{bold}Argument logfile: No such file or directory: %s{end}" %path)
if lenopt > 2: if lenopt > 2:
pretty_errors(46, logger, get_text = False, put_text = msg_long, log_text = False) pretty_printer(log_obj, to_exit = True, put_text = msg_long)
if 'FILESTDOUT' in optionlog: if 'FILESTDOUT' in optionlog:
if lenopt == 1: if lenopt == 1:
@ -156,33 +156,50 @@ def check_logfile(optionlog, defaultlog, logger):
checkdir(optionlog[1]) checkdir(optionlog[1])
else: else:
if lenopt == 2: if lenopt == 2:
pretty_errors(46, logger, get_text = False, put_text = msg_long, log_text = False) pretty_printer(46, log_obj, to_exit = True, put_text = msg_long)
elif lenopt == 1 and 'STDOUT' not in optionlog: elif lenopt == 1 and 'STDOUT' not in optionlog:
# check directory path. # check directory path.
checkdir(optionlog[0]) checkdir(optionlog[0])
return optionlog return optionlog
def pretty_errors(error_num, logger, **kwargs): def pretty_printer(log_obj, **kwargs):
""" error_num --> an int or list of int. """ `log_obj` --> logging object.
kwargs: kwargs:
get_text --> True (default) / False. `get_text` --> if True obtain text not ansi formatted,
put_text --> string / list of strings/ None. (applied to each "error_num") after printing it with ansi formattation.
log_text --> True (default) / False. `put_text` --> a string or list of strings with ansi formattation.
to_exit --> True (default) / False. if None refer to `num_text` for printing process.
`num_text` --> a number or list of numbers of numbered message map.
if None `put_text` must be defined for printing process.
`log_text` --> if True the text not ansi formatted is logged.
`to_exit ` --> if True system exit is called.
""" """
# Set defaults for not defined options. # Set defaults for not defined options.
options = {'get_text' : True, options = {'get_text' : False,
'put_text' : None, 'put_text' : None,
'log_text' : True, 'num_text' : None,
'to_exit' : True, 'log_text' : False,
'to_exit' : False,
} }
options.update(kwargs) options.update(kwargs)
# Check options.
if (options['num_text'] is None) and (options['put_text'] is None):
raise ValueError('One of `num_text` and `put_text` must be provided.')
elif (options['num_text'] is not None) and (options['put_text'] is not None):
raise ValueError('These parameters are mutually exclusive.')
if (options['num_text'] is not None) and (not isinstance(options['num_text'], list)):
options['num_text'] = [options['num_text']]
if (options['put_text'] is not None) and (not isinstance(options['put_text'], list)):
options['put_text'] = [options['put_text']]
# Process errors. # Process errors.
error_msgs = ShellMessage.Process(error_num, get_text = options['get_text'], put_text = options['put_text']).run() plain_messages = ShellMessage.Process(options['num_text'], get_text = options['get_text'], put_text = options['put_text']).run()
if options['log_text']: if options['log_text']:
for err in error_msgs: for plain_message in plain_messages:
logger.error(err) log_obj(plain_message)
if options['to_exit']: if options['to_exit']:
sys.exit(1) sys.exit(1)
@ -210,7 +227,7 @@ ValidLcid = [1025, 1026, 1027, 1028, 1029,
13313, 13321, 13322, 14337, 14346, 15361, 15370, 16385, 16394, 17418, 18442, 19466, 20490] 13313, 13321, 13322, 14337, 14346, 15361, 15370, 16385, 16394, 17418, 18442, 19466, 20490]
# http://stackoverflow.com/questions/3425294/how-to-detect-the-os-default-language-in-python # http://stackoverflow.com/questions/3425294/how-to-detect-the-os-default-language-in-python
def check_lcid(lcid, logger): def check_lcid(lcid, log_obj):
if not lcid or (lcid not in ValidLcid): if not lcid or (lcid not in ValidLcid):
if hasattr(sys, 'implementation') and sys.implementation.name == 'cpython': if hasattr(sys, 'implementation') and sys.implementation.name == 'cpython':
fixlcid = 1033 fixlcid = 1033
@ -225,7 +242,8 @@ def check_lcid(lcid, logger):
fixlcid = next(k for k, v in locale.windows_locale.items() if v == locale.getdefaultlocale()[0]) fixlcid = next(k for k, v in locale.windows_locale.items() if v == locale.getdefaultlocale()[0])
except StopIteration: except StopIteration:
fixlcid = 1033 fixlcid = 1033
logger.warning("lcid %s auto-fixed with lcid %s" %(lcid, fixlcid)) pretty_printer(log_obj, get_text = True, log_text = True,
put_text = "{yellow}{bold}lcid %s auto-fixed with lcid %s{end}" %(lcid, fixlcid))
return fixlcid return fixlcid
return lcid return lcid

View file

@ -7,7 +7,8 @@ import logging
from pykms_Base import kmsBase from pykms_Base import kmsBase
from pykms_Structure import Structure from pykms_Structure import Structure
from pykms_Aes import AES from pykms_Aes import AES
from pykms_Format import justify, byterize, enco, deco, ShellMessage from pykms_Format import justify, byterize, enco, deco
from pykms_Misc import pretty_printer
#--------------------------------------------------------------------------------------------------------------------------------------------------------- #---------------------------------------------------------------------------------------------------------------------------------------------------------
@ -105,7 +106,7 @@ class kmsRequestV4(kmsBase):
response['padding'] = bytes(bytearray(self.getPadding(bodyLength))) response['padding'] = bytes(bytearray(self.getPadding(bodyLength)))
## Debug stuff. ## Debug stuff.
ShellMessage.Process(16).run() pretty_printer(None, num_text = 16)
response = byterize(response) response = byterize(response)
loggersrv.debug("KMS V4 Response: \n%s\n" % justify(response.dump(print_to_stdout = False))) loggersrv.debug("KMS V4 Response: \n%s\n" % justify(response.dump(print_to_stdout = False)))
loggersrv.debug("KMS V4 Response Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(response), 'latin-1')), 'utf-8'))) loggersrv.debug("KMS V4 Response Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(response), 'latin-1')), 'utf-8')))
@ -124,7 +125,7 @@ class kmsRequestV4(kmsBase):
request['padding'] = bytes(bytearray(self.getPadding(bodyLength))) request['padding'] = bytes(bytearray(self.getPadding(bodyLength)))
## Debug stuff. ## Debug stuff.
ShellMessage.Process(10).run() pretty_printer(None, num_text = 10)
request = byterize(request) request = byterize(request)
loggersrv.debug("Request V4 Data: \n%s\n" % justify(request.dump(print_to_stdout = False))) loggersrv.debug("Request V4 Data: \n%s\n" % justify(request.dump(print_to_stdout = False)))
loggersrv.debug("Request V4: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(request), 'latin-1')), 'utf-8'))) loggersrv.debug("Request V4: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(request), 'latin-1')), 'utf-8')))

View file

@ -8,7 +8,8 @@ import random
import pykms_Aes as aes import pykms_Aes as aes
from pykms_Base import kmsBase from pykms_Base import kmsBase
from pykms_Structure import Structure from pykms_Structure import Structure
from pykms_Format import justify, byterize, enco, deco, ShellMessage from pykms_Format import justify, byterize, enco, deco
from pykms_Misc import pretty_printer
#-------------------------------------------------------------------------------------------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------------------------------------------------------------
@ -140,7 +141,7 @@ class kmsRequestV5(kmsBase):
response['encrypted'] = bytes(bytearray(encryptedResponse)) response['encrypted'] = bytes(bytearray(encryptedResponse))
response['padding'] = bytes(bytearray(self.getPadding(bodyLength))) response['padding'] = bytes(bytearray(self.getPadding(bodyLength)))
ShellMessage.Process(16).run() pretty_printer(None, num_text = 16)
response = byterize(response) response = byterize(response)
loggersrv.info("KMS V%d Response: \n%s\n" % (self.ver, justify(response.dump(print_to_stdout = False)))) loggersrv.info("KMS V%d Response: \n%s\n" % (self.ver, justify(response.dump(print_to_stdout = False))))
loggersrv.info("KMS V%d Structure Bytes: \n%s\n" % (self.ver, justify(deco(binascii.b2a_hex(enco(str(response), 'latin-1')), 'utf-8')))) loggersrv.info("KMS V%d Structure Bytes: \n%s\n" % (self.ver, justify(deco(binascii.b2a_hex(enco(str(response), 'latin-1')), 'utf-8'))))
@ -172,7 +173,7 @@ class kmsRequestV5(kmsBase):
request['versionMajor'] = requestBase['versionMajor'] request['versionMajor'] = requestBase['versionMajor']
request['message'] = message request['message'] = message
ShellMessage.Process(10).run() pretty_printer(None, num_text = 10)
request = byterize(request) request = byterize(request)
loggersrv.info("Request V%d Data: \n%s\n" % (self.ver, justify(request.dump(print_to_stdout = False)))) loggersrv.info("Request V%d Data: \n%s\n" % (self.ver, justify(request.dump(print_to_stdout = False))))
loggersrv.info("Request V%d: \n%s\n" % (self.ver, justify(deco(binascii.b2a_hex(enco(str(request), 'latin-1')), 'utf-8')))) loggersrv.info("Request V%d: \n%s\n" % (self.ver, justify(deco(binascii.b2a_hex(enco(str(request), 'latin-1')), 'utf-8'))))

View file

@ -7,7 +7,8 @@ import uuid
import pykms_RpcBase import pykms_RpcBase
from pykms_Dcerpc import MSRPCHeader, MSRPCBindAck from pykms_Dcerpc import MSRPCHeader, MSRPCBindAck
from pykms_Structure import Structure from pykms_Structure import Structure
from pykms_Format import justify, byterize, enco, deco, ShellMessage from pykms_Format import justify, byterize, enco, deco
from pykms_Misc import pretty_printer
#-------------------------------------------------------------------------------------------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------------------------------------------------------------
@ -77,7 +78,7 @@ class MSRPCBind(Structure):
class handler(pykms_RpcBase.rpcBase): class handler(pykms_RpcBase.rpcBase):
def parseRequest(self): def parseRequest(self):
request = MSRPCHeader(self.data) request = MSRPCHeader(self.data)
ShellMessage.Process(3).run() pretty_printer(None, num_text = 3)
request = byterize(request) request = byterize(request)
loggersrv.debug("RPC Bind Request Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(self.data), 'utf-8'))) loggersrv.debug("RPC Bind Request Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(self.data), 'utf-8')))
loggersrv.debug("RPC Bind Request: \n%s\n%s\n" % (justify(request.dump(print_to_stdout = False)), loggersrv.debug("RPC Bind Request: \n%s\n%s\n" % (justify(request.dump(print_to_stdout = False)),
@ -121,7 +122,7 @@ class handler(pykms_RpcBase.rpcBase):
resp = preparedResponses[ts_uuid] resp = preparedResponses[ts_uuid]
response['ctx_items'] += str(resp) response['ctx_items'] += str(resp)
ShellMessage.Process(4).run() pretty_printer(None, num_text = 4)
response = byterize(response) response = byterize(response)
loggersrv.debug("RPC Bind Response: \n%s\n" % justify(response.dump(print_to_stdout = False))) loggersrv.debug("RPC Bind Response: \n%s\n" % justify(response.dump(print_to_stdout = False)))
loggersrv.debug("RPC Bind Response Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(response), 'latin-1')), 'utf-8'))) loggersrv.debug("RPC Bind Response Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(response), 'latin-1')), 'utf-8')))
@ -162,7 +163,7 @@ class handler(pykms_RpcBase.rpcBase):
request['call_id'] = self.srv_config['call_id'] request['call_id'] = self.srv_config['call_id']
request['pduData'] = str(bind) request['pduData'] = str(bind)
ShellMessage.Process(0).run() pretty_printer(None, num_text = 0)
bind = byterize(bind) bind = byterize(bind)
request = byterize(request) request = byterize(request)
loggersrv.debug("RPC Bind Request: \n%s\n%s\n" % (justify(request.dump(print_to_stdout = False)), loggersrv.debug("RPC Bind Request: \n%s\n%s\n" % (justify(request.dump(print_to_stdout = False)),

View file

@ -6,7 +6,8 @@ import logging
import pykms_Base import pykms_Base
import pykms_RpcBase import pykms_RpcBase
from pykms_Dcerpc import MSRPCRequestHeader, MSRPCRespHeader from pykms_Dcerpc import MSRPCRequestHeader, MSRPCRespHeader
from pykms_Format import justify, byterize, enco, deco, ShellMessage from pykms_Format import justify, byterize, enco, deco
from pykms_Misc import pretty_printer
#---------------------------------------------------------------------------------------------------------------------------------------------------------- #----------------------------------------------------------------------------------------------------------------------------------------------------------
@ -15,7 +16,7 @@ loggersrv = logging.getLogger('logsrv')
class handler(pykms_RpcBase.rpcBase): class handler(pykms_RpcBase.rpcBase):
def parseRequest(self): def parseRequest(self):
request = MSRPCRequestHeader(self.data) request = MSRPCRequestHeader(self.data)
ShellMessage.Process(14).run() pretty_printer(None, num_text = 14)
request = byterize(request) request = byterize(request)
loggersrv.debug("RPC Message Request Bytes: \n%s\n" % justify(binascii.b2a_hex(self.data).decode('utf-8'))) loggersrv.debug("RPC Message Request Bytes: \n%s\n" % justify(binascii.b2a_hex(self.data).decode('utf-8')))
loggersrv.debug("RPC Message Request: \n%s\n" % justify(request.dump(print_to_stdout = False))) loggersrv.debug("RPC Message Request: \n%s\n" % justify(request.dump(print_to_stdout = False)))
@ -40,7 +41,7 @@ class handler(pykms_RpcBase.rpcBase):
response['pduData'] = responseData response['pduData'] = responseData
ShellMessage.Process(17).run() pretty_printer(None, num_text = 17)
response = byterize(response) response = byterize(response)
loggersrv.debug("RPC Message Response: \n%s\n" % justify(response.dump(print_to_stdout = False))) loggersrv.debug("RPC Message Response: \n%s\n" % justify(response.dump(print_to_stdout = False)))
loggersrv.debug("RPC Message Response Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(response), 'latin-1')), 'utf-8'))) loggersrv.debug("RPC Message Response Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(response), 'latin-1')), 'utf-8')))
@ -59,7 +60,7 @@ class handler(pykms_RpcBase.rpcBase):
request['alloc_hint'] = len(self.data) request['alloc_hint'] = len(self.data)
request['pduData'] = str(self.data) request['pduData'] = str(self.data)
ShellMessage.Process(11).run() pretty_printer(None, num_text = 11)
request = byterize(request) request = byterize(request)
loggersrv.debug("RPC Message Request: \n%s\n" % justify(request.dump(print_to_stdout = False))) loggersrv.debug("RPC Message Request: \n%s\n" % justify(request.dump(print_to_stdout = False)))
loggersrv.debug("RPC Message Request Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(request), 'latin-1')), 'utf-8'))) loggersrv.debug("RPC Message Request Bytes: \n%s\n" % justify(deco(binascii.b2a_hex(enco(str(request), 'latin-1')), 'utf-8')))

56
py-kms/pykms_Server.py Normal file → Executable file
View file

@ -23,7 +23,7 @@ except ImportError:
import pykms_RpcBind, pykms_RpcRequest import pykms_RpcBind, pykms_RpcRequest
from pykms_RpcBase import rpcBase from pykms_RpcBase import rpcBase
from pykms_Dcerpc import MSRPCHeader from pykms_Dcerpc import MSRPCHeader
from pykms_Misc import logger_create, check_logfile, check_lcid, pretty_errors from pykms_Misc import logger_create, check_logfile, check_lcid, pretty_printer
from pykms_Format import enco, deco, ShellMessage from pykms_Format import enco, deco, ShellMessage
srv_description = 'KMS Server Emulator written in Python' srv_description = 'KMS Server Emulator written in Python'
@ -36,7 +36,10 @@ class KeyServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
allow_reuse_address = True allow_reuse_address = True
def handle_timeout(self): def handle_timeout(self):
pretty_errors(40, loggersrv) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
put_text = "{red}{bold}Server connection timed out. Exiting...{end}")
def handle_error(self, request, client_address):
pass
class server_thread(threading.Thread): class server_thread(threading.Thread):
def __init__(self): def __init__(self):
@ -134,9 +137,9 @@ def server_options():
try: try:
srv_config.update(vars(parser.parse_args())) srv_config.update(vars(parser.parse_args()))
# Check logfile. # Check logfile.
srv_config['logfile'] = check_logfile(srv_config['logfile'], srv_options['lfile']['def'], loggersrv) srv_config['logfile'] = check_logfile(srv_config['logfile'], srv_options['lfile']['def'], loggersrv.error)
except KmsSrvException as e: except KmsSrvException as e:
pretty_errors(46, loggersrv, get_text = False, put_text = str(e), log_text = False) pretty_printer(loggersrv.error, to_exit = True, put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
def server_check(): def server_check():
# Setup hidden or not messages. # Setup hidden or not messages.
@ -155,33 +158,40 @@ def server_check():
diff = set(hexstr).symmetric_difference(set(hexsub)) diff = set(hexstr).symmetric_difference(set(hexsub))
if len(diff) != 0: if len(diff) != 0:
pretty_errors(41, loggersrv, put_text = [hexstr.upper(), diff]) diff = str(diff).replace('{', '').replace('}', '')
pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
put_text = "{red}{bold}HWID '%s' is invalid. Digit %s non hexadecimal. Exiting...{end}" %(hexstr.upper(), diff))
else: else:
lh = len(hexsub) lh = len(hexsub)
if lh % 2 != 0: if lh % 2 != 0:
pretty_errors(42, loggersrv, put_text = hexsub.upper()) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
put_text = "{red}{bold}HWID '%s' is invalid. Hex string is odd length. Exiting...{end}" %hexsub.upper())
elif lh < 16: elif lh < 16:
pretty_errors(43, loggersrv, put_text = hexsub.upper()) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
put_text = "{red}{bold}HWID '%s' is invalid. Hex string is too short. Exiting...{end}" %hexsub.upper())
elif lh > 16: elif lh > 16:
pretty_errors(44, loggersrv, put_text = hexsub.upper()) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
put_text = "{red}{bold}HWID '%s' is invalid. Hex string is too long. Exiting...{end}" %hexsub.upper())
else: else:
srv_config['hwid'] = binascii.a2b_hex(hexsub) srv_config['hwid'] = binascii.a2b_hex(hexsub)
# Check LCID. # Check LCID.
srv_config['lcid'] = check_lcid(srv_config['lcid'], loggersrv) srv_config['lcid'] = check_lcid(srv_config['lcid'], loggersrv.warning)
# Check sqlite. # Check sqlite.
try: try:
import sqlite3 import sqlite3
except: except:
loggersrv.warning("Module \"sqlite3\" is not installed, database support disabled.") pretty_printer(loggersrv.warning, get_text = True, log_text = True,
put_text = "Module 'sqlite3' is not installed, database support disabled.")
srv_config['dbSupport'] = False srv_config['dbSupport'] = False
else: else:
srv_config['dbSupport'] = True srv_config['dbSupport'] = True
# Check port. # Check port.
if not 1 <= srv_config['port'] <= 65535: if not 1 <= srv_config['port'] <= 65535:
pretty_errors(45, loggersrv, put_text = srv_config['port']) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
put_text = "{red}{bold}Port number '%s' is invalid. Enter between 1 - 65535. Exiting...{end}" %srv_config['port'])
def server_create(): def server_create():
server = KeyServer((srv_config['ip'], srv_config['port']), kmsServerHandler) server = KeyServer((srv_config['ip'], srv_config['port']), kmsServerHandler)
@ -222,27 +232,27 @@ class kmsServerHandler(socketserver.BaseRequestHandler):
# self.request is the TCP socket connected to the client # self.request is the TCP socket connected to the client
try: try:
self.data = self.request.recv(1024) self.data = self.request.recv(1024)
except socket.error as e: if self.data == '' or not self.data:
if e.errno == errno.ECONNRESET: pretty_printer(loggersrv.warning, get_text = True, log_text = True,
loggersrv.error("Connection reset by peer.") put_text = "{yellow}{bold}No data received.{end}")
break break
else: except socket.error as e:
raise pretty_printer(loggersrv.error, get_text = True, log_text = True,
if self.data == '' or not self.data: put_text = "{red}{bold}While receiving: %s{end}" %str(e))
loggersrv.warning("No data received !")
break break
packetType = MSRPCHeader(self.data)['type'] packetType = MSRPCHeader(self.data)['type']
if packetType == rpcBase.packetType['bindReq']: if packetType == rpcBase.packetType['bindReq']:
loggersrv.info("RPC bind request received.") loggersrv.info("RPC bind request received.")
ShellMessage.Process([-2, 2]).run() pretty_printer(None, num_text = [-2, 2])
handler = pykms_RpcBind.handler(self.data, srv_config) handler = pykms_RpcBind.handler(self.data, srv_config)
elif packetType == rpcBase.packetType['request']: elif packetType == rpcBase.packetType['request']:
loggersrv.info("Received activation request.") loggersrv.info("Received activation request.")
ShellMessage.Process([-2, 13]).run() pretty_printer(None, num_text = [-2, 13])
handler = pykms_RpcRequest.handler(self.data, srv_config) handler = pykms_RpcRequest.handler(self.data, srv_config)
else: else:
loggersrv.error("Invalid RPC request type ", packetType) pretty_printer(loggersrv.error, get_text = True, log_text = True,
put_text = "Invalid RPC request type %s" %packetType)
break break
res = enco(str(handler.populate()), 'latin-1') res = enco(str(handler.populate()), 'latin-1')
@ -250,10 +260,10 @@ class kmsServerHandler(socketserver.BaseRequestHandler):
if packetType == rpcBase.packetType['bindReq']: if packetType == rpcBase.packetType['bindReq']:
loggersrv.info("RPC bind acknowledged.") loggersrv.info("RPC bind acknowledged.")
ShellMessage.Process([-3, 5, 6]).run() pretty_printer(None, num_text = [-3, 5, 6])
elif packetType == rpcBase.packetType['request']: elif packetType == rpcBase.packetType['request']:
loggersrv.info("Responded to activation request.") loggersrv.info("Responded to activation request.")
ShellMessage.Process([-3, 18, 19]).run() pretty_printer(None, num_text = [-3, 18, 19])
break break
def finish(self): def finish(self):

View file

@ -10,6 +10,8 @@ try:
except ImportError: except ImportError:
pass pass
from pykms_Misc import pretty_printer
#-------------------------------------------------------------------------------------------------------------------------------------------------------- #--------------------------------------------------------------------------------------------------------------------------------------------------------
loggersrv = logging.getLogger('logsrv') loggersrv = logging.getLogger('logsrv')
@ -26,8 +28,8 @@ def sql_initialize():
licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)") licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)")
except sqlite3.Error as e: except sqlite3.Error as e:
loggersrv.error("Error %s:" % e.args[0]) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
sys.exit(1) put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
finally: finally:
if con: if con:
con.commit() con.commit()
@ -63,11 +65,11 @@ skuId, licenseStatus, lastRequestTime, requestCount) VALUES (:clientMachineId, :
cur.execute("UPDATE clients SET requestCount=requestCount+1 WHERE clientMachineId=:clientMachineId;", infoDict) cur.execute("UPDATE clients SET requestCount=requestCount+1 WHERE clientMachineId=:clientMachineId;", infoDict)
except sqlite3.Error as e: except sqlite3.Error as e:
loggersrv.error("Error %s:" % e.args[0]) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
sys.exit(1) put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
except sqlite3.Error as e: except sqlite3.Error as e:
loggersrv.error("Error %s:" % e.args[0]) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
sys.exit(1) put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
finally: finally:
if con: if con:
con.commit() con.commit()
@ -88,11 +90,11 @@ def sql_update_epid(dbName, kmsRequest, response):
cur.execute("UPDATE clients SET kmsEpid=? WHERE clientMachineId=?;", (str(response["kmsEpid"].decode('utf-16le')), cur.execute("UPDATE clients SET kmsEpid=? WHERE clientMachineId=?;", (str(response["kmsEpid"].decode('utf-16le')),
cmid)) cmid))
except sqlite3.Error as e: except sqlite3.Error as e:
loggersrv.error("Error %s:" % e.args[0]) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
sys.exit(1) put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
except sqlite3.Error as e: except sqlite3.Error as e:
loggersrv.error("Error %s:" % e.args[0]) pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
sys.exit(1) put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
finally: finally:
if con: if con:
con.commit() con.commit()