Skip to contentSkip to conversation

Add deferred authentication support to plugin-auth-pam

PATCH Superseded Gert Doering 2 participants 10 messages Jun 20, 2020 – Jul 15, 2020

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Add deferred authentication support to plugin-auth-pam

If OpenVPN signals deferred authentication support (by setting the internal environment variable "auth_control_file"), do not wait for PAM stack to finish. Instead, the privileged PAM process returns RESPONSE_DEFER via the control socket, which gets turned into OPENVPN_PLUGIN_FUNC_DEFERRED towards openvpn.

The PAM process will then fork() and handle all the PAM auth in the new process, signalling success/failure back by means of the auth_control_file (forking twice, to simplify wait() handling).

With the extra fork(), multiple deferred authentications can run at the same time - otherwise the first one would block the next auth call (because the child would not be ready again to read from the control socket).

Lightly tested on Linux.

---
 src/plugins/auth-pam/auth-pam.c | 88 ++++++++++++++++++++++++++++++++-
 1 file changed, 86 insertions(+), 2 deletions(-)
src/plugins/auth-pam/auth-pam.c +86 -2
index 9a11876d..777957fa 100644
@@ -62,6 +62,7 @@
 #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;
@@ -524,12 +525,21 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
         const char *password = get_env("password", envp);
         const char *common_name = get_env("common_name", envp) ? get_env("common_name", envp) : "";
 
+        /* get auth_control_file filename from envp string array*/
+        const char *auth_control_file = get_env("auth_control_file", envp);
+        if ( auth_control_file == NULL )
+        {
+            auth_control_file = "";
+        }
+        plugin_log(PLOG_NOTE, MODULE, "deferred auth '%s'", 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, 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");
             }
@@ -540,6 +550,11 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
                 {
                     return OPENVPN_PLUGIN_FUNC_SUCCESS;
                 }
+                if (status == RESPONSE_DEFER)
+                {
+                    plugin_log(PLOG_NOTE, MODULE, "deferred authentication active");
+                    return OPENVPN_PLUGIN_FUNC_DEFERRED;
+                }
                 if (status == -1)
                 {
                     plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error receiving auth confirmation from background process");
@@ -789,6 +804,7 @@ 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";
@@ -847,7 +863,8 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
             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, 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);
@@ -867,6 +884,73 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
                 /* If password is of the form SCRV1:base64:base64 split it up */
                 split_scrv1_password(&up);
 
+                /* client wants deferred auth
+                 * TODO: put this into its own function
+                 */
+                if ( strlen(ac_file_name) > 0 )
+                {
+                    if (send_control(fd, RESPONSE_DEFER) == -1)
+                    {
+                        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error on response socket [4]");
+                        goto done;
+                    }
+
+                    /* 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");
+                        goto done;
+                    }
+                    if ( p1 != 0 )                         /* parent */
+                    {
+                        waitpid(p1, NULL, 0);
+                        /* plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: fork(1), parent=%d, waitpid(%d) done, loop on", (int) getpid(), (int) p1 ); */
+                        break;
+                    }
+
+                    /* child */
+                    pid_t p2 = fork();
+
+                    if ( p2 < 0 )
+                    {
+                        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: fork(2) failed");
+                        goto done;
+                    }
+
+                    if ( p2 != 0 )                        /* parent-child */
+                    {
+                        /* plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: fork(2), mid=%d, exiting", (int) getpid() ); */
+                        exit(0);
+                    }
+
+                    /* grandchild */
+                    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: deferred auth handler, pid=%d", (int) getpid() );
+
+                    /* 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: deferred auth finished" );
+                    exit(0);
+                }
+
+                /* 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)
Signature · 1 line
2.26.2
#1 lore raw

Hi,

Quoted 5 lines · Gert Doering

If OpenVPN signals deferred authentication support (by setting the internal environment variable "auth_control_file"), do not wait for PAM stack to finish. Instead, the privileged PAM process returns RESPONSE_DEFER via the control socket, which gets turned into OPENVPN_PLUGIN_FUNC_DEFERRED towards openvpn.

[..]

Quoted 1 line

Lightly tested on Linux.

This is sort of a "v1" of this patch, knowing well that it needs some more polishing regarding logging etc. - but it would be good to have some feedback if I'm overlooking something crucial here.

"It seems to work, though" - as in "I've built a pam stack with pam_auth_radius talking to a non-existing radius server, which will always add 15 seconds of delay - and with this patch, two clients can authenticate concurrently, TLS handshakes do work while a client is authenticating, and pings for client A do not stop while client B is connecting". And, no zombie processes.

I have not tested this in anger, like "100 clients connecting at the same time" or "let it run for two weeks with 1000 clients connecting and disconnecting all the time".

It goes on top of the patch that adds plugin_log() logging to auth-pam.c

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#2 lore raw
In reply to Gert Doering

Hi,

Quoted 7 lines · Gert Doering

If OpenVPN signals deferred authentication support (by setting the internal environment variable "auth_control_file"), do not wait for PAM stack to finish. Instead, the privileged PAM process returns RESPONSE_DEFER via the control socket, which gets turned into OPENVPN_PLUGIN_FUNC_DEFERRED towards openvpn.

Quoted 8 lines

The PAM process will then fork() and handle all the PAM auth in the new process, signalling success/failure back by means of the auth_control_file (forking twice, to simplify wait() handling).

With the extra fork(), multiple deferred authentications can run at the same time - otherwise the first one would block the next auth call (because the child would not be ready again to read from the control socket).

I have no doubt this will work, but can we avoid the double fork? Instead, we could set a handler for SIGCHLD and reap all child pids there using a non blocking waitpid(-1, NULL, WNOHANG). Will have to also check for EINTR and retry in recv_control() and possibly recv_string().

Fork is probably not expensive, but two of them per auth event look excessive and not very elegant, somehow.

Quoted 74 lines

Lightly tested on Linux.

---
 src/plugins/auth-pam/auth-pam.c | 88 ++++++++++++++++++++++++++++++++-
 1 file changed, 86 insertions(+), 2 deletions(-)
src/plugins/auth-pam/auth-pam.c +19 -2
index 9a11876d..777957fa 100644
@@ -62,6 +62,7 @@
 #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;
@@ -524,12 +525,21 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
         const char *password = get_env("password", envp);
         const char *common_name = get_env("common_name", envp) ? get_env("common_name", envp) : "";
 
+        /* get auth_control_file filename from envp string array*/
+        const char *auth_control_file = get_env("auth_control_file", envp);
+        if ( auth_control_file == NULL )
+        {
+            auth_control_file = "";
+        }
+        plugin_log(PLOG_NOTE, MODULE, "deferred auth '%s'", 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, 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");
             }
@@ -540,6 +550,11 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
                 {
                     return OPENVPN_PLUGIN_FUNC_SUCCESS;
                 }
+                if (status == RESPONSE_DEFER)
+                {
+                    plugin_log(PLOG_NOTE, MODULE, "deferred authentication active");
+                    return OPENVPN_PLUGIN_FUNC_DEFERRED;
+                }
                 if (status == -1)
                 {
                     plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "Error receiving auth confirmation from background process");
@@ -789,6 +804,7 @@ 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";
@@ -847,7 +863,8 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
             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, 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);

src/plugins/auth-pam/auth-pam.c pam_server(int fd, const char *service, int verb, const struct name_value_list * · line 889

Quoted 6 lines
src/plugins/auth-pam/auth-pam.c +3 -0
@@ -867,6 +884,73 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
                 /* If password is of the form SCRV1:base64:base64 split it up */
                 split_scrv1_password(&up);
 
+                /* client wants deferred auth
+                 * TODO: put this into its own function
+                 */

TODOs seldom get attended to, it's now or never :)

Quoted 32 lines
src/plugins/auth-pam/auth-pam.c +32 -0
+                if ( strlen(ac_file_name) > 0 )
+                {
+                    if (send_control(fd, RESPONSE_DEFER) == -1)
+                    {
+                        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: write error on response socket [4]");
+                        goto done;
+                    }
+
+                    /* 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");
+                        goto done;
+                    }
+                    if ( p1 != 0 )                         /* parent */
+                    {
+                        waitpid(p1, NULL, 0);
+                        /* plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: fork(1), parent=%d, waitpid(%d) done, loop on", (int) getpid(), (int) p1 ); */
+                        break;
+                    }
+
+                    /* child */
+                    pid_t p2 = fork();
+
+                    if ( p2 < 0 )
+                    {
+                        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: fork(2) failed");
+                        goto done;

src/plugins/auth-pam/auth-pam.c pam_server(int fd, const char *service, int verb, const struct name_value_list * · line 931

Quoted 10 lines
src/plugins/auth-pam/auth-pam.c +10 -0
+                    }
+
+                    if ( p2 != 0 )                        /* parent-child */
+                    {
+                        /* plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: fork(2), mid=%d, exiting", (int) getpid() ); */
+                        exit(0);
+                    }
+
+                    /* grandchild */
+                    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: deferred auth handler, pid=%d", (int) getpid() );

I think the scoket in the parent could be closed here. The child doesn't need it.

Quoted 26 lines
src/plugins/auth-pam/auth-pam.c +22 -1
+
+                    /* 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: deferred auth finished" );
+                    exit(0);
+                }
+
+                /* 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)
--
Quoted 1 line

2.26.2

Looks good otherwise.

As auth_control_file is always generated by the core built with PLUGIN_DEF_AUTH, the patch appears to make deferred auth the default with this plugin. So PLUGIN_DEF_AUTH takes a new meaning now.

Not a fault of this patch, but I noticed that the auth_control_file is removed only during the next auth cycle for the same client, or while restarting the client, not promptly after an auth success or failure.

Selva

#3 lore raw

Good morning,

and thanks for the quick review :-)

Quoted 16 lines · Selva Nair
Quoted 6 lines · Gert Doering

If OpenVPN signals deferred authentication support (by setting the internal environment variable "auth_control_file"), do not wait for PAM stack to finish. Instead, the privileged PAM process returns RESPONSE_DEFER via the control socket, which gets turned into OPENVPN_PLUGIN_FUNC_DEFERRED towards openvpn.

Quoted 8 lines

The PAM process will then fork() and handle all the PAM auth in the new process, signalling success/failure back by means of the auth_control_file (forking twice, to simplify wait() handling).

With the extra fork(), multiple deferred authentications can run at the same time - otherwise the first one would block the next auth call (because the child would not be ready again to read from the control socket).

Quoted 7 lines

I have no doubt this will work, but can we avoid the double fork? Instead, we could set a handler for SIGCHLD and reap all child pids there using a non blocking waitpid(-1, NULL, WNOHANG). Will have to also check for EINTR and retry in recv_control() and possibly recv_string().

Fork is probably not expensive, but two of them per auth event look excessive and not very elegant, somehow.

I have started with signal handlers, and then decided that this will lead to more complications (EINTR) and possibly someone in the PAM stack will also might fork(), so we need to reset signal handlers in the child, and then I found it all much more complicated than I liked...

fork() isn't as costly anymore as it used to be "in old unix legends" :-) (it does have a cost, for setting up new memory mappings for COW, which can get large if the memory footprint is large) - and I find the code much simpler and much more straightforward, as in "everything related to deferred auth happens *here*"...

[..]

Quoted 7 lines

src/plugins/auth-pam/auth-pam.c pam_server(int fd, const char *service, int verb, const struct name_value_list * · line 889

Quoted 5 lines
                 split_scrv1_password(&up);
src/plugins/auth-pam/auth-pam.c +3 -0
+                /* client wants deferred auth
+                 * TODO: put this into its own function
+                 */

TODOs seldom get attended to, it's now or never :)

Right. v2 is coming :-) - I wanted some quick initial feedback on whether something here is a truly bad idea or if I had overlooked something crucial.

(In the meantime, the code has gotten some more excercise - I've let a client connect in a loop, with "connect", "die with --inactive 30", "be restarted from script", while another client was connected all the time and pinging the server - and no zombies and no ping loss so far, over ~30 hours)

[..]

Quoted 10 lines

src/plugins/auth-pam/auth-pam.c pam_server(int fd, const char *service, int verb, const struct name_value_list * · line 931

Quoted 7 lines
src/plugins/auth-pam/auth-pam.c +7 -0
+                    {
+                        /* plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: fork(2), mid=%d, exiting", (int) getpid() ); */
+                        exit(0);
+                    }
+
+                    /* grandchild */
+                    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: deferred auth handler, pid=%d", (int) getpid() );

I think the scoket in the parent could be closed here. The child doesn't need it.

I had this initially, and then the socket got messed up - but that might have been some other bug in the early code. I'll re-add and re-test.

[..]

Quoted 3 lines

As auth_control_file is always generated by the core built with PLUGIN_DEF_AUTH, the patch appears to make deferred auth the default with this plugin. So PLUGIN_DEF_AUTH takes a new meaning now.

Yes. I plan on adding a new (internal) environment variable to control this, like

setenv deferred-auth-pam 1

or the like. So the default would be "synchronous, as it is now", and you get deferred if "auth_control_file *and* deferred-auth-pam are set" (or we could do it the other way round, "no-deferred-auth-pam"?).

Quoted 3 lines

Not a fault of this patch, but I noticed that the auth_control_file is removed only during the next auth cycle for the same client, or while restarting the client, not promptly after an auth success or failure.

Indeed

gentoo ~/t_server/tun-udp-p2mp-global-authpam # ls -l /tmp/*acf*
-rw------- 1 root root 0 Jun 22 08:14 /tmp/openvpn_acf_6d4bb9bdca44e95168015833e2ff3273.tmp -rw------- 1 root root 1 Jun 22 08:13 /tmp/openvpn_acf_7055788f18a55f221abf8f9b10751dde.tmp gentoo ~/t_server/tun-udp-p2mp-global-authpam # ls -l /tmp/*acf*
-rw------- 1 root root 1 Jun 22 08:14 /tmp/openvpn_acf_6d4bb9bdca44e95168015833e2ff3273.tmp

(that's the client-in-a-loop)

Not related to this patch, but it might be worth a look on whether this can be easily fixed.

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#4 lore raw

PATCH v2 1/1 Add deferred authentication support to plugin-auth-pam

In reply to Gert Doering

If OpenVPN signals deferred authentication support (by setting the internal environment variables "auth_control_file" and "deferred_auth_pam"), do not wait for PAM stack to finish. Instead, the privileged PAM process returns RESPONSE_DEFER via the control socket, which gets turned into OPENVPN_PLUGIN_FUNC_DEFERRED towards openvpn.

The PAM process will then fork() and handle all the PAM auth in the new process, signalling success/failure back by means of the auth_control_file (forking twice, to simplify wait() handling).

With the extra fork(), multiple deferred authentications can run at the same time - otherwise the first one would block the next auth call (because the child would not be ready again to read from the control socket).

Lightly tested on Linux.

--
v2:
- only do deferred auth if "deferred_auth_pam" is set (env)
- put deferred auth logic into do_deferred_pam_auth()
- line-wrap lines where needed
- close "background end" of socketpair in deferred auth process
- remove leftover /* plugin_log() */ lines from initial testing
- tested over a few hundred "15s delayed" authentication cycles

---
 src/plugins/auth-pam/auth-pam.c | 124 +++++++++++++++++++++++++++++++-
 1 file changed, 122 insertions(+), 2 deletions(-)
src/plugins/auth-pam/auth-pam.c +122 -2
index 9a11876d..2a75e5f0 100644
@@ -62,6 +62,7 @@
 #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;
@@ -524,12 +525,31 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
         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, 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");
             }
@@ -540,6 +560,14 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
                 {
                     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");
@@ -782,6 +810,80 @@ pam_auth(const char *service, const struct user_pass *up)
     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 int
+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 -1;
+    }
+
+    /* 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 -1;
+    }
+    if ( p1 != 0 )                         /* parent */
+    {
+        waitpid(p1, NULL, 0);
+        return 0;                          /* 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.
  */
@@ -789,6 +891,7 @@ 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";
@@ -847,7 +950,8 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
             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, 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);
@@ -867,6 +971,22 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
                 /* 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 )
+                {
+                    if (do_deferred_pam_auth(fd, ac_file_name,
+                                             service, &up) < 0)
+                    {
+                        goto done;
+                    }
+                    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)
Signature · 1 line
2.26.2
Acked-by on v2 1/1
#5 lore raw

Hi,

Sorry for the long delay in getting back to this.. A few minor nitpicks on style follows:

Quoted 46 lines · Gert Doering

If OpenVPN signals deferred authentication support (by setting the internal environment variables "auth_control_file" and "deferred_auth_pam"), do not wait for PAM stack to finish. Instead, the privileged PAM process returns RESPONSE_DEFER via the control socket, which gets turned into OPENVPN_PLUGIN_FUNC_DEFERRED towards openvpn.

The PAM process will then fork() and handle all the PAM auth in the new process, signalling success/failure back by means of the auth_control_file (forking twice, to simplify wait() handling).

With the extra fork(), multiple deferred authentications can run at the same time - otherwise the first one would block the next auth call (because the child would not be ready again to read from the control socket).

Lightly tested on Linux.

--
v2:
- only do deferred auth if "deferred_auth_pam" is set (env)
- put deferred auth logic into do_deferred_pam_auth()
- line-wrap lines where needed
- close "background end" of socketpair in deferred auth process
- remove leftover /* plugin_log() */ lines from initial testing
- tested over a few hundred "15s delayed" authentication cycles

---
 src/plugins/auth-pam/auth-pam.c | 124 +++++++++++++++++++++++++++++++-
 1 file changed, 122 insertions(+), 2 deletions(-)
src/plugins/auth-pam/auth-pam.c +1 -0
index 9a11876d..2a75e5f0 100644
@@ -62,6 +62,7 @@
 #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;

src/plugins/auth-pam/auth-pam.c openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha · line 533

Quoted 9 lines
src/plugins/auth-pam/auth-pam.c +6 -0
@@ -524,12 +525,31 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
         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)

We don't add spaces around parentheses, do we? A few such cases below..

Quoted 61 lines
src/plugins/auth-pam/auth-pam.c +41 -1
+        {
+            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, 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");
             }
@@ -540,6 +560,14 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
                 {
                     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");
@@ -782,6 +810,80 @@ pam_auth(const char *service, const struct user_pass *up)
     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 int
+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 -1;
+    }

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 841

Quoted 10 lines
src/plugins/auth-pam/auth-pam.c +10 -0
+
+    /* 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 -1;
+    }
+    if ( p1 != 0 )                         /* parent */

Same here..

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 851

Quoted 10 lines
src/plugins/auth-pam/auth-pam.c +10 -0
+    {
+        waitpid(p1, NULL, 0);
+        return 0;                          /* parent's job succeeded */
+    }
+
+    /* child */
+    close(fd);                              /* socketpair no longer needed */
+
+    pid_t p2 = fork();
+    if ( p2 < 0 )

and here

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 857

Quoted 6 lines
src/plugins/auth-pam/auth-pam.c +6 -0
+    {
+        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "BACKGROUND: fork(2) failed");
+        exit(1);
+    }
+
+    if ( p2 != 0 )                          /* new parent: exit right away */

ditto..

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 864

Quoted 7 lines
src/plugins/auth-pam/auth-pam.c +7 -0
+    {
+        exit(0);
+    }
+
+    /* grandchild */
+    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: deferred auth for '%s', pid=%d",
+               up->username, (int) getpid() );

extra space before the closing )

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 867

Quoted 3 lines
src/plugins/auth-pam/auth-pam.c +3 -0
+
+    /* the rest is very simple: do PAM, write status byte to file, done */
+    int ac_fd = open( ac_file_name, O_WRONLY );

and around here

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 868

Quoted 1 line
src/plugins/auth-pam/auth-pam.c +1 -0
+    if ( ac_fd < 0 )

and here

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 871

Quoted 3 lines
src/plugins/auth-pam/auth-pam.c +3 -0
+    {
+        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "cannot open '%s' for writing",
+                   ac_file_name );

Space before the closing )

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 876

Quoted 5 lines
src/plugins/auth-pam/auth-pam.c +5 -0
+        exit(1);
+    }
+    int pam_success = pam_auth(service, up);
+
+    if ( write( ac_fd, pam_success? "1": "0", 1 ) != 1 )

and here

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 879

Quoted 3 lines
src/plugins/auth-pam/auth-pam.c +3 -0
+    {
+        plugin_log(PLOG_ERR|PLOG_ERRNO, MODULE, "cannot write to '%s'",
+                   ac_file_name );

and before the last )

src/plugins/auth-pam/auth-pam.c pam_auth(const char *service, const struct user_pass *up) · line 883

Quoted 4 lines
src/plugins/auth-pam/auth-pam.c +4 -0
+    }
+    close(ac_fd);
+    plugin_log(PLOG_NOTE, MODULE, "BACKGROUND: %s: deferred auth: PAM %s",
+               up->username, pam_success? "succeeded": "rejected" );

Same here before the closing ")"

Quoted 26 lines
src/plugins/auth-pam/auth-pam.c +6 -1
+    exit(0);
+}
+
 /*
  * Background process -- runs with privilege.
  */
@@ -789,6 +891,7 @@ 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";
@@ -847,7 +950,8 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
             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, 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);
@@ -867,6 +971,22 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
                 /* If password is of the form SCRV1:base64:base64 split it up */

src/plugins/auth-pam/auth-pam.c pam_server(int fd, const char *service, int verb, const struct name_value_list * · line 981

Quoted 10 lines
src/plugins/auth-pam/auth-pam.c +8 -0
                 split_scrv1_password(&up);
 
+                /* client wants deferred auth
+                 */
+                if ( strlen(ac_file_name) > 0 )
+                {
+                    if (do_deferred_pam_auth(fd, ac_file_name,
+                                             service, &up) < 0)
+                    {
+                        goto done;

Do we have to abort in this case? This will exit the background process and cripple the server while this could be a temporary memory pressure causing the fork to fail. Why not just break and plough along? The core will fail to get a response via the ac_file, but that could happen if the grand-child fails as well -- the server is supposed to cope with such failures.

src/plugins/auth-pam/auth-pam.c pam_server(int fd, const char *service, int verb, const struct name_value_list *

Quoted 12 lines
src/plugins/auth-pam/auth-pam.c +8 -1
+                    }
+                    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)
--

Apart from these minor issues that could be corrected or ignored at merge time, all look good.

We should put the usage info into README.auth-pam as that seems to be the only documentation of the plugin. Also an entry in changelog? Could be a separate patch.

#6 lore raw

Hi,

Quoted 2 lines · Selva Nair

Sorry for the long delay in getting back to this.. A few minor nitpicks on style follows:

Thanks for the review. Indeed, my style fu was sort of absent when I wrote this :-) (it's "mgetty+sendfax" style, with "I must remember to use vim and :set expandtab!!!", but the braces always escape me... and Antonio was busy elsewhere :) )

This...:

Quoted 10 lines · Gert Doering

src/plugins/auth-pam/auth-pam.c pam_server(int fd, const char *service, int verb, const struct name_value_list * · line 981

Quoted 8 lines
src/plugins/auth-pam/auth-pam.c +8 -0
+                /* client wants deferred auth
+                 */
+                if ( strlen(ac_file_name) > 0 )
+                {
+                    if (do_deferred_pam_auth(fd, ac_file_name,
+                                             service, &up) < 0)
+                    {
+                        goto done;
Quoted 6 lines

Do we have to abort in this case? This will exit the background process and cripple the server while this could be a temporary memory pressure causing the fork to fail. Why not just break and plough along? The core will fail to get a response via the ac_file, but that could happen if the grand-child fails as well -- the server is supposed to cope with such failures.

... is something I need to look more closely at. I remember that the general approach to "mmmh, something failed!" here is "goto done", but your argument about "yeah, fork() failed, so what - try again later!" has merits.

Quoted 2 lines

Apart from these minor issues that could be corrected or ignored at merge time, all look good.

This is actually a code change, so I think I'll send a v3 with all the nitpicks fixed (uncrustify is my friend :-) ) and this one changed.

Quoted 3 lines

We should put the usage info into README.auth-pam as that seems to be the only documentation of the plugin. Also an entry in changelog? Could be a separate patch.

When I do a v3 anyway, I can add this as well. Makes sense to have it one commit.

gert

Signature · 6 lines
"If was one thing all people took for granted, was conviction that if you 
 feed honest figures into a computer, honest figures come out. Never doubted 
 it myself till I met a computer with a sense of humor."
                             Robert A. Heinlein, The Moon is a Harsh Mistress

Gert Doering - Munich, Germany                             [email protected]...
#7 lore raw

PATCH v3 1/1 Add deferred authentication support to plugin-auth-pam

In reply to Gert Doering

If OpenVPN signals deferred authentication support (by setting the internal environment variables "auth_control_file" and "deferred_auth_pam"), do not wait for PAM stack to finish. Instead, the privileged PAM process returns RESPONSE_DEFER via the control socket, which gets turned into OPENVPN_PLUGIN_FUNC_DEFERRED towards openvpn.

The PAM process will then fork() and handle all the PAM auth in the new process, signalling success/failure back by means of the auth_control_file (forking twice, to simplify wait() handling).

With the extra fork(), multiple deferred authentications can run at the same time - otherwise the first one would block the next auth call (because the child would not be ready again to read from the control socket).

Lightly tested on Linux.

--
v2:
- only do deferred auth if "deferred_auth_pam" is set (env)
- put deferred auth logic into do_deferred_pam_auth()
- line-wrap lines where needed
- close "background end" of socketpair in deferred auth process
- remove leftover /* plugin_log() */ lines from initial testing
- tested over a few hundred "15s delayed" authentication cycles

v3:
- uncrustify new code
- do not abort background process if do_deferred_pam_auth() fails (this can only happen if fork() fails, which is assumed to be temporary, or if something is wrong with the socketpair which we should notice on the next read()) --> change do_deferred_pam_auth() to "void"
- add documentation to README.auth-pam and Changes.rst

---
 Changes.rst                          |   3 +
 src/plugins/auth-pam/README.auth-pam |  35 ++++++++
 src/plugins/auth-pam/auth-pam.c      | 122 ++++++++++++++++++++++++++-
 3 files changed, 157 insertions(+), 3 deletions(-)
Changes.rst +3 -0
index 00dd6ed8..8d9d74c1 100644
@@ -13,6 +13,9 @@ ChaCha20-Poly1305 cipher support
     Added support for using the ChaCha20-Poly1305 cipher in the OpenVPN data
     channel.
 
+Asynchronous (deferred) authentication support for auth-pam plugin.
+    See src/plugins/auth-pam/README.auth-pam for details.
+
 
 Overview of changes in 2.4
 ==========================
src/plugins/auth-pam/README.auth-pam +35 -0
index 4d3d4ecc..e604d5a8 100644
@@ -73,6 +73,41 @@ underlying PAM module.  This is a useful debugging tool to figure
 out which queries a given PAM module is making, so that you can
 craft the appropriate plugin directive to answer it.
 
+Since running OpenVPN with verb 7 is quite verbose, alternatively
+you can put
+
+   verb 3
+   setenv verb 9
+
+in the openvpn config which will only increase logging for this plugin.
+
+
+ASYNCHRONOUS OPERATION
+
+Sometimes PAM modules take very long to complete (for example, a LDAP
+or Radius query might timeout trying to connect an unreachable external
+server).  Normal plugin auth operation will block the whole OpenVPN
+process in this time, that is, all forwarding for all other client stops.
+
+The auth-pam plugin can operate asynchronously ("deferred authentication")
+to remedy this situation.  To enable this, put
+
+  setenv deferred_auth_pam 1
+
+in your openvpn server config.  If set, this will make the "PAM background
+process" fork() and do its job detached from OpenVPN.  When finished, a
+status file is written, which OpenVPN will then pick up and read the
+success/failure result from it.
+
+While the plugin is working in the background, OpenVPN will continue to
+service other clients normally.
+
+Asynchronous operation is recommended for all PAM queries that could
+"take time" (LDAP, Radius, NIS, ...).  If only local files are queried
+(passwd, pam_userdb, ...), synchronous operation has slightly lower
+overhead, so this is still the default mode of operation.
+
+
 CAVEATS
 
 This module will only work on *nix systems which support PAM,
src/plugins/auth-pam/auth-pam.c +119 -3

175 lines not on this page · raw message

Signature · 1 line
2.26.2
Acked-by on v3 1/1
#8 lore raw

Hi,

Thanks for v3. All good except Changes.rst has diverged, so the patch doesn't apply as is. Can be fixed at merge time.

The code is unchanged from the last version and the added text in README is clear and detailed. A minor grammar thingy:

"all forwarding for all other client" -- > "all forwarding for all other clients"

Quoted 300 lines · Gert Doering

If OpenVPN signals deferred authentication support (by setting the internal environment variables "auth_control_file" and "deferred_auth_pam"), do not wait for PAM stack to finish. Instead, the privileged PAM process returns RESPONSE_DEFER via the control socket, which gets turned into OPENVPN_PLUGIN_FUNC_DEFERRED towards openvpn.

The PAM process will then fork() and handle all the PAM auth in the new process, signalling success/failure back by means of the auth_control_file (forking twice, to simplify wait() handling).

With the extra fork(), multiple deferred authentications can run at the same time - otherwise the first one would block the next auth call (because the child would not be ready again to read from the control socket).

Lightly tested on Linux.

--
v2:
- only do deferred auth if "deferred_auth_pam" is set (env)
- put deferred auth logic into do_deferred_pam_auth()
- line-wrap lines where needed
- close "background end" of socketpair in deferred auth process
- remove leftover /* plugin_log() */ lines from initial testing
- tested over a few hundred "15s delayed" authentication cycles

v3:
- uncrustify new code
- do not abort background process if do_deferred_pam_auth() fails (this can only happen if fork() fails, which is assumed to be temporary, or if something is wrong with the socketpair which we should notice on the next read()) --> change do_deferred_pam_auth() to "void"
- add documentation to README.auth-pam and Changes.rst

---
 Changes.rst                          |   3 +
 src/plugins/auth-pam/README.auth-pam |  35 ++++++++
 src/plugins/auth-pam/auth-pam.c      | 122 ++++++++++++++++++++++++++-
 3 files changed, 157 insertions(+), 3 deletions(-)
Changes.rst +3 -0
index 00dd6ed8..8d9d74c1 100644
@@ -13,6 +13,9 @@ ChaCha20-Poly1305 cipher support
     Added support for using the ChaCha20-Poly1305 cipher in the OpenVPN data
     channel.
 
+Asynchronous (deferred) authentication support for auth-pam plugin.
+    See src/plugins/auth-pam/README.auth-pam for details.
+
 
 Overview of changes in 2.4
 ==========================
src/plugins/auth-pam/README.auth-pam +35 -0
index 4d3d4ecc..e604d5a8 100644
@@ -73,6 +73,41 @@ underlying PAM module.  This is a useful debugging tool to figure
 out which queries a given PAM module is making, so that you can
 craft the appropriate plugin directive to answer it.
 
+Since running OpenVPN with verb 7 is quite verbose, alternatively
+you can put
+
+   verb 3
+   setenv verb 9
+
+in the openvpn config which will only increase logging for this plugin.
+
+
+ASYNCHRONOUS OPERATION
+
+Sometimes PAM modules take very long to complete (for example, a LDAP
+or Radius query might timeout trying to connect an unreachable external
+server).  Normal plugin auth operation will block the whole OpenVPN
+process in this time, that is, all forwarding for all other client stops.
+
+The auth-pam plugin can operate asynchronously ("deferred authentication")
+to remedy this situation.  To enable this, put
+
+  setenv deferred_auth_pam 1
+
+in your openvpn server config.  If set, this will make the "PAM background
+process" fork() and do its job detached from OpenVPN.  When finished, a
+status file is written, which OpenVPN will then pick up and read the
+success/failure result from it.
+
+While the plugin is working in the background, OpenVPN will continue to
+service other clients normally.
+
+Asynchronous operation is recommended for all PAM queries that could
+"take time" (LDAP, Radius, NIS, ...).  If only local files are queried
+(passwd, pam_userdb, ...), synchronous operation has slightly lower
+overhead, so this is still the default mode of operation.
+
+
 CAVEATS
 
 This module will only work on *nix systems which support PAM,
src/plugins/auth-pam/auth-pam.c +119 -4
index 9a11876d..f537652e 100644
@@ -62,6 +62,7 @@
 #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;
@@ -69,7 +70,7 @@ 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";
+static char *MODULE = "AUTH-PAM";
 
 /*
  * Plugin state, used by foreground
@@ -524,12 +525,31 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
         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, 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");
             }
@@ -540,6 +560,14 @@ openvpn_plugin_func_v1(openvpn_plugin_handle_t handle, const int type, const cha
                 {
                     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");
@@ -782,6 +810,80 @@ pam_auth(const char *service, const struct user_pass *up)
     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.
  */
@@ -789,6 +891,7 @@ 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";
@@ -847,7 +950,8 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
             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, 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);
@@ -867,6 +971,18 @@ pam_server(int fd, const char *service, int verb, const struct name_value_list *
                 /* 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)
--

2.26.2

_______________________________________________
Openvpn-devel mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/openvpn-devel

#9 lore raw
In reply to Gert Doering

Patch has been applied to the master branch.

(Changes.rst hunk and "all other clients" adjusted appropriately)

commit c83b197a72a6f909a4ddcded027469f0da5d4a24

Author: Gert Doering
Date:   Wed Jul 15 11:01:05 2020 +0200
     Add deferred authentication support to plugin-auth-pam

     Signed-off-by: Gert Doering <[email protected]...>
     Acked-by: Selva Nair <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg20361.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering