Beispiel #1
0
    def _request(self, endpoint, params=None, json=None):
        """Handle the requesting of information from the API.

        :param endpoint: Endpoint to send the request to.
        :type endpoint: str
        :param params: Request parameters.
        :type param: dict
        :param json: Request's JSON payload.
        :type json: dict
        :returns: Response's JSON payload
        :rtype: dict
        :raises RequestFailure: when HTTP status code is not 2xx

        """
        if params is None:
            params = {}
        headers = {
            "User-Agent": "greyNoise/{}".format(self.CLIENT_VERSION),
            "key": self.api_key,
        }
        url = "/".join([self.BASE_URL, self.API_VERSION, endpoint])
        response = self.session.get(url,
                                    headers=headers,
                                    timeout=self.timeout,
                                    params=params,
                                    json=json)

        body = response.json()
        if response.status_code == 429:
            raise RateLimitError()
        if not 200 <= response.status_code < 300:
            raise RequestFailure(response.status_code, body)

        return body
Beispiel #2
0
    def _request(self, endpoint, params=None, json=None, method="get"):
        """Handle the requesting of information from the API.

        :param endpoint: Endpoint to send the request to
        :type endpoint: str
        :param params: Request parameters
        :type param: dict
        :param json: Request's JSON payload
        :type json: dict
        :param method: Request method name
        :type method: str
        :returns: Response's JSON payload
        :rtype: dict
        :raises RequestFailure: when HTTP status code is not 2xx

        """
        if params is None:
            params = {}

        user_agent_parts = ["GreyNoise/{}".format(__version__)]
        if self.integration_name:
            user_agent_parts.append("({})".format(self.integration_name))
        headers = {
            "User-Agent": " ".join(user_agent_parts),
            "key": self.api_key,
        }
        url = "/".join([self.api_server, self.API_VERSION, endpoint])
        LOGGER.debug(
            "Sending API request...",
            url=url,
            method=method,
            headers=headers,
            params=params,
            json=json,
        )
        request_method = getattr(self.session, method)
        response = request_method(url,
                                  headers=headers,
                                  timeout=self.timeout,
                                  params=params,
                                  json=json)
        content_type = response.headers.get("Content-Type", "")
        if "application/json" in content_type:
            body = response.json()
        else:
            body = response.text

        LOGGER.debug(
            "API response received",
            status_code=response.status_code,
            content_type=content_type,
            body=body,
        )

        if response.status_code == 429:
            raise RateLimitError()
        if response.status_code >= 400:
            raise RequestFailure(response.status_code, body)

        return body
Beispiel #3
0
    def test_not_implemented(self, api_client):
        """Not implemented error message returned."""
        runner = CliRunner()
        expected_output = "Error: 'signature' subcommand is not implemented yet.\n"

        api_client.not_implemented.side_effect = RequestFailure(501)
        result = runner.invoke(subcommand.signature)
        api_client.not_implemented.assert_called_with("signature")
        assert result.exit_code == 1
        assert result.output == expected_output
    def test_request_failure(self, api_client):
        """Error is displayed on API request failure."""
        runner = CliRunner()

        api_client.stats.side_effect = RequestFailure(
            401, {"error": "forbidden", "status": "error"}
        )
        expected = "API error: forbidden"

        result = runner.invoke(subcommand.stats, ["<query>"])
        assert result.exit_code == -1
        assert expected in result.output
Beispiel #5
0
    def test_request_failure(self, api_client):
        """Error is displayed on API request failure."""
        runner = CliRunner()

        api_client.filter.side_effect = RequestFailure(401, {
            "error": "forbidden",
            "status": "error"
        })
        expected = "API error: forbidden\n"

        result = runner.invoke(subcommand.filter, input="some text")
        assert result.exit_code == -1
        assert result.output == expected
Beispiel #6
0
def validate_api_key(api_key, logger=None):
    """
    Validate the API key using the actual lightweight call to the GreyNoise API.
    Returns false only when 401 code is thrown, indicating the unauthorised access.
    :param api_key: 
    :param logger:
    """
    URL = "https://api.greynoise.io/v2/meta/ping"
    HEADER = {"key": api_key}

    if logger:
        logger.debug("Validating the api key...")

    try:
        response = requests.get(url=URL, headers=HEADER)

        if response.status_code == 429:
            raise RateLimitError()
        if response.status_code >= 400:
            # Processing API response
            content_type = response.headers.get("Content-Type", "")
            if "application/json" in content_type:
                body = response.json()
            else:
                body = response.text
            raise RequestFailure(response.status_code, body)
        return (True, 'API key is valid')

    except RateLimitError:
        msg = "RateLimitError occured, please contact the Administrator"
        return (False, 'API key not validated, Error: {}'.format(msg))
    except RequestFailure as e:
        response_code, response_message = e.args
        if response_code == 401:
            return (False, 'Unauthorized. Please check your API key.')
        else:
            # Need to handle this, as splunklib is unable to handle the exception with (400, {'error': 'error_reason'}) format
            msg = "The API call to the GreyNoise platform have been failed with status_code: {} and error: {}".format(
                response_code, response_message['error'] if isinstance(
                    response_message, dict) else response_message)
            return (False, 'API key not validated, Error: {}'.format(msg))
    except ConnectionError:
        msg = "ConnectionError occured, please check your connection and try again."
        return (False, 'API key not validated, Error: {}'.format(msg))
    except RequestException:
        msg = "An ambiguous exception occured, please try again."
        return (False, 'API key not validated, Error: {}'.format(msg))
    except Exception as e:
        return (False, 'API key not validated, Error: {}'.format(str(e)))
Beispiel #7
0
    def _request(self, endpoint, params=None, json=None):
        """Handle the requesting of information from the API.

        :param endpoint: Endpoint to send the request to.
        :type endpoint: str
        :param params: Request parameters.
        :type param: dict
        :param json: Request's JSON payload.
        :type json: dict
        :returns: Response's JSON payload
        :rtype: dict
        :raises RequestFailure: when HTTP status code is not 2xx

        """
        if params is None:
            params = {}
        headers = {
            "User-Agent": "GreyNoise/{}".format(__version__),
            "key": self.api_key,
        }
        url = "/".join([self.BASE_URL, self.API_VERSION, endpoint])
        LOGGER.debug("Sending API request...",
                     url=url,
                     params=params,
                     json=json)
        response = self.session.get(url,
                                    headers=headers,
                                    timeout=self.timeout,
                                    params=params,
                                    json=json)

        if "application/json" in response.headers.get("Content-Type", ""):
            body = response.json()
        else:
            body = response.text

        if response.status_code == 429:
            raise RateLimitError()
        if response.status_code >= 400:
            raise RequestFailure(response.status_code, body)

        return body