OpenVPN
auth_token.c
Go to the documentation of this file.
1#ifdef HAVE_CONFIG_H
2#include "config.h"
3#endif
4
5#include "syshead.h"
6
7#include "base64.h"
8#include "buffer.h"
9#include "crypto.h"
10#include "openvpn.h"
11#include "ssl_common.h"
12#include "auth_token.h"
13#include "push.h"
14#include "integer.h"
15#include "ssl.h"
16#include "ssl_verify.h"
17#include <inttypes.h>
18
19const char *auth_token_pem_name = "OpenVPN auth-token server key";
20
21#define AUTH_TOKEN_SESSION_ID_LEN 12
22#define AUTH_TOKEN_SESSION_ID_BASE64_LEN (OPENVPN_BASE64_LENGTH(AUTH_TOKEN_SESSION_ID_LEN))
23
24/* We want our token to be a multiple of 3 bytes to avoid the base64 padding */
25static_assert(AUTH_TOKEN_SESSION_ID_LEN % 3 == 0, "AUTH_TOKEN_SESSION_ID_LEN needs to be multiple a 3");
26
27#define AUTH_TOKEN_HMAC_LEN SHA256_DIGEST_LENGTH
28/* Size of the data of the token (not b64 encoded and without prefix) */
29#define TOKEN_DATA_LEN (2 * sizeof(int64_t) + AUTH_TOKEN_SESSION_ID_LEN + AUTH_TOKEN_HMAC_LEN)
30#define TOKEN_DATA_BASE64_LEN (OPENVPN_BASE64_LENGTH(TOKEN_DATA_LEN))
31
32
33#define TOTAL_SESSION_TOKEN_LEN (strlen(SESSION_ID_PREFIX) + TOKEN_DATA_BASE64_LEN)
34
35/* Ensure that TOKEN_DATA_LEN is a multiple of 3 so the we avoid the base64
36 * padding */
37static_assert(TOKEN_DATA_LEN % 3 == 0, "TOKEN_DATA_BASE64_LEN is not a multiple of 3");
38
39bool
40is_auth_token(const char *password)
41{
42 if (strlen(password) != TOTAL_SESSION_TOKEN_LEN)
43 {
44 return false;
45 }
46
47 return (memcmp_constant_time(SESSION_ID_PREFIX, password, strlen(SESSION_ID_PREFIX)) == 0);
48}
49
50static struct key_type
52{
53 return create_kt("none", "SHA256", "auth-gen-token");
54}
55
56void
58 const struct user_pass *up)
59{
60 if (!multi->opt.auth_token_generate)
61 {
62 return;
63 }
64
65 int auth_token_state_flags = session->key[KS_PRIMARY].auth_token_state_flags;
66
67 const char *state;
68
69 if (!is_auth_token(up->password))
70 {
71 state = "Initial";
72 }
73 else if (auth_token_state_flags & AUTH_TOKEN_HMAC_OK)
74 {
75 switch (auth_token_state_flags & (AUTH_TOKEN_VALID_EMPTYUSER | AUTH_TOKEN_EXPIRED))
76 {
77 case 0:
78 state = "Authenticated";
79 break;
80
82 state = "Expired";
83 break;
84
86 state = "AuthenticatedEmptyUser";
87 break;
88
90 state = "ExpiredEmptyUser";
91 break;
92
93 default:
94 /* Silence compiler warning, all four possible combinations are covered */
95 ASSERT(0);
96 }
97 }
98 else
99 {
100 state = "Invalid";
101 }
102
103 setenv_str(session->opt->es, "session_state", state);
104
105 /* We had a valid session id before */
106 const char *session_id_source;
107 if (auth_token_state_flags & AUTH_TOKEN_HMAC_OK
108 && !(auth_token_state_flags & AUTH_TOKEN_EXPIRED))
109 {
110 session_id_source = up->password;
111 }
112 else
113 {
114 /*
115 * No session before, generate a new session token for the new session
116 */
117 if (!multi->auth_token_initial)
118 {
119 generate_auth_token(up, multi);
120 }
121 session_id_source = multi->auth_token_initial;
122 }
123 /*
124 * In the auth-token the auth token is already base64 encoded
125 * and being a multiple of 4 ensure that it a multiple of bytes
126 * in the encoding
127 */
128 char session_id[AUTH_TOKEN_SESSION_ID_LEN * 2] = { 0 };
129 memcpy(session_id, session_id_source + strlen(SESSION_ID_PREFIX),
131
132 setenv_str(session->opt->es, "session_id", session_id);
133}
134
135void
137{
139}
140
141void
142auth_token_init_secret(struct key_ctx *key_ctx, const char *key_file, bool key_inline)
143{
144 struct key_type kt = auth_token_kt();
145
146 struct buffer server_secret_key = alloc_buf(2048);
147
148 bool key_loaded = false;
149 if (key_file)
150 {
151 key_loaded =
153 }
154 else
155 {
157 }
158
159 if (!key_loaded)
160 {
161 msg(M_FATAL, "ERROR: Cannot load auth-token secret");
162 }
163
164 struct key key;
165
166 if (!buf_read(&server_secret_key, &key, sizeof(key)))
167 {
168 msg(M_FATAL, "ERROR: not enough data in auth-token secret");
169 }
170
171 struct key_parameters key_params;
172 key_parameters_from_key(&key_params, &key);
173 init_key_ctx(key_ctx, &key_params, &kt, false, "auth-token secret");
174
175 free_buf(&server_secret_key);
176}
177
178void
179generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
180{
181 struct gc_arena gc = gc_new();
182
183 int64_t timestamp = htonll((uint64_t)now);
184 int64_t initial_timestamp = timestamp;
185
186 hmac_ctx_t *ctx = multi->opt.auth_token_key.hmac;
187 ASSERT(hmac_ctx_size(ctx) == 256 / 8);
188
189 uint8_t sessid[AUTH_TOKEN_SESSION_ID_LEN];
190
191 if (multi->auth_token_initial)
192 {
193 /* Just enough space to fit 8 bytes + 1 extra to decode a non-padded
194 * base64 string (multiple of 3 bytes). 9 bytes => 12 bytes base64
195 * bytes
196 */
197 char old_tstamp_decode[9];
198
199 /* Make a copy of the string to not modify multi->auth_token_initial */
200 char *initial_token_copy = string_alloc(multi->auth_token_initial, &gc);
201
202 char *old_sessid = initial_token_copy + strlen(SESSION_ID_PREFIX);
203 char *old_tstamp_initial = old_sessid + AUTH_TOKEN_SESSION_ID_BASE64_LEN;
204
205 /*
206 * We null terminate the old token just after the session ID to let
207 * our base64 decode function only decode the session ID
208 */
209 old_tstamp_initial[12] = '\0';
210 ASSERT(openvpn_base64_decode(old_tstamp_initial, old_tstamp_decode, 9) == 9);
211
212 memcpy(&initial_timestamp, &old_tstamp_decode, sizeof(initial_timestamp));
213
214 old_tstamp_initial[0] = '\0';
217 }
218 else if (!rand_bytes(sessid, AUTH_TOKEN_SESSION_ID_LEN))
219 {
220 msg(M_FATAL, "Failed to get enough randomness for "
221 "authentication token");
222 }
223
224 /* Calculate the HMAC */
225 /* We enforce up->username to be \0 terminated in ssl.c.. Allowing username
226 * with \0 in them is asking for troubles in so many ways anyway that we
227 * ignore that corner case here
228 */
229 uint8_t hmac_output[256 / 8];
230
231 hmac_ctx_reset(ctx);
232
233 /*
234 * If the token was only valid for the empty user, also generate
235 * a new token with the empty username since we do not want to loose
236 * the information that the username cannot be trusted
237 */
238 struct key_state *ks = &multi->session[TM_ACTIVE].key[KS_PRIMARY];
240 {
241 hmac_ctx_update(ctx, (const uint8_t *)"", 0);
242 }
243 else
244 {
245 hmac_ctx_update(ctx, (uint8_t *)up->username, (int)strlen(up->username));
246 }
248 hmac_ctx_update(ctx, (uint8_t *)&initial_timestamp, sizeof(initial_timestamp));
249 hmac_ctx_update(ctx, (uint8_t *)&timestamp, sizeof(timestamp));
250 hmac_ctx_final(ctx, hmac_output);
251
252 /* Construct the unencoded session token */
253 struct buffer token =
254 alloc_buf_gc(2 * sizeof(uint64_t) + AUTH_TOKEN_SESSION_ID_LEN + 256 / 8, &gc);
255
256 ASSERT(buf_write(&token, sessid, sizeof(sessid)));
258 ASSERT(buf_write(&token, &timestamp, sizeof(timestamp)));
260
261 char *b64output = NULL;
263
264 struct buffer session_token =
266
270
271 free(b64output);
272
273 /* free the auth-token if defined, we will replace it with a new one */
274 free(multi->auth_token);
275 multi->auth_token = strdup((char *)BPTR(&session_token));
276
277 dmsg(D_SHOW_KEYS, "Generated token for client: %s (%s)", multi->auth_token, up->username);
278
279 if (!multi->auth_token_initial)
280 {
281 /*
282 * Save the initial auth token to continue using the same session ID
283 * and timestamp in updates
284 */
285 multi->auth_token_initial = strdup(multi->auth_token);
286 }
287
288 gc_free(&gc);
289}
290
291
292static bool
293check_hmac_token(hmac_ctx_t *ctx, const uint8_t *b64decoded, const char *username)
294{
295 ASSERT(hmac_ctx_size(ctx) == 256 / 8);
296
297 uint8_t hmac_output[256 / 8];
298
299 hmac_ctx_reset(ctx);
300 hmac_ctx_update(ctx, (uint8_t *)username, (int)strlen(username));
303
304 const uint8_t *hmac = b64decoded + TOKEN_DATA_LEN - 256 / 8;
306}
307
308unsigned int
309verify_auth_token(struct user_pass *up, struct tls_multi *multi, struct tls_session *session)
310{
311 /*
312 * Base64 is <= input and input is < USER_PASS_LEN, so using USER_PASS_LEN
313 * is safe here but a bit overkill
314 */
315 ASSERT(up && !up->protected);
317 int decoded_len =
319
320 /*
321 * Ensure that the decoded data is the size of the
322 * timestamp + hmac + session id
323 */
325 {
326 msg(M_WARN, "ERROR: --auth-token wrong size (%d!=%d)", decoded_len, (int)TOKEN_DATA_LEN);
327 return 0;
328 }
329
330 unsigned int ret = 0;
331
332 const uint8_t *sessid = b64decoded;
334 const uint8_t *tstamp = tstamp_initial + sizeof(uint64_t);
335
336 /* tstamp, tstamp_initial might not be aligned to an uint64, use memcpy
337 * to avoid unaligned access */
338 uint64_t timestamp = 0, timestamp_initial = 0;
339 memcpy(&timestamp, tstamp, sizeof(uint64_t));
340 timestamp = ntohll(timestamp);
341
344
345 hmac_ctx_t *ctx = multi->opt.auth_token_key.hmac;
346 if (check_hmac_token(ctx, b64decoded, up->username))
347 {
349 }
350 else if (check_hmac_token(ctx, b64decoded, ""))
351 {
354 /* overwrite the username of the client with the empty one */
355 strcpy(up->username, "");
356 }
357 else
358 {
359 msg(M_WARN, "--auth-gen-token: HMAC on token from client failed (%s)", up->username);
360 return 0;
361 }
362
363 /* Accept session tokens only if their timestamp is in the acceptable range
364 * for renegotiations.
365 * Cast is required for systems with 32bit time_t, e.g. Windows x86.
366 */
367 const time_t token_reneg_deadline = (time_t)timestamp + 2 * session->opt->auth_token_renewal;
368 bool in_renegotiation_time = now >= (time_t)timestamp && now < token_reneg_deadline;
369
371 {
372 msg(M_WARN, "Timestamp (%" PRIu64 ") of auth-token is out of the renewal window",
373 timestamp);
375 }
376
377 /* Sanity check the initial timestamp */
378 if (timestamp < timestamp_initial)
379 {
380 msg(M_WARN,
381 "Initial timestamp (%" PRIu64 ") in token from client earlier than "
382 "current timestamp %" PRIu64 ". Broken/unsynchronised clock?",
383 timestamp_initial, timestamp);
385 }
386
388 if (multi->opt.auth_token_lifetime && now > token_eol)
389 {
391 }
392
394 {
395 /* Tell client that the session token is expired */
396 auth_set_client_reason(multi, "SESSION: token expired");
397 msg(M_INFO, "--auth-gen-token: auth-token from client expired");
398 }
399
400 /* Check that we do have the same session ID in the token as in our stored
401 * auth-token to ensure that it did not change.
402 * This also compares the prefix and session part of the
403 * tokens, which should be identical if the session ID stayed the same */
404 if (multi->auth_token_initial
407 {
408 msg(M_WARN, "--auth-gen-token: session id in token changed (Rejecting "
409 "token.");
410 ret = 0;
411 }
412 return ret;
413}
414
415void
417{
418 if (multi)
419 {
420 if (multi->auth_token)
421 {
423 free(multi->auth_token);
424 }
425 if (multi->auth_token_initial)
426 {
428 free(multi->auth_token_initial);
429 }
430 multi->auth_token = NULL;
431 multi->auth_token_initial = NULL;
432 }
433}
434
435void
437{
438 struct tls_multi *multi = c->c2.tls_multi;
439 struct tls_session *session = &multi->session[TM_ACTIVE];
440
441 if (get_primary_key(multi)->state < S_GENERATED_KEYS
442 || get_primary_key(multi)->authenticated != KS_AUTH_TRUE)
443 {
444 /* the currently active session is still in renegotiation or another
445 * not fully authorized state. We are either very close to a
446 * renegotiation or have deauthorized the client. In both cases
447 * we just ignore the request to send another token
448 */
449 return;
450 }
451
452 if (!multi->auth_token_initial)
453 {
454 msg(D_SHOW_KEYS, "initial auth-token not generated yet, skipping "
455 "auth-token renewal.");
456 return;
457 }
458
459 if (!multi->locked_username)
460 {
461 msg(D_SHOW_KEYS, "username not locked, skipping auth-token renewal.");
462 return;
463 }
464
465 struct user_pass up;
466 CLEAR(up);
467 strncpynt(up.username, multi->locked_username, sizeof(up.username));
468
469 generate_auth_token(&up, multi);
470
472}
473
474void
476{
477 /*
478 * Auth token already sent to client, update auth-token on client.
479 * The initial auth-token is sent as part of the push message, for this
480 * update we need to schedule an extra push message.
481 *
482 * Otherwise, the auth-token get pushed out as part of the "normal"
483 * push-reply
484 */
485 if (multi->auth_token_initial)
486 {
487 /*
488 * We do not explicitly reschedule the sending of the
489 * control message here. This might delay this reply
490 * a few seconds but this message is not time critical
491 */
493 }
494}
void auth_token_write_server_key_file(const char *filename)
Generate a auth-token server secret key, and write to file.
Definition auth_token.c:136
static bool check_hmac_token(hmac_ctx_t *ctx, const uint8_t *b64decoded, const char *username)
Definition auth_token.c:293
void auth_token_init_secret(struct key_ctx *key_ctx, const char *key_file, bool key_inline)
Loads an HMAC secret from a file or if no file is present generates a epheremal secret for the run ti...
Definition auth_token.c:142
void generate_auth_token(const struct user_pass *up, struct tls_multi *multi)
Generate an auth token based on username and timestamp.
Definition auth_token.c:179
#define AUTH_TOKEN_SESSION_ID_LEN
Definition auth_token.c:21
#define TOTAL_SESSION_TOKEN_LEN
Definition auth_token.c:33
unsigned int verify_auth_token(struct user_pass *up, struct tls_multi *multi, struct tls_session *session)
Verifies the auth token to be in the format that generate_auth_token create and checks if the token i...
Definition auth_token.c:309
static struct key_type auth_token_kt(void)
Definition auth_token.c:51
#define AUTH_TOKEN_SESSION_ID_BASE64_LEN
Definition auth_token.c:22
void add_session_token_env(struct tls_session *session, struct tls_multi *multi, const struct user_pass *up)
Put the session id, and auth token status into the environment if auth-token is enabled.
Definition auth_token.c:57
const char * auth_token_pem_name
Definition auth_token.c:19
#define TOKEN_DATA_LEN
Definition auth_token.c:29
void check_send_auth_token(struct context *c)
Checks if the timer to resend the auth-token has expired and if a new auth-token should be send to th...
Definition auth_token.c:436
#define AUTH_TOKEN_HMAC_LEN
Definition auth_token.c:27
void wipe_auth_token(struct tls_multi *multi)
Wipes the authentication token out of the memory, frees and cleans up related buffers and flags.
Definition auth_token.c:416
void resend_auth_token_renegotiation(struct tls_multi *multi, struct tls_session *session)
Checks if a client should be sent a new auth token to update its current auth-token.
Definition auth_token.c:475
bool is_auth_token(const char *password)
Return if the password string has the format of a password.
Definition auth_token.c:40
#define SESSION_ID_PREFIX
The prefix given to auth tokens start with, this prefix is special cased to not show up in log files ...
Definition auth_token.h:109
void free_buf(struct buffer *buf)
Definition buffer.c:189
struct buffer alloc_buf_gc(size_t size, struct gc_arena *gc)
Definition buffer.c:88
struct buffer alloc_buf(size_t size)
Definition buffer.c:63
char * string_alloc(const char *str, struct gc_arena *gc)
Definition buffer.c:653
#define BPTR(buf)
Definition buffer.h:123
static bool buf_read(struct buffer *src, void *dest, int size)
Definition buffer.h:763
static void secure_memzero(void *data, size_t len)
Securely zeroise memory.
Definition buffer.h:415
static bool buf_write(struct buffer *dest, const void *src, size_t size)
Definition buffer.h:661
static bool buf_write_u8(struct buffer *dest, uint8_t data)
Definition buffer.h:685
#define BLEN(buf)
Definition buffer.h:126
static void strncpynt(char *dest, const char *src, size_t maxlen)
Definition buffer.h:362
static void gc_free(struct gc_arena *a)
Definition buffer.h:1049
static struct gc_arena gc_new(void)
Definition buffer.h:1041
void init_key_ctx(struct key_ctx *ctx, const struct key_parameters *key, const struct key_type *kt, int enc, const char *prefix)
Definition crypto.c:996
bool read_pem_key_file(struct buffer *key, const char *pem_name, const char *key_file, bool key_inline)
Read key material from a PEM encoded files into the key structure.
Definition crypto.c:1879
bool generate_ephemeral_key(struct buffer *key, const char *key_name)
Generate ephermal key material into the key structure.
Definition crypto.c:1861
void write_pem_key_file(const char *filename, const char *pem_name)
Generate a server key with enough randomness to fill a key struct and write to file.
Definition crypto.c:1824
void key_parameters_from_key(struct key_parameters *key_params, const struct key *key)
Converts a struct key representation into a struct key_parameters representation.
Definition crypto.c:1189
Data Channel Cryptography Module.
int memcmp_constant_time(const void *a, const void *b, size_t size)
As memcmp(), but constant-time.
static struct key_type create_kt(const char *cipher, const char *md, const char *optname)
Creates and validates an instance of struct key_type with the provided algs.
Definition crypto.h:686
void hmac_ctx_update(hmac_ctx_t *ctx, const uint8_t *src, int src_len)
void hmac_ctx_reset(hmac_ctx_t *ctx)
void hmac_ctx_final(hmac_ctx_t *ctx, uint8_t *dst)
int hmac_ctx_size(hmac_ctx_t *ctx)
int rand_bytes(uint8_t *output, int len)
Wrapper for secure random number generator.
void setenv_str(struct env_set *es, const char *name, const char *value)
Definition env_set.c:307
#define D_SHOW_KEYS
Definition errlevel.h:120
#define M_INFO
Definition errlevel.h:54
#define KS_PRIMARY
Primary key state index.
Definition ssl_common.h:464
#define TM_ACTIVE
Active tls_session.
Definition ssl_common.h:544
#define S_GENERATED_KEYS
The data channel keys have been generated The TLS session is fully authenticated when reaching this s...
Definition ssl_common.h:105
#define ntohll(x)
Definition integer.h:36
#define htonll(x)
Definition integer.h:29
#define USER_PASS_LEN
Definition misc.h:67
#define CLEAR(x)
Definition basic.h:32
#define M_FATAL
Definition error.h:90
#define dmsg(flags,...)
Definition error.h:172
#define msg(flags,...)
Definition error.h:152
#define ASSERT(x)
Definition error.h:219
#define M_WARN
Definition error.h:92
time_t now
Definition otime.c:33
void send_push_reply_auth_token(struct tls_multi *multi)
Sends a push reply message only containin the auth-token to update the auth-token on the client.
Definition push.c:785
int openvpn_base64_decode(const char *str, void *data, int size)
Definition base64.c:160
int openvpn_base64_encode(const void *data, int size, char **str)
Definition base64.c:51
Control Channel SSL/Data channel negotiation module.
Control Channel Common Data Structures.
#define AUTH_TOKEN_HMAC_OK
Auth-token sent from client has valid hmac.
Definition ssl_common.h:686
#define AUTH_TOKEN_EXPIRED
Auth-token sent from client has expired.
Definition ssl_common.h:688
@ KS_AUTH_TRUE
Key state is authenticated.
Definition ssl_common.h:157
static const struct key_state * get_primary_key(const struct tls_multi *multi)
gets an item of key_state objects in the order they should be scanned by data channel modules.
Definition ssl_common.h:755
#define AUTH_TOKEN_VALID_EMPTYUSER
Auth-token is only valid for an empty username and not the username actually supplied from the client...
Definition ssl_common.h:696
void auth_set_client_reason(struct tls_multi *multi, const char *client_reason)
Sets the reason why authentication of a client failed.
Definition ssl_verify.c:814
Control Channel Verification Module.
Wrapper structure for dynamically allocated memory.
Definition buffer.h:60
int len
Length in bytes of the actual content within the allocated memory.
Definition buffer.h:65
struct tls_multi * tls_multi
TLS state structure for this VPN tunnel.
Definition openvpn.h:323
Contains all state information for one tunnel.
Definition openvpn.h:471
struct context_2 c2
Level 2 context.
Definition openvpn.h:514
Garbage collection arena used to keep track of dynamically allocated memory.
Definition buffer.h:116
Container for one set of cipher and/or HMAC contexts.
Definition crypto.h:202
hmac_ctx_t * hmac
Generic HMAC context.
Definition crypto.h:204
internal structure similar to struct key that holds key information but is not represented on wire an...
Definition crypto.h:163
Security parameter state of one TLS and data channel key session.
Definition ssl_common.h:208
unsigned int auth_token_state_flags
The state of the auth-token sent from the client.
Definition ssl_common.h:211
Container for unidirectional cipher and HMAC key material.
Definition crypto.h:152
Security parameter state for a single VPN tunnel.
Definition ssl_common.h:611
char * auth_token_initial
The first auth-token we sent to a client.
Definition ssl_common.h:683
char * locked_username
The locked username is the username we assume the client is using.
Definition ssl_common.h:649
struct tls_options opt
Definition ssl_common.h:616
struct tls_session session[TM_SIZE]
Array of tls_session objects representing control channel sessions with the remote peer.
Definition ssl_common.h:711
char * auth_token
If server sends a generated auth-token, this is the token to use for future user/pass authentications...
Definition ssl_common.h:678
struct key_ctx auth_token_key
Definition ssl_common.h:407
unsigned int auth_token_lifetime
Definition ssl_common.h:404
bool auth_token_generate
Generate auth-tokens on successful user/pass auth,seet via options->auth_token_generate.
Definition ssl_common.h:400
Security parameter state of a single session within a VPN tunnel.
Definition ssl_common.h:489
struct key_state key[KS_SIZE]
Definition ssl_common.h:524
bool protected
Definition misc.h:61
char password[USER_PASS_LEN]
Definition misc.h:71
char username[USER_PASS_LEN]
Definition misc.h:70
struct gc_arena gc
Definition test_ssl.c:133