예제 #1
0
        def generateResponse(self):
                request = self.requestData

                responseData = org.meter.kms.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)
                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).encode('latin-1')).decode('utf-8'))) #*2to3*
                
                return response
예제 #2
0
 def parseRequest(self):
         request = MSRPCRequestHeader(self.data)
         
         shell_message(nshell = 14)
         request = byterize(request)
         logging.debug("RPC Message Request Bytes: \n%s\n" % justify(binascii.b2a_hex(self.data).decode('utf-8')))
         logging.debug("RPC Message Request: \n%s\n" % justify(request.dump(print_to_stdout = False)))
                         
         return request
예제 #3
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)))  #*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
예제 #4
0
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'] = org.meter.kms.tools.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
예제 #5
0
    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
예제 #6
0
    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)
예제 #7
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.config['call_id']
                request['alloc_hint'] = len(self.data)
                request['pduData'] = str(self.data)

                shell_message(nshell = 11)
                request = byterize(request)
                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).encode('latin-1')).decode('utf-8'))) #*2to3*
                
                return request
예제 #8
0
    def generateRequest(self, requestBase):
        esalt = self.getRandomSalt()

        moo = org.meter.kms.tools.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 = org.meter.kms.tools.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
예제 #9
0
    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)
예제 #10
0
    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
예제 #11
0
    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 = org.meter.kms.tools.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)
예제 #12
0
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 = org.meter.kms.rpc.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 = org.meter.kms.rpc.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()