Justin
Justin

Reputation: 48

How to write an Ansible playbook with port knocking

My server is set up to require port knocking in order to white-list an IP for port 22 SSH. I've found guides on setting up an Ansible playbook to configure port knocking on the server side, but not to perform port knocking on the client side.

For example, what would my playbook and/or inventory files look like if I need to knock port 9999, 9000, then connect to port 22 in order to run my Ansible tasks?

Upvotes: 1

Views: 2328

Answers (4)

Andrey Baznikin
Andrey Baznikin

Reputation: 1

Just update ssh_pkn plugin to recent Ansible 2.16: https://github.com/baznikin/ansible-knock

Upvotes: 0

steadfasterX
steadfasterX

Reputation: 21

I have used https://stackoverflow.com/a/42647902/10191134 until it broke on an ansible update so I searched for another solution and finally stumbled over wait_for:

hosts:

[myserver]
knock_ports=[123,333,444]

play:

- name: Port knocking
  wait_for:
    port: "{{ item }}"
    delay: 0
    connect_timeout: 1
    state: stopped
    host: "{{ inventory_hostname }}"
  connection: local
  become: no
  with_items: "{{ knock_ports }}"
  when: knock_ports is defined

ofc can be adjusted to make the delay and/or timeout configurable in the hosts as well.

Upvotes: 2

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

You can try out my ssh_pkn connection plugin.

# Example host definition:
#   [pkn]
#   myserver ansible_host=my.server.at.example.com
#   [pkn:vars]
#   ansible_connection=ssh_pkn
#   knock_ports=[8000,9000]
#   knock_delay=2

Upvotes: 3

300D7309EF17
300D7309EF17

Reputation: 24603

Here's a brute-force example. The timeouts will be hit, so this'll add 2 seconds per host to a play.

- hosts: all
  connection: local
  tasks:
  - uri:
      url: "http://{{ansible_host}}:9999"
      timeout: 1
    ignore_errors: yes
  - uri:
      url: "http://{{ansible_host}}:9000"
      timeout: 1
    ignore_errors: yes
  - hosts: all
  # your normal plays here

Other ways: use telnet, put a wrapper around Ansible (though it isn't recommended in Ansible2), make a role and then include with meta, write a custom module (and pull that back into Ansible itself).

Upvotes: 1

Related Questions