Moved packet_t to libstrongswan
[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 <processing/jobs/job.h>
26 #include <processing/jobs/process_message_job.h>
27 #include <processing/jobs/callback_job.h>
28 #include <crypto/hashers/hasher.h>
29 #include <threading/mutex.h>
30 #include <utils/packet.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 chunk_t data, marker = chunk_from_chars(0x00, 0x00, 0x00, 0x00);
421
422 /* read in a packet */
423 status = charon->socket->receive(charon->socket, &packet);
424 if (status == NOT_SUPPORTED)
425 {
426 return JOB_REQUEUE_NONE;
427 }
428 else if (status != SUCCESS)
429 {
430 DBG2(DBG_NET, "receiving from socket failed!");
431 return JOB_REQUEUE_FAIR;
432 }
433
434 data = packet->get_data(packet);
435 if (data.len == 1 && data.ptr[0] == 0xFF)
436 { /* silently drop NAT-T keepalives */
437 packet->destroy(packet);
438 return JOB_REQUEUE_DIRECT;
439 }
440 else if (data.len < marker.len)
441 { /* drop packets that are too small */
442 DBG3(DBG_NET, "received packet is too short (%d bytes)", data.len);
443 packet->destroy(packet);
444 return JOB_REQUEUE_DIRECT;
445 }
446
447 /* if neither source nor destination port is 500 we assume an IKE packet
448 * with Non-ESP marker or an ESP packet */
449 dst = packet->get_destination(packet);
450 src = packet->get_source(packet);
451 if (dst->get_port(dst) != IKEV2_UDP_PORT &&
452 src->get_port(src) != IKEV2_UDP_PORT)
453 {
454 if (memeq(data.ptr, marker.ptr, marker.len))
455 { /* remove Non-ESP marker */
456 packet->skip_bytes(packet, marker.len);
457 }
458 else
459 { /* this seems to be an ESP packet */
460 this->esp_cb_mutex->lock(this->esp_cb_mutex);
461 if (this->esp_cb.cb)
462 {
463 this->esp_cb.cb(this->esp_cb.data, packet);
464 }
465 else
466 {
467 packet->destroy(packet);
468 }
469 this->esp_cb_mutex->unlock(this->esp_cb_mutex);
470 return JOB_REQUEUE_DIRECT;
471 }
472 }
473
474 /* parse message header */
475 message = message_create_from_packet(packet);
476 if (message->parse_header(message) != SUCCESS)
477 {
478 DBG1(DBG_NET, "received invalid IKE header from %H - ignored",
479 packet->get_source(packet));
480 message->destroy(message);
481 return JOB_REQUEUE_DIRECT;
482 }
483
484 /* check IKE major version */
485 switch (message->get_major_version(message))
486 {
487 case IKEV2_MAJOR_VERSION:
488 #ifndef USE_IKEV2
489 if (message->get_exchange_type(message) == IKE_SA_INIT &&
490 message->get_request(message))
491 {
492 send_notify(message, IKEV1_MAJOR_VERSION, INFORMATIONAL_V1,
493 INVALID_MAJOR_VERSION, chunk_empty);
494 supported = FALSE;
495 }
496 #endif /* USE_IKEV2 */
497 break;
498 case IKEV1_MAJOR_VERSION:
499 #ifndef USE_IKEV1
500 if (message->get_exchange_type(message) == ID_PROT ||
501 message->get_exchange_type(message) == AGGRESSIVE)
502 {
503 send_notify(message, IKEV2_MAJOR_VERSION, INFORMATIONAL,
504 INVALID_MAJOR_VERSION, chunk_empty);
505 supported = FALSE;
506 }
507 #endif /* USE_IKEV1 */
508 break;
509 default:
510 #ifdef USE_IKEV2
511 send_notify(message, IKEV2_MAJOR_VERSION, INFORMATIONAL,
512 INVALID_MAJOR_VERSION, chunk_empty);
513 #endif /* USE_IKEV2 */
514 #ifdef USE_IKEV1
515 send_notify(message, IKEV1_MAJOR_VERSION, INFORMATIONAL_V1,
516 INVALID_MAJOR_VERSION, chunk_empty);
517 #endif /* USE_IKEV1 */
518 supported = FALSE;
519 break;
520 }
521 if (!supported)
522 {
523 DBG1(DBG_NET, "received unsupported IKE version %d.%d from %H, sending "
524 "INVALID_MAJOR_VERSION", message->get_major_version(message),
525 message->get_minor_version(message), packet->get_source(packet));
526 message->destroy(message);
527 return JOB_REQUEUE_DIRECT;
528 }
529 if (message->get_request(message) &&
530 message->get_exchange_type(message) == IKE_SA_INIT)
531 {
532 if (drop_ike_sa_init(this, message))
533 {
534 message->destroy(message);
535 return JOB_REQUEUE_DIRECT;
536 }
537 }
538 if (message->get_exchange_type(message) == ID_PROT ||
539 message->get_exchange_type(message) == AGGRESSIVE)
540 {
541 id = message->get_ike_sa_id(message);
542 if (id->get_responder_spi(id) == 0 &&
543 drop_ike_sa_init(this, message))
544 {
545 message->destroy(message);
546 return JOB_REQUEUE_DIRECT;
547 }
548 }
549
550 if (this->receive_delay)
551 {
552 if (this->receive_delay_type == 0 ||
553 this->receive_delay_type == message->get_exchange_type(message))
554 {
555 if ((message->get_request(message) && this->receive_delay_request) ||
556 (!message->get_request(message) && this->receive_delay_response))
557 {
558 DBG1(DBG_NET, "using receive delay: %dms",
559 this->receive_delay);
560 lib->scheduler->schedule_job_ms(lib->scheduler,
561 (job_t*)process_message_job_create(message),
562 this->receive_delay);
563 return JOB_REQUEUE_DIRECT;
564 }
565 }
566 }
567 lib->processor->queue_job(lib->processor,
568 (job_t*)process_message_job_create(message));
569 return JOB_REQUEUE_DIRECT;
570 }
571
572 METHOD(receiver_t, add_esp_cb, void,
573 private_receiver_t *this, receiver_esp_cb_t callback, void *data)
574 {
575 this->esp_cb_mutex->lock(this->esp_cb_mutex);
576 this->esp_cb.cb = callback;
577 this->esp_cb.data = data;
578 this->esp_cb_mutex->unlock(this->esp_cb_mutex);
579 }
580
581 METHOD(receiver_t, del_esp_cb, void,
582 private_receiver_t *this, receiver_esp_cb_t callback)
583 {
584 this->esp_cb_mutex->lock(this->esp_cb_mutex);
585 if (this->esp_cb.cb == callback)
586 {
587 this->esp_cb.cb = NULL;
588 this->esp_cb.data = NULL;
589 }
590 this->esp_cb_mutex->unlock(this->esp_cb_mutex);
591 }
592
593 METHOD(receiver_t, destroy, void,
594 private_receiver_t *this)
595 {
596 this->rng->destroy(this->rng);
597 this->hasher->destroy(this->hasher);
598 this->esp_cb_mutex->destroy(this->esp_cb_mutex);
599 free(this);
600 }
601
602 /*
603 * Described in header.
604 */
605 receiver_t *receiver_create()
606 {
607 private_receiver_t *this;
608 u_int32_t now = time_monotonic(NULL);
609
610 INIT(this,
611 .public = {
612 .add_esp_cb = _add_esp_cb,
613 .del_esp_cb = _del_esp_cb,
614 .destroy = _destroy,
615 },
616 .esp_cb_mutex = mutex_create(MUTEX_TYPE_DEFAULT),
617 .secret_switch = now,
618 .secret_offset = random() % now,
619 );
620
621 if (lib->settings->get_bool(lib->settings,
622 "%s.dos_protection", TRUE, charon->name))
623 {
624 this->cookie_threshold = lib->settings->get_int(lib->settings,
625 "%s.cookie_threshold", COOKIE_THRESHOLD_DEFAULT, charon->name);
626 this->block_threshold = lib->settings->get_int(lib->settings,
627 "%s.block_threshold", BLOCK_THRESHOLD_DEFAULT, charon->name);
628 }
629 this->init_limit_job_load = lib->settings->get_int(lib->settings,
630 "%s.init_limit_job_load", 0, charon->name);
631 this->init_limit_half_open = lib->settings->get_int(lib->settings,
632 "%s.init_limit_half_open", 0, charon->name);
633 this->receive_delay = lib->settings->get_int(lib->settings,
634 "%s.receive_delay", 0, charon->name);
635 this->receive_delay_type = lib->settings->get_int(lib->settings,
636 "%s.receive_delay_type", 0, charon->name),
637 this->receive_delay_request = lib->settings->get_bool(lib->settings,
638 "%s.receive_delay_request", TRUE, charon->name),
639 this->receive_delay_response = lib->settings->get_bool(lib->settings,
640 "%s.receive_delay_response", TRUE, charon->name),
641
642 this->hasher = lib->crypto->create_hasher(lib->crypto, HASH_PREFERRED);
643 if (!this->hasher)
644 {
645 DBG1(DBG_NET, "creating cookie hasher failed, no hashers supported");
646 free(this);
647 return NULL;
648 }
649 this->rng = lib->crypto->create_rng(lib->crypto, RNG_STRONG);
650 if (!this->rng)
651 {
652 DBG1(DBG_NET, "creating cookie RNG failed, no RNG supported");
653 this->hasher->destroy(this->hasher);
654 free(this);
655 return NULL;
656 }
657 if (!this->rng->get_bytes(this->rng, SECRET_LENGTH, this->secret))
658 {
659 DBG1(DBG_NET, "creating cookie secret failed");
660 destroy(this);
661 return NULL;
662 }
663 memcpy(this->secret_old, this->secret, SECRET_LENGTH);
664
665 lib->processor->queue_job(lib->processor,
666 (job_t*)callback_job_create_with_prio((callback_job_cb_t)receive_packets,
667 this, NULL, (callback_job_cancel_t)return_false, JOB_PRIO_CRITICAL));
668
669 return &this->public;
670 }
671