Blame SOURCES/Add-option-to-control-timeout-for-Basic-Auth.patch

22acb1
From b4ddd657ccc7793df9378209433f0142195a94d1 Mon Sep 17 00:00:00 2001
22acb1
From: Simo Sorce <simo@redhat.com>
22acb1
Date: Thu, 14 May 2020 09:19:37 -0400
22acb1
Subject: [PATCH] Add option to control timeout for Basic Auth
22acb1
22acb1
Adds new option and tests.
22acb1
Adds optional dependency on libfaketime to test this feature.
22acb1
22acb1
Fixes: #210
22acb1
Signed-off-by: Simo Sorce <simo@redhat.com>
22acb1
Merges: #217
22acb1
Reviewed-by: Robbie Harwood <rharwood@redhat.com>
22acb1
(cherry picked from commit 09df7584b4abadbfea411adafdcc825da5b720d3)
22acb1
[rharwood@redhat.com: git got confused by not having localname test]
22acb1
---
22acb1
 README                   | 24 +++++++++++++
22acb1
 src/mod_auth_gssapi.c    | 27 +++++++++++---
22acb1
 src/mod_auth_gssapi.h    |  1 +
22acb1
 tests/Makefile.am        |  1 +
22acb1
 tests/httpd.conf         | 32 ++++++++++++++++-
22acb1
 tests/magtests.py        | 76 ++++++++++++++++++++++++++++++++++++++++
22acb1
 tests/t_basic_timeout.py | 34 ++++++++++++++++++
22acb1
 7 files changed, 190 insertions(+), 5 deletions(-)
22acb1
 create mode 100755 tests/t_basic_timeout.py
22acb1
22acb1
diff --git a/README b/README
22acb1
index 700b57e..5eac94f 100644
22acb1
--- a/README
22acb1
+++ b/README
22acb1
@@ -97,6 +97,7 @@ Configuration Directives
22acb1
 [GssapiAllowedMech](#gssapiallowedmech)
22acb1
 [GssapiBasicAuth](#gssapibasicauth)
22acb1
 [GssapiBasicAuthMech](#gssapibasicauthmech)
22acb1
+[GssapiBasicTicketTimeout](#gssapibasicticketvalidity)
22acb1
 [GssapiConnectionBound](#gssapiconnectionbound)
22acb1
 [GssapiCredStore](#gssapicredstore)
22acb1
 [GssapiDelegCcacheDir](#gssapidelegccachedir)
22acb1
@@ -503,3 +504,26 @@ Note: The GSS_C_NT_HOSTBASED_SERVICE format is used for names (see example).
22acb1
     GssapiAcceptorName HTTP@www.example.com
22acb1
 
22acb1
 
22acb1
+### GssapiBasicTicketTimeout
22acb1
+
22acb1
+This option controls the ticket validity time requested for the user TGT by the
22acb1
+Basic Auth method.
22acb1
+
22acb1
+Normally basic auth is repeated by the browser on each request so a short
22acb1
+validity period is used to reduce the scope of the ticket as it will be
22acb1
+replaced quickly.
22acb1
+However in cases where the authentication page is separate and the session
22acb1
+is used by other pages the validity can be changed to arbitrary duration.
22acb1
+
22acb1
+Note: the validity of a ticket is still capped by KDC configuration.
22acb1
+
22acb1
+Note: the value is specified in seconds.
22acb1
+
22acb1
+- **Default:** GssapiBasicTicketTimeout 300
22acb1
+
22acb1
+#### Example
22acb1
+    GssapiBasicTicketTimeout 36000
22acb1
+
22acb1
+Sets ticket/session validity to 10 hours.
22acb1
+
22acb1
+
22acb1
diff --git a/src/mod_auth_gssapi.c b/src/mod_auth_gssapi.c
22acb1
index 9e42ef4..b099973 100644
22acb1
--- a/src/mod_auth_gssapi.c
22acb1
+++ b/src/mod_auth_gssapi.c
22acb1
@@ -1,4 +1,5 @@
22acb1
-/* Copyright (C) 2014, 2016 mod_auth_gssapi contributors - See COPYING for (C) terms */
22acb1
+/* Copyright (C) 2014, 2016, 2020 mod_auth_gssapi contributors
22acb1
+ * See COPYING for (C) terms */
22acb1
 
22acb1
 #include "mod_auth_gssapi.h"
22acb1
 #include "mag_parse.h"
22acb1
@@ -600,7 +601,7 @@ static int mag_auth_basic(struct mag_req_cfg *req_cfg, struct mag_conn *mc,
22acb1
     }
22acb1
 
22acb1
     maj = gss_acquire_cred_with_password(&min, user, &ba_pwd,
22acb1
-                                         GSS_C_INDEFINITE,
22acb1
+                                         cfg->basic_timeout,
22acb1
                                          allowed_mechs,
22acb1
                                          GSS_C_INITIATE,
22acb1
                                          &user_cred, &actual_mechs, NULL);
22acb1
@@ -619,8 +620,8 @@ static int mag_auth_basic(struct mag_req_cfg *req_cfg, struct mag_conn *mc,
22acb1
 
22acb1
     for (int i = 0; i < actual_mechs->count; i++) {
22acb1
         maj = mag_context_loop(&min, req, cfg, user_cred, server_cred,
22acb1
-                               &actual_mechs->elements[i], 300, &client,
22acb1
-                               &vtime, &delegated_cred);
22acb1
+                               &actual_mechs->elements[i], cfg->basic_timeout,
22acb1
+                               &client, &vtime, &delegated_cred);
22acb1
         if (maj == GSS_S_COMPLETE) {
22acb1
             ret = mag_complete(req_cfg, mc, client, &actual_mechs->elements[i],
22acb1
                                vtime, delegated_cred);
22acb1
@@ -1299,6 +1300,7 @@ static void *mag_create_dir_config(apr_pool_t *p, char *dir)
22acb1
 #ifdef HAVE_CRED_STORE
22acb1
     cfg->ccname_envvar = "KRB5CCNAME";
22acb1
 #endif
22acb1
+    cfg->basic_timeout = 300;
22acb1
 
22acb1
     return cfg;
22acb1
 }
22acb1
@@ -1789,6 +1791,21 @@ static const char *mag_acceptor_name(cmd_parms *parms, void *mconfig,
22acb1
     return NULL;
22acb1
 }
22acb1
 
22acb1
+static const char *mag_basic_timeout(cmd_parms *parms, void *mconfig,
22acb1
+                                     const char *w)
22acb1
+{
22acb1
+    struct mag_config *cfg = (struct mag_config *)mconfig;
22acb1
+    unsigned long int value;
22acb1
+
22acb1
+    value = strtoul(w, NULL, 10);
22acb1
+    if (value >= UINT32_MAX) {
22acb1
+        cfg->basic_timeout = GSS_C_INDEFINITE;
22acb1
+        return NULL;
22acb1
+    }
22acb1
+    cfg->basic_timeout = value;
22acb1
+    return NULL;
22acb1
+}
22acb1
+
22acb1
 static void *mag_create_server_config(apr_pool_t *p, server_rec *s)
22acb1
 {
22acb1
     struct mag_server_config *scfg;
22acb1
@@ -1865,6 +1882,8 @@ static const command_rec mag_commands[] = {
22acb1
                  "Publish GSSAPI Errors in Envionment Variables"),
22acb1
     AP_INIT_RAW_ARGS("GssapiAcceptorName", mag_acceptor_name, NULL, OR_AUTHCFG,
22acb1
                      "Name of the acceptor credentials."),
22acb1
+    AP_INIT_TAKE1("GssapiBasicTicketTimeout", mag_basic_timeout, NULL,
22acb1
+                  OR_AUTHCFG, "Ticket Validity Timeout with Basic Auth."),
22acb1
     { NULL }
22acb1
 };
22acb1
 
22acb1
diff --git a/src/mod_auth_gssapi.h b/src/mod_auth_gssapi.h
22acb1
index 8c0b972..2312ab5 100644
22acb1
--- a/src/mod_auth_gssapi.h
22acb1
+++ b/src/mod_auth_gssapi.h
22acb1
@@ -93,6 +93,7 @@ struct mag_config {
22acb1
     int enverrs;
22acb1
     gss_name_t acceptor_name;
22acb1
     bool acceptor_name_from_req;
22acb1
+    uint32_t basic_timeout;
22acb1
 };
22acb1
 
22acb1
 struct mag_server_config {
22acb1
diff --git a/tests/Makefile.am b/tests/Makefile.am
22acb1
index 16d87e9..c830e95 100644
22acb1
--- a/tests/Makefile.am
22acb1
+++ b/tests/Makefile.am
22acb1
@@ -11,6 +11,7 @@ EXTRA_DIST = \
22acb1
 	t_basic_k5.py \
22acb1
 	t_basic_k5_two_users.py \
22acb1
 	t_basic_proxy.py \
22acb1
+	t_basic_timeout.py \
22acb1
 	t_localname.py \
22acb1
 	t_hostname_acceptor.py \
22acb1
 	t_nonego.py \
22acb1
diff --git a/tests/httpd.conf b/tests/httpd.conf
22acb1
index 8c91e1c..f76f2b6 100644
22acb1
--- a/tests/httpd.conf
22acb1
+++ b/tests/httpd.conf
22acb1
@@ -111,7 +111,7 @@ DocumentRoot "{HTTPROOT}/html"
22acb1
 PidFile "{HTTPROOT}/logs/httpd.pid"
22acb1
 
22acb1
 <IfModule log_config_module>
22acb1
-LogFormat "%h %l %u %t \"%r\" %>s %b \"%{{Referer}}i\" \"%{{User-Agent}}i\"" combined
22acb1
+LogFormat "%h %l %u %t \"%r\" %>s %b \"%{{Referer}}i\" \"%{{User-Agent}}i\" \"%{{Cookie}}i\"" combined
22acb1
 CustomLog "logs/access_log" combined
22acb1
 </IfModule>
22acb1
 
22acb1
@@ -288,3 +288,33 @@ CoreDumpDirectory "{HTTPROOT}"
22acb1
     Require valid-user
22acb1
   </Proxy>
22acb1
 </VirtualHost>
22acb1
+
22acb1
+<Location /basic_auth_timeout/auth>
22acb1
+  Options +Includes
22acb1
+  AddOutputFilter INCLUDES .html
22acb1
+  AuthType GSSAPI
22acb1
+  AuthName "Password Login"
22acb1
+  GssapiSSLonly Off
22acb1
+  GssapiUseSessions On
22acb1
+  Session On
22acb1
+  SessionCookieName gssapi_session path=/basic_auth_timeout;httponly
22acb1
+  GssapiSessionKey file:{HTTPROOT}/session.key
22acb1
+  GssapiCredStore keytab:{HTTPROOT}/http.keytab
22acb1
+  GssapiBasicAuth On
22acb1
+  GssapiBasicAuthMech krb5
22acb1
+  GssapiBasicTicketTimeout 400
22acb1
+  GssapiDelegCcacheDir {HTTPROOT}
22acb1
+  Require valid-user
22acb1
+</Location>
22acb1
+<Location /basic_auth_timeout/session>
22acb1
+  Options +Includes
22acb1
+  AddOutputFilter INCLUDES .html
22acb1
+  AuthType GSSAPI
22acb1
+  AuthName "Session Login"
22acb1
+  GssapiSSLonly Off
22acb1
+  GssapiUseSessions On
22acb1
+  Session On
22acb1
+  SessionCookieName gssapi_session path=/basic_auth_timeout;httponly
22acb1
+  GssapiSessionKey file:{HTTPROOT}/session.key
22acb1
+  Require valid-user
22acb1
+</Location>
22acb1
diff --git a/tests/magtests.py b/tests/magtests.py
22acb1
index a4842a0..da1cca7 100755
22acb1
--- a/tests/magtests.py
22acb1
+++ b/tests/magtests.py
22acb1
@@ -3,11 +3,13 @@
22acb1
 
22acb1
 import argparse
22acb1
 import os
22acb1
+import os.path
22acb1
 import random
22acb1
 import shutil
22acb1
 import signal
22acb1
 import subprocess
22acb1
 import sys
22acb1
+import time
22acb1
 import traceback
22acb1
 
22acb1
 # check that we can import requests (for use in test scripts)
22acb1
@@ -341,6 +343,7 @@ USR_PWD_2 = "magpwd2"
22acb1
 USR_NAME_3 = "maguser3"
22acb1
 SVC_KTNAME = "httpd/http.keytab"
22acb1
 KEY_TYPE = "aes256-cts-hmac-sha1-96:normal"
22acb1
+USR_NAME_4 = "timeoutusr"
22acb1
 
22acb1
 
22acb1
 def setup_keys(tesdir, env):
22acb1
@@ -361,6 +364,9 @@ def setup_keys(tesdir, env):
22acb1
     cmd = "addprinc -pw %s -e %s %s" % (USR_PWD_2, KEY_TYPE, USR_NAME_2)
22acb1
     kadmin_local(cmd, env, logfile)
22acb1
 
22acb1
+    cmd = "addprinc -pw %s -e %s %s" % (USR_PWD, KEY_TYPE, USR_NAME_4)
22acb1
+    kadmin_local(cmd, env, logfile)
22acb1
+
22acb1
     # alias for multinamed hosts testing
22acb1
     alias_name = "HTTP/%s" % WRAP_ALIASNAME
22acb1
     cmd = "addprinc -randkey -e %s %s" % (KEY_TYPE, alias_name)
22acb1
@@ -600,6 +606,30 @@ def test_basic_auth_krb5(testdir, testenv, logfile):
22acb1
     return error_count
22acb1
 
22acb1
 
22acb1
+def test_basic_auth_timeout(testdir, testenv, logfile):
22acb1
+    httpdir = os.path.join(testdir, 'httpd')
22acb1
+    timeoutdir = os.path.join(httpdir, 'html', 'basic_auth_timeout')
22acb1
+    os.mkdir(timeoutdir)
22acb1
+    authdir = os.path.join(timeoutdir, 'auth')
22acb1
+    os.mkdir(authdir)
22acb1
+    sessdir = os.path.join(timeoutdir, 'session')
22acb1
+    os.mkdir(sessdir)
22acb1
+    shutil.copy('tests/index.html', os.path.join(authdir))
22acb1
+    shutil.copy('tests/index.html', os.path.join(sessdir))
22acb1
+
22acb1
+    basictout = subprocess.Popen(["tests/t_basic_timeout.py"],
22acb1
+                                 stdout=logfile, stderr=logfile,
22acb1
+                                 env=testenv, preexec_fn=os.setsid)
22acb1
+    basictout.wait()
22acb1
+    if basictout.returncode != 0:
22acb1
+        sys.stderr.write('BASIC Timeout Behavior: FAILED\n')
22acb1
+        return 1
22acb1
+    else:
22acb1
+        sys.stderr.write('BASIC Timeout Behavior: SUCCESS\n')
22acb1
+
22acb1
+    return 0
22acb1
+
22acb1
+
22acb1
 def test_bad_acceptor_name(testdir, testenv, logfile):
22acb1
     bandir = os.path.join(testdir, 'httpd', 'html', 'bad_acceptor_name')
22acb1
     os.mkdir(bandir)
22acb1
@@ -661,6 +691,33 @@ def test_hostname_acceptor(testdir, testenv, logfile):
22acb1
     return 0
22acb1
 
22acb1
 
22acb1
+def faketime_setup(testenv):
22acb1
+    libfaketime = '/usr/lib64/faketime/libfaketime.so.1'
22acb1
+    # optional faketime
22acb1
+    if not os.path.isfile(libfaketime):
22acb1
+        raise NotImplementedError
22acb1
+
22acb1
+    # spedup x100
22acb1
+    fakeenv = {'FAKETIME': '+0 x100'}
22acb1
+    fakeenv.update(testenv)
22acb1
+    fakeenv['LD_PRELOAD'] = ' '.join((testenv['LD_PRELOAD'], libfaketime))
22acb1
+    return fakeenv
22acb1
+
22acb1
+
22acb1
+def http_restart(testdir, so_dir, testenv):
22acb1
+
22acb1
+    httpenv = {'PATH': '/sbin:/bin:/usr/sbin:/usr/bin',
22acb1
+               'MALLOC_CHECK_': '3',
22acb1
+               'MALLOC_PERTURB_': str(random.randint(0, 32767) % 255 + 1)}
22acb1
+    httpenv.update(testenv)
22acb1
+
22acb1
+    httpd = "httpd" if os.path.exists("/etc/httpd/modules") else "apache2"
22acb1
+    config = os.path.join(testdir, 'httpd', 'httpd.conf')
22acb1
+    httpproc = subprocess.Popen([httpd, '-DFOREGROUND', '-f', config],
22acb1
+                                env=httpenv, preexec_fn=os.setsid)
22acb1
+    return httpproc
22acb1
+
22acb1
+
22acb1
 if __name__ == '__main__':
22acb1
     args = parse_args()
22acb1
 
22acb1
@@ -722,6 +779,25 @@ if __name__ == '__main__':
22acb1
         errs += test_basic_auth_krb5(testdir, testenv, logfile)
22acb1
 
22acb1
         errs += test_no_negotiate(testdir, testenv, logfile)
22acb1
+
22acb1
+        # After this point we need to speed up httpd to test creds timeout
22acb1
+        try:
22acb1
+            fakeenv = faketime_setup(kdcenv)
22acb1
+            timeenv = {'TIMEOUT_USER': USR_NAME_4,
22acb1
+                       'MAG_USER_PASSWORD': USR_PWD}
22acb1
+            timeenv.update(fakeenv)
22acb1
+            curporc = httpproc
22acb1
+            pid = processes['HTTPD(%d)' % httpproc.pid].pid
22acb1
+            os.killpg(pid, signal.SIGTERM)
22acb1
+            time.sleep(1)
22acb1
+            del processes['HTTPD(%d)' % httpproc.pid]
22acb1
+            httpproc = http_restart(testdir, so_dir, timeenv)
22acb1
+            processes['HTTPD(%d)' % httpproc.pid] = httpproc
22acb1
+
22acb1
+            errs += test_basic_auth_timeout(testdir, timeenv, logfile)
22acb1
+        except NotImplementedError:
22acb1
+            sys.stderr.write('BASIC Timeout Behavior: SKIPPED\n')
22acb1
+
22acb1
     except Exception:
22acb1
         traceback.print_exc()
22acb1
     finally:
22acb1
diff --git a/tests/t_basic_timeout.py b/tests/t_basic_timeout.py
22acb1
new file mode 100755
22acb1
index 0000000..983dfd2
22acb1
--- /dev/null
22acb1
+++ b/tests/t_basic_timeout.py
22acb1
@@ -0,0 +1,34 @@
22acb1
+#!/usr/bin/env python
22acb1
+# Copyright (C) 2020 - mod_auth_gssapi contributors, see COPYING for license.
22acb1
+
22acb1
+import os
22acb1
+import time
22acb1
+
22acb1
+import requests
22acb1
+from requests.auth import HTTPBasicAuth
22acb1
+
22acb1
+
22acb1
+if __name__ == '__main__':
22acb1
+    s = requests.Session()
22acb1
+    url = 'http://{}/basic_auth_timeout/auth/'.format(
22acb1
+            os.environ['NSS_WRAPPER_HOSTNAME']
22acb1
+    )
22acb1
+    url2 = 'http://{}/basic_auth_timeout/session/'.format(
22acb1
+            os.environ['NSS_WRAPPER_HOSTNAME']
22acb1
+    )
22acb1
+
22acb1
+    r = s.get(url, auth=HTTPBasicAuth(os.environ['TIMEOUT_USER'],
22acb1
+                                      os.environ['MAG_USER_PASSWORD']))
22acb1
+    if r.status_code != 200:
22acb1
+        raise ValueError('Basic Auth Failed')
22acb1
+
22acb1
+    time.sleep(301)
22acb1
+    r = s.get(url2)
22acb1
+    if r.status_code != 200:
22acb1
+        raise ValueError('Session Auth Failed')
22acb1
+
22acb1
+    time.sleep(401)
22acb1
+
22acb1
+    r = s.get(url2)
22acb1
+    if r.status_code == 200:
22acb1
+        raise ValueError('Timeout check Failed')