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