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): 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): 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 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 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 = MSRPCHeader(self.data) shell_message(nshell = 3) request = byterize(request) logging.debug("RPC Bind Request Bytes: \n%s\n" % justify(binascii.b2a_hex(self.data).decode('utf-8'))) 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 parseRequest(self): request = MSRPCRequestHeader(self.data) shell_message(nshell=14) request = byterize(request) logger.debug("RPC Message Request Bytes: \n%s\n" % justify(binascii.b2a_hex(self.data).decode('utf-8'))) logger.debug("RPC Message Request: \n%s\n" % justify(request.dump(print_to_stdout=False))) return request
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 parseRequest(self): request = MSRPCHeader(self.data) shell_message(nshell=3) request = byterize(request) logging.debug("RPC Bind Request Bytes: \n%s\n" % justify(binascii.b2a_hex(self.data).decode('utf-8'))) 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, 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 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'] = bytes(encryptedResponse) #*2to3* response['padding'] = self.getResponsePadding(bodyLength).decode('latin-1').encode('latin-1') #*2to3* shell_message(nshell = 16) response = byterize(response) 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).encode('latin-1')).decode('utf-8')))) #*2to3* return str(response)
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 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 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 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) request = byterize(request) logger.debug("RPC Message Request: \n%s\n" % justify(request.dump(print_to_stdout=False))) logger.debug("RPC Message Request Bytes: \n%s\n" % justify( binascii.b2a_hex(str(request).encode('latin-1')).decode('utf-8'))) 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.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 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)
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)