Beispiel #1
0
        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

                pretty_printer(num_text = 10, where = "clt")
                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
Beispiel #2
0
def server_create():
    # Create address list (when the current user indicates execution inside the Windows Sandbox,
    # then we wont allow port reuse - it is not supported).
    all_address = [(
                    srv_config['ip'], srv_config['port'],
                    (srv_config['backlog_main'] if 'backlog_main' in srv_config else srv_options['backlog']['def']),
                    (srv_config['reuse_main'] if 'reuse_main' in srv_config else False if getuser() == 'WDAGUtilityAccount' \
                     else srv_options['reuse']['def'])
                    )]
    log_address = "TCP server listening at %s on port %d" % (
        srv_config['ip'], srv_config['port'])

    if 'listen' in srv_config:
        for l, b, r in zip(srv_config['listen'], srv_config['backlog'],
                           srv_config['reuse']):
            r = (False if getuser() == 'WDAGUtilityAccount' else r)
            all_address.append(l + (b, ) + (r, ))
            log_address += justify("at %s on port %d" % (l[0], l[1]),
                                   indent=56)

    server = KeyServer(all_address,
                       kmsServerHandler,
                       want_dual=(srv_config['dual'] if 'dual' in srv_config
                                  else srv_options['dual']['def']))
    server.timeout = srv_config['timeoutidle']

    loggersrv.info(log_address)
    loggersrv.info("HWID: %s" %
                   deco(binascii.b2a_hex(srv_config['hwid']), 'utf-8').upper())

    return server
Beispiel #3
0
def readKmsResponseV4(data, request):
    response = kmsRequestV4.ResponseV4(data)
    hashed = kmsRequestV4(data, clt_config).generateHash(
        bytearray(enco(str(response['response']), 'latin-1')))
    if deco(hashed, 'latin-1') == response['hash']:
        loggerclt.info("Response Hash has expected value !")
    return response
Beispiel #4
0
    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

        pretty_printer(num_text=17, where="srv")
        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
Beispiel #5
0
def server_create():
    server = KeyServer((srv_config['ip'], srv_config['port']),
                       kmsServerHandler)
    server.timeout = srv_config['timeout']
    loggersrv.info("TCP server listening at %s on port %d." %
                   (srv_config['ip'], srv_config['port']))
    loggersrv.info("HWID: %s" %
                   deco(binascii.b2a_hex(srv_config['hwid']), 'utf-8').upper())
    return server
Beispiel #6
0
def server_create():
    socketserver.TCPServer.allow_reuse_address = True
    server = socketserver.TCPServer((srv_config['ip'], srv_config['port']),
                                    kmsServer)
    server.timeout = srv_config['timeout']
    loggersrv.info("TCP server listening at %s on port %d." %
                   (srv_config['ip'], srv_config['port']))
    loggersrv.info("HWID: %s" %
                   deco(binascii.b2a_hex(srv_config['hwid']), 'utf-8').upper())
    return server
Beispiel #7
0
def server_create():
        try:
                server = KeyServer((srv_config['ip'], srv_config['port']), kmsServerHandler)
        except (socket.gaierror, socket.error) as e:
                pretty_printer(log_obj = loggersrv.error, to_exit = True,
                               put_text = "{reverse}{red}{bold}Connection failed '%s:%d': %s. Exiting...{end}" %(srv_config['ip'],
                                                                                                                srv_config['port'],
                                                                                                                str(e)))
        server.timeout = srv_config['timeoutidle']
        loggersrv.info("TCP server listening at %s on port %d." % (srv_config['ip'], srv_config['port']))
        loggersrv.info("HWID: %s" % deco(binascii.b2a_hex(srv_config['hwid']), 'utf-8').upper())
        return server
Beispiel #8
0
    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
Beispiel #9
0
    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
Beispiel #10
0
 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)
Beispiel #11
0
    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
Beispiel #12
0
        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
Beispiel #13
0
        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
Beispiel #14
0
    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)
Beispiel #15
0
    def serverLogic(self, kmsRequest):
        if self.srv_config['sqlite']:
            sql_initialize(self.srv_config['sqlite'])

        pretty_printer(num_text=15, where="srv")
        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:
                pretty_printer(
                    log_obj=loggersrv.warning,
                    put_text=
                    "{reverse}{yellow}{bold}Unknown time zone ! Request time not localized.{end}"
                )
                local_dt = requestDatetime
        except ImportError:
            pretty_printer(
                log_obj=loggersrv.warning,
                put_text=
                "{reverse}{yellow}{bold}Module 'tzlocal' not available ! Request time not localized.{end}"
            )
            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["clientcount"] != None:
            if 0 < self.srv_config["clientcount"] < MinClients:
                # fixed to 6 (product server) or 26 (product desktop)
                currentClientCount = MinClients + 1
                pretty_printer(
                    log_obj=loggersrv.warning,
                    put_text=
                    "{reverse}{yellow}{bold}Not enough clients ! Fixed with %s, but activated client \
could be detected as not genuine !{end}" % currentClientCount)
            elif MinClients <= self.srv_config["clientcount"] < RequiredClients:
                currentClientCount = self.srv_config["clientcount"]
                pretty_printer(
                    log_obj=loggersrv.warning,
                    put_text=
                    "{reverse}{yellow}{bold}With count = %s, activated client could be detected as not genuine !{end}"
                    % currentClientCount)
            elif self.srv_config["clientcount"] >= RequiredClients:
                # fixed to 10 (product server) or 50 (product desktop)
                currentClientCount = RequiredClients
                if self.srv_config["clientcount"] > RequiredClients:
                    pretty_printer(
                        log_obj=loggersrv.warning,
                        put_text=
                        "{reverse}{yellow}{bold}Too many clients ! Fixed with %s{end}"
                        % 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
                        pretty_printer(
                            log_obj=loggersrv.warning,
                            put_text=
                            "{reverse}{yellow}{bold}Can't find a name for this product !{end}"
                        )

            try:
                if uuid.UUID(appitem['Id']) == applicationId:
                    appName = appitem['DisplayName']
            except:
                appName = applicationId
                pretty_printer(
                    log_obj=loggersrv.warning,
                    put_text=
                    "{reverse}{yellow}{bold}Can't find a name for this application group !{end}"
                )

        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']:
            sql_update(self.srv_config['sqlite'], infoDict)

        return self.createKmsResponse(kmsRequest, currentClientCount)
Beispiel #16
0
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()
Beispiel #17
0
def server_check():
    # Setup hidden or not messages.
    ShellMessage.view = (False if srv_config['logfile'] == 'STDOUT' else True)
    # Create log.
    logger_create(loggersrv, srv_config, mode='a')

    # Random HWID.
    if srv_config['hwid'] == "RANDOM":
        randomhwid = uuid.uuid4().hex
        srv_config['hwid'] = randomhwid[:16]

    # Sanitize HWID.
    try:
        srv_config['hwid'] = binascii.a2b_hex(
            re.sub(r'[^0-9a-fA-F]', '', srv_config['hwid'].strip('0x')))
        if len(binascii.b2a_hex(srv_config['hwid'])) < 16:
            loggersrv.error(
                "HWID \"%s\" is invalid. Hex string is too short." %
                deco(binascii.b2a_hex(srv_config['hwid']), 'utf-8').upper())
            return
        elif len(binascii.b2a_hex(srv_config['hwid'])) > 16:
            loggersrv.error(
                "HWID \"%s\" is invalid. Hex string is too long." %
                deco(binascii.b2a_hex(srv_config['hwid']), 'utf-8').upper())
            return
    except TypeError:
        loggersrv.error(
            "HWID \"%s\" is invalid. Odd-length hex string." %
            deco(binascii.b2a_hex(srv_config['hwid']), 'utf-8').upper())
        return

    # Check LCID.
    # http://stackoverflow.com/questions/3425294/how-to-detect-the-os-default-language-in-python
    if not srv_config['lcid'] or (srv_config['lcid'] not in ValidLcid):
        if hasattr(sys,
                   'implementation') and sys.implementation.name == 'cpython':
            srv_config['lcid'] = 1033
        elif os.name == 'nt':
            import ctypes

            srv_config[
                'lcid'] = ctypes.windll.kernel32.GetUserDefaultUILanguage()
        else:
            import locale

            try:
                srv_config['lcid'] = next(
                    k for k, v in locale.windows_locale.items()
                    if v == locale.getdefaultlocale()[0])
            except StopIteration:
                srv_config['lcid'] = 1033

    # Check sqlite.
    try:
        import sqlite3
    except:
        loggersrv.warning(
            "Module \"sqlite3\" is not installed, database support disabled.")
        srv_config['dbSupport'] = False
    else:
        srv_config['dbSupport'] = True

    # Check port.
    try:
        p = srv_config['port']
        if p > 65535:
            loggersrv.error(
                'Please enter a valid port number between 1 - 65535')
            return
    except Exception as e:
        loggersrv.error('%s' % e)
        return
Beispiel #18
0
def client_create(clt_sock):
        binder = pykms_RpcBind.handler(None, clt_config)
        RPC_Bind = enco(str(binder.generateRequest()), 'latin-1')

        try:
                loggerclt.info("Sending RPC bind request...")
                pretty_printer(num_text = [-1, 1], where = "clt")
                clt_sock.send(RPC_Bind)
        except socket.error as e:
                pretty_printer(log_obj = loggerclt.error, to_exit = True, where = "clt",
                               put_text = "{reverse}{red}{bold}While sending: %s. Exiting...{end}" %str(e))
        try:
                bindResponse = clt_sock.recv(1024)
                if bindResponse == '' or not bindResponse:
                        pretty_printer(log_obj = loggerclt.warning, to_exit = True, where = "clt",
                                       put_text = "{reverse}{yellow}{bold}No data received. Exiting...{end}")
                pretty_printer(num_text = [-4, 7], where = "clt")
        except socket.error as e:
                pretty_printer(log_obj = loggerclt.error, to_exit = True, where = "clt",
                               put_text = "{reverse}{red}{bold}While receiving: %s. Exiting...{end}" %str(e))

        packetType = MSRPCHeader(bindResponse)['type']
        if packetType == rpcBase.packetType['bindAck']:
                loggerclt.info("RPC bind acknowledged.")
                pretty_printer(num_text = 8, where = "clt")
                kmsRequest = createKmsRequest()
                requester = pykms_RpcRequest.handler(kmsRequest, clt_config)

                try:
                        loggerclt.info("Sending RPC activation request...")
                        RPC_Actv = enco(str(requester.generateRequest()), 'latin-1')
                        pretty_printer(num_text = [-1, 12], where = "clt")
                        clt_sock.send(RPC_Actv)
                except socket.error as e:
                        pretty_printer(log_obj = loggerclt.error, to_exit = True, where = "clt",
                                       put_text = "{reverse}{red}{bold}While sending: %s. Exiting...{end}" %str(e))
                try:
                        response = clt_sock.recv(1024)
                        pretty_printer(num_text = [-4, 20], where = "clt")
                except socket.error as e:
                        pretty_printer(log_obj = loggerclt.error, to_exit = True, where = "clt",
                                       put_text = "{reverse}{red}{bold}While receiving: %s. Exiting...{end}" %str(e))

                loggerclt.debug("Response: \n%s\n" % justify(deco(binascii.b2a_hex(response), 'latin-1')))
                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'] == 'MININFO':
                        loggerclt.mininfo("", extra = {'host': str(clt_sock.getpeername()),
                                                       'status' : kmsBase.licenseStates[requester.srv_config['KMSClientLicenseStatus']],
                                                       'product' : clt_config["mode"]})

                pretty_printer(num_text = 21, where = "clt")
                
        elif packetType == rpcBase.packetType['bindNak']:
                loggerclt.info(justify(MSRPCBindNak(bindResponse).dump(print_to_stdout = False)))
                sys.exit(0)
        else:
                pretty_printer(log_obj = loggerclt.warning, to_exit = True, where = "clt",
                               put_text = "{reverse}{magenta}{bold}Something went wrong. Exiting...{end}")