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