---

- name: Apply rate limits
  iptables_raw:
    name: sshd_limit
    rules: |
      -N SSH_LIMIT
      {% if trusted_ip is defined and trusted_ip | length > 0 %}
      -A SSH_LIMIT -s {{ trusted_ip | join(',') }} -j RETURN
      {% endif %}
      -A SSH_LIMIT -m recent --name ssh_limit --set
      -A SSH_LIMIT -m recent --name ssh_limit --rcheck --seconds 60 --hitcount {{ sshd_max_conn_per_minute }} -j LOG --log-prefix "Firewall (ssh limit): "
      -A SSH_LIMIT -m recent --name ssh_limit --rcheck --seconds 60 --hitcount {{ sshd_max_conn_per_minute }} -j REJECT
      -A INPUT -p tcp -m state --state NEW -m multiport --dports {{ sshd_ports | join(',') }} -j SSH_LIMIT
    state: "{{ (sshd_max_conn_per_minute > 0) | ternary('present','absent') }}"
    weight: 10
  tags: ssh,firewall

- name: Handle ssh ports
  iptables_raw:
    name: sshd_ports
    state: "{{ (sshd_src_ip is defined and sshd_src_ip | length > 0) | ternary('present','absent') }}"
    rules: "-A INPUT -m state --state new -p tcp -m multiport --dports {{ sshd_ports | join(',') }} -s {{ sshd_src_ip | flatten | join(',') }} -j ACCEPT"
  tags: ssh,firewall
