Exemplo n.º 1
0
Arquivo: api.py Projeto: rapid7/lecli
def tail_logs(logkeys, leql, poll_interval, favorites=None, logset=None, saved_query_id=None):
    """
    Tail given logs
    """
    if favorites:
        logkeys = api_utils.get_named_logkey_group(favorites)
    elif logset:
        logkeys = api.get_log_keys_from_logset(logset)
    if saved_query_id:
        if logkeys:
            url = _url(('live', 'logs', ':'.join(logkeys), str(saved_query_id)))[1]
        else:
            url = _url(('live', 'saved_query', str(saved_query_id)))[1]
    else:
        url = _url(('live', 'logs'))[1]
    try:
        if saved_query_id:
            response = requests.get(url, headers=api_utils.generate_headers('rw'))
        else:
            payload = {'logs': logkeys}
            if leql:
                payload.update({'leql': {'statement': leql}})

            response = requests.post(url, headers=api_utils.generate_headers('rw'), json=payload)
        handle_tail(response, poll_interval)
        return True
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 2
0
def tail_logs(logkeys, leql, poll_interval, favorites=None, logset=None, saved_query_id=None):
    """
    Tail given logs
    """
    if favorites:
        logkeys = api_utils.get_named_logkey_group(favorites)
    elif logset:
        logkeys = api.get_log_keys_from_logset(logset)
    if saved_query_id:
        if logkeys:
            url = _url(('live', 'logs', ':'.join(logkeys), str(saved_query_id)))[1]
        else:
            url = _url(('live', 'saved_query', str(saved_query_id)))[1]
    else:
        url = _url(('live', 'logs'))[1]
    try:
        if saved_query_id:
            response = requests.get(url, headers=api_utils.generate_headers('rw'))
        else:
            payload = {'logs': logkeys}
            if leql:
                payload.update({'leql': {'statement': leql}})

            response = requests.post(url, headers=api_utils.generate_headers('rw'), json=payload)
        handle_tail(response, poll_interval)
        return True
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 3
0
Arquivo: api.py Projeto: rapid7/lecli
def delete_user_from_team(team_id, user_key):
    """
    Delete a user from a team.
    """
    headers = api_utils.generate_headers('rw')
    params = {'teamid': team_id}
    try:
        response = requests.request('GET', _url((team_id,))[1], params=params,
                                    headers=headers)
        if response.status_code == 200:
            params = {
                'team': {
                    'name': response.json()['team']['name'],
                    'users': [user for user in response.json()['team']['users'] if user['id'] !=
                              user_key]
                }
            }
            headers = api_utils.generate_headers('rw')
            try:
                response = requests.put(_url((team_id,))[1], json=params, headers=headers)
                if response_utils.response_error(response):  # Check response has no errors
                    click.echo('Deleting user from team with key: %s failed.' % team_id, err=True)
                    sys.exit(1)
                elif response.status_code == 200:
                    click.echo("Deleted user with key: '%s' from team: %s" % (user_key, team_id))
            except requests.exceptions.RequestException as error:
                click.echo(error, err=True)
                sys.exit(1)
        elif response_utils.response_error(response):
            click.echo('Cannot find team. Deleting user from team %s failed.' % team_id, err=True)
            sys.exit(1)
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 4
0
def add_user_to_team(team_id, user_key):
    """
    Add user with the provided user_key to team with provided team_id.
    """
    headers = api_utils.generate_headers('rw')
    params = {'teamid': team_id}
    try:
        response = requests.get(_url((team_id, ))[1],
                                params=params,
                                headers=headers)
        if response.status_code == 200:
            params = {
                'team': {
                    'name':
                    response.json()['team']['name'],
                    'users': [
                        # we are doing a patch request here so it's safe to include the user_key
                        # we want to add here
                        {
                            'id': user_key
                        }
                    ]
                }
            }
            headers = api_utils.generate_headers('rw')
            try:
                response = requests.patch(_url((team_id, ))[1],
                                          json=params,
                                          headers=headers)
                if response_utils.response_error(
                        response):  # Check response has no errors
                    click.echo('Adding user to team with key: %s failed.' %
                               team_id,
                               err=True)
                    sys.exit(1)
                elif response.status_code == 200:
                    click.echo('Added user with key: %s to team.' % user_key)
            except requests.exceptions.RequestException as error:
                click.echo(error, err=True)
                sys.exit(1)
        elif response_utils.response_error(response):
            click.echo('Cannot find team. Adding user to team %s failed.' %
                       team_id,
                       err=True)
            sys.exit(1)
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 5
0
def rename_team(team_id, team_name):
    """
    Rename team with the provided team_id.
    """
    params = {
        'team': {
            'name': team_name,
            # as this is a patch request, it won't modify users in the team.
            # what we want is to update the name of the team only.
            'users': [{
                'id': ''
            }]
        }
    }
    headers = api_utils.generate_headers('rw')

    try:
        response = requests.patch(_url((team_id, ))[1],
                                  json=params,
                                  headers=headers)
        if response_utils.response_error(
                response):  # Check response has no errors
            click.echo('Renaming team with id: %s failed.' % team_id, err=True)
            sys.exit(1)
        elif response.status_code == 200:
            click.echo("Team: '%s' renamed to: '%s'" % (team_id, team_name))
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 6
0
def get_recent_events(log_keys, last_x_seconds=1200, time_range=None):
    """
    Get recent events belonging to provided log_keys in the last_x_seconds.
    """
    if time_range:
        leql = {
            "during": {
                "time_range": time_range
            },
            "statement": ALL_EVENTS_QUERY
        }
    else:
        to_ts = int(time.time()) * 1000
        from_ts = (int(time.time()) - last_x_seconds) * 1000
        leql = {
            "during": {
                "from": from_ts,
                "to": to_ts
            },
            "statement": ALL_EVENTS_QUERY
        }
    payload = {"logs": log_keys, "leql": leql}

    try:
        response = requests.post(_url('logs'),
                                 headers=api_utils.generate_headers('rw'),
                                 json=payload)
        with click.progressbar(length=100, label='Progress') as progress_bar:
            handle_response(response, progress_bar)
    except requests.exceptions.RequestException as error:
        print error
        exit(1)
Exemplo n.º 7
0
def test_generate_header_rw(mocked_rw_apikey):
    mocked_rw_apikey.return_value = ID_WITH_VALID_LENGTH

    headers = api_utils.generate_headers(api_key_type='rw')

    assert 'x-api-key' in headers
    assert headers['x-api-key'] == ID_WITH_VALID_LENGTH
Exemplo n.º 8
0
def post_query(log_keys, query_string, time_from=None, time_to=None, date_from=None,
               date_to=None, time_range=None):
    """
    Post query to Logentries.
    """
    if date_from and date_to:
        from_ts = int(time.mktime(time.strptime(date_from, "%Y-%m-%d %H:%M:%S"))) * 1000
        to_ts = int(time.mktime(time.strptime(date_to, "%Y-%m-%d %H:%M:%S"))) * 1000
        leql = {"during": {"from": from_ts, "to": to_ts}, "statement": query_string}
    elif time_from and time_to:
        leql = {"during": {"from": time_from * 1000, "to": time_to * 1000},
                "statement": query_string}
    else:
        leql = {"during": {"time_range": time_range}, "statement": query_string}

    payload = {"logs": log_keys, "leql": leql}

    try:
        response = requests.post(_url('logs'), headers=api_utils.generate_headers('rw'),
                                 json=payload)
        with click.progressbar(length=100, label='Progress') as progress_bar:
            handle_response(response, progress_bar)
    except requests.exceptions.RequestException as error:
        click.echo(error)
        sys.exit(1)
Exemplo n.º 9
0
Arquivo: api.py Projeto: rapid7/lecli
def add_log(logset_id, log_id):
    """
    Add a log to the logset
    """
    params = {
        "logset":{
            "logs_info": [{
                "id": str(log_id)
            }]
        }
    }
    headers = api_utils.generate_headers('ro')

    try:
        response = requests.get(_url((logset_id,))[1], headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Add log %s to logset %s failed\n'
                             % (log_id, logset_id))
            sys.exit(1)
        elif response.status_code == 200:
            existing_logset = response.json()
            replace_logset(logset_id, api_utils.combine_objects(existing_logset, params))
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 10
0
def get_events(log_keys, time_from=None, time_to=None, date_from=None, date_to=None,
               time_range=None):
    """
    Get events belonging to log_keys and within the time range provided.
    """
    if date_from and date_to:
        from_ts = int(time.mktime(time.strptime(date_from, "%Y-%m-%d %H:%M:%S"))) * 1000
        to_ts = int(time.mktime(time.strptime(date_to, "%Y-%m-%d %H:%M:%S"))) * 1000
        leql = {"during": {"from": from_ts, "to": to_ts}, "statement": ALL_EVENTS_QUERY}
    elif time_to and time_from:
        from_ts = time_from * 1000
        to_ts = time_to * 1000
        leql = {"during": {"from": from_ts, "to": to_ts}, "statement": ALL_EVENTS_QUERY}
    else:
        leql = {"during": {"time_range": time_range}, "statement": ALL_EVENTS_QUERY}

    payload = {"logs": log_keys, "leql": leql}

    try:
        response = requests.post(_url('logs'), headers=api_utils.generate_headers('rw'),
                                 json=payload)
        with click.progressbar(length=100, label='Progress') as progress_bar:
            handle_response(response, progress_bar)
    except requests.exceptions.RequestException as error:
        click.echo(error)
        sys.exit(1)
Exemplo n.º 11
0
def update(api_key_id, active):
    """
    Enable or disable an api key with given ID
    """
    action, url = _url((api_key_id,))
    payload = {
        "apikey":
            {
                "active": active
            }
    }

    headers = api_utils.generate_headers('owner', method='PATCH', body=json.dumps(payload),
                                         action=action)
    try:
        response = requests.patch(url, json=payload, headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Failed to %s api key with id: %s \n' %
                             ('enable' if active else 'disable', api_key_id))
            sys.exit(1)
        elif response.status_code == 200:
            sys.stdout.write('%s api key with id: %s\n' %
                             ('Enabled' if active else 'Disabled', api_key_id))
            handle_api_key_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 12
0
def add_new_user(first_name, last_name, email):
    """
    Add a new user to the current account.
    """
    action = 'management/accounts/%s/users' % api_utils.get_account_resource_id(
    )
    json_content = {
        "user": {
            "email": str(email),
            "first_name": str(first_name),
            "last_name": str(last_name)
        }
    }
    body = json.dumps(json_content)
    headers = api_utils.generate_headers('owner',
                                         method='POST',
                                         action=action,
                                         body=body)

    try:
        response = requests.request('POST',
                                    _url('user'),
                                    json=json_content,
                                    headers=headers)
        handle_create_user_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 13
0
def rename_team(team_id, team_name):
    """
    Rename team with the provided team_id.
    """
    url = _url() + '/' + team_id
    params = {
        'team': {
            'name': team_name,
            # as this is a patch request, it won't modify users in the team.
            # what we want is to update the name of the team only.
            'users': [{
                'id': ''
            }]
        }
    }
    headers = api_utils.generate_headers('rw')

    try:
        response = requests.patch(url, json=params, headers=headers)
        if response_utils.response_error(
                response):  # Check response has no errors
            print 'Renaming team with id: %s failed, status code: %d' \
                  % (team_id, response.status_code)
            sys.exit(1)
        elif response.status_code == 200:
            print "Team: '%s' renamed to: '%s'" % (team_id, team_name)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 14
0
def create_log(logname, params):
    """Add a new log to the current account.
    If a JSON object is given, use that as the request parameters.
    Otherwise, use the name provided
    """
    if params is not None:
        request_params = params
    else:
        request_params = {
            'log': {
                'name': logname
            }
        }

    headers = api_utils.generate_headers('rw')

    try:
        response = requests.post(_url(), json=request_params, headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Create log failed, status code: %d' % response.status_code)
            sys.exit(1)
        elif response.status_code == 201:
            api_utils.pretty_print_string_as_json(response.text)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 15
0
def test_generate_headers_ro(mocked_ro_apikey):
    mocked_ro_apikey.return_value = ID_WITH_VALID_LENGTH

    headers = api_utils.generate_headers(api_key_type='ro')

    assert "x-api-key" in headers
    assert headers["x-api-key"] == ID_WITH_VALID_LENGTH
Exemplo n.º 16
0
Arquivo: api.py Projeto: rapid7/lecli
def rename_team(team_id, team_name):
    """
    Rename team with the provided team_id.
    """
    params = {
        'team': {
            'name': team_name,
            # as this is a patch request, it won't modify users in the team.
            # what we want is to update the name of the team only.
            'users': [
                {'id': ''}
            ]
        }
    }
    headers = api_utils.generate_headers('rw')

    try:
        response = requests.patch(_url((team_id,))[1], json=params, headers=headers)
        if response_utils.response_error(response):  # Check response has no errors
            click.echo('Renaming team with id: %s failed.' % team_id, err=True)
            sys.exit(1)
        elif response.status_code == 200:
            click.echo("Team: '%s' renamed to: '%s'" % (team_id, team_name))
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 17
0
Arquivo: api.py Projeto: rapid7/lecli
def update(api_key_id, active):
    """
    Enable or disable an api key with given ID
    """
    action, url = _url((api_key_id,))
    payload = {
        "apikey":
            {
                "active": active
            }
    }

    headers = api_utils.generate_headers('owner', method='PATCH', body=json.dumps(payload),
                                         action=action)
    try:
        response = requests.patch(url, json=payload, headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Failed to %s api key with id: %s \n' %
                             ('enable' if active else 'disable', api_key_id))
            sys.exit(1)
        elif response.status_code == 200:
            sys.stdout.write('%s api key with id: %s\n' %
                             ('Enabled' if active else 'Disabled', api_key_id))
            handle_api_key_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 18
0
def test_generate_headers_ro(mocked_ro_apikey):
    mocked_ro_apikey.return_value = ID_WITH_VALID_LENGTH

    headers = api_utils.generate_headers(api_key_type='ro')

    assert "x-api-key" in headers
    assert headers["x-api-key"] == ID_WITH_VALID_LENGTH
Exemplo n.º 19
0
def test_generate_header_rw(mocked_rw_apikey):
    mocked_rw_apikey.return_value = ID_WITH_VALID_LENGTH

    headers = api_utils.generate_headers(api_key_type='rw')

    assert 'x-api-key' in headers
    assert headers['x-api-key'] == ID_WITH_VALID_LENGTH
Exemplo n.º 20
0
def delete_user_from_team(team_id, user_key):
    """
    Delete a user from a team.
    """
    headers = api_utils.generate_headers('rw')
    params = {'teamid': team_id}
    try:
        response = requests.request('GET',
                                    _url((team_id, ))[1],
                                    params=params,
                                    headers=headers)
        if response.status_code == 200:
            params = {
                'team': {
                    'name':
                    response.json()['team']['name'],
                    'users': [
                        user for user in response.json()['team']['users']
                        if user['id'] != user_key
                    ]
                }
            }
            headers = api_utils.generate_headers('rw')
            try:
                response = requests.put(_url((team_id, ))[1],
                                        json=params,
                                        headers=headers)
                if response_utils.response_error(
                        response):  # Check response has no errors
                    click.echo('Deleting user from team with key: %s failed.' %
                               team_id,
                               err=True)
                    sys.exit(1)
                elif response.status_code == 200:
                    click.echo("Deleted user with key: '%s' from team: %s" %
                               (user_key, team_id))
            except requests.exceptions.RequestException as error:
                click.echo(error, err=True)
                sys.exit(1)
        elif response_utils.response_error(response):
            click.echo('Cannot find team. Deleting user from team %s failed.' %
                       team_id,
                       err=True)
            sys.exit(1)
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 21
0
def test_generate_header_owner(mocked_owner_apikey, mocked_owner_apikey_id):
    mocked_owner_apikey.return_value = ID_WITH_VALID_LENGTH
    mocked_owner_apikey_id.return_value = ID_WITH_VALID_LENGTH
    headers = api_utils.generate_headers(api_key_type='owner', body='', method="GET", action="action")

    assert 'Date' in headers
    assert 'authorization-api-key' in headers
    assert ID_WITH_VALID_LENGTH in headers['authorization-api-key']
Exemplo n.º 22
0
def add_user_to_team(team_id, user_key):
    """
    Add user with the provided user_key to team with provided team_id.
    """
    headers = api_utils.generate_headers('rw')
    params = {'teamid': team_id}
    try:
        response = requests.request('GET',
                                    _url() + '/' + team_id,
                                    params=params,
                                    headers=headers)
        if response.status_code == 200:
            url = _url() + '/' + team_id
            params = {
                'team': {
                    'name':
                    response.json()['team']['name'],
                    'users': [
                        # we are doing a patch request here so it's safe to include the user_key
                        # we want to add here
                        {
                            'id': user_key
                        }
                    ]
                }
            }
            headers = api_utils.generate_headers('rw')
            try:
                response = requests.patch(url, json=params, headers=headers)
                if response_utils.response_error(
                        response):  # Check response has no errors
                    print 'Adding user to team with key: %s failed, status code: %d' \
                          % (team_id, response.status_code)
                    sys.exit(1)
                elif response.status_code == 200:
                    print "Added user with key: '%s' to team" % user_key
            except requests.exceptions.RequestException as error:
                sys.stderr.write(error)
                sys.exit(1)
        elif response_utils.response_error(response):
            print 'Cannot find team. Adding user to team %s failed, ' \
                  'status code: %d' % (team_id, response.status_code)
            sys.exit(1)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 23
0
def delete_user_from_team(team_id, user_key):
    """
    Delete a user from a team.
    """
    headers = api_utils.generate_headers('rw')
    params = {'teamid': team_id}
    try:
        response = requests.request('GET',
                                    _url() + '/' + team_id,
                                    params=params,
                                    headers=headers)
        if response.status_code == 200:
            url = _url() + '/' + team_id
            params = {
                'team': {
                    'name':
                    response.json()['team']['name'],
                    'users': [
                        user for user in response.json()['team']['users']
                        if user['id'] != user_key
                    ]
                }
            }
            headers = api_utils.generate_headers('rw')
            try:
                response = requests.put(url, json=params, headers=headers)
                if response_utils.response_error(
                        response):  # Check response has no errors
                    print 'Deleting user from team with key: %s failed, status code: %d' \
                          % (team_id, response.status_code)
                    sys.exit(1)
                elif response.status_code == 200:
                    print "Deleted user with key: '%s' from team: %s" % (
                        user_key, team_id)
            except requests.exceptions.RequestException as error:
                sys.stderr.write(error)
                sys.exit(1)
        elif response_utils.response_error(response):
            print 'Cannot find team. Deleting user from team %s failed, ' \
                  'status code: %d' % (team_id, response.status_code)
            sys.exit(1)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 24
0
def fetch_results(provided_url):
    """
    Make the get request to the url and return the response.
    """
    try:
        response = requests.get(provided_url, headers=api_utils.generate_headers('rw'))
        return response
    except requests.exceptions.RequestException as error:
        click.echo(error)
        sys.exit(1)
Exemplo n.º 25
0
Arquivo: api.py Projeto: rapid7/lecli
def get_teams():
    """
    Get teams associated with the user.
    """
    headers = api_utils.generate_headers('rw')
    try:
        response = requests.get(_url()[1], data='', headers=headers)
        handle_get_teams_response(response)
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 26
0
def get_teams():
    """
    Get teams associated with the user.
    """
    headers = api_utils.generate_headers('rw')
    try:
        response = requests.get(_url()[1], data='', headers=headers)
        handle_get_teams_response(response)
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 27
0
def get_teams():
    """
    Get teams associated with the user.
    """
    headers = api_utils.generate_headers('rw')
    try:
        response = requests.request('GET', _url(), data='', headers=headers)
        handle_get_teams_response(response)
    except requests.exceptions.RequestException as error:
        print error
        exit(1)
Exemplo n.º 28
0
def get_logs():
    """
    Get logs associated with the user
    """
    headers = api_utils.generate_headers('ro')
    try:
        response = requests.request('GET', _url(), headers=headers)
        handle_get_log_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 29
0
Arquivo: api.py Projeto: rapid7/lecli
def fetch_results(provided_url, params=None):
    """
    Make the get request to the url and return the response.
    """
    try:
        response = requests.get(provided_url, headers=api_utils.generate_headers('rw'),
                                params=params)
        return response
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 30
0
def get_logsets():
    """
    Get all logsets
    """
    headers = api_utils.generate_headers('ro')
    try:
        response = requests.request('GET', _url()[1], headers=headers)
        handle_response(response, 'Unable to fetch logsets\n', 200)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 31
0
def get_log(log_id):
    """
    Get a specific log
    """
    headers = api_utils.generate_headers('ro')
    try:
        response = requests.get("/".join([_url(), log_id]), headers=headers)
        handle_get_log_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 32
0
Arquivo: api.py Projeto: rapid7/lecli
def get_logset(logset_id):
    """
    Get the logset with the given id
    """
    headers = api_utils.generate_headers('ro')
    try:
        response = requests.get(_url((logset_id,))[1], headers=headers)
        handle_response(response, 'Unable to fetch logset %s \n' % logset_id, 200)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 33
0
Arquivo: api.py Projeto: rapid7/lecli
def get_logsets():
    """
    Get all logsets
    """
    headers = api_utils.generate_headers('ro')
    try:
        response = requests.request('GET', _url()[1], headers=headers)
        handle_response(response, 'Unable to fetch logsets\n', 200)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 34
0
def test_generate_header_owner(mocked_owner_apikey, mocked_owner_apikey_id):
    mocked_owner_apikey.return_value = ID_WITH_VALID_LENGTH
    mocked_owner_apikey_id.return_value = ID_WITH_VALID_LENGTH
    headers = api_utils.generate_headers(api_key_type='owner',
                                         body='',
                                         method="GET",
                                         action="action")

    assert 'Date' in headers
    assert 'authorization-api-key' in headers
    assert ID_WITH_VALID_LENGTH in headers['authorization-api-key']
Exemplo n.º 35
0
def get(api_key_id):
    """
    Get a specific apikey
    """
    action, url = _url((api_key_id,))
    headers = api_utils.generate_headers('rw', method='GET', body='', action=action)
    try:
        response = requests.get(url, headers=headers)
        handle_api_key_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 36
0
def get_all(owner=False):
    """
    Get apikeys associated with the account - this uses rw apikey so does not return owner api keys
    """
    action, url = _url()
    headers = api_utils.generate_headers('owner' if owner else 'rw', method='GET', body='', action=action)
    try:
        response = requests.get(url, headers=headers)
        handle_api_key_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 37
0
def get_logset(logset_id):
    """
    Get the logset with the given id
    """
    headers = api_utils.generate_headers('ro')
    try:
        response = requests.get(_url((logset_id, ))[1], headers=headers)
        handle_response(response, 'Unable to fetch logset %s \n' % logset_id,
                        200)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 38
0
Arquivo: api.py Projeto: rapid7/lecli
def get_team(team_id):
    """
    Get a specific team.
    """
    headers = api_utils.generate_headers('rw')
    params = {'teamid': team_id}
    try:
        response = requests.get(_url((team_id,))[1], params=params, headers=headers)
        handle_get_teams_response(response)
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 39
0
Arquivo: api.py Projeto: rapid7/lecli
def replace_logset(logset_id, params):
    """
    Replace a given logset with the details provided
    """
    headers = api_utils.generate_headers('rw')

    try:
        response = requests.put(_url((logset_id,))[1], json=params, headers=headers)
        handle_response(response, 'Update logset with details %s failed.\n' % params, 200)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 40
0
Arquivo: api.py Projeto: rapid7/lecli
def list_users():
    """
    List users that is in the current account.
    """
    action, url = _url(('users',))
    try:
        response = requests.request('GET', url,
                                    headers=api_utils.generate_headers('owner', 'GET', action, ''))
        handle_userlist_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 41
0
Arquivo: api.py Projeto: fcr--/lecli
def list_users():
    """
    List users that is in the current account.
    """
    action, url = _url(('users',))
    try:
        response = requests.request('GET', url,
                                    headers=api_utils.generate_headers('owner', 'GET', action, ''))
        handle_userlist_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 42
0
def post_query(log_keys, query_string, time_range):
    """
    POST a request to Rest Query API

    :param log_keys: list of log keys
    :param query_string: leql query statement
    :param time_range: time range including either relative time range or start and end times
    :return: response
    """
    payload = {"logs": log_keys, "leql": {"statement": query_string, "during": time_range}}
    response = requests.post(_url(('logs',))[1], headers=api_utils.generate_headers('rw'),
                             json=payload)
    return response
Exemplo n.º 43
0
Arquivo: api.py Projeto: rapid7/lecli
def get_all(owner=False):
    """
    Get apikeys associated with the account - this uses rw apikey so does not return owner api keys
    """
    action, url = _url()
    headers = api_utils.generate_headers('owner' if owner else 'rw', method='GET', body='',
                                         action=action)
    try:
        response = requests.get(url, headers=headers)
        handle_api_key_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 44
0
Arquivo: api.py Projeto: fcr--/lecli
def add_existing_user(user_key):
    """
    Add a user that already exist to the current account.
    """
    action, url = _url(('users', user_key))
    headers = api_utils.generate_headers('owner', method='POST', action=action, body='')

    try:
        response = requests.request('POST', url, data='', headers=headers)
        handle_create_user_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 45
0
Arquivo: api.py Projeto: rapid7/lecli
def post_query(log_keys, query_string, time_range):
    """
    POST a request to Rest Query API

    :param log_keys: list of log keys
    :param query_string: leql query statement
    :param time_range: time range including either relative time range or start and end times
    :return: response
    """
    payload = {"logs": log_keys, "leql": {"statement": query_string, "during": time_range}}
    response = requests.post(_url(('logs',))[1], headers=api_utils.generate_headers('rw'),
                             json=payload)
    return response
Exemplo n.º 46
0
Arquivo: api.py Projeto: rapid7/lecli
def get(api_key_id):
    """
    Get a specific apikey
    """
    action, url = _url((api_key_id,))
    headers = api_utils.generate_headers('rw', method='GET', body='',
                                         action=action)
    try:
        response = requests.get(url, headers=headers)
        handle_api_key_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 47
0
Arquivo: api.py Projeto: rapid7/lecli
def add_existing_user(user_key):
    """
    Add a user that already exist to the current account.
    """
    action, url = _url(('users', user_key))
    headers = api_utils.generate_headers('owner', method='POST', action=action, body='')

    try:
        response = requests.request('POST', url, data='', headers=headers)
        handle_create_user_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 48
0
def delete_logset(logset_id):
    """
    Delete the logset with the given id
    """
    headers = api_utils.generate_headers('rw')

    try:
        response = requests.delete(_url((logset_id, ))[1], headers=headers)
        handle_response(response, 'Delete logset failed.\n', 204,
                        'Deleted logset with id: %s \n' % logset_id)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 49
0
Arquivo: api.py Projeto: rapid7/lecli
def delete_logset(logset_id):
    """
    Delete the logset with the given id
    """
    headers = api_utils.generate_headers('rw')

    try:
        response = requests.delete(_url((logset_id,))[1], headers=headers)
        handle_response(response, 'Delete logset failed.\n', 204,
                        'Deleted logset with id: %s \n' % logset_id)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 50
0
Arquivo: api.py Projeto: rapid7/lecli
def update_saved_query(query_id, name=None, statement=None, from_ts=None, to_ts=None,
                       time_range=None, logs=None):
    """
    Update a saved query with the given parameters.
    :param query_id: id of the saved query to be updated
    :param name: new name of the saved query
    :param statement: new leql statement of the saved query
    :param from_ts: new 'from' timestamp of the saved query
    :param to_ts: new 'to' timestamp of the saved query
    :param time_range: new time range of the saved query
    :param logs: colon(:) separated list of logs of the saved query
    """
    headers = api_utils.generate_headers('rw')
    params = {
        'saved_query': {
        }
    }

    if name:
        params['saved_query']['name'] = name

    if logs:
        params['saved_query']['logs'] = logs.split(':')

    if any([statement, from_ts, to_ts, time_range]):
        leql = {}
        if statement:
            leql['statement'] = statement
        if any([from_ts, to_ts, time_range]):
            during = {}
            if from_ts:
                during.update({'from': from_ts, 'to': None, 'time_range': None})
            if to_ts:
                during.update({'to': to_ts, 'time_range': None})
            if time_range:
                during.update({'time_range': time_range, 'from': None, 'to': None})
            leql['during'] = during
        params['saved_query']['leql'] = leql

    try:
        response = requests.patch(_url((query_id,))[1], json=params, headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Updating saved query failed.\n')
            _pretty_print_saved_query_error(response)
        elif response.status_code == 200:
            click.echo('Saved query with id %s updated.' % query_id)
            _pretty_print_saved_query(response.json()['saved_query'])
    except requests.exceptions.RequestException as error:
        click.echo(error)
        sys.exit(1)
Exemplo n.º 51
0
def update_saved_query(query_id, name=None, statement=None, from_ts=None, to_ts=None,
                       time_range=None, logs=None):
    """
    Update a saved query with the given parameters.
    :param query_id: id of the saved query to be updated
    :param name: new name of the saved query
    :param statement: new leql statement of the saved query
    :param from_ts: new 'from' timestamp of the saved query
    :param to_ts: new 'to' timestamp of the saved query
    :param time_range: new time range of the saved query
    :param logs: colon(:) separated list of logs of the saved query
    """
    headers = api_utils.generate_headers('rw')
    params = {
        'saved_query': {
        }
    }

    if name:
        params['saved_query']['name'] = name

    if logs:
        params['saved_query']['logs'] = logs.split(':')

    if any([statement, from_ts, to_ts, time_range]):
        leql = {}
        if statement:
            leql['statement'] = statement
        if any([from_ts, to_ts, time_range]):
            during = {}
            if from_ts:
                during.update({'from': from_ts, 'to': None, 'time_range': None})
            if to_ts:
                during.update({'to': to_ts, 'time_range': None})
            if time_range:
                during.update({'time_range': time_range, 'from': None, 'to': None})
            leql['during'] = during
        params['saved_query']['leql'] = leql

    try:
        response = requests.patch(_url() + "/" + query_id, json=params, headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Updating saved query failed, status code: %d' % response.status_code)
            _pretty_print_saved_query_error(response)
        elif response.status_code == 200:
            click.echo('Saved query with id %s updated.' % query_id)
            _pretty_print_saved_query(response.json()['saved_query'])
    except requests.exceptions.RequestException as error:
        click.echo(error)
        sys.exit(1)
Exemplo n.º 52
0
Arquivo: api.py Projeto: rapid7/lecli
def add_user_to_team(team_id, user_key):
    """
    Add user with the provided user_key to team with provided team_id.
    """
    headers = api_utils.generate_headers('rw')
    params = {'teamid': team_id}
    try:
        response = requests.get(_url((team_id,))[1], params=params, headers=headers)
        if response.status_code == 200:
            params = {
                'team': {
                    'name': response.json()['team']['name'],
                    'users': [
                        # we are doing a patch request here so it's safe to include the user_key
                        # we want to add here
                        {'id': user_key}
                    ]
                }
            }
            headers = api_utils.generate_headers('rw')
            try:
                response = requests.patch(_url((team_id,))[1], json=params, headers=headers)
                if response_utils.response_error(response):  # Check response has no errors
                    click.echo('Adding user to team with key: %s failed.' % team_id, err=True)
                    sys.exit(1)
                elif response.status_code == 200:
                    click.echo('Added user with key: %s to team.' % user_key)
            except requests.exceptions.RequestException as error:
                click.echo(error, err=True)
                sys.exit(1)
        elif response_utils.response_error(response):
            click.echo('Cannot find team. Adding user to team %s failed.' % team_id, err=True)
            sys.exit(1)
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 53
0
Arquivo: api.py Projeto: rapid7/lecli
def delete_saved_query(query_id):
    """
    Delete a specific saved query
    :param query_id: uuid of saved query to be deleted
    """
    headers = api_utils.generate_headers('rw')
    try:
        response = requests.delete(_url((query_id,))[1], headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Delete saved query failed.\n')
        elif response.status_code == 204:
            click.echo('Deleted saved query with id: %s' % query_id)
    except requests.exceptions.RequestException as error:
        click.echo(error)
        sys.exit(1)
Exemplo n.º 54
0
Arquivo: api.py Projeto: rapid7/lecli
def delete_team(team_id):
    """
    Delete a team with the provided team ID.
    """
    headers = api_utils.generate_headers('rw')

    try:
        response = requests.delete(_url((team_id,))[1], headers=headers)
        if response_utils.response_error(response):  # Check response has no errors
            click.echo('Delete team failed.', err=True)
            sys.exit(1)
        elif response.status_code == 204:
            click.echo('Deleted team with id: %s.' % team_id)
    except requests.exceptions.RequestException as error:
        click.echo(error, err=True)
        sys.exit(1)
Exemplo n.º 55
0
Arquivo: api.py Projeto: rapid7/lecli
def delete_user(user_key):
    """
    Delete a user from the current account.
    """
    action, url = _url(('users', user_key))
    headers = api_utils.generate_headers('owner', method='DELETE', action=action, body='')

    try:
        response = requests.request('DELETE', url, data='', headers=headers)
        if response_utils.response_error(response) is True:  # Check response has no errors
            sys.stderr.write('Delete user failed, status code: %s' % response.status_code)
            sys.exit(1)
        elif response.status_code == 204:
            print 'Deleted user'
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 56
0
Arquivo: api.py Projeto: rapid7/lecli
def delete(api_key_id):
    """
    Delete an api key with the provided ID
    """
    action, url = _url((api_key_id,))
    headers = api_utils.generate_headers('owner', method='DELETE', body='', action=action)

    try:
        response = requests.delete(url, headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Deleting api key failed.')
            sys.exit(1)
        elif response.status_code == 204:
            sys.stdout.write('Deleted api key with id: %s \n' % api_key_id)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 57
0
Arquivo: api.py Projeto: rapid7/lecli
def get_usage(start, end):
    """
    Get usage information for the account between start and end dates.
    """
    headers = api_utils.generate_headers('rw')
    params = {'from': start,
              'to': end}
    try:
        response = requests.get(_url()[1], params=params, headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write("Getting account usage failed. Status code %s"
                             % response.status_code)
            sys.exit(1)
        else:
            _handle_get_usage_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 58
0
Arquivo: api.py Projeto: rapid7/lecli
def rename_logset(logset_id, logset_name):
    """
    Rename a given logset
    """
    headers = api_utils.generate_headers('ro')

    try:
        response = requests.get(_url((logset_id,))[1], headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Rename logset failed.\n')
            sys.exit(1)
        elif response.status_code == 200:
            params = response.json()
            params['logset']['name'] = logset_name
            replace_logset(logset_id, params)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 59
0
Arquivo: api.py Projeto: rapid7/lecli
def delete_log(logset_id, log_id):
    """
    Delete a log from the logset
    """
    headers = api_utils.generate_headers('ro')
    try:
        response = requests.get(_url((logset_id,))[1], headers=headers)
        if response_utils.response_error(response):
            sys.stderr.write('Delete log %s from logset %s failed\n'
                             % (log_id, logset_id))
            sys.exit(1)
        elif response.status_code == 200:
            existing_logset = response.json()
            params = extract_log_from_logset(existing_logset, log_id)
            replace_logset(logset_id, params)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)
Exemplo n.º 60
0
Arquivo: api.py Projeto: rapid7/lecli
def create(payload):
    """
    Create an api key with the provided ID
    """
    action, url = _url()

    headers = api_utils.generate_headers('owner', method='POST', body=json.dumps(payload),
                                         action=action)

    try:
        response = requests.post(url, headers=headers, json=payload)
        if response_utils.response_error(response):
            sys.stderr.write('Create api key failed.')
            sys.exit(1)
        elif response.status_code == 201:
            handle_api_key_response(response)
    except requests.exceptions.RequestException as error:
        sys.stderr.write(error)
        sys.exit(1)