fixed release of virtual IP for XAUTH identities
[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 identification_t *client_id;
301
302 old_cur_connection = cur_connection == c? NULL : cur_connection;
303 #ifdef DEBUG
304 lset_t old_cur_debugging = cur_debugging;
305 #endif
306
307 set_cur_connection(c);
308
309 /* Must be careful to avoid circularity:
310 * we mark c as going away so it won't get deleted recursively.
311 */
312 passert(c->kind != CK_GOING_AWAY);
313 if (c->kind == CK_INSTANCE)
314 {
315 plog("deleting connection \"%s\" instance with peer %s {isakmp=#%lu/ipsec=#%lu}"
316 , c->name
317 , ip_str(&c->spd.that.host_addr)
318 , c->newest_isakmp_sa, c->newest_ipsec_sa);
319 c->kind = CK_GOING_AWAY;
320 }
321 else
322 {
323 plog("deleting connection");
324 }
325 release_connection(c, relations); /* won't delete c */
326
327 if (c->kind == CK_GROUP)
328 {
329 delete_group(c);
330 }
331
332 /* free up any logging resources */
333 perpeer_logfree(c);
334
335 /* find and delete c from connections list */
336 list_rm(connection_t, ac_next, c, connections);
337 cur_connection = old_cur_connection;
338
339 /* find and delete c from the host pair list */
340 if (c->host_pair == NULL)
341 {
342 if (c->ikev1)
343 {
344 list_rm(connection_t, hp_next, c, unoriented_connections);
345 }
346 }
347 else
348 {
349 struct host_pair *hp = c->host_pair;
350
351 list_rm(connection_t, hp_next, c, hp->connections);
352 c->host_pair = NULL; /* redundant, but safe */
353
354 /* if there are no more connections with this host_pair
355 * and we haven't even made an initial contact, let's delete
356 * this guy in case we were created by an attempted DOS attack.
357 */
358 if (hp->connections == NULL
359 && !hp->initial_connection_sent)
360 {
361 passert(hp->pending == NULL); /* ??? must deal with this! */
362 list_rm(struct host_pair, next, hp, host_pairs);
363 free(hp);
364 }
365 }
366 if (c->kind != CK_GOING_AWAY)
367 {
368 free(c->spd.that.virt);
369 }
370
371 client_id = (c->xauth_identity) ? c->xauth_identity : c->spd.that.id;
372
373 /* release virtual IP address lease if any */
374 if (c->spd.that.modecfg && c->spd.that.pool &&
375 !c->spd.that.host_srcip->is_anyaddr(c->spd.that.host_srcip))
376 {
377 hydra->attributes->release_address(hydra->attributes, c->spd.that.pool,
378 c->spd.that.host_srcip, client_id);
379 }
380
381 /* release requested attributes if any */
382 if (c->requested)
383 {
384 c->requested->destroy_function(c->requested,
385 (void*)modecfg_attribute_destroy);
386 }
387
388 /* release other attributes if any */
389 if (c->attributes)
390 {
391 while (c->attributes->remove_last(c->attributes, (void **)&ca) == SUCCESS)
392 {
393 hydra->attributes->release(hydra->attributes, ca->handler,
394 client_id, ca->type, ca->value);
395 modecfg_attribute_destroy(ca);
396 }
397 c->attributes->destroy(c->attributes);
398 }
399
400 if (c->kind != CK_GOING_AWAY)
401 {
402 whack_attr->del_pool(whack_attr, c->name);
403 }
404
405 /* free internal data */
406 #ifdef DEBUG
407 cur_debugging = old_cur_debugging;
408 #endif
409 free(c->name);
410 DESTROY_IF(c->xauth_identity);
411 DESTROY_IF(c->spd.this.id);
412 DESTROY_IF(c->spd.this.ca);
413 DESTROY_IF(c->spd.this.groups);
414 DESTROY_IF(c->spd.this.host_srcip);
415 free(c->spd.this.updown);
416 free(c->spd.this.pool);
417 DESTROY_IF(c->spd.that.id);
418 DESTROY_IF(c->spd.that.ca);
419 DESTROY_IF(c->spd.that.groups);
420 DESTROY_IF(c->spd.that.host_srcip);
421 free(c->spd.that.updown);
422 free(c->spd.that.pool);
423 if (c->requested_ca)
424 {
425 c->requested_ca->destroy_offset(c->requested_ca,
426 offsetof(identification_t, destroy));
427 }
428 gw_delref(&c->gw_info);
429
430 lock_certs_and_keys("delete_connection");
431 cert_release(c->spd.this.cert);
432 scx_release(c->spd.this.sc);
433 cert_release(c->spd.that.cert);
434 scx_release(c->spd.that.sc);
435 unlock_certs_and_keys("delete_connection");
436
437 alg_info_delref((struct alg_info **)&c->alg_info_esp);
438 alg_info_delref((struct alg_info **)&c->alg_info_ike);
439
440 free(c);
441 }
442
443 /* Delete connections with the specified name */
444 void delete_connections_by_name(const char *name, bool strict)
445 {
446 connection_t *c = con_by_name(name, strict);
447
448 for (; c != NULL; c = con_by_name(name, FALSE))
449 delete_connection(c, FALSE);
450 }
451
452 void delete_every_connection(void)
453 {
454 while (connections)
455 {
456 delete_connection(connections, TRUE);
457 }
458 }
459
460 void release_dead_interfaces(void)
461 {
462 struct host_pair *hp;
463
464 for (hp = host_pairs; hp != NULL; hp = hp->next)
465 {
466 connection_t **pp
467 , *p;
468
469 for (pp = &hp->connections; (p = *pp) != NULL; )
470 {
471 if (p->interface->change == IFN_DELETE)
472 {
473 /* this connection's interface is going away */
474 enum connection_kind k = p->kind;
475
476 release_connection(p, TRUE);
477
478 if (k <= CK_PERMANENT)
479 {
480 /* The connection should have survived release:
481 * move it to the unoriented_connections list.
482 */
483 passert(p == *pp);
484
485 p->interface = NULL;
486
487 *pp = p->hp_next; /* advance *pp */
488 p->host_pair = NULL;
489 p->hp_next = unoriented_connections;
490 unoriented_connections = p;
491 }
492 else
493 {
494 /* The connection should have vanished,
495 * but the previous connection remains.
496 */
497 passert(p != *pp);
498 }
499 }
500 else
501 {
502 pp = &p->hp_next; /* advance pp */
503 }
504 }
505 }
506 }
507
508 /* adjust orientations of connections to reflect newly added interfaces */
509 void check_orientations(void)
510 {
511 /* try to orient all the unoriented connections */
512 {
513 connection_t *c = unoriented_connections;
514
515 unoriented_connections = NULL;
516
517 while (c)
518 {
519 connection_t *nxt = c->hp_next;
520
521 (void)orient(c);
522 connect_to_host_pair(c);
523 c = nxt;
524 }
525 }
526
527 /* Check that no oriented connection has become double-oriented.
528 * In other words, the far side must not match one of our new interfaces.
529 */
530 {
531 struct iface *i;
532
533 for (i = interfaces; i != NULL; i = i->next)
534 {
535 if (i->change == IFN_ADD)
536 {
537 struct host_pair *hp;
538
539 for (hp = host_pairs; hp != NULL; hp = hp->next)
540 {
541 if (sameaddr(&hp->him.addr, &i->addr)
542 && hp->him.port == pluto_port)
543 {
544 /* bad news: the whole chain of connections
545 * hanging off this host pair has both sides
546 * matching an interface.
547 * We'll get rid of them, using orient and
548 * connect_to_host_pair. But we'll be lazy
549 * and not ditch the host_pair itself (the
550 * cost of leaving it is slight and cannot
551 * be induced by a foe).
552 */
553 connection_t *c = hp->connections;
554
555 hp->connections = NULL;
556 while (c)
557 {
558 connection_t *nxt = c->hp_next;
559
560 c->interface = NULL;
561 (void)orient(c);
562 connect_to_host_pair(c);
563 c = nxt;
564 }
565 }
566 }
567 }
568 }
569 }
570 }
571
572 static err_t default_end(struct end *e, ip_address *dflt_nexthop)
573 {
574 err_t ugh = NULL;
575 int af = addrtypeof(&e->host_addr);
576
577 if (af != AF_INET && af != AF_INET6)
578 {
579 return "unknown address family in default_end";
580 }
581
582 /* default ID to IP (but only if not NO_IP -- WildCard) */
583 if (e->id->get_type(e->id) == ID_ANY && !isanyaddr(&e->host_addr))
584 {
585 e->id->destroy(e->id);
586 e->id = identification_create_from_sockaddr((sockaddr_t*)&e->host_addr);
587 e->has_id_wildcards = FALSE;
588 }
589
590 /* default nexthop to other side */
591 if (isanyaddr(&e->host_nexthop))
592 {
593 e->host_nexthop = *dflt_nexthop;
594 }
595
596 /* default client to subnet containing only self
597 * XXX This may mean that the client's address family doesn't match
598 * tunnel_addr_family.
599 */
600 if (!e->has_client)
601 {
602 ugh = addrtosubnet(&e->host_addr, &e->client);
603 }
604 return ugh;
605 }
606
607 /* Format the topology of a connection end, leaving out defaults.
608 * Largest left end looks like: client === host : port [ host_id ] --- hop
609 * Note: if that==NULL, skip nexthop
610 * Returns strlen of formated result (length excludes NUL at end).
611 */
612 size_t format_end(char *buf, size_t buf_len, const struct end *this,
613 const struct end *that, bool is_left, lset_t policy)
614 {
615 char client[BUF_LEN];
616 const char *client_sep = "";
617 char protoport[sizeof(":255/65535")];
618 const char *host = NULL;
619 char host_space[ADDRTOT_BUF];
620 char host_port[sizeof(":65535")];
621 char host_id[BUF_LEN + 2];
622 char hop[ADDRTOT_BUF];
623 const char *hop_sep = "";
624 const char *open_brackets = "";
625 const char *close_brackets = "";
626
627 if (isanyaddr(&this->host_addr))
628 {
629 switch (policy & (POLICY_GROUP | POLICY_OPPO))
630 {
631 case POLICY_GROUP:
632 host = "%group";
633 break;
634 case POLICY_OPPO:
635 host = "%opportunistic";
636 break;
637 case POLICY_GROUP | POLICY_OPPO:
638 host = "%opportunisticgroup";
639 break;
640 default:
641 host = "%any";
642 break;
643 }
644 }
645
646 client[0] = '\0';
647
648 if (is_virtual_end(this) && isanyaddr(&this->host_addr))
649 {
650 host = "%virtual";
651 }
652
653 /* [client===] */
654 if (this->has_client)
655 {
656 ip_address client_net, client_mask;
657
658 networkof(&this->client, &client_net);
659 maskof(&this->client, &client_mask);
660 client_sep = "===";
661
662 /* {client_subnet_wildcard} */
663 if (this->has_client_wildcard)
664 {
665 open_brackets = "{";
666 close_brackets = "}";
667 }
668
669 if (isanyaddr(&client_net) && isanyaddr(&client_mask)
670 && (policy & (POLICY_GROUP | POLICY_OPPO)))
671 {
672 client_sep = ""; /* boring case */
673 }
674 else if (subnetisnone(&this->client))
675 {
676 strcpy(client, "?");
677 }
678 else
679 {
680 subnettot(&this->client, 0, client, sizeof(client));
681 }
682 }
683 else if (this->modecfg && this->host_srcip->is_anyaddr(this->host_srcip))
684 {
685 /* we are mode config client, or a server with a pool */
686 client_sep = "===";
687 client[0] = '%';
688 strcpy(client+1, this->pool ? this->pool : "modecfg");
689 }
690
691 /* host */
692 if (host == NULL)
693 {
694 addrtot(&this->host_addr, 0, host_space, sizeof(host_space));
695 host = host_space;
696 }
697
698 host_port[0] = '\0';
699 if (this->host_port != IKE_UDP_PORT)
700 {
701 snprintf(host_port, sizeof(host_port), ":%u", this->host_port);
702 }
703
704 /* payload portocol and port */
705 protoport[0] = '\0';
706 if (this->has_port_wildcard)
707 {
708 snprintf(protoport, sizeof(protoport), ":%u/%%any", this->protocol);
709 }
710 else if (this->port || this->protocol)
711 {
712 snprintf(protoport, sizeof(protoport), ":%u/%u", this->protocol
713 , this->port);
714 }
715
716 /* id */
717 snprintf(host_id, sizeof(host_id), "[%Y]", this->id);
718
719 /* [---hop] */
720 hop[0] = '\0';
721 hop_sep = "";
722 if (that && !sameaddr(&this->host_nexthop, &that->host_addr))
723 {
724 addrtot(&this->host_nexthop, 0, hop, sizeof(hop));
725 hop_sep = "---";
726 }
727
728 if (is_left)
729 {
730 snprintf(buf, buf_len, "%s%s%s%s%s%s%s%s%s%s%s"
731 , open_brackets, client, close_brackets, client_sep
732 , this->allow_any? "%":""
733 , host, host_port, host_id, protoport
734 , hop_sep, hop);
735 }
736 else
737 {
738 snprintf(buf, buf_len, "%s%s%s%s%s%s%s%s%s%s%s"
739 , hop, hop_sep
740 , this->allow_any? "%":""
741 , host, host_port, host_id, protoport, client_sep
742 , open_brackets, client, close_brackets);
743 }
744 return strlen(buf);
745 }
746
747 /* format topology of a connection.
748 * Two symmetric ends separated by ...
749 */
750 #define CONNECTION_BUF (2 * (END_BUF - 1) + 4)
751
752 static size_t format_connection(char *buf, size_t buf_len,
753 const connection_t *c,
754 struct spd_route *sr)
755 {
756 size_t w = format_end(buf, buf_len, &sr->this, &sr->that, TRUE, LEMPTY);
757
758 w += snprintf(buf + w, buf_len - w, "...");
759 return w + format_end(buf + w, buf_len - w, &sr->that, &sr->this, FALSE, c->policy);
760 }
761
762 static void unshare_connection_strings(connection_t *c)
763 {
764 c->name = clone_str(c->name);
765 if (c->xauth_identity)
766 {
767 c->xauth_identity = c->xauth_identity->clone(c->xauth_identity);
768 }
769 c->spd.this.id = c->spd.this.id->clone(c->spd.this.id);
770 c->spd.this.pool = clone_str(c->spd.this.pool);
771 c->spd.this.updown = clone_str(c->spd.this.updown);
772 c->spd.this.host_srcip = c->spd.this.host_srcip->clone(c->spd.this.host_srcip);
773 scx_share(c->spd.this.sc);
774 cert_share(c->spd.this.cert);
775 if (c->spd.this.ca)
776 {
777 c->spd.this.ca = c->spd.this.ca->clone(c->spd.this.ca);
778 }
779 if (c->spd.this.groups)
780 {
781 c->spd.this.groups = c->spd.this.groups->get_ref(c->spd.this.groups);
782 }
783 c->spd.that.id = c->spd.that.id->clone(c->spd.that.id);
784 c->spd.that.pool = clone_str(c->spd.that.pool);
785 c->spd.that.updown = clone_str(c->spd.that.updown);
786 c->spd.that.host_srcip = c->spd.that.host_srcip->clone(c->spd.that.host_srcip);
787 scx_share(c->spd.that.sc);
788 cert_share(c->spd.that.cert);
789 if (c->spd.that.ca)
790 {
791 c->spd.that.ca = c->spd.that.ca->clone(c->spd.that.ca);
792 }
793 if (c->spd.that.groups)
794 {
795 c->spd.that.groups = c->spd.that.groups->get_ref(c->spd.that.groups);
796 }
797
798 /* increment references to algo's */
799 alg_info_addref((struct alg_info *)c->alg_info_esp);
800 alg_info_addref((struct alg_info *)c->alg_info_ike);
801 }
802
803 static void load_end_certificate(char *filename, struct end *dst)
804 {
805 time_t notBefore, notAfter;
806 cert_t *cert = NULL;
807 certificate_t *certificate;
808 bool cached_cert = FALSE;
809
810 /* initialize end certificate */
811 dst->cert = NULL;
812
813 /* initialize smartcard info record */
814 dst->sc = NULL;
815
816 if (filename)
817 {
818 if (scx_on_smartcard(filename))
819 {
820 /* load cert from smartcard */
821 cert = scx_load_cert(filename, &dst->sc, &cached_cert);
822 }
823 else
824 {
825 /* load cert from file */
826 cert = load_host_cert(filename);
827 }
828 }
829
830 if (cert)
831 {
832 certificate = cert->cert;
833
834 if (dst->id->get_type(dst->id) == ID_ANY ||
835 !certificate->has_subject(certificate, dst->id))
836 {
837 plog( " id '%Y' not confirmed by certificate, defaulting to '%Y'",
838 dst->id, certificate->get_subject(certificate));
839 dst->id->destroy(dst->id);
840 dst->id = certificate->get_subject(certificate);
841 dst->id = dst->id->clone(dst->id);
842 }
843
844 if (cached_cert)
845 {
846 dst->cert = cert;
847 }
848 else
849 {
850 if (!certificate->get_validity(certificate, NULL, &notBefore, &notAfter))
851 {
852 plog("certificate is invalid (valid from %T to %T)",
853 &notBefore, FALSE, &notAfter, FALSE);
854 cert_free(cert);
855 return;
856 }
857 DBG(DBG_CONTROL,
858 DBG_log("certificate is valid")
859 )
860 add_public_key_from_cert(cert, notAfter, DAL_LOCAL);
861 dst->cert = cert_add(cert);
862 }
863 certificate = dst->cert->cert;
864
865 /* if no CA is defined, use issuer as default */
866 if (dst->ca == NULL && certificate->get_type(certificate) == CERT_X509)
867 {
868 identification_t *issuer;
869
870 issuer = certificate->get_issuer(certificate);
871 dst->ca = issuer->clone(issuer);
872 }
873
874 /* cache the certificate that was last retrieved from the smartcard */
875 if (dst->sc)
876 {
877 if (!certificate->equals(certificate, dst->sc->last_cert->cert))
878 {
879 lock_certs_and_keys("load_end_certificates");
880 cert_release(dst->sc->last_cert);
881 dst->sc->last_cert = dst->cert;
882 cert_share(dst->cert);
883 unlock_certs_and_keys("load_end_certificates");
884 }
885 time(&dst->sc->last_load);
886 }
887 }
888 scx_share(dst->sc);
889 cert_share(dst->cert);
890 }
891
892 static bool extract_end(struct end *dst, const whack_end_t *src,
893 const char *name, bool is_left)
894 {
895 bool same_ca = FALSE;
896
897 dst->is_left = is_left;
898 dst->id = identification_create_from_string(src->id);
899 dst->ca = NULL;
900
901 /* decode CA distinguished name, if any */
902 if (src->ca)
903 {
904 if streq(src->ca, "%same")
905 {
906 same_ca = TRUE;
907 }
908 else if (!streq(src->ca, "%any"))
909 {
910 dst->ca = identification_create_from_string(src->ca);
911 if (dst->ca->get_type(dst->ca) != ID_DER_ASN1_DN)
912 {
913 plog("bad CA string '%s', ignored", src->ca);
914 dst->ca->destroy(dst->ca);
915 dst->ca = NULL;
916 }
917 }
918 }
919
920 /* load local end certificate and extract ID, if any */
921 load_end_certificate(src->cert, dst);
922
923 /* does id has wildcards? */
924 dst->has_id_wildcards = dst->id->contains_wildcards(dst->id);
925
926 /* decode group attributes, if any */
927 if (src->groups)
928 {
929 dst->groups = ietf_attributes_create_from_string(src->groups);
930 }
931
932 /* the rest is simple copying of corresponding fields */
933 dst->host_addr = src->host_addr;
934 dst->host_nexthop = src->host_nexthop;
935 dst->host_srcip = host_create_from_sockaddr((sockaddr_t*)&src->host_srcip);
936 dst->has_natip = src->has_natip;
937 dst->client = src->client;
938 dst->protocol = src->protocol;
939 dst->port = src->port;
940 dst->has_port_wildcard = src->has_port_wildcard;
941 dst->key_from_DNS_on_demand = src->key_from_DNS_on_demand;
942 dst->has_client = src->has_client;
943 dst->has_client_wildcard = src->has_client_wildcard;
944 dst->modecfg = src->modecfg;
945 dst->hostaccess = src->hostaccess;
946 dst->allow_any = src->allow_any;
947 dst->sendcert = src->sendcert;
948 dst->updown = clone_str(src->updown);
949 dst->host_port = src->host_port;
950
951 /* if the sourceip netmask is zero a named pool exists */
952 if (src->sourceip_mask == 0)
953 {
954 dst->pool = clone_str(src->sourceip);
955 }
956
957 /* if host sourceip is defined but no client is present
958 * behind the host then set client to sourceip/32
959 */
960 if (!dst->host_srcip->is_anyaddr(dst->host_srcip) &&
961 !dst->has_natip && !dst->has_client)
962 {
963 ip_address addr;
964 err_t ugh;
965
966 addr = *(ip_address*)dst->host_srcip->get_sockaddr(dst->host_srcip);
967 ugh = addrtosubnet(&addr, &dst->client);
968
969 if (ugh)
970 {
971 plog("could not assign host sourceip to client subnet");
972 }
973 else
974 {
975 dst->has_client = TRUE;
976 }
977 }
978 return same_ca;
979 }
980
981 static bool check_connection_end(const whack_end_t *this,
982 const whack_end_t *that,
983 const whack_message_t *wm)
984 {
985 if (wm->addr_family != addrtypeof(&this->host_addr)
986 || wm->addr_family != addrtypeof(&this->host_nexthop)
987 || (this->has_client? wm->tunnel_addr_family : wm->addr_family)
988 != subnettypeof(&this->client)
989 || subnettypeof(&this->client) != subnettypeof(&that->client))
990 {
991 /* this should have been diagnosed by whack, so we need not be clear
992 * !!! overloaded use of RC_CLASH
993 */
994 loglog(RC_CLASH, "address family inconsistency in connection");
995 return FALSE;
996 }
997
998 if (isanyaddr(&that->host_addr))
999 {
1000 /* other side is wildcard: we must check if other conditions met */
1001 if (isanyaddr(&this->host_addr))
1002 {
1003 loglog(RC_ORIENT, "connection must specify host IP address for our side");
1004 return FALSE;
1005 }
1006 }
1007
1008 if (this->virt && (!isanyaddr(&this->host_addr) || this->has_client))
1009 {
1010 loglog(RC_CLASH,
1011 "virtual IP must only be used with %%any and without client");
1012 return FALSE;
1013 }
1014
1015 return TRUE; /* happy */
1016 }
1017
1018 connection_t *find_connection_by_reqid(uint32_t reqid)
1019 {
1020 connection_t *c;
1021
1022 reqid &= ~3;
1023 for (c = connections; c != NULL; c = c->ac_next)
1024 {
1025 if (c->spd.reqid == reqid)
1026 {
1027 return c;
1028 }
1029 }
1030
1031 return NULL;
1032 }
1033
1034 static uint32_t gen_reqid(void)
1035 {
1036 uint32_t start;
1037 static uint32_t reqid = IPSEC_MANUAL_REQID_MAX & ~3;
1038
1039 start = reqid;
1040 do {
1041 reqid += 4;
1042 if (reqid == 0)
1043 {
1044 reqid = (IPSEC_MANUAL_REQID_MAX & ~3) + 4;
1045 }
1046 if (!find_connection_by_reqid(reqid))
1047 {
1048 return reqid;
1049 }
1050 } while (reqid != start);
1051
1052 exit_log("unable to allocate reqid");
1053 return 0; /* never reached ... */
1054 }
1055
1056 void add_connection(const whack_message_t *wm)
1057 {
1058 if (con_by_name(wm->name, FALSE) != NULL)
1059 {
1060 loglog(RC_DUPNAME, "attempt to redefine connection \"%s\"", wm->name);
1061 }
1062 else if (wm->right.protocol != wm->left.protocol)
1063 {
1064 /* this should haven been diagnosed by whack
1065 * !!! overloaded use of RC_CLASH
1066 */
1067 loglog(RC_CLASH, "the protocol must be the same for leftport and rightport");
1068 }
1069 else if (check_connection_end(&wm->right, &wm->left, wm)
1070 && check_connection_end(&wm->left, &wm->right, wm))
1071 {
1072 bool same_rightca, same_leftca;
1073 connection_t *c = malloc_thing(connection_t);
1074
1075 zero(c);
1076 c->name = clone_str(wm->name);
1077 c->ikev1 = wm->ikev1;
1078 c->policy = wm->policy;
1079
1080 if ((c->policy & POLICY_COMPRESS) && !can_do_IPcomp)
1081 {
1082 loglog(RC_COMMENT
1083 , "ignoring --compress in \"%s\" because kernel does not support IPCOMP"
1084 , c->name);
1085 }
1086
1087 if (wm->esp)
1088 {
1089 DBG(DBG_CONTROL,
1090 DBG_log("from whack: got --esp=%s", wm->esp ? wm->esp: "NULL")
1091 )
1092 c->alg_info_esp = alg_info_esp_create_from_str(wm->esp? wm->esp : "");
1093
1094 DBG(DBG_CRYPT|DBG_CONTROL,
1095 static char buf[BUF_LEN]="<NULL>";
1096
1097 if (c->alg_info_esp)
1098 {
1099 alg_info_snprint(buf, sizeof(buf)
1100 ,(struct alg_info *)c->alg_info_esp);
1101 }
1102 DBG_log("esp proposal: %s", buf);
1103 )
1104 if (c->alg_info_esp)
1105 {
1106 if (c->alg_info_esp->alg_info_cnt == 0)
1107 {
1108 loglog(RC_LOG_SERIOUS, "got 0 esp transforms");
1109 }
1110 }
1111 else
1112 {
1113 loglog(RC_LOG_SERIOUS, "syntax error in esp string");
1114 }
1115 }
1116
1117 if (wm->ike)
1118 {
1119 DBG(DBG_CONTROL,
1120 DBG_log("from whack: got --ike=%s", wm->ike ? wm->ike: "NULL")
1121 )
1122 c->alg_info_ike= alg_info_ike_create_from_str(wm->ike? wm->ike : "");
1123
1124 DBG(DBG_CRYPT|DBG_CONTROL,
1125 static char buf[BUF_LEN]="<NULL>";
1126
1127 if (c->alg_info_ike)
1128 {
1129 alg_info_snprint(buf, sizeof(buf)
1130 , (struct alg_info *)c->alg_info_ike);
1131 }
1132 DBG_log("ike proposal: %s", buf);
1133 )
1134 if (c->alg_info_ike)
1135 {
1136 if (c->alg_info_ike->alg_info_cnt == 0)
1137 {
1138 loglog(RC_LOG_SERIOUS, "got 0 ike transforms");
1139 }
1140 }
1141 else
1142 {
1143 loglog(RC_LOG_SERIOUS, "syntax error in ike string");
1144 }
1145 }
1146
1147 if (wm->xauth_identity)
1148 {
1149 c->xauth_identity
1150 = identification_create_from_string(wm->xauth_identity);
1151 }
1152
1153 c->sa_ike_life_seconds = wm->sa_ike_life_seconds;
1154 c->sa_ipsec_life_seconds = wm->sa_ipsec_life_seconds;
1155 c->sa_rekey_margin = wm->sa_rekey_margin;
1156 c->sa_rekey_fuzz = wm->sa_rekey_fuzz;
1157 c->sa_keying_tries = wm->sa_keying_tries;
1158
1159 /* RFC 3706 DPD */
1160 c->dpd_delay = wm->dpd_delay;
1161 c->dpd_timeout = wm->dpd_timeout;
1162 c->dpd_action = wm->dpd_action;
1163
1164 c->addr_family = wm->addr_family;
1165 c->tunnel_addr_family = wm->tunnel_addr_family;
1166
1167 c->requested_ca = NULL;
1168 same_leftca = extract_end(&c->spd.this, &wm->left, wm->name, TRUE);
1169 same_rightca = extract_end(&c->spd.that, &wm->right, wm->name, FALSE);
1170
1171 if (same_rightca && c->spd.this.ca)
1172 {
1173 c->spd.that.ca = c->spd.this.ca->clone(c->spd.this.ca);
1174 }
1175 else if (same_leftca && c->spd.that.ca)
1176 {
1177 c->spd.this.ca = c->spd.that.ca->clone(c->spd.that.ca);
1178 }
1179
1180 default_end(&c->spd.this, &c->spd.that.host_addr);
1181 default_end(&c->spd.that, &c->spd.this.host_addr);
1182
1183 /* force any wildcard host IP address, any wildcard subnet
1184 * or any wildcard ID to that end
1185 */
1186 if (isanyaddr(&c->spd.this.host_addr) || c->spd.this.has_client_wildcard
1187 || c->spd.this.has_port_wildcard || c->spd.this.has_id_wildcards
1188 || c->spd.this.allow_any)
1189 {
1190 struct end t = c->spd.this;
1191
1192 c->spd.this = c->spd.that;
1193 c->spd.that = t;
1194 }
1195
1196 c->spd.next = NULL;
1197 c->spd.reqid = wm->reqid ?: gen_reqid();
1198
1199 c->spd.mark_in.value = wm->mark_in.value;
1200 c->spd.mark_in.mask = wm->mark_in.mask;
1201 c->spd.mark_out.value = wm->mark_out.value;
1202 c->spd.mark_out.mask = wm->mark_out.mask;
1203
1204 /* set internal fields */
1205 c->instance_serial = 0;
1206 c->ac_next = connections;
1207 connections = c;
1208 c->interface = NULL;
1209 c->spd.routing = RT_UNROUTED;
1210 c->newest_isakmp_sa = SOS_NOBODY;
1211 c->newest_ipsec_sa = SOS_NOBODY;
1212 c->spd.eroute_owner = SOS_NOBODY;
1213
1214 if (c->policy & POLICY_GROUP)
1215 {
1216 c->kind = CK_GROUP;
1217 add_group(c);
1218 }
1219 else if ((isanyaddr(&c->spd.that.host_addr) && !NEVER_NEGOTIATE(c->policy))
1220 || c->spd.that.has_client_wildcard || c->spd.that.has_port_wildcard
1221 || c->spd.that.has_id_wildcards || c->spd.that.allow_any)
1222 {
1223 /* Opportunistic or Road Warrior or wildcard client subnet
1224 * or wildcard ID */
1225 c->kind = CK_TEMPLATE;
1226 }
1227 else
1228 {
1229 c->kind = CK_PERMANENT;
1230 }
1231 set_policy_prio(c); /* must be after kind is set */
1232
1233 #ifdef DEBUG
1234 c->extra_debugging = wm->debugging;
1235 #endif
1236
1237 c->gw_info = NULL;
1238
1239 passert(!(wm->left.virt && wm->right.virt));
1240 if (wm->left.virt || wm->right.virt)
1241 {
1242 passert(isanyaddr(&c->spd.that.host_addr));
1243 c->spd.that.virt = create_virtual(c,
1244 wm->left.virt ? wm->left.virt : wm->right.virt);
1245 if (c->spd.that.virt)
1246 c->spd.that.has_client = TRUE;
1247 }
1248
1249 (void)orient(c);
1250
1251 /* if rightsourceip defines a subnet then create an in-memory pool */
1252 if (whack_attr->add_pool(whack_attr, c->name,
1253 c->spd.this.is_left ? &wm->right : &wm->left))
1254 {
1255 c->spd.that.pool = clone_str(c->name);
1256 c->spd.that.modecfg = TRUE;
1257 c->spd.that.has_client = FALSE;
1258 /* reset the host_srcip so that it gets assigned in modecfg */
1259 DESTROY_IF(c->spd.that.host_srcip);
1260 c->spd.that.host_srcip = host_create_any(AF_INET);
1261 }
1262
1263 if (c->ikev1)
1264 {
1265 connect_to_host_pair(c);
1266 }
1267
1268 /* log all about this connection */
1269 plog("added connection description \"%s\"", c->name);
1270 DBG(DBG_CONTROL,
1271 char topo[BUF_LEN];
1272
1273 (void) format_connection(topo, sizeof(topo), c, &c->spd);
1274
1275 DBG_log("%s", topo);
1276
1277 /* Make sure that address families can be correctly inferred
1278 * from printed ends.
1279 */
1280 passert(c->addr_family == addrtypeof(&c->spd.this.host_addr)
1281 && c->addr_family == addrtypeof(&c->spd.this.host_nexthop)
1282 && (c->spd.this.has_client? c->tunnel_addr_family : c->addr_family)
1283 == subnettypeof(&c->spd.this.client)
1284
1285 && c->addr_family == addrtypeof(&c->spd.that.host_addr)
1286 && c->addr_family == addrtypeof(&c->spd.that.host_nexthop)
1287 && (c->spd.that.has_client? c->tunnel_addr_family : c->addr_family)
1288 == subnettypeof(&c->spd.that.client));
1289
1290 DBG_log("ike_life: %lus; ipsec_life: %lus; rekey_margin: %lus;"
1291 " rekey_fuzz: %lu%%; keyingtries: %lu; policy: %s"
1292 , (unsigned long) c->sa_ike_life_seconds
1293 , (unsigned long) c->sa_ipsec_life_seconds
1294 , (unsigned long) c->sa_rekey_margin
1295 , (unsigned long) c->sa_rekey_fuzz
1296 , (unsigned long) c->sa_keying_tries
1297 , prettypolicy(c->policy));
1298 );
1299 }
1300 }
1301
1302 /* Derive a template connection from a group connection and target.
1303 * Similar to instantiate(). Happens at whack --listen.
1304 * Returns name of new connection. May be NULL.
1305 * Caller is responsible for freeing.
1306 */
1307 char *add_group_instance(connection_t *group, const ip_subnet *target)
1308 {
1309 char namebuf[100], targetbuf[SUBNETTOT_BUF];
1310 connection_t *t;
1311 char *name = NULL;
1312
1313 passert(group->kind == CK_GROUP);
1314 passert(oriented(*group));
1315
1316 /* manufacture a unique name for this template */
1317 subnettot(target, 0, targetbuf, sizeof(targetbuf));
1318 snprintf(namebuf, sizeof(namebuf), "%s#%s", group->name, targetbuf);
1319
1320 if (con_by_name(namebuf, FALSE) != NULL)
1321 {
1322 loglog(RC_DUPNAME, "group name + target yields duplicate name \"%s\""
1323 , namebuf);
1324 }
1325 else
1326 {
1327 t = clone_thing(*group);
1328 t->name = namebuf;
1329 unshare_connection_strings(t);
1330 name = clone_str(t->name);
1331 t->spd.that.client = *target;
1332 t->policy &= ~(POLICY_GROUP | POLICY_GROUTED);
1333 t->kind = isanyaddr(&t->spd.that.host_addr) && !NEVER_NEGOTIATE(t->policy)
1334 ? CK_TEMPLATE : CK_INSTANCE;
1335
1336 /* reset log file info */
1337 t->log_file_name = NULL;
1338 t->log_file = NULL;
1339 t->log_file_err = FALSE;
1340
1341 t->spd.reqid = gen_reqid();
1342
1343 if (t->spd.that.virt)
1344 {
1345 DBG_log("virtual_ip not supported in group instance");
1346 t->spd.that.virt = NULL;
1347 }
1348
1349 /* add to connections list */
1350 t->ac_next = connections;
1351 connections = t;
1352
1353 /* same host_pair as parent: stick after parent on list */
1354 group->hp_next = t;
1355
1356 /* route if group is routed */
1357 if (group->policy & POLICY_GROUTED)
1358 {
1359 if (!trap_connection(t))
1360 whack_log(RC_ROUTE, "could not route");
1361 }
1362 }
1363 return name;
1364 }
1365
1366 /* an old target has disappeared for a group: delete instance */
1367 void remove_group_instance(const connection_t *group USED_BY_DEBUG,
1368 const char *name)
1369 {
1370 passert(group->kind == CK_GROUP);
1371 passert(oriented(*group));
1372
1373 delete_connections_by_name(name, FALSE);
1374 }
1375
1376 /* Common part of instantiating a Road Warrior or Opportunistic connection.
1377 * his_id can be used to carry over an ID discovered in Phase 1.
1378 * It must not disagree with the one in c, but if that is unspecified,
1379 * the new connection will use his_id.
1380 * If his_id is NULL, and c.that.id is uninstantiated (ID_ANY), the
1381 * new connection will continue to have an uninstantiated that.id.
1382 * Note: instantiation does not affect port numbers.
1383 *
1384 * Note that instantiate can only deal with a single SPD/eroute.
1385 */
1386 static connection_t *instantiate(connection_t *c, const ip_address *him,
1387 u_int16_t his_port, identification_t *his_id)
1388 {
1389 connection_t *d;
1390
1391 passert(c->kind == CK_TEMPLATE);
1392 passert(c->spd.next == NULL);
1393
1394 c->instance_serial++;
1395 d = clone_thing(*c);
1396 d->spd.that.allow_any = FALSE;
1397
1398 if (his_id)
1399 {
1400 d->spd.that.id = his_id;
1401 d->spd.that.has_id_wildcards = FALSE;
1402 }
1403 unshare_connection_strings(d);
1404 if (d->spd.this.groups)
1405 {
1406 d->spd.this.groups = d->spd.this.groups->get_ref(d->spd.this.groups);
1407 }
1408 if (d->spd.that.groups)
1409 {
1410 d->spd.that.groups = d->spd.that.groups->get_ref(d->spd.that.groups);
1411 }
1412 d->kind = CK_INSTANCE;
1413
1414 passert(oriented(*d));
1415 d->spd.that.host_addr = *him;
1416 setportof(htons(c->spd.that.port), &d->spd.that.host_addr);
1417
1418 if (his_port) d->spd.that.host_port = his_port;
1419
1420 default_end(&d->spd.that, &d->spd.this.host_addr);
1421
1422 /* We cannot guess what our next_hop should be, but if it was
1423 * explicitly specified as 0.0.0.0, we set it to be him.
1424 * (whack will not allow nexthop to be elided in RW case.)
1425 */
1426 default_end(&d->spd.this, &d->spd.that.host_addr);
1427 d->spd.next = NULL;
1428 d->spd.reqid = gen_reqid();
1429
1430 /* set internal fields */
1431 d->ac_next = connections;
1432 connections = d;
1433 d->spd.routing = RT_UNROUTED;
1434 d->newest_isakmp_sa = SOS_NOBODY;
1435 d->newest_ipsec_sa = SOS_NOBODY;
1436 d->spd.eroute_owner = SOS_NOBODY;
1437
1438 /* reset log file info */
1439 d->log_file_name = NULL;
1440 d->log_file = NULL;
1441 d->log_file_err = FALSE;
1442
1443 connect_to_host_pair(d);
1444
1445 return d;
1446 if (sameaddr(&d->spd.that.host_addr, &d->spd.this.host_nexthop))
1447 {
1448 d->spd.this.host_nexthop = *him;
1449 }
1450 }
1451
1452 connection_t *rw_instantiate(connection_t *c, const ip_address *him,
1453 u_int16_t his_port, const ip_subnet *his_net,
1454 identification_t *his_id)
1455 {
1456 connection_t *d = instantiate(c, him, his_port, his_id);
1457
1458 if (d && his_net && is_virtual_connection(c))
1459 {
1460 d->spd.that.client = *his_net;
1461 d->spd.that.virt = NULL;
1462 if (subnetishost(his_net) && addrinsubnet(him, his_net))
1463 d->spd.that.has_client = FALSE;
1464 }
1465
1466 if (d->policy & POLICY_OPPO)
1467 {
1468 /* This must be before we know the client addresses.
1469 * Fill in one that is impossible. This prevents anyone else from
1470 * trying to use this connection to get to a particular client
1471 */
1472 d->spd.that.client = *aftoinfo(subnettypeof(&d->spd.that.client))->none;
1473 }
1474 DBG(DBG_CONTROL
1475 , DBG_log("instantiated \"%s\" for %s" , d->name, ip_str(him)));
1476 return d;
1477 }
1478
1479 connection_t *oppo_instantiate(connection_t *c, const ip_address *him,
1480 identification_t *his_id, struct gw_info *gw,
1481 const ip_address *our_client USED_BY_DEBUG,
1482 const ip_address *peer_client)
1483 {
1484 connection_t *d = instantiate(c, him, 0, his_id);
1485
1486 passert(d->spd.next == NULL);
1487
1488 /* fill in our client side */
1489 if (d->spd.this.has_client)
1490 {
1491 /* there was a client in the abstract connection
1492 * so we demand that the required client is within that subnet.
1493 */
1494 passert(addrinsubnet(our_client, &d->spd.this.client));
1495 happy(addrtosubnet(our_client, &d->spd.this.client));
1496 /* opportunistic connections do not use port selectors */
1497 setportof(0, &d->spd.this.client.addr);
1498 }
1499 else
1500 {
1501 /* there was no client in the abstract connection
1502 * so we demand that the required client be the host
1503 */
1504 passert(sameaddr(our_client, &d->spd.this.host_addr));
1505 }
1506
1507 /* fill in peer's client side.
1508 * If the client is the peer, excise the client from the connection.
1509 */
1510 passert((d->policy & POLICY_OPPO)
1511 && addrinsubnet(peer_client, &d->spd.that.client));
1512 happy(addrtosubnet(peer_client, &d->spd.that.client));
1513 /* opportunistic connections do not use port selectors */
1514 setportof(0, &d->spd.that.client.addr);
1515
1516 if (sameaddr(peer_client, &d->spd.that.host_addr))
1517 d->spd.that.has_client = FALSE;
1518
1519 passert(d->gw_info == NULL);
1520 gw_addref(gw);
1521 d->gw_info = gw;
1522
1523 /* Adjust routing if something is eclipsing c.
1524 * It must be a %hold for us (hard to passert this).
1525 * If there was another instance eclipsing, we'd be using it.
1526 */
1527 if (c->spd.routing == RT_ROUTED_ECLIPSED)
1528 d->spd.routing = RT_ROUTED_PROSPECTIVE;
1529
1530 /* Remember if the template is routed:
1531 * if so, this instance applies for initiation
1532 * even if it is created for responding.
1533 */
1534 if (routed(c->spd.routing))
1535 d->instance_initiation_ok = TRUE;
1536
1537 DBG(DBG_CONTROL,
1538 char topo[BUF_LEN];
1539
1540 (void) format_connection(topo, sizeof(topo), d, &d->spd);
1541 DBG_log("instantiated \"%s\": %s", d->name, topo);
1542 );
1543 return d;
1544 }
1545
1546 /* priority formatting */
1547 void fmt_policy_prio(policy_prio_t pp, char buf[POLICY_PRIO_BUF])
1548 {
1549 if (pp == BOTTOM_PRIO)
1550 {
1551 snprintf(buf, POLICY_PRIO_BUF, "0");
1552 }
1553 else
1554 {
1555 snprintf(buf, POLICY_PRIO_BUF, "%lu,%lu"
1556 , pp>>16, (pp & ~(~(policy_prio_t)0 << 16)) >> 8);
1557 }
1558 }
1559
1560 /* Format any information needed to identify an instance of a connection.
1561 * Fills any needed information into buf which MUST be big enough.
1562 * Road Warrior: peer's IP address
1563 * Opportunistic: [" " myclient "==="] " ..." peer ["===" hisclient] '\0'
1564 */
1565 static size_t fmt_client(const ip_subnet *client, const ip_address *gw,
1566 const char *prefix, char buf[ADDRTOT_BUF])
1567 {
1568 if (subnetisaddr(client, gw))
1569 {
1570 buf[0] = '\0'; /* compact denotation for "self" */
1571 }
1572 else
1573 {
1574 char *ap;
1575
1576 strcpy(buf, prefix);
1577 ap = buf + strlen(prefix);
1578 if (subnetisnone(client))
1579 strcpy(ap, "?"); /* unknown */
1580 else
1581 subnettot(client, 0, ap, SUBNETTOT_BUF);
1582 }
1583 return strlen(buf);
1584 }
1585
1586 void fmt_conn_instance(const connection_t *c, char buf[CONN_INST_BUF])
1587 {
1588 char *p = buf;
1589
1590 *p = '\0';
1591
1592 if (c->kind == CK_INSTANCE)
1593 {
1594 if (c->instance_serial != 0)
1595 {
1596 snprintf(p, CONN_INST_BUF, "[%lu]", c->instance_serial);
1597 p += strlen(p);
1598 }
1599
1600 if (c->policy & POLICY_OPPO)
1601 {
1602 size_t w = fmt_client(&c->spd.this.client, &c->spd.this.host_addr, " ", p);
1603
1604 p += w;
1605
1606 strcpy(p, w == 0? " ..." : "=== ...");
1607 p += strlen(p);
1608
1609 addrtot(&c->spd.that.host_addr, 0, p, ADDRTOT_BUF);
1610 p += strlen(p);
1611
1612 (void) fmt_client(&c->spd.that.client, &c->spd.that.host_addr, "===", p);
1613 }
1614 else
1615 {
1616 *p++ = ' ';
1617 addrtot(&c->spd.that.host_addr, 0, p, ADDRTOT_BUF);
1618 #
1619 if (c->spd.that.host_port != pluto_port)
1620 {
1621 p += strlen(p);
1622 sprintf(p, ":%d", c->spd.that.host_port);
1623 }
1624 }
1625 }
1626 }
1627
1628 /* Find an existing connection for a trapped outbound packet.
1629 * This is attempted before we bother with gateway discovery.
1630 * + this connection is routed or instance_of_routed_template
1631 * (i.e. approved for on-demand)
1632 * + this subnet contains our_client (or we are our_client)
1633 * + that subnet contains peer_client (or peer is peer_client)
1634 * + don't care about Phase 1 IDs (we don't know)
1635 * Note: result may still need to be instantiated.
1636 * The winner has the highest policy priority.
1637 *
1638 * If there are several with that priority, we give preference to
1639 * the first one that is an instance.
1640 *
1641 * See also build_outgoing_opportunistic_connection.
1642 */
1643 connection_t *find_connection_for_clients(struct spd_route **srp,
1644 const ip_address *our_client,
1645 const ip_address *peer_client,
1646 int transport_proto)
1647 {
1648 connection_t *c = connections, *best = NULL;
1649 policy_prio_t best_prio = BOTTOM_PRIO;
1650 struct spd_route *sr;
1651 struct spd_route *best_sr = NULL;
1652 int our_port = ntohs(portof(our_client));
1653 int peer_port = ntohs(portof(peer_client));
1654
1655 passert(!isanyaddr(our_client) && !isanyaddr(peer_client));
1656 #ifdef DEBUG
1657 if (DBGP(DBG_CONTROL))
1658 {
1659 char ocb[ADDRTOT_BUF], pcb[ADDRTOT_BUF];
1660
1661 addrtot(our_client, 0, ocb, sizeof(ocb));
1662 addrtot(peer_client, 0, pcb, sizeof(pcb));
1663 DBG_log("find_connection: "
1664 "looking for policy for connection: %s:%d/%d -> %s:%d/%d"
1665 , ocb, transport_proto, our_port, pcb, transport_proto, peer_port);
1666 }
1667 #endif /* DEBUG */
1668
1669 for (c = connections; c != NULL; c = c->ac_next)
1670 {
1671 if (c->kind == CK_GROUP)
1672 {
1673 continue;
1674 }
1675
1676 for (sr = &c->spd; best!=c && sr; sr = sr->next)
1677 {
1678 if ((routed(sr->routing) || c->instance_initiation_ok)
1679 && addrinsubnet(our_client, &sr->this.client)
1680 && addrinsubnet(peer_client, &sr->that.client)
1681 && addrinsubnet(peer_client, &sr->that.client)
1682 && (!sr->this.protocol || transport_proto == sr->this.protocol)
1683 && (!sr->this.port || our_port == sr->this.port)
1684 && (!sr->that.port || peer_port == sr->that.port))
1685 {
1686 char cib[CONN_INST_BUF];
1687 char cib2[CONN_INST_BUF];
1688
1689 policy_prio_t prio = 8 * (c->prio + (c->kind == CK_INSTANCE))
1690 + 2 * (sr->this.port == our_port)
1691 + 2 * (sr->that.port == peer_port)
1692 + (sr->this.protocol == transport_proto);
1693
1694 #ifdef DEBUG
1695 if (DBGP(DBG_CONTROL|DBG_CONTROLMORE))
1696 {
1697 char c_ocb[SUBNETTOT_BUF], c_pcb[SUBNETTOT_BUF];
1698
1699 subnettot(&c->spd.this.client, 0, c_ocb, sizeof(c_ocb));
1700 subnettot(&c->spd.that.client, 0, c_pcb, sizeof(c_pcb));
1701 DBG_log("find_connection: conn \"%s\"%s has compatible peers: %s->%s [pri: %ld]"
1702 , c->name
1703 , (fmt_conn_instance(c, cib), cib)
1704 , c_ocb, c_pcb, prio);
1705 }
1706 #endif /* DEBUG */
1707
1708 if (best == NULL)
1709 {
1710 best = c;
1711 best_sr = sr;
1712 best_prio = prio;
1713 }
1714
1715 DBG(DBG_CONTROLMORE,
1716 DBG_log("find_connection: "
1717 "comparing best \"%s\"%s [pri:%ld]{%p} (child %s) to \"%s\"%s [pri:%ld]{%p} (child %s)"
1718 , best->name
1719 , (fmt_conn_instance(best, cib), cib)
1720 , best_prio
1721 , best
1722 , (best->policy_next ? best->policy_next->name : "none")
1723 , c->name
1724 , (fmt_conn_instance(c, cib2), cib2)
1725 , prio
1726 , c
1727 , (c->policy_next ? c->policy_next->name : "none")));
1728
1729 if (prio > best_prio)
1730 {
1731 best = c;
1732 best_sr = sr;
1733 best_prio = prio;
1734 }
1735 }
1736 }
1737 }
1738
1739 if (best && NEVER_NEGOTIATE(best->policy))
1740 {
1741 best = NULL;
1742 }
1743 if (srp && best)
1744 {
1745 *srp = best_sr;
1746 }
1747
1748 #ifdef DEBUG
1749 if (DBGP(DBG_CONTROL))
1750 {
1751 if (best)
1752 {
1753 char cib[CONN_INST_BUF];
1754 DBG_log("find_connection: concluding with \"%s\"%s [pri:%ld]{%p} kind=%s"
1755 , best->name
1756 , (fmt_conn_instance(best, cib), cib)
1757 , best_prio
1758 , best
1759 , enum_name(&connection_kind_names, best->kind));
1760 } else {
1761 DBG_log("find_connection: concluding with empty");
1762 }
1763 }
1764 #endif /* DEBUG */
1765
1766 return best;
1767 }
1768
1769 /* Find and instantiate a connection for an outgoing Opportunistic connection.
1770 * We've already discovered its gateway.
1771 * We look for a the connection such that:
1772 * + this is one of our interfaces
1773 * + this subnet contains our_client (or we are our_client)
1774 * (we will specialize the client). We prefer the smallest such subnet.
1775 * + that subnet contains peer_clent (we will specialize the client).
1776 * We prefer the smallest such subnet.
1777 * + is opportunistic
1778 * + that peer is NO_IP
1779 * + don't care about Phase 1 IDs (probably should be default)
1780 * We could look for a connection that already had the desired peer
1781 * (rather than NO_IP) specified, but it doesn't seem worth the
1782 * bother.
1783 *
1784 * We look for the routed policy applying to the narrowest subnets.
1785 * We only succeed if we find such a policy AND it is satisfactory.
1786 *
1787 * The body of the inner loop is a lot like that in
1788 * find_connection_for_clients. In this case, we know the gateways
1789 * that we need to instantiate an opportunistic connection.
1790 */
1791 connection_t *build_outgoing_opportunistic_connection(struct gw_info *gw,
1792 const ip_address *our_client,
1793 const ip_address *peer_client)
1794 {
1795 struct iface *p;
1796 connection_t *best = NULL;
1797 struct spd_route *sr, *bestsr;
1798 char ocb[ADDRTOT_BUF], pcb[ADDRTOT_BUF];
1799
1800 addrtot(our_client, 0, ocb, sizeof(ocb));
1801 addrtot(peer_client, 0, pcb, sizeof(pcb));
1802
1803 /* for each of our addresses... */
1804 for (p = interfaces; p != NULL; p = p->next)
1805 {
1806 /* go through those connections with our address and NO_IP as hosts
1807 * We cannot know what port the peer would use, so we assume
1808 * that it is pluto_port (makes debugging easier).
1809 */
1810 connection_t *c = find_host_pair_connections(&p->addr, pluto_port,
1811 (ip_address *)NULL, pluto_port);
1812
1813 for (; c != NULL; c = c->hp_next)
1814 {
1815 DBG(DBG_OPPO,
1816 DBG_log("checking %s", c->name));
1817 if (c->kind == CK_GROUP)
1818 {
1819 continue;
1820 }
1821
1822 for (sr = &c->spd; best!=c && sr; sr = sr->next)
1823 {
1824 if (routed(sr->routing)
1825 && addrinsubnet(our_client, &sr->this.client)
1826 && addrinsubnet(peer_client, &sr->that.client))
1827 {
1828 if (best == NULL)
1829 {
1830 best = c;
1831 break;
1832 }
1833
1834 DBG(DBG_OPPO,
1835 DBG_log("comparing best %s to %s"
1836 , best->name, c->name));
1837
1838 for (bestsr = &best->spd; best!=c && bestsr; bestsr=bestsr->next)
1839 {
1840 if (!subnetinsubnet(&bestsr->this.client, &sr->this.client)
1841 || (samesubnet(&bestsr->this.client, &sr->this.client)
1842 && !subnetinsubnet(&bestsr->that.client
1843 , &sr->that.client)))
1844 {
1845 best = c;
1846 }
1847 }
1848 }
1849 }
1850 }
1851 }
1852
1853 if (best == NULL || NEVER_NEGOTIATE(best->policy) ||
1854 (best->policy & POLICY_OPPO) == LEMPTY || best->kind != CK_TEMPLATE)
1855 {
1856 return NULL;
1857 }
1858 else
1859 {
1860 chunk_t encoding = gw->gw_id->get_encoding(gw->gw_id);
1861 id_type_t type = gw->gw_id->get_type(gw->gw_id);
1862 ip_address ip_addr;
1863
1864 initaddr(encoding.ptr, encoding.len,
1865 (type == ID_IPV4_ADDR) ? AF_INET : AF_INET6, &ip_addr);
1866
1867 return oppo_instantiate(best, &ip_addr, NULL, gw, our_client, peer_client);
1868 }
1869 }
1870
1871 bool orient(connection_t *c)
1872 {
1873 struct spd_route *sr;
1874
1875 if (!oriented(*c))
1876 {
1877 struct iface *p;
1878
1879 for (sr = &c->spd; sr; sr = sr->next)
1880 {
1881 /* Note: this loop does not stop when it finds a match:
1882 * it continues checking to catch any ambiguity.
1883 */
1884 for (p = interfaces; p != NULL; p = p->next)
1885 {
1886 if (p->ike_float)
1887 {
1888 continue;
1889 }
1890
1891 for (;;)
1892 {
1893 /* check if this interface matches this end */
1894 if (sameaddr(&sr->this.host_addr, &p->addr)
1895 && sr->this.host_port == pluto_port)
1896 {
1897 if (oriented(*c))
1898 {
1899 if (c->interface == p)
1900 loglog(RC_LOG_SERIOUS
1901 , "both sides of \"%s\" are our interface %s!"
1902 , c->name, p->rname);
1903 else
1904 loglog(RC_LOG_SERIOUS, "two interfaces match \"%s\" (%s, %s)"
1905 , c->name, c->interface->rname, p->rname);
1906 c->interface = NULL; /* withdraw orientation */
1907 return FALSE;
1908 }
1909 c->interface = p;
1910 }
1911
1912 /* done with this interface if it doesn't match that end */
1913 if (!(sameaddr(&sr->that.host_addr, &p->addr)
1914 && sr->that.host_port == pluto_port))
1915 break;
1916
1917 /* swap ends and try again.
1918 * It is a little tricky to see that this loop will stop.
1919 * Only continue if the far side matches.
1920 * If both sides match, there is an error-out.
1921 */
1922 {
1923 struct end t = sr->this;
1924
1925 sr->this = sr->that;
1926 sr->that = t;
1927 }
1928 }
1929 }
1930 }
1931 }
1932 return oriented(*c);
1933 }
1934
1935 void initiate_connection(const char *name, int whackfd)
1936 {
1937 connection_t *c = con_by_name(name, TRUE);
1938
1939 if (c && c->ikev1)
1940 {
1941 set_cur_connection(c);
1942 if (!oriented(*c))
1943 {
1944 loglog(RC_ORIENT, "we have no ipsecN interface for either end of this connection");
1945 }
1946 else if (NEVER_NEGOTIATE(c->policy))
1947 {
1948 loglog(RC_INITSHUNT
1949 , "cannot initiate an authby=never connection");
1950 }
1951 else if (c->kind != CK_PERMANENT && !c->spd.that.allow_any)
1952 {
1953 if (isanyaddr(&c->spd.that.host_addr))
1954 loglog(RC_NOPEERIP, "cannot initiate connection without knowing peer IP address");
1955 else
1956 loglog(RC_WILDCARD, "cannot initiate connection with ID wildcards");
1957 }
1958 else
1959 {
1960 /* do we have to prompt for a PIN code? */
1961 if (c->spd.this.sc && !c->spd.this.sc->valid && whackfd != NULL_FD)
1962 {
1963 scx_get_pin(c->spd.this.sc, whackfd);
1964 }
1965 if (c->spd.this.sc && !c->spd.this.sc->valid)
1966 {
1967 loglog(RC_NOVALIDPIN, "cannot initiate connection without valid PIN");
1968 }
1969 else
1970 {
1971
1972 if (c->spd.that.allow_any)
1973 {
1974 c = instantiate(c, &c->spd.that.host_addr,
1975 c->spd.that.host_port, c->spd.that.id);
1976 }
1977
1978 /* We will only request an IPsec SA if policy isn't empty
1979 * (ignoring Main Mode items).
1980 * This is a fudge, but not yet important.
1981 * If we are to proceed asynchronously, whackfd will be NULL_FD.
1982 */
1983 c->policy |= POLICY_UP;
1984 ipsecdoi_initiate(whackfd, c, c->policy, 1, SOS_NOBODY);
1985 whackfd = NULL_FD; /* protect from close */
1986 }
1987 }
1988 reset_cur_connection();
1989 }
1990 close_any(whackfd);
1991 }
1992
1993 /* (Possibly) Opportunistic Initiation:
1994 * Knowing clients (single IP addresses), try to build an tunnel.
1995 * This may involve discovering a gateway and instantiating an
1996 * Opportunistic connection. Called when a packet is caught by
1997 * a %trap, or when whack --oppohere --oppothere is used.
1998 * It may turn out that an existing or non-opporunistic connnection
1999 * can handle the traffic.
2000 *
2001 * Most of the code will be restarted if an ADNS request is made
2002 * to discover the gateway. The only difference between the first
2003 * and second entry is whether gateways_from_dns is NULL or not.
2004 * initiate_opportunistic: initial entrypoint
2005 * continue_oppo: where we pickup when ADNS result arrives
2006 * initiate_opportunistic_body: main body shared by above routines
2007 * cannot_oppo: a helper function to log a diagnostic
2008 * This structure repeats a lot of code when the ADNS result arrives.
2009 * This seems like a waste, but anything learned the first time through
2010 * may no longer be true!
2011 *
2012 * After the first IKE message is sent, the regular state machinery
2013 * carries negotiation forward.
2014 */
2015
2016 enum find_oppo_step {
2017 fos_start,
2018 fos_myid_ip_txt,
2019 fos_myid_hostname_txt,
2020 fos_myid_ip_key,
2021 fos_myid_hostname_key,
2022 fos_our_client,
2023 fos_our_txt,
2024 #ifdef USE_KEYRR
2025 fos_our_key,
2026 #endif /* USE_KEYRR */
2027 fos_his_client,
2028 fos_done
2029 };
2030
2031 #ifdef DEBUG
2032 static const char *const oppo_step_name[] = {
2033 "fos_start",
2034 "fos_myid_ip_txt",
2035 "fos_myid_hostname_txt",
2036 "fos_myid_ip_key",
2037 "fos_myid_hostname_key",
2038 "fos_our_client",
2039 "fos_our_txt",
2040 #ifdef USE_KEYRR
2041 "fos_our_key",
2042 #endif /* USE_KEYRR */
2043 "fos_his_client",
2044 "fos_done"
2045 };
2046 #endif /* DEBUG */
2047
2048 struct find_oppo_bundle {
2049 enum find_oppo_step step;
2050 err_t want;
2051 bool failure_ok; /* if true, continue_oppo should not die on DNS failure */
2052 ip_address our_client; /* not pointer! */
2053 ip_address peer_client;
2054 int transport_proto;
2055 bool held;
2056 policy_prio_t policy_prio;
2057 ipsec_spi_t failure_shunt; /* in host order! 0 for delete. */
2058 int whackfd;
2059 };
2060
2061 struct find_oppo_continuation {
2062 struct adns_continuation ac; /* common prefix */
2063 struct find_oppo_bundle b;
2064 };
2065
2066 static void cannot_oppo(connection_t *c, struct find_oppo_bundle *b, err_t ugh)
2067 {
2068 char pcb[ADDRTOT_BUF];
2069 char ocb[ADDRTOT_BUF];
2070
2071 addrtot(&b->peer_client, 0, pcb, sizeof(pcb));
2072 addrtot(&b->our_client, 0, ocb, sizeof(ocb));
2073
2074 DBG(DBG_DNS | DBG_OPPO, DBG_log("Can't Opportunistically initiate for %s to %s: %s"
2075 , ocb, pcb, ugh));
2076
2077 whack_log(RC_OPPOFAILURE
2078 , "Can't Opportunistically initiate for %s to %s: %s"
2079 , ocb, pcb, ugh);
2080
2081 if (c && c->policy_next)
2082 {
2083 /* there is some policy that comes afterwards */
2084 struct spd_route *shunt_spd;
2085 connection_t *nc = c->policy_next;
2086 struct state *st;
2087
2088 passert(c->kind == CK_TEMPLATE);
2089 passert(c->policy_next->kind == CK_PERMANENT);
2090
2091 DBG(DBG_OPPO, DBG_log("OE failed for %s to %s, but %s overrides shunt"
2092 , ocb, pcb, c->policy_next->name));
2093
2094 /*
2095 * okay, here we need add to the "next" policy, which is ought
2096 * to be an instance.
2097 * We will add another entry to the spd_route list for the specific
2098 * situation that we have.
2099 */
2100
2101 shunt_spd = clone_thing(nc->spd);
2102
2103 shunt_spd->next = nc->spd.next;
2104 nc->spd.next = shunt_spd;
2105
2106 happy(addrtosubnet(&b->peer_client, &shunt_spd->that.client));
2107
2108 if (sameaddr(&b->peer_client, &shunt_spd->that.host_addr))
2109 shunt_spd->that.has_client = FALSE;
2110
2111 /*
2112 * override the tunnel destination with the one from the secondaried
2113 * policy
2114 */
2115 shunt_spd->that.host_addr = nc->spd.that.host_addr;
2116
2117 /* now, lookup the state, and poke it up.
2118 */
2119
2120 st = state_with_serialno(nc->newest_ipsec_sa);
2121
2122 /* XXX what to do if the IPSEC SA has died? */
2123 passert(st != NULL);
2124
2125 /* link the new connection instance to the state's list of
2126 * connections
2127 */
2128
2129 DBG(DBG_OPPO, DBG_log("installing state: %ld for %s to %s"
2130 , nc->newest_ipsec_sa
2131 , ocb, pcb));
2132
2133 #ifdef DEBUG
2134 if (DBGP(DBG_OPPO | DBG_CONTROLMORE))
2135 {
2136 char state_buf[LOG_WIDTH];
2137 char state_buf2[LOG_WIDTH];
2138 time_t n = now();
2139
2140 fmt_state(FALSE, st, n
2141 , state_buf, sizeof(state_buf)
2142 , state_buf2, sizeof(state_buf2));
2143 DBG_log("cannot_oppo, failure SA1: %s", state_buf);
2144 DBG_log("cannot_oppo, failure SA2: %s", state_buf2);
2145 }
2146 #endif /* DEBUG */
2147
2148 if (!route_and_eroute(c, shunt_spd, st))
2149 {
2150 whack_log(RC_OPPOFAILURE
2151 , "failed to instantiate shunt policy %s for %s to %s"
2152 , c->name
2153 , ocb, pcb);
2154 }
2155 return;
2156 }
2157 }
2158
2159 static void initiate_opportunistic_body(struct find_oppo_bundle *b
2160 , struct adns_continuation *ac, err_t ac_ugh); /* forward */
2161
2162 void initiate_opportunistic(const ip_address *our_client,
2163 const ip_address *peer_client, int transport_proto,
2164 bool held, int whackfd)
2165 {
2166 struct find_oppo_bundle b;
2167
2168 b.want = (whackfd == NULL_FD ? "whack" : "acquire");
2169 b.failure_ok = FALSE;
2170 b.our_client = *our_client;
2171 b.peer_client = *peer_client;
2172 b.transport_proto = transport_proto;
2173 b.held = held;
2174 b.policy_prio = BOTTOM_PRIO;
2175 b.failure_shunt = 0;
2176 b.whackfd = whackfd;
2177 b.step = fos_start;
2178 initiate_opportunistic_body(&b, NULL, NULL);
2179 }
2180
2181 static void continue_oppo(struct adns_continuation *acr, err_t ugh)
2182 {
2183 struct find_oppo_continuation *cr = (void *)acr; /* inherit, damn you! */
2184 connection_t *c;
2185 bool was_held = cr->b.held;
2186 int whackfd = cr->b.whackfd;
2187
2188 /* note: cr->id has no resources; cr->sgw_id is ID_ANY:
2189 * neither need freeing.
2190 */
2191 whack_log_fd = whackfd;
2192
2193 #ifdef DEBUG
2194 /* if we're going to ignore the error, at least note it in debugging log */
2195 if (cr->b.failure_ok && ugh)
2196 {
2197 DBG(DBG_CONTROL | DBG_DNS,
2198 {
2199 char ocb[ADDRTOT_BUF];
2200 char pcb[ADDRTOT_BUF];
2201
2202 addrtot(&cr->b.our_client, 0, ocb, sizeof(ocb));
2203 addrtot(&cr->b.peer_client, 0, pcb, sizeof(pcb));
2204 DBG_log("continuing from failed DNS lookup for %s, %s to %s: %s"
2205 , cr->b.want, ocb, pcb, ugh);
2206 });
2207 }
2208 #endif
2209
2210 if (!cr->b.failure_ok && ugh)
2211 {
2212 c = find_connection_for_clients(NULL, &cr->b.our_client, &cr->b.peer_client
2213 , cr->b.transport_proto);
2214 cannot_oppo(c, &cr->b
2215 , builddiag("%s: %s", cr->b.want, ugh));
2216 }
2217 else if (was_held && !cr->b.held)
2218 {
2219 /* was_held indicates we were started due to a %trap firing
2220 * (as opposed to a "whack --oppohere --oppothere").
2221 * Since the %hold has gone, we can assume that somebody else
2222 * has beaten us to the punch. We can go home. But lets log it.
2223 */
2224 char ocb[ADDRTOT_BUF];
2225 char pcb[ADDRTOT_BUF];
2226
2227 addrtot(&cr->b.our_client, 0, ocb, sizeof(ocb));
2228 addrtot(&cr->b.peer_client, 0, pcb, sizeof(pcb));
2229
2230 loglog(RC_COMMENT
2231 , "%%hold otherwise handled during DNS lookup for Opportunistic Initiation for %s to %s"
2232 , ocb, pcb);
2233 }
2234 else
2235 {
2236 initiate_opportunistic_body(&cr->b, &cr->ac, ugh);
2237 whackfd = NULL_FD; /* was handed off */
2238 }
2239
2240 whack_log_fd = NULL_FD;
2241 close_any(whackfd);
2242 }
2243
2244 #ifdef USE_KEYRR
2245 static err_t check_key_recs(enum myid_state try_state, const connection_t *c,
2246 struct adns_continuation *ac)
2247 {
2248 /* Check if KEY lookup yielded good results.
2249 * Looking up based on our ID. Used if
2250 * client is ourself, or if TXT had no public key.
2251 * Note: if c is different this time, there is
2252 * a chance that we did the wrong query.
2253 * If so, treat as a kind of failure.
2254 */
2255 enum myid_state old_myid_state = myid_state;
2256 private_key_t *private;
2257 err_t ugh = NULL;
2258
2259 myid_state = try_state;
2260
2261 if (old_myid_state != myid_state && old_myid_state == MYID_SPECIFIED)
2262 {
2263 ugh = "%myid was specified while we were guessing";
2264 }
2265 else if ((private = get_private_key(c)) == NULL)
2266 {
2267 ugh = "we don't know our own RSA key";
2268 }
2269 else if (!same_id(&ac->id, &c->spd.this.id))
2270 {
2271 ugh = "our ID changed underfoot";
2272 }
2273 else
2274 {
2275 /* Similar to code in RSA_check_signature
2276 * for checking the other side.
2277 */
2278 pubkey_list_t *kr;
2279
2280 ugh = "no KEY RR found for us";
2281 for (kr = ac->keys_from_dns; kr != NULL; kr = kr->next)
2282 {
2283 ugh = "all our KEY RRs have the wrong public key";
2284 if (kr->key->alg == PUBKEY_ALG_RSA
2285 && private->belongs_to(private, &kr->key->public_key))
2286 {
2287 ugh = NULL; /* good! */
2288 break;
2289 }
2290 }
2291 }
2292 if (ugh)
2293 {
2294 myid_state = old_myid_state;
2295 }
2296 return ugh;
2297 }
2298 #endif /* USE_KEYRR */
2299
2300 static err_t check_txt_recs(enum myid_state try_state, const connection_t *c,
2301 struct adns_continuation *ac)
2302 {
2303 /* Check if TXT lookup yielded good results.
2304 * Looking up based on our ID. Used if
2305 * client is ourself, or if TXT had no public key.
2306 * Note: if c is different this time, there is
2307 * a chance that we did the wrong query.
2308 * If so, treat as a kind of failure.
2309 */
2310 enum myid_state old_myid_state = myid_state;
2311 private_key_t *private;
2312 err_t ugh = NULL;
2313
2314 myid_state = try_state;
2315
2316 if (old_myid_state != myid_state
2317 && old_myid_state == MYID_SPECIFIED)
2318 {
2319 ugh = "%myid was specified while we were guessing";
2320 }
2321 else if ((private = get_private_key(c)) == NULL)
2322 {
2323 ugh = "we don't know our own RSA key";
2324 }
2325 else if (!ac->id->equals(ac->id, c->spd.this.id))
2326 {
2327 ugh = "our ID changed underfoot";
2328 }
2329 else
2330 {
2331 /* Similar to code in RSA_check_signature
2332 * for checking the other side.
2333 */
2334 struct gw_info *gwp;
2335
2336 ugh = "no TXT RR found for us";
2337 for (gwp = ac->gateways_from_dns; gwp != NULL; gwp = gwp->next)
2338 {
2339 public_key_t *pub_key = gwp->key->public_key;
2340
2341 ugh = "all our TXT RRs have the wrong public key";
2342 if (pub_key->get_type(pub_key) == KEY_RSA &&
2343 private->belongs_to(private, pub_key))
2344 {
2345 ugh = NULL; /* good! */
2346 break;
2347 }
2348 }
2349 }
2350 if (ugh)
2351 {
2352 myid_state = old_myid_state;
2353 }
2354 return ugh;
2355 }
2356
2357
2358 /* note: gateways_from_dns must be NULL iff this is the first call */
2359 static void initiate_opportunistic_body(struct find_oppo_bundle *b,
2360 struct adns_continuation *ac,
2361 err_t ac_ugh)
2362 {
2363 connection_t *c;
2364 struct spd_route *sr;
2365
2366 /* What connection shall we use?
2367 * First try for one that explicitly handles the clients.
2368 */
2369 DBG(DBG_CONTROL,
2370 {
2371 char ours[ADDRTOT_BUF];
2372 char his[ADDRTOT_BUF];
2373 int ourport;
2374 int hisport;
2375
2376 addrtot(&b->our_client, 0, ours, sizeof(ours));
2377 addrtot(&b->peer_client, 0, his, sizeof(his));
2378 ourport = ntohs(portof(&b->our_client));
2379 hisport = ntohs(portof(&b->peer_client));
2380 DBG_log("initiate on demand from %s:%d to %s:%d proto=%d state: %s because: %s"
2381 , ours, ourport, his, hisport, b->transport_proto
2382 , oppo_step_name[b->step], b->want);
2383 });
2384 if (isanyaddr(&b->our_client) || isanyaddr(&b->peer_client))
2385 {
2386 cannot_oppo(NULL, b, "impossible IP address");
2387 }
2388 else if ((c = find_connection_for_clients(&sr
2389 , &b->our_client
2390 , &b->peer_client
2391 , b->transport_proto)) == NULL)
2392 {
2393 /* No connection explicitly handles the clients and there
2394 * are no Opportunistic connections -- whine and give up.
2395 * The failure policy cannot be gotten from a connection; we pick %pass.
2396 */
2397 cannot_oppo(NULL, b, "no routed Opportunistic template covers this pair");
2398 }
2399 else if (c->kind != CK_TEMPLATE)
2400 {
2401 /* We've found a connection that can serve.
2402 * Do we have to initiate it?
2403 * Not if there is currently an IPSEC SA.
2404 * But if there is an IPSEC SA, then the kernel would not
2405 * have generated the acquire. So we assume that there isn't one.
2406 * This may be redundant if a non-opportunistic
2407 * negotiation is already being attempted.
2408 */
2409
2410 /* If we are to proceed asynchronously, b->whackfd will be NULL_FD. */
2411
2412 if(c->kind == CK_INSTANCE)
2413 {
2414 char cib[CONN_INST_BUF];
2415 /* there is already an instance being negotiated, no nothing */
2416 DBG(DBG_CONTROL, DBG_log("found existing instance \"%s\"%s, rekeying it"
2417 , c->name
2418 , (fmt_conn_instance(c, cib), cib)));
2419 /* XXX-mcr - return; */
2420 }
2421
2422 /* otherwise, there is some kind of static conn that can handle
2423 * this connection, so we initiate it */
2424
2425 if (b->held)
2426 {
2427 /* what should we do on failure? */
2428 (void) assign_hold(c, sr, b->transport_proto, &b->our_client, &b->peer_client);
2429 }
2430 ipsecdoi_initiate(b->whackfd, c, c->policy, 1, SOS_NOBODY);
2431 b->whackfd = NULL_FD; /* protect from close */
2432 }
2433 else
2434 {
2435 /* We are handling an opportunistic situation.
2436 * This involves several DNS lookup steps that require suspension.
2437 * Note: many facts might change while we're suspended.
2438 * Here be dragons.
2439 *
2440 * The first chunk of code handles the result of the previous
2441 * DNS query (if any). It also selects the kind of the next step.
2442 * The second chunk initiates the next DNS query (if any).
2443 */
2444 enum find_oppo_step next_step = fos_myid_ip_txt;
2445 err_t ugh = ac_ugh;
2446 char mycredentialstr[BUF_LEN];
2447 char cib[CONN_INST_BUF];
2448
2449 DBG(DBG_CONTROL, DBG_log("creating new instance from \"%s\"%s",
2450 c->name, (fmt_conn_instance(c, cib), cib)));
2451 snprintf(mycredentialstr, BUF_LEN, "%Y", sr->this.id);
2452
2453 /* handle any DNS answer; select next step */
2454 switch (b->step)
2455 {
2456 case fos_start:
2457 /* just starting out: select first query step */
2458 next_step = fos_myid_ip_txt;
2459 break;
2460
2461 case fos_myid_ip_txt: /* TXT for our default IP address as %myid */
2462 ugh = check_txt_recs(MYID_IP, c, ac);
2463 if (ugh)
2464 {
2465 /* cannot use our IP as OE identitiy for initiation */
2466 DBG(DBG_OPPO,
2467 DBG_log("can not use our IP (%Y:TXT) as identity: %s",
2468 myids[MYID_IP], ugh));
2469 if (!logged_myid_ip_txt_warning)
2470 {
2471 loglog(RC_LOG_SERIOUS,
2472 "can not use our IP (%Y:TXT) as identity: %s",
2473 myids[MYID_IP], ugh);
2474 logged_myid_ip_txt_warning = TRUE;
2475 }
2476
2477 next_step = fos_myid_hostname_txt;
2478 ugh = NULL; /* failure can be recovered from */
2479 }
2480 else
2481 {
2482 /* we can use our IP as OE identity for initiation */
2483 if (!logged_myid_ip_txt_warning)
2484 {
2485 loglog(RC_LOG_SERIOUS,
2486 "using our IP (%Y:TXT) as identity!",
2487 myids[MYID_IP]);
2488 logged_myid_ip_txt_warning = TRUE;
2489 }
2490
2491 next_step = fos_our_client;
2492 }
2493 break;
2494
2495 case fos_myid_hostname_txt: /* TXT for our hostname as %myid */
2496 ugh = check_txt_recs(MYID_HOSTNAME, c, ac);
2497 if (ugh)
2498 {
2499 /* cannot use our hostname as OE identitiy for initiation */
2500 DBG(DBG_OPPO,
2501 DBG_log("can not use our hostname (%Y:TXT) as identity: %s",
2502 myids[MYID_HOSTNAME], ugh));
2503 if (!logged_myid_fqdn_txt_warning)
2504 {
2505 loglog(RC_LOG_SERIOUS,
2506 "can not use our hostname (%Y:TXT) as identity: %s",
2507 myids[MYID_HOSTNAME], ugh);
2508 logged_myid_fqdn_txt_warning = TRUE;
2509 }
2510 #ifdef USE_KEYRR
2511 next_step = fos_myid_ip_key;
2512 ugh = NULL; /* failure can be recovered from */
2513 #endif
2514 }
2515 else
2516 {
2517 /* we can use our hostname as OE identity for initiation */
2518 if (!logged_myid_fqdn_txt_warning)
2519 {
2520 loglog(RC_LOG_SERIOUS,
2521 "using our hostname (%Y:TXT) as identity!",
2522 myids[MYID_HOSTNAME]);
2523 logged_myid_fqdn_txt_warning = TRUE;
2524 }
2525 next_step = fos_our_client;
2526 }
2527 break;
2528
2529 #ifdef USE_KEYRR
2530 case fos_myid_ip_key: /* KEY for our default IP address as %myid */
2531 ugh = check_key_recs(MYID_IP, c, ac);
2532 if (ugh)
2533 {
2534 /* cannot use our IP as OE identitiy for initiation */
2535 DBG(DBG_OPPO,
2536 DBG_log("can not use our IP (%Y:KEY) as identity: %s",
2537 myids[MYID_IP], ugh));
2538 if (!logged_myid_ip_key_warning)
2539 {
2540 loglog(RC_LOG_SERIOUS,
2541 "can not use our IP (%Y:KEY) as identity: %s",
2542 myids[MYID_IP], ugh);
2543 logged_myid_ip_key_warning = TRUE;
2544 }
2545
2546 next_step = fos_myid_hostname_key;
2547 ugh = NULL; /* failure can be recovered from */
2548 }
2549 else
2550 {
2551 /* we can use our IP as OE identity for initiation */
2552 if (!logged_myid_ip_key_warning)
2553 {
2554 loglog(RC_LOG_SERIOUS,
2555 "using our IP (%Y:KEY) as identity!",
2556 myids[MYID_IP]);
2557 logged_myid_ip_key_warning = TRUE;
2558 }
2559 next_step = fos_our_client;
2560 }
2561 break;
2562
2563 case fos_myid_hostname_key: /* KEY for our hostname as %myid */
2564 ugh = check_key_recs(MYID_HOSTNAME, c, ac);
2565 if (ugh)
2566 {
2567 /* cannot use our IP as OE identitiy for initiation */
2568 DBG(DBG_OPPO,
2569 DBG_log("can not use our hostname (%Y:KEY) as identity: %s",
2570 myids[MYID_HOSTNAME], ugh));
2571 if (!logged_myid_fqdn_key_warning)
2572 {
2573 loglog(RC_LOG_SERIOUS,
2574 "can not use our hostname (%Y:KEY) as identity: %s",
2575 myids[MYID_HOSTNAME], ugh);
2576 logged_myid_fqdn_key_warning = TRUE;
2577 }
2578 next_step = fos_myid_hostname_key;
2579 ugh = NULL; /* failure can be recovered from */
2580 }
2581 else
2582 {
2583 /* we can use our IP as OE identity for initiation */
2584 if (!logged_myid_fqdn_key_warning)
2585 {
2586 loglog(RC_LOG_SERIOUS,
2587 "using our hostname (%Y:KEY) as identity!",
2588 myids[MYID_HOSTNAME]);
2589 logged_myid_fqdn_key_warning = TRUE;
2590 }
2591 next_step = fos_our_client;
2592 }
2593 break;
2594 #endif
2595
2596 case fos_our_client: /* TXT for our client */
2597 {
2598 /* Our client is not us: we must check the TXT records.
2599 * Note: if c is different this time, there is
2600 * a chance that we did the wrong query.
2601 * If so, treat as a kind of failure.
2602 */
2603 private_key_t *private = get_private_key(c);
2604
2605 next_step = fos_his_client; /* normal situation */
2606
2607 if (private == NULL)
2608 {
2609 ugh = "we don't know our own RSA key";
2610 }
2611 else if (sameaddr(&sr->this.host_addr, &b->our_client))
2612 {
2613 /* this wasn't true when we started -- bail */
2614 ugh = "our IP address changed underfoot";
2615 }
2616 else if (!ac->sgw_id->equals(ac->sgw_id, sr->this.id))
2617 {
2618 /* this wasn't true when we started -- bail */
2619 ugh = "our ID changed underfoot";
2620 }
2621 else
2622 {
2623 /* Similar to code in quick_inI1_outR1_tail
2624 * for checking the other side.
2625 */
2626 struct gw_info *gwp;
2627
2628 ugh = "no TXT RR for our client delegates us";
2629 for (gwp = ac->gateways_from_dns; gwp != NULL; gwp = gwp->next)
2630 {
2631 ugh = "TXT RR for our client has wrong key";
2632 /* If there is a key from the TXT record,
2633 * we count it as a win if we match the key.
2634 * If there was no key, we have a tentative win:
2635 * we need to check our KEY record to be sure.
2636 */
2637 if (!gwp->gw_key_present)
2638 {
2639 /* Success, but the TXT had no key
2640 * so we must check our our own KEY records.
2641 */
2642 next_step = fos_our_txt;
2643 ugh = NULL; /* good! */
2644 break;
2645 }
2646 if (private->belongs_to(private, gwp->key->public_key))
2647 {
2648 ugh = NULL; /* good! */
2649 break;
2650 }
2651 }
2652 }
2653 }
2654 break;
2655
2656 case fos_our_txt: /* TXT for us */
2657 {
2658 /* Check if TXT lookup yielded good results.
2659 * Looking up based on our ID. Used if
2660 * client is ourself, or if TXT had no public key.
2661 * Note: if c is different this time, there is
2662 * a chance that we did the wrong query.
2663 * If so, treat as a kind of failure.
2664 */
2665 private_key_t *private = get_private_key(c);
2666
2667 next_step = fos_his_client; /* unless we decide to look for KEY RR */
2668
2669 if (private == NULL)
2670 {
2671 ugh = "we don't know our own RSA key";
2672 }
2673 else if (!ac->id->equals(ac->id, c->spd.this.id))
2674 {
2675 ugh = "our ID changed underfoot";
2676 }
2677 else
2678 {
2679 /* Similar to code in RSA_check_signature
2680 * for checking the other side.
2681 */
2682 struct gw_info *gwp;
2683
2684 ugh = "no TXT RR for us";
2685 for (gwp = ac->gateways_from_dns; gwp != NULL; gwp = gwp->next)
2686 {
2687 ugh = "TXT RR for us has wrong key";
2688 if (gwp->gw_key_present &&
2689 private->belongs_to(private, gwp->key->public_key))
2690 {
2691 DBG(DBG_CONTROL,
2692 DBG_log("initiate on demand found TXT with right public key at: %s"
2693 , mycredentialstr));
2694 ugh = NULL;
2695 break;
2696 }
2697 }
2698 #ifdef USE_KEYRR
2699 if (ugh)
2700 {
2701 /* if no TXT with right key, try KEY */
2702 DBG(DBG_CONTROL,
2703 DBG_log("will try for KEY RR since initiate on demand found %s: %s"
2704 , ugh, mycredentialstr));
2705 next_step = fos_our_key;
2706 ugh = NULL;
2707 }
2708 #endif
2709 }
2710 }
2711 break;
2712
2713 #ifdef USE_KEYRR
2714 case fos_our_key: /* KEY for us */
2715 {
2716 /* Check if KEY lookup yielded good results.
2717 * Looking up based on our ID. Used if
2718 * client is ourself, or if TXT had no public key.
2719 * Note: if c is different this time, there is
2720 * a chance that we did the wrong query.
2721 * If so, treat as a kind of failure.
2722 */
2723 private_key_t *private = get_private_key(c);
2724
2725 next_step = fos_his_client; /* always */
2726
2727 if (private == NULL)
2728 {
2729 ugh = "we don't know our own RSA key";
2730 }
2731 else if (!same_id(&ac->id, &c->spd.this.id))
2732 {
2733 ugh = "our ID changed underfoot";
2734 }
2735 else
2736 {
2737 /* Similar to code in RSA_check_signature
2738 * for checking the other side.
2739 */
2740 pubkey_list_t *kr;
2741
2742 ugh = "no KEY RR found for us (and no good TXT RR)";
2743 for (kr = ac->keys_from_dns; kr != NULL; kr = kr->next)
2744 {
2745 ugh = "all our KEY RRs have the wrong public key (and no good TXT RR)";
2746 if (kr->key->alg == PUBKEY_ALG_RSA
2747 && private->belongs_to(private, kr->key->public_key))
2748 {
2749 /* do this only once a day */
2750 if (!logged_txt_warning)
2751 {
2752 loglog(RC_LOG_SERIOUS
2753 , "found KEY RR but not TXT RR for %s. See http://www.freeswan.org/err/txt-change.html."
2754 , mycredentialstr);
2755 logged_txt_warning = TRUE;
2756 }
2757 ugh = NULL; /* good! */
2758 break;
2759 }
2760 }
2761 }
2762 }
2763 break;
2764 #endif /* USE_KEYRR */
2765
2766 case fos_his_client: /* TXT for his client */
2767 {
2768 /* We've finished last DNS queries: TXT for his client.
2769 * Using the information, try to instantiate a connection
2770 * and start negotiating.
2771 * We now know the peer. The chosing of "c" ignored this,
2772 * so we will disregard its current value.
2773 * !!! We need to randomize the entry in gw that we choose.
2774 */
2775 next_step = fos_done; /* no more queries */
2776
2777 c = build_outgoing_opportunistic_connection(ac->gateways_from_dns
2778 , &b->our_client
2779 , &b->peer_client);
2780
2781 if (c == NULL)
2782 {
2783 /* We cannot seem to instantiate a suitable connection:
2784 * complain clearly.
2785 */
2786 char ocb[ADDRTOT_BUF], pcb[ADDRTOT_BUF];
2787
2788 addrtot(&b->our_client, 0, ocb, sizeof(ocb));
2789 addrtot(&b->peer_client, 0, pcb, sizeof(pcb));
2790 loglog(RC_OPPOFAILURE,
2791 "no suitable connection for opportunism "
2792 "between %s and %s with %Y as peer",
2793 ocb, pcb, ac->gateways_from_dns->gw_id);
2794 }
2795 else
2796 {
2797 /* If we are to proceed asynchronously, b->whackfd will be NULL_FD. */
2798 passert(c->kind == CK_INSTANCE);
2799 passert(c->gw_info != NULL);
2800 passert(HAS_IPSEC_POLICY(c->policy));
2801 passert(LHAS(LELEM(RT_UNROUTED) | LELEM(RT_ROUTED_PROSPECTIVE), c->spd.routing));
2802 if (b->held)
2803 {
2804 /* what should we do on failure? */
2805 (void) assign_hold(c, &c->spd
2806 , b->transport_proto
2807 , &b->our_client, &b->peer_client);
2808 }
2809 c->gw_info->key->last_tried_time = now();
2810 ipsecdoi_initiate(b->whackfd, c, c->policy, 1, SOS_NOBODY);
2811 b->whackfd = NULL_FD; /* protect from close */
2812 }
2813 }
2814 break;
2815
2816 default:
2817 bad_case(b->step);
2818 }
2819
2820 /* the second chunk: initiate the next DNS query (if any) */
2821 DBG(DBG_CONTROL,
2822 {
2823 char ours[ADDRTOT_BUF];
2824 char his[ADDRTOT_BUF];
2825
2826 addrtot(&b->our_client, 0, ours, sizeof(ours));
2827 addrtot(&b->peer_client, 0, his, sizeof(his));
2828 DBG_log("initiate on demand from %s to %s new state: %s with ugh: %s"
2829 , ours, his, oppo_step_name[b->step], ugh ? ugh : "ok");
2830 });
2831
2832 if (ugh)
2833 {
2834 b->policy_prio = c->prio;
2835 b->failure_shunt = shunt_policy_spi(c, FALSE);
2836 cannot_oppo(c, b, ugh);
2837 }
2838 else if (next_step == fos_done)
2839 {
2840 /* nothing to do */
2841 }
2842 else
2843 {
2844 /* set up the next query */
2845 struct find_oppo_continuation *cr = malloc_thing(struct find_oppo_continuation);
2846 identification_t *id;
2847
2848 b->policy_prio = c->prio;
2849 b->failure_shunt = shunt_policy_spi(c, FALSE);
2850 cr->b = *b; /* copy; start hand off of whackfd */
2851 cr->b.failure_ok = FALSE;
2852 cr->b.step = next_step;
2853
2854 for (sr = &c->spd
2855 ; sr!=NULL && !sameaddr(&sr->this.host_addr, &b->our_client)
2856 ; sr = sr->next)
2857 ;
2858
2859 if (sr == NULL)
2860 sr = &c->spd;
2861
2862 /* If a %hold shunt has replaced the eroute for this template,
2863 * record this fact.
2864 */
2865 if (b->held
2866 && sr->routing == RT_ROUTED_PROSPECTIVE && eclipsable(sr))
2867 {
2868 sr->routing = RT_ROUTED_ECLIPSED;
2869 eclipse_count++;
2870 }
2871
2872 /* Switch to issue next query.
2873 * A case may turn out to be unnecessary. If so, it falls
2874 * through to the next case.
2875 * Figuring out what %myid can stand for must be done before
2876 * our client credentials are looked up: we must know what
2877 * the client credentials may use to identify us.
2878 * On the other hand, our own credentials should be looked
2879 * up after our clients in case our credentials are not
2880 * needed at all.
2881 * XXX this is a wasted effort if we don't have credentials
2882 * BUT they are not needed.
2883 */
2884 switch (next_step)
2885 {
2886 case fos_myid_ip_txt:
2887 if (c->spd.this.id->get_type(c->spd.this.id) == ID_MYID
2888 && myid_state != MYID_SPECIFIED)
2889 {
2890 cr->b.failure_ok = TRUE;
2891 cr->b.want = b->want = "TXT record for IP address as %myid";
2892 ugh = start_adns_query(myids[MYID_IP], myids[MYID_IP],
2893 T_TXT, continue_oppo, &cr->ac);
2894 break;
2895 }
2896 cr->b.step = fos_myid_hostname_txt;
2897 /* fall through */
2898
2899 case fos_myid_hostname_txt:
2900 if (c->spd.this.id->get_type(c->spd.this.id) == ID_MYID
2901 && myid_state != MYID_SPECIFIED)
2902 {
2903 #ifdef USE_KEYRR
2904 cr->b.failure_ok = TRUE;
2905 #else
2906 cr->b.failure_ok = FALSE;
2907 #endif
2908 cr->b.want = b->want = "TXT record for hostname as %myid";
2909 ugh = start_adns_query(myids[MYID_HOSTNAME],
2910 myids[MYID_HOSTNAME],
2911 T_TXT, continue_oppo, &cr->ac);
2912 break;
2913 }
2914
2915 #ifdef USE_KEYRR
2916 cr->b.step = fos_myid_ip_key;
2917 /* fall through */
2918
2919 case fos_myid_ip_key:
2920 if (c->spd.this.id.kind == ID_MYID
2921 && myid_state != MYID_SPECIFIED)
2922 {
2923 cr->b.failure_ok = TRUE;
2924 cr->b.want = b->want = "KEY record for IP address as %myid (no good TXT)";
2925 ugh = start_adns_query(myids[MYID_IP], NULL, /* security gateway meaningless */
2926 T_KEY, continue_oppo, &cr->ac);
2927 break;
2928 }
2929 cr->b.step = fos_myid_hostname_key;
2930 /* fall through */
2931
2932 case fos_myid_hostname_key:
2933 if (c->spd.this.id.kind == ID_MYID
2934 && myid_state != MYID_SPECIFIED)
2935 {
2936 cr->b.failure_ok = FALSE; /* last attempt! */
2937 cr->b.want = b->want = "KEY record for hostname as %myid (no good TXT)";
2938 ugh = start_adns_query(myids[MYID_HOSTNAME], NULL, /* security gateway meaningless */
2939 T_KEY, continue_oppo, &cr->ac);
2940 break;
2941 }
2942 #endif
2943 cr->b.step = fos_our_client;
2944 /* fall through */
2945
2946 case fos_our_client: /* TXT for our client */
2947 if (!sameaddr(&c->spd.this.host_addr, &b->our_client))
2948 {
2949 /* Check that at least one TXT(reverse(b->our_client)) is workable.
2950 * Note: {unshare|free}_id_content not needed for id: ephemeral.
2951 */
2952 cr->b.want = b->want = "our client's TXT record";
2953 id = identification_create_from_sockaddr((sockaddr_t*)&b->our_client);
2954 ugh = start_adns_query(id, c->spd.this.id, /* we are the security gateway */
2955 T_TXT, continue_oppo, &cr->ac);
2956 id->destroy(id);
2957 break;
2958 }
2959 cr->b.step = fos_our_txt;
2960 /* fall through */
2961
2962 case fos_our_txt: /* TXT for us */
2963 cr->b.failure_ok = b->failure_ok = TRUE;
2964 cr->b.want = b->want = "our TXT record";
2965 ugh = start_adns_query(sr->this.id, sr->this.id, /* we are the security gateway */
2966 T_TXT, continue_oppo, &cr->ac);
2967 break;
2968
2969 #ifdef USE_KEYRR
2970 case fos_our_key: /* KEY for us */
2971 cr->b.want = b->want = "our KEY record";
2972 cr->b.failure_ok = b->failure_ok = FALSE;
2973 ugh = start_adns_query(sr->this.id, NULL, /* security gateway meaningless */
2974 T_KEY, continue_oppo, &cr->ac);
2975 break;
2976 #endif /* USE_KEYRR */
2977
2978 case fos_his_client: /* TXT for his client */
2979 /* note: {unshare|free}_id_content not needed for id: ephemeral */
2980 cr->b.want = b->want = "target's TXT record";
2981 cr->b.failure_ok = b->failure_ok = FALSE;
2982 id = identification_create_from_sockaddr((sockaddr_t*)&b->peer_client);
2983 ugh = start_adns_query(id, NULL, /* security gateway unconstrained */
2984 T_TXT, continue_oppo, &cr->ac);
2985 id->destroy(id);
2986 break;
2987
2988 default:
2989 bad_case(next_step);
2990 }
2991
2992 if (ugh == NULL)
2993 b->whackfd = NULL_FD; /* complete hand-off */
2994 else
2995 cannot_oppo(c, b, ugh);
2996 }
2997 }
2998 close_any(b->whackfd);
2999 }
3000
3001 void terminate_connection(const char *nm)
3002 {
3003 /* Loop because more than one may match (master and instances)
3004 * But at least one is required (enforced by con_by_name).
3005 */
3006 connection_t *c = con_by_name(nm, TRUE);
3007
3008 if (c == NULL || !c->ikev1)
3009 return;
3010
3011 do
3012 {
3013 connection_t *n = c->ac_next; /* grab this before c might disappear */
3014
3015 if (streq(c->name, nm)
3016 && c->kind >= CK_PERMANENT
3017 && !NEVER_NEGOTIATE(c->policy))
3018 {
3019 set_cur_connection(c);
3020 plog("terminating SAs using this connection");
3021 c->policy &= ~POLICY_UP;
3022 flush_pending_by_connection(c);
3023 delete_states_by_connection(c, FALSE);
3024 if (c->kind == CK_INSTANCE)
3025 delete_connection(c, FALSE);
3026 reset_cur_connection();
3027 }
3028 c = n;
3029 } while (c);
3030 }
3031
3032 /* an ISAKMP SA has been established.
3033 * Note the serial number, and release any connections with
3034 * the same peer ID but different peer IP address.
3035 */
3036 bool uniqueIDs = FALSE; /* --uniqueids? */
3037
3038 void ISAKMP_SA_established(connection_t *c, so_serial_t serial)
3039 {
3040 c->newest_isakmp_sa = serial;
3041
3042 /* the connection is now oriented so that we are able to determine
3043 * whether we are a mode config server with a virtual IP to send.
3044 */
3045 if (!c->spd.that.host_srcip->is_anyaddr(c->spd.that.host_srcip) &&
3046 !c->spd.that.has_natip)
3047 {
3048 c->spd.that.modecfg = TRUE;
3049 }
3050
3051 if (uniqueIDs)
3052 {
3053 /* for all connections: if the same Phase 1 IDs are used
3054 * for a different IP address, unorient that connection.
3055 */
3056 connection_t *d;
3057
3058 for (d = connections; d != NULL; )
3059 {
3060 connection_t *next = d->ac_next; /* might move underneath us */
3061
3062 if (d->kind >= CK_PERMANENT &&
3063 c->spd.this.id->equals(c->spd.this.id, d->spd.this.id) &&
3064 c->spd.that.id->equals(c->spd.that.id, d->spd.that.id) &&
3065 !sameaddr(&c->spd.that.host_addr, &d->spd.that.host_addr))
3066 {
3067 release_connection(d, FALSE);
3068 }
3069 d = next;
3070 }
3071 }
3072 }
3073
3074 /* Find the connection to connection c's peer's client with the
3075 * largest value of .routing. All other things being equal,
3076 * preference is given to c. If none is routed, return NULL.
3077 *
3078 * If erop is non-null, set *erop to a connection sharing both
3079 * our client subnet and peer's client subnet with the largest value
3080 * of .routing. If none is erouted, set *erop to NULL.
3081 *
3082 * The return value is used to find other connections sharing a route.
3083 * *erop is used to find other connections sharing an eroute.
3084 */
3085 connection_t *route_owner(connection_t *c, struct spd_route **srp,
3086 connection_t **erop, struct spd_route **esrp)
3087 {
3088 connection_t *d
3089 , *best_ro = c
3090 , *best_ero = c;
3091 struct spd_route *srd, *src;
3092 struct spd_route *best_sr, *best_esr;
3093 enum routing_t best_routing, best_erouting;
3094
3095 passert(oriented(*c));
3096 best_sr = NULL;
3097 best_esr = NULL;
3098 best_routing = c->spd.routing;
3099 best_erouting = best_routing;
3100
3101 for (d = connections; d != NULL; d = d->ac_next)
3102 {
3103 for (srd = &d->spd; srd; srd = srd->next)
3104 {
3105 if (srd->routing == RT_UNROUTED)
3106 continue;