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.

219 lines
7.1KB

  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. # let's just see if it starts with a number or a colon, for simplicity
  14. if re.match(r'^[0-9:]', host):
  15. return host
  16. return socket.gethostbyname(host)
  17. def _as_rule(method, app, interface, protocol, from_addr, from_port, to_addr, to_port, comment):
  18. cmd = [method]
  19. if app is not None:
  20. cmd.append("from")
  21. if from_addr is not None:
  22. cmd.append(from_addr)
  23. else:
  24. cmd.append("any")
  25. cmd.append("to")
  26. if to_addr is not None:
  27. cmd.append(to_addr)
  28. else:
  29. cmd.append("any")
  30. cmd.append("app")
  31. cmd.append(app)
  32. elif interface is not None:
  33. cmd.append("in")
  34. cmd.append("on")
  35. cmd.append(interface)
  36. else:
  37. if protocol is not None:
  38. cmd.append("proto")
  39. cmd.append(protocol)
  40. cmd.append("from")
  41. if from_addr is not None:
  42. cmd.append(_resolve(from_addr))
  43. else:
  44. cmd.append("any")
  45. if from_port is not None:
  46. cmd.append("port")
  47. cmd.append(_resolve(from_port))
  48. cmd.append("to")
  49. if to_addr is not None:
  50. cmd.append(to_addr)
  51. else:
  52. cmd.append("any")
  53. if to_port is not None:
  54. cmd.append("port")
  55. cmd.append(to_port)
  56. if comment is not None:
  57. cmd.append("comment")
  58. cmd.append(comment)
  59. real_cmd = ' '.join(cmd)
  60. return real_cmd
  61. def _add_rule(method, name, app=None, interface=None, protocol=None,
  62. from_addr=None, from_port=None, to_addr=None, to_port=None, comment=None):
  63. if app and app.strip('"\' ') == '*':
  64. app = None
  65. if to_port and to_port.strip('"\' ') == '*':
  66. to_port = None
  67. rule = _as_rule(method, app=app, interface=interface, protocol=protocol,
  68. from_addr=from_addr, from_port=from_port, to_addr=to_addr, to_port=to_port, comment=comment)
  69. try:
  70. out = __salt__['ufw.add_rule'](rule)
  71. except (CommandExecutionError, CommandNotFoundError) as e:
  72. if method.startswith('insert 1 deny') and "Invalid position '1'" in e.message:
  73. # This is probably the first rule to be added, so try again without "insert 1"
  74. return _add_rule('deny', name, app, interface, protocol, from_addr, from_port, to_addr, to_port, comment)
  75. return _error(name, e.message)
  76. adds = False
  77. inserts = False
  78. updates = False
  79. for line in out.split('\n'):
  80. if re.match('^Skipping', line):
  81. return _unchanged(name, "{0} is already configured".format(name))
  82. break
  83. if re.match('^Rule(s)? added', line):
  84. adds = True
  85. break
  86. if re.match('^Rule(s)? inserted', line):
  87. inserts = True
  88. break
  89. if re.match('^Rule(s)? updated', line):
  90. updates = True
  91. break
  92. if __opts__['test']:
  93. return _test(name, "{0} would have been configured".format(name))
  94. break
  95. if method.startswith('insert 1 deny') and "Invalid position '1'" in line:
  96. # This is probably the first rule to be added, so try again without "insert 1"
  97. return _add_rule('deny', name, app, interface, protocol, from_addr, from_port, to_addr, to_port, comment)
  98. return _error(name, line)
  99. if adds:
  100. return _changed(name, "{0} added".format(name), rule=rule)
  101. elif inserts:
  102. return _changed(name, "{0} inserted".format(name), rule=rule)
  103. elif updates:
  104. return _changed(name, "{0} updated".format(name), rule=rule)
  105. else:
  106. return _unchanged(name, "{0} was already configured".format(name))
  107. def enabled(name, **kwargs):
  108. if __salt__['ufw.is_enabled']():
  109. return _unchanged(name, "UFW is already enabled")
  110. try:
  111. __salt__['ufw.set_enabled'](True)
  112. except (CommandExecutionError, CommandNotFoundError) as e:
  113. return _error(name, e.message)
  114. if __opts__['test']:
  115. return _test(name, "UFW would have been enabled")
  116. else:
  117. return _changed(name, "UFW is enabled", enabled=True)
  118. def default_incoming(name, default):
  119. rule = "default {0} incoming".format(default)
  120. if __opts__['test']:
  121. return _test(name, "{0}: {1}".format(name, rule))
  122. current = __salt__['ufw.get_default_incoming']()
  123. if default != current:
  124. try:
  125. out = __salt__['ufw.add_rule'](rule)
  126. except (CommandExecutionError, CommandNotFoundError) as e:
  127. return _error(name, e.message)
  128. for line in out.split('\n'):
  129. if line.startswith("Default incoming policy changed to"):
  130. return _changed(name, "{0} set to {1}".format(name, default), rule=rule)
  131. return _error(name, line)
  132. return _unchanged(name, "{0} was already set to {1}".format(name, default))
  133. def default_outgoing(name, default):
  134. rule = "default {0} outgoing".format(default)
  135. if __opts__['test']:
  136. return _test(name, "{0}: {1}".format(name, rule))
  137. current = __salt__['ufw.get_default_outgoing']()
  138. if default != current:
  139. try:
  140. out = __salt__['ufw.add_rule'](rule)
  141. except (CommandExecutionError, CommandNotFoundError) as e:
  142. return _error(name, e.message)
  143. for line in out.split('\n'):
  144. if line.startswith("Default outgoing policy changed to"):
  145. return _changed(name, "{0} set to {1}".format(name, default), rule=rule)
  146. return _error(name, line)
  147. return _unchanged(name, "{0} was already set to {1}".format(name, default))
  148. def deny(name, app=None, interface=None, protocol=None,
  149. from_addr=None, from_port=None, to_addr=None, to_port=None, comment=None):
  150. return _add_rule('insert 1 deny', name, app, interface, protocol, from_addr, from_port, to_addr, to_port, comment)
  151. def limit(name, app=None, interface=None, protocol=None,
  152. from_addr=None, from_port=None, to_addr=None, to_port=None, comment=None):
  153. return _add_rule('limit', name, app, interface, protocol, from_addr, from_port, to_addr, to_port, comment)
  154. def allow(name, app=None, interface=None, protocol=None,
  155. from_addr=None, from_port=None, to_addr=None, to_port=None, comment=None):
  156. return _add_rule('allow', name, app, interface, protocol, from_addr, from_port, to_addr, to_port, comment)
  157. def allowed(name, app=None, interface=None, protocol=None,
  158. from_addr=None, from_port=None, to_addr=None, to_port=None, comment=None):
  159. """
  160. allow() is aliased to allowed() to maintain backwards compatibility.
  161. """
  162. return allow(name, app, interface, protocol, from_addr, from_port, to_addr, to_port, comment)