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