Debian Codegraph @

ansible_collections/community/hrobot/plugins/modules/firewall.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2019 Felix Fontein <[email protected]>
5 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
6 # SPDX-License-Identifier: GPL-3.0-or-later
7
8 from __future__ import absolute_import, division, print_function
9 __metaclass__ = type
10
11
12 DOCUMENTATION = r"""
13 module: firewall
14 short_description: Manage Hetzner's dedicated server firewall
15 author:
16 - Felix Fontein (@felixfontein)
17 description:
18 - Manage Hetzner's dedicated server firewall.
19 - Note that idempotency check for TCP flags simply compares strings and does not try to interpret the rules. This might
20 change in the future.
21 requirements:
22 - ipaddress
23 seealso:
24 - name: Firewall documentation
25 description: Hetzner's documentation on the stateless firewall for dedicated servers.
26 link: https://docs.hetzner.com/robot/dedicated-server/firewall/
27 - module: community.hrobot.firewall_info
28 description: Retrieve information on firewall configuration.
29 extends_documentation_fragment:
30 - community.hrobot.robot
31 - community.hrobot.attributes
32 - community.hrobot.attributes.actiongroup_robot
33
34 attributes:
35 action_group:
36 version_added: 1.6.0
37 check_mode:
38 support: full
39 diff_mode:
40 support: full
41 idempotent:
42 support: full
43
44 options:
45 server_ip:
46 description:
47 - The server's main IP address.
48 - Exactly one of O(server_ip) and O(server_number) must be specified.
49 - Note that Hetzner deprecated identifying the server's firewall by the server's main IP. Using this option can thus
50 stop working at any time in the future. Use O(server_number) instead.
51 type: str
52 server_number:
53 description:
54 - The server's number.
55 - Exactly one of O(server_ip) and O(server_number) must be specified.
56 type: int
57 version_added: 1.8.0
58 filter_ipv6:
59 description:
60 - Whether to filter IPv6 traffic as well.
61 - IPv4 traffic is always filtered, IPv6 traffic filtering needs to be explicitly enabled.
62 type: bool
63 version_added: 1.8.0
64 port:
65 description:
66 - Switch port of firewall.
67 type: str
68 choices: [main, kvm]
69 default: main
70 state:
71 description:
72 - Status of the firewall.
73 - Firewall is active if state is V(present), and disabled if state is V(absent).
74 type: str
75 default: present
76 choices: [present, absent]
77 allowlist_hos:
78 description:
79 - Whether Hetzner services have access.
80 type: bool
81 aliases:
82 - whitelist_hos
83 rules:
84 description:
85 - Firewall rules.
86 type: dict
87 suboptions:
88 input:
89 description:
90 - Input firewall rules.
91 type: list
92 elements: dict
93 suboptions:
94 name:
95 description:
96 - Name of the firewall rule.
97 - Note that Hetzner restricts the characters that can be used for rule names. At the moment, only letters C(a-z),
98 C(A-Z), space, and the symbols C(.), C(-), C(+), C(_), and C(@) are allowed.
99 type: str
100 ip_version:
101 description:
102 - Internet protocol version.
103 - Leave away to filter both protocols. Note that in that case, none of O(rules.input[].dst_ip), O(rules.input[].src_ip),
104 or O(rules.input[].protocol) can be specified.
105 type: str
106 dst_ip:
107 description:
108 - Destination IP address or subnet address.
109 - CIDR notation.
110 type: str
111 dst_port:
112 description:
113 - Destination port or port range.
114 type: str
115 src_ip:
116 description:
117 - Source IP address or subnet address.
118 - CIDR notation.
119 type: str
120 src_port:
121 description:
122 - Source port or port range.
123 type: str
124 protocol:
125 description:
126 - Protocol above IP layer.
127 type: str
128 tcp_flags:
129 description:
130 - TCP flags or logical combination of flags.
131 - Flags supported by Hetzner are V(syn), V(fin), V(rst), V(psh) and V(urg).
132 - They can be combined with V(|) (logical or) and V(&) (logical and).
133 - See L(the documentation,https://wiki.hetzner.de/index.php/Robot_Firewall/en#Parameter) for more information.
134 type: str
135 action:
136 description:
137 - Action if rule matches.
138 required: true
139 type: str
140 choices: [accept, discard]
141 output:
142 description:
143 - Output firewall rules.
144 type: list
145 elements: dict
146 version_added: 1.8.0
147 suboptions:
148 name:
149 description:
150 - Name of the firewall rule.
151 - Note that Hetzner restricts the characters that can be used for rule names. At the moment, only letters C(a-z),
152 C(A-Z), space, and the symbols C(.), C(-), C(+), C(_), and C(@) are allowed.
153 type: str
154 ip_version:
155 description:
156 - Internet protocol version.
157 - Leave away to filter both protocols. Note that in that case, none of O(rules.output[].dst_ip), O(rules.output[].src_ip),
158 or O(rules.output[].protocol) can be specified.
159 type: str
160 dst_ip:
161 description:
162 - Destination IP address or subnet address.
163 - CIDR notation.
164 type: str
165 dst_port:
166 description:
167 - Destination port or port range.
168 type: str
169 src_ip:
170 description:
171 - Source IP address or subnet address.
172 - CIDR notation.
173 type: str
174 src_port:
175 description:
176 - Source port or port range.
177 type: str
178 protocol:
179 description:
180 - Protocol above IP layer.
181 type: str
182 tcp_flags:
183 description:
184 - TCP flags or logical combination of flags.
185 - Flags supported by Hetzner are V(syn), V(fin), V(rst), V(psh) and V(urg).
186 - They can be combined with V(|) (logical or) and V(&) (logical and).
187 - See L(the documentation,https://wiki.hetzner.de/index.php/Robot_Firewall/en#Parameter) for more information.
188 type: str
189 action:
190 description:
191 - Action if rule matches.
192 required: true
193 type: str
194 choices: [accept, discard]
195 update_timeout:
196 description:
197 - Timeout to use when configuring the firewall.
198 - Note that the API call returns before the firewall has been successfully set up.
199 type: int
200 default: 30
201 wait_for_configured:
202 description:
203 - Whether to wait until the firewall has been successfully configured before determining what to do, and before returning
204 from the module.
205 - The API returns status C(in progress) when the firewall is currently being configured. If this happens, the module
206 will try again until the status changes to C(active) or C(disabled).
207 - Please note that there is a request limit. If you have to do multiple updates, it can be better to disable waiting,
208 and regularly use M(community.hrobot.firewall_info) to query status.
209 type: bool
210 default: true
211 wait_delay:
212 description:
213 - Delay to wait (in seconds) before checking again whether the firewall has been configured.
214 type: int
215 default: 10
216 timeout:
217 description:
218 - Timeout (in seconds) for waiting for firewall to be configured.
219 type: int
220 default: 180
221 """
222
223 EXAMPLES = r"""
224 ---
225 - name: Configure firewall for server with main IP 1.2.3.4
226 community.hrobot.firewall:
227 hetzner_user: foo
228 hetzner_password: bar
229 server_ip: 1.2.3.4
230 state: present
231 filter_ipv6: true
232 allowlist_hos: true
233 rules:
234 input:
235 - name: Allow ICMP protocol
236 # This is needed so you can ping your server
237 ip_version: ipv4
238 protocol: icmp
239 action: accept
240 # Note that it is not possible to disable ICMP for IPv6
241 # (https://robot.hetzner.com/doc/webservice/en.html#post-firewall-server-id)
242 - name: Allow responses to incoming TCP connections
243 protocol: tcp
244 dst_port: '32768-65535'
245 tcp_flags: ack
246 action: accept
247 - name: Allow restricted access from some known IPv4 addresses
248 # Allow everything to ports 20-23 from 4.3.2.1/24 (IPv4 only)
249 ip_version: ipv4
250 src_ip: 4.3.2.1/24
251 dst_port: '20-23'
252 action: accept
253 - name: Allow everything to port 443
254 dst_port: '443'
255 action: accept
256 - name: Drop everything else
257 action: discard
258 output:
259 - name: Accept everything
260 action: accept
261 register: result
262
263 - ansible.builtin.debug:
264 msg: "{{ result }}"
265 """
266
267 RETURN = r"""
268 firewall:
269 description:
270 - The firewall configuration.
271 type: dict
272 returned: success
273 contains:
274 port:
275 description:
276 - Switch port of firewall.
277 - V(main) or V(kvm).
278 type: str
279 sample: main
280 server_ip:
281 description:
282 - Server's main IP address.
283 type: str
284 sample: 1.2.3.4
285 server_number:
286 description:
287 - Hetzner's internal server number.
288 type: int
289 sample: 12345
290 status:
291 description:
292 - Status of the firewall.
293 - V(active) or V(disabled).
294 - Will be V(in process) if the firewall is currently updated, and O(wait_for_configured) is set to V(false) or O(timeout)
295 to a too small value.
296 type: str
297 sample: active
298 allowlist_hos:
299 description:
300 - Whether Hetzner services have access.
301 type: bool
302 sample: true
303 version_added: 1.2.0
304 whitelist_hos:
305 description:
306 - Whether Hetzner services have access.
307 - Old name of return value V(allowlist_hos), will be removed eventually.
308 type: bool
309 sample: true
310 rules:
311 description:
312 - Firewall rules.
313 type: dict
314 contains:
315 input:
316 description:
317 - Input firewall rules.
318 type: list
319 elements: dict
320 contains:
321 name:
322 description:
323 - Name of the firewall rule.
324 type: str
325 sample: Allow HTTP access to server
326 ip_version:
327 description:
328 - Internet protocol version.
329 - No value means the rule applies both to IPv4 and IPv6.
330 type: str
331 sample: ipv4
332 dst_ip:
333 description:
334 - Destination IP address or subnet address.
335 - CIDR notation.
336 type: str
337 sample: 1.2.3.4/32
338 dst_port:
339 description:
340 - Destination port or port range.
341 type: str
342 sample: "443"
343 src_ip:
344 description:
345 - Source IP address or subnet address.
346 - CIDR notation.
347 type: str
348 sample:
349 src_port:
350 description:
351 - Source port or port range.
352 type: str
353 sample:
354 protocol:
355 description:
356 - Protocol above IP layer.
357 type: str
358 sample: tcp
359 tcp_flags:
360 description:
361 - TCP flags or logical combination of flags.
362 type: str
363 sample:
364 action:
365 description:
366 - Action if rule matches.
367 - V(accept) or V(discard).
368 type: str
369 sample: accept
370 choices:
371 - accept
372 - discard
373 output:
374 description:
375 - Output firewall rules.
376 type: list
377 elements: dict
378 contains:
379 name:
380 description:
381 - Name of the firewall rule.
382 type: str
383 sample: Allow HTTP access to server
384 ip_version:
385 description:
386 - Internet protocol version.
387 - No value means the rule applies both to IPv4 and IPv6.
388 type: str
389 sample:
390 dst_ip:
391 description:
392 - Destination IP address or subnet address.
393 - CIDR notation.
394 type: str
395 sample: 1.2.3.4/32
396 dst_port:
397 description:
398 - Destination port or port range.
399 type: str
400 sample: "443"
401 src_ip:
402 description:
403 - Source IP address or subnet address.
404 - CIDR notation.
405 type: str
406 sample:
407 src_port:
408 description:
409 - Source port or port range.
410 type: str
411 sample:
412 protocol:
413 description:
414 - Protocol above IP layer.
415 type: str
416 sample: tcp
417 tcp_flags:
418 description:
419 - TCP flags or logical combination of flags.
420 type: str
421 sample:
422 action:
423 description:
424 - Action if rule matches.
425 - V(accept) or V(discard).
426 type: str
427 sample: accept
428 choices:
429 - accept
430 - discard
431 """
432
433 import traceback
434
435 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
436 from ansible_collections.community.hrobot.plugins.module_utils.common import (
437 CheckDoneTimeoutException,
438 )
439 from ansible_collections.community.hrobot.plugins.module_utils.robot import (
440 ROBOT_DEFAULT_ARGUMENT_SPEC,
441 BASE_URL,
442 fetch_url_json,
443 fetch_url_json_with_retries,
444 )
445 from ansible.module_utils.common.text.converters import to_native, to_text
446
447 try:
448 import ipaddress
449 HAS_IPADDRESS = True
450 IPADDRESS_IMP_ERR = None
451 except ImportError as exc:
452 IPADDRESS_IMP_ERR = traceback.format_exc()
453 HAS_IPADDRESS = False
454
455 try:
456 from urllib.parse import urlencode
457 except ImportError:
458 # Python 2.x fallback:
459 from urllib import urlencode
460
461
462 RULE_OPTION_NAMES = [
463 'name', 'ip_version', 'dst_ip', 'dst_port', 'src_ip', 'src_port',
464 'protocol', 'tcp_flags', 'action',
465 ]
466
467 RULES = ['input', 'output']
468
469
470 def restrict_dict(dictionary, fields):
471 result = dict()
472 for k, v in dictionary.items():
473 if k in fields:
474 result[k] = v
475 return result
476
477
478 def restrict_firewall_config(config):
479 result = restrict_dict(config, ['port', 'status', 'filter_ipv6', 'whitelist_hos'])
480 result['rules'] = dict()
481 for ruleset in RULES:
482 result['rules'][ruleset] = [
483 restrict_dict(rule, RULE_OPTION_NAMES)
484 for rule in config['rules'].get(ruleset) or []
485 ]
486 return result
487
488
489 def update(before, after, params, name, param_name=None):
490 bv = before.get(name)
491 after[name] = bv
492 changed = False
493 pv = params[param_name or name]
494 if pv is not None:
495 changed = pv != bv
496 if changed:
497 after[name] = pv
498 return changed
499
500
501 def normalize_ip(ip, ip_version):
502 if ip is None or ip_version is None:
503 return ip
504 if '/' in ip:
505 ip, range = ip.split('/')
506 else:
507 ip, range = ip, '' # pylint: disable=self-assigning-variable
508 ip_addr = to_native(ipaddress.ip_address(to_text(ip)).compressed)
509 if range == '':
510 range = '32' if ip_version.lower() == 'ipv4' else '128'
511 return ip_addr + '/' + range
512
513
514 def update_rules(before, after, params, ruleset):
515 before_rules = before['rules'][ruleset]
516 after_rules = after['rules'][ruleset]
517 params_rules = params['rules'][ruleset]
518 changed = len(before_rules) != len(params_rules)
519 for no, rule in enumerate(params_rules):
520 rule['src_ip'] = normalize_ip(rule['src_ip'], rule['ip_version'])
521 rule['dst_ip'] = normalize_ip(rule['dst_ip'], rule['ip_version'])
522 if no < len(before_rules):
523 before_rule = before_rules[no]
524 before_rule['src_ip'] = normalize_ip(before_rule['src_ip'], before_rule['ip_version'])
525 before_rule['dst_ip'] = normalize_ip(before_rule['dst_ip'], before_rule['ip_version'])
526 if before_rule != rule:
527 changed = True
528 after_rules.append(rule)
529 return changed
530
531
532 def encode_rule(output, rulename, input):
533 for i, rule in enumerate(input['rules'][rulename]):
534 for k, v in rule.items():
535 if v is not None:
536 output['rules[{0}][{1}][{2}]'.format(rulename, i, k)] = v
537
538
539 def create_default_rules_object():
540 rules = dict()
541 for ruleset in RULES:
542 rules[ruleset] = []
543 return rules
544
545
546 def fix_naming(firewall_result):
547 firewall_result = firewall_result.copy()
548 firewall_result['allowlist_hos'] = firewall_result.get('whitelist_hos', False)
549 return firewall_result
550
551
552 def firewall_configured(result, error):
553 return result['firewall']['status'] != 'in process'
554
555
556 def main():
557 argument_spec = dict(
558 server_ip=dict(type='str'),
559 server_number=dict(type='int'),
560 port=dict(type='str', default='main', choices=['main', 'kvm']),
561 filter_ipv6=dict(type='bool'),
562 state=dict(type='str', default='present', choices=['present', 'absent']),
563 allowlist_hos=dict(type='bool', aliases=['whitelist_hos']),
564 rules=dict(type='dict', options=dict(
565 input=dict(type='list', elements='dict', options=dict(
566 name=dict(type='str'),
567 ip_version=dict(type='str'),
568 dst_ip=dict(type='str'),
569 dst_port=dict(type='str'),
570 src_ip=dict(type='str'),
571 src_port=dict(type='str'),
572 protocol=dict(type='str'),
573 tcp_flags=dict(type='str'),
574 action=dict(type='str', required=True, choices=['accept', 'discard']),
575 ), required_by=dict(dst_ip=['ip_version'], src_ip=['ip_version'], protocol=['ip_version'])),
576 output=dict(type='list', elements='dict', options=dict(
577 name=dict(type='str'),
578 ip_version=dict(type='str'),
579 dst_ip=dict(type='str'),
580 dst_port=dict(type='str'),
581 src_ip=dict(type='str'),
582 src_port=dict(type='str'),
583 protocol=dict(type='str'),
584 tcp_flags=dict(type='str'),
585 action=dict(type='str', required=True, choices=['accept', 'discard']),
586 ), required_by=dict(dst_ip=['ip_version'], src_ip=['ip_version'], protocol=['ip_version'])),
587 )),
588 update_timeout=dict(type='int', default=30),
589 wait_for_configured=dict(type='bool', default=True),
590 wait_delay=dict(type='int', default=10),
591 timeout=dict(type='int', default=180),
592 )
593 argument_spec.update(ROBOT_DEFAULT_ARGUMENT_SPEC)
594 module = AnsibleModule(
595 argument_spec=argument_spec,
596 supports_check_mode=True,
597 )
598
599 if not HAS_IPADDRESS:
600 module.fail_json(msg=missing_required_lib('ipaddress'), exception=IPADDRESS_IMP_ERR)
601
602 # Sanitize input
603 module.params['status'] = 'active' if (module.params['state'] == 'present') else 'disabled'
604 if module.params['rules'] is None:
605 module.params['rules'] = {}
606 for chain in RULES:
607 if module.params['rules'].get(chain) is None:
608 module.params['rules'][chain] = []
609
610 server_id = module.params['server_ip'] or module.params['server_number']
611
612 # https://robot.your-server.de/doc/webservice/en.html#get-firewall-server-ip
613 url = "{0}/firewall/{1}".format(BASE_URL, server_id)
614 if module.params['wait_for_configured']:
615 try:
616 result, error = fetch_url_json_with_retries(
617 module,
618 url,
619 check_done_callback=firewall_configured,
620 check_done_delay=module.params['wait_delay'],
621 check_done_timeout=module.params['timeout'],
622 )
623 except CheckDoneTimeoutException as dummy:
624 module.fail_json(msg='Timeout while waiting for firewall to be configured.')
625 else:
626 result, error = fetch_url_json(module, url)
627 if not firewall_configured(result, error):
628 module.fail_json(msg='Firewall configuration cannot be read as it is not configured.')
629
630 full_before = result['firewall']
631 if not full_before.get('rules'):
632 full_before['rules'] = create_default_rules_object()
633 before = restrict_firewall_config(full_before)
634
635 # Build wanted (after) state and compare
636 after = dict(before)
637 changed = False
638 changed |= update(before, after, module.params, 'filter_ipv6')
639 changed |= update(before, after, module.params, 'port')
640 changed |= update(before, after, module.params, 'status')
641 changed |= update(before, after, module.params, 'whitelist_hos', 'allowlist_hos')
642 after['rules'] = create_default_rules_object()
643 if module.params['status'] == 'active':
644 for ruleset in RULES:
645 changed |= update_rules(before, after, module.params, ruleset)
646
647 # Update if different
648 construct_result = True
649 construct_status = None
650 if changed and not module.check_mode:
651 # https://robot.your-server.de/doc/webservice/en.html#post-firewall-server-ip
652 url = "{0}/firewall/{1}".format(BASE_URL, server_id)
653 headers = {"Content-type": "application/x-www-form-urlencoded"}
654 data = dict(after)
655 data['filter_ipv6'] = str(data['filter_ipv6']).lower()
656 data['whitelist_hos'] = str(data['whitelist_hos']).lower()
657 del data['rules']
658 for ruleset in RULES:
659 encode_rule(data, ruleset, after)
660 result, error = fetch_url_json(
661 module,
662 url,
663 method='POST',
664 timeout=module.params['update_timeout'],
665 data=urlencode(data),
666 headers=headers,
667 )
668 if module.params['wait_for_configured'] and not firewall_configured(result, error):
669 try:
670 result, error = fetch_url_json_with_retries(
671 module,
672 url,
673 check_done_callback=firewall_configured,
674 check_done_delay=module.params['wait_delay'],
675 check_done_timeout=module.params['timeout'],
676 skip_first=True,
677 )
678 except CheckDoneTimeoutException as e:
679 result, error = e.result, e.error
680 module.warn('Timeout while waiting for firewall to be configured.')
681
682 full_after = result['firewall']
683 if not full_after.get('rules'):
684 full_after['rules'] = create_default_rules_object()
685 construct_status = full_after['status']
686 if construct_status != 'in process':
687 # Only use result if configuration is done, so that diff will be ok
688 after = restrict_firewall_config(full_after)
689 construct_result = False
690
691 if construct_result:
692 # Construct result (used for check mode, and configuration still in process)
693 full_after = dict(full_before)
694 for k, v in after.items():
695 if k != 'rules':
696 full_after[k] = after[k]
697 if construct_status is not None:
698 # We want 'in process' here
699 full_after['status'] = construct_status
700 full_after['rules'] = dict()
701 for ruleset in RULES:
702 full_after['rules'][ruleset] = after['rules'][ruleset]
703
704 module.exit_json(
705 changed=changed,
706 diff=dict(
707 before=fix_naming(before),
708 after=fix_naming(after),
709 ),
710 firewall=fix_naming(full_after),
711 )
712
713
714 if __name__ == '__main__': # pragma: no cover
715 main() # pragma: no cover