fde3e47c0845ed064517a5fa85751197c63c4cc2
[strongswan.git] / src / pluto / connections.c
1 /* information about connections between hosts and clients
2 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
3 * Copyright (C) 2009 Andreas Steffen - Hochschule fuer Technik Rapperswil
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 #include <string.h>
17 #include <stdio.h>
18 #include <stddef.h>
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <netinet/in.h>
22 #include <sys/socket.h>
23 #include <sys/stat.h>
24 #include <netinet/in.h>
25 #include <arpa/inet.h>
26 #include <resolv.h>
27 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
28 #include <sys/queue.h>
29
30 #include <freeswan.h>
31 #include "kameipsec.h"
32
33 #include <hydra.h>
34 #include <credentials/certificates/ac.h>
35 #include <credentials/keys/private_key.h>
36
37 #include "constants.h"
38 #include "defs.h"
39 #include "myid.h"
40 #include "x509.h"
41 #include "ca.h"
42 #include "crl.h"
43 #include "certs.h"
44 #include "ac.h"
45 #include "smartcard.h"
46 #include "fetch.h"
47 #include "connections.h"
48 #include "foodgroups.h"
49 #include "demux.h"
50 #include "state.h"
51 #include "timer.h"
52 #include "ipsec_doi.h" /* needs demux.h and state.h */
53 #include "server.h"
54 #include "kernel.h"
55 #include "log.h"
56 #include "keys.h"
57 #include "adns.h" /* needs <resolv.h> */
58 #include "dnskey.h" /* needs keys.h and adns.h */
59 #include "whack.h"
60 #include "alg_info.h"
61 #include "ike_alg.h"
62 #include "kernel_alg.h"
63 #include "nat_traversal.h"
64 #include "virtual.h"
65 #include "whack_attribute.h"
66 #include "modecfg.h"
67
68 static void flush_pending_by_connection(connection_t *c); /* forward */
69
70 static connection_t *connections = NULL;
71
72 /* struct host_pair: a nexus of information about a pair of hosts.
73 * A host is an IP address, UDP port pair. This is a debatable choice:
74 * - should port be considered (no choice of port in standard)?
75 * - should ID be considered (hard because not always known)?
76 * - should IP address matter on our end (we don't know our end)?
77 * Only oriented connections are registered.
78 * Unoriented connections are kept on the unoriented_connections
79 * linked list (using hp_next). For them, host_pair is NULL.
80 */
81
82 struct host_pair {
83 struct {
84 ip_address addr;
85 u_int16_t port; /* host order */
86 } me, him;
87 bool initial_connection_sent;
88 connection_t *connections; /* connections with this pair */
89 struct pending *pending; /* awaiting Keying Channel */
90 struct host_pair *next;
91 };
92
93 static struct host_pair *host_pairs = NULL;
94
95 static connection_t *unoriented_connections = NULL;
96
97 /**
98 * Check if an id was instantiated by assigning to it the current IP address
99 */
100 bool his_id_was_instantiated(const connection_t *c)
101 {
102 if (c->kind != CK_INSTANCE)
103 {
104 return FALSE;
105 }
106 if (id_is_ipaddr(c->spd.that.id))
107 {
108 identification_t *host;
109 bool equal;
110
111 host = identification_create_from_sockaddr((sockaddr_t*)&c->spd.that.host_addr);
112 equal = host->equals(host, c->spd.that.id);
113 host->destroy(host);
114 return equal;
115 }
116 else
117 {
118 return TRUE;
119 }
120 }
121
122 /**
123 * Check to see that IDs of peers match
124 */
125 bool same_peer_ids(const connection_t *c, const connection_t *d,
126 identification_t *his_id)
127 {
128 return d->spd.this.id->equals(d->spd.this.id, c->spd.this.id) &&
129 d->spd.that.id->equals(d->spd.that.id,
130 his_id ? his_id : c->spd.that.id);
131 }
132
133 static struct host_pair *find_host_pair(const ip_address *myaddr,
134 u_int16_t myport,
135 const ip_address *hisaddr,
136 u_int16_t hisport)
137 {
138 struct host_pair *p, *prev;
139
140 /* default hisaddr to an appropriate any */
141 if (hisaddr == NULL)
142 hisaddr = aftoinfo(addrtypeof(myaddr))->any;
143
144 if (nat_traversal_enabled)
145 {
146 /**
147 * port is not relevant in host_pair. with nat_traversal we
148 * always use pluto_port (500)
149 */
150 myport = pluto_port;
151 hisport = pluto_port;
152 }
153
154 for (prev = NULL, p = host_pairs; p != NULL; prev = p, p = p->next)
155 {
156 if (sameaddr(&p->me.addr, myaddr) && p->me.port == myport
157 && sameaddr(&p->him.addr, hisaddr) && p->him.port == hisport)
158 {
159 if (prev)
160 {
161 prev->next = p->next; /* remove p from list */
162 p->next = host_pairs; /* and stick it on front */
163 host_pairs = p;
164 }
165 break;
166 }
167 }
168 return p;
169 }
170
171 /* find head of list of connections with this pair of hosts */
172 static connection_t *find_host_pair_connections(const ip_address *myaddr,
173 u_int16_t myport,
174 const ip_address *hisaddr,
175 u_int16_t hisport)
176 {
177 struct host_pair *hp = find_host_pair(myaddr, myport, hisaddr, hisport);
178
179 if (nat_traversal_enabled && hp && hisaddr)
180 {
181 connection_t *c;
182
183 for (c = hp->connections; c != NULL; c = c->hp_next)
184 {
185 if (c->spd.this.host_port == myport && c->spd.that.host_port == hisport)
186 return c;
187 }
188 return NULL;
189 }
190 return hp == NULL? NULL : hp->connections;
191 }
192
193 static void connect_to_host_pair(connection_t *c)
194 {
195 if (oriented(*c))
196 {
197 struct host_pair *hp;
198
199 ip_address his_addr = (c->spd.that.allow_any)
200 ? *aftoinfo(addrtypeof(&c->spd.that.host_addr))->any
201 : c->spd.that.host_addr;
202
203 hp = find_host_pair(&c->spd.this.host_addr, c->spd.this.host_port
204 , &his_addr, c->spd.that.host_port);
205
206 if (hp == NULL)
207 {
208 /* no suitable host_pair -- build one */
209 hp = malloc_thing(struct host_pair);
210 hp->me.addr = c->spd.this.host_addr;
211 hp->him.addr = his_addr;
212 hp->me.port = nat_traversal_enabled ? pluto_port : c->spd.this.host_port;
213 hp->him.port = nat_traversal_enabled ? pluto_port : c->spd.that.host_port;
214 hp->initial_connection_sent = FALSE;
215 hp->connections = NULL;
216 hp->pending = NULL;
217 hp->next = host_pairs;
218 host_pairs = hp;
219 }
220 c->host_pair = hp;
221 c->hp_next = hp->connections;
222 hp->connections = c;
223 }
224 else
225 {
226 /* since this connection isn't oriented, we place it
227 * in the unoriented_connections list instead.
228 */
229 c->host_pair = NULL;
230 c->hp_next = unoriented_connections;
231 unoriented_connections = c;
232 }
233 }
234
235 /* find a connection by name.
236 * If strict, don't accept a CK_INSTANCE.
237 * Move the winner (if any) to the front.
238 * If none is found, and strict, a diagnostic is logged to whack.
239 */
240 connection_t *con_by_name(const char *nm, bool strict)
241 {
242 connection_t *p, *prev;
243
244 for (prev = NULL, p = connections; ; prev = p, p = p->ac_next)
245 {
246 if (p == NULL)
247 {
248 if (strict)
249 whack_log(RC_UNKNOWN_NAME
250 , "no connection named \"%s\"", nm);
251 break;
252 }
253 if (streq(p->name, nm)
254 && (!strict || p->kind != CK_INSTANCE))
255 {
256 if (prev)
257 {
258 prev->ac_next = p->ac_next; /* remove p from list */
259 p->ac_next = connections; /* and stick it on front */
260 connections = p;
261 }
262 break;
263 }
264 }
265 return p;
266 }
267
268 void release_connection(connection_t *c, bool relations)
269 {
270 if (c->kind == CK_INSTANCE)
271 {
272 /* This does everything we need.
273 * Note that we will be called recursively by delete_connection,
274 * but kind will be CK_GOING_AWAY.
275 */
276 delete_connection(c, relations);
277 }
278 else
279 {
280 flush_pending_by_connection(c);
281 delete_states_by_connection(c, relations);
282 unroute_connection(c);
283 }
284 }
285
286 /* Delete a connection */
287
288 #define list_rm(etype, enext, e, ehead) { \
289 etype **ep; \
290 for (ep = &(ehead); *ep != (e); ep = &(*ep)->enext) \
291 passert(*ep != NULL); /* we must not come up empty-handed */ \
292 *ep = (e)->enext; \
293 }
294
295
296 void delete_connection(connection_t *c, bool relations)
297 {
298 modecfg_attribute_t *ca;
299 connection_t *old_cur_connection;
300
301 old_cur_connection = cur_connection == c? NULL : cur_connection;
302 #ifdef DEBUG
303 lset_t old_cur_debugging = cur_debugging;
304 #endif
305
306 set_cur_connection(c);
307
308 /* Must be careful to avoid circularity:
309 * we mark c as going away so it won't get deleted recursively.
310 */
311 passert(c->kind != CK_GOING_AWAY);
312 if (c->kind == CK_INSTANCE)
313 {
314 plog("deleting connection \"%s\" instance with peer %s {isakmp=#%lu/ipsec=#%lu}"
315 , c->name
316 , ip_str(&c->spd.that.host_addr)
317 , c->newest_isakmp_sa, c->newest_ipsec_sa);
318 c->kind = CK_GOING_AWAY;
319 }
320 else
321 {
322 plog("deleting connection");
323 }
324 release_connection(c, relations); /* won't delete c */
325
326 if (c->kind == CK_GROUP)
327 {
328 delete_group(c);
329 }
330
331 /* free up any logging resources */
332 perpeer_logfree(c);
333
334 /* find and delete c from connections list */
335 list_rm(connection_t, ac_next, c, connections);
336 cur_connection = old_cur_connection;
337
338 /* find and delete c from the host pair list */
339 if (c->host_pair == NULL)
340 {
341 if (c->ikev1)
342 {
343 list_rm(connection_t, hp_next, c, unoriented_connections);
344 }
345 }
346 else
347 {
348 struct host_pair *hp = c->host_pair;
349
350 list_rm(connection_t, hp_next, c, hp->connections);
351 c->host_pair = NULL; /* redundant, but safe */
352
353 /* if there are no more connections with this host_pair
354 * and we haven't even made an initial contact, let's delete
355 * this guy in case we were created by an attempted DOS attack.
356 */
357 if (hp->connections == NULL
358 && !hp->initial_connection_sent)
359 {
360 passert(hp->pending == NULL); /* ??? must deal with this! */
361 list_rm(struct host_pair, next, hp, host_pairs);
362 free(hp);
363 }
364 }
365 if (c->kind != CK_GOING_AWAY)
366 {
367 free(c->spd.that.virt);
368 }
369
370 /* release virtual IP address lease if any */
371 if (c->spd.that.modecfg && c->spd.that.pool &&
372 !c->spd.that.host_srcip->is_anyaddr(c->spd.that.host_srcip))
373 {
374 hydra->attributes->release_address(hydra->attributes, c->spd.that.pool,
375 c->spd.that.host_srcip, c->spd.that.id);
376 }
377
378 /* release requested attributes if any */
379 if (c->requested)
380 {
381 c->requested->destroy_function(c->requested,
382 (void*)modecfg_attribute_destroy);
383 }
384
385 /* release other attributes if any */
386 if (c->attributes)
387 {
388 while (c->attributes->remove_last(c->attributes, (void **)&ca) == SUCCESS)
389 {
390 hydra->attributes->release(hydra->attributes, ca->handler,
391 c->spd.that.id, ca->type, ca->value);
392 modecfg_attribute_destroy(ca);
393 }
394 c->attributes->destroy(c->attributes);
395 }
396
397 if (c->kind != CK_GOING_AWAY)
398 {
399 whack_attr->del_pool(whack_attr, c->name);
400 }
401
402 /* free internal data */
403 #ifdef DEBUG
404 cur_debugging = old_cur_debugging;
405 #endif
406 free(c->name);
407 DESTROY_IF(c->xauth_identity);
408 DESTROY_IF(c->spd.this.id);
409 DESTROY_IF(c->spd.this.ca);
410 DESTROY_IF(c->spd.this.groups);
411 DESTROY_IF(c->spd.this.host_srcip);
412 free(c->spd.this.updown);
413 free(c->spd.this.pool);
414 DESTROY_IF(c->spd.that.id);
415 DESTROY_IF(c->spd.that.ca);
416 DESTROY_IF(c->spd.that.groups);
417 DESTROY_IF(c->spd.that.host_srcip);
418 free(c->spd.that.updown);
419 free(c->spd.that.pool);
420 if (c->requested_ca)
421 {
422 c->requested_ca->destroy_offset(c->requested_ca,
423 offsetof(identification_t, destroy));
424 }
425 gw_delref(&c->gw_info);
426
427 lock_certs_and_keys("delete_connection");
428 cert_release(c->spd.this.cert);
429 scx_release(c->spd.this.sc);
430 cert_release(c->spd.that.cert);
431 scx_release(c->spd.that.sc);
432 unlock_certs_and_keys("delete_connection");
433
434 alg_info_delref((struct alg_info **)&c->alg_info_esp);
435 alg_info_delref((struct alg_info **)&c->alg_info_ike);
436
437 free(c);
438 }
439
440 /* Delete connections with the specified name */
441 void delete_connections_by_name(const char *name, bool strict)
442 {
443 connection_t *c = con_by_name(name, strict);
444
445 for (; c != NULL; c = con_by_name(name, FALSE))
446 delete_connection(c, FALSE);
447 }
448
449 void delete_every_connection(void)
450 {
451 while (connections)
452 {
453 delete_connection(connections, TRUE);
454 }
455 }
456
457 void release_dead_interfaces(void)
458 {
459 struct host_pair *hp;
460
461 for (hp = host_pairs; hp != NULL; hp = hp->next)
462 {
463 connection_t **pp
464 , *p;
465
466 for (pp = &hp->connections; (p = *pp) != NULL; )
467 {
468 if (p->interface->change == IFN_DELETE)
469 {
470 /* this connection's interface is going away */
471 enum connection_kind k = p->kind;
472
473 release_connection(p, TRUE);
474
475 if (k <= CK_PERMANENT)
476 {
477 /* The connection should have survived release:
478 * move it to the unoriented_connections list.
479 */
480 passert(p == *pp);
481
482 p->interface = NULL;
483
484 *pp = p->hp_next; /* advance *pp */
485 p->host_pair = NULL;
486 p->hp_next = unoriented_connections;
487 unoriented_connections = p;
488 }
489 else
490 {
491 /* The connection should have vanished,
492 * but the previous connection remains.
493 */
494 passert(p != *pp);
495 }
496 }
497 else
498 {
499 pp = &p->hp_next; /* advance pp */
500 }
501 }
502 }
503 }
504
505 /* adjust orientations of connections to reflect newly added interfaces */
506 void check_orientations(void)
507 {
508 /* try to orient all the unoriented connections */
509 {
510 connection_t *c = unoriented_connections;
511
512 unoriented_connections = NULL;
513
514 while (c)
515 {
516 connection_t *nxt = c->hp_next;
517
518 (void)orient(c);
519 connect_to_host_pair(c);
520 c = nxt;
521 }
522 }
523
524 /* Check that no oriented connection has become double-oriented.
525 * In other words, the far side must not match one of our new interfaces.
526 */
527 {
528 struct iface *i;
529
530 for (i = interfaces; i != NULL; i = i->next)
531 {
532 if (i->change == IFN_ADD)
533 {
534 struct host_pair *hp;
535
536 for (hp = host_pairs; hp != NULL; hp = hp->next)
537 {
538 if (sameaddr(&hp->him.addr, &i->addr)
539 && hp->him.port == pluto_port)
540 {
541 /* bad news: the whole chain of connections
542 * hanging off this host pair has both sides
543 * matching an interface.
544 * We'll get rid of them, using orient and
545 * connect_to_host_pair. But we'll be lazy
546 * and not ditch the host_pair itself (the
547 * cost of leaving it is slight and cannot
548 * be induced by a foe).
549 */
550 connection_t *c = hp->connections;
551
552 hp->connections = NULL;
553 while (c)
554 {
555 connection_t *nxt = c->hp_next;
556
557 c->interface = NULL;
558 (void)orient(c);
559 connect_to_host_pair(c);
560 c = nxt;
561 }
562 }
563 }
564 }
565 }
566 }
567 }
568
569 static err_t default_end(struct end *e, ip_address *dflt_nexthop)
570 {
571 err_t ugh = NULL;
572 int af = addrtypeof(&e->host_addr);
573
574 if (af != AF_INET && af != AF_INET6)
575 {
576 return "unknown address family in default_end";
577 }
578
579 /* default ID to IP (but only if not NO_IP -- WildCard) */
580 if (e->id->get_type(e->id) == ID_ANY && !isanyaddr(&e->host_addr))
581 {
582 e->id->destroy(e->id);
583 e->id = identification_create_from_sockaddr((sockaddr_t*)&e->host_addr);
584 e->has_id_wildcards = FALSE;
585 }
586
587 /* default nexthop to other side */
588 if (isanyaddr(&e->host_nexthop))
589 {
590 e->host_nexthop = *dflt_nexthop;
591 }
592
593 /* default client to subnet containing only self
594 * XXX This may mean that the client's address family doesn't match
595 * tunnel_addr_family.
596 */
597 if (!e->has_client)
598 {
599 ugh = addrtosubnet(&e->host_addr, &e->client);
600 }
601 return ugh;
602 }
603
604 /* Format the topology of a connection end, leaving out defaults.
605 * Largest left end looks like: client === host : port [ host_id ] --- hop
606 * Note: if that==NULL, skip nexthop
607 * Returns strlen of formated result (length excludes NUL at end).
608 */
609 size_t format_end(char *buf, size_t buf_len, const struct end *this,
610 const struct end *that, bool is_left, lset_t policy)
611 {
612 char client[BUF_LEN];
613 const char *client_sep = "";
614 char protoport[sizeof(":255/65535")];
615 const char *host = NULL;
616 char host_space[ADDRTOT_BUF];
617 char host_port[sizeof(":65535")];
618 char host_id[BUF_LEN + 2];
619 char hop[ADDRTOT_BUF];
620 const char *hop_sep = "";
621 const char *open_brackets = "";
622 const char *close_brackets = "";
623
624 if (isanyaddr(&this->host_addr))
625 {
626 switch (policy & (POLICY_GROUP | POLICY_OPPO))
627 {
628 case POLICY_GROUP:
629 host = "%group";
630 break;
631 case POLICY_OPPO:
632 host = "%opportunistic";
633 break;
634 case POLICY_GROUP | POLICY_OPPO:
635 host = "%opportunisticgroup";
636 break;
637 default:
638 host = "%any";
639 break;
640 }
641 }
642
643 client[0] = '\0';
644
645 if (is_virtual_end(this) && isanyaddr(&this->host_addr))
646 {
647 host = "%virtual";
648 }
649
650 /* [client===] */
651 if (this->has_client)
652 {
653 ip_address client_net, client_mask;
654
655 networkof(&this->client, &client_net);
656 maskof(&this->client, &client_mask);
657 client_sep = "===";
658
659 /* {client_subnet_wildcard} */
660 if (this->has_client_wildcard)
661 {
662 open_brackets = "{";
663 close_brackets = "}";
664 }
665
666 if (isanyaddr(&client_net) && isanyaddr(&client_mask)
667 && (policy & (POLICY_GROUP | POLICY_OPPO)))
668 {
669 client_sep = ""; /* boring case */
670 }
671 else if (subnetisnone(&this->client))
672 {
673 strcpy(client, "?");
674 }
675 else
676 {
677 subnettot(&this->client, 0, client, sizeof(client));
678 }
679 }
680 else if (this->modecfg && this->host_srcip->is_anyaddr(this->host_srcip))
681 {
682 /* we are mode config client, or a server with a pool */
683 client_sep = "===";
684 client[0] = '%';
685 strcpy(client+1, this->pool ? this->pool : "modecfg");
686 }
687
688 /* host */
689 if (host == NULL)
690 {
691 addrtot(&this->host_addr, 0, host_space, sizeof(host_space));
692 host = host_space;
693 }
694
695 host_port[0] = '\0';
696 if (this->host_port != IKE_UDP_PORT)
697 {
698 snprintf(host_port, sizeof(host_port), ":%u", this->host_port);
699 }
700
701 /* payload portocol and port */
702 protoport[0] = '\0';
703 if (this->has_port_wildcard)
704 {
705 snprintf(protoport, sizeof(protoport), ":%u/%%any", this->protocol);
706 }
707 else if (this->port || this->protocol)
708 {
709 snprintf(protoport, sizeof(protoport), ":%u/%u", this->protocol
710 , this->port);
711 }
712
713 /* id */
714 snprintf(host_id, sizeof(host_id), "[%Y]", this->id);
715
716 /* [---hop] */
717 hop[0] = '\0';
718 hop_sep = "";
719 if (that && !sameaddr(&this->host_nexthop, &that->host_addr))
720 {
721 addrtot(&this->host_nexthop, 0, hop, sizeof(hop));
722 hop_sep = "---";
723 }
724
725 if (is_left)
726 {
727 snprintf(buf, buf_len, "%s%s%s%s%s%s%s%s%s%s%s"
728 , open_brackets, client, close_brackets, client_sep
729 , this->allow_any? "%":""
730 , host, host_port, host_id, protoport
731 , hop_sep, hop);
732 }
733 else
734 {
735 snprintf(buf, buf_len, "%s%s%s%s%s%s%s%s%s%s%s"
736 , hop, hop_sep
737 , this->allow_any? "%":""
738 , host, host_port, host_id, protoport, client_sep
739 , open_brackets, client, close_brackets);
740 }
741 return strlen(buf);
742 }
743
744 /* format topology of a connection.
745 * Two symmetric ends separated by ...
746 */
747 #define CONNECTION_BUF (2 * (END_BUF - 1) + 4)
748
749 static size_t format_connection(char *buf, size_t buf_len,
750 const connection_t *c,
751 struct spd_route *sr)
752 {
753 size_t w = format_end(buf, buf_len, &sr->this, &sr->that, TRUE, LEMPTY);
754
755 w += snprintf(buf + w, buf_len - w, "...");
756 return w + format_end(buf + w, buf_len - w, &sr->that, &sr->this, FALSE, c->policy);
757 }
758
759 static void unshare_connection_strings(connection_t *c)
760 {
761 c->name = clone_str(c->name);
762 if (c->xauth_identity)
763 {
764 c->xauth_identity = c->xauth_identity->clone(c->xauth_identity);
765 }
766 c->spd.this.id = c->spd.this.id->clone(c->spd.this.id);
767 c->spd.this.pool = clone_str(c->spd.this.pool);
768 c->spd.this.updown = clone_str(c->spd.this.updown);
769 c->spd.this.host_srcip = c->spd.this.host_srcip->clone(c->spd.this.host_srcip);
770 scx_share(c->spd.this.sc);
771 cert_share(c->spd.this.cert);
772 if (c->spd.this.ca)
773 {
774 c->spd.this.ca = c->spd.this.ca->clone(c->spd.this.ca);
775 }
776 if (c->spd.this.groups)
777 {
778 c->spd.this.groups = c->spd.this.groups->get_ref(c->spd.this.groups);
779 }
780 c->spd.that.id = c->spd.that.id->clone(c->spd.that.id);
781 c->spd.that.pool = clone_str(c->spd.that.pool);
782 c->spd.that.updown = clone_str(c->spd.that.updown);
783 c->spd.that.host_srcip = c->spd.that.host_srcip->clone(c->spd.that.host_srcip);
784 scx_share(c->spd.that.sc);
785 cert_share(c->spd.that.cert);
786 if (c->spd.that.ca)
787 {
788 c->spd.that.ca = c->spd.that.ca->clone(c->spd.that.ca);
789 }
790 if (c->spd.that.groups)
791 {
792 c->spd.that.groups = c->spd.that.groups->get_ref(c->spd.that.groups);
793 }
794
795 /* increment references to algo's */
796 alg_info_addref((struct alg_info *)c->alg_info_esp);
797 alg_info_addref((struct alg_info *)c->alg_info_ike);
798 }
799
800 static void load_end_certificate(char *filename, struct end *dst)
801 {
802 time_t notBefore, notAfter;
803 cert_t *cert = NULL;
804 certificate_t *certificate;
805 bool cached_cert = FALSE;
806
807 /* initialize end certificate */
808 dst->cert = NULL;
809
810 /* initialize smartcard info record */
811 dst->sc = NULL;
812
813 if (filename)
814 {
815 if (scx_on_smartcard(filename))
816 {
817 /* load cert from smartcard */
818 cert = scx_load_cert(filename, &dst->sc, &cached_cert);
819 }
820 else
821 {
822 /* load cert from file */
823 cert = load_host_cert(filename);
824 }
825 }
826
827 if (cert)
828 {
829 certificate = cert->cert;
830
831 if (dst->id->get_type(dst->id) == ID_ANY ||
832 !certificate->has_subject(certificate, dst->id))
833 {
834 plog( " id '%Y' not confirmed by certificate, defaulting to '%Y'",
835 dst->id, certificate->get_subject(certificate));
836 dst->id->destroy(dst->id);
837 dst->id = certificate->get_subject(certificate);
838 dst->id = dst->id->clone(dst->id);
839 }
840
841 if (cached_cert)
842 {
843 dst->cert = cert;
844 }
845 else
846 {
847 if (!certificate->get_validity(certificate, NULL, &notBefore, &notAfter))
848 {
849 plog("certificate is invalid (valid from %T to %T)",
850 &notBefore, FALSE, &notAfter, FALSE);
851 cert_free(cert);
852 return;
853 }
854 DBG(DBG_CONTROL,
855 DBG_log("certificate is valid")
856 )
857 add_public_key_from_cert(cert, notAfter, DAL_LOCAL);
858 dst->cert = cert_add(cert);
859 }
860 certificate = dst->cert->cert;
861
862 /* if no CA is defined, use issuer as default */
863 if (dst->ca == NULL && certificate->get_type(certificate) == CERT_X509)
864 {
865 identification_t *issuer;
866
867 issuer = certificate->get_issuer(certificate);
868 dst->ca = issuer->clone(issuer);
869 }
870
871 /* cache the certificate that was last retrieved from the smartcard */
872 if (dst->sc)
873 {
874 if (!certificate->equals(certificate, dst->sc->last_cert->cert))
875 {
876 lock_certs_and_keys("load_end_certificates");
877 cert_release(dst->sc->last_cert);
878 dst->sc->last_cert = dst->cert;
879 cert_share(dst->cert);
880 unlock_certs_and_keys("load_end_certificates");
881 }
882 time(&dst->sc->last_load);
883 }
884 }
885 scx_share(dst->sc);
886 cert_share(dst->cert);
887 }
888
889 static bool extract_end(struct end *dst, const whack_end_t *src,
890 const char *name, bool is_left)
891 {
892 bool same_ca = FALSE;
893
894 dst->is_left = is_left;
895 dst->id = identification_create_from_string(src->id);
896 dst->ca = NULL;
897
898 /* decode CA distinguished name, if any */
899 if (src->ca)
900 {
901 if streq(src->ca, "%same")
902 {
903 same_ca = TRUE;
904 }
905 else if (!streq(src->ca, "%any"))
906 {
907 dst->ca = identification_create_from_string(src->ca);
908 if (dst->ca->get_type(dst->ca) != ID_DER_ASN1_DN)
909 {
910 plog("bad CA string '%s', ignored", src->ca);
911 dst->ca->destroy(dst->ca);
912 dst->ca = NULL;
913 }
914 }
915 }
916
917 /* load local end certificate and extract ID, if any */
918 load_end_certificate(src->cert, dst);
919
920 /* does id has wildcards? */
921 dst->has_id_wildcards = dst->id->contains_wildcards(dst->id);
922
923 /* decode group attributes, if any */
924 if (src->groups)
925 {
926 dst->groups = ietf_attributes_create_from_string(src->groups);
927 }
928
929 /* the rest is simple copying of corresponding fields */
930 dst->host_addr = src->host_addr;
931 dst->host_nexthop = src->host_nexthop;
932 dst->host_srcip = host_create_from_sockaddr((sockaddr_t*)&src->host_srcip);
933 dst->has_natip = src->has_natip;
934 dst->client = src->client;
935 dst->protocol = src->protocol;
936 dst->port = src->port;
937 dst->has_port_wildcard = src->has_port_wildcard;
938 dst->key_from_DNS_on_demand = src->key_from_DNS_on_demand;
939 dst->has_client = src->has_client;
940 dst->has_client_wildcard = src->has_client_wildcard;
941 dst->modecfg = src->modecfg;
942 dst->hostaccess = src->hostaccess;
943 dst->allow_any = src->allow_any;
944 dst->sendcert = src->sendcert;
945 dst->updown = clone_str(src->updown);
946 dst->host_port = src->host_port;
947
948 /* if the sourceip netmask is zero a named pool exists */
949 if (src->sourceip_mask == 0)
950 {
951 dst->pool = clone_str(src->sourceip);
952 }
953
954 /* if host sourceip is defined but no client is present
955 * behind the host then set client to sourceip/32
956 */
957 if (!dst->host_srcip->is_anyaddr(dst->host_srcip) &&
958 !dst->has_natip && !dst->has_client)
959 {
960 ip_address addr;
961 err_t ugh;
962
963 addr = *(ip_address*)dst->host_srcip->get_sockaddr(dst->host_srcip);
964 ugh = addrtosubnet(&addr, &dst->client);
965
966 if (ugh)
967 {
968 plog("could not assign host sourceip to client subnet");
969 }
970 else
971 {
972 dst->has_client = TRUE;
973 }
974 }
975 return same_ca;
976 }
977
978 static bool check_connection_end(const whack_end_t *this,
979 const whack_end_t *that,
980 const whack_message_t *wm)
981 {
982 if (wm->addr_family != addrtypeof(&this->host_addr)
983 || wm->addr_family != addrtypeof(&this->host_nexthop)
984 || (this->has_client? wm->tunnel_addr_family : wm->addr_family)
985 != subnettypeof(&this->client)
986 || subnettypeof(&this->client) != subnettypeof(&that->client))
987 {
988 /* this should have been diagnosed by whack, so we need not be clear
989 * !!! overloaded use of RC_CLASH
990 */
991 loglog(RC_CLASH, "address family inconsistency in connection");
992 return FALSE;
993 }
994
995 if (isanyaddr(&that->host_addr))
996 {
997 /* other side is wildcard: we must check if other conditions met */
998 if (isanyaddr(&this->host_addr))
999 {
1000 loglog(RC_ORIENT, "connection must specify host IP address for our side");
1001 return FALSE;
1002 }
1003 }
1004
1005 if (this->virt && (!isanyaddr(&this->host_addr) || this->has_client))
1006 {
1007 loglog(RC_CLASH,
1008 "virtual IP must only be used with %%any and without client");
1009 return FALSE;
1010 }
1011
1012 return TRUE; /* happy */
1013 }
1014
1015 connection_t *find_connection_by_reqid(uint32_t reqid)
1016 {
1017 connection_t *c;
1018
1019 reqid &= ~3;
1020 for (c = connections; c != NULL; c = c->ac_next)
1021 {
1022 if (c->spd.reqid == reqid)
1023 {
1024 return c;
1025 }
1026 }
1027
1028 return NULL;
1029 }
1030
1031 static uint32_t gen_reqid(void)
1032 {
1033 uint32_t start;
1034 static uint32_t reqid = IPSEC_MANUAL_REQID_MAX & ~3;
1035
1036 start = reqid;
1037 do {
1038 reqid += 4;
1039 if (reqid == 0)
1040 {
1041 reqid = (IPSEC_MANUAL_REQID_MAX & ~3) + 4;
1042 }
1043 if (!find_connection_by_reqid(reqid))
1044 {
1045 return reqid;
1046 }
1047 } while (reqid != start);
1048
1049 exit_log("unable to allocate reqid");
1050 return 0; /* never reached ... */
1051 }
1052
1053 void add_connection(const whack_message_t *wm)
1054 {
1055 if (con_by_name(wm->name, FALSE) != NULL)
1056 {
1057 loglog(RC_DUPNAME, "attempt to redefine connection \"%s\"", wm->name);
1058 }
1059 else if (wm->right.protocol != wm->left.protocol)
1060 {
1061 /* this should haven been diagnosed by whack
1062 * !!! overloaded use of RC_CLASH
1063 */
1064 loglog(RC_CLASH, "the protocol must be the same for leftport and rightport");
1065 }
1066 else if (check_connection_end(&wm->right, &wm->left, wm)
1067 && check_connection_end(&wm->left, &wm->right, wm))
1068 {
1069 bool same_rightca, same_leftca;
1070 connection_t *c = malloc_thing(connection_t);
1071
1072 zero(c);
1073 c->name = clone_str(wm->name);
1074 c->ikev1 = wm->ikev1;
1075 c->policy = wm->policy;
1076
1077 if ((c->policy & POLICY_COMPRESS) && !can_do_IPcomp)
1078 {
1079 loglog(RC_COMMENT
1080 , "ignoring --compress in \"%s\" because kernel does not support IPCOMP"
1081 , c->name);
1082 }
1083
1084 if (wm->esp)
1085 {
1086 DBG(DBG_CONTROL,
1087 DBG_log("from whack: got --esp=%s", wm->esp ? wm->esp: "NULL")
1088 )
1089 c->alg_info_esp = alg_info_esp_create_from_str(wm->esp? wm->esp : "");
1090
1091 DBG(DBG_CRYPT|DBG_CONTROL,
1092 static char buf[BUF_LEN]="<NULL>";
1093
1094 if (c->alg_info_esp)
1095 {
1096 alg_info_snprint(buf, sizeof(buf)
1097 ,(struct alg_info *)c->alg_info_esp);
1098 }
1099 DBG_log("esp proposal: %s", buf);
1100 )
1101 if (c->alg_info_esp)
1102 {
1103 if (c->alg_info_esp->alg_info_cnt == 0)
1104 {
1105 loglog(RC_LOG_SERIOUS, "got 0 esp transforms");
1106 }
1107 }
1108 else
1109 {
1110 loglog(RC_LOG_SERIOUS, "syntax error in esp string");
1111 }
1112 }
1113
1114 if (wm->ike)
1115 {
1116 DBG(DBG_CONTROL,
1117 DBG_log("from whack: got --ike=%s", wm->ike ? wm->ike: "NULL")
1118 )
1119 c->alg_info_ike= alg_info_ike_create_from_str(wm->ike? wm->ike : "");
1120
1121 DBG(DBG_CRYPT|DBG_CONTROL,
1122 static char buf[BUF_LEN]="<NULL>";
1123
1124 if (c->alg_info_ike)
1125 {
1126 alg_info_snprint(buf, sizeof(buf)
1127 , (struct alg_info *)c->alg_info_ike);
1128 }
1129 DBG_log("ike proposal: %s", buf);
1130 )
1131 if (c->alg_info_ike)
1132 {
1133 if (c->alg_info_ike->alg_info_cnt == 0)
1134 {
1135 loglog(RC_LOG_SERIOUS, "got 0 ike transforms");
1136 }
1137 }
1138 else
1139 {
1140 loglog(RC_LOG_SERIOUS, "syntax error in ike string");
1141 }
1142 }
1143
1144 if (wm->xauth_identity)
1145 {
1146 c->xauth_identity
1147 = identification_create_from_string(wm->xauth_identity);
1148 }
1149
1150 c->sa_ike_life_seconds = wm->sa_ike_life_seconds;
1151 c->sa_ipsec_life_seconds = wm->sa_ipsec_life_seconds;
1152 c->sa_rekey_margin = wm->sa_rekey_margin;
1153 c->sa_rekey_fuzz = wm->sa_rekey_fuzz;
1154 c->sa_keying_tries = wm->sa_keying_tries;
1155
1156 /* RFC 3706 DPD */
1157 c->dpd_delay = wm->dpd_delay;
1158 c->dpd_timeout = wm->dpd_timeout;
1159 c->dpd_action = wm->dpd_action;
1160
1161 c->addr_family = wm->addr_family;
1162 c->tunnel_addr_family = wm->tunnel_addr_family;
1163
1164 c->requested_ca = NULL;
1165 same_leftca = extract_end(&c->spd.this, &wm->left, wm->name, TRUE);
1166 same_rightca = extract_end(&c->spd.that, &wm->right, wm->name, FALSE);
1167
1168 if (same_rightca && c->spd.this.ca)
1169 {
1170 c->spd.that.ca = c->spd.this.ca->clone(c->spd.this.ca);
1171 }
1172 else if (same_leftca && c->spd.that.ca)
1173 {
1174 c->spd.this.ca = c->spd.that.ca->clone(c->spd.that.ca);
1175 }
1176
1177 default_end(&c->spd.this, &c->spd.that.host_addr);
1178 default_end(&c->spd.that, &c->spd.this.host_addr);
1179
1180 /* force any wildcard host IP address, any wildcard subnet
1181 * or any wildcard ID to that end
1182 */
1183 if (isanyaddr(&c->spd.this.host_addr) || c->spd.this.has_client_wildcard
1184 || c->spd.this.has_port_wildcard || c->spd.this.has_id_wildcards
1185 || c->spd.this.allow_any)
1186 {
1187 struct end t = c->spd.this;
1188
1189 c->spd.this = c->spd.that;
1190 c->spd.that = t;
1191 }
1192
1193 c->spd.next = NULL;
1194 c->spd.reqid = gen_reqid();
1195
1196 c->spd.mark_in.value = wm->mark_in.value;
1197 c->spd.mark_in.mask = wm->mark_in.mask;
1198 c->spd.mark_out.value = wm->mark_out.value;
1199 c->spd.mark_out.mask = wm->mark_out.mask;
1200
1201 /* set internal fields */
1202 c->instance_serial = 0;
1203 c->ac_next = connections;
1204 connections = c;
1205 c->interface = NULL;
1206 c->spd.routing = RT_UNROUTED;
1207 c->newest_isakmp_sa = SOS_NOBODY;
1208 c->newest_ipsec_sa = SOS_NOBODY;
1209 c->spd.eroute_owner = SOS_NOBODY;
1210
1211 if (c->policy & POLICY_GROUP)
1212 {
1213 c->kind = CK_GROUP;
1214 add_group(c);
1215 }
1216 else if ((isanyaddr(&c->spd.that.host_addr) && !NEVER_NEGOTIATE(c->policy))
1217 || c->spd.that.has_client_wildcard || c->spd.that.has_port_wildcard
1218 || c->spd.that.has_id_wildcards || c->spd.that.allow_any)
1219 {
1220 /* Opportunistic or Road Warrior or wildcard client subnet
1221 * or wildcard ID */
1222 c->kind = CK_TEMPLATE;
1223 }
1224 else
1225 {
1226 c->kind = CK_PERMANENT;
1227 }
1228 set_policy_prio(c); /* must be after kind is set */
1229
1230 #ifdef DEBUG
1231 c->extra_debugging = wm->debugging;
1232 #endif
1233
1234 c->gw_info = NULL;
1235
1236 passert(!(wm->left.virt && wm->right.virt));
1237 if (wm->left.virt || wm->right.virt)
1238 {
1239 passert(isanyaddr(&c->spd.that.host_addr));
1240 c->spd.that.virt = create_virtual(c,
1241 wm->left.virt ? wm->left.virt : wm->right.virt);
1242 if (c->spd.that.virt)
1243 c->spd.that.has_client = TRUE;
1244 }
1245
1246 (void)orient(c);
1247
1248 /* if rightsourceip defines a subnet then create an in-memory pool */
1249 if (whack_attr->add_pool(whack_attr, c->name,
1250 c->spd.this.is_left ? &wm->right : &wm->left))
1251 {
1252 c->spd.that.pool = clone_str(c->name);
1253 c->spd.that.modecfg = TRUE;
1254 c->spd.that.has_client = FALSE;
1255 /* reset the host_srcip so that it gets assigned in modecfg */
1256 DESTROY_IF(c->spd.that.host_srcip);
1257 c->spd.that.host_srcip = host_create_any(AF_INET);
1258 }
1259
1260 if (c->ikev1)
1261 {
1262 connect_to_host_pair(c);
1263 }
1264
1265 /* log all about this connection */
1266 plog("added connection description \"%s\"", c->name);
1267 DBG(DBG_CONTROL,
1268 char topo[BUF_LEN];
1269
1270 (void) format_connection(topo, sizeof(topo), c, &c->spd);
1271
1272 DBG_log("%s", topo);
1273
1274 /* Make sure that address families can be correctly inferred
1275 * from printed ends.
1276 */
1277 passert(c->addr_family == addrtypeof(&c->spd.this.host_addr)
1278 && c->addr_family == addrtypeof(&c->spd.this.host_nexthop)
1279 && (c->spd.this.has_client? c->tunnel_addr_family : c->addr_family)
1280 == subnettypeof(&c->spd.this.client)
1281
1282 && c->addr_family == addrtypeof(&c->spd.that.host_addr)
1283 && c->addr_family == addrtypeof(&c->spd.that.host_nexthop)
1284 && (c->spd.that.has_client? c->tunnel_addr_family : c->addr_family)
1285 == subnettypeof(&c->spd.that.client));
1286
1287 DBG_log("ike_life: %lus; ipsec_life: %lus; rekey_margin: %lus;"
1288 " rekey_fuzz: %lu%%; keyingtries: %lu; policy: %s"
1289 , (unsigned long) c->sa_ike_life_seconds
1290 , (unsigned long) c->sa_ipsec_life_seconds
1291 , (unsigned long) c->sa_rekey_margin
1292 , (unsigned long) c->sa_rekey_fuzz
1293 , (unsigned long) c->sa_keying_tries
1294 , prettypolicy(c->policy));
1295 );
1296 }
1297 }
1298
1299 /* Derive a template connection from a group connection and target.
1300 * Similar to instantiate(). Happens at whack --listen.
1301 * Returns name of new connection. May be NULL.
1302 * Caller is responsible for freeing.
1303 */
1304 char *add_group_instance(connection_t *group, const ip_subnet *target)
1305 {
1306 char namebuf[100], targetbuf[SUBNETTOT_BUF];
1307 connection_t *t;
1308 char *name = NULL;
1309
1310 passert(group->kind == CK_GROUP);
1311 passert(oriented(*group));
1312
1313 /* manufacture a unique name for this template */
1314 subnettot(target, 0, targetbuf, sizeof(targetbuf));
1315 snprintf(namebuf, sizeof(namebuf), "%s#%s", group->name, targetbuf);
1316
1317 if (con_by_name(namebuf, FALSE) != NULL)
1318 {
1319 loglog(RC_DUPNAME, "group name + target yields duplicate name \"%s\""
1320 , namebuf);
1321 }
1322 else
1323 {
1324 t = clone_thing(*group);
1325 t->name = namebuf;
1326 unshare_connection_strings(t);
1327 name = clone_str(t->name);
1328 t->spd.that.client = *target;
1329 t->policy &= ~(POLICY_GROUP | POLICY_GROUTED);
1330 t->kind = isanyaddr(&t->spd.that.host_addr) && !NEVER_NEGOTIATE(t->policy)
1331 ? CK_TEMPLATE : CK_INSTANCE;
1332
1333 /* reset log file info */
1334 t->log_file_name = NULL;
1335 t->log_file = NULL;
1336 t->log_file_err = FALSE;
1337
1338 t->spd.reqid = gen_reqid();
1339
1340 if (t->spd.that.virt)
1341 {
1342 DBG_log("virtual_ip not supported in group instance");
1343 t->spd.that.virt = NULL;
1344 }
1345
1346 /* add to connections list */
1347 t->ac_next = connections;
1348 connections = t;
1349
1350 /* same host_pair as parent: stick after parent on list */
1351 group->hp_next = t;
1352
1353 /* route if group is routed */
1354 if (group->policy & POLICY_GROUTED)
1355 {
1356 if (!trap_connection(t))
1357 whack_log(RC_ROUTE, "could not route");
1358 }
1359 }
1360 return name;
1361 }
1362
1363 /* an old target has disappeared for a group: delete instance */
1364 void remove_group_instance(const connection_t *group USED_BY_DEBUG,
1365 const char *name)
1366 {
1367 passert(group->kind == CK_GROUP);
1368 passert(oriented(*group));
1369
1370 delete_connections_by_name(name, FALSE);
1371 }
1372
1373 /* Common part of instantiating a Road Warrior or Opportunistic connection.
1374 * his_id can be used to carry over an ID discovered in Phase 1.
1375 * It must not disagree with the one in c, but if that is unspecified,
1376 * the new connection will use his_id.
1377 * If his_id is NULL, and c.that.id is uninstantiated (ID_ANY), the
1378 * new connection will continue to have an uninstantiated that.id.
1379 * Note: instantiation does not affect port numbers.
1380 *
1381 * Note that instantiate can only deal with a single SPD/eroute.
1382 */
1383 static connection_t *instantiate(connection_t *c, const ip_address *him,
1384 u_int16_t his_port, identification_t *his_id)
1385 {
1386 connection_t *d;
1387
1388 passert(c->kind == CK_TEMPLATE);
1389 passert(c->spd.next == NULL);
1390
1391 c->instance_serial++;
1392 d = clone_thing(*c);
1393 d->spd.that.allow_any = FALSE;
1394
1395 if (his_id)
1396 {
1397 d->spd.that.id = his_id;
1398 d->spd.that.has_id_wildcards = FALSE;
1399 }
1400 unshare_connection_strings(d);
1401 if (d->spd.this.groups)
1402 {
1403 d->spd.this.groups = d->spd.this.groups->get_ref(d->spd.this.groups);
1404 }
1405 if (d->spd.that.groups)
1406 {
1407 d->spd.that.groups = d->spd.that.groups->get_ref(d->spd.that.groups);
1408 }
1409 d->kind = CK_INSTANCE;
1410
1411 passert(oriented(*d));
1412 d->spd.that.host_addr = *him;
1413 setportof(htons(c->spd.that.port), &d->spd.that.host_addr);
1414
1415 if (his_port) d->spd.that.host_port = his_port;
1416
1417 default_end(&d->spd.that, &d->spd.this.host_addr);
1418
1419 /* We cannot guess what our next_hop should be, but if it was
1420 * explicitly specified as 0.0.0.0, we set it to be him.
1421 * (whack will not allow nexthop to be elided in RW case.)
1422 */
1423 default_end(&d->spd.this, &d->spd.that.host_addr);
1424 d->spd.next = NULL;
1425 d->spd.reqid = gen_reqid();
1426
1427 /* set internal fields */
1428 d->ac_next = connections;
1429 connections = d;
1430 d->spd.routing = RT_UNROUTED;
1431 d->newest_isakmp_sa = SOS_NOBODY;
1432 d->newest_ipsec_sa = SOS_NOBODY;
1433 d->spd.eroute_owner = SOS_NOBODY;
1434
1435 /* reset log file info */
1436 d->log_file_name = NULL;
1437 d->log_file = NULL;
1438 d->log_file_err = FALSE;
1439
1440 connect_to_host_pair(d);
1441
1442 return d;
1443 if (sameaddr(&d->spd.that.host_addr, &d->spd.this.host_nexthop))
1444 {
1445 d->spd.this.host_nexthop = *him;
1446 }
1447 }
1448
1449 connection_t *rw_instantiate(connection_t *c, const ip_address *him,
1450 u_int16_t his_port, const ip_subnet *his_net,
1451 identification_t *his_id)
1452 {
1453 connection_t *d = instantiate(c, him, his_port, his_id);
1454
1455 if (d && his_net && is_virtual_connection(c))
1456 {
1457 d->spd.that.client = *his_net;
1458 d->spd.that.virt = NULL;
1459 if (subnetishost(his_net) && addrinsubnet(him, his_net))
1460 d->spd.that.has_client = FALSE;
1461 }
1462
1463 if (d->policy & POLICY_OPPO)
1464 {
1465 /* This must be before we know the client addresses.
1466 * Fill in one that is impossible. This prevents anyone else from
1467 * trying to use this connection to get to a particular client
1468 */
1469 d->spd.that.client = *aftoinfo(subnettypeof(&d->spd.that.client))->none;
1470 }
1471 DBG(DBG_CONTROL
1472 , DBG_log("instantiated \"%s\" for %s" , d->name, ip_str(him)));
1473 return d;
1474 }
1475
1476 connection_t *oppo_instantiate(connection_t *c, const ip_address *him,
1477 identification_t *his_id, struct gw_info *gw,
1478 const ip_address *our_client USED_BY_DEBUG,
1479 const ip_address *peer_client)
1480 {
1481 connection_t *d = instantiate(c, him, 0, his_id);
1482
1483 passert(d->spd.next == NULL);
1484
1485 /* fill in our client side */
1486 if (d->spd.this.has_client)
1487 {
1488 /* there was a client in the abstract connection
1489 * so we demand that the required client is within that subnet.
1490 */
1491 passert(addrinsubnet(our_client, &d->spd.this.client));
1492 happy(addrtosubnet(our_client, &d->spd.this.client));
1493 /* opportunistic connections do not use port selectors */
1494 setportof(0, &d->spd.this.client.addr);
1495 }
1496 else
1497 {
1498 /* there was no client in the abstract connection
1499 * so we demand that the required client be the host
1500 */
1501 passert(sameaddr(our_client, &d->spd.this.host_addr));
1502 }
1503
1504 /* fill in peer's client side.
1505 * If the client is the peer, excise the client from the connection.
1506 */
1507 passert((d->policy & POLICY_OPPO)
1508 && addrinsubnet(peer_client, &d->spd.that.client));
1509 happy(addrtosubnet(peer_client, &d->spd.that.client));
1510 /* opportunistic connections do not use port selectors */
1511 setportof(0, &d->spd.that.client.addr);
1512
1513 if (sameaddr(peer_client, &d->spd.that.host_addr))
1514 d->spd.that.has_client = FALSE;
1515
1516 passert(d->gw_info == NULL);
1517 gw_addref(gw);
1518 d->gw_info = gw;
1519
1520 /* Adjust routing if something is eclipsing c.
1521 * It must be a %hold for us (hard to passert this).
1522 * If there was another instance eclipsing, we'd be using it.
1523 */
1524 if (c->spd.routing == RT_ROUTED_ECLIPSED)
1525 d->spd.routing = RT_ROUTED_PROSPECTIVE;
1526
1527 /* Remember if the template is routed:
1528 * if so, this instance applies for initiation
1529 * even if it is created for responding.
1530 */
1531 if (routed(c->spd.routing))
1532 d->instance_initiation_ok = TRUE;
1533
1534 DBG(DBG_CONTROL,
1535 char topo[BUF_LEN];
1536
1537 (void) format_connection(topo, sizeof(topo), d, &d->spd);
1538 DBG_log("instantiated \"%s\": %s", d->name, topo);
1539 );
1540 return d;
1541 }
1542
1543 /* priority formatting */
1544 void fmt_policy_prio(policy_prio_t pp, char buf[POLICY_PRIO_BUF])
1545 {
1546 if (pp == BOTTOM_PRIO)
1547 {
1548 snprintf(buf, POLICY_PRIO_BUF, "0");
1549 }
1550 else
1551 {
1552 snprintf(buf, POLICY_PRIO_BUF, "%lu,%lu"
1553 , pp>>16, (pp & ~(~(policy_prio_t)0 << 16)) >> 8);
1554 }
1555 }
1556
1557 /* Format any information needed to identify an instance of a connection.
1558 * Fills any needed information into buf which MUST be big enough.
1559 * Road Warrior: peer's IP address
1560 * Opportunistic: [" " myclient "==="] " ..." peer ["===" hisclient] '\0'
1561 */
1562 static size_t fmt_client(const ip_subnet *client, const ip_address *gw,
1563 const char *prefix, char buf[ADDRTOT_BUF])
1564 {
1565 if (subnetisaddr(client, gw))
1566 {
1567 buf[0] = '\0'; /* compact denotation for "self" */
1568 }
1569 else
1570 {
1571 char *ap;
1572
1573 strcpy(buf, prefix);
1574 ap = buf + strlen(prefix);
1575 if (subnetisnone(client))
1576 strcpy(ap, "?"); /* unknown */
1577 else
1578 subnettot(client, 0, ap, SUBNETTOT_BUF);
1579 }
1580 return strlen(buf);
1581 }
1582
1583 void fmt_conn_instance(const connection_t *c, char buf[CONN_INST_BUF])
1584 {
1585 char *p = buf;
1586
1587 *p = '\0';
1588
1589 if (c->kind == CK_INSTANCE)
1590 {
1591 if (c->instance_serial != 0)
1592 {
1593 snprintf(p, CONN_INST_BUF, "[%lu]", c->instance_serial);
1594 p += strlen(p);
1595 }
1596
1597 if (c->policy & POLICY_OPPO)
1598 {
1599 size_t w = fmt_client(&c->spd.this.client, &c->spd.this.host_addr, " ", p);
1600
1601 p += w;
1602
1603 strcpy(p, w == 0? " ..." : "=== ...");
1604 p += strlen(p);
1605
1606 addrtot(&c->spd.that.host_addr, 0, p, ADDRTOT_BUF);
1607 p += strlen(p);
1608
1609 (void) fmt_client(&c->spd.that.client, &c->spd.that.host_addr, "===", p);
1610 }
1611 else
1612 {
1613 *p++ = ' ';
1614 addrtot(&c->spd.that.host_addr, 0, p, ADDRTOT_BUF);
1615 #
1616 if (c->spd.that.host_port != pluto_port)
1617 {
1618 p += strlen(p);
1619 sprintf(p, ":%d", c->spd.that.host_port);
1620 }
1621 }
1622 }
1623 }
1624
1625 /* Find an existing connection for a trapped outbound packet.
1626 * This is attempted before we bother with gateway discovery.
1627 * + this connection is routed or instance_of_routed_template
1628 * (i.e. approved for on-demand)
1629 * + this subnet contains our_client (or we are our_client)
1630 * + that subnet contains peer_client (or peer is peer_client)
1631 * + don't care about Phase 1 IDs (we don't know)
1632 * Note: result may still need to be instantiated.
1633 * The winner has the highest policy priority.
1634 *
1635 * If there are several with that priority, we give preference to
1636 * the first one that is an instance.
1637 *
1638 * See also build_outgoing_opportunistic_connection.
1639 */
1640 connection_t *find_connection_for_clients(struct spd_route **srp,
1641 const ip_address *our_client,
1642 const ip_address *peer_client,
1643 int transport_proto)
1644 {
1645 connection_t *c = connections, *best = NULL;
1646 policy_prio_t best_prio = BOTTOM_PRIO;
1647 struct spd_route *sr;
1648 struct spd_route *best_sr = NULL;
1649 int our_port = ntohs(portof(our_client));
1650 int peer_port = ntohs(portof(peer_client));
1651
1652 passert(!isanyaddr(our_client) && !isanyaddr(peer_client));
1653 #ifdef DEBUG
1654 if (DBGP(DBG_CONTROL))
1655 {
1656 char ocb[ADDRTOT_BUF], pcb[ADDRTOT_BUF];
1657
1658 addrtot(our_client, 0, ocb, sizeof(ocb));
1659 addrtot(peer_client, 0, pcb, sizeof(pcb));
1660 DBG_log("find_connection: "
1661 "looking for policy for connection: %s:%d/%d -> %s:%d/%d"
1662 , ocb, transport_proto, our_port, pcb, transport_proto, peer_port);
1663 }
1664 #endif /* DEBUG */
1665
1666 for (c = connections; c != NULL; c = c->ac_next)
1667 {
1668 if (c->kind == CK_GROUP)
1669 {
1670 continue;
1671 }
1672
1673 for (sr = &c->spd; best!=c && sr; sr = sr->next)
1674 {
1675 if ((routed(sr->routing) || c->instance_initiation_ok)
1676 && addrinsubnet(our_client, &sr->this.client)
1677 && addrinsubnet(peer_client, &sr->that.client)
1678 && addrinsubnet(peer_client, &sr->that.client)
1679 && (!sr->this.protocol || transport_proto == sr->this.protocol)
1680 && (!sr->this.port || our_port == sr->this.port)
1681 && (!sr->that.port || peer_port == sr->that.port))
1682 {
1683 char cib[CONN_INST_BUF];
1684 char cib2[CONN_INST_BUF];
1685
1686 policy_prio_t prio = 8 * (c->prio + (c->kind == CK_INSTANCE))
1687 + 2 * (sr->this.port == our_port)
1688 + 2 * (sr->that.port == peer_port)
1689 + (sr->this.protocol == transport_proto);
1690
1691 #ifdef DEBUG
1692 if (DBGP(DBG_CONTROL|DBG_CONTROLMORE))
1693 {
1694 char c_ocb[SUBNETTOT_BUF], c_pcb[SUBNETTOT_BUF];
1695
1696 subnettot(&c->spd.this.client, 0, c_ocb, sizeof(c_ocb));
1697 subnettot(&c->spd.that.client, 0, c_pcb, sizeof(c_pcb));
1698 DBG_log("find_connection: conn \"%s\"%s has compatible peers: %s->%s [pri: %ld]"
1699 , c->name
1700 , (fmt_conn_instance(c, cib), cib)
1701 , c_ocb, c_pcb, prio);
1702 }
1703 #endif /* DEBUG */
1704
1705 if (best == NULL)
1706 {
1707 best = c;
1708 best_sr = sr;
1709 best_prio = prio;
1710 }
1711
1712 DBG(DBG_CONTROLMORE,
1713 DBG_log("find_connection: "
1714 "comparing best \"%s\"%s [pri:%ld]{%p} (child %s) to \"%s\"%s [pri:%ld]{%p} (child %s)"
1715 , best->name
1716 , (fmt_conn_instance(best, cib), cib)
1717 , best_prio
1718 , best
1719 , (best->policy_next ? best->policy_next->name : "none")
1720 , c->name
1721 , (fmt_conn_instance(c, cib2), cib2)
1722 , prio
1723 , c
1724 , (c->policy_next ? c->policy_next->name : "none")));
1725
1726 if (prio > best_prio)
1727 {
1728 best = c;
1729 best_sr = sr;
1730 best_prio = prio;
1731 }
1732 }
1733 }
1734 }
1735
1736 if (best && NEVER_NEGOTIATE(best->policy))
1737 {
1738 best = NULL;
1739 }
1740 if (srp && best)
1741 {
1742 *srp = best_sr;
1743 }
1744
1745 #ifdef DEBUG
1746 if (DBGP(DBG_CONTROL))
1747 {
1748 if (best)
1749 {
1750 char cib[CONN_INST_BUF];
1751 DBG_log("find_connection: concluding with \"%s\"%s [pri:%ld]{%p} kind=%s"
1752 , best->name
1753 , (fmt_conn_instance(best, cib), cib)
1754 , best_prio
1755 , best
1756 , enum_name(&connection_kind_names, best->kind));
1757 } else {
1758 DBG_log("find_connection: concluding with empty");
1759 }
1760 }
1761 #endif /* DEBUG */
1762
1763 return best;
1764 }
1765
1766 /* Find and instantiate a connection for an outgoing Opportunistic connection.
1767 * We've already discovered its gateway.
1768 * We look for a the connection such that:
1769 * + this is one of our interfaces
1770 * + this subnet contains our_client (or we are our_client)
1771 * (we will specialize the client). We prefer the smallest such subnet.
1772 * + that subnet contains peer_clent (we will specialize the client).
1773 * We prefer the smallest such subnet.
1774 * + is opportunistic
1775 * + that peer is NO_IP
1776 * + don't care about Phase 1 IDs (probably should be default)
1777 * We could look for a connection that already had the desired peer
1778 * (rather than NO_IP) specified, but it doesn't seem worth the
1779 * bother.
1780 *
1781 * We look for the routed policy applying to the narrowest subnets.
1782 * We only succeed if we find such a policy AND it is satisfactory.
1783 *
1784 * The body of the inner loop is a lot like that in
1785 * find_connection_for_clients. In this case, we know the gateways
1786 * that we need to instantiate an opportunistic connection.
1787 */
1788 connection_t *build_outgoing_opportunistic_connection(struct gw_info *gw,
1789 const ip_address *our_client,
1790 const ip_address *peer_client)
1791 {
1792 struct iface *p;
1793 connection_t *best = NULL;
1794 struct spd_route *sr, *bestsr;
1795 char ocb[ADDRTOT_BUF], pcb[ADDRTOT_BUF];
1796
1797 addrtot(our_client, 0, ocb, sizeof(ocb));
1798 addrtot(peer_client, 0, pcb, sizeof(pcb));
1799
1800 /* for each of our addresses... */
1801 for (p = interfaces; p != NULL; p = p->next)
1802 {
1803 /* go through those connections with our address and NO_IP as hosts
1804 * We cannot know what port the peer would use, so we assume
1805 * that it is pluto_port (makes debugging easier).
1806 */
1807 connection_t *c = find_host_pair_connections(&p->addr, pluto_port,
1808 (ip_address *)NULL, pluto_port);
1809
1810 for (; c != NULL; c = c->hp_next)
1811 {
1812 DBG(DBG_OPPO,
1813 DBG_log("checking %s", c->name));
1814 if (c->kind == CK_GROUP)
1815 {
1816 continue;
1817 }
1818
1819 for (sr = &c->spd; best!=c && sr; sr = sr->next)
1820 {
1821 if (routed(sr->routing)
1822 && addrinsubnet(our_client, &sr->this.client)
1823 && addrinsubnet(peer_client, &sr->that.client))
1824 {
1825 if (best == NULL)
1826 {
1827 best = c;
1828 break;
1829 }
1830
1831 DBG(DBG_OPPO,
1832 DBG_log("comparing best %s to %s"
1833 , best->name, c->name));
1834
1835 for (bestsr = &best->spd; best!=c && bestsr; bestsr=bestsr->next)
1836 {
1837 if (!subnetinsubnet(&bestsr->this.client, &sr->this.client)
1838 || (samesubnet(&bestsr->this.client, &sr->this.client)
1839 && !subnetinsubnet(&bestsr->that.client
1840 , &sr->that.client)))
1841 {
1842 best = c;
1843 }
1844 }
1845 }
1846 }
1847 }
1848 }
1849
1850 if (best == NULL || NEVER_NEGOTIATE(best->policy) ||
1851 (best->policy & POLICY_OPPO) == LEMPTY || best->kind != CK_TEMPLATE)
1852 {
1853 return NULL;
1854 }
1855 else
1856 {
1857 chunk_t encoding = gw->gw_id->get_encoding(gw->gw_id);
1858 id_type_t type = gw->gw_id->get_type(gw->gw_id);
1859 ip_address ip_addr;
1860
1861 initaddr(encoding.ptr, encoding.len,
1862 (type == ID_IPV4_ADDR) ? AF_INET : AF_INET6, &ip_addr);
1863
1864 return oppo_instantiate(best, &ip_addr, NULL, gw, our_client, peer_client);
1865 }
1866 }
1867
1868 bool orient(connection_t *c)
1869 {
1870 struct spd_route *sr;
1871
1872 if (!oriented(*c))
1873 {
1874 struct iface *p;
1875
1876 for (sr = &c->spd; sr; sr = sr->next)
1877 {
1878 /* Note: this loop does not stop when it finds a match:
1879 * it continues checking to catch any ambiguity.
1880 */
1881 for (p = interfaces; p != NULL; p = p->next)
1882 {
1883 if (p->ike_float)
1884 {
1885 continue;
1886 }
1887
1888 for (;;)
1889 {
1890 /* check if this interface matches this end */
1891 if (sameaddr(&sr->this.host_addr, &p->addr)
1892 && sr->this.host_port == pluto_port)
1893 {
1894 if (oriented(*c))
1895 {
1896 if (c->interface == p)
1897 loglog(RC_LOG_SERIOUS
1898 , "both sides of \"%s\" are our interface %s!"
1899 , c->name, p->rname);
1900 else
1901 loglog(RC_LOG_SERIOUS, "two interfaces match \"%s\" (%s, %s)"
1902 , c->name, c->interface->rname, p->rname);
1903 c->interface = NULL; /* withdraw orientation */
1904 return FALSE;
1905 }
1906 c->interface = p;
1907 }
1908
1909 /* done with this interface if it doesn't match that end */
1910 if (!(sameaddr(&sr->that.host_addr, &p->addr)
1911 && sr->that.host_port == pluto_port))
1912 break;
1913
1914 /* swap ends and try again.
1915 * It is a little tricky to see that this loop will stop.
1916 * Only continue if the far side matches.
1917 * If both sides match, there is an error-out.
1918 */
1919 {
1920 struct end t = sr->this;
1921
1922 sr->this = sr->that;
1923 sr->that = t;
1924 }
1925 }
1926 }
1927 }
1928 }
1929 return oriented(*c);
1930 }
1931
1932 void initiate_connection(const char *name, int whackfd)
1933 {
1934 connection_t *c = con_by_name(name, TRUE);
1935
1936 if (c && c->ikev1)
1937 {
1938 set_cur_connection(c);
1939 if (!oriented(*c))
1940 {
1941 loglog(RC_ORIENT, "we have no ipsecN interface for either end of this connection");
1942 }
1943 else if (NEVER_NEGOTIATE(c->policy))
1944 {
1945 loglog(RC_INITSHUNT
1946 , "cannot initiate an authby=never connection");
1947 }
1948 else if (c->kind != CK_PERMANENT && !c->spd.that.allow_any)
1949 {
1950 if (isanyaddr(&c->spd.that.host_addr))
1951 loglog(RC_NOPEERIP, "cannot initiate connection without knowing peer IP address");
1952 else
1953 loglog(RC_WILDCARD, "cannot initiate connection with ID wildcards");
1954 }
1955 else
1956 {
1957 /* do we have to prompt for a PIN code? */
1958 if (c->spd.this.sc && !c->spd.this.sc->valid && whackfd != NULL_FD)
1959 {
1960 scx_get_pin(c->spd.this.sc, whackfd);
1961 }
1962 if (c->spd.this.sc && !c->spd.this.sc->valid)
1963 {
1964 loglog(RC_NOVALIDPIN, "cannot initiate connection without valid PIN");
1965 }
1966 else
1967 {
1968
1969 if (c->spd.that.allow_any)
1970 {
1971 c = instantiate(c, &c->spd.that.host_addr,
1972 c->spd.that.host_port, c->spd.that.id);
1973 }
1974
1975 /* We will only request an IPsec SA if policy isn't empty
1976 * (ignoring Main Mode items).
1977 * This is a fudge, but not yet important.
1978 * If we are to proceed asynchronously, whackfd will be NULL_FD.
1979 */
1980 c->policy |= POLICY_UP;
1981 ipsecdoi_initiate(whackfd, c, c->policy, 1, SOS_NOBODY);
1982 whackfd = NULL_FD; /* protect from close */
1983 }
1984 }
1985 reset_cur_connection();
1986 }
1987 close_any(whackfd);
1988 }
1989
1990 /* (Possibly) Opportunistic Initiation:
1991 * Knowing clients (single IP addresses), try to build an tunnel.
1992 * This may involve discovering a gateway and instantiating an
1993 * Opportunistic connection. Called when a packet is caught by
1994 * a %trap, or when whack --oppohere --oppothere is used.
1995 * It may turn out that an existing or non-opporunistic connnection
1996 * can handle the traffic.
1997 *
1998 * Most of the code will be restarted if an ADNS request is made
1999 * to discover the gateway. The only difference between the first
2000 * and second entry is whether gateways_from_dns is NULL or not.
2001 * initiate_opportunistic: initial entrypoint
2002 * continue_oppo: where we pickup when ADNS result arrives
2003 * initiate_opportunistic_body: main body shared by above routines
2004 * cannot_oppo: a helper function to log a diagnostic
2005 * This structure repeats a lot of code when the ADNS result arrives.
2006 * This seems like a waste, but anything learned the first time through
2007 * may no longer be true!
2008 *
2009 * After the first IKE message is sent, the regular state machinery
2010 * carries negotiation forward.
2011 */
2012
2013 enum find_oppo_step {
2014 fos_start,
2015 fos_myid_ip_txt,
2016 fos_myid_hostname_txt,
2017 fos_myid_ip_key,
2018 fos_myid_hostname_key,
2019 fos_our_client,
2020 fos_our_txt,
2021 #ifdef USE_KEYRR
2022 fos_our_key,
2023 #endif /* USE_KEYRR */
2024 fos_his_client,
2025 fos_done
2026 };
2027
2028 #ifdef DEBUG
2029 static const char *const oppo_step_name[] = {
2030 "fos_start",
2031 "fos_myid_ip_txt",
2032 "fos_myid_hostname_txt",
2033 "fos_myid_ip_key",
2034 "fos_myid_hostname_key",
2035 "fos_our_client",
2036 "fos_our_txt",
2037 #ifdef USE_KEYRR
2038 "fos_our_key",
2039 #endif /* USE_KEYRR */
2040 "fos_his_client",
2041 "fos_done"
2042 };
2043 #endif /* DEBUG */
2044
2045 struct find_oppo_bundle {
2046 enum find_oppo_step step;
2047 err_t want;
2048 bool failure_ok; /* if true, continue_oppo should not die on DNS failure */
2049 ip_address our_client; /* not pointer! */
2050 ip_address peer_client;
2051 int transport_proto;
2052 bool held;
2053 policy_prio_t policy_prio;
2054 ipsec_spi_t failure_shunt; /* in host order! 0 for delete. */
2055 int whackfd;
2056 };
2057
2058 struct find_oppo_continuation {
2059 struct adns_continuation ac; /* common prefix */
2060 struct find_oppo_bundle b;
2061 };
2062
2063 static void cannot_oppo(connection_t *c, struct find_oppo_bundle *b, err_t ugh)
2064 {
2065 char pcb[ADDRTOT_BUF];
2066 char ocb[ADDRTOT_BUF];
2067
2068 addrtot(&b->peer_client, 0, pcb, sizeof(pcb));
2069 addrtot(&b->our_client, 0, ocb, sizeof(ocb));
2070
2071 DBG(DBG_DNS | DBG_OPPO, DBG_log("Can't Opportunistically initiate for %s to %s: %s"
2072 , ocb, pcb, ugh));
2073
2074 whack_log(RC_OPPOFAILURE
2075 , "Can't Opportunistically initiate for %s to %s: %s"
2076 , ocb, pcb, ugh);
2077
2078 if (c && c->policy_next)
2079 {
2080 /* there is some policy that comes afterwards */
2081 struct spd_route *shunt_spd;
2082 connection_t *nc = c->policy_next;
2083 struct state *st;
2084
2085 passert(c->kind == CK_TEMPLATE);
2086 passert(c->policy_next->kind == CK_PERMANENT);
2087
2088 DBG(DBG_OPPO, DBG_log("OE failed for %s to %s, but %s overrides shunt"
2089 , ocb, pcb, c->policy_next->name));
2090
2091 /*
2092 * okay, here we need add to the "next" policy, which is ought
2093 * to be an instance.
2094 * We will add another entry to the spd_route list for the specific
2095 * situation that we have.
2096 */
2097
2098 shunt_spd = clone_thing(nc->spd);
2099
2100 shunt_spd->next = nc->spd.next;
2101 nc->spd.next = shunt_spd;
2102
2103 happy(addrtosubnet(&b->peer_client, &shunt_spd->that.client));
2104
2105 if (sameaddr(&b->peer_client, &shunt_spd->that.host_addr))
2106 shunt_spd->that.has_client = FALSE;
2107
2108 /*
2109 * override the tunnel destination with the one from the secondaried
2110 * policy
2111 */
2112 shunt_spd->that.host_addr = nc->spd.that.host_addr;
2113
2114 /* now, lookup the state, and poke it up.
2115 */
2116
2117 st = state_with_serialno(nc->newest_ipsec_sa);
2118
2119 /* XXX what to do if the IPSEC SA has died? */
2120 passert(st != NULL);
2121
2122 /* link the new connection instance to the state's list of
2123 * connections
2124 */
2125
2126 DBG(DBG_OPPO, DBG_log("installing state: %ld for %s to %s"
2127 , nc->newest_ipsec_sa
2128 , ocb, pcb));
2129
2130 #ifdef DEBUG
2131 if (DBGP(DBG_OPPO | DBG_CONTROLMORE))
2132 {
2133 char state_buf[LOG_WIDTH];
2134 char state_buf2[LOG_WIDTH];
2135 time_t n = now();
2136
2137 fmt_state(FALSE, st, n
2138 , state_buf, sizeof(state_buf)
2139 , state_buf2, sizeof(state_buf2));
2140 DBG_log("cannot_oppo, failure SA1: %s", state_buf);
2141 DBG_log("cannot_oppo, failure SA2: %s", state_buf2);
2142 }
2143 #endif /* DEBUG */
2144
2145 if (!route_and_eroute(c, shunt_spd, st))
2146 {
2147 whack_log(RC_OPPOFAILURE
2148 , "failed to instantiate shunt policy %s for %s to %s"
2149 , c->name
2150 , ocb, pcb);
2151 }
2152 return;
2153 }
2154 }
2155
2156 static void initiate_opportunistic_body(struct find_oppo_bundle *b
2157 , struct adns_continuation *ac, err_t ac_ugh); /* forward */
2158
2159 void initiate_opportunistic(const ip_address *our_client,
2160 const ip_address *peer_client, int transport_proto,
2161 bool held, int whackfd)
2162 {
2163 struct find_oppo_bundle b;
2164
2165 b.want = (whackfd == NULL_FD ? "whack" : "acquire");
2166 b.failure_ok = FALSE;
2167 b.our_client = *our_client;
2168 b.peer_client = *peer_client;
2169 b.transport_proto = transport_proto;
2170 b.held = held;
2171 b.policy_prio = BOTTOM_PRIO;
2172 b.failure_shunt = 0;
2173 b.whackfd = whackfd;
2174 b.step = fos_start;
2175 initiate_opportunistic_body(&b, NULL, NULL);
2176 }
2177
2178 static void continue_oppo(struct adns_continuation *acr, err_t ugh)
2179 {
2180 struct find_oppo_continuation *cr = (void *)acr; /* inherit, damn you! */
2181 connection_t *c;
2182 bool was_held = cr->b.held;
2183 int whackfd = cr->b.whackfd;
2184
2185 /* note: cr->id has no resources; cr->sgw_id is ID_ANY:
2186 * neither need freeing.
2187 */
2188 whack_log_fd = whackfd;
2189
2190 #ifdef DEBUG
2191 /* if we're going to ignore the error, at least note it in debugging log */
2192 if (cr->b.failure_ok && ugh)
2193 {
2194 DBG(DBG_CONTROL | DBG_DNS,
2195 {
2196 char ocb[ADDRTOT_BUF];
2197 char pcb[ADDRTOT_BUF];
2198
2199 addrtot(&cr->b.our_client, 0, ocb, sizeof(ocb));
2200 addrtot(&cr->b.peer_client, 0, pcb, sizeof(pcb));
2201 DBG_log("continuing from failed DNS lookup for %s, %s to %s: %s"
2202 , cr->b.want, ocb, pcb, ugh);
2203 });
2204 }
2205 #endif
2206
2207 if (!cr->b.failure_ok && ugh)
2208 {
2209 c = find_connection_for_clients(NULL, &cr->b.our_client, &cr->b.peer_client
2210 , cr->b.transport_proto);
2211 cannot_oppo(c, &cr->b
2212 , builddiag("%s: %s", cr->b.want, ugh));
2213 }
2214 else if (was_held && !cr->b.held)
2215 {
2216 /* was_held indicates we were started due to a %trap firing
2217 * (as opposed to a "whack --oppohere --oppothere").
2218 * Since the %hold has gone, we can assume that somebody else
2219 * has beaten us to the punch. We can go home. But lets log it.
2220 */
2221 char ocb[ADDRTOT_BUF];
2222 char pcb[ADDRTOT_BUF];
2223
2224 addrtot(&cr->b.our_client, 0, ocb, sizeof(ocb));
2225 addrtot(&cr->b.peer_client, 0, pcb, sizeof(pcb));
2226
2227 loglog(RC_COMMENT
2228 , "%%hold otherwise handled during DNS lookup for Opportunistic Initiation for %s to %s"
2229 , ocb, pcb);
2230 }
2231 else
2232 {
2233 initiate_opportunistic_body(&cr->b, &cr->ac, ugh);
2234 whackfd = NULL_FD; /* was handed off */
2235 }
2236
2237 whack_log_fd = NULL_FD;
2238 close_any(whackfd);
2239 }
2240
2241 #ifdef USE_KEYRR
2242 static err_t check_key_recs(enum myid_state try_state, const connection_t *c,
2243 struct adns_continuation *ac)
2244 {
2245 /* Check if KEY lookup yielded good results.
2246 * Looking up based on our ID. Used if
2247 * client is ourself, or if TXT had no public key.
2248 * Note: if c is different this time, there is
2249 * a chance that we did the wrong query.
2250 * If so, treat as a kind of failure.
2251 */
2252 enum myid_state old_myid_state = myid_state;
2253 private_key_t *private;
2254 err_t ugh = NULL;
2255
2256 myid_state = try_state;
2257
2258 if (old_myid_state != myid_state && old_myid_state == MYID_SPECIFIED)
2259 {
2260 ugh = "%myid was specified while we were guessing";
2261 }
2262 else if ((private = get_private_key(c)) == NULL)
2263 {
2264 ugh = "we don't know our own RSA key";
2265 }
2266 else if (!same_id(&ac->id, &c->spd.this.id))
2267 {
2268 ugh = "our ID changed underfoot";
2269 }
2270 else
2271 {
2272 /* Similar to code in RSA_check_signature
2273 * for checking the other side.
2274 */
2275 pubkey_list_t *kr;
2276
2277 ugh = "no KEY RR found for us";
2278 for (kr = ac->keys_from_dns; kr != NULL; kr = kr->next)
2279 {
2280 ugh = "all our KEY RRs have the wrong public key";
2281 if (kr->key->alg == PUBKEY_ALG_RSA
2282 && private->belongs_to(private, &kr->key->public_key))
2283 {
2284 ugh = NULL; /* good! */
2285 break;
2286 }
2287 }
2288 }
2289 if (ugh)
2290 {
2291 myid_state = old_myid_state;
2292 }
2293 return ugh;
2294 }
2295 #endif /* USE_KEYRR */
2296
2297 static err_t check_txt_recs(enum myid_state try_state, const connection_t *c,
2298 struct adns_continuation *ac)
2299 {
2300 /* Check if TXT lookup yielded good results.
2301 * Looking up based on our ID. Used if
2302 * client is ourself, or if TXT had no public key.
2303 * Note: if c is different this time, there is
2304 * a chance that we did the wrong query.
2305 * If so, treat as a kind of failure.
2306 */
2307 enum myid_state old_myid_state = myid_state;
2308 private_key_t *private;
2309 err_t ugh = NULL;
2310
2311 myid_state = try_state;
2312
2313 if (old_myid_state != myid_state
2314 && old_myid_state == MYID_SPECIFIED)
2315 {
2316 ugh = "%myid was specified while we were guessing";
2317 }
2318 else if ((private = get_private_key(c)) == NULL)
2319 {
2320 ugh = "we don't know our own RSA key";
2321 }
2322 else if (!ac->id->equals(ac->id, c->spd.this.id))
2323 {
2324 ugh = "our ID changed underfoot";
2325 }
2326 else
2327 {
2328 /* Similar to code in RSA_check_signature
2329 * for checking the other side.
2330 */
2331 struct gw_info *gwp;
2332
2333 ugh = "no TXT RR found for us";
2334 for (gwp = ac->gateways_from_dns; gwp != NULL; gwp = gwp->next)
2335 {
2336 public_key_t *pub_key = gwp->key->public_key;
2337
2338 ugh = "all our TXT RRs have the wrong public key";
2339 if (pub_key->get_type(pub_key) == KEY_RSA &&
2340 private->belongs_to(private, pub_key))
2341 {
2342 ugh = NULL; /* good! */
2343 break;
2344 }
2345 }
2346 }
2347 if (ugh)
2348 {
2349 myid_state = old_myid_state;
2350 }
2351 return ugh;
2352 }
2353
2354
2355 /* note: gateways_from_dns must be NULL iff this is the first call */
2356 static void initiate_opportunistic_body(struct find_oppo_bundle *b,
2357 struct adns_continuation *ac,
2358 err_t ac_ugh)
2359 {
2360 connection_t *c;
2361 struct spd_route *sr;
2362
2363 /* What connection shall we use?
2364 * First try for one that explicitly handles the clients.
2365 */
2366 DBG(DBG_CONTROL,
2367 {
2368 char ours[ADDRTOT_BUF];
2369 char his[ADDRTOT_BUF];
2370 int ourport;
2371 int hisport;
2372
2373 addrtot(&b->our_client, 0, ours, sizeof(ours));
2374 addrtot(&b->peer_client, 0, his, sizeof(his));
2375 ourport = ntohs(portof(&b->our_client));
2376 hisport = ntohs(portof(&b->peer_client));
2377 DBG_log("initiate on demand from %s:%d to %s:%d proto=%d state: %s because: %s"
2378 , ours, ourport, his, hisport, b->transport_proto
2379 , oppo_step_name[b->step], b->want);
2380 });
2381 if (isanyaddr(&b->our_client) || isanyaddr(&b->peer_client))
2382 {
2383 cannot_oppo(NULL, b, "impossible IP address");
2384 }
2385 else if ((c = find_connection_for_clients(&sr
2386 , &b->our_client
2387 , &b->peer_client
2388 , b->transport_proto)) == NULL)
2389 {
2390 /* No connection explicitly handles the clients and there
2391 * are no Opportunistic connections -- whine and give up.
2392 * The failure policy cannot be gotten from a connection; we pick %pass.
2393 */
2394 cannot_oppo(NULL, b, "no routed Opportunistic template covers this pair");
2395 }
2396 else if (c->kind != CK_TEMPLATE)
2397 {
2398 /* We've found a connection that can serve.
2399 * Do we have to initiate it?
2400 * Not if there is currently an IPSEC SA.
2401 * But if there is an IPSEC SA, then the kernel would not
2402 * have generated the acquire. So we assume that there isn't one.
2403 * This may be redundant if a non-opportunistic
2404 * negotiation is already being attempted.
2405 */
2406
2407 /* If we are to proceed asynchronously, b->whackfd will be NULL_FD. */
2408
2409 if(c->kind == CK_INSTANCE)
2410 {
2411 char cib[CONN_INST_BUF];
2412 /* there is already an instance being negotiated, no nothing */
2413 DBG(DBG_CONTROL, DBG_log("found existing instance \"%s\"%s, rekeying it"
2414 , c->name
2415 , (fmt_conn_instance(c, cib), cib)));
2416 /* XXX-mcr - return; */
2417 }
2418
2419 /* otherwise, there is some kind of static conn that can handle
2420 * this connection, so we initiate it */
2421
2422 if (b->held)
2423 {
2424 /* what should we do on failure? */
2425 (void) assign_hold(c, sr, b->transport_proto, &b->our_client, &b->peer_client);
2426 }
2427 ipsecdoi_initiate(b->whackfd, c, c->policy, 1, SOS_NOBODY);
2428 b->whackfd = NULL_FD; /* protect from close */
2429 }
2430 else
2431 {
2432 /* We are handling an opportunistic situation.
2433 * This involves several DNS lookup steps that require suspension.
2434 * Note: many facts might change while we're suspended.
2435 * Here be dragons.
2436 *
2437 * The first chunk of code handles the result of the previous
2438 * DNS query (if any). It also selects the kind of the next step.
2439 * The second chunk initiates the next DNS query (if any).
2440 */
2441 enum find_oppo_step next_step = fos_myid_ip_txt;
2442 err_t ugh = ac_ugh;
2443 char mycredentialstr[BUF_LEN];
2444 char cib[CONN_INST_BUF];
2445
2446 DBG(DBG_CONTROL, DBG_log("creating new instance from \"%s\"%s",
2447 c->name, (fmt_conn_instance(c, cib), cib)));
2448 snprintf(mycredentialstr, BUF_LEN, "%Y", sr->this.id);
2449
2450 /* handle any DNS answer; select next step */
2451 switch (b->step)
2452 {
2453 case fos_start:
2454 /* just starting out: select first query step */
2455 next_step = fos_myid_ip_txt;
2456 break;
2457
2458 case fos_myid_ip_txt: /* TXT for our default IP address as %myid */
2459 ugh = check_txt_recs(MYID_IP, c, ac);
2460 if (ugh)
2461 {
2462 /* cannot use our IP as OE identitiy for initiation */
2463 DBG(DBG_OPPO,
2464 DBG_log("can not use our IP (%Y:TXT) as identity: %s",
2465 myids[MYID_IP], ugh));
2466 if (!logged_myid_ip_txt_warning)
2467 {
2468 loglog(RC_LOG_SERIOUS,
2469 "can not use our IP (%Y:TXT) as identity: %s",
2470 myids[MYID_IP], ugh);
2471 logged_myid_ip_txt_warning = TRUE;
2472 }
2473
2474 next_step = fos_myid_hostname_txt;
2475 ugh = NULL; /* failure can be recovered from */
2476 }
2477 else
2478 {
2479 /* we can use our IP as OE identity for initiation */
2480 if (!logged_myid_ip_txt_warning)
2481 {
2482 loglog(RC_LOG_SERIOUS,
2483 "using our IP (%Y:TXT) as identity!",
2484 myids[MYID_IP]);
2485 logged_myid_ip_txt_warning = TRUE;
2486 }
2487
2488 next_step = fos_our_client;
2489 }
2490 break;
2491
2492 case fos_myid_hostname_txt: /* TXT for our hostname as %myid */
2493 ugh = check_txt_recs(MYID_HOSTNAME, c, ac);
2494 if (ugh)
2495 {
2496 /* cannot use our hostname as OE identitiy for initiation */
2497 DBG(DBG_OPPO,
2498 DBG_log("can not use our hostname (%Y:TXT) as identity: %s",
2499 myids[MYID_HOSTNAME], ugh));
2500 if (!logged_myid_fqdn_txt_warning)
2501 {
2502 loglog(RC_LOG_SERIOUS,
2503 "can not use our hostname (%Y:TXT) as identity: %s",
2504 myids[MYID_HOSTNAME], ugh);
2505 logged_myid_fqdn_txt_warning = TRUE;
2506 }
2507 #ifdef USE_KEYRR
2508 next_step = fos_myid_ip_key;
2509 ugh = NULL; /* failure can be recovered from */
2510 #endif
2511 }
2512 else
2513 {
2514 /* we can use our hostname as OE identity for initiation */
2515 if (!logged_myid_fqdn_txt_warning)
2516 {
2517 loglog(RC_LOG_SERIOUS,
2518 "using our hostname (%Y:TXT) as identity!",
2519 myids[MYID_HOSTNAME]);
2520 logged_myid_fqdn_txt_warning = TRUE;
2521 }
2522 next_step = fos_our_client;
2523 }
2524 break;
2525
2526 #ifdef USE_KEYRR
2527 case fos_myid_ip_key: /* KEY for our default IP address as %myid */
2528 ugh = check_key_recs(MYID_IP, c, ac);
2529 if (ugh)
2530 {
2531 /* cannot use our IP as OE identitiy for initiation */
2532 DBG(DBG_OPPO,
2533 DBG_log("can not use our IP (%Y:KEY) as identity: %s",
2534 myids[MYID_IP], ugh));
2535 if (!logged_myid_ip_key_warning)
2536 {
2537 loglog(RC_LOG_SERIOUS,
2538 "can not use our IP (%Y:KEY) as identity: %s",
2539 myids[MYID_IP], ugh);
2540 logged_myid_ip_key_warning = TRUE;
2541 }
2542
2543 next_step = fos_myid_hostname_key;
2544 ugh = NULL; /* failure can be recovered from */
2545 }
2546 else
2547 {
2548 /* we can use our IP as OE identity for initiation */
2549 if (!logged_myid_ip_key_warning)
2550 {
2551 loglog(RC_LOG_SERIOUS,
2552 "using our IP (%Y:KEY) as identity!",
2553 myids[MYID_IP]);
2554 logged_myid_ip_key_warning = TRUE;
2555 }
2556 next_step = fos_our_client;
2557 }
2558 break;
2559
2560 case fos_myid_hostname_key: /* KEY for our hostname as %myid */
2561 ugh = check_key_recs(MYID_HOSTNAME, c, ac);
2562 if (ugh)
2563 {
2564 /* cannot use our IP as OE identitiy for initiation */
2565 DBG(DBG_OPPO,
2566 DBG_log("can not use our hostname (%Y:KEY) as identity: %s",
2567 myids[MYID_HOSTNAME], ugh));
2568 if (!logged_myid_fqdn_key_warning)
2569 {
2570 loglog(RC_LOG_SERIOUS,
2571 "can not use our hostname (%Y:KEY) as identity: %s",
2572 myids[MYID_HOSTNAME], ugh);
2573 logged_myid_fqdn_key_warning = TRUE;
2574 }
2575 next_step = fos_myid_hostname_key;
2576 ugh = NULL; /* failure can be recovered from */
2577 }
2578 else
2579 {
2580 /* we can use our IP as OE identity for initiation */
2581 if (!logged_myid_fqdn_key_warning)
2582 {
2583 loglog(RC_LOG_SERIOUS,
2584 "using our hostname (%Y:KEY) as identity!",
2585 myids[MYID_HOSTNAME]);
2586 logged_myid_fqdn_key_warning = TRUE;
2587 }
2588 next_step = fos_our_client;
2589 }
2590 break;
2591 #endif
2592
2593 case fos_our_client: /* TXT for our client */
2594 {
2595 /* Our client is not us: we must check the TXT records.
2596 * Note: if c is different this time, there is
2597 * a chance that we did the wrong query.
2598 * If so, treat as a kind of failure.
2599 */
2600 private_key_t *private = get_private_key(c);
2601
2602 next_step = fos_his_client; /* normal situation */
2603
2604 if (private == NULL)
2605 {
2606 ugh = "we don't know our own RSA key";
2607 }
2608 else if (sameaddr(&sr->this.host_addr, &b->our_client))
2609 {
2610 /* this wasn't true when we started -- bail */
2611 ugh = "our IP address changed underfoot";
2612 }
2613 else if (!ac->sgw_id->equals(ac->sgw_id, sr->this.id))
2614 {
2615 /* this wasn't true when we started -- bail */
2616 ugh = "our ID changed underfoot";
2617 }
2618 else
2619 {
2620 /* Similar to code in quick_inI1_outR1_tail
2621 * for checking the other side.
2622 */
2623 struct gw_info *gwp;
2624
2625 ugh = "no TXT RR for our client delegates us";
2626 for (gwp = ac->gateways_from_dns; gwp != NULL; gwp = gwp->next)
2627 {
2628 ugh = "TXT RR for our client has wrong key";
2629 /* If there is a key from the TXT record,
2630 * we count it as a win if we match the key.
2631 * If there was no key, we have a tentative win:
2632 * we need to check our KEY record to be sure.
2633 */
2634 if (!gwp->gw_key_present)
2635 {
2636 /* Success, but the TXT had no key
2637 * so we must check our our own KEY records.
2638 */
2639 next_step = fos_our_txt;
2640 ugh = NULL; /* good! */
2641 break;
2642 }
2643 if (private->belongs_to(private, gwp->key->public_key))
2644 {
2645 ugh = NULL; /* good! */
2646 break;
2647 }
2648 }
2649 }
2650 }
2651 break;
2652
2653 case fos_our_txt: /* TXT for us */
2654 {
2655 /* Check if TXT lookup yielded good results.
2656 * Looking up based on our ID. Used if
2657 * client is ourself, or if TXT had no public key.
2658 * Note: if c is different this time, there is
2659 * a chance that we did the wrong query.
2660 * If so, treat as a kind of failure.
2661 */
2662 private_key_t *private = get_private_key(c);
2663
2664 next_step = fos_his_client; /* unless we decide to look for KEY RR */
2665
2666 if (private == NULL)
2667 {
2668 ugh = "we don't know our own RSA key";
2669 }
2670 else if (!ac->id->equals(ac->id, c->spd.this.id))
2671 {
2672 ugh = "our ID changed underfoot";
2673 }
2674 else
2675 {
2676 /* Similar to code in RSA_check_signature
2677 * for checking the other side.
2678 */
2679 struct gw_info *gwp;
2680
2681 ugh = "no TXT RR for us";
2682 for (gwp = ac->gateways_from_dns; gwp != NULL; gwp = gwp->next)
2683 {
2684 ugh = "TXT RR for us has wrong key";
2685 if (gwp->gw_key_present &&
2686 private->belongs_to(private, gwp->key->public_key))
2687 {
2688 DBG(DBG_CONTROL,
2689 DBG_log("initiate on demand found TXT with right public key at: %s"
2690 , mycredentialstr));
2691 ugh = NULL;
2692 break;
2693 }
2694 }
2695 #ifdef USE_KEYRR
2696 if (ugh)
2697 {
2698 /* if no TXT with right key, try KEY */
2699 DBG(DBG_CONTROL,
2700 DBG_log("will try for KEY RR since initiate on demand found %s: %s"
2701 , ugh, mycredentialstr));
2702 next_step = fos_our_key;
2703 ugh = NULL;
2704 }
2705 #endif
2706 }
2707 }
2708 break;
2709
2710 #ifdef USE_KEYRR
2711 case fos_our_key: /* KEY for us */
2712 {
2713 /* Check if KEY lookup yielded good results.
2714 * Looking up based on our ID. Used if
2715 * client is ourself, or if TXT had no public key.
2716 * Note: if c is different this time, there is
2717 * a chance that we did the wrong query.
2718 * If so, treat as a kind of failure.
2719 */
2720 private_key_t *private = get_private_key(c);
2721
2722 next_step = fos_his_client; /* always */
2723
2724 if (private == NULL)
2725 {
2726 ugh = "we don't know our own RSA key";
2727 }
2728 else if (!same_id(&ac->id, &c->spd.this.id))
2729 {
2730 ugh = "our ID changed underfoot";
2731 }
2732 else
2733 {
2734 /* Similar to code in RSA_check_signature
2735 * for checking the other side.
2736 */
2737 pubkey_list_t *kr;
2738
2739 ugh = "no KEY RR found for us (and no good TXT RR)";
2740 for (kr = ac->keys_from_dns; kr != NULL; kr = kr->next)
2741 {
2742 ugh = "all our KEY RRs have the wrong public key (and no good TXT RR)";
2743 if (kr->key->alg == PUBKEY_ALG_RSA
2744 && private->belongs_to(private, kr->key->public_key))
2745 {
2746 /* do this only once a day */
2747 if (!logged_txt_warning)
2748 {
2749 loglog(RC_LOG_SERIOUS
2750 , "found KEY RR but not TXT RR for %s. See http://www.freeswan.org/err/txt-change.html."
2751 , mycredentialstr);
2752 logged_txt_warning = TRUE;
2753 }
2754 ugh = NULL; /* good! */
2755 break;
2756 }
2757 }
2758 }
2759 }
2760 break;
2761 #endif /* USE_KEYRR */
2762
2763 case fos_his_client: /* TXT for his client */
2764 {
2765 /* We've finished last DNS queries: TXT for his client.
2766 * Using the information, try to instantiate a connection
2767 * and start negotiating.
2768 * We now know the peer. The chosing of "c" ignored this,
2769 * so we will disregard its current value.
2770 * !!! We need to randomize the entry in gw that we choose.
2771 */
2772 next_step = fos_done; /* no more queries */
2773
2774 c = build_outgoing_opportunistic_connection(ac->gateways_from_dns
2775 , &b->our_client
2776 , &b->peer_client);
2777
2778 if (c == NULL)
2779 {
2780 /* We cannot seem to instantiate a suitable connection:
2781 * complain clearly.
2782 */
2783 char ocb[ADDRTOT_BUF], pcb[ADDRTOT_BUF];
2784
2785 addrtot(&b->our_client, 0, ocb, sizeof(ocb));
2786 addrtot(&b->peer_client, 0, pcb, sizeof(pcb));
2787 loglog(RC_OPPOFAILURE,
2788 "no suitable connection for opportunism "
2789 "between %s and %s with %Y as peer",
2790 ocb, pcb, ac->gateways_from_dns->gw_id);
2791 }
2792 else
2793 {
2794 /* If we are to proceed asynchronously, b->whackfd will be NULL_FD. */
2795 passert(c->kind == CK_INSTANCE);
2796 passert(c->gw_info != NULL);
2797 passert(HAS_IPSEC_POLICY(c->policy));
2798 passert(LHAS(LELEM(RT_UNROUTED) | LELEM(RT_ROUTED_PROSPECTIVE), c->spd.routing));
2799 if (b->held)
2800 {
2801 /* what should we do on failure? */
2802 (void) assign_hold(c, &c->spd
2803 , b->transport_proto
2804 , &b->our_client, &b->peer_client);
2805 }
2806 c->gw_info->key->last_tried_time = now();
2807 ipsecdoi_initiate(b->whackfd, c, c->policy, 1, SOS_NOBODY);
2808 b->whackfd = NULL_FD; /* protect from close */
2809 }
2810 }
2811 break;
2812
2813 default:
2814 bad_case(b->step);
2815 }
2816
2817 /* the second chunk: initiate the next DNS query (if any) */
2818 DBG(DBG_CONTROL,
2819 {
2820 char ours[ADDRTOT_BUF];
2821 char his[ADDRTOT_BUF];
2822
2823 addrtot(&b->our_client, 0, ours, sizeof(ours));
2824 addrtot(&b->peer_client, 0, his, sizeof(his));
2825 DBG_log("initiate on demand from %s to %s new state: %s with ugh: %s"
2826 , ours, his, oppo_step_name[b->step], ugh ? ugh : "ok");
2827 });
2828
2829 if (ugh)
2830 {
2831 b->policy_prio = c->prio;
2832 b->failure_shunt = shunt_policy_spi(c, FALSE);
2833 cannot_oppo(c, b, ugh);
2834 }
2835 else if (next_step == fos_done)
2836 {
2837 /* nothing to do */
2838 }
2839 else
2840 {
2841 /* set up the next query */
2842 struct find_oppo_continuation *cr = malloc_thing(struct find_oppo_continuation);
2843 identification_t *id;
2844
2845 b->policy_prio = c->prio;
2846 b->failure_shunt = shunt_policy_spi(c, FALSE);
2847 cr->b = *b; /* copy; start hand off of whackfd */
2848 cr->b.failure_ok = FALSE;
2849 cr->b.step = next_step;
2850
2851 for (sr = &c->spd
2852 ; sr!=NULL && !sameaddr(&sr->this.host_addr, &b->our_client)
2853 ; sr = sr->next)
2854 ;
2855
2856 if (sr == NULL)
2857 sr = &c->spd;
2858
2859 /* If a %hold shunt has replaced the eroute for this template,
2860 * record this fact.
2861 */
2862 if (b->held
2863 && sr->routing == RT_ROUTED_PROSPECTIVE && eclipsable(sr))
2864 {
2865 sr->routing = RT_ROUTED_ECLIPSED;
2866 eclipse_count++;
2867 }
2868
2869 /* Switch to issue next query.
2870 * A case may turn out to be unnecessary. If so, it falls
2871 * through to the next case.
2872 * Figuring out what %myid can stand for must be done before
2873 * our client credentials are looked up: we must know what
2874 * the client credentials may use to identify us.
2875 * On the other hand, our own credentials should be looked
2876 * up after our clients in case our credentials are not
2877 * needed at all.
2878 * XXX this is a wasted effort if we don't have credentials
2879 * BUT they are not needed.
2880 */
2881 switch (next_step)
2882 {
2883 case fos_myid_ip_txt:
2884 if (c->spd.this.id->get_type(c->spd.this.id) == ID_MYID
2885 && myid_state != MYID_SPECIFIED)
2886 {
2887 cr->b.failure_ok = TRUE;
2888 cr->b.want = b->want = "TXT record for IP address as %myid";
2889 ugh = start_adns_query(myids[MYID_IP], myids[MYID_IP],
2890 T_TXT, continue_oppo, &cr->ac);
2891 break;
2892 }
2893 cr->b.step = fos_myid_hostname_txt;
2894 /* fall through */
2895
2896 case fos_myid_hostname_txt:
2897 if (c->spd.this.id->get_type(c->spd.this.id) == ID_MYID
2898 && myid_state != MYID_SPECIFIED)
2899 {
2900 #ifdef USE_KEYRR
2901 cr->b.failure_ok = TRUE;
2902 #else
2903 cr->b.failure_ok = FALSE;
2904 #endif
2905 cr->b.want = b->want = "TXT record for hostname as %myid";
2906 ugh = start_adns_query(myids[MYID_HOSTNAME],
2907 myids[MYID_HOSTNAME],
2908 T_TXT, continue_oppo, &cr->ac);
2909 break;
2910 }
2911
2912 #ifdef USE_KEYRR
2913 cr->b.step = fos_myid_ip_key;
2914 /* fall through */
2915
2916 case fos_myid_ip_key:
2917 if (c->spd.this.id.kind == ID_MYID
2918 && myid_state != MYID_SPECIFIED)
2919 {
2920 cr->b.failure_ok = TRUE;
2921 cr->b.want = b->want = "KEY record for IP address as %myid (no good TXT)";
2922 ugh = start_adns_query(myids[MYID_IP], NULL, /* security gateway meaningless */
2923 T_KEY, continue_oppo, &cr->ac);
2924 break;
2925 }
2926 cr->b.step = fos_myid_hostname_key;
2927 /* fall through */
2928
2929 case fos_myid_hostname_key:
2930 if (c->spd.this.id.kind == ID_MYID
2931 && myid_state != MYID_SPECIFIED)
2932 {
2933 cr->b.failure_ok = FALSE; /* last attempt! */
2934 cr->b.want = b->want = "KEY record for hostname as %myid (no good TXT)";
2935 ugh = start_adns_query(myids[MYID_HOSTNAME], NULL, /* security gateway meaningless */
2936 T_KEY, continue_oppo, &cr->ac);
2937 break;
2938 }
2939 #endif
2940 cr->b.step = fos_our_client;
2941 /* fall through */
2942
2943 case fos_our_client: /* TXT for our client */
2944 if (!sameaddr(&c->spd.this.host_addr, &b->our_client))
2945 {
2946 /* Check that at least one TXT(reverse(b->our_client)) is workable.
2947 * Note: {unshare|free}_id_content not needed for id: ephemeral.
2948 */
2949 cr->b.want = b->want = "our client's TXT record";
2950 id = identification_create_from_sockaddr((sockaddr_t*)&b->our_client);
2951 ugh = start_adns_query(id, c->spd.this.id, /* we are the security gateway */
2952 T_TXT, continue_oppo, &cr->ac);
2953 id->destroy(id);
2954 break;
2955 }
2956 cr->b.step = fos_our_txt;
2957 /* fall through */
2958
2959 case fos_our_txt: /* TXT for us */
2960 cr->b.failure_ok = b->failure_ok = TRUE;
2961 cr->b.want = b->want = "our TXT record";
2962 ugh = start_adns_query(sr->this.id, sr->this.id, /* we are the security gateway */
2963 T_TXT, continue_oppo, &cr->ac);
2964 break;
2965
2966 #ifdef USE_KEYRR
2967 case fos_our_key: /* KEY for us */
2968 cr->b.want = b->want = "our KEY record";
2969 cr->b.failure_ok = b->failure_ok = FALSE;
2970 ugh = start_adns_query(sr->this.id, NULL, /* security gateway meaningless */
2971 T_KEY, continue_oppo, &cr->ac);
2972 break;
2973 #endif /* USE_KEYRR */
2974
2975 case fos_his_client: /* TXT for his client */
2976 /* note: {unshare|free}_id_content not needed for id: ephemeral */
2977 cr->b.want = b->want = "target's TXT record";
2978 cr->b.failure_ok = b->failure_ok = FALSE;
2979 id = identification_create_from_sockaddr((sockaddr_t*)&b->peer_client);
2980 ugh = start_adns_query(id, NULL, /* security gateway unconstrained */
2981 T_TXT, continue_oppo, &cr->ac);
2982 id->destroy(id);
2983 break;
2984
2985 default:
2986 bad_case(next_step);
2987 }
2988
2989 if (ugh == NULL)
2990 b->whackfd = NULL_FD; /* complete hand-off */
2991 else
2992 cannot_oppo(c, b, ugh);
2993 }
2994 }
2995 close_any(b->whackfd);
2996 }
2997
2998 void terminate_connection(const char *nm)
2999 {
3000 /* Loop because more than one may match (master and instances)
3001 * But at least one is required (enforced by con_by_name).
3002 */
3003 connection_t *c = con_by_name(nm, TRUE);
3004
3005 if (c == NULL || !c->ikev1)
3006 return;
3007
3008 do
3009 {
3010 connection_t *n = c->ac_next; /* grab this before c might disappear */
3011
3012 if (streq(c->name, nm)
3013 && c->kind >= CK_PERMANENT
3014 && !NEVER_NEGOTIATE(c->policy))
3015 {
3016 set_cur_connection(c);
3017 plog("terminating SAs using this connection");
3018 c->policy &= ~POLICY_UP;
3019 flush_pending_by_connection(c);
3020 delete_states_by_connection(c, FALSE);
3021 if (c->kind == CK_INSTANCE)
3022 delete_connection(c, FALSE);
3023 reset_cur_connection();
3024 }
3025 c = n;
3026 } while (c);
3027 }
3028
3029 /* an ISAKMP SA has been established.
3030 * Note the serial number, and release any connections with
3031 * the same peer ID but different peer IP address.
3032 */
3033 bool uniqueIDs = FALSE; /* --uniqueids? */
3034
3035 void ISAKMP_SA_established(connection_t *c, so_serial_t serial)
3036 {
3037 c->newest_isakmp_sa = serial;
3038
3039 /* the connection is now oriented so that we are able to determine
3040 * whether we are a mode config server with a virtual IP to send.
3041 */
3042 if (!c->spd.that.host_srcip->is_anyaddr(c->spd.that.host_srcip) &&
3043 !c->spd.that.has_natip)
3044 {
3045 c->spd.that.modecfg = TRUE;
3046 }
3047
3048 if (uniqueIDs)
3049 {
3050 /* for all connections: if the same Phase 1 IDs are used
3051 * for a different IP address, unorient that connection.
3052 */
3053 connection_t *d;
3054
3055 for (d = connections; d != NULL; )
3056 {
3057 connection_t *next = d->ac_next; /* might move underneath us */
3058
3059 if (d->kind >= CK_PERMANENT &&
3060 c->spd.this.id->equals(c->spd.this.id, d->spd.this.id) &&
3061 c->spd.that.id->equals(c->spd.that.id, d->spd.that.id) &&
3062 !sameaddr(&c->spd.that.host_addr, &d->spd.that.host_addr))
3063 {
3064 release_connection(d, FALSE);
3065 }
3066 d = next;
3067 }
3068 }
3069 }
3070
3071 /* Find the connection to connection c's peer's client with the
3072 * largest value of .routing. All other things being equal,
3073 * preference is given to c. If none is routed, return NULL.
3074 *
3075 * If erop is non-null, set *erop to a connection sharing both
3076 * our client subnet and peer's client subnet with the largest value
3077 * of .routing. If none is erouted, set *erop to NULL.
3078 *
3079 * The return value is used to find other connections sharing a route.
3080 * *erop is used to find other connections sharing an eroute.
3081 */
3082 connection_t *route_owner(connection_t *c, struct spd_route **srp,
3083 connection_t **erop, struct spd_route **esrp)
3084 {
3085 connection_t *d
3086 , *best_ro = c
3087 , *best_ero = c;
3088 struct spd_route *srd, *src;
3089 struct spd_route *best_sr, *best_esr;
3090 enum routing_t best_routing, best_erouting;
3091
3092 passert(oriented(*c));
3093 best_sr = NULL;
3094 best_esr = NULL;
3095 best_routing = c->spd.routing;
3096 best_erouting = best_routing;
3097
3098 for (d = connections; d != NULL; d = d->ac_next)
3099 {
3100 for (srd = &d->spd; srd; srd = srd->next)
3101 {
3102 if (srd->routing == RT_UNROUTED)
3103 continue;
3104
3105 for (src = &c->spd; src; src=src->next)
3106 {
3107 if (!samesubnet(&src->that.client, &srd->that.client))
3108 {
3109 continue;
3110 }
3111 if (src->that.protocol != srd->that.protocol)
3112 {
3113 continue;
3114 }
3115 if (src->that.port != srd->that.port)
3116 {
3117 continue;
3118 }
3119 passert(oriented(*d));
3120 if (srd->routing > best_routing)
3121 {
3122 best_ro = d;
3123 best_sr = srd;
3124 best_routing = srd->routing;
3125 }
3126
3127 if (!samesubnet(&src->this.client, &srd->this.client))
3128 {
3129 continue;
3130 }
3131 if (src->this.protocol != srd->this.protocol)
3132 {
3133 continue;
3134 }
3135 if (src->this.port != srd->this.port)
3136 {
3137 continue;
3138 }
3139 if (srd->routing > best_erouting)
3140 {
3141 best_ero = d;
3142 best_esr = srd;
3143 best_erouting = srd->routing;
3144 }
3145 }
3146 }
3147 }
3148
3149 DBG(DBG_CONTROL,
3150 {
3151 char cib[CONN_INST_BUF];
3152 err_t m = builddiag("route owner of \"%s\"%s %s:"
3153 , c->name
3154 , (fmt_conn_instance(c, cib), cib)
3155 , enum_name(&routing_story, c->spd.routing));
3156
3157 if (!routed(best_ro->spd.routing))
3158 m = builddiag("%s NULL", m);
3159 else if (best_ro == c)
3160 m = builddiag("%s self", m);
3161 else
3162 m = builddiag("%s \"%s\"%s %s", m
3163 , best_ro->name
3164 , (fmt_conn_instance(best_ro, cib), cib)
3165 , enum_name(&routing_story, best_ro->spd.routing));
3166
3167 if (erop)
3168 {
3169 m = builddiag("%s; eroute owner:", m);
3170 if (!erouted(best_ero->spd.routing))
3171 m = builddiag("%s NULL", m);
3172 else if (best_ero == c)
3173 m = builddiag("%s self", m);
3174 else
3175 m = builddiag("%s \"%s\"%s %s", m
3176 , best_ero->name
3177 , (fmt_conn_instance(best_ero, cib), cib)
3178 , enum_name(&routing_story, best_ero->spd.routing));
3179 }
3180
3181 DBG_log("%s", m);
3182 });
3183
3184 if (erop)
3185 {
3186 *erop = erouted(best_erouting)? best_ero : NULL;
3187 }
3188 if (srp)
3189 {
3190 *srp = best_sr;
3191 if (esrp)
3192 {
3193 *esrp = best_esr;
3194 }
3195 }
3196
3197 return routed(best_routing)? best_ro : NULL;
3198 }
3199
3200 /* Find a connection that owns the shunt eroute between subnets.
3201 * There ought to be only one.
3202 * This might get to be a bottleneck -- try hashing if it does.
3203 */
3204 connection_t *shunt_owner(const ip_subnet *ours, const ip_subnet *his)
3205 {
3206 connection_t *c;
3207 struct spd_route *sr;
3208
3209 for (c = connections; c != NULL; c = c->ac_next)
3210 {
3211 for (sr = &c->spd; sr; sr = sr->next)
3212 {
3213 if (shunt_erouted(sr->routing)
3214 && samesubnet(ours, &sr->this.client)
3215 && samesubnet(his, &sr->that.client))
3216 return c;
3217 }
3218 }
3219 return NULL;
3220 }
3221
3222 /* Find some connection with this pair of hosts.
3223 * We don't know enough to chose amongst those available.
3224 * ??? no longer usefully different from find_host_pair_connections
3225 */
3226 connection_t *find_host_connection(const ip_address *me, u_int16_t my_port,
3227 const ip_address *him, u_int16_t his_port,
3228 lset_t policy)
3229 {
3230 connection_t *c = find_host_pair_connections(me, my_port, him, his_port);
3231
3232 if (policy != LEMPTY)
3233 {
3234 lset_t auth_requested = policy & POLICY_ID_AUTH_MASK;
3235
3236 /* if we have requirements for the policy,
3237 * choose the first matching connection.
3238 */
3239 while (c)
3240 {
3241 if (c->policy & auth_requested)
3242 {
3243 break;
3244 }
3245 c = c->hp_next;
3246 }
3247 }
3248 return c;
3249 }
3250
3251 /* given an up-until-now satisfactory connection, find the best connection
3252 * now that we just got the Phase 1 Id Payload from the peer.
3253 *
3254 * Comments in the code describe the (tricky!) matching criteria.
3255 * Although this routine could handle the initiator case,
3256 * it isn't currently called in this case.
3257 * If it were, it could "upgrade" an Opportunistic Connection
3258 * to a Road Warrior Connection if a suitable Peer ID were found.
3259 *
3260 * In RFC 2409 "The Internet Key Exchange (IKE)",
3261 * in 5.1 "IKE Phase 1 Authenticated With Signatures", describing Main
3262 * Mode:
3263 *
3264 * Initiator Responder
3265 * ----------- -----------
3266 * HDR, SA -->
3267 * <-- HDR, SA
3268 * HDR, KE, Ni -->
3269 * <-- HDR, KE, Nr
3270 * HDR*, IDii, [ CERT, ] SIG_I -->
3271 * <-- HDR*, IDir, [ CERT, ] SIG_R
3272 *
3273 * In 5.4 "Phase 1 Authenticated With a Pre-Shared Key":
3274 *
3275 * HDR, SA -->
3276 * <-- HDR, SA
3277 * HDR, KE, Ni -->
3278 * <-- HDR, KE, Nr
3279 * HDR*, IDii, HASH_I -->
3280 * <-- HDR*, IDir, HASH_R
3281 *
3282 * refine_host_connection could be called in two case:
3283 *
3284 * - the Responder receives the IDii payload:
3285 * + [PSK] after using PSK to decode this message
3286 * + before sending its IDir payload
3287 * + before using its ID in HASH_R computation
3288 * + [DSig] before using its private key to sign SIG_R
3289 * + before using the Initiator's ID in HASH_I calculation
3290 * + [DSig] before using the Initiator's public key to check SIG_I
3291 *
3292 * - the Initiator receives the IDir payload:
3293 * + [PSK] after using PSK to encode previous message and decode this message
3294 * + after sending its IDii payload
3295 * + after using its ID in HASH_I computation
3296 * + [DSig] after using its private key to sign SIG_I
3297 * + before using the Responder's ID to compute HASH_R
3298 * + [DSig] before using Responder's public key to check SIG_R
3299 *
3300 * refine_host_connection can choose a different connection, as long as
3301 * nothing already used is changed.
3302 *
3303 * In the Initiator case, the particular connection might have been
3304 * specified by whatever provoked Pluto to initiate. For example:
3305 * whack --initiate connection-name
3306 * The advantages of switching connections when we're the Initiator seem
3307 * less important than the disadvantages, so after FreeS/WAN 1.9, we
3308 * don't do this.
3309 */
3310 #define PRIO_NO_MATCH_FOUND 2048
3311
3312 connection_t *refine_host_connection(const struct state *st,
3313 identification_t *peer_id,
3314 identification_t *peer_ca)
3315 {
3316 connection_t *c = st->st_connection;
3317 connection_t *d;
3318 connection_t *best_found = NULL;
3319 u_int16_t auth = st->st_oakley.auth;
3320 lset_t auth_policy = POLICY_PSK;
3321 const chunk_t *psk = NULL;
3322 bool wcpip; /* wildcard Peer IP? */
3323 int best_prio = PRIO_NO_MATCH_FOUND;
3324 int our_pathlen, peer_pathlen;
3325
3326 if (c->spd.that.id->equals(c->spd.that.id, peer_id) &&
3327 trusted_ca(peer_ca, c->spd.that.ca, &peer_pathlen) &&
3328 peer_pathlen == 0 &&
3329 match_requested_ca(c->requested_ca, c->spd.this.ca, &our_pathlen) &&
3330 our_pathlen == 0)
3331 {
3332 DBG(DBG_CONTROL,
3333 DBG_log("current connection is a full match"
3334 " -- no need to look further");
3335 )
3336 return c;
3337 }
3338
3339 switch (auth)
3340 {
3341 case OAKLEY_PRESHARED_KEY:
3342 auth_policy = POLICY_PSK;
3343 psk = get_preshared_secret(c);
3344 /* It should be virtually impossible to fail to find PSK:
3345 * we just used it to decode the current message!
3346 */
3347 if (psk == NULL)
3348 {
3349 return NULL; /* cannot determine PSK! */
3350 }
3351 break;
3352 case XAUTHInitPreShared:
3353 case XAUTHRespPreShared:
3354 auth_policy = POLICY_XAUTH_PSK;
3355 psk = get_preshared_secret(c);
3356 if (psk == NULL)
3357 {
3358 return NULL; /* cannot determine PSK! */
3359 }
3360 break;
3361 case OAKLEY_RSA_SIG:
3362 case OAKLEY_ECDSA_256:
3363 case OAKLEY_ECDSA_384:
3364 case OAKLEY_ECDSA_521:
3365 auth_policy = POLICY_PUBKEY;
3366 break;
3367 case XAUTHInitRSA:
3368 case XAUTHRespRSA:
3369 auth_policy = POLICY_XAUTH_RSASIG;
3370 break;
3371 default:
3372 bad_case(auth);
3373 }
3374
3375 /* The current connection won't do: search for one that will.
3376 * First search for one with the same pair of hosts.
3377 * If that fails, search for a suitable Road Warrior or Opportunistic
3378 * connection (i.e. wildcard peer IP).
3379 * We need to match:
3380 * - peer_id (slightly complicated by instantiation)
3381 * - if PSK auth, the key must not change (we used it to decode message)
3382 * - policy-as-used must be acceptable to new connection
3383 */
3384 d = c->host_pair->connections;
3385 for (wcpip = FALSE; ; wcpip = TRUE)
3386 {
3387 for (; d != NULL; d = d->hp_next)
3388 {
3389 const char *match_name[] = {"no", "ok"};
3390
3391 id_match_t match_level = peer_id->matches(peer_id, d->spd.that.id);
3392
3393 bool matching_id = match_level > ID_MATCH_NONE;
3394
3395 bool matching_auth = (d->policy & auth_policy) != LEMPTY;
3396
3397 bool matching_trust = trusted_ca(peer_ca
3398 , d->spd.that.ca, &peer_pathlen);
3399 bool matching_request = match_requested_ca(c->requested_ca
3400 , d->spd.this.ca, &our_pathlen);
3401 bool match = matching_id && matching_auth && matching_trust;
3402
3403 int prio = (ID_MATCH_PERFECT) * !matching_request +
3404 ID_MATCH_PERFECT - match_level;
3405
3406 prio = (X509_MAX_PATH_LEN + 1) * prio + peer_pathlen;
3407 prio = (X509_MAX_PATH_LEN + 1) * prio + our_pathlen;
3408
3409 DBG(DBG_CONTROLMORE,
3410 DBG_log("%s: %s match (id: %s, auth: %s, trust: %s, request: %s, prio: %4d)"
3411 , d->name
3412 , match ? "full":" no"
3413 , match_name[matching_id]
3414 , match_name[matching_auth]
3415 , match_name[matching_trust]
3416 , match_name[matching_request]
3417 , match ? prio:PRIO_NO_MATCH_FOUND)
3418 )
3419
3420 /* do we have a match? */
3421 if (!match)
3422 {
3423 continue;
3424 }
3425
3426 /* ignore group connections */
3427 if (d->policy & POLICY_GROUP)
3428 {
3429 continue;
3430 }
3431
3432 if (c->spd.that.host_port != d->spd.that.host_port
3433 && d->kind == CK_INSTANCE)
3434 {
3435 continue;
3436 }
3437
3438 switch (auth)
3439 {
3440 case OAKLEY_PRESHARED_KEY:
3441 case XAUTHInitPreShared:
3442 case XAUTHRespPreShared:
3443 /* secret must match the one we already used */
3444 {
3445 const chunk_t *dpsk = get_preshared_secret(d);
3446
3447 if (dpsk == NULL)
3448 {
3449 continue; /* no secret */
3450 }
3451 if (psk != dpsk)
3452 {
3453 if (psk->len != dpsk->len
3454 || memcmp(psk->ptr, dpsk->ptr, psk->len) != 0)
3455 {
3456 continue; /* different secret */
3457 }
3458 }
3459 }
3460 break;
3461
3462 case OAKLEY_RSA_SIG:
3463 case OAKLEY_ECDSA_256:
3464 case OAKLEY_ECDSA_384:
3465 case OAKLEY_ECDSA_521:
3466 case XAUTHInitRSA:
3467 case XAUTHRespRSA:
3468 /*
3469 * We must at least be able to find our private key
3470 .*/
3471 if (d->spd.this.sc == NULL /* no smartcard */
3472 && get_private_key(d) == NULL) /* no private key */
3473 {
3474 continue;
3475 }
3476 break;
3477
3478 default:
3479 bad_case(auth);
3480 }
3481
3482 /* d has passed all the tests.
3483 * We'll go with it if the Peer ID was an exact match.
3484 */
3485 if (prio == 0)
3486 {
3487 return d;
3488 }
3489
3490 /* We'll remember it as best_found in case an exact
3491 * match doesn't come along.
3492 */
3493 if (prio < best_prio)
3494 {
3495 best_found = d;
3496 best_prio = prio;
3497 }
3498 }
3499 if (wcpip)
3500 return best_found; /* been around twice already */
3501
3502 /* Starting second time around.
3503 * We're willing to settle for a connection that needs Peer IP
3504 * instantiated: Road Warrior or Opportunistic.
3505 * Look on list of connections for host pair with wildcard Peer IP
3506 */
3507 d = find_host_pair_connections(&c->spd.this.host_addr, c->spd.this.host_port
3508 , (ip_address *)NULL, c->spd.that.host_port);
3509 }
3510 }
3511
3512 /**
3513 * With virtual addressing, we must not allow someone to use an already
3514 * used (by another id) addr/net.
3515 */
3516 static bool is_virtual_net_used(const ip_subnet *peer_net,
3517 identification_t *peer_id)
3518 {
3519 connection_t *d;
3520
3521 for (d = connections; d != NULL; d = d->ac_next)
3522 {
3523 switch (d->kind)
3524 {
3525 case CK_PERMANENT:
3526 case CK_INSTANCE:
3527 if ((subnetinsubnet(peer_net,&d->spd.that.client) ||
3528 subnetinsubnet(&d->spd.that.client,peer_net))
3529 && !d->spd.that.id->equals(d->spd.that.id, peer_id))
3530 {
3531 char client[SUBNETTOT_BUF];
3532
3533 subnettot(peer_net, 0, client, sizeof(client));
3534 plog("Virtual IP %s is already used by '%Y'",
3535 client, d->spd.that.id);
3536 plog("Your ID is '%Y'", peer_id);
3537
3538 return TRUE; /* already used by another one */
3539 }
3540 break;
3541 case CK_GOING_AWAY:
3542 default:
3543 break;
3544 }
3545 }
3546 return FALSE; /* you can safely use it */
3547 }
3548
3549 /* find_client_connection: given a connection suitable for ISAKMP
3550 * (i.e. the hosts match), find a one suitable for IPSEC
3551 * (i.e. with matching clients).
3552 *
3553 * If we don't find an exact match (not even our current connection),
3554 * we try for one that still needs instantiation. Try Road Warrior
3555 * abstract connections and the Opportunistic abstract connections.
3556 * This requires inverse instantiation: abstraction.
3557 *
3558 * After failing to find an exact match, we abstract the peer
3559 * to be NO_IP (the wildcard value). This enables matches with
3560 * Road Warrior and Opportunistic abstract connections.
3561 *
3562 * After failing that search, we also abstract the Phase 1 peer ID
3563 * if possible. If the peer's ID was the peer's IP address, we make
3564 * it NO_ID; instantiation will make it the peer's IP address again.
3565 *
3566 * If searching for a Road Warrior abstract connection fails,
3567 * and conditions are suitable, we search for the best Opportunistic
3568 * abstract connection.
3569 *
3570 * Note: in the end, both Phase 1 IDs must be preserved, after any
3571 * instantiation. They are the IDs that have been authenticated.
3572 */
3573
3574 #define PATH_WEIGHT 1
3575 #define WILD_WEIGHT (X509_MAX_PATH_LEN+1)
3576 #define PRIO_WEIGHT (ID_MATCH_PERFECT+1) * WILD_WEIGHT
3577
3578 /* fc_try: a helper function for find_client_connection */
3579 static connection_t *fc_try(const connection_t *c, struct host_pair *hp,
3580 identification_t *peer_id,
3581 const ip_subnet *our_net,
3582 const ip_subnet *peer_net,
3583 const u_int8_t our_protocol,
3584 const u_int16_t our_port,
3585 const u_int8_t peer_protocol,
3586 const u_int16_t peer_port,
3587 identification_t *peer_ca,
3588 ietf_attributes_t *peer_attributes)
3589 {
3590 connection_t *d;
3591 connection_t *best = NULL;
3592 policy_prio_t best_prio = BOTTOM_PRIO;
3593 id_match_t match_level;
3594 int pathlen;
3595
3596
3597 const bool peer_net_is_host = subnetisaddr(peer_net, &c->spd.that.host_addr);
3598
3599 for (d = hp->connections; d != NULL; d = d->hp_next)
3600 {
3601 struct spd_route *sr;