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