| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
DOCUMENTATION = r''' |
| 11 |
--- |
| 12 |
module: bigip_user |
| 13 |
short_description: Manage user accounts and user attributes on a BIG-IP |
| 14 |
description: |
| 15 |
- Manage user accounts and user attributes on a BIG-IP system. Typically this |
| 16 |
module operates only on REST API users and not CLI users. |
| 17 |
When specifying C(root), you may only change the password. |
| 18 |
Your other parameters are ignored in this case. Changing the C(root) |
| 19 |
password is not an idempotent operation. Therefore, it changes the |
| 20 |
password every time this module attempts to change it. |
| 21 |
version_added: "1.0.0" |
| 22 |
options: |
| 23 |
full_name: |
| 24 |
description: |
| 25 |
- Full name of the user. |
| 26 |
type: str |
| 27 |
username_credential: |
| 28 |
description: |
| 29 |
- Name of the user to create, remove, or modify. |
| 30 |
- The C(root) user may not be removed. |
| 31 |
type: str |
| 32 |
required: True |
| 33 |
aliases: |
| 34 |
- name |
| 35 |
password_credential: |
| 36 |
description: |
| 37 |
- Set the user's password to this unencrypted value. |
| 38 |
C(password_credential) is required when creating a new account. |
| 39 |
type: str |
| 40 |
shell: |
| 41 |
description: |
| 42 |
- Optionally set the users shell. |
| 43 |
type: str |
| 44 |
choices: |
| 45 |
- bash |
| 46 |
- none |
| 47 |
- tmsh |
| 48 |
partition_access: |
| 49 |
description: |
| 50 |
- Specifies the administrative partition to which the user has access. |
| 51 |
C(partition_access) is required when creating a new account, and |
| 52 |
should be in the form "partition:role". |
| 53 |
- Valid roles include C(acceleration-policy-editor), C(admin), C(application-editor), |
| 54 |
C(auditor), C(certificate-manager), C(guest), C(irule-manager), C(manager), C(no-access), |
| 55 |
C(operator), C(resource-admin), C(user-manager), C(web-application-security-administrator), |
| 56 |
and C(web-application-security-editor). |
| 57 |
- The partition portion the of tuple should be an existing partition or the value 'all'. |
| 58 |
type: list |
| 59 |
elements: str |
| 60 |
state: |
| 61 |
description: |
| 62 |
- Whether the account should exist or not, taking action if the state is |
| 63 |
different from what is stated. |
| 64 |
type: str |
| 65 |
choices: |
| 66 |
- present |
| 67 |
- absent |
| 68 |
default: present |
| 69 |
update_password: |
| 70 |
description: |
| 71 |
- C(always) allows the user to update passwords. |
| 72 |
C(on_create) only sets the password for newly created users. |
| 73 |
- When C(username_credential) is C(root), this value is forced to C(always). |
| 74 |
type: str |
| 75 |
choices: |
| 76 |
- always |
| 77 |
- on_create |
| 78 |
default: always |
| 79 |
partition: |
| 80 |
description: |
| 81 |
- Device partition to manage resources on. |
| 82 |
type: str |
| 83 |
default: Common |
| 84 |
notes: |
| 85 |
- Requires BIG-IP versions >= 12.0.0 |
| 86 |
extends_documentation_fragment: f5networks.f5_modules.f5 |
| 87 |
author: |
| 88 |
- Tim Rupp (@caphrim007) |
| 89 |
- Wojciech Wypior (@wojtek0806) |
| 90 |
''' |
| 91 |
|
| 92 |
EXAMPLES = r''' |
| 93 |
- name: Add the user 'johnd' as an admin |
| 94 |
bigip_user: |
| 95 |
username_credential: johnd |
| 96 |
password_credential: password |
| 97 |
full_name: John Doe |
| 98 |
partition_access: |
| 99 |
- all:admin |
| 100 |
update_password: on_create |
| 101 |
state: present |
| 102 |
provider: |
| 103 |
server: lb.mydomain.com |
| 104 |
user: admin |
| 105 |
password: secret |
| 106 |
delegate_to: localhost |
| 107 |
|
| 108 |
- name: Change the user "johnd's" role and shell |
| 109 |
bigip_user: |
| 110 |
username_credential: johnd |
| 111 |
partition_access: |
| 112 |
- NewPartition:manager |
| 113 |
shell: tmsh |
| 114 |
state: present |
| 115 |
provider: |
| 116 |
server: lb.mydomain.com |
| 117 |
user: admin |
| 118 |
password: secret |
| 119 |
delegate_to: localhost |
| 120 |
|
| 121 |
- name: Make the user 'johnd' an admin and set to advanced shell |
| 122 |
bigip_user: |
| 123 |
name: johnd |
| 124 |
partition_access: |
| 125 |
- all:admin |
| 126 |
shell: bash |
| 127 |
state: present |
| 128 |
provider: |
| 129 |
server: lb.mydomain.com |
| 130 |
user: admin |
| 131 |
password: secret |
| 132 |
delegate_to: localhost |
| 133 |
|
| 134 |
- name: Remove the user 'johnd' |
| 135 |
bigip_user: |
| 136 |
name: johnd |
| 137 |
state: absent |
| 138 |
provider: |
| 139 |
server: lb.mydomain.com |
| 140 |
user: admin |
| 141 |
password: secret |
| 142 |
delegate_to: localhost |
| 143 |
|
| 144 |
- name: Update password |
| 145 |
bigip_user: |
| 146 |
state: present |
| 147 |
username_credential: johnd |
| 148 |
password_credential: newsupersecretpassword |
| 149 |
provider: |
| 150 |
server: lb.mydomain.com |
| 151 |
user: admin |
| 152 |
password: secret |
| 153 |
delegate_to: localhost |
| 154 |
|
| 155 |
# Note that the second time this task runs, it would fail because |
| 156 |
# The password has been changed. Therefore, it is recommended that |
| 157 |
# you either, |
| 158 |
# |
| 159 |
# * Put this in its own playbook that you run when you need to |
| 160 |
# * Put this task in a `block` |
| 161 |
# * Include `ignore_errors` on this task |
| 162 |
- name: Change the Admin password |
| 163 |
bigip_user: |
| 164 |
state: present |
| 165 |
username_credential: admin |
| 166 |
password_credential: NewSecretPassword |
| 167 |
provider: |
| 168 |
server: lb.mydomain.com |
| 169 |
user: admin |
| 170 |
password: secret |
| 171 |
delegate_to: localhost |
| 172 |
|
| 173 |
- name: Change the root user's password |
| 174 |
bigip_user: |
| 175 |
username_credential: root |
| 176 |
password_credential: secret |
| 177 |
state: present |
| 178 |
provider: |
| 179 |
server: lb.mydomain.com |
| 180 |
user: admin |
| 181 |
password: secret |
| 182 |
delegate_to: localhost |
| 183 |
''' |
| 184 |
|
| 185 |
RETURN = r''' |
| 186 |
full_name: |
| 187 |
description: Full name of the user. |
| 188 |
returned: changed and success |
| 189 |
type: str |
| 190 |
sample: John Doe |
| 191 |
partition_access: |
| 192 |
description: |
| 193 |
- List of strings containing the user's roles and to which partitions they |
| 194 |
are applied. They are specified in the form "partition:role". |
| 195 |
returned: changed and success |
| 196 |
type: list |
| 197 |
sample: ['all:admin'] |
| 198 |
shell: |
| 199 |
description: The shell assigned to the user account. |
| 200 |
returned: changed and success |
| 201 |
type: str |
| 202 |
sample: tmsh |
| 203 |
''' |
| 204 |
|
| 205 |
import os |
| 206 |
import tempfile |
| 207 |
import traceback |
| 208 |
from datetime import datetime |
| 209 |
|
| 210 |
try: |
| 211 |
from packaging.version import Version |
| 212 |
except ImportError: |
| 213 |
HAS_PACKAGING = False |
| 214 |
Version = None |
| 215 |
PACKAGING_IMPORT_ERROR = traceback.format_exc() |
| 216 |
else: |
| 217 |
HAS_PACKAGING = True |
| 218 |
PACKAGING_IMPORT_ERROR = None |
| 219 |
|
| 220 |
try: |
| 221 |
from BytesIO import BytesIO |
| 222 |
except ImportError: |
| 223 |
from io import BytesIO |
| 224 |
|
| 225 |
from ansible.module_utils.basic import ( |
| 226 |
AnsibleModule, env_fallback, missing_required_lib |
| 227 |
) |
| 228 |
from ansible.module_utils.six import string_types |
| 229 |
from ansible.module_utils._text import to_bytes |
| 230 |
|
| 231 |
from ..module_utils.bigip import F5RestClient |
| 232 |
from ..module_utils.common import ( |
| 233 |
F5ModuleError, AnsibleF5Parameters, f5_argument_spec, is_empty_list |
| 234 |
) |
| 235 |
from ..module_utils.icontrol import ( |
| 236 |
tmos_version, upload_file |
| 237 |
) |
| 238 |
from ..module_utils.teem import send_teem |
| 239 |
|
| 240 |
try: |
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 249 |
|
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
|
| 256 |
|
| 257 |
|
| 258 |
|
| 259 |
|
| 260 |
from cryptography.hazmat.backends import default_backend |
| 261 |
from cryptography.hazmat.primitives import serialization |
| 262 |
from cryptography.hazmat.primitives.asymmetric import padding |
| 263 |
HAS_CRYPTO = True |
| 264 |
except ImportError: |
| 265 |
HAS_CRYPTO = False |
| 266 |
|
| 267 |
|
| 268 |
class Parameters(AnsibleF5Parameters): |
| 269 |
api_map = { |
| 270 |
'partitionAccess': 'partition_access', |
| 271 |
'description': 'full_name', |
| 272 |
} |
| 273 |
|
| 274 |
updatables = [ |
| 275 |
'partition_access', |
| 276 |
'full_name', |
| 277 |
'shell', |
| 278 |
'password_credential', |
| 279 |
] |
| 280 |
|
| 281 |
returnables = [ |
| 282 |
'shell', |
| 283 |
'partition_access', |
| 284 |
'full_name', |
| 285 |
'username_credential', |
| 286 |
'password_credential', |
| 287 |
] |
| 288 |
|
| 289 |
api_attributes = [ |
| 290 |
'shell', |
| 291 |
'partitionAccess', |
| 292 |
'description', |
| 293 |
'name', |
| 294 |
'password', |
| 295 |
] |
| 296 |
|
| 297 |
@property |
| 298 |
def temp_upload_file(self): |
| 299 |
if self._values['temp_upload_file'] is None: |
| 300 |
f = tempfile.NamedTemporaryFile() |
| 301 |
name = os.path.basename(f.name) |
| 302 |
self._values['temp_upload_file'] = name |
| 303 |
return self._values['temp_upload_file'] |
| 304 |
|
| 305 |
|
| 306 |
class ApiParameters(Parameters): |
| 307 |
@property |
| 308 |
def partition_access(self): |
| 309 |
if self._values['partition_access'] is None: |
| 310 |
return None |
| 311 |
result = [] |
| 312 |
part_access = self._values['partition_access'] |
| 313 |
for access in part_access: |
| 314 |
if isinstance(access, dict): |
| 315 |
if 'nameReference' in access: |
| 316 |
del access['nameReference'] |
| 317 |
result.append(access) |
| 318 |
else: |
| 319 |
result.append(access) |
| 320 |
return result |
| 321 |
|
| 322 |
|
| 323 |
class ModuleParameters(Parameters): |
| 324 |
@property |
| 325 |
def partition_access(self): |
| 326 |
if self._values['partition_access'] is None: |
| 327 |
return None |
| 328 |
if is_empty_list(self._values['partition_access']): |
| 329 |
return [] |
| 330 |
result = [] |
| 331 |
part_access = self._values['partition_access'] |
| 332 |
for access in part_access: |
| 333 |
if isinstance(access, string_types): |
| 334 |
acl = access.split(':') |
| 335 |
if acl[0].lower() == 'all': |
| 336 |
acl[0] = 'all-partitions' |
| 337 |
value = dict( |
| 338 |
name=acl[0], |
| 339 |
role=acl[1] |
| 340 |
) |
| 341 |
result.append(value) |
| 342 |
return result |
| 343 |
|
| 344 |
|
| 345 |
class Changes(Parameters): |
| 346 |
def to_return(self): |
| 347 |
result = {} |
| 348 |
for returnable in self.returnables: |
| 349 |
try: |
| 350 |
result[returnable] = getattr(self, returnable) |
| 351 |
except Exception: |
| 352 |
pass |
| 353 |
result = self._filter_params(result) |
| 354 |
return result |
| 355 |
|
| 356 |
|
| 357 |
class UsableChanges(Changes): |
| 358 |
@property |
| 359 |
def password(self): |
| 360 |
if self._values['password_credential'] is None: |
| 361 |
return None |
| 362 |
return self._values['password_credential'] |
| 363 |
|
| 364 |
|
| 365 |
class ReportableChanges(Changes): |
| 366 |
@property |
| 367 |
def partition_access(self): |
| 368 |
if self._values['partition_access'] is None: |
| 369 |
return None |
| 370 |
result = [] |
| 371 |
part_access = self._values['partition_access'] |
| 372 |
for access in part_access: |
| 373 |
if access['name'] == 'all-partitions': |
| 374 |
name = 'all' |
| 375 |
else: |
| 376 |
name = access['name'] |
| 377 |
role = access['role'] |
| 378 |
result.append(('{0}:{1}'.format(name, role))) |
| 379 |
return result |
| 380 |
|
| 381 |
|
| 382 |
class Difference(object): |
| 383 |
def __init__(self, want, have=None): |
| 384 |
self.want = want |
| 385 |
self.have = have |
| 386 |
|
| 387 |
def compare(self, param): |
| 388 |
try: |
| 389 |
result = getattr(self, param) |
| 390 |
return result |
| 391 |
except AttributeError: |
| 392 |
return self.__default(param) |
| 393 |
|
| 394 |
def __default(self, param): |
| 395 |
attr1 = getattr(self.want, param) |
| 396 |
try: |
| 397 |
attr2 = getattr(self.have, param) |
| 398 |
if attr1 != attr2: |
| 399 |
return attr1 |
| 400 |
except AttributeError: |
| 401 |
return attr1 |
| 402 |
|
| 403 |
@property |
| 404 |
def password_credential(self): |
| 405 |
if self.want.password_credential is None: |
| 406 |
return None |
| 407 |
if self.want.update_password in ['always']: |
| 408 |
return self.want.password_credential |
| 409 |
return None |
| 410 |
|
| 411 |
@property |
| 412 |
def shell(self): |
| 413 |
if self.want.shell == 'none' and self.have.shell is None: |
| 414 |
return None |
| 415 |
if self.want.shell == 'bash': |
| 416 |
self._validate_shell_parameter() |
| 417 |
if self.want.shell == self.have.shell: |
| 418 |
return None |
| 419 |
else: |
| 420 |
return self.want.shell |
| 421 |
if self.want.shell != self.have.shell: |
| 422 |
return self.want.shell |
| 423 |
|
| 424 |
def _validate_shell_parameter(self): |
| 425 |
"""Method to validate shell parameters. |
| 426 |
|
| 427 |
Raise when shell attribute is set to 'bash' with roles set to |
| 428 |
either 'admin' or 'resource-admin'. |
| 429 |
|
| 430 |
NOTE: Admin and Resource-Admin roles automatically enable access to |
| 431 |
all partitions, removing any other roles that the user might have |
| 432 |
had. There are few other roles which do that but those roles, |
| 433 |
do not allow bash. |
| 434 |
""" |
| 435 |
|
| 436 |
err = "Shell access is only available to " \ |
| 437 |
"'admin' or 'resource-admin' roles." |
| 438 |
permit = ['admin', 'resource-admin'] |
| 439 |
|
| 440 |
have = self.have.partition_access |
| 441 |
if not any(r['role'] for r in have if r['role'] in permit): |
| 442 |
raise F5ModuleError(err) |
| 443 |
|
| 444 |
if self.want.partition_access is not None: |
| 445 |
want = self.want.partition_access |
| 446 |
if not any(r['role'] for r in want if r['role'] in permit): |
| 447 |
raise F5ModuleError(err) |
| 448 |
|
| 449 |
|
| 450 |
class ModuleManager(object): |
| 451 |
def __init__(self, *args, **kwargs): |
| 452 |
self.module = kwargs.get('module', None) |
| 453 |
self.client = F5RestClient(**self.module.params) |
| 454 |
self.kwargs = kwargs |
| 455 |
|
| 456 |
def exec_module(self): |
| 457 |
if self.is_root_username_credential(): |
| 458 |
manager = self.get_manager('root') |
| 459 |
elif self.is_version_less_than_13(): |
| 460 |
manager = self.get_manager('v1') |
| 461 |
else: |
| 462 |
manager = self.get_manager('v2') |
| 463 |
return manager.exec_module() |
| 464 |
|
| 465 |
def get_manager(self, type): |
| 466 |
if type == 'root': |
| 467 |
return RootUserManager(**self.kwargs) |
| 468 |
elif type == 'v1': |
| 469 |
return UnpartitionedManager(**self.kwargs) |
| 470 |
elif type == 'v2': |
| 471 |
return PartitionedManager(**self.kwargs) |
| 472 |
|
| 473 |
def is_version_less_than_13(self): |
| 474 |
"""Checks to see if the TMOS version is less than 13 |
| 475 |
|
| 476 |
Anything less than BIG-IP 13.x does not support users |
| 477 |
on different partitions. |
| 478 |
|
| 479 |
:return: Bool |
| 480 |
""" |
| 481 |
version = tmos_version(self.client) |
| 482 |
if Version(version) < Version('13.0.0'): |
| 483 |
return True |
| 484 |
else: |
| 485 |
return False |
| 486 |
|
| 487 |
def is_root_username_credential(self): |
| 488 |
user = self.module.params.get('username_credential', None) |
| 489 |
if user == 'root': |
| 490 |
return True |
| 491 |
return False |
| 492 |
|
| 493 |
|
| 494 |
class BaseManager(object): |
| 495 |
def __init__(self, *args, **kwargs): |
| 496 |
self.module = kwargs.get('module', None) |
| 497 |
self.client = F5RestClient(**self.module.params) |
| 498 |
self.want = ModuleParameters(params=self.module.params) |
| 499 |
self.have = ApiParameters() |
| 500 |
self.changes = UsableChanges() |
| 501 |
|
| 502 |
def _announce_deprecations(self, result): |
| 503 |
warnings = result.pop('__warnings', []) |
| 504 |
for warning in warnings: |
| 505 |
self.module.deprecate( |
| 506 |
msg=warning['msg'], |
| 507 |
version=warning['version'] |
| 508 |
) |
| 509 |
|
| 510 |
def _set_changed_options(self): |
| 511 |
changed = {} |
| 512 |
for key in Parameters.returnables: |
| 513 |
if getattr(self.want, key) is not None: |
| 514 |
changed[key] = getattr(self.want, key) |
| 515 |
if changed: |
| 516 |
self.changes = UsableChanges(params=changed) |
| 517 |
|
| 518 |
def _update_changed_options(self): |
| 519 |
diff = Difference(self.want, self.have) |
| 520 |
updatables = Parameters.updatables |
| 521 |
changed = dict() |
| 522 |
for k in updatables: |
| 523 |
change = diff.compare(k) |
| 524 |
if change is None: |
| 525 |
continue |
| 526 |
else: |
| 527 |
if isinstance(change, dict): |
| 528 |
changed.update(change) |
| 529 |
else: |
| 530 |
changed[k] = change |
| 531 |
if changed: |
| 532 |
self.changes = UsableChanges(params=changed) |
| 533 |
return True |
| 534 |
return False |
| 535 |
|
| 536 |
def exec_module(self): |
| 537 |
start = datetime.now().isoformat() |
| 538 |
version = tmos_version(self.client) |
| 539 |
changed = False |
| 540 |
result = dict() |
| 541 |
state = self.want.state |
| 542 |
|
| 543 |
if state == "present": |
| 544 |
changed = self.present() |
| 545 |
elif state == "absent": |
| 546 |
changed = self.absent() |
| 547 |
|
| 548 |
reportable = ReportableChanges(params=self.changes.to_return()) |
| 549 |
changes = reportable.to_return() |
| 550 |
result.update(**changes) |
| 551 |
result.update(dict(changed=changed)) |
| 552 |
self._announce_deprecations(result) |
| 553 |
send_teem(start, self.client, self.module, version) |
| 554 |
return result |
| 555 |
|
| 556 |
def present(self): |
| 557 |
if self.exists(): |
| 558 |
return self.update() |
| 559 |
else: |
| 560 |
return self.create() |
| 561 |
|
| 562 |
def absent(self): |
| 563 |
if self.exists(): |
| 564 |
return self.remove() |
| 565 |
return False |
| 566 |
|
| 567 |
def should_update(self): |
| 568 |
result = self._update_changed_options() |
| 569 |
if result: |
| 570 |
return True |
| 571 |
return False |
| 572 |
|
| 573 |
def update(self): |
| 574 |
self.have = self.read_current_from_device() |
| 575 |
if not self.should_update(): |
| 576 |
return False |
| 577 |
if self.module.check_mode: |
| 578 |
return True |
| 579 |
self.update_on_device() |
| 580 |
return True |
| 581 |
|
| 582 |
def remove(self): |
| 583 |
if self.module.check_mode: |
| 584 |
return True |
| 585 |
self.remove_from_device() |
| 586 |
if self.exists(): |
| 587 |
raise F5ModuleError("Failed to delete the user.") |
| 588 |
return True |
| 589 |
|
| 590 |
def create(self): |
| 591 |
self.validate_create_parameters() |
| 592 |
if self.want.shell == 'bash': |
| 593 |
self.validate_shell_parameter() |
| 594 |
self._set_changed_options() |
| 595 |
if self.module.check_mode: |
| 596 |
return True |
| 597 |
self.create_on_device() |
| 598 |
return True |
| 599 |
|
| 600 |
def validate_shell_parameter(self): |
| 601 |
"""Method to validate shell parameters. |
| 602 |
|
| 603 |
Raise when shell attribute is set to 'bash' with roles set to |
| 604 |
either 'admin' or 'resource-admin'. |
| 605 |
|
| 606 |
NOTE: Admin and Resource-Admin roles automatically enable access to |
| 607 |
all partitions, removing any other roles that the user might have |
| 608 |
had. There are few other roles which do that but those roles, |
| 609 |
do not allow bash. |
| 610 |
""" |
| 611 |
|
| 612 |
err = "Shell access is only available to " \ |
| 613 |
"'admin' or 'resource-admin' roles." |
| 614 |
permit = ['admin', 'resource-admin'] |
| 615 |
|
| 616 |
if self.want.partition_access is not None: |
| 617 |
want = self.want.partition_access |
| 618 |
if not any(r['role'] for r in want if r['role'] in permit): |
| 619 |
raise F5ModuleError(err) |
| 620 |
|
| 621 |
def validate_create_parameters(self): |
| 622 |
if self.want.partition_access is None: |
| 623 |
err = "The 'partition_access' option " \ |
| 624 |
"is required when creating a resource." |
| 625 |
raise F5ModuleError(err) |
| 626 |
|
| 627 |
|
| 628 |
class UnpartitionedManager(BaseManager): |
| 629 |
def exists(self): |
| 630 |
uri = "https://{0}:{1}/mgmt/tm/auth/user/{2}".format( |
| 631 |
self.client.provider['server'], |
| 632 |
self.client.provider['server_port'], |
| 633 |
self.want.username_credential |
| 634 |
) |
| 635 |
resp = self.client.api.get(uri) |
| 636 |
try: |
| 637 |
response = resp.json() |
| 638 |
except ValueError as ex: |
| 639 |
raise F5ModuleError(str(ex)) |
| 640 |
|
| 641 |
if resp.status == 404 or 'code' in response and response['code'] == 404: |
| 642 |
return False |
| 643 |
if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]: |
| 644 |
return True |
| 645 |
|
| 646 |
errors = [401, 403, 409, 500, 501, 502, 503, 504] |
| 647 |
|
| 648 |
if resp.status in errors or 'code' in response and response['code'] in errors: |
| 649 |
if 'message' in response: |
| 650 |
raise F5ModuleError(response['message']) |
| 651 |
else: |
| 652 |
raise F5ModuleError(resp.content) |
| 653 |
|
| 654 |
def create_on_device(self): |
| 655 |
params = self.changes.api_params() |
| 656 |
params['name'] = self.want.username_credential |
| 657 |
uri = "https://{0}:{1}/mgmt/tm/auth/user/".format( |
| 658 |
self.client.provider['server'], |
| 659 |
self.client.provider['server_port'] |
| 660 |
) |
| 661 |
resp = self.client.api.post(uri, json=params) |
| 662 |
try: |
| 663 |
response = resp.json() |
| 664 |
except ValueError as ex: |
| 665 |
raise F5ModuleError(str(ex)) |
| 666 |
|
| 667 |
if 'code' in response and response['code'] in [400, 403]: |
| 668 |
if 'message' in response: |
| 669 |
raise F5ModuleError(response['message']) |
| 670 |
else: |
| 671 |
raise F5ModuleError(resp.content) |
| 672 |
return response['selfLink'] |
| 673 |
|
| 674 |
def update_on_device(self): |
| 675 |
params = self.changes.api_params() |
| 676 |
uri = "https://{0}:{1}/mgmt/tm/auth/user/{2}".format( |
| 677 |
self.client.provider['server'], |
| 678 |
self.client.provider['server_port'], |
| 679 |
self.want.username_credential |
| 680 |
) |
| 681 |
resp = self.client.api.patch(uri, json=params) |
| 682 |
try: |
| 683 |
response = resp.json() |
| 684 |
except ValueError as ex: |
| 685 |
raise F5ModuleError(str(ex)) |
| 686 |
|
| 687 |
if 'code' in response and response['code'] == 400: |
| 688 |
if 'message' in response: |
| 689 |
raise F5ModuleError(response['message']) |
| 690 |
else: |
| 691 |
raise F5ModuleError(resp.content) |
| 692 |
|
| 693 |
def remove_from_device(self): |
| 694 |
uri = "https://{0}:{1}/mgmt/tm/auth/user/{2}".format( |
| 695 |
self.client.provider['server'], |
| 696 |
self.client.provider['server_port'], |
| 697 |
self.want.username_credential |
| 698 |
) |
| 699 |
response = self.client.api.delete(uri) |
| 700 |
if response.status == 200: |
| 701 |
return True |
| 702 |
raise F5ModuleError(response.content) |
| 703 |
|
| 704 |
def read_current_from_device(self): |
| 705 |
uri = "https://{0}:{1}/mgmt/tm/auth/user/{2}".format( |
| 706 |
self.client.provider['server'], |
| 707 |
self.client.provider['server_port'], |
| 708 |
self.want.username_credential |
| 709 |
) |
| 710 |
resp = self.client.api.get(uri) |
| 711 |
try: |
| 712 |
response = resp.json() |
| 713 |
except ValueError as ex: |
| 714 |
raise F5ModuleError(str(ex)) |
| 715 |
|
| 716 |
if 'code' in response and response['code'] == 400: |
| 717 |
if 'message' in response: |
| 718 |
raise F5ModuleError(response['message']) |
| 719 |
else: |
| 720 |
raise F5ModuleError(resp.content) |
| 721 |
return ApiParameters(params=response) |
| 722 |
|
| 723 |
|
| 724 |
class PartitionedManager(BaseManager): |
| 725 |
def exists(self): |
| 726 |
response = self.list_users_on_device() |
| 727 |
if 'items' in response: |
| 728 |
collection = [x for x in response['items'] if x['name'] == self.want.username_credential] |
| 729 |
if len(collection) == 1: |
| 730 |
return True |
| 731 |
elif len(collection) == 0: |
| 732 |
return False |
| 733 |
else: |
| 734 |
raise F5ModuleError( |
| 735 |
"Multiple users with the provided name were found!" |
| 736 |
) |
| 737 |
return False |
| 738 |
|
| 739 |
def create_on_device(self): |
| 740 |
params = self.changes.api_params() |
| 741 |
params['name'] = self.want.username_credential |
| 742 |
params['partition'] = self.want.partition |
| 743 |
uri = "https://{0}:{1}/mgmt/tm/auth/user/".format( |
| 744 |
self.client.provider['server'], |
| 745 |
self.client.provider['server_port'] |
| 746 |
) |
| 747 |
resp = self.client.api.post(uri, json=params) |
| 748 |
try: |
| 749 |
response = resp.json() |
| 750 |
except ValueError as ex: |
| 751 |
raise F5ModuleError(str(ex)) |
| 752 |
if 'code' in response and response['code'] in [400, 404, 409, 403]: |
| 753 |
if 'message' in response: |
| 754 |
raise F5ModuleError(response['message']) |
| 755 |
else: |
| 756 |
raise F5ModuleError(resp.content) |
| 757 |
return True |
| 758 |
|
| 759 |
def read_current_from_device(self): |
| 760 |
response = self.list_users_on_device() |
| 761 |
collection = [x for x in response['items'] if x['name'] == self.want.username_credential] |
| 762 |
if len(collection) == 1: |
| 763 |
user = collection.pop() |
| 764 |
return ApiParameters(params=user) |
| 765 |
elif len(collection) == 0: |
| 766 |
raise F5ModuleError( |
| 767 |
"No accounts with the provided name were found." |
| 768 |
) |
| 769 |
else: |
| 770 |
raise F5ModuleError( |
| 771 |
"Multiple users with the provided name were found!" |
| 772 |
) |
| 773 |
|
| 774 |
def update_on_device(self): |
| 775 |
params = self.changes.api_params() |
| 776 |
uri = "https://{0}:{1}/mgmt/tm/auth/user/{2}".format( |
| 777 |
self.client.provider['server'], |
| 778 |
self.client.provider['server_port'], |
| 779 |
self.want.username_credential |
| 780 |
) |
| 781 |
resp = self.client.api.patch(uri, json=params) |
| 782 |
try: |
| 783 |
response = resp.json() |
| 784 |
except ValueError as ex: |
| 785 |
raise F5ModuleError(str(ex)) |
| 786 |
|
| 787 |
if 'code' in response and response['code'] in [400, 404, 409, 403]: |
| 788 |
if 'message' in response: |
| 789 |
if 'updated successfully' not in response['message']: |
| 790 |
raise F5ModuleError(response['message']) |
| 791 |
else: |
| 792 |
raise F5ModuleError(resp.content) |
| 793 |
|
| 794 |
def remove_from_device(self): |
| 795 |
uri = "https://{0}:{1}/mgmt/tm/auth/user/{2}".format( |
| 796 |
self.client.provider['server'], |
| 797 |
self.client.provider['server_port'], |
| 798 |
self.want.username_credential |
| 799 |
) |
| 800 |
response = self.client.api.delete(uri) |
| 801 |
if response.status == 200: |
| 802 |
return True |
| 803 |
raise F5ModuleError(response.content) |
| 804 |
|
| 805 |
def list_users_on_device(self): |
| 806 |
uri = "https://{0}:{1}/mgmt/tm/auth/user/".format( |
| 807 |
self.client.provider['server'], |
| 808 |
self.client.provider['server_port'], |
| 809 |
) |
| 810 |
query = "?$filter=partition+eq+'{0}'".format(self.want.partition) |
| 811 |
resp = self.client.api.get(uri + query) |
| 812 |
try: |
| 813 |
response = resp.json() |
| 814 |
except ValueError as ex: |
| 815 |
raise F5ModuleError(str(ex)) |
| 816 |
|
| 817 |
if 'code' in response and response['code'] == 400: |
| 818 |
if 'message' in response: |
| 819 |
raise F5ModuleError(response['message']) |
| 820 |
else: |
| 821 |
raise F5ModuleError(resp.content) |
| 822 |
return response |
| 823 |
|
| 824 |
|
| 825 |
class RootUserManager(BaseManager): |
| 826 |
def exec_module(self): |
| 827 |
if not HAS_CRYPTO: |
| 828 |
raise F5ModuleError( |
| 829 |
"An installed and up-to-date python 'cryptography' package is " |
| 830 |
"required to change the 'root' password." |
| 831 |
) |
| 832 |
|
| 833 |
start = datetime.now().isoformat() |
| 834 |
version = tmos_version(self.client) |
| 835 |
changed = False |
| 836 |
result = dict() |
| 837 |
state = self.want.state |
| 838 |
|
| 839 |
if state == "present": |
| 840 |
changed = self.present() |
| 841 |
elif state == "absent": |
| 842 |
raise F5ModuleError( |
| 843 |
"You may not remove the root user." |
| 844 |
) |
| 845 |
|
| 846 |
reportable = ReportableChanges(params=self.changes.to_return()) |
| 847 |
changes = reportable.to_return() |
| 848 |
result.update(**changes) |
| 849 |
result.update(dict(changed=changed)) |
| 850 |
self._announce_deprecations(result) |
| 851 |
send_teem(start, self.client, self.module, version) |
| 852 |
return result |
| 853 |
|
| 854 |
def exists(self): |
| 855 |
return True |
| 856 |
|
| 857 |
def update(self): |
| 858 |
public_key = self.get_public_key_from_device() |
| 859 |
public_key = self.extract_key(public_key) |
| 860 |
encrypted = self.encrypt_password_change_file( |
| 861 |
public_key, self.want.password_credential |
| 862 |
) |
| 863 |
self.upload_to_device(encrypted, self.want.temp_upload_file) |
| 864 |
result = self.update_on_device() |
| 865 |
self.remove_uploaded_file_from_device(self.want.temp_upload_file) |
| 866 |
return result |
| 867 |
|
| 868 |
def encrypt_password_change_file(self, public_key, password): |
| 869 |
|
| 870 |
pub = serialization.load_pem_public_key( |
| 871 |
to_bytes(public_key), |
| 872 |
backend=default_backend() |
| 873 |
) |
| 874 |
|
| 875 |
message = to_bytes("{0}\n{0}\n".format(password)) |
| 876 |
ciphertext = pub.encrypt( |
| 877 |
message, |
| 878 |
|
| 879 |
|
| 880 |
|
| 881 |
|
| 882 |
|
| 883 |
padding.PKCS1v15(), |
| 884 |
|
| 885 |
|
| 886 |
|
| 887 |
|
| 888 |
|
| 889 |
|
| 890 |
|
| 891 |
|
| 892 |
|
| 893 |
|
| 894 |
|
| 895 |
|
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
|
| 900 |
|
| 901 |
|
| 902 |
|
| 903 |
|
| 904 |
|
| 905 |
|
| 906 |
|
| 907 |
|
| 908 |
|
| 909 |
|
| 910 |
|
| 911 |
|
| 912 |
|
| 913 |
|
| 914 |
) |
| 915 |
return BytesIO(ciphertext) |
| 916 |
|
| 917 |
def extract_key(self, content): |
| 918 |
"""Extracts the public key from the openssl command output over REST |
| 919 |
|
| 920 |
The REST output includes some extra output that is not relevant to the |
| 921 |
public key. This function attempts to only return the valid public key |
| 922 |
data from the openssl output |
| 923 |
|
| 924 |
Args: |
| 925 |
content: The output from the REST API command to view the public key. |
| 926 |
|
| 927 |
Returns: |
| 928 |
string: The discovered public key |
| 929 |
""" |
| 930 |
|
| 931 |
lines = content.split("\n") |
| 932 |
start = lines.index('-----BEGIN PUBLIC KEY-----') |
| 933 |
end = lines.index('-----END PUBLIC KEY-----') |
| 934 |
result = "\n".join(lines[start:end + 1]) |
| 935 |
return result |
| 936 |
|
| 937 |
def update_on_device(self): |
| 938 |
errors = ['Bad password', 'password change canceled', 'based on a dictionary word'] |
| 939 |
|
| 940 |
|
| 941 |
|
| 942 |
|
| 943 |
|
| 944 |
|
| 945 |
|
| 946 |
|
| 947 |
|
| 948 |
|
| 949 |
|
| 950 |
|
| 951 |
|
| 952 |
|
| 953 |
|
| 954 |
|
| 955 |
|
| 956 |
|
| 957 |
|
| 958 |
|
| 959 |
|
| 960 |
|
| 961 |
|
| 962 |
|
| 963 |
|
| 964 |
|
| 965 |
|
| 966 |
|
| 967 |
|
| 968 |
|
| 969 |
|
| 970 |
|
| 971 |
|
| 972 |
|
| 973 |
openssl = [ |
| 974 |
'openssl', 'pkeyutl', '-in', '/var/config/rest/downloads/{0}'.format(self.want.temp_upload_file), |
| 975 |
'-decrypt', '-inkey', '/config/ssl/ssl.key/default.key', |
| 976 |
] |
| 977 |
cmd = '-c "{0} | tmsh modify auth password root"'.format(' '.join(openssl)) |
| 978 |
|
| 979 |
params = dict( |
| 980 |
command='run', |
| 981 |
utilCmdArgs=cmd |
| 982 |
) |
| 983 |
uri = "https://{0}:{1}/mgmt/tm/util/bash".format( |
| 984 |
self.client.provider['server'], |
| 985 |
self.client.provider['server_port'] |
| 986 |
) |
| 987 |
resp = self.client.api.post(uri, json=params) |
| 988 |
try: |
| 989 |
response = resp.json() |
| 990 |
if 'commandResult' in response: |
| 991 |
if any(x for x in errors if x in response['commandResult']): |
| 992 |
raise F5ModuleError(response['commandResult']) |
| 993 |
except ValueError as ex: |
| 994 |
raise F5ModuleError(str(ex)) |
| 995 |
if 'code' in response and response['code'] in [400, 403]: |
| 996 |
if 'message' in response: |
| 997 |
raise F5ModuleError(response['message']) |
| 998 |
else: |
| 999 |
raise F5ModuleError(resp.content) |
| 1000 |
return True |
| 1001 |
|
| 1002 |
def upload_to_device(self, content, name): |
| 1003 |
"""Uploads a file-like object via the REST API to a given filename |
| 1004 |
|
| 1005 |
Args: |
| 1006 |
content: The file-like object whose content to upload |
| 1007 |
name: The remote name of the file to store the content in. The |
| 1008 |
final location of the file will be in /var/config/rest/downloads. |
| 1009 |
|
| 1010 |
Returns: |
| 1011 |
void |
| 1012 |
""" |
| 1013 |
url = 'https://{0}:{1}/mgmt/shared/file-transfer/uploads'.format( |
| 1014 |
self.client.provider['server'], |
| 1015 |
self.client.provider['server_port'] |
| 1016 |
) |
| 1017 |
try: |
| 1018 |
upload_file(self.client, url, content, name) |
| 1019 |
except F5ModuleError: |
| 1020 |
raise F5ModuleError( |
| 1021 |
"Failed to upload the file." |
| 1022 |
) |
| 1023 |
|
| 1024 |
def remove_uploaded_file_from_device(self, name): |
| 1025 |
filepath = '/var/config/rest/downloads/{0}'.format(name) |
| 1026 |
params = { |
| 1027 |
"command": "run", |
| 1028 |
"utilCmdArgs": filepath |
| 1029 |
} |
| 1030 |
uri = "https://{0}:{1}/mgmt/tm/util/unix-rm".format( |
| 1031 |
self.client.provider['server'], |
| 1032 |
self.client.provider['server_port'] |
| 1033 |
) |
| 1034 |
resp = self.client.api.post(uri, json=params) |
| 1035 |
try: |
| 1036 |
response = resp.json() |
| 1037 |
except ValueError as ex: |
| 1038 |
raise F5ModuleError(str(ex)) |
| 1039 |
if 'code' in response and response['code'] in [400, 403]: |
| 1040 |
if 'message' in response: |
| 1041 |
raise F5ModuleError(response['message']) |
| 1042 |
else: |
| 1043 |
raise F5ModuleError(resp.content) |
| 1044 |
|
| 1045 |
def get_public_key_from_device(self): |
| 1046 |
cmd = '-c "openssl rsa -in /config/ssl/ssl.key/default.key -pubout"' |
| 1047 |
|
| 1048 |
params = dict( |
| 1049 |
command='run', |
| 1050 |
utilCmdArgs=cmd |
| 1051 |
) |
| 1052 |
uri = "https://{0}:{1}/mgmt/tm/util/bash".format( |
| 1053 |
self.client.provider['server'], |
| 1054 |
self.client.provider['server_port'] |
| 1055 |
) |
| 1056 |
resp = self.client.api.post(uri, json=params) |
| 1057 |
try: |
| 1058 |
response = resp.json() |
| 1059 |
except ValueError as ex: |
| 1060 |
raise F5ModuleError(str(ex)) |
| 1061 |
if 'code' in response and response['code'] in [400, 403]: |
| 1062 |
if 'message' in response: |
| 1063 |
raise F5ModuleError(response['message']) |
| 1064 |
else: |
| 1065 |
raise F5ModuleError(resp.content) |
| 1066 |
if 'commandResult' in response: |
| 1067 |
return response['commandResult'] |
| 1068 |
return None |
| 1069 |
|
| 1070 |
|
| 1071 |
class ArgumentSpec(object): |
| 1072 |
def __init__(self): |
| 1073 |
self.supports_check_mode = True |
| 1074 |
argument_spec = dict( |
| 1075 |
username_credential=dict( |
| 1076 |
required=True, |
| 1077 |
aliases=['name'] |
| 1078 |
), |
| 1079 |
password_credential=dict( |
| 1080 |
no_log=True, |
| 1081 |
), |
| 1082 |
partition_access=dict( |
| 1083 |
type='list', |
| 1084 |
elements='str', |
| 1085 |
), |
| 1086 |
full_name=dict(), |
| 1087 |
shell=dict( |
| 1088 |
choices=['none', 'bash', 'tmsh'] |
| 1089 |
), |
| 1090 |
update_password=dict( |
| 1091 |
default='always', |
| 1092 |
choices=['always', 'on_create'], |
| 1093 |
no_log=False |
| 1094 |
), |
| 1095 |
state=dict(default='present', choices=['absent', 'present']), |
| 1096 |
partition=dict( |
| 1097 |
default='Common', |
| 1098 |
fallback=(env_fallback, ['F5_PARTITION']) |
| 1099 |
) |
| 1100 |
) |
| 1101 |
self.argument_spec = {} |
| 1102 |
self.argument_spec.update(f5_argument_spec) |
| 1103 |
self.argument_spec.update(argument_spec) |
| 1104 |
|
| 1105 |
|
| 1106 |
def main(): |
| 1107 |
spec = ArgumentSpec() |
| 1108 |
|
| 1109 |
module = AnsibleModule( |
| 1110 |
argument_spec=spec.argument_spec, |
| 1111 |
supports_check_mode=spec.supports_check_mode |
| 1112 |
) |
| 1113 |
|
| 1114 |
if not HAS_PACKAGING: |
| 1115 |
module.fail_json( |
| 1116 |
msg=missing_required_lib('packaging'), |
| 1117 |
exception=PACKAGING_IMPORT_ERROR |
| 1118 |
) |
| 1119 |
|
| 1120 |
try: |
| 1121 |
mm = ModuleManager(module=module) |
| 1122 |
results = mm.exec_module() |
| 1123 |
module.exit_json(**results) |
| 1124 |
except F5ModuleError as ex: |
| 1125 |
module.fail_json(msg=str(ex)) |
| 1126 |
|
| 1127 |
|
| 1128 |
if __name__ == '__main__': |
| 1129 |
main() |