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-2005 OpenVPN Solutions LLC <info@openvpn.net>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2
12 * as published by the Free Software Foundation.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program (see the file COPYING included with this
21 * distribution); if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 #if defined(USE_CRYPTO) && defined(USE_SSL)
30 #include <openssl/ssl.h>
31 #include <openssl/bio.h>
32 #include <openssl/rand.h>
33 #include <openssl/err.h>
34 #include <openssl/pkcs12.h>
35 #include <openssl/x509v3.h>
40 #include "packet_id.h"
41 #include "session_id.h"
50 * OpenVPN Protocol, taken from ssl.h in OpenVPN source code.
52 * TCP/UDP Packet: This represents the top-level encapsulation.
54 * TCP/UDP packet format:
56 * Packet length (16 bits, unsigned) -- TCP only, always sent as
57 * plaintext. Since TCP is a stream protocol, the packet
58 * length words define the packetization of the stream.
60 * Packet opcode/key_id (8 bits) -- TLS only, not used in
61 * pre-shared secret mode.
62 * packet message type, a P_* constant (high 5 bits)
63 * key_id (low 3 bits, see key_id in struct tls_session
64 * below for comment). The key_id refers to an
65 * already negotiated TLS session. OpenVPN seamlessly
66 * renegotiates the TLS session by using a new key_id
67 * for the new session. Overlap (controlled by
68 * user definable parameters) between old and new TLS
69 * sessions is allowed, providing a seamless transition
70 * during tunnel operation.
72 * Payload (n bytes), which may be a P_CONTROL, P_ACK, or P_DATA
77 * P_CONTROL_HARD_RESET_CLIENT_V1 -- Key method 1, initial key from
78 * client, forget previous state.
80 * P_CONTROL_HARD_RESET_SERVER_V1 -- Key method 2, initial key
81 * from server, forget previous state.
83 * P_CONTROL_SOFT_RESET_V1 -- New key, with a graceful transition
84 * from old to new key in the sense that a transition window
85 * exists where both the old or new key_id can be used. OpenVPN
86 * uses two different forms of key_id. The first form is 64 bits
87 * and is used for all P_CONTROL messages. P_DATA messages on the
88 * other hand use a shortened key_id of 3 bits for efficiency
89 * reasons since the vast majority of OpenVPN packets in an
90 * active tunnel will be P_DATA messages. The 64 bit form
91 * is referred to as a session_id, while the 3 bit form is
92 * referred to as a key_id.
94 * P_CONTROL_V1 -- Control channel packet (usually TLS ciphertext).
96 * P_ACK_V1 -- Acknowledgement for P_CONTROL packets received.
98 * P_DATA_V1 -- Data channel packet containing actual tunnel data
101 * P_CONTROL_HARD_RESET_CLIENT_V2 -- Key method 2, initial key from
102 * client, forget previous state.
104 * P_CONTROL_HARD_RESET_SERVER_V2 -- Key method 2, initial key from
105 * server, forget previous state.
107 * P_CONTROL* and P_ACK Payload: The P_CONTROL message type
108 * indicates a TLS ciphertext packet which has been encapsulated
109 * inside of a reliability layer. The reliability layer is
110 * implemented as a straightforward ACK and retransmit model.
112 * P_CONTROL message format:
114 * local session_id (random 64 bit value to identify TLS session).
115 * HMAC signature of entire encapsulation header for integrity
116 * check if --tls-auth is specified (usually 16 or 20 bytes).
117 * packet-id for replay protection (4 or 8 bytes, includes
118 * sequence number and optional time_t timestamp).
119 * P_ACK packet_id array length (1 byte).
120 * P_ACK packet-id array (if length > 0).
121 * P_ACK remote session_id (if length > 0).
122 * message packet-id (4 bytes).
123 * TLS payload ciphertext (n bytes) (only for P_CONTROL).
125 * Once the TLS session has been initialized and authenticated,
126 * the TLS channel is used to exchange random key material for
127 * bidirectional cipher and HMAC keys which will be
128 * used to secure actual tunnel packets. OpenVPN currently
129 * implements two key methods. Key method 1 directly
130 * derives keys using random bits obtained from the RAND_bytes
131 * OpenSSL function. Key method 2 mixes random key material
132 * from both sides of the connection using the TLS PRF mixing
133 * function. Key method 2 is the preferred method and is the default
136 * TLS plaintext content:
138 * TLS plaintext packet (if key_method == 1):
140 * Cipher key length in bytes (1 byte).
141 * Cipher key (n bytes).
142 * HMAC key length in bytes (1 byte).
143 * HMAC key (n bytes).
144 * Options string (n bytes, null terminated, client/server options
145 * string should match).
147 * TLS plaintext packet (if key_method == 2):
149 * Literal 0 (4 bytes).
150 * key_method type (1 byte).
151 * key_source structure (pre_master only defined for client ->
153 * options_string_length, including null (2 bytes).
154 * Options string (n bytes, null terminated, client/server options
155 * string must match).
156 * [The username/password data below is optional, record can end
158 * username_string_length, including null (2 bytes).
159 * Username string (n bytes, null terminated).
160 * password_string_length, including null (2 bytes).
161 * Password string (n bytes, null terminated).
163 * The P_DATA payload represents encrypted, encapsulated tunnel
164 * packets which tend to be either IP packets or Ethernet frames.
165 * This is essentially the "payload" of the VPN.
167 * P_DATA message content:
168 * HMAC of ciphertext IV + ciphertext (if not disabled by
170 * Ciphertext IV (size is cipher-dependent, if not disabled by
172 * Tunnel packet ciphertext.
175 * packet_id (4 or 8 bytes, if not disabled by --no-replay).
176 * In SSL/TLS mode, 4 bytes are used because the implementation
177 * can force a TLS renegotation before 2^32 packets are sent.
178 * In pre-shared key mode, 8 bytes are used (sequence number
179 * and time_t value) to allow long-term key usage without
180 * packet_id collisions.
181 * User plaintext (n bytes).
184 * (1) ACK messages can be encoded in either the dedicated
185 * P_ACK record or they can be prepended to a P_CONTROL message.
186 * (2) P_DATA and P_CONTROL/P_ACK use independent packet-id
187 * sequences because P_DATA is an unreliable channel while
188 * P_CONTROL/P_ACK is a reliable channel. Each use their
189 * own independent HMAC keys.
190 * (3) Note that when --tls-auth is used, all message types are
191 * protected with an HMAC signature, even the initial packets
192 * of the TLS handshake. This makes it easy for OpenVPN to
193 * throw away bogus packets quickly, without wasting resources
194 * on attempting a TLS handshake which will ultimately fail.
197 /* Used in the TLS PRF function */
198 #define KEY_EXPANSION_ID "OpenVPN"
201 #define UP_TYPE_AUTH "Auth"
202 #define UP_TYPE_PRIVATE_KEY "Private Key"
204 /* packet opcode (high 5 bits) and key-id (low 3 bits) are combined in one byte */
205 #define P_KEY_ID_MASK 0x07
206 #define P_OPCODE_SHIFT 3
208 /* packet opcodes -- the V1 is intended to allow protocol changes in the future */
209 #define P_CONTROL_HARD_RESET_CLIENT_V1 1 /* initial key from client, forget previous state */
210 #define P_CONTROL_HARD_RESET_SERVER_V1 2 /* initial key from server, forget previous state */
211 #define P_CONTROL_SOFT_RESET_V1 3 /* new key, graceful transition from old to new key */
212 #define P_CONTROL_V1 4 /* control channel packet (usually TLS ciphertext) */
213 #define P_ACK_V1 5 /* acknowledgement for packets received */
214 #define P_DATA_V1 6 /* data channel packet */
216 /* indicates key_method >= 2 */
217 #define P_CONTROL_HARD_RESET_CLIENT_V2 7 /* initial key from client, forget previous state */
218 #define P_CONTROL_HARD_RESET_SERVER_V2 8 /* initial key from server, forget previous state */
220 /* define the range of legal opcodes */
221 #define P_FIRST_OPCODE 1
222 #define P_LAST_OPCODE 8
224 /* key negotiation states */
227 #define S_INITIAL 1 /* tls_init() was called */
228 #define S_PRE_START 2 /* waiting for initial reset & acknowledgement */
229 #define S_START 3 /* ready to exchange keys */
230 #define S_SENT_KEY 4 /* client does S_SENT_KEY -> S_GOT_KEY */
231 #define S_GOT_KEY 5 /* server does S_GOT_KEY -> S_SENT_KEY */
232 #define S_ACTIVE 6 /* ready to exchange data channel packets */
233 #define S_NORMAL 7 /* normal operations */
236 * Are we ready to receive data channel packets?
238 * Also, if true, we can safely assume session has been
239 * authenticated by TLS.
241 * NOTE: Assumes S_SENT_KEY + 1 == S_GOT_KEY.
243 #define DECRYPT_KEY_ENABLED(multi, ks) ((ks)->state >= (S_GOT_KEY - (multi)->opt.server))
245 /* Should we aggregate TLS acknowledgements, and tack them onto control packets? */
246 #define TLS_AGGREGATE_ACK
249 * If TLS_AGGREGATE_ACK, set the
250 * max number of acknowledgments that
251 * can "hitch a ride" on an outgoing
252 * non-P_ACK_V1 control packet.
254 #define CONTROL_SEND_ACK_MAX 4
257 * Define number of buffers for send and receive in the reliability layer.
259 #define TLS_RELIABLE_N_SEND_BUFFERS 4 /* also window size for reliablity layer */
260 #define TLS_RELIABLE_N_REC_BUFFERS 8
266 #define TLS_MULTI_REFRESH 15 /* call tls_multi_process once every n seconds */
267 #define TLS_MULTI_HORIZON 2 /* call tls_multi_process frequently for n seconds after
268 every packet sent/received action */
270 /* The SSL/TLS worker thread will wait at most this many seconds for the interprocess
271 communication pipe to the main thread to be ready to accept writes. */
272 #define TLS_MULTI_THREAD_SEND_TIMEOUT 5
275 * Buffer sizes (also see mtu.h).
278 #define PLAINTEXT_BUFFER_SIZE TLS_CHANNEL_BUF_SIZE
280 /* Maximum length of common name */
281 #define TLS_CN_LEN 64
283 /* Legal characters in an X509 or common name */
284 #define X509_NAME_CHAR_CLASS (CC_ALNUM|CC_UNDERBAR|CC_DASH|CC_DOT|CC_AT|CC_COLON|CC_SLASH|CC_EQUAL)
285 #define COMMON_NAME_CHAR_CLASS (CC_ALNUM|CC_UNDERBAR|CC_DASH|CC_DOT|CC_AT)
287 /* Maximum length of OCC options string passed as part of auth handshake */
288 #define TLS_OPTIONS_LEN 512
291 * Range of key exchange methods
293 #define KEY_METHOD_MIN 1
294 #define KEY_METHOD_MAX 2
296 /* key method taken from lower 4 bits */
297 #define KEY_METHOD_MASK 0x0F
300 * Measure success rate of TLS handshakes, for debugging only
302 /* #define MEASURE_TLS_HANDSHAKE_STATS */
305 * Key material, used as source for PRF-based
310 uint8_t pre_master
[48]; /* client generated */
311 uint8_t random1
[32]; /* generated by both client and server */
312 uint8_t random2
[32]; /* generated by both client and server */
316 struct key_source client
;
317 struct key_source server
;
321 * Represents a single instantiation of a TLS negotiation and
322 * data channel key exchange. 4 keys are kept: encrypt hmac,
323 * decrypt hmac, encrypt cipher, and decrypt cipher. The TLS
324 * control channel is used to exchange these keys.
325 * Each hard or soft reset will build
326 * a fresh key_state. Normally an openvpn session will contain two
327 * key_state objects, one for the current TLS connection, and other
328 * for the retiring or "lame duck" key. The lame duck key_state is
329 * used to maintain transmission continuity on the data-channel while
330 * a key renegotiation is taking place.
335 int key_id
; /* inherited from struct tls_session below */
337 SSL
*ssl
; /* SSL object -- new obj created for each new key */
338 BIO
*ssl_bio
; /* read/write plaintext from here */
339 BIO
*ct_in
; /* write ciphertext to here */
340 BIO
*ct_out
; /* read ciphertext from here */
342 time_t established
; /* when our state went S_ACTIVE */
343 time_t must_negotiate
; /* key negotiation times out if not finished before this time */
344 time_t must_die
; /* this object is destroyed at this time */
346 int initial_opcode
; /* our initial P_ opcode */
347 struct session_id session_id_remote
; /* peer's random session ID */
348 struct sockaddr_in remote_addr
; /* peer's IP addr */
349 struct packet_id packet_id
; /* for data channel, to prevent replay attacks */
351 struct key_ctx_bi key
; /* data channel keys for encrypt/decrypt/hmac */
353 struct key_source2
*key_src
; /* source entropy for key expansion */
355 struct buffer plaintext_read_buf
;
356 struct buffer plaintext_write_buf
;
357 struct buffer ack_write_buf
;
359 struct reliable
*send_reliable
; /* holds a copy of outgoing packets until ACK received */
360 struct reliable
*rec_reliable
; /* order incoming ciphertext packets before we pass to TLS */
361 struct reliable_ack
*rec_ack
; /* buffers all packet IDs we want to ACK back to sender */
363 int n_bytes
; /* how many bytes sent/recvd since last key exchange */
364 int n_packets
; /* how many packets sent/recvd since last key exchange */
367 * If bad username/password, TLS connection will come up but 'authenticated' will be false.
373 * Our const options, obtained directly or derived from
374 * command line options.
378 /* our master SSL_CTX from which all SSL objects derived */
381 /* data channel cipher, hmac, and key lengths */
382 struct key_type key_type
;
384 /* true if we are a TLS server, client otherwise */
388 /* local and remote options strings
389 that must match between client and server */
390 const char *local_options
;
391 const char *remote_options
;
394 /* from command line */
401 int transition_window
;
402 int handshake_window
;
403 interval_t packet_timeout
;
404 int renegotiate_bytes
;
405 int renegotiate_packets
;
406 interval_t renegotiate_seconds
;
408 /* cert verification parms */
409 const char *verify_command
;
410 const char *verify_x509name
;
411 const char *crl_file
;
414 /* allow openvpn config info to be
415 passed over control channel */
416 bool pass_config_info
;
418 /* struct crypto_option flags */
419 unsigned int crypto_flags_and
;
420 unsigned int crypto_flags_or
;
422 int replay_window
; /* --replay-window parm */
423 int replay_time
; /* --replay-window parm */
425 /* packet authentication for TLS handshake */
426 struct crypto_options tls_auth
;
427 struct key_ctx_bi tls_auth_key
;
429 /* frame parameters for TLS control channel */
432 /* used for username/password authentication */
433 const char *auth_user_pass_verify_script
;
434 bool auth_user_pass_verify_script_via_file
;
436 bool username_as_common_name
;
438 /* use the client-config-dir as a positive authenticator */
439 const char *client_config_dir_exclusive
;
441 /* instance-wide environment variable set */
443 const struct plugin_list
*plugins
;
449 /* index into tls_session.key */
450 #define KS_PRIMARY 0 /* the primary key */
451 #define KS_LAME_DUCK 1 /* the key that's going to retire soon */
455 * A tls_session lives through multiple key_state life-cycles. Soft resets
456 * will reuse a tls_session object, but hard resets or errors will require
457 * that a fresh object be built. Normally three tls_session objects are maintained
458 * by an active openvpn session. The first is the current, TLS authenticated
459 * session, the second is used to process connection requests from a new
460 * client that would usurp the current session if successfully authenticated,
461 * and the third is used as a repository for a "lame-duck" key in the event
462 * that the primary session resets due to error while the lame-duck key still
463 * has time left before its expiration. Lame duck keys are used to maintain
464 * the continuity of the data channel connection while a new key is being
469 /* const options and config info */
470 const struct tls_options
*opt
;
472 /* during hard reset used to control burst retransmit */
475 /* authenticate control packets */
476 struct crypto_options tls_auth
;
477 struct packet_id tls_auth_pid
;
479 int initial_opcode
; /* our initial P_ opcode */
480 struct session_id session_id
; /* our random session ID */
481 int key_id
; /* increments with each soft reset (for key renegotiation) */
483 int limit_next
; /* used for traffic shaping on the control channel */
488 bool verified
; /* true if peer certificate was verified against CA */
490 /* not-yet-authenticated incoming client */
491 struct sockaddr_in untrusted_sockaddr
;
493 struct key_state key
[KS_SIZE
];
496 /* index into tls_multi.session */
498 #define TM_UNTRUSTED 1
499 #define TM_LAME_DUCK 2
503 * The number of keys we will scan on encrypt or decrypt. The first
504 * is the "active" key. The second is the lame_duck or retiring key
505 * associated with the active key's session ID. The third is a detached
506 * lame duck session that only occurs in situations where a key renegotiate
507 * failed on the active key, but a lame duck key was still valid. By
508 * preserving the lame duck session, we can be assured of having a data
509 * channel key available even when network conditions are so bad that
510 * we can't negotiate a new key within the time allotted.
512 #define KEY_SCAN_SIZE 3
515 * An openvpn session running with TLS enabled has one tls_multi object.
519 /* used to coordinate access between main thread and TLS thread */
520 /*MUTEX_PTR_DEFINE (mutex);*/
522 /* const options and config info */
523 struct tls_options opt
;
526 * A list of key_state objects in the order they should be
527 * scanned by data channel encrypt and decrypt routines.
529 struct key_state
* key_scan
[KEY_SCAN_SIZE
];
532 * used by tls_pre_encrypt to communicate the encrypt key
533 * to tls_post_encrypt()
535 struct key_state
*save_ks
; /* temporary pointer used between pre/post routines */
538 * Number of sessions negotiated thus far.
545 int n_hard_errors
; /* errors due to TLS negotiation failure */
546 int n_soft_errors
; /* errors due to unrecognized or failed-to-authenticate incoming packets */
549 * Our locked common name (cannot change during the life of this tls_multi object)
554 * Our session objects.
556 struct tls_session session
[TM_SIZE
];
560 * Used in --mode server mode to check tls-auth signature on initial
561 * packets received from new clients.
563 struct tls_auth_standalone
565 struct key_ctx_bi tls_auth_key
;
566 struct crypto_options tls_auth_options
;
570 void init_ssl_lib (void);
571 void free_ssl_lib (void);
573 /* Build master SSL_CTX object that serves for the whole of openvpn instantiation */
574 SSL_CTX
*init_ssl (const struct options
*options
);
576 struct tls_multi
*tls_multi_init (struct tls_options
*tls_options
);
578 struct tls_auth_standalone
*tls_auth_standalone_init (struct tls_options
*tls_options
,
579 struct gc_arena
*gc
);
581 void tls_auth_standalone_finalize (struct tls_auth_standalone
*tas
,
582 const struct frame
*frame
);
584 void tls_multi_init_finalize(struct tls_multi
*multi
,
585 const struct frame
*frame
);
587 void tls_multi_init_set_options(struct tls_multi
* multi
,
591 bool tls_multi_process (struct tls_multi
*multi
,
592 struct buffer
*to_link
,
593 struct sockaddr_in
*to_link_addr
,
594 struct link_socket_info
*to_link_socket_info
,
597 void tls_multi_free (struct tls_multi
*multi
, bool clear
);
599 bool tls_pre_decrypt (struct tls_multi
*multi
,
600 struct sockaddr_in
*from
,
602 struct crypto_options
*opt
);
604 bool tls_pre_decrypt_lite (const struct tls_auth_standalone
*tas
,
605 const struct sockaddr_in
*from
,
606 const struct buffer
*buf
);
608 void tls_pre_encrypt (struct tls_multi
*multi
,
609 struct buffer
*buf
, struct crypto_options
*opt
);
611 void tls_post_encrypt (struct tls_multi
*multi
, struct buffer
*buf
);
613 void show_available_tls_ciphers (void);
614 void get_highest_preference_tls_cipher (char *buf
, int size
);
616 void pem_password_setup (const char *auth_file
);
617 int pem_password_callback (char *buf
, int size
, int rwflag
, void *u
);
618 void auth_user_pass_setup (const char *auth_file
);
619 void ssl_set_auth_nocache (void);
620 void ssl_purge_auth (void);
622 void tls_set_verify_command (const char *cmd
);
623 void tls_set_crl_verify (const char *crl
);
624 void tls_set_verify_x509name (const char *x509name
);
626 void tls_adjust_frame_parameters(struct frame
*frame
);
628 bool tls_send_payload (struct tls_multi
*multi
,
632 bool tls_rec_payload (struct tls_multi
*multi
,
635 const char *tls_common_name (struct tls_multi
* multi
, bool null
);
636 void tls_set_common_name (struct tls_multi
*multi
, const char *common_name
);
637 void tls_lock_common_name (struct tls_multi
*multi
);
639 bool tls_authenticated (struct tls_multi
*multi
);
640 void tls_deauthenticate (struct tls_multi
*multi
);
647 tls_test_payload_len (const struct tls_multi
*multi
)
651 const struct key_state
*ks
= &multi
->session
[TM_ACTIVE
].key
[KS_PRIMARY
];
652 if (ks
->state
>= S_ACTIVE
)
653 return BLEN (&ks
->plaintext_read_buf
);
659 tls_set_single_session (struct tls_multi
*multi
)
662 multi
->opt
.single_session
= true;
666 * protocol_dump() flags
668 #define PD_TLS_AUTH_HMAC_SIZE_MASK 0xFF
669 #define PD_SHOW_DATA (1<<8)
670 #define PD_TLS (1<<9)
671 #define PD_VERBOSE (1<<10)
673 const char *protocol_dump (struct buffer
*buffer
,
675 struct gc_arena
*gc
);
681 #ifdef MEASURE_TLS_HANDSHAKE_STATS
682 void show_tls_performance_stats(void);
685 /*#define EXTRACT_X509_FIELD_TEST*/
686 void extract_x509_field_test (void);
688 #endif /* USE_CRYPTO && USE_SSL */