| 1 |
# Copyright (c) 2017 Ansible Project |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
from __future__ import annotations |
| 6 |
|
| 7 |
DOCUMENTATION = r""" |
| 8 |
author: Unknown (!UNKNOWN) |
| 9 |
name: nmap |
| 10 |
short_description: Uses nmap to find hosts to target |
| 11 |
description: |
| 12 |
- Uses a YAML configuration file with a valid YAML extension. |
| 13 |
extends_documentation_fragment: |
| 14 |
- ansible.builtin.constructed |
| 15 |
- ansible.builtin.inventory_cache |
| 16 |
requirements: |
| 17 |
- nmap CLI installed |
| 18 |
options: |
| 19 |
plugin: |
| 20 |
description: Token that ensures this is a source file for the P(community.general.nmap#inventory) plugin. |
| 21 |
type: string |
| 22 |
required: true |
| 23 |
choices: ['nmap', 'community.general.nmap'] |
| 24 |
sudo: |
| 25 |
description: Set to V(true) to execute a C(sudo nmap) plugin scan. |
| 26 |
version_added: 4.8.0 |
| 27 |
default: false |
| 28 |
type: boolean |
| 29 |
address: |
| 30 |
description: Network IP or range of IPs to scan, you can use a simple range (10.2.2.15-25) or CIDR notation. |
| 31 |
type: string |
| 32 |
required: true |
| 33 |
env: |
| 34 |
- name: ANSIBLE_NMAP_ADDRESS |
| 35 |
version_added: 6.6.0 |
| 36 |
exclude: |
| 37 |
description: |
| 38 |
- List of addresses to exclude. |
| 39 |
- For example V(10.2.2.15-25) or V(10.2.2.15,10.2.2.16). |
| 40 |
type: list |
| 41 |
elements: string |
| 42 |
env: |
| 43 |
- name: ANSIBLE_NMAP_EXCLUDE |
| 44 |
version_added: 6.6.0 |
| 45 |
port: |
| 46 |
description: |
| 47 |
- Only scan specific port or port range (C(-p)). |
| 48 |
- For example, you could pass V(22) for a single port, V(1-65535) for a range of ports, or V(U:53,137,T:21-25,139,8080,S:9) |
| 49 |
to check port 53 with UDP, ports 21-25 with TCP, port 9 with SCTP, and ports 137, 139, and 8080 with all. |
| 50 |
type: string |
| 51 |
version_added: 6.5.0 |
| 52 |
ports: |
| 53 |
description: Enable/disable scanning ports. |
| 54 |
type: boolean |
| 55 |
default: true |
| 56 |
ipv4: |
| 57 |
description: Use IPv4 type addresses. |
| 58 |
type: boolean |
| 59 |
default: true |
| 60 |
ipv6: |
| 61 |
description: Use IPv6 type addresses. |
| 62 |
type: boolean |
| 63 |
default: true |
| 64 |
udp_scan: |
| 65 |
description: |
| 66 |
- Scan using UDP. |
| 67 |
- Depending on your system you might need O(sudo=true) for this to work. |
| 68 |
type: boolean |
| 69 |
default: false |
| 70 |
version_added: 6.1.0 |
| 71 |
icmp_timestamp: |
| 72 |
description: |
| 73 |
- Scan using ICMP Timestamp (C(-PP)). |
| 74 |
- Depending on your system you might need O(sudo=true) for this to work. |
| 75 |
type: boolean |
| 76 |
default: false |
| 77 |
version_added: 6.1.0 |
| 78 |
open: |
| 79 |
description: Only scan for open (or possibly open) ports. |
| 80 |
type: boolean |
| 81 |
default: false |
| 82 |
version_added: 6.5.0 |
| 83 |
dns_resolve: |
| 84 |
description: Whether to always (V(true)) or never (V(false)) do DNS resolution. |
| 85 |
type: boolean |
| 86 |
default: false |
| 87 |
version_added: 6.1.0 |
| 88 |
dns_servers: |
| 89 |
description: Specify which DNS servers to use for name resolution. |
| 90 |
type: list |
| 91 |
elements: string |
| 92 |
version_added: 10.5.0 |
| 93 |
use_arp_ping: |
| 94 |
description: Whether to always (V(true)) use the quick ARP ping or (V(false)) a slower but more reliable method. |
| 95 |
type: boolean |
| 96 |
default: true |
| 97 |
version_added: 7.4.0 |
| 98 |
skip_host_discovery: |
| 99 |
description: |
| 100 |
- Skip nmap host discovery phase and treat all hosts as online (C(-Pn)). |
| 101 |
- Useful when scanning remote hosts over VPN or through firewalls where nmap's default discovery probes |
| 102 |
(TCP SYN to ports 80/443) are blocked but the target port is open. |
| 103 |
- When V(false) (default), nmap performs host discovery before port scanning, which may send packets |
| 104 |
to ports 80 and 443 regardless of the O(port) setting. |
| 105 |
type: boolean |
| 106 |
default: false |
| 107 |
version_added: 13.0.0 |
| 108 |
set_name_variable: |
| 109 |
description: |
| 110 |
- Set the C(name) variable for each host. |
| 111 |
- When V(true), sets the C(name) variable which may trigger a warning about using a reserved name. |
| 112 |
- Set to V(false) to avoid the warning when C(name) is not needed as a variable. |
| 113 |
type: boolean |
| 114 |
default: true |
| 115 |
version_added: 13.0.0 |
| 116 |
notes: |
| 117 |
- At least one of O(ipv4) or O(ipv6) is required to be V(true); both can be V(true), but they cannot both be V(false). |
| 118 |
- 'TODO: add OS fingerprinting.' |
| 119 |
""" |
| 120 |
EXAMPLES = r""" |
| 121 |
--- |
| 122 |
# inventory.config file in YAML format |
| 123 |
plugin: community.general.nmap |
| 124 |
strict: false |
| 125 |
address: 192.168.0.0/24 |
| 126 |
|
| 127 |
--- |
| 128 |
# a sudo nmap scan to fully use nmap scan power. |
| 129 |
plugin: community.general.nmap |
| 130 |
sudo: true |
| 131 |
strict: false |
| 132 |
address: 192.168.0.0/24 |
| 133 |
|
| 134 |
--- |
| 135 |
# an nmap scan specifying ports and classifying results to an inventory group |
| 136 |
plugin: community.general.nmap |
| 137 |
address: 192.168.0.0/24 |
| 138 |
exclude: 192.168.0.1, web.example.com |
| 139 |
port: 22, 443 |
| 140 |
groups: |
| 141 |
web_servers: "ports | selectattr('port', 'equalto', '443')" |
| 142 |
|
| 143 |
--- |
| 144 |
# an nmap scan without setting the 'name' variable to avoid warnings |
| 145 |
plugin: community.general.nmap |
| 146 |
address: 192.168.0.0/24 |
| 147 |
set_name_variable: false |
| 148 |
""" |
| 149 |
|
| 150 |
import os |
| 151 |
import re |
| 152 |
from subprocess import PIPE, Popen |
| 153 |
|
| 154 |
from ansible import constants as C |
| 155 |
from ansible.errors import AnsibleParserError |
| 156 |
from ansible.module_utils.common.process import get_bin_path |
| 157 |
from ansible.module_utils.common.text.converters import to_native, to_text |
| 158 |
from ansible.plugins.inventory import BaseInventoryPlugin, Cacheable, Constructable |
| 159 |
|
| 160 |
from ansible_collections.community.general.plugins.plugin_utils._unsafe import make_unsafe |
| 161 |
|
| 162 |
|
| 163 |
class InventoryModule(BaseInventoryPlugin, Constructable, Cacheable): |
| 164 |
NAME = "community.general.nmap" |
| 165 |
find_host = re.compile(r"^Nmap scan report for ([\w,.,-]+)(?: \(([\w,.,:,\[,\]]+)\))?") |
| 166 |
find_port = re.compile(r"^(\d+)/(\w+)\s+(\w+)\s+(\w+)") |
| 167 |
|
| 168 |
def __init__(self): |
| 169 |
self._nmap = None |
| 170 |
super().__init__() |
| 171 |
|
| 172 |
def _populate(self, hosts): |
| 173 |
# Use constructed if applicable |
| 174 |
strict = self.get_option("strict") |
| 175 |
set_name_variable = self.get_option("set_name_variable") |
| 176 |
|
| 177 |
for host in hosts: |
| 178 |
host = make_unsafe(host) |
| 179 |
hostname = host["name"] |
| 180 |
self.inventory.add_host(hostname) |
| 181 |
for var, value in host.items(): |
| 182 |
if var == "name" and not set_name_variable: |
| 183 |
continue |
| 184 |
self.inventory.set_variable(hostname, var, value) |
| 185 |
|
| 186 |
# Composed variables |
| 187 |
self._set_composite_vars(self.get_option("compose"), host, hostname, strict=strict) |
| 188 |
|
| 189 |
# Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group |
| 190 |
self._add_host_to_composed_groups(self.get_option("groups"), host, hostname, strict=strict) |
| 191 |
|
| 192 |
# Create groups based on variable values and add the corresponding hosts to it |
| 193 |
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), host, hostname, strict=strict) |
| 194 |
|
| 195 |
def verify_file(self, path): |
| 196 |
valid = False |
| 197 |
if super().verify_file(path): |
| 198 |
file_name, ext = os.path.splitext(path) |
| 199 |
|
| 200 |
if not ext or ext in C.YAML_FILENAME_EXTENSIONS: |
| 201 |
valid = True |
| 202 |
|
| 203 |
return valid |
| 204 |
|
| 205 |
def parse(self, inventory, loader, path, cache=True): |
| 206 |
try: |
| 207 |
self._nmap = get_bin_path("nmap") |
| 208 |
except ValueError as e: |
| 209 |
raise AnsibleParserError(f"nmap inventory plugin requires the nmap cli tool to work: {e}") from e |
| 210 |
|
| 211 |
super().parse(inventory, loader, path, cache=cache) |
| 212 |
|
| 213 |
self._read_config_data(path) |
| 214 |
|
| 215 |
cache_key = self.get_cache_key(path) |
| 216 |
|
| 217 |
# cache may be True or False at this point to indicate if the inventory is being refreshed |
| 218 |
# get the user's cache option too to see if we should save the cache if it is changing |
| 219 |
user_cache_setting = self.get_option("cache") |
| 220 |
|
| 221 |
# read if the user has caching enabled and the cache isn't being refreshed |
| 222 |
attempt_to_read_cache = user_cache_setting and cache |
| 223 |
# update if the user has caching enabled and the cache is being refreshed; update this value to True if the cache has expired below |
| 224 |
cache_needs_update = user_cache_setting and not cache |
| 225 |
|
| 226 |
if attempt_to_read_cache: |
| 227 |
try: |
| 228 |
results = self._cache[cache_key] |
| 229 |
except KeyError: |
| 230 |
# This occurs if the cache_key is not in the cache or if the cache_key expired, so the cache needs to be updated |
| 231 |
cache_needs_update = True |
| 232 |
|
| 233 |
if not user_cache_setting or cache_needs_update: |
| 234 |
# setup command |
| 235 |
cmd = [self._nmap] |
| 236 |
|
| 237 |
if self.get_option("sudo"): |
| 238 |
cmd.insert(0, "sudo") |
| 239 |
|
| 240 |
if self.get_option("port"): |
| 241 |
cmd.append("-p") |
| 242 |
cmd.append(self.get_option("port")) |
| 243 |
|
| 244 |
if not self.get_option("ports"): |
| 245 |
cmd.append("-sP") |
| 246 |
|
| 247 |
if self.get_option("ipv4") and not self.get_option("ipv6"): |
| 248 |
cmd.append("-4") |
| 249 |
elif self.get_option("ipv6") and not self.get_option("ipv4"): |
| 250 |
cmd.append("-6") |
| 251 |
elif not self.get_option("ipv6") and not self.get_option("ipv4"): |
| 252 |
raise AnsibleParserError("One of ipv4 or ipv6 must be enabled for this plugin") |
| 253 |
|
| 254 |
if self.get_option("exclude"): |
| 255 |
cmd.append("--exclude") |
| 256 |
cmd.append(",".join(self.get_option("exclude"))) |
| 257 |
|
| 258 |
if self.get_option("dns_resolve"): |
| 259 |
cmd.append("-n") |
| 260 |
|
| 261 |
if self.get_option("dns_servers"): |
| 262 |
cmd.append("--dns-servers") |
| 263 |
cmd.append(",".join(self.get_option("dns_servers"))) |
| 264 |
|
| 265 |
if self.get_option("udp_scan"): |
| 266 |
cmd.append("-sU") |
| 267 |
|
| 268 |
if self.get_option("icmp_timestamp"): |
| 269 |
cmd.append("-PP") |
| 270 |
|
| 271 |
if self.get_option("open"): |
| 272 |
cmd.append("--open") |
| 273 |
|
| 274 |
if not self.get_option("use_arp_ping"): |
| 275 |
cmd.append("--disable-arp-ping") |
| 276 |
|
| 277 |
if self.get_option("skip_host_discovery"): |
| 278 |
cmd.append("-Pn") |
| 279 |
|
| 280 |
cmd.append(self.get_option("address")) |
| 281 |
try: |
| 282 |
# execute |
| 283 |
p = Popen(cmd, stdout=PIPE, stderr=PIPE) |
| 284 |
stdout, stderr = p.communicate() |
| 285 |
if p.returncode != 0: |
| 286 |
raise AnsibleParserError(f"Failed to run nmap, rc={p.returncode}: {to_native(stderr)}") |
| 287 |
|
| 288 |
# parse results |
| 289 |
host = None |
| 290 |
ip = None |
| 291 |
ports = [] |
| 292 |
results = [] |
| 293 |
|
| 294 |
try: |
| 295 |
t_stdout = to_text(stdout, errors="surrogate_or_strict") |
| 296 |
except UnicodeError as e: |
| 297 |
raise AnsibleParserError(f"Invalid (non unicode) input returned: {e}") from e |
| 298 |
|
| 299 |
for line in t_stdout.splitlines(): |
| 300 |
hits = self.find_host.match(line) |
| 301 |
if hits: |
| 302 |
if host is not None and ports: |
| 303 |
results[-1]["ports"] = ports |
| 304 |
|
| 305 |
# if dns only shows arpa, just use ip instead as hostname |
| 306 |
if hits.group(1).endswith(".in-addr.arpa"): |
| 307 |
host = hits.group(2) |
| 308 |
else: |
| 309 |
host = hits.group(1) |
| 310 |
|
| 311 |
# if no reverse dns exists, just use ip instead as hostname |
| 312 |
if hits.group(2) is not None: |
| 313 |
ip = hits.group(2) |
| 314 |
else: |
| 315 |
ip = hits.group(1) |
| 316 |
|
| 317 |
if host is not None: |
| 318 |
# update inventory |
| 319 |
results.append(dict()) |
| 320 |
results[-1]["name"] = host |
| 321 |
results[-1]["ip"] = ip |
| 322 |
ports = [] |
| 323 |
continue |
| 324 |
|
| 325 |
host_ports = self.find_port.match(line) |
| 326 |
if host is not None and host_ports: |
| 327 |
ports.append( |
| 328 |
{ |
| 329 |
"port": host_ports.group(1), |
| 330 |
"protocol": host_ports.group(2), |
| 331 |
"state": host_ports.group(3), |
| 332 |
"service": host_ports.group(4), |
| 333 |
} |
| 334 |
) |
| 335 |
continue |
| 336 |
|
| 337 |
# if any leftovers |
| 338 |
if host and ports: |
| 339 |
results[-1]["ports"] = ports |
| 340 |
|
| 341 |
except Exception as e: |
| 342 |
raise AnsibleParserError(f"failed to parse {to_native(path)}: {e} ") from e |
| 343 |
|
| 344 |
if cache_needs_update: |
| 345 |
self._cache[cache_key] = results |
| 346 |
|
| 347 |
self._populate(results) |