Callback for ESP packets added to receiver.
[strongswan.git] / src / libcharon / network / receiver.c
1 /*
2 * Copyright (C) 2008-2012 Tobias Brunner
3 * Copyright (C) 2005-2006 Martin Willi
4 * Copyright (C) 2005 Jan Hutter
5 * Hochschule fuer Technik Rapperswil
6 *
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2 of the License, or (at your
10 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 * for more details.
16 */
17
18 #include <stdlib.h>
19 #include <unistd.h>
20
21 #include "receiver.h"
22
23 #include <daemon.h>
24 #include <network/socket.h>
25 #include <network/packet.h>
26 #include <processing/jobs/job.h>
27 #include <processing/jobs/process_message_job.h>
28 #include <processing/jobs/callback_job.h>
29 #include <crypto/hashers/hasher.h>
30 #include <threading/mutex.h>
31
32 /** lifetime of a cookie, in seconds */
33 #define COOKIE_LIFETIME 10
34 /** time we wait before disabling cookies */
35 #define COOKIE_CALMDOWN_DELAY 10
36 /** how many times to reuse the secret */
37 #define COOKIE_REUSE 10000
38 /** default value for private_receiver_t.cookie_threshold */
39 #define COOKIE_THRESHOLD_DEFAULT 10
40 /** default value for private_receiver_t.block_threshold */
41 #define BLOCK_THRESHOLD_DEFAULT 5
42 /** length of the secret to use for cookie calculation */
43 #define SECRET_LENGTH 16
44 /** Length of a notify payload header */
45 #define NOTIFY_PAYLOAD_HEADER_LENGTH 8
46
47 typedef struct private_receiver_t private_receiver_t;
48
49 /**
50 * Private data of a receiver_t object.
51 */
52 struct private_receiver_t {
53 /**
54 * Public part of a receiver_t object.
55 */
56 receiver_t public;
57
58 /**
59 * Registered callback for ESP packets
60 */
61 struct {
62 receiver_esp_cb_t cb;
63 void *data;
64 } esp_cb;
65
66 /**
67 * Mutex for ESP callback
68 */
69 mutex_t *esp_cb_mutex;
70
71 /**
72 * current secret to use for cookie calculation
73 */
74 char secret[SECRET_LENGTH];
75
76 /**
77 * previous secret used to verify older cookies
78 */
79 char secret_old[SECRET_LENGTH];
80
81 /**
82 * how many times we have used "secret" so far
83 */
84 u_int32_t secret_used;
85
86 /**
87 * time we did the cookie switch
88 */
89 u_int32_t secret_switch;
90
91 /**
92 * time offset to use, hides our system time
93 */
94 u_int32_t secret_offset;
95
96 /**
97 * the RNG to use for secret generation
98 */
99 rng_t *rng;
100
101 /**
102 * hasher to use for cookie calculation
103 */
104 hasher_t *hasher;
105
106 /**
107 * require cookies after this many half open IKE_SAs
108 */
109 u_int32_t cookie_threshold;
110
111 /**
112 * timestamp of last cookie requested
113 */
114 time_t last_cookie;
115
116 /**
117 * how many half open IKE_SAs per peer before blocking
118 */
119 u_int32_t block_threshold;
120
121 /**
122 * Drop IKE_SA_INIT requests if processor job load exceeds this limit
123 */
124 u_int init_limit_job_load;
125
126 /**
127 * Drop IKE_SA_INIT requests if half open IKE_SA count exceeds this limit
128 */
129 u_int init_limit_half_open;
130
131 /**
132 * Delay for receiving incoming packets, to simulate larger RTT
133 */
134 int receive_delay;
135
136 /**
137 * Specific message type to delay, 0 for any
138 */
139 int receive_delay_type;
140
141 /**
142 * Delay request messages?
143 */
144 bool receive_delay_request;
145
146 /**
147 * Delay response messages?
148 */
149 bool receive_delay_response;
150 };
151
152 /**
153 * send a notify back to the sender
154 */
155 static void send_notify(message_t *request, int major, exchange_type_t exchange,
156 notify_type_t type, chunk_t data)
157 {
158 ike_sa_id_t *ike_sa_id;
159 message_t *response;
160 host_t *src, *dst;
161 packet_t *packet;
162
163 response = message_create(major, 0);
164 response->set_exchange_type(response, exchange);
165 response->add_notify(response, FALSE, type, data);
166 dst = request->get_source(request);
167 src = request->get_destination(request);
168 response->set_source(response, src->clone(src));
169 response->set_destination(response, dst->clone(dst));
170 if (major == IKEV2_MAJOR_VERSION)
171 {
172 response->set_request(response, FALSE);
173 }
174 response->set_message_id(response, 0);
175 ike_sa_id = request->get_ike_sa_id(request);
176 ike_sa_id->switch_initiator(ike_sa_id);
177 response->set_ike_sa_id(response, ike_sa_id);
178 if (response->generate(response, NULL, &packet) == SUCCESS)
179 {
180 charon->sender->send(charon->sender, packet);
181 }
182 response->destroy(response);
183 }
184
185 /**
186 * build a cookie
187 */
188 static bool cookie_build(private_receiver_t *this, message_t *message,
189 u_int32_t t, chunk_t secret, chunk_t *cookie)
190 {
191 u_int64_t spi = message->get_initiator_spi(message);
192 host_t *ip = message->get_source(message);
193 chunk_t input, hash;
194
195 /* COOKIE = t | sha1( IPi | SPIi | t | secret ) */
196 input = chunk_cata("cccc", ip->get_address(ip), chunk_from_thing(spi),
197 chunk_from_thing(t), secret);
198 hash = chunk_alloca(this->hasher->get_hash_size(this->hasher));
199 if (!this->hasher->get_hash(this->hasher, input, hash.ptr))
200 {
201 return FALSE;
202 }
203 *cookie = chunk_cat("cc", chunk_from_thing(t), hash);
204 return TRUE;
205 }
206
207 /**
208 * verify a received cookie
209 */
210 static bool cookie_verify(private_receiver_t *this, message_t *message,
211 chunk_t cookie)
212 {
213 u_int32_t t, now;
214 chunk_t reference;
215 chunk_t secret;
216
217 now = time_monotonic(NULL);
218 t = *(u_int32_t*)cookie.ptr;
219
220 if (cookie.len != sizeof(u_int32_t) +
221 this->hasher->get_hash_size(this->hasher) ||
222 t < now - this->secret_offset - COOKIE_LIFETIME)
223 {
224 DBG2(DBG_NET, "received cookie lifetime expired, rejecting");
225 return FALSE;
226 }
227
228 /* check if cookie is derived from old_secret */
229 if (t + this->secret_offset > this->secret_switch)
230 {
231 secret = chunk_from_thing(this->secret);
232 }
233 else
234 {
235 secret = chunk_from_thing(this->secret_old);
236 }
237
238 /* compare own calculation against received */
239 if (!cookie_build(this, message, t, secret, &reference))
240 {
241 return FALSE;
242 }
243 if (chunk_equals(reference, cookie))
244 {
245 chunk_free(&reference);
246 return TRUE;
247 }
248 chunk_free(&reference);
249 return FALSE;
250 }
251
252 /**
253 * Check if a valid cookie found
254 */
255 static bool check_cookie(private_receiver_t *this, message_t *message)
256 {
257 packet_t *packet;
258 chunk_t data;
259
260 /* check for a cookie. We don't use our parser here and do it
261 * quick and dirty for performance reasons.
262 * we assume the cookie is the first payload (which is a MUST), and
263 * the cookie's SPI length is zero. */
264 packet = message->get_packet(message);
265 data = packet->get_data(packet);
266 if (data.len <
267 IKE_HEADER_LENGTH + NOTIFY_PAYLOAD_HEADER_LENGTH +
268 sizeof(u_int32_t) + this->hasher->get_hash_size(this->hasher) ||
269 *(data.ptr + 16) != NOTIFY ||
270 *(u_int16_t*)(data.ptr + IKE_HEADER_LENGTH + 6) != htons(COOKIE))
271 {
272 /* no cookie found */
273 packet->destroy(packet);
274 return FALSE;
275 }
276 data.ptr += IKE_HEADER_LENGTH + NOTIFY_PAYLOAD_HEADER_LENGTH;
277 data.len = sizeof(u_int32_t) + this->hasher->get_hash_size(this->hasher);
278 if (!cookie_verify(this, message, data))
279 {
280 DBG2(DBG_NET, "found cookie, but content invalid");
281 packet->destroy(packet);
282 return FALSE;
283 }
284 return TRUE;
285 }
286
287 /**
288 * Check if we currently require cookies
289 */
290 static bool cookie_required(private_receiver_t *this,
291 u_int half_open, u_int32_t now)
292 {
293 if (this->cookie_threshold && half_open >= this->cookie_threshold)
294 {
295 this->last_cookie = now;
296 return TRUE;
297 }
298 if (now < this->last_cookie + COOKIE_CALMDOWN_DELAY)
299 {
300 /* We don't disable cookies unless we haven't seen IKE_SA_INITs
301 * for COOKIE_CALMDOWN_DELAY seconds. This avoids jittering between
302 * cookie on / cookie off states, which is problematic. Consider the
303 * following: A legitimiate initiator sends a IKE_SA_INIT while we
304 * are under a DoS attack. If we toggle our cookie behavior,
305 * multiple retransmits of this IKE_SA_INIT might get answered with
306 * and without cookies. The initiator goes on and retries with
307 * a cookie, but it can't know if the completing IKE_SA_INIT response
308 * is to its IKE_SA_INIT request with or without cookies. This is
309 * problematic, as the cookie is part of AUTH payload data.
310 */
311 this->last_cookie = now;
312 return TRUE;
313 }
314 return FALSE;
315 }
316
317 /**
318 * Check if we should drop IKE_SA_INIT because of cookie/overload checking
319 */
320 static bool drop_ike_sa_init(private_receiver_t *this, message_t *message)
321 {
322 u_int half_open;
323 u_int32_t now;
324
325 now = time_monotonic(NULL);
326 half_open = charon->ike_sa_manager->get_half_open_count(
327 charon->ike_sa_manager, NULL);
328
329 /* check for cookies in IKEv2 */
330 if (message->get_major_version(message) == IKEV2_MAJOR_VERSION &&
331 cookie_required(this, half_open, now) && !check_cookie(this, message))
332 {
333 chunk_t cookie;
334
335 DBG2(DBG_NET, "received packet from: %#H to %#H",
336 message->get_source(message),
337 message->get_destination(message));
338 if (!cookie_build(this, message, now - this->secret_offset,
339 chunk_from_thing(this->secret), &cookie))
340 {
341 return TRUE;
342 }
343 DBG2(DBG_NET, "sending COOKIE notify to %H",
344 message->get_source(message));
345 send_notify(message, IKEV2_MAJOR_VERSION, IKE_SA_INIT, COOKIE, cookie);
346 chunk_free(&cookie);
347 if (++this->secret_used > COOKIE_REUSE)
348 {
349 char secret[SECRET_LENGTH];
350
351 DBG1(DBG_NET, "generating new cookie secret after %d uses",
352 this->secret_used);
353 if (this->rng->get_bytes(this->rng, SECRET_LENGTH, secret))
354 {
355 memcpy(this->secret_old, this->secret, SECRET_LENGTH);
356 memcpy(this->secret, secret, SECRET_LENGTH);
357 memwipe(secret, SECRET_LENGTH);
358 this->secret_switch = now;
359 this->secret_used = 0;
360 }
361 else
362 {
363 DBG1(DBG_NET, "failed to allocated cookie secret, keeping old");
364 }
365 }
366 return TRUE;
367 }
368
369 /* check if peer has too many IKE_SAs half open */
370 if (this->block_threshold &&
371 charon->ike_sa_manager->get_half_open_count(charon->ike_sa_manager,
372 message->get_source(message)) >= this->block_threshold)
373 {
374 DBG1(DBG_NET, "ignoring IKE_SA setup from %H, "
375 "peer too aggressive", message->get_source(message));
376 return TRUE;
377 }
378
379 /* check if global half open IKE_SA limit reached */
380 if (this->init_limit_half_open &&
381 half_open >= this->init_limit_half_open)
382 {
383 DBG1(DBG_NET, "ignoring IKE_SA setup from %H, half open IKE_SA "
384 "count of %d exceeds limit of %d", message->get_source(message),
385 half_open, this->init_limit_half_open);
386 return TRUE;
387 }
388
389 /* check if job load acceptable */
390 if (this->init_limit_job_load)
391 {
392 u_int jobs = 0, i;
393
394 for (i = 0; i < JOB_PRIO_MAX; i++)
395 {
396 jobs += lib->processor->get_job_load(lib->processor, i);
397 }
398 if (jobs > this->init_limit_job_load)
399 {
400 DBG1(DBG_NET, "ignoring IKE_SA setup from %H, job load of %d "
401 "exceeds limit of %d", message->get_source(message),
402 jobs, this->init_limit_job_load);
403 return TRUE;
404 }
405 }
406 return FALSE;
407 }
408
409 /**
410 * Job callback to receive packets
411 */
412 static job_requeue_t receive_packets(private_receiver_t *this)
413 {
414 ike_sa_id_t *id;
415 packet_t *packet;
416 message_t *message;
417 host_t *src, *dst;
418 status_t status;
419 bool supported = TRUE;
420
421 /* read in a packet */
422 status = charon->socket->receive(charon->socket, &packet);
423 if (status == NOT_SUPPORTED)
424 {
425 return JOB_REQUEUE_NONE;
426 }
427 else if (status != SUCCESS)
428 {
429 DBG2(DBG_NET, "receiving from socket failed!");
430 return JOB_REQUEUE_FAIR;
431 }
432
433 /* if neither source nor destination port is 500 we assume an IKE packet
434 * with Non-ESP marker or an ESP packet */
435 dst = packet->get_destination(packet);
436 src = packet->get_source(packet);
437 if (dst->get_port(dst) != IKEV2_UDP_PORT &&
438 src->get_port(src) != IKEV2_UDP_PORT)
439 {
440 chunk_t marker = chunk_from_chars(0x00, 0x00, 0x00, 0x00), data;
441
442 data = packet->get_data(packet);
443 if (memeq(data.ptr, marker.ptr, marker.len))
444 { /* remove Non-ESP marker */
445 data = chunk_skip(data, marker.len);
446 packet->set_data(packet, chunk_clone(data));
447 }
448 else
449 { /* this seems to be an ESP packet */
450 this->esp_cb_mutex->lock(this->esp_cb_mutex);
451 if (this->esp_cb.cb)
452 {
453 this->esp_cb.cb(this->esp_cb.data, packet);
454 }
455 else
456 {
457 packet->destroy(packet);
458 }
459 this->esp_cb_mutex->unlock(this->esp_cb_mutex);
460 return JOB_REQUEUE_DIRECT;
461 }
462 }
463
464 /* parse message header */
465 message = message_create_from_packet(packet);
466 if (message->parse_header(message) != SUCCESS)
467 {
468 DBG1(DBG_NET, "received invalid IKE header from %H - ignored",
469 packet->get_source(packet));
470 message->destroy(message);
471 return JOB_REQUEUE_DIRECT;
472 }
473
474 /* check IKE major version */
475 switch (message->get_major_version(message))
476 {
477 case IKEV2_MAJOR_VERSION:
478 #ifndef USE_IKEV2
479 if (message->get_exchange_type(message) == IKE_SA_INIT &&
480 message->get_request(message))
481 {
482 send_notify(message, IKEV1_MAJOR_VERSION, INFORMATIONAL_V1,
483 INVALID_MAJOR_VERSION, chunk_empty);
484 supported = FALSE;
485 }
486 #endif /* USE_IKEV2 */
487 break;
488 case IKEV1_MAJOR_VERSION:
489 #ifndef USE_IKEV1
490 if (message->get_exchange_type(message) == ID_PROT ||
491 message->get_exchange_type(message) == AGGRESSIVE)
492 {
493 send_notify(message, IKEV2_MAJOR_VERSION, INFORMATIONAL,
494 INVALID_MAJOR_VERSION, chunk_empty);
495 supported = FALSE;
496 }
497 #endif /* USE_IKEV1 */
498 break;
499 default:
500 #ifdef USE_IKEV2
501 send_notify(message, IKEV2_MAJOR_VERSION, INFORMATIONAL,
502 INVALID_MAJOR_VERSION, chunk_empty);
503 #endif /* USE_IKEV2 */
504 #ifdef USE_IKEV1
505 send_notify(message, IKEV1_MAJOR_VERSION, INFORMATIONAL_V1,
506 INVALID_MAJOR_VERSION, chunk_empty);
507 #endif /* USE_IKEV1 */
508 supported = FALSE;
509 break;
510 }
511 if (!supported)
512 {
513 DBG1(DBG_NET, "received unsupported IKE version %d.%d from %H, sending "
514 "INVALID_MAJOR_VERSION", message->get_major_version(message),
515 message->get_minor_version(message), packet->get_source(packet));
516 message->destroy(message);
517 return JOB_REQUEUE_DIRECT;
518 }
519 if (message->get_request(message) &&
520 message->get_exchange_type(message) == IKE_SA_INIT)
521 {
522 if (drop_ike_sa_init(this, message))
523 {
524 message->destroy(message);
525 return JOB_REQUEUE_DIRECT;
526 }
527 }
528 if (message->get_exchange_type(message) == ID_PROT ||
529 message->get_exchange_type(message) == AGGRESSIVE)
530 {
531 id = message->get_ike_sa_id(message);
532 if (id->get_responder_spi(id) == 0 &&
533 drop_ike_sa_init(this, message))
534 {
535 message->destroy(message);
536 return JOB_REQUEUE_DIRECT;
537 }
538 }
539
540 if (this->receive_delay)
541 {
542 if (this->receive_delay_type == 0 ||
543 this->receive_delay_type == message->get_exchange_type(message))
544 {
545 if ((message->get_request(message) && this->receive_delay_request) ||
546 (!message->get_request(message) && this->receive_delay_response))
547 {
548 DBG1(DBG_NET, "using receive delay: %dms",
549 this->receive_delay);
550 lib->scheduler->schedule_job_ms(lib->scheduler,
551 (job_t*)process_message_job_create(message),
552 this->receive_delay);
553 return JOB_REQUEUE_DIRECT;
554 }
555 }
556 }
557 lib->processor->queue_job(lib->processor,
558 (job_t*)process_message_job_create(message));
559 return JOB_REQUEUE_DIRECT;
560 }
561
562 METHOD(receiver_t, add_esp_cb, void,
563 private_receiver_t *this, receiver_esp_cb_t callback, void *data)
564 {
565 this->esp_cb_mutex->lock(this->esp_cb_mutex);
566 this->esp_cb.cb = callback;
567 this->esp_cb.data = data;
568 this->esp_cb_mutex->unlock(this->esp_cb_mutex);
569 }
570
571 METHOD(receiver_t, del_esp_cb, void,
572 private_receiver_t *this, receiver_esp_cb_t callback)
573 {
574 this->esp_cb_mutex->lock(this->esp_cb_mutex);
575 if (this->esp_cb.cb == callback)
576 {
577 this->esp_cb.cb = NULL;
578 this->esp_cb.data = NULL;
579 }
580 this->esp_cb_mutex->unlock(this->esp_cb_mutex);
581 }
582
583 METHOD(receiver_t, destroy, void,
584 private_receiver_t *this)
585 {
586 this->rng->destroy(this->rng);
587 this->hasher->destroy(this->hasher);
588 this->esp_cb_mutex->destroy(this->esp_cb_mutex);
589 free(this);
590 }
591
592 /*
593 * Described in header.
594 */
595 receiver_t *receiver_create()
596 {
597 private_receiver_t *this;
598 u_int32_t now = time_monotonic(NULL);
599
600 INIT(this,
601 .public = {
602 .add_esp_cb = _add_esp_cb,
603 .del_esp_cb = _del_esp_cb,
604 .destroy = _destroy,
605 },
606 .esp_cb_mutex = mutex_create(MUTEX_TYPE_DEFAULT),
607 .secret_switch = now,
608 .secret_offset = random() % now,
609 );
610
611 if (lib->settings->get_bool(lib->settings,
612 "%s.dos_protection", TRUE, charon->name))
613 {
614 this->cookie_threshold = lib->settings->get_int(lib->settings,
615 "%s.cookie_threshold", COOKIE_THRESHOLD_DEFAULT, charon->name);
616 this->block_threshold = lib->settings->get_int(lib->settings,
617 "%s.block_threshold", BLOCK_THRESHOLD_DEFAULT, charon->name);
618 }
619 this->init_limit_job_load = lib->settings->get_int(lib->settings,
620 "%s.init_limit_job_load", 0, charon->name);
621 this->init_limit_half_open = lib->settings->get_int(lib->settings,
622 "%s.init_limit_half_open", 0, charon->name);
623 this->receive_delay = lib->settings->get_int(lib->settings,
624 "%s.receive_delay", 0, charon->name);
625 this->receive_delay_type = lib->settings->get_int(lib->settings,
626 "%s.receive_delay_type", 0, charon->name),
627 this->receive_delay_request = lib->settings->get_bool(lib->settings,
628 "%s.receive_delay_request", TRUE, charon->name),
629 this->receive_delay_response = lib->settings->get_bool(lib->settings,
630 "%s.receive_delay_response", TRUE, charon->name),
631
632 this->hasher = lib->crypto->create_hasher(lib->crypto, HASH_PREFERRED);
633 if (!this->hasher)
634 {
635 DBG1(DBG_NET, "creating cookie hasher failed, no hashers supported");
636 free(this);
637 return NULL;
638 }
639 this->rng = lib->crypto->create_rng(lib->crypto, RNG_STRONG);
640 if (!this->rng)
641 {
642 DBG1(DBG_NET, "creating cookie RNG failed, no RNG supported");
643 this->hasher->destroy(this->hasher);
644 free(this);
645 return NULL;
646 }
647 if (!this->rng->get_bytes(this->rng, SECRET_LENGTH, this->secret))
648 {
649 DBG1(DBG_NET, "creating cookie secret failed");
650 destroy(this);
651 return NULL;
652 }
653 memcpy(this->secret_old, this->secret, SECRET_LENGTH);
654
655 lib->processor->queue_job(lib->processor,
656 (job_t*)callback_job_create_with_prio((callback_job_cb_t)receive_packets,
657 this, NULL, (callback_job_cancel_t)return_false, JOB_PRIO_CRITICAL));
658
659 return &this->public;
660 }
661