mirror of
https://github.com/SystemRage/py-kms.git
synced 2024-11-22 08:15:38 +01:00
Made all pretty-print process handy
This commit is contained in:
parent
dddc02530b
commit
19e5abbbbd
@ -13,7 +13,8 @@ from pykms_DB2Dict import kmsDB2Dict
|
||||
from pykms_PidGenerator import epidGenerator
|
||||
from pykms_Filetimes import filetime_to_dt
|
||||
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
|
||||
|
||||
#--------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
@ -111,8 +112,8 @@ class kmsBase:
|
||||
def serverLogic(self, kmsRequest):
|
||||
if self.srv_config['sqlite'] and self.srv_config['dbSupport']:
|
||||
self.dbName = sql_initialize()
|
||||
|
||||
ShellMessage.Process(15).run()
|
||||
|
||||
pretty_printer(None, num_text = 15)
|
||||
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: \n%s\n" % justify(kmsRequest.dump(print_to_stdout = False)))
|
||||
@ -130,10 +131,12 @@ class kmsBase:
|
||||
tz = get_localzone()
|
||||
local_dt = tz.localize(requestDatetime)
|
||||
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
|
||||
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
|
||||
|
||||
# Activation threshold.
|
||||
|
@ -22,7 +22,7 @@ from pykms_RequestV5 import kmsRequestV5
|
||||
from pykms_RequestV6 import kmsRequestV6
|
||||
from pykms_RpcBase import rpcBase
|
||||
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
|
||||
|
||||
clt_description = 'KMS Client Emulator written in Python'
|
||||
@ -126,31 +126,30 @@ def client_create():
|
||||
binder = pykms_RpcBind.handler(None, clt_config)
|
||||
RPC_Bind = enco(str(binder.generateRequest()), 'latin-1')
|
||||
loggerclt.info("Sending RPC bind request...")
|
||||
ShellMessage.Process([-1, 1]).run()
|
||||
pretty_printer(None, num_text = [-1, 1])
|
||||
s.send(RPC_Bind)
|
||||
|
||||
try:
|
||||
ShellMessage.Process([-4, 7]).run()
|
||||
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:
|
||||
if e.errno == errno.ECONNRESET:
|
||||
loggerclt.error("Connection reset by peer. Exiting...")
|
||||
sys.exit()
|
||||
else:
|
||||
raise
|
||||
if bindResponse == '' or not bindResponse:
|
||||
loggerclt.error("No data received ! Exiting...")
|
||||
sys.exit()
|
||||
pretty_printer(loggerclt.error, get_text = True, log_text = True, to_exit = True,
|
||||
put_text = "{red}{bold}While receiving: %s{end}" %str(e))
|
||||
|
||||
packetType = MSRPCHeader(bindResponse)['type']
|
||||
if packetType == rpcBase.packetType['bindAck']:
|
||||
loggerclt.info("RPC bind acknowledged.")
|
||||
ShellMessage.Process(8).run()
|
||||
pretty_printer(None, num_text = 8)
|
||||
kmsRequest = createKmsRequest()
|
||||
requester = pykms_RpcRequest.handler(kmsRequest, clt_config)
|
||||
s.send(enco(str(requester.generateRequest()), 'latin-1'))
|
||||
ShellMessage.Process([-1, 12]).run()
|
||||
pretty_printer(None, num_text = [-1, 12])
|
||||
response = s.recv(1024)
|
||||
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)
|
||||
kmsData = readKmsResponse(parsed['pduData'], kmsRequest, clt_config)
|
||||
kmsResp = kmsData['response']
|
||||
@ -169,16 +168,15 @@ def client_create():
|
||||
loggerclt.mini("", extra = {'host': socket.gethostname() + " [" + clt_config["ip"] + "]",
|
||||
'status' : "Activated",
|
||||
'product' : clt_config["mode"]})
|
||||
|
||||
ShellMessage.Process(21).run()
|
||||
|
||||
pretty_printer(None, num_text = 21)
|
||||
|
||||
elif packetType == rpcBase.packetType['bindNak']:
|
||||
loggerclt.info(justify(MSRPCBindNak(bindResponse).dump(print_to_stdout = False)))
|
||||
sys.exit()
|
||||
sys.exit(0)
|
||||
else:
|
||||
loggerclt.critical("Something went wrong.")
|
||||
sys.exit()
|
||||
|
||||
pretty_printer(loggerclt.warning, get_text = True, log_text = True, to_exit = True,
|
||||
put_text = "{magenta}{bold}Something went wrong.{end}")
|
||||
|
||||
def clt_main(with_gui = False):
|
||||
if not with_gui:
|
||||
@ -211,7 +209,7 @@ def createKmsRequestBase():
|
||||
requestDict['mnPad'] = '\0'.encode('utf-16le') * (63 - len(requestDict['machineName'].decode('utf-16le')))
|
||||
|
||||
# Debug Stuff
|
||||
ShellMessage.Process(9).run()
|
||||
pretty_printer(None, num_text = 9)
|
||||
requestDict = byterize(requestDict)
|
||||
loggerclt.debug("Request Base Dictionary: \n%s\n" % justify(requestDict.dump(print_to_stdout = False)))
|
||||
|
||||
|
@ -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"},
|
||||
21 : {'text' : "{green}{bold}\t\t\tActivation Done !!!{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"},
|
||||
-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):
|
||||
@ -180,30 +172,25 @@ class ShellMessage(object):
|
||||
class Process(object):
|
||||
def __init__(self, nshell, get_text = False, put_text = None):
|
||||
self.nshell = nshell
|
||||
self.print_queue = Queue.Queue()
|
||||
self.get_text = get_text
|
||||
self.put_text = put_text
|
||||
self.print_queue = Queue.Queue()
|
||||
self.plaintext = []
|
||||
|
||||
if not isinstance(nshell, list):
|
||||
self.nshell = [nshell]
|
||||
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)
|
||||
|
||||
def formatter(self, msgtofrmt):
|
||||
self.msgfrmt = msgtofrmt.format(**ColorExtraMap)
|
||||
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):
|
||||
if not ShellMessage.view:
|
||||
if self.get_text:
|
||||
for num in self.nshell:
|
||||
self.formatter(num)
|
||||
if self.put_text is not None:
|
||||
for mess in self.put_text:
|
||||
self.formatter(mess)
|
||||
else:
|
||||
for num in self.nshell:
|
||||
self.formatter(MsgMap[num]['text'])
|
||||
return self.plaintext
|
||||
else:
|
||||
return
|
||||
@ -234,9 +221,14 @@ class ShellMessage(object):
|
||||
|
||||
try:
|
||||
# Print something.
|
||||
for num in self.nshell:
|
||||
self.formatter(num)
|
||||
print(self.msg, flush = True)
|
||||
if self.put_text is not None:
|
||||
for mess in self.put_text:
|
||||
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:
|
||||
# Restore stdout and send content.
|
||||
sys.stdout = sys.__stdout__
|
||||
|
@ -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):
|
||||
optionlog = [optionlog]
|
||||
|
||||
lenopt = len(optionlog)
|
||||
msg_long = "argument logfile: too much arguments"
|
||||
msg_long = "{red}{bold}Argument logfile: Too much arguments{end}"
|
||||
|
||||
def checkdir(path):
|
||||
msg_path = "argument logfile: No such file or directory: %s" %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:
|
||||
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 lenopt == 1:
|
||||
@ -156,33 +156,50 @@ def check_logfile(optionlog, defaultlog, logger):
|
||||
checkdir(optionlog[1])
|
||||
else:
|
||||
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:
|
||||
# check directory path.
|
||||
checkdir(optionlog[0])
|
||||
return optionlog
|
||||
|
||||
|
||||
def pretty_errors(error_num, logger, **kwargs):
|
||||
""" error_num --> an int or list of int.
|
||||
def pretty_printer(log_obj, **kwargs):
|
||||
""" `log_obj` --> logging object.
|
||||
kwargs:
|
||||
get_text --> True (default) / False.
|
||||
put_text --> string / list of strings/ None. (applied to each "error_num")
|
||||
log_text --> True (default) / False.
|
||||
to_exit --> True (default) / False.
|
||||
`get_text` --> if True obtain text not ansi formatted,
|
||||
after printing it with ansi formattation.
|
||||
`put_text` --> a string or list of strings with ansi formattation.
|
||||
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.
|
||||
options = {'get_text' : True,
|
||||
options = {'get_text' : False,
|
||||
'put_text' : None,
|
||||
'log_text' : True,
|
||||
'to_exit' : True,
|
||||
'num_text' : None,
|
||||
'log_text' : False,
|
||||
'to_exit' : False,
|
||||
}
|
||||
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.
|
||||
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']:
|
||||
for err in error_msgs:
|
||||
logger.error(err)
|
||||
for plain_message in plain_messages:
|
||||
log_obj(plain_message)
|
||||
if options['to_exit']:
|
||||
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]
|
||||
|
||||
# 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 hasattr(sys, 'implementation') and sys.implementation.name == 'cpython':
|
||||
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])
|
||||
except StopIteration:
|
||||
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 lcid
|
||||
|
||||
|
@ -7,7 +7,8 @@ import logging
|
||||
from pykms_Base import kmsBase
|
||||
from pykms_Structure import Structure
|
||||
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)))
|
||||
|
||||
## Debug stuff.
|
||||
ShellMessage.Process(16).run()
|
||||
pretty_printer(None, num_text = 16)
|
||||
response = byterize(response)
|
||||
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')))
|
||||
@ -124,7 +125,7 @@ class kmsRequestV4(kmsBase):
|
||||
request['padding'] = bytes(bytearray(self.getPadding(bodyLength)))
|
||||
|
||||
## Debug stuff.
|
||||
ShellMessage.Process(10).run()
|
||||
pretty_printer(None, num_text = 10)
|
||||
request = byterize(request)
|
||||
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')))
|
||||
|
@ -8,7 +8,8 @@ import random
|
||||
import pykms_Aes as aes
|
||||
from pykms_Base import kmsBase
|
||||
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['padding'] = bytes(bytearray(self.getPadding(bodyLength)))
|
||||
|
||||
ShellMessage.Process(16).run()
|
||||
pretty_printer(None, num_text = 16)
|
||||
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 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['message'] = message
|
||||
|
||||
ShellMessage.Process(10).run()
|
||||
pretty_printer(None, num_text = 10)
|
||||
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: \n%s\n" % (self.ver, justify(deco(binascii.b2a_hex(enco(str(request), 'latin-1')), 'utf-8'))))
|
||||
|
@ -7,7 +7,8 @@ import uuid
|
||||
import pykms_RpcBase
|
||||
from pykms_Dcerpc import MSRPCHeader, MSRPCBindAck
|
||||
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):
|
||||
def parseRequest(self):
|
||||
request = MSRPCHeader(self.data)
|
||||
ShellMessage.Process(3).run()
|
||||
pretty_printer(None, num_text = 3)
|
||||
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: \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]
|
||||
response['ctx_items'] += str(resp)
|
||||
|
||||
ShellMessage.Process(4).run()
|
||||
pretty_printer(None, num_text = 4)
|
||||
response = byterize(response)
|
||||
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')))
|
||||
@ -161,8 +162,8 @@ class handler(pykms_RpcBase.rpcBase):
|
||||
request['flags'] = self.packetFlags['firstFrag'] | self.packetFlags['lastFrag'] | self.packetFlags['multiplex']
|
||||
request['call_id'] = self.srv_config['call_id']
|
||||
request['pduData'] = str(bind)
|
||||
|
||||
ShellMessage.Process(0).run()
|
||||
|
||||
pretty_printer(None, num_text = 0)
|
||||
bind = byterize(bind)
|
||||
request = byterize(request)
|
||||
loggersrv.debug("RPC Bind Request: \n%s\n%s\n" % (justify(request.dump(print_to_stdout = False)),
|
||||
|
@ -6,7 +6,8 @@ import logging
|
||||
import pykms_Base
|
||||
import pykms_RpcBase
|
||||
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):
|
||||
def parseRequest(self):
|
||||
request = MSRPCRequestHeader(self.data)
|
||||
ShellMessage.Process(14).run()
|
||||
pretty_printer(None, num_text = 14)
|
||||
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: \n%s\n" % justify(request.dump(print_to_stdout = False)))
|
||||
@ -40,7 +41,7 @@ class handler(pykms_RpcBase.rpcBase):
|
||||
|
||||
response['pduData'] = responseData
|
||||
|
||||
ShellMessage.Process(17).run()
|
||||
pretty_printer(None, num_text = 17)
|
||||
response = byterize(response)
|
||||
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')))
|
||||
@ -58,8 +59,8 @@ class handler(pykms_RpcBase.rpcBase):
|
||||
request['call_id'] = self.srv_config['call_id']
|
||||
request['alloc_hint'] = len(self.data)
|
||||
request['pduData'] = str(self.data)
|
||||
|
||||
ShellMessage.Process(11).run()
|
||||
|
||||
pretty_printer(None, num_text = 11)
|
||||
request = byterize(request)
|
||||
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')))
|
||||
|
56
py-kms/pykms_Server.py
Normal file → Executable file
56
py-kms/pykms_Server.py
Normal file → Executable file
@ -23,7 +23,7 @@ except ImportError:
|
||||
import pykms_RpcBind, pykms_RpcRequest
|
||||
from pykms_RpcBase import rpcBase
|
||||
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
|
||||
|
||||
srv_description = 'KMS Server Emulator written in Python'
|
||||
@ -36,7 +36,10 @@ class KeyServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
|
||||
allow_reuse_address = True
|
||||
|
||||
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):
|
||||
def __init__(self):
|
||||
@ -134,9 +137,9 @@ def server_options():
|
||||
try:
|
||||
srv_config.update(vars(parser.parse_args()))
|
||||
# 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:
|
||||
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():
|
||||
# Setup hidden or not messages.
|
||||
@ -155,33 +158,40 @@ def server_check():
|
||||
diff = set(hexstr).symmetric_difference(set(hexsub))
|
||||
|
||||
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:
|
||||
lh = len(hexsub)
|
||||
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:
|
||||
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:
|
||||
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:
|
||||
srv_config['hwid'] = binascii.a2b_hex(hexsub)
|
||||
|
||||
# Check LCID.
|
||||
srv_config['lcid'] = check_lcid(srv_config['lcid'], loggersrv)
|
||||
srv_config['lcid'] = check_lcid(srv_config['lcid'], loggersrv.warning)
|
||||
|
||||
# Check sqlite.
|
||||
try:
|
||||
import sqlite3
|
||||
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
|
||||
else:
|
||||
srv_config['dbSupport'] = True
|
||||
|
||||
# Check port.
|
||||
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():
|
||||
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
|
||||
try:
|
||||
self.data = self.request.recv(1024)
|
||||
except socket.error as e:
|
||||
if e.errno == errno.ECONNRESET:
|
||||
loggersrv.error("Connection reset by peer.")
|
||||
if self.data == '' or not self.data:
|
||||
pretty_printer(loggersrv.warning, get_text = True, log_text = True,
|
||||
put_text = "{yellow}{bold}No data received.{end}")
|
||||
break
|
||||
else:
|
||||
raise
|
||||
if self.data == '' or not self.data:
|
||||
loggersrv.warning("No data received !")
|
||||
except socket.error as e:
|
||||
pretty_printer(loggersrv.error, get_text = True, log_text = True,
|
||||
put_text = "{red}{bold}While receiving: %s{end}" %str(e))
|
||||
break
|
||||
|
||||
packetType = MSRPCHeader(self.data)['type']
|
||||
if packetType == rpcBase.packetType['bindReq']:
|
||||
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)
|
||||
elif packetType == rpcBase.packetType['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)
|
||||
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
|
||||
|
||||
res = enco(str(handler.populate()), 'latin-1')
|
||||
@ -250,10 +260,10 @@ class kmsServerHandler(socketserver.BaseRequestHandler):
|
||||
|
||||
if packetType == rpcBase.packetType['bindReq']:
|
||||
loggersrv.info("RPC bind acknowledged.")
|
||||
ShellMessage.Process([-3, 5, 6]).run()
|
||||
pretty_printer(None, num_text = [-3, 5, 6])
|
||||
elif packetType == rpcBase.packetType['request']:
|
||||
loggersrv.info("Responded to activation request.")
|
||||
ShellMessage.Process([-3, 18, 19]).run()
|
||||
pretty_printer(None, num_text = [-3, 18, 19])
|
||||
break
|
||||
|
||||
def finish(self):
|
||||
|
@ -10,6 +10,8 @@ try:
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
from pykms_Misc import pretty_printer
|
||||
|
||||
#--------------------------------------------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
loggersrv = logging.getLogger('logsrv')
|
||||
@ -26,8 +28,8 @@ def sql_initialize():
|
||||
licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)")
|
||||
|
||||
except sqlite3.Error as e:
|
||||
loggersrv.error("Error %s:" % e.args[0])
|
||||
sys.exit(1)
|
||||
pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
|
||||
put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
|
||||
finally:
|
||||
if con:
|
||||
con.commit()
|
||||
@ -63,11 +65,11 @@ skuId, licenseStatus, lastRequestTime, requestCount) VALUES (:clientMachineId, :
|
||||
cur.execute("UPDATE clients SET requestCount=requestCount+1 WHERE clientMachineId=:clientMachineId;", infoDict)
|
||||
|
||||
except sqlite3.Error as e:
|
||||
loggersrv.error("Error %s:" % e.args[0])
|
||||
sys.exit(1)
|
||||
pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
|
||||
put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
|
||||
except sqlite3.Error as e:
|
||||
loggersrv.error("Error %s:" % e.args[0])
|
||||
sys.exit(1)
|
||||
pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
|
||||
put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
|
||||
finally:
|
||||
if con:
|
||||
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')),
|
||||
cmid))
|
||||
except sqlite3.Error as e:
|
||||
loggersrv.error("Error %s:" % e.args[0])
|
||||
sys.exit(1)
|
||||
pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
|
||||
put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
|
||||
except sqlite3.Error as e:
|
||||
loggersrv.error("Error %s:" % e.args[0])
|
||||
sys.exit(1)
|
||||
pretty_printer(loggersrv.error, get_text = True, log_text = True, to_exit = True,
|
||||
put_text = "{red}{bold}%s. Exiting...{end}" %str(e))
|
||||
finally:
|
||||
if con:
|
||||
con.commit()
|
||||
|
Loading…
Reference in New Issue
Block a user