def createKmsRequestBase(): requestDict = kmsBase.kmsRequestStruct() requestDict['versionMinor'] = clt_config['KMSProtocolMinorVersion'] requestDict['versionMajor'] = clt_config['KMSProtocolMajorVersion'] requestDict['isClientVm'] = 0 requestDict['licenseStatus'] = clt_config['KMSClientLicenseStatus'] requestDict['graceTime'] = 43200 requestDict['applicationId'] = UUID( uuid.UUID(clt_config['KMSClientAppID']).bytes_le) requestDict['skuId'] = UUID( uuid.UUID(clt_config['KMSClientSkuID']).bytes_le) requestDict['kmsCountedId'] = UUID( uuid.UUID(clt_config['KMSClientKMSCountedID']).bytes_le) requestDict['clientMachineId'] = UUID( uuid.UUID(clt_config['cmid']).bytes_le if ( clt_config['cmid'] is not None) else uuid.uuid4().bytes_le) requestDict[ 'previousClientMachineId'] = '\0' * 16 # I'm pretty sure this is supposed to be a null UUID. requestDict['requiredClientCount'] = clt_config['RequiredClientCount'] requestDict['requestTime'] = dt_to_filetime(datetime.datetime.utcnow()) requestDict['machineName'] = (clt_config['machineName'] if ( clt_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 ShellMessage.Process(9).run() requestDict = byterize(requestDict) loggerclt.debug("Request Base Dictionary: \n%s\n" % justify(requestDict.dump(print_to_stdout=False))) return requestDict
def parseRequest(self): request = MSRPCRequestHeader(self.data) ShellMessage.Process(14).run() 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))) return request
def parseRequest(self): request = MSRPCHeader(self.data) ShellMessage.Process(3).run() 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)), justify( MSRPCBind(request['pduData']).dump(print_to_stdout=False)))) return request
def handle(self): while True: # 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.") break else: raise if self.data == '' or not self.data: loggersrv.warning("No data received !") break packetType = MSRPCHeader(self.data)['type'] if packetType == rpcBase.packetType['bindReq']: loggersrv.info("RPC bind request received.") ShellMessage.Process([-2, 2]).run() handler = pykms_RpcBind.handler(self.data, srv_config) elif packetType == rpcBase.packetType['request']: loggersrv.info("Received activation request.") ShellMessage.Process([-2, 13]).run() handler = pykms_RpcRequest.handler(self.data, srv_config) else: loggersrv.error("Invalid RPC request type ", packetType) break res = enco(str(handler.populate()), 'latin-1') self.request.send(res) if packetType == rpcBase.packetType['bindReq']: loggersrv.info("RPC bind acknowledged.") ShellMessage.Process([-3, 5, 6]).run() elif packetType == rpcBase.packetType['request']: loggersrv.info("Responded to activation request.") ShellMessage.Process([-3, 18, 19]).run() break
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))) 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.srv_config['call_id'] request['pduData'] = str(bind) ShellMessage.Process(0).run() bind = byterize(bind) request = byterize(request) loggersrv.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)))) loggersrv.debug("RPC Bind Request Bytes: \n%s\n" % justify( deco(binascii.b2a_hex(enco(str(request), 'latin-1')), 'utf-8'))) return request
def generateResponse(self, responseBuffer, thehash): response = self.ResponseV4() bodyLength = len(responseBuffer) + len(thehash) response['bodyLength1'] = bodyLength response['bodyLength2'] = bodyLength response['response'] = responseBuffer response['hash'] = thehash response['padding'] = bytes(bytearray(self.getPadding(bodyLength))) ## Debug stuff. ShellMessage.Process(16).run() 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'))) return str(response)
def generateResponse(self, request): response = MSRPCBindAck() 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.srv_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) ShellMessage.Process(4).run() 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'))) return response
def generateRequest(self, requestBase): thehash = self.generateHash(bytearray(enco(str(requestBase), 'latin-1'))) request = kmsRequestV4.RequestV4() bodyLength = len(requestBase) + len(thehash) request['bodyLength1'] = bodyLength request['bodyLength2'] = bodyLength request['request'] = requestBase request['hash'] = thehash request['padding'] = bytes(bytearray(self.getPadding(bodyLength))) ## Debug stuff. ShellMessage.Process(10).run() 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'))) return request
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.srv_config['call_id'] request['alloc_hint'] = len(self.data) request['pduData'] = str(self.data) ShellMessage.Process(11).run() 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'))) 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'] = bytes(dsalt) decrypted['request'] = requestBase padded = aes.append_PKCS7_padding(enco(str(decrypted), '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(bytearray(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 ShellMessage.Process(10).run() 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')))) return request
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(bytearray(encryptedResponse)) response['padding'] = bytes(bytearray(self.getPadding(bodyLength))) ShellMessage.Process(16).run() 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')))) return str(response)
def generateResponse(self, request): responseData = pykms_Base.generateKmsResponseData(request['pduData'], self.srv_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 ShellMessage.Process(17).run() 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'))) return response
def client_create(): loggerclt.info("Connecting to %s on port %d..." % (clt_config['ip'], clt_config['port'])) s = socket.create_connection((clt_config['ip'], clt_config['port'])) loggerclt.info("Connection successful !") 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() s.send(RPC_Bind) try: ShellMessage.Process([-4, 7]).run() bindResponse = s.recv(1024) 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() packetType = MSRPCHeader(bindResponse)['type'] if packetType == rpcBase.packetType['bindAck']: loggerclt.info("RPC bind acknowledged.") ShellMessage.Process(8).run() kmsRequest = createKmsRequest() requester = pykms_RpcRequest.handler(kmsRequest, clt_config) s.send(enco(str(requester.generateRequest()), 'latin-1')) ShellMessage.Process([-1, 12]).run() response = s.recv(1024) loggerclt.debug("Response: \n%s\n" % justify(deco(binascii.b2a_hex(response), 'latin-1'))) ShellMessage.Process([-4, 20]).run() parsed = MSRPCRespHeader(response) kmsData = readKmsResponse(parsed['pduData'], kmsRequest, clt_config) kmsResp = kmsData['response'] try: hwid = kmsData['hwid'] loggerclt.info( "KMS Host HWID: %s" % deco(binascii.b2a_hex(enco(hwid, 'latin-1')).upper(), 'utf-8')) except KeyError: pass loggerclt.info("KMS Host ePID: %s" % kmsResp['kmsEpid'].encode('utf-8').decode('utf-16le')) loggerclt.info("KMS Host Current Client Count: %s" % kmsResp['currentClientCount']) loggerclt.info("KMS VL Activation Interval: %s" % kmsResp['vLActivationInterval']) loggerclt.info("KMS VL Renewal Interval: %s" % kmsResp['vLRenewalInterval']) if clt_config['loglevel'] == 'MINI': loggerclt.mini("", extra={ 'host': socket.gethostname() + " [" + clt_config["ip"] + "]", 'status': "Activated", 'product': clt_config["mode"] }) ShellMessage.Process(21).run() elif packetType == rpcBase.packetType['bindNak']: loggerclt.info( justify(MSRPCBindNak(bindResponse).dump(print_to_stdout=False))) sys.exit() else: loggerclt.critical("Something went wrong.") sys.exit()
def serverLogic(self, kmsRequest): if self.srv_config['sqlite'] and self.srv_config['dbSupport']: self.dbName = sql_initialize() ShellMessage.Process(15).run() 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))) clientMachineId = kmsRequest['clientMachineId'].get() applicationId = kmsRequest['applicationId'].get() skuId = kmsRequest['skuId'].get() requestDatetime = 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: loggersrv.warning( 'Unknown time zone ! Request time not localized.') local_dt = requestDatetime except ImportError: loggersrv.warning( 'Module "tzlocal" not available ! Request time not localized.') local_dt = requestDatetime # Activation threshold. # https://docs.microsoft.com/en-us/windows/deployment/volume-activation/activate-windows-10-clients-vamt MinClients = kmsRequest['requiredClientCount'] RequiredClients = MinClients * 2 if self.srv_config["CurrentClientCount"] != None: if 0 < self.srv_config["CurrentClientCount"] < MinClients: # fixed to 6 (product server) or 26 (product desktop) currentClientCount = MinClients + 1 loggersrv.warning( "Not enough clients ! Fixed with %s, but activated client could be detected as not genuine !" % currentClientCount) elif MinClients <= self.srv_config[ "CurrentClientCount"] < RequiredClients: currentClientCount = self.srv_config["CurrentClientCount"] loggersrv.warning( "With count = %s, activated client could be detected as not genuine !" % currentClientCount) elif self.srv_config["CurrentClientCount"] >= RequiredClients: # fixed to 10 (product server) or 50 (product desktop) currentClientCount = RequiredClients if self.srv_config["CurrentClientCount"] > RequiredClients: loggersrv.warning("Too many clients ! Fixed with %s" % currentClientCount) else: # fixed to 10 (product server) or 50 (product desktop) currentClientCount = RequiredClients # Get a name for SkuId, AppId. kmsdb = kmsDB2Dict() appitems = kmsdb[2] for appitem in appitems: kmsitems = appitem['KmsItems'] for kmsitem in kmsitems: skuitems = kmsitem['SkuItems'] for skuitem in skuitems: try: if uuid.UUID(skuitem['Id']) == skuId: skuName = skuitem['DisplayName'] break except: skuName = skuId loggersrv.warning( "Can't find a name for this product !!") try: if uuid.UUID(appitem['Id']) == applicationId: appName = appitem['DisplayName'] except: appName = applicationId loggersrv.warning( "Can't find a name for this application group !!") infoDict = { "machineName": kmsRequest.getMachineName(), "clientMachineId": str(clientMachineId), "appId": appName, "skuId": skuName, "licenseStatus": kmsRequest.getLicenseStatus(), "requestTime": int(time.time()), "kmsEpid": None } loggersrv.info("Machine Name: %s" % infoDict["machineName"]) loggersrv.info("Client Machine ID: %s" % infoDict["clientMachineId"]) loggersrv.info("Application ID: %s" % infoDict["appId"]) loggersrv.info("SKU ID: %s" % infoDict["skuId"]) loggersrv.info("License Status: %s" % infoDict["licenseStatus"]) loggersrv.info("Request Time: %s" % local_dt.strftime('%Y-%m-%d %H:%M:%S %Z (UTC%z)')) if self.srv_config['loglevel'] == 'MINI': loggersrv.mini("", extra={ 'host': socket.gethostname() + " [" + self.srv_config["ip"] + "]", 'status': infoDict["licenseStatus"], 'product': infoDict["skuId"] }) if self.srv_config['sqlite'] and self.srv_config['dbSupport']: sql_update(self.dbName, infoDict) return self.createKmsResponse(kmsRequest, currentClientCount)