Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merge devel changes into main #511

Merged
merged 25 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
9d499f1
fix(kernel_support_info): adding new module that supports querying ke…
carlosmmatos Apr 11, 2024
0edc365
fix: update doc fragment to separate sort option
carlosmmatos Apr 11, 2024
5ceae44
fix: fixes ansible-test found issues
carlosmmatos Apr 11, 2024
d6829e6
chore(kernel_support_info): add changelog fragment
carlosmmatos Apr 11, 2024
8aaafef
Merge pull request #499 from carlosmmatos/kernel-compat-module
redhatrises Apr 11, 2024
0580df7
feat: add new sensor update builds info module
carlosmmatos Apr 27, 2024
020ea95
chore: minor updates for galaxy and gitignore
carlosmmatos Apr 27, 2024
07d4ece
chore: adding changelog fragment for new module
carlosmmatos Apr 27, 2024
f473671
Merge pull request #500 from carlosmmatos/sensor-update-builds-info
redhatrises Apr 27, 2024
fccfeaa
feat: new host_ids lookup plugin
carlosmmatos Apr 29, 2024
e284840
chore: add chagelog + update readme
carlosmmatos Apr 29, 2024
6721300
chore: fix linting issues
carlosmmatos Apr 29, 2024
fc12db2
Merge pull request #503 from carlosmmatos/falcon-host-lookup
redhatrises Apr 29, 2024
e3454bb
feat: add new host_info module
carlosmmatos Apr 30, 2024
735d827
chore: fix return docstring due to ansible-test issues
carlosmmatos Apr 30, 2024
d671aa1
chore: add changelog + update readme
carlosmmatos Apr 30, 2024
e43449f
chore: add description for using lookup plugin
carlosmmatos Apr 30, 2024
255446c
Merge pull request #504 from carlosmmatos/host-info-module
redhatrises Apr 30, 2024
53345ae
docs: update description to include ref to new lookup
carlosmmatos Apr 30, 2024
0838e05
Merge pull request #505 from carlosmmatos/update-host-descriptions
redhatrises Apr 30, 2024
e26528f
docs: update lookup descriptions (#506)
carlosmmatos Apr 30, 2024
3f7ec2a
feat: add new lookup plugin to fetch maintenance token (#507)
carlosmmatos Apr 30, 2024
271960d
Minor updates for 4.4.0 prep (#510)
carlosmmatos May 2, 2024
45d8caf
chore(ci): update core version of ansible-test
carlosmmatos May 6, 2024
28b6574
chore(docs): update readme to reflect new ansible core reqs
carlosmmatos May 6, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ansible-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,6 @@ jobs:
- name: Perform sanity testing with ansible-test
uses: ansible-community/ansible-test-gh-action@release/v1
with:
ansible-core-version: stable-2.14
ansible-core-version: stable-2.15
testing-type: sanity
pre-test-cmd: 'rm -rf .devcontainer/ .git* .pre-commit-config.yaml'
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ changelogs/.plugin-cache.yaml
__pycache__/
/**venv
/.vscode
html/
ansible.cfg
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ The Falcon Ansible Collection serves as a comprehensive toolkit for streamlining

## Ansible version compatibility

Tested with the Ansible Core >= 2.14.0 versions, and the current development version of Ansible. Ansible Core versions before 2.14.0 are not supported.
Tested with the Ansible Core >= 2.15.0 versions, and the current development version of Ansible. Ansible Core versions before 2.15.0 are not supported.

## Python version compatibility

Expand Down Expand Up @@ -44,8 +44,11 @@ Name | Description
[crowdstrike.falcon.cid_info](https://crowdstrike.github.io/ansible_collection_falcon/cid_info_module.html)|Get CID with checksum
[crowdstrike.falcon.host_contain](https://crowdstrike.github.io/ansible_collection_falcon/host_contain_module.html)|Network contain hosts in Falcon
[crowdstrike.falcon.host_hide](https://crowdstrike.github.io/ansible_collection_falcon/host_hide_module.html)|Hide/Unhide hosts from the Falcon console
[crowdstrike.falcon.host_info](https://crowdstrike.github.io/ansible_collection_falcon/host_info_module.html)|Get information about Falcon hosts
[crowdstrike.falcon.kernel_support_info](https://crowdstrike.github.io/ansible_collection_falcon/kernel_support_info_module.html)|Get information about kernels supported by the Falcon Sensor for Linux
[crowdstrike.falcon.sensor_download](https://crowdstrike.github.io/ansible_collection_falcon/sensor_download_module.html)|Download Falcon Sensor Installer
[crowdstrike.falcon.sensor_download_info](https://crowdstrike.github.io/ansible_collection_falcon/sensor_download_info_module.html)|Get information about Falcon Sensor Installers
[crowdstrike.falcon.sensor_update_builds_info](https://crowdstrike.github.io/ansible_collection_falcon/sensor_update_builds_info_module.html)|Get a list of available sensor build versions
[crowdstrike.falcon.sensor_update_policy_info](https://crowdstrike.github.io/ansible_collection_falcon/sensor_update_policy_info_module.html)|Get information about Falcon Update Sensor Policies

### Inventory plugins
Expand All @@ -54,6 +57,13 @@ Name | Description
--- | ---
[crowdstrike.falcon.falcon_discover](https://crowdstrike.github.io/ansible_collection_falcon/falcon_discover_inventory.html)|Falcon Discover inventory source
[crowdstrike.falcon.falcon_hosts](https://crowdstrike.github.io/ansible_collection_falcon/falcon_hosts_inventory.html)|Falcon Hosts inventory source

### Lookup plugins

Name | Description
--- | ---
[crowdstrike.falcon.host_ids](https://crowdstrike.github.io/ansible_collection_falcon/host_ids_lookup.html)|Fetch host IDs in Falcon
[crowdstrike.falcon.maintenance_token](https://crowdstrike.github.io/ansible_collection_falcon/maintenance_token_lookup.html)|Fetch maintenance token
<!--end collection content-->

<!--start eda content-->
Expand Down
2 changes: 2 additions & 0 deletions changelogs/fragments/host_ids.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
minor_changes:
- host_ids - adds a new lookup plugin for getting host IDs (https://github.com/CrowdStrike/ansible_collection_falcon/pull/503)
2 changes: 2 additions & 0 deletions changelogs/fragments/host_info.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
minor_changes:
- host_info - adds new module for retrieving host details (https://github.com/CrowdStrike/ansible_collection_falcon/pull/504)
2 changes: 2 additions & 0 deletions changelogs/fragments/kernel_support_info.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
minor_changes:
- kernel_support_info - adds new module for kernel support information (https://github.com/CrowdStrike/ansible_collection_falcon/pull/499)
2 changes: 2 additions & 0 deletions changelogs/fragments/sensor_update_builds_info.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
minor_changes:
- sensor_update_builds_info - adds new module for retrieving sensor build versions (https://github.com/CrowdStrike/ansible_collection_falcon/pull/500)
5 changes: 2 additions & 3 deletions galaxy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ authors:

# A short summary description of the collection
description: >
A collection of roles developed by CrowdStrike for the
installation, configuration, and verification of CrowdStrike's software.
The Falcon Ansible Collection serves as a comprehensive toolkit for streamlining your interactions
with the CrowdStrike Falcon platform.

# Either a single license or a list of licenses for content inside of a collection. Ansible Galaxy currently only
# accepts L(SPDX,https://spdx.org/licenses/) licenses. This key is mutually exclusive with 'license_file'
Expand Down Expand Up @@ -74,5 +74,4 @@ build_ignore:
- '.devcontainer'
- '.git*'
- '.pre-commit-config.yaml'
- 'docs'
- 'tox.ini'
2 changes: 1 addition & 1 deletion meta/runtime.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
---
requires_ansible: ">=2.14.0"
requires_ansible: ">=2.15.0"
6 changes: 5 additions & 1 deletion plugins/doc_fragments/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ class ModuleDocFragment(object):
filter:
description:
- The filter expression that should be used to limit the results using FQL (Falcon Query Language) syntax.
- See the return values for more information about the available filters that can be used.
- See the return values or CrowdStrike docs for more information about the available filters that can be used.
type: str
limit:
description:
Expand All @@ -28,6 +28,10 @@ class ModuleDocFragment(object):
description:
- The offset to start retrieving records from.
type: int
"""
# Not all endpoints will have a sort option
SORT = r"""
options:
sort:
description:
- The property to sort by in FQL (Falcon Query Language) syntax.
Expand Down
198 changes: 198 additions & 0 deletions plugins/lookup/host_ids.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
# -*- coding: utf-8 -*-

# Copyright: (c) 2024, CrowdStrike Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function

__metaclass__ = type

DOCUMENTATION = r"""
---
name: host_ids

short_description: fetch host IDs (AIDs)

version_added: "4.4.0"

description:
- This lookup returns a list of host IDs (AIDs) which match the search criteria.
- You can use optional FQL filters in your requests to find host IDs based on specific
attributes, such as platform, hostname, or IP.
- Can be used for other modules that require a list of host IDs as input.

options:
_terms:
description:
- The filter expression that should be used to limit the results using FQL (Falcon Query Language) syntax.
- See the L(Falcon documentation,https://falcon.crowdstrike.com/documentation/page/c0b16f1b/host-and-host-group-management-apis#qadd6f8f)
for more information about the available filters.

extends_documentation_fragment:
- crowdstrike.falcon.credentials

notes:
- This plugin will automatically handle pagination for you, so you do not need to worry about it.
- You can avoid escaping double quotes by using a multiline string or setting a variable. See examples.

requirements:
- Hosts [B(READ)] API scope

author:
- Carlos Matos (@carlosmmatos)
"""

EXAMPLES = r"""
- name: Print all hosts IDs
ansible.builtin.debug:
msg: "{{ lookup('crowdstrike.falcon.host_ids', '') }}"

- name: Print all Windows hosts IDs (escaped double quotes)
ansible.builtin.debug:
msg: "{{ lookup('crowdstrike.falcon.host_ids', 'platform_name:\"Windows\"') }}"

- name: Print all Linux hosts IDs in reduced functionality mode (multiline string)
ansible.builtin.debug:
msg: >
{{
lookup('crowdstrike.falcon.host_ids',
'platform_name:"Linux"
+ reduced_functionality_mode:"yes"')
}}

- name: Hide stale devices that haven't been seen in 15 days (using a filter variable)
crowdstrike.falcon.host_hide:
hidden: true
hosts: "{{ lookup('crowdstrike.falcon.host_ids', stale_filter) }}"
vars:
stale_filter: 'last_seen:<="now-15d"'
"""

RETURN = r"""
_raw:
description:
- A list of host IDs (AIDs) that match the search criteria.
type: list
returned: success
elements: str
"""

import os
import traceback
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.utils.display import Display


FALCONPY_IMPORT_ERROR = None
try:
from falconpy import Hosts
from falconpy._version import _VERSION

HAS_FALCONPY = True
except ImportError:
HAS_FALCONPY = False
FALCONPY_IMPORT_ERROR = traceback.format_exc()

display = Display()


class LookupModule(LookupBase):
"""Lookup plugin for fetching host IDs based on filter expressions."""

def _credential_setup(self):
"""Setup credentials for FalconPy."""
cred_mapping = {
"client_id": "FALCON_CLIENT_ID",
"client_secret": "FALCON_CLIENT_SECRET",
"member_cid": "FALCON_MEMBER_CID",
"cloud": "FALCON_CLOUD",
}

creds = {}
for key, env in cred_mapping.items():
value = self.get_option(key) or os.getenv(env)
if value:
if key == "cloud":
self._verify_cloud(value)
creds["base_url"] = value
else:
creds[key] = value

# Make sure we have client_id and client_secret
if "client_id" not in creds or "client_secret" not in creds:
raise AnsibleError(
"You must provide a client_id and client_secret to authenticate to the Falcon API."
)

return creds

def _verify_cloud(self, cloud):
"""Verify the cloud region."""
valid_clouds = ["us-1", "us-2", "eu-1", "us-gov-1"]
if cloud not in valid_clouds:
raise AnsibleError(
f"Invalid cloud region: '{cloud}'. Valid values are {', '.join(valid_clouds)}"
)

def _authenticate(self):
"""Authenticate to the CrowdStrike Falcon API."""
creds = self._credential_setup()

return Hosts(**creds)

def _get_device_ids(self, falcon, term):
"""Fetch host IDs based on the provided filter expression."""
max_limit = 5000
host_ids = []
running = True
offset = None
while running:
host_lookup = falcon.query_devices_by_filter_scroll(filter=term, offset=offset, limit=max_limit)
if host_lookup["status_code"] != 200:
raise AnsibleError(
f"Unable to query hosts: {host_lookup['body']['errors']}"
)

if host_lookup["body"]["resources"]:
host_ids.extend(host_lookup["body"]["resources"])
else:
return host_ids

# Check if we need to continue
offset = host_lookup["body"]["meta"]["pagination"]["offset"]
if host_lookup["body"]["meta"]["pagination"]["total"] <= len(host_ids):
running = False

return host_ids

def run(self, terms, variables=None, **kwargs):
"""Fetch host IDs based on the provided filter expression."""

# Check if the 'falconpy' library is installed
if not HAS_FALCONPY:
raise AnsibleError(
"The 'crowdstrike.falcon.host_ids' lookup cannot be run because the 'falconpy' library is not installed."
)

# Check if the 'falconpy' library is compatible
if _VERSION < "1.3.0":
raise AnsibleError(
f"Unsupported FalconPy version: {_VERSION}. Upgrade to 1.3.0 or higher."
)

self.set_options(var_options=variables, direct=kwargs)

falcon = self._authenticate()
ret = []

for term in terms:
display.debug(f"Fetching host IDs with filter expression: {term}")
try:
# Fetch host IDs based on the provided filter expression
display.vvv(f"FQL Filter used: {term}")
ret.append(self._get_device_ids(falcon, term))
except Exception as e: # pylint: disable=broad-except
raise AnsibleError(f"Failed to fetch host IDs: {e}") from e

return ret
Loading
Loading