From 570d0da295f3e2fcd7b8c80ae2e6c42fc365abdd Mon Sep 17 00:00:00 2001 From: Sam Chudnick Date: Mon, 27 Jun 2022 20:41:01 -0400 Subject: Initial commit --- server/mfac.py | 113 ++++++++++++++++++++++++++ server/mfad.py | 246 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 359 insertions(+) create mode 100755 server/mfac.py create mode 100755 server/mfad.py (limited to 'server') diff --git a/server/mfac.py b/server/mfac.py new file mode 100755 index 0000000..779fa44 --- /dev/null +++ b/server/mfac.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python3 + +import argparse +import sqlite3 +import pyotp +import sys + +DB_NAME = "mfa.db" +KEY_LENGTH = 64 + +def die(msg): + print(msg) + sys.exit(1) + +def parse_arguments(): + parser = argparse.ArgumentParser() + parser.add_argument("--add-client",action="store_true",help="Add a client") + parser.add_argument("--alias",type=str,help="Alias for new client") + + parser.add_argument("--add-app",action="store_true",help="Add an application") + parser.add_argument("--user",type=str,help="Application username") + parser.add_argument("--host",type=str,help="Application hostname") + parser.add_argument("--service",type=str,help="Application service name") + parser.add_argument("--methods",type=str,nargs="+",help="Allowed MFA methods") + + parser.add_argument("--get-client",action="store_true",help="Get a client key") + + return parser.parse_args() + + +def alias_exists(alias): + conn = sqlite3.connect(DB_NAME) + c = conn.cursor() + c.execute("SELECT * FROM clients WHERE alias=?",(alias,)) + client = c.fetchall() + conn.close() + if len(client) == 0: + return False + elif len(client) == 1: + return True + + +def get_client_key(alias): + CLIENT_ALIAS_INDEX = 0 + CLIENT_KEY_INDEX = 1 + if not alias_exists(alias): + die("Error: alias does not exist") + else: + conn = sqlite3.connect(DB_NAME) + c = conn.cursor() + c.execute("SELECT * FROM clients WHERE alias=?",(alias,)) + client = c.fetchone() + conn.close() + return str(client[CLIENT_KEY_INDEX]) + + +def add_client(alias): + if not alias_exists(alias): + key = pyotp.random_base32(length=64) + conn = sqlite3.connect(DB_NAME) + c = conn.cursor() + c.execute("INSERT INTO clients VALUES (?,?)",(alias,key)) + conn.commit() + conn.close() + print("key: " + key) + else: + die("Error: alias already used") + + +def add_app(username, hostname, service, alias, mfa_methods): + if not alias_exists(alias): + die("Error: alias does not exist") + else: + client_key = get_client_key(alias) + conn = sqlite3.connect(DB_NAME) + c = conn.cursor() + c.execute("INSERT INTO applications VALUES (?,?,?,?,?)", + (username,hostname,service,alias,mfa_methods)) + conn.commit() + conn.close() + + +def main(): + args = parse_arguments() + # Sanity checks + if (args.add_client and args.add_app) or (args.add_client and args.get_client) \ + or (args.get_client and args.add_app): + die("Error: cannot specify multiple actions") + if args.add_client and args.alias == None: + die("Error: must specify alias to provision a client") + if args.get_client and args.alias == None: + die("Error: no alias specified") + if args.add_app and (args.user == None or args.host == None or \ + args.service == None or args.alias == None \ + or args.methods == None): + die("Error: --add-app requires all of --user,--host,--service,--alias,--methods") + + if args.add_client: + add_client(args.alias) + elif args.get_client: + key = get_client_key(args.alias) + print(key) + elif args.add_app: + methods = " ".join(args.methods) + add_app(args.user,args.host,args.service,args.alias,methods) + + + + +if __name__ == '__main__': + main() + + diff --git a/server/mfad.py b/server/mfad.py new file mode 100755 index 0000000..7a2fc40 --- /dev/null +++ b/server/mfad.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python3 +import socket +import os +import sys +import time +import threading +import pyotp +import sqlite3 +import re + +## Listens for authentication request from PAM module +## Recevies connection from client +## Correlates authentication request to client connection +## Sends MFA prompt to client +## Evaluates response from client +## Return pass or fail response to PAM moudle + + +DB_NAME = "mfa.db" +HEADER_LENGTH = 64 +KEY_LENGTH = 64 +DISCONNECT_LENGTH = ACK_LENGTH = 3 +ACK_MESSAGE = "ACK" +DISCONNECT_MESSAGE = "BYE" +FORMAT = "utf-8" +AUTHED = 0 +DENIED = 1 + +# Stores connected clients as a dictionary with the client key as the dictionary +# key and a tuple of (socket,(addr,port)) as the value +client_connections = dict() + + +def eval_mfa(mfa_methods,client_response): + # Evaluates MFA and decides if authenticated or denied + # Returns 0 for authenticated on 1 for denied + if "push" in mfa_methods and client_response == "allow": + return AUTHED + elif "totp" in mfa_methods and len(client_response) == 6: + # Only attempt to validate if response is a valid TOTP format + totp_format = (r'(\d)(\d)(\d)(\d)(\d)(\d)') + totp_regex = re.compile(totp_format) + matched = totp_regex.match(client_response) + if matched: + return validate_totp(int(client_response)) + return DENIED + + +def validate_totp(client_response): + pass + + +################################################################################ + +# Client is registered by admin with secret key stored on server +# Client is provisioned with secret key and passes secret key to server on +# connection for identification +# Client key is used to identify client throughout communication process + +# //TODO RSA public/private key pairs for proper authentication + +def get_client_key(username,hostname,service): + # Correlates a PAM request to a registered client + # This is done by checking the PAM request against a preconfigured + # database mapping request info (username,hostname,etc...) to clients + # Returns a tuple consisting of the key and approved MFA methods + DB_USERNAME_INDEX = 0 + DB_HOSTNAME_INDEX = 1 + DB_SERVICE_INDEX = 2 + DB_ALIAS_INDEX = 3 + DB_MFAMETHODS_INDEX = 4 + + CLIENT_ALIAS_INDEX = 0 + CLIENT_KEY_INDEX = 1 + + conn = sqlite3.connect(DB_NAME) + c = conn.cursor() + c.execute("""SELECT * FROM applications WHERE username=? AND hostname=? + AND service=?""",(username,hostname,service)) + application = c.fetchone() + # Return None if no results found + if application == None: + return application + + alias = application[DB_ALIAS_INDEX] + c.execute("SELECT * FROM clients WHERE alias=?",(alias,)) + client = c.fetchone() + conn.close() + client_key = client[CLIENT_KEY_INDEX] + methods = application[DB_MFAMETHODS_INDEX] + return (client_key,methods) + + + +def prompt_client(client_key, user, host, service, methods, timeout=10): + # Prompts client for MFA + timer = 0 + while timer < timeout: + if client_key in client_connections.keys(): + conn = client_connections[client_key][0] + # Use try block to catch cases where client was connected and so + # is in list but is not currently connected + try: + # send prompts + methodstr = ", ".join(methods) + methodstr = "Available methods: " + methodstr + prompt_msg = "Login approved for user '" + user + \ + "' attempting to access service '" + service + \ + "' on host '" + host + "'?\n" + methodstr + prompt_len = len(prompt_msg) + length_msg = str(prompt_len) + length_msg += ' ' * (HEADER_LENGTH - len(length_msg)) + conn.send(length_msg.encode(FORMAT)) + conn.send(prompt_msg.encode(FORMAT)) + # receive response + response_length = int(conn.recv(HEADER_LENGTH).decode(FORMAT)) + response = conn.recv(response_length).decode(FORMAT) + return response + except BrokenPipeError: + client_connections.pop(client_key) + timer += 1 + time.sleep(1) + else: + timer +=1 + time.sleep(1) + + return 0 + + +def validate_client(client_key): + # Validates a client + conn = sqlite3.connect(DB_NAME) + c = conn.cursor() + c.execute("SELECT * FROM clients WHERE key=?",(client_key,)) + client = c.fetchall() + conn.close() + if len(client) == 0: + # No client matches provided key, invalid + return False + elif len(client) == 1: + return True + else: + print("A strange error has occurred") + return False + + + +def handle_client(conn, addr): + # Receive key from client + key = conn.recv(KEY_LENGTH).decode(FORMAT) + # Validate client + if not validate_client(key): + print("WARNING: client attempted to connect with invalid key") + conn.send(DISCONNECT_MESSAGE.encode(FORMAT)) + conn.close() + else: + conn.send(ACK_MESSAGE.encode(FORMAT)) + client_connections[key] = (conn,addr) + print("client connected with key " + key) + + +def parse_pam_data(data): + # Parses pam data and returns (user,host,service) tuple + return tuple(data.split(',')) + +def handle_pam(conn, addr): + # Get request and data from PAM module + data_length = int(conn.recv(HEADER_LENGTH).decode(FORMAT)) + pam_data = conn.recv(data_length).decode(FORMAT) + print("Got pam_data: " + pam_data) + user,host,service = parse_pam_data(pam_data) + + # Correlate request to client + client_key,mfa_methods = get_client_key(user,host,service) + mfa_methods = mfa_methods.split(',') + if client_key == None: + print("No applications found for user="+user+" host="+host+" service="+service) + conn.send(str(DENIED).encode(FORMAT)) + return + + # Prompt client + response = prompt_client(client_key,user,host,service,mfa_methods) + + # Evaluate Response + auth_type = "push" + decision = eval_mfa(auth_type, response) + + # Return response to PAM module + # Respone will either be 0 for authenticated and 1 for denied + conn.send(str(decision).encode(FORMAT)) + + +def listen_client(addr, port): + with socket.create_server((addr, port)) as server: + while True: + conn, addr = server.accept() + thread = threading.Thread(target=handle_client,args=(conn,addr)) + thread.start() + + +def listen_pam(addr, port): + with socket.create_server((addr,port)) as pam_server: + while True: + conn, addr = pam_server.accept() + thread = threading.Thread(target=handle_pam,args=(conn,addr)) + thread.start() + + +################################################################################ + +def create_db(): + conn = sqlite3.connect(DB_NAME) + c = conn.cursor() + c.execute("""CREATE TABLE applications ( + username text, + hostname text, + service text, + client_key text, + mfa_methods text + )""") + conn.commit() + c.execute("""CREATE TABLE clients ( + alias, + key + )""") + conn.commit() + conn.close() + + +def main(): + global connection_list + bind_addr = "127.0.0.1" + pam_port = 8000 + client_port = 8001 + + if not os.path.exists(DB_NAME): + create_db() + + clients = threading.Thread(target=listen_client,args=(bind_addr,client_port)) + pam = threading.Thread(target=listen_pam,args=(bind_addr,pam_port)) + clients.start() + pam.start() + + +if __name__ == '__main__': + main() -- cgit v1.2.3