summaryrefslogtreecommitdiff
path: root/src/plugins/auth-pam/auth-pam.c
blob: f537652ea35212d57f485374562de5a543a7229a (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
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
/*
 *  OpenVPN -- An application to securely tunnel IP networks
 *             over a single TCP/UDP port, with support for SSL/TLS-based
 *             session authentication and key exchange,
 *             packet encryption, packet authentication, and
 *             packet compression.
 *
 *  Copyright (C) 2002-2018 OpenVPN Inc <sales@openvpn.net>
 *  Copyright (C) 2016-2018 Selva Nair <selva.nair@gmail.com>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 2
 *  as published by the Free Software Foundation.
 *
 *  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.
 */

/*
 * OpenVPN plugin module to do PAM authentication using a split
 * privilege model.
 */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <security/pam_appl.h>

#ifdef USE_PAM_DLOPEN
#include "pamdl.h"
#endif

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <signal.h>
#include <syslog.h>
#include "utils.h"

#include <openvpn-plugin.h>

#define DEBUG(verb) ((verb) >= 4)

/* Command codes for foreground -> background communication */
#define COMMAND_VERIFY 0
#define COMMAND_EXIT   1

/* Response codes for background -> foreground communication */
#define RESPONSE_INIT_SUCCEEDED   10
#define RESPONSE_INIT_FAILED      11
#define RESPONSE_VERIFY_SUCCEEDED 12
#define RESPONSE_VERIFY_FAILED    13
#define RESPONSE_DEFER            14

/* Pointers to functions exported from openvpn */
static plugin_log_t plugin_log = NULL;
static plugin_secure_memzero_t plugin_secure_memzero = NULL;
static plugin_base64_decode_t plugin_base64_decode = NULL;

/* module name for plugin_log() */
static char *MODULE = "AUTH-PAM";

/*
 * Plugin state, used by foreground
 */
struct auth_pam_context
{
    /* Foreground's socket to background process */
    int foreground_fd;

    /* Process ID of background process */
    pid_t background_pid;

    /* Verbosity level of OpenVPN */
    int verb;
};

/*
 * Name/Value pairs for conversation function.
 * Special Values:
 *
 *  "USERNAME" -- substitute client-supplied username
 *  "PASSWORD" -- substitute client-specified password
 *  "COMMONNAME" -- substitute client certificate common name
 *  "OTP" -- substitute static challenge response if available
 */

#define N_NAME_VALUE 16

struct name_value {
    const char *name;
    const char *value;
};

struct name_value_list {
    int len;
    struct name_value data[N_NAME_VALUE];
};

/*
 * Used to pass the username/password
 * to the PAM conversation function.
 */
struct user_pass {
    int verb;

    char username[128];
    char password[128];
    char common_name[128];
    char response[128];

    const struct name_value_list *name_value_list;
};

/* Background process function */
static void pam_server(int fd, const char *service, int verb, const struct name_value_list *name_value_list);


/*
 * Socket read/write functions.
 */

static int
recv_control(int fd)
{
    unsigned char c;
    const ssize_t size = read(fd, &c, sizeof(c));
    if (size == sizeof(c))
    {
        return c;
    }
    else
    {
        /*fprintf (stderr, "AUTH-PAM: DEBUG recv_control.read=%d\n", (int)size);*/
        return -1;
    }
}

static int
send_control(int fd, int code)
{
    unsigned char c = (unsigned char) code;
    const ssize_t size = write(fd, &c, sizeof(c));
    if (size == sizeof(c))
    {
        return (int) size;
    }
    else
    {
        return -1;
    }
}

static int
recv_string(int fd, char *buffer, int len)
{
    if (len > 0)
    {
        ssize_t size;
        memset(buffer, 0, len);
        size = read(fd, buffer, len);
        buffer[len-1] = 0;
        if (size >= 1)
        {
            return (int)size;
        }
    }
    return -1;
}

static int
send_string(int fd, const char *string)
{
    const int len = strlen(string) + 1;
    const ssize_t size = write(fd, string, len);
    if (size == len)
    {
        return (int) size;
    }
    else
    {
        return -1;
    }
}

#ifdef DO_DAEMONIZE

/*
 * Daemonize if "daemon" env var is true.
 * Preserve stderr across daemonization if
 * "daemon_log_redirect" env var is true.
 */
static void
daemonize(const char *envp[])
{
    const char *daemon_string = get_env("daemon", envp);
    if (daemon_string && daemon_string[0] == '1')
    {
        const char *log_redirect = get_env("daemon_log_redirect", envp);
        int fd = -1;
        if (log_redirect && log_redirect[0] == '1')
        {
            fd = dup(2);
        }
        if (daemon(0, 0) < 0)
        {
            plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "daemonization failed");
        }
        else if (fd >= 3)
        {
            dup2(fd, 2);
            close(fd);
        }
    }
}

#endif /* ifdef DO_DAEMONIZE */

/*
 * Close most of parent's fds.
 * Keep stdin/stdout/stderr, plus one
 * other fd which is presumed to be
 * our pipe back to parent.
 * Admittedly, a bit of a kludge,
 * but posix doesn't give us a kind
 * of FD_CLOEXEC which will stop
 * fds from crossing a fork().
 */
static void
close_fds_except(int keep)
{
    int i;
    closelog();
    for (i = 3; i <= 100; ++i)
    {
        if (i != keep)
        {
            close(i);
        }
    }
}

/*
 * Usually we ignore signals, because our parent will
 * deal with them.
 */
static void
set_signals(void)
{
    signal(SIGTERM, SIG_DFL);

    signal(SIGINT, SIG_IGN);
    signal(SIGHUP, SIG_IGN);
    signal(SIGUSR1, SIG_IGN);
    signal(SIGUSR2, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
}

/*
 * Return 1 if query matches match.
 */
static int
name_value_match(const char *query, const char *match)
{
    while (!isalnum(*query))
    {
        if (*query == '\0')
        {
            return 0;
        }
        ++query;
    }
    return strncasecmp(match, query, strlen(match)) == 0;
}

/*
 * Split and decode up->password in the form SCRV1:base64_pass:base64_response
 * into pass and response and save in up->password and up->response.
 * If the password is not in the expected format, input is not changed.
 */
static void
split_scrv1_password(struct user_pass *up)
{
    const int skip = strlen("SCRV1:");
    if (strncmp(up->password, "SCRV1:", skip) != 0)
    {
        return;
    }

    char *tmp = strdup(up->password);
    if (!tmp)
    {
        plugin_log(PLOG_ERR, MODULE, "out of memory parsing static challenge password");
        goto out;
    }

    char *pass = tmp + skip;
    char *resp = strchr(pass, ':');
    if (!resp) /* string not in SCRV1:xx:yy format */
    {
        goto out;
    }
    *resp++ = '\0';

    int n = plugin_base64_decode(pass, up->password, sizeof(up->password)-1);
    if (n >= 0)
    {
        up->password[n] = '\0';
        n = plugin_base64_decode(resp, up->response, sizeof(up->response)-1);
        if (n >= 0)
        {
            up->response[n] = '\0';
            if (DEBUG(up->verb))
            {
                plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: parsed static challenge password");
            }
            goto out;
        }
    }

    /* decode error: reinstate original value of up->password and return */
    plugin_secure_memzero(up->password, sizeof(up->password));
    plugin_secure_memzero(up->response, sizeof(up->response));
    strcpy(up->password, tmp); /* tmp is guaranteed to fit in up->password */

    plugin_log(PLOG_ERR, MODULE, "base64 decode error while parsing static challenge password");

out:
    if (tmp)
    {
        plugin_secure_memzero(tmp, strlen(tmp));
        free(tmp);
    }
}

OPENVPN_EXPORT int
openvpn_plugin_open_v3(const int v3structver,
                       struct openvpn_plugin_args_open_in const *args,
                       struct openvpn_plugin_args_open_return *ret)
{
    pid_t pid;
    int fd[2];

    struct auth_pam_context *context;
    struct name_value_list name_value_list;

    const int base_parms = 2;

    const char **argv = args->argv;
    const char **envp = args->envp;

    /* Check API compatibility -- struct version 5 or higher needed */
    if (v3structver < 5)
    {
        fprintf(stderr, "AUTH-PAM: This plugin is incompatible with the running version of OpenVPN\n");
        return OPENVPN_PLUGIN_FUNC_ERROR;
    }

    /*
     * Allocate our context
     */
    context = (struct auth_pam_context *) calloc(1, sizeof(struct auth_pam_context));
    if (!context)
    {
        goto error;
    }
    context->foreground_fd = -1;

    /*
     * Intercept the --auth-user-pass-verify callback.
     */
    ret->type_mask = OPENVPN_PLUGIN_MASK(OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY);

    /* Save global pointers to functions exported from openvpn */
    plugin_log = args->callbacks->plugin_log;
    plugin_secure_memzero = args->callbacks->plugin_secure_memzero;
    plugin_base64_decode = args->callbacks->plugin_base64_decode;

    /*
     * Make sure we have two string arguments: the first is the .so name,
     * the second is the PAM service type.
     */
    if (string_array_len(argv) < base_parms)
    {
        plugin_log(PLOG_ERR, MODULE, "need PAM service parameter");
        goto error;
    }

    /*
     * See if we have optional name/value pairs to match against
     * PAM module queried fields in the conversation function.
     */
    name_value_list.len = 0;
    if (string_array_len(argv) > base_parms)
    {
        const int nv_len = string_array_len(argv) - base_parms;
        int i;

        if ((nv_len & 1) == 1 || (nv_len / 2) > N_NAME_VALUE)
        {
            plugin_log(PLOG_ERR, MODULE, "bad name/value list length");
            goto error;
        }

        name_value_list.len = nv_len / 2;
        for (i = 0; i < name_value_list.len; ++i)
        {
            const int base = base_parms + i * 2;
            name_value_list.data[i].name = argv[base];
            name_value_list.data[i].value = argv[base+1];
        }
    }

    /*
     * Get verbosity level from environment
     */
    {
        const char *verb_string = get_env("verb", envp);
        if (verb_string)
        {
            context->verb = atoi(verb_string);
        }
    }

    /*
     * Make a socket for foreground and background processes
     * to communicate.
     */
    if (socketpair(PF_UNIX, SOCK_DGRAM, 0, fd) == -1)
    {
        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "socketpair call failed");
        goto error;
    }

    /*
     * Fork off the privileged process.  It will remain privileged
     * even after the foreground process drops its privileges.
     */
    pid = fork();

    if (pid)
    {
        int status;

        /*
         * Foreground Process
         */

        context->background_pid = pid;

        /* close our copy of child's socket */
        close(fd[1]);

        /* don't let future subprocesses inherit child socket */
        if (fcntl(fd[0], F_SETFD, FD_CLOEXEC) < 0)
        {
            plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Set FD_CLOEXEC flag on socket file descriptor failed");
        }

        /* wait for background child process to initialize */
        status = recv_control(fd[0]);
        if (status == RESPONSE_INIT_SUCCEEDED)
        {
            context->foreground_fd = fd[0];
            ret->handle = (openvpn_plugin_handle_t *) context;
            plugin_log( PLOG_NOTE, MODULE, "initialization succeeded (fg)" );
            return OPENVPN_PLUGIN_FUNC_SUCCESS;
        }
    }
    else
    {
        /*
         * Background Process
         */

        /* close all parent fds except our socket back to parent */
        close_fds_except(fd[1]);

        /* Ignore most signals (the parent will receive them) */
        set_signals();

#ifdef DO_DAEMONIZE
        /* Daemonize if --daemon option is set. */
        daemonize(envp);
#endif

        /* execute the event loop */
        pam_server(fd[1], argv[1], context->verb, &name_value_list);

        close(fd[1]);

        exit(0);
        return 0; /* NOTREACHED */
    }

error:
    if (context)
    {
        free(context);
    }
    return OPENVPN_PLUGIN_FUNC_ERROR;
}

OPENVPN_EXPORT int
openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const char *argv[], const char *envp[])
{
    struct auth_pam_context *context = (struct auth_pam_context *) handle;

    if (type == OPENVPN_PLUGIN_AUTH_USER_PASS_VERIFY && context->foreground_fd >= 0)
    {
        /* get username/password from envp string array */
        const char *username = get_env("username", envp);
        const char *password = get_env("password", envp);
        const char *common_name = get_env("common_name", envp) ? get_env("common_name", envp) : "";

        /* should we do deferred auth?
         *  yes, if there is "auth_control_file" and "deferred_auth_pam" env
         */
        const char *auth_control_file = get_env("auth_control_file", envp);
        const char *deferred_auth_pam = get_env("deferred_auth_pam", envp);
        if (auth_control_file != NULL && deferred_auth_pam != NULL)
        {
            if (DEBUG(context->verb))
            {
                plugin_log(PLOG_NOTE, MODULE, "do deferred auth '%s'",
                           auth_control_file);
            }
        }
        else
        {
            auth_control_file = "";
        }

        if (username && strlen(username) > 0 && password)
        {
            if (send_control(context->foreground_fd, COMMAND_VERIFY) == -1
                || send_string(context->foreground_fd, username) == -1
                || send_string(context->foreground_fd, password) == -1
                || send_string(context->foreground_fd, common_name) == -1
                || send_string(context->foreground_fd, auth_control_file) == -1)
            {
                plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error sending auth info to background process");
            }
            else
            {
                const int status = recv_control(context->foreground_fd);
                if (status == RESPONSE_VERIFY_SUCCEEDED)
                {
                    return OPENVPN_PLUGIN_FUNC_SUCCESS;
                }
                if (status == RESPONSE_DEFER)
                {
                    if (DEBUG(context->verb))
                    {
                        plugin_log(PLOG_NOTE, MODULE, "deferred authentication");
                    }
                    return OPENVPN_PLUGIN_FUNC_DEFERRED;
                }
                if (status == -1)
                {
                    plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error receiving auth confirmation from background process");
                }
            }
        }
    }
    return OPENVPN_PLUGIN_FUNC_ERROR;
}

OPENVPN_EXPORT void
openvpn_plugin_close_v1(openvpn_plugin_handle_t handle)
{
    struct auth_pam_context *context = (struct auth_pam_context *) handle;

    if (DEBUG(context->verb))
    {
        plugin_log(PLOG_NOTE, MODULE, "close");
    }

    if (context->foreground_fd >= 0)
    {
        /* tell background process to exit */
        if (send_control(context->foreground_fd, COMMAND_EXIT) == -1)
        {
            plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error signaling background process to exit");
        }

        /* wait for background process to exit */
        if (context->background_pid > 0)
        {
            waitpid(context->background_pid, NULL, 0);
        }

        close(context->foreground_fd);
        context->foreground_fd = -1;
    }

    free(context);
}

OPENVPN_EXPORT void
openvpn_plugin_abort_v1(openvpn_plugin_handle_t handle)
{
    struct auth_pam_context *context = (struct auth_pam_context *) handle;

    /* tell background process to exit */
    if (context && context->foreground_fd >= 0)
    {
        send_control(context->foreground_fd, COMMAND_EXIT);
        close(context->foreground_fd);
        context->foreground_fd = -1;
    }
}

/*
 * PAM conversation function
 */
static int
my_conv(int n, const struct pam_message **msg_array,
        struct pam_response **response_array, void *appdata_ptr)
{
    const struct user_pass *up = ( const struct user_pass *) appdata_ptr;
    struct pam_response *aresp;
    int i;
    int ret = PAM_SUCCESS;

    *response_array = NULL;

    if (n <= 0 || n > PAM_MAX_NUM_MSG)
    {
        return (PAM_CONV_ERR);
    }
    if ((aresp = calloc(n, sizeof *aresp)) == NULL)
    {
        return (PAM_BUF_ERR);
    }

    /* loop through each PAM-module query */
    for (i = 0; i < n; ++i)
    {
        const struct pam_message *msg = msg_array[i];
        aresp[i].resp_retcode = 0;
        aresp[i].resp = NULL;

        if (DEBUG(up->verb))
        {
            plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: my_conv[%d] query='%s' style=%d",
                    i,
                    msg->msg ? msg->msg : "NULL",
                    msg->msg_style);
        }

        if (up->name_value_list && up->name_value_list->len > 0)
        {
            /* use name/value list match method */
            const struct name_value_list *list = up->name_value_list;
            int j;

            /* loop through name/value pairs */
            for (j = 0; j < list->len; ++j)
            {
                const char *match_name = list->data[j].name;
                const char *match_value = list->data[j].value;

                if (name_value_match(msg->msg, match_name))
                {
                    /* found name/value match */
                    aresp[i].resp = NULL;

                    if (DEBUG(up->verb))
                    {
                        plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: name match found, query/match-string ['%s', '%s'] = '%s'",
                                msg->msg,
                                match_name,
                                match_value);
                    }

                    if (strstr(match_value, "USERNAME"))
                    {
                        aresp[i].resp = searchandreplace(match_value, "USERNAME", up->username);
                    }
                    else if (strstr(match_value, "PASSWORD"))
                    {
                        aresp[i].resp = searchandreplace(match_value, "PASSWORD", up->password);
                    }
                    else if (strstr(match_value, "COMMONNAME"))
                    {
                        aresp[i].resp = searchandreplace(match_value, "COMMONNAME", up->common_name);
                    }
                    else if (strstr(match_value, "OTP"))
                    {
                        aresp[i].resp = searchandreplace(match_value, "OTP", up->response);
                    }
                    else
                    {
                        aresp[i].resp = strdup(match_value);
                    }

                    if (aresp[i].resp == NULL)
                    {
                        ret = PAM_CONV_ERR;
                    }
                    break;
                }
            }

            if (j == list->len)
            {
                ret = PAM_CONV_ERR;
            }
        }
        else
        {
            /* use PAM_PROMPT_ECHO_x hints */
            switch (msg->msg_style)
            {
                case PAM_PROMPT_ECHO_OFF:
                    aresp[i].resp = strdup(up->password);
                    if (aresp[i].resp == NULL)
                    {
                        ret = PAM_CONV_ERR;
                    }
                    break;

                case PAM_PROMPT_ECHO_ON:
                    aresp[i].resp = strdup(up->username);
                    if (aresp[i].resp == NULL)
                    {
                        ret = PAM_CONV_ERR;
                    }
                    break;

                case PAM_ERROR_MSG:
                case PAM_TEXT_INFO:
                    break;

                default:
                    ret = PAM_CONV_ERR;
                    break;
            }
        }
    }

    if (ret == PAM_SUCCESS)
    {
        *response_array = aresp;
    }
    else
    {
        free(aresp);
    }

    return ret;
}

/*
 * Return 1 if authenticated and 0 if failed.
 * Called once for every username/password
 * to be authenticated.
 */
static int
pam_auth(const char *service, const struct user_pass *up)
{
    struct pam_conv conv;
    pam_handle_t *pamh = NULL;
    int status = PAM_SUCCESS;
    int ret = 0;
    const int name_value_list_provided = (up->name_value_list && up->name_value_list->len > 0);

    /* Initialize PAM */
    conv.conv = my_conv;
    conv.appdata_ptr = (void *)up;
    status = pam_start(service, name_value_list_provided ? NULL : up->username, &conv, &pamh);
    if (status == PAM_SUCCESS)
    {
        /* Call PAM to verify username/password */
        status = pam_authenticate(pamh, 0);
        if (status == PAM_SUCCESS)
        {
            status = pam_acct_mgmt(pamh, 0);
        }
        if (status == PAM_SUCCESS)
        {
            ret = 1;
        }

        /* Output error message if failed */
        if (!ret)
        {
            plugin_log(PLOG_ERR, MODULE, "BACKGROUND: user '%s' failed to authenticate: %s",
                    up->username,
                    pam_strerror(pamh, status));
        }

        /* Close PAM */
        pam_end(pamh, status);
    }

    return ret;
}

/*
 * deferred auth handler
 *   - fork() (twice, to avoid the need for async wait / SIGCHLD handling)
 *   - query PAM stack via pam_auth()
 *   - send response back to OpenVPN via "ac_file_name"
 *
 * parent process returns "0" for "fork() and wait() succeeded",
 *                        "-1" for "something went wrong, abort program"
 */

static void
do_deferred_pam_auth(int fd, const char *ac_file_name,
                     const char *service, const struct user_pass *up)
{
    if (send_control(fd, RESPONSE_DEFER) == -1)
    {
        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error on response socket [4]");
        return;
    }

    /* double forking so we do not need to wait() for async auth kids */
    pid_t p1 = fork();

    if (p1 < 0)
    {
        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: fork(1) failed");
        return;
    }
    if (p1 != 0)                           /* parent */
    {
        waitpid(p1, NULL, 0);
        return;                            /* parent's job succeeded */
    }

    /* child */
    close(fd);                              /* socketpair no longer needed */

    pid_t p2 = fork();
    if (p2 < 0)
    {
        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: fork(2) failed");
        exit(1);
    }

    if (p2 != 0)                            /* new parent: exit right away */
    {
        exit(0);
    }

    /* grandchild */
    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: deferred auth for '%s', pid=%d",
               up->username, (int) getpid() );

    /* the rest is very simple: do PAM, write status byte to file, done */
    int ac_fd = open( ac_file_name, O_WRONLY );
    if (ac_fd < 0)
    {
        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "cannot open '%s' for writing",
                   ac_file_name );
        exit(1);
    }
    int pam_success = pam_auth(service, up);

    if (write( ac_fd, pam_success ? "1" : "0", 1 ) != 1)
    {
        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "cannot write to '%s'",
                   ac_file_name );
    }
    close(ac_fd);
    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: %s: deferred auth: PAM %s",
               up->username, pam_success ? "succeeded" : "rejected" );
    exit(0);
}

/*
 * Background process -- runs with privilege.
 */
static void
pam_server(int fd, const char *service, int verb, const struct name_value_list *name_value_list)
{
    struct user_pass up;
    char ac_file_name[PATH_MAX];
    int command;
#ifdef USE_PAM_DLOPEN
    static const char pam_so[] = "libpam.so";
#endif

    /*
     * Do initialization
     */
    if (DEBUG(verb))
    {
        plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: INIT service='%s'", service);
    }

#ifdef USE_PAM_DLOPEN
    /*
     * Load PAM shared object
     */
    if (!dlopen_pam(pam_so))
    {
        plugin_log(PLOG_ERR, MODULE, "BACKGROUND: could not load PAM lib %s: %s", pam_so, dlerror());
        send_control(fd, RESPONSE_INIT_FAILED);
        goto done;
    }
#endif

    /*
     * Tell foreground that we initialized successfully
     */
    if (send_control(fd, RESPONSE_INIT_SUCCEEDED) == -1)
    {
        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error on response socket [1]");
        goto done;
    }

    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: initialization succeeded");

    /*
     * Event loop
     */
    while (1)
    {
        memset(&up, 0, sizeof(up));
        up.verb = verb;
        up.name_value_list = name_value_list;

        /* get a command from foreground process */
        command = recv_control(fd);

        if (DEBUG(verb))
        {
            plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: received command code: %d", command);
        }

        switch (command)
        {
            case COMMAND_VERIFY:
                if (recv_string(fd, up.username, sizeof(up.username)) == -1
                    || recv_string(fd, up.password, sizeof(up.password)) == -1
                    || recv_string(fd, up.common_name, sizeof(up.common_name)) == -1
                    || recv_string(fd, ac_file_name, sizeof(ac_file_name)) == -1)
                {
                    plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: read error on command channel: code=%d, exiting",
                            command);
                    goto done;
                }

                if (DEBUG(verb))
                {
#if 0
                    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: USER/PASS: %s/%s",
                            up.username, up.password);
#else
                    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: USER: %s", up.username);
#endif
                }

                /* If password is of the form SCRV1:base64:base64 split it up */
                split_scrv1_password(&up);

                /* client wants deferred auth
                 */
                if (strlen(ac_file_name) > 0)
                {
                    do_deferred_pam_auth(fd, ac_file_name, service, &up);
                    break;
                }


                /* non-deferred auth: wait for pam result and send
                 * result back via control socketpair
                 */
                if (pam_auth(service, &up)) /* Succeeded */
                {
                    if (send_control(fd, RESPONSE_VERIFY_SUCCEEDED) == -1)
                    {
                        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error on response socket [2]");
                        goto done;
                    }
                }
                else /* Failed */
                {
                    if (send_control(fd, RESPONSE_VERIFY_FAILED) == -1)
                    {
                        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error on response socket [3]");
                        goto done;
                    }
                }
                plugin_secure_memzero(up.password, sizeof(up.password));
                break;

            case COMMAND_EXIT:
                goto done;

            case -1:
                plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: read error on command channel");
                goto done;

            default:
                plugin_log(PLOG_ERR, MODULE, "BACKGROUND: unknown command code: code=%d, exiting",
                        command);
                goto done;
        }
        plugin_secure_memzero(up.response, sizeof(up.response));
    }
done:
    plugin_secure_memzero(up.password, sizeof(up.password));
    plugin_secure_memzero(up.response, sizeof(up.response));
#ifdef USE_PAM_DLOPEN
    dlclose_pam();
#endif
    if (DEBUG(verb))
    {
        plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: EXIT");
    }

    return;
}