check_users.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #!/usr/bin/python
  2. import pwd
  3. import json
  4. from ansible.module_utils.basic import *
  5. NOOP_SHELL = [
  6. "/usr/sbin/nologin",
  7. '/bin/nologin',
  8. '/bin/false'
  9. ]
  10. class CheckUsers(object):
  11. def __init__(self, module):
  12. self.module = module
  13. self.cusers = self.module.params["users_var"]
  14. self.fail_on_error = self.module["fail_on_error"]
  15. def main(self):
  16. users = pwd.getpwall()
  17. count = 0
  18. for user in users:
  19. name = user.pw_name
  20. shell = user.pw_shell
  21. uid = user.pw_uid
  22. home_dir = user.pw_dir
  23. if (uid > 999 and self.isValidShell(shell)):
  24. if not self.isUserNameInDb(name):
  25. self.exitWithResult("User {} not defined by ansible".format(name))
  26. else:
  27. self.checkUsersKeys(user)
  28. count = count + 1
  29. result = {"changed": False, "msg": "Checked {} user accounts".format(count)}
  30. self.module.exit_json(**result)
  31. def isUserNameInDb(self, name):
  32. for entry in self.cusers['users_db']:
  33. if entry['name'] == name:
  34. return True
  35. return False
  36. def isValidShell(self, shell):
  37. if shell in NOOP_SHELL:
  38. return False
  39. return True
  40. def checkUsersKeys(self, user):
  41. usersKeys = None
  42. for keys in self.cusers['key_db']:
  43. if keys['user'] == user.pw_name:
  44. usersKeys = keys
  45. break
  46. if usersKeys == None:
  47. self.exitWithResult("User {} has no ansible defined SSH keys".format(user.pw_name))
  48. installed_keys = self.loadInstalledAuthorizedKeys(user)
  49. configured_keys = []
  50. for key in usersKeys['keys']:
  51. configured_keys.append(key['key'])
  52. for key in installed_keys:
  53. if not key in configured_keys:
  54. self.exitWithResult("User {} has rogue ssh authorized keys".format(user.pw_name))
  55. def loadInstalledAuthorizedKeys(self, user):
  56. authorized_keys_file = os.path.join(user.pw_dir,'.ssh','authorized_keys')
  57. if not os.path.isfile(authorized_keys_file):
  58. self.exitWithResult("Can't load authorized keys from {} for user {}".format(authorized_keys_file, user.pw_name))
  59. with open(authorized_keys_file, 'r') as infile:
  60. data = infile.read()
  61. authorized_keys = data.splitlines()
  62. return authorized_keys
  63. def exitWithResult(self, message):
  64. if self.fail_on_error:
  65. self.module.fail_json(msg=message)
  66. else:
  67. self.module.exit_json(msg=message)
  68. def main():
  69. module = AnsibleModule(
  70. argument_spec=dict(
  71. users_var=dict(default=None, required=True, type='dict')
  72. fail_on_error=dict(default=True, required=False, type='bool')
  73. ),
  74. supports_check_mode=False
  75. )
  76. CheckUsers(module).main()
  77. if __name__ == '__main__':
  78. main()