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