summaryrefslogtreecommitdiffstats
path: root/plugin/eurephia.c
blob: 5777cd7b373304c759b69f18afa3841d9932aa37 (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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
/* eurephia.c  --  Main functions for the eurephia authentication module
 *
 *  GPLv2 only - Copyright (C) 2008 - 2013
 *               David Sommerseth <dazo@users.sourceforge.net>
 *
 *  This program is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU General Public License
 *  as published by the Free Software Foundation; version 2
 *  of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 */

/**
 * @file   eurephia.c
 * @author David Sommerseth <dazo@users.sourceforge.net>
 * @date   2008-08-06
 *
 * @brief  The core eurephia functions which is called from OpenVPN.
 *
 */


#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/mman.h>
#include <string.h>
#include <getopt.h>
#include <unistd.h>
#include <assert.h>
#include <errno.h>
#include <openssl/x509.h>

#define EUREPHIA_FWINTF         /**< Include the proper eurephiaFWINTF declaration in eurephiaCTX */
#include <eurephiafw_struct.h>
#include <eurephia_context.h>
#include <eurephia_context.h>
#include <eurephia_authplugin_driver.h>
#include <eurephia_authplugin_context.h>
#include <eurephia_authplugin_func.h>
#include <eurephia_nullsafe.h>
#include <eurephiadb_driver.h>
#include <eurephiadb.h>
#include <eurephiafw.h>
#include <eurephia_values.h>
#include <eurephiadb_session_common.h>
#include <eurephiadb_session.h>
#include <certinfo.h>
#include <randstr.h>
#include <passwd.h>
#include <environment.h>

#define MAX_ARGUMENTS 64      /**<  Maximum arguments we will parse from the openvpn plug-in configuration */


/**
 * Initialises the eurephia OpenVPN plug-in and prepares a eurephiaCTX (context)
 *
 * @param argv  Arguments from the openvpn configuration file.
 *
 * @return returns a pointer to a eurephiaCTX context.  On failure NULL is returned.
 */
eurephiaCTX *eurephiaInit(const char const **argv, const char const **envp,
                          struct openvpn_plugin_callbacks const *ovpn_callbacks)
{
        static struct option eurephia_opts[] = {
                {"log-destination", required_argument, 0, 'l'},
                {"log-level", required_argument, 0, 'L'},
                {"database-interface", required_argument, 0, 'i'},
                {0, 0, 0 ,0}
        };
        int argc = 0, error = 0, loglvl = 0, dbargc = 0;
        const char *dbargv[MAX_ARGUMENTS];
        const char *fwintf = NULL, *logfile = NULL, *dbi = NULL;
        eurephiaCTX *ctx = NULL;

        //
        // Parse input arguments
        //

        // Count arguments
        for( argc = 0; argv[argc] != NULL; argc++ ) {}

        while(1) {
                int opt_idx = 0;
                int c = 0;

                c = getopt_long(argc, (char **)argv, "l:L:i:", eurephia_opts, &opt_idx);
                if( c == -1 ) {
                        break;
                }

                switch( c ) {
                case 'l':
                        logfile = optarg;
                        break;

                case 'L':
                        loglvl = atoi_nullsafe(optarg);
                        break;

                case 'i':
                        dbi = optarg;
                        break;

                default:
                        fprintf(stderr, "Error parsing eurephia-auth arguments.\n");
                        return NULL;
                        break;
                }
        }

        // Put the rest of the arguments into an own array which will be the db module arguments
        if( optind < argc ) {
                // copy arguments, but make sure we do not exceed our limit
                while( (optind < argc) && (dbargc < MAX_ARGUMENTS) ) {
                        dbargv[dbargc] = argv[optind++];
                        dbargc++;
                        dbargv[dbargc] = NULL;
                }
        }
        // End of argument parsing

        // Prepare a context area for eurephia-auth
        ctx = (eurephiaCTX *) malloc_nullsafe(NULL, sizeof(eurephiaCTX)+2);
        assert( ctx != NULL );
        if( mlock(ctx, sizeof(eurephiaCTX)+2) < 0 ) {
                eurephia_log(ctx, LOG_CRITICAL, 0, "Could not mlock() eurephia context: %s",
                             strerror(errno));
        };
        ctx->context_type = ECTX_PLUGIN_AUTH;

        // Open a log file
        if( (logfile == NULL) || (strcmp(logfile, "openvpn:") == 0) ) {
                // If no logfile is given, or openvpn: is given,
                // log to the OpenVPN plug-in v3 log callback if available,
                // otherwise stderr which OpenVPN will take care of in a different way
                if( (ovpn_callbacks != NULL) && (ovpn_callbacks->plugin_vlog != NULL) ) {
                        eurephia_log_init(ctx, "eurephia-auth", "openvpn:", loglvl,
                                          ovpn_callbacks->plugin_vlog);
                } else {
                        eurephia_log_init(ctx, "eurephia-auth", "stderr:", loglvl, NULL);
                }
        } else  {
                // If another log file is given, process that
                eurephia_log_init(ctx, "eurephia-auth", logfile, loglvl, NULL);
        }
        eurephia_log(ctx, LOG_INFO, 0, "Initialising eurephia v" EUREPHIAVERSION
                     " (David Sommerseth (C) 2008-2012 GPLv2)");

        // Load the database driver
        if( (error == 0) && eDBlink_init(ctx, dbi, 4) ) {
                // Connect to the database
                if( !eDBconnect(ctx, dbargc, dbargv) ) {
                        eurephia_log(ctx, LOG_PANIC, 0, "Could not connect to the database");
                        error = 1;
                        eDBlink_close(ctx);
                }
        } else {
                eurephia_log(ctx, LOG_PANIC, 0, "Could not load the database driver");
                error = 1;
        }

        if( error > 0 ) {
                eurephia_log(ctx, LOG_PANIC, 0, "eurephia-auth is not available");
                eurephia_log_close(ctx);
                free_nullsafe(ctx, ctx);
                return NULL;
        }

        // Get data for server_salt - which will be used for the password cache
        ctx->server_salt = (char *) malloc_nullsafe(ctx, SIZE_PWDCACHE_SALT+2);
        assert( ctx->server_salt != NULL );
        if( mlock(ctx->server_salt, SIZE_PWDCACHE_SALT+2) < 0 ) {
                eurephia_log(ctx, LOG_CRITICAL, 0, "Could not mlock() eurephia server salt: %s",
                             strerror(errno));
        }

        if( !eurephia_randstring(ctx, ctx->server_salt, SIZE_PWDCACHE_SALT) ) {
                eurephia_log(ctx, LOG_PANIC, 0 ,
                             "Could not get enough random data for password cache.");

                free_nullsafe(ctx, ctx->server_salt);
                eDBdisconnect(ctx);
                eurephia_log_close(ctx);
                free_nullsafe(ctx, ctx);
                return NULL;
        }

        // Check if firewall functionality is enabled, load module if given
        fwintf = eGet_value(ctx->dbc->config, "firewall_interface");
        if( fwintf != NULL ) {
                if( eFW_load(ctx, fwintf) ) {
                        char *daemon_s = GETENV_DAEMON(envp);
                        char *logredir_s = GETENV_DAEMONLOGREDIR(envp);

                        eurephia_log(ctx, LOG_INFO, 0, "Loaded firewall interface: %s", fwintf);
                        eFW_StartFirewall(ctx,
                                          (daemon_s && (daemon_s[0] == '1')),
                                          (logredir_s && logredir_s[0] == '1'));
                        free_nullsafe(ctx, daemon_s);
                        free_nullsafe(ctx, logredir_s);
                } else {
                        eurephia_log(ctx, LOG_FATAL, 0, "Loading of firewall interface failed (%s)", fwintf);
                        ctx->eurephia_fw_intf = NULL;
                }
        } else {
                ctx->eurephia_fw_intf = NULL;
        }

        // Initialise authentication plug-ins.  If no authentication plug-ins have been enabled,
        // the authplugs context will be NULL.
        ctx->authplugs = eAuthPlugin_Init(ctx);
        ctx->nointernalauth = atoi_nullsafe(eGet_value(ctx->dbc->config, "auth_disable_internal")) > 0;

        // Prepare an empty disconnected list.
        // This one is used to track all clients IP addresses and their corresponding eurephia session ID
        // when they disconnect.  This is especially needed in TUN mode, the eurephia_learn_address()
        // delete call with otherwise have too little information to identify the session.
        ctx->disconnected = eCreate_value_space(ctx, 12);

        eurephia_log(ctx, LOG_INFO, 1, "eurephia-auth is initialised");
        return ctx;
}


/**
 * Shutdowns the eurephia plug-in properly, disconnecting from database, unloading drivers,
 * closing log files and cleaning up the memory used.
 *
 * @param ctx  The eurephiaCTX used by openvpn.
 *
 * @return Returns 1 on success, otherwise 0.
 */
int eurephiaShutdown(eurephiaCTX *ctx)
{
        if( ctx == NULL ) {
                return 0;
        }

        if( ctx->disconnected != NULL ) {
                eFree_values(ctx, ctx->disconnected);
                ctx->disconnected = NULL;
        }

        if( ctx->eurephia_fw_intf != NULL ) {
                if( ctx->fwcfg != NULL ) {
                        eFW_StopFirewall(ctx);
                }
                eFW_unload(ctx);
        }

        if( ctx->authplugs != NULL ) {
                eAuthPlugin_Close(ctx, ctx->authplugs);
        }

        if( (ctx->dbc != NULL) && (ctx->dbc->dbhandle != NULL) ) {
                eDBdisconnect(ctx);
        }

        if( ctx->eurephia_driver != NULL ) {
                eDBlink_close(ctx);
        }

        eurephia_log_close(ctx);

        memset(ctx->server_salt, 0xff, SIZE_PWDCACHE_SALT+2);
        munlock(ctx->server_salt, SIZE_PWDCACHE_SALT+2);
        free_nullsafe(ctx, ctx->server_salt);
        munlock(ctx, sizeof(eurephiaCTX)+2);
        free_nullsafe(ctx, ctx);
        return 1;
}


/**
 * Verifies the certificate digest (SHA1 fingerprint) against the database.
 *
 * @param ctx        eurephiaCTX
 * @param env        openvpn environment table containing all the information we need
 * @param depth_str  If depth is 0, it's a client certificate, or else it's a CA certificate.
 *                   The input is a string containing the depth value.
 *
 * @return Returns 0 on failure and 1 on success.
 */
int eurephia_tlsverify(eurephiaCTX *ctx, const char **env, const char *depth_str,
                       certinfo *ci)
{
        int result = 0;
        char *ipaddr;
        unsigned int depth = atoi_nullsafe(depth_str);

        DEBUG(ctx, 10, "** Function call: eurephia_tlsverify(...)");

        // Check if IP address is blacklisted
        ipaddr = GETENV_UNTRUSTEDIP(ctx, env);
        if( eDBblacklist_check(ctx, attempt_IPADDR, ipaddr) == 1 ) {
                eDBregister_attempt(ctx, attempt_IPADDR, ATTEMPT_REGISTER, ipaddr);

                // If fw blacklisting is configured, also blacklist there too
                if( (ctx->fwcfg != NULL) && (ctx->fwcfg->fwblacklist != NULL ) ) {
                        eFWupdateRequest req = { .mode = fwBLACKLIST, };
                        strncpy(req.ipaddress, ipaddr, sizeof(req.ipaddress));
                        eFW_UpdateFirewall(ctx, &req);
                }
                free_nullsafe(ctx, ipaddr);
                return 0;
        }

        // Check if certificate digest is blacklisted
        if( eDBblacklist_check(ctx, attempt_CERTIFICATE, ci->digest) == 1 ) {
                eDBregister_attempt(ctx, attempt_IPADDR, ATTEMPT_REGISTER, ipaddr);
                eDBregister_attempt(ctx, attempt_CERTIFICATE, ATTEMPT_REGISTER, ci->digest);
                free_nullsafe(ctx, ipaddr);
                return 0;
        }

        // Check if certificate is registered and allowed
        result = eDBauth_TLS(ctx, ci->org, ci->common_name, ci->email, ci->digest, depth);
        if( result < 1 ) {
                eDBregister_attempt(ctx, attempt_IPADDR, ATTEMPT_REGISTER, ipaddr);
                eDBregister_attempt(ctx, attempt_CERTIFICATE, ATTEMPT_REGISTER, ci->digest);
        }

        if( result > 0 ) {
                // Certificate is okay, result contains the certificate ID
                eurephia_log(ctx, LOG_INFO, (depth == 0 ? 0 : 1),
                             "Found certid %i for user: %s/%s/%s",
                             result, ci->org, ci->common_name, ci->email);
        } else {
                eurephia_log(ctx, LOG_WARNING, 0,
                             "Unknown certificate for: %s/%s/%s (depth %i, digest: %s)",
                             ci->org, ci->common_name, ci->email, depth, ci->digest);
        }
        free_nullsafe(ctx, ipaddr);
        DEBUG(ctx, 10, "** Function result: eurephia_tlsverify(...) == %i", result > 0);

        return (result > 0);
}


/**
 * Authenticates the given user name, password and client certificate against the database.
 *
 * @param ctx  eurephiaCTX
 * @param env  openvpn environment table
 *
 * @return Returns 0 on failure and 1 on success.
 */
int eurephia_userauth(eurephiaCTX *ctx, const char **env, certinfo *ci)
{
        eurephiaSESSION *authsess = NULL;
        eDBauthMethodResult *authmeth = NULL;
        eAuthPlugin *authplug = NULL;
        eAuthResult *authres = NULL;
        int result = 0, certid = 0;
        char *remport, *ipaddr = NULL;
        char *username = NULL;
        char *passwd = NULL, *pwdcache = NULL, *chkpwd = NULL;

        DEBUG(ctx, 10, "** Function call: eurephia_userauth(...)");


        // Check if IP address is blacklisted
        ipaddr = GETENV_UNTRUSTEDIP(ctx, env);
        if( eDBblacklist_check(ctx, attempt_IPADDR, ipaddr) == 1 ) {
                eDBregister_attempt(ctx, attempt_IPADDR, ATTEMPT_REGISTER, ipaddr);

                // If fw blacklisting is configured, also blacklist there too
                if( (ctx->fwcfg != NULL) && (ctx->fwcfg->fwblacklist != NULL ) ) {
                        eFWupdateRequest req = { .mode = fwBLACKLIST, };
                        strncpy(req.ipaddress, ipaddr, sizeof(req.ipaddress));
                        eFW_UpdateFirewall(ctx, &req);
                }
                free_nullsafe(ctx, ipaddr);

                return 0;
        }

        // Check if certificate digest is blacklisted
        if( eDBblacklist_check(ctx, attempt_CERTIFICATE, ci->digest) == 1 ) {
                eDBregister_attempt(ctx, attempt_IPADDR, ATTEMPT_REGISTER, ipaddr);
                eDBregister_attempt(ctx, attempt_CERTIFICATE, ATTEMPT_REGISTER, ci->digest);
                free_nullsafe(ctx, ipaddr);
                return 0;
        }

        // Check if username is blacklisted
        username = GETENV_USERNAME(ctx, env);
        if( eDBblacklist_check(ctx, attempt_USERNAME, username) == 1 ) {
                eDBregister_attempt(ctx, attempt_IPADDR, ATTEMPT_REGISTER, ipaddr);
                eDBregister_attempt(ctx, attempt_CERTIFICATE, ATTEMPT_REGISTER, ci->digest);
                eDBregister_attempt(ctx, attempt_USERNAME, ATTEMPT_REGISTER, username);
                free_nullsafe(ctx, username);
                free_nullsafe(ctx, ipaddr);
                return 0;
        }

        // Get certificate ID
        certid = eDBauth_TLS(ctx, ci->org, ci->common_name, ci->email, ci->digest, 0);
        if( certid < 1 ) {
                eDBregister_attempt(ctx, attempt_IPADDR, ATTEMPT_REGISTER, ipaddr);
                eDBregister_attempt(ctx, attempt_CERTIFICATE, ATTEMPT_REGISTER, ci->digest);
                eDBregister_attempt(ctx, attempt_USERNAME, ATTEMPT_REGISTER, username);
                free_nullsafe(ctx, username);
                free_nullsafe(ctx, ipaddr);
                return 0;
        }

        // Do username/password/certificate authentication
        passwd = GETENV_PASSWORD(ctx, env);
        mlock(passwd, strlen_nullsafe(passwd));
        if( (passwd == NULL) || (strlen_nullsafe(passwd) == 0) ) {
                eurephia_log(ctx, LOG_WARNING, 0, "eurephia-auth: No password received.  Action aborted");
                memset(passwd, 0, strlen_nullsafe(passwd));
                munlock(passwd, strlen_nullsafe(passwd));
                free_nullsafe(ctx, passwd);
                free_nullsafe(ctx, username);
                free_nullsafe(ctx, ipaddr);
                return 0;
        }

        // Check if we have a valid password cached
        chkpwd = eurephia_quick_hash(ctx->server_salt, passwd);

        // Get an authentication session, which is not a real session ticket
        // but it uses almost the same system
        remport   = GETENV_UNTRUSTEDPORT(ctx, env);

        // an authentication session do not use assigned VPN address
        authsess = eDBopen_session_seed(ctx, ci->digest, ci->common_name, username,
                                        NULL, NULL,
                                        ipaddr, remport);
        if( authsess == NULL ) {
                // No session found
                goto chk_pwd;
        }
        // Get cached password from password cache
        pwdcache = eGet_value(authsess->sessvals, "pwdcache");

        if( (pwdcache != NULL) && (chkpwd != NULL) && (strcmp(pwdcache, chkpwd) == 0) ) {
                // if cached password matches users password, we're done
                eurephia_log(ctx, LOG_INFO, 3, "Authenticated user '%s' against password cache",
                             username);
                eDBfree_session(ctx, authsess);
                result = 1;
                goto exit;
        }

        // If we do not have a valid password cached, check against the user database
 chk_pwd:
        authmeth = eDBauth_GetAuthMethod(ctx, certid, username);
        if( authmeth == NULL ) {
                eurephia_log(ctx, LOG_ERROR, 0,
                             "Failed to identify authentication method for user '%s' with"
                             "certid %i", username, certid);
                result = 0;
                goto exit;
        }

        switch (authmeth->method) {
        case eAM_INTERNDB:
                DEBUG(ctx, 12, "Using internal authentication for user '%s'/certid %i",
                      username, certid);
                if( ctx->nointernalauth == 0 ) {
                        /* Authenticate against the internal eurephia database */
                        result = eDBauth_user(ctx, certid, username, passwd);
                } else {
                        eurephia_log(ctx, LOG_WARNING, 0,
                                     "Internal authentication has been disabled.  Enable "
                                     "authentication plug-in for user '%s' with certid %i",
                                     username, certid);
                        result = 0;
                }
                break;

        case eAM_PLUGIN:
                authplug = eAuthPlugin_Get(ctx->authplugs, authmeth->authplugid);
                if( authplug == NULL ) {
                        eurephia_log(ctx, LOG_ERROR, 0,
                                     "Failed to find authentication plug-in %i to authenticate"
                                     "user '%s' with certid %i",
                                     authmeth->authplugid, username, certid);
                        result = 0;
                        goto exit;
                }
                DEBUG(ctx, 12, "Using authentication plugin %i for user '%s'/certid %i",
                      authmeth->authplugid, username, certid);

                /* Authenticate the user via the auth plug-in */
                authres = authplug->AuthenticateUser(ctx, authmeth->username, passwd);
                if( authres == NULL ) {
                        eurephia_log(ctx, LOG_FATAL, 0,
                                     "Invalid response from authentication plug-in %i",
                                     authmeth->authplugid);
                        result = 0;
                        goto exit;
                }

                /* Parse the authentication result */
                switch( authres->status ) {
                case eAUTH_FAILED:
                        eurephia_log(ctx, LOG_WARNING, 0,"Authentication failed for user '%s': %s",
                                     username, authres->msg);
                        sleep(2);
                        result = -1;
                        break;

                case eAUTH_PLGERROR:
                        eurephia_log(ctx, LOG_ERROR, 0,
                                     "Authentication plug-in %i returned with an internal error "
                                     "while authenticating user '%s' (uicid: %i): %s",
                                     authmeth->authplugid,
                                     authmeth->username,
                                     authmeth->uicid,
                                     authres->msg);
                        result = 0;
                        goto exit;

                case eAUTH_SUCCESS:
                        result = authmeth->uicid;
                        if( authres->msg != NULL ) {
                                eurephia_log(ctx, LOG_INFO, 1,
                                             "Authentication plug-in (%i) success response "
                                             "for user '%s' (uicid: %i): %s",
                                             authmeth->authplugid,
                                             authmeth->username,
                                             result,
                                             authres->msg);
                        }
                        break;

                default:
                        eurephia_log(ctx, LOG_FATAL, 0,
                                     "Invalid response from authentication plug-in %i when "
                                     "authenticating user '%s': %i",
                                     authmeth->authplugid, authmeth->username, authres->status);
                        result = 0;
                        break;
                }
                break;

        case eAM_BLACKLISTED:
                DEBUG(ctx, 12, "User '%s'/certid %i is blacklisted", username, certid);
                result = -1;
                break;

        case eAM_INACTIVE:
                DEBUG(ctx, 12, "User '%s' is not activated", username);
                result = -1;
                break;

        default:
                eurephia_log(ctx, LOG_FATAL, 0,
                             "Invalid authentication method attempted (%i) for "
                             "user '%s' with certid %i",
                             authmeth->method, username, certid);
                break;
        }
        eDBauth_FreeAuthMethodResult(ctx, authmeth);

        /* If the authentication failed, register the failed attempt */
        if( result < 0 ) {
                eDBregister_attempt(ctx, attempt_IPADDR, ATTEMPT_REGISTER, ipaddr);
                eDBregister_attempt(ctx, attempt_CERTIFICATE, ATTEMPT_REGISTER, ci->digest);
                eDBregister_attempt(ctx, attempt_USERNAME, ATTEMPT_REGISTER, username);
        }

        if( result > 0 ) {
                // If we have a valid result, reset all attempt counters.
                eDBregister_attempt(ctx, attempt_IPADDR, ATTEMPT_RESET, ipaddr);
                eDBregister_attempt(ctx, attempt_CERTIFICATE, ATTEMPT_RESET, ci->digest);
                eDBregister_attempt(ctx, attempt_USERNAME, ATTEMPT_RESET, username);

                if( !eDBset_session_value(ctx, authsess, "pwdcache", chkpwd) ) {
                        eurephia_log(ctx, LOG_WARNING, 0,
                                     "Failed to cache password for user '%s'", username);
                }
                eurephia_log(ctx, LOG_INFO, 0, "User '%s' authenticated", username);
        }

 exit:
        memset(passwd, 0, strlen_nullsafe(passwd));
        munlock(passwd, strlen_nullsafe(passwd));
        eDBfree_session(ctx, authsess);
        free_nullsafe(ctx, remport);
        free_nullsafe(ctx, passwd);
        free_nullsafe(ctx, username);
        free_nullsafe(ctx, ipaddr);
        free_nullsafe(ctx, chkpwd);
        DEBUG(ctx, 10, "** Function result: eurephia_userauth(...) = %i", (result>0));
        return (result > 0);
}


/**
 * Called when openvpn has authenticated the user and granted it access.  This function
 * will log information about the client
 *
 * @param ctx eurephiaCTX
 * @param env  openvpn environment table
 *
 * @return Returns 0 on failure and 1 on success.
 */
int eurephia_connect(eurephiaCTX *ctx, const char **env, certinfo *ci) {
        eurephiaSESSION *session = NULL;
        char *uname, *vpnipaddr, *vpnipmask, *remipaddr, *remport, *proto;
        int certid = 0, uid = 0, accprofile = -1, ret = 0;

        DEBUG(ctx, 10, "** Function call: eurephia_connect(...)");

        // Fetch needed info
        uname     = GETENV_USERNAME(ctx, env);
        vpnipaddr = GETENV_POOLIPADDR(ctx, env);
        vpnipmask = GETENV_POOLNETMASK(ctx, env);
        remipaddr = GETENV_TRUSTEDIP(ctx, env);
        remport   = GETENV_TRUSTEDPORT(ctx, env);
        proto     = GETENV_PROTO1(ctx, env);

        // Get a session ticket
        session = eDBopen_session_seed(ctx, ci->digest, ci->common_name,
                                       uname, vpnipaddr, vpnipmask,
                                       remipaddr, remport);
        if( session == NULL ) {
                free_nullsafe(ctx, proto);
                free_nullsafe(ctx, remport);
                free_nullsafe(ctx, remipaddr);
                free_nullsafe(ctx, vpnipaddr);
                free_nullsafe(ctx, vpnipmask);
                free_nullsafe(ctx, uname);
                return 0;
        }

        certid = eDBauth_TLS(ctx, ci->org, ci->common_name, ci->email, ci->digest, 0);
        if( certid < 1 ) {
                eurephia_log(ctx, LOG_WARNING, 0, "Failed to lookup certificate: %s/%s/%s [%s]",
                             ci->org, ci->common_name, ci->email, ci->digest);
                return 0;
        }
        uid = eDBget_uid(ctx, certid, uname);

        // Register the session login
        accprofile = eDBget_accessprofile(ctx, uid, certid);
        ret = eDBregister_login2(ctx, session, certid, accprofile, uid, proto,
                                 remipaddr, remport);
        eDBfree_session(ctx, session);
        eurephia_log(ctx, LOG_INFO, 1, "User '%s' connected", uname);

        free_nullsafe(ctx, proto);
        free_nullsafe(ctx, remport);
        free_nullsafe(ctx, remipaddr);
        free_nullsafe(ctx, vpnipaddr);
        free_nullsafe(ctx, vpnipmask);
        free_nullsafe(ctx, uname);

        DEBUG(ctx, 10, "** Function result: eurephia_connect(...) = %i", ret);
        return ret;
}

/**
 * Called when the client disconnects.  This function logs some statistics about the session
 *
 * @param ctx  eurephiaCTX
 * @param env  openvpn environment table
 *
 * @return Returns 0 on failure and 1 on success.
 */
int eurephia_disconnect(eurephiaCTX *ctx, const char **env, certinfo *ci) {
        eurephiaSESSION *session = NULL;
        char *uname, *vpnipaddr, *vpnipmask, *remipaddr, *remport;
        char *bytes_sent, *bytes_rec, *duration;
        int ret = 0;

        DEBUG(ctx, 10, "** Function call: eurephia_disconnect(...)");

        // Fetch needed info
        uname     = GETENV_USERNAME(ctx, env);
        vpnipaddr = GETENV_POOLIPADDR(ctx, env);
        vpnipmask = GETENV_POOLNETMASK(ctx, env);
        remipaddr = GETENV_TRUSTEDIP(ctx, env);
        remport   = GETENV_TRUSTEDPORT(ctx, env);
        bytes_sent= GETENV_BYTESSENT(ctx, env);
        bytes_rec = GETENV_BYTESRECEIVED(ctx, env);
        duration  = GETENV_TIMEDURATION(ctx, env);

        // Get a session ticket
        session = eDBopen_session_seed(ctx, ci->digest, ci->common_name, uname,
                                       vpnipaddr, vpnipmask,
                                       remipaddr, remport);
        if( session == NULL ) {
                free_nullsafe(ctx, duration);
                free_nullsafe(ctx, bytes_rec);
                free_nullsafe(ctx, bytes_sent);
                free_nullsafe(ctx, remport);
                free_nullsafe(ctx, remipaddr);
                free_nullsafe(ctx, vpnipaddr);
                free_nullsafe(ctx, vpnipmask);
                free_nullsafe(ctx, uname);
                return 0;
        }

        if( ctx->tuntype == tuntype_TUN ) {
                // Put the clients IP address into the disconnected list, to be used and freed
                // by eurephia_learn_address() afterwards
                eAdd_value(ctx, ctx->disconnected, vpnipaddr, session->sessionkey);
        }

        ret = eDBregister_logout(ctx, session, bytes_sent, bytes_rec, duration);
        eDBfree_session(ctx, session);
        eurephia_log(ctx, LOG_INFO, 1, "User '%s' logged out", uname);

        // Get the authentication session and destroy it
        session = eDBopen_session_seed(ctx, ci->digest, ci->common_name, uname,
                                       NULL, NULL, remipaddr, remport);
        if( !eDBdestroy_session(ctx, session) ) {
                eurephia_log(ctx, LOG_WARNING, 0,
                             "Could not destroy authentication session (%s/%s/%s)",
                             uname, ci->common_name, ci->digest);
        }
        eDBfree_session(ctx, session);
        free_nullsafe(ctx, duration);
        free_nullsafe(ctx, bytes_rec);
        free_nullsafe(ctx, bytes_sent);
        free_nullsafe(ctx, remport);
        free_nullsafe(ctx, remipaddr);
        free_nullsafe(ctx, vpnipaddr);
        free_nullsafe(ctx, vpnipmask);
        free_nullsafe(ctx, uname);

        DEBUG(ctx, 10, "** Function result: eurephia_disconnect(...) = %i", ret);
        return ret;
}

/**
 * Called whenever openvpn assigns or changes IP addresses of the client.  The function logs
 * this information to keep track of which user was assigned which IP address and which MAC address
 * the user had during the connection as well.  If the firewall interface is enabled, it will also
 * request an update via the firewall driver.
 *
 * @param ctx     eurephiaCTX
 * @param mode    strings which can be "add", "delete".  In some cases also "update".
 * @param macaddr string containing the MAC address of the client, if received from openvpn
 * @param env     openvpn environment table
 *
 * @return Returns 0 on failure and 1 on success.
 */
int eurephia_learn_address(eurephiaCTX *ctx, const char *mode, const char *clientaddr,
                           const char **env, certinfo *ci) {
        eurephiaSESSION *session = NULL;
        char *uname = NULL, *vpnipaddr = NULL, *vpnipmask = NULL,
                *remipaddr = NULL, *remport = NULL;
        char *fwprofile = NULL, *fwdest = NULL;
        int ret = 0, fw_enabled = 0;

        DEBUG(ctx, 10, "** Function call: eurephia_learn_address(ctx, '%.10s', '%.64s', ...)",
              mode, clientaddr);

        // Get firewall information
        fw_enabled = (eGet_value(ctx->dbc->config, "firewall_interface") != NULL);
        fwdest = eGet_value(ctx->dbc->config, "firewall_destination");
        if( fw_enabled && (fwdest == NULL) ) {
                eurephia_log(ctx, LOG_CRITICAL, 0, "No firewall destination defined in the config.");
        }

        // In TUN mode, if a client reconnects quickly after a disconnect,
        // OpenVPN re-uses the session for this and just sends an update
        // call to LEARN_ADDRESS.  As eurephia in TUN mode treats disconnects
        // with an explicit 'delete' (see eurephia-auth.c for more info) and
        // don't wait for a separate LEARN_ADDRESS delete call (which never
        // seems to come), we treat 'update' as an ordinary 'add' in TUN mode.
        if( (strncmp(mode, "add", 3) == 0)
            || ((ctx->tuntype == tuntype_TUN) && (strncmp(mode, "update", 6) == 0)) ) {

                // Fetch needed info
                uname     = GETENV_USERNAME(ctx, env);
                vpnipaddr = GETENV_POOLIPADDR(ctx, env);
                vpnipmask = GETENV_POOLNETMASK(ctx, env);
                remipaddr = GETENV_TRUSTEDIP(ctx, env);
                remport   = GETENV_TRUSTEDPORT(ctx, env);

                // Get a session ticket
                session = eDBopen_session_seed(ctx, ci->digest, ci->common_name, uname,
                                               vpnipaddr, vpnipmask,
                                               remipaddr, remport);
                if( session == NULL ) {
                        ret = 0;
                        goto exit;
                }

                // Update openvpn_lastlog with the active VPN client addresses, and save it as a
                // session variable.  clientaddr will contain the MAC address in TAP mode
                ret = eDBregister_vpnclientaddr(ctx, session,
                                                (ctx->tuntype == tuntype_TAP ? clientaddr : NULL),
                                                vpnipaddr, NULL);

                if( (fw_enabled) && (fwdest != NULL) ) {
                        fwprofile = eDBget_firewall_profile(ctx, session);
                        if( fwprofile != NULL ) {
                                eFWupdateRequest req = { .mode = fwADD, };
                                if( ctx->tuntype == tuntype_TAP ) {
                                        strncpy(req.macaddress, clientaddr, sizeof(req.macaddress));
                                } else {
                                        strncpy(req.ipaddress, vpnipaddr, sizeof(req.ipaddress));
                                }
                                strncpy(req.rule_destination, fwdest, sizeof(req.rule_destination));
                                strncpy(req.goto_destination, fwprofile, sizeof(req.goto_destination));
                                eFW_UpdateFirewall(ctx, &req);
                                free_nullsafe(ctx, fwprofile);
                        }
                }
                eDBfree_session(ctx, session);

        } else if( strncmp(mode, "delete", 6) == 0 ) {

                // Load the session
                if( ctx->tuntype == tuntype_TAP ) {
                        // in TAP mode - use the MAC address
                        session = eDBopen_session_macaddr(ctx, clientaddr);
                } else {
                        // in TUN mode - use the disconnected list to find the session key
                        eurephiaVALUES *sessval = eGet_valuestruct(ctx->disconnected, clientaddr);
                        if( sessval ) {
                                session = eDBsession_load(ctx, sessval->val, stSESSION);
                                if( ctx->disconnected->next != NULL ) {
                                        ctx->disconnected = eRemove_value(ctx, ctx->disconnected,
                                                                          sessval->evgid, sessval->evid);
                                } else {
                                        eClear_key_value(ctx->disconnected);
                                }
                        }
                }
                if( session == NULL ) {
                        eurephia_log(ctx, LOG_WARNING, 0,
                                     "Could not find any session connected to the client address %s",
                                     clientaddr);
                        ret = 0;
                        goto exit;
                }

                if( (fw_enabled) && (fwdest != NULL) ) {
                        fwprofile = eDBget_firewall_profile(ctx, session);
                        if( fwprofile != NULL ) {
                                eFWupdateRequest req = { .mode = fwDELETE, };
                                if( ctx->tuntype == tuntype_TAP) {
                                        strncpy(req.macaddress, clientaddr, sizeof(req.macaddress));
                                } else {
                                        strncpy(req.ipaddress, clientaddr, sizeof(req.ipaddress));
                                }
                                strncpy(req.rule_destination, fwdest, sizeof(req.rule_destination));
                                strncpy(req.goto_destination, fwprofile, sizeof(req.goto_destination));
                                eFW_UpdateFirewall(ctx, &req);
                                free_nullsafe(ctx, fwprofile);
                        }
                }
                ret = eDBdestroy_session(ctx, session);
                eDBfree_session(ctx, session);
        }

 exit:
        free_nullsafe(ctx, remport);
        free_nullsafe(ctx, remipaddr);
        free_nullsafe(ctx, vpnipaddr);
        free_nullsafe(ctx, vpnipmask);
        free_nullsafe(ctx, uname);
        DEBUG(ctx, 10, "** Function result: eurephia_learn_address(ctx, '%s', '%.18s', ...) = %i",
                     mode, clientaddr, ret);

        return ret;
}