def generateRequest(self, requestBase): esalt = self.getRandomSalt() moo = aes.AESModeOfOperation() moo.aes.v6 = self.v6 dsalt = moo.decrypt(esalt, 16, moo.ModeOfOperation["CBC"], self.key, moo.aes.KeySize["SIZE_128"], esalt) dsalt = bytearray(dsalt) decrypted = self.DecryptedRequest() decrypted['salt'] = dsalt decrypted['request'] = requestBase padded = aes.append_PKCS7_padding(str(decrypted).encode('latin-1')) mode, orig_len, crypted = moo.encrypt(padded, moo.ModeOfOperation["CBC"], self.key, moo.aes.KeySize["SIZE_128"], esalt) message = self.RequestV5.Message(bytes(crypted)) request = self.RequestV5() bodyLength = 2 + 2 + len(message) request['bodyLength1'] = bodyLength request['bodyLength2'] = bodyLength request['versionMinor'] = requestBase['versionMinor'] request['versionMajor'] = requestBase['versionMajor'] request['message'] = message shell_message(nshell = 10) request = byterize(request) logger.info("Request V%d Data: \n%s\n" % (self.ver, justify(request.dump(print_to_stdout = False)))) logger.info("Request V%d: \n%s\n" % (self.ver, justify(binascii.b2a_hex(str(request).encode('latin-1')).decode('utf-8')))) return request
def generateResponse(self): request = self.requestData responseData = kmsBase.generateKmsResponseData(request['pduData'], self.config) envelopeLength = len(responseData) response = MSRPCRespHeader() response['ver_major'] = request['ver_major'] response['ver_minor'] = request['ver_minor'] response['type'] = self.packetType['response'] response['flags'] = self.packetFlags['firstFrag'] | self.packetFlags['lastFrag'] response['representation'] = request['representation'] response['call_id'] = request['call_id'] response['alloc_hint'] = envelopeLength response['ctx_id'] = request['ctx_id'] response['cancel_count'] = 0 response['pduData'] = responseData shell_message(nshell = 17) logging.debug("RPC Message Response: \n%s\n" % justify(response.dump(print_to_stdout = False))) logging.debug("RPC Message Response Bytes: \n%s\n" % justify(binascii.b2a_hex(str(response)))) return response
def generateRequest(self, requestBase): esalt = self.getRandomSalt() moo = aes.AESModeOfOperation() moo.aes.v6 = self.v6 dsalt = moo.decrypt(esalt, 16, moo.ModeOfOperation["CBC"], self.key, moo.aes.KeySize["SIZE_128"], esalt) #*2to3* dsalt = bytearray(dsalt) decrypted = self.DecryptedRequest() decrypted['salt'] = dsalt #*2to3* decrypted['request'] = requestBase padded = aes.append_PKCS7_padding(str(decrypted).encode('latin-1')) #*2to3* mode, orig_len, crypted = moo.encrypt(padded, moo.ModeOfOperation["CBC"], self.key, moo.aes.KeySize["SIZE_128"], esalt) #*2to3* message = self.RequestV5.Message(bytes(crypted)) #*2to3* bodyLength = len(message) + 2 + 2 request = self.RequestV5() request['bodyLength1'] = bodyLength request['bodyLength2'] = bodyLength request['versionMinor'] = requestBase['versionMinor'] request['versionMajor'] = requestBase['versionMajor'] request['message'] = message shell_message(nshell = 10) request = byterize(request) logging.info("Request V%d Data: \n%s\n" % (self.ver, justify(request.dump(print_to_stdout = False)))) logging.info("Request V%d: \n%s\n" % (self.ver, justify(binascii.b2a_hex(str(request).encode('latin-1')).decode('utf-8')))) #*2to3* return request
def parseRequest(self): request = MSRPCRequestHeader(self.data) shell_message(nshell = 14) logging.debug("RPC Message Request Bytes: \n%s\n" % justify(binascii.b2a_hex(self.data))) logging.debug("RPC Message Request: \n%s\n" % justify(request.dump(print_to_stdout = False))) return request
def generateResponse(self, request): responseData = kmsBase.generateKmsResponseData(request['pduData'], self.config) envelopeLength = len(responseData) response = MSRPCRespHeader() response['ver_major'] = request['ver_major'] response['ver_minor'] = request['ver_minor'] response['type'] = self.packetType['response'] response['flags'] = self.packetFlags['firstFrag'] | self.packetFlags[ 'lastFrag'] response['representation'] = request['representation'] response['call_id'] = request['call_id'] response['alloc_hint'] = envelopeLength response['ctx_id'] = request['ctx_id'] response['cancel_count'] = 0 response['pduData'] = responseData shell_message(nshell=17) response = byterize(response) logger.debug("RPC Message Response: \n%s\n" % justify(response.dump(print_to_stdout=False))) logger.debug("RPC Message Response Bytes: \n%s\n" % justify( binascii.b2a_hex(str(response).encode('latin-1')).decode('utf-8'))) return response
def parseRequest(self): request = MSRPCHeader(self.data) shell_message(nshell = 3) logging.debug("RPC Bind Request Bytes: \n%s\n" % justify(binascii.b2a_hex(self.data))) logging.debug("RPC Bind Request: \n%s\n%s\n" % (justify(request.dump(print_to_stdout = False)), justify(MSRPCBind(request['pduData']).dump(print_to_stdout = False)))) return request
def generateResponse(self, responseBuffer, hash): bodyLength = len(responseBuffer) + len(hash) response = self.ResponseV4() response['response'] = responseBuffer response['hash'] = hash response['padding'] = self.getResponsePadding(bodyLength) shell_message(nshell = 16) logging.debug("KMS V4 Response: %s" % justify(response.dump(print_to_stdout = False))) logging.debug("KMS V4 Response Bytes: %s" % justify(binascii.b2a_hex(str(response)))) return str(response)
def generateRequest(self): firstCtxItem = CtxItem() firstCtxItem['ContextID'] = 0 firstCtxItem['TransItems'] = 1 firstCtxItem['Pad'] = 0 firstCtxItem['AbstractSyntaxUUID'] = uuid.UUID( '51c82175-844e-4750-b0d8-ec255555bc06').bytes_le firstCtxItem['AbstractSyntaxVer'] = 1 firstCtxItem['TransferSyntaxUUID'] = uuidNDR32.bytes_le firstCtxItem['TransferSyntaxVer'] = 2 secondCtxItem = CtxItem() secondCtxItem['ContextID'] = 1 secondCtxItem['TransItems'] = 1 secondCtxItem['Pad'] = 0 secondCtxItem['AbstractSyntaxUUID'] = uuid.UUID( '51c82175-844e-4750-b0d8-ec255555bc06').bytes_le secondCtxItem['AbstractSyntaxVer'] = 1 secondCtxItem['TransferSyntaxUUID'] = uuidTime.bytes_le secondCtxItem['TransferSyntaxVer'] = 1 bind = MSRPCBind() bind['max_tfrag'] = 5840 bind['max_rfrag'] = 5840 bind['assoc_group'] = 0 bind['ctx_num'] = 2 bind['ctx_items'] = str( bind.CtxItemArray(str(firstCtxItem) + str(secondCtxItem))) #*2to3* request = MSRPCHeader() request['ver_major'] = 5 request['ver_minor'] = 0 request['type'] = self.packetType['bindReq'] request['flags'] = self.packetFlags['firstFrag'] | self.packetFlags[ 'lastFrag'] | self.packetFlags['multiplex'] request['call_id'] = self.config['call_id'] request['pduData'] = str(bind) shell_message(nshell=0) bind = byterize(bind) request = byterize(request) logging.debug( "RPC Bind Request: \n%s\n%s\n" % (justify(request.dump(print_to_stdout=False)), justify( MSRPCBind(request['pduData']).dump(print_to_stdout=False)))) logging.debug("RPC Bind Request Bytes: \n%s\n" % justify( binascii.b2a_hex( str(request).encode('latin-1')).decode('utf-8'))) #*2to3* return request
def generateResponse(self, iv, encryptedResponse): bodyLength = 4 + len(iv) + len(encryptedResponse) response = self.ResponseV5() response['versionMinor'] = self.requestData['versionMinor'] response['versionMajor'] = self.requestData['versionMajor'] response['salt'] = iv response['encrypted'] = encryptedResponse response['padding'] = self.getResponsePadding(bodyLength) shell_message(nshell = 16) logging.info("KMS V%d Response: \n%s\n" % (self.ver, justify(response.dump(print_to_stdout = False)))) logging.info("KMS V%d Structure Bytes: \n%s\n" % (self.ver, justify(binascii.b2a_hex(str(response))))) return str(response)
def generateResponse(self, responseBuffer, thehash): bodyLength = len(responseBuffer) + len(thehash) response = self.ResponseV4() response['response'] = responseBuffer response['hash'] = thehash.decode('latin-1') #*2to3* response['padding'] = self.getResponsePadding(bodyLength).decode('latin-1') #*2to3* ## Debug stuff. shell_message(nshell = 16) response = byterize(response) logging.debug("KMS V4 Response: \n%s\n" % justify(response.dump(print_to_stdout = False))) logging.debug("KMS V4 Response Bytes: \n%s\n" % justify(binascii.b2a_hex(str(response).encode('latin-1')).decode('utf-8'))) #*2to3* return str(response)
def createKmsRequestBase(): requestDict = kmsBase.kmsRequestStruct() requestDict['versionMinor'] = config['KMSProtocolMinorVersion'] requestDict['versionMajor'] = config['KMSProtocolMajorVersion'] requestDict['isClientVm'] = 0 requestDict['licenseStatus'] = config['KMSClientLicenseStatus'] requestDict['graceTime'] = 43200 requestDict['applicationId'] = UUID( uuid.UUID(config['KMSClientAppID']).bytes_le) requestDict['skuId'] = UUID(uuid.UUID(config['KMSClientSkuID']).bytes_le) requestDict['kmsCountedId'] = UUID( uuid.UUID(config['KMSClientKMSCountedID']).bytes_le) requestDict['clientMachineId'] = UUID( uuid.UUID(config['cmid']).bytes_le if ( config['cmid'] is not None) else uuid.uuid4().bytes_le) requestDict[ 'previousClientMachineId'] = '\0' * 16 #requestDict['clientMachineId'] # I'm pretty sure this is supposed to be a null UUID. requestDict['requiredClientCount'] = config['RequiredClientCount'] requestDict['requestTime'] = filetimes.dt_to_filetime( datetime.datetime.utcnow()) requestDict['machineName'] = (config['machineName'] if ( config['machineName'] is not None) else ''.join( random.choice(string.ascii_letters + string.digits) for i in range(random.randint(2, 63)))).encode('utf-16le') requestDict['mnPad'] = '\0'.encode('utf-16le') * ( 63 - len(requestDict['machineName'].decode('utf-16le'))) # Debug Stuff shell_message(nshell=9) requestDict = byterize(requestDict) logging.debug("Request Base Dictionary: \n%s\n" % justify(requestDict.dump(print_to_stdout=False))) return requestDict
def generateResponse(self): response = MSRPCBindAck() request = self.requestData bind = MSRPCBind(request['pduData']) response['ver_major'] = request['ver_major'] response['ver_minor'] = request['ver_minor'] response['type'] = self.packetType['bindAck'] response['flags'] = self.packetFlags['firstFrag'] | self.packetFlags[ 'lastFrag'] | self.packetFlags['multiplex'] response['representation'] = request['representation'] response['frag_len'] = 36 + bind['ctx_num'] * 24 response['auth_len'] = request['auth_len'] response['call_id'] = request['call_id'] response['max_tfrag'] = bind['max_tfrag'] response['max_rfrag'] = bind['max_rfrag'] response['assoc_group'] = 0x1063bf3f port = str(self.config['port']) response['SecondaryAddrLen'] = len(port) + 1 response['SecondaryAddr'] = port pad = (4 - ((response["SecondaryAddrLen"] + MSRPCBindAck._SIZE) % 4)) % 4 response['Pad'] = '\0' * pad response['ctx_num'] = bind['ctx_num'] preparedResponses = {} preparedResponses[uuidNDR32] = CtxItemResult(0, 0, uuidNDR32, 2) preparedResponses[uuidNDR64] = CtxItemResult(2, 2, uuidEmpty, 0) preparedResponses[uuidTime] = CtxItemResult(3, 3, uuidEmpty, 0) response['ctx_items'] = '' for i in range(0, bind['ctx_num']): ts_uuid = bind['ctx_items'][i].ts() resp = preparedResponses[ts_uuid] response['ctx_items'] += str(resp) shell_message(nshell=4) response = byterize(response) logging.debug("RPC Bind Response: \n%s\n" % justify(response.dump(print_to_stdout=False))) logging.debug("RPC Bind Response Bytes: \n%s\n" % justify( binascii.b2a_hex( str(response).encode('latin-1')).decode('utf-8'))) #*2to3* return response
def generateRequest(self): request = MSRPCRequestHeader() request['ver_major'] = 5 request['ver_minor'] = 0 request['type'] = self.packetType['request'] request['flags'] = self.packetFlags['firstFrag'] | self.packetFlags['lastFrag'] request['representation'] = 0x10 request['call_id'] = self.config['call_id'] request['alloc_hint'] = len(self.data) request['pduData'] = str(self.data) shell_message(nshell = 11) logging.debug("RPC Message Request: \n%s\n" % justify(request.dump(print_to_stdout = False))) logging.debug("RPC Message Request Bytes: \n%s\n" % justify(binascii.b2a_hex(str(request)))) return request
def generateResponse(self, responseBuffer, hash): response = self.ResponseV4() bodyLength = len(responseBuffer) + len(hash) response['bodyLength1'] = bodyLength response['bodyLength2'] = bodyLength response['response'] = responseBuffer response['hash'] = hash response['padding'] = bytearray(self.getPadding(bodyLength)) ## Debug stuff. shell_message(nshell=16) logging.debug("KMS V4 Response: \n%s\n" % justify(response.dump(print_to_stdout=False))) logging.debug("KMS V4 Response Bytes: \n%s\n" % justify(binascii.b2a_hex(str(response)))) return str(response)
def generateResponse(self, iv, encryptedResponse, requestData): response = self.ResponseV5() bodyLength = 2 + 2 + len(iv) + len(encryptedResponse) response['bodyLength1'] = bodyLength response['bodyLength2'] = bodyLength response['versionMinor'] = requestData['versionMinor'] response['versionMajor'] = requestData['versionMajor'] response['salt'] = iv response['encrypted'] = bytes(encryptedResponse) response['padding'] = bytearray(self.getPadding(bodyLength)).decode('latin-1').encode('latin-1') shell_message(nshell = 16) response = byterize(response) logger.info("KMS V%d Response: \n%s\n" % (self.ver, justify(response.dump(print_to_stdout = False)))) logger.info("KMS V%d Structure Bytes: \n%s\n" % (self.ver, justify(binascii.b2a_hex(str(response).encode('latin-1')).decode('utf-8')))) return str(response)
def generateRequest(self, requestBase): hash = str(self.generateHash(bytearray(str(requestBase)))) bodyLength = len(requestBase) + len(hash) request = kmsRequestV4.RequestV4() request['bodyLength1'] = bodyLength request['bodyLength2'] = bodyLength request['request'] = requestBase request['hash'] = hash request['padding'] = self.getResponsePadding(bodyLength) shell_message(nshell = 10) logging.debug("Request V4 Data: %s" % justify(request.dump(print_to_stdout = False))) logging.debug("Request V4: %s" % justify(binascii.b2a_hex(str(request)))) return request
def generateResponse(self, responseBuffer, thehash): bodyLength = len(responseBuffer) + len(thehash) response = self.ResponseV4() response['response'] = responseBuffer response['hash'] = thehash.decode('latin-1') #*2to3* response['padding'] = self.getResponsePadding(bodyLength).decode( 'latin-1') #*2to3* ## Debug stuff. shell_message(nshell=16) response = byterize(response) logging.debug("KMS V4 Response: \n%s\n" % justify(response.dump(print_to_stdout=False))) logging.debug("KMS V4 Response Bytes: \n%s\n" % justify( binascii.b2a_hex( str(response).encode('latin-1')).decode('utf-8'))) #*2to3* return str(response)
def generateRequest(self, requestBase): thehash = self.generateHash(bytearray(str(requestBase).encode('latin-1'))) #*2to3* bodyLength = len(requestBase) + len(thehash) request = kmsRequestV4.RequestV4() request['bodyLength1'] = bodyLength request['bodyLength2'] = bodyLength request['request'] = requestBase request['hash'] = thehash.decode('latin-1') #*2to3* request['padding'] = self.getResponsePadding(bodyLength).decode('latin-1') #*2to3* ## Debug stuff. shell_message(nshell = 10) request = byterize(request) logging.debug("Request V4 Data: \n%s\n" % justify(request.dump(print_to_stdout = False))) logging.debug("Request V4: \n%s\n" % justify(binascii.b2a_hex(str(request).encode('latin-1')).decode('utf-8'))) #*2to3* return request
def generateRequest(self, requestBase): hash = str(self.generateHash(bytearray(str(requestBase)))) request = self.RequestV4() bodyLength = len(requestBase) + len(hash) request['bodyLength1'] = bodyLength request['bodyLength2'] = bodyLength request['request'] = requestBase request['hash'] = hash request['padding'] = bytearray(self.getPadding(bodyLength)) ## Debug stuff. shell_message(nshell=10) logger.debug("Request V4 Data: \n%s\n" % justify(request.dump(print_to_stdout=False))) logger.debug("Request V4: \n%s\n" % justify(binascii.b2a_hex(str(request)))) return request
def generateResponse(self): response = MSRPCBindAck() request = self.requestData bind = MSRPCBind(request['pduData']) response['ver_major'] = request['ver_major'] response['ver_minor'] = request['ver_minor'] response['type'] = self.packetType['bindAck'] response['flags'] = self.packetFlags['firstFrag'] | self.packetFlags['lastFrag'] | self.packetFlags['multiplex'] response['representation'] = request['representation'] response['frag_len'] = 36 + bind['ctx_num'] * 24 response['auth_len'] = request['auth_len'] response['call_id'] = request['call_id'] response['max_tfrag'] = bind['max_tfrag'] response['max_rfrag'] = bind['max_rfrag'] response['assoc_group'] = 0x1063bf3f port = str(self.config['port']) response['SecondaryAddrLen'] = len(port) + 1 response['SecondaryAddr'] = port pad = (4 - ((response["SecondaryAddrLen"] + MSRPCBindAck._SIZE) % 4)) % 4 response['Pad'] = '\0' * pad response['ctx_num'] = bind['ctx_num'] preparedResponses = {} preparedResponses[uuidNDR32] = CtxItemResult(0, 0, uuidNDR32, 2) preparedResponses[uuidNDR64] = CtxItemResult(2, 2, uuidEmpty, 0) preparedResponses[uuidTime] = CtxItemResult(3, 3, uuidEmpty, 0) response['ctx_items'] = '' for i in range (0, bind['ctx_num']): ts_uuid = bind['ctx_items'][i].ts() resp = preparedResponses[ts_uuid] response['ctx_items'] += str(resp) shell_message(nshell = 4) response = byterize(response) logging.debug("RPC Bind Response: \n%s\n" % justify(response.dump(print_to_stdout = False))) logging.debug("RPC Bind Response Bytes: \n%s\n" % justify(binascii.b2a_hex(str(response).encode('latin-1')).decode('utf-8'))) #*2to3* return response
def generateRequest(self): firstCtxItem = CtxItem() firstCtxItem['ContextID'] = 0 firstCtxItem['TransItems'] = 1 firstCtxItem['Pad'] = 0 firstCtxItem['AbstractSyntaxUUID'] = uuid.UUID('51c82175-844e-4750-b0d8-ec255555bc06').bytes_le firstCtxItem['AbstractSyntaxVer'] = 1 firstCtxItem['TransferSyntaxUUID'] = uuidNDR32.bytes_le firstCtxItem['TransferSyntaxVer'] = 2 secondCtxItem = CtxItem() secondCtxItem['ContextID'] = 1 secondCtxItem['TransItems'] = 1 secondCtxItem['Pad'] = 0 secondCtxItem['AbstractSyntaxUUID'] = uuid.UUID('51c82175-844e-4750-b0d8-ec255555bc06').bytes_le secondCtxItem['AbstractSyntaxVer'] = 1 secondCtxItem['TransferSyntaxUUID'] = uuidTime.bytes_le secondCtxItem['TransferSyntaxVer'] = 1 bind = MSRPCBind() bind['max_tfrag'] = 5840 bind['max_rfrag'] = 5840 bind['assoc_group'] = 0 bind['ctx_num'] = 2 bind['ctx_items'] = str(bind.CtxItemArray(str(firstCtxItem) + str(secondCtxItem))) #*2to3* request = MSRPCHeader() request['ver_major'] = 5 request['ver_minor'] = 0 request['type'] = self.packetType['bindReq'] request['flags'] = self.packetFlags['firstFrag'] | self.packetFlags['lastFrag'] | self.packetFlags['multiplex'] request['call_id'] = self.config['call_id'] request['pduData'] = str(bind) shell_message(nshell = 0) bind = byterize(bind) request = byterize(request) logging.debug("RPC Bind Request: \n%s\n%s\n" % (justify(request.dump(print_to_stdout = False)), justify(MSRPCBind(request['pduData']).dump(print_to_stdout = False)))) logging.debug("RPC Bind Request Bytes: \n%s\n" % justify(binascii.b2a_hex(str(request).encode('latin-1')).decode('utf-8'))) #*2to3* return request
def generateRequest(self, requestBase): thehash = self.generateHash( bytearray(str(requestBase).encode('latin-1'))) request = kmsRequestV4.RequestV4() bodyLength = len(requestBase) + len(thehash) request['bodyLength1'] = bodyLength request['bodyLength2'] = bodyLength request['request'] = requestBase request['hash'] = thehash.decode('latin-1') request['padding'] = bytearray( self.getPadding(bodyLength)).decode('latin-1') ## Debug stuff. shell_message(nshell=10) request = byterize(request) logging.debug("Request V4 Data: \n%s\n" % justify(request.dump(print_to_stdout=False))) logging.debug("Request V4: \n%s\n" % justify( binascii.b2a_hex(str(request).encode('latin-1')).decode('utf-8'))) return request
def createKmsRequestBase(): requestDict = kmsBase.kmsRequestStruct() requestDict['versionMinor'] = config['KMSProtocolMinorVersion'] requestDict['versionMajor'] = config['KMSProtocolMajorVersion'] requestDict['isClientVm'] = 0 requestDict['licenseStatus'] = config['KMSClientLicenseStatus'] requestDict['graceTime'] = 43200 requestDict['applicationId'] = UUID(uuid.UUID(config['KMSClientAppID']).bytes_le) requestDict['skuId'] = UUID(uuid.UUID(config['KMSClientSkuID']).bytes_le) requestDict['kmsCountedId'] = UUID(uuid.UUID(config['KMSClientKMSCountedID']).bytes_le) requestDict['clientMachineId'] = UUID(uuid.UUID(config['cmid']).bytes_le if (config['cmid'] is not None) else uuid.uuid4().bytes_le) requestDict['previousClientMachineId'] = '\0' * 16 #requestDict['clientMachineId'] # I'm pretty sure this is supposed to be a null UUID. requestDict['requiredClientCount'] = config['RequiredClientCount'] requestDict['requestTime'] = filetimes.dt_to_filetime(datetime.datetime.utcnow()) requestDict['machineName'] = (config['machineName'] if (config['machineName'] is not None) else ''.join(random.choice(string.letters + string.digits) for i in range(random.randint(2,63)))).encode('utf-16le') requestDict['mnPad'] = '\0'.encode('utf-16le') * (63 - len(requestDict['machineName'].decode('utf-16le'))) # Debug Stuff shell_message(nshell = 9) logging.debug("Request Base Dictionary: \n%s\n" % justify(requestDict.dump(print_to_stdout = False))) return requestDict
sys.exit() else: raise if bindResponse == '' or not bindResponse: logging.error("No data received ! Exiting...") sys.exit() packetType = MSRPCHeader(bindResponse)['type'] if packetType == rpcBase.packetType['bindAck']: logging.info("RPC bind acknowledged.") shell_message(nshell = 8) kmsRequest = createKmsRequest() requester = rpcRequest.handler(kmsRequest, config) s.send(str(requester.generateRequest())) shell_message(nshell = [-1, 12]) response = s.recv(1024) logging.debug("Response: \n%s\n" % justify(binascii.b2a_hex(response))) shell_message(nshell = [-4, 20]) parsed = MSRPCRespHeader(response) kmsData = readKmsResponse(parsed['pduData'], kmsRequest, config) kmsResp = kmsData['response'] try: hwid = kmsData['hwid'] except: hwid = None logging.info("KMS Host ePID: %s" % kmsResp['kmsEpid'].decode('utf-16le').encode('utf-8')) if hwid is not None: logging.info("KMS Host HWID: %s" % binascii.b2a_hex(hwid).upper()) logging.info("KMS Host Current Client Count: %s" % kmsResp['currentClientCount']) logging.info("KMS VL Activation Interval: %s" % kmsResp['vLActivationInterval'])
def main(): parser = argparse.ArgumentParser() parser.add_argument("ip", action="store", help='The IP address or hostname of the KMS server.', type=str) parser.add_argument("port", nargs="?", action="store", default=1688, help='The port the KMS service is listening on. The default is \"1688\".', type=int) parser.add_argument("-m", "--mode", dest="mode", choices=["WindowsVista","Windows7","Windows8","Windows81","Windows10","Office2010","Office2013","Office2016"], default="Windows7", help='Use this flag to manually specify a Microsoft product for testing the server. The default is \"Windows81\".', type=str) parser.add_argument("-c", "--cmid", dest="cmid", default=None, help='Use this flag to manually specify a CMID to use. If no CMID is specified, a random CMID will be generated.', type=str) parser.add_argument("-n", "--name", dest="machineName", default=None, help='Use this flag to manually specify an ASCII machineName to use. If no machineName is specified,\ a random machineName will be generated.', type=str) parser.add_argument("-v", "--loglevel", dest="loglevel", action="store", default="ERROR", choices=["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"], help='Use this flag to set a Loglevel. The default is \"ERROR\".', type=str) parser.add_argument("-f", "--logfile", dest="logfile", action="store", default=os.path.dirname(os.path.abspath( __file__ )) + "/py3kms_client.log", help='Use this flag to set an output Logfile. The default is \"pykms_client.log\".', type=str) config.update(vars(parser.parse_args())) logging.basicConfig(level=config['loglevel'], format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename=config['logfile'], filemode='w') checkConfig() config['call_id'] = 1 updateConfig() s = socket.socket() logging.info("Connecting to %s on port %d..." % (config['ip'], config['port'])) s.connect((config['ip'], config['port'])) logging.info("Connection successful !") binder = rpcBind.handler(None, config) RPC_Bind = str(binder.generateRequest()).encode('latin-1') #*2to3* logging.info("Sending RPC bind request...") shell_message(nshell = [-1, 1]) s.send(RPC_Bind) try: shell_message(nshell = [-4, 7]) bindResponse = s.recv(1024) except socket.error as e: #*2to3* if e[0] == 104: logging.error("Connection reset by peer. Exiting...") sys.exit() else: raise if bindResponse == '' or not bindResponse: logging.error("No data received ! Exiting...") sys.exit() packetType = MSRPCHeader(bindResponse)['type'] if packetType == rpcBase.packetType['bindAck']: logging.info("RPC bind acknowledged.") shell_message(nshell = 8) kmsRequest = createKmsRequest() requester = rpcRequest.handler(kmsRequest, config) s.send(str(requester.generateRequest()).encode('latin-1')) #*2to3* shell_message(nshell = [-1, 12]) response = s.recv(1024) logging.debug("Response: \n%s\n" % justify(binascii.b2a_hex(response).decode('latin-1'))) #*2to3* shell_message(nshell = [-4, 20]) parsed = MSRPCRespHeader(response) kmsData = readKmsResponse(parsed['pduData'], kmsRequest, config) kmsResp = kmsData['response'] try: hwid = kmsData['hwid'] except: hwid = None logging.info("KMS Host ePID: %s" % kmsResp['kmsEpid'].encode('utf-8').decode('utf-16le')) #*2to3* if hwid is not None: logging.info("KMS Host HWID: %s" % binascii.b2a_hex(hwid.encode('latin-1')).upper().decode('utf-8')) #*2to3* logging.info("KMS Host Current Client Count: %s" % kmsResp['currentClientCount']) logging.info("KMS VL Activation Interval: %s" % kmsResp['vLActivationInterval']) logging.info("KMS VL Renewal Interval: %s" % kmsResp['vLRenewalInterval']) shell_message(nshell = 21) elif packetType == rpcBase.packetType['bindNak']: logging.info(justify(MSRPCBindNak(bindResponse).dump(print_to_stdout = False))) sys.exit() else: logging.critical("Something went wrong.") sys.exit()
def serverLogic(self, kmsRequest): if self.config['sqlite'] and self.config['dbSupport']: self.dbName = 'clients.db' if not os.path.isfile(self.dbName): # Initialize the database. con = None try: con = sqlite3.connect(self.dbName) cur = con.cursor() cur.execute( "CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, \ applicationId TEXT, skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)" ) except sqlite3.Error as e: #*2to3* logging.error("%s:" % e.args[0]) sys.exit(1) finally: if con: con.commit() con.close() shell_message(nshell=15) kmsRequest = byterize(kmsRequest) logging.debug("KMS Request Bytes: \n%s\n" % justify( binascii.b2a_hex( str(kmsRequest).encode('latin-1')).decode('utf-8'))) #*2to3* logging.debug("KMS Request: \n%s\n" % justify(kmsRequest.dump(print_to_stdout=False))) clientMachineId = kmsRequest['clientMachineId'].get() applicationId = kmsRequest['applicationId'].get() skuId = kmsRequest['skuId'].get() requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime']) # Try and localize the request time, if pytz is available try: import timezones from pytz import utc local_dt = utc.localize(requestDatetime).astimezone( timezones.localtz()) except ImportError: local_dt = requestDatetime infoDict = { "machineName": kmsRequest.getMachineName(), "clientMachineId": str(clientMachineId), "appId": self.appIds.get(applicationId, str(applicationId)), "skuId": self.skuIds.get(skuId, str(skuId)), "licenseStatus": kmsRequest.getLicenseStatus(), "requestTime": int(time.time()), "kmsEpid": None } #print infoDict logging.info("Machine Name: %s" % infoDict["machineName"]) logging.info("Client Machine ID: %s" % infoDict["clientMachineId"]) logging.info("Application ID: %s" % infoDict["appId"]) logging.info("SKU ID: %s" % infoDict["skuId"]) logging.info("License Status: %s" % infoDict["licenseStatus"]) logging.info("Request Time: %s" % local_dt.strftime('%Y-%m-%d %H:%M:%S %Z (UTC%z)')) if self.config['sqlite'] and self.config['dbSupport']: con = None try: con = sqlite3.connect(self.dbName) cur = con.cursor() cur.execute( "SELECT * FROM clients WHERE clientMachineId=:clientMachineId;", infoDict) try: data = cur.fetchone() if not data: #print "Inserting row..." cur.execute( "INSERT INTO clients (clientMachineId, machineName, \ applicationId, skuId, licenseStatus, lastRequestTime, requestCount) VALUES (:clientMachineId, :machineName, :appId, \ :skuId, :licenseStatus, :requestTime, 1);", infoDict) else: #print "Data:", data if data[1] != infoDict["machineName"]: cur.execute( "UPDATE clients SET machineName=:machineName WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[2] != infoDict["appId"]: cur.execute( "UPDATE clients SET applicationId=:appId WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[3] != infoDict["skuId"]: cur.execute( "UPDATE clients SET skuId=:skuId WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[4] != infoDict["licenseStatus"]: cur.execute( "UPDATE clients SET licenseStatus=:licenseStatus WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[5] != infoDict["requestTime"]: cur.execute( "UPDATE clients SET lastRequestTime=:requestTime WHERE \ clientMachineId=:clientMachineId;", infoDict) # Increment requestCount cur.execute( "UPDATE clients SET requestCount=requestCount+1 WHERE \ clientMachineId=:clientMachineId;", infoDict) except sqlite3.Error as e: #*2to3* logging.error("%s:" % e.args[0]) except sqlite3.Error as e: #*2to3* logging.error("%s:" % e.args[0]) sys.exit(1) finally: if con: con.commit() con.close() return self.createKmsResponse(kmsRequest)
def main(): parser = argparse.ArgumentParser() parser.add_argument("ip", action="store", help='The IP address or hostname of the KMS server.', type=str) parser.add_argument( "port", nargs="?", action="store", default=1688, help= 'The port the KMS service is listening on. The default is \"1688\".', type=int) parser.add_argument( "-m", "--mode", dest="mode", choices=[ "WindowsVista", "Windows7", "Windows8", "Windows81", "Windows10", "Office2010", "Office2013", "Office2016" ], default="Windows7", help= 'Use this flag to manually specify a Microsoft product for testing the server. The default is \"Windows81\".', type=str) parser.add_argument( "-c", "--cmid", dest="cmid", default=None, help= 'Use this flag to manually specify a CMID to use. If no CMID is specified, a random CMID will be generated.', type=str) parser.add_argument( "-n", "--name", dest="machineName", default=None, help= 'Use this flag to manually specify an ASCII machineName to use. If no machineName is specified,\ a random machineName will be generated.', type=str) parser.add_argument( "-v", "--loglevel", dest="loglevel", action="store", default="ERROR", choices=["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"], help='Use this flag to set a Loglevel. The default is \"ERROR\".', type=str) parser.add_argument( "-f", "--logfile", dest="logfile", action="store", default=os.path.dirname(os.path.abspath(__file__)) + "/py3kms_client.log", help= 'Use this flag to set an output Logfile. The default is \"pykms_client.log\".', type=str) config.update(vars(parser.parse_args())) logging.basicConfig(level=config['loglevel'], format='%(asctime)s %(levelname)-8s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filename=config['logfile'], filemode='w') checkConfig() config['call_id'] = 1 updateConfig() s = socket.socket() logging.info("Connecting to %s on port %d..." % (config['ip'], config['port'])) s.connect((config['ip'], config['port'])) logging.info("Connection successful !") binder = rpcBind.handler(None, config) RPC_Bind = str(binder.generateRequest()).encode('latin-1') #*2to3* logging.info("Sending RPC bind request...") shell_message(nshell=[-1, 1]) s.send(RPC_Bind) try: shell_message(nshell=[-4, 7]) bindResponse = s.recv(1024) except socket.error as e: #*2to3* if e[0] == 104: logging.error("Connection reset by peer. Exiting...") sys.exit() else: raise if bindResponse == '' or not bindResponse: logging.error("No data received ! Exiting...") sys.exit() packetType = MSRPCHeader(bindResponse)['type'] if packetType == rpcBase.packetType['bindAck']: logging.info("RPC bind acknowledged.") shell_message(nshell=8) kmsRequest = createKmsRequest() requester = rpcRequest.handler(kmsRequest, config) s.send(str(requester.generateRequest()).encode('latin-1')) #*2to3* shell_message(nshell=[-1, 12]) response = s.recv(1024) logging.debug( "Response: \n%s\n" % justify(binascii.b2a_hex(response).decode('latin-1'))) #*2to3* shell_message(nshell=[-4, 20]) parsed = MSRPCRespHeader(response) kmsData = readKmsResponse(parsed['pduData'], kmsRequest, config) kmsResp = kmsData['response'] try: hwid = kmsData['hwid'] except: hwid = None logging.info( "KMS Host ePID: %s" % kmsResp['kmsEpid'].encode('utf-8').decode('utf-16le')) #*2to3* if hwid is not None: logging.info("KMS Host HWID: %s" % binascii.b2a_hex( hwid.encode('latin-1')).upper().decode('utf-8')) #*2to3* logging.info("KMS Host Current Client Count: %s" % kmsResp['currentClientCount']) logging.info("KMS VL Activation Interval: %s" % kmsResp['vLActivationInterval']) logging.info("KMS VL Renewal Interval: %s" % kmsResp['vLRenewalInterval']) shell_message(nshell=21) elif packetType == rpcBase.packetType['bindNak']: logging.info( justify(MSRPCBindNak(bindResponse).dump(print_to_stdout=False))) sys.exit() else: logging.critical("Something went wrong.") sys.exit()
try: con = sqlite3.connect(self.dbName) cur = con.cursor() cur.execute("CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, applicationId TEXT, skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)") except sqlite3.Error, e: logging.error("%s:" % e.args[0]) sys.exit(1) finally: if con: con.commit() con.close() shell_message(nshell = 15) logging.debug("KMS Request Bytes: \n%s\n" % justify(binascii.b2a_hex(str(kmsRequest)))) logging.debug("KMS Request: \n%s\n" % justify(kmsRequest.dump(print_to_stdout = False))) clientMachineId = kmsRequest['clientMachineId'].get() global applicationId applicationId = kmsRequest['applicationId'].get() skuId = kmsRequest['skuId'].get() requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime']) # Try and localize the request time, if pytz is available try: import timezones from pytz import utc local_dt = utc.localize(requestDatetime).astimezone(timezones.localtz()) except ImportError: local_dt = requestDatetime
def serverLogic(self, kmsRequest): if self.config['sqlite'] and self.config['dbSupport']: self.dbName = 'clients.db' if not os.path.isfile(self.dbName): # Initialize the database. con = None try: con = sqlite3.connect(self.dbName) cur = con.cursor() cur.execute("CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, \ applicationId TEXT, skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)") except sqlite3.Error as e: #*2to3* logging.error("%s:" % e.args[0]) sys.exit(1) finally: if con: con.commit() con.close() shell_message(nshell = 15) kmsRequest = byterize(kmsRequest) logging.debug("KMS Request Bytes: \n%s\n" % justify(binascii.b2a_hex(str(kmsRequest).encode('latin-1')).decode('utf-8'))) #*2to3* logging.debug("KMS Request: \n%s\n" % justify(kmsRequest.dump(print_to_stdout = False))) clientMachineId = kmsRequest['clientMachineId'].get() applicationId = kmsRequest['applicationId'].get() skuId = kmsRequest['skuId'].get() requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime']) # Try and localize the request time, if pytz is available try: import timezones from pytz import utc local_dt = utc.localize(requestDatetime).astimezone(timezones.localtz()) except ImportError: local_dt = requestDatetime infoDict = { "machineName" : kmsRequest.getMachineName(), "clientMachineId" : str(clientMachineId), "appId" : self.appIds.get(applicationId, str(applicationId)), "skuId" : self.skuIds.get(skuId, str(skuId)), "licenseStatus" : kmsRequest.getLicenseStatus(), "requestTime" : int(time.time()), "kmsEpid" : None } #print infoDict logging.info("Machine Name: %s" % infoDict["machineName"]) logging.info("Client Machine ID: %s" % infoDict["clientMachineId"]) logging.info("Application ID: %s" % infoDict["appId"]) logging.info("SKU ID: %s" % infoDict["skuId"]) logging.info("License Status: %s" % infoDict["licenseStatus"]) logging.info("Request Time: %s" % local_dt.strftime('%Y-%m-%d %H:%M:%S %Z (UTC%z)')) if self.config['sqlite'] and self.config['dbSupport']: con = None try: con = sqlite3.connect(self.dbName) cur = con.cursor() cur.execute("SELECT * FROM clients WHERE clientMachineId=:clientMachineId;", infoDict) try: data = cur.fetchone() if not data: #print "Inserting row..." cur.execute("INSERT INTO clients (clientMachineId, machineName, \ applicationId, skuId, licenseStatus, lastRequestTime, requestCount) VALUES (:clientMachineId, :machineName, :appId, \ :skuId, :licenseStatus, :requestTime, 1);", infoDict) else: #print "Data:", data if data[1] != infoDict["machineName"]: cur.execute("UPDATE clients SET machineName=:machineName WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[2] != infoDict["appId"]: cur.execute("UPDATE clients SET applicationId=:appId WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[3] != infoDict["skuId"]: cur.execute("UPDATE clients SET skuId=:skuId WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[4] != infoDict["licenseStatus"]: cur.execute("UPDATE clients SET licenseStatus=:licenseStatus WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[5] != infoDict["requestTime"]: cur.execute("UPDATE clients SET lastRequestTime=:requestTime WHERE \ clientMachineId=:clientMachineId;", infoDict) # Increment requestCount cur.execute("UPDATE clients SET requestCount=requestCount+1 WHERE \ clientMachineId=:clientMachineId;", infoDict) except sqlite3.Error as e: #*2to3* logging.error("%s:" % e.args[0]) except sqlite3.Error as e: #*2to3* logging.error("%s:" % e.args[0]) sys.exit(1) finally: if con: con.commit() con.close() return self.createKmsResponse(kmsRequest)
def serverLogic(self, kmsRequest): if self.config['sqlite'] and self.config['dbSupport']: self.dbName = 'clients.db' if not os.path.isfile(self.dbName): # Initialize the database. con = None try: con = sqlite3.connect(self.dbName) cur = con.cursor() cur.execute( "CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, applicationId TEXT, \ skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)" ) except sqlite3.Error as e: logger.error("Error %s:" % e.args[0]) sys.exit(1) finally: if con: con.commit() con.close() shell_message(nshell=15) kmsRequest = byterize(kmsRequest) logger.debug("KMS Request Bytes: \n%s\n" % justify( binascii.b2a_hex( str(kmsRequest).encode('latin-1')).decode('utf-8'))) logger.debug("KMS Request: \n%s\n" % justify(kmsRequest.dump(print_to_stdout=False))) clientMachineId = kmsRequest['clientMachineId'].get() applicationId = kmsRequest['applicationId'].get() skuId = kmsRequest['skuId'].get() requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime']) # Localize the request time, if module "tzlocal" is available. try: from tzlocal import get_localzone from pytz.exceptions import UnknownTimeZoneError try: tz = get_localzone() local_dt = tz.localize(requestDatetime) except UnknownTimeZoneError: logger.warning( 'Unknown time zone ! Request time not localized.') local_dt = requestDatetime except ImportError: logger.warning( 'Module "tzlocal" not available ! Request time not localized.') local_dt = requestDatetime # Get SkuId, AppId and client threshold. appName, skuName = applicationId, skuId kmsdb = kmsDB2Dict() appitems = kmsdb[2] for appitem in appitems: kmsitems = appitem['KmsItems'] for kmsitem in kmsitems: # Activation threshold. try: count = int(kmsitem['NCountPolicy']) except KeyError: count = 25 if self.config["CurrentClientCount"] <= count: currentClientCount = count + 1 else: currentClientCount = self.config["CurrentClientCount"] skuitems = kmsitem['SkuItems'] for skuitem in skuitems: try: if uuid.UUID(skuitem['Id']) == skuId: skuName = skuitem['DisplayName'] break except IndexError: pass if uuid.UUID(appitem['Id']) == applicationId: appName = appitem['DisplayName'] infoDict = { "machineName": kmsRequest.getMachineName(), "clientMachineId": str(clientMachineId), "appId": appName, "skuId": skuName, "licenseStatus": kmsRequest.getLicenseStatus(), "requestTime": int(time.time()), "kmsEpid": None } #print infoDict logger.info("Machine Name: %s" % infoDict["machineName"]) logger.info("Client Machine ID: %s" % infoDict["clientMachineId"]) logger.info("Application ID: %s" % infoDict["appId"]) logger.info("SKU ID: %s" % infoDict["skuId"]) logger.info("License Status: %s" % infoDict["licenseStatus"]) logger.info("Request Time: %s" % local_dt.strftime('%Y-%m-%d %H:%M:%S %Z (UTC%z)')) if self.config['sqlite'] and self.config['dbSupport']: con = None try: con = sqlite3.connect(self.dbName) cur = con.cursor() cur.execute( "SELECT * FROM clients WHERE clientMachineId=:clientMachineId;", infoDict) try: data = cur.fetchone() if not data: #print "Inserting row..." cur.execute( "INSERT INTO clients (clientMachineId, machineName, applicationId, \ skuId, licenseStatus, lastRequestTime, requestCount) VALUES (:clientMachineId, :machineName, :appId, :skuId, :licenseStatus, :requestTime, 1);", infoDict) else: #print "Data:", data if data[1] != infoDict["machineName"]: cur.execute( "UPDATE clients SET machineName=:machineName WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[2] != infoDict["appId"]: cur.execute( "UPDATE clients SET applicationId=:appId WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[3] != infoDict["skuId"]: cur.execute( "UPDATE clients SET skuId=:skuId WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[4] != infoDict["licenseStatus"]: cur.execute( "UPDATE clients SET licenseStatus=:licenseStatus WHERE \ clientMachineId=:clientMachineId;", infoDict) if data[5] != infoDict["requestTime"]: cur.execute( "UPDATE clients SET lastRequestTime=:requestTime WHERE \ clientMachineId=:clientMachineId;", infoDict) # Increment requestCount cur.execute( "UPDATE clients SET requestCount=requestCount+1 WHERE \ clientMachineId=:clientMachineId;", infoDict) except sqlite3.Error as e: logger.error("Error %s:" % e.args[0]) except sqlite3.Error as e: logger.error("Error %s:" % e.args[0]) sys.exit(1) finally: if con: con.commit() con.close() return self.createKmsResponse(kmsRequest, currentClientCount)
cur.execute( "CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, applicationId TEXT, skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)" ) except sqlite3.Error, e: logging.error("%s:" % e.args[0]) sys.exit(1) finally: if con: con.commit() con.close() shell_message(nshell=15) logging.debug("KMS Request Bytes: \n%s\n" % justify(binascii.b2a_hex(str(kmsRequest)))) logging.debug("KMS Request: \n%s\n" % justify(kmsRequest.dump(print_to_stdout=False))) clientMachineId = kmsRequest['clientMachineId'].get() global applicationId applicationId = kmsRequest['applicationId'].get() skuId = kmsRequest['skuId'].get() requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime']) # Try and localize the request time, if pytz is available try: import timezones from pytz import utc local_dt = utc.localize(requestDatetime).astimezone( timezones.localtz())
con = sqlite3.connect(self.dbName) cur = con.cursor() cur.execute("CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, applicationId TEXT, \ skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)") except sqlite3.Error, e: logging.error("Error %s:" % e.args[0]) sys.exit(1) finally: if con: con.commit() con.close() shell_message(nshell = 15) logging.debug("KMS Request Bytes: \n%s\n" % justify(binascii.b2a_hex(str(kmsRequest)))) logging.debug("KMS Request: \n%s\n" % justify(kmsRequest.dump(print_to_stdout = False))) clientMachineId = kmsRequest['clientMachineId'].get() applicationId = kmsRequest['applicationId'].get() skuId = kmsRequest['skuId'].get() requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime']) # Localize the request time, if module "tzlocal" is available. try: from tzlocal import get_localzone from pytz.exceptions import UnknownTimeZoneError try: tz = get_localzone() local_dt = tz.localize(requestDatetime) except UnknownTimeZoneError: