Ejemplo n.º 1
0
 def init_with_options(cls, options):
     if cls._securenative is None:
         cls._securenative = SecureNative(options)
         return cls._securenative
     else:
         Logger.debug('This SDK was already initialized.')
         raise SecureNativeSDKException(u'This SDK was already initialized.')
Ejemplo n.º 2
0
 def encrypt(cls, text, cipher_key):
     try:
         key = cipher_key[:cls.KEY_SIZE]
         iv = Random.new().read(AES.block_size)
         cipher = AES.new(key.encode("utf8"), AES.MODE_CBC, iv)
         raw = str(cls._pad(text))
         return hexlify(iv + cipher.encrypt(raw.encode("utf8")))
     except Exception as e:
         Logger.error("Could not encrypt text {}; {}".format(text, e))
         return None
Ejemplo n.º 3
0
    def read_resource_file(cls, resource_path):
        try:
            cls.config.read(resource_path)
        except Exception as e:
            Logger.debug("Invalid config file; {}, using default options".format(e))

        properties = {}
        for key, value in cls.config.defaults().items():
            properties[key.upper()] = value

        return properties
Ejemplo n.º 4
0
    def init_with_api_key(cls, api_key):
        if Utils.is_null_or_empty(api_key):
            raise SecureNativeConfigException("You must pass your SecureNative api key")

        if cls._securenative is None:
            options = SecureNativeOptions(api_key=api_key)
            cls._securenative = SecureNative(options)
            return cls._securenative
        else:
            Logger.debug('This SDK was already initialized.')
            raise SecureNativeSDKException(u'This SDK was already initialized.')
Ejemplo n.º 5
0
    def __init__(self, options):
        if Utils.is_null_or_empty(options.api_key):
            raise SecureNativeSDKException("You must pass your SecureNative api key")

        self._options = options
        self._event_manager = EventManager(self._options)

        if self._options.api_url:
            self._event_manager.start_event_persist()

        self._api_manager = ApiManager(self._event_manager, self._options)
        Logger.init_logger(self._options.log_level)
Ejemplo n.º 6
0
 def verify(self, event_options):
     Logger.debug("Verify event call")
     event = SDKEvent(event_options, self.options)
     try:
         res = json.loads(
             self.event_manager.send_sync(event,
                                          ApiRoute.VERIFY.value).text)
         return VerifyResult(res["riskLevel"], res["score"],
                             res["triggers"])
     except Exception as e:
         Logger.debug("Failed to call verify; {}".format(e))
         if self.options.fail_over_strategy is FailOverStrategy.FAIL_OPEN.value:
             return VerifyResult(RiskLevel.LOW.value, 0, [])
         return VerifyResult(RiskLevel.HIGH.value, 1, [])
    def send_async(self, event, resource_path):
        if self.options.disable:
            Logger.warning("SDK is disabled. no operation will be performed")
            return

        item = QueueItem(
            resource_path,
            json.dumps(EventManager.serialize(event)),
            False
        )

        self.queue.append(item)
        if self._is_queue_full():
            self.queue = self.queue[:len(self.queue - 1)]
Ejemplo n.º 8
0
 def decrypt(cls, encrypted, cipher_key):
     try:
         key = cipher_key[:cls.KEY_SIZE]
         content = unhexlify(encrypted)
         iv = content[:cls.BLOCK_SIZE]
         cipher_text = content[cls.BLOCK_SIZE:]
         aes = AES.new(key.encode("utf8"), AES.MODE_CBC, iv)
         rv = aes.decrypt(cipher_text).decode("utf-8").strip()
         secret = json.loads(rv)
         return ClientToken(secret.get("cid"), secret.get("vid"),
                            secret.get("fp"))
     except Exception as e:
         Logger.error("Could not decrypt str {}; {}".format(encrypted, e))
         return None
    def run(self):
        while True:
            if len(self.queue) > 0 and self.send_enabled:
                for item in self.queue:
                    try:
                        res = self.http_client.post(item.url, item.body)
                        if res.status_code == 401:
                            item.retry = False
                        elif res.status_code != 200:
                            item.retry = True
                        self.queue.remove(item)

                        Logger.debug("Event successfully sent; {}".format(item.body))
                    except Exception as e:
                        Logger.error("Failed to send event; {}".format(e))
                        if item.retry:
                            if len(self.coefficients) == self.attempt + 1:
                                self.attempt = 0

                            back_off = self.coefficients[self.attempt] * self.options.interval
                            Logger.debug("Automatic back-off of {}".format(back_off))
                            self.send_enabled = False
                            time.sleep(back_off)
                            self.send_enabled = True
                time.sleep(self.interval/1000)
    def stop_event_persist(self):
        if self.send_enabled:
            Logger.debug("Attempting to stop automatic event persistence")
            try:
                self.flush()
                if self.thread:
                    self.thread.stop()
            except ValueError as e:
                Logger.error("Could not stop event scheduler; {}".format(e))

            Logger.debug("Stopped event persistence")
    def send_sync(self, event, resource_path):
        if self.options.disable:
            Logger.warning("SDK is disabled. no operation will be performed")
            return

        Logger.debug("Attempting to send event {}".format(event))
        res = self.http_client.post(
            resource_path,
            json.dumps(EventManager.serialize(event))
        )
        if res is None or res.status_code != 200:
            Logger.info("SecureNative failed to call endpoint {} with event {}.".format(resource_path, event))

        return res
Ejemplo n.º 12
0
 def track(self, event_options):
     Logger.debug("Track event call")
     event = SDKEvent(event_options, self.options)
     return self.event_manager.send_async(event, ApiRoute.TRACK.value)
 def start_event_persist(self):
     Logger.debug("Starting automatic event persistence")
     if self.options.auto_send or self.send_enabled:
         self.send_enabled = True
     else:
         Logger.debug("Automatic event persistence is disabled, you should persist events manually")