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