Skip to content

Instantly share code, notes, and snippets.

@hexedpackets
Created July 22, 2015 16:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hexedpackets/209cbcba40cb7aaa5040 to your computer and use it in GitHub Desktop.
Save hexedpackets/209cbcba40cb7aaa5040 to your computer and use it in GitHub Desktop.
Consul PAM account script for authenticating SSH users on an EC2 host based on the name of the host, as passed into the user data.
#!/usr/bin/env python
"""Authenticates a user in PAM based on the name of the current host."""
import re
import requests
import os
import sys
DEFAULT_EXIT_CODE = 500 # fail closed
UNAUTHORIZED_HOST = 403
DATACENTER = 'dc1'
ORG_KEY = 'org/users'
USER_DATA_HOST_NAME = 'Name'
if __name__ == '__main__':
username = os.environ.get('PAM_USER')
resp = requests.get('http://169.254.169.254/latest/user-data')
if not resp.ok:
# fail closed
sys.exit(DEFAULT_EXIT_CODE)
user_data = dict(map(lambda x: x.split('='), resp.text.split('& ')))
# Check hostname auth
resp = requests.get('http://localhost:8500/v1/kv/{org_key}/{user}/allowed_hosts?raw&dc={dc}'.format(
org_key=ORG_KEY, user=username, dc=DATACENTER))
if resp.ok:
hosts = resp.text.split('\n')
for host in hosts:
if re.match(host, user_data[USER_DATA_HOST_NAME]):
break
else:
sys.exit(UNAUTHORIZED_HOST)
else:
sys.exit(DEFAULT_EXIT_CODE)
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment