# SSH two-factor authentication (pam + telegram)


# apt-get install libpam-python

# grep -m 1 ChallengeResponseAuthentication /etc/ssh/sshd_config
ChallengeResponseAuthentication yes

# cat /etc/pam.d/sshd | grep -B 1 -A 1 authentication
auth requisite /lib/security/pam_python.so /lib/security/telegramPIN.py
# Standard Un*x authentication.
@include common-auth

# cat /lib/security/telegramPIN.py
import base64
import random
import subprocess

def pam_sm_authenticate(pamh, flags, argv):
  local_network = '192.168.1.'
  if local_network in pamh.rhost:
      return pamh.PAM_SUCCESS
  else:
    try:
      user = pamh.get_user(None)
    except pamh.exception, e:
      return e.pam_result
    r = random.SystemRandom()
    pin = ''.join([str(r.randint(0, 9)) for i in xrange(0,8)])
    b64 = base64.b64encode('SSH-PIN = ' + pin)
    subprocess.Popen(['/send_telegram_msg.py', b64])
    msg = pamh.Message(pamh.PAM_PROMPT_ECHO_OFF, 'PIN: ')
    rsp = pamh.conversation(msg)
    if rsp.resp == pin:
      return pamh.PAM_SUCCESS
    return pamh.PAM_AUTH_ERR

def pam_sm_setcred(pamh, flags, argv):
  return pamh.PAM_SUCCESS

def pam_sm_acct_mgmt(pamh, flags, argv):
  return pamh.PAM_SUCCESS

def pam_sm_open_session(pamh, flags, argv):
  return pamh.PAM_SUCCESS

def pam_sm_close_session(pamh, flags, argv):
  return pamh.PAM_SUCCESS

def pam_sm_chauthtok(pamh, flags, argv):
  return pamh.PAM_SUCCESS

# service ssh restart

References

http://pam-python.sourceforge.net/doc/html/
http://www.linux-pam.org/Linux-PAM-html/Linux-PAM_MWG.html

2 comments:

edmund dante said...

should be nice to have also the content of this referenced script located at /

subprocess.Popen(['/send_telegram_msg.py', b64])

Abhis27 said...

Should be nice if you got TeleBot frm github.. :-|