

class credsAPI(object):
    def __init__(self):

    def get_credentials(self):
        raise NotImplementedError('Not implemented')

    def fetch(self, hawk, threat_id):

        api = hawkapi(hawk)

        try:
            hawk.login(masterConfig['username'], masterConfig['password'])
        except Exception as e:
            hawk_print("Login error: %s" % e)
            return False

        rows = api.enrichmentGet(False)
        hT = None
        for row in rows:
            if 'global' in masterConfig:
                if "true" in masterConfig['global'].lower():
                    if row['group_name'] != '.':
                        continue

            if (int(row['e_id']) == int(threat_id)):
                row['token'] = self.token_hash
                row['engine_id'] = self.engine['engine_id']
                hT = hawkThread(hawk, row)
                break

        if hT:
            hT.run()
        else:
            hawk_print("No list found")

    def registerCredentials(self, hawk):
        # make the request to hawk
        kf = "/opt/hawk/.engine.key"
        if not os.path.isfile(kf):
            # generate pki, write private key to file
            # register engine with public key
            random_generator = Random.new().read
            # generate pub and priv key
            key = RSA.generate(4096, random_generator)
            publickey = key.publickey()  # pub key export for exchange

            # register with public key
            # if success, write private key locally
            # use parent group from login
            group_name = self.group_name

            # engine name is hostname
            hostname = socket.gethostname()
            #
            request = {'group_name': group_name, 'engine_name': hostname,
                       'active': 'true', 'public_key': publickey.exportKey()}

            # $this->client->put('/credentials/engine', $request);
            x = hawk.doPut('credentials/engine', request)
            if x:  # response given i think...
                with open(kf, "w") as prv_file:
                    prv_file.write(key.exportKey())
                    prv_file.close()

                    return True
            os.unlink(kf)
            return False

        return True

    def processToken(self):

        if not self.token_hash:
            return False
        # base 64 decode self.token_hash
        # then use private key to decrypt
        kf = "/opt/hawk/.engine.key"
        with open(kf, 'r') as f:
            va = f.read()
            r = RSA.importKey(va)

        x = base64.b64decode(self.token_hash)
        cipher = PKCS1_v1_5.new(r)
        iv = Random.new().read(16)
        key = cipher.decrypt(x, iv)
        if not key or len(key) < 64:
            return False
        # key for aes 256
        # aes = AES.new(key, AES.MODE_CFB, iv)
        # token = aes.decrypt(x)
        self.token = json.loads(key)
        return True

    def checkApproval(self, hawk):

        data = hawk.doGet('credentials/engine')
        hostname = socket.gethostname()
        seen = False
        for x in data:
            if x['engine_name'] == hostname:
                if x['active']:
                    self.token_hash = x['token']
                    self.engine = x
                    return True
                seen = True
                break

        if not seen:
            kf = "/opt/hawk/.engine.key"
            os.unlink(kf)
            self.registerCredentials(hawk)

            return self.checkApproval(hawk)

        return False
