summaryrefslogtreecommitdiff
path: root/server/mfad.py
blob: cc5073bc06c07278d1e9121915062ab4c809c72f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
#!/usr/bin/env python3
import socket
import ssl
import os
import sys
import time
import threading
import pyotp
import sqlite3
import re
import configparser
import argparse

## 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


HEADER_LENGTH = 64
KEY_LENGTH = 64
DISCONNECT_LENGTH = ACK_LENGTH = 3
ACK_MESSAGE = "ACK"
DISCONNECT_MESSAGE = "BYE"
FORMAT = "utf-8"
AUTHED = 0
DENIED = 1

# DB object index constants
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
CLIENT_SECRET_INDEX = 2

# 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 die(msg):
    print(msg)
    sys.exit(1)

def parse_arguments():
    parser = argparse.ArgumentParser()
    parser.add_argument("--address",type=str,help="Bind Address")
    parser.add_argument("--pam-port",type=int,help="Port to listen for PAM requests")
    parser.add_argument("--client-port",type=int,help="Port for client connections")
    parser.add_argument("--pam-tls-port",type=int,
                        help="Port to listen for encrypted PAM requests")
    parser.add_argument("--client-tls-port",type=int,
                        help="Port for encrypted client connections")
    parser.add_argument("--database",type=str,help="Path to database file")
    parser.add_argument("--cert",type=str,help="TLS certificate file")
    parser.add_argument("--key",type=str,help="TLS private key file")
    parser.add_argument("--ciphers",type=str,help="TLS ciphers to use")
    parser.add_argument("--config",type=str,help="Alternate config file location",\
                         default="/etc/mfa/mfa.conf")
    return parser.parse_args()


def read_config(config):
    parser = configparser.ConfigParser(inline_comment_prefixes="#")
    parser.read(config)
    return parser


def eval_mfa(db, client_key, mfa_methods, client_response):
    print("response: " + client_response)
    print("length: " + str(len(client_response)))
    print("methods: " + str(mfa_methods))
    # 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(db, client_key, client_response)
    return DENIED


def validate_totp(db, client_key, client_response):
    secret = ""
    with sqlite3.connect(db) as conn:
        c = conn.cursor()
        c.execute("SELECT * FROM clients WHERE key=?",(client_key,))
        client = c.fetchone()
        secret = client[CLIENT_SECRET_INDEX]
    totp = pyotp.TOTP(secret)
    print("Client Response: " + str(client_response))
    print("Valid TOTP: " + str(totp.now()))
    if totp.verify(client_response):
        return AUTHED
    else:
        return DENIED


################################################################################

# 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(db, 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

    application = None
    client = None
    with sqlite3.connect(db) as conn:
        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()

    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
                header = conn.recv(HEADER_LENGTH).decode(FORMAT)
                if header == "":
                    die("error: lost connection to client")
                response_length = int(header)
                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(db, client_key):
    # Validates a client
    client = None
    with sqlite3.connect(db) as conn:
        c = conn.cursor()
        c.execute("SELECT * FROM clients WHERE key=?",(client_key,))
        client = c.fetchall()

    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(db, conn, addr):
    # Receive key from client
    key = conn.recv(KEY_LENGTH).decode(FORMAT)
    # Validate client
    if not validate_client(db, 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(db, conn, addr):
    # Get request and data from PAM module
    header = conn.recv(HEADER_LENGTH).decode(FORMAT)
    if len(header) != HEADER_LENGTH:
        conn.close()
        die("error: invalid data from PAM module")
    data_length = int(header)
    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(db, 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
    decision = eval_mfa(db, client_key, mfa_methods, response)

    # Return response to PAM module
    # Respone will either be 0 for authenticated and 1 for denied
    conn.send(str(decision).encode(FORMAT))


def get_tls_context(cert, key, ciphers):
    if not os.path.exists(cert):
        die("error: cannot open cert file")
    if not os.path.exists(key):
        die("error: cannot open key file")

    # Create context, load cert and key
    context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
    context.load_cert_chain(certfile=cert, keyfile=key)
    context.minimum_version = ssl.TLSVersion.TLSv1_2
    context.maximum_version = ssl.TLSVersion.TLSv1_3

    if ciphers == None:
        # Mozilla intermediate compatibility
        ciphers = "ECDHE+ECDSA+AESGCM:ECDHE+aRSA+AESGCM:ECDHE+ECDSA+CHACHA20:ECDHE+aRSA+CHACHA20:DHE+aRSA+AESGCM:!aNULL:!eNULL"

    # Set ciphers
    try:
        context.set_ciphers(ciphers)
    except ssl.SSLError:
        die("error: invalid cipherlist")

    return context

def listen_client_tls(db, addr, port, tls_context):
    with socket.create_server((addr, port)) as sock:
        with tls_context.wrap_socket(sock, server_side=True) as tls_socket:
            while True:
                try:
                    conn, addr = tls_socket.accept()
                    thread = threading.Thread(target=handle_client,args=(db,conn,addr))
                    thread.start()
                except ssl.SSLError:
                    print("client: ssl handshake error")


def listen_pam_tls(db, addr, port, tls_context):
    with socket.create_server((addr,port)) as sock:
        with tls_context.wrap_socket(sock, server_side=True) as tls_socket:
            while True:
                try:
                    conn, addr = tls_socket.accept()
                    thread = threading.Thread(target=handle_pam,args=(db, conn,addr))
                    thread.start()
                except ssl.SSLError:
                    print("pam: ssl handshake error")


def listen_client(db, addr, port):
    with socket.create_server((addr, port)) as sock:
        while True:
            conn, addr = sock.accept()
            thread = threading.Thread(target=handle_client,args=(db,conn,addr))
            thread.start()


def listen_pam(db, addr, port):
    with socket.create_server((addr, port)) as sock:
        while True:
            conn, addr = sock.accept()
            thread = threading.Thread(target=handle_pam,args=(db,conn,addr))
            thread.start()


################################################################################

def create_db(db):
    with sqlite3.connect(db) as conn:
        c = conn.cursor()
        c.execute("""CREATE TABLE applications (
                    username text,
                    hostname text,
                    service text,
                    alias text,
                    mfa_methods text
                )""")
        c.execute("""CREATE TABLE clients (
                    alias text,
                    key text,
                    totp_secret text
                 )""")
        conn.commit()


def get_vars(args,confparser):
    if not os.path.exists(args.config):
        die("Unable to open config file")

    bind_addr = None
    client_port = None
    client_tls_port = None
    pam_port = None
    pam_tls_port = None
    database = None
    cert = None
    key = None
    ciphers = None

    # Set values from config file first
    if confparser.has_section("mfad"):
        bind_addr = confparser.get("mfad","address",fallback=None) 
        client_port = confparser.get("mfad","client-port",fallback=None) 
        pam_port = confparser.get("mfad","pam-port",fallback=None) 
        client_tls_port = confparser.get("mfad","client-tls-port",fallback=None) 
        pam_tls_port = confparser.get("mfad","pam-tls-port",fallback=None) 
        database = confparser.get("mfad","database",fallback=None) 
        cert = confparser.get("mfad","cert",fallback=None) 
        key = confparser.get("mfad","key",fallback=None) 
        ciphers = confparser.get("mfad","ciphers",fallback=None) 
        
    # Let command line args overwrite any values
    if args.address != None:
        bind_addr = args.address
    if args.client_port != None:
        client_port = args.client_port
    if args.pam_port != None:
        pam_port = args.pam_port
    if args.client_tls_port != None:
        client_tls_port = args.client_tls_port
    if args.pam_tls_port != None:
        pam_tls_port = args.pam_tls_port
    if args.database != None:
        database = args.database
    if args.cert != None:
        cert = args.cert
    if args.key != None:
        key = args.key
    if args.ciphers != None:
        ciphers = args.ciphers

    # Exit if any value is null
    if None in [bind_addr,database,cert,key]:
        die("error: one or more items unspecified")

    ports = [pam_port, client_port, pam_tls_port, client_tls_port]
    for port in ports:
        if port == None:
            ports[ports.index(port)] = 0

    return bind_addr, ports, database, cert, key, ciphers


def main():
    args = parse_arguments()
    confparser = read_config(args.config)

    bind_addr,ports,db,cert,key,ciphers = get_vars(args,confparser)
    pam_port = int(ports[0])
    client_port = int(ports[1])
    pam_tls_port = int(ports[2])
    client_tls_port = int(ports[3])

    if pam_port == 0 and pam_tls_port == 0:
        die("error: not listening for any PAM connections")
    if client_port == 0 and client_tls_port == 0:
        die("error: not listening for any client connections")


    if not os.path.exists(db):
        print("Creating DB")
        create_db(db)
    
    context = get_tls_context(cert,key,ciphers)

    if pam_port != 0: 
        threading.Thread(target=listen_pam,args=(db,bind_addr,pam_port)).start()
    if client_port != 0: 
        threading.Thread(target=listen_client,args=(db,bind_addr,client_port)).start()
    if pam_tls_port != 0: 
        threading.Thread(target=listen_pam_tls,
                args=(db,bind_addr,pam_tls_port,context)).start()
    if client_tls_port != 0: 
        threading.Thread(target=listen_client_tls,
                args=(db,bind_addr,client_tls_port,context)).start()


if __name__ == '__main__':
    main()