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