Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, 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_auth
13 short_description: Manage system authentication on a BIG-IP
14 description:
15 - Manage the system authentication configuration. This module can assist in configuring
16 a number of different system authentication types. Note that this module can not be used
17 to configure APM authentication types.
18 version_added: "1.0.0"
19 options:
20 type:
21 description:
22 - The authentication type to manage with this module.
23 - Take special note that the parameters supported by this module will vary depending
24 on the C(type) that you are configuring.
25 - At this time, this module only supports a subset of the total available auth types.
26 type: str
27 required: True
28 choices:
29 - tacacs
30 - local
31 servers:
32 description:
33 - Specifies a list of the IPv4 addresses for servers using the Terminal
34 Access Controller Access System (TACACS)+ protocol with which the system
35 communicates to obtain authorization data.
36 - For each address, an alternate TCP port number may be optionally specified
37 by specifying the C(port) key.
38 - If no port number is specified, the default port C(49163) is used.
39 - This parameter is supported by the C(tacacs) type.
40 type: raw
41 suboptions:
42 address:
43 description:
44 - The IP address of the server.
45 - This field is required, unless you are specifying a simple list of servers.
46 In that case, the simple list can specify server IPs. See the examples for
47 more clarification.
48 port:
49 description:
50 - The port of the server.
51 secret:
52 description:
53 - Secret key used to encrypt and decrypt packets sent or received from the
54 server.
55 - B(Do not) use the pound/hash sign in the secret for TACACS+ servers.
56 - When configuring TACACS+ auth for the first time, this value is required.
57 type: str
58 service_name:
59 description:
60 - Specifies the name of the service the user is requesting to be
61 authorized to use.
62 - Identifying what the user is asking to be authorized for enables the
63 TACACS+ serverc to behave differently for different types of authorization
64 requests.
65 - This setting is required when configuring this form of system authentication.
66 - Note that the majority of TACACS+ implementations are of service type C(ppp),
67 so try that first.
68 type: str
69 choices:
70 - slip
71 - ppp
72 - arap
73 - shell
74 - tty-daemon
75 - connection
76 - system
77 - firewall
78 protocol_name:
79 description:
80 - Specifies the protocol associated with the value specified in C(service_name),
81 which is a subset of the associated service being used for client authorization
82 or system accounting.
83 - Note that the majority of TACACS+ implementations are of protocol type C(ip),
84 so try that first.
85 type: str
86 choices:
87 - lcp
88 - ip
89 - ipx
90 - atalk
91 - vines
92 - lat
93 - xremote
94 - tn3270
95 - telnet
96 - rlogin
97 - pad
98 - vpdn
99 - ftp
100 - http
101 - deccp
102 - osicp
103 - unknown
104 authentication:
105 description:
106 - Specifies the process the system employs when sending authentication requests.
107 - When C(use-first-server), specifies the system sends authentication
108 attempts only to the first server in the list.
109 - When C(use-all-servers), specifies the system sends an authentication
110 request to each server until authentication succeeds, or until the system has
111 sent a request to all servers in the list.
112 - This parameter is supported by the C(tacacs) type.
113 type: str
114 choices:
115 - use-first-server
116 - use-all-servers
117 accounting:
118 description:
119 - Specifies how the system returns accounting information, such as which services
120 users access and the amount of network resources they consume, to the TACACS+ server.
121 - When C(send-to-first-server), specifies the system transmits accounting
122 information back to the first available TACACS+ server in the list.
123 - When C(send-to-all-servers), specifies the system transmits accounting
124 information back to all TACACS+ servers in the list.
125 - This parameter is supported by the C(tacacs) type.
126 type: str
127 choices:
128 - send-to-first-server
129 - send-to-all-servers
130 use_for_auth:
131 description:
132 - Specifies whether or not this auth source is put in use on the system.
133 type: bool
134 state:
135 description:
136 - The state of the authentication configuration on the system.
137 - When C(present), guarantees the system is configured for the specified C(type).
138 - When C(absent), sets the system auth source back to C(local).
139 type: str
140 choices:
141 - absent
142 - present
143 default: present
144 update_secret:
145 description:
146 - C(always) will allow updating secrets if the user chooses to do so.
147 - C(on_create) will only set the secret when a C(use_auth_source) is C(true)
148 and TACACS+ is not currently the auth source.
149 type: str
150 choices:
151 - always
152 - on_create
153 default: always
154 extends_documentation_fragment: f5networks.f5_modules.f5
155 author:
156 - Tim Rupp (@caphrim007)
157 - Nitin Khanna (@nitinthewiz)
158 '''
159
160 EXAMPLES = r'''
161 - name: Set the system auth to TACACS+, default server port
162 bigip_device_auth:
163 type: tacacs
164 authentication: use-all-servers
165 accounting: send-to-all-servers
166 protocol_name: ip
167 secret: secret
168 servers:
169 - 10.10.10.10
170 - 10.10.10.11
171 service_name: ppp
172 state: present
173 use_for_auth: true
174 provider:
175 password: secret
176 server: lb.mydomain.com
177 user: admin
178 delegate_to: localhost
179
180 - name: Set the system auth to TACACS+, override server port
181 bigip_device_auth:
182 type: tacacs
183 authentication: use-all-servers
184 protocol_name: ip
185 secret: secret
186 servers:
187 - address: 10.10.10.10
188 port: 1234
189 - 10.10.10.11
190 service_name: ppp
191 use_for_auth: true
192 state: present
193 provider:
194 password: secret
195 server: lb.mydomain.com
196 user: admin
197 delegate_to: localhost
198 '''
199
200 RETURN = r'''
201 servers:
202 description: List of servers used in TACACS authentication.
203 returned: changed
204 type: list
205 sample: ['1.2.2.1', '4.5.5.4']
206 authentication:
207 description: Process the system uses to serve authentication requests when using TACACS.
208 returned: changed
209 type: str
210 sample: use-all-servers
211 accounting:
212 description: Which servers to send information to when using TACACS.
213 returned: changed
214 type: str
215 sample: send-to-all-servers
216 service_name:
217 description: Name of the service the user is requesting to be authorized to use.
218 returned: changed
219 type: str
220 sample: ppp
221 protocol_name:
222 description: Name of the protocol associated with C(service_name) used for client authentication.
223 returned: changed
224 type: str
225 sample: ip
226 '''
227 from datetime import datetime
228 from ansible.module_utils.basic import AnsibleModule
229 from ansible.module_utils.six import string_types
230
231 from ..module_utils.bigip import F5RestClient
232 from ..module_utils.common import (
233 F5ModuleError, AnsibleF5Parameters, f5_argument_spec
234 )
235 from ..module_utils.icontrol import tmos_version
236 from ..module_utils.teem import send_teem
237
238
239 class BaseParameters(AnsibleF5Parameters):
240 @property
241 def api_map(self):
242 return {}
243
244 @property
245 def api_attributes(self):
246 return []
247
248 @property
249 def returnables(self):
250 return []
251
252 @property
253 def updatables(self):
254 return []
255
256
257 class BaseApiParameters(BaseParameters):
258 pass
259
260
261 class BaseModuleParameters(BaseParameters):
262 pass
263
264
265 class BaseChanges(BaseParameters):
266 def to_return(self):
267 result = {}
268 try:
269 for returnable in self.returnables:
270 result[returnable] = getattr(self, returnable)
271 result = self._filter_params(result)
272 except Exception:
273 raise
274 return result
275
276
277 class BaseUsableChanges(BaseChanges):
278 pass
279
280
281 class BaseReportableChanges(BaseChanges):
282 pass
283
284
285 class TacacsParameters(BaseParameters):
286 api_map = {
287 'protocol': 'protocol_name',
288 'service': 'service_name'
289 }
290
291 api_attributes = [
292 'authentication',
293 'accounting',
294 'protocol',
295 'service',
296 'secret',
297 'servers'
298 ]
299
300 returnables = [
301 'servers',
302 'secret',
303 'authentication',
304 'accounting',
305 'service_name',
306 'protocol_name'
307 ]
308
309 updatables = [
310 'servers',
311 'secret',
312 'authentication',
313 'accounting',
314 'service_name',
315 'protocol_name',
316 'auth_source',
317 ]
318
319
320 class TacacsApiParameters(TacacsParameters):
321 pass
322
323
324 class TacacsModuleParameters(TacacsParameters):
325 @property
326 def servers(self):
327 if self._values['servers'] is None:
328 return None
329 result = []
330 for server in self._values['servers']:
331 if isinstance(server, dict):
332 if 'address' not in server:
333 raise F5ModuleError(
334 "An 'address' field must be provided when specifying separate fields to the 'servers' parameter."
335 )
336 address = server.get('address')
337 port = server.get('port', None)
338 elif isinstance(server, string_types):
339 address = server
340 port = None
341 if port is None:
342 result.append('{0}'.format(address))
343 else:
344 result.append('{0}:{1}'.format(address, port))
345 return result
346
347 @property
348 def auth_source(self):
349 return 'tacacs'
350
351
352 class TacacsChanges(BaseChanges, TacacsParameters):
353 pass
354
355
356 class TacacsUsableChanges(TacacsChanges):
357 pass
358
359
360 class TacacsReportableChanges(TacacsChanges):
361 @property
362 def secret(self):
363 return None
364
365
366 class Difference(object):
367 def __init__(self, want, have=None):
368 self.want = want
369 self.have = have
370
371 def compare(self, param):
372 try:
373 result = getattr(self, param)
374 return result
375 except AttributeError:
376 return self.__default(param)
377
378 def __default(self, param):
379 want = getattr(self.want, param)
380 try:
381 have = getattr(self.have, param)
382 if want != have:
383 return want
384 except AttributeError:
385 return want
386
387 @property
388 def secret(self):
389 if self.want.secret != self.have.secret and self.want.update_secret == 'always':
390 return self.want.secret
391
392
393 class BaseManager(object):
394 def _set_changed_options(self):
395 changed = {}
396 for key in self.returnables:
397 if getattr(self.want, key) is not None:
398 changed[key] = getattr(self.want, key)
399 if changed:
400 self.changes = self.get_usable_changes(params=changed)
401
402 def _update_changed_options(self):
403 diff = Difference(self.want, self.have)
404 updatables = self.updatables
405 changed = dict()
406 for k in updatables:
407 change = diff.compare(k)
408 if change is None:
409 continue
410 else:
411 if isinstance(change, dict):
412 changed.update(change)
413 else:
414 changed[k] = change
415 if changed:
416 self.changes = self.get_usable_changes(params=changed)
417 return True
418 return False
419
420 def should_update(self):
421 result = self._update_changed_options()
422 if result:
423 return True
424 return False
425
426 def exec_module(self):
427 start = datetime.now().isoformat()
428 version = tmos_version(self.client)
429 changed = False
430 result = dict()
431 state = self.want.state
432
433 if state == "present":
434 changed = self.present()
435 elif state == "absent":
436 changed = self.absent()
437
438 reportable = self.get_reportable_changes(params=self.changes.to_return())
439 changes = reportable.to_return()
440 result.update(**changes)
441 result.update(dict(changed=changed))
442 self._announce_deprecations(result)
443 send_teem(start, self.client, self.module, version)
444 return result
445
446 def _announce_deprecations(self, result):
447 warnings = result.pop('__warnings', [])
448 for warning in warnings:
449 self.client.module.deprecate(
450 msg=warning['msg'],
451 version=warning['version']
452 )
453
454 def present(self):
455 if self.exists():
456 return self.update()
457 return self.create()
458
459 def absent(self):
460 if self.exists():
461 return self.remove()
462 return False
463
464 def update_auth_source_on_device(self, source):
465 """Set the system auth source.
466
467 Configuring the authentication source is only one step in the process of setting
468 up an auth source. The other step is to inform the system of the auth source
469 you want to use.
470
471 This method is used for situations where
472
473 * The ``use_for_auth`` parameter is set to ``yes``
474 * The ``use_for_auth`` parameter is set to ``no``
475 * The ``state`` parameter is set to ``absent``
476
477 When ``state`` equal to ``absent``, before you can delete the TACACS+ configuration,
478 you must set the system auth to "something else". The system ships with a system
479 auth called "local", so this is the logical "something else" to use.
480
481 When ``use_for_auth`` is no, the same situation applies as when ``state`` equal
482 to ``absent`` is done above.
483
484 When ``use_for_auth`` is ``yes``, this method will set the current system auth
485 state to TACACS+.
486
487 Arguments:
488 source (string): The source that you want to set on the device.
489 """
490 params = dict(
491 type=source
492 )
493 uri = 'https://{0}:{1}/mgmt/tm/auth/source/'.format(
494 self.client.provider['server'],
495 self.client.provider['server_port']
496 )
497
498 resp = self.client.api.patch(uri, json=params)
499 try:
500 response = resp.json()
501 except ValueError as ex:
502 raise F5ModuleError(str(ex))
503
504 if 'code' in response and response['code'] == 400:
505 if 'message' in response:
506 raise F5ModuleError(response['message'])
507 else:
508 raise F5ModuleError(resp.content)
509
510 def read_current_auth_source_from_device(self):
511 uri = "https://{0}:{1}/mgmt/tm/auth/source".format(
512 self.client.provider['server'],
513 self.client.provider['server_port'],
514 )
515 resp = self.client.api.get(uri)
516 try:
517 response = resp.json()
518 except ValueError as ex:
519 raise F5ModuleError(str(ex))
520
521 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
522 return response['type']
523 raise F5ModuleError(resp.content)
524
525
526 class LocalManager(BaseManager):
527 def __init__(self, *args, **kwargs):
528 self.module = kwargs.get('module', None)
529 self.client = F5RestClient(**self.module.params)
530 self.want = self.get_module_parameters(params=self.module.params)
531 self.have = self.get_api_parameters()
532 self.changes = self.get_usable_changes()
533
534 @property
535 def returnables(self):
536 return []
537
538 @property
539 def updatables(self):
540 return []
541
542 def get_parameters(self, params=None):
543 return BaseParameters(params=params)
544
545 def get_usable_changes(self, params=None):
546 return BaseUsableChanges(params=params)
547
548 def get_reportable_changes(self, params=None):
549 return BaseReportableChanges(params=params)
550
551 def get_module_parameters(self, params=None):
552 return BaseModuleParameters(params=params)
553
554 def get_api_parameters(self, params=None):
555 return BaseApiParameters(params=params)
556
557 def exists(self):
558 uri = "https://{0}:{1}/mgmt/tm/auth/source".format(
559 self.client.provider['server'],
560 self.client.provider['server_port'],
561 )
562 resp = self.client.api.get(uri)
563 try:
564 response = resp.json()
565 except ValueError as ex:
566 raise F5ModuleError(str(ex))
567 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
568 if response['type'] == 'local':
569 return True
570 return False
571 raise F5ModuleError(resp.content)
572
573 def create(self):
574 self._set_changed_options()
575 if self.module.check_mode:
576 return True
577 self.update_auth_source_on_device('local')
578 return True
579
580 def present(self):
581 if not self.exists():
582 return self.create()
583
584 def absent(self):
585 raise F5ModuleError(
586 "The 'local' type cannot be removed. "
587 "Instead, specify a 'state' of 'present' on other types."
588 )
589
590
591 class TacacsManager(BaseManager):
592 def __init__(self, *args, **kwargs):
593 self.module = kwargs.get('module', None)
594 self.client = F5RestClient(**self.module.params)
595 self.want = self.get_module_parameters(params=self.module.params)
596 self.have = self.get_api_parameters()
597 self.changes = self.get_usable_changes()
598
599 @property
600 def returnables(self):
601 return TacacsParameters.returnables
602
603 @property
604 def updatables(self):
605 return TacacsParameters.updatables
606
607 def get_usable_changes(self, params=None):
608 return TacacsUsableChanges(params=params)
609
610 def get_reportable_changes(self, params=None):
611 return TacacsReportableChanges(params=params)
612
613 def get_module_parameters(self, params=None):
614 return TacacsModuleParameters(params=params)
615
616 def get_api_parameters(self, params=None):
617 return TacacsApiParameters(params=params)
618
619 def exists(self):
620 errors = [401, 403, 409, 500, 501, 502, 503, 504]
621 uri = "https://{0}:{1}/mgmt/tm/auth/tacacs/~Common~system-auth".format(
622 self.client.provider['server'],
623 self.client.provider['server_port'],
624 )
625 resp = self.client.api.get(uri)
626 try:
627 response = resp.json()
628 except ValueError as ex:
629 raise F5ModuleError(str(ex))
630
631 if resp.status == 404 or 'code' in response and response['code'] == 404:
632 return False
633 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
634 return True
635
636 if resp.status in errors or 'code' in response and response['code'] in errors:
637 if 'message' in response:
638 raise F5ModuleError(response['message'])
639 else:
640 raise F5ModuleError(resp.content)
641
642 def create(self):
643 self._set_changed_options()
644 if self.module.check_mode:
645 return True
646 self.create_on_device()
647 if self.want.use_for_auth:
648 self.update_auth_source_on_device('tacacs')
649 return True
650
651 def update(self):
652 self.have = self.read_current_from_device()
653 if not self.should_update():
654 return False
655 if self.module.check_mode:
656 return True
657 result = False
658 if self.update_on_device():
659 result = True
660 if self.want.use_for_auth and self.changes.auth_source == 'tacacs':
661 self.update_auth_source_on_device('tacacs')
662 result = True
663 return result
664
665 def remove(self):
666 if self.module.check_mode:
667 return True
668 self.update_auth_source_on_device('local')
669 self.remove_from_device()
670 if self.exists():
671 raise F5ModuleError("Failed to delete the resource.")
672 return True
673
674 def create_on_device(self):
675 params = self.changes.api_params()
676 params['name'] = 'system-auth'
677 uri = "https://{0}:{1}/mgmt/tm/auth/tacacs".format(
678 self.client.provider['server'],
679 self.client.provider['server_port']
680 )
681 resp = self.client.api.post(uri, json=params)
682 try:
683 response = resp.json()
684 except ValueError as ex:
685 raise F5ModuleError(str(ex))
686
687 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
688 return True
689 raise F5ModuleError(resp.content)
690
691 def update_on_device(self):
692 params = self.changes.api_params()
693 if not params:
694 return False
695
696 uri = 'https://{0}:{1}/mgmt/tm/auth/tacacs/~Common~system-auth'.format(
697 self.client.provider['server'],
698 self.client.provider['server_port']
699 )
700
701 resp = self.client.api.patch(uri, json=params)
702 try:
703 response = resp.json()
704 except ValueError as ex:
705 raise F5ModuleError(str(ex))
706
707 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
708 return True
709 raise F5ModuleError(resp.content)
710
711 def remove_from_device(self):
712 uri = "https://{0}:{1}/mgmt/tm/auth/tacacs/~Common~system-auth".format(
713 self.client.provider['server'],
714 self.client.provider['server_port']
715 )
716 response = self.client.api.delete(uri)
717
718 if response.status in [200, 201]:
719 return True
720 raise F5ModuleError(response.content)
721
722 def read_current_from_device(self):
723 uri = "https://{0}:{1}/mgmt/tm/auth/tacacs/~Common~system-auth".format(
724 self.client.provider['server'],
725 self.client.provider['server_port'],
726 )
727 resp = self.client.api.get(uri)
728 try:
729 response = resp.json()
730 except ValueError as ex:
731 raise F5ModuleError(str(ex))
732 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
733 response['auth_source'] = self.read_current_auth_source_from_device()
734 return self.get_api_parameters(params=response)
735 raise F5ModuleError(resp.content)
736
737
738 class ModuleManager(object):
739 def __init__(self, *args, **kwargs):
740 self.module = kwargs.get('module', None)
741 self.kwargs = kwargs
742
743 def exec_module(self):
744 manager = self.get_manager(self.module.params['type'])
745 return manager.exec_module()
746
747 def get_manager(self, type):
748 if type == 'tacacs':
749 return TacacsManager(**self.kwargs)
750 elif type == 'local':
751 return LocalManager(**self.kwargs)
752 else:
753 raise F5ModuleError(
754 "The provided 'type' is unknown."
755 )
756
757
758 class ArgumentSpec(object):
759 def __init__(self):
760 self.supports_check_mode = True
761 argument_spec = dict(
762 type=dict(
763 required=True,
764 choices=['local', 'tacacs']
765 ),
766 servers=dict(type='raw'),
767 secret=dict(no_log=True),
768 service_name=dict(
769 choices=[
770 'slip', 'ppp', 'arap', 'shell', 'tty-daemon',
771 'connection', 'system', 'firewall'
772 ]
773 ),
774 protocol_name=dict(
775 choices=[
776 'lcp', 'ip', 'ipx', 'atalk', 'vines', 'lat',
777 'xremote', 'tn3270', 'telnet', 'rlogin', 'pad',
778 'vpdn', 'ftp', 'http', 'deccp', 'osicp', 'unknown'
779 ]
780 ),
781 authentication=dict(
782 choices=[
783 'use-first-server',
784 'use-all-servers'
785 ]
786 ),
787 accounting=dict(
788 choices=[
789 'send-to-first-server',
790 'send-to-all-servers'
791 ]
792 ),
793 use_for_auth=dict(type='bool'),
794 update_secret=dict(
795 choices=['always', 'on_create'],
796 default='always'
797 ),
798 state=dict(
799 default='present',
800 choices=['present', 'absent']
801 ),
802
803 )
804 self.argument_spec = {}
805 self.argument_spec.update(f5_argument_spec)
806 self.argument_spec.update(argument_spec)
807
808
809 def main():
810 spec = ArgumentSpec()
811
812 module = AnsibleModule(
813 argument_spec=spec.argument_spec,
814 supports_check_mode=spec.supports_check_mode,
815 )
816
817 try:
818 mm = ModuleManager(module=module)
819 results = mm.exec_module()
820 module.exit_json(**results)
821 except F5ModuleError as ex:
822 module.fail_json(msg=str(ex))
823
824
825 if __name__ == '__main__':
826 main()