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