4d6af23aa9bf16f9f7de08df2c17849b31016bb4
[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 /* set internal fields */
1197 c->instance_serial = 0;
1198 c->ac_next = connections;
1199 connections = c;
1200 c->interface = NULL;
1201 c->spd.routing = RT_UNROUTED;
1202 c->newest_isakmp_sa = SOS_NOBODY;
1203 c->newest_ipsec_sa = SOS_NOBODY;
1204 c->spd.eroute_owner = SOS_NOBODY;
1205
1206 if (c->policy & POLICY_GROUP)
1207 {
1208 c->kind = CK_GROUP;
1209 add_group(c);
1210 }
1211 else if ((isanyaddr(&c->spd.that.host_addr) && !NEVER_NEGOTIATE(c->policy))
1212 || c->spd.that.has_client_wildcard || c->spd.that.has_port_wildcard
1213 || c->spd.that.has_id_wildcards || c->spd.that.allow_any)
1214 {
1215 /* Opportunistic or Road Warrior or wildcard client subnet
1216 * or wildcard ID */
1217 c->kind = CK_TEMPLATE;
1218 }
1219 else
1220 {
1221 c->kind = CK_PERMANENT;
1222 }
1223 set_policy_prio(c); /* must be after kind is set */
1224
1225 #ifdef DEBUG
1226 c->extra_debugging = wm->debugging;
1227 #endif
1228
1229 c->gw_info = NULL;
1230
1231 passert(!(wm->left.virt && wm->right.virt));
1232 if (wm->left.virt || wm->right.virt)
1233 {
1234 passert(isanyaddr(&c->spd.that.host_addr));
1235 c->spd.that.virt = create_virtual(c,
1236 wm->left.virt ? wm->left.virt : wm->right.virt);
1237 if (c->spd.that.virt)
1238 c->spd.that.has_client = TRUE;
1239 }
1240
1241 (void)orient(c);
1242
1243 /* if rightsourceip defines a subnet then create an in-memory pool */
1244 if (whack_attr->add_pool(whack_attr, c->name,
1245 c->spd.this.is_left ? &wm->right : &wm->left))
1246 {
1247 c->spd.that.pool = clone_str(c->name);
1248 c->spd.that.modecfg = TRUE;
1249 c->spd.that.has_client = FALSE;
1250 /* reset the host_srcip so that it gets assigned in modecfg */
1251 DESTROY_IF(c->spd.that.host_srcip);
1252 c->spd.that.host_srcip = host_create_any(AF_INET);
1253 }
1254
1255 if (c->ikev1)
1256 {
1257 connect_to_host_pair(c);
1258 }
1259
1260 /* log all about this connection */
1261 plog("added connection description \"%s\"", c->name);
1262 DBG(DBG_CONTROL,
1263 char topo[BUF_LEN];
1264
1265 (void) format_connection(topo, sizeof(topo), c, &c->spd);
1266
1267 DBG_log("%s", topo);
1268
1269 /* Make sure that address families can be correctly inferred
1270 * from printed ends.
1271 */
1272 passert(c->addr_family == addrtypeof(&c->spd.this.host_addr)
1273 && c->addr_family == addrtypeof(&c->spd.this.host_nexthop)
1274 && (c->spd.this.has_client? c->tunnel_addr_family : c->addr_family)
1275 == subnettypeof(&c->spd.this.client)
1276
1277 && c->addr_family == addrtypeof(&c->spd.that.host_addr)
1278 && c->addr_family == addrtypeof(&c->spd.that.host_nexthop)
1279 && (c->spd.that.has_client? c->tunnel_addr_family : c->addr_family)
1280 == subnettypeof(&c->spd.that.client));
1281
1282 DBG_log("ike_life: %lus; ipsec_life: %lus; rekey_margin: %lus;"
1283 " rekey_fuzz: %lu%%; keyingtries: %lu; policy: %s"
1284 , (unsigned long) c->sa_ike_life_seconds
1285 , (unsigned long) c->sa_ipsec_life_seconds
1286 , (unsigned long) c->sa_rekey_margin
1287 , (unsigned long) c->sa_rekey_fuzz
1288 , (unsigned long) c->sa_keying_tries
1289 , prettypolicy(c->policy));
1290 );
1291 }
1292 }
1293
1294 /* Derive a template connection from a group connection and target.
1295 * Similar to instantiate(). Happens at whack --listen.
1296 * Returns name of new connection. May be NULL.
1297 * Caller is responsible for freeing.
1298 */
1299 char *add_group_instance(connection_t *group, const ip_subnet *target)
1300 {
1301 char namebuf[100], targetbuf[SUBNETTOT_BUF];
1302 connection_t *t;
1303 char *name = NULL;
1304
1305 passert(group->kind == CK_GROUP);
1306 passert(oriented(*group));
1307
1308 /* manufacture a unique name for this template */
1309 subnettot(target, 0, targetbuf, sizeof(targetbuf));
1310 snprintf(namebuf, sizeof(namebuf), "%s#%s", group->name, targetbuf);
1311
1312 if (con_by_name(namebuf, FALSE) != NULL)
1313 {
1314 loglog(RC_DUPNAME, "group name + target yields duplicate name \"%s\""
1315 , namebuf);
1316 }
1317 else
1318 {
1319 t = clone_thing(*group);
1320 t->name = namebuf;
1321 unshare_connection_strings(t);
1322 name = clone_str(t->name);
1323 t->spd.that.client = *target;
1324 t->policy &= ~(POLICY_GROUP | POLICY_GROUTED);
1325 t->kind = isanyaddr(&t->spd.that.host_addr) && !NEVER_NEGOTIATE(t->policy)
1326 ? CK_TEMPLATE : CK_INSTANCE;
1327
1328 /* reset log file info */
1329 t->log_file_name = NULL;
1330 t->log_file = NULL;
1331 t->log_file_err = FALSE;
1332
1333 t->spd.reqid = gen_reqid();
1334
1335 if (t->spd.that.virt)
1336 {
1337 DBG_log("virtual_ip not supported in group instance");
1338 t->spd.that.virt = NULL;
1339 }
1340
1341 /* add to connections list */
1342 t->ac_next = connections;
1343 connections = t;
1344
1345 /* same host_pair as parent: stick after parent on list */
1346 group->hp_next = t;
1347
1348 /* route if group is routed */
1349 if (group->policy & POLICY_GROUTED)
1350 {
1351 if (!trap_connection(t))
1352 whack_log(RC_ROUTE, "could not route");
1353 }
1354 }
1355 return name;
1356 }
1357
1358 /* an old target has disappeared for a group: delete instance */
1359 void remove_group_instance(const connection_t *group USED_BY_DEBUG,
1360 const char *name)
1361 {
1362 passert(group->kind == CK_GROUP);
1363 passert(oriented(*group));
1364
1365 delete_connections_by_name(name, FALSE);
1366 }
1367
1368 /* Common part of instantiating a Road Warrior or Opportunistic connection.
1369 * his_id can be used to carry over an ID discovered in Phase 1.
1370 * It must not disagree with the one in c, but if that is unspecified,
1371 * the new connection will use his_id.
1372 * If his_id is NULL, and c.that.id is uninstantiated (ID_ANY), the
1373 * new connection will continue to have an uninstantiated that.id.
1374 * Note: instantiation does not affect port numbers.
1375 *
1376 * Note that instantiate can only deal with a single SPD/eroute.
1377 */
1378 static connection_t *instantiate(connection_t *c, const ip_address *him,
1379 u_int16_t his_port, identification_t *his_id)
1380 {
1381 connection_t *d;
1382
1383 passert(c->kind == CK_TEMPLATE);
1384 passert(c->spd.next == NULL);
1385
1386 c->instance_serial++;
1387 d = clone_thing(*c);
1388 d->spd.that.allow_any = FALSE;
1389
1390 if (his_id)
1391 {
1392 d->spd.that.id = his_id;
1393 d->spd.that.has_id_wildcards = FALSE;
1394 }
1395 unshare_connection_strings(d);
1396 if (d->spd.this.groups)
1397 {
1398 d->spd.this.groups = d->spd.this.groups->get_ref(d->spd.this.groups);
1399 }
1400 if (d->spd.that.groups)
1401 {
1402 d->spd.that.groups = d->spd.that.groups->get_ref(d->spd.that.groups);
1403 }
1404 d->kind = CK_INSTANCE;
1405
1406 passert(oriented(*d));
1407 d->spd.that.host_addr = *him;
1408 setportof(htons(c->spd.that.port), &d->spd.that.host_addr);
1409
1410 if (his_port) d->spd.that.host_port = his_port;
1411
1412 default_end(&d->spd.that, &d->spd.this.host_addr);
1413
1414 /* We cannot guess what our next_hop should be, but if it was
1415 * explicitly specified as 0.0.0.0, we set it to be him.
1416 * (whack will not allow nexthop to be elided in RW case.)
1417 */
1418 default_end(&d->spd.this, &d->spd.that.host_addr);
1419 d->spd.next = NULL;
1420 d->spd.reqid = gen_reqid();
1421
1422 /* set internal fields */
1423 d->ac_next = connections;
1424 connections = d;
1425 d->spd.routing = RT_UNROUTED;
1426 d->newest_isakmp_sa = SOS_NOBODY;
1427 d->newest_ipsec_sa = SOS_NOBODY;
1428 d->spd.eroute_owner = SOS_NOBODY;
1429
1430 /* reset log file info */
1431 d->log_file_name = NULL;
1432 d->log_file = NULL;
1433 d->log_file_err = FALSE;
1434
1435 connect_to_host_pair(d);
1436
1437 return d;
1438 if (sameaddr(&d->spd.that.host_addr, &d->spd.this.host_nexthop))
1439 {
1440 d->spd.this.host_nexthop = *him;
1441 }
1442 }
1443
1444 connection_t *rw_instantiate(connection_t *c, const ip_address *him,
1445 u_int16_t his_port, const ip_subnet *his_net,
1446 identification_t *his_id)
1447 {
1448 connection_t *d = instantiate(c, him, his_port, his_id);
1449
1450 if (d && his_net && is_virtual_connection(c))
1451 {
1452 d->spd.that.client = *his_net;
1453 d->spd.that.virt = NULL;
1454 if (subnetishost(his_net) && addrinsubnet(him, his_net))
1455 d->spd.that.has_client = FALSE;
1456 }
1457
1458 if (d->policy & POLICY_OPPO)
1459 {
1460 /* This must be before we know the client addresses.
1461 * Fill in one that is impossible. This prevents anyone else from
1462 * trying to use this connection to get to a particular client
1463 */
1464 d->spd.that.client = *aftoinfo(subnettypeof(&d->spd.that.client))->none;
1465 }
1466 DBG(DBG_CONTROL
1467 , DBG_log("instantiated \"%s\" for %s" , d->name, ip_str(him)));
1468 return d;
1469 }
1470
1471 connection_t *oppo_instantiate(connection_t *c, const ip_address *him,
1472 identification_t *his_id, struct gw_info *gw,
1473 const ip_address *our_client USED_BY_DEBUG,
1474 const ip_address *peer_client)
1475 {
1476 connection_t *d = instantiate(c, him, 0, his_id);
1477
1478 passert(d->spd.next == NULL);
1479
1480 /* fill in our client side */
1481 if (d->spd.this.has_client)
1482 {
1483 /* there was a client in the abstract connection
1484 * so we demand that the required client is within that subnet.
1485 */
1486 passert(addrinsubnet(our_client, &d->spd.this.client));
1487 happy(addrtosubnet(our_client, &d->spd.this.client));
1488 /* opportunistic connections do not use port selectors */
1489 setportof(0, &d->spd.this.client.addr);
1490 }
1491 else
1492 {
1493 /* there was no client in the abstract connection
1494 * so we demand that the required client be the host
1495 */
1496 passert(sameaddr(our_client, &d->spd.this.host_addr));
1497 }
1498
1499 /* fill in peer's client side.
1500 * If the client is the peer, excise the client from the connection.
1501 */
1502 passert((d->policy & POLICY_OPPO)
1503 && addrinsubnet(peer_client, &d->spd.that.client));
1504 happy(addrtosubnet(peer_client, &d->spd.that.client));
1505 /* opportunistic connections do not use port selectors */
1506 setportof(0, &d->spd.that.client.addr);
1507
1508 if (sameaddr(peer_client, &d->spd.that.host_addr))
1509 d->spd.that.has_client = FALSE;
1510
1511 passert(d->gw_info == NULL);
1512 gw_addref(gw);
1513 d->gw_info = gw;
1514
1515 /* Adjust routing if something is eclipsing c.
1516 * It must be a %hold for us (hard to passert this).
1517 * If there was another instance eclipsing, we'd be using it.
1518 */
1519 if (c->spd.routing == RT_ROUTED_ECLIPSED)
1520 d->spd.routing = RT_ROUTED_PROSPECTIVE;
1521
1522 /* Remember if the template is routed:
1523 * if so, this instance applies for initiation
1524 * even if it is created for responding.
1525 */
1526 if (routed(c->spd.routing))
1527 d->instance_initiation_ok = TRUE;
1528
1529 DBG(DBG_CONTROL,
1530 char topo[BUF_LEN];
1531
1532 (void) format_connection(topo, sizeof(topo), d, &d->spd);
1533 DBG_log("instantiated \"%s\": %s", d->name, topo);
1534 );
1535 return d;
1536 }
1537
1538 /* priority formatting */
1539 void fmt_policy_prio(policy_prio_t pp, char buf[POLICY_PRIO_BUF])
1540 {
1541 if (pp == BOTTOM_PRIO)
1542 {
1543 snprintf(buf, POLICY_PRIO_BUF, "0");
1544 }
1545 else
1546 {
1547 snprintf(buf, POLICY_PRIO_BUF, "%lu,%lu"
1548 , pp>>16, (pp & ~(~(policy_prio_t)0 << 16)) >> 8);
1549 }
1550 }
1551
1552 /* Format any information needed to identify an instance of a connection.
1553 * Fills any needed information into buf which MUST be big enough.
1554 * Road Warrior: peer's IP address
1555 * Opportunistic: [" " myclient "==="] " ..." peer ["===" hisclient] '\0'
1556 */
1557 static size_t fmt_client(const ip_subnet *client, const ip_address *gw,
1558 const char *prefix, char buf[ADDRTOT_BUF])
1559 {
1560 if (subnetisaddr(client, gw))
1561 {
1562 buf[0] = '\0'; /* compact denotation for "self" */
1563 }
1564 else
1565 {
1566 char *ap;
1567
1568 strcpy(buf, prefix);
1569 ap = buf + strlen(prefix);
1570 if (subnetisnone(client))
1571 strcpy(ap, "?"); /* unknown */
1572 else
1573 subnettot(client, 0, ap, SUBNETTOT_BUF);
1574 }
1575 return strlen(buf);
1576 }
1577
1578 void fmt_conn_instance(const connection_t *c, char buf[CONN_INST_BUF])
1579 {
1580 char *p = buf;
1581
1582 *p = '\0';
1583
1584 if (c->kind == CK_INSTANCE)
1585 {
1586 if (c->instance_serial != 0)
1587 {
1588 snprintf(p, CONN_INST_BUF, "[%lu]", c->instance_serial);
1589 p += strlen(p);
1590 }
1591
1592 if (c->policy & POLICY_OPPO)
1593 {
1594 size_t w = fmt_client(&c->spd.this.client, &c->spd.this.host_addr, " ", p);
1595
1596 p += w;
1597
1598 strcpy(p, w == 0? " ..." : "=== ...");
1599 p += strlen(p);
1600
1601 addrtot(&c->spd.that.host_addr, 0, p, ADDRTOT_BUF);
1602 p += strlen(p);
1603
1604 (void) fmt_client(&c->spd.that.client, &c->spd.that.host_addr, "===", p);
1605 }
1606 else
1607 {
1608 *p++ = ' ';
1609 addrtot(&c->spd.that.host_addr, 0, p, ADDRTOT_BUF);
1610 #
1611 if (c->spd.that.host_port != pluto_port)
1612 {
1613 p += strlen(p);
1614 sprintf(p, ":%d", c->spd.that.host_port);
1615 }
1616 }
1617 }
1618 }
1619
1620 /* Find an existing connection for a trapped outbound packet.
1621 * This is attempted before we bother with gateway discovery.
1622 * + this connection is routed or instance_of_routed_template
1623 * (i.e. approved for on-demand)
1624 * + this subnet contains our_client (or we are our_client)
1625 * + that subnet contains peer_client (or peer is peer_client)
1626 * + don't care about Phase 1 IDs (we don't know)
1627 * Note: result may still need to be instantiated.
1628 * The winner has the highest policy priority.
1629 *
1630 * If there are several with that priority, we give preference to
1631 * the first one that is an instance.
1632 *
1633 * See also build_outgoing_opportunistic_connection.
1634 */
1635 connection_t *find_connection_for_clients(struct spd_route **srp,
1636 const ip_address *our_client,
1637 const ip_address *peer_client,
1638 int transport_proto)
1639 {
1640 connection_t *c = connections, *best = NULL;
1641 policy_prio_t best_prio = BOTTOM_PRIO;
1642 struct spd_route *sr;
1643 struct spd_route *best_sr = NULL;
1644 int our_port = ntohs(portof(our_client));
1645 int peer_port = ntohs(portof(peer_client));
1646
1647 passert(!isanyaddr(our_client) && !isanyaddr(peer_client));
1648 #ifdef DEBUG
1649 if (DBGP(DBG_CONTROL))
1650 {
1651 char ocb[ADDRTOT_BUF], pcb[ADDRTOT_BUF];
1652
1653 addrtot(our_client, 0, ocb, sizeof(ocb));
1654 addrtot(peer_client, 0, pcb, sizeof(pcb));
1655 DBG_log("find_connection: "
1656 "looking for policy for connection: %s:%d/%d -> %s:%d/%d"
1657 , ocb, transport_proto, our_port, pcb, transport_proto, peer_port);
1658 }
1659 #endif /* DEBUG */
1660
1661 for (c = connections; c != NULL; c = c->ac_next)
1662 {
1663 if (c->kind == CK_GROUP)
1664 {
1665 continue;
1666 }
1667
1668 for (sr = &c->spd; best!=c && sr; sr = sr->next)
1669 {
1670 if ((routed(sr->routing) || c->instance_initiation_ok)
1671 && addrinsubnet(our_client, &sr->this.client)
1672 && addrinsubnet(peer_client, &sr->that.client)
1673 && addrinsubnet(peer_client, &sr->that.client)
1674 && (!sr->this.protocol || transport_proto == sr->this.protocol)
1675 && (!sr->this.port || our_port == sr->this.port)
1676 && (!sr->that.port || peer_port == sr->that.port))
1677 {
1678 char cib[CONN_INST_BUF];
1679 char cib2[CONN_INST_BUF];
1680
1681 policy_prio_t prio = 8 * (c->prio + (c->kind == CK_INSTANCE))
1682 + 2 * (sr->this.port == our_port)
1683 + 2 * (sr->that.port == peer_port)
1684 + (sr->this.protocol == transport_proto);
1685
1686 #ifdef DEBUG
1687 if (DBGP(DBG_CONTROL|DBG_CONTROLMORE))
1688 {
1689 char c_ocb[SUBNETTOT_BUF], c_pcb[SUBNETTOT_BUF];
1690
1691 subnettot(&c->spd.this.client, 0, c_ocb, sizeof(c_ocb));
1692 subnettot(&c->spd.that.client, 0, c_pcb, sizeof(c_pcb));
1693 DBG_log("find_connection: conn \"%s\"%s has compatible peers: %s->%s [pri: %ld]"
1694 , c->name
1695 , (fmt_conn_instance(c, cib), cib)
1696 , c_ocb, c_pcb, prio);
1697 }
1698 #endif /* DEBUG */
1699
1700 if (best == NULL)
1701 {
1702 best = c;
1703 best_sr = sr;
1704 best_prio = prio;
1705 }
1706
1707 DBG(DBG_CONTROLMORE,
1708 DBG_log("find_connection: "
1709 "comparing best \"%s\"%s [pri:%ld]{%p} (child %s) to \"%s\"%s [pri:%ld]{%p} (child %s)"
1710 , best->name
1711 , (fmt_conn_instance(best, cib), cib)
1712 , best_prio
1713 , best
1714 , (best->policy_next ? best->policy_next->name : "none")
1715 , c->name
1716 , (fmt_conn_instance(c, cib2), cib2)
1717 , prio
1718 , c
1719 , (c->policy_next ? c->policy_next->name : "none")));
1720
1721 if (prio > best_prio)
1722 {
1723 best = c;
1724 best_sr = sr;
1725 best_prio = prio;
1726 }
1727 }
1728 }
1729 }
1730
1731 if (best && NEVER_NEGOTIATE(best->policy))
1732 {
1733 best = NULL;
1734 }
1735 if (srp && best)
1736 {
1737 *srp = best_sr;
1738 }
1739
1740 #ifdef DEBUG
1741 if (DBGP(DBG_CONTROL))
1742 {
1743 if (best)
1744 {
1745 char cib[CONN_INST_BUF];
1746 DBG_log("find_connection: concluding with \"%s\"%s [pri:%ld]{%p} kind=%s"
1747 , best->name
1748 , (fmt_conn_instance(best, cib), cib)
1749 , best_prio
1750 , best
1751 , enum_name(&connection_kind_names, best->kind));
1752 } else {
1753 DBG_log("find_connection: concluding with empty");
1754 }
1755 }
1756 #endif /* DEBUG */
1757
1758 return best;
1759 }
1760
1761 /* Find and instantiate a connection for an outgoing Opportunistic connection.
1762 * We've already discovered its gateway.
1763 * We look for a the connection such that:
1764 * + this is one of our interfaces
1765 * + this subnet contains our_client (or we are our_client)
1766 * (we will specialize the client). We prefer the smallest such subnet.
1767 * + that subnet contains peer_clent (we will specialize the client).
1768 * We prefer the smallest such subnet.
1769 * + is opportunistic
1770 * + that peer is NO_IP
1771 * + don't care about Phase 1 IDs (probably should be default)
1772 * We could look for a connection that already had the desired peer
1773 * (rather than NO_IP) specified, but it doesn't seem worth the
1774 * bother.
1775 *
1776 * We look for the routed policy applying to the narrowest subnets.
1777 * We only succeed if we find such a policy AND it is satisfactory.
1778 *
1779 * The body of the inner loop is a lot like that in
1780 * find_connection_for_clients. In this case, we know the gateways
1781 * that we need to instantiate an opportunistic connection.
1782 */
1783 connection_t *build_outgoing_opportunistic_connection(struct gw_info *gw,
1784 const ip_address *our_client,
1785 const ip_address *peer_client)
1786 {
1787 struct iface *p;
1788 connection_t *best = NULL;
1789 struct spd_route *sr, *bestsr;
1790 char ocb[ADDRTOT_BUF], pcb[ADDRTOT_BUF];
1791
1792 addrtot(our_client, 0, ocb, sizeof(ocb));
1793 addrtot(peer_client, 0, pcb, sizeof(pcb));
1794
1795 /* for each of our addresses... */
1796 for (p = interfaces; p != NULL; p = p->next)
1797 {
1798 /* go through those connections with our address and NO_IP as hosts
1799 * We cannot know what port the peer would use, so we assume
1800 * that it is pluto_port (makes debugging easier).
1801 */
1802 connection_t *c = find_host_pair_connections(&p->addr, pluto_port,
1803 (ip_address *)NULL, pluto_port);
1804
1805 for (; c != NULL; c = c->hp_next)
1806 {
1807 DBG(DBG_OPPO,
1808 DBG_log("checking %s", c->name));
1809 if (c->kind == CK_GROUP)
1810 {
1811 continue;
1812 }
1813
1814 for (sr = &c->spd; best!=c && sr; sr = sr->next)
1815 {
1816 if (routed(sr->routing)
1817 && addrinsubnet(our_client, &sr->this.client)
1818 && addrinsubnet(peer_client, &sr->that.client))
1819 {
1820 if (best == NULL)
1821 {
1822 best = c;
1823 break;
1824 }
1825
1826 DBG(DBG_OPPO,
1827 DBG_log("comparing best %s to %s"
1828 , best->name, c->name));
1829
1830 for (bestsr = &best->spd; best!=c && bestsr; bestsr=bestsr->next)
1831 {
1832 if (!subnetinsubnet(&bestsr->this.client, &sr->this.client)
1833 || (samesubnet(&bestsr->this.client, &sr->this.client)
1834 && !subnetinsubnet(&bestsr->that.client
1835 , &sr->that.client)))
1836 {
1837 best = c;
1838 }
1839 }
1840 }
1841 }
1842 }
1843 }
1844
1845 if (best == NULL || NEVER_NEGOTIATE(best->policy) ||
1846 (best->policy & POLICY_OPPO) == LEMPTY || best->kind != CK_TEMPLATE)
1847 {
1848 return NULL;
1849 }
1850 else
1851 {
1852 chunk_t encoding = gw->gw_id->get_encoding(gw->gw_id);
1853 id_type_t type = gw->gw_id->get_type(gw->gw_id);
1854 ip_address ip_addr;
1855
1856 initaddr(encoding.ptr, encoding.len,
1857 (type == ID_IPV4_ADDR) ? AF_INET : AF_INET6, &ip_addr);
1858
1859 return oppo_instantiate(best, &ip_addr, NULL, gw, our_client, peer_client);
1860 }
1861 }
1862
1863 bool orient(connection_t *c)
1864 {
1865 struct spd_route *sr;
1866
1867 if (!oriented(*c))
1868 {
1869 struct iface *p;
1870
1871 for (sr = &c->spd; sr; sr = sr->next)
1872 {
1873 /* Note: this loop does not stop when it finds a match:
1874 * it continues checking to catch any ambiguity.
1875 */
1876 for (p = interfaces; p != NULL; p = p->next)
1877 {
1878 if (p->ike_float)
1879 {
1880 continue;
1881 }
1882
1883 for (;;)
1884 {
1885 /* check if this interface matches this end */
1886 if (sameaddr(&sr->this.host_addr, &p->addr)
1887 && sr->this.host_port == pluto_port)
1888 {
1889 if (oriented(*c))
1890 {
1891 if (c->interface == p)
1892 loglog(RC_LOG_SERIOUS
1893 , "both sides of \"%s\" are our interface %s!"
1894 , c->name, p->rname);
1895 else
1896 loglog(RC_LOG_SERIOUS, "two interfaces match \"%s\" (%s, %s)"
1897 , c->name, c->interface->rname, p->rname);
1898 c->interface = NULL; /* withdraw orientation */
1899 return FALSE;
1900 }
1901 c->interface = p;
1902 }
1903
1904 /* done with this interface if it doesn't match that end */
1905 if (!(sameaddr(&sr->that.host_addr, &p->addr)
1906 && sr->that.host_port == pluto_port))
1907 break;
1908
1909 /* swap ends and try again.
1910 * It is a little tricky to see that this loop will stop.
1911 * Only continue if the far side matches.
1912 * If both sides match, there is an error-out.
1913 */
1914 {
1915 struct end t = sr->this;
1916
1917 sr->this = sr->that;
1918 sr->that = t;
1919 }
1920 }
1921 }
1922 }
1923 }
1924 return oriented(*c);
1925 }
1926
1927 void initiate_connection(const char *name, int whackfd)
1928 {
1929 connection_t *c = con_by_name(name, TRUE);
1930
1931 if (c && c->ikev1)
1932 {
1933 set_cur_connection(c);
1934 if (!oriented(*c))
1935 {
1936 loglog(RC_ORIENT, "we have no ipsecN interface for either end of this connection");
1937 }
1938 else if (NEVER_NEGOTIATE(c->policy))
1939 {
1940 loglog(RC_INITSHUNT
1941 , "cannot initiate an authby=never connection");
1942 }
1943 else if (c->kind != CK_PERMANENT && !c->spd.that.allow_any)
1944 {
1945 if (isanyaddr(&c->spd.that.host_addr))
1946 loglog(RC_NOPEERIP, "cannot initiate connection without knowing peer IP address");
1947 else
1948 loglog(RC_WILDCARD, "cannot initiate connection with ID wildcards");
1949 }
1950 else
1951 {
1952 /* do we have to prompt for a PIN code? */
1953 if (c->spd.this.sc && !c->spd.this.sc->valid && whackfd != NULL_FD)
1954 {
1955 scx_get_pin(c->spd.this.sc, whackfd);
1956 }
1957 if (c->spd.this.sc && !c->spd.this.sc->valid)
1958 {
1959 loglog(RC_NOVALIDPIN, "cannot initiate connection without valid PIN");
1960 }
1961 else
1962 {
1963
1964 if (c->spd.that.allow_any)
1965 {
1966 c = instantiate(c, &c->spd.that.host_addr,
1967 c->spd.that.host_port, c->spd.that.id);
1968 }
1969
1970 /* We will only request an IPsec SA if policy isn't empty
1971 * (ignoring Main Mode items).
1972 * This is a fudge, but not yet important.
1973 * If we are to proceed asynchronously, whackfd will be NULL_FD.
1974 */
1975 c->policy |= POLICY_UP;
1976 ipsecdoi_initiate(whackfd, c, c->policy, 1, SOS_NOBODY);
1977 whackfd = NULL_FD; /* protect from close */
1978 }
1979 }
1980 reset_cur_connection();
1981 }
1982 close_any(whackfd);
1983 }
1984
1985 /* (Possibly) Opportunistic Initiation:
1986 * Knowing clients (single IP addresses), try to build an tunnel.
1987 * This may involve discovering a gateway and instantiating an
1988 * Opportunistic connection. Called when a packet is caught by
1989 * a %trap, or when whack --oppohere --oppothere is used.
1990 * It may turn out that an existing or non-opporunistic connnection
1991 * can handle the traffic.
1992 *
1993 * Most of the code will be restarted if an ADNS request is made
1994 * to discover the gateway. The only difference between the first
1995 * and second entry is whether gateways_from_dns is NULL or not.
1996 * initiate_opportunistic: initial entrypoint
1997 * continue_oppo: where we pickup when ADNS result arrives
1998 * initiate_opportunistic_body: main body shared by above routines
1999 * cannot_oppo: a helper function to log a diagnostic
2000 * This structure repeats a lot of code when the ADNS result arrives.
2001 * This seems like a waste, but anything learned the first time through
2002 * may no longer be true!
2003 *
2004 * After the first IKE message is sent, the regular state machinery
2005 * carries negotiation forward.
2006 */
2007
2008 enum find_oppo_step {
2009 fos_start,
2010 fos_myid_ip_txt,
2011 fos_myid_hostname_txt,
2012 fos_myid_ip_key,
2013 fos_myid_hostname_key,
2014 fos_our_client,
2015 fos_our_txt,
2016 #ifdef USE_KEYRR
2017 fos_our_key,
2018 #endif /* USE_KEYRR */
2019 fos_his_client,
2020 fos_done
2021 };
2022
2023 #ifdef DEBUG
2024 static const char *const oppo_step_name[] = {
2025 "fos_start",
2026 "fos_myid_ip_txt",
2027 "fos_myid_hostname_txt",
2028 "fos_myid_ip_key",
2029 "fos_myid_hostname_key",
2030 "fos_our_client",
2031 "fos_our_txt",
2032 #ifdef USE_KEYRR
2033 "fos_our_key",
2034 #endif /* USE_KEYRR */
2035 "fos_his_client",
2036 "fos_done"
2037 };
2038 #endif /* DEBUG */
2039
2040 struct find_oppo_bundle {
2041 enum find_oppo_step step;
2042 err_t want;
2043 bool failure_ok; /* if true, continue_oppo should not die on DNS failure */
2044 ip_address our_client; /* not pointer! */
2045 ip_address peer_client;
2046 int transport_proto;
2047 bool held;
2048 policy_prio_t policy_prio;
2049 ipsec_spi_t failure_shunt; /* in host order! 0 for delete. */
2050 int whackfd;
2051 };
2052
2053 struct find_oppo_continuation {
2054 struct adns_continuation ac; /* common prefix */
2055 struct find_oppo_bundle b;
2056 };
2057
2058 static void cannot_oppo(connection_t *c, struct find_oppo_bundle *b, err_t ugh)
2059 {
2060 char pcb[ADDRTOT_BUF];
2061 char ocb[ADDRTOT_BUF];
2062
2063 addrtot(&b->peer_client, 0, pcb, sizeof(pcb));
2064 addrtot(&b->our_client, 0, ocb, sizeof(ocb));
2065
2066 DBG(DBG_DNS | DBG_OPPO, DBG_log("Can't Opportunistically initiate for %s to %s: %s"
2067 , ocb, pcb, ugh));
2068
2069 whack_log(RC_OPPOFAILURE
2070 , "Can't Opportunistically initiate for %s to %s: %s"
2071 , ocb, pcb, ugh);
2072
2073 if (c && c->policy_next)
2074 {
2075 /* there is some policy that comes afterwards */
2076 struct spd_route *shunt_spd;
2077 connection_t *nc = c->policy_next;
2078 struct state *st;
2079
2080 passert(c->kind == CK_TEMPLATE);
2081 passert(c->policy_next->kind == CK_PERMANENT);
2082
2083 DBG(DBG_OPPO, DBG_log("OE failed for %s to %s, but %s overrides shunt"
2084 , ocb, pcb, c->policy_next->name));
2085
2086 /*
2087 * okay, here we need add to the "next" policy, which is ought
2088 * to be an instance.
2089 * We will add another entry to the spd_route list for the specific
2090 * situation that we have.
2091 */
2092
2093 shunt_spd = clone_thing(nc->spd);
2094
2095 shunt_spd->next = nc->spd.next;
2096 nc->spd.next = shunt_spd;
2097
2098 happy(addrtosubnet(&b->peer_client, &shunt_spd->that.client));
2099
2100 if (sameaddr(&b->peer_client, &shunt_spd->that.host_addr))
2101 shunt_spd->that.has_client = FALSE;
2102
2103 /*
2104 * override the tunnel destination with the one from the secondaried
2105 * policy
2106 */
2107 shunt_spd->that.host_addr = nc->spd.that.host_addr;
2108
2109 /* now, lookup the state, and poke it up.
2110 */
2111
2112 st = state_with_serialno(nc->newest_ipsec_sa);
2113
2114 /* XXX what to do if the IPSEC SA has died? */
2115 passert(st != NULL);
2116
2117 /* link the new connection instance to the state's list of
2118 * connections
2119 */
2120
2121 DBG(DBG_OPPO, DBG_log("installing state: %ld for %s to %s"
2122 , nc->newest_ipsec_sa
2123 , ocb, pcb));
2124
2125 #ifdef DEBUG
2126 if (DBGP(DBG_OPPO | DBG_CONTROLMORE))
2127 {
2128 char state_buf[LOG_WIDTH];
2129 char state_buf2[LOG_WIDTH];
2130 time_t n = now();
2131
2132 fmt_state(FALSE, st, n
2133 , state_buf, sizeof(state_buf)
2134 , state_buf2, sizeof(state_buf2));
2135 DBG_log("cannot_oppo, failure SA1: %s", state_buf);
2136 DBG_log("cannot_oppo, failure SA2: %s", state_buf2);
2137 }
2138 #endif /* DEBUG */
2139
2140 if (!route_and_eroute(c, shunt_spd, st))
2141 {
2142 whack_log(RC_OPPOFAILURE
2143 , "failed to instantiate shunt policy %s for %s to %s"
2144 , c->name
2145 , ocb, pcb);
2146 }
2147 return;
2148 }
2149 }
2150
2151 static void initiate_opportunistic_body(struct find_oppo_bundle *b
2152 , struct adns_continuation *ac, err_t ac_ugh); /* forward */
2153
2154 void initiate_opportunistic(const ip_address *our_client,
2155 const ip_address *peer_client, int transport_proto,
2156 bool held, int whackfd)
2157 {
2158 struct find_oppo_bundle b;
2159
2160 b.want = (whackfd == NULL_FD ? "whack" : "acquire");
2161 b.failure_ok = FALSE;
2162 b.our_client = *our_client;
2163 b.peer_client = *peer_client;
2164 b.transport_proto = transport_proto;
2165 b.held = held;
2166 b.policy_prio = BOTTOM_PRIO;
2167 b.failure_shunt = 0;
2168 b.whackfd = whackfd;
2169 b.step = fos_start;
2170 initiate_opportunistic_body(&b, NULL, NULL);
2171 }
2172
2173 static void continue_oppo(struct adns_continuation *acr, err_t ugh)
2174 {
2175 struct find_oppo_continuation *cr = (void *)acr; /* inherit, damn you! */
2176 connection_t *c;
2177 bool was_held = cr->b.held;
2178 int whackfd = cr->b.whackfd;
2179
2180 /* note: cr->id has no resources; cr->sgw_id is ID_ANY:
2181 * neither need freeing.
2182 */
2183 whack_log_fd = whackfd;
2184
2185 #ifdef DEBUG
2186 /* if we're going to ignore the error, at least note it in debugging log */
2187 if (cr->b.failure_ok && ugh)
2188 {
2189 DBG(DBG_CONTROL | DBG_DNS,
2190 {
2191 char ocb[ADDRTOT_BUF];
2192 char pcb[ADDRTOT_BUF];
2193
2194 addrtot(&cr->b.our_client, 0, ocb, sizeof(ocb));
2195 addrtot(&cr->b.peer_client, 0, pcb, sizeof(pcb));
2196 DBG_log("continuing from failed DNS lookup for %s, %s to %s: %s"
2197 , cr->b.want, ocb, pcb, ugh);
2198 });
2199 }
2200 #endif
2201
2202 if (!cr->b.failure_ok && ugh)
2203 {
2204 c = find_connection_for_clients(NULL, &cr->b.our_client, &cr->b.peer_client
2205 , cr->b.transport_proto);
2206 cannot_oppo(c, &cr->b
2207 , builddiag("%s: %s", cr->b.want, ugh));
2208 }
2209 else if (was_held && !cr->b.held)
2210 {
2211 /* was_held indicates we were started due to a %trap firing
2212 * (as opposed to a "whack --oppohere --oppothere").
2213 * Since the %hold has gone, we can assume that somebody else
2214 * has beaten us to the punch. We can go home. But lets log it.
2215 */
2216 char ocb[ADDRTOT_BUF];
2217 char pcb[ADDRTOT_BUF];
2218
2219 addrtot(&cr->b.our_client, 0, ocb, sizeof(ocb));
2220 addrtot(&cr->b.peer_client, 0, pcb, sizeof(pcb));
2221
2222 loglog(RC_COMMENT
2223 , "%%hold otherwise handled during DNS lookup for Opportunistic Initiation for %s to %s"
2224 , ocb, pcb);
2225 }
2226 else
2227 {
2228 initiate_opportunistic_body(&cr->b, &cr->ac, ugh);
2229 whackfd = NULL_FD; /* was handed off */
2230 }
2231
2232 whack_log_fd = NULL_FD;
2233 close_any(whackfd);
2234 }
2235
2236 #ifdef USE_KEYRR
2237 static err_t check_key_recs(enum myid_state try_state, const connection_t *c,
2238 struct adns_continuation *ac)
2239 {
2240 /* Check if KEY lookup yielded good results.
2241 * Looking up based on our ID. Used if
2242 * client is ourself, or if TXT had no public key.
2243 * Note: if c is different this time, there is
2244 * a chance that we did the wrong query.
2245 * If so, treat as a kind of failure.
2246 */
2247 enum myid_state old_myid_state = myid_state;
2248 private_key_t *private;
2249 err_t ugh = NULL;
2250
2251 myid_state = try_state;
2252
2253 if (old_myid_state != myid_state && old_myid_state == MYID_SPECIFIED)
2254 {
2255 ugh = "%myid was specified while we were guessing";
2256 }
2257 else if ((private = get_private_key(c)) == NULL)
2258 {
2259 ugh = "we don't know our own RSA key";
2260 }
2261 else if (!same_id(&ac->id, &c->spd.this.id))
2262 {
2263 ugh = "our ID changed underfoot";
2264 }
2265 else
2266 {
2267 /* Similar to code in RSA_check_signature
2268 * for checking the other side.
2269 */
2270 pubkey_list_t *kr;
2271
2272 ugh = "no KEY RR found for us";
2273 for (kr = ac->keys_from_dns; kr != NULL; kr = kr->next)
2274 {
2275 ugh = "all our KEY RRs have the wrong public key";
2276 if (kr->key->alg == PUBKEY_ALG_RSA
2277 && private->belongs_to(private, &kr->key->public_key))
2278 {
2279 ugh = NULL; /* good! */
2280 break;
2281 }
2282 }
2283 }
2284 if (ugh)
2285 {
2286 myid_state = old_myid_state;
2287 }
2288 return ugh;
2289 }
2290 #endif /* USE_KEYRR */
2291
2292 static err_t check_txt_recs(enum myid_state try_state, const connection_t *c,
2293 struct adns_continuation *ac)
2294 {
2295 /* Check if TXT lookup yielded good results.
2296 * Looking up based on our ID. Used if
2297 * client is ourself, or if TXT had no public key.
2298 * Note: if c is different this time, there is
2299 * a chance that we did the wrong query.
2300 * If so, treat as a kind of failure.
2301 */
2302 enum myid_state old_myid_state = myid_state;
2303 private_key_t *private;
2304 err_t ugh = NULL;
2305
2306 myid_state = try_state;
2307
2308 if (old_myid_state != myid_state
2309 && old_myid_state == MYID_SPECIFIED)
2310 {
2311 ugh = "%myid was specified while we were guessing";
2312 }
2313 else if ((private = get_private_key(c)) == NULL)
2314 {
2315 ugh = "we don't know our own RSA key";
2316 }
2317 else if (!ac->id->equals(ac->id, c->spd.this.id))
2318 {
2319 ugh = "our ID changed underfoot";
2320 }
2321 else
2322 {
2323 /* Similar to code in RSA_check_signature
2324 * for checking the other side.
2325 */
2326 struct gw_info *gwp;
2327
2328 ugh = "no TXT RR found for us";
2329 for (gwp = ac->gateways_from_dns; gwp != NULL; gwp = gwp->next)
2330 {
2331 public_key_t *pub_key = gwp->key->public_key;
2332
2333 ugh = "all our TXT RRs have the wrong public key";
2334 if (pub_key->get_type(pub_key) == KEY_RSA &&
2335 private->belongs_to(private, pub_key))
2336 {
2337 ugh = NULL; /* good! */
2338 break;
2339 }
2340 }
2341 }
2342 if (ugh)
2343 {
2344 myid_state = old_myid_state;
2345 }
2346 return ugh;
2347 }
2348
2349
2350 /* note: gateways_from_dns must be NULL iff this is the first call */
2351 static void initiate_opportunistic_body(struct find_oppo_bundle *b,
2352 struct adns_continuation *ac,
2353 err_t ac_ugh)
2354 {
2355 connection_t *c;
2356 struct spd_route *sr;
2357
2358 /* What connection shall we use?
2359 * First try for one that explicitly handles the clients.
2360 */
2361 DBG(DBG_CONTROL,
2362 {
2363 char ours[ADDRTOT_BUF];
2364 char his[ADDRTOT_BUF];
2365 int ourport;
2366 int hisport;
2367
2368 addrtot(&b->our_client, 0, ours, sizeof(ours));
2369 addrtot(&b->peer_client, 0, his, sizeof(his));
2370 ourport = ntohs(portof(&b->our_client));
2371 hisport = ntohs(portof(&b->peer_client));
2372 DBG_log("initiate on demand from %s:%d to %s:%d proto=%d state: %s because: %s"
2373 , ours, ourport, his, hisport, b->transport_proto
2374 , oppo_step_name[b->step], b->want);
2375 });
2376 if (isanyaddr(&b->our_client) || isanyaddr(&b->peer_client))
2377 {
2378 cannot_oppo(NULL, b, "impossible IP address");
2379 }
2380 else if ((c = find_connection_for_clients(&sr
2381 , &b->our_client
2382 , &b->peer_client
2383 , b->transport_proto)) == NULL)
2384 {
2385 /* No connection explicitly handles the clients and there
2386 * are no Opportunistic connections -- whine and give up.
2387 * The failure policy cannot be gotten from a connection; we pick %pass.
2388 */
2389 cannot_oppo(NULL, b, "no routed Opportunistic template covers this pair");
2390 }
2391 else if (c->kind != CK_TEMPLATE)
2392 {
2393 /* We've found a connection that can serve.
2394 * Do we have to initiate it?
2395 * Not if there is currently an IPSEC SA.
2396 * But if there is an IPSEC SA, then the kernel would not
2397 * have generated the acquire. So we assume that there isn't one.
2398 * This may be redundant if a non-opportunistic
2399 * negotiation is already being attempted.
2400 */
2401
2402 /* If we are to proceed asynchronously, b->whackfd will be NULL_FD. */
2403
2404 if(c->kind == CK_INSTANCE)
2405 {
2406 char cib[CONN_INST_BUF];
2407 /* there is already an instance being negotiated, no nothing */
2408 DBG(DBG_CONTROL, DBG_log("found existing instance \"%s\"%s, rekeying it"
2409 , c->name
2410 , (fmt_conn_instance(c, cib), cib)));
2411 /* XXX-mcr - return; */
2412 }
2413
2414 /* otherwise, there is some kind of static conn that can handle
2415 * this connection, so we initiate it */
2416
2417 if (b->held)
2418 {
2419 /* what should we do on failure? */
2420 (void) assign_hold(c, sr, b->transport_proto, &b->our_client, &b->peer_client);
2421 }
2422 ipsecdoi_initiate(b->whackfd, c, c->policy, 1, SOS_NOBODY);
2423 b->whackfd = NULL_FD; /* protect from close */
2424 }
2425 else
2426 {
2427 /* We are handling an opportunistic situation.
2428 * This involves several DNS lookup steps that require suspension.
2429 * Note: many facts might change while we're suspended.
2430 * Here be dragons.
2431 *
2432 * The first chunk of code handles the result of the previous
2433 * DNS query (if any). It also selects the kind of the next step.
2434 * The second chunk initiates the next DNS query (if any).
2435 */
2436 enum find_oppo_step next_step = fos_myid_ip_txt;
2437 err_t ugh = ac_ugh;
2438 char mycredentialstr[BUF_LEN];
2439 char cib[CONN_INST_BUF];
2440
2441 DBG(DBG_CONTROL, DBG_log("creating new instance from \"%s\"%s",
2442 c->name, (fmt_conn_instance(c, cib), cib)));
2443 snprintf(mycredentialstr, BUF_LEN, "%Y", sr->this.id);
2444
2445 /* handle any DNS answer; select next step */
2446 switch (b->step)
2447 {
2448 case fos_start:
2449 /* just starting out: select first query step */
2450 next_step = fos_myid_ip_txt;
2451 break;
2452
2453 case fos_myid_ip_txt: /* TXT for our default IP address as %myid */
2454 ugh = check_txt_recs(MYID_IP, c, ac);
2455 if (ugh)
2456 {
2457 /* cannot use our IP as OE identitiy for initiation */
2458 DBG(DBG_OPPO,
2459 DBG_log("can not use our IP (%Y:TXT) as identity: %s",
2460 myids[MYID_IP], ugh));
2461 if (!logged_myid_ip_txt_warning)
2462 {
2463 loglog(RC_LOG_SERIOUS,
2464 "can not use our IP (%Y:TXT) as identity: %s",
2465 myids[MYID_IP], ugh);
2466 logged_myid_ip_txt_warning = TRUE;
2467 }
2468
2469 next_step = fos_myid_hostname_txt;
2470 ugh = NULL; /* failure can be recovered from */
2471 }
2472 else
2473 {
2474 /* we can use our IP as OE identity for initiation */
2475 if (!logged_myid_ip_txt_warning)
2476 {
2477 loglog(RC_LOG_SERIOUS,
2478 "using our IP (%Y:TXT) as identity!",
2479 myids[MYID_IP]);
2480 logged_myid_ip_txt_warning = TRUE;
2481 }
2482
2483 next_step = fos_our_client;
2484 }
2485 break;
2486
2487 case fos_myid_hostname_txt: /* TXT for our hostname as %myid */
2488 ugh = check_txt_recs(MYID_HOSTNAME, c, ac);
2489 if (ugh)
2490 {
2491 /* cannot use our hostname as OE identitiy for initiation */
2492 DBG(DBG_OPPO,
2493 DBG_log("can not use our hostname (%Y:TXT) as identity: %s",
2494 myids[MYID_HOSTNAME], ugh));
2495 if (!logged_myid_fqdn_txt_warning)
2496 {
2497 loglog(RC_LOG_SERIOUS,
2498 "can not use our hostname (%Y:TXT) as identity: %s",
2499 myids[MYID_HOSTNAME], ugh);
2500 logged_myid_fqdn_txt_warning = TRUE;
2501 }
2502 #ifdef USE_KEYRR
2503 next_step = fos_myid_ip_key;
2504 ugh = NULL; /* failure can be recovered from */
2505 #endif
2506 }
2507 else
2508 {
2509 /* we can use our hostname as OE identity for initiation */
2510 if (!logged_myid_fqdn_txt_warning)
2511 {
2512 loglog(RC_LOG_SERIOUS,
2513 "using our hostname (%Y:TXT) as identity!",
2514 myids[MYID_HOSTNAME]);
2515 logged_myid_fqdn_txt_warning = TRUE;
2516 }
2517 next_step = fos_our_client;
2518 }
2519 break;
2520
2521 #ifdef USE_KEYRR
2522 case fos_myid_ip_key: /* KEY for our default IP address as %myid */
2523 ugh = check_key_recs(MYID_IP, c, ac);
2524 if (ugh)
2525 {
2526 /* cannot use our IP as OE identitiy for initiation */
2527 DBG(DBG_OPPO,
2528 DBG_log("can not use our IP (%Y:KEY) as identity: %s",
2529 myids[MYID_IP], ugh));
2530 if (!logged_myid_ip_key_warning)
2531 {
2532 loglog(RC_LOG_SERIOUS,
2533 "can not use our IP (%Y:KEY) as identity: %s",
2534 myids[MYID_IP], ugh);
2535 logged_myid_ip_key_warning = TRUE;
2536 }
2537
2538 next_step = fos_myid_hostname_key;
2539 ugh = NULL; /* failure can be recovered from */
2540 }
2541 else
2542 {
2543 /* we can use our IP as OE identity for initiation */
2544 if (!logged_myid_ip_key_warning)
2545 {
2546 loglog(RC_LOG_SERIOUS,
2547 "using our IP (%Y:KEY) as identity!",
2548 myids[MYID_IP]);
2549 logged_myid_ip_key_warning = TRUE;
2550 }
2551 next_step = fos_our_client;
2552 }
2553 break;
2554
2555 case fos_myid_hostname_key: /* KEY for our hostname as %myid */
2556 ugh = check_key_recs(MYID_HOSTNAME, c, ac);
2557 if (ugh)
2558 {
2559 /* cannot use our IP as OE identitiy for initiation */
2560 DBG(DBG_OPPO,
2561 DBG_log("can not use our hostname (%Y:KEY) as identity: %s",
2562 myids[MYID_HOSTNAME], ugh));
2563 if (!logged_myid_fqdn_key_warning)
2564 {
2565 loglog(RC_LOG_SERIOUS,
2566 "can not use our hostname (%Y:KEY) as identity: %s",
2567 myids[MYID_HOSTNAME], ugh);
2568 logged_myid_fqdn_key_warning = TRUE;
2569 }
2570 next_step = fos_myid_hostname_key;
2571 ugh = NULL; /* failure can be recovered from */
2572 }
2573 else
2574 {
2575 /* we can use our IP as OE identity for initiation */
2576 if (!logged_myid_fqdn_key_warning)
2577 {
2578 loglog(RC_LOG_SERIOUS,
2579 "using our hostname (%Y:KEY) as identity!",
2580 myids[MYID_HOSTNAME]);
2581 logged_myid_fqdn_key_warning = TRUE;
2582 }
2583 next_step = fos_our_client;
2584 }
2585 break;
2586 #endif
2587
2588 case fos_our_client: /* TXT for our client */
2589 {
2590 /* Our client is not us: we must check the TXT records.
2591 * Note: if c is different this time, there is
2592 * a chance that we did the wrong query.
2593 * If so, treat as a kind of failure.
2594 */
2595 private_key_t *private = get_private_key(c);
2596
2597 next_step = fos_his_client; /* normal situation */
2598
2599 if (private == NULL)
2600 {
2601 ugh = "we don't know our own RSA key";
2602 }
2603 else if (sameaddr(&sr->this.host_addr, &b->our_client))
2604 {
2605 /* this wasn't true when we started -- bail */
2606 ugh = "our IP address changed underfoot";
2607 }
2608 else if (!ac->sgw_id->equals(ac->sgw_id, sr->this.id))
2609 {
2610 /* this wasn't true when we started -- bail */
2611 ugh = "our ID changed underfoot";
2612 }
2613 else
2614 {
2615 /* Similar to code in quick_inI1_outR1_tail
2616 * for checking the other side.
2617 */
2618 struct gw_info *gwp;
2619
2620 ugh = "no TXT RR for our client delegates us";
2621 for (gwp = ac->gateways_from_dns; gwp != NULL; gwp = gwp->next)
2622 {
2623 ugh = "TXT RR for our client has wrong key";
2624 /* If there is a key from the TXT record,
2625 * we count it as a win if we match the key.
2626 * If there was no key, we have a tentative win:
2627 * we need to check our KEY record to be sure.
2628 */
2629 if (!gwp->gw_key_present)
2630 {
2631 /* Success, but the TXT had no key
2632 * so we must check our our own KEY records.
2633 */
2634 next_step = fos_our_txt;
2635 ugh = NULL; /* good! */
2636 break;
2637 }
2638 if (private->belongs_to(private, gwp->key->public_key))
2639 {
2640 ugh = NULL; /* good! */
2641 break;
2642 }
2643 }
2644 }
2645 }
2646 break;
2647
2648 case fos_our_txt: /* TXT for us */
2649 {
2650 /* Check if TXT lookup yielded good results.
2651 * Looking up based on our ID. Used if
2652 * client is ourself, or if TXT had no public key.
2653 * Note: if c is different this time, there is
2654 * a chance that we did the wrong query.
2655 * If so, treat as a kind of failure.
2656 */
2657 private_key_t *private = get_private_key(c);
2658
2659 next_step = fos_his_client; /* unless we decide to look for KEY RR */
2660
2661 if (private == NULL)
2662 {
2663 ugh = "we don't know our own RSA key";
2664 }
2665 else if (!ac->id->equals(ac->id, c->spd.this.id))
2666 {
2667 ugh = "our ID changed underfoot";
2668 }
2669 else
2670 {
2671 /* Similar to code in RSA_check_signature
2672 * for checking the other side.
2673 */
2674 struct gw_info *gwp;
2675
2676 ugh = "no TXT RR for us";
2677 for (gwp = ac->gateways_from_dns; gwp != NULL; gwp = gwp->next)
2678 {
2679 ugh = "TXT RR for us has wrong key";
2680 if (gwp->gw_key_present &&
2681 private->belongs_to(private, gwp->key->public_key))
2682 {
2683 DBG(DBG_CONTROL,
2684 DBG_log("initiate on demand found TXT with right public key at: %s"
2685 , mycredentialstr));
2686 ugh = NULL;
2687 break;
2688 }
2689 }
2690 #ifdef USE_KEYRR
2691 if (ugh)
2692 {
2693 /* if no TXT with right key, try KEY */
2694 DBG(DBG_CONTROL,
2695 DBG_log("will try for KEY RR since initiate on demand found %s: %s"
2696 , ugh, mycredentialstr));
2697 next_step = fos_our_key;
2698 ugh = NULL;
2699 }
2700 #endif
2701 }
2702 }
2703 break;
2704
2705 #ifdef USE_KEYRR
2706 case fos_our_key: /* KEY for us */
2707 {
2708 /* Check if KEY lookup yielded good results.
2709 * Looking up based on our ID. Used if
2710 * client is ourself, or if TXT had no public key.
2711 * Note: if c is different this time, there is
2712 * a chance that we did the wrong query.
2713 * If so, treat as a kind of failure.
2714 */
2715 private_key_t *private = get_private_key(c);
2716
2717 next_step = fos_his_client; /* always */
2718
2719 if (private == NULL)
2720 {
2721 ugh = "we don't know our own RSA key";
2722 }
2723 else if (!same_id(&ac->id, &c->spd.this.id))
2724 {
2725 ugh = "our ID changed underfoot";
2726 }
2727 else
2728 {
2729 /* Similar to code in RSA_check_signature
2730 * for checking the other side.
2731 */
2732 pubkey_list_t *kr;
2733
2734 ugh = "no KEY RR found for us (and no good TXT RR)";
2735 for (kr = ac->keys_from_dns; kr != NULL; kr = kr->next)
2736 {
2737 ugh = "all our KEY RRs have the wrong public key (and no good TXT RR)";
2738 if (kr->key->alg == PUBKEY_ALG_RSA
2739 && private->belongs_to(private, kr->key->public_key))
2740 {
2741 /* do this only once a day */
2742 if (!logged_txt_warning)
2743 {
2744 loglog(RC_LOG_SERIOUS
2745 , "found KEY RR but not TXT RR for %s. See http://www.freeswan.org/err/txt-change.html."
2746 , mycredentialstr);
2747 logged_txt_warning = TRUE;
2748 }
2749 ugh = NULL; /* good! */
2750 break;
2751 }
2752 }
2753 }
2754 }
2755 break;
2756 #endif /* USE_KEYRR */
2757
2758 case fos_his_client: /* TXT for his client */
2759 {
2760 /* We've finished last DNS queries: TXT for his client.
2761 * Using the information, try to instantiate a connection
2762 * and start negotiating.
2763 * We now know the peer. The chosing of "c" ignored this,
2764 * so we will disregard its current value.
2765 * !!! We need to randomize the entry in gw that we choose.
2766 */
2767 next_step = fos_done; /* no more queries */
2768
2769 c = build_outgoing_opportunistic_connection(ac->gateways_from_dns
2770 , &b->our_client
2771 , &b->peer_client);
2772
2773 if (c == NULL)
2774 {
2775 /* We cannot seem to instantiate a suitable connection:
2776 * complain clearly.
2777 */
2778 char ocb[ADDRTOT_BUF], pcb[ADDRTOT_BUF];
2779
2780 addrtot(&b->our_client, 0, ocb, sizeof(ocb));
2781 addrtot(&b->peer_client, 0, pcb, sizeof(pcb));
2782 loglog(RC_OPPOFAILURE,
2783 "no suitable connection for opportunism "
2784 "between %s and %s with %Y as peer",
2785 ocb, pcb, ac->gateways_from_dns->gw_id);
2786 }
2787 else
2788 {
2789 /* If we are to proceed asynchronously, b->whackfd will be NULL_FD. */
2790 passert(c->kind == CK_INSTANCE);
2791 passert(c->gw_info != NULL);
2792 passert(HAS_IPSEC_POLICY(c->policy));
2793 passert(LHAS(LELEM(RT_UNROUTED) | LELEM(RT_ROUTED_PROSPECTIVE), c->spd.routing));
2794 if (b->held)
2795 {
2796 /* what should we do on failure? */
2797 (void) assign_hold(c, &c->spd
2798 , b->transport_proto
2799 , &b->our_client, &b->peer_client);
2800 }
2801 c->gw_info->key->last_tried_time = now();
2802 ipsecdoi_initiate(b->whackfd, c, c->policy, 1, SOS_NOBODY);
2803 b->whackfd = NULL_FD; /* protect from close */
2804 }
2805 }
2806 break;
2807
2808 default:
2809 bad_case(b->step);
2810 }
2811
2812 /* the second chunk: initiate the next DNS query (if any) */
2813 DBG(DBG_CONTROL,
2814 {
2815 char ours[ADDRTOT_BUF];
2816 char his[ADDRTOT_BUF];
2817
2818 addrtot(&b->our_client, 0, ours, sizeof(ours));
2819 addrtot(&b->peer_client, 0, his, sizeof(his));
2820 DBG_log("initiate on demand from %s to %s new state: %s with ugh: %s"
2821 , ours, his, oppo_step_name[b->step], ugh ? ugh : "ok");
2822 });
2823
2824 if (ugh)
2825 {
2826 b->policy_prio = c->prio;
2827 b->failure_shunt = shunt_policy_spi(c, FALSE);
2828 cannot_oppo(c, b, ugh);
2829 }
2830 else if (next_step == fos_done)
2831 {
2832 /* nothing to do */
2833 }
2834 else
2835 {
2836 /* set up the next query */
2837 struct find_oppo_continuation *cr = malloc_thing(struct find_oppo_continuation);
2838 identification_t *id;
2839
2840 b->policy_prio = c->prio;
2841 b->failure_shunt = shunt_policy_spi(c, FALSE);
2842 cr->b = *b; /* copy; start hand off of whackfd */
2843 cr->b.failure_ok = FALSE;
2844 cr->b.step = next_step;
2845
2846 for (sr = &c->spd
2847 ; sr!=NULL && !sameaddr(&sr->this.host_addr, &b->our_client)
2848 ; sr = sr->next)
2849 ;
2850
2851 if (sr == NULL)
2852 sr = &c->spd;
2853
2854 /* If a %hold shunt has replaced the eroute for this template,
2855 * record this fact.
2856 */
2857 if (b->held
2858 && sr->routing == RT_ROUTED_PROSPECTIVE && eclipsable(sr))
2859 {
2860 sr->routing = RT_ROUTED_ECLIPSED;
2861 eclipse_count++;
2862 }
2863
2864 /* Switch to issue next query.
2865 * A case may turn out to be unnecessary. If so, it falls
2866 * through to the next case.
2867 * Figuring out what %myid can stand for must be done before
2868 * our client credentials are looked up: we must know what
2869 * the client credentials may use to identify us.
2870 * On the other hand, our own credentials should be looked
2871 * up after our clients in case our credentials are not
2872 * needed at all.
2873 * XXX this is a wasted effort if we don't have credentials
2874 * BUT they are not needed.
2875 */
2876 switch (next_step)
2877 {
2878 case fos_myid_ip_txt:
2879 if (c->spd.this.id->get_type(c->spd.this.id) == ID_MYID
2880 && myid_state != MYID_SPECIFIED)
2881 {
2882 cr->b.failure_ok = TRUE;
2883 cr->b.want = b->want = "TXT record for IP address as %myid";
2884 ugh = start_adns_query(myids[MYID_IP], myids[MYID_IP],
2885 T_TXT, continue_oppo, &cr->ac);
2886 break;
2887 }
2888 cr->b.step = fos_myid_hostname_txt;
2889 /* fall through */
2890
2891 case fos_myid_hostname_txt:
2892 if (c->spd.this.id->get_type(c->spd.this.id) == ID_MYID
2893 && myid_state != MYID_SPECIFIED)
2894 {
2895 #ifdef USE_KEYRR
2896 cr->b.failure_ok = TRUE;
2897 #else
2898 cr->b.failure_ok = FALSE;
2899 #endif
2900 cr->b.want = b->want = "TXT record for hostname as %myid";
2901 ugh = start_adns_query(myids[MYID_HOSTNAME],
2902 myids[MYID_HOSTNAME],
2903 T_TXT, continue_oppo, &cr->ac);
2904 break;
2905 }
2906
2907 #ifdef USE_KEYRR
2908 cr->b.step = fos_myid_ip_key;
2909 /* fall through */
2910
2911 case fos_myid_ip_key:
2912 if (c->spd.this.id.kind == ID_MYID
2913 && myid_state != MYID_SPECIFIED)
2914 {
2915 cr->b.failure_ok = TRUE;
2916 cr->b.want = b->want = "KEY record for IP address as %myid (no good TXT)";
2917 ugh = start_adns_query(myids[MYID_IP], NULL, /* security gateway meaningless */
2918 T_KEY, continue_oppo, &cr->ac);
2919 break;
2920 }
2921 cr->b.step = fos_myid_hostname_key;
2922 /* fall through */
2923
2924 case fos_myid_hostname_key:
2925 if (c->spd.this.id.kind == ID_MYID
2926 && myid_state != MYID_SPECIFIED)
2927 {
2928 cr->b.failure_ok = FALSE; /* last attempt! */
2929 cr->b.want = b->want = "KEY record for hostname as %myid (no good TXT)";
2930 ugh = start_adns_query(myids[MYID_HOSTNAME], NULL, /* security gateway meaningless */
2931 T_KEY, continue_oppo, &cr->ac);
2932 break;
2933 }
2934 #endif
2935 cr->b.step = fos_our_client;
2936 /* fall through */
2937
2938 case fos_our_client: /* TXT for our client */
2939 if (!sameaddr(&c->spd.this.host_addr, &b->our_client))
2940 {
2941 /* Check that at least one TXT(reverse(b->our_client)) is workable.
2942 * Note: {unshare|free}_id_content not needed for id: ephemeral.
2943 */
2944 cr->b.want = b->want = "our client's TXT record";
2945 id = identification_create_from_sockaddr((sockaddr_t*)&b->our_client);
2946 ugh = start_adns_query(id, c->spd.this.id, /* we are the security gateway */
2947 T_TXT, continue_oppo, &cr->ac);
2948 id->destroy(id);
2949 break;
2950 }
2951 cr->b.step = fos_our_txt;
2952 /* fall through */
2953
2954 case fos_our_txt: /* TXT for us */
2955 cr->b.failure_ok = b->failure_ok = TRUE;
2956 cr->b.want = b->want = "our TXT record";
2957 ugh = start_adns_query(sr->this.id, sr->this.id, /* we are the security gateway */
2958 T_TXT, continue_oppo, &cr->ac);
2959 break;
2960
2961 #ifdef USE_KEYRR
2962 case fos_our_key: /* KEY for us */
2963 cr->b.want = b->want = "our KEY record";
2964 cr->b.failure_ok = b->failure_ok = FALSE;
2965 ugh = start_adns_query(sr->this.id, NULL, /* security gateway meaningless */
2966 T_KEY, continue_oppo, &cr->ac);
2967 break;
2968 #endif /* USE_KEYRR */
2969
2970 case fos_his_client: /* TXT for his client */
2971 /* note: {unshare|free}_id_content not needed for id: ephemeral */
2972 cr->b.want = b->want = "target's TXT record";
2973 cr->b.failure_ok = b->failure_ok = FALSE;
2974 id = identification_create_from_sockaddr((sockaddr_t*)&b->peer_client);
2975 ugh = start_adns_query(id, NULL, /* security gateway unconstrained */
2976 T_TXT, continue_oppo, &cr->ac);
2977 id->destroy(id);
2978 break;
2979
2980 default:
2981 bad_case(next_step);
2982 }
2983
2984 if (ugh == NULL)
2985 b->whackfd = NULL_FD; /* complete hand-off */
2986 else
2987 cannot_oppo(c, b, ugh);
2988 }
2989 }
2990 close_any(b->whackfd);
2991 }
2992
2993 void terminate_connection(const char *nm)
2994 {
2995 /* Loop because more than one may match (master and instances)
2996 * But at least one is required (enforced by con_by_name).
2997 */
2998 connection_t *c = con_by_name(nm, TRUE);
2999
3000 if (c == NULL || !c->ikev1)
3001 return;
3002
3003 do
3004 {
3005 connection_t *n = c->ac_next; /* grab this before c might disappear */
3006
3007 if (streq(c->name, nm)
3008 && c->kind >= CK_PERMANENT
3009 && !NEVER_NEGOTIATE(c->policy))
3010 {
3011 set_cur_connection(c);
3012 plog("terminating SAs using this connection");
3013 c->policy &= ~POLICY_UP;
3014 flush_pending_by_connection(c);
3015 delete_states_by_connection(c, FALSE);
3016 if (c->kind == CK_INSTANCE)
3017 delete_connection(c, FALSE);
3018 reset_cur_connection();
3019 }
3020 c = n;
3021 } while (c);
3022 }
3023
3024 /* an ISAKMP SA has been established.
3025 * Note the serial number, and release any connections with
3026 * the same peer ID but different peer IP address.
3027 */
3028 bool uniqueIDs = FALSE; /* --uniqueids? */
3029
3030 void ISAKMP_SA_established(connection_t *c, so_serial_t serial)
3031 {
3032 c->newest_isakmp_sa = serial;
3033
3034 /* the connection is now oriented so that we are able to determine
3035 * whether we are a mode config server with a virtual IP to send.
3036 */
3037 if (!c->spd.that.host_srcip->is_anyaddr(c->spd.that.host_srcip) &&
3038 !c->spd.that.has_natip)
3039 {
3040 c->spd.that.modecfg = TRUE;
3041 }
3042
3043 if (uniqueIDs)
3044 {
3045 /* for all connections: if the same Phase 1 IDs are used
3046 * for a different IP address, unorient that connection.
3047 */
3048 connection_t *d;
3049
3050 for (d = connections; d != NULL; )
3051 {
3052 connection_t *next = d->ac_next; /* might move underneath us */
3053
3054 if (d->kind >= CK_PERMANENT &&
3055 c->spd.this.id->equals(c->spd.this.id, d->spd.this.id) &&
3056 c->spd.that.id->equals(c->spd.that.id, d->spd.that.id) &&
3057 !sameaddr(&c->spd.that.host_addr, &d->spd.that.host_addr))
3058 {
3059 release_connection(d, FALSE);
3060 }
3061 d = next;
3062 }
3063 }
3064 }
3065
3066 /* Find the connection to connection c's peer's client with the
3067 * largest value of .routing. All other things being equal,
3068 * preference is given to c. If none is routed, return NULL.
3069 *
3070 * If erop is non-null, set *erop to a connection sharing both
3071 * our client subnet and peer's client subnet with the largest value
3072 * of .routing. If none is erouted, set *erop to NULL.
3073 *
3074 * The return value is used to find other connections sharing a route.
3075 * *erop is used to find other connections sharing an eroute.
3076 */
3077 connection_t *route_owner(connection_t *c, struct spd_route **srp,
3078 connection_t **erop, struct spd_route **esrp)
3079 {
3080 connection_t *d
3081 , *best_ro = c
3082 , *best_ero = c;
3083 struct spd_route *srd, *src;
3084 struct spd_route *best_sr, *best_esr;
3085 enum routing_t best_routing, best_erouting;
3086
3087 passert(oriented(*c));
3088 best_sr = NULL;
3089 best_esr = NULL;
3090 best_routing = c->spd.routing;
3091 best_erouting = best_routing;
3092
3093 for (d = connections; d != NULL; d = d->ac_next)
3094 {
3095 for (srd = &d->spd; srd; srd = srd->next)
3096 {
3097 if (srd->routing == RT_UNROUTED)
3098 continue;
3099
3100 for (src = &c->spd; src; src=src->next)
3101 {
3102 if (!samesubnet(&src->that.client, &srd->that.client))
3103 {
3104 continue;
3105 }
3106 if (src->that.protocol != srd->that.protocol)
3107 {
3108 continue;
3109 }
3110 if (src->that.port != srd->that.port)
3111 {
3112 continue;
3113 }
3114 passert(oriented(*d));
3115 if (srd->routing > best_routing)
3116 {
3117 best_ro = d;
3118 best_sr = srd;
3119 best_routing = srd->routing;
3120 }
3121
3122 if (!samesubnet(&src->this.client, &srd->this.client))
3123 {
3124 continue;
3125 }
3126 if (src->this.protocol != srd->this.protocol)
3127 {
3128 continue;
3129 }
3130 if (src->this.port != srd->this.port)
3131 {
3132 continue;
3133 }
3134 if (srd->routing > best_erouting)
3135 {
3136 best_ero = d;
3137 best_esr = srd;
3138 best_erouting = srd->routing;
3139 }
3140 }
3141 }
3142 }
3143
3144 DBG(DBG_CONTROL,
3145 {
3146 char cib[CONN_INST_BUF];
3147 err_t m = builddiag("route owner of \"%s\"%s %s:"
3148 , c->name
3149 , (fmt_conn_instance(c, cib), cib)
3150 , enum_name(&routing_story, c->spd.routing));
3151
3152 if (!routed(best_ro->spd.routing))
3153 m = builddiag("%s NULL", m);
3154 else if (best_ro == c)
3155 m = builddiag("%s self", m);
3156 else
3157 m = builddiag("%s \"%s\"%s %s", m
3158 , best_ro->name
3159 , (fmt_conn_instance(best_ro, cib), cib)
3160 , enum_name(&routing_story, best_ro->spd.routing));
3161
3162 if (erop)
3163 {
3164 m = builddiag("%s; eroute owner:", m);
3165 if (!erouted(best_ero->spd.routing))
3166 m = builddiag("%s NULL", m);
3167 else if (best_ero == c)
3168 m = builddiag("%s self", m);
3169 else
3170 m = builddiag("%s \"%s\"%s %s", m
3171 , best_ero->name
3172 , (fmt_conn_instance(best_ero, cib), cib)
3173 , enum_name(&routing_story, best_ero->spd.routing));
3174 }
3175
3176 DBG_log("%s", m);
3177 });
3178
3179 if (erop)
3180 {
3181 *erop = erouted(best_erouting)? best_ero : NULL;
3182 }
3183 if (srp)
3184 {
3185 *srp = best_sr;
3186 if (esrp)
3187 {
3188 *esrp = best_esr;
3189 }
3190 }
3191
3192 return routed(best_routing)? best_ro : NULL;
3193 }
3194
3195 /* Find a connection that owns the shunt eroute between subnets.
3196 * There ought to be only one.
3197 * This might get to be a bottleneck -- try hashing if it does.
3198 */
3199 connection_t *shunt_owner(const ip_subnet *ours, const ip_subnet *his)
3200 {
3201 connection_t *c;
3202 struct spd_route *sr;
3203
3204 for (c = connections; c != NULL; c = c->ac_next)
3205 {
3206 for (sr = &c->spd; sr; sr = sr->next)
3207 {
3208 if (shunt_erouted(sr->routing)
3209 && samesubnet(ours, &sr->this.client)
3210 && samesubnet(his, &sr->that.client))
3211 return c;
3212 }
3213 }
3214 return NULL;
3215 }
3216
3217 /* Find some connection with this pair of hosts.
3218 * We don't know enough to chose amongst those available.
3219 * ??? no longer usefully different from find_host_pair_connections
3220 */
3221 connection_t *find_host_connection(const ip_address *me, u_int16_t my_port,
3222 const ip_address *him, u_int16_t his_port,
3223 lset_t policy)
3224 {
3225 connection_t *c = find_host_pair_connections(me, my_port, him, his_port);
3226
3227 if (policy != LEMPTY)
3228 {
3229 lset_t auth_requested = policy & POLICY_ID_AUTH_MASK;
3230
3231 /* if we have requirements for the policy,
3232 * choose the first matching connection.
3233 */
3234 while (c)
3235 {
3236 if (c->policy & auth_requested)
3237 {
3238 break;
3239 }
3240 c = c->hp_next;
3241 }
3242 }
3243 return c;
3244 }
3245
3246 /* given an up-until-now satisfactory connection, find the best connection
3247 * now that we just got the Phase 1 Id Payload from the peer.
3248 *
3249 * Comments in the code describe the (tricky!) matching criteria.
3250 * Although this routine could handle the initiator case,
3251 * it isn't currently called in this case.
3252 * If it were, it could "upgrade" an Opportunistic Connection
3253 * to a Road Warrior Connection if a suitable Peer ID were found.
3254 *
3255 * In RFC 2409 "The Internet Key Exchange (IKE)",
3256 * in 5.1 "IKE Phase 1 Authenticated With Signatures", describing Main
3257 * Mode:
3258 *
3259 * Initiator Responder
3260 * ----------- -----------
3261 * HDR, SA -->
3262 * <-- HDR, SA
3263 * HDR, KE, Ni -->
3264 * <-- HDR, KE, Nr
3265 * HDR*, IDii, [ CERT, ] SIG_I -->
3266 * <-- HDR*, IDir, [ CERT, ] SIG_R
3267 *
3268 * In 5.4 "Phase 1 Authenticated With a Pre-Shared Key":
3269 *
3270 * HDR, SA -->
3271 * <-- HDR, SA
3272 * HDR, KE, Ni -->
3273 * <-- HDR, KE, Nr
3274 * HDR*, IDii, HASH_I -->
3275 * <-- HDR*, IDir, HASH_R
3276 *
3277 * refine_host_connection could be called in two case:
3278 *
3279 * - the Responder receives the IDii payload:
3280 * + [PSK] after using PSK to decode this message
3281 * + before sending its IDir payload
3282 * + before using its ID in HASH_R computation
3283 * + [DSig] before using its private key to sign SIG_R
3284 * + before using the Initiator's ID in HASH_I calculation
3285 * + [DSig] before using the Initiator's public key to check SIG_I
3286 *
3287 * - the Initiator receives the IDir payload:
3288 * + [PSK] after using PSK to encode previous message and decode this message
3289 * + after sending its IDii payload
3290 * + after using its ID in HASH_I computation
3291 * + [DSig] after using its private key to sign SIG_I
3292 * + before using the Responder's ID to compute HASH_R
3293 * + [DSig] before using Responder's public key to check SIG_R
3294 *
3295 * refine_host_connection can choose a different connection, as long as
3296 * nothing already used is changed.
3297 *
3298 * In the Initiator case, the particular connection might have been
3299 * specified by whatever provoked Pluto to initiate. For example:
3300 * whack --initiate connection-name
3301 * The advantages of switching connections when we're the Initiator seem
3302 * less important than the disadvantages, so after FreeS/WAN 1.9, we
3303 * don't do this.
3304 */
3305 #define PRIO_NO_MATCH_FOUND 2048
3306
3307 connection_t *refine_host_connection(const struct state *st,
3308 identification_t *peer_id,
3309 identification_t *peer_ca)
3310 {
3311 connection_t *c = st->st_connection;
3312 connection_t *d;
3313 connection_t *best_found = NULL;
3314 u_int16_t auth = st->st_oakley.auth;
3315 lset_t auth_policy = POLICY_PSK;
3316 const chunk_t *psk = NULL;
3317 bool wcpip; /* wildcard Peer IP? */
3318 int best_prio = PRIO_NO_MATCH_FOUND;
3319 int our_pathlen, peer_pathlen;
3320
3321 if (c->spd.that.id->equals(c->spd.that.id, peer_id) &&
3322 trusted_ca(peer_ca, c->spd.that.ca, &peer_pathlen) &&
3323 peer_pathlen == 0 &&
3324 match_requested_ca(c->requested_ca, c->spd.this.ca, &our_pathlen) &&
3325 our_pathlen == 0)
3326 {
3327 DBG(DBG_CONTROL,
3328 DBG_log("current connection is a full match"
3329 " -- no need to look further");
3330 )
3331 return c;
3332 }
3333
3334 switch (auth)
3335 {
3336 case OAKLEY_PRESHARED_KEY:
3337 auth_policy = POLICY_PSK;
3338 psk = get_preshared_secret(c);
3339 /* It should be virtually impossible to fail to find PSK:
3340 * we just used it to decode the current message!
3341 */
3342 if (psk == NULL)
3343 {
3344 return NULL; /* cannot determine PSK! */
3345 }
3346 break;
3347 case XAUTHInitPreShared:
3348 case XAUTHRespPreShared:
3349 auth_policy = POLICY_XAUTH_PSK;
3350 psk = get_preshared_secret(c);
3351 if (psk == NULL)
3352 {
3353 return NULL; /* cannot determine PSK! */
3354 }
3355 break;
3356 case OAKLEY_RSA_SIG:
3357 case OAKLEY_ECDSA_256:
3358 case OAKLEY_ECDSA_384:
3359 case OAKLEY_ECDSA_521:
3360 auth_policy = POLICY_PUBKEY;
3361 break;
3362 case XAUTHInitRSA:
3363 case XAUTHRespRSA:
3364 auth_policy = POLICY_XAUTH_RSASIG;
3365 break;
3366 default:
3367 bad_case(auth);
3368 }
3369
3370 /* The current connection won't do: search for one that will.
3371 * First search for one with the same pair of hosts.
3372 * If that fails, search for a suitable Road Warrior or Opportunistic
3373 * connection (i.e. wildcard peer IP).
3374 * We need to match:
3375 * - peer_id (slightly complicated by instantiation)
3376 * - if PSK auth, the key must not change (we used it to decode message)
3377 * - policy-as-used must be acceptable to new connection
3378 */
3379 d = c->host_pair->connections;
3380 for (wcpip = FALSE; ; wcpip = TRUE)
3381 {
3382 for (; d != NULL; d = d->hp_next)
3383 {
3384 const char *match_name[] = {"no", "ok"};
3385
3386 id_match_t match_level = peer_id->matches(peer_id, d->spd.that.id);
3387
3388 bool matching_id = match_level > ID_MATCH_NONE;
3389
3390 bool matching_auth = (d->policy & auth_policy) != LEMPTY;
3391
3392 bool matching_trust = trusted_ca(peer_ca
3393 , d->spd.that.ca, &peer_pathlen);
3394 bool matching_request = match_requested_ca(c->requested_ca
3395 , d->spd.this.ca, &our_pathlen);
3396 bool match = matching_id && matching_auth && matching_trust;
3397
3398 int prio = (ID_MATCH_PERFECT) * !matching_request +
3399 ID_MATCH_PERFECT - match_level;
3400
3401 prio = (X509_MAX_PATH_LEN + 1) * prio + peer_pathlen;
3402 prio = (X509_MAX_PATH_LEN + 1) * prio + our_pathlen;
3403
3404 DBG(DBG_CONTROLMORE,
3405 DBG_log("%s: %s match (id: %s, auth: %s, trust: %s, request: %s, prio: %4d)"
3406 , d->name
3407 , match ? "full":" no"
3408 , match_name[matching_id]
3409 , match_name[matching_auth]
3410 , match_name[matching_trust]
3411 , match_name[matching_request]
3412 , match ? prio:PRIO_NO_MATCH_FOUND)
3413 )
3414
3415 /* do we have a match? */
3416 if (!match)
3417 {
3418 continue;
3419 }
3420
3421 /* ignore group connections */
3422 if (d->policy & POLICY_GROUP)
3423 {
3424 continue;
3425 }
3426
3427 if (c->spd.that.host_port != d->spd.that.host_port
3428 && d->kind == CK_INSTANCE)
3429 {
3430 continue;
3431 }
3432
3433 switch (auth)
3434 {
3435 case OAKLEY_PRESHARED_KEY:
3436 case XAUTHInitPreShared:
3437 case XAUTHRespPreShared:
3438 /* secret must match the one we already used */
3439 {
3440 const chunk_t *dpsk = get_preshared_secret(d);
3441
3442 if (dpsk == NULL)
3443 {
3444 continue; /* no secret */
3445 }
3446 if (psk != dpsk)
3447 {
3448 if (psk->len != dpsk->len
3449 || memcmp(psk->ptr, dpsk->ptr, psk->len) != 0)
3450 {
3451 continue; /* different secret */
3452 }
3453 }
3454 }
3455 break;
3456
3457 case OAKLEY_RSA_SIG:
3458 case OAKLEY_ECDSA_256:
3459 case OAKLEY_ECDSA_384:
3460 case OAKLEY_ECDSA_521:
3461 case XAUTHInitRSA:
3462 case XAUTHRespRSA:
3463 /*
3464 * We must at least be able to find our private key
3465 .*/
3466 if (d->spd.this.sc == NULL /* no smartcard */
3467 && get_private_key(d) == NULL) /* no private key */
3468 {
3469 continue;
3470 }
3471 break;
3472
3473 default:
3474 bad_case(auth);
3475 }
3476
3477 /* d has passed all the tests.
3478 * We'll go with it if the Peer ID was an exact match.
3479 */
3480 if (prio == 0)
3481 {
3482 return d;
3483 }
3484
3485 /* We'll remember it as best_found in case an exact
3486 * match doesn't come along.
3487 */
3488 if (prio < best_prio)
3489 {
3490 best_found = d;
3491 best_prio = prio;
3492 }
3493 }
3494 if (wcpip)
3495 return best_found; /* been around twice already */
3496
3497 /* Starting second time around.
3498 * We're willing to settle for a connection that needs Peer IP
3499 * instantiated: Road Warrior or Opportunistic.
3500 * Look on list of connections for host pair with wildcard Peer IP
3501 */
3502 d = find_host_pair_connections(&c->spd.this.host_addr, c->spd.this.host_port
3503 , (ip_address *)NULL, c->spd.that.host_port);
3504 }
3505 }
3506
3507 /**
3508 * With virtual addressing, we must not allow someone to use an already
3509 * used (by another id) addr/net.
3510 */
3511 static bool is_virtual_net_used(const ip_subnet *peer_net,
3512 identification_t *peer_id)
3513 {
3514 connection_t *d;
3515
3516 for (d = connections; d != NULL; d = d->ac_next)
3517 {
3518 switch (d->kind)
3519 {
3520 case CK_PERMANENT:
3521 case CK_INSTANCE:
3522 if ((subnetinsubnet(peer_net,&d->spd.that.client) ||
3523 subnetinsubnet(&d->spd.that.client,peer_net))
3524 && !d->spd.that.id->equals(d->spd.that.id, peer_id))
3525 {
3526 char client[SUBNETTOT_BUF];
3527
3528 subnettot(peer_net, 0, client, sizeof(client));
3529 plog("Virtual IP %s is already used by '%Y'",
3530 client, d->spd.that.id);
3531 plog("Your ID is '%Y'", peer_id);
3532
3533 return TRUE; /* already used by another one */
3534 }
3535 break;
3536 case CK_GOING_AWAY:
3537 default:
3538 break;
3539 }
3540 }
3541 return FALSE; /* you can safely use it */
3542 }
3543
3544 /* find_client_connection: given a connection suitable for ISAKMP
3545 * (i.e. the hosts match), find a one suitable for IPSEC
3546 * (i.e. with matching clients).
3547 *
3548 * If we don't find an exact match (not even our current connection),
3549 * we try for one that still needs instantiation. Try Road Warrior
3550 * abstract connections and the Opportunistic abstract connections.
3551 * This requires inverse instantiation: abstraction.
3552 *
3553 * After failing to find an exact match, we abstract the peer
3554 * to be NO_IP (the wildcard value). This enables matches with
3555 * Road Warrior and Opportunistic abstract connections.
3556 *
3557 * After failing that search, we also abstract the Phase 1 peer ID
3558 * if possible. If the peer's ID was the peer's IP address, we make
3559 * it NO_ID; instantiation will make it the peer's IP address again.
3560 *
3561 * If searching for a Road Warrior abstract connection fails,
3562 * and conditions are suitable, we search for the best Opportunistic
3563 * abstract connection.
3564 *
3565 * Note: in the end, both Phase 1 IDs must be preserved, after any
3566 * instantiation. They are the IDs that have been authenticated.
3567 */
3568
3569 #define PATH_WEIGHT 1
3570 #define WILD_WEIGHT (X509_MAX_PATH_LEN+1)
3571 #define PRIO_WEIGHT (ID_MATCH_PERFECT+1) * WILD_WEIGHT
3572
3573 /* fc_try: a helper function for find_client_connection */
3574 static connection_t *fc_try(const connection_t *c, struct host_pair *hp,
3575 identification_t *peer_id,
3576 const ip_subnet *our_net,
3577 const ip_subnet *peer_net,
3578 const u_int8_t our_protocol,
3579 const u_int16_t our_port,
3580 const u_int8_t peer_protocol,
3581 const u_int16_t peer_port,
3582 identification_t *peer_ca,
3583 ietf_attributes_t *peer_attributes)
3584 {
3585 connection_t *d;
3586 connection_t *best = NULL;
3587 policy_prio_t best_prio = BOTTOM_PRIO;
3588 id_match_t match_level;
3589 int pathlen;
3590
3591
3592 const bool peer_net_is_host = subnetisaddr(peer_net, &c->spd.that.host_addr);
3593
3594 for (d = hp->connections; d != NULL; d = d->hp_next)
3595 {
3596 struct spd_route *sr;
3597
3598 if (d->policy & POLICY_GROUP)
3599 {
3600 continue;
3601 }
3602
3603 match_level = c->spd.that.id->matches(c->spd.that.id, d->spd.