2 * OpenVPN -- An application to securely tunnel IP networks
3 * over a single TCP/UDP port, with support for SSL/TLS-based
4 * session authentication and key exchange,
5 * packet encryption, packet authentication, and
8 * Copyright (C) 2002-2025 OpenVPN Inc <sales@openvpn.net>
9 * Copyright (C) 2010-2021 Fox Crypto B.V. <openvpn@foxcrypto.com>
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License version 2
13 * as published by the Free Software Foundation.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
27 * Control Channel Common Data Structures
33 #include "session_id.h"
35 #include "packet_id.h"
39 #include "ssl_backend.h"
42 #define UP_TYPE_AUTH "Auth"
43 #define UP_TYPE_PRIVATE_KEY "Private Key"
45 /** @addtogroup control_processor
48 * @name Control channel negotiation states
50 * These states represent the different phases of control channel
51 * negotiation between OpenVPN peers. OpenVPN servers and clients
52 * progress through the states in a different order, because of their
53 * different roles during exchange of random material. The references to
54 * the \c key_source2 structure in the list below is only valid if %key
55 * method 2 is being used. See the \link key_generation data channel key
56 * generation\endlink related page for more information.
58 * Clients follow this order:
59 * -# \c S_INITIAL, ready to begin three-way handshake and control
60 * channel negotiation.
61 * -# \c S_PRE_START, have started three-way handshake, waiting for
62 * acknowledgment from remote.
63 * -# \c S_START, initial three-way handshake complete.
64 * -# \c S_SENT_KEY, have sent local part of \c key_source2 random
66 * -# \c S_GOT_KEY, have received remote part of \c key_source2 random
68 * -# \c S_ACTIVE, control channel successfully established
69 * -# \c S_GENERATED_KEYS, the data channel keys have been generated
71 * Servers follow the same order, except for \c S_SENT_KEY and \c
72 * S_GOT_KEY being reversed, because the server first receives the
73 * client's \c key_source2 random material before generating and sending
78 #define S_ERROR (-2) /**< Error state. */
79 #define S_ERROR_PRE (-1) /**< Error state but try to send out alerts
80 * before killing the keystore and moving
82 #define S_UNDEF 0 /**< Undefined state, used after a \c
83 * key_state is cleaned up. */
84 #define S_INITIAL 1 /**< Initial \c key_state state after
85 * initialization by \c key_state_init()
86 * before start of three-way handshake. */
87 #define S_PRE_START_SKIP 2 /**< Waiting for the remote OpenVPN peer
88 * to acknowledge during the initial
89 * three-way handshake. */
90 #define S_PRE_START 3 /**< Waiting for the remote OpenVPN peer
91 * to acknowledge during the initial
92 * three-way handshake. */
93 #define S_START 4 /**< Three-way handshake is complete,
94 * start of key exchange. */
95 #define S_SENT_KEY 5 /**< Local OpenVPN process has sent its
96 * part of the key material. */
97 #define S_GOT_KEY 6 /**< Local OpenVPN process has received
98 * the remote's part of the key
100 #define S_ACTIVE 7 /**< Operational \c key_state state
101 * immediately after negotiation has
102 * completed while still within the
103 * handshake window. Deferred auth and
104 * client connect can still be pending. */
105 #define S_GENERATED_KEYS 8 /**< The data channel keys have been generated
106 * The TLS session is fully authenticated
107 * when reaching this state. */
109 /* Note that earlier versions also had a S_OP_NORMAL state that was
110 * virtually identical with S_ACTIVE and the code still assumes everything
111 * >= S_ACTIVE to be fully operational */
112 /** @} name Control channel negotiation states */
113 /** @} addtogroup control_processor */
116 * Container for one half of random material to be used in %key method 2
117 * \ref key_generation "data channel key generation".
118 * @ingroup control_processor
121 uint8_t pre_master
[48]; /**< Random used for master secret
122 * generation, provided only by client
124 uint8_t random1
[32]; /**< Seed used for master secret
125 * generation, provided by both client
127 uint8_t random2
[32]; /**< Seed used for key expansion, provided
128 * by both client and server. */
133 * Container for both halves of random material to be used in %key method
134 * 2 \ref key_generation "data channel key generation".
135 * @ingroup control_processor
138 struct key_source client
; /**< Random provided by client. */
139 struct key_source server
; /**< Random provided by server. */
144 * This reflects the (server side) authentication state after the TLS
145 * session has been established and key_method_2_read is called. If async auth
146 * is enabled the state will first move to KS_AUTH_DEFERRED before eventually
147 * being set to KS_AUTH_TRUE or KS_AUTH_FALSE
148 * Only KS_AUTH_TRUE is fully authenticated
151 KS_AUTH_FALSE
, /**< Key state is not authenticated */
152 KS_AUTH_DEFERRED
, /**< Key state authentication is being deferred,
154 KS_AUTH_TRUE
/**< Key state is authenticated. TLS and user/pass
155 * succeeded. This includes AUTH_PENDING/OOB
156 * authentication as those hold the
157 * connection artificially in KS_AUTH_DEFERRED
161 struct auth_deferred_status
163 char *auth_control_file
;
164 char *auth_pending_file
;
165 char *auth_failed_reason_file
;
166 unsigned int auth_control_status
;
169 /* key_state_test_auth_control_file return values, these specify the
170 * current status of a deferred authentication */
171 enum auth_deferred_result
{
172 ACF_PENDING
, /**< deferred auth still pending */
173 ACF_SUCCEEDED
, /**< deferred auth has suceeded */
174 ACF_DISABLED
, /**< deferred auth is not used */
175 ACF_FAILED
/**< deferred auth has failed */
178 enum dco_key_status
{
180 DCO_INSTALLED_PRIMARY
,
181 DCO_INSTALLED_SECONDARY
185 * Security parameter state of one TLS and data channel %key session.
186 * @ingroup control_processor
188 * This structure represents one security parameter session between
189 * OpenVPN peers. It includes the control channel TLS state and the data
190 * channel crypto state. It also contains the reliability layer
191 * structures used for control channel messages.
193 * A new \c key_state structure is initialized for each hard or soft
197 * - This structure should be initialized using the \c key_state_init()
199 * - This structure should be cleaned up using the \c key_state_free()
205 /** The state of the auth-token sent from the client */
206 unsigned int auth_token_state_flags
;
209 * Key id for this key_state, inherited from struct tls_session.
210 * @see tls_session::key_id.
215 * Key id for this key_state, inherited from struct tls_session.
216 * @see tls_multi::peer_id.
220 struct key_state_ssl ks_ssl
; /* contains SSL object and BIOs for the control channel */
222 time_t initial
; /* when we created this session */
223 time_t established
; /* when our state went S_ACTIVE */
224 time_t must_negotiate
; /* key negotiation times out if not finished before this time */
225 time_t must_die
; /* this object is destroyed at this time */
226 time_t peer_last_packet
; /* Last time we received a packet in this control session */
228 int initial_opcode
; /* our initial P_ opcode */
229 struct session_id session_id_remote
; /* peer's random session ID */
230 struct link_socket_actual remote_addr
; /* peer's IP addr */
232 struct crypto_options crypto_options
;/* data channel crypto options */
234 struct key_source2
*key_src
; /* source entropy for key expansion */
236 struct buffer plaintext_read_buf
;
237 struct buffer plaintext_write_buf
;
238 struct buffer ack_write_buf
;
240 struct reliable
*send_reliable
; /* holds a copy of outgoing packets until ACK received */
241 struct reliable
*rec_reliable
; /* order incoming ciphertext packets before we pass to TLS */
242 struct reliable_ack
*rec_ack
; /* buffers all packet IDs we want to ACK back to sender */
243 struct reliable_ack
*lru_acks
; /* keeps the most recently acked packages*/
245 /** Holds outgoing message for the control channel until ks->state reaches
247 struct buffer_list
*paybuf
;
248 counter_type n_bytes
; /* how many bytes sent/recvd since last key exchange */
249 counter_type n_packets
; /* how many packets sent/recvd since last key exchange */
252 * If bad username/password, TLS connection will come up but 'authenticated' will be false.
254 enum ks_auth_state authenticated
;
255 time_t auth_deferred_expire
;
257 #ifdef ENABLE_MANAGEMENT
258 unsigned int mda_key_id
;
259 enum auth_deferred_result mda_status
;
263 struct auth_deferred_status plugin_auth
;
264 struct auth_deferred_status script_auth
;
266 enum dco_key_status dco_status
;
269 /** Control channel wrapping (--tls-auth/--tls-crypt) context */
273 TLS_WRAP_NONE
= 0, /**< No control channel wrapping */
274 TLS_WRAP_AUTH
, /**< Control channel authentication */
275 TLS_WRAP_CRYPT
, /**< Control channel encryption and authentication */
276 } mode
; /**< Control channel wrapping mode */
277 struct crypto_options opt
; /**< Crypto state */
278 struct buffer work
; /**< Work buffer (only for --tls-crypt) */
279 struct key_ctx tls_crypt_v2_server_key
; /**< Decrypts client keys */
280 const struct buffer
*tls_crypt_v2_wkc
; /**< Wrapped client key,
282 struct buffer tls_crypt_v2_metadata
; /**< Received from client */
283 bool cleanup_key_ctx
; /**< opt.key_ctx_bi is owned by
285 /** original key data to be xored in to the key for dynamic tls-crypt.
287 * We keep the original key data to ensure that the newly generated key
288 * for the dynamic tls-crypt has the same level of quality by using
289 * xor with the original key. This gives us the same same entropy/randomness
290 * as the original tls-crypt key to ensure the post-quantum use case of
291 * tls-crypt still holds true
293 struct key2 original_wrap_keydata
;
297 * Our const options, obtained directly or derived from
298 * command line options.
302 /* our master TLS context from which all SSL objects derived */
303 struct tls_root_ctx ssl_ctx
;
305 /* data channel cipher, hmac, and key lengths */
306 struct key_type key_type
;
308 /* true if we are a TLS server, client otherwise */
311 /* if true, don't xmit until first packet from peer is received */
314 /* local and remote options strings
315 * that must match between client and server */
316 const char *local_options
;
317 const char *remote_options
;
319 /* from command line */
324 * The detail of info we push in peer info
326 * 0 - nothing at all, P2MP server only
327 * 1 - only the most basic information to negotiate cipher and features
329 * 2 - normal setting for clients
330 * 3 - full information including "sensitive data" like IV_HWADDR
331 * enabled by --push-peer-info
333 int push_peer_info_detail
;
334 int transition_window
;
335 int handshake_window
;
336 interval_t packet_timeout
;
337 int64_t renegotiate_bytes
;
338 int64_t renegotiate_packets
;
339 /** limit for AEAD cipher when not running in epoch data key mode,
340 * this is the sum of packets + blocks that are allowed to be used */
341 uint64_t aead_usage_limit
;
342 interval_t renegotiate_seconds
;
344 /* cert verification parms */
345 const char *verify_command
;
346 int verify_x509_type
;
347 const char *verify_x509_name
;
348 const char *crl_file
;
349 bool crl_file_inline
;
351 unsigned remote_cert_ku
[MAX_PARMS
];
352 const char *remote_cert_eku
;
353 struct verify_hash_list
*verify_hash
;
354 int verify_hash_depth
;
355 bool verify_hash_no_ca
;
356 hash_algo_type verify_hash_algo
;
357 #ifdef ENABLE_X509ALTUSERNAME
358 char *x509_username_field
[MAX_PARMS
];
360 char *x509_username_field
[2];
363 /* struct crypto_option flags */
364 unsigned int crypto_flags
;
366 int replay_window
; /* --replay-window parm */
367 int replay_time
; /* --replay-window parm */
369 const char *config_ciphername
;
370 const char *config_ncp_ciphers
;
372 /** whether our underlying data channel supports new data channel
373 * features (epoch keys with AEAD tag at the end). This is always true
374 * for the internal implementation but can be false for DCO
376 bool data_epoch_supported
;
379 const char *tls_crypt_v2_verify_script
;
381 /** TLS handshake wrapping state */
382 struct tls_wrap_ctx tls_wrap
;
386 /* used for username/password authentication */
387 const char *auth_user_pass_verify_script
;
388 const char *client_crresponse_script
;
389 bool auth_user_pass_verify_script_via_file
;
391 const char *export_peer_cert_dir
;
392 const char *auth_user_pass_file
;
393 bool auth_user_pass_file_inline
;
395 bool auth_token_generate
; /**< Generate auth-tokens on successful
396 * user/pass auth,seet via
397 * options->auth_token_generate. */
398 bool auth_token_call_auth
; /**< always call normal authentication */
399 unsigned int auth_token_lifetime
;
400 unsigned int auth_token_renewal
;
402 struct key_ctx auth_token_key
;
404 /* use the client-config-dir as a positive authenticator */
405 const char *client_config_dir_exclusive
;
407 /* instance-wide environment variable set */
409 openvpn_net_ctx_t
*net_ctx
;
410 const struct plugin_list
*plugins
;
412 /* compression parms */
414 struct compress_options comp_options
;
417 /* configuration file SSL-related boolean and low-permutation options */
418 #define SSLF_CLIENT_CERT_NOT_REQUIRED (1<<0)
419 #define SSLF_CLIENT_CERT_OPTIONAL (1<<1)
420 #define SSLF_USERNAME_AS_COMMON_NAME (1<<2)
421 #define SSLF_AUTH_USER_PASS_OPTIONAL (1<<3)
422 #define SSLF_OPT_VERIFY (1<<4)
423 #define SSLF_CRL_VERIFY_DIR (1<<5)
424 #define SSLF_TLS_VERSION_MIN_SHIFT 6
425 #define SSLF_TLS_VERSION_MIN_MASK 0xF /* (uses bit positions 6 to 9) */
426 #define SSLF_TLS_VERSION_MAX_SHIFT 10
427 #define SSLF_TLS_VERSION_MAX_MASK 0xF /* (uses bit positions 10 to 13) */
428 #define SSLF_TLS_DEBUG_ENABLED (1<<14)
429 unsigned int ssl_flags
;
431 #ifdef ENABLE_MANAGEMENT
432 struct man_def_auth_context
*mda_context
;
435 const struct x509_track
*x509_track
;
437 #ifdef ENABLE_MANAGEMENT
438 const struct static_challenge_info
*sci
;
444 /* Keying Material Exporter [RFC 5705] parameters */
445 const char *ekm_label
;
446 size_t ekm_label_size
;
449 bool dco_enabled
; /**< Whether keys have to be installed in DCO or not */
452 /** @addtogroup control_processor
454 /** @name Index of key_state objects within a tls_session structure
456 * This is the index of \c tls_session.key
459 #define KS_PRIMARY 0 /**< Primary %key state index. */
460 #define KS_LAME_DUCK 1 /**< %Key state index that will retire
462 #define KS_SIZE 2 /**< Size of the \c tls_session.key array. */
463 /** @} name Index of key_state objects within a tls_session structure */
464 /** @} addtogroup control_processor */
467 * Security parameter state of a single session within a VPN tunnel.
468 * @ingroup control_processor
470 * This structure represents an OpenVPN peer-to-peer control channel
473 * A \c tls_session remains over soft resets, but a new instance is
474 * initialized for each hard reset.
477 * - This structure should be initialized using the \c tls_session_init()
479 * - This structure should be cleaned up using the \c tls_session_free()
484 /* const options and config info */
485 struct tls_options
*opt
;
487 /* during hard reset used to control burst retransmit */
490 /* authenticate control packets */
491 struct tls_wrap_ctx tls_wrap
;
493 /* Specific tls-crypt for renegotiations, if this is valid,
494 * tls_wrap_reneg.mode is TLS_WRAP_CRYPT, otherwise ignore it */
495 struct tls_wrap_ctx tls_wrap_reneg
;
497 int initial_opcode
; /* our initial P_ opcode */
498 struct session_id session_id
; /* our random session ID */
501 * The current active key id, used to keep track of renegotiations.
502 * key_id increments with each soft reset to KEY_ID_MASK then recycles back
503 * to 1. This way you know that if key_id is 0, it is the first key.
511 struct cert_hash_set
*cert_hash_set
;
513 bool verified
; /* true if peer certificate was verified against CA */
515 /* not-yet-authenticated incoming client */
516 struct link_socket_actual untrusted_addr
;
518 struct key_state key
[KS_SIZE
];
521 /** @addtogroup control_processor
523 /** @name Index of tls_session objects within a tls_multi structure
525 * This is the index of \c tls_multi.session
527 * Normally three tls_session objects are maintained by an active openvpn
528 * session. The first is the current, TLS authenticated session, the
529 * second is used to process connection requests from a new client that
530 * would usurp the current session if successfully authenticated, and the
531 * third is used as a repository for a "lame-duck" %key in the event that
532 * the primary session resets due to error while the lame-duck %key still
533 * has time left before its expiration. Lame duck keys are used to
534 * maintain the continuity of the data channel connection while a new %key
535 * is being negotiated.
538 #define TM_ACTIVE 0 /**< Active \c tls_session. */
539 #define TM_INITIAL 1 /**< As yet un-trusted \c tls_session
540 * being negotiated. */
541 #define TM_LAME_DUCK 2 /**< Old \c tls_session. */
542 #define TM_SIZE 3 /**< Size of the \c tls_multi.session
544 /** @} name Index of tls_session objects within a tls_multi structure */
545 /** @} addtogroup control_processor */
549 * The number of keys we will scan on encrypt or decrypt. The first
550 * is the "active" key. The second is the lame_duck or retiring key
551 * associated with the active key's session ID. The third is a detached
552 * lame duck session that only occurs in situations where a key renegotiate
553 * failed on the active key, but a lame duck key was still valid. By
554 * preserving the lame duck session, we can be assured of having a data
555 * channel key available even when network conditions are so bad that
556 * we can't negotiate a new key within the time allotted.
558 #define KEY_SCAN_SIZE 3
561 /* multi state (originally client authentication state (=CAS))
562 * CAS_NOT_CONNECTED must be 0 since non multi code paths still check
563 * this variable but do not explicitly initialise it and depend
564 * on zero initialisation */
566 /* CAS_NOT_CONNECTED is the initial state for every context. When the *first*
567 * tls_session reaches S_ACTIVE, this state machine moves to CAS_PENDING (server)
568 * or CAS_CONNECT_DONE (client/p2p) as clients skip the stages associated with
569 * connect scripts/plugins */
573 CAS_WAITING_AUTH
, /**< Initial TLS connection established but deferred auth is not yet finished
575 CAS_PENDING
, /**< Options import (Connect script/plugin, ccd,...) */
576 CAS_PENDING_DEFERRED
, /**< Waiting on an async option import handler */
577 CAS_PENDING_DEFERRED_PARTIAL
, /**< at least handler succeeded but another is still pending */
578 CAS_FAILED
, /**< Option import failed or explicitly denied the client */
579 CAS_WAITING_OPTIONS_IMPORT
, /**< client with pull or p2p waiting for first time options import
581 /** session has already successful established (CAS_CONNECT_DONE) but has a
582 * reconnect and needs to redo some initialisation, this state is similar
583 * CAS_WAITING_OPTIONS_IMPORT but skips a few things. The normal connection
584 * skips this step. */
585 CAS_RECONNECT_PENDING
,
591 * Security parameter state for a single VPN tunnel.
592 * @ingroup control_processor
594 * An active VPN tunnel running with TLS enabled has one \c tls_multi
595 * object, in which it stores all control channel and data channel
596 * security parameter state. This structure can contain multiple,
597 * possibly simultaneously active, \c tls_context objects to allow for
598 * interruption-less transitions during session renegotiations. Each \c
599 * tls_context represents one control channel session, which can span
600 * multiple data channel security parameter sessions stored in \c
601 * key_state structures.
605 /* used to coordinate access between main thread and TLS thread */
606 /*MUTEX_PTR_DEFINE (mutex);*/
608 /* const options and config info */
609 struct tls_options opt
;
612 * used by tls_pre_encrypt to communicate the encrypt key
613 * to tls_post_encrypt()
615 struct key_state
*save_ks
; /* temporary pointer used between pre/post routines */
618 * Used to return outgoing address from
621 struct link_socket_actual to_link_addr
;
623 int n_sessions
; /**< Number of sessions negotiated thus
625 enum multi_status multi_state
;
630 int n_hard_errors
; /* errors due to TLS negotiation failure */
631 int n_soft_errors
; /* errors due to unrecognized or failed-to-authenticate incoming packets */
634 * Our locked common name, username, and cert hashes
635 * (cannot change during the life of this tls_multi object)
639 /** The locked username is the username we assume the client is using.
640 * Normally the username used for initial authentication unless
641 * overridden by --override-username */
642 char *locked_username
;
644 /** The username that client initially used before being overridden
645 * by --override-user */
646 char *locked_original_username
;
648 struct cert_hash_set
*locked_cert_hash_set
;
651 * Time of last when we updated the cached state of
652 * tls_authentication_status deferred files */
653 time_t tas_cache_last_update
;
655 /** The number of times we updated the cache */
656 unsigned int tas_cache_num_updates
;
658 /** An error message to send to client on AUTH_FAILED */
662 * A multi-line string of general-purpose info received from peer
663 * over control channel.
667 * If server sends a generated auth-token,
668 * this is the token to use for future
669 * user/pass authentications in this session.
673 * The first auth-token we sent to a client. We use this to remember
674 * the session ID and initial timestamp when generating new auth-token.
676 char *auth_token_initial
;
678 /** Auth-token sent from client has valid hmac */
679 #define AUTH_TOKEN_HMAC_OK (1 << 0)
680 /** Auth-token sent from client has expired */
681 #define AUTH_TOKEN_EXPIRED (1 << 1)
683 * Auth-token is only valid for an empty username
684 * and not the username actually supplied from the client
686 * OpenVPN 3 clients sometimes wipes or replaces the username with a
687 * username hint from their config.
689 #define AUTH_TOKEN_VALID_EMPTYUSER (1 << 2)
695 char *remote_ciphername
; /**< cipher specified in peer's config file */
696 bool remote_usescomp
; /**< remote announced comp-lzo in OCC string */
699 * Our session objects.
701 /** Array of \c tls_session objects
702 * representing control channel
703 * sessions with the remote peer. */
704 struct tls_session session
[TM_SIZE
];
706 /* Only used when DCO is used to remember how many keys we installed
707 * for this session */
708 int dco_keys_installed
;
710 * This is the handle that DCO uses to identify this session with the
713 * We keep this separate as the normal peer_id can change during
714 * p2p NCP and we need to track the id that is really used.
721 /** gets an item of \c key_state objects in the
722 * order they should be scanned by data
723 * channel modules. */
724 static inline struct key_state
*
725 get_key_scan(struct tls_multi
*multi
, int index
)
730 return &multi
->session
[TM_ACTIVE
].key
[KS_PRIMARY
];
733 return &multi
->session
[TM_ACTIVE
].key
[KS_LAME_DUCK
];
736 return &multi
->session
[TM_LAME_DUCK
].key
[KS_LAME_DUCK
];
740 return NULL
; /* NOTREACHED */
744 /** gets an item of \c key_state objects in the
745 * order they should be scanned by data
746 * channel modules. */
747 static inline const struct key_state
*
748 get_primary_key(const struct tls_multi
*multi
)
750 return &multi
->session
[TM_ACTIVE
].key
[KS_PRIMARY
];
753 #endif /* SSL_COMMON_H_ */