Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_device_httpd.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_device_httpd
13 short_description: Manage HTTPD related settings on a BIG-IP system
14 description:
15 - Manages HTTPD related settings on the BIG-IP. These settings are useful
16 when you want to set GUI timeouts and other TMUI related settings.
17 version_added: "1.0.0"
18 options:
19 allow:
20 description:
21 - If you have enabled HTTPD access, specifies the IP address or address
22 range for other systems that can communicate with this system.
23 - To specify all addresses, use the value C(all).
24 - An IP address can be specified, such as 172.27.1.10.
25 - IP ranges can be specified, such as 172.27.*.* or 172.27.0.0/255.255.0.0.
26 type: list
27 elements: str
28 auth_name:
29 description:
30 - Sets the BIG-IP authentication realm name.
31 type: str
32 auth_pam_idle_timeout:
33 description:
34 - Sets the GUI timeout for automatic logout, in seconds.
35 type: int
36 auth_pam_validate_ip:
37 description:
38 - Sets the authPamValidateIp setting.
39 type: bool
40 auth_pam_dashboard_timeout:
41 description:
42 - Sets whether or not the BIG-IP dashboard will timeout.
43 type: bool
44 fast_cgi_timeout:
45 description:
46 - Sets the timeout of FastCGI.
47 type: int
48 hostname_lookup:
49 description:
50 - Sets whether or not to display the hostname, if possible.
51 type: bool
52 log_level:
53 description:
54 - Sets the minimum HTTPD log level.
55 type: str
56 choices:
57 - alert
58 - crit
59 - debug
60 - emerg
61 - error
62 - info
63 - notice
64 - warn
65 max_clients:
66 description:
67 - Sets the maximum number of clients that can connect to the GUI at once.
68 type: int
69 redirect_http_to_https:
70 description:
71 - Whether or not to redirect HTTP requests to the GUI to HTTPS.
72 type: bool
73 ssl_port:
74 description:
75 - The HTTPS port on which the system should listen.
76 type: int
77 ssl_cipher_suite:
78 description:
79 - Specifies the ciphers the system uses.
80 - The values in the suite are separated by colons (:).
81 - Can be specified in either a string or list form. The list form is the
82 recommended way to provide the cipher suite. See examples for usage.
83 - Use the value C(default) to set the cipher suite to the system default.
84 This value is equivalent to specifying a list of C(ECDHE-RSA-AES128-GCM-SHA256,
85 ECDHE-RSA-AES256-GCM-SHA384,ECDHE-RSA-AES128-SHA,ECDHE-RSA-AES256-SHA,
86 ECDHE-RSA-AES128-SHA256,ECDHE-RSA-AES256-SHA384,ECDHE-ECDSA-AES128-GCM-SHA256,
87 ECDHE-ECDSA-AES256-GCM-SHA384,ECDHE-ECDSA-AES128-SHA,ECDHE-ECDSA-AES256-SHA,
88 ECDHE-ECDSA-AES128-SHA256,ECDHE-ECDSA-AES256-SHA384,AES128-GCM-SHA256,
89 AES256-GCM-SHA384,AES128-SHA,AES256-SHA,AES128-SHA256,AES256-SHA256,
90 ECDHE-RSA-DES-CBC3-SHA,ECDHE-ECDSA-DES-CBC3-SHA,DES-CBC3-SHA).
91 type: raw
92 ssl_protocols:
93 description:
94 - The list of SSL protocols to accept on the management console.
95 - A space-separated list of tokens in the format accepted by the Apache
96 mod_ssl SSLProtocol directive.
97 - Can be specified in either a string or list form. The list form is the
98 recommended way to provide the cipher suite. See examples for usage.
99 - Use the value C(default) to set the SSL protocols to the system default.
100 This value is equivalent to specifying a list of C(all,-SSLv2,-SSLv3).
101 type: raw
102 notes:
103 - Requires the B(requests) Python package on the host. This is as easy as
104 running C(pip install requests).
105 requirements:
106 - requests
107 extends_documentation_fragment: f5networks.f5_modules.f5
108 author:
109 - Joe Reifel (@JoeReifel)
110 - Tim Rupp (@caphrim007)
111 '''
112
113 EXAMPLES = r'''
114 - name: Set the BIG-IP authentication realm name
115 bigip_device_httpd:
116 auth_name: BIG-IP
117 provider:
118 password: secret
119 server: lb.mydomain.com
120 user: admin
121 delegate_to: localhost
122
123 - name: Set the auth pam timeout to 3600 seconds
124 bigip_device_httpd:
125 auth_pam_idle_timeout: 1200
126 provider:
127 password: secret
128 server: lb.mydomain.com
129 user: admin
130 delegate_to: localhost
131
132 - name: Set the validate IP settings
133 bigip_device_httpd:
134 auth_pam_validate_ip: false
135 provider:
136 password: secret
137 server: lb.mydomain.com
138 user: admin
139 delegate_to: localhost
140
141 - name: Set SSL cipher suite by list
142 bigip_device_httpd:
143 ssl_cipher_suite:
144 - ECDHE-RSA-AES128-GCM-SHA256
145 - ECDHE-RSA-AES256-GCM-SHA384
146 - ECDHE-RSA-AES128-SHA
147 - AES256-SHA256
148 provider:
149 password: secret
150 server: lb.mydomain.com
151 user: admin
152 delegate_to: localhost
153
154 - name: Set SSL cipher suite by string
155 bigip_device_httpd:
156 ssl_cipher_suite: ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA:AES256-SHA256
157 provider:
158 password: secret
159 server: lb.mydomain.com
160 user: admin
161 delegate_to: localhost
162
163 - name: Set SSL protocols by list
164 bigip_device_httpd:
165 ssl_protocols:
166 - all
167 - -SSLv2
168 - -SSLv3
169 provider:
170 password: secret
171 server: lb.mydomain.com
172 user: admin
173 delegate_to: localhost
174
175 - name: Set SSL protocols by string
176 bigip_device_httpd:
177 ssl_protocols: all -SSLv2 -SSLv3
178 provider:
179 password: secret
180 server: lb.mydomain.com
181 user: admin
182 delegate_to: localhost
183 '''
184
185 RETURN = r'''
186 auth_pam_idle_timeout:
187 description: The new number of seconds for GUI timeout.
188 returned: changed
189 type: str
190 sample: 1200
191 auth_name:
192 description: The new authentication realm name.
193 returned: changed
194 type: str
195 sample: 'foo'
196 auth_pam_validate_ip:
197 description: The new authPamValidateIp setting.
198 returned: changed
199 type: bool
200 sample: on
201 auth_pam_dashboard_timeout:
202 description: Whether or not the BIG-IP dashboard will timeout.
203 returned: changed
204 type: bool
205 sample: off
206 fast_cgi_timeout:
207 description: The new timeout of FastCGI.
208 returned: changed
209 type: int
210 sample: 500
211 hostname_lookup:
212 description: Whether or not to display the hostname, if possible.
213 returned: changed
214 type: bool
215 sample: on
216 log_level:
217 description: The new minimum HTTPD log level.
218 returned: changed
219 type: str
220 sample: crit
221 max_clients:
222 description: The new maximum number of clients that can connect to the GUI at once.
223 returned: changed
224 type: int
225 sample: 20
226 redirect_http_to_https:
227 description: Whether or not to redirect HTTP requests to the GUI to HTTPS.
228 returned: changed
229 type: bool
230 sample: on
231 ssl_port:
232 description: The new HTTPS port to listen on.
233 returned: changed
234 type: int
235 sample: 10443
236 ssl_cipher_suite:
237 description: The new ciphers the system uses.
238 returned: changed
239 type: str
240 sample: ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA
241 ssl_cipher_suite_list:
242 description: List of the new ciphers the system uses.
243 returned: changed
244 type: str
245 sample: ['ECDHE-RSA-AES256-GCM-SHA384', 'ECDHE-RSA-AES128-SHA']
246 ssl_protocols:
247 description: The new list of SSL protocols to accept on the management console.
248 returned: changed
249 type: str
250 sample: all -SSLv2 -SSLv3
251 '''
252 import time
253 from datetime import datetime
254
255
256 from ansible.module_utils.basic import AnsibleModule
257 from ansible.module_utils.six import string_types
258
259 from ..module_utils.bigip import F5RestClient
260 from ..module_utils.common import (
261 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
262 )
263 from ..module_utils.icontrol import tmos_version
264 from ..module_utils.teem import send_teem
265
266
267 class Parameters(AnsibleF5Parameters):
268 api_map = {
269 'authPamIdleTimeout': 'auth_pam_idle_timeout',
270 'authPamValidateIp': 'auth_pam_validate_ip',
271 'authName': 'auth_name',
272 'authPamDashboardTimeout': 'auth_pam_dashboard_timeout',
273 'fastcgiTimeout': 'fast_cgi_timeout',
274 'hostnameLookup': 'hostname_lookup',
275 'logLevel': 'log_level',
276 'maxClients': 'max_clients',
277 'redirectHttpToHttps': 'redirect_http_to_https',
278 'sslPort': 'ssl_port',
279 'sslCiphersuite': 'ssl_cipher_suite',
280 'sslProtocol': 'ssl_protocols'
281 }
282
283 api_attributes = [
284 'authPamIdleTimeout', 'authPamValidateIp', 'authName', 'authPamDashboardTimeout',
285 'fastcgiTimeout', 'hostnameLookup', 'logLevel', 'maxClients', 'sslPort',
286 'redirectHttpToHttps', 'allow', 'sslCiphersuite', 'sslProtocol'
287 ]
288
289 returnables = [
290 'auth_pam_idle_timeout', 'auth_pam_validate_ip', 'auth_name',
291 'auth_pam_dashboard_timeout', 'fast_cgi_timeout', 'hostname_lookup',
292 'log_level', 'max_clients', 'redirect_http_to_https', 'ssl_port',
293 'allow', 'ssl_cipher_suite', 'ssl_protocols', 'ssl_cipher_suite_list',
294 ]
295
296 updatables = [
297 'auth_pam_idle_timeout', 'auth_pam_validate_ip', 'auth_name',
298 'auth_pam_dashboard_timeout', 'fast_cgi_timeout', 'hostname_lookup',
299 'log_level', 'max_clients', 'redirect_http_to_https', 'ssl_port',
300 'allow', 'ssl_cipher_suite', 'ssl_protocols'
301 ]
302
303 _ciphers = "ECDHE-RSA-AES128-GCM-SHA256:" \
304 "ECDHE-RSA-AES256-GCM-SHA384:" \
305 "ECDHE-RSA-AES128-SHA:" \
306 "ECDHE-RSA-AES256-SHA:" \
307 "ECDHE-RSA-AES128-SHA256:" \
308 "ECDHE-RSA-AES256-SHA384:" \
309 "ECDHE-ECDSA-AES128-GCM-SHA256:" \
310 "ECDHE-ECDSA-AES256-GCM-SHA384:" \
311 "ECDHE-ECDSA-AES128-SHA:" \
312 "ECDHE-ECDSA-AES256-SHA:" \
313 "ECDHE-ECDSA-AES128-SHA256:" \
314 "ECDHE-ECDSA-AES256-SHA384:" \
315 "AES128-GCM-SHA256:" \
316 "AES256-GCM-SHA384:" \
317 "AES128-SHA:" \
318 "AES256-SHA:" \
319 "AES128-SHA256:" \
320 "AES256-SHA256:" \
321 "ECDHE-RSA-DES-CBC3-SHA:" \
322 "ECDHE-ECDSA-DES-CBC3-SHA:" \
323 "DES-CBC3-SHA"
324
325 _protocols = 'all -SSLv2 -SSLv3'
326
327 @property
328 def auth_pam_idle_timeout(self):
329 if self._values['auth_pam_idle_timeout'] is None:
330 return None
331 return int(self._values['auth_pam_idle_timeout'])
332
333 @property
334 def fast_cgi_timeout(self):
335 if self._values['fast_cgi_timeout'] is None:
336 return None
337 return int(self._values['fast_cgi_timeout'])
338
339 @property
340 def max_clients(self):
341 if self._values['max_clients'] is None:
342 return None
343 return int(self._values['max_clients'])
344
345 @property
346 def ssl_port(self):
347 if self._values['ssl_port'] is None:
348 return None
349 return int(self._values['ssl_port'])
350
351
352 class ModuleParameters(Parameters):
353 @property
354 def auth_pam_validate_ip(self):
355 if self._values['auth_pam_validate_ip'] is None:
356 return None
357 if self._values['auth_pam_validate_ip']:
358 return "on"
359 return "off"
360
361 @property
362 def auth_pam_dashboard_timeout(self):
363 if self._values['auth_pam_dashboard_timeout'] is None:
364 return None
365 if self._values['auth_pam_dashboard_timeout']:
366 return "on"
367 return "off"
368
369 @property
370 def hostname_lookup(self):
371 if self._values['hostname_lookup'] is None:
372 return None
373 if self._values['hostname_lookup']:
374 return "on"
375 return "off"
376
377 @property
378 def redirect_http_to_https(self):
379 if self._values['redirect_http_to_https'] is None:
380 return None
381 if self._values['redirect_http_to_https']:
382 return "enabled"
383 return "disabled"
384
385 @property
386 def allow(self):
387 if self._values['allow'] is None:
388 return None
389 if self._values['allow'][0] == 'all':
390 return 'all'
391 if self._values['allow'][0] == '':
392 return ''
393 allow = self._values['allow']
394 result = list(set([str(x) for x in allow]))
395 result = sorted(result)
396 return result
397
398 @property
399 def ssl_cipher_suite(self):
400 if self._values['ssl_cipher_suite'] is None:
401 return None
402 if isinstance(self._values['ssl_cipher_suite'], string_types):
403 ciphers = self._values['ssl_cipher_suite'].strip()
404 else:
405 ciphers = self._values['ssl_cipher_suite']
406 if not ciphers:
407 raise F5ModuleError(
408 "ssl_cipher_suite may not be set to 'none'"
409 )
410 if ciphers == 'default':
411 ciphers = ':'.join(Parameters._ciphers.split(':'))
412 elif isinstance(self._values['ssl_cipher_suite'], string_types):
413 ciphers = ':'.join(ciphers.split(':'))
414 else:
415 ciphers = ':'.join(ciphers)
416 return ciphers
417
418 @property
419 def ssl_protocols(self):
420 if self._values['ssl_protocols'] is None:
421 return None
422 if isinstance(self._values['ssl_protocols'], string_types):
423 protocols = self._values['ssl_protocols'].strip()
424 else:
425 protocols = self._values['ssl_protocols']
426 if not protocols:
427 raise F5ModuleError(
428 "ssl_protocols may not be set to 'none'"
429 )
430 if protocols == 'default':
431 protocols = ' '.join(Parameters._protocols.split(' '))
432 elif isinstance(protocols, string_types):
433 protocols = ' '.join(protocols.split(' '))
434 else:
435 protocols = ' '.join(protocols)
436 return protocols
437
438
439 class ApiParameters(Parameters):
440 @property
441 def allow(self):
442 if self._values['allow'] is None:
443 return ''
444 if self._values['allow'][0] == 'All':
445 return 'all'
446 allow = self._values['allow']
447 result = list(set([str(x) for x in allow]))
448 result = sorted(result)
449 return result
450
451
452 class Changes(Parameters):
453 def to_return(self):
454 result = {}
455 try:
456 for returnable in self.returnables:
457 result[returnable] = getattr(self, returnable)
458 result = self._filter_params(result)
459 except Exception:
460 raise
461 return result
462
463
464 class UsableChanges(Changes):
465 pass
466
467
468 class ReportableChanges(Changes):
469 @property
470 def ssl_cipher_suite(self):
471 default = ':'.join(Parameters._ciphers.split(':'))
472 if self._values['ssl_cipher_suite'] == default:
473 return 'default'
474 else:
475 return self._values['ssl_cipher_suite']
476
477 @property
478 def ssl_cipher_suite_list(self):
479 return self._values['ssl_cipher_suite'].split(':')
480
481 @property
482 def ssl_protocols(self):
483 default = ' '.join(Parameters._protocols.split(' '))
484 if self._values['ssl_protocols'] == default:
485 return 'default'
486 else:
487 return self._values['ssl_protocols']
488
489
490 class Difference(object):
491 def __init__(self, want, have=None):
492 self.want = want
493 self.have = have
494
495 def compare(self, param):
496 try:
497 result = getattr(self, param)
498 return result
499 except AttributeError:
500 return self.__default(param)
501
502 def __default(self, param):
503 attr1 = getattr(self.want, param)
504 try:
505 attr2 = getattr(self.have, param)
506 if attr1 != attr2:
507 return attr1
508 except AttributeError:
509 return attr1
510
511 @property
512 def allow(self):
513 if self.want.allow is None:
514 return None
515 if self.want.allow == 'all' and self.have.allow == 'all':
516 return None
517 if self.want.allow == 'all':
518 return ['All']
519 if self.want.allow == '' and self.have.allow == '':
520 return None
521 if self.want.allow == '':
522 return []
523 if self.want.allow != self.have.allow:
524 return self.want.allow
525
526
527 class ModuleManager(object):
528 def __init__(self, *args, **kwargs):
529 self.module = kwargs.get('module', None)
530 self.client = F5RestClient(**self.module.params)
531 self.want = ModuleParameters(params=self.module.params)
532 self.have = ApiParameters()
533 self.changes = UsableChanges()
534
535 def _set_changed_options(self):
536 changed = {}
537 for key in Parameters.returnables:
538 if getattr(self.want, key) is not None:
539 changed[key] = getattr(self.want, key)
540 if changed:
541 self.changes = Changes(params=changed)
542
543 def _update_changed_options(self):
544 diff = Difference(self.want, self.have)
545 updatables = Parameters.updatables
546 changed = dict()
547 for k in updatables:
548 change = diff.compare(k)
549 if change is None:
550 continue
551 else:
552 if isinstance(change, dict):
553 changed.update(change)
554 else:
555 changed[k] = change
556 if changed:
557 self.changes = UsableChanges(params=changed)
558 return True
559 return False
560
561 def should_update(self):
562 result = self._update_changed_options()
563 if result:
564 return True
565 return False
566
567 def exec_module(self):
568 start = datetime.now().isoformat()
569 version = tmos_version(self.client)
570 result = dict()
571
572 changed = self.present()
573
574 reportable = ReportableChanges(params=self.changes.to_return())
575 changes = reportable.to_return()
576 result.update(**changes)
577 result.update(dict(changed=changed))
578 self._announce_deprecations(result)
579 send_teem(start, self.client, self.module, version)
580 return result
581
582 def _announce_deprecations(self, result):
583 warnings = result.pop('__warnings', [])
584 for warning in warnings:
585 self.module.deprecate(
586 msg=warning['msg'],
587 version=warning['version']
588 )
589
590 def present(self):
591 return self.update()
592
593 def update(self):
594 self.have = self.read_current_from_device()
595 if not self.should_update():
596 return False
597 if self.module.check_mode:
598 return True
599 self.update_on_device()
600 return True
601
602 def update_on_device(self):
603 params = self.changes.api_params()
604 uri = "https://{0}:{1}/mgmt/tm/sys/httpd".format(
605 self.client.provider['server'],
606 self.client.provider['server_port']
607 )
608
609 try:
610 resp = self.client.api.patch(uri, json=params)
611 try:
612 response = resp.json()
613 except ValueError as ex:
614 raise F5ModuleError(str(ex))
615
616 if resp.status not in [200, 201] or 'code' in response and response['code'] not in [200, 201]:
617 raise F5ModuleError(resp.content)
618
619 except Exception as ex:
620 valid = [
621 'Remote end closed connection',
622 'Connection aborted',
623 ]
624 # BIG-IP will kill your management connection when you change the HTTP
625 # redirect setting. So this catches that and handles it gracefully.
626 if 'redirectHttpToHttps' in params:
627 if any(i for i in valid if i in str(ex)):
628 # Wait for BIG-IP web server to settle after changing this
629 time.sleep(2)
630 return True
631 raise F5ModuleError(str(ex))
632
633 def read_current_from_device(self):
634 uri = "https://{0}:{1}/mgmt/tm/sys/httpd".format(
635 self.client.provider['server'],
636 self.client.provider['server_port']
637 )
638 resp = self.client.api.get(uri)
639 try:
640 response = resp.json()
641 except ValueError as ex:
642 raise F5ModuleError(str(ex))
643
644 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
645 return ApiParameters(params=response)
646 raise F5ModuleError(resp.content)
647
648
649 class ArgumentSpec(object):
650 def __init__(self):
651 self.supports_check_mode = True
652 argument_spec = dict(
653 allow=dict(
654 type='list',
655 elements='str',
656 ),
657 auth_name=dict(),
658 auth_pam_idle_timeout=dict(
659 type='int'
660 ),
661 fast_cgi_timeout=dict(
662 type='int'
663 ),
664 max_clients=dict(
665 type='int'
666 ),
667 ssl_port=dict(
668 type='int'
669 ),
670 auth_pam_validate_ip=dict(
671 type='bool'
672 ),
673 auth_pam_dashboard_timeout=dict(
674 type='bool'
675 ),
676 hostname_lookup=dict(
677 type='bool'
678 ),
679 log_level=dict(
680 choices=[
681 'alert', 'crit', 'debug', 'emerg',
682 'error', 'info', 'notice', 'warn'
683 ]
684 ),
685 redirect_http_to_https=dict(
686 type='bool'
687 ),
688 ssl_cipher_suite=dict(type='raw'),
689 ssl_protocols=dict(type='raw')
690 )
691 self.argument_spec = {}
692 self.argument_spec.update(f5_argument_spec)
693 self.argument_spec.update(argument_spec)
694
695
696 def main():
697 spec = ArgumentSpec()
698
699 module = AnsibleModule(
700 argument_spec=spec.argument_spec,
701 supports_check_mode=spec.supports_check_mode,
702 )
703
704 try:
705 mm = ModuleManager(module=module)
706 results = mm.exec_module()
707 module.exit_json(**results)
708 except F5ModuleError as ex:
709 module.fail_json(msg=str(ex))
710
711
712 if __name__ == '__main__':
713 main()