Skip to contentSkip to conversation

Move auth_token_state from multi to key_state

PATCH In review Arne Schwabe 5 participants 63 messages May 20, 2021 – Nov 17, 2021

lore
Share & tools
lore
#0 lore raw

PATCH v2 1/9 Move auth_token_state from multi to key_state

The auth-token check is tied to the username/password that is coming via a specific SSL session, so keep the state also in the key_state structure.

This also ensures the auth_token_state is always set to 0 on a new session since we clear the key_state object at the start of a new SSL session.

This is a prerequisite patch to fix 2020-15078 in the following two commits.

This also applies the changes to the auth_token_test.c. The change of tls_session to a pointer is necessary since before that we had tls_session not tied to the multi and had two tls_session used in the test. One implicitly in tls_multi and one explicit one. Merge these to one.

---
 src/openvpn/auth_token.c                   | 12 +--
 src/openvpn/ssl_common.h                   |  4 +-
 src/openvpn/ssl_verify.c                   |  8 +-
 tests/unit_tests/openvpn/test_auth_token.c | 91 +++++++++++-----------
 4 files changed, 60 insertions(+), 55 deletions(-)
src/openvpn/auth_token.c +7 -5
index d571b686e..0ea6d1832 100644
@@ -57,6 +57,7 @@ add_session_token_env(struct tls_session *session, struct tls_multi *multi,
         return;
     }
 
+    int auth_token_state_flags = session->key[KS_PRIMARY].auth_token_state_flags;
 
     const char *state;
 
@@ -64,9 +65,9 @@ add_session_token_env(struct tls_session *session, struct tls_multi *multi,
     {
         state = "Initial";
     }
-    else if (multi->auth_token_state_flags & AUTH_TOKEN_HMAC_OK)
+    else if (auth_token_state_flags & AUTH_TOKEN_HMAC_OK)
     {
-        switch (multi->auth_token_state_flags & (AUTH_TOKEN_VALID_EMPTYUSER|AUTH_TOKEN_EXPIRED))
+        switch (auth_token_state_flags & (AUTH_TOKEN_VALID_EMPTYUSER|AUTH_TOKEN_EXPIRED))
         {
             case 0:
                 state = "Authenticated";
@@ -98,8 +99,8 @@ add_session_token_env(struct tls_session *session, struct tls_multi *multi,
 
     /* We had a valid session id before */
     const char *session_id_source;
-    if (multi->auth_token_state_flags & AUTH_TOKEN_HMAC_OK
-        && !(multi->auth_token_state_flags & AUTH_TOKEN_EXPIRED))
+    if (auth_token_state_flags & AUTH_TOKEN_HMAC_OK
+        && !(auth_token_state_flags & AUTH_TOKEN_EXPIRED))
     {
         session_id_source = up->password;
     }
@@ -236,7 +237,8 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
      * a new token with the empty username since we do not want to loose
      * the information that the username cannot be trusted
      */
-    if (multi->auth_token_state_flags & AUTH_TOKEN_VALID_EMPTYUSER)
+    struct key_state *ks = &multi->session[TM_ACTIVE].key[KS_PRIMARY];
+    if (ks->auth_token_state_flags & AUTH_TOKEN_VALID_EMPTYUSER)
     {
         hmac_ctx_update(ctx, (const uint8_t *) "", 0);
     }
src/openvpn/ssl_common.h +2 -2
index 61cae7419..53325e556 100644
@@ -182,6 +182,8 @@ enum auth_deferred_result {
 struct key_state
 {
     int state;
+    /** The state of the auth-token sent from the client */
+    int auth_token_state_flags;
 
     /**
      * Key id for this key_state,  inherited from struct tls_session.
@@ -598,8 +600,6 @@ struct tls_multi
      * OpenVPN 3 clients sometimes wipes or replaces the username with a
      * username hint from their config.
      */
-    int auth_token_state_flags;
-    /**< The state of the auth-token sent from the client last time */
 
     /* For P_DATA_V2 */
     uint32_t peer_id;
src/openvpn/ssl_verify.c +4 -4
index 0b41eea2d..7992a6eb9 100644
@@ -1484,7 +1484,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
      */
     if (session->opt->auth_token_generate && is_auth_token(up->password))
     {
-        multi->auth_token_state_flags = verify_auth_token(up, multi, session);
+        ks->auth_token_state_flags = verify_auth_token(up, multi, session);
         if (session->opt->auth_token_call_auth)
         {
             /*
@@ -1493,7 +1493,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
              * decide what to do with the result
              */
         }
-        else if (multi->auth_token_state_flags == AUTH_TOKEN_HMAC_OK)
+        else if (ks->auth_token_state_flags == AUTH_TOKEN_HMAC_OK)
         {
             /*
              * We do not want the EXPIRED or EMPTY USER flags here so check
@@ -1592,8 +1592,8 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
              * the initial timestamp and session id can be extracted from it
              */
             if (!multi->auth_token
-                && (multi->auth_token_state_flags & AUTH_TOKEN_HMAC_OK)
-                && !(multi->auth_token_state_flags & AUTH_TOKEN_EXPIRED))
+                && (ks->auth_token_state_flags & AUTH_TOKEN_HMAC_OK)
+                && !(ks->auth_token_state_flags & AUTH_TOKEN_EXPIRED))
             {
                 multi->auth_token = strdup(up->password);
             }
tests/unit_tests/openvpn/test_auth_token.c +47 -44

232 lines not on this page · raw message

Signature · 1 line
2.31.1
#1 lore raw

PATCH v2 2/9 Implement auth-token-user

When not using username and password (i.e. auth-user-pass) it can still make to provide the client with an auth-token, e.g. for allowing a session to continue after a reconnect without requiring 2FA again.

However, without --auth-user-pass openvpn does not have a username and will ignore any pushed auth-token command.

This patch adds support for auth-token-user to set the username that should be used for auth-token

The spec of using auth-token-user base64-encoded-user are the ones that OpenVPN3 already implements.

Patch V2: Improve style, fix comments and commit message

---
 doc/man-sections/client-options.rst |  8 +++++++
 src/openvpn/misc.c                  | 37 +++++++++++++++++++++++++----
 src/openvpn/misc.h                  | 21 +++++++++++++---
 src/openvpn/options.c               |  5 ++++
 src/openvpn/ssl.c                   | 12 +++++++---
 src/openvpn/ssl.h                   |  2 ++
 6 files changed, 74 insertions(+), 11 deletions(-)
doc/man-sections/client-options.rst +8 -0
index af21fbcd7..c5b7ad960 100644
@@ -50,6 +50,14 @@ configuration.
   after a failed auth. Older clients will keep using the token value and
   react according to ``--auth-retry``
 
+--auth-token-user base64username
+  Companion option to ``--auth-token``. This options allows to override
+  the username used by the client when reauthenticating with the ``auth-token``.
+  It also allows to use ``--auth-token`` in setups that normally do not use
+  username and password.
+
+  The username has to be base64 encoded.
+
 --auth-user-pass
   Authenticate with server using username/password.
 
src/openvpn/misc.c +32 -5
index 650daa0c6..29061cd6f 100644
@@ -490,22 +490,49 @@ void
 set_auth_token(struct user_pass *up, struct user_pass *tk, const char *token)
 {
 
-    if (strlen(token) && (up->defined || tk->defined))
+    if (strlen(token))
     {
-        /* auth-token has no password, so it needs the username
-         * either already set or copied from up */
         strncpynt(tk->password, token, USER_PASS_LEN);
-        if (up->defined)
+        tk->token_defined = true;
+
+        /*
+         * --auth-token has no username, so it needs the username
+         * either already set or copied from up, or later set by
+         * --auth-token-user
+         *
+         * Do not overwrite the username if already set to avoid
+         * overwriting an auth-token
+         */
+        if (up->defined && !tk->defined)
         {
             strncpynt(tk->username, up->username, USER_PASS_LEN);
+            tk->defined = true;
         }
-        tk->defined = true;
     }
 
     /* Cleans user/pass for nocache */
     purge_user_pass(up, false);
 }
 
+void
+set_auth_token_user(struct user_pass *tk, const char *username)
+{
+    if (strlen(username))
+    {
+        /* Clear the username before decoding to ensure no old material is left
+         * and also allow decoding to not use all space to ensure the last byte is
+         * always 0 */
+        CLEAR(tk->username);
+        int len = openvpn_base64_decode(username, tk->username, USER_PASS_LEN - 1);
+        tk->defined = len > 0;
+        if (!tk->defined)
+        {
+            msg(D_PUSH, "Error decoding auth-token-username");
+        }
+    }
+}
+
+
 /*
  * Process string received by untrusted peer before
  * printing to console or log file.
src/openvpn/misc.h +18 -3
index d9005353e..0d2d42489 100644
@@ -56,6 +56,9 @@ const char *hostname_randomize(const char *hostname, struct gc_arena *gc);
 struct user_pass
 {
     bool defined;
+    /* For auth-token username and token can be set individually, so
+     * we this second bool to track if the token (password) is defined */
+    bool token_defined;
     bool nocache;
 
 /* max length of username/password */
@@ -138,19 +141,31 @@ void fail_user_pass(const char *prefix,
 void purge_user_pass(struct user_pass *up, const bool force);
 
 /**
- * Sets the auth-token to token if a username is available from either
- * up or already present in tk. The method will also purge up if
+ * Sets the auth-token to token. Ff a username is available from either
+ * up or already present in tk is the auth-token that will be used as default
+ * username for the token. The method will also purge up if
  * the auth-nocache option is active.
  *
  * @param up        (non Auth-token) Username/password
  * @param tk        auth-token userpass to set
- * @param token     token to use as password for the
+ * @param token     token to use as password for the auth-token
  *
  * @note    all parameters to this function must not be null.
  */
 void set_auth_token(struct user_pass *up, struct user_pass *tk,
                     const char *token);
 
+/**
+ * Sets the auth-token username by base64 decoding the passed
+ * username
+ *
+ * @param tk        auth-token userpass to set
+ * @param username  base64 encoded username to set
+ *
+ * @note    all parameters to this function must not be null.
+ */
+void set_auth_token_user(struct user_pass *tk, const char *username);
+
 /*
  * Process string received by untrusted peer before
  * printing to console or log file.
src/openvpn/options.c +5 -0
index 5a6f37d7d..fa3ee50d6 100644
@@ -8308,6 +8308,11 @@ add_option(struct options *options,
         }
 #endif
     }
+    else if (streq(p[0], "auth-token-user") && p[1] && !p[2])
+    {
+        VERIFY_PERMISSION(OPT_P_ECHO);
+        ssl_set_auth_token_user(p[1]);
+    }
     else if (streq(p[0], "single-session") && !p[1])
     {
         VERIFY_PERMISSION(OPT_P_GENERAL);
src/openvpn/ssl.c +9 -3
index e843b2152..7eb356ddf 100644
@@ -446,6 +446,12 @@ ssl_set_auth_token(const char *token)
     set_auth_token(&auth_user_pass, &auth_token, token);
 }
 
+void
+ssl_set_auth_token_user(const char *username)
+{
+    set_auth_token_user(&auth_token, username);
+}
+
 /*
  * Cleans an auth token and checks if it was active
  */
@@ -2310,8 +2316,8 @@ key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls_sessi
         }
     }
 
-    /* write username/password if specified */
-    if (auth_user_pass_enabled)
+    /* write username/password if specified or we are using a auth-token */
+    if (auth_user_pass_enabled || (auth_token.token_defined && auth_token.defined))
     {
 #ifdef ENABLE_MANAGEMENT
         auth_user_pass_setup(session->opt->auth_user_pass_file, session->opt->sci);
@@ -2324,7 +2330,7 @@ key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls_sessi
          * If we have a valid auth-token, send that instead of real
          * username/password
          */
-        if (auth_token.defined)
+        if (auth_token.token_defined && auth_token.defined)
         {
             up = &auth_token;
         }
src/openvpn/ssl.h +2 -0
index 88f89876a..81cc22131 100644
@@ -450,6 +450,8 @@ void ssl_purge_auth(const bool auth_user_pass_only);
 
 void ssl_set_auth_token(const char *token);
 
+void ssl_set_auth_token_user(const char *username);
+
 bool ssl_clean_auth_token(void);
 
 #ifdef ENABLE_MANAGEMENT
Signature · 1 line
2.31.1
#6 lore raw

PATCH v2 3/9 Add connection_established as state in tls_multi->context_auth

In reply to Arne Schwabe

the socket_info->connection_establish is set through link_socket_set_outgoing_addr when we reach FULL_SYNC. This patch introduces a new state in context_auth that replaces the connection_established state for TLS connections. This make the state machine easier to understand.

Patch v2: fix p2p mode server without (without ncp)

---
 src/openvpn/forward.c    |  6 +++---
 src/openvpn/forward.h    | 13 ++++++++++++-
 src/openvpn/multi.c      | 15 ++++++++-------
 src/openvpn/occ.c        |  2 +-
 src/openvpn/openvpn.h    |  4 +++-
 src/openvpn/push.c       |  2 +-
 src/openvpn/ssl.c        | 38 ++++++++++++++++++++++++++++----------
 src/openvpn/ssl_common.h | 12 +++++++++---
 8 files changed, 65 insertions(+), 27 deletions(-)
src/openvpn/forward.c +3 -3
index e302d8e0a..692ca7271 100644
@@ -280,7 +280,7 @@ void
 check_connection_established(struct context *c)
 {
 
-    if (CONNECTION_ESTABLISHED(c))
+    if (connection_established(c))
     {
         /* if --pull was specified, send a push request to server */
         if (c->c2.tls_multi && c->options.pull)
@@ -536,7 +536,7 @@ encrypt_sign(struct context *c, bool comp_frag)
      * has not yet succeeded. In non-TLS tls_multi mode is not defined
      * and we always pass packets.
      */
-    if (c->c2.tls_multi && c->c2.tls_multi->multi_state != CAS_SUCCEEDED)
+    if (c->c2.tls_multi && c->c2.tls_multi->multi_state < CAS_CONNECT_DONE)
     {
         c->c2.buf.len = 0;
     }
@@ -971,7 +971,7 @@ process_incoming_link_part1(struct context *c, struct link_socket_info *lsi, boo
          * has not yet succeeded. In non-TLS mode tls_multi is not defined
          * and we always pass packets.
          */
-        if (c->c2.tls_multi && c->c2.tls_multi->multi_state != CAS_SUCCEEDED)
+        if (c->c2.tls_multi && c->c2.tls_multi->multi_state < CAS_CONNECT_DONE)
         {
             c->c2.buf.len = 0;
         }
src/openvpn/forward.h +12 -1
index 2a67c1445..3461e6422 100644
@@ -445,6 +445,17 @@ io_wait(struct context *c, const unsigned int flags)
     }
 }
 
-#define CONNECTION_ESTABLISHED(c) (get_link_socket_info(c)->connection_established)
+static inline bool
+connection_established(struct context *c)
+{
+    if (c->c2.tls_multi)
+    {
+        return c->c2.tls_multi->multi_state >= CAS_CONNECT_DONE;
+    }
+    else
+    {
+        return get_link_socket_info(c)->connection_established;
+    }
+}
 
 #endif /* FORWARD_H */
src/openvpn/multi.c +8 -7
index def5dd40b..3f9710134 100644
@@ -674,7 +674,8 @@ multi_close_instance(struct multi_context *m,
 #ifdef ENABLE_MANAGEMENT
     set_cc_config(mi, NULL);
 #endif
-    if (mi->context.c2.tls_multi->multi_state == CAS_SUCCEEDED)
+
+    if (mi->context.c2.tls_multi->multi_state >= CAS_CONNECT_DONE)
     {
         multi_client_disconnect_script(mi);
     }
@@ -775,7 +776,7 @@ multi_create_instance(struct multi_context *m, const struct mroute_addr *real)
         goto err;
     }
 
-    mi->context.c2.tls_multi->multi_state = CAS_PENDING;
+    mi->context.c2.tls_multi->multi_state = CAS_NOT_CONNECTED;
 
     if (hash_n_elements(m->hash) >= m->max_clients)
     {
@@ -2407,7 +2408,7 @@ multi_client_connect_late_setup(struct multi_context *m,
     mi->reporting_addr_ipv6 = mi->context.c2.push_ifconfig_ipv6_local;
 
     /* set context-level authentication flag */
-    mi->context.c2.tls_multi->multi_state = CAS_SUCCEEDED;
+    mi->context.c2.tls_multi->multi_state = CAS_CONNECT_DONE;
 
     /* authentication complete, calculate dynamic client specific options */
     if (!multi_client_set_protocol_options(&mi->context))
@@ -2649,9 +2650,9 @@ multi_connection_established(struct multi_context *m, struct multi_instance *mi)
 
             case CC_RET_DEFERRED:
                 /*
-                 * we already set client_connect_status to DEFERRED_RESULT or
+                 * we already set multi_status to DEFERRED_RESULT or
                  * DEFERRED_NO_RESULT. We just return
-                 * from the function as having client_connect_status
+                 * from the function as having multi_status
                  */
                 return;
 
@@ -3003,8 +3004,8 @@ multi_process_post(struct multi_context *m, struct multi_instance *mi, const uns
         {
             /* connection is "established" when SSL/TLS key negotiation succeeds
              * and (if specified) auth user/pass succeeds */
-            if (is_cas_pending(mi->context.c2.tls_multi->multi_state)
-                && CONNECTION_ESTABLISHED(&mi->context))
+
+            if (is_cas_pending(mi->context.c2.tls_multi->multi_state))
             {
                 multi_connection_established(m, mi);
             }
src/openvpn/occ.c +1 -1
index 3ff351aa0..c169838e1 100644
@@ -185,7 +185,7 @@ check_send_occ_req_dowork(struct context *c)
 void
 check_send_occ_load_test_dowork(struct context *c)
 {
-    if (CONNECTION_ESTABLISHED(c))
+    if (connection_established(c))
     {
         const struct mtu_load_test *entry;
 
src/openvpn/openvpn.h +3 -1
index 6e4651cf5..2b74975fa 100644
@@ -206,7 +206,7 @@ struct context_1
 
 
 static inline bool
-is_cas_pending(enum client_connect_status cas)
+is_cas_pending(enum multi_status cas)
 {
     return cas == CAS_PENDING || cas == CAS_PENDING_DEFERRED
            || cas == CAS_PENDING_DEFERRED_PARTIAL;
@@ -237,6 +237,8 @@ struct context_2
 
     struct link_socket *link_socket;     /* socket used for TCP/UDP connection to remote */
     bool link_socket_owned;
+
+    /** This variable is used instead link_socket->info for P2MP UDP childs */
     struct link_socket_info *link_socket_info;
     const struct link_socket *accept_from; /* possibly do accept() on a parent link_socket */
 
src/openvpn/push.c +1 -1
index 85f9488a5..2d621e472 100644
@@ -867,7 +867,7 @@ process_incoming_push_request(struct context *c)
         send_auth_failed(c, client_reason);
         ret = PUSH_MSG_AUTH_FAILURE;
     }
-    else if (c->c2.tls_multi->multi_state == CAS_SUCCEEDED)
+    else if (c->c2.tls_multi->multi_state >= CAS_CONNECT_DONE)
     {
         time_t now;
 
src/openvpn/ssl.c +28 -10
index 7eb356ddf..9f3f83f16 100644
@@ -2381,19 +2381,22 @@ key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls_sessi
      * If we're a p2mp server to allow NCP, the first key
      * generation is postponed until after the connect script finished and the
      * NCP options can be processed. Since that always happens at after connect
-     * script options are available the CAS_SUCCEEDED status is identical to
-     * NCP options are processed and we have no extra state for NCP finished.
+     * script options are available the CAS_CONNECT_DONE status is identical to
+     * NCP options are processed and do not wait for NCP being finished.
      */
-    if (session->opt->server && (session->opt->mode != MODE_SERVER
-            || multi->multi_state == CAS_SUCCEEDED))
+    if (ks->authenticated > KS_AUTH_FALSE && session->opt->server
+        && ((session->opt->mode == MODE_SERVER && multi->multi_state >= CAS_CONNECT_DONE)
+            || (session->opt->mode == MODE_POINT_TO_POINT && !session->opt->pull)))
     {
-        if (ks->authenticated > KS_AUTH_FALSE)
+        /* if key_id >= 1, is a renegotiation, so we use the already established
+         * parameters and do not need to delay anything. */
+
+        /* key-id == 0 and multi_state >= CAS_CONNECT_DONE is a special case of
+         * the server reusing the session of a reconnecting client. */
+        if (!tls_session_generate_data_channel_keys(session))
         {
-            if (!tls_session_generate_data_channel_keys(session))
-            {
-                msg(D_TLS_ERRORS, "TLS Error: server generate_key_expansion failed");
-                goto error;
-            }
+            msg(D_TLS_ERRORS, "TLS Error: server generate_key_expansion failed");
+            goto error;
         }
     }
 
@@ -2801,6 +2804,21 @@ tls_process(struct tls_multi *multi,
                 /* Set outgoing address for data channel packets */
                 link_socket_set_outgoing_addr(to_link_socket_info, &ks->remote_addr, session->common_name, session->opt->es);
 
+                /* Check if we need to advance the tls_multi state machine */
+                if (multi->multi_state == CAS_NOT_CONNECTED)
+                {
+                    if (session->opt->mode == MODE_SERVER)
+                    {
+                        /* On a server we continue with running connect scripts next */
+                        multi->multi_state = CAS_PENDING;
+                    }
+                    else
+                    {
+                        /* Skip the connect script related states */
+                        multi->multi_state = CAS_CONNECT_DONE;
+                    }
+                }
+
                 /* Flush any payload packets that were buffered before our state transitioned to S_ACTIVE */
                 flush_payload_buffer(ks);
 
src/openvpn/ssl_common.h +9 -3
index 53325e556..8a65ab984 100644
@@ -504,12 +504,18 @@ struct tls_session
 /* client authentication state, CAS_SUCCEEDED must be 0 since
  * non multi code path still checks this variable but does not initialise it
  * so the code depends on zero initialisation */
-enum client_connect_status {
-    CAS_SUCCEEDED=0,
+
+/* CAS_NOT_CONNECTED is the initial state for every context. When the *first*
+ * tls_session reaches S_ACTIVE, this state machine moves to CAS_PENDING (server)
+ * or CAS_CONNECT_DONE (client/p2p) as clients skip the stages associated with
+ * connect scripts/plugins */
+enum multi_status {
+    CAS_NOT_CONNECTED,
     CAS_PENDING,
     CAS_PENDING_DEFERRED,
     CAS_PENDING_DEFERRED_PARTIAL,   /**< at least handler succeeded, no result yet*/
     CAS_FAILED,
+    CAS_CONNECT_DONE,
 };
 
 
@@ -548,7 +554,7 @@ struct tls_multi
 
     int n_sessions;             /**< Number of sessions negotiated thus
                                  *   far. */
-    enum client_connect_status multi_state;
+    enum multi_status multi_state;
 
     /*
      * Number of errors.
Signature · 1 line
2.31.1
#9 lore raw

PATCH v2 4/9 Make waiting on auth an explicit state in the context state machine

In reply to Arne Schwabe

Previously we relied on checking tls_authentication_status to check wether to determine if the context auth state is actually valid or not. This patch eliminates that check by introducing waiting on the authentication as extra state in the context auth, state machine.

---
 src/openvpn/multi.c      | 5 -----
 src/openvpn/ssl.c        | 9 ++++++++-
 src/openvpn/ssl_common.h | 1 +
 3 files changed, 9 insertions(+), 6 deletions(-)
src/openvpn/multi.c +0 -5
index 3f9710134..7cb9e86aa 100644
@@ -2596,11 +2596,6 @@ static const multi_client_connect_handler client_connect_handlers[] = {
 static void
 multi_connection_established(struct multi_context *m, struct multi_instance *mi)
 {
-    if (tls_authentication_status(mi->context.c2.tls_multi) != TLS_AUTHENTICATION_SUCCEEDED)
-    {
-        return;
-    }
-
     /* We are only called for the CAS_PENDING_x states, so we
      * can ignore other states here */
     bool from_deferred = (mi->context.c2.tls_multi->multi_state != CAS_PENDING);
src/openvpn/ssl.c +8 -1
index 9f3f83f16..fd64b8d4e 100644
@@ -2810,7 +2810,7 @@ tls_process(struct tls_multi *multi,
                     if (session->opt->mode == MODE_SERVER)
                     {
                         /* On a server we continue with running connect scripts next */
-                        multi->multi_state = CAS_PENDING;
+                        multi->multi_state = CAS_WAITING_AUTH;
                     }
                     else
                     {
@@ -3136,6 +3136,13 @@ tls_multi_process(struct tls_multi *multi,
 
     enum tls_auth_status tas = tls_authentication_status(multi);
 
+    /* If we have successfully authenticated and are still waiting for the authentication to finish
+     * move the state machine for the multi context forward */
+    if (multi->multi_state == CAS_WAITING_AUTH && tas == TLS_AUTHENTICATION_SUCCEEDED)
+    {
+        multi->multi_state = CAS_PENDING;
+    }
+
     /*
      * If lame duck session expires, kill it.
      */
src/openvpn/ssl_common.h +1 -0
index 8a65ab984..66700bf68 100644
@@ -511,6 +511,7 @@ struct tls_session
  * connect scripts/plugins */
 enum multi_status {
     CAS_NOT_CONNECTED,
+    CAS_WAITING_AUTH,               /**< TLS connection established but deferred auth not finished */
     CAS_PENDING,
     CAS_PENDING_DEFERRED,
     CAS_PENDING_DEFERRED_PARTIAL,   /**< at least handler succeeded, no result yet*/
Signature · 1 line
2.31.1
#14 lore raw

PATCH v2 5/9 Extracting key_state deferred auth status update into function

In reply to Arne Schwabe

This extract the update of a deferred key status into into own function.

Patch v2: Do not ignore auth_deferred_expire. Minor format changes.

---
 src/openvpn/ssl_verify.c | 96 ++++++++++++++++++++++++++--------------
 1 file changed, 62 insertions(+), 34 deletions(-)
src/openvpn/ssl_verify.c +62 -34
index 7992a6eb9..455a5cd1b 100644
@@ -1073,6 +1073,60 @@ key_state_test_auth_control_file(struct auth_deferred_status *ads, bool cached)
     return ACF_DISABLED;
 }
 
+/**
+ * This method takes a key_state and if updates the state
+ * of the key if it is deferred.
+ * @param cached    If auth control files should be tried to be opened or th
+ *                  cached results should be used
+ * @param ks        The key_state to update
+ */
+static void
+update_key_auth_status(bool cached, struct key_state *ks)
+{
+    if (ks->authenticated == KS_AUTH_FALSE)
+    {
+        return;
+    }
+    else
+    {
+        enum auth_deferred_result auth_plugin = ACF_DISABLED;
+        enum auth_deferred_result auth_script = ACF_DISABLED;
+        enum auth_deferred_result auth_man = ACF_DISABLED;
+        auth_plugin = key_state_test_auth_control_file(&ks->plugin_auth, cached);
+        auth_script = key_state_test_auth_control_file(&ks->script_auth, cached);
+#ifdef ENABLE_MANAGEMENT
+        auth_man = man_def_auth_test(ks);
+#endif
+        ASSERT(auth_plugin < 4 && auth_script < 4 && auth_man < 4);
+
+        if (auth_plugin == ACF_FAILED || auth_script == ACF_FAILED
+           || auth_man == ACF_FAILED)
+        {
+            ks->authenticated = KS_AUTH_FALSE;
+            return;
+        }
+        else if (auth_plugin == ACF_PENDING || auth_script == ACF_PENDING
+                 || auth_man == ACF_PENDING)
+        {
+            if (now > ks->auth_deferred_expire)
+            {
+                /* Window to authenticate the key has expired, mark
+                 * the key as unauthenticated */
+                ks->authenticated = KS_AUTH_FALSE;
+            }
+        }
+        else
+        {
+            /* all auth states (auth_plugin, auth_script, auth_man)
+             * are either ACF_DISABLED or ACF_SUCCEDED now, which
+             * translates to "not checked" or "auth succeeded"
+             */
+            ks->authenticated = KS_AUTH_TRUE;
+        }
+    }
+}
+
+
 /**
  * The minimum times to have passed to update the cache. Older versions
  * of OpenVPN had code path that did not do any caching, so we start
@@ -1115,46 +1169,20 @@ tls_authentication_status(struct tls_multi *multi)
         if (TLS_AUTHENTICATED(multi, ks))
         {
             active++;
+            update_key_auth_status(cached, ks);
+
             if (ks->authenticated == KS_AUTH_FALSE)
             {
                 failed_auth = true;
             }
-            else
+            else if (ks->authenticated == KS_AUTH_DEFERRED)
             {
-                enum auth_deferred_result auth_plugin = ACF_DISABLED;
-                enum auth_deferred_result auth_script = ACF_DISABLED;
-                enum auth_deferred_result auth_man = ACF_DISABLED;
-                auth_plugin = key_state_test_auth_control_file(&ks->plugin_auth, cached);
-                auth_script = key_state_test_auth_control_file(&ks->script_auth, cached);
-#ifdef ENABLE_MANAGEMENT
-                auth_man = man_def_auth_test(ks);
-#endif
-                ASSERT(auth_plugin < 4 && auth_script < 4 && auth_man < 4);
 
-                if (auth_plugin == ACF_FAILED || auth_script == ACF_FAILED
-                   || auth_man == ACF_FAILED)
-                {
-                    ks->authenticated = KS_AUTH_FALSE;
-                    failed_auth = true;
-                }
-                else if (auth_plugin == ACF_PENDING
-                         || auth_script == ACF_PENDING
-                         || auth_man == ACF_PENDING)
-                {
-                    if (now < ks->auth_deferred_expire)
-                    {
-                        deferred = true;
-                    }
-                }
-                else
-                {
-                    /* all auth states (auth_plugin, auth_script, auth_man)
-                     * are either ACF_DISABLED or ACF_SUCCEDED now, which
-                     * translates to "not checked" or "auth succeeded"
-                     */
-                    success = true;
-                    ks->authenticated = KS_AUTH_TRUE;
-                }
+                deferred = true;
+            }
+            else if (ks->authenticated == KS_AUTH_TRUE)
+            {
+                success = true;
             }
         }
     }
Signature · 1 line
2.31.1
#18 lore raw

PATCH v2 6/9 Introduce S_GENERATED_KEYS state and generate keys only when authenticated

In reply to Arne Schwabe

Since generating data channel keys does not happen when we have reach the S_ACTIVE/S_GOT_KEY state anymore like it used to be before NCP, the state that data channel keys deserves its own state in the TLS session state machine.

The changes done by this commit are rather intrusive since they move the key generation to a completely different place and also rely on the state machine to decide if keys should be generated rather than on the complicated conditions that were implemented in the key_method_2_write/read methods.

A (intended) side effect of this change is that sessions that are still in deferred state (ks->authenticated == KS_DEFERRED) will not have data channel keys generated. This avoids corner cases where a not fully authenticated sessions might leak data.

Patch v2: rebased

---
 src/openvpn/forward.h    |  2 +-
 src/openvpn/init.c       |  1 +
 src/openvpn/ssl.c        | 89 +++++++++++++++++-----------------------
 src/openvpn/ssl.h        | 10 +++++
 src/openvpn/ssl_common.h |  9 +++-
 5 files changed, 57 insertions(+), 54 deletions(-)
src/openvpn/forward.h +1 -1
index 3461e6422..b8760099e 100644
@@ -450,7 +450,7 @@ connection_established(struct context *c)
 {
     if (c->c2.tls_multi)
     {
-        return c->c2.tls_multi->multi_state >= CAS_CONNECT_DONE;
+        return c->c2.tls_multi->multi_state >= CAS_WAITING_OPTIONS_IMPORT;
     }
     else
     {
src/openvpn/init.c +1 -0
index 49c742928..4335d4870 100644
@@ -2202,6 +2202,7 @@ do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
         }
 
         c->c2.do_up_ran = true;
+        c->c2.tls_multi->multi_state = CAS_CONNECT_DONE;
     }
     return true;
 }
src/openvpn/ssl.c +38 -51

157 lines not on this page · raw message

src/openvpn/ssl.h +10 -0
index 81cc22131..baf3560d2 100644
@@ -612,4 +612,14 @@ show_available_tls_ciphers(const char *cipher_list,
                            const char *cipher_list_tls13,
                            const char *tls_cert_profile);
 
+
+/**
+ * Generate data channel keys for the supplied TLS session.
+ *
+ * This erases the source material used to generate the data channel keys, and
+ * can thus be called only once per session.
+ */
+bool
+tls_session_generate_data_channel_keys(struct tls_session *session);
+
 #endif /* ifndef OPENVPN_SSL_H */
src/openvpn/ssl_common.h +7 -2
index 66700bf68..928e80929 100644
@@ -64,7 +64,8 @@
  *      material.
  *   -# \c S_GOT_KEY, have received remote part of \c key_source2 random
  *      material.
- *   -# \c S_ACTIVE, normal operation
+ *   -# \c S_ACTIVE, control channel successfully established
+ *   -# \c S_GENERATED_KEYS, the
  *
  * Servers follow the same order, except for \c S_SENT_KEY and \c
  * S_GOT_KEY being reversed, because the server first receives the
@@ -92,7 +93,10 @@
 #define S_ACTIVE          6     /**< Operational \c key_state state
                                  *   immediately after negotiation has
                                  *   completed while still within the
-                                 *   handshake window. */
+                                 *   handshake window, deferred auth, client
+                                 *   connect and can still
+                                 *   be pending. */
+#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated */
 /* Note that earlier versions also had a S_OP_NORMAL state that was
  * virtually identical with S_ACTIVE and the code still assumes everything
  * >= S_ACTIVE to be fully operational */
@@ -516,6 +520,7 @@ enum multi_status {
     CAS_PENDING_DEFERRED,
     CAS_PENDING_DEFERRED_PARTIAL,   /**< at least handler succeeded, no result yet*/
     CAS_FAILED,
+    CAS_WAITING_OPTIONS_IMPORT,     /**< client with pull or p2p waiting for first time options import */
     CAS_CONNECT_DONE,
 };
 
Signature · 1 line
2.31.1
#24 lore raw

PATCH v2 7/9 Move auth_token_state_flags to tls_session and cleanup initial_token

In reply to Arne Schwabe

The usage of the auth_token_state_flags is tied to the authentication. The other authentication related flags and status are in the tls_session struct instead of the tls_multi struct. Move auth_token_state_flags to the right place.

This also changes that auth_token_initial is set when the token is initially generated instead when pushing the token. Even I don't know anymore why I did it in this way in the first place. Also use multi->auth_token_initial as source for the sesssion ID since it should now always be available.

---
 src/openvpn/auth_token.c                   | 28 +++++++++++++++-------
 src/openvpn/push.c                         |  8 -------
 src/openvpn/ssl_verify.c                   |  5 +++-
 tests/unit_tests/openvpn/test_auth_token.c | 15 ++++++++----
 4 files changed, 35 insertions(+), 21 deletions(-)
src/openvpn/auth_token.c +20 -8
index 0ea6d1832..60604e6e3 100644
@@ -109,11 +109,11 @@ add_session_token_env(struct tls_session *session, struct tls_multi *multi,
         /*
          * No session before, generate a new session token for the new session
          */
-        if (!multi->auth_token)
+        if (!multi->auth_token_initial)
         {
             generate_auth_token(up, multi);
         }
-        session_id_source = multi->auth_token;
+        session_id_source = multi->auth_token_initial;
     }
     /*
      * In the auth-token the auth token is already base64 encoded
@@ -184,7 +184,7 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
     uint8_t sessid[AUTH_TOKEN_SESSION_ID_LEN];
 
-    if (multi->auth_token)
+    if (multi->auth_token_initial)
     {
         /* Just enough space to fit 8 bytes+ 1 extra to decode a non padded
          * base64 string (multiple of 3 bytes). 9 bytes => 12 bytes base64
@@ -192,13 +192,18 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
          */
         char old_tstamp_decode[9];
 
+        /* Make a copy of the string to not modify multi->auth_token_initial */
+        char* initial_token_copy = string_alloc(multi->auth_token_initial, &gc);
+
         /*
          * reuse the same session id and timestamp and null terminate it at
          * for base64 decode it only decodes the session id part of it
          */
-        char *old_sessid = multi->auth_token + strlen(SESSION_ID_PREFIX);
+        char *old_sessid =initial_token_copy + strlen(SESSION_ID_PREFIX);
         char *old_tsamp_initial = old_sessid + AUTH_TOKEN_SESSION_ID_LEN*8/6;
 
+
+
         old_tsamp_initial[12] = '\0';
         ASSERT(openvpn_base64_decode(old_tsamp_initial, old_tstamp_decode, 9) == 9);
 
@@ -212,10 +217,6 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
         old_tsamp_initial[0] = '\0';
         ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSION_ID_LEN)==AUTH_TOKEN_SESSION_ID_LEN);
-
-
-        /* free the auth-token, we will replace it with a new one */
-        free(multi->auth_token);
     }
     else if (!rand_bytes(sessid, AUTH_TOKEN_SESSION_ID_LEN))
     {
@@ -272,11 +273,22 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
     free(b64output);
 
+    /* free the auth-token if defined, we will replace it with a new one */
+    free(multi->auth_token);
     multi->auth_token = strdup((char *)BPTR(&session_token));
 
     dmsg(D_SHOW_KEYS, "Generated token for client: %s (%s)",
          multi->auth_token, up->username);
 
+    if (!multi->auth_token_initial)
+    {
+        /*
+         * Save the initial auth token for clients that ignore
+         * the updates to the token
+         */
+        multi->auth_token_initial = strdup(multi->auth_token);
+    }
+
     gc_free(&gc);
 }
 
src/openvpn/push.c +0 -8
index 2d621e472..98a9c3689 100644
@@ -527,14 +527,6 @@ prepare_auth_token_push_reply(struct tls_multi *tls_multi, struct gc_arena *gc,
         push_option_fmt(gc, push_list, M_USAGE,
                         "auth-token %s",
                         tls_multi->auth_token);
-        if (!tls_multi->auth_token_initial)
-        {
-            /*
-             * Save the initial auth token for clients that ignore
-             * the updates to the token
-             */
-            tls_multi->auth_token_initial = strdup(tls_multi->auth_token);
-        }
     }
 }
 
src/openvpn/ssl_verify.c +4 -1
index 455a5cd1b..dfb475017 100644
@@ -1512,6 +1512,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
      */
     if (session->opt->auth_token_generate && is_auth_token(up->password))
     {
+
         ks->auth_token_state_flags = verify_auth_token(up, multi, session);
         if (session->opt->auth_token_call_auth)
         {
@@ -1640,7 +1641,9 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
          * Otherwise the auth-token get pushed out as part of the "normal"
          * push-reply
          */
-        if (multi->auth_token_initial)
+        bool initial_connect = session->key[KS_PRIMARY].key_id == 0;
+
+        if (multi->auth_token_initial && !initial_connect)
         {
             /*
              * We do not explicitly schedule the sending of the
tests/unit_tests/openvpn/test_auth_token.c +11 -4
index 69fc1f8c9..161bc4499 100644
@@ -174,7 +174,10 @@ auth_token_test_timeout(void **state)
 
     now = 100000;
     generate_auth_token(&ctx->up, &ctx->multi);
+
     strcpy(ctx->up.password, ctx->multi.auth_token);
+    free(ctx->multi.auth_token_initial);
+    ctx->multi.auth_token_initial = NULL;
 
     /* No time has passed */
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
@@ -244,10 +247,10 @@ auth_token_test_known_keys(void **state)
 
     now = 0;
     /* Preload the session id so the same session id is used here */
-    ctx->multi.auth_token = strdup(now0key0);
+    ctx->multi.auth_token_initial = strdup(now0key0);
 
     /* Zero the hmac part to ensure we have a newly generated token */
-    zerohmac(ctx->multi.auth_token);
+    zerohmac(ctx->multi.auth_token_initial);
 
     generate_auth_token(&ctx->up, &ctx->multi);
 
@@ -305,13 +308,16 @@ auth_token_test_env(void **state)
 {
     struct test_context *ctx = (struct test_context *) *state;
 
+
     struct key_state *ks = &ctx->multi.session[TM_ACTIVE].key[KS_PRIMARY];
     
     ks->auth_token_state_flags = 0;
+
     ctx->multi.auth_token = NULL;
     add_session_token_env(ctx->session, &ctx->multi, &ctx->up);
     assert_string_equal(lastsesion_statevalue, "Initial");
 
+
     ks->auth_token_state_flags = 0;
     strcpy(ctx->up.password, now0key0);
     add_session_token_env(ctx->session, &ctx->multi, &ctx->up);
@@ -331,6 +337,7 @@ auth_token_test_env(void **state)
 
     ks->auth_token_state_flags = AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED|AUTH_TOKEN_VALID_EMPTYUSER;
     add_session_token_env(ctx->session, &ctx->multi, &ctx->up);
+
     assert_string_equal(lastsesion_statevalue, "ExpiredEmptyUser");
 }
 
@@ -341,13 +348,13 @@ auth_token_test_random_keys(void **state)
 
     now = 0x5c331e9c;
     /* Preload the session id so the same session id is used here */
-    ctx->multi.auth_token = strdup(random_token);
+    ctx->multi.auth_token_initial = strdup(random_token);
 
     free_key_ctx(&ctx->multi.opt.auth_token_key);
     auth_token_init_secret(&ctx->multi.opt.auth_token_key, random_key, true);
 
     /* Zero the hmac part to ensure we have a newly generated token */
-    zerohmac(ctx->multi.auth_token);
+    zerohmac(ctx->multi.auth_token_initial);
 
     generate_auth_token(&ctx->up, &ctx->multi);
 
Signature · 1 line
2.31.1
#50 lore raw

PATCH v2 8/9 Remove --ncp-disable option

In reply to Arne Schwabe

NCP has proven to be stable and apart from the one VPN Provider doing hacky things with homebrewed NCP we have not had any reports about ncp-disable being required. Remove ncp-disable to simplify code paths.

Note: This patch breaks client without --pull. The follow up patch for P2P NCP will restore that. But to avoid all the NCP/non-NCP special cases to be implemented in P2P. P2P will directly switch from always non-NCP to always NCP.

---
 Changes.rst                           |  4 +++
 doc/man-sections/protocol-options.rst |  8 ++----
 src/openvpn/init.c                    | 17 ++++---------
 src/openvpn/multi.c                   |  4 ---
 src/openvpn/options.c                 | 36 +++------------------------
 src/openvpn/options.h                 |  1 -
 src/openvpn/ssl.c                     |  3 +--
 src/openvpn/ssl_common.h              |  1 -
 src/openvpn/ssl_ncp.c                 |  4 ---
 9 files changed, 16 insertions(+), 62 deletions(-)
Changes.rst +4 -0
index 9185b55f7..e7ae6abed 100644
@@ -57,6 +57,10 @@ Deprecated features
     is considered "too complicated", using ``--peer-fingerprint`` makes
     TLS mode about as easy as using ``--secret``.
 
+``ncp-disable`` has been removed
+    This option mainly served a role as debug option when NCP was first
+    introduced. It should now no longer be necessary.
+
 Overview of changes in 2.5
 ==========================
 
doc/man-sections/protocol-options.rst +2 -6
index 34d4255ee..5ae780e1f 100644
@@ -65,8 +65,8 @@ configured in a compatible way between both the local and remote side.
   The default is :code:`BF-CBC`, an abbreviation for Blowfish in Cipher
   Block Chaining mode. When cipher negotiation (NCP) is allowed,
   OpenVPN 2.4 and newer on both client and server side will automatically
-  upgrade to :code:`AES-256-GCM`.  See ``--data-ciphers`` and
-  ``--ncp-disable`` for more details on NCP.
+  upgrade to :code:`AES-256-GCM`.  See ``--data-ciphers`` for more details
+  on NCP.
 
   Using :code:`BF-CBC` is no longer recommended, because of its 64-bit
   block size. This small block size allows attacks based on collisions, as
@@ -235,10 +235,6 @@ configured in a compatible way between both the local and remote side.
     have been configured with `--enable-small`
     (typically used on routers or other embedded devices).
 
---ncp-disable
-  **DEPRECATED** Disable "Negotiable Crypto Parameters". This completely
-  disables cipher negotiation.
-
 --secret args
   **DEPRECATED** Enable Static Key encryption mode (non-TLS). Use pre-shared secret
   ``file`` which was generated with ``--genkey``.
src/openvpn/init.c +5 -12
index 4335d4870..38abf9f3a 100644
@@ -2227,18 +2227,14 @@ pull_permission_mask(const struct context *c)
         | OPT_P_EXPLICIT_NOTIFY
         | OPT_P_ECHO
         | OPT_P_PULL_MODE
-        | OPT_P_PEER_ID;
+        | OPT_P_PEER_ID
+        | OPT_P_NCP;
 
     if (!c->options.route_nopull)
     {
         flags |= (OPT_P_ROUTE | OPT_P_IPWIN32);
     }
 
-    if (c->options.ncp_enabled)
-    {
-        flags |= OPT_P_NCP;
-    }
-
     return flags;
 }
 
@@ -2720,8 +2716,6 @@ do_init_crypto_tls_c1(struct context *c)
         *
         * Therefore, the key structure has to be initialized when:
         * - any non-BF-CBC cipher was selected; or
-        * - BF-CBC is selected and NCP is disabled (explicit request to
-        *   use the BF-CBC cipher); or
         * - BF-CBC is selected, NCP is enabled and fallback is enabled
         *   (BF-CBC will be the fallback).
         * - BF-CBC is in data-ciphers and we negotiate to use BF-CBC:
@@ -2731,12 +2725,12 @@ do_init_crypto_tls_c1(struct context *c)
         * Note that BF-CBC will still be part of the OCC string to retain
         * backwards compatibility with older clients.
         */
-        if (!streq(options->ciphername, "BF-CBC") || !options->ncp_enabled
-            || (options->ncp_enabled && tls_item_in_cipher_list("BF-CBC", options->ncp_ciphers))
+        if (!streq(options->ciphername, "BF-CBC")
+            || tls_item_in_cipher_list("BF-CBC", options->ncp_ciphers)
             || options->enable_ncp_fallback)
         {
             /* Do not warn if the if the cipher is used only in OCC */
-            bool warn = !options->ncp_enabled || options->enable_ncp_fallback;
+            bool warn = options->enable_ncp_fallback;
             init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname,
                           true, warn);
         }
@@ -2838,7 +2832,6 @@ do_init_crypto_tls(struct context *c, const unsigned int flags)
     to.tcp_mode = link_socket_proto_connection_oriented(options->ce.proto);
     to.config_ciphername = c->options.ciphername;
     to.config_ncp_ciphers = c->options.ncp_ciphers;
-    to.ncp_enabled = options->ncp_enabled;
     to.transition_window = options->transition_window;
     to.handshake_window = options->handshake_window;
     to.packet_timeout = options->tls_timeout;
src/openvpn/multi.c +0 -4
index 7cb9e86aa..2507108e2 100644
@@ -1791,10 +1791,6 @@ multi_client_set_protocol_options(struct context *c)
 #endif
 
     /* Select cipher if client supports Negotiable Crypto Parameters */
-    if (!o->ncp_enabled)
-    {
-        return true;
-    }
 
     /* if we have already created our key, we cannot *change* our own
      * cipher -> so log the fact and push the "what we have now" cipher
src/openvpn/options.c +4 -32
index fa3ee50d6..2f4ccaa09 100644
@@ -526,7 +526,6 @@ static const char usage_message[] =
     "                  (default=%s).\n"
     "                  Set alg=none to disable encryption.\n"
     "--data-ciphers list : List of ciphers that are allowed to be negotiated.\n"
-    "--ncp-disable   : (DEPRECATED) Disable cipher negotiation.\n"
     "--prng alg [nsl] : For PRNG, use digest algorithm alg, and\n"
     "                   nonce_secret_len=nsl.  Set alg=none to disable PRNG.\n"
 #ifndef ENABLE_CRYPTO_MBEDTLS
@@ -843,7 +842,6 @@ init_options(struct options *o, const bool init_gc)
     o->stale_routes_check_interval = 0;
     o->ifconfig_pool_persist_refresh_freq = 600;
     o->scheduled_exit_interval = 5;
-    o->ncp_enabled = true;
     o->ncp_ciphers = "AES-256-GCM:AES-128-GCM";
     o->authname = "SHA1";
     o->prng_hash = "SHA1";
@@ -1719,7 +1717,6 @@ show_settings(const struct options *o)
     SHOW_STR_INLINE(shared_secret_file);
     SHOW_PARM(key_direction, keydirection2ascii(o->key_direction, false, true), "%s");
     SHOW_STR(ciphername);
-    SHOW_BOOL(ncp_enabled);
     SHOW_STR(ncp_ciphers);
     SHOW_STR(authname);
     SHOW_STR(prng_hash);
@@ -3082,7 +3079,6 @@ options_postprocess_cipher(struct options *o)
     if (!o->pull && !(o->mode == MODE_SERVER))
     {
         /* we are in the classic P2P mode */
-        o->ncp_enabled = false;
         msg( M_WARN, "Cipher negotiation is disabled since neither "
              "P2MP client nor server mode is enabled");
 
@@ -3099,18 +3095,6 @@ options_postprocess_cipher(struct options *o)
     /* pull or P2MP mode */
     if (!o->ciphername)
     {
-        if (!o->ncp_enabled)
-        {
-            msg(M_USAGE, "--ncp-disable needs an explicit --cipher or "
-                         "--data-ciphers-fallback config option");
-        }
-
-        msg(M_WARN, "--cipher is not set. Previous OpenVPN version defaulted to "
-            "BF-CBC as fallback when cipher negotiation failed in this case. "
-            "If you need this fallback please add '--data-ciphers-fallback "
-            "BF-CBC' to your configuration and/or add BF-CBC to "
-            "--data-ciphers.");
-
         /* We still need to set the ciphername to BF-CBC since various other
          * parts of OpenVPN assert that the ciphername is set */
         o->ciphername = "BF-CBC";
@@ -3152,13 +3136,10 @@ options_postprocess_mutate(struct options *o)
     options_postprocess_cipher(o);
     options_postprocess_mutate_invariant(o);
 
-    if (o->ncp_enabled)
+    o->ncp_ciphers = mutate_ncp_cipher_list(o->ncp_ciphers, &o->gc);
+    if (o->ncp_ciphers == NULL)
     {
-        o->ncp_ciphers = mutate_ncp_cipher_list(o->ncp_ciphers, &o->gc);
-        if (o->ncp_ciphers == NULL)
-        {
-            msg(M_USAGE, "NCP cipher list contains unsupported ciphers or is too long.");
-        }
+        msg(M_USAGE, "NCP cipher list contains unsupported ciphers or is too long.");
     }
 
     if (o->remote_list && !o->connection_list)
@@ -3908,8 +3889,7 @@ options_string(const struct options *o,
         }
         /* Only announce the cipher to our peer if we are willing to
          * support it */
-        if (p2p_nopull || !o->ncp_enabled
-            || tls_item_in_cipher_list(ciphername, o->ncp_ciphers))
+        if (p2p_nopull || tls_item_in_cipher_list(ciphername, o->ncp_ciphers))
         {
             buf_printf(&out, ",cipher %s", ciphername);
         }
@@ -7994,14 +7974,6 @@ add_option(struct options *options,
             msg(msglevel, "Unknown key-derivation method %s", p[1]);
         }
     }
-    else if (streq(p[0], "ncp-disable") && !p[1])
-    {
-        VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INSTANCE);
-        options->ncp_enabled = false;
-        msg(M_WARN, "DEPRECATED OPTION: ncp-disable. Disabling "
-            "cipher negotiation is a deprecated debug feature that "
-            "will be removed in OpenVPN 2.6");
-    }
     else if (streq(p[0], "prng") && p[1] && !p[3])
     {
         VERIFY_PERMISSION(OPT_P_GENERAL);
src/openvpn/options.h +0 -1
index 41e84f7e1..69897c5a7 100644
@@ -512,7 +512,6 @@ struct options
     const char *ciphername;
     bool enable_ncp_fallback;      /**< If defined fall back to
                                     * ciphername if NCP fails */
-    bool ncp_enabled;
     const char *ncp_ciphers;
     const char *authname;
     const char *prng_hash;
src/openvpn/ssl.c +1 -2
index b28d8edf8..dd6e462d0 100644
@@ -2187,8 +2187,7 @@ push_peer_info(struct buffer *buf, struct tls_session *session)
         }
 
         /* support for Negotiable Crypto Parameters */
-        if (session->opt->ncp_enabled
-            && (session->opt->mode == MODE_SERVER || session->opt->pull))
+        if (session->opt->mode == MODE_SERVER || session->opt->pull)
         {
             if (tls_item_in_cipher_list("AES-128-GCM", session->opt->config_ncp_ciphers)
                 && tls_item_in_cipher_list("AES-256-GCM", session->opt->config_ncp_ciphers))
src/openvpn/ssl_common.h +0 -1
index 928e80929..43af51ee9 100644
@@ -324,7 +324,6 @@ struct tls_options
 
     const char *config_ciphername;
     const char *config_ncp_ciphers;
-    bool ncp_enabled;
 
     bool tls_crypt_v2;
     const char *tls_crypt_v2_verify_script;
src/openvpn/ssl_ncp.c +0 -4
index f02a3103c..722256b42 100644
@@ -289,10 +289,6 @@ check_pull_client_ncp(struct context *c, const int found)
         return true;
     }
 
-    if (!c->options.ncp_enabled)
-    {
-        return true;
-    }
     /* If the server did not push a --cipher, we will switch to the
      * remote cipher if it is in our ncp-ciphers list */
     if(tls_poor_mans_ncp(&c->options, c->c2.tls_multi->remote_ciphername))
Signature · 1 line
2.31.1
#53 lore raw

PATCH v2 9/9 Support NCP in pure P2P VPN setups

In reply to Arne Schwabe

Currently P2P mode of OpenVPN is on of the few places that cannot negotiate modern OpenVPN features. This becomes more and more problematic since P2P and P2MP code diverge more and more and also the lack of switching to more advanced features like Data v2 currently blocks P2P mode from working together with the upcoming ovpn-dco support.

This NCP support is a lot simpler and works in the following way:

- P2P peer announce an extremely limited IV_ variable set (IV_PROTO and IV_CIPHERS)
- Both peers check if the IV_PROTO_NCP_P2P bit is present in IV_PROTO
- if yes both sides deterministically determine according to IV_PROTO and IV_CIPHER what options can be used and start using these

There are no poor man's NCP or other compatibility workaround like in the normal NCP, making this NCP leaner and more deterministic.

---
 src/openvpn/init.c                  | 100 ++++++++++++++++---
 src/openvpn/options.c               |   8 +-
 src/openvpn/ssl.c                   | 120 +++++++++++++++--------
 src/openvpn/ssl.h                   |   5 +
 src/openvpn/ssl_backend.h           |   1 +
 src/openvpn/ssl_common.h            |  10 ++
 src/openvpn/ssl_ncp.c               | 145 ++++++++++++++++++++++++++++
 src/openvpn/ssl_ncp.h               |  25 +++++
 tests/unit_tests/openvpn/test_ncp.c |  11 +++
 9 files changed, 366 insertions(+), 59 deletions(-)
src/openvpn/init.c +84 -16
index 38abf9f3a..5d4852ae1 100644
@@ -68,6 +68,7 @@ static const char *saved_pid_file_name; /* GLOBAL */
 #define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
 
 static void do_init_first_time(struct context *c);
+static bool do_deferred_p2p_ncp(struct context *c);
 
 void
 context_clear(struct context *c)
@@ -2151,6 +2152,14 @@ do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
                 return false;
             }
         }
+        else if (c->mode == MODE_POINT_TO_POINT)
+        {
+            if (!do_deferred_p2p_ncp(c))
+            {
+                msg(D_TLS_ERRORS, "ERROR: Failed to apply P2P negotiated protocol options");
+                return false;
+            }
+        }
 
         /* if --up-delay specified, open tun, do ifconfig, and run up script now */
         if (c->options.up_delay || PULL_DEFINED(&c->options))
@@ -2238,6 +2247,72 @@ pull_permission_mask(const struct context *c)
     return flags;
 }
 
+static
+void adjust_mtu_peerid(struct context *c)
+{
+    frame_add_to_extra_frame(&c->c2.frame, +3);     /* peer-id overhead */
+    if (!c->options.ce.link_mtu_defined)
+    {
+        frame_add_to_link_mtu(&c->c2.frame, +3);
+        msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
+            EXPANDED_SIZE(&c->c2.frame));
+    }
+    else
+    {
+        msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
+                    " fixed by config - reducing tun-mtu to %d, expect"
+                    " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );
+    }
+}
+
+static bool
+do_deferred_p2p_ncp(struct context *c)
+{
+
+    if (!c->c2.tls_multi)
+    {
+        return true;
+    }
+
+    if (c->c2.tls_multi->use_peer_id)
+    {
+        adjust_mtu_peerid(c);
+    }
+
+    struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
+
+    const char *ncp_cipher = get_p2p_ncp_cipher(session, c->c2.tls_multi->peer_info,
+                                                &c->options.gc);
+
+    if (ncp_cipher)
+    {
+        c->options.ciphername = ncp_cipher;
+    }
+    else if (!c->options.enable_ncp_fallback)
+    {
+        msg(D_TLS_ERRORS, "ERROR: failed to negotiate cipher with peer and "
+                          "--data-ciphers-fallback not enabled. No useable "
+                          "data channel cipher");
+        return false;
+    }
+
+    struct frame *frame_fragment = NULL;
+#ifdef ENABLE_FRAGMENT
+    if (c->options.ce.fragment)
+    {
+        frame_fragment = &c->c2.frame_fragment;
+    }
+#endif
+
+    if (!tls_session_update_crypto_params(session, &c->options, &c->c2.frame,
+                                         frame_fragment))
+    {
+        msg(D_TLS_ERRORS, "ERROR: failed to set crypto cipher");
+        return false;
+    }
+    return true;
+}
+
 /*
  * Handle non-tun-related pulled options.
  */
@@ -2325,19 +2400,7 @@ do_deferred_options(struct context *c, const unsigned int found)
         msg(D_PUSH, "OPTIONS IMPORT: peer-id set");
         c->c2.tls_multi->use_peer_id = true;
         c->c2.tls_multi->peer_id = c->options.peer_id;
-        frame_add_to_extra_frame(&c->c2.frame, +3);     /* peer-id overhead */
-        if (!c->options.ce.link_mtu_defined)
-        {
-            frame_add_to_link_mtu(&c->c2.frame, +3);
-            msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
-                EXPANDED_SIZE(&c->c2.frame));
-        }
-        else
-        {
-            msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
-                " fixed by config - reducing tun-mtu to %d, expect"
-                " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );
-        }
+        adjust_mtu_peerid(c);
     }
 
     /* process (potentially pushed) crypto options */
@@ -2856,16 +2919,21 @@ do_init_crypto_tls(struct context *c, const unsigned int flags)
     to.pull = options->pull;
     if (options->push_peer_info)        /* all there is */
     {
-        to.push_peer_info_detail = 2;
+        to.push_peer_info_detail = 3;
     }
     else if (options->pull)             /* pull clients send some details */
     {
-        to.push_peer_info_detail = 1;
+        to.push_peer_info_detail = 2;
     }
-    else                                /* default: no peer-info at all */
+    else if (options->mode == MODE_SERVER) /* server: no peer info at all */
     {
         to.push_peer_info_detail = 0;
     }
+    else                  /* default: minimal info to allow NCP in P2P mode */
+    {
+        to.push_peer_info_detail = 1;
+    }
+
 
     /* should we not xmit any packets until we get an initial
      * response from client? */
src/openvpn/options.c +4 -4
index 2f4ccaa09..9cd88a36e 100644
@@ -3078,10 +3078,6 @@ options_postprocess_cipher(struct options *o)
 {
     if (!o->pull && !(o->mode == MODE_SERVER))
     {
-        /* we are in the classic P2P mode */
-        msg( M_WARN, "Cipher negotiation is disabled since neither "
-             "P2MP client nor server mode is enabled");
-
         /* If the cipher is not set, use the old default of BF-CBC. We will
          * warn that this is deprecated on cipher initialisation, no need
          * to warn here as well */
@@ -3089,6 +3085,10 @@ options_postprocess_cipher(struct options *o)
         {
             o->ciphername = "BF-CBC";
         }
+        else
+        {
+            o->enable_ncp_fallback = true;
+        }
         return;
     }
 
src/openvpn/ssl.c +81 -39

195 lines not on this page · raw message

src/openvpn/ssl.h +5 -0
index baf3560d2..14fabcc26 100644
@@ -119,6 +119,11 @@
 /** Supports signaling keywords with AUTH_PENDING, e.g. timeout=xy */
 #define IV_PROTO_AUTH_PENDING_KW (1<<4)
 
+/** Support doing NCP in P2P mode. This mode works by both peers looking at
+ * each other's IV_ variables and deterministically deciding both on the same
+ * result. */
+#define IV_PROTO_NCP_P2P         (1<<5)
+
 /* Default field in X509 to be username */
 #define X509_USERNAME_FIELD_DEFAULT "CN"
 
src/openvpn/ssl_backend.h +1 -0
index c3d12e5be..d228c70d8 100644
@@ -390,6 +390,7 @@ void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
                                 const char *crl_file, bool crl_inline);
 
 #define EXPORT_KEY_DATA_LABEL       "EXPORTER-OpenVPN-datakeys"
+#define EXPORT_P2P_PEERID_LABEL     "EXPORTER-OpenVPN-p2p-peerid"
 /**
  * Keying Material Exporters [RFC 5705] allows additional keying material to be
  * derived from existing TLS channel. This exported keying material can then be
src/openvpn/ssl_common.h +10 -0
index 43af51ee9..bcb199176 100644
@@ -287,6 +287,16 @@ struct tls_options
     bool disable_occ;
     int mode;
     bool pull;
+    /**
+     * The detail of info we push in peer info
+     *
+     * 0 - nothing at all, P2MP server only
+     * 1 - only the most basic information to negotiate cipher and features
+     *     for P2P NCP
+     * 2 - normal setting for clients
+     * 3 - full information including "sensitive data" like IV_HWADDR
+     *     enabled by --push-peer-info
+     */
     int push_peer_info_detail;
     int transition_window;
     int handshake_window;
src/openvpn/ssl_ncp.c +145 -0

149 lines not on this page · raw message

src/openvpn/ssl_ncp.h +25 -0
index 39158a568..c02be6939 100644
@@ -32,6 +32,7 @@
 
 #include "buffer.h"
 #include "options.h"
+#include "ssl_common.h"
 
 /**
  * Returns whether the client supports NCP either by
@@ -115,4 +116,28 @@ bool tls_item_in_cipher_list(const char *item, const char *list);
  */
 #define MAX_NCP_CIPHERS_LENGTH 127
 
+/**
+ * Determines if there is common cipher of both peer by looking at the
+ * IV_CIPHER peer info. In contrast of the server mode NCP that tries to
+ * accomandate all kind of corner cases in P2P mode NCP only takes IV_CIPHER
+ * into account and falls back to previous behaviour if this fails.
+ */
+void p2p_mode_ncp(struct tls_multi *multi, struct tls_session *session);
+
+/**
+ * Determines the best common cipher from both peers IV_CIPHER lists. The
+ * first cipher from the tls-server that is also in the tls-client IV_CIPHER
+ * list will be returned. If no common cipher can be found, both peer
+ * will continue to use whatever cipher is their default and NULL will be
+ * returned.
+ *
+ * @param session       tls_session
+ * @param peer_info     peer info of the peer
+ * @param gc            gc arena that will be used to allocate the returned cipher
+ * @return              common cipher if one exist.
+ */
+const char *
+get_p2p_ncp_cipher(struct tls_session *session, const char *peer_info,
+                   struct gc_arena *gc);
+
 #endif /* ifndef OPENVPN_SSL_NCP_H */
tests/unit_tests/openvpn/test_ncp.c +11 -0
index 4077be5e8..9dcd6f0a7 100644
@@ -44,6 +44,17 @@
 const char *bf_chacha = "BF-CBC:CHACHA20-POLY1305";
 const char *aes_ciphers = "AES-256-GCM:AES-128-GCM";
 
+
+/* Define this function here as dummy since including the ssl_*.c files
+ * leads to having to include even more unrelated code */
+bool
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 void *ekm, size_t ekm_size)
+{
+    ASSERT(0);
+}
+
 static void
 test_check_ncp_ciphers_list(void **state)
 {
Signature · 1 line
2.31.1
#10 lore raw

PATCH v3 4/9 Make waiting on auth an explicit state in the context state machine

In reply to Arne Schwabe

Previously we relied on checking tls_authentication_status to check wether to determine if the context auth state is actually valid or not. This patch eliminates that check by introducing waiting on the authentication as extra state in the context auth, state machine.

Patch v3: Fix ccd config from management being ignored

---
 src/openvpn/multi.c      | 7 +------
 src/openvpn/ssl.c        | 9 ++++++++-
 src/openvpn/ssl_common.h | 1 +
 3 files changed, 10 insertions(+), 7 deletions(-)
src/openvpn/multi.c +1 -6
index 3f9710134..2cb71d851 100644
@@ -2596,11 +2596,6 @@ static const multi_client_connect_handler client_connect_handlers[] = {
 static void
 multi_connection_established(struct multi_context *m, struct multi_instance *mi)
 {
-    if (tls_authentication_status(mi->context.c2.tls_multi) != TLS_AUTHENTICATION_SUCCEEDED)
-    {
-        return;
-    }
-
     /* We are only called for the CAS_PENDING_x states, so we
      * can ignore other states here */
     bool from_deferred = (mi->context.c2.tls_multi->multi_state != CAS_PENDING);
@@ -3970,7 +3965,7 @@ management_client_auth(void *arg,
         {
             if (auth)
             {
-                if (is_cas_pending(mi->context.c2.tls_multi->multi_state))
+                if (mi->context.c2.tls_multi->multi_state == CAS_WAITING_AUTH)
                 {
                     set_cc_config(mi, cc_config);
                     cc_config_owned = false;
src/openvpn/ssl.c +8 -1
index 9f3f83f16..fd64b8d4e 100644
@@ -2810,7 +2810,7 @@ tls_process(struct tls_multi *multi,
                     if (session->opt->mode == MODE_SERVER)
                     {
                         /* On a server we continue with running connect scripts next */
-                        multi->multi_state = CAS_PENDING;
+                        multi->multi_state = CAS_WAITING_AUTH;
                     }
                     else
                     {
@@ -3136,6 +3136,13 @@ tls_multi_process(struct tls_multi *multi,
 
     enum tls_auth_status tas = tls_authentication_status(multi);
 
+    /* If we have successfully authenticated and are still waiting for the authentication to finish
+     * move the state machine for the multi context forward */
+    if (multi->multi_state == CAS_WAITING_AUTH && tas == TLS_AUTHENTICATION_SUCCEEDED)
+    {
+        multi->multi_state = CAS_PENDING;
+    }
+
     /*
      * If lame duck session expires, kill it.
      */
src/openvpn/ssl_common.h +1 -0
index 8a65ab984..66700bf68 100644
@@ -511,6 +511,7 @@ struct tls_session
  * connect scripts/plugins */
 enum multi_status {
     CAS_NOT_CONNECTED,
+    CAS_WAITING_AUTH,               /**< TLS connection established but deferred auth not finished */
     CAS_PENDING,
     CAS_PENDING_DEFERRED,
     CAS_PENDING_DEFERRED_PARTIAL,   /**< at least handler succeeded, no result yet*/
Signature · 1 line
2.31.1
#11 lore raw

PATCH v4 4/9 Make waiting on auth an explicit state in the context state machine

In reply to Arne Schwabe

Previously we relied on checking tls_authentication_status to check wether to determine if the context auth state is actually valid or not. This patch eliminates that check by introducing waiting on the authentication as extra state in the context auth, state machine.

Patch v3: Fix ccd config from management being ignored Patch v4: Fix race condition, we need to accept the config from
management if we are in CAS_WAITING_AUTH or earlier states and not just in CAS_WAITING_AUTH state

---
 src/openvpn/multi.c      | 7 +------
 src/openvpn/ssl.c        | 9 ++++++++-
 src/openvpn/ssl_common.h | 1 +
 3 files changed, 10 insertions(+), 7 deletions(-)
src/openvpn/multi.c +1 -6
index 3f9710134..eada7e155 100644
@@ -2596,11 +2596,6 @@ static const multi_client_connect_handler client_connect_handlers[] = {
 static void
 multi_connection_established(struct multi_context *m, struct multi_instance *mi)
 {
-    if (tls_authentication_status(mi->context.c2.tls_multi) != TLS_AUTHENTICATION_SUCCEEDED)
-    {
-        return;
-    }
-
     /* We are only called for the CAS_PENDING_x states, so we
      * can ignore other states here */
     bool from_deferred = (mi->context.c2.tls_multi->multi_state != CAS_PENDING);
@@ -3970,7 +3965,7 @@ management_client_auth(void *arg,
         {
             if (auth)
             {
-                if (is_cas_pending(mi->context.c2.tls_multi->multi_state))
+                if (mi->context.c2.tls_multi->multi_state <= CAS_WAITING_AUTH)
                 {
                     set_cc_config(mi, cc_config);
                     cc_config_owned = false;
src/openvpn/ssl.c +8 -1
index 9f3f83f16..fd64b8d4e 100644
@@ -2810,7 +2810,7 @@ tls_process(struct tls_multi *multi,
                     if (session->opt->mode == MODE_SERVER)
                     {
                         /* On a server we continue with running connect scripts next */
-                        multi->multi_state = CAS_PENDING;
+                        multi->multi_state = CAS_WAITING_AUTH;
                     }
                     else
                     {
@@ -3136,6 +3136,13 @@ tls_multi_process(struct tls_multi *multi,
 
     enum tls_auth_status tas = tls_authentication_status(multi);
 
+    /* If we have successfully authenticated and are still waiting for the authentication to finish
+     * move the state machine for the multi context forward */
+    if (multi->multi_state == CAS_WAITING_AUTH && tas == TLS_AUTHENTICATION_SUCCEEDED)
+    {
+        multi->multi_state = CAS_PENDING;
+    }
+
     /*
      * If lame duck session expires, kill it.
      */
src/openvpn/ssl_common.h +1 -0
index 8a65ab984..66700bf68 100644
@@ -511,6 +511,7 @@ struct tls_session
  * connect scripts/plugins */
 enum multi_status {
     CAS_NOT_CONNECTED,
+    CAS_WAITING_AUTH,               /**< TLS connection established but deferred auth not finished */
     CAS_PENDING,
     CAS_PENDING_DEFERRED,
     CAS_PENDING_DEFERRED_PARTIAL,   /**< at least handler succeeded, no result yet*/
Signature · 1 line
2.31.1
Acked-by on v2 1/9
#61 lore raw
In reply to Arne Schwabe

Hi,

Quoted 11 lines · Arne Schwabe

The auth-token check is tied to the username/password that is coming via a specific SSL session, so keep the state also in the key_state structure.

This also ensures the auth_token_state is always set to 0 on a new session since we clear the key_state object at the start of a new SSL session.

This is a prerequisite patch to fix 2020-15078 in the following two commits.

Quoted 6 lines

This also applies the changes to the auth_token_test.c. The change of tls_session to a pointer is necessary since before that we had tls_session not tied to the multi and had two tls_session used in the test. One implicitly in tls_multi and one explicit one. Merge these to one.

Looks good and does what it says. The key-state object is initialized by key_state_init() which wipes the entire thing before setting fields, therefore the auth-token-flags are indeed erased as expected during the key-state life cycle.

No functional change, as expected.

Compile zoo is happy.

Basic connectivity tests with auth-user-pass along with auth-gen-token have worked fine, including renegotiation.

Signature · 1 line
Antonio Quartulli
#2 lore raw

Re: [Openvpn-devel] [PATCH v2 2/9] Implement auth-token-user

In reply to Arne Schwabe

Hi,

Quoted 10 lines · Arne Schwabe

When not using username and password (i.e. auth-user-pass) it can still make to provide the client with an auth-token, e.g. for allowing a session to continue after a reconnect without requiring 2FA again.

However, without --auth-user-pass openvpn does not have a username and will ignore any pushed auth-token command.

This patch adds support for auth-token-user to set the username that should be used for auth-token

Quoted 6 lines

The spec of using auth-token-user base64-encoded-user are the ones that OpenVPN3 already implements.

Patch V2: Improve style, fix comments and commit message

This patch hasn't changed since the last time it was on the mailing list (and I acked it), so the same goes for this copy.

@Arne I have a new question though: what is expected to happen is the --auth-token-user is specified in the global config?

Is the same user supposed to be used with every client? Or is it just ignored?

I am testing this case and I don't see the user being pushed to the client.

Cheers,

Signature · 1 line
Antonio Quartulli
Acked-by on v2 3/9
#7 lore raw

Re: [Openvpn-devel] [PATCH v2 3/9] Add connection_established as state in tls_multi->context_auth

In reply to Arne Schwabe

Hi,

Quoted 9 lines · Arne Schwabe

the socket_info->connection_establish is set through link_socket_set_outgoing_addr when we reach FULL_SYNC. This patch introduces a new state in context_auth that replaces the connection_established state for TLS connections. This make the state machine easier to understand.

Patch v2: fix p2p mode server without (without ncp)

Compile zoo is happy.

Performed various tests, including:
* classic server/client
* p2p+tls with ncp
* p2p+tls without ncp

All passed and renegotiation also worked as expected.

The patch looks sane (already reviewed v1 and the added change makes sense) and it's a reasonable step forward towards making the state machine simpler to understand.

Signature · 1 line
Antonio Quartulli
#3 lore raw

Re: [Openvpn-devel] [PATCH v2 2/9] Implement auth-token-user

In reply to Antonio Quartulli

Am 11.06.21 um 02:41 schrieb Antonio Quartulli:

Quoted 23 lines

Hi,

Quoted 10 lines · Arne Schwabe

When not using username and password (i.e. auth-user-pass) it can still make to provide the client with an auth-token, e.g. for allowing a session to continue after a reconnect without requiring 2FA again.

However, without --auth-user-pass openvpn does not have a username and will ignore any pushed auth-token command.

This patch adds support for auth-token-user to set the username that should be used for auth-token

Quoted 6 lines

The spec of using auth-token-user base64-encoded-user are the ones that OpenVPN3 already implements.

Patch V2: Improve style, fix comments and commit message

This patch hasn't changed since the last time it was on the mailing list (and I acked it), so the same goes for this copy.

Quoted 8 lines

@Arne I have a new question though: what is expected to happen is the --auth-token-user is specified in the global config?

Is the same user supposed to be used with every client? Or is it just ignored?

I am testing this case and I don't see the user being pushed to the client.

It is probably the same as with auth-token itself. OpenVPN will pick it up and use it but most times it is not every useful as auth-token should be pushed from the server. It is an artefact from how we parse things.

Arne

Acked-by on v4 4/9
#12 lore raw

Re: [Openvpn-devel] [PATCH v4 4/9] Make waiting on auth an explicit state in the context state machine

In reply to Arne Schwabe

Hi,

Quoted 11 lines · Arne Schwabe

Previously we relied on checking tls_authentication_status to check wether to determine if the context auth state is actually valid or not. This patch eliminates that check by introducing waiting on the authentication as extra state in the context auth, state machine.

Patch v3: Fix ccd config from management being ignored Patch v4: Fix race condition, we need to accept the config from
management if we are in CAS_WAITING_AUTH or earlier states and not just in CAS_WAITING_AUTH state

This patch gets an ACK from me because all my tests have passed and I find the code reasonable.

My compile zoo was happy too.

My tests included client/server, with auth, with deferred auth, p2p.

I have not tested this patch using the mgmt interface.

From now on, when Acking a patch I will imply that:
* my GitLab CI is all green with this patch applied;
* the patch compiled against mbedtls (various versions), openssl (various versions), libressl (various versions), wolfssl (master branch).

This way I don't have to talk about my compile zoo every time :-)

Signature · 1 line
Antonio Quartulli
#4 lore raw

Re: [Openvpn-devel] [PATCH v2 2/9] Implement auth-token-user

In reply to Arne Schwabe

Hi,

Quoted 30 lines · Arne Schwabe

Am 11.06.21 um 02:41 schrieb Antonio Quartulli:

Quoted 29 lines

Hi,

Quoted 10 lines · Arne Schwabe

When not using username and password (i.e. auth-user-pass) it can still make to provide the client with an auth-token, e.g. for allowing a session to continue after a reconnect without requiring 2FA again.

However, without --auth-user-pass openvpn does not have a username and will ignore any pushed auth-token command.

This patch adds support for auth-token-user to set the username that should be used for auth-token

Quoted 6 lines

The spec of using auth-token-user base64-encoded-user are the ones that OpenVPN3 already implements.

Patch V2: Improve style, fix comments and commit message

This patch hasn't changed since the last time it was on the mailing list (and I acked it), so the same goes for this copy.

@Arne I have a new question though: what is expected to happen is the --auth-token-user is specified in the global config?

Is the same user supposed to be used with every client? Or is it just ignored?

Quoted 7 lines
Quoted 2 lines

I am testing this case and I don't see the user being pushed to the client.

It is probably the same as with auth-token itself. OpenVPN will pick it up and use it but most times it is not every useful as auth-token should be pushed from the server. It is an artefact from how we parse things.

Makes sense - it is jus interpreted locally, but there is not much sense.

This said, the rest looks good.

Signature · 1 line
Antonio Quartulli
#15 lore raw

Re: [Openvpn-devel] [PATCH v2 5/9] Extracting key_state deferred auth status update into function

In reply to Arne Schwabe

Hi,

Quoted 44 lines · Arne Schwabe

This extract the update of a deferred key status into into own function.

Patch v2: Do not ignore auth_deferred_expire. Minor format changes.

---
 src/openvpn/ssl_verify.c | 96 ++++++++++++++++++++++++++--------------
 1 file changed, 62 insertions(+), 34 deletions(-)
src/openvpn/ssl_verify.c +26 -0
index 7992a6eb9..455a5cd1b 100644
@@ -1073,6 +1073,60 @@ key_state_test_auth_control_file(struct auth_deferred_status *ads, bool cached)
     return ACF_DISABLED;
 }
 
+/**
+ * This method takes a key_state and if updates the state
+ * of the key if it is deferred.
+ * @param cached    If auth control files should be tried to be opened or th
+ *                  cached results should be used
+ * @param ks        The key_state to update
+ */
+static void
+update_key_auth_status(bool cached, struct key_state *ks)
+{
+    if (ks->authenticated == KS_AUTH_FALSE)
+    {
+        return;
+    }
+    else
+    {
+        enum auth_deferred_result auth_plugin = ACF_DISABLED;
+        enum auth_deferred_result auth_script = ACF_DISABLED;
+        enum auth_deferred_result auth_man = ACF_DISABLED;
+        auth_plugin = key_state_test_auth_control_file(&ks->plugin_auth, cached);
+        auth_script = key_state_test_auth_control_file(&ks->script_auth, cached);
+#ifdef ENABLE_MANAGEMENT
+        auth_man = man_def_auth_test(ks);
+#endif
+        ASSERT(auth_plugin < 4 && auth_script < 4 && auth_man < 4);
+

src/openvpn/ssl_verify.c key_state_test_auth_control_file(struct auth_deferred_status *ads, bool cached) · line 1111

Quoted 10 lines
src/openvpn/ssl_verify.c +10 -0
+        if (auth_plugin == ACF_FAILED || auth_script == ACF_FAILED
+           || auth_man == ACF_FAILED)
+        {
+            ks->authenticated = KS_AUTH_FALSE;
+            return;
+        }
+        else if (auth_plugin == ACF_PENDING || auth_script == ACF_PENDING
+                 || auth_man == ACF_PENDING)
+        {
+            if (now > ks->auth_deferred_expire)

To be 100% semantically the same of the code we have now this comparison should be '>=' - just for consistency I'd change it.

src/openvpn/ssl_verify.c key_state_test_auth_control_file(struct auth_deferred_status *ads, bool cached) · line 1116

Quoted 5 lines
src/openvpn/ssl_verify.c +5 -0
+            {
+                /* Window to authenticate the key has expired, mark
+                 * the key as unauthenticated */
+                ks->authenticated = KS_AUTH_FALSE;
+            }

If the if-condition above is false, we assume that authenticated is KS_AUTH_DEFERRED. Can we safely rely on this assumption? I could not find anywhere in the code an explicit link between KS_AUTH_DEFERRED and ACF_PENDING (actually I could not find anywhere setting the value ACF_PENDING).

Quoted 62 lines
src/openvpn/ssl_verify.c +16 -32
+        }
+        else
+        {
+            /* all auth states (auth_plugin, auth_script, auth_man)
+             * are either ACF_DISABLED or ACF_SUCCEDED now, which
+             * translates to "not checked" or "auth succeeded"
+             */
+            ks->authenticated = KS_AUTH_TRUE;
+        }
+    }
+}
+
+
 /**
  * The minimum times to have passed to update the cache. Older versions
  * of OpenVPN had code path that did not do any caching, so we start
@@ -1115,46 +1169,20 @@ tls_authentication_status(struct tls_multi *multi)
         if (TLS_AUTHENTICATED(multi, ks))
         {
             active++;
+            update_key_auth_status(cached, ks);
+
             if (ks->authenticated == KS_AUTH_FALSE)
             {
                 failed_auth = true;
             }
-            else
+            else if (ks->authenticated == KS_AUTH_DEFERRED)
             {
-                enum auth_deferred_result auth_plugin = ACF_DISABLED;
-                enum auth_deferred_result auth_script = ACF_DISABLED;
-                enum auth_deferred_result auth_man = ACF_DISABLED;
-                auth_plugin = key_state_test_auth_control_file(&ks->plugin_auth, cached);
-                auth_script = key_state_test_auth_control_file(&ks->script_auth, cached);
-#ifdef ENABLE_MANAGEMENT
-                auth_man = man_def_auth_test(ks);
-#endif
-                ASSERT(auth_plugin < 4 && auth_script < 4 && auth_man < 4);
 
-                if (auth_plugin == ACF_FAILED || auth_script == ACF_FAILED
-                   || auth_man == ACF_FAILED)
-                {
-                    ks->authenticated = KS_AUTH_FALSE;
-                    failed_auth = true;
-                }
-                else if (auth_plugin == ACF_PENDING
-                         || auth_script == ACF_PENDING
-                         || auth_man == ACF_PENDING)
-                {
-                    if (now < ks->auth_deferred_expire)
-                    {
-                        deferred = true;
-                    }
-                }
-                else
-                {
-                    /* all auth states (auth_plugin, auth_script, auth_man)
-                     * are either ACF_DISABLED or ACF_SUCCEDED now, which
-                     * translates to "not checked" or "auth succeeded"
-                     */
-                    success = true;

src/openvpn/ssl_verify.c tls_authentication_status(struct tls_multi *multi) · line 1188

Quoted 10 lines
src/openvpn/ssl_verify.c +5 -2
-                    ks->authenticated = KS_AUTH_TRUE;
-                }
+                deferred = true;
+            }
+            else if (ks->authenticated == KS_AUTH_TRUE)
+            {
+                success = true;
             }
         }
     }

Other that that, the patch looks good and passed all my tests. So, despite my doubts as reported above, I could not hit any issue after applying this patch.

Tested with deferred auth, client/server and p2p.

Regards,

Signature · 1 line
Antonio Quartulli
#16 lore raw

Re: [Openvpn-devel] [PATCH v2 5/9] Extracting key_state deferred auth status update into function

Hi,

Quoted 67 lines · Antonio Quartulli

Hi,

Quoted 44 lines · Arne Schwabe

This extract the update of a deferred key status into into own function.

Patch v2: Do not ignore auth_deferred_expire. Minor format changes.

---
 src/openvpn/ssl_verify.c | 96 ++++++++++++++++++++++++++--------------
 1 file changed, 62 insertions(+), 34 deletions(-)
src/openvpn/ssl_verify.c +26 -0
index 7992a6eb9..455a5cd1b 100644
@@ -1073,6 +1073,60 @@ key_state_test_auth_control_file(struct auth_deferred_status *ads, bool cached)
     return ACF_DISABLED;
 }
 
+/**
+ * This method takes a key_state and if updates the state
+ * of the key if it is deferred.
+ * @param cached    If auth control files should be tried to be opened or th
+ *                  cached results should be used
+ * @param ks        The key_state to update
+ */
+static void
+update_key_auth_status(bool cached, struct key_state *ks)
+{
+    if (ks->authenticated == KS_AUTH_FALSE)
+    {
+        return;
+    }
+    else
+    {
+        enum auth_deferred_result auth_plugin = ACF_DISABLED;
+        enum auth_deferred_result auth_script = ACF_DISABLED;
+        enum auth_deferred_result auth_man = ACF_DISABLED;
+        auth_plugin = key_state_test_auth_control_file(&ks->plugin_auth, cached);
+        auth_script = key_state_test_auth_control_file(&ks->script_auth, cached);
+#ifdef ENABLE_MANAGEMENT
+        auth_man = man_def_auth_test(ks);
+#endif
+        ASSERT(auth_plugin < 4 && auth_script < 4 && auth_man < 4);
+

src/openvpn/ssl_verify.c key_state_test_auth_control_file(struct auth_deferred_status *ads, bool cached) · line 1111

Quoted 10 lines
src/openvpn/ssl_verify.c +10 -0
+        if (auth_plugin == ACF_FAILED || auth_script == ACF_FAILED
+           || auth_man == ACF_FAILED)
+        {
+            ks->authenticated = KS_AUTH_FALSE;
+            return;
+        }
+        else if (auth_plugin == ACF_PENDING || auth_script == ACF_PENDING
+                 || auth_man == ACF_PENDING)
+        {
+            if (now > ks->auth_deferred_expire)

To be 100% semantically the same of the code we have now this comparison should be '>=' - just for consistency I'd change it.

src/openvpn/ssl_verify.c key_state_test_auth_control_file(struct auth_deferred_status *ads, bool cached) · line 1116

Quoted 5 lines
src/openvpn/ssl_verify.c +5 -0
+            {
+                /* Window to authenticate the key has expired, mark
+                 * the key as unauthenticated */
+                ks->authenticated = KS_AUTH_FALSE;
+            }
Quoted 5 lines

If the if-condition above is false, we assume that authenticated is KS_AUTH_DEFERRED. Can we safely rely on this assumption? I could not find anywhere in the code an explicit link between KS_AUTH_DEFERRED and ACF_PENDING (actually I could not find anywhere setting the value ACF_PENDING).

self-answer: when ks is initialized it is zero'd. ACF_PENDING is zero so it's implicitly assigned until further change.

For this reason the assumption here is correct.

@Gert: could you apply the '>' -> '>=' ont he fly?

For me the rest looks good.

Signature · 1 line
Antonio Quartulli
Acked-by on v2 6/9
#19 lore raw

Re: [Openvpn-devel] [PATCH v2 6/9] Introduce S_GENERATED_KEYS state and generate keys only when authenticated

In reply to Arne Schwabe

Hi,

Quoted 136 lines · Arne Schwabe

Since generating data channel keys does not happen when we have reach the S_ACTIVE/S_GOT_KEY state anymore like it used to be before NCP, the state that data channel keys deserves its own state in the TLS session state machine.

The changes done by this commit are rather intrusive since they move the key generation to a completely different place and also rely on the state machine to decide if keys should be generated rather than on the complicated conditions that were implemented in the key_method_2_write/read methods.

A (intended) side effect of this change is that sessions that are still in deferred state (ks->authenticated == KS_DEFERRED) will not have data channel keys generated. This avoids corner cases where a not fully authenticated sessions might leak data.

Patch v2: rebased

---
 src/openvpn/forward.h    |  2 +-
 src/openvpn/init.c       |  1 +
 src/openvpn/ssl.c        | 89 +++++++++++++++++-----------------------
 src/openvpn/ssl.h        | 10 +++++
 src/openvpn/ssl_common.h |  9 +++-
 5 files changed, 57 insertions(+), 54 deletions(-)
src/openvpn/forward.h +1 -1
index 3461e6422..b8760099e 100644
@@ -450,7 +450,7 @@ connection_established(struct context *c)
 {
     if (c->c2.tls_multi)
     {
-        return c->c2.tls_multi->multi_state >= CAS_CONNECT_DONE;
+        return c->c2.tls_multi->multi_state >= CAS_WAITING_OPTIONS_IMPORT;
     }
     else
     {
src/openvpn/init.c +1 -0
index 49c742928..4335d4870 100644
@@ -2202,6 +2202,7 @@ do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
         }
 
         c->c2.do_up_ran = true;
+        c->c2.tls_multi->multi_state = CAS_CONNECT_DONE;
     }
     return true;
 }
src/openvpn/ssl.c +8 -33
index fd64b8d4e..b28d8edf8 100644
@@ -788,6 +788,9 @@ state_name(int state)
         case S_ERROR:
             return "S_ERROR";
 
+        case S_GENERATED_KEYS:
+            return "S_GENERATED_KEYS";
+
         default:
             return "S_???";
     }
@@ -1840,13 +1843,13 @@ key_ctx_update_implicit_iv(struct key_ctx *ctx, uint8_t *key, size_t key_len)
  * This erases the source material used to generate the data channel keys, and
  * can thus be called only once per session.
  */
-static bool
+bool
 tls_session_generate_data_channel_keys(struct tls_session *session)
 {
     bool ret = false;
     struct key_state *ks = &session->key[KS_PRIMARY];   /* primary key */
 
-    if (ks->authenticated == KS_AUTH_FALSE)
+    if (ks->authenticated <= KS_AUTH_FALSE)
     {
         msg(D_TLS_ERRORS, "TLS Error: key_state not authenticated");
         goto cleanup;
@@ -1862,6 +1865,9 @@ tls_session_generate_data_channel_keys(struct tls_session *session)
     tls_limit_reneg_bytes(session->opt->key_type.cipher,
                           &session->opt->renegotiate_bytes);
 
+    /* set the state of the keys for the session to generated */
+    ks->state = S_GENERATED_KEYS;
+
     ret = true;
 cleanup:
     secure_memzero(ks->key_src, sizeof(*ks->key_src));
@@ -2375,31 +2381,6 @@ key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls_sessi
         goto error;
     }
 
-    /*
-     * Generate tunnel keys if we're a TLS server.
-     *
-     * If we're a p2mp server to allow NCP, the first key
-     * generation is postponed until after the connect script finished and the
-     * NCP options can be processed. Since that always happens at after connect
-     * script options are available the CAS_CONNECT_DONE status is identical to
-     * NCP options are processed and do not wait for NCP being finished.
-     */
-    if (ks->authenticated > KS_AUTH_FALSE && session->opt->server
-        && ((session->opt->mode == MODE_SERVER && multi->multi_state >= CAS_CONNECT_DONE)
-            || (session->opt->mode == MODE_POINT_TO_POINT && !session->opt->pull)))
-    {
-        /* if key_id >= 1, is a renegotiation, so we use the already established
-         * parameters and do not need to delay anything. */
-
-        /* key-id == 0 and multi_state >= CAS_CONNECT_DONE is a special case of
-         * the server reusing the session of a reconnecting client. */
-        if (!tls_session_generate_data_channel_keys(session))
-        {
-            msg(D_TLS_ERRORS, "TLS Error: server generate_key_expansion failed");
-            goto error;
-        }
-    }
-
     return true;
 
 error:
@@ -2599,21 +2580,7 @@ key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_sessio
 
         setenv_del(session->opt->es, "exported_keying_material");
     }
-
-    /*
-     * Generate tunnel keys if we're a client.
-     * If --pull is enabled, the first key generation is postponed until after the
-     * pull/push, so we can process pushed cipher directives.
-     */

src/openvpn/ssl.c key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_sessio · line 2583

Quoted 10 lines
src/openvpn/ssl.c +1 -9
-    if (!session->opt->server && (!session->opt->pull || ks->key_id > 0))
-    {
-        if (!tls_session_generate_data_channel_keys(session))
-        {
-            msg(D_TLS_ERRORS, "TLS Error: client generate_key_expansion failed");
-            goto error;
-        }
-    }
-
+    

^^ trailing spaces

Quoted 17 lines
src/openvpn/ssl.c +2 -1
     gc_free(&gc);
     return true;
 
@@ -2815,7 +2782,7 @@ tls_process(struct tls_multi *multi,
                     else
                     {
                         /* Skip the connect script related states */
-                        multi->multi_state = CAS_CONNECT_DONE;
+                        multi->multi_state = CAS_WAITING_OPTIONS_IMPORT;
                     }
                 }
 
@@ -3138,6 +3105,27 @@ tls_multi_process(struct tls_multi *multi,
 
     /* If we have successfully authenticated and are still waiting for the authentication to finish
      * move the state machine for the multi context forward */
+

src/openvpn/ssl.c tls_multi_process(struct tls_multi *multi, · line 3118

Quoted 10 lines
src/openvpn/ssl.c +10 -0
+    if (multi->multi_state >= CAS_CONNECT_DONE)
+    {
+        for (int i = 0; i < TM_SIZE; ++i)
+        {
+            struct tls_session *session = &multi->session[i];
+            struct key_state *ks = &session->key[KS_PRIMARY];
+
+            if (ks->state == S_ACTIVE && ks->authenticated == KS_AUTH_TRUE)
+            {
+                /* This will ks->state from S_ACTIVE to S_GENERATED_KEYS */

word missing: "switch" ?

Quoted 14 lines
src/openvpn/ssl.c +10 -0
+                if (!tls_session_generate_data_channel_keys(session))
+                {
+                    msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
+                    ks->authenticated = KS_AUTH_FALSE;
+                    ks->state = S_ERROR;
+                }
+            }
+        }
+    }
+
     if (multi->multi_state == CAS_WAITING_AUTH && tas == TLS_AUTHENTICATION_SUCCEEDED)
     {
         multi->multi_state = CAS_PENDING;

src/openvpn/ssl.c handle_data_channel_packet(struct tls_multi *multi, · line 3237

Quoted 7 lines
src/openvpn/ssl.c +1 -3
@@ -3246,11 +3234,10 @@ handle_data_channel_packet(struct tls_multi *multi,
          * passive side is the server which only listens for the connections, the
          * active side is the client which initiates connections).
          */
-        if (TLS_AUTHENTICATED(multi, ks)
-            && key_id == ks->key_id
-            && (ks->authenticated == KS_AUTH_TRUE)
+        if (ks->state >= S_GENERATED_KEYS  && key_id == ks->key_id

extra space after S_GENERATED_KEYS

Quoted 65 lines
src/openvpn/ssl.c +6 -5
             && (floated || link_socket_actual_match(from, &ks->remote_addr)))
         {
+            ASSERT(ks->authenticated == KS_AUTH_TRUE);
             if (!ks->crypto_options.key_ctx_bi.initialized)
             {
                 msg(D_MULTI_DROPPED,
@@ -3572,8 +3559,7 @@ tls_pre_decrypt(struct tls_multi *multi,
         /*
          * Remote is requesting a key renegotiation
          */
-        if (op == P_CONTROL_SOFT_RESET_V1
-            && TLS_AUTHENTICATED(multi, ks))
+        if (op == P_CONTROL_SOFT_RESET_V1 && TLS_AUTHENTICATED(multi, ks))
         {
             if (!read_control_auth(buf, &session->tls_wrap, from,
                                    session->opt))
@@ -3834,10 +3820,11 @@ struct key_state *tls_select_encryption_key(struct tls_multi *multi)
     for (int i = 0; i < KEY_SCAN_SIZE; ++i)
     {
         struct key_state *ks = get_key_scan(multi, i);
-        if (ks->state >= S_ACTIVE
-            && ks->authenticated == KS_AUTH_TRUE
-            && ks->crypto_options.key_ctx_bi.initialized)
+        if (ks->state >= S_GENERATED_KEYS)
         {
+            ASSERT(ks->authenticated == KS_AUTH_TRUE);
+            ASSERT(ks->crypto_options.key_ctx_bi.initialized);
+
             if (!ks_select)
             {
                 ks_select = ks;
src/openvpn/ssl.h +10 -0
index 81cc22131..baf3560d2 100644
@@ -612,4 +612,14 @@ show_available_tls_ciphers(const char *cipher_list,
                            const char *cipher_list_tls13,
                            const char *tls_cert_profile);
 
+
+/**
+ * Generate data channel keys for the supplied TLS session.
+ *
+ * This erases the source material used to generate the data channel keys, and
+ * can thus be called only once per session.
+ */
+bool
+tls_session_generate_data_channel_keys(struct tls_session *session);
+
 #endif /* ifndef OPENVPN_SSL_H */
src/openvpn/ssl_common.h +2 -1
index 66700bf68..928e80929 100644
@@ -64,7 +64,8 @@
  *      material.
  *   -# \c S_GOT_KEY, have received remote part of \c key_source2 random
  *      material.
- *   -# \c S_ACTIVE, normal operation
+ *   -# \c S_ACTIVE, control channel successfully established
+ *   -# \c S_GENERATED_KEYS, the
  *
  * Servers follow the same order, except for \c S_SENT_KEY and \c
  * S_GOT_KEY being reversed, because the server first receives the

src/openvpn/ssl_common.h line 97

Quoted 6 lines
src/openvpn/ssl_common.h +2 -1
@@ -92,7 +93,10 @@
 #define S_ACTIVE          6     /**< Operational \c key_state state
                                  *   immediately after negotiation has
                                  *   completed while still within the
-                                 *   handshake window. */
+                                 *   handshake window, deferred auth, client
+                                 *   connect and can still

typ0: "and can" -> "can"

src/openvpn/ssl_common.h enum multi_status { · line 523

Quoted 10 lines
src/openvpn/ssl_common.h +3 -0
+                                 *   be pending. */
+#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated */
 /* Note that earlier versions also had a S_OP_NORMAL state that was
  * virtually identical with S_ACTIVE and the code still assumes everything
  * >= S_ACTIVE to be fully operational */
@@ -516,6 +520,7 @@ enum multi_status {
     CAS_PENDING_DEFERRED,
     CAS_PENDING_DEFERRED_PARTIAL,   /**< at least handler succeeded, no result yet*/
     CAS_FAILED,
+    CAS_WAITING_OPTIONS_IMPORT,     /**< client with pull or p2p waiting for first time options import */

do we wait for "options" in p2p mode? I thought in client/server we could have "pull" enabled, no?

src/openvpn/ssl_common.h enum multi_status { · line 526

Quoted 4 lines
src/openvpn/ssl_common.h +0 -0
     CAS_CONNECT_DONE,
 };
 

Due to your previous simplifications, this change is easier to digest.

However, I wonder if it was easier to split the introduction of CAS_WAITING_OPTIONS_IMPORT in a different patch?

This said, keeping everything in one patch is still reasonable - mostly matter of taste I think.

To me this looks like yet another nice simplification which helps making the whole flow easier to understand.

I tried to break the key generation in various ways, but I was unable to do so.

So far it worked fine with deferred auth, without it, with client/server and p2p mode as well.

Even though this patch is intrusive I find it very reasonable.

Signature · 1 line
Antonio Quartulli
#5 lore raw

[Openvpn-devel] [PATCH applied] Re: Implement auth-token-user

In reply to Arne Schwabe

Your patch has been applied to the master and release/2.5 branch (long-term compat).

I'm not exactly happy with this patch for a number of reasons, which is why I was a bit reluctant to merge it. It does what it says on the lid, the code is safe, and it got ACKs. So, merging.

That said, this is sort of a special case for a special case that seems to have come out of OpenVPN Inc product marketing (do 2FA outside OpenVPN and then notice that this doesn't actually work) - and it makes the code even more complex by having this extra boolean to check in a number of places... (a somewhat simpler approach could be to have a "default username" - <NOT-SET> or such - and use that if up is not defined)

Anyway. I have tested the "does auth-token, on reneg, and token expiry still work?" bit fairly thoroughly - as this is code that took us quite a while to get right - and it seems to still work. I have not tested actually pushing "auth-token-user bla", but I have been told Heiko and David have tested that path in earnest.

I have also taken the liberty to clean up the comments quite a bit (seems Richard did not like this patch and did not spell-check :-) ).

commit b398aa37ca309948b481401adf0074ea5589eb2d (master) commit d38d61111d08558e2f52cc9bcdc928ca9c4fca61 (release/2.5)

Author: Arne Schwabe
Date:   Thu May 20 17:11:41 2021 +0200
     Implement auth-token-user

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg22417.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#62 lore raw
In reply to Arne Schwabe

Your patch has been applied to the master branch.

I did some stare-at-code and testing of my own, and most of this patch is fairly straightforward - it's only that long because the auth-token-test module is really extensive, and due to the pointer change, lots of lines change.

Also tested with the "renegotiate, then reconnect from same port" nuisance client, and that seems to be a bit worse now (this re-introduces "we send a PUSH_REPLY right away on client-reconnect-same-port") but I understand that this is fixed in 3/9+4/9 (and verified that it is).

commit 716049923e3e70c3de938d6da5d05f529ec515b5

Author: Arne Schwabe
Date:   Thu May 20 17:11:40 2021 +0200
     Move auth_token_state from multi to key_state

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg22415.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#8 lore raw

[Openvpn-devel] [PATCH applied] Re: Add connection_established as state in tls_multi->context_auth

In reply to Arne Schwabe

Stared at the patch, seems to make sense.

Tested on the t_server test rig, and behaves nicely - both alone, and together with 4/9 (the final patch needed to fix the CVE). Test rig has p2mp and p2p servers.

Client tests also succeded (unsurprisingly).

As discussed on IRC, added refererences to CVE-2020-15078 to the commit message. Also added some comments about the CAS_* changes to the commit message, which were missing.

Your patch has been applied to the master branch.

commit d01277608a248f31df3fde1883eba6dd8d16a1e4

Author: Arne Schwabe
Date:   Thu May 20 17:11:42 2021 +0200
     Add connection_established as state in tls_multi->context_auth

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg22419.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#13 lore raw

[Openvpn-devel] [PATCH applied] Re: Make waiting on auth an explicit state in the context state machine

In reply to Arne Schwabe

Stared at the code a bit, discussed on IRC about "what state does what?"
- so this new state is "TLS is ok, waiting for (deferred) authentication" and CAS_PENDING* is "waiting for (deferred) *client-connect* things" - which MUST NOT run before authentication is finished (= CVE...).

With that explanation, the changes looks straightforward enough, with the new state added and the explanation given.

Arne also stated that a patch will come that better documents all CAS_ values.

Tested on the client side (no surprises) and on the server side test rig, with all the nasties - deferred plugin auth, deferred client connect, deferred script auth, succeeding and failing, config from ccd/ and from --client-connect scripts - and it behaved nicely.

[Note: I still have no test rig with management auth, so we need to trust the AS QA team to test all these cases...]

This still does not fix the "PUSH_REPLY is sent too quickly" CVE in all cases, it seems. But with the *next* one, it is finally fixed.

As discussed on IRC, added a note about the CVE to the commit message.

Your patch has been applied to the master branch.

commit 489c45fb373adfb22c2f1dd0a524bde17c686876

Author: Arne Schwabe
Date:   Fri Jun 4 16:39:38 2021 +0200
     Make waiting on auth an explicit state in the context state machine

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg22491.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#17 lore raw

[Openvpn-devel] [PATCH applied] Re: Extracting key_state deferred auth status update into function

In reply to Arne Schwabe

Stared at the code - it's "just moving code", though the part about "where does the KS_AUTH_DEFERRED come from?" needs a bit more digging.

The new code is slightly ugly - it's the old if/else deep nesting style, with early returns intermixed (but keeping the old else branch, so "yes, same code" is easier to see). A followup patch might want to refactor this to "consistent early return style".

Tested on the server side test rig (all OK), including deferred auth by plugin and by script.

I have adjusted the "now >= ks->auth_deferred_expire" clause as instructed and agreed on IRC, and killed a blank line.

Your patch has been applied to the master branch.

commit e55bedd4ea435f95d288e60691abc6e53b8bf014

Author: Arne Schwabe
Date:   Thu May 20 17:11:44 2021 +0200
     Extracting key_state deferred auth status update into function

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg22420.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#20 lore raw

Re: [Openvpn-devel] [PATCH v2 6/9] Introduce S_GENERATED_KEYS state and generate keys only when authenticated

In reply to Arne Schwabe

Hi,

Quoted 4 lines · Arne Schwabe

Since generating data channel keys does not happen when we have reach the S_ACTIVE/S_GOT_KEY state anymore like it used to be before NCP, the state that data channel keys deserves its own state in the TLS session state machine.

Master as of today (ccee09d1478a) + this patch crashes on p2p --secret

2021-07-02 15:06:31 us=336025 Peer Connection Initiated with [AF_INET6]::ffff:194.97.140.21:41858
2021-07-02 15:06:31 us=336099 WARNING: this configuration may cache passwords in memory -- use the auth-nocache option to prevent this
2021-07-02 15:06:31 us=336118 Initialization Sequence Completed

Program received signal SIGSEGV, Segmentation fault.
0x00005555555794c9 in do_up ([email protected]...=0x7fffffffd660, [email protected]...=false,

    [email protected]...=0) at init.c:2205
    2205            c->c2.tls_multi->multi_state = CAS_CONNECT_DONE;

(gdb) print c->c2.tls_multi
$1 = (struct tls_multi *) 0x0

I'm fairly sure it should not do that :-)

Is this fixed in 7/9...9/9? Or do we need a v3 of this one?

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]...
#21 lore raw

PATCH v3 6/9 Introduce S_GENERATED_KEYS state and generate keys only when authenticated

In reply to Arne Schwabe

Since generating data channel keys does not happen when we have reach the S_ACTIVE/S_GOT_KEY state anymore like it used to be before NCP, the state that data channel keys deserves its own state in the TLS session state machine.

The changes done by this commit are rather intrusive since they move the key generation to a completely different place and also rely on the state machine to decide if keys should be generated rather than on the complicated conditions that were implemented in the key_method_2_write/read methods.

A (intended) side effect of this change is that sessions that are still in deferred state (ks->authenticated == KS_DEFERRED) will not have data channel keys generated. This avoids corner cases where a not fully authenticated sessions might leak data.

Patch v2: rebased

Patch v3: fix crash in non TLS mode

---
 src/openvpn/forward.h    |  2 +-
 src/openvpn/init.c       |  4 ++
 src/openvpn/ssl.c        | 89 +++++++++++++++++-----------------------
 src/openvpn/ssl.h        | 10 +++++
 src/openvpn/ssl_common.h |  9 +++-
 5 files changed, 60 insertions(+), 54 deletions(-)
src/openvpn/forward.h +1 -1
index c9d9de7a4..2fb67e04c 100644
@@ -416,7 +416,7 @@ connection_established(struct context *c)
 {
     if (c->c2.tls_multi)
     {
-        return c->c2.tls_multi->multi_state >= CAS_CONNECT_DONE;
+        return c->c2.tls_multi->multi_state >= CAS_WAITING_OPTIONS_IMPORT;
     }
     else
     {
src/openvpn/init.c +4 -0
index 1c674a243..3d4ba6226 100644
@@ -2202,6 +2202,10 @@ do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
         }
 
         c->c2.do_up_ran = true;
+        if (c->c2.tls_multi)
+        {
+            c->c2.tls_multi->multi_state = CAS_CONNECT_DONE;
+        }
     }
     return true;
 }
src/openvpn/ssl.c +38 -51

157 lines not on this page · raw message

src/openvpn/ssl.h +10 -0
index 933e0559a..58b39466b 100644
@@ -612,4 +612,14 @@ show_available_tls_ciphers(const char *cipher_list,
                            const char *cipher_list_tls13,
                            const char *tls_cert_profile);
 
+
+/**
+ * Generate data channel keys for the supplied TLS session.
+ *
+ * This erases the source material used to generate the data channel keys, and
+ * can thus be called only once per session.
+ */
+bool
+tls_session_generate_data_channel_keys(struct tls_session *session);
+
 #endif /* ifndef OPENVPN_SSL_H */
src/openvpn/ssl_common.h +7 -2
index 6bfb40679..43d6276be 100644
@@ -64,7 +64,8 @@
  *      material.
  *   -# \c S_GOT_KEY, have received remote part of \c key_source2 random
  *      material.
- *   -# \c S_ACTIVE, normal operation
+ *   -# \c S_ACTIVE, control channel successfully established
+ *   -# \c S_GENERATED_KEYS, the
  *
  * Servers follow the same order, except for \c S_SENT_KEY and \c
  * S_GOT_KEY being reversed, because the server first receives the
@@ -92,7 +93,10 @@
 #define S_ACTIVE          6     /**< Operational \c key_state state
                                  *   immediately after negotiation has
                                  *   completed while still within the
-                                 *   handshake window. */
+                                 *   handshake window, deferred auth, client
+                                 *   connect and can still
+                                 *   be pending. */
+#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated */
 /* Note that earlier versions also had a S_OP_NORMAL state that was
  * virtually identical with S_ACTIVE and the code still assumes everything
  * >= S_ACTIVE to be fully operational */
@@ -516,6 +520,7 @@ enum multi_status {
     CAS_PENDING_DEFERRED,
     CAS_PENDING_DEFERRED_PARTIAL,   /**< at least handler succeeded, no result yet*/
     CAS_FAILED,
+    CAS_WAITING_OPTIONS_IMPORT,     /**< client with pull or p2p waiting for first time options import */
     CAS_CONNECT_DONE,
 };
 
Signature · 1 line
2.32.0
#22 lore raw

Re: [Openvpn-devel] [PATCH v3 6/9] Introduce S_GENERATED_KEYS state and generate keys only when authenticated

Hi,

Quoted 16 lines · Arne Schwabe

Since generating data channel keys does not happen when we have reach the S_ACTIVE/S_GOT_KEY state anymore like it used to be before NCP, the state that data channel keys deserves its own state in the TLS session state machine.

The changes done by this commit are rather intrusive since they move the key generation to a completely different place and also rely on the state machine to decide if keys should be generated rather than on the complicated conditions that were implemented in the key_method_2_write/read methods.

A (intended) side effect of this change is that sessions that are still in deferred state (ks->authenticated == KS_DEFERRED) will not have data channel keys generated. This avoids corner cases where a not fully authenticated sessions might leak data.

Quoted 7 lines

Patch v2: rebased

Patch v3: fix crash in non TLS mode

Thanks for fixing the crash. I added the basic --secret test to my suite and I could indeed see the crash when using v2 of this patch.

I can confirm that v3 is indeed fixing the crash. Classic client/server and p2p with TLS still works as expected.

Deferred auth works too.

Regards,

Signature · 1 line
Antonio Quartulli
#25 lore raw

PATCH v3 7/9 Cleanup handling of initial auth token

In reply to Arne Schwabe

This changes that auth_token_initial is set when the token is initially generated instead when pushing the token. Even I do not know anymore why I did it in this way in the first place. Also use multi->auth_token_initial as source for the sesssion ID since it should now always be available.

Since the change makes auth_token_initial always available we need to add a check to only send a PUSH reply to update the token on renegotiations. The old code relied on multi->auth_token not being set in this case.

This commit also removes the workaround for old OpenVPN clients. These were only available as commercial OpenVPN Connect client and not in use anymore.

Patch V2: rebase.
Patch V3: fix formatting, clarifying commit message, remove initial
token workaround for old v3.

---
 doc/man-sections/server-options.rst        |  4 +--
 src/openvpn/auth_token.c                   | 34 ++++++++++++----------
 src/openvpn/push.c                         |  8 -----
 src/openvpn/ssl_common.h                   |  4 +--
 src/openvpn/ssl_verify.c                   |  6 ++--
 tests/unit_tests/openvpn/test_auth_token.c |  7 +++--
 6 files changed, 32 insertions(+), 31 deletions(-)
doc/man-sections/server-options.rst +2 -2
index 047f2270f..1ab00e81b 100644
@@ -35,7 +35,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   token is reached or after not being renewed for more than 2 \*
   ``reneg-sec`` seconds. Clients will be sent renewed tokens on every TLS
   renogiation to keep the client's token updated. This is done to
-  invalidate a token if a client is disconnected for a sufficently long
+  invalidate a token if a client is disconnected for a sufficiently long
   time, while at the same time permitting much longer token lifetimes for
   active clients.
 
@@ -46,7 +46,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   When the :code:`external-auth` keyword is present the normal
   authentication method will always be called even if auth-token succeeds.
   Normally other authentications method are skipped if auth-token
-  verification suceeds or fails.
+  verification succeeds or fails.
 
   This option postpones this decision to the external authentication
   methods and checks the validity of the account and do other checks.
src/openvpn/auth_token.c +19 -15
index 0ea6d1832..a681d726f 100644
@@ -109,11 +109,11 @@ add_session_token_env(struct tls_session *session, struct tls_multi *multi,
         /*
          * No session before, generate a new session token for the new session
          */
-        if (!multi->auth_token)
+        if (!multi->auth_token_initial)
         {
             generate_auth_token(up, multi);
         }
-        session_id_source = multi->auth_token;
+        session_id_source = multi->auth_token_initial;
     }
     /*
      * In the auth-token the auth token is already base64 encoded
@@ -184,7 +184,7 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
     uint8_t sessid[AUTH_TOKEN_SESSION_ID_LEN];
 
-    if (multi->auth_token)
+    if (multi->auth_token_initial)
     {
         /* Just enough space to fit 8 bytes+ 1 extra to decode a non padded
          * base64 string (multiple of 3 bytes). 9 bytes => 12 bytes base64
@@ -192,11 +192,14 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
          */
         char old_tstamp_decode[9];
 
+        /* Make a copy of the string to not modify multi->auth_token_initial */
+        char* initial_token_copy = string_alloc(multi->auth_token_initial, &gc);
+
         /*
          * reuse the same session id and timestamp and null terminate it at
          * for base64 decode it only decodes the session id part of it
          */
-        char *old_sessid = multi->auth_token + strlen(SESSION_ID_PREFIX);
+        char *old_sessid = initial_token_copy + strlen(SESSION_ID_PREFIX);
         char *old_tsamp_initial = old_sessid + AUTH_TOKEN_SESSION_ID_LEN*8/6;
 
         old_tsamp_initial[12] = '\0';
@@ -212,10 +215,6 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
         old_tsamp_initial[0] = '\0';
         ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSION_ID_LEN)==AUTH_TOKEN_SESSION_ID_LEN);
-
-
-        /* free the auth-token, we will replace it with a new one */
-        free(multi->auth_token);
     }
     else if (!rand_bytes(sessid, AUTH_TOKEN_SESSION_ID_LEN))
     {
@@ -272,11 +271,22 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
     free(b64output);
 
+    /* free the auth-token if defined, we will replace it with a new one */
+    free(multi->auth_token);
     multi->auth_token = strdup((char *)BPTR(&session_token));
 
     dmsg(D_SHOW_KEYS, "Generated token for client: %s (%s)",
          multi->auth_token, up->username);
 
+    if (!multi->auth_token_initial)
+    {
+        /*
+         * Save the initial auth token to continue using the same session ID
+         * and timestamp in updates
+         */
+        multi->auth_token_initial = strdup(multi->auth_token);
+    }
+
     gc_free(&gc);
 }
 
@@ -353,13 +363,7 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi,
     bool in_renog_time = now >= timestamp
                          && now < timestamp + 2 * session->opt->renegotiate_seconds;
 
-    /* We could still have a client that does not update
-     * its auth-token, so also allow the initial auth-token */
-    bool initialtoken = multi->auth_token_initial
-                        && memcmp_constant_time(up->password, multi->auth_token_initial,
-                                                strlen(multi->auth_token_initial)) == 0;
-
-    if (!in_renog_time && !initialtoken)
+    if (!in_renog_time)
     {
         ret |= AUTH_TOKEN_EXPIRED;
     }
src/openvpn/push.c +0 -8
index f4957f147..53cb7ca6f 100644
@@ -527,14 +527,6 @@ prepare_auth_token_push_reply(struct tls_multi *tls_multi, struct gc_arena *gc,
         push_option_fmt(gc, push_list, M_USAGE,
                         "auth-token %s",
                         tls_multi->auth_token);
-        if (!tls_multi->auth_token_initial)
-        {
-            /*
-             * Save the initial auth token for clients that ignore
-             * the updates to the token
-             */
-            tls_multi->auth_token_initial = strdup(tls_multi->auth_token);
-        }
     }
 }
 
src/openvpn/ssl_common.h +2 -2
index 43d6276be..1914a0015 100644
@@ -597,8 +597,8 @@ struct tls_multi
                           *   user/pass authentications in this session.
                           */
     char *auth_token_initial;
-    /**< The first auth-token we sent to a client, for clients that do
-     * not update their auth-token (older OpenVPN3 core versions)
+    /**< The first auth-token we sent to a client. We use this to remember
+     * the session ID and initial timestamp when generating new auth-token.
      */
 #define  AUTH_TOKEN_HMAC_OK              (1<<0)
     /**< Auth-token sent from client has valid hmac */
src/openvpn/ssl_verify.c +4 -2
index bbb1878a3..61dde1791 100644
@@ -1639,7 +1639,9 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
          * Otherwise the auth-token get pushed out as part of the "normal"
          * push-reply
          */
-        if (multi->auth_token_initial)
+        bool is_renegotiation = session->key[KS_PRIMARY].key_id != 0;
+
+        if (multi->auth_token_initial && !is_renegotiation)
         {
             /*
              * We do not explicitly schedule the sending of the
@@ -1648,7 +1650,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
              * established and furthermore since this is called in
              * the middle of authentication, there are other messages
              * (new data channel keys) that are sent anyway and will
-             * trigger schedueling
+             * trigger scheduling
              */
             send_push_reply_auth_token(multi);
         }
tests/unit_tests/openvpn/test_auth_token.c +5 -2
index 4030052e0..a504eed91 100644
@@ -174,7 +174,10 @@ auth_token_test_timeout(void **state)
 
     now = 100000;
     generate_auth_token(&ctx->up, &ctx->multi);
+
     strcpy(ctx->up.password, ctx->multi.auth_token);
+    free(ctx->multi.auth_token_initial);
+    ctx->multi.auth_token_initial = NULL;
 
     /* No time has passed */
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
@@ -244,10 +247,10 @@ auth_token_test_known_keys(void **state)
 
     now = 0;
     /* Preload the session id so the same session id is used here */
-    ctx->multi.auth_token = strdup(now0key0);
+    ctx->multi.auth_token_initial = strdup(now0key0);
 
     /* Zero the hmac part to ensure we have a newly generated token */
-    zerohmac(ctx->multi.auth_token);
+    zerohmac(ctx->multi.auth_token_initial);
 
     generate_auth_token(&ctx->up, &ctx->multi);
 
Signature · 1 line
2.32.0
#26 lore raw

Re: [Openvpn-devel] [PATCH v3 7/9] Cleanup handling of initial auth token

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

Hi,

this is a comment about a comment which this patch is not changing but the comment is so awful I thought it best to make a note. See below.

Also, two typos. And FYI, 'anymore' ought to be 'any more'

R

Sent with ProtonMail Secure Email, which still cannot handle diffs.

‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐

Quoted 4 lines · Arne Schwabe

This changes that auth_token_initial is set when the token is initially generated instead when pushing the token. Even I do not know anymore why I did it in this way in the first place. Also use multi->auth_token_initial as source for the sesssion ID since it should

sesssion -> session

Quoted 30 lines

now always be available.

Since the change makes auth_token_initial always available we need to add a check to only send a PUSH reply to update the token on renegotiations. The old code relied on multi->auth_token not being set in this case.

This commit also removes the workaround for old OpenVPN clients. These were only available as commercial OpenVPN Connect client and not in use anymore.

Patch V2: rebase.
Patch V3: fix formatting, clarifying commit message, remove initial
token workaround for old v3.

---
 doc/man-sections/server-options.rst        |  4 +--
 src/openvpn/auth_token.c                   | 34 ++++++++++++----------
 src/openvpn/push.c                         |  8 -----
 src/openvpn/ssl_common.h                   |  4 +--
 src/openvpn/ssl_verify.c                   |  6 ++--
 tests/unit_tests/openvpn/test_auth_token.c |  7 +++--
 6 files changed, 32 insertions(+), 31 deletions(-)
doc/man-sections/server= renamed from doc/man-sections/server-options.rst +0 -1
-options.rst

index 047f2270f..1ab00e81b 100644

doc/man-sections/server-options.rst +0 -0
@@ -35,7 +35,7 @@ fast hardware. SSL/TLS authentication must be used in th=
Quoted 4 lines

is mode.
token is reached or after not being renewed for more than 2 \* ``reneg-sec`` seconds. Clients will be sent renewed tokens on every TLS renogiation to keep the client's token updated. This is done to

I know this is not in this patch but .. renogiation -> renegotiation

Quoted 55 lines
doc/man-sections/server-options.rst +1 -1
-  invalidate a token if a client is disconnected for a sufficently long
+  invalidate a token if a client is disconnected for a sufficiently long
   time, while at the same time permitting much longer token lifetimes for
   active clients.
@@ -46,7 +46,7 @@ fast hardware. SSL/TLS authentication must be used in th=

is mode.
When the :code:external-auth keyword is present the normal authentication method will always be called even if auth-token succeeds=
.
Normally other authentications method are skipped if auth-token

doc/man-sections/server-options.rst +1 -1
-  verification suceeds or fails.
+  verification succeeds or fails.
 
   This option postpones this decision to the external authentication
   methods and checks the validity of the account and do other checks.
src/openvpn/auth_token.c +0 -0
index 0ea6d1832..a681d726f 100644
@@ -109,11 +109,11 @@ add_session_token_env(struct tls_session *session, s=
 truct tls_multi *multi,
         /*
          * No session before, generate a new session token for the new se=

ssion

          */
src/openvpn/auth_token.c +3 -3
-        if (!multi->auth_token)
+        if (!multi->auth_token_initial)
         {
             generate_auth_token(up, multi);
         }
-        session_id_source =3D multi->auth_token;
+        session_id_source =3D multi->auth_token_initial;
     }
     /*
      * In the auth-token the auth token is already base64 encoded
@@ -184,7 +184,7 @@ generate_auth_token(const struct user_pass *up, struct=
 tls_multi *multi)
 
     uint8_t sessid[AUTH_TOKEN_SESSION_ID_LEN];
 
-    if (multi->auth_token)
+    if (multi->auth_token_initial)
     {
         /* Just enough space to fit 8 bytes+ 1 extra to decode a non padd=

ed
* base64 string (multiple of 3 bytes). 9 bytes =3D> 12 bytes bas=
e64

src/openvpn/auth_token.c +1 -0
@@ -192,11 +192,14 @@ generate_auth_token(const struct user_pass *up, stru=
 ct tls_multi *multi)
          */
         char old_tstamp_decode[9];
 
+        /* Make a copy of the string to not modify multi->auth_token_init=

ial */

Quoted 8 lines

+ char* initial_token_copy =3D string_alloc(multi->auth_token_initi=
al, &gc);
+
/*
* reuse the same session id and timestamp and null terminate it =
at
* for base64 decode it only decodes the session id part of it */

For the sake of readability:

/*
* reuse the same session id and timestamp and null terminate it at
* for base64 decode it only decodes the session id part of it */

What does this mean ? I can't decipher it ..

Quoted 166 lines

- char *old_sessid =3D multi->auth_token + strlen(SESSION_ID_PREFIX=
);
+ char *old_sessid =3D initial_token_copy + strlen(SESSION_ID_PREFI=
X);
char *old_tsamp_initial =3D old_sessid + AUTH_TOKEN_SESSION_ID_LE=
N*8/6;

         old_tsamp_initial[12] =3D '\0';
src/openvpn/auth_token.c +0 -4
@@ -212,10 +215,6 @@ generate_auth_token(const struct user_pass *up, struc=
 t tls_multi *multi)
 
         old_tsamp_initial[0] =3D '\0';
         ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSI=
 ON_ID_LEN)=3D=3DAUTH_TOKEN_SESSION_ID_LEN);
-
-
-        /* free the auth-token, we will replace it with a new one */
-        free(multi->auth_token);
     }

else if (!rand_bytes(sessid, AUTH_TOKEN_SESSION_ID_LEN)) {

src/openvpn/auth_token.c +11 -0
@@ -272,11 +271,22 @@ generate_auth_token(const struct user_pass *up, stru=
 ct tls_multi *multi)
 
     free(b64output);
 
+    /* free the auth-token if defined, we will replace it with a new one =
 */
+    free(multi->auth_token);
     multi->auth_token =3D strdup((char *)BPTR(&session_token));
 
     dmsg(D_SHOW_KEYS, "Generated token for client: %s (%s)",
          multi->auth_token, up->username);
 
+    if (!multi->auth_token_initial)
+    {
+        /*
+         * Save the initial auth token to continue using the same session=
 ID
+         * and timestamp in updates
+         */
+        multi->auth_token_initial =3D strdup(multi->auth_token);
+    }
+
     gc_free(&gc);

}

src/openvpn/auth_token.c +1 -7
@@ -353,13 +363,7 @@ verify_auth_token(struct user_pass *up, struct tls_mu=
 lti *multi,
     bool in_renog_time =3D now >=3D timestamp
                          && now < timestamp + 2 * session->opt->renegotia=
 te_seconds;
 
-    /* We could still have a client that does not update
-     * its auth-token, so also allow the initial auth-token */
-    bool initialtoken =3D multi->auth_token_initial
-                        && memcmp_constant_time(up->password, multi->auth=
 _token_initial,
-                                                strlen(multi->auth_token_=
 initial)) =3D=3D 0;
-
-    if (!in_renog_time && !initialtoken)
+    if (!in_renog_time)
     {
         ret |=3D AUTH_TOKEN_EXPIRED;
     }
src/openvpn/push.c +0 -8
index f4957f147..53cb7ca6f 100644
@@ -527,14 +527,6 @@ prepare_auth_token_push_reply(struct tls_multi *tls_m=
 ulti, struct gc_arena *gc,
         push_option_fmt(gc, push_list, M_USAGE,
                         "auth-token %s",
                         tls_multi->auth_token);
-        if (!tls_multi->auth_token_initial)
-        {
-            /*
-             * Save the initial auth token for clients that ignore
-             * the updates to the token
-             */
-            tls_multi->auth_token_initial =3D strdup(tls_multi->auth_toke=
 n);
-        }
     }

}

src/openvpn/ssl_common.h +1 -2
index 43d6276be..1914a0015 100644
@@ -597,8 +597,8 @@ struct tls_multi
                           *   user/pass authentications in this session.
                           */
     char *auth_token_initial;
-    /**< The first auth-token we sent to a client, for clients that do
-     * not update their auth-token (older OpenVPN3 core versions)
+    /**< The first auth-token we sent to a client. We use this to remembe=

r
+ * the session ID and initial timestamp when generating new auth-toke=
n.

      */
 #define  AUTH_TOKEN_HMAC_OK              (1<<0)
     /**< Auth-token sent from client has valid hmac */
src/openvpn/ssl_verify.c +0 -0
index bbb1878a3..61dde1791 100644
@@ -1639,7 +1639,9 @@ verify_user_pass(struct user_pass *up, struct tls_mu=
 lti *multi,
          * Otherwise the auth-token get pushed out as part of the "normal=

"
* push-reply
*/

src/openvpn/ssl_verify.c +4 -2
-        if (multi->auth_token_initial)
+        bool is_renegotiation =3D session->key[KS_PRIMARY].key_id !=3D 0;
+
+        if (multi->auth_token_initial && !is_renegotiation)
         {
             /*
              * We do not explicitly schedule the sending of the
@@ -1648,7 +1650,7 @@ verify_user_pass(struct user_pass *up, struct tls_mu=
 lti *multi,
              * established and furthermore since this is called in
              * the middle of authentication, there are other messages
              * (new data channel keys) that are sent anyway and will
-             * trigger schedueling
+             * trigger scheduling
              */
             send_push_reply_auth_token(multi);
         }
tests/unit_tests= renamed from tests/unit_tests/openvpn/test_auth_token.c +0 -0

/openvpn/test_auth_token.c
index 4030052e0..a504eed91 100644

tests/unit_tests/openvpn/test_auth_token.c +3 -0
@@ -174,7 +174,10 @@ auth_token_test_timeout(void **state)
 
     now =3D 100000;
     generate_auth_token(&ctx->up, &ctx->multi);
+
     strcpy(ctx->up.password, ctx->multi.auth_token);
+    free(ctx->multi.auth_token_initial);
+    ctx->multi.auth_token_initial =3D NULL;
 
     /* No time has passed */
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->sessio=

n),

tests/unit_tests/openvpn/test_auth_token.c +2 -3
@@ -244,10 +247,10 @@ auth_token_test_known_keys(void **state)
 
     now =3D 0;
     /* Preload the session id so the same session id is used here */
-    ctx->multi.auth_token =3D strdup(now0key0);
+    ctx->multi.auth_token_initial =3D strdup(now0key0);
 
     /* Zero the hmac part to ensure we have a newly generated token */
-    zerohmac(ctx->multi.auth_token);
+    zerohmac(ctx->multi.auth_token_initial);
 
     generate_auth_token(&ctx->up, &ctx->multi);
 
--

2.32.0

Quoted 4 lines

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

-----BEGIN PGP SIGNATURE-----
Version: ProtonMail

wsBzBAEBCAAGBQJg5LfeACEJEE+XnPZrkLidFiEECbw9RGejjXJ5xVVVT5ec 9muQuJ2UwQf9HRGKdMwuFN5gofphNKjx5u5PnF3woa+LOmg12VHHc99K+JHB 5S7UmRMbt7V+i67paCYMZ54YPE6jeB30UHqw/GY9Rwx+fnh6Qq0Hv8mwvKKz lM4jweoYCmZKIFcHj8C3UxbOIMugK1F7HSj2s7M7NsF6OqF2ursQQtQHhi80 1HBcYjADWNGufli8JC7CPUNp7MDzKAXu/HK9sxsrIp0B4YAft3WF3+U1OhVt sOAz0KghaX3tllfqbblNoQGfwzowP78Rxc9jh2dSzsEtl2C6HNSGvDcXjGdS DT9whFFw8mYkIJ/OPwUDsn8k3sxagYeE0h8X3eppojRgC2JDmRO0Ng== =Dq71
-----END PGP SIGNATURE-----

#27 lore raw

PATCH v4 1/1 Cleanup handling of initial auth token

In reply to Arne Schwabe

This changes that auth_token_initial is set when the token is initially generated instead when pushing the token. Even I do not know anymore why I did it in this way in the first place. Also use multi->auth_token_initial as source for the sesssion ID since it should now always be available.

Since the change makes auth_token_initial always available we need to add a check to only send a PUSH reply to update the token on renegotiations. The old code relied on multi->auth_token not being set in this case.

This commit also removes the workaround for old OpenVPN clients. These were only available as commercial OpenVPN Connect client and not in use anymore.

Patch V2: rebase.
Patch V3: fix formatting, clarifying commit message, remove initial
token workaround for old v3.
Patch v4: move sending the auth-token for renegotiations to a sane place
and trigger it when the TLS session reaches its fully authenticated state.

---
 doc/man-sections/server-options.rst        |  4 +-
 src/openvpn/auth_token.c                   | 58 ++++++++++++++++------
 src/openvpn/auth_token.h                   |  9 ++++
 src/openvpn/push.c                         |  8 ---
 src/openvpn/ssl.c                          |  7 ++-
 src/openvpn/ssl_common.h                   |  8 +--
 src/openvpn/ssl_verify.c                   | 22 +-------
 tests/unit_tests/openvpn/test_auth_token.c |  7 ++-
 8 files changed, 71 insertions(+), 52 deletions(-)
doc/man-sections/server-options.rst +2 -2
index 047f2270f..1ab00e81b 100644
@@ -35,7 +35,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   token is reached or after not being renewed for more than 2 \*
   ``reneg-sec`` seconds. Clients will be sent renewed tokens on every TLS
   renogiation to keep the client's token updated. This is done to
-  invalidate a token if a client is disconnected for a sufficently long
+  invalidate a token if a client is disconnected for a sufficiently long
   time, while at the same time permitting much longer token lifetimes for
   active clients.
 
@@ -46,7 +46,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   When the :code:`external-auth` keyword is present the normal
   authentication method will always be called even if auth-token succeeds.
   Normally other authentications method are skipped if auth-token
-  verification suceeds or fails.
+  verification succeeds or fails.
 
   This option postpones this decision to the external authentication
   methods and checks the validity of the account and do other checks.
src/openvpn/auth_token.c +43 -15

110 lines not on this page · raw message

src/openvpn/auth_token.h +9 -0
index 73a00ddd7..e9c33dc37 100644
@@ -129,4 +129,13 @@ is_auth_token(const char *password)
     return (memcmp_constant_time(SESSION_ID_PREFIX, password,
                                  strlen(SESSION_ID_PREFIX)) == 0);
 }
+/**
+ * Checks if a client has should be send a new auth token to update its
+ * current auth-token
+ * @param multi     Pointer the multi object of the TLS session
+ * @param session   Pointer to the TLS session itself
+ */
+void
+resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session);
+
 #endif /* AUTH_TOKEN_H */
src/openvpn/push.c +0 -8
index f4957f147..53cb7ca6f 100644
@@ -527,14 +527,6 @@ prepare_auth_token_push_reply(struct tls_multi *tls_multi, struct gc_arena *gc,
         push_option_fmt(gc, push_list, M_USAGE,
                         "auth-token %s",
                         tls_multi->auth_token);
-        if (!tls_multi->auth_token_initial)
-        {
-            /*
-             * Save the initial auth token for clients that ignore
-             * the updates to the token
-             */
-            tls_multi->auth_token_initial = strdup(tls_multi->auth_token);
-        }
     }
 }
 
src/openvpn/ssl.c +6 -1
index 592b2b893..504efab72 100644
@@ -3115,13 +3115,18 @@ tls_multi_process(struct tls_multi *multi,
 
             if (ks->state == S_ACTIVE && ks->authenticated == KS_AUTH_TRUE)
             {
-                /* This will ks->state from S_ACTIVE to S_GENERATED_KEYS */
+                /* Session is now fully authenticated.
+                 * tls_session_generate_data_channel_keys will ks->state
+                 * from S_ACTIVE to S_GENERATED_KEYS */
                 if (!tls_session_generate_data_channel_keys(session))
                 {
                     msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
                     ks->authenticated = KS_AUTH_FALSE;
                     ks->state = S_ERROR;
                 }
+
+                /* Update auth token on the client if needed */
+                resend_auth_token_renegotiation(multi, session);
             }
         }
     }
src/openvpn/ssl_common.h +5 -3
index 43d6276be..5c261115c 100644
@@ -96,7 +96,9 @@
                                  *   handshake window, deferred auth, client
                                  *   connect and can still
                                  *   be pending. */
-#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated */
+#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated.
+                                  *  The TLS session is fully authenticated
+                                  *  when reaching this state. */
 /* Note that earlier versions also had a S_OP_NORMAL state that was
  * virtually identical with S_ACTIVE and the code still assumes everything
  * >= S_ACTIVE to be fully operational */
@@ -597,8 +599,8 @@ struct tls_multi
                           *   user/pass authentications in this session.
                           */
     char *auth_token_initial;
-    /**< The first auth-token we sent to a client, for clients that do
-     * not update their auth-token (older OpenVPN3 core versions)
+    /**< The first auth-token we sent to a client. We use this to remember
+     * the session ID and initial timestamp when generating new auth-token.
      */
 #define  AUTH_TOKEN_HMAC_OK              (1<<0)
     /**< Auth-token sent from client has valid hmac */
src/openvpn/ssl_verify.c +1 -21
index bbb1878a3..6cc49c876 100644
@@ -1631,27 +1631,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
              */
             generate_auth_token(up, multi);
         }
-        /*
-         * Auth token already sent to client, update auth-token on client.
-         * The initial auth-token is sent as part of the push message, for this
-         * update we need to schedule an extra push message.
-         *
-         * Otherwise the auth-token get pushed out as part of the "normal"
-         * push-reply
-         */
-        if (multi->auth_token_initial)
-        {
-            /*
-             * We do not explicitly schedule the sending of the
-             * control message here but control message are only
-             * postponed when the control channel  is not yet fully
-             * established and furthermore since this is called in
-             * the middle of authentication, there are other messages
-             * (new data channel keys) that are sent anyway and will
-             * trigger schedueling
-             */
-            send_push_reply_auth_token(multi);
-        }
+
         msg(D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
             (ks->authenticated == KS_AUTH_DEFERRED) ? "deferred" : "succeeded",
             up->username,
tests/unit_tests/openvpn/test_auth_token.c +5 -2
index 4030052e0..a504eed91 100644
@@ -174,7 +174,10 @@ auth_token_test_timeout(void **state)
 
     now = 100000;
     generate_auth_token(&ctx->up, &ctx->multi);
+
     strcpy(ctx->up.password, ctx->multi.auth_token);
+    free(ctx->multi.auth_token_initial);
+    ctx->multi.auth_token_initial = NULL;
 
     /* No time has passed */
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
@@ -244,10 +247,10 @@ auth_token_test_known_keys(void **state)
 
     now = 0;
     /* Preload the session id so the same session id is used here */
-    ctx->multi.auth_token = strdup(now0key0);
+    ctx->multi.auth_token_initial = strdup(now0key0);
 
     /* Zero the hmac part to ensure we have a newly generated token */
-    zerohmac(ctx->multi.auth_token);
+    zerohmac(ctx->multi.auth_token_initial);
 
     generate_auth_token(&ctx->up, &ctx->multi);
 
Signature · 1 line
2.32.0
#28 lore raw

PATCH v5 1/1 Cleanup handling of initial auth token

In reply to Arne Schwabe

This changes that auth_token_initial is set when the token is initially generated instead when pushing the token. Even I do not know anymore why I did it in this way in the first place. Also use multi->auth_token_initial as source for the sesssion ID since it should now always be available. Also set auth_token_initial directly to up->password once we verified that we have gotten a valid token from a client. This cleans ups the logic in generating the environment and makes the code flow clearer.

Since the change makes auth_token_initial always available we need to add a check to only send a PUSH reply to update the token on renegotiations. The old code relied on multi->auth_token not being set in this case.

This commit also removes the workaround for old OpenVPN clients. These were only available as commercial OpenVPN Connect client and not in use anymore.

Furthermore, introduce a check if the session ID has changed during a session. Even though this is still a valid authentication changing to a different auth token mid session is highly irregular and should never occur naturally.

Patch V2: rebase.
Patch V3: fix formatting, clarifying commit message, remove initial
token workaround for old v3.
Patch v4: move sending the auth-token for renegotiations to a sane place
and trigger it when the TLS session reaches its fully authenticated state.
Patch v5: Move also setting auth_token_inital from up->password to a more
logical place, general cleanups, add session id mismatch check

---
 doc/man-sections/server-options.rst        |  4 +-
 src/openvpn/auth_token.c                   | 76 +++++++++++++++++-----
 src/openvpn/auth_token.h                   |  9 +++
 src/openvpn/push.c                         |  8 ---
 src/openvpn/ssl.c                          |  7 +-
 src/openvpn/ssl_common.h                   |  8 ++-
 src/openvpn/ssl_verify.c                   | 31 +++------
 tests/unit_tests/openvpn/test_auth_token.c | 49 +++++++++++---
 8 files changed, 130 insertions(+), 62 deletions(-)
doc/man-sections/server-options.rst +2 -2
index 715473353..f1d2ec317 100644
@@ -35,7 +35,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   token is reached or after not being renewed for more than 2 \*
   ``reneg-sec`` seconds. Clients will be sent renewed tokens on every TLS
   renogiation to keep the client's token updated. This is done to
-  invalidate a token if a client is disconnected for a sufficently long
+  invalidate a token if a client is disconnected for a sufficiently long
   time, while at the same time permitting much longer token lifetimes for
   active clients.
 
@@ -46,7 +46,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   When the :code:`external-auth` keyword is present the normal
   authentication method will always be called even if auth-token succeeds.
   Normally other authentications method are skipped if auth-token
-  verification suceeds or fails.
+  verification succeeds or fails.
 
   This option postpones this decision to the external authentication
   methods and checks the validity of the account and do other checks.
src/openvpn/auth_token.c +58 -18

140 lines not on this page · raw message

src/openvpn/auth_token.h +9 -0
index 73a00ddd7..e9c33dc37 100644
@@ -129,4 +129,13 @@ is_auth_token(const char *password)
     return (memcmp_constant_time(SESSION_ID_PREFIX, password,
                                  strlen(SESSION_ID_PREFIX)) == 0);
 }
+/**
+ * Checks if a client has should be send a new auth token to update its
+ * current auth-token
+ * @param multi     Pointer the multi object of the TLS session
+ * @param session   Pointer to the TLS session itself
+ */
+void
+resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session);
+
 #endif /* AUTH_TOKEN_H */
src/openvpn/push.c +0 -8
index f4957f147..53cb7ca6f 100644
@@ -527,14 +527,6 @@ prepare_auth_token_push_reply(struct tls_multi *tls_multi, struct gc_arena *gc,
         push_option_fmt(gc, push_list, M_USAGE,
                         "auth-token %s",
                         tls_multi->auth_token);
-        if (!tls_multi->auth_token_initial)
-        {
-            /*
-             * Save the initial auth token for clients that ignore
-             * the updates to the token
-             */
-            tls_multi->auth_token_initial = strdup(tls_multi->auth_token);
-        }
     }
 }
 
src/openvpn/ssl.c +6 -1
index 592b2b893..504efab72 100644
@@ -3115,13 +3115,18 @@ tls_multi_process(struct tls_multi *multi,
 
             if (ks->state == S_ACTIVE && ks->authenticated == KS_AUTH_TRUE)
             {
-                /* This will ks->state from S_ACTIVE to S_GENERATED_KEYS */
+                /* Session is now fully authenticated.
+                 * tls_session_generate_data_channel_keys will ks->state
+                 * from S_ACTIVE to S_GENERATED_KEYS */
                 if (!tls_session_generate_data_channel_keys(session))
                 {
                     msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
                     ks->authenticated = KS_AUTH_FALSE;
                     ks->state = S_ERROR;
                 }
+
+                /* Update auth token on the client if needed */
+                resend_auth_token_renegotiation(multi, session);
             }
         }
     }
src/openvpn/ssl_common.h +5 -3
index 43d6276be..5c261115c 100644
@@ -96,7 +96,9 @@
                                  *   handshake window, deferred auth, client
                                  *   connect and can still
                                  *   be pending. */
-#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated */
+#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated.
+                                  *  The TLS session is fully authenticated
+                                  *  when reaching this state. */
 /* Note that earlier versions also had a S_OP_NORMAL state that was
  * virtually identical with S_ACTIVE and the code still assumes everything
  * >= S_ACTIVE to be fully operational */
@@ -597,8 +599,8 @@ struct tls_multi
                           *   user/pass authentications in this session.
                           */
     char *auth_token_initial;
-    /**< The first auth-token we sent to a client, for clients that do
-     * not update their auth-token (older OpenVPN3 core versions)
+    /**< The first auth-token we sent to a client. We use this to remember
+     * the session ID and initial timestamp when generating new auth-token.
      */
 #define  AUTH_TOKEN_HMAC_OK              (1<<0)
     /**< Auth-token sent from client has valid hmac */
src/openvpn/ssl_verify.c +10 -21
index bbb1878a3..e8cd87088 100644
@@ -1512,6 +1512,15 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
     if (session->opt->auth_token_generate && is_auth_token(up->password))
     {
         ks->auth_token_state_flags = verify_auth_token(up, multi, session);
+
+        /* If this is the first time we see an auth-token in this session, save
+         * it as initial auth token so to continue using the same session ID
+         * and timestamp in updates */
+        if (!multi->auth_token_initial)
+        {
+            multi->auth_token_initial = strdup(up->password);
+        }
+
         if (session->opt->auth_token_call_auth)
         {
             /*
@@ -1631,27 +1640,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
              */
             generate_auth_token(up, multi);
         }
-        /*
-         * Auth token already sent to client, update auth-token on client.
-         * The initial auth-token is sent as part of the push message, for this
-         * update we need to schedule an extra push message.
-         *
-         * Otherwise the auth-token get pushed out as part of the "normal"
-         * push-reply
-         */
-        if (multi->auth_token_initial)
-        {
-            /*
-             * We do not explicitly schedule the sending of the
-             * control message here but control message are only
-             * postponed when the control channel  is not yet fully
-             * established and furthermore since this is called in
-             * the middle of authentication, there are other messages
-             * (new data channel keys) that are sent anyway and will
-             * trigger schedueling
-             */
-            send_push_reply_auth_token(multi);
-        }
+
         msg(D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
             (ks->authenticated == KS_AUTH_DEFERRED) ? "deferred" : "succeeded",
             up->username,
tests/unit_tests/openvpn/test_auth_token.c +40 -9

93 lines not on this page · raw message

Signature · 1 line
2.32.0
Acked-by on v3 6/9
#23 lore raw

[Openvpn-devel] [PATCH applied] Re: Introduce S_GENERATED_KEYS state and generate keys only when authenticated

In reply to Arne Schwabe

Adding my ACK on v3 to Antonio's test report on v3 and ACK on v2.

v3 is really exactly identical to the v2 patch, except for one extra "is this pointer non-NULL?" check in do_up() - where v2 crashed.

Stared a bit at the code (again), subjected to t_client and server torture chamber - and this time, everything succeeded, even the --secret tests.

Fixed whitespace (as instructed for v2), added description for S_GENERATED_KEYs ("The"), and clarified description for S_ACTIVE (as discussed on IRC). Added a "move" to "ks->state from S_ACTIVE" :-)

My test rig exhibited something new regarding timing with deferred auth (20s radius delay). "Master without this" has the timings like this:

2021-07-14 13:59:27 PLUGIN AUTH-PAM: BACKGROUND: fbsd-tc-master: deferred auth: PAM succeeded
2021-07-14 13:59:28 PUSH: Received control message: 'PUSH_REQUEST'
2021-07-14 13:59:28 SENT CONTROL [cron2-freebsd-tc-amd64]: 'PUSH_REPLY,...

while "master with this patch" adds extra 5s delay here *if the client reconnects often enough* (connecting 3 times from the same source port):

2021-07-14 14:03:54 PLUGIN AUTH-PAM: BACKGROUND: fbsd-tc-master: deferred auth: PAM succeeded
2021-07-14 14:03:56 PUSH: Received control message: 'PUSH_REQUEST'
2021-07-14 14:04:01 Outgoing Data Channel: Cipher 'AES-256-GCM' initialized with 256 bit key
2021-07-14 14:04:01 Incoming Data Channel: Cipher 'AES-256-GCM' initialized with 256 bit key
2021-07-14 14:04:01 PUSH: Received control message: 'PUSH_REQUEST'
2021-07-14 14:04:01 SENT CONTROL [cron2-freebsd-tc-amd64]: 'PUSH_REPLY,...

this looks like the "let's avoid too many disk accesses" cache is not being reset to 0 when a new connection from the same user comes in, or something along that lines. I know how to reproduce it, so I can go and debug more now :-) - it does NOT happen if the source port changes (--nobind).

Since this is a special case of a special case, it should not hold up this patch as such. So, not considering this a show stopper.

This patch introduces new ASSERT()s on ks->authenticated, which we checked very throughly. Both can only be reached if the ks->state is S_GENERATED_KEY, which in the normal path is only ever set if ks->authenticated is KS_AUTH_TRUE. There is a special hack path via tls_session_update_crypto_params(), which in p2mp mode is only reached after client connect, which depends on CAS_PENDING, which depends on TLS_AUTHENTICATION_SUCCEEDED. In p2p + TLS, this might be triggerable, but "coming soon" patches will clean up that path.

Your patch has been applied to the master branch.

commit 34b42549c980b19730a0beb03096d2dd915865c0

Author: Arne Schwabe
Date:   Mon Jul 5 15:34:14 2021 +0200
     Introduce S_GENERATED_KEYS state and generate keys only when authenticated

     Signed-off-by: Arne Schwabe <[email protected]...>
     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Acked-by: Gert Doering <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg22617.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#29 lore raw

Re: [Openvpn-devel] [PATCH v5] Cleanup handling of initial auth token

In reply to Arne Schwabe

Hi,

Quoted 47 lines · Arne Schwabe

This changes that auth_token_initial is set when the token is initially generated instead when pushing the token. Even I do not know anymore why I did it in this way in the first place. Also use multi->auth_token_initial as source for the sesssion ID since it should now always be available. Also set auth_token_initial directly to up->password once we verified that we have gotten a valid token from a client. This cleans ups the logic in generating the environment and makes the code flow clearer.

Since the change makes auth_token_initial always available we need to add a check to only send a PUSH reply to update the token on renegotiations. The old code relied on multi->auth_token not being set in this case.

This commit also removes the workaround for old OpenVPN clients. These were only available as commercial OpenVPN Connect client and not in use anymore.

Furthermore, introduce a check if the session ID has changed during a session. Even though this is still a valid authentication changing to a different auth token mid session is highly irregular and should never occur naturally.

Patch V2: rebase.
Patch V3: fix formatting, clarifying commit message, remove initial
token workaround for old v3.
Patch v4: move sending the auth-token for renegotiations to a sane place
and trigger it when the TLS session reaches its fully authenticated state.
Patch v5: Move also setting auth_token_inital from up->password to a more
logical place, general cleanups, add session id mismatch check

---
 doc/man-sections/server-options.rst        |  4 +-
 src/openvpn/auth_token.c                   | 76 +++++++++++++++++-----
 src/openvpn/auth_token.h                   |  9 +++
 src/openvpn/push.c                         |  8 ---
 src/openvpn/ssl.c                          |  7 +-
 src/openvpn/ssl_common.h                   |  8 ++-
 src/openvpn/ssl_verify.c                   | 31 +++------
 tests/unit_tests/openvpn/test_auth_token.c | 49 +++++++++++---
 8 files changed, 130 insertions(+), 62 deletions(-)
doc/man-sections/server-options.rst +0 -0
index 715473353..f1d2ec317 100644

doc/man-sections/server-options.rst fast hardware. SSL/TLS authentication must be used in this mode. · line 37

Quoted 3 lines
doc/man-sections/server-options.rst +0 -0
@@ -35,7 +35,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   token is reached or after not being renewed for more than 2 \*
   ``reneg-sec`` seconds. Clients will be sent renewed tokens on every TLS
   renogiation to keep the client's token updated. This is done to

while here we could fix "renogiation" -> "renegotiation"

Quoted 42 lines
doc/man-sections/server-options.rst +2 -2
-  invalidate a token if a client is disconnected for a sufficently long
+  invalidate a token if a client is disconnected for a sufficiently long
   time, while at the same time permitting much longer token lifetimes for
   active clients.
 
@@ -46,7 +46,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   When the :code:`external-auth` keyword is present the normal
   authentication method will always be called even if auth-token succeeds.
   Normally other authentications method are skipped if auth-token
-  verification suceeds or fails.
+  verification succeeds or fails.
 
   This option postpones this decision to the external authentication
   methods and checks the validity of the account and do other checks.
src/openvpn/auth_token.c +3 -3
index 0ea6d1832..6c1bec799 100644
@@ -109,11 +109,11 @@ add_session_token_env(struct tls_session *session, struct tls_multi *multi,
         /*
          * No session before, generate a new session token for the new session
          */
-        if (!multi->auth_token)
+        if (!multi->auth_token_initial)
         {
             generate_auth_token(up, multi);
         }
-        session_id_source = multi->auth_token;
+        session_id_source = multi->auth_token_initial;
     }
     /*
      * In the auth-token the auth token is already base64 encoded
@@ -184,7 +184,7 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
     uint8_t sessid[AUTH_TOKEN_SESSION_ID_LEN];
 
-    if (multi->auth_token)
+    if (multi->auth_token_initial)
     {
         /* Just enough space to fit 8 bytes+ 1 extra to decode a non padded
          * base64 string (multiple of 3 bytes). 9 bytes => 12 bytes base64

src/openvpn/auth_token.c generate_auth_token(const struct user_pass *up, struct tls_multi *multi) · line 201

Quoted 10 lines
src/openvpn/auth_token.c +3 -0
@@ -192,11 +192,14 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
          */
         char old_tstamp_decode[9];
 
+        /* Make a copy of the string to not modify multi->auth_token_initial */
+        char *initial_token_copy = string_alloc(multi->auth_token_initial, &gc);
+
         /*
          * reuse the same session id and timestamp and null terminate it at
          * for base64 decode it only decodes the session id part of it
          */

This comment above does not make much sense to me, but since it has been there since "ever", I'd suggest to fix it in a follow-up patch. (This patch is not changing the logic that the comment is trying to explain)

On top of that, this function makes huge assumptions about the length of the token and later it moves pointers across this buffer without checking boundaries.
I am pretty sure that this code works well because the token has a static and predictable length, but it might be good to make this assumptions explicit by adding at least some comments.

Anyway, for a follow up patch too.

Quoted 42 lines
src/openvpn/auth_token.c +13 -6
-        char *old_sessid = multi->auth_token + strlen(SESSION_ID_PREFIX);
+        char *old_sessid = initial_token_copy + strlen(SESSION_ID_PREFIX);
         char *old_tsamp_initial = old_sessid + AUTH_TOKEN_SESSION_ID_LEN*8/6;
 
         old_tsamp_initial[12] = '\0';
@@ -211,11 +214,7 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
         initial_timestamp = *tstamp_ptr;
 
         old_tsamp_initial[0] = '\0';
-        ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSION_ID_LEN)==AUTH_TOKEN_SESSION_ID_LEN);
-
-
-        /* free the auth-token, we will replace it with a new one */
-        free(multi->auth_token);
+        ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSION_ID_LEN) == AUTH_TOKEN_SESSION_ID_LEN);
     }
     else if (!rand_bytes(sessid, AUTH_TOKEN_SESSION_ID_LEN))
     {
@@ -272,11 +271,22 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
     free(b64output);
 
+    /* free the auth-token if defined, we will replace it with a new one */
+    free(multi->auth_token);
     multi->auth_token = strdup((char *)BPTR(&session_token));
 
     dmsg(D_SHOW_KEYS, "Generated token for client: %s (%s)",
          multi->auth_token, up->username);
 
+    if (!multi->auth_token_initial)
+    {
+        /*
+         * Save the initial auth token to continue using the same session ID
+         * and timestamp in updates
+         */
+        multi->auth_token_initial = strdup(multi->auth_token);
+    }
+
     gc_free(&gc);
 }
 

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 356

Quoted 5 lines
src/openvpn/auth_token.c +1 -1
@@ -343,7 +353,7 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi,
     }
     else
     {
-        msg(M_WARN, "--auth-token-gen: HMAC on token from client failed (%s)",
+        msg(M_WARN, "--auth-gen-token: HMAC on token from client failed (%s)",

totally unrelated to this patch :-) I let Gert decide if we can keep it here or not.

Quoted 5 lines
src/openvpn/auth_token.c +0 -0
             up->username);
         return 0;
     }
@@ -353,13 +363,7 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi,
     bool in_renog_time = now >= timestamp

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 366

Quoted 10 lines
src/openvpn/auth_token.c +1 -7
                          && now < timestamp + 2 * session->opt->renegotiate_seconds;
 
-    /* We could still have a client that does not update
-     * its auth-token, so also allow the initial auth-token */
-    bool initialtoken = multi->auth_token_initial
-                        && memcmp_constant_time(up->password, multi->auth_token_initial,
-                                                strlen(multi->auth_token_initial)) == 0;
-
-    if (!in_renog_time && !initialtoken)
+    if (!in_renog_time)

uhm, was this always supposed to be "in_reneg_time" ? maybe we can fix it while at it..

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 394

Quoted 13 lines
src/openvpn/auth_token.c +5 -1
     {
         ret |= AUTH_TOKEN_EXPIRED;
     }
@@ -383,7 +387,19 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi,
     {
         /* Tell client that the session token is expired */
         auth_set_client_reason(multi, "SESSION: token expired");
-        msg(M_INFO, "--auth-token-gen: auth-token from client expired");
+        msg(M_INFO, "--auth-gen-token: auth-token from client expired");
+    }
+
+    /* Check that we do have the same session ID in the token and the session
+     * did not change, this also compares the prefix and session part of the

Regarding the sentence above, is it possible that we have the same session ID and the sessions are not the same? From the comment it seems it could be possible, but I am not sure this can be the case.

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 398

Quoted 4 lines
src/openvpn/auth_token.c +4 -0
+     * tokens, which should be identical if the session stayed the same */
+    if (multi->auth_token_initial
+        && memcmp_constant_time(multi->auth_token_initial, up->password,
+                                strlen(SESSION_ID_PREFIX) + AUTH_TOKEN_SESSION_ID_LEN * 8 / 6))

Is this hunk actually fixing a problematic behaviour? It seems before this patch we were missing this specific check? or wasn't it needed?

Cosmetic note:
AUTH_TOKEN_SESSION_ID_LEN * 8 / 6 << this constant is used in several places in the code.
Can we rather define another constant with a name that makes it clear what it is? IIRC this "* 8 / 6" is used to compute the expected length in base64, right?

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 400

Quoted 2 lines
src/openvpn/auth_token.c +2 -0
+    {
+        msg(M_WARN, "--auth-gen-token: session id in token changed (. Rejecting "

The '.' is misplaced imho

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 401

Quoted 1 line
src/openvpn/auth_token.c +1 -0
+                    "token.");

I Would just not put any '.' between parenthesis.

Quoted 18 lines
src/openvpn/auth_token.c +11 -0
+        ret = 0;
     }
     return ret;
 }
@@ -408,3 +424,27 @@ wipe_auth_token(struct tls_multi *multi)
         multi->auth_token_initial = NULL;
     }
 }
+
+void
+resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session)
+{
+    /*
+     * Auth token already sent to client, update auth-token on client.
+     * The initial auth-token is sent as part of the push message, for this
+     * update we need to schedule an extra push message.
+     *
+     * Otherwise the auth-token get pushed out as part of the "normal"

src/openvpn/auth_token.c wipe_auth_token(struct tls_multi *multi) · line 446

Quoted 10 lines
src/openvpn/auth_token.c +10 -0
+     * push-reply
+     */
+    bool is_renegotiation = session->key[KS_PRIMARY].key_id != 0;
+
+    if (multi->auth_token_initial && is_renegotiation)
+    {
+        /*
+         * We do not explicitly reschedule the sending of the
+         * control message here. This might delay this reply
+         * a few seconds until but this message is not time critical

until .. ? is something missing? or "until" was supposed to be removed?

Quoted 10 lines
src/openvpn/auth_token.c +4 -0
+         */
+        send_push_reply_auth_token(multi);
+    }
+}
\ No newline at end of file
src/openvpn/auth_token.h +0 -0
index 73a00ddd7..e9c33dc37 100644

src/openvpn/auth_token.h is_auth_token(const char *password) · line 133

Quoted 5 lines
src/openvpn/auth_token.h +2 -0
@@ -129,4 +129,13 @@ is_auth_token(const char *password)
     return (memcmp_constant_time(SESSION_ID_PREFIX, password,
                                  strlen(SESSION_ID_PREFIX)) == 0);
 }
+/**
+ * Checks if a client has should be send a new auth token to update its

send -> sent

Quoted 84 lines
src/openvpn/auth_token.h +7 -0
+ * current auth-token
+ * @param multi     Pointer the multi object of the TLS session
+ * @param session   Pointer to the TLS session itself
+ */
+void
+resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session);
+
 #endif /* AUTH_TOKEN_H */
src/openvpn/push.c +0 -8
index f4957f147..53cb7ca6f 100644
@@ -527,14 +527,6 @@ prepare_auth_token_push_reply(struct tls_multi *tls_multi, struct gc_arena *gc,
         push_option_fmt(gc, push_list, M_USAGE,
                         "auth-token %s",
                         tls_multi->auth_token);
-        if (!tls_multi->auth_token_initial)
-        {
-            /*
-             * Save the initial auth token for clients that ignore
-             * the updates to the token
-             */
-            tls_multi->auth_token_initial = strdup(tls_multi->auth_token);
-        }
     }
 }
 
src/openvpn/ssl.c +6 -1
index 592b2b893..504efab72 100644
@@ -3115,13 +3115,18 @@ tls_multi_process(struct tls_multi *multi,
 
             if (ks->state == S_ACTIVE && ks->authenticated == KS_AUTH_TRUE)
             {
-                /* This will ks->state from S_ACTIVE to S_GENERATED_KEYS */
+                /* Session is now fully authenticated.
+                 * tls_session_generate_data_channel_keys will ks->state
+                 * from S_ACTIVE to S_GENERATED_KEYS */
                 if (!tls_session_generate_data_channel_keys(session))
                 {
                     msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
                     ks->authenticated = KS_AUTH_FALSE;
                     ks->state = S_ERROR;
                 }
+
+                /* Update auth token on the client if needed */
+                resend_auth_token_renegotiation(multi, session);
             }
         }
     }
src/openvpn/ssl_common.h +5 -3
index 43d6276be..5c261115c 100644
@@ -96,7 +96,9 @@
                                  *   handshake window, deferred auth, client
                                  *   connect and can still
                                  *   be pending. */
-#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated */
+#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated.
+                                  *  The TLS session is fully authenticated
+                                  *  when reaching this state. */
 /* Note that earlier versions also had a S_OP_NORMAL state that was
  * virtually identical with S_ACTIVE and the code still assumes everything
  * >= S_ACTIVE to be fully operational */
@@ -597,8 +599,8 @@ struct tls_multi
                           *   user/pass authentications in this session.
                           */
     char *auth_token_initial;
-    /**< The first auth-token we sent to a client, for clients that do
-     * not update their auth-token (older OpenVPN3 core versions)
+    /**< The first auth-token we sent to a client. We use this to remember
+     * the session ID and initial timestamp when generating new auth-token.
      */
 #define  AUTH_TOKEN_HMAC_OK              (1<<0)
     /**< Auth-token sent from client has valid hmac */
src/openvpn/ssl_verify.c +0 -0
index bbb1878a3..e8cd87088 100644
@@ -1512,6 +1512,15 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
     if (session->opt->auth_token_generate && is_auth_token(up->password))
     {

src/openvpn/ssl_verify.c verify_user_pass(struct user_pass *up, struct tls_multi *multi, · line 1523

Quoted 10 lines
src/openvpn/ssl_verify.c +9 -0
         ks->auth_token_state_flags = verify_auth_token(up, multi, session);
+
+        /* If this is the first time we see an auth-token in this session, save
+         * it as initial auth token so to continue using the same session ID
+         * and timestamp in updates */
+        if (!multi->auth_token_initial)
+        {
+            multi->auth_token_initial = strdup(up->password);
+        }
+

We have the very same code in generate_auth_token(), why do we need it here too? I had thought that the auth-token-initial is saved only upon first token generation.

What use case are we covering here in verify_user_pass()?

Quoted 15 lines
src/openvpn/ssl_verify.c +0 -8
         if (session->opt->auth_token_call_auth)
         {
             /*
@@ -1631,27 +1640,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
              */
             generate_auth_token(up, multi);
         }
-        /*
-         * Auth token already sent to client, update auth-token on client.
-         * The initial auth-token is sent as part of the push message, for this
-         * update we need to schedule an extra push message.
-         *
-         * Otherwise the auth-token get pushed out as part of the "normal"
-         * push-reply
-         */

src/openvpn/ssl_verify.c verify_user_pass(struct user_pass *up, struct tls_multi *multi, · line 1651

Quoted 10 lines
src/openvpn/ssl_verify.c +0 -10
-        if (multi->auth_token_initial)
-        {
-            /*
-             * We do not explicitly schedule the sending of the
-             * control message here but control message are only
-             * postponed when the control channel  is not yet fully
-             * established and furthermore since this is called in
-             * the middle of authentication, there are other messages
-             * (new data channel keys) that are sent anyway and will
-             * trigger schedueling

typ0: scheduling

Quoted 104 lines
src/openvpn/ssl_verify.c +1 -3
-             */
-            send_push_reply_auth_token(multi);
-        }
+
         msg(D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
             (ks->authenticated == KS_AUTH_DEFERRED) ? "deferred" : "succeeded",
             up->username,
tests/unit_tests/openvpn/test_auth_token.c +39 -9
index 4030052e0..476f64b89 100644
@@ -174,7 +174,10 @@ auth_token_test_timeout(void **state)
 
     now = 100000;
     generate_auth_token(&ctx->up, &ctx->multi);
+
     strcpy(ctx->up.password, ctx->multi.auth_token);
+    free(ctx->multi.auth_token_initial);
+    ctx->multi.auth_token_initial = NULL;
 
     /* No time has passed */
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
@@ -195,11 +198,6 @@ auth_token_test_timeout(void **state)
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
                      AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED);
 
-    /* Check if the mode for a client that never updates its token works */
-    ctx->multi.auth_token_initial = strdup(ctx->up.password);
-    assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
-                     AUTH_TOKEN_HMAC_OK);
-
     /* But not when we reached our timeout */
     now = 100000 + ctx->session->opt->auth_token_lifetime + 1;
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
@@ -244,10 +242,10 @@ auth_token_test_known_keys(void **state)
 
     now = 0;
     /* Preload the session id so the same session id is used here */
-    ctx->multi.auth_token = strdup(now0key0);
+    ctx->multi.auth_token_initial = strdup(now0key0);
 
     /* Zero the hmac part to ensure we have a newly generated token */
-    zerohmac(ctx->multi.auth_token);
+    zerohmac(ctx->multi.auth_token_initial);
 
     generate_auth_token(&ctx->up, &ctx->multi);
 
@@ -268,6 +266,38 @@ setenv_str(struct env_set *es, const char *name, const char *value)
     }
 }
 
+void
+auth_token_test_session_mismatch(void **state)
+{
+    struct test_context *ctx = (struct test_context *) *state;
+
+    /* Generate first auth token and check it is correct */
+    generate_auth_token(&ctx->up, &ctx->multi);
+    strcpy(ctx->up.password, ctx->multi.auth_token);
+    assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
+                     AUTH_TOKEN_HMAC_OK);
+
+    char *token_sessiona = strdup(ctx->multi.auth_token);
+
+    /* Generate second token */
+    wipe_auth_token(&ctx->multi);
+
+    generate_auth_token(&ctx->up, &ctx->multi);
+    strcpy(ctx->up.password, ctx->multi.auth_token);
+    assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
+                     AUTH_TOKEN_HMAC_OK);
+
+    assert_int_not_equal(0, memcmp(ctx->multi.auth_token_initial + strlen(SESSION_ID_PREFIX),
+                                   token_sessiona + strlen(SESSION_ID_PREFIX),
+                                   AUTH_TOKEN_SESSION_ID_LEN * 8 / 6));
+
+    /* The first token is valid but should trigger the invalid response since
+     * the session id is not the same */
+    strcpy(ctx->up.password, token_sessiona);
+    assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session), 0);
+    free(token_sessiona);
+}
+
 static void
 auth_token_test_empty_user(void **state)
 {
@@ -341,13 +371,13 @@ auth_token_test_random_keys(void **state)
 
     now = 0x5c331e9c;
     /* Preload the session id so the same session id is used here */
-    ctx->multi.auth_token = strdup(random_token);
+    ctx->multi.auth_token_initial = strdup(random_token);
 
     free_key_ctx(&ctx->multi.opt.auth_token_key);
     auth_token_init_secret(&ctx->multi.opt.auth_token_key, random_key, true);
 
     /* Zero the hmac part to ensure we have a newly generated token */
-    zerohmac(ctx->multi.auth_token);
+    zerohmac(ctx->multi.auth_token_initial);
 
     generate_auth_token(&ctx->up, &ctx->multi);
 

tests/unit_tests/openvpn/test_auth_token.c main(void) · line 421

Quoted 7 lines
tests/unit_tests/openvpn/test_auth_token.c +1 -0
@@ -385,6 +415,7 @@ main(void)
         cmocka_unit_test_setup_teardown(auth_token_test_random_keys, setup, teardown),
         cmocka_unit_test_setup_teardown(auth_token_test_key_load, setup, teardown),
         cmocka_unit_test_setup_teardown(auth_token_test_timeout, setup, teardown),
+        cmocka_unit_test_setup_teardown(auth_token_test_session_mismatch, setup, teardown)
     };
 
 #if defined(ENABLE_CRYPTO_OPENSSL)

The rest looks good. I like seeing more auth-token logic being moved to auth-token.c, in the proper functions.

In any case, will still wait for Arne to clarify my doubts, as expressed above.

[note: I am still testing..]

Regards,

Signature · 1 line
Antonio Quartulli
#30 lore raw

Re: [Openvpn-devel] [PATCH v5] Cleanup handling of initial auth token

Quoted 10 lines
Quoted 5 lines

/*
* reuse the same session id and timestamp and null terminate it at
* for base64 decode it only decodes the session id part of it */

This comment above does not make much sense to me, but since it has been there since "ever", I'd suggest to fix it in a follow-up patch. (This patch is not changing the logic that the comment is trying to explain)

Quoted 6 lines

On top of that, this function makes huge assumptions about the length of the token and later it moves pointers across this buffer without checking boundaries.
I am pretty sure that this code works well because the token has a static and predictable length, but it might be good to make this assumptions explicit by adding at least some comments.

The underlying assumption is that that the token in multi->auth_token/initial_auth_token is always verified and is safe to use because otherwise we screwed up elsewhere.

Quoted 8 lines

Anyway, for a follow up patch too.

Quoted 5 lines
src/openvpn/auth_token.c +1 -1
-        char *old_sessid = multi->auth_token + strlen(SESSION_ID_PREFIX);
+        char *old_sessid = initial_token_copy + strlen(SESSION_ID_PREFIX);
         char *old_tsamp_initial = old_sessid + AUTH_TOKEN_SESSION_ID_LEN*8/6;
 
         old_tsamp_initial[12] = '\0';

This is the line the comment above refers to. We null terminate the session token part of the token to make it a shorter string to feed into

Quoted 9 lines

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 356

Quoted 6 lines
src/openvpn/auth_token.c +1 -1
@@ -343,7 +353,7 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi,
     }
     else
     {
-        msg(M_WARN, "--auth-token-gen: HMAC on token from client failed (%s)",
+        msg(M_WARN, "--auth-gen-token: HMAC on token from client failed (%s)",

totally unrelated to this patch :-) I let Gert decide if we can keep it here or not.

Yeah. I noticed that I swapped the name around on accident.

Quoted 8 lines
Quoted 8 lines
src/openvpn/auth_token.c +0 -0
             up->username);
         return 0;
     }
@@ -353,13 +363,7 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi,
     bool in_renog_time = now >= timestamp
                          && now < timestamp + 2 * session->opt->renegotiate_seconds;
 
Quoted 11 lines

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 366

Quoted 8 lines
src/openvpn/auth_token.c +1 -7
-    /* We could still have a client that does not update
-     * its auth-token, so also allow the initial auth-token */
-    bool initialtoken = multi->auth_token_initial
-                        && memcmp_constant_time(up->password, multi->auth_token_initial,
-                                                strlen(multi->auth_token_initial)) == 0;
-
-    if (!in_renog_time && !initialtoken)
+    if (!in_renog_time)

uhm, was this always supposed to be "in_reneg_time" ? maybe we can fix it while at it..

Sure can do that as cleanup

Quoted 10 lines
Quoted 10 lines
src/openvpn/auth_token.c +1 -1
     {
         ret |= AUTH_TOKEN_EXPIRED;
     }
@@ -383,7 +387,19 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi,
     {
         /* Tell client that the session token is expired */
         auth_set_client_reason(multi, "SESSION: token expired");
-        msg(M_INFO, "--auth-token-gen: auth-token from client expired");
+        msg(M_INFO, "--auth-gen-token: auth-token from client expired");
Quoted 8 lines

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 394

Quoted 4 lines
src/openvpn/auth_token.c +4 -0
+    }
+
+    /* Check that we do have the same session ID in the token and the session
+     * did not change, this also compares the prefix and session part of the

Regarding the sentence above, is it possible that we have the same session ID and the sessions are not the same? From the comment it seems it could be possible, but I am not sure this can be the case.

Will rewrite it.

Quoted 11 lines

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 398

Quoted 5 lines
src/openvpn/auth_token.c +4 -0
+     * tokens, which should be identical if the session stayed the same */
+    if (multi->auth_token_initial
+        && memcmp_constant_time(multi->auth_token_initial, up->password,
+                                strlen(SESSION_ID_PREFIX) + AUTH_TOKEN_SESSION_ID_LEN * 8 / 6))

Is this hunk actually fixing a problematic behaviour? It seems before this patch we were missing this specific check? or wasn't it needed?

Quoted 6 lines

Cosmetic note:
AUTH_TOKEN_SESSION_ID_LEN * 8 / 6 << this constant is used in several places in the code.
Can we rather define another constant with a name that makes it clear what it is? IIRC this "* 8 / 6" is used to compute the expected length in base64, right?

I will replace it with a define

Quoted 14 lines
Quoted 14 lines
src/openvpn/auth_token.c +14 -0
+
+void
+resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session)
+{
+    /*
+     * Auth token already sent to client, update auth-token on client.
+     * The initial auth-token is sent as part of the push message, for this
+     * update we need to schedule an extra push message.
+     *
+     * Otherwise the auth-token get pushed out as part of the "normal"
+     * push-reply
+     */
+    bool is_renegotiation = session->key[KS_PRIMARY].key_id != 0;
+
Quoted 8 lines

src/openvpn/auth_token.c wipe_auth_token(struct tls_multi *multi) · line 446

Quoted 6 lines
src/openvpn/auth_token.c +6 -0
+    if (multi->auth_token_initial && is_renegotiation)
+    {
+        /*
+         * We do not explicitly reschedule the sending of the
+         * control message here. This might delay this reply
+         * a few seconds until but this message is not time critical

until .. ? is something missing? or "until" was supposed to be removed?

Yes the old moved function had an actually wrong part after the util.

Quoted 17 lines

src/openvpn/ssl_verify.c verify_user_pass(struct user_pass *up, struct tls_multi *multi, · line 1523

Quoted 12 lines
     if (session->opt->auth_token_generate && is_auth_token(up->password))
     {
         ks->auth_token_state_flags = verify_auth_token(up, multi, session);
src/openvpn/ssl_verify.c +9 -0
+
+        /* If this is the first time we see an auth-token in this session, save
+         * it as initial auth token so to continue using the same session ID
+         * and timestamp in updates */
+        if (!multi->auth_token_initial)
+        {
+            multi->auth_token_initial = strdup(up->password);
+        }
+

We have the very same code in generate_auth_token(), why do we need it here too? I had thought that the auth-token-initial is saved only upon first token generation.

Quoted 1 line

What use case are we covering here in verify_user_pass()?

Client authenticates with an auth-token and we want to keep the session ID and initial token time in all tokens we push later to the client.

Quoted 10 lines
Quoted 1 line

The rest looks good. I like seeing more auth-token logic being moved to auth-token.c, in the proper functions.

In any case, will still wait for Arne to clarify my doubts, as expressed above.

[note: I am still testing..]

#31 lore raw

PATCH v6 1/1 Cleanup handling of initial auth token

In reply to Arne Schwabe

This changes that auth_token_initial is set when the token is initially generated instead when pushing the token. Even I do not know anymore why I did it in this way in the first place. Also use multi->auth_token_initial as source for the sesssion ID since it should now always be available. Also set auth_token_initial directly to up->password once we verified that we have gotten a valid token from a client. This cleans ups the logic in generating the environment and makes the code flow clearer.

Since the change makes auth_token_initial always available we need to add a check to only send a PUSH reply to update the token on renegotiations. The old code relied on multi->auth_token not being set in this case.

This commit also removes the workaround for old OpenVPN clients. These were only available as commercial OpenVPN Connect client and not in use anymore.

Furthermore, introduce a check if the session ID has changed during a session. Even though this is still a valid authentication changing to a different auth token mid session is highly irregular and should never occur naturally.

Patch V2: rebase.
Patch V3: fix formatting, clarifying commit message, remove initial
token workaround for old v3.
Patch v4: move sending the auth-token for renegotiations to a sane place
and trigger it when the TLS session reaches its fully authenticated state.
Patch v5: Move also setting auth_token_inital from up->password to a more
logical place, general cleanups, add session id mismatch check
Patch v6: Rework some comments and general cleanup of small things

---
 doc/man-sections/server-options.rst        |  4 +-
 src/openvpn/auth_token.c                   | 89 ++++++++++++++++------
 src/openvpn/auth_token.h                   | 11 ++-
 src/openvpn/push.c                         |  8 --
 src/openvpn/ssl.c                          |  7 +-
 src/openvpn/ssl_common.h                   |  9 ++-
 src/openvpn/ssl_verify.c                   | 31 +++-----
 tests/unit_tests/openvpn/test_auth_token.c | 49 +++++++++---
 8 files changed, 140 insertions(+), 68 deletions(-)
doc/man-sections/server-options.rst +2 -2
index 715473353..f1d2ec317 100644
@@ -35,7 +35,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   token is reached or after not being renewed for more than 2 \*
   ``reneg-sec`` seconds. Clients will be sent renewed tokens on every TLS
   renogiation to keep the client's token updated. This is done to
-  invalidate a token if a client is disconnected for a sufficently long
+  invalidate a token if a client is disconnected for a sufficiently long
   time, while at the same time permitting much longer token lifetimes for
   active clients.
 
@@ -46,7 +46,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   When the :code:`external-auth` keyword is present the normal
   authentication method will always be called even if auth-token succeeds.
   Normally other authentications method are skipped if auth-token
-  verification suceeds or fails.
+  verification succeeds or fails.
 
   This option postpones this decision to the external authentication
   methods and checks the validity of the account and do other checks.
src/openvpn/auth_token.c +66 -23

159 lines not on this page · raw message

src/openvpn/auth_token.h +10 -1
index 73a00ddd7..de93a9413 100644
@@ -117,7 +117,7 @@ void wipe_auth_token(struct tls_multi *multi);
 /**
  * Return if the password string has the format of a password.
  *
- * This fuction will always read as many bytes as SESSION_ID_PREFIX is longer
+ * This function will always read as many bytes as SESSION_ID_PREFIX is longer
  * the caller needs ensure that password memory is at least that long (true for
  * calling with struct user_pass)
  * @param password
@@ -129,4 +129,13 @@ is_auth_token(const char *password)
     return (memcmp_constant_time(SESSION_ID_PREFIX, password,
                                  strlen(SESSION_ID_PREFIX)) == 0);
 }
+/**
+ * Checks if a client should be sent a new auth token to update its
+ * current auth-token
+ * @param multi     Pointer the multi object of the TLS session
+ * @param session   Pointer to the TLS session itself
+ */
+void
+resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session);
+
 #endif /* AUTH_TOKEN_H */
src/openvpn/push.c +0 -8
index f4957f147..53cb7ca6f 100644
@@ -527,14 +527,6 @@ prepare_auth_token_push_reply(struct tls_multi *tls_multi, struct gc_arena *gc,
         push_option_fmt(gc, push_list, M_USAGE,
                         "auth-token %s",
                         tls_multi->auth_token);
-        if (!tls_multi->auth_token_initial)
-        {
-            /*
-             * Save the initial auth token for clients that ignore
-             * the updates to the token
-             */
-            tls_multi->auth_token_initial = strdup(tls_multi->auth_token);
-        }
     }
 }
 
src/openvpn/ssl.c +6 -1
index 615ed69e5..e9b8d1b92 100644
@@ -3115,13 +3115,18 @@ tls_multi_process(struct tls_multi *multi,
 
             if (ks->state == S_ACTIVE && ks->authenticated == KS_AUTH_TRUE)
             {
-                /* This will move ks->state from S_ACTIVE to S_GENERATED_KEYS */
+                /* Session is now fully authenticated.
+                 * tls_session_generate_data_channel_keys will move ks->state
+                 * from S_ACTIVE to S_GENERATED_KEYS */
                 if (!tls_session_generate_data_channel_keys(session))
                 {
                     msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
                     ks->authenticated = KS_AUTH_FALSE;
                     ks->state = S_ERROR;
                 }
+
+                /* Update auth token on the client if needed */
+                resend_auth_token_renegotiation(multi, session);
             }
         }
     }
src/openvpn/ssl_common.h +6 -3
index 72eb55bd3..64c1d53f3 100644
@@ -95,7 +95,10 @@
                                  *   completed while still within the
                                  *   handshake window.  Deferred auth and
                                  *   client connect can still be pending. */
-#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated */
+#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated
+                                  *  The TLS session is fully authenticated
+                                  *  when reaching this state. */
+
 /* Note that earlier versions also had a S_OP_NORMAL state that was
  * virtually identical with S_ACTIVE and the code still assumes everything
  * >= S_ACTIVE to be fully operational */
@@ -596,8 +599,8 @@ struct tls_multi
                           *   user/pass authentications in this session.
                           */
     char *auth_token_initial;
-    /**< The first auth-token we sent to a client, for clients that do
-     * not update their auth-token (older OpenVPN3 core versions)
+    /**< The first auth-token we sent to a client. We use this to remember
+     * the session ID and initial timestamp when generating new auth-token.
      */
 #define  AUTH_TOKEN_HMAC_OK              (1<<0)
     /**< Auth-token sent from client has valid hmac */
src/openvpn/ssl_verify.c +10 -21
index bbb1878a3..913c95620 100644
@@ -1512,6 +1512,15 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
     if (session->opt->auth_token_generate && is_auth_token(up->password))
     {
         ks->auth_token_state_flags = verify_auth_token(up, multi, session);
+
+        /* If this is the first time we see an auth-token in this multi session,
+         * save it as initial auth token. This ensures using the
+         * same session ID and initial timestamp in new tokens */
+        if (!multi->auth_token_initial)
+        {
+            multi->auth_token_initial = strdup(up->password);
+        }
+
         if (session->opt->auth_token_call_auth)
         {
             /*
@@ -1631,27 +1640,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
              */
             generate_auth_token(up, multi);
         }
-        /*
-         * Auth token already sent to client, update auth-token on client.
-         * The initial auth-token is sent as part of the push message, for this
-         * update we need to schedule an extra push message.
-         *
-         * Otherwise the auth-token get pushed out as part of the "normal"
-         * push-reply
-         */
-        if (multi->auth_token_initial)
-        {
-            /*
-             * We do not explicitly schedule the sending of the
-             * control message here but control message are only
-             * postponed when the control channel  is not yet fully
-             * established and furthermore since this is called in
-             * the middle of authentication, there are other messages
-             * (new data channel keys) that are sent anyway and will
-             * trigger schedueling
-             */
-            send_push_reply_auth_token(multi);
-        }
+
         msg(D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
             (ks->authenticated == KS_AUTH_DEFERRED) ? "deferred" : "succeeded",
             up->username,
tests/unit_tests/openvpn/test_auth_token.c +40 -9

93 lines not on this page · raw message

Signature · 1 line
2.32.0
Acked-by on v6 1/1
#32 lore raw

Re: [Openvpn-devel] [PATCH v6] Cleanup handling of initial auth token

Hi,

Quoted 73 lines · Arne Schwabe

This changes that auth_token_initial is set when the token is initially generated instead when pushing the token. Even I do not know anymore why I did it in this way in the first place. Also use multi->auth_token_initial as source for the sesssion ID since it should now always be available. Also set auth_token_initial directly to up->password once we verified that we have gotten a valid token from a client. This cleans ups the logic in generating the environment and makes the code flow clearer.

Since the change makes auth_token_initial always available we need to add a check to only send a PUSH reply to update the token on renegotiations. The old code relied on multi->auth_token not being set in this case.

This commit also removes the workaround for old OpenVPN clients. These were only available as commercial OpenVPN Connect client and not in use anymore.

Furthermore, introduce a check if the session ID has changed during a session. Even though this is still a valid authentication changing to a different auth token mid session is highly irregular and should never occur naturally.

Patch V2: rebase.
Patch V3: fix formatting, clarifying commit message, remove initial
token workaround for old v3.
Patch v4: move sending the auth-token for renegotiations to a sane place
and trigger it when the TLS session reaches its fully authenticated state.
Patch v5: Move also setting auth_token_inital from up->password to a more
logical place, general cleanups, add session id mismatch check
Patch v6: Rework some comments and general cleanup of small things

---
 doc/man-sections/server-options.rst        |  4 +-
 src/openvpn/auth_token.c                   | 89 ++++++++++++++++------
 src/openvpn/auth_token.h                   | 11 ++-
 src/openvpn/push.c                         |  8 --
 src/openvpn/ssl.c                          |  7 +-
 src/openvpn/ssl_common.h                   |  9 ++-
 src/openvpn/ssl_verify.c                   | 31 +++-----
 tests/unit_tests/openvpn/test_auth_token.c | 49 +++++++++---
 8 files changed, 140 insertions(+), 68 deletions(-)
doc/man-sections/server-options.rst +2 -2
index 715473353..f1d2ec317 100644
@@ -35,7 +35,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   token is reached or after not being renewed for more than 2 \*
   ``reneg-sec`` seconds. Clients will be sent renewed tokens on every TLS
   renogiation to keep the client's token updated. This is done to
-  invalidate a token if a client is disconnected for a sufficently long
+  invalidate a token if a client is disconnected for a sufficiently long
   time, while at the same time permitting much longer token lifetimes for
   active clients.
 
@@ -46,7 +46,7 @@ fast hardware. SSL/TLS authentication must be used in this mode.
   When the :code:`external-auth` keyword is present the normal
   authentication method will always be called even if auth-token succeeds.
   Normally other authentications method are skipped if auth-token
-  verification suceeds or fails.
+  verification succeeds or fails.
 
   This option postpones this decision to the external authentication
   methods and checks the validity of the account and do other checks.
src/openvpn/auth_token.c +0 -0
index 0ea6d1832..d7c005256 100644

src/openvpn/auth_token.c line 24

Quoted 4 lines
src/openvpn/auth_token.c +1 -0
@@ -21,6 +21,8 @@
 const char *auth_token_pem_name = "OpenVPN auth-token server key";
 
 #define AUTH_TOKEN_SESSION_ID_LEN 12
+

IF we want an empty line, I'd put this empty line after AUTH_TOKEN_SESSION_ID_BASE64_LEN, but I leave this to Gert's taste.

Quoted 31 lines
src/openvpn/auth_token.c +4 -3
+#define AUTH_TOKEN_SESSION_ID_BASE64_LEN (AUTH_TOKEN_SESSION_ID_LEN * 8 / 6)
 #if AUTH_TOKEN_SESSION_ID_LEN % 3
 #error AUTH_TOKEN_SESSION_ID_LEN needs to be multiple a 3
 #endif
@@ -109,11 +111,11 @@ add_session_token_env(struct tls_session *session, struct tls_multi *multi,
         /*
          * No session before, generate a new session token for the new session
          */
-        if (!multi->auth_token)
+        if (!multi->auth_token_initial)
         {
             generate_auth_token(up, multi);
         }
-        session_id_source = multi->auth_token;
+        session_id_source = multi->auth_token_initial;
     }
     /*
      * In the auth-token the auth token is already base64 encoded
@@ -184,7 +186,7 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
     uint8_t sessid[AUTH_TOKEN_SESSION_ID_LEN];
 
-    if (multi->auth_token)
+    if (multi->auth_token_initial)
     {
         /* Just enough space to fit 8 bytes+ 1 extra to decode a non padded
          * base64 string (multiple of 3 bytes). 9 bytes => 12 bytes base64
@@ -192,13 +194,16 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
          */
         char old_tstamp_decode[9];
 

src/openvpn/auth_token.c generate_auth_token(const struct user_pass *up, struct tls_multi *multi) · line 201

Quoted 10 lines
src/openvpn/auth_token.c +4 -5
-        /*
-         * reuse the same session id and timestamp and null terminate it at
-         * for base64 decode it only decodes the session id part of it
-         */
-        char *old_sessid = multi->auth_token + strlen(SESSION_ID_PREFIX);
+        /* Make a copy of the string to not modify multi->auth_token_initial */
+        char *initial_token_copy = string_alloc(multi->auth_token_initial, &gc);
+
+        char *old_sessid = initial_token_copy + strlen(SESSION_ID_PREFIX);
         char *old_tsamp_initial = old_sessid + AUTH_TOKEN_SESSION_ID_LEN*8/6;

You've introduced the new constant but you're substituted it here ^ :-(

Quoted 49 lines
src/openvpn/auth_token.c +16 -6
+        /*
+         * We null terminate the old token just after the session ID to let
+         * our base64 decode function only decode the session ID
+         */
         old_tsamp_initial[12] = '\0';
         ASSERT(openvpn_base64_decode(old_tsamp_initial, old_tstamp_decode, 9) == 9);
 
@@ -211,11 +216,7 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
         initial_timestamp = *tstamp_ptr;
 
         old_tsamp_initial[0] = '\0';
-        ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSION_ID_LEN)==AUTH_TOKEN_SESSION_ID_LEN);
-
-
-        /* free the auth-token, we will replace it with a new one */
-        free(multi->auth_token);
+        ASSERT(openvpn_base64_decode(old_sessid, sessid, AUTH_TOKEN_SESSION_ID_LEN) == AUTH_TOKEN_SESSION_ID_LEN);
     }
     else if (!rand_bytes(sessid, AUTH_TOKEN_SESSION_ID_LEN))
     {
@@ -272,11 +273,22 @@ generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
 
     free(b64output);
 
+    /* free the auth-token if defined, we will replace it with a new one */
+    free(multi->auth_token);
     multi->auth_token = strdup((char *)BPTR(&session_token));
 
     dmsg(D_SHOW_KEYS, "Generated token for client: %s (%s)",
          multi->auth_token, up->username);
 
+    if (!multi->auth_token_initial)
+    {
+        /*
+         * Save the initial auth token to continue using the same session ID
+         * and timestamp in updates
+         */
+        multi->auth_token_initial = strdup(multi->auth_token);
+    }
+
     gc_free(&gc);
 }
 
@@ -343,23 +355,17 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi,
     }
     else
     {
-        msg(M_WARN, "--auth-token-gen: HMAC on token from client failed (%s)",

src/openvpn/auth_token.c verify_auth_token(struct user_pass *up, struct tls_multi *multi, · line 366

Quoted 10 lines
src/openvpn/auth_token.c +2 -1
+        msg(M_WARN, "--auth-gen-token: HMAC on token from client failed (%s)",
             up->username);
         return 0;
     }
 
     /* Accept session tokens that not expired are in the acceptable range
      * for renogiations */
-    bool in_renog_time = now >= timestamp
+    bool in_renegotiation_time = now >= timestamp
                          && now < timestamp + 2 * session->opt->renegotiate_seconds;

This second line should now be re-aligned..

Quoted 306 lines
src/openvpn/auth_token.c +39 -8
-    /* We could still have a client that does not update
-     * its auth-token, so also allow the initial auth-token */
-    bool initialtoken = multi->auth_token_initial
-                        && memcmp_constant_time(up->password, multi->auth_token_initial,
-                                                strlen(multi->auth_token_initial)) == 0;
-
-    if (!in_renog_time && !initialtoken)
+    if (!in_renegotiation_time)
     {
         ret |= AUTH_TOKEN_EXPIRED;
     }
@@ -383,7 +389,20 @@ verify_auth_token(struct user_pass *up, struct tls_multi *multi,
     {
         /* Tell client that the session token is expired */
         auth_set_client_reason(multi, "SESSION: token expired");
-        msg(M_INFO, "--auth-token-gen: auth-token from client expired");
+        msg(M_INFO, "--auth-gen-token: auth-token from client expired");
+    }
+
+    /* Check that we do have the same session ID in the token as in our stored
+     * auth-token to ensure that it did not change.
+     * This also compares the prefix and session part of the
+     * tokens, which should be identical if the session ID stayed the same */
+    if (multi->auth_token_initial
+        && memcmp_constant_time(multi->auth_token_initial, up->password,
+                                strlen(SESSION_ID_PREFIX) + AUTH_TOKEN_SESSION_ID_BASE64_LEN))
+    {
+        msg(M_WARN, "--auth-gen-token: session id in token changed (Rejecting "
+                    "token.");
+        ret = 0;
     }
     return ret;
 }
@@ -408,3 +427,27 @@ wipe_auth_token(struct tls_multi *multi)
         multi->auth_token_initial = NULL;
     }
 }
+
+void
+resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session)
+{
+    /*
+     * Auth token already sent to client, update auth-token on client.
+     * The initial auth-token is sent as part of the push message, for this
+     * update we need to schedule an extra push message.
+     *
+     * Otherwise the auth-token get pushed out as part of the "normal"
+     * push-reply
+     */
+    bool is_renegotiation = session->key[KS_PRIMARY].key_id != 0;
+
+    if (multi->auth_token_initial && is_renegotiation)
+    {
+        /*
+         * We do not explicitly reschedule the sending of the
+         * control message here. This might delay this reply
+         * a few seconds but this message is not time critical
+         */
+        send_push_reply_auth_token(multi);
+    }
+}
\ No newline at end of file
src/openvpn/auth_token.h +10 -1
index 73a00ddd7..de93a9413 100644
@@ -117,7 +117,7 @@ void wipe_auth_token(struct tls_multi *multi);
 /**
  * Return if the password string has the format of a password.
  *
- * This fuction will always read as many bytes as SESSION_ID_PREFIX is longer
+ * This function will always read as many bytes as SESSION_ID_PREFIX is longer
  * the caller needs ensure that password memory is at least that long (true for
  * calling with struct user_pass)
  * @param password
@@ -129,4 +129,13 @@ is_auth_token(const char *password)
     return (memcmp_constant_time(SESSION_ID_PREFIX, password,
                                  strlen(SESSION_ID_PREFIX)) == 0);
 }
+/**
+ * Checks if a client should be sent a new auth token to update its
+ * current auth-token
+ * @param multi     Pointer the multi object of the TLS session
+ * @param session   Pointer to the TLS session itself
+ */
+void
+resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session);
+
 #endif /* AUTH_TOKEN_H */
src/openvpn/push.c +0 -8
index f4957f147..53cb7ca6f 100644
@@ -527,14 +527,6 @@ prepare_auth_token_push_reply(struct tls_multi *tls_multi, struct gc_arena *gc,
         push_option_fmt(gc, push_list, M_USAGE,
                         "auth-token %s",
                         tls_multi->auth_token);
-        if (!tls_multi->auth_token_initial)
-        {
-            /*
-             * Save the initial auth token for clients that ignore
-             * the updates to the token
-             */
-            tls_multi->auth_token_initial = strdup(tls_multi->auth_token);
-        }
     }
 }
 
src/openvpn/ssl.c +6 -1
index 615ed69e5..e9b8d1b92 100644
@@ -3115,13 +3115,18 @@ tls_multi_process(struct tls_multi *multi,
 
             if (ks->state == S_ACTIVE && ks->authenticated == KS_AUTH_TRUE)
             {
-                /* This will move ks->state from S_ACTIVE to S_GENERATED_KEYS */
+                /* Session is now fully authenticated.
+                 * tls_session_generate_data_channel_keys will move ks->state
+                 * from S_ACTIVE to S_GENERATED_KEYS */
                 if (!tls_session_generate_data_channel_keys(session))
                 {
                     msg(D_TLS_ERRORS, "TLS Error: generate_key_expansion failed");
                     ks->authenticated = KS_AUTH_FALSE;
                     ks->state = S_ERROR;
                 }
+
+                /* Update auth token on the client if needed */
+                resend_auth_token_renegotiation(multi, session);
             }
         }
     }
src/openvpn/ssl_common.h +6 -3
index 72eb55bd3..64c1d53f3 100644
@@ -95,7 +95,10 @@
                                  *   completed while still within the
                                  *   handshake window.  Deferred auth and
                                  *   client connect can still be pending. */
-#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated */
+#define S_GENERATED_KEYS  7     /**< The data channel keys have been generated
+                                  *  The TLS session is fully authenticated
+                                  *  when reaching this state. */
+
 /* Note that earlier versions also had a S_OP_NORMAL state that was
  * virtually identical with S_ACTIVE and the code still assumes everything
  * >= S_ACTIVE to be fully operational */
@@ -596,8 +599,8 @@ struct tls_multi
                           *   user/pass authentications in this session.
                           */
     char *auth_token_initial;
-    /**< The first auth-token we sent to a client, for clients that do
-     * not update their auth-token (older OpenVPN3 core versions)
+    /**< The first auth-token we sent to a client. We use this to remember
+     * the session ID and initial timestamp when generating new auth-token.
      */
 #define  AUTH_TOKEN_HMAC_OK              (1<<0)
     /**< Auth-token sent from client has valid hmac */
src/openvpn/ssl_verify.c +10 -21
index bbb1878a3..913c95620 100644
@@ -1512,6 +1512,15 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
     if (session->opt->auth_token_generate && is_auth_token(up->password))
     {
         ks->auth_token_state_flags = verify_auth_token(up, multi, session);
+
+        /* If this is the first time we see an auth-token in this multi session,
+         * save it as initial auth token. This ensures using the
+         * same session ID and initial timestamp in new tokens */
+        if (!multi->auth_token_initial)
+        {
+            multi->auth_token_initial = strdup(up->password);
+        }
+
         if (session->opt->auth_token_call_auth)
         {
             /*
@@ -1631,27 +1640,7 @@ verify_user_pass(struct user_pass *up, struct tls_multi *multi,
              */
             generate_auth_token(up, multi);
         }
-        /*
-         * Auth token already sent to client, update auth-token on client.
-         * The initial auth-token is sent as part of the push message, for this
-         * update we need to schedule an extra push message.
-         *
-         * Otherwise the auth-token get pushed out as part of the "normal"
-         * push-reply
-         */
-        if (multi->auth_token_initial)
-        {
-            /*
-             * We do not explicitly schedule the sending of the
-             * control message here but control message are only
-             * postponed when the control channel  is not yet fully
-             * established and furthermore since this is called in
-             * the middle of authentication, there are other messages
-             * (new data channel keys) that are sent anyway and will
-             * trigger schedueling
-             */
-            send_push_reply_auth_token(multi);
-        }
+
         msg(D_HANDSHAKE, "TLS: Username/Password authentication %s for username '%s' %s",
             (ks->authenticated == KS_AUTH_DEFERRED) ? "deferred" : "succeeded",
             up->username,
tests/unit_tests/openvpn/test_auth_token.c +39 -9
index 4030052e0..6bfad6efb 100644
@@ -174,7 +174,10 @@ auth_token_test_timeout(void **state)
 
     now = 100000;
     generate_auth_token(&ctx->up, &ctx->multi);
+
     strcpy(ctx->up.password, ctx->multi.auth_token);
+    free(ctx->multi.auth_token_initial);
+    ctx->multi.auth_token_initial = NULL;
 
     /* No time has passed */
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
@@ -195,11 +198,6 @@ auth_token_test_timeout(void **state)
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
                      AUTH_TOKEN_HMAC_OK|AUTH_TOKEN_EXPIRED);
 
-    /* Check if the mode for a client that never updates its token works */
-    ctx->multi.auth_token_initial = strdup(ctx->up.password);
-    assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
-                     AUTH_TOKEN_HMAC_OK);
-
     /* But not when we reached our timeout */
     now = 100000 + ctx->session->opt->auth_token_lifetime + 1;
     assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
@@ -244,10 +242,10 @@ auth_token_test_known_keys(void **state)
 
     now = 0;
     /* Preload the session id so the same session id is used here */
-    ctx->multi.auth_token = strdup(now0key0);
+    ctx->multi.auth_token_initial = strdup(now0key0);
 
     /* Zero the hmac part to ensure we have a newly generated token */
-    zerohmac(ctx->multi.auth_token);
+    zerohmac(ctx->multi.auth_token_initial);
 
     generate_auth_token(&ctx->up, &ctx->multi);
 
@@ -268,6 +266,38 @@ setenv_str(struct env_set *es, const char *name, const char *value)
     }
 }
 
+void
+auth_token_test_session_mismatch(void **state)
+{
+    struct test_context *ctx = (struct test_context *) *state;
+
+    /* Generate first auth token and check it is correct */
+    generate_auth_token(&ctx->up, &ctx->multi);
+    strcpy(ctx->up.password, ctx->multi.auth_token);
+    assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
+                     AUTH_TOKEN_HMAC_OK);
+
+    char *token_sessiona = strdup(ctx->multi.auth_token);
+
+    /* Generate second token */
+    wipe_auth_token(&ctx->multi);
+
+    generate_auth_token(&ctx->up, &ctx->multi);
+    strcpy(ctx->up.password, ctx->multi.auth_token);
+    assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session),
+                     AUTH_TOKEN_HMAC_OK);
+
+    assert_int_not_equal(0, memcmp(ctx->multi.auth_token_initial + strlen(SESSION_ID_PREFIX),
+                                   token_sessiona + strlen(SESSION_ID_PREFIX),
+                                   AUTH_TOKEN_SESSION_ID_BASE64_LEN));
+
+    /* The first token is valid but should trigger the invalid response since
+     * the session id is not the same */
+    strcpy(ctx->up.password, token_sessiona);
+    assert_int_equal(verify_auth_token(&ctx->up, &ctx->multi, ctx->session), 0);
+    free(token_sessiona);
+}
+
 static void
 auth_token_test_empty_user(void **state)
 {
@@ -341,13 +371,13 @@ auth_token_test_random_keys(void **state)
 
     now = 0x5c331e9c;
     /* Preload the session id so the same session id is used here */
-    ctx->multi.auth_token = strdup(random_token);
+    ctx->multi.auth_token_initial = strdup(random_token);
 
     free_key_ctx(&ctx->multi.opt.auth_token_key);
     auth_token_init_secret(&ctx->multi.opt.auth_token_key, random_key, true);
 
     /* Zero the hmac part to ensure we have a newly generated token */
-    zerohmac(ctx->multi.auth_token);
+    zerohmac(ctx->multi.auth_token_initial);
 
     generate_auth_token(&ctx->up, &ctx->multi);
 

tests/unit_tests/openvpn/test_auth_token.c main(void) · line 421

Quoted 7 lines
tests/unit_tests/openvpn/test_auth_token.c +1 -0
@@ -385,6 +415,7 @@ main(void)
         cmocka_unit_test_setup_teardown(auth_token_test_random_keys, setup, teardown),
         cmocka_unit_test_setup_teardown(auth_token_test_key_load, setup, teardown),
         cmocka_unit_test_setup_teardown(auth_token_test_timeout, setup, teardown),
+        cmocka_unit_test_setup_teardown(auth_token_test_session_mismatch, setup, teardown)
     };
 
 #if defined(ENABLE_CRYPTO_OPENSSL)

Other than the few cosmetic issues mentioned above, this patch looks good to me and passed my tests.

I am not sure if a new patch is required to substitute the hardcoded computation with the new constant. maybe Gert can do that :)

Signature · 1 line
Antonio Quartulli
Acked-by on v2 8/9
#51 lore raw

Re: [Openvpn-devel] [PATCH v2 8/9] Remove --ncp-disable option

In reply to Arne Schwabe

Hi,

Quoted 10 lines · Arne Schwabe

NCP has proven to be stable and apart from the one VPN Provider doing hacky things with homebrewed NCP we have not had any reports about ncp-disable being required. Remove ncp-disable to simplify code paths.

Note: This patch breaks client without --pull. The follow up patch for P2P NCP will restore that. But to avoid all the NCP/non-NCP special cases to be implemented in P2P. P2P will directly switch from always non-NCP to always NCP.

I tested this patch on top of master and against master, 2.5 and 2.4 (2.3 did not compile and I did not want to check why) and I alternated server and client.

Everything works also when the server is running 2.4 with --ncp-disabled and the client is master+this-patch.

Change also looks good and it is fairly contained.

Quoted 277 lines
---
 Changes.rst                           |  4 +++
 doc/man-sections/protocol-options.rst |  8 ++----
 src/openvpn/init.c                    | 17 ++++---------
 src/openvpn/multi.c                   |  4 ---
 src/openvpn/options.c                 | 36 +++------------------------
 src/openvpn/options.h                 |  1 -
 src/openvpn/ssl.c                     |  3 +--
 src/openvpn/ssl_common.h              |  1 -
 src/openvpn/ssl_ncp.c                 |  4 ---
 9 files changed, 16 insertions(+), 62 deletions(-)
Changes.rst +4 -0
index 9185b55f7..e7ae6abed 100644
@@ -57,6 +57,10 @@ Deprecated features
     is considered "too complicated", using ``--peer-fingerprint`` makes
     TLS mode about as easy as using ``--secret``.
 
+``ncp-disable`` has been removed
+    This option mainly served a role as debug option when NCP was first
+    introduced. It should now no longer be necessary.
+
 Overview of changes in 2.5
 ==========================
 
doc/man-sections/protocol-options.rst +2 -6
index 34d4255ee..5ae780e1f 100644
@@ -65,8 +65,8 @@ configured in a compatible way between both the local and remote side.
   The default is :code:`BF-CBC`, an abbreviation for Blowfish in Cipher
   Block Chaining mode. When cipher negotiation (NCP) is allowed,
   OpenVPN 2.4 and newer on both client and server side will automatically
-  upgrade to :code:`AES-256-GCM`.  See ``--data-ciphers`` and
-  ``--ncp-disable`` for more details on NCP.
+  upgrade to :code:`AES-256-GCM`.  See ``--data-ciphers`` for more details
+  on NCP.
 
   Using :code:`BF-CBC` is no longer recommended, because of its 64-bit
   block size. This small block size allows attacks based on collisions, as
@@ -235,10 +235,6 @@ configured in a compatible way between both the local and remote side.
     have been configured with `--enable-small`
     (typically used on routers or other embedded devices).
 
---ncp-disable
-  **DEPRECATED** Disable "Negotiable Crypto Parameters". This completely
-  disables cipher negotiation.
-
 --secret args
   **DEPRECATED** Enable Static Key encryption mode (non-TLS). Use pre-shared secret
   ``file`` which was generated with ``--genkey``.
src/openvpn/init.c +5 -12
index 4335d4870..38abf9f3a 100644
@@ -2227,18 +2227,14 @@ pull_permission_mask(const struct context *c)
         | OPT_P_EXPLICIT_NOTIFY
         | OPT_P_ECHO
         | OPT_P_PULL_MODE
-        | OPT_P_PEER_ID;
+        | OPT_P_PEER_ID
+        | OPT_P_NCP;
 
     if (!c->options.route_nopull)
     {
         flags |= (OPT_P_ROUTE | OPT_P_IPWIN32);
     }
 
-    if (c->options.ncp_enabled)
-    {
-        flags |= OPT_P_NCP;
-    }
-
     return flags;
 }
 
@@ -2720,8 +2716,6 @@ do_init_crypto_tls_c1(struct context *c)
         *
         * Therefore, the key structure has to be initialized when:
         * - any non-BF-CBC cipher was selected; or
-        * - BF-CBC is selected and NCP is disabled (explicit request to
-        *   use the BF-CBC cipher); or
         * - BF-CBC is selected, NCP is enabled and fallback is enabled
         *   (BF-CBC will be the fallback).
         * - BF-CBC is in data-ciphers and we negotiate to use BF-CBC:
@@ -2731,12 +2725,12 @@ do_init_crypto_tls_c1(struct context *c)
         * Note that BF-CBC will still be part of the OCC string to retain
         * backwards compatibility with older clients.
         */
-        if (!streq(options->ciphername, "BF-CBC") || !options->ncp_enabled
-            || (options->ncp_enabled && tls_item_in_cipher_list("BF-CBC", options->ncp_ciphers))
+        if (!streq(options->ciphername, "BF-CBC")
+            || tls_item_in_cipher_list("BF-CBC", options->ncp_ciphers)
             || options->enable_ncp_fallback)
         {
             /* Do not warn if the if the cipher is used only in OCC */
-            bool warn = !options->ncp_enabled || options->enable_ncp_fallback;
+            bool warn = options->enable_ncp_fallback;
             init_key_type(&c->c1.ks.key_type, options->ciphername, options->authname,
                           true, warn);
         }
@@ -2838,7 +2832,6 @@ do_init_crypto_tls(struct context *c, const unsigned int flags)
     to.tcp_mode = link_socket_proto_connection_oriented(options->ce.proto);
     to.config_ciphername = c->options.ciphername;
     to.config_ncp_ciphers = c->options.ncp_ciphers;
-    to.ncp_enabled = options->ncp_enabled;
     to.transition_window = options->transition_window;
     to.handshake_window = options->handshake_window;
     to.packet_timeout = options->tls_timeout;
src/openvpn/multi.c +0 -4
index 7cb9e86aa..2507108e2 100644
@@ -1791,10 +1791,6 @@ multi_client_set_protocol_options(struct context *c)
 #endif
 
     /* Select cipher if client supports Negotiable Crypto Parameters */
-    if (!o->ncp_enabled)
-    {
-        return true;
-    }
 
     /* if we have already created our key, we cannot *change* our own
      * cipher -> so log the fact and push the "what we have now" cipher
src/openvpn/options.c +4 -32
index fa3ee50d6..2f4ccaa09 100644
@@ -526,7 +526,6 @@ static const char usage_message[] =
     "                  (default=%s).\n"
     "                  Set alg=none to disable encryption.\n"
     "--data-ciphers list : List of ciphers that are allowed to be negotiated.\n"
-    "--ncp-disable   : (DEPRECATED) Disable cipher negotiation.\n"
     "--prng alg [nsl] : For PRNG, use digest algorithm alg, and\n"
     "                   nonce_secret_len=nsl.  Set alg=none to disable PRNG.\n"
 #ifndef ENABLE_CRYPTO_MBEDTLS
@@ -843,7 +842,6 @@ init_options(struct options *o, const bool init_gc)
     o->stale_routes_check_interval = 0;
     o->ifconfig_pool_persist_refresh_freq = 600;
     o->scheduled_exit_interval = 5;
-    o->ncp_enabled = true;
     o->ncp_ciphers = "AES-256-GCM:AES-128-GCM";
     o->authname = "SHA1";
     o->prng_hash = "SHA1";
@@ -1719,7 +1717,6 @@ show_settings(const struct options *o)
     SHOW_STR_INLINE(shared_secret_file);
     SHOW_PARM(key_direction, keydirection2ascii(o->key_direction, false, true), "%s");
     SHOW_STR(ciphername);
-    SHOW_BOOL(ncp_enabled);
     SHOW_STR(ncp_ciphers);
     SHOW_STR(authname);
     SHOW_STR(prng_hash);
@@ -3082,7 +3079,6 @@ options_postprocess_cipher(struct options *o)
     if (!o->pull && !(o->mode == MODE_SERVER))
     {
         /* we are in the classic P2P mode */
-        o->ncp_enabled = false;
         msg( M_WARN, "Cipher negotiation is disabled since neither "
              "P2MP client nor server mode is enabled");
 
@@ -3099,18 +3095,6 @@ options_postprocess_cipher(struct options *o)
     /* pull or P2MP mode */
     if (!o->ciphername)
     {
-        if (!o->ncp_enabled)
-        {
-            msg(M_USAGE, "--ncp-disable needs an explicit --cipher or "
-                         "--data-ciphers-fallback config option");
-        }
-
-        msg(M_WARN, "--cipher is not set. Previous OpenVPN version defaulted to "
-            "BF-CBC as fallback when cipher negotiation failed in this case. "
-            "If you need this fallback please add '--data-ciphers-fallback "
-            "BF-CBC' to your configuration and/or add BF-CBC to "
-            "--data-ciphers.");
-
         /* We still need to set the ciphername to BF-CBC since various other
          * parts of OpenVPN assert that the ciphername is set */
         o->ciphername = "BF-CBC";
@@ -3152,13 +3136,10 @@ options_postprocess_mutate(struct options *o)
     options_postprocess_cipher(o);
     options_postprocess_mutate_invariant(o);
 
-    if (o->ncp_enabled)
+    o->ncp_ciphers = mutate_ncp_cipher_list(o->ncp_ciphers, &o->gc);
+    if (o->ncp_ciphers == NULL)
     {
-        o->ncp_ciphers = mutate_ncp_cipher_list(o->ncp_ciphers, &o->gc);
-        if (o->ncp_ciphers == NULL)
-        {
-            msg(M_USAGE, "NCP cipher list contains unsupported ciphers or is too long.");
-        }
+        msg(M_USAGE, "NCP cipher list contains unsupported ciphers or is too long.");
     }
 
     if (o->remote_list && !o->connection_list)
@@ -3908,8 +3889,7 @@ options_string(const struct options *o,
         }
         /* Only announce the cipher to our peer if we are willing to
          * support it */
-        if (p2p_nopull || !o->ncp_enabled
-            || tls_item_in_cipher_list(ciphername, o->ncp_ciphers))
+        if (p2p_nopull || tls_item_in_cipher_list(ciphername, o->ncp_ciphers))
         {
             buf_printf(&out, ",cipher %s", ciphername);
         }
@@ -7994,14 +7974,6 @@ add_option(struct options *options,
             msg(msglevel, "Unknown key-derivation method %s", p[1]);
         }
     }
-    else if (streq(p[0], "ncp-disable") && !p[1])
-    {
-        VERIFY_PERMISSION(OPT_P_GENERAL|OPT_P_INSTANCE);
-        options->ncp_enabled = false;
-        msg(M_WARN, "DEPRECATED OPTION: ncp-disable. Disabling "
-            "cipher negotiation is a deprecated debug feature that "
-            "will be removed in OpenVPN 2.6");
-    }
     else if (streq(p[0], "prng") && p[1] && !p[3])
     {
         VERIFY_PERMISSION(OPT_P_GENERAL);
src/openvpn/options.h +0 -1
index 41e84f7e1..69897c5a7 100644
@@ -512,7 +512,6 @@ struct options
     const char *ciphername;
     bool enable_ncp_fallback;      /**< If defined fall back to
                                     * ciphername if NCP fails */
-    bool ncp_enabled;
     const char *ncp_ciphers;
     const char *authname;
     const char *prng_hash;
src/openvpn/ssl.c +1 -2
index b28d8edf8..dd6e462d0 100644
@@ -2187,8 +2187,7 @@ push_peer_info(struct buffer *buf, struct tls_session *session)
         }
 
         /* support for Negotiable Crypto Parameters */
-        if (session->opt->ncp_enabled
-            && (session->opt->mode == MODE_SERVER || session->opt->pull))
+        if (session->opt->mode == MODE_SERVER || session->opt->pull)
         {
             if (tls_item_in_cipher_list("AES-128-GCM", session->opt->config_ncp_ciphers)
                 && tls_item_in_cipher_list("AES-256-GCM", session->opt->config_ncp_ciphers))
src/openvpn/ssl_common.h +0 -1
index 928e80929..43af51ee9 100644
@@ -324,7 +324,6 @@ struct tls_options
 
     const char *config_ciphername;
     const char *config_ncp_ciphers;
-    bool ncp_enabled;
 
     bool tls_crypt_v2;
     const char *tls_crypt_v2_verify_script;
src/openvpn/ssl_ncp.c +0 -4
index f02a3103c..722256b42 100644
@@ -289,10 +289,6 @@ check_pull_client_ncp(struct context *c, const int found)
         return true;
     }
 
-    if (!c->options.ncp_enabled)
-    {
-        return true;
-    }
     /* If the server did not push a --cipher, we will switch to the
      * remote cipher if it is in our ncp-ciphers list */
     if(tls_poor_mans_ncp(&c->options, c->c2.tls_multi->remote_ciphername))
Signature · 1 line
Antonio Quartulli
#54 lore raw

Re: [Openvpn-devel] [PATCH v2 9/9] Support NCP in pure P2P VPN setups

In reply to Arne Schwabe

Hi,

This patch does not apply on top of master + v6-cleanup + 8/9 Can you rebase it? or maybe you you can point me to some commit in your branch that I can pull for now?

Cheers,

Signature · 1 line
Antonio Quartulli
#55 lore raw

Re: [Openvpn-devel] [PATCH v2 9/9] Support NCP in pure P2P VPN setups

Am 20.07.21 um 02:00 schrieb Antonio Quartulli:

Quoted 9 lines

Hi,

This patch does not apply on top of master + v6-cleanup + 8/9 Can you rebase it? or maybe you you can point me to some commit in your branch that I can pull for now?

Cheers,

Sure the dco branch on github.com/schwabe/openvpn is up to date.

Arne

#56 lore raw

Re: [Openvpn-devel] [PATCH v2 9/9] Support NCP in pure P2P VPN setups

In reply to Arne Schwabe

Hi,

Quoted 58 lines · Arne Schwabe

Currently P2P mode of OpenVPN is on of the few places that cannot negotiate modern OpenVPN features. This becomes more and more problematic since P2P and P2MP code diverge more and more and also the lack of switching to more advanced features like Data v2 currently blocks P2P mode from working together with the upcoming ovpn-dco support.

This NCP support is a lot simpler and works in the following way:

- P2P peer announce an extremely limited IV_ variable set (IV_PROTO and IV_CIPHERS)
- Both peers check if the IV_PROTO_NCP_P2P bit is present in IV_PROTO
- if yes both sides deterministically determine according to IV_PROTO and IV_CIPHER what options can be used and start using these

There are no poor man's NCP or other compatibility workaround like in the normal NCP, making this NCP leaner and more deterministic.

---
 src/openvpn/init.c                  | 100 ++++++++++++++++---
 src/openvpn/options.c               |   8 +-
 src/openvpn/ssl.c                   | 120 +++++++++++++++--------
 src/openvpn/ssl.h                   |   5 +
 src/openvpn/ssl_backend.h           |   1 +
 src/openvpn/ssl_common.h            |  10 ++
 src/openvpn/ssl_ncp.c               | 145 ++++++++++++++++++++++++++++
 src/openvpn/ssl_ncp.h               |  25 +++++
 tests/unit_tests/openvpn/test_ncp.c |  11 +++
 9 files changed, 366 insertions(+), 59 deletions(-)
src/openvpn/init.c +9 -0
index 38abf9f3a..5d4852ae1 100644
@@ -68,6 +68,7 @@ static const char *saved_pid_file_name; /* GLOBAL */
 #define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
 
 static void do_init_first_time(struct context *c);
+static bool do_deferred_p2p_ncp(struct context *c);
 
 void
 context_clear(struct context *c)
@@ -2151,6 +2152,14 @@ do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
                 return false;
             }
         }
+        else if (c->mode == MODE_POINT_TO_POINT)
+        {
+            if (!do_deferred_p2p_ncp(c))
+            {
+                msg(D_TLS_ERRORS, "ERROR: Failed to apply P2P negotiated protocol options");
+                return false;
+            }
+        }
 
         /* if --up-delay specified, open tun, do ifconfig, and run up script now */
         if (c->options.up_delay || PULL_DEFINED(&c->options))

src/openvpn/init.c pull_permission_mask(const struct context *c) · line 2253

Quoted 7 lines
src/openvpn/init.c +4 -0
@@ -2238,6 +2247,72 @@ pull_permission_mask(const struct context *c)
     return flags;
 }
 
+static
+void adjust_mtu_peerid(struct context *c)
+{
+    frame_add_to_extra_frame(&c->c2.frame, +3);     /* peer-id overhead */

any reason for the '+' before the '3'? I don't think we do that anywhere else :)

src/openvpn/init.c pull_permission_mask(const struct context *c) · line 2264

Quoted 11 lines
src/openvpn/init.c +11 -0
+    if (!c->options.ce.link_mtu_defined)
+    {
+        frame_add_to_link_mtu(&c->c2.frame, +3);
+        msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
+            EXPANDED_SIZE(&c->c2.frame));
+    }
+    else
+    {
+        msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
+                    " fixed by config - reducing tun-mtu to %d, expect"
+                    " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );

there should be no space before the last ')'

On top of that, this message seems too pessimistic? maybe the MTU was configured with a reasonably low value so everything will just work.

Maybe the message can be rephrased as: "reducing tun-mtu to %d, the connection may experience issues if the configured value is not correct"

src/openvpn/init.c pull_permission_mask(const struct context *c) · line 2271

Quoted 7 lines
src/openvpn/init.c +7 -0
+    }
+}
+
+static bool
+do_deferred_p2p_ncp(struct context *c)
+{
+

this empty line should go

Quoted 13 lines
src/openvpn/init.c +13 -0
+    if (!c->c2.tls_multi)
+    {
+        return true;
+    }
+
+    if (c->c2.tls_multi->use_peer_id)
+    {
+        adjust_mtu_peerid(c);
+    }
+
+    struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
+
+    const char *ncp_cipher = get_p2p_ncp_cipher(session, c->c2.tls_multi->peer_info,

src/openvpn/init.c pull_permission_mask(const struct context *c) · line 2294

Quoted 10 lines
src/openvpn/init.c +10 -0
+                                                &c->options.gc);
+
+    if (ncp_cipher)
+    {
+        c->options.ciphername = ncp_cipher;
+    }
+    else if (!c->options.enable_ncp_fallback)
+    {
+        msg(D_TLS_ERRORS, "ERROR: failed to negotiate cipher with peer and "
+                          "--data-ciphers-fallback not enabled. No useable "

useable -> usable

Quoted 101 lines
src/openvpn/init.c +30 -16
+                          "data channel cipher");
+        return false;
+    }
+
+    struct frame *frame_fragment = NULL;
+#ifdef ENABLE_FRAGMENT
+    if (c->options.ce.fragment)
+    {
+        frame_fragment = &c->c2.frame_fragment;
+    }
+#endif
+
+    if (!tls_session_update_crypto_params(session, &c->options, &c->c2.frame,
+                                         frame_fragment))
+    {
+        msg(D_TLS_ERRORS, "ERROR: failed to set crypto cipher");
+        return false;
+    }
+    return true;
+}
+
 /*
  * Handle non-tun-related pulled options.
  */
@@ -2325,19 +2400,7 @@ do_deferred_options(struct context *c, const unsigned int found)
         msg(D_PUSH, "OPTIONS IMPORT: peer-id set");
         c->c2.tls_multi->use_peer_id = true;
         c->c2.tls_multi->peer_id = c->options.peer_id;
-        frame_add_to_extra_frame(&c->c2.frame, +3);     /* peer-id overhead */
-        if (!c->options.ce.link_mtu_defined)
-        {
-            frame_add_to_link_mtu(&c->c2.frame, +3);
-            msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
-                EXPANDED_SIZE(&c->c2.frame));
-        }
-        else
-        {
-            msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
-                " fixed by config - reducing tun-mtu to %d, expect"
-                " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );
-        }
+        adjust_mtu_peerid(c);
     }
 
     /* process (potentially pushed) crypto options */
@@ -2856,16 +2919,21 @@ do_init_crypto_tls(struct context *c, const unsigned int flags)
     to.pull = options->pull;
     if (options->push_peer_info)        /* all there is */
     {
-        to.push_peer_info_detail = 2;
+        to.push_peer_info_detail = 3;
     }
     else if (options->pull)             /* pull clients send some details */
     {
-        to.push_peer_info_detail = 1;
+        to.push_peer_info_detail = 2;
     }
-    else                                /* default: no peer-info at all */
+    else if (options->mode == MODE_SERVER) /* server: no peer info at all */
     {
         to.push_peer_info_detail = 0;
     }
+    else                  /* default: minimal info to allow NCP in P2P mode */
+    {
+        to.push_peer_info_detail = 1;
+    }
+
 
     /* should we not xmit any packets until we get an initial
      * response from client? */
src/openvpn/options.c +4 -4
index 2f4ccaa09..9cd88a36e 100644
@@ -3078,10 +3078,6 @@ options_postprocess_cipher(struct options *o)
 {
     if (!o->pull && !(o->mode == MODE_SERVER))
     {
-        /* we are in the classic P2P mode */
-        msg( M_WARN, "Cipher negotiation is disabled since neither "
-             "P2MP client nor server mode is enabled");
-
         /* If the cipher is not set, use the old default of BF-CBC. We will
          * warn that this is deprecated on cipher initialisation, no need
          * to warn here as well */
@@ -3089,6 +3085,10 @@ options_postprocess_cipher(struct options *o)
         {
             o->ciphername = "BF-CBC";
         }
+        else
+        {
+            o->enable_ncp_fallback = true;
+        }
         return;
     }
 
src/openvpn/ssl.c +0 -0
index dd6e462d0..8a02a2006 100644

src/openvpn/ssl.c cleanup: · line 1877

Quoted 4 lines
src/openvpn/ssl.c +1 -0
@@ -1874,33 +1874,18 @@ cleanup:
     return ret;
 }
 
+

this empty line can go

Quoted 106 lines
src/openvpn/ssl.c +42 -23
 bool
-tls_session_update_crypto_params(struct tls_session *session,
-                                 struct options *options, struct frame *frame,
+tls_session_update_crypto_params_do_work(struct tls_session *session,
+                                 struct options* options, struct frame *frame,
                                  struct frame *frame_fragment)
 {
     if (session->key[KS_PRIMARY].crypto_options.key_ctx_bi.initialized)
     {
         /* keys already generated, nothing to do */
         return true;
-    }
 
-    bool cipher_allowed_as_fallback = options->enable_ncp_fallback
-                                      && streq(options->ciphername, session->opt->config_ciphername);
-
-    if (!session->opt->server && !cipher_allowed_as_fallback
-        && !tls_item_in_cipher_list(options->ciphername, options->ncp_ciphers))
-    {
-        msg(D_TLS_ERRORS, "Error: pushed cipher not allowed - %s not in %s",
-            options->ciphername, options->ncp_ciphers);
-        /* undo cipher push, abort connection setup */
-        options->ciphername = session->opt->config_ciphername;
-        return false;
     }
-
-    /* Import crypto settings that might be set by pull/push */
-    session->opt->crypto_flags |= options->data_channel_crypto_flags;
-
     if (strcmp(options->ciphername, session->opt->config_ciphername))
     {
         msg(D_HANDSHAKE, "Data Channel: using negotiated cipher '%s'",
@@ -1952,6 +1937,32 @@ tls_session_update_crypto_params(struct tls_session *session,
     return tls_session_generate_data_channel_keys(session);
 }
 
+bool
+tls_session_update_crypto_params(struct tls_session *session,
+                                 struct options *options, struct frame *frame,
+                                 struct frame *frame_fragment)
+{
+
+    bool cipher_allowed_as_fallback = options->enable_ncp_fallback
+        && streq(options->ciphername, session->opt->config_ciphername);
+
+    if (!session->opt->server && !cipher_allowed_as_fallback
+        && !tls_item_in_cipher_list(options->ciphername, options->ncp_ciphers))
+    {
+        msg(D_TLS_ERRORS, "Error: negotiated cipher not allowed - %s not in %s",
+            options->ciphername, options->ncp_ciphers);
+        /* undo cipher push, abort connection setup */
+        options->ciphername = session->opt->config_ciphername;
+        return false;
+    }
+
+    /* Import crypto settings that might be set by pull/push */
+    session->opt->crypto_flags |= options->data_channel_crypto_flags;
+
+    return tls_session_update_crypto_params_do_work(session, options, frame, frame_fragment);
+}
+
+
 static bool
 random_bytes_to_buf(struct buffer *buf,
                     uint8_t *out,
@@ -2145,12 +2156,10 @@ push_peer_info(struct buffer *buf, struct tls_session *session)
 {
     struct gc_arena gc = gc_new();
     bool ret = false;
+    struct buffer out = alloc_buf_gc(512 * 3, &gc);
 
-    if (session->opt->push_peer_info_detail > 0)
+    if (session->opt->push_peer_info_detail > 1)
     {
-        struct env_set *es = session->opt->es;
-        struct buffer out = alloc_buf_gc(512*3, &gc);
-
         /* push version */
         buf_printf(&out, "IV_VER=%s\n", PACKAGE_VERSION);
 
@@ -2172,7 +2181,11 @@ push_peer_info(struct buffer *buf, struct tls_session *session)
 #elif defined(_WIN32)
         buf_printf(&out, "IV_PLAT=win\n");
 #endif
+    }
 
+    /* These are the IV variable that are sent to peers in p2p mode */
+    if (session->opt->push_peer_info_detail > 0)
+    {
         /* support for P_DATA_V2 */
         int iv_proto = IV_PROTO_DATA_V2;
 
@@ -2195,19 +2208,28 @@ push_peer_info(struct buffer *buf, struct tls_session *session)
 
                 buf_printf(&out, "IV_NCP=2\n");
             }
-            buf_printf(&out, "IV_CIPHERS=%s\n", session->opt->config_ncp_ciphers);
+        }
+        else
+        {
+            /* We are not using pull or p2mp server, instead do P2P NCP */
+            iv_proto |= IV_PROTO_NCP_P2P;
+        }
+
+        buf_printf(&out, "IV_CIPHERS=%s\n", session->opt->config_ncp_ciphers);
 

src/openvpn/ssl.c push_peer_info(struct buffer *buf, struct tls_session *session) · line 2226

Quoted 10 lines
src/openvpn/ssl.c +2 -3
 #ifdef HAVE_EXPORT_KEYING_MATERIAL
-            iv_proto |= IV_PROTO_TLS_KEY_EXPORT;
+        iv_proto |= IV_PROTO_TLS_KEY_EXPORT;
 #endif
-        }
 
         buf_printf(&out, "IV_PROTO=%d\n", iv_proto);
 
-        /* push compression status */
+        if (session->opt->push_peer_info_detail > 1)

isn't this check the same as the one below:

"if (session->opt->push_peer_info_detail >= 2)"

I don't think there is any integer number between 1 and 2.

Quoted 38 lines
src/openvpn/ssl.c +14 -12
+        {
+            /* push compression status */
 #ifdef USE_COMP
-        comp_generate_peer_info_string(&session->opt->comp_options, &out);
+            comp_generate_peer_info_string(&session->opt->comp_options, &out);
 #endif
+        }
 
         if (session->opt->push_peer_info_detail >= 2)
         {
@@ -2224,24 +2246,29 @@ push_peer_info(struct buffer *buf, struct tls_session *session)
 #endif
         }
 
-        /* push env vars that begin with UV_, IV_PLAT_VER and IV_GUI_VER */
-        for (struct env_item *e = es->list; e != NULL; e = e->next)
+        if (session->opt->push_peer_info_detail > 1)
         {
-            if (e->string)
+            struct env_set *es = session->opt->es;
+            /* push env vars that begin with UV_, IV_PLAT_VER and IV_GUI_VER */
+            for (struct env_item *e = es->list; e != NULL; e = e->next)
             {
-                if ((((strncmp(e->string, "UV_", 3)==0
-                       || strncmp(e->string, "IV_PLAT_VER=", sizeof("IV_PLAT_VER=")-1)==0)
-                      && session->opt->push_peer_info_detail >= 2)
-                     || (strncmp(e->string,"IV_GUI_VER=",sizeof("IV_GUI_VER=")-1)==0)
-                     || (strncmp(e->string,"IV_SSO=",sizeof("IV_SSO=")-1)==0)
-                     )
-                    && buf_safe(&out, strlen(e->string)+1))
+                if (e->string)
                 {
-                    buf_printf(&out, "%s\n", e->string);
+                    if ((((strncmp(e->string, "UV_", 3) == 0
+                        || strncmp(e->string, "IV_PLAT_VER=", sizeof("IV_PLAT_VER=") - 1) == 0)
+                        && session->opt->push_peer_info_detail >= 2)
+                        || (strncmp(e->string, "IV_GUI_VER=", sizeof("IV_GUI_VER=") - 1) == 0)
+                        || (strncmp(e->string, "IV_SSO=", sizeof("IV_SSO=") - 1) == 0)

src/openvpn/ssl.c push_peer_info(struct buffer *buf, struct tls_session *session) · line 2271

Quoted 10 lines
src/openvpn/ssl.c +6 -0
+                    )
+                        && buf_safe(&out, strlen(e->string) + 1))
+                    {
+                        buf_printf(&out, "%s\n", e->string);
+                    }
                 }
             }
         }
 
+

this empty line should go

Quoted 123 lines
src/openvpn/ssl.c +16 -1
         if (!write_string(buf, BSTR(&out), -1))
         {
             goto error;
@@ -2380,6 +2407,14 @@ key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls_sessi
         goto error;
     }
 
+    if (session->opt->server &&session->opt->mode != MODE_SERVER
+        && ks->key_id == 0)
+    {
+        /* tls-server option set and not P2MP server, so we
+         * are a P2P client running in tls-server mode */
+        p2p_mode_ncp(multi, session);
+    }
+
     return true;
 
 error:
@@ -2579,7 +2614,14 @@ key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_sessio
 
         setenv_del(session->opt->es, "exported_keying_material");
     }
-    
+
+    if (!session->opt->server && !session->opt->pull && ks->key_id == 0)
+    {
+        /* We are a p2p tls-client without pull, enable common
+         * protocol options */
+        p2p_mode_ncp(multi, session);
+    }
+
     gc_free(&gc);
     return true;
 
src/openvpn/ssl.h +5 -0
index baf3560d2..14fabcc26 100644
@@ -119,6 +119,11 @@
 /** Supports signaling keywords with AUTH_PENDING, e.g. timeout=xy */
 #define IV_PROTO_AUTH_PENDING_KW (1<<4)
 
+/** Support doing NCP in P2P mode. This mode works by both peers looking at
+ * each other's IV_ variables and deterministically deciding both on the same
+ * result. */
+#define IV_PROTO_NCP_P2P         (1<<5)
+
 /* Default field in X509 to be username */
 #define X509_USERNAME_FIELD_DEFAULT "CN"
 
src/openvpn/ssl_backend.h +1 -0
index c3d12e5be..d228c70d8 100644
@@ -390,6 +390,7 @@ void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
                                 const char *crl_file, bool crl_inline);
 
 #define EXPORT_KEY_DATA_LABEL       "EXPORTER-OpenVPN-datakeys"
+#define EXPORT_P2P_PEERID_LABEL     "EXPORTER-OpenVPN-p2p-peerid"
 /**
  * Keying Material Exporters [RFC 5705] allows additional keying material to be
  * derived from existing TLS channel. This exported keying material can then be
src/openvpn/ssl_common.h +10 -0
index 43af51ee9..bcb199176 100644
@@ -287,6 +287,16 @@ struct tls_options
     bool disable_occ;
     int mode;
     bool pull;
+    /**
+     * The detail of info we push in peer info
+     *
+     * 0 - nothing at all, P2MP server only
+     * 1 - only the most basic information to negotiate cipher and features
+     *     for P2P NCP
+     * 2 - normal setting for clients
+     * 3 - full information including "sensitive data" like IV_HWADDR
+     *     enabled by --push-peer-info
+     */
     int push_peer_info_detail;
     int transition_window;
     int handshake_window;
src/openvpn/ssl_ncp.c +32 -0
index 722256b42..8850ba237 100644
@@ -324,3 +324,148 @@ check_pull_client_ncp(struct context *c, const int found)
         return false;
     }
 }
+
+const char*
+get_p2p_ncp_cipher(struct tls_session *session, const char *peer_info,
+                   struct gc_arena *gc)
+{
+    /* we use a local gc arena to keep the temporary strings needed by strsep */
+    struct gc_arena gc_local = gc_new();
+    const char *peer_ciphers = extract_var_peer_info(peer_info, "IV_CIPHERS=", &gc_local);
+
+    if (!peer_ciphers)
+    {
+        gc_free(&gc_local);
+        return NULL;
+    }
+
+    const char* server_ciphers;
+    const char* client_ciphers;
+
+    if (session->opt->server)
+    {
+        server_ciphers = session->opt->config_ncp_ciphers;
+        client_ciphers = peer_ciphers;
+    }
+    else
+    {
+        client_ciphers = session->opt->config_ncp_ciphers;
+        server_ciphers = peer_ciphers;
+    }
+
+    /* Find the first common cipher from TLS server and TLS client. We
+     * use the preference of the server here to make it deterministic */
+    char *tmp_ciphers = string_alloc(server_ciphers, &gc_local);

src/openvpn/ssl_ncp.c check_pull_client_ncp(struct context *c, const int found) · line 368

Quoted 10 lines
src/openvpn/ssl_ncp.c +10 -0
+
+    const char *token;
+    while ((token = strsep(&tmp_ciphers, ":")))
+    {
+        if (tls_item_in_cipher_list(token, client_ciphers))
+        {
+            break;
+        }
+    }
+

From here

src/openvpn/ssl_ncp.c check_pull_client_ncp(struct context *c, const int found) · line 377

Quoted 9 lines
src/openvpn/ssl_ncp.c +9 -0
+    const char *ret = NULL;
+    if (token != NULL)
+    {
+        const char *chosen_cipher = string_alloc(token, gc);
+        ret = chosen_cipher;
+    }
+    gc_free(&gc_local);
+
+    return ret;

to here could just be simplified as:

   gc_free(&gc_local);
   return string_alloc(token, gc);

no need for 'ret' or any if-block (the same condition is already inside string_alloc()).

Quoted 5 lines
src/openvpn/ssl_ncp.c +5 -0
+}
+
+static void
+p2p_ncp_set_options(struct tls_multi *multi, struct tls_session *session)
+{

src/openvpn/ssl_ncp.c check_pull_client_ncp(struct context *c, const int found) · line 392

Quoted 10 lines
src/openvpn/ssl_ncp.c +10 -0
+    /* will return 0 if peer_info is null */
+    const unsigned int iv_proto_peer = extract_iv_proto(multi->peer_info);
+
+    /* The other peer does not support P2P NCP */
+    if (!(iv_proto_peer & IV_PROTO_NCP_P2P))
+    {
+        return;
+    }
+
+    if (iv_proto_peer & IV_PROTO_DATA_V2)

is it really possible to have NCP_P2P set and no DATA_V2?

I think NCP_P2P should automatically imply DATA_V2. Or maybe we just don't wanna make such assumption to avoid anything breaking in the future? (it'd make sense to me)

src/openvpn/ssl_ncp.c check_pull_client_ncp(struct context *c, const int found) · line 396

Quoted 4 lines
src/openvpn/ssl_ncp.c +4 -0
+    {
+        multi->use_peer_id = true;
+        multi->peer_id = 0x76706e; // 'v' 'p' 'n'
+

empty line should go

Quoted 7 lines
src/openvpn/ssl_ncp.c +7 -0
+    }
+
+#if defined(HAVE_EXPORT_KEYING_MATERIAL)
+    if (iv_proto_peer & IV_PROTO_TLS_KEY_EXPORT)
+    {
+        session->opt->crypto_flags |= CO_USE_TLS_KEY_MATERIAL_EXPORT;
+

src/openvpn/ssl_ncp.c check_pull_client_ncp(struct context *c, const int found) · line 413

Quoted 10 lines
src/openvpn/ssl_ncp.c +10 -0
+        if (multi->use_peer_id)
+        {
+            /* Using a non hardcoded peer-id makes a tiny bit harder to
+             * fingerprint packets and also gives each connection a unique
+             * peer-id that can be useful for NAT tracking etc. */
+
+            uint8_t peerid[3];
+            if (!key_state_export_keying_material(session, EXPORT_P2P_PEERID_LABEL,
+                                                  strlen(EXPORT_P2P_PEERID_LABEL),
+                                                  &peerid, 3))

nice idea! :)

Quoted 18 lines
src/openvpn/ssl_ncp.c +18 -0
+            {
+                /* Non DCO setup might still work but also this should never
+                 * happen or very likely the TLS encryption key exporter will
+                 * also fail */
+                msg(M_NONFATAL, "TLS key export for P2P peer id failed. "
+                                "Continuing anyway, expect problems");
+            }
+            else
+            {
+                multi->peer_id = (peerid[0] << 16) + (peerid[1] << 8) + peerid[2];
+            }
+
+        }
+    }
+#endif
+}
+
+void

src/openvpn/ssl_ncp.c check_pull_client_ncp(struct context *c, const int found) · line 441

Quoted 10 lines
src/openvpn/ssl_ncp.c +10 -0
+p2p_mode_ncp(struct tls_multi *multi, struct tls_session *session)
+{
+    /* Set the common options */
+    p2p_ncp_set_options(multi, session);
+
+    struct gc_arena gc = gc_new();
+
+    /* Query the common cipher here to log it as part of our message.
+     * We postpone switching the cipher to do_up */
+    const char* common_cipher = get_p2p_ncp_cipher(session, multi->peer_info, &gc);

why re-extracting the cipher again instead of reading it (somehow) from c->options.ciphername ?

Maybe reading it from that field is not correct, but isn't there a way to avoid doing the string parsing twice? (it was performed in do_deferred_p2p_ncp() already)

Quoted 85 lines
src/openvpn/ssl_ncp.c +30 -0
+
+    if (!common_cipher)
+    {
+        struct buffer out = alloc_buf_gc(128, &gc);
+        struct key_state *ks = get_key_scan(multi, KS_PRIMARY);
+
+        const cipher_ctx_t *ctx = ks->crypto_options.key_ctx_bi.encrypt.cipher;
+        const cipher_kt_t *cipher = cipher_ctx_get_cipher_kt(ctx);
+        const char *fallback_name = cipher_kt_name(cipher);
+
+        if (!cipher)
+        {
+            /* at this point we do not really know if our fallback is
+             * not enabled or if we use 'none' cipher as fallback, so
+             * keep this ambiguity here and print fallback-cipher: none
+             */
+            fallback_name = "none";
+        }
+
+        buf_printf(&out, "(not negotiated, fallback-cipher: %s)", fallback_name);
+        common_cipher = BSTR(&out);
+    }
+
+    msg(D_TLS_DEBUG_LOW, "P2P mode NCP negotiation result: "
+                         "TLS_export=%d, DATA_v2=%d, peer-id %d, cipher=%s",
+                         (bool)(session->opt->crypto_flags & CO_USE_TLS_KEY_MATERIAL_EXPORT),
+                         multi->use_peer_id, multi->peer_id, common_cipher);
+
+    gc_free(&gc);
+}
\ No newline at end of file
src/openvpn/ssl_ncp.h +25 -0
index 39158a568..c02be6939 100644
@@ -32,6 +32,7 @@
 
 #include "buffer.h"
 #include "options.h"
+#include "ssl_common.h"
 
 /**
  * Returns whether the client supports NCP either by
@@ -115,4 +116,28 @@ bool tls_item_in_cipher_list(const char *item, const char *list);
  */
 #define MAX_NCP_CIPHERS_LENGTH 127
 
+/**
+ * Determines if there is common cipher of both peer by looking at the
+ * IV_CIPHER peer info. In contrast of the server mode NCP that tries to
+ * accomandate all kind of corner cases in P2P mode NCP only takes IV_CIPHER
+ * into account and falls back to previous behaviour if this fails.
+ */
+void p2p_mode_ncp(struct tls_multi *multi, struct tls_session *session);
+
+/**
+ * Determines the best common cipher from both peers IV_CIPHER lists. The
+ * first cipher from the tls-server that is also in the tls-client IV_CIPHER
+ * list will be returned. If no common cipher can be found, both peer
+ * will continue to use whatever cipher is their default and NULL will be
+ * returned.
+ *
+ * @param session       tls_session
+ * @param peer_info     peer info of the peer
+ * @param gc            gc arena that will be used to allocate the returned cipher
+ * @return              common cipher if one exist.
+ */
+const char *
+get_p2p_ncp_cipher(struct tls_session *session, const char *peer_info,
+                   struct gc_arena *gc);
+
 #endif /* ifndef OPENVPN_SSL_NCP_H */
tests/unit_tests/openvpn/test_ncp.c +4 -0
index 4077be5e8..9dcd6f0a7 100644
@@ -44,6 +44,17 @@
 const char *bf_chacha = "BF-CBC:CHACHA20-POLY1305";
 const char *aes_ciphers = "AES-256-GCM:AES-128-GCM";
 
+
+/* Define this function here as dummy since including the ssl_*.c files
+ * leads to having to include even more unrelated code */
+bool

tests/unit_tests/openvpn/test_ncp.c line 60

Quoted 10 lines
tests/unit_tests/openvpn/test_ncp.c +7 -0
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 void *ekm, size_t ekm_size)
+{
+    ASSERT(0);
+}
+
 static void
 test_check_ncp_ciphers_list(void **state)
 {

I am so willing to restyle push_peer_info() now .... maybe in another patch :-)

Apart from the questions and comments above, the patch looks reasonable.

It tries to re-use as much logic as possible for any common part we have with the P2MP code path.

At the same time it adds code that is basically confined to P2P mode only and it is pretty simple.

Basic tests that passed:
* p2p-ncp vs p2p-ncp -> OK
* p2p-ncp vs p2p-ncp with different IV_CIPHERS advertised (still one cipher in common) -> OK
* p2p-ncp vs p2p (2.5) -> OK
* server vs client -> OK

My GitLab CI was also happy.

I also like the output as it clarifies the result of the "negotiation".

Cheers,

Signature · 1 line
Antonio Quartulli
#33 lore raw

[Openvpn-devel] [PATCH applied] Re: Cleanup handling of initial auth token

In reply to Arne Schwabe

I have stared a bit at the code, and the changes mostly look reasonable (though I got confused on the way, see below :-) ). Also, extra tests are certainly good :-)

I have also run this through the client- and server-side test parcours. The latter has auth-token instances, so also testing "renegotiate with auth-token" and "token expiry, fall back to AUTH_FAILED, client falling back to 'ok, here's password'". Together with deferred (25s) auth.

These all worked nicely.

I have changed whitespace (blank line and indent) as suggested, but not the "new define" part. This is code...

Some additional remarks that could go to a followup cleanup patch:

- the "We null terminate the old token..." comment in auth_token.c is in the wrong place - at that point, it's about the old_tstamp_initial

- since the "in renegotiation time?" check in verify_auth_token() is no longer checking for "&& !initialtoken", the code might become even more readable by getting rid of "in_renegotiation_time" and just doing the check directly in the if() clause.

- the wrapped "session id in token changed (Rejecting token." line is missing a closing bracket and looks ugly if wrapped for just a single word, especially if the memcmp_constant_time() expression above already has a longer line...

Your patch has been applied to the master branch.

commit d75e0736b4a0501a2c038ecb55730bf4f482b990

Author: Arne Schwabe
Date:   Mon Jul 19 15:31:32 2021 +0200
     Cleanup handling of initial auth token

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg22645.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#57 lore raw

Re: [Openvpn-devel] [PATCH v2 9/9] Support NCP in pure P2P VPN setups

In reply to Antonio Quartulli
Quoted 3 lines

nice idea! :)

Thanks!

Quoted 16 lines

src/openvpn/ssl_ncp.c check_pull_client_ncp(struct context *c, const int found) · line 441

Quoted 12 lines
src/openvpn/ssl_ncp.c +12 -0
+
+void
+p2p_mode_ncp(struct tls_multi *multi, struct tls_session *session)
+{
+    /* Set the common options */
+    p2p_ncp_set_options(multi, session);
+
+    struct gc_arena gc = gc_new();
+
+    /* Query the common cipher here to log it as part of our message.
+     * We postpone switching the cipher to do_up */
+    const char* common_cipher = get_p2p_ncp_cipher(session, multi->peer_info, &gc);

why re-extracting the cipher again instead of reading it (somehow) from c->options.ciphername ?

Quoted 3 lines

Maybe reading it from that field is not correct, but isn't there a way to avoid doing the string parsing twice? (it was performed in do_deferred_p2p_ncp() already)

It will be performed in do_deferred_p2p_ncp as part of do_up much later. The call here to get_p2p_ncp_cipher is basically "only" for creating the P2P mode NCP negotiation result message. The problem here is that setting cipher from the context that p2p_mode_NCP has (multi and session) not possible, so we would need to move options->cipher into multi or session struct and that would be quite disruptive. So I opted here to do get_p2p_ncp_cipher just to be able to print a nice message.

Arne

#58 lore raw

PATCH v2 1/1 Support NCP in pure P2P VPN setups

In reply to Arne Schwabe

Currently P2P mode of OpenVPN is on of the few places that cannot negotiate modern OpenVPN features. This becomes more and more problematic since P2P and P2MP code diverge more and more and also the lack of switching to more advanced features like Data v2 currently blocks P2P mode from working together with the upcoming ovpn-dco support.

This NCP support is a lot simpler and works in the following way:

- P2P peer announce an extremely limited IV_ variable set (IV_PROTO and IV_CIPHERS)
- Both peers check if the IV_PROTO_NCP_P2P bit is present in IV_PROTO
- if yes both sides deterministically determine according to IV_PROTO and IV_CIPHER what options can be used and start using these

There are no poor man's NCP or other compatibility workaround like in the normal NCP, making this NCP leaner and more deterministic.

Patch v2: remove empty lines, add doxygen comment to push_peer_info, fix
push_peer_info >= 2 that should be > 2

---
 src/openvpn/init.c                  |  99 +++++++++++++++----
 src/openvpn/options.c               |   8 +-
 src/openvpn/ssl.c                   | 133 ++++++++++++++++++--------
 src/openvpn/ssl.h                   |   5 +
 src/openvpn/ssl_backend.h           |   1 +
 src/openvpn/ssl_common.h            |  10 ++
 src/openvpn/ssl_ncp.c               | 143 ++++++++++++++++++++++++++++
 src/openvpn/ssl_ncp.h               |  25 +++++
 tests/unit_tests/openvpn/test_ncp.c |  11 +++
 9 files changed, 376 insertions(+), 59 deletions(-)
src/openvpn/init.c +83 -16
index 60471833e..386aee230 100644
@@ -68,6 +68,7 @@ static const char *saved_pid_file_name; /* GLOBAL */
 #define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
 
 static void do_init_first_time(struct context *c);
+static bool do_deferred_p2p_ncp(struct context *c);
 
 void
 context_clear(struct context *c)
@@ -2151,6 +2152,14 @@ do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
                 return false;
             }
         }
+        else if (c->mode == MODE_POINT_TO_POINT)
+        {
+            if (!do_deferred_p2p_ncp(c))
+            {
+                msg(D_TLS_ERRORS, "ERROR: Failed to apply P2P negotiated protocol options");
+                return false;
+            }
+        }
 
         /* if --up-delay specified, open tun, do ifconfig, and run up script now */
         if (c->options.up_delay || PULL_DEFINED(&c->options))
@@ -2241,6 +2250,71 @@ pull_permission_mask(const struct context *c)
     return flags;
 }
 
+static
+void adjust_mtu_peerid(struct context *c)
+{
+    frame_add_to_extra_frame(&c->c2.frame, 3);     /* peer-id overhead */
+    if (!c->options.ce.link_mtu_defined)
+    {
+        frame_add_to_link_mtu(&c->c2.frame, 3);
+        msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
+            EXPANDED_SIZE(&c->c2.frame));
+    }
+    else
+    {
+        msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
+                    " fixed by config - reducing tun-mtu to %d, expect"
+                    " MTU problems", TUN_MTU_SIZE(&c->c2.frame));
+    }
+}
+
+static bool
+do_deferred_p2p_ncp(struct context *c)
+{
+    if (!c->c2.tls_multi)
+    {
+        return true;
+    }
+
+    if (c->c2.tls_multi->use_peer_id)
+    {
+        adjust_mtu_peerid(c);
+    }
+
+    struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
+
+    const char *ncp_cipher = get_p2p_ncp_cipher(session, c->c2.tls_multi->peer_info,
+                                                &c->options.gc);
+
+    if (ncp_cipher)
+    {
+        c->options.ciphername = ncp_cipher;
+    }
+    else if (!c->options.enable_ncp_fallback)
+    {
+        msg(D_TLS_ERRORS, "ERROR: failed to negotiate cipher with peer and "
+                          "--data-ciphers-fallback not enabled. No usable "
+                          "data channel cipher");
+        return false;
+    }
+
+    struct frame *frame_fragment = NULL;
+#ifdef ENABLE_FRAGMENT
+    if (c->options.ce.fragment)
+    {
+        frame_fragment = &c->c2.frame_fragment;
+    }
+#endif
+
+    if (!tls_session_update_crypto_params(session, &c->options, &c->c2.frame,
+                                         frame_fragment))
+    {
+        msg(D_TLS_ERRORS, "ERROR: failed to set crypto cipher");
+        return false;
+    }
+    return true;
+}
+
 /*
  * Handle non-tun-related pulled options.
  */
@@ -2328,19 +2402,7 @@ do_deferred_options(struct context *c, const unsigned int found)
         msg(D_PUSH, "OPTIONS IMPORT: peer-id set");
         c->c2.tls_multi->use_peer_id = true;
         c->c2.tls_multi->peer_id = c->options.peer_id;
-        frame_add_to_extra_frame(&c->c2.frame, +3);     /* peer-id overhead */
-        if (!c->options.ce.link_mtu_defined)
-        {
-            frame_add_to_link_mtu(&c->c2.frame, +3);
-            msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
-                EXPANDED_SIZE(&c->c2.frame));
-        }
-        else
-        {
-            msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
-                " fixed by config - reducing tun-mtu to %d, expect"
-                " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );
-        }
+        adjust_mtu_peerid(c);
     }
 
     /* process (potentially pushed) crypto options */
@@ -2860,16 +2922,21 @@ do_init_crypto_tls(struct context *c, const unsigned int flags)
     to.pull = options->pull;
     if (options->push_peer_info)        /* all there is */
     {
-        to.push_peer_info_detail = 2;
+        to.push_peer_info_detail = 3;
     }
     else if (options->pull)             /* pull clients send some details */
     {
-        to.push_peer_info_detail = 1;
+        to.push_peer_info_detail = 2;
     }
-    else                                /* default: no peer-info at all */
+    else if (options->mode == MODE_SERVER) /* server: no peer info at all */
     {
         to.push_peer_info_detail = 0;
     }
+    else                  /* default: minimal info to allow NCP in P2P mode */
+    {
+        to.push_peer_info_detail = 1;
+    }
+
 
     /* should we not xmit any packets until we get an initial
      * response from client? */
src/openvpn/options.c +4 -4
index b57e8ecc6..63cda1e86 100644
@@ -3081,10 +3081,6 @@ options_postprocess_cipher(struct options *o)
 {
     if (!o->pull && !(o->mode == MODE_SERVER))
     {
-        /* we are in the classic P2P mode */
-        msg( M_WARN, "Cipher negotiation is disabled since neither "
-             "P2MP client nor server mode is enabled");
-
         /* If the cipher is not set, use the old default of BF-CBC. We will
          * warn that this is deprecated on cipher initialisation, no need
          * to warn here as well */
@@ -3092,6 +3088,10 @@ options_postprocess_cipher(struct options *o)
         {
             o->ciphername = "BF-CBC";
         }
+        else
+        {
+            o->enable_ncp_fallback = true;
+        }
         return;
     }
 
src/openvpn/ssl.c +94 -39

209 lines not on this page · raw message

src/openvpn/ssl.h +5 -0
index 58b39466b..b14453fe2 100644
@@ -119,6 +119,11 @@
 /** Supports signaling keywords with AUTH_PENDING, e.g. timeout=xy */
 #define IV_PROTO_AUTH_PENDING_KW (1<<4)
 
+/** Support doing NCP in P2P mode. This mode works by both peers looking at
+ * each other's IV_ variables and deterministically deciding both on the same
+ * result. */
+#define IV_PROTO_NCP_P2P         (1<<5)
+
 /* Default field in X509 to be username */
 #define X509_USERNAME_FIELD_DEFAULT "CN"
 
src/openvpn/ssl_backend.h +1 -0
index fe93263ca..c877e1947 100644
@@ -390,6 +390,7 @@ void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
                                 const char *crl_file, bool crl_inline);
 
 #define EXPORT_KEY_DATA_LABEL       "EXPORTER-OpenVPN-datakeys"
+#define EXPORT_P2P_PEERID_LABEL     "EXPORTER-OpenVPN-p2p-peerid"
 /**
  * Keying Material Exporters [RFC 5705] allows additional keying material to be
  * derived from existing TLS channel. This exported keying material can then be
src/openvpn/ssl_common.h +10 -0
index d7c89575a..3ab24b851 100644
@@ -289,6 +289,16 @@ struct tls_options
     bool disable_occ;
     int mode;
     bool pull;
+    /**
+     * The detail of info we push in peer info
+     *
+     * 0 - nothing at all, P2MP server only
+     * 1 - only the most basic information to negotiate cipher and features
+     *     for P2P NCP
+     * 2 - normal setting for clients
+     * 3 - full information including "sensitive data" like IV_HWADDR
+     *     enabled by --push-peer-info
+     */
     int push_peer_info_detail;
     int transition_window;
     int handshake_window;
src/openvpn/ssl_ncp.c +143 -0

147 lines not on this page · raw message

src/openvpn/ssl_ncp.h +25 -0
index 3fa68e262..4a2601a2e 100644
@@ -32,6 +32,7 @@
 
 #include "buffer.h"
 #include "options.h"
+#include "ssl_common.h"
 
 /**
  * Returns whether the client supports NCP either by
@@ -115,4 +116,28 @@ bool tls_item_in_cipher_list(const char *item, const char *list);
  */
 #define MAX_NCP_CIPHERS_LENGTH 127
 
+/**
+ * Determines if there is common cipher of both peer by looking at the
+ * IV_CIPHER peer info. In contrast of the server mode NCP that tries to
+ * accomandate all kind of corner cases in P2P mode NCP only takes IV_CIPHER
+ * into account and falls back to previous behaviour if this fails.
+ */
+void p2p_mode_ncp(struct tls_multi *multi, struct tls_session *session);
+
+/**
+ * Determines the best common cipher from both peers IV_CIPHER lists. The
+ * first cipher from the tls-server that is also in the tls-client IV_CIPHER
+ * list will be returned. If no common cipher can be found, both peer
+ * will continue to use whatever cipher is their default and NULL will be
+ * returned.
+ *
+ * @param session       tls_session
+ * @param peer_info     peer info of the peer
+ * @param gc            gc arena that will be used to allocate the returned cipher
+ * @return              common cipher if one exist.
+ */
+const char *
+get_p2p_ncp_cipher(struct tls_session *session, const char *peer_info,
+                   struct gc_arena *gc);
+
 #endif /* ifndef OPENVPN_SSL_NCP_H */
tests/unit_tests/openvpn/test_ncp.c +11 -0
index 494a02846..293093f1a 100644
@@ -44,6 +44,17 @@
 const char *bf_chacha = "BF-CBC:CHACHA20-POLY1305";
 const char *aes_ciphers = "AES-256-GCM:AES-128-GCM";
 
+
+/* Define this function here as dummy since including the ssl_*.c files
+ * leads to having to include even more unrelated code */
+bool
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 void *ekm, size_t ekm_size)
+{
+    ASSERT(0);
+}
+
 static void
 test_check_ncp_ciphers_list(void **state)
 {
Signature · 1 line
2.32.0
Acked-by on v2 1/1
#59 lore raw

Re: [Openvpn-devel] [PATCH v2] Support NCP in pure P2P VPN setups

Hi,

I saw a few small things that can be fixed on the fly:

Quoted 516 lines · Arne Schwabe

Currently P2P mode of OpenVPN is on of the few places that cannot negotiate modern OpenVPN features. This becomes more and more problematic since P2P and P2MP code diverge more and more and also the lack of switching to more advanced features like Data v2 currently blocks P2P mode from working together with the upcoming ovpn-dco support.

This NCP support is a lot simpler and works in the following way:

- P2P peer announce an extremely limited IV_ variable set (IV_PROTO and IV_CIPHERS)
- Both peers check if the IV_PROTO_NCP_P2P bit is present in IV_PROTO
- if yes both sides deterministically determine according to IV_PROTO and IV_CIPHER what options can be used and start using these

There are no poor man's NCP or other compatibility workaround like in the normal NCP, making this NCP leaner and more deterministic.

Patch v2: remove empty lines, add doxygen comment to push_peer_info, fix
push_peer_info >= 2 that should be > 2

---
 src/openvpn/init.c                  |  99 +++++++++++++++----
 src/openvpn/options.c               |   8 +-
 src/openvpn/ssl.c                   | 133 ++++++++++++++++++--------
 src/openvpn/ssl.h                   |   5 +
 src/openvpn/ssl_backend.h           |   1 +
 src/openvpn/ssl_common.h            |  10 ++
 src/openvpn/ssl_ncp.c               | 143 ++++++++++++++++++++++++++++
 src/openvpn/ssl_ncp.h               |  25 +++++
 tests/unit_tests/openvpn/test_ncp.c |  11 +++
 9 files changed, 376 insertions(+), 59 deletions(-)
src/openvpn/init.c +83 -16
index 60471833e..386aee230 100644
@@ -68,6 +68,7 @@ static const char *saved_pid_file_name; /* GLOBAL */
 #define CF_INIT_TLS_AUTH_STANDALONE (1<<2)
 
 static void do_init_first_time(struct context *c);
+static bool do_deferred_p2p_ncp(struct context *c);
 
 void
 context_clear(struct context *c)
@@ -2151,6 +2152,14 @@ do_up(struct context *c, bool pulled_options, unsigned int option_types_found)
                 return false;
             }
         }
+        else if (c->mode == MODE_POINT_TO_POINT)
+        {
+            if (!do_deferred_p2p_ncp(c))
+            {
+                msg(D_TLS_ERRORS, "ERROR: Failed to apply P2P negotiated protocol options");
+                return false;
+            }
+        }
 
         /* if --up-delay specified, open tun, do ifconfig, and run up script now */
         if (c->options.up_delay || PULL_DEFINED(&c->options))
@@ -2241,6 +2250,71 @@ pull_permission_mask(const struct context *c)
     return flags;
 }
 
+static
+void adjust_mtu_peerid(struct context *c)
+{
+    frame_add_to_extra_frame(&c->c2.frame, 3);     /* peer-id overhead */
+    if (!c->options.ce.link_mtu_defined)
+    {
+        frame_add_to_link_mtu(&c->c2.frame, 3);
+        msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
+            EXPANDED_SIZE(&c->c2.frame));
+    }
+    else
+    {
+        msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
+                    " fixed by config - reducing tun-mtu to %d, expect"
+                    " MTU problems", TUN_MTU_SIZE(&c->c2.frame));
+    }
+}
+
+static bool
+do_deferred_p2p_ncp(struct context *c)
+{
+    if (!c->c2.tls_multi)
+    {
+        return true;
+    }
+
+    if (c->c2.tls_multi->use_peer_id)
+    {
+        adjust_mtu_peerid(c);
+    }
+
+    struct tls_session *session = &c->c2.tls_multi->session[TM_ACTIVE];
+
+    const char *ncp_cipher = get_p2p_ncp_cipher(session, c->c2.tls_multi->peer_info,
+                                                &c->options.gc);
+
+    if (ncp_cipher)
+    {
+        c->options.ciphername = ncp_cipher;
+    }
+    else if (!c->options.enable_ncp_fallback)
+    {
+        msg(D_TLS_ERRORS, "ERROR: failed to negotiate cipher with peer and "
+                          "--data-ciphers-fallback not enabled. No usable "
+                          "data channel cipher");
+        return false;
+    }
+
+    struct frame *frame_fragment = NULL;
+#ifdef ENABLE_FRAGMENT
+    if (c->options.ce.fragment)
+    {
+        frame_fragment = &c->c2.frame_fragment;
+    }
+#endif
+
+    if (!tls_session_update_crypto_params(session, &c->options, &c->c2.frame,
+                                         frame_fragment))
+    {
+        msg(D_TLS_ERRORS, "ERROR: failed to set crypto cipher");
+        return false;
+    }
+    return true;
+}
+
 /*
  * Handle non-tun-related pulled options.
  */
@@ -2328,19 +2402,7 @@ do_deferred_options(struct context *c, const unsigned int found)
         msg(D_PUSH, "OPTIONS IMPORT: peer-id set");
         c->c2.tls_multi->use_peer_id = true;
         c->c2.tls_multi->peer_id = c->options.peer_id;
-        frame_add_to_extra_frame(&c->c2.frame, +3);     /* peer-id overhead */
-        if (!c->options.ce.link_mtu_defined)
-        {
-            frame_add_to_link_mtu(&c->c2.frame, +3);
-            msg(D_PUSH, "OPTIONS IMPORT: adjusting link_mtu to %d",
-                EXPANDED_SIZE(&c->c2.frame));
-        }
-        else
-        {
-            msg(M_WARN, "OPTIONS IMPORT: WARNING: peer-id set, but link-mtu"
-                " fixed by config - reducing tun-mtu to %d, expect"
-                " MTU problems", TUN_MTU_SIZE(&c->c2.frame) );
-        }
+        adjust_mtu_peerid(c);
     }
 
     /* process (potentially pushed) crypto options */
@@ -2860,16 +2922,21 @@ do_init_crypto_tls(struct context *c, const unsigned int flags)
     to.pull = options->pull;
     if (options->push_peer_info)        /* all there is */
     {
-        to.push_peer_info_detail = 2;
+        to.push_peer_info_detail = 3;
     }
     else if (options->pull)             /* pull clients send some details */
     {
-        to.push_peer_info_detail = 1;
+        to.push_peer_info_detail = 2;
     }
-    else                                /* default: no peer-info at all */
+    else if (options->mode == MODE_SERVER) /* server: no peer info at all */
     {
         to.push_peer_info_detail = 0;
     }
+    else                  /* default: minimal info to allow NCP in P2P mode */
+    {
+        to.push_peer_info_detail = 1;
+    }
+
 
     /* should we not xmit any packets until we get an initial
      * response from client? */
src/openvpn/options.c +4 -4
index b57e8ecc6..63cda1e86 100644
@@ -3081,10 +3081,6 @@ options_postprocess_cipher(struct options *o)
 {
     if (!o->pull && !(o->mode == MODE_SERVER))
     {
-        /* we are in the classic P2P mode */
-        msg( M_WARN, "Cipher negotiation is disabled since neither "
-             "P2MP client nor server mode is enabled");
-
         /* If the cipher is not set, use the old default of BF-CBC. We will
          * warn that this is deprecated on cipher initialisation, no need
          * to warn here as well */
@@ -3092,6 +3088,10 @@ options_postprocess_cipher(struct options *o)
         {
             o->ciphername = "BF-CBC";
         }
+        else
+        {
+            o->enable_ncp_fallback = true;
+        }
         return;
     }
 
src/openvpn/ssl.c +94 -39
index 96e04ac11..2b2d8b841 100644
@@ -1875,32 +1875,16 @@ cleanup:
 }
 
 bool
-tls_session_update_crypto_params(struct tls_session *session,
-                                 struct options *options, struct frame *frame,
+tls_session_update_crypto_params_do_work(struct tls_session *session,
+                                 struct options* options, struct frame *frame,
                                  struct frame *frame_fragment)
 {
     if (session->key[KS_PRIMARY].crypto_options.key_ctx_bi.initialized)
     {
         /* keys already generated, nothing to do */
         return true;
-    }
-
-    bool cipher_allowed_as_fallback = options->enable_ncp_fallback
-                                      && streq(options->ciphername, session->opt->config_ciphername);
 
-    if (!session->opt->server && !cipher_allowed_as_fallback
-        && !tls_item_in_cipher_list(options->ciphername, options->ncp_ciphers))
-    {
-        msg(D_TLS_ERRORS, "Error: pushed cipher not allowed - %s not in %s",
-            options->ciphername, options->ncp_ciphers);
-        /* undo cipher push, abort connection setup */
-        options->ciphername = session->opt->config_ciphername;
-        return false;
     }
-
-    /* Import crypto settings that might be set by pull/push */
-    session->opt->crypto_flags |= options->data_channel_crypto_flags;
-
     if (strcmp(options->ciphername, session->opt->config_ciphername))
     {
         msg(D_HANDSHAKE, "Data Channel: using negotiated cipher '%s'",
@@ -1952,6 +1936,32 @@ tls_session_update_crypto_params(struct tls_session *session,
     return tls_session_generate_data_channel_keys(session);
 }
 
+bool
+tls_session_update_crypto_params(struct tls_session *session,
+                                 struct options *options, struct frame *frame,
+                                 struct frame *frame_fragment)
+{
+
+    bool cipher_allowed_as_fallback = options->enable_ncp_fallback
+        && streq(options->ciphername, session->opt->config_ciphername);
+
+    if (!session->opt->server && !cipher_allowed_as_fallback
+        && !tls_item_in_cipher_list(options->ciphername, options->ncp_ciphers))
+    {
+        msg(D_TLS_ERRORS, "Error: negotiated cipher not allowed - %s not in %s",
+            options->ciphername, options->ncp_ciphers);
+        /* undo cipher push, abort connection setup */
+        options->ciphername = session->opt->config_ciphername;
+        return false;
+    }
+
+    /* Import crypto settings that might be set by pull/push */
+    session->opt->crypto_flags |= options->data_channel_crypto_flags;
+
+    return tls_session_update_crypto_params_do_work(session, options, frame, frame_fragment);
+}
+
+
 static bool
 random_bytes_to_buf(struct buffer *buf,
                     uint8_t *out,
@@ -2140,17 +2150,30 @@ read_string_alloc(struct buffer *buf)
     return str;
 }
 
+/**
+ * Prepares the IV_ and UV_ variables that are part of the
+ * exchange to signal the peer's capabilities. The amount
+ * of variables is determined by session->opt->push_peer_info_detail
+ *
+ *     0     nothing. Used on a TLS P2MP server side to send no information
+ *           to the client
+ *     1     minimal info needed for NCP in P2P mode
+ *     2     when --pull is enabled, the "default" set of variables
+ *     3     all information including MAC address and library versions
+ *
+ * @param buf       the buffer to write these variables to
+ * @param session   the TLS session object
+ * @return          true if no error was encountered
+ */
 static bool
 push_peer_info(struct buffer *buf, struct tls_session *session)
 {
     struct gc_arena gc = gc_new();
     bool ret = false;
+    struct buffer out = alloc_buf_gc(512 * 3, &gc);
 
-    if (session->opt->push_peer_info_detail > 0)
+    if (session->opt->push_peer_info_detail > 1)
     {
-        struct env_set *es = session->opt->es;
-        struct buffer out = alloc_buf_gc(512*3, &gc);
-
         /* push version */
         buf_printf(&out, "IV_VER=%s\n", PACKAGE_VERSION);
 
@@ -2172,7 +2195,11 @@ push_peer_info(struct buffer *buf, struct tls_session *session)
 #elif defined(_WIN32)
         buf_printf(&out, "IV_PLAT=win\n");
 #endif
+    }
 
+    /* These are the IV variable that are sent to peers in p2p mode */
+    if (session->opt->push_peer_info_detail > 0)
+    {
         /* support for P_DATA_V2 */
         int iv_proto = IV_PROTO_DATA_V2;
 
@@ -2195,21 +2222,30 @@ push_peer_info(struct buffer *buf, struct tls_session *session)
 
                 buf_printf(&out, "IV_NCP=2\n");
             }
-            buf_printf(&out, "IV_CIPHERS=%s\n", session->opt->config_ncp_ciphers);
+        }
+        else
+        {
+            /* We are not using pull or p2mp server, instead do P2P NCP */
+            iv_proto |= IV_PROTO_NCP_P2P;
+        }
+
+        buf_printf(&out, "IV_CIPHERS=%s\n", session->opt->config_ncp_ciphers);
 
 #ifdef HAVE_EXPORT_KEYING_MATERIAL
-            iv_proto |= IV_PROTO_TLS_KEY_EXPORT;
+        iv_proto |= IV_PROTO_TLS_KEY_EXPORT;
 #endif
-        }
 
         buf_printf(&out, "IV_PROTO=%d\n", iv_proto);
 
-        /* push compression status */
+        if (session->opt->push_peer_info_detail > 1)
+        {
+            /* push compression status */
 #ifdef USE_COMP
-        comp_generate_peer_info_string(&session->opt->comp_options, &out);
+            comp_generate_peer_info_string(&session->opt->comp_options, &out);
 #endif
+        }
 
-        if (session->opt->push_peer_info_detail >= 2)
+        if (session->opt->push_peer_info_detail > 2)
         {
             /* push mac addr */
             struct route_gateway_info rgi;
@@ -2224,20 +2260,24 @@ push_peer_info(struct buffer *buf, struct tls_session *session)
 #endif
         }
 
-        /* push env vars that begin with UV_, IV_PLAT_VER and IV_GUI_VER */
-        for (struct env_item *e = es->list; e != NULL; e = e->next)
+        if (session->opt->push_peer_info_detail > 1)
         {
-            if (e->string)
+            struct env_set *es = session->opt->es;
+            /* push env vars that begin with UV_, IV_PLAT_VER and IV_GUI_VER */
+            for (struct env_item *e = es->list; e != NULL; e = e->next)
             {
-                if ((((strncmp(e->string, "UV_", 3)==0
-                       || strncmp(e->string, "IV_PLAT_VER=", sizeof("IV_PLAT_VER=")-1)==0)
-                      && session->opt->push_peer_info_detail >= 2)
-                     || (strncmp(e->string,"IV_GUI_VER=",sizeof("IV_GUI_VER=")-1)==0)
-                     || (strncmp(e->string,"IV_SSO=",sizeof("IV_SSO=")-1)==0)
-                     )
-                    && buf_safe(&out, strlen(e->string)+1))
+                if (e->string)
                 {
-                    buf_printf(&out, "%s\n", e->string);
+                    if ((((strncmp(e->string, "UV_", 3) == 0
+                        || strncmp(e->string, "IV_PLAT_VER=", sizeof("IV_PLAT_VER=") - 1) == 0)
+                        && session->opt->push_peer_info_detail >= 2)
+                        || (strncmp(e->string, "IV_GUI_VER=", sizeof("IV_GUI_VER=") - 1) == 0)
+                        || (strncmp(e->string, "IV_SSO=", sizeof("IV_SSO=") - 1) == 0)
+                    )
+                        && buf_safe(&out, strlen(e->string) + 1))
+                    {
+                        buf_printf(&out, "%s\n", e->string);
+                    }
                 }
             }
         }
@@ -2380,6 +2420,14 @@ key_method_2_write(struct buffer *buf, struct tls_multi *multi, struct tls_sessi
         goto error;
     }
 
+    if (session->opt->server &&session->opt->mode != MODE_SERVER
+        && ks->key_id == 0)
+    {
+        /* tls-server option set and not P2MP server, so we
+         * are a P2P client running in tls-server mode */
+        p2p_mode_ncp(multi, session);
+    }
+
     return true;
 
 error:
@@ -2580,6 +2628,13 @@ key_method_2_read(struct buffer *buf, struct tls_multi *multi, struct tls_sessio
         setenv_del(session->opt->es, "exported_keying_material");
     }
 
+    if (!session->opt->server && !session->opt->pull && ks->key_id == 0)
+    {
+        /* We are a p2p tls-client without pull, enable common
+         * protocol options */
+        p2p_mode_ncp(multi, session);
+    }
+
     gc_free(&gc);
     return true;
 
src/openvpn/ssl.h +5 -0
index 58b39466b..b14453fe2 100644
@@ -119,6 +119,11 @@
 /** Supports signaling keywords with AUTH_PENDING, e.g. timeout=xy */
 #define IV_PROTO_AUTH_PENDING_KW (1<<4)
 
+/** Support doing NCP in P2P mode. This mode works by both peers looking at
+ * each other's IV_ variables and deterministically deciding both on the same
+ * result. */
+#define IV_PROTO_NCP_P2P         (1<<5)
+
 /* Default field in X509 to be username */
 #define X509_USERNAME_FIELD_DEFAULT "CN"
 
src/openvpn/ssl_backend.h +1 -0
index fe93263ca..c877e1947 100644
@@ -390,6 +390,7 @@ void backend_tls_ctx_reload_crl(struct tls_root_ctx *ssl_ctx,
                                 const char *crl_file, bool crl_inline);
 
 #define EXPORT_KEY_DATA_LABEL       "EXPORTER-OpenVPN-datakeys"
+#define EXPORT_P2P_PEERID_LABEL     "EXPORTER-OpenVPN-p2p-peerid"
 /**
  * Keying Material Exporters [RFC 5705] allows additional keying material to be
  * derived from existing TLS channel. This exported keying material can then be
src/openvpn/ssl_common.h +10 -0
index d7c89575a..3ab24b851 100644
@@ -289,6 +289,16 @@ struct tls_options
     bool disable_occ;
     int mode;
     bool pull;
+    /**
+     * The detail of info we push in peer info
+     *
+     * 0 - nothing at all, P2MP server only
+     * 1 - only the most basic information to negotiate cipher and features
+     *     for P2P NCP
+     * 2 - normal setting for clients
+     * 3 - full information including "sensitive data" like IV_HWADDR
+     *     enabled by --push-peer-info
+     */
     int push_peer_info_detail;
     int transition_window;
     int handshake_window;
src/openvpn/ssl_ncp.c +34 -0
index 0258e6a72..b44186514 100644
@@ -324,3 +324,146 @@ check_pull_client_ncp(struct context *c, const int found)
         return false;
     }
 }
+
+const char*
+get_p2p_ncp_cipher(struct tls_session *session, const char *peer_info,
+                   struct gc_arena *gc)
+{
+    /* we use a local gc arena to keep the temporary strings needed by strsep */
+    struct gc_arena gc_local = gc_new();
+    const char *peer_ciphers = extract_var_peer_info(peer_info, "IV_CIPHERS=", &gc_local);
+
+    if (!peer_ciphers)
+    {
+        gc_free(&gc_local);
+        return NULL;
+    }
+
+    const char* server_ciphers;
+    const char* client_ciphers;
+
+    if (session->opt->server)
+    {
+        server_ciphers = session->opt->config_ncp_ciphers;
+        client_ciphers = peer_ciphers;
+    }
+    else
+    {
+        client_ciphers = session->opt->config_ncp_ciphers;
+        server_ciphers = peer_ciphers;
+    }
+
+    /* Find the first common cipher from TLS server and TLS client. We
+     * use the preference of the server here to make it deterministic */
+    char *tmp_ciphers = string_alloc(server_ciphers, &gc_local);
+
+    const char *token;

src/openvpn/ssl_ncp.c check_pull_client_ncp(struct context *c, const int found) · line 370

Quoted 10 lines
src/openvpn/ssl_ncp.c +10 -0
+    while ((token = strsep(&tmp_ciphers, ":")))
+    {
+        if (tls_item_in_cipher_list(token, client_ciphers))
+        {
+            break;
+        }
+    }
+
+    const char *ret = NULL;
+    if (token != NULL)

this can just be "if (token)" like you have done for all other conditions you introduced :)

Quoted 84 lines
src/openvpn/ssl_ncp.c +84 -0
+    {
+        ret = string_alloc(token, gc);
+    }
+    gc_free(&gc_local);
+
+    return ret;
+}
+
+static void
+p2p_ncp_set_options(struct tls_multi *multi, struct tls_session *session)
+{
+    /* will return 0 if peer_info is null */
+    const unsigned int iv_proto_peer = extract_iv_proto(multi->peer_info);
+
+    /* The other peer does not support P2P NCP */
+    if (!(iv_proto_peer & IV_PROTO_NCP_P2P))
+    {
+        return;
+    }
+
+    if (iv_proto_peer & IV_PROTO_DATA_V2)
+    {
+        multi->use_peer_id = true;
+        multi->peer_id = 0x76706e; // 'v' 'p' 'n'
+    }
+
+#if defined(HAVE_EXPORT_KEYING_MATERIAL)
+    if (iv_proto_peer & IV_PROTO_TLS_KEY_EXPORT)
+    {
+        session->opt->crypto_flags |= CO_USE_TLS_KEY_MATERIAL_EXPORT;
+
+        if (multi->use_peer_id)
+        {
+            /* Using a non hardcoded peer-id makes a tiny bit harder to
+             * fingerprint packets and also gives each connection a unique
+             * peer-id that can be useful for NAT tracking etc. */
+
+            uint8_t peerid[3];
+            if (!key_state_export_keying_material(session, EXPORT_P2P_PEERID_LABEL,
+                                                  strlen(EXPORT_P2P_PEERID_LABEL),
+                                                  &peerid, 3))
+            {
+                /* Non DCO setup might still work but also this should never
+                 * happen or very likely the TLS encryption key exporter will
+                 * also fail */
+                msg(M_NONFATAL, "TLS key export for P2P peer id failed. "
+                                "Continuing anyway, expect problems");
+            }
+            else
+            {
+                multi->peer_id = (peerid[0] << 16) + (peerid[1] << 8) + peerid[2];
+            }
+
+        }
+    }
+#endif
+}
+
+void
+p2p_mode_ncp(struct tls_multi *multi, struct tls_session *session)
+{
+    /* Set the common options */
+    p2p_ncp_set_options(multi, session);
+
+    struct gc_arena gc = gc_new();
+
+    /* Query the common cipher here to log it as part of our message.
+     * We postpone switching the cipher to do_up */
+    const char* common_cipher = get_p2p_ncp_cipher(session, multi->peer_info, &gc);
+
+    if (!common_cipher)
+    {
+        struct buffer out = alloc_buf_gc(128, &gc);
+        struct key_state *ks = get_key_scan(multi, KS_PRIMARY);
+
+        const cipher_ctx_t *ctx = ks->crypto_options.key_ctx_bi.encrypt.cipher;
+        const cipher_kt_t *cipher = cipher_ctx_get_cipher_kt(ctx);
+        const char *fallback_name = cipher_kt_name(cipher);
+
+        if (!cipher)
+        {
+            /* at this point we do not really know if our fallback is
+             * not enabled or if we use 'none' cipher as fallback, so
+             * keep this ambiguity here and print fallback-cipher: none

src/openvpn/ssl_ncp.c check_pull_client_ncp(struct context *c, const int found) · line 464

Quoted 10 lines
src/openvpn/ssl_ncp.c +10 -0
+             */
+            fallback_name = "none";
+        }
+
+        buf_printf(&out, "(not negotiated, fallback-cipher: %s)", fallback_name);
+        common_cipher = BSTR(&out);
+    }
+
+    msg(D_TLS_DEBUG_LOW, "P2P mode NCP negotiation result: "
+                         "TLS_export=%d, DATA_v2=%d, peer-id %d, cipher=%s",

the following two lines should be indented after the opening '(' because they are not part of the message string.

Quoted 60 lines
src/openvpn/ssl_ncp.c +5 -0
+                         (bool)(session->opt->crypto_flags & CO_USE_TLS_KEY_MATERIAL_EXPORT),
+                         multi->use_peer_id, multi->peer_id, common_cipher);
+
+    gc_free(&gc);
+}
\ No newline at end of file
src/openvpn/ssl_ncp.h +25 -0
index 3fa68e262..4a2601a2e 100644
@@ -32,6 +32,7 @@
 
 #include "buffer.h"
 #include "options.h"
+#include "ssl_common.h"
 
 /**
  * Returns whether the client supports NCP either by
@@ -115,4 +116,28 @@ bool tls_item_in_cipher_list(const char *item, const char *list);
  */
 #define MAX_NCP_CIPHERS_LENGTH 127
 
+/**
+ * Determines if there is common cipher of both peer by looking at the
+ * IV_CIPHER peer info. In contrast of the server mode NCP that tries to
+ * accomandate all kind of corner cases in P2P mode NCP only takes IV_CIPHER
+ * into account and falls back to previous behaviour if this fails.
+ */
+void p2p_mode_ncp(struct tls_multi *multi, struct tls_session *session);
+
+/**
+ * Determines the best common cipher from both peers IV_CIPHER lists. The
+ * first cipher from the tls-server that is also in the tls-client IV_CIPHER
+ * list will be returned. If no common cipher can be found, both peer
+ * will continue to use whatever cipher is their default and NULL will be
+ * returned.
+ *
+ * @param session       tls_session
+ * @param peer_info     peer info of the peer
+ * @param gc            gc arena that will be used to allocate the returned cipher
+ * @return              common cipher if one exist.
+ */
+const char *
+get_p2p_ncp_cipher(struct tls_session *session, const char *peer_info,
+                   struct gc_arena *gc);
+
 #endif /* ifndef OPENVPN_SSL_NCP_H */
tests/unit_tests/openvpn/test_ncp.c +4 -0
index 494a02846..293093f1a 100644
@@ -44,6 +44,17 @@
 const char *bf_chacha = "BF-CBC:CHACHA20-POLY1305";
 const char *aes_ciphers = "AES-256-GCM:AES-128-GCM";
 
+
+/* Define this function here as dummy since including the ssl_*.c files
+ * leads to having to include even more unrelated code */
+bool

tests/unit_tests/openvpn/test_ncp.c line 60

Quoted 10 lines
tests/unit_tests/openvpn/test_ncp.c +7 -0
+key_state_export_keying_material(struct tls_session *session,
+                                 const char* label, size_t label_size,
+                                 void *ekm, size_t ekm_size)
+{
+    ASSERT(0);
+}
+
 static void
 test_check_ncp_ciphers_list(void **state)
 {

The rest looks good!
My tests and compile-tests all passed.

Signature · 1 line
Antonio Quartulli
#52 lore raw

[Openvpn-devel] [PATCH applied] Re: Remove --ncp-disable option

In reply to Arne Schwabe

Stared at the code for a while... this all looks very reasonable, except for removal of that warning

- msg(M_WARN, "--cipher is not set. Previous OpenVPN version defaulted to
"

-            "BF-CBC as fallback when cipher negotiation failed in this case. "
-            "If you need this fallback please add '--data-ciphers-fallback "
-            "BF-CBC' to your configuration and/or add BF-CBC to "
-            "--data-ciphers.");

.. which I find a bit surprising, since it was just recently added to help users figure out why their existing configs "suddenly fail".

Discussed this on IRC, warning will come back with a cleanup patch "soonish".

Threw this at the server side test rig, which has p2p instances, which
says: "Test sets failed: 4a 9 9a".

4a is spurious (FreeBSD, TAP, IPv6), but 9 / 9a are the p2p instances that get broken by this patch, and partially (!) repaired by the next one.

"9" is "--client" to "--tls-server".
"9a" is "--tls-client" (no -pull) to "--tls-server".

In both cases, the server does not set up data channel keys (as far as I could determine) and then fails with something like this:

2021-07-28 19:45:16 us=967365 TLS Error: local/remote TLS keys are out of sync: [AF_INET6]2001:608:0:814::f000:21:29749 (received key id: 0, known key ids:  [key#0 state=S_ACTIVE auth=KS_AUTH_TRUE id=0 sid=6491e324 c7d580ce] [key#1 state=S_UNDEF auth=KS_AUTH_FALSE id=0 sid=00000000 00000000] [key#2 state=S_UNDEF auth=KS_AUTH_FALSE id=0 sid=00000000 00000000])
..
2021-07-28 19:45:18 us=260931 Bad LZO decompression header byte: 161
..
2021-07-28 19:40:31 us=196824 Authenticate/Decrypt packet error: bad packet ID (may be a replay): [ #2721835462 ] -- see the man page entry for --no-replay and --replay-window for more info or silence this warning with --mute-replay-warnings
2021-07-28 19:40:31 us=196836 Fatal decryption error (process_incoming_link), restarting

Adding

data-ciphers-fallback BF-CBC
data-ciphers BF-CBC

to the server side config makes it work, though <<<--!!! (basically, disabling any server-side attempt at NCP, as "there is only one choice", I think).

Since this is document to break p2p, and the next patch (in this series) un-breaks this - well, breaks it in different ways - we move forward.

Your patch has been applied to the master branch.

commit caacd629f872c37c39453d3d0f2dfac229c921b1

Author: Arne Schwabe
Date:   Thu May 20 17:11:47 2021 +0200
     Remove --ncp-disable option

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg22418.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#60 lore raw

[Openvpn-devel] [PATCH applied] Re: Support NCP in pure P2P VPN setups

In reply to Arne Schwabe

I have stared at the code a bit, and it generally looks good (indent fixed as instructed).

One observation:

- in options_postprocess_cipher(), we now set "o->enable_ncp_fallback = true", but *only* if a "cipher foo" is set in the config. If not, we set the cipher to o->ciphername = "BF-CBC", but disallow ncp-fallback
- not sure if this is part of the crusade against BF-CBC "as default", but it looks a bit weird (we *set* BF-CBC as default, but do not want to use it).

Testing this in the server side testbed yielded interesting problems for the two p2p test cases, when connecting from a "pre P2P NCP" client (master, but a few months old):

** "9" is "--client" to "--tls-server" **

With a "plain" config (no data-ciphers or data-cipher-fallback) the connection works fine, both ends negotiate AES-256-GCM (= NCP works)

P2P mode NCP negotiation result: TLS_export=0, DATA_v2=0, peer-id 0, cipher=AES-256-GCM
Data Channel: using negotiated cipher 'AES-256-GCM'
Data Channel MTU parms [ L:1468 D:1450 EF:-64 EB:392 ET:32 EL:3 AF:14/8 ]
Outgoing Data Channel: Cipher 'AES-256-GCM' initialized with 256 bit key
SENT CONTROL [cron2-freebsd-tc-amd64]: 'PUSH_REPLY,route 10.204.0.0 255.255.0.0 10.204.9.1,route-ipv6 fd00:abcd:204::/48,cipher AES-256-GCM' (status=1)

.. but then:

TCP/UDP packet too large on write to [AF_INET6]::ffff:194.97.140.21:36144 (tried=1504,max=1468)

so the frame calculation is wrong, and pinging with large packets fails.

If I force the server to "no AES" (data-ciphers BF-CBC), it works:

P2P mode NCP negotiation result: TLS_export=0, DATA_v2=0, peer-id 0, cipher=BF-CBC
Outgoing Data Channel: Cipher 'BF-CBC' initialized with 128 bit key
SENT CONTROL [cron2-freebsd-tc-amd64]: 'PUSH_REPLY,route 10.204.0.0 255.255.0.0 10.204.9.1,route-ipv6 fd00:abcd:204::/48,cipher BF-CBC' (status=1)

Notably it's not telling me anything about "using negotiated cipher", and also nothing about the MTU params.

** "9a" is "--tls-client" (no -pull) to "--tls-server" **

Using the config "without --data-ciphers or --data-cipher-fallback", incoming connections fail:

P2P mode NCP negotiation result: TLS_export=0, DATA_v2=0, peer-id 0, cipher=(not negotiated, fallback-cipher: none)
TLS Error: local/remote TLS keys are out of sync: [AF_INET6]2001:608:0:814::f000:21:36664 (received key id: 0, known key ids: [key#0 state=S_ACTIVE auth=KS_AUTH_TRUE id=0 sid=9daa0f59 9d7bf877] [key#1 state=S_UNDEF auth=KS_AUTH_FALSE id=0 sid=00000000 00000000] [key#2 state=S_UNDEF auth=KS_AUTH_FALSE id=0 sid=00000000 00000000]
ERROR: failed to negotiate cipher with peer and --data-ciphers-fallback not enabled. No usable data channel cipher
ERROR: Failed to apply P2P negotiated protocol options
TLS Error: local/remote TLS keys are out of sync: [AF_INET6]2001:608:0:814::f000:21:36664 (received key id: 0, known key ids: [key#0 state=S_ACTIVE auth=KS_AUTH_TRUE id=0 sid=9daa0f59 9d7bf877] [key#1 state=S_UNDEF auth=KS_AUTH_FALSE id=0 sid=00000000 00000000] [key#2 state=S_UNDEF auth=KS_AUTH_FALSE id=0 sid=00000000 00000000])

but the server does not actively terminate the connection - so we'll see "TLS Error" errors scroll through, masking the actual error.

Adding "data-ciphers-fallback BF-CBC" makes this test instance well-behaved (though there still is *one* TLS error):

P2P mode NCP negotiation result: TLS_export=0, DATA_v2=0, peer-id 0, cipher=(not negotiated, fallback-cipher: none)
TLS Error: local/remote TLS keys are out of sync: [AF_INET6]2001:608:0:814::f000:21:47925 (received key id: 0, known key ids: [key#0 state=S_ACTIVE auth=KS_AUTH_TRUE id=0 sid=bfa5ccf1 c5c5e901] [key#1 state=S_UNDEF auth=KS_AUTH_FALSE id=0 sid=00000000 00000000] [key#2 state=S_UNDEF auth=KS_AUTH_FALSE id=0 sid=00000000 00000000]) Outgoing Data Channel: Cipher 'BF-CBC' initialized with 128 bit key

("Fallback-cipher: none" looks a bit bogus, though... this might be related to BF-CBC not being initialized early, or something)

The first case definitely needs fixing (I have more failing "frame" test cases...), the second case could need some polishing - abort the session, so it's clear "*this* is the error".

Connecting to the same instances from a client with P2P NCP yielded different results (unsurprisingly) :-)

** "9" is "--client" to "--tls-server" **

If the server is configured to "data-ciphers BF-CBC", this works. If AES is added to the cipher list, the client's IV_CIPHER= wins, and they negotiate AES-256-GCM...

peer info: IV_CIPHERS=AES-256-GCM:AES-128-GCM
peer info: IV_PROTO=30
P2P mode NCP negotiation result: TLS_export=0, DATA_v2=0, peer-id 0, cipher=AES-256-GCM Data Channel: using negotiated cipher 'AES-256-GCM'
Data Channel MTU parms [ L:1504 D:1450 EF:-28 EB:398 ET:32 EL:3 ]

.. and it fails:

TCP/UDP packet too large on write to [AF_INET6]2001:608:4::ce:c0f:51605 (tried=1536,max=1504)

forcing the client to "--data-ciphers BF-CBC" makes them "negotiate" BF-CBC, sidestepping the frame problem.

(I assume that having "--cipher AES-256-GCM" in both client and server configs upfront would also solve this, but "having to add a cipher on both sides to make NCP work" sounds like the wrong way forward)

** "9a" is "--tls-client" (no -pull) to "--tls-server" **

Given the changes to the server.conf ("data-ciphers BF-CBC") to work around the "frame" problem, this now fails with

peer info: IV_CIPHERS=BF-CBC
peer info: IV_PROTO=42
P2P mode NCP negotiation result: TLS_export=1, DATA_v2=1, peer-id 16371030, cipher=(not negotiated, fallback-cipher: none)
ERROR: failed to negotiate cipher with peer and --data-ciphers-fallback not enabled. No usable data channel cipher
ERROR: Failed to apply P2P negotiated protocol options

(but the client is not aborting!) - extending --data-ciphers makes it connect fine:

    peer info: IV_CIPHERS=BF-CBC:AES-256-GCM:AES-128-GCM
    P2P mode NCP negotiation result: TLS_export=1, DATA_v2=1, peer-id 14972877, cipher=AES-256-GCM

.. but then we are back into the "frame problem" land...

    TCP/UDP packet too large on write to [AF_INET6]2001:608:0:814::f000:11:51204 (tried=1539,max=1471)

So the only way to make this work is to restrict the client to BF-CBC, as with the --client test case.

Your patch has been applied to the master branch.

commit 8c72d7981c32c43d1c7967a312bb439e13fc5b40

Author: Arne Schwabe
Date:   Wed Jul 28 14:30:50 2021 +0200
     Support NCP in pure P2P VPN setups

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg22671.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#34 lore raw

PATCH v5 1/1 Refactor early initialisation and uninitialisation into methods

In reply to Arne Schwabe

This put the early initialisation and uninitialisation that needs to happen between option parsing and post processing into small methods.

---
 src/openvpn/openvpn.c | 23 ++++++++++++++++++-----
 1 file changed, 18 insertions(+), 5 deletions(-)
src/openvpn/openvpn.c +18 -5
index 0ac961429..da06f59c2 100644
@@ -105,6 +105,20 @@ tunnel_point_to_point(struct context *c)
 
 #undef PROCESS_SIGNAL_P2P
 
+void init_early(struct context *c)
+{
+    net_ctx_init(c, &c->net_ctx);
+
+    /* init verbosity and mute levels */
+    init_verb_mute(c, IVM_LEVEL_1);
+
+}
+
+static void uninit_early(struct context *c)
+{
+    net_ctx_free(&c->net_ctx);
+}
+
 
 /**************************************************************************/
 /**
@@ -193,10 +207,9 @@ openvpn_main(int argc, char *argv[])
             open_plugins(&c, true, OPENVPN_PLUGIN_INIT_PRE_CONFIG_PARSE);
 #endif
 
-            net_ctx_init(&c, &c.net_ctx);
-
-            /* init verbosity and mute levels */
-            init_verb_mute(&c, IVM_LEVEL_1);
+            /* Early initialisation that need to happen before option
+             * post processing and other early startup but after parsing */
+            init_early(&c);
 
             /* set dev options */
             init_options_dev(&c.options);
@@ -308,7 +321,7 @@ openvpn_main(int argc, char *argv[])
             env_set_destroy(c.es);
             uninit_options(&c.options);
             gc_reset(&c.gc);
-            net_ctx_free(&c.net_ctx);
+            uninit_early(&c);
         }
         while (c.sig->signal_received == SIGHUP);
     }
Signature · 1 line
2.33.0
Acked-by on v5 1/1
#35 lore raw

Re: [Openvpn-devel] [PATCH v5] Refactor early initialisation and uninitialisation into methods

Hi,

Quoted 4 lines · Arne Schwabe

This put the early initialisation and uninitialisation that needs to happen between option parsing and post processing into small methods.

Change looks good, no error/warning upon compilation and a basic connectivity test just worked with both sitnl and iproute2.

Signature · 1 line
Antonio Quartulli
#36 lore raw

[Openvpn-devel] [PATCH applied] Re: Refactor early initialisation and uninitialisation into methods

In reply to Arne Schwabe

Took us long enough for such a "simple" refactoring task... pesky language, this "C" stuff :-)

Thanks, Antonio, for verifying the sitnl stuff.

(GCC on Linux actually found and errored on the v4 bit with the missing "&", I just did not look at the compile result because I saw the mismatch in the diff earlier... now, no more warnings, and success on Linux/sitnl with the v5 patch)

Your patch has been applied to the master branch.

commit 97056dbf936b01b367a66ea78cca3dadc41bdf64

Author: Arne Schwabe
Date:   Sat Nov 6 19:00:55 2021 +0100
     Refactor early initialisation and uninitialisation into methods

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Antonio Quartulli <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/[email protected]/msg23110.html
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#37 lore raw

PATCH v4 1/1 Use TYPE_do_all_provided function for listing cipher/digest

In reply to Arne Schwabe

With OpenSSL 3.0 the use of nid values is deprecated and new algorithms do not even have NID values anymore.

This also works nicely with providers now:

   openvpn --provider legacy:default --show-ciphers

shows more ciphers (e.g. BF-CBC) than just

   openvpn --show-ciphers

when compiled with OpenSSL 3.0

Patch v4: Use SIZE instead size(x)/sizeof(*x)

---
 src/openvpn/crypto_openssl.c | 95 +++++++++++++++++++++++-------------
 1 file changed, 61 insertions(+), 34 deletions(-)
src/openvpn/crypto_openssl.c +61 -34
index 24ef9e90d..ab38d6e5c 100644
@@ -316,86 +316,113 @@ cipher_name_cmp(const void *a, const void *b)
     return strcmp(cipher_kt_name(*cipher_a), cipher_kt_name(*cipher_b));
 }
 
+struct collect_ciphers {
+    /* If we ever exceed this, we must be more selective */
+    const EVP_CIPHER *list[1000];
+    size_t num;
+};
+
+static void collect_ciphers(EVP_CIPHER *cipher, void *list)
+{
+    struct collect_ciphers* cipher_list = list;
+    if (cipher_list->num == SIZE(cipher_list->list))
+    {
+        msg(M_WARN, "WARNING: Too many ciphers, not showing all");
+        return;
+    }
+
+    if (cipher && (cipher_kt_mode_cbc(cipher)
+#ifdef ENABLE_OFB_CFB_MODE
+        || cipher_kt_mode_ofb_cfb(cipher)
+#endif
+        || cipher_kt_mode_aead(cipher)
+    ))
+    {
+        cipher_list->list[cipher_list->num++] = cipher;
+    }
+}
+
 void
 show_available_ciphers(void)
 {
-    int nid;
-    size_t i;
+    struct collect_ciphers cipher_list = { 0 };
 
-    /* If we ever exceed this, we must be more selective */
-    const EVP_CIPHER *cipher_list[1000];
-    size_t num_ciphers = 0;
 #ifndef ENABLE_SMALL
     printf("The following ciphers and cipher modes are available for use\n"
            "with " PACKAGE_NAME ".  Each cipher shown below may be used as a\n"
            "parameter to the --data-ciphers (or --cipher) option. In static \n"
-           "key mode only CBC mode is allowed.\n\n");
+           "key mode only CBC mode is allowed.\n");
+    printf("See also openssl list -cipher-algorithms\n\n");
 #endif
 
-    for (nid = 0; nid < 10000; ++nid)
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    EVP_CIPHER_do_all_provided(NULL, collect_ciphers, &cipher_list);
+#else
+    for (int nid = 0; nid < 10000; ++nid)
     {
         const EVP_CIPHER *cipher = EVP_get_cipherbynid(nid);
-        if (cipher && (cipher_kt_mode_cbc(cipher)
-#ifdef ENABLE_OFB_CFB_MODE
-                       || cipher_kt_mode_ofb_cfb(cipher)
-#endif
-                       || cipher_kt_mode_aead(cipher)
-                       ))
-        {
-            cipher_list[num_ciphers++] = cipher;
-        }
-        if (num_ciphers == (sizeof(cipher_list)/sizeof(*cipher_list)))
-        {
-            msg(M_WARN, "WARNING: Too many ciphers, not showing all");
-            break;
-        }
+        /* We cast the const away so we can keep the function prototype
+         * compatible with EVP_CIPHER_do_all_provided */
+        collect_ciphers((EVP_CIPHER *)cipher, &cipher_list);
     }
+#endif
 
     /* cast to non-const to prevent warning */
-    qsort((EVP_CIPHER *)cipher_list, num_ciphers, sizeof(*cipher_list), cipher_name_cmp);
+    qsort((EVP_CIPHER *)cipher_list.list, cipher_list.num, sizeof(*cipher_list.list), cipher_name_cmp);
 
-    for (i = 0; i < num_ciphers; i++)
+    for (size_t i = 0; i < cipher_list.num; i++)
     {
-        if (!cipher_kt_insecure(cipher_list[i]))
+        if (!cipher_kt_insecure(cipher_list.list[i]))
         {
-            print_cipher(cipher_list[i]);
+            print_cipher(cipher_list.list[i]);
         }
     }
 
     printf("\nThe following ciphers have a block size of less than 128 bits, \n"
            "and are therefore deprecated.  Do not use unless you have to.\n\n");
-    for (i = 0; i < num_ciphers; i++)
+    for (int i = 0; i < cipher_list.num; i++)
     {
-        if (cipher_kt_insecure(cipher_list[i]))
+        if (cipher_kt_insecure(cipher_list.list[i]))
         {
-            print_cipher(cipher_list[i]);
+            print_cipher(cipher_list.list[i]);
         }
     }
     printf("\n");
 }
 
 void
-show_available_digests(void)
+print_digest(EVP_MD* digest, void* unused)
 {
-    int nid;
+    printf("%s %d bit digest size\n", EVP_MD_get0_name(digest),
+           EVP_MD_size(digest) * 8);
+}
 
+void
+show_available_digests(void)
+{
 #ifndef ENABLE_SMALL
     printf("The following message digests are available for use with\n"
            PACKAGE_NAME ".  A message digest is used in conjunction with\n"
            "the HMAC function, to authenticate received packets.\n"
            "You can specify a message digest as parameter to\n"
-           "the --auth option.\n\n");
+           "the --auth option.\n");
+    printf("See also openssl list -digest-algorithms\n\n");
 #endif
 
-    for (nid = 0; nid < 10000; ++nid)
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    EVP_MD_do_all_provided(NULL, print_digest, NULL);
+#else
+    for (int nid = 0; nid < 10000; ++nid)
     {
         const EVP_MD *digest = EVP_get_digestbynid(nid);
         if (digest)
         {
-            printf("%s %d bit digest size\n",
-                   OBJ_nid2sn(nid), EVP_MD_size(digest) * 8);
+            /* We cast the const away so we can keep the function prototype
+             * compatible with EVP_MD_do_all_provided */
+            print_digest((EVP_MD *)digest, NULL);
         }
     }
+#endif
     printf("\n");
 }
 
Signature · 1 line
2.33.0
Acked-by on v4 1/1
#38 lore raw

[Openvpn-devel] [PATCH applied] Re: Use TYPE_do_all_provided function for listing cipher/digest

This is "v3 with the SIZE() change", and this change looks good. Max has already stated "looks good and works", but wanted the sizeof() change which is now in - so taking his pre-review, adding my own testing (makes the "cipher" part of "make check" finally succeed with 3.0, yay :-) )

The "load providers" part is not in, so I couldn't test

  openvpn --provider legacy:default --show-ciphers

yet... will come back.

Your patch has been applied to the master branch.

commit ab3f32b9069c31d1724d906b38549ab683c0d97b

Author: Arne Schwabe
Date:   Tue Nov 9 15:48:11 2021 +0100
     Use TYPE_do_all_provided function for listing cipher/digest

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

--
kind regards,

Gert Doering

#40 lore raw

PATCH v4 1/1 Allow loading of non default providers

In reply to Arne Schwabe

This allows OpenVPN to load non-default providers. This is mainly useful for loading the legacy provider with --provider legacy default

Patch v4: use spaces to seperate providers, unload providers.

---
 doc/man-sections/generic-options.rst | 10 ++++++++++
 src/openvpn/crypto_backend.h         | 14 +++++++++++++
 src/openvpn/crypto_mbedtls.c         | 13 ++++++++++++
 src/openvpn/crypto_mbedtls.h         |  3 +++
 src/openvpn/crypto_openssl.c         | 30 ++++++++++++++++++++++++++++
 src/openvpn/crypto_openssl.h         |  9 +++++++++
 src/openvpn/openvpn.c                | 13 ++++++++++++
 src/openvpn/options.c                |  7 +++++++
 src/openvpn/options.h                |  9 +++++++++
 9 files changed, 108 insertions(+)
doc/man-sections/generic-options.rst +10 -0
index e6c1fe455..f5b8a9135 100644
@@ -280,6 +280,16 @@ which mode OpenVPN is configured as.
   This option solves the problem by persisting keys across :code:`SIGUSR1`
   resets, so they don't need to be re-read.
 
+--provider providers
+  Load the : separated list of (OpenSSL) providers. This is mainly useful for
+  using an external provider for key management like tpm2-openssl or to load
+  the legacy provider with
+
+  ::
+
+      --provider "legacy:default"
+
+
 --remap-usr1 signal
   Control whether internally or externally generated :code:`SIGUSR1` signals
   are remapped to :code:`SIGHUP` (restart without persisting state) or
src/openvpn/crypto_backend.h +14 -0
index 5aab3e1b7..40984c559 100644
@@ -78,6 +78,20 @@ void crypto_clear_error(void);
  */
 void crypto_init_lib_engine(const char *engine_name);
 
+
+/**
+ * Load the given (OpenSSL) providers
+ * @param provider name of providers to load
+ * @return reference to the loaded provider
+ */
+provider_t *crypto_load_provider(const char *provider);
+
+/**
+ * Unloads the given (OpneSSL) provider
+ * @param provider pointer to the provider to unload
+ */
+void crypto_unload_provider(const char* provname, provider_t *provider);
+
 #ifdef DMALLOC
 /*
  * OpenSSL memory debugging.  If dmalloc debugging is enabled, tell
src/openvpn/crypto_mbedtls.c +13 -0
index 08b9e004f..39dbf38a5 100644
@@ -69,6 +69,19 @@ crypto_init_lib_engine(const char *engine_name)
         "available");
 }
 
+provider_t *crypto_load_provider(const char *provider)
+{
+    if (provider)
+    {
+        msg(M_WARN, "Note: mbed TLS provider functionality is not available");
+    }
+    return NULL;
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{
+}
+
 /*
  *
  * Functions related to the core crypto library
src/openvpn/crypto_mbedtls.h +3 -0
index 019de01d1..758ab1b40 100644
@@ -48,6 +48,9 @@ typedef mbedtls_md_context_t md_ctx_t;
 /** Generic HMAC %context. */
 typedef mbedtls_md_context_t hmac_ctx_t;
 
+/* Use a dummy type for the provider */
+typedef void provider_t;
+
 /** Maximum length of an IV */
 #define OPENVPN_MAX_IV_LENGTH   MBEDTLS_MAX_IV_LENGTH
 
src/openvpn/crypto_openssl.c +30 -0
index cc1d62210..ab38d6e5c 100644
@@ -54,6 +54,9 @@
 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
 #include <openssl/kdf.h>
 #endif
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
 
 #if defined(_WIN32) && defined(OPENSSL_NO_EC)
 #error Windows build with OPENSSL_NO_EC: disabling EC key is not supported.
@@ -149,6 +152,33 @@ crypto_init_lib_engine(const char *engine_name)
 #endif
 }
 
+provider_t *
+crypto_load_provider(const char *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    /* Load providers into the default (NULL) library context */
+    OSSL_PROVIDER* prov = OSSL_PROVIDER_load(NULL, provider);
+    if (!prov)
+    {
+        crypto_msg(M_FATAL, "failed to load provider '%s'", provider);
+    }
+    return prov;
+#else  /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
+    msg(M_WARN, "Note: OpenSSL hardware crypto engine functionality is not available");
+    return NULL;
+#endif
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    if (!OSSL_PROVIDER_unload(provider))
+    {
+        crypto_msg(M_FATAL, "failed to undload provider '%s'", provname);
+    }
+#endif
+}
+
 /*
  *
  * Functions related to the core crypto library
src/openvpn/crypto_openssl.h +9 -0
index e540a76b9..446f08508 100644
@@ -33,6 +33,10 @@
 #include <openssl/hmac.h>
 #include <openssl/md5.h>
 #include <openssl/sha.h>
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
+
 
 /** Generic cipher key type %context. */
 typedef EVP_CIPHER cipher_kt_t;
@@ -49,12 +53,17 @@ typedef EVP_MD_CTX md_ctx_t;
 /** Generic HMAC %context. */
 #if OPENSSL_VERSION_NUMBER < 0x30000000L
 typedef HMAC_CTX hmac_ctx_t;
+
+/* Use a dummy type for the provider */
+typedef void provider_t;
 #else
 typedef struct {
     OSSL_PARAM params[3];
     uint8_t key[EVP_MAX_KEY_LENGTH];
     EVP_MAC_CTX *ctx;
 } hmac_ctx_t;
+
+typedef OSSL_PROVIDER provider_t;
 #endif
 
 /** Maximum length of an IV */
src/openvpn/openvpn.c +13 -0
index da06f59c2..095d448b0 100644
@@ -112,10 +112,23 @@ void init_early(struct context *c)
     /* init verbosity and mute levels */
     init_verb_mute(c, IVM_LEVEL_1);
 
+    /* Initialise OpenVPN provider, this needs to be initialised this
+    * early since option post-processing and also openssl info
+    * printing depends on it */
+    for (int j=1; j < MAX_PARMS && c->options.providers.names[j]; j++)
+    {
+        c->options.providers.providers[j] =
+            crypto_load_provider(c->options.providers.names[j]);
+    }
 }
 
 static void uninit_early(struct context *c)
 {
+    for (int j=1; j < MAX_PARMS && c->options.providers.providers[j]; j++)
+    {
+        crypto_unload_provider(c->options.providers.names[j],
+                               c->options.providers.providers[j]);
+    }
     net_ctx_free(&c->net_ctx);
 }
 
src/openvpn/options.c +7 -0
index b5d65d293..87062d58d 100644
@@ -8157,6 +8157,13 @@ add_option(struct options *options,
             options->engine = "auto";
         }
     }
+    else if (streq(p[0], "provider") && p[1])
+    {
+        for (size_t j = 1; j < MAX_PARMS && p[j] != NULL;j++)
+        {
+            options->providers.names[j] = p[j];
+        }
+    }
 #endif /* ENABLE_CRYPTO_MBEDTLS */
 #ifdef ENABLE_PREDICTION_RESISTANCE
     else if (streq(p[0], "use-prediction-resistance") && !p[1])
src/openvpn/options.h +9 -0
index 20b34ed4e..d4f41cd71 100644
@@ -179,6 +179,14 @@ struct remote_list
     struct remote_entry *array[CONNECTION_LIST_SIZE];
 };
 
+struct provider_list
+{
+    /* Names of the providers */
+    const char *names[MAX_PARMS];
+    /* Pointers to the loaded providers to unload them */
+    provider_t *providers[MAX_PARMS];
+};
+
 enum vlan_acceptable_frames
 {
     VLAN_ONLY_TAGGED,
@@ -519,6 +527,7 @@ struct options
     const char *ncp_ciphers;
     const char *authname;
     const char *engine;
+    struct provider_list providers;
     bool replay;
     bool mute_replay_warnings;
     int replay_window;
Signature · 1 line
2.33.0
#41 lore raw

Re: [Openvpn-devel] [PATCH v4] [OSSL 3.0] Allow loading of non default providers

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

One tiny typo:

Sent with ProtonMail Secure Email.

‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐

Quoted 228 lines · Arne Schwabe

This allows OpenVPN to load non-default providers. This is mainly

useful for loading the legacy provider with --provider legacy default

Patch v4: use spaces to seperate providers, unload providers.

doc/man-sections/generic-options.rst | 10 ++++++++++

src/openvpn/crypto_backend.h | 14 +++++++++++++

src/openvpn/crypto_mbedtls.c | 13 ++++++++++++

src/openvpn/crypto_mbedtls.h | 3 +++

src/openvpn/crypto_openssl.c | 30 ++++++++++++++++++++++++++++

src/openvpn/crypto_openssl.h | 9 +++++++++

src/openvpn/openvpn.c | 13 ++++++++++++

src/openvpn/options.c | 7 +++++++

src/openvpn/options.h | 9 +++++++++

9 files changed, 108 insertions(+)
doc/man-sections/generic-options.rst +0 -0

index e6c1fe455..f5b8a9135 100644

--- a/doc/man-sections/generic-options.rst

+++ b/doc/man-sections/generic-options.rst

doc/man-sections/generic-options.rst +0 -0
@@ -280,6 +280,16 @@ which mode OpenVPN is configured as.
 

This option solves the problem by persisting keys across :code:SIGUSR1

resets, so they don't need to be re-read.

+--provider providers

doc/man-sections/generic-options.rst +0 -6
-   Load the : separated list of (OpenSSL) providers. This is mainly useful for
-   using an external provider for key management like tpm2-openssl or to load
-   the legacy provider with
 
-   ::
 
-        --provider "legacy:default"
 
 
 
--remap-usr1 signal

Control whether internally or externally generated :code:SIGUSR1 signals

are remapped to :code:SIGHUP (restart without persisting state) or

src/openvpn/crypto_backend.h +0 -0

index 5aab3e1b7..40984c559 100644

--- a/src/openvpn/crypto_backend.h

+++ b/src/openvpn/crypto_backend.h

src/openvpn/crypto_backend.h +0 -0
@@ -78,6 +78,20 @@ void crypto_clear_error(void);
 

/

void crypto_init_lib_engine(const char engine_name);

src/openvpn/crypto_backend.h +3 -7
+
 
+/
 
-   -   Load the given (OpenSSL) providers
-   -   @param provider name of providers to load
-   -   @return reference to the loaded provider
-   */
 
    +provider_t *crypto_load_provider(const char *provider);
 
+/**
 
-   -   Unloads the given (OpneSSL) provider
-   -   @param provider pointer to the provider to unload
-   /
 
    +void crypto_unload_provider(const char provname, provider_t *provider);

#ifdef DMALLOC

/*

src/openvpn/crypto_backend.h +4 -6
-   OpenSSL memory debugging. If dmalloc debugging is enabled, tell
 
    diff --git a/src/openvpn/crypto_mbedtls.c b/src/openvpn/crypto_mbedtls.c
 
    index 08b9e004f..39dbf38a5 100644
 
    --- a/src/openvpn/crypto_mbedtls.c
 
    +++ b/src/openvpn/crypto_mbedtls.c
 
    @@ -69,6 +69,19 @@ crypto_init_lib_engine(const char *engine_name)
 
    "available");
 
    }
 
    +provider_t *crypto_load_provider(const char *provider)
 
    +{
 
-   if (provider)
-   {
-          msg(M_WARN, "Note: mbed TLS provider functionality is not available");
 
 
-   }
-   return NULL;
 
    +}
 
+void crypto_unload_provider(const char* provname, provider_t provider)
 
+{
 
+}
 
+

/

*

- Functions related to the core crypto library

    diff --git a/src/openvpn/crypto_mbedtls.h b/src/openvpn/crypto_mbedtls.h

    index 019de01d1..758ab1b40 100644

    --- a/src/openvpn/crypto_mbedtls.h

    +++ b/src/openvpn/crypto_mbedtls.h

    @@ -48,6 +48,9 @@ typedef mbedtls_md_context_t md_ctx_t;

    /** Generic HMAC %context. /

    typedef mbedtls_md_context_t hmac_ctx_t;

    +/ Use a dummy type for the provider */

    +typedef void provider_t;

/** Maximum length of an IV */

#define OPENVPN_MAX_IV_LENGTH MBEDTLS_MAX_IV_LENGTH

src/openvpn/crypto_openssl.c +0 -0

index cc1d62210..ab38d6e5c 100644

--- a/src/openvpn/crypto_openssl.c

+++ b/src/openvpn/crypto_openssl.c

src/openvpn/crypto_openssl.c +3 -0
@@ -54,6 +54,9 @@
 
 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
 
 #include <openssl/kdf.h>
 
 #endif
 
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
 
+#include <openssl/provider.h>
 
+#endif

#if defined(_WIN32) && defined(OPENSSL_NO_EC)

#error Windows build with OPENSSL_NO_EC: disabling EC key is not supported.

src/openvpn/crypto_openssl.c +4 -9
@@ -149,6 +152,33 @@ crypto_init_lib_engine(const char *engine_name)
 
 #endif
 
 }
 
+provider_t *
 
+crypto_load_provider(const char *provider)
 
+{
 
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
 
-   /* Load providers into the default (NULL) library context */
 
-   OSSL_PROVIDER* prov = OSSL_PROVIDER_load(NULL, provider);
 
-   if (!prov)
 
-   {
 
-          crypto_msg(M_FATAL, "failed to load provider '%s'", provider);
 
 
-   }
 
-   return prov;
 
    +#else /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
 
-   msg(M_WARN, "Note: OpenSSL hardware crypto engine functionality is not available");
 
-   return NULL;
 
    +#endif
 
    +}
 

src/openvpn/crypto_openssl.c crypto_init_lib_engine(const char *engine_name)

Quoted 10 lines
src/openvpn/crypto_openssl.c +3 -3
 
+void crypto_unload_provider(const char* provname, provider_t *provider)
 
+{
 
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
 
-   if (!OSSL_PROVIDER_unload(provider))
-   {
-          crypto_msg(M_FATAL, "failed to undload provider '%s'", provname);

undload -> unload

Quoted 225 lines

- }

    +#endif

    +}

/*

*

- Functions related to the core crypto library

    diff --git a/src/openvpn/crypto_openssl.h b/src/openvpn/crypto_openssl.h

    index e540a76b9..446f08508 100644

    --- a/src/openvpn/crypto_openssl.h

    +++ b/src/openvpn/crypto_openssl.h

    @@ -33,6 +33,10 @@

    #include <openssl/hmac.h>

#include <openssl/md5.h>

#include <openssl/sha.h>

src/openvpn/crypto_openssl.c +4 -0
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
 
+#include <openssl/provider.h>
 
+#endif
 
+

/** Generic cipher key type %context. /

typedef EVP_CIPHER cipher_kt_t;

src/openvpn/crypto_openssl.c +3 -0
@@ -49,12 +53,17 @@ typedef EVP_MD_CTX md_ctx_t;
 
 /* Generic HMAC %context. /
 
 #if OPENSSL_VERSION_NUMBER < 0x30000000L
 
 typedef HMAC_CTX hmac_ctx_t;
 
+
 
+/ Use a dummy type for the provider /
 
+typedef void provider_t;
 
 #else
 

typedef struct {

OSSL_PARAM params[3];

uint8_t key[EVP_MAX_KEY_LENGTH];

EVP_MAC_CTX ctx;

} hmac_ctx_t;

src/openvpn/crypto_openssl.c +2 -0
+
 
+typedef OSSL_PROVIDER provider_t;

#endif

/ Maximum length of an IV */

src/openvpn/openvpn.c +0 -0

index da06f59c2..095d448b0 100644

--- a/src/openvpn/openvpn.c

+++ b/src/openvpn/openvpn.c

src/openvpn/openvpn.c +0 -0
@@ -112,10 +112,23 @@ void init_early(struct context c)
 

/ init verbosity and mute levels */

init_verb_mute(c, IVM_LEVEL_1);

src/openvpn/openvpn.c +0 -13
-   /* Initialise OpenVPN provider, this needs to be initialised this
 
-   -   early since option post-processing and also openssl info
-   -   printing depends on it */
-   for (int j=1; j < MAX_PARMS && c->options.providers.names[j]; j++)
 
-   {
 
-          c->options.providers.providers[j] =
 
 
-              crypto_load_provider(c->options.providers.names[j]);
 
 
-   }
 
    }
 
    static void uninit_early(struct context *c)
 
    {
 
-   for (int j=1; j < MAX_PARMS && c->options.providers.providers[j]; j++)
 
-   {
 
-          crypto_unload_provider(c->options.providers.names[j],
 
 
-                                 c->options.providers.providers[j]);
 
 
-   }
 
    net_ctx_free(&c->net_ctx);

}

src/openvpn/options.c +0 -0

index b5d65d293..87062d58d 100644

--- a/src/openvpn/options.c

+++ b/src/openvpn/options.c

src/openvpn/options.c +0 -11
@@ -8157,6 +8157,13 @@ add_option(struct options *options,
 
 options->engine = "auto";
 
         }
     }
 
 
-   else if (streq(p[0], "provider") && p[1])
 
-   {
 
-          for (size_t j = 1; j < MAX_PARMS && p[j] != NULL;j++)
 
 
-          {
 
 
-              options->providers.names[j] = p[j];
 
 
-          }
 
 
-   }
 
    #endif /* ENABLE_CRYPTO_MBEDTLS */
 
    #ifdef ENABLE_PREDICTION_RESISTANCE
 
    else if (streq(p[0], "use-prediction-resistance") && !p[1])
 
    diff --git a/src/openvpn/options.h b/src/openvpn/options.h
 
    index 20b34ed4e..d4f41cd71 100644
 
    --- a/src/openvpn/options.h
 
    +++ b/src/openvpn/options.h
 
    @@ -179,6 +179,14 @@ struct remote_list
 
    struct remote_entry *array[CONNECTION_LIST_SIZE];
 
    };
 
    +struct provider_list
 
    +{
 
-   /* Names of the providers */
 
-   const char *names[MAX_PARMS];
 
-   /* Pointers to the loaded providers to unload them */
 
-   provider_t *providers[MAX_PARMS];
 
    +};

enum vlan_acceptable_frames

{

VLAN_ONLY_TAGGED,

src/openvpn/options.c +0 -1
@@ -519,6 +527,7 @@ struct options
 
 const char *ncp_ciphers;
 
 const char *authname;
 
 const char *engine;
 
-   struct provider_list providers;
 
    bool replay;
 
    bool mute_replay_warnings;
 
    int replay_window;
 
    --
 
    2.33.0
Quoted 5 lines

Openvpn-devel mailing list

[email protected]

https://lists.sourceforge.net/lists/listinfo/openvpn-devel

-----BEGIN PGP SIGNATURE-----
Version: ProtonMail

wsBzBAEBCAAGBQJhjR3tACEJEE+XnPZrkLidFiEECbw9RGejjXJ5xVVVT5ec 9muQuJ0z7gf7BDEY0eogQt1IyxRsviF0xmpbN/vmAZo0Fbkid6DSxQF9IrOv XiIp3OZl48IlqR1PGcl2uuI71bwcmFfpU2cXjPPEDklqRxBDEr5RVT3a5Zjf Jd4Kb3n52hzfDpHqak1CNvQpc6aTSyK8fKQzk0cYJRr7JcyU9c+JVVHELU98 eBsEyXCz9IcD/7sX3NpNJS+pKds35SV/TWmOyzzBrPZFOijkE3g03R/cLhxD YVzIj+3EeewlYLufTNH9yVofUT8B8elKMeCBqij3FWTIh5eYofboG6JuXXQu KgbOeaM6/djMDWnXcdjg92gkLcRhetOb0vhfck+uSrbrplA6UE1hdg== =KyKQ
-----END PGP SIGNATURE-----

#42 lore raw

Re: [Openvpn-devel] [PATCH v4] [OSSL 3.0] Allow loading of non default providers

In reply to Arne Schwabe

Hi,

Looks good except for some documentation errors and some nits

Quoted 24 lines · Arne Schwabe

This allows OpenVPN to load non-default providers. This is mainly useful for loading the legacy provider with --provider legacy default

Patch v4: use spaces to seperate providers, unload providers.

---
 doc/man-sections/generic-options.rst | 10 ++++++++++
 src/openvpn/crypto_backend.h         | 14 +++++++++++++
 src/openvpn/crypto_mbedtls.c         | 13 ++++++++++++
 src/openvpn/crypto_mbedtls.h         |  3 +++
 src/openvpn/crypto_openssl.c         | 30 ++++++++++++++++++++++++++++
 src/openvpn/crypto_openssl.h         |  9 +++++++++
 src/openvpn/openvpn.c                | 13 ++++++++++++
 src/openvpn/options.c                |  7 +++++++
 src/openvpn/options.h                |  9 +++++++++
 9 files changed, 108 insertions(+)
doc/man-sections/generic-options.rst +0 -0
index e6c1fe455..f5b8a9135 100644

doc/man-sections/generic-options.rst which mode OpenVPN is configured as. · line 284

Quoted 5 lines
doc/man-sections/generic-options.rst +1 -0
@@ -280,6 +280,16 @@ which mode OpenVPN is configured as.
   This option solves the problem by persisting keys across :code:`SIGUSR1`
   resets, so they don't need to be re-read.
 
+--provider providers
 

For the option name please use "--providers" in plural. Here and in options.c. For the missing one-line description in usage_message, "--providers provider-list" would be apt.

+ Load the : separated list of (OpenSSL) providers. This is mainly useful

doc/man-sections/generic-options.rst which mode OpenVPN is configured as. · line 290

Quoted 9 lines

for
+ using an external provider for key management like tpm2-openssl or to load

doc/man-sections/generic-options.rst +5 -0
+  the legacy provider with
+
+  ::
+
+      --provider "legacy:default"

This is now changed to space-separated, right? So:

--providers legacy default

It may be worth pointing out that it's best to not change this option between SIGHUPs.

Unlike most other options, this would behave somewhat unintuitively on SIGHUP. If started with "--providers foo" and then if this option is removed and a SIGHUP done, no providers will be loaded and connection will fail. On the other hand a fresh start with no "--providers" option, the fallback provider (default) will get auto-loaded.

Quoted 14 lines
doc/man-sections/generic-options.rst +2 -0
+
+
 --remap-usr1 signal
   Control whether internally or externally generated :code:`SIGUSR1`

signals
are remapped to :code:SIGHUP (restart without persisting state) or

src/openvpn/crypto_backend.h +0 -0
index 5aab3e1b7..40984c559 100644
@@ -78,6 +78,20 @@ void crypto_clear_error(void);
  */
 void crypto_init_lib_engine(const char *engine_name);
 

src/openvpn/crypto_backend.h void crypto_clear_error(void); · line 90

Quoted 10 lines
src/openvpn/crypto_backend.h +10 -0
+
+/**
+ * Load the given (OpenSSL) providers
+ * @param provider name of providers to load
+ * @return reference to the loaded provider
+ */
+provider_t *crypto_load_provider(const char *provider);
+
+/**
+ * Unloads the given (OpneSSL) provider

To nit-pick: @param provname

Quoted 17 lines
src/openvpn/crypto_backend.h +4 -0
+ * @param provider pointer to the provider to unload
+ */
+void crypto_unload_provider(const char* provname, provider_t *provider);
+
 #ifdef DMALLOC
 /*
  * OpenSSL memory debugging.  If dmalloc debugging is enabled, tell
src/openvpn/crypto_mbedtls.c +2 -0
index 08b9e004f..39dbf38a5 100644
@@ -69,6 +69,19 @@ crypto_init_lib_engine(const char *engine_name)
         "available");
 }
 
+provider_t *crypto_load_provider(const char *provider)
+{

src/openvpn/crypto_mbedtls.c crypto_init_lib_engine(const char *engine_name) · line 83

Quoted 10 lines
src/openvpn/crypto_mbedtls.c +9 -0
+    if (provider)
+    {
+        msg(M_WARN, "Note: mbed TLS provider functionality is not
 available");
+    }
+    return NULL;
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{

Personally I do not care, but in case we have a policy on no-unused vars, something like "(void) provname;" etc would be needed.

Quoted 44 lines
src/openvpn/crypto_mbedtls.c +2 -0
+}
+
 /*
  *

* Functions related to the core crypto library

src/openvpn/crypto_mbedtls.h +3 -0
index 019de01d1..758ab1b40 100644
@@ -48,6 +48,9 @@ typedef mbedtls_md_context_t md_ctx_t;
 /** Generic HMAC %context. */
 typedef mbedtls_md_context_t hmac_ctx_t;
 
+/* Use a dummy type for the provider */
+typedef void provider_t;
+
 /** Maximum length of an IV */
 #define OPENVPN_MAX_IV_LENGTH   MBEDTLS_MAX_IV_LENGTH
 
src/openvpn/crypto_openssl.c +3 -0
index cc1d62210..ab38d6e5c 100644
@@ -54,6 +54,9 @@
 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) &&
 !defined(LIBRESSL_VERSION_NUMBER)
 #include <openssl/kdf.h>
 #endif
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
 
 #if defined(_WIN32) && defined(OPENSSL_NO_EC)

#error Windows build with OPENSSL_NO_EC: disabling EC key is not
supported.

src/openvpn/crypto_openssl.c +5 -0
@@ -149,6 +152,33 @@ crypto_init_lib_engine(const char *engine_name)
 #endif
 }
 
+provider_t *
+crypto_load_provider(const char *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    /* Load providers into the default (NULL) library context */

src/openvpn/crypto_openssl.c crypto_init_lib_engine(const char *engine_name) · line 169

Quoted 10 lines
src/openvpn/crypto_openssl.c +8 -0
+    OSSL_PROVIDER* prov = OSSL_PROVIDER_load(NULL, provider);
+    if (!prov)
+    {
+        crypto_msg(M_FATAL, "failed to load provider '%s'", provider);
+    }
+    return prov;
+#else  /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
+    msg(M_WARN, "Note: OpenSSL hardware crypto engine functionality is
 not available");
 

"hardware crypto engine" --> "provider"

src/openvpn/crypto_openssl.c crypto_init_lib_engine(const char *engine_name)

Quoted 11 lines
src/openvpn/crypto_openssl.c +10 -0
+    return NULL;
+#endif
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    if (!OSSL_PROVIDER_unload(provider))
+    {
+        crypto_msg(M_FATAL, "failed to undload provider '%s'", provname);
 

"undload" --> "unload"

Quoted 45 lines
src/openvpn/crypto_openssl.c +4 -0
+    }
+#endif
+}
+

/*
*
* Functions related to the core crypto library

src/openvpn/crypto_openssl.h +9 -0
index e540a76b9..446f08508 100644
@@ -33,6 +33,10 @@
 #include <openssl/hmac.h>
 #include <openssl/md5.h>
 #include <openssl/sha.h>
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
+
 
 /** Generic cipher key type %context. */
 typedef EVP_CIPHER cipher_kt_t;
@@ -49,12 +53,17 @@ typedef EVP_MD_CTX md_ctx_t;
 /** Generic HMAC %context. */
 #if OPENSSL_VERSION_NUMBER < 0x30000000L
 typedef HMAC_CTX hmac_ctx_t;
+
+/* Use a dummy type for the provider */
+typedef void provider_t;
 #else
 typedef struct {
     OSSL_PARAM params[3];
     uint8_t key[EVP_MAX_KEY_LENGTH];
     EVP_MAC_CTX *ctx;
 } hmac_ctx_t;
+
+typedef OSSL_PROVIDER provider_t;
 #endif
 
 /** Maximum length of an IV */
src/openvpn/openvpn.c +0 -0
index da06f59c2..095d448b0 100644

src/openvpn/openvpn.c void init_early(struct context *c) · line 116

Quoted 5 lines
src/openvpn/openvpn.c +1 -0
@@ -112,10 +112,23 @@ void init_early(struct context *c)
     /* init verbosity and mute levels */
     init_verb_mute(c, IVM_LEVEL_1);
 
+    /* Initialise OpenVPN provider, this needs to be initialised this
 

"OpenVPN provider" --> "OpenSSL provider"

Quoted 24 lines
src/openvpn/openvpn.c +12 -0
+    * early since option post-processing and also openssl info
+    * printing depends on it */
+    for (int j=1; j < MAX_PARMS && c->options.providers.names[j]; j++)
+    {
+        c->options.providers.providers[j] =
+            crypto_load_provider(c->options.providers.names[j]);
+    }
 }
 
 static void uninit_early(struct context *c)
 {
+    for (int j=1; j < MAX_PARMS && c->options.providers.providers[j]; j++)
+    {
+        crypto_unload_provider(c->options.providers.names[j],
+                               c->options.providers.providers[j]);
+    }
     net_ctx_free(&c->net_ctx);
 }
src/openvpn/options.c +0 -0
index b5d65d293..87062d58d 100644

src/openvpn/options.c add_option(struct options *options, · line 8161

Quoted 5 lines
src/openvpn/options.c +1 -0
@@ -8157,6 +8157,13 @@ add_option(struct options *options,
             options->engine = "auto";
         }
     }
+    else if (streq(p[0], "provider") && p[1])
 

"providers" please

Quoted 30 lines
src/openvpn/options.c +6 -0
+    {
+        for (size_t j = 1; j < MAX_PARMS && p[j] != NULL;j++)
+        {
+            options->providers.names[j] = p[j];
+        }
+    }
 #endif /* ENABLE_CRYPTO_MBEDTLS */
 #ifdef ENABLE_PREDICTION_RESISTANCE
     else if (streq(p[0], "use-prediction-resistance") && !p[1])
src/openvpn/options.h +8 -0
index 20b34ed4e..d4f41cd71 100644
@@ -179,6 +179,14 @@ struct remote_list
     struct remote_entry *array[CONNECTION_LIST_SIZE];
 };
 
+struct provider_list
+{
+    /* Names of the providers */
+    const char *names[MAX_PARMS];
+    /* Pointers to the loaded providers to unload them */
+    provider_t *providers[MAX_PARMS];
+};
+
 enum vlan_acceptable_frames
 {
     VLAN_ONLY_TAGGED,

src/openvpn/options.h struct options · line 533

Quoted 7 lines
src/openvpn/options.h +1 -0
@@ -519,6 +527,7 @@ struct options
     const char *ncp_ciphers;
     const char *authname;
     const char *engine;
+    struct provider_list providers;
     bool replay;
     bool mute_replay_warnings;
     int replay_window;

The new option is not added to usage_message for --help and usage().

Selva

#43 lore raw

PATCH v5 1/1 Allow loading of non default providers

In reply to Arne Schwabe

This allows OpenVPN to load non-default providers. This is mainly useful for loading the legacy provider with --providers legacy default

Patch v4: use spaces to seperate providers, unload providers. Patch v5: General cleanup, rename option to --providers, add
option to usage() and add an entry to Changes.rst

---
 Changes.rst                          |  7 +++++++
 doc/man-sections/generic-options.rst | 12 +++++++++++
 src/openvpn/crypto_backend.h         | 15 ++++++++++++++
 src/openvpn/crypto_mbedtls.c         | 13 ++++++++++++
 src/openvpn/crypto_mbedtls.h         |  3 +++
 src/openvpn/crypto_openssl.c         | 30 ++++++++++++++++++++++++++++
 src/openvpn/crypto_openssl.h         |  9 +++++++++
 src/openvpn/openvpn.c                | 13 ++++++++++++
 src/openvpn/options.c                |  8 ++++++++
 src/openvpn/options.h                |  9 +++++++++
 10 files changed, 119 insertions(+)
Changes.rst +7 -0
index 6f04e59ac..0ce39a839 100644
@@ -50,6 +50,13 @@ Compatibility mode (``--compat-mode``)
     with older peers. The options ``--compat-mode`` allows UIs to provide users
     with an easy way to still connect to older servers.
 
+OpenSSL 3.0 support
+    OpenSSL 3.0 has been added. Most of OpenSSL 3.0 changes are not user visible but
+    improve general compatibility with OpenSSL 3.0. ``--tls-cert-profile insecure``
+    has been added to allow selecting the lowest OpenSSL security level (not
+    recommended, use only if you must). OpenSSL 3.0 no longer supports the Blowfish
+    (and other deprecated) algorithm by default and the new option ``--provider``
+    allows loading the legacy provider to renable these algorithms.
 
 Deprecated features
 -------------------
doc/man-sections/generic-options.rst +12 -0
index e6c1fe455..a8f049f20 100644
@@ -280,6 +280,18 @@ which mode OpenVPN is configured as.
   This option solves the problem by persisting keys across :code:`SIGUSR1`
   resets, so they don't need to be re-read.
 
+--providers providers
+  Load the list of (OpenSSL) providers. This is mainly useful for using an
+  external provider for key management like tpm2-openssl or to load the
+  legacy provider with
+
+  ::
+
+      --providers legacy default
+
+  Behaviour of changing this option between SIGHUP might not be well behaving.
+  If you need to change/add/remove this option, fully restart OpenVPN.
+
 --remap-usr1 signal
   Control whether internally or externally generated :code:`SIGUSR1` signals
   are remapped to :code:`SIGHUP` (restart without persisting state) or
src/openvpn/crypto_backend.h +15 -0
index 5aab3e1b7..c16837619 100644
@@ -78,6 +78,21 @@ void crypto_clear_error(void);
  */
 void crypto_init_lib_engine(const char *engine_name);
 
+
+/**
+ * Load the given (OpenSSL) providers
+ * @param provider name of providers to load
+ * @return reference to the loaded provider
+ */
+provider_t *crypto_load_provider(const char *provider);
+
+/**
+ * Unloads the given (OpenSSL) provider
+ * @param provname  name of the provider to unload
+ * @param provider  pointer to the provider to unload
+ */
+void crypto_unload_provider(const char* provname, provider_t *provider);
+
 #ifdef DMALLOC
 /*
  * OpenSSL memory debugging.  If dmalloc debugging is enabled, tell
src/openvpn/crypto_mbedtls.c +13 -0
index 08b9e004f..39dbf38a5 100644
@@ -69,6 +69,19 @@ crypto_init_lib_engine(const char *engine_name)
         "available");
 }
 
+provider_t *crypto_load_provider(const char *provider)
+{
+    if (provider)
+    {
+        msg(M_WARN, "Note: mbed TLS provider functionality is not available");
+    }
+    return NULL;
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{
+}
+
 /*
  *
  * Functions related to the core crypto library
src/openvpn/crypto_mbedtls.h +3 -0
index 019de01d1..758ab1b40 100644
@@ -48,6 +48,9 @@ typedef mbedtls_md_context_t md_ctx_t;
 /** Generic HMAC %context. */
 typedef mbedtls_md_context_t hmac_ctx_t;
 
+/* Use a dummy type for the provider */
+typedef void provider_t;
+
 /** Maximum length of an IV */
 #define OPENVPN_MAX_IV_LENGTH   MBEDTLS_MAX_IV_LENGTH
 
src/openvpn/crypto_openssl.c +30 -0
index cc1d62210..c9731adb3 100644
@@ -54,6 +54,9 @@
 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
 #include <openssl/kdf.h>
 #endif
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
 
 #if defined(_WIN32) && defined(OPENSSL_NO_EC)
 #error Windows build with OPENSSL_NO_EC: disabling EC key is not supported.
@@ -149,6 +152,33 @@ crypto_init_lib_engine(const char *engine_name)
 #endif
 }
 
+provider_t *
+crypto_load_provider(const char *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    /* Load providers into the default (NULL) library context */
+    OSSL_PROVIDER* prov = OSSL_PROVIDER_load(NULL, provider);
+    if (!prov)
+    {
+        crypto_msg(M_FATAL, "failed to load provider '%s'", provider);
+    }
+    return prov;
+#else  /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
+    msg(M_WARN, "Note: OpenSSL provider functionality is not available");
+    return NULL;
+#endif
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    if (!OSSL_PROVIDER_unload(provider))
+    {
+        crypto_msg(M_FATAL, "failed to unload provider '%s'", provname);
+    }
+#endif
+}
+
 /*
  *
  * Functions related to the core crypto library
src/openvpn/crypto_openssl.h +9 -0
index e540a76b9..446f08508 100644
@@ -33,6 +33,10 @@
 #include <openssl/hmac.h>
 #include <openssl/md5.h>
 #include <openssl/sha.h>
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
+
 
 /** Generic cipher key type %context. */
 typedef EVP_CIPHER cipher_kt_t;
@@ -49,12 +53,17 @@ typedef EVP_MD_CTX md_ctx_t;
 /** Generic HMAC %context. */
 #if OPENSSL_VERSION_NUMBER < 0x30000000L
 typedef HMAC_CTX hmac_ctx_t;
+
+/* Use a dummy type for the provider */
+typedef void provider_t;
 #else
 typedef struct {
     OSSL_PARAM params[3];
     uint8_t key[EVP_MAX_KEY_LENGTH];
     EVP_MAC_CTX *ctx;
 } hmac_ctx_t;
+
+typedef OSSL_PROVIDER provider_t;
 #endif
 
 /** Maximum length of an IV */
src/openvpn/openvpn.c +13 -0
index da06f59c2..a18a4dd43 100644
@@ -112,10 +112,23 @@ void init_early(struct context *c)
     /* init verbosity and mute levels */
     init_verb_mute(c, IVM_LEVEL_1);
 
+    /* Initialise OpenSSL provider, this needs to be initialised this
+    * early since option post-processing and also openssl info
+    * printing depends on it */
+    for (int j=1; j < MAX_PARMS && c->options.providers.names[j]; j++)
+    {
+        c->options.providers.providers[j] =
+            crypto_load_provider(c->options.providers.names[j]);
+    }
 }
 
 static void uninit_early(struct context *c)
 {
+    for (int j=1; j < MAX_PARMS && c->options.providers.providers[j]; j++)
+    {
+        crypto_unload_provider(c->options.providers.names[j],
+                               c->options.providers.providers[j]);
+    }
     net_ctx_free(&c->net_ctx);
 }
 
src/openvpn/options.c +8 -0
index b5d65d293..b1f9473dc 100644
@@ -581,6 +581,7 @@ static const char usage_message[] =
     "                : Use --show-tls to see a list of supported TLS ciphers (suites).\n"
     "--tls-cert-profile p : Set the allowed certificate crypto algorithm profile\n"
     "                  (default=legacy).\n"
+    "--providers l   : A list l of OpenSSL providers to load.\n"
     "--tls-timeout n : Packet retransmit timeout on TLS control channel\n"
     "                  if no ACK from remote within n seconds (default=%d).\n"
     "--reneg-bytes n : Renegotiate data chan. key after n bytes sent and recvd.\n"
@@ -8157,6 +8158,13 @@ add_option(struct options *options,
             options->engine = "auto";
         }
     }
+    else if (streq(p[0], "providers") && p[1])
+    {
+        for (size_t j = 1; j < MAX_PARMS && p[j] != NULL;j++)
+        {
+            options->providers.names[j] = p[j];
+        }
+    }
 #endif /* ENABLE_CRYPTO_MBEDTLS */
 #ifdef ENABLE_PREDICTION_RESISTANCE
     else if (streq(p[0], "use-prediction-resistance") && !p[1])
src/openvpn/options.h +9 -0
index 20b34ed4e..d4f41cd71 100644
@@ -179,6 +179,14 @@ struct remote_list
     struct remote_entry *array[CONNECTION_LIST_SIZE];
 };
 
+struct provider_list
+{
+    /* Names of the providers */
+    const char *names[MAX_PARMS];
+    /* Pointers to the loaded providers to unload them */
+    provider_t *providers[MAX_PARMS];
+};
+
 enum vlan_acceptable_frames
 {
     VLAN_ONLY_TAGGED,
@@ -519,6 +527,7 @@ struct options
     const char *ncp_ciphers;
     const char *authname;
     const char *engine;
+    struct provider_list providers;
     bool replay;
     bool mute_replay_warnings;
     int replay_window;
Signature · 1 line
2.33.0
Acked-by on v5 1/1
#44 lore raw

Re: [Openvpn-devel] [PATCH v5] [OSSL 3.0] Allow loading of non default providers

Hi,

Quoted 305 lines · Arne Schwabe

This allows OpenVPN to load non-default providers. This is mainly useful for loading the legacy provider with --providers legacy default

Patch v4: use spaces to seperate providers, unload providers. Patch v5: General cleanup, rename option to --providers, add
option to usage() and add an entry to Changes.rst

---
 Changes.rst                          |  7 +++++++
 doc/man-sections/generic-options.rst | 12 +++++++++++
 src/openvpn/crypto_backend.h         | 15 ++++++++++++++
 src/openvpn/crypto_mbedtls.c         | 13 ++++++++++++
 src/openvpn/crypto_mbedtls.h         |  3 +++
 src/openvpn/crypto_openssl.c         | 30 ++++++++++++++++++++++++++++
 src/openvpn/crypto_openssl.h         |  9 +++++++++
 src/openvpn/openvpn.c                | 13 ++++++++++++
 src/openvpn/options.c                |  8 ++++++++
 src/openvpn/options.h                |  9 +++++++++
 10 files changed, 119 insertions(+)
Changes.rst +0 -0
index 6f04e59ac..0ce39a839 100644
@@ -50,6 +50,13 @@ Compatibility mode (``--compat-mode``)
     with older peers. The options ``--compat-mode`` allows UIs to provide

users
with an easy way to still connect to older servers.

Changes.rst +2 -0
+OpenSSL 3.0 support
+    OpenSSL 3.0 has been added. Most of OpenSSL 3.0 changes are not user

visible but
+ improve general compatibility with OpenSSL 3.0. ``--tls-cert-profile
insecure``
+ has been added to allow selecting the lowest OpenSSL security level
(not
+ recommended, use only if you must). OpenSSL 3.0 no longer supports
the Blowfish
+ (and other deprecated) algorithm by default and the new option
``--provider``

Changes.rst +1 -0
+    allows loading the legacy provider to renable these algorithms.
 
 Deprecated features
 -------------------
doc/man-sections/generic-options.rst +10 -0
index e6c1fe455..a8f049f20 100644
@@ -280,6 +280,18 @@ which mode OpenVPN is configured as.
   This option solves the problem by persisting keys across :code:`SIGUSR1`
   resets, so they don't need to be re-read.
 
+--providers providers
+  Load the list of (OpenSSL) providers. This is mainly useful for using an
+  external provider for key management like tpm2-openssl or to load the
+  legacy provider with
+
+  ::
+
+      --providers legacy default
+
+  Behaviour of changing this option between SIGHUP might not be well

behaving.

doc/man-sections/generic-options.rst +2 -0
+  If you need to change/add/remove this option, fully restart OpenVPN.
+
 --remap-usr1 signal
   Control whether internally or externally generated :code:`SIGUSR1`

signals
are remapped to :code:SIGHUP (restart without persisting state) or

src/openvpn/crypto_backend.h +15 -0
index 5aab3e1b7..c16837619 100644
@@ -78,6 +78,21 @@ void crypto_clear_error(void);
  */
 void crypto_init_lib_engine(const char *engine_name);
 
+
+/**
+ * Load the given (OpenSSL) providers
+ * @param provider name of providers to load
+ * @return reference to the loaded provider
+ */
+provider_t *crypto_load_provider(const char *provider);
+
+/**
+ * Unloads the given (OpenSSL) provider
+ * @param provname  name of the provider to unload
+ * @param provider  pointer to the provider to unload
+ */
+void crypto_unload_provider(const char* provname, provider_t *provider);
+
 #ifdef DMALLOC
 /*
  * OpenSSL memory debugging.  If dmalloc debugging is enabled, tell
src/openvpn/crypto_mbedtls.c +13 -0
index 08b9e004f..39dbf38a5 100644
@@ -69,6 +69,19 @@ crypto_init_lib_engine(const char *engine_name)
         "available");
 }
 
+provider_t *crypto_load_provider(const char *provider)
+{
+    if (provider)
+    {
+        msg(M_WARN, "Note: mbed TLS provider functionality is not
 available");
+    }
+    return NULL;
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{
+}
+
 /*
  *

* Functions related to the core crypto library

src/openvpn/crypto_mbedtls.h +3 -0
index 019de01d1..758ab1b40 100644
@@ -48,6 +48,9 @@ typedef mbedtls_md_context_t md_ctx_t;
 /** Generic HMAC %context. */
 typedef mbedtls_md_context_t hmac_ctx_t;
 
+/* Use a dummy type for the provider */
+typedef void provider_t;
+
 /** Maximum length of an IV */
 #define OPENVPN_MAX_IV_LENGTH   MBEDTLS_MAX_IV_LENGTH
 
src/openvpn/crypto_openssl.c +3 -0
index cc1d62210..c9731adb3 100644
@@ -54,6 +54,9 @@
 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) &&
 !defined(LIBRESSL_VERSION_NUMBER)
 #include <openssl/kdf.h>
 #endif
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
 
 #if defined(_WIN32) && defined(OPENSSL_NO_EC)

#error Windows build with OPENSSL_NO_EC: disabling EC key is not
supported.

src/openvpn/crypto_openssl.c +27 -0
@@ -149,6 +152,33 @@ crypto_init_lib_engine(const char *engine_name)
 #endif
 }
 
+provider_t *
+crypto_load_provider(const char *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    /* Load providers into the default (NULL) library context */
+    OSSL_PROVIDER* prov = OSSL_PROVIDER_load(NULL, provider);
+    if (!prov)
+    {
+        crypto_msg(M_FATAL, "failed to load provider '%s'", provider);
+    }
+    return prov;
+#else  /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
+    msg(M_WARN, "Note: OpenSSL provider functionality is not available");
+    return NULL;
+#endif
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    if (!OSSL_PROVIDER_unload(provider))
+    {
+        crypto_msg(M_FATAL, "failed to unload provider '%s'", provname);
+    }
+#endif
+}
+
 /*
  *
  * Functions related to the core crypto library
src/openvpn/crypto_openssl.h +9 -0
index e540a76b9..446f08508 100644
@@ -33,6 +33,10 @@
 #include <openssl/hmac.h>
 #include <openssl/md5.h>
 #include <openssl/sha.h>
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
+
 
 /** Generic cipher key type %context. */
 typedef EVP_CIPHER cipher_kt_t;
@@ -49,12 +53,17 @@ typedef EVP_MD_CTX md_ctx_t;
 /** Generic HMAC %context. */
 #if OPENSSL_VERSION_NUMBER < 0x30000000L
 typedef HMAC_CTX hmac_ctx_t;
+
+/* Use a dummy type for the provider */
+typedef void provider_t;
 #else
 typedef struct {
     OSSL_PARAM params[3];
     uint8_t key[EVP_MAX_KEY_LENGTH];
     EVP_MAC_CTX *ctx;
 } hmac_ctx_t;
+
+typedef OSSL_PROVIDER provider_t;
 #endif
 
 /** Maximum length of an IV */
src/openvpn/openvpn.c +13 -0
index da06f59c2..a18a4dd43 100644
@@ -112,10 +112,23 @@ void init_early(struct context *c)
     /* init verbosity and mute levels */
     init_verb_mute(c, IVM_LEVEL_1);
 
+    /* Initialise OpenSSL provider, this needs to be initialised this
+    * early since option post-processing and also openssl info
+    * printing depends on it */
+    for (int j=1; j < MAX_PARMS && c->options.providers.names[j]; j++)
+    {
+        c->options.providers.providers[j] =
+            crypto_load_provider(c->options.providers.names[j]);
+    }
 }
 
 static void uninit_early(struct context *c)
 {
+    for (int j=1; j < MAX_PARMS && c->options.providers.providers[j]; j++)
+    {
+        crypto_unload_provider(c->options.providers.names[j],
+                               c->options.providers.providers[j]);
+    }
     net_ctx_free(&c->net_ctx);
 }
 
src/openvpn/options.c +0 -0
index b5d65d293..b1f9473dc 100644
@@ -581,6 +581,7 @@ static const char usage_message[] =
     "                : Use --show-tls to see a list of supported TLS

ciphers (suites).\n"
"--tls-cert-profile p : Set the allowed certificate crypto algorithm
profile\n"
" (default=legacy).\n"
+ "--providers l : A list l of OpenSSL providers to load.\n"
"--tls-timeout n : Packet retransmit timeout on TLS control channel\n"
" if no ACK from remote within n seconds
(default=%d).\n"
"--reneg-bytes n : Renegotiate data chan. key after n bytes sent and
recvd.\n"

src/openvpn/options.c +7 -0
@@ -8157,6 +8158,13 @@ add_option(struct options *options,
             options->engine = "auto";
         }
     }
+    else if (streq(p[0], "providers") && p[1])
+    {
+        for (size_t j = 1; j < MAX_PARMS && p[j] != NULL;j++)
+        {
+            options->providers.names[j] = p[j];
+        }
+    }
 #endif /* ENABLE_CRYPTO_MBEDTLS */
 #ifdef ENABLE_PREDICTION_RESISTANCE
     else if (streq(p[0], "use-prediction-resistance") && !p[1])
src/openvpn/options.h +9 -1
index 20b34ed4e..d4f41cd71 100644
@@ -179,6 +179,14 @@ struct remote_list
     struct remote_entry *array[CONNECTION_LIST_SIZE];
 };
 
+struct provider_list
+{
+    /* Names of the providers */
+    const char *names[MAX_PARMS];
+    /* Pointers to the loaded providers to unload them */
+    provider_t *providers[MAX_PARMS];
+};
+
 enum vlan_acceptable_frames
 {
     VLAN_ONLY_TAGGED,
@@ -519,6 +527,7 @@ struct options
     const char *ncp_ciphers;
     const char *authname;
     const char *engine;
+    struct provider_list providers;
     bool replay;
     bool mute_replay_warnings;
     int replay_window;
--
Quoted 2 lines

2.33.0

Request for nit-fix during commit:
In the newly added paragraph in Changes.rst please change ``--provider`` to ``--providers``

Selva

#45 lore raw

Re: [Openvpn-devel] [PATCH v5] [OSSL 3.0] Allow loading of non default providers

In reply to Arne Schwabe

Hi,

Quoted 6 lines · Arne Schwabe
src/openvpn/options.c +0 -0
index b5d65d293..b1f9473dc 100644
@@ -8157,6 +8158,13 @@ add_option(struct options *options,
             options->engine = "auto";

src/openvpn/options.c add_option(struct options *options, · line 8168

Quoted 10 lines
src/openvpn/options.c +7 -0
         }
     }
+    else if (streq(p[0], "providers") && p[1])
+    {
+        for (size_t j = 1; j < MAX_PARMS && p[j] != NULL;j++)
+        {
+            options->providers.names[j] = p[j];
+        }
+    }
 #endif /* ENABLE_CRYPTO_MBEDTLS */

This seems to be in an #ifndef ENABLE_CRYPTO_MBEDTLS block, which means an mbedTLS build won't understand the option "--providers" (but --help shows it, and there's a "mbed TLS provider functionality is not available" patch in crypto_mbedtls.c...)

Sounds somewhat unintentional?

(I'm primarily complaining because my server side testbed strongly dislikes options that are necessary for particular builds, but break on other builds... :-) )

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]...
#46 lore raw

Re: [Openvpn-devel] [PATCH v5] [OSSL 3.0] Allow loading of non default providers

Quoted 17 lines · Gert Doering

Hi,

Quoted 13 lines · Arne Schwabe
src/openvpn/options.c +5 -0
index b5d65d293..b1f9473dc 100644
@@ -8157,6 +8158,13 @@ add_option(struct options *options,
             options->engine = "auto";
         }
     }
+    else if (streq(p[0], "providers") && p[1])
+    {
+        for (size_t j = 1; j < MAX_PARMS && p[j] != NULL;j++)
+        {
+            options->providers.names[j] = p[j];
Quoted 8 lines

src/openvpn/options.c add_option(struct options *options, · line 8168

Quoted 3 lines
src/openvpn/options.c +2 -0
+        }
+    }
 #endif /* ENABLE_CRYPTO_MBEDTLS */

This seems to be in an #ifndef ENABLE_CRYPTO_MBEDTLS block, which means an mbedTLS build won't understand the option "--providers" (but --help shows it, and there's a "mbed TLS provider functionality is not available" patch in crypto_mbedtls.c...)

hmm.. obviously I did not build with mbed TLS nor think about it. Some empty functions in crypto_mbedtls.c are still required as the load and unload are unconditionally called.

Moving this out of the #ifndef will make --help consistent with the option, but at the same time it's misleading to include this in --help for mbedTLS builds: the user will get a warning if the option is used. I think we should add this option to --help only for OpenSSL. And, while parsing, add provider names to the list only for OpenSSL, show a warning for mbedTLS. That way the list will remain empty for mbedTLS. I'm supposing that we do not want --provider to become a M_FATAL error in mbedTLS builds.

Whether the msg(WARN,..) in crypto_mbedtls.c are removed or not is a matter of taste -- they will never get executed if not parsed here.

Selva

#47 lore raw

Re: [Openvpn-devel] [PATCH v5] [OSSL 3.0] Allow loading of non default providers

Hi,

Quoted 2 lines · Selva Nair

I'm supposing that we do not want --provider to become a M_FATAL error in mbedTLS builds.

For "generic OpenVPN" I'm not sure this makes a real difference - you know what your build uses, and if you need --provider, you know that you do (it's not something you add for fun).

For my server testing environment it does, as it builds with different crypto libraries for different days (mbedTLS, OpenSSL 1.1, OpenSSL 3.0), so having an option that is needed for 3.0 builds but breaks mbedTLS builds would complicate things...

That said, the code looks like it assumed "the option is always there, so on mbedTLS, ignore and warn" :-)

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]...
#48 lore raw

PATCH v6 1/1 Allow loading of non default providers

In reply to Arne Schwabe

This allows OpenVPN to load non-default providers. This is mainly useful for loading the legacy provider with --providers legacy default

Patch v4: use spaces to seperate providers, unload providers. Patch v5: General cleanup, rename option to --providers, add
option to usage() and add an entry to Changes.rst
Patch v6: allow --providers also to be used (and be ignored) with mbed TLS

---
 Changes.rst                          |  7 +++++++
 doc/man-sections/generic-options.rst | 12 +++++++++++
 src/openvpn/crypto_backend.h         | 15 ++++++++++++++
 src/openvpn/crypto_mbedtls.c         | 13 ++++++++++++
 src/openvpn/crypto_mbedtls.h         |  3 +++
 src/openvpn/crypto_openssl.c         | 30 ++++++++++++++++++++++++++++
 src/openvpn/crypto_openssl.h         |  9 +++++++++
 src/openvpn/openvpn.c                | 13 ++++++++++++
 src/openvpn/options.c                |  8 ++++++++
 src/openvpn/options.h                |  9 +++++++++
 10 files changed, 119 insertions(+)
Changes.rst +7 -0
index 6f04e59ac..7cceffcdb 100644
@@ -50,6 +50,13 @@ Compatibility mode (``--compat-mode``)
     with older peers. The options ``--compat-mode`` allows UIs to provide users
     with an easy way to still connect to older servers.
 
+OpenSSL 3.0 support
+    OpenSSL 3.0 has been added. Most of OpenSSL 3.0 changes are not user visible but
+    improve general compatibility with OpenSSL 3.0. ``--tls-cert-profile insecure``
+    has been added to allow selecting the lowest OpenSSL security level (not
+    recommended, use only if you must). OpenSSL 3.0 no longer supports the Blowfish
+    (and other deprecated) algorithm by default and the new option ``--providers``
+    allows loading the legacy provider to renable these algorithms.
 
 Deprecated features
 -------------------
doc/man-sections/generic-options.rst +12 -0
index e6c1fe455..a8f049f20 100644
@@ -280,6 +280,18 @@ which mode OpenVPN is configured as.
   This option solves the problem by persisting keys across :code:`SIGUSR1`
   resets, so they don't need to be re-read.
 
+--providers providers
+  Load the list of (OpenSSL) providers. This is mainly useful for using an
+  external provider for key management like tpm2-openssl or to load the
+  legacy provider with
+
+  ::
+
+      --providers legacy default
+
+  Behaviour of changing this option between SIGHUP might not be well behaving.
+  If you need to change/add/remove this option, fully restart OpenVPN.
+
 --remap-usr1 signal
   Control whether internally or externally generated :code:`SIGUSR1` signals
   are remapped to :code:`SIGHUP` (restart without persisting state) or
src/openvpn/crypto_backend.h +15 -0
index 5aab3e1b7..c16837619 100644
@@ -78,6 +78,21 @@ void crypto_clear_error(void);
  */
 void crypto_init_lib_engine(const char *engine_name);
 
+
+/**
+ * Load the given (OpenSSL) providers
+ * @param provider name of providers to load
+ * @return reference to the loaded provider
+ */
+provider_t *crypto_load_provider(const char *provider);
+
+/**
+ * Unloads the given (OpenSSL) provider
+ * @param provname  name of the provider to unload
+ * @param provider  pointer to the provider to unload
+ */
+void crypto_unload_provider(const char* provname, provider_t *provider);
+
 #ifdef DMALLOC
 /*
  * OpenSSL memory debugging.  If dmalloc debugging is enabled, tell
src/openvpn/crypto_mbedtls.c +13 -0
index 08b9e004f..39dbf38a5 100644
@@ -69,6 +69,19 @@ crypto_init_lib_engine(const char *engine_name)
         "available");
 }
 
+provider_t *crypto_load_provider(const char *provider)
+{
+    if (provider)
+    {
+        msg(M_WARN, "Note: mbed TLS provider functionality is not available");
+    }
+    return NULL;
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{
+}
+
 /*
  *
  * Functions related to the core crypto library
src/openvpn/crypto_mbedtls.h +3 -0
index 019de01d1..758ab1b40 100644
@@ -48,6 +48,9 @@ typedef mbedtls_md_context_t md_ctx_t;
 /** Generic HMAC %context. */
 typedef mbedtls_md_context_t hmac_ctx_t;
 
+/* Use a dummy type for the provider */
+typedef void provider_t;
+
 /** Maximum length of an IV */
 #define OPENVPN_MAX_IV_LENGTH   MBEDTLS_MAX_IV_LENGTH
 
src/openvpn/crypto_openssl.c +30 -0
index cc1d62210..c9731adb3 100644
@@ -54,6 +54,9 @@
 #if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
 #include <openssl/kdf.h>
 #endif
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
 
 #if defined(_WIN32) && defined(OPENSSL_NO_EC)
 #error Windows build with OPENSSL_NO_EC: disabling EC key is not supported.
@@ -149,6 +152,33 @@ crypto_init_lib_engine(const char *engine_name)
 #endif
 }
 
+provider_t *
+crypto_load_provider(const char *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    /* Load providers into the default (NULL) library context */
+    OSSL_PROVIDER* prov = OSSL_PROVIDER_load(NULL, provider);
+    if (!prov)
+    {
+        crypto_msg(M_FATAL, "failed to load provider '%s'", provider);
+    }
+    return prov;
+#else  /* OPENSSL_VERSION_NUMBER >= 0x30000000L */
+    msg(M_WARN, "Note: OpenSSL provider functionality is not available");
+    return NULL;
+#endif
+}
+
+void crypto_unload_provider(const char* provname, provider_t *provider)
+{
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+    if (!OSSL_PROVIDER_unload(provider))
+    {
+        crypto_msg(M_FATAL, "failed to unload provider '%s'", provname);
+    }
+#endif
+}
+
 /*
  *
  * Functions related to the core crypto library
src/openvpn/crypto_openssl.h +9 -0
index e540a76b9..446f08508 100644
@@ -33,6 +33,10 @@
 #include <openssl/hmac.h>
 #include <openssl/md5.h>
 #include <openssl/sha.h>
+#if OPENSSL_VERSION_NUMBER >= 0x30000000L
+#include <openssl/provider.h>
+#endif
+
 
 /** Generic cipher key type %context. */
 typedef EVP_CIPHER cipher_kt_t;
@@ -49,12 +53,17 @@ typedef EVP_MD_CTX md_ctx_t;
 /** Generic HMAC %context. */
 #if OPENSSL_VERSION_NUMBER < 0x30000000L
 typedef HMAC_CTX hmac_ctx_t;
+
+/* Use a dummy type for the provider */
+typedef void provider_t;
 #else
 typedef struct {
     OSSL_PARAM params[3];
     uint8_t key[EVP_MAX_KEY_LENGTH];
     EVP_MAC_CTX *ctx;
 } hmac_ctx_t;
+
+typedef OSSL_PROVIDER provider_t;
 #endif
 
 /** Maximum length of an IV */
src/openvpn/openvpn.c +13 -0
index da06f59c2..a18a4dd43 100644
@@ -112,10 +112,23 @@ void init_early(struct context *c)
     /* init verbosity and mute levels */
     init_verb_mute(c, IVM_LEVEL_1);
 
+    /* Initialise OpenSSL provider, this needs to be initialised this
+    * early since option post-processing and also openssl info
+    * printing depends on it */
+    for (int j=1; j < MAX_PARMS && c->options.providers.names[j]; j++)
+    {
+        c->options.providers.providers[j] =
+            crypto_load_provider(c->options.providers.names[j]);
+    }
 }
 
 static void uninit_early(struct context *c)
 {
+    for (int j=1; j < MAX_PARMS && c->options.providers.providers[j]; j++)
+    {
+        crypto_unload_provider(c->options.providers.names[j],
+                               c->options.providers.providers[j]);
+    }
     net_ctx_free(&c->net_ctx);
 }
 
src/openvpn/options.c +8 -0
index b5d65d293..310e169aa 100644
@@ -581,6 +581,7 @@ static const char usage_message[] =
     "                : Use --show-tls to see a list of supported TLS ciphers (suites).\n"
     "--tls-cert-profile p : Set the allowed certificate crypto algorithm profile\n"
     "                  (default=legacy).\n"
+    "--providers l   : A list l of OpenSSL providers to load.\n"
     "--tls-timeout n : Packet retransmit timeout on TLS control channel\n"
     "                  if no ACK from remote within n seconds (default=%d).\n"
     "--reneg-bytes n : Renegotiate data chan. key after n bytes sent and recvd.\n"
@@ -8158,6 +8159,13 @@ add_option(struct options *options,
         }
     }
 #endif /* ENABLE_CRYPTO_MBEDTLS */
+    else if (streq(p[0], "providers") && p[1])
+    {
+        for (size_t j = 1; j < MAX_PARMS && p[j] != NULL;j++)
+        {
+            options->providers.names[j] = p[j];
+        }
+    }
 #ifdef ENABLE_PREDICTION_RESISTANCE
     else if (streq(p[0], "use-prediction-resistance") && !p[1])
     {
src/openvpn/options.h +9 -0
index 20b34ed4e..d4f41cd71 100644
@@ -179,6 +179,14 @@ struct remote_list
     struct remote_entry *array[CONNECTION_LIST_SIZE];
 };
 
+struct provider_list
+{
+    /* Names of the providers */
+    const char *names[MAX_PARMS];
+    /* Pointers to the loaded providers to unload them */
+    provider_t *providers[MAX_PARMS];
+};
+
 enum vlan_acceptable_frames
 {
     VLAN_ONLY_TAGGED,
@@ -519,6 +527,7 @@ struct options
     const char *ncp_ciphers;
     const char *authname;
     const char *engine;
+    struct provider_list providers;
     bool replay;
     bool mute_replay_warnings;
     int replay_window;
Signature · 1 line
2.33.0
Acked-by on v6 1/1
#49 lore raw

[Openvpn-devel] [PATCH applied] Re: Allow loading of non default providers

I tool Selva's patch, and added my own for the change v5->v6 (which is really just moving the #ifdef to the other side of the block, so the options.c code is always compiled in).

Tested on 1.1 ("unsurprisingly, no change") and 3.0 builds ("my test cases against 2.3 servers with BF-CBC are working again").

Code change also looks reasonable. In it goes!

A few minor whitespace fixes ("type* var" vs. "type *var").

Your patch has been applied to the master branch.

commit 8a636779d9a28dc8040448483dc4a8af05d5c37f

Author: Arne Schwabe
Date:   Fri Nov 12 14:02:31 2021 +0100
     Allow loading of non default providers

     Signed-off-by: Arne Schwabe <[email protected]...>
     Acked-by: Selva Nair <[email protected]...>
     Acked-by: Gert Doering <[email protected]...>
     Message-Id: <[email protected]...>
     URL: https://www.mail-archive.com/search?l=mid&[email protected]...
     Signed-off-by: Gert Doering <[email protected]...>

--
kind regards,

Gert Doering

#39 lore raw

Re: [Openvpn-devel] [PATCH applied] Re: Use TYPE_do_all_provided function for listing cipher/digest

In reply to Gert Doering

Hi,

Quoted 8 lines · Gert Doering

This is "v3 with the SIZE() change", and this change looks good. Max has already stated "looks good and works", but wanted the sizeof() change which is now in - so taking his pre-review, adding my own testing (makes the "cipher" part of "make check" finally succeed with 3.0, yay :-) )

Quoted 5 lines

The "load providers" part is not in, so I couldn't test

  openvpn --provider legacy:default --show-ciphers

yet... will come back.

As promised, I'm back. "It works".

For giggles, look at "openvpn --providers legacy --show-cipher"... (on a 3.0 build, of course) :-)

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]...