Saltstack Official UFW Formula
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

105 lines
2.8KB

  1. from salt.exceptions import CommandExecutionError, CommandNotFoundError
  2. import re
  3. import socket
  4. def _unchanged(name, msg):
  5. return {'name': name, 'result': True, 'comment': msg, 'changes': {}}
  6. def _test(name, msg):
  7. return {'name': name, 'result': None, 'comment': msg, 'changes': {}}
  8. def _error(name, msg):
  9. return {'name': name, 'result': False, 'comment': msg, 'changes': {}}
  10. def _changed(name, msg, **changes):
  11. return {'name': name, 'result': True, 'comment': msg, 'changes': changes}
  12. def _resolve(host):
  13. # pure IP address / netmask IPv4 or IPv6 ?
  14. if re.match(r'^([0-9\.](::))+(/[0-9]+)?$', host):
  15. return
  16. return socket.gethostbyname(host)
  17. def _as_rule(method, app, protocol, from_addr, from_port, to_addr, to_port):
  18. cmd = [method]
  19. if app is not None:
  20. cmd.append(app)
  21. else:
  22. if protocol is not None:
  23. cmd.append("proto")
  24. cmd.append(protocol)
  25. cmd.append("from")
  26. if from_addr is not None:
  27. cmd.append(_resolve(from_addr))
  28. else:
  29. cmd.append("any")
  30. if from_port is not None:
  31. cmd.append("port")
  32. cmd.append(_resolve(from_port))
  33. cmd.append("to")
  34. if to_addr is not None:
  35. cmd.append(to_addr)
  36. else:
  37. cmd.append("any")
  38. if to_port is not None:
  39. cmd.append("port")
  40. cmd.append(to_port)
  41. real_cmd = ' '.join(cmd)
  42. return real_cmd
  43. def enabled(name, **kwargs):
  44. if __salt__['ufw.is_enabled']():
  45. return _unchanged(name, "UFW is already enabled")
  46. if __opts__['test']:
  47. return _test(name, "UFW will be enabled")
  48. try:
  49. __salt__['ufw.set_enabled'](True)
  50. except (CommandExecutionError, CommandNotFoundError) as e:
  51. return _error(name, e.message)
  52. return _changed(name, "UFW is enabled", enabled=True)
  53. def allowed(name, app=None, protocol=None,
  54. from_addr=None, from_port=None, to_addr=None, to_port=None):
  55. rule = _as_rule("allow", app=app, protocol=protocol,
  56. from_addr=from_addr, from_port=from_port, to_addr=to_addr, to_port=to_port)
  57. if __opts__['test']:
  58. return _test(name, "{0}: {1}".format(name, rule))
  59. try:
  60. out = __salt__['ufw.add_rule'](rule)
  61. except (CommandExecutionError, CommandNotFoundError) as e:
  62. return _error(name, e.message)
  63. changes = False
  64. for line in out.split('\n'):
  65. if line.startswith("Skipping"):
  66. continue
  67. if line.startswith("Rule added") or line.startswith("Rules updated"):
  68. changes = True
  69. break
  70. return _error(name, line)
  71. if changes:
  72. return _changed(name, "{0} allowed".format(name), rule=rule)
  73. else:
  74. return _unchanged(name, "{0} was already allowed".format(name))