Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2019, 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_radius
13 short_description: Manages RADIUS auth configuration on a BIG-IP device
14 description:
15 - Module creates a RADIUS configuration.
16 version_added: "1.3.0"
17 options:
18 servers:
19 description:
20 - Specifies the names of RADIUS servers for use with RADIUS authentication profiles.
21 type: list
22 elements: str
23 accounting_bug:
24 description:
25 - Enables or disables validation of the accounting response vector.
26 - This option should be necessary only on older servers.
27 type: bool
28 retries:
29 description:
30 - Specifies the number of authentication retries the BIG-IP Local Traffic Management system allows before
31 authentication fails.
32 type: int
33 service_type:
34 description:
35 - Specifies the type of service requested from the RADIUS server. The default value is C(authenticate-only).
36 type: str
37 choices:
38 - authenticate-only
39 - login
40 - default
41 - framed
42 - callback-login
43 - callback-framed
44 - outbound
45 - administrative
46 - nas-prompt
47 - callback-nas-prompt
48 - call-check
49 - callback-administrative
50 fallback_to_local:
51 description:
52 - Specifies the system uses the Local authentication method if the remote
53 authentication method is not available.
54 - Option only available on C(TMOS 13.0.0) and above.
55 type: bool
56 use_for_auth:
57 description:
58 - Specifies whether or not this auth source is put in use on the system.
59 - If C(true), the module sets the current system auth type to the value of C(radius).
60 - If C(false), the module sets the authentication type to C(local), similar behavior to when C(state) is C(absent),
61 without removing the configured RADIUS resource.
62 type: bool
63 state:
64 description:
65 - When C(state) is C(present), ensures the RADIUS server exists.
66 - When C(state) is C(absent), ensures the RADIUS server is removed.
67 type: str
68 choices:
69 - present
70 - absent
71 default: present
72 extends_documentation_fragment: f5networks.f5_modules.f5
73 notes:
74 - This module is based on the command line (TMSH) configuration capabilities of RADIUS authentication,
75 not the GUI.
76 author:
77 - Andrey Kashcheev (@andreykashcheev)
78 - Wojciech Wypior (@wojtek0806)
79 '''
80
81 EXAMPLES = r'''
82 - name: Create an RADIUS device configuration
83 bigip_device_auth_radius:
84 servers:
85 - "ansible_test1"
86 - "ansible_test2"
87 retries: 3
88 service_type: authenticate-only
89 accounting_bug: false
90 use_for_auth: true
91 fallback_to_local: true
92 state: present
93 provider:
94 password: secret
95 server: lb.mydomain.com
96 user: admin
97 delegate_to: localhost
98
99 - name: Update an RADIUS device configuration
100 bigip_device_auth_radius:
101 retries: 5
102 service_type: administrative
103 accounting_bug: true
104 state: present
105 provider:
106 password: secret
107 server: lb.mydomain.com
108 user: admin
109 delegate_to: localhost
110
111 - name: Delete RADIUS auth configuration
112 bigip_device_auth_radius:
113 state: absent
114 provider:
115 password: secret
116 server: lb.mydomain.com
117 user: admin
118 delegate_to: localhost
119 '''
120
121 RETURN = r'''
122 servers:
123 description: The servers value of the resource.
124 returned: changed
125 type: list
126 sample: hash/dictionary of values
127 service_type:
128 description: Type of service requested from the RADIUS server.
129 returned: changed
130 type: str
131 sample: login
132 retries:
133 description: Number of authentication retries before authentication fails.
134 type: int
135 returned: changed
136 sample: 10
137 accounting_bug:
138 description: Enables or disables validation of the accounting response vector.
139 type: bool
140 returned: changed
141 sample: true
142 '''
143 from datetime import datetime
144 from ansible.module_utils.basic import AnsibleModule
145
146 from ..module_utils.bigip import F5RestClient
147 from ..module_utils.common import (
148 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name, is_empty_list
149 )
150 from ..module_utils.icontrol import tmos_version
151 from ..module_utils.teem import send_teem
152
153
154 class Parameters(AnsibleF5Parameters):
155 api_map = {
156 'serviceType': 'service_type',
157 'accountingBug': 'accounting_bug',
158 'fallback': 'fallback_to_local',
159 }
160
161 api_attributes = [
162 'accountingBug',
163 'serviceType',
164 'servers',
165 'retries',
166 ]
167
168 returnables = [
169 'accounting_bug',
170 'servers',
171 'service_type',
172 'retries',
173 'fallback_to_local',
174 ]
175
176 updatables = [
177 'accounting_bug',
178 'servers',
179 'service_type',
180 'retries',
181 'auth_source',
182 'fallback_to_local',
183 ]
184
185 @property
186 def fallback_to_local(self):
187 return flatten_boolean(self._values['fallback_to_local'])
188
189
190 class ApiParameters(Parameters):
191 pass
192
193
194 class ModuleParameters(Parameters):
195 @property
196 def accounting_bug(self):
197 result = flatten_boolean(self._values['accounting_bug'])
198 if result == 'yes':
199 return 'enabled'
200 if result == 'no':
201 return 'disabled'
202
203 @property
204 def use_for_auth(self):
205 return flatten_boolean(self._values['use_for_auth'])
206
207 @property
208 def auth_source(self):
209 if self._values['use_for_auth'] is None:
210 return None
211 if self.use_for_auth == 'yes':
212 return 'radius'
213 if self.use_for_auth == 'no':
214 return 'local'
215
216 @property
217 def servers(self):
218 if self._values['servers'] is None:
219 return None
220 if is_empty_list(self._values['servers']):
221 return []
222 result = list()
223 for item in self._values['servers']:
224 result.append(fq_name('Common', item))
225 return result
226
227
228 class Changes(Parameters):
229 def to_return(self):
230 result = {}
231 try:
232 for returnable in self.returnables:
233 result[returnable] = getattr(self, returnable)
234 result = self._filter_params(result)
235 except Exception:
236 raise
237 return result
238
239
240 class UsableChanges(Changes):
241 @property
242 def fallback_to_local(self):
243 if self._values['fallback_to_local'] is None:
244 return None
245 elif self._values['fallback_to_local'] == 'yes':
246 return 'true'
247 return 'false'
248
249
250 class ReportableChanges(Changes):
251 pass
252
253
254 class Difference(object):
255 def __init__(self, want, have=None):
256 self.want = want
257 self.have = have
258
259 def compare(self, param):
260 try:
261 result = getattr(self, param)
262 return result
263 except AttributeError:
264 return self.__default(param)
265
266 def __default(self, param):
267 want = getattr(self.want, param)
268 try:
269 have = getattr(self.have, param)
270 if want != have:
271 return want
272 except AttributeError:
273 return want
274
275
276 class ModuleManager(object):
277 def __init__(self, *args, **kwargs):
278 self.module = kwargs.get('module', None)
279 self.client = F5RestClient(**self.module.params)
280 self.want = ModuleParameters(params=self.module.params)
281 self.have = ApiParameters()
282 self.changes = UsableChanges()
283
284 def _set_changed_options(self):
285 changed = {}
286 for key in Parameters.returnables:
287 if getattr(self.want, key) is not None:
288 changed[key] = getattr(self.want, key)
289 if changed:
290 self.changes = UsableChanges(params=changed)
291
292 def _update_changed_options(self):
293 diff = Difference(self.want, self.have)
294 updatables = Parameters.updatables
295 changed = dict()
296 for k in updatables:
297 change = diff.compare(k)
298 if change is None:
299 continue
300 else:
301 if isinstance(change, dict):
302 changed.update(change)
303 else:
304 changed[k] = change
305 if changed:
306 self.changes = UsableChanges(params=changed)
307 return True
308 return False
309
310 def _announce_deprecations(self, result):
311 warnings = result.pop('__warnings', [])
312 for warning in warnings:
313 self.client.module.deprecate(
314 msg=warning['msg'],
315 version=warning['version']
316 )
317
318 def exec_module(self):
319 start = datetime.now().isoformat()
320 version = tmos_version(self.client)
321 changed = False
322 result = dict()
323 state = self.want.state
324
325 if state == "present":
326 changed = self.present()
327 elif state == "absent":
328 changed = self.absent()
329
330 reportable = ReportableChanges(params=self.changes.to_return())
331 changes = reportable.to_return()
332 result.update(**changes)
333 result.update(dict(changed=changed))
334 self._announce_deprecations(result)
335 send_teem(start, self.client, self.module, version)
336 return result
337
338 def present(self):
339 if self.exists():
340 return self.update()
341 else:
342 return self.create()
343
344 def absent(self):
345 if self.exists():
346 return self.remove()
347 return False
348
349 def should_update(self):
350 result = self._update_changed_options()
351 if result:
352 return True
353 return False
354
355 def update(self):
356 self.have = self.read_current_from_device()
357 if not self.should_update():
358 return False
359 if self.module.check_mode:
360 return True
361 self.update_on_device()
362 if self.want.fallback_to_local == 'yes':
363 self.update_fallback_on_device('true')
364 elif self.want.fallback_to_local == 'no':
365 self.update_fallback_on_device('false')
366 if self.want.use_for_auth and self.changes.auth_source:
367 self.update_auth_source_on_device(self.changes.auth_source)
368 return True
369
370 def remove(self):
371 if self.module.check_mode:
372 return True
373 self.update_auth_source_on_device('local')
374 self.remove_from_device()
375 if self.exists():
376 raise F5ModuleError("Failed to delete the resource.")
377 return True
378
379 def create(self):
380 self._set_changed_options()
381 if self.module.check_mode:
382 return True
383 self.create_on_device()
384 if self.want.fallback_to_local == 'yes':
385 self.update_fallback_on_device('true')
386 elif self.want.fallback_to_local == 'no':
387 self.update_fallback_on_device('false')
388 if self.want.use_for_auth:
389 self.update_auth_source_on_device(self.want.auth_source)
390 return True
391
392 def update_fallback_on_device(self, fallback):
393 params = dict(
394 fallback=fallback
395 )
396 uri = 'https://{0}:{1}/mgmt/tm/auth/source/'.format(
397 self.client.provider['server'],
398 self.client.provider['server_port']
399 )
400 resp = self.client.api.patch(uri, json=params)
401 try:
402 response = resp.json()
403 except ValueError as ex:
404 raise F5ModuleError(str(ex))
405
406 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
407 return True
408 raise F5ModuleError(resp.content)
409
410 def exists(self):
411 uri = "https://{0}:{1}/mgmt/tm/auth/radius/~Common~system-auth".format(
412 self.client.provider['server'],
413 self.client.provider['server_port'],
414 )
415 resp = self.client.api.get(uri)
416 try:
417 response = resp.json()
418 except ValueError as ex:
419 raise F5ModuleError(str(ex))
420
421 if resp.status == 404 or 'code' in response and response['code'] == 404:
422 return False
423 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
424 return True
425
426 errors = [401, 403, 409, 500, 501, 502, 503, 504]
427
428 if resp.status in errors or 'code' in response and response['code'] in errors:
429 if 'message' in response:
430 raise F5ModuleError(response['message'])
431 else:
432 raise F5ModuleError(resp.content)
433
434 def create_on_device(self):
435 params = self.changes.api_params()
436 params['name'] = 'system-auth'
437 params['partition'] = 'Common'
438 uri = 'https://{0}:{1}/mgmt/tm/auth/radius'.format(
439 self.client.provider['server'],
440 self.client.provider['server_port']
441 )
442 resp = self.client.api.post(uri, json=params)
443 try:
444 response = resp.json()
445 except ValueError as ex:
446 raise F5ModuleError(str(ex))
447
448 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
449 return True
450 raise F5ModuleError(resp.content)
451
452 def update_on_device(self):
453 params = self.changes.api_params()
454 if not params:
455 return
456 uri = "https://{0}:{1}/mgmt/tm/auth/radius/{2}".format(
457 self.client.provider['server'],
458 self.client.provider['server_port'],
459 transform_name('Common', 'system-auth')
460 )
461 resp = self.client.api.patch(uri, json=params)
462 try:
463 response = resp.json()
464 except ValueError as ex:
465 raise F5ModuleError(str(ex))
466
467 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
468 return True
469 raise F5ModuleError(resp.content)
470
471 def remove_from_device(self):
472 uri = "https://{0}:{1}/mgmt/tm/auth/radius/{2}".format(
473 self.client.provider['server'],
474 self.client.provider['server_port'],
475 transform_name('Common', 'system-auth')
476 )
477 response = self.client.api.delete(uri)
478
479 if response.status in [200, 201]:
480 return True
481 raise F5ModuleError(response.content)
482
483 def read_current_from_device(self):
484 uri = "https://{0}:{1}/mgmt/tm/auth/radius/{2}".format(
485 self.client.provider['server'],
486 self.client.provider['server_port'],
487 transform_name('Common', 'system-auth')
488 )
489 resp = self.client.api.get(uri)
490 try:
491 response = resp.json()
492 except ValueError as ex:
493 raise F5ModuleError(str(ex))
494
495 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
496 response.update(self.read_current_auth_source_from_device())
497 return ApiParameters(params=response)
498 raise F5ModuleError(resp.content)
499
500 def read_current_auth_source_from_device(self):
501 uri = "https://{0}:{1}/mgmt/tm/auth/source".format(
502 self.client.provider['server'],
503 self.client.provider['server_port'],
504 )
505 resp = self.client.api.get(uri)
506 try:
507 response = resp.json()
508 except ValueError as ex:
509 raise F5ModuleError(str(ex))
510 result = {}
511 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
512 if 'fallback' in response:
513 result['fallback'] = response['fallback']
514 if 'type' in response:
515 result['auth_source'] = response['type']
516 return result
517 raise F5ModuleError(resp.content)
518
519 def update_auth_source_on_device(self, source):
520 """Set the system auth source.
521
522 Configuring the authentication source is only one step in the process of setting
523 up an auth source. The other step is to inform the system of the auth source
524 you want to use.
525
526 This method is used for situations where
527
528 * The ``use_for_auth`` parameter is set to ``yes``
529 * The ``use_for_auth`` parameter is set to ``no``
530 * The ``state`` parameter is set to ``absent``
531
532 When ``state`` equal to ``absent``, before you can delete the Radius+ configuration,
533 you must set the system auth to "something else". The system ships with a system
534 auth called "local", so this is the logical "something else" to use.
535
536 When ``use_for_auth`` is no, the same situation applies as when ``state`` equal
537 to ``absent`` is done above.
538
539 When ``use_for_auth`` is ``yes``, this method will set the current system auth
540 state to Radius+.
541
542 Arguments:
543 source (string): The source that you want to set on the device.
544 """
545 params = dict(
546 type=source
547 )
548 uri = 'https://{0}:{1}/mgmt/tm/auth/source/'.format(
549 self.client.provider['server'],
550 self.client.provider['server_port']
551 )
552 resp = self.client.api.patch(uri, json=params)
553 try:
554 response = resp.json()
555 except ValueError as ex:
556 raise F5ModuleError(str(ex))
557
558 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
559 return True
560 raise F5ModuleError(resp.content)
561
562
563 class ArgumentSpec(object):
564 def __init__(self):
565 self.supports_check_mode = True
566 argument_spec = dict(
567 retries=dict(
568 type='int'
569 ),
570 service_type=dict(
571 choices=[
572 'authenticate-only',
573 'login',
574 'default',
575 'framed',
576 'callback-login',
577 'callback-framed',
578 'outbound',
579 'administrative',
580 'nas-prompt',
581 'callback-nas-prompt',
582 'call-check',
583 'callback-administrative'
584 ]
585 ),
586 accounting_bug=dict(
587 type='bool'
588 ),
589 servers=dict(
590 type='list',
591 elements='str',
592 ),
593 fallback_to_local=dict(type='bool'),
594 use_for_auth=dict(type='bool'),
595 state=dict(
596 default='present',
597 choices=['absent', 'present']
598 ),
599 )
600 self.argument_spec = {}
601 self.argument_spec.update(f5_argument_spec)
602 self.argument_spec.update(argument_spec)
603
604
605 def main():
606 spec = ArgumentSpec()
607
608 module = AnsibleModule(
609 argument_spec=spec.argument_spec,
610 supports_check_mode=spec.supports_check_mode,
611 )
612
613 try:
614 mm = ModuleManager(module=module)
615 results = mm.exec_module()
616 module.exit_json(**results)
617 except F5ModuleError as ex:
618 module.fail_json(msg=str(ex))
619
620
621 if __name__ == '__main__':
622 main()