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