1 /* information about connections between hosts and clients
2 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
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>.
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
14 * RCSID $Id: connections.c,v 1.124 2002/03/23 20:15:31 dhr Exp $
22 #include <netinet/in.h>
23 #include <sys/socket.h>
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
28 #include <arpa/nameser.h> /* missing from <resolv.h> on old systems */
32 #include "constants.h"
36 #include "connections.h" /* needs id.h */
38 #include "demux.h" /* needs packet.h */
41 #include "ipsec_doi.h" /* needs demux.h and state.h */
45 #include "preshared.h"
46 #include "adns.h" /* needs <resolv.h> */
47 #include "dnskey.h" /* needs preshared.h and adns.h */
51 #include "kernel_alg.h"
54 #include "nat_traversal.h"
61 static void flush_pending_by_connection(struct connection *c); /* forward */
63 static struct connection *connections = NULL;
65 /* struct host_pair: a nexus of information about a pair of hosts.
66 * A host is an IP address, UDP port pair. This is a debatable choice:
67 * - should port be considered (no choice of port in standard)?
68 * - should ID be considered (hard because not always known)?
69 * - should IP address matter on our end (we don't know our end)?
70 * Only oriented connections are registered.
71 * Unoriented connections are kept on the unoriented_connections
72 * linked list (using hp_next). For them, host_pair is NULL.
78 u_int16_t port; /* host order */
80 bool initial_connection_sent;
81 struct connection *connections; /* connections with this pair */
82 struct pending *pending; /* awaiting Keying Channel */
83 struct host_pair *next;
86 static struct host_pair *host_pairs = NULL;
88 static struct connection *unoriented_connections = NULL;
90 static int oppo_templates = 0; /* count of opportunistic templates */
92 /* check to see that Ids of peers match */
94 same_peer_ids(const struct connection *c, const struct connection *d
95 , const struct id *his_id)
97 return same_id(&c->this.id, &d->this.id)
98 && same_id(his_id == NULL? &c->that.id : his_id, &d->that.id);
101 /* update the host pairs with the latest DNS ip address */
102 /* XXX: I don't like this, it assumes everything in a host pair
103 * has the same dnshostname, which isn't a valid assumption,
104 * even though it will nearly always be true. */
106 update_host_pairs(void)
109 struct connection *c;
112 for (p = host_pairs; p != NULL; p = p->next)
116 || c->dnshostname == NULL
117 || ttoaddr(c->dnshostname, 0, c->addr_family, &new_addr) != NULL
118 || sameaddr(&new_addr, &p->him.addr))
121 for (; c != NULL; c = c->hp_next)
123 c->that.host_addr = new_addr;
127 p->him.addr = new_addr;
133 find_host_connection_mode(const ip_address *myaddr, u_int16_t myport
134 , const ip_address *hisaddr, u_int16_t hisport, bool main)
136 struct host_pair *p, *prev;
137 struct connection *c;
139 /* update the host pairs with the latest DNS ip address */
142 /* default hisaddr to an appropriate any */
144 hisaddr = aftoinfo(addrtypeof(myaddr))->any;
146 for (prev = NULL, p = host_pairs; p != NULL; prev = p, p = p->next)
148 if (sameaddr(&p->me.addr, myaddr) && p->me.port == myport
149 && sameaddr(&p->him.addr, hisaddr)
150 #ifdef DO_NOT_ACCEPT_IKE_FROM_DIFFERENT_SOURCE_PORT
151 && (p->him.port == hisport)
155 for (c = p->connections; c != NULL; c = c->hp_next)
157 if(c->kind != CK_TEMPLATE && c->kind != CK_PERMANENT)
161 if(!LALLIN(c->policy, POLICY_AGGRESSIVE))
165 prev->next = p->next; /* remove p from list */
166 p->next = host_pairs; /* and stick it on front */
172 if (LALLIN(c->policy, POLICY_AGGRESSIVE)) {
175 prev->next = p->next; /* remove p from list */
176 p->next = host_pairs; /* and stick it on front */
191 static struct host_pair *
192 find_host_pair(const ip_address *myaddr, u_int16_t myport
193 , const ip_address *hisaddr, u_int16_t hisport)
195 struct host_pair *p, *prev;
197 /* default hisaddr to an appropriate any */
199 hisaddr = aftoinfo(addrtypeof(myaddr))->any;
202 if (nat_traversal_enabled) {
204 * port is not relevant in host_pair. with nat_traversal we
205 * always use pluto_port (500)
208 hisport = pluto_port;
212 for (prev = NULL, p = host_pairs; p != NULL; prev = p, p = p->next)
214 if (sameaddr(&p->me.addr, myaddr) && p->me.port == myport
215 && sameaddr(&p->him.addr, hisaddr) && p->him.port == hisport)
219 prev->next = p->next; /* remove p from list */
220 p->next = host_pairs; /* and stick it on front */
229 /* find head of list of connections with this pair of hosts */
230 static struct connection *
231 find_host_pair_connections(const ip_address *myaddr, u_int16_t myport
232 , const ip_address *hisaddr, u_int16_t hisport)
234 struct host_pair *hp = find_host_pair(myaddr, myport, hisaddr, hisport);
237 if (nat_traversal_enabled && hp && hisaddr) {
238 struct connection *c;
239 for (c = hp->connections; c != NULL; c = c->hp_next) {
240 if ((c->this.host_port==myport) && (c->that.host_port==hisport))
247 return hp == NULL? NULL : hp->connections;
251 connect_to_host_pair(struct connection *c)
255 struct host_pair *hp = find_host_pair(&c->this.host_addr, c->this.host_port
256 , &c->that.host_addr, c->that.host_port);
260 /* no suitable host_pair -- build one */
261 hp = alloc_thing(struct host_pair, "host_pair");
262 hp->me.addr = c->this.host_addr;
263 hp->him.addr = c->that.host_addr;
265 hp->me.port = nat_traversal_enabled ? pluto_port : c->this.host_port;
266 hp->him.port = nat_traversal_enabled ? pluto_port : c->that.host_port;
268 hp->me.port = c->this.host_port;
269 hp->him.port = c->that.host_port;
271 hp->initial_connection_sent = FALSE;
272 hp->connections = NULL;
274 hp->next = host_pairs;
278 c->hp_next = hp->connections;
283 /* since this connection isn't oriented, we place it
284 * in the unoriented_connections list instead.
287 c->hp_next = unoriented_connections;
288 unoriented_connections = c;
292 /* find a connection by name.
293 * If strict, don't accept a CK_INSTANCE.
294 * Move the winner (if any) to the front.
295 * If none is found, and strict, a diagnostic is logged to whack.
298 con_by_name(const char *nm, bool strict)
300 struct connection *p, *prev;
302 for (prev = NULL, p = connections; ; prev = p, p = p->ac_next)
307 whack_log(RC_UNKNOWN_NAME
308 , "no connection named \"%s\"", nm);
311 if (streq(p->name, nm)
312 && (!strict || p->kind != CK_INSTANCE))
316 prev->ac_next = p->ac_next; /* remove p from list */
317 p->ac_next = connections; /* and stick it on front */
327 release_connection(struct connection *c)
329 if (c->kind == CK_INSTANCE)
331 /* This does everything we need.
332 * Note that we will be called recursively by delete_connection,
333 * but kind will be CK_GOING_AWAY.
335 delete_connection(c);
339 flush_pending_by_connection(c);
340 delete_states_by_connection(c);
341 unroute_connection(c);
345 /* Delete a connection */
347 #define list_rm(etype, enext, e, ehead) { \
349 for (ep = &(ehead); *ep != (e); ep = &(*ep)->enext) \
350 passert(*ep != NULL); /* we must not come up empty-handed */ \
356 delete_connection(struct connection *c)
358 struct connection *old_cur_connection
359 = cur_connection == c? NULL : cur_connection;
361 unsigned int old_cur_debugging = cur_debugging;
364 set_cur_connection(c);
366 /* Must be careful to avoid circularity:
367 * we mark c as going away so it won't get deleted recursively.
369 passert(c->kind != CK_GOING_AWAY);
370 if (c->kind == CK_INSTANCE)
372 log("deleting connection \"%s\" instance with peer %s"
373 , c->name, ip_str(&c->that.host_addr));
374 c->kind = CK_GOING_AWAY;
378 log("deleting connection");
380 release_connection(c); /* won't delete c */
382 /* find and delete c from connections list */
383 list_rm(struct connection, ac_next, c, connections);
384 cur_connection = old_cur_connection;
386 /* find and delete c from the host pair list */
387 if (c->host_pair == NULL)
389 list_rm(struct connection, hp_next, c, unoriented_connections);
393 struct host_pair *hp = c->host_pair;
395 list_rm(struct connection, hp_next, c, hp->connections);
396 c->host_pair = NULL; /* redundant, but safe */
398 /* if there are no more connections with this host_pair
399 * and we haven't even made an initial contact, let's delete
400 * this guy in case we were created by an attempted DOS attack.
402 if (hp->connections == NULL
403 && !hp->initial_connection_sent)
405 passert(hp->pending == NULL); /* ??? must deal with this! */
406 list_rm(struct host_pair, next, hp, host_pairs);
412 if (c->kind != CK_GOING_AWAY) pfreeany(c->that.virt);
415 if (c->kind == CK_TEMPLATE && (c->policy & POLICY_OPPO))
419 cur_debugging = old_cur_debugging;
422 pfreeany(c->dnshostname);
423 free_id_content(&c->this.id);
424 pfreeany(c->this.updown);
425 release_x509cert(c->this.cert);
426 free_id_content(&c->that.id);
427 release_x509cert(c->that.cert);
428 pfreeany(c->that.updown);
429 gw_delref(&c->gw_info);
430 #ifndef NO_KERNEL_ALG
431 alg_info_delref((struct alg_info **)&c->alg_info_esp);
434 alg_info_delref((struct alg_info **)&c->alg_info_ike);
440 delete_every_connection(void)
442 while (connections != NULL)
443 delete_connection(connections);
447 release_dead_interfaces(void)
449 struct host_pair *hp;
451 for (hp = host_pairs; hp != NULL; hp = hp->next)
453 struct connection **pp
456 for (pp = &hp->connections; (p = *pp) != NULL; )
458 if (p->interface->change == IFN_DELETE)
460 /* this connection's interface is going away */
461 enum connection_kind k = p->kind;
463 release_connection(p);
465 if (k == CK_PERMANENT || k == CK_TEMPLATE)
467 /* The connection should have survived release:
468 * move it to the unoriented_connections list.
474 *pp = p->hp_next; /* advance *pp */
476 p->hp_next = unoriented_connections;
477 unoriented_connections = p;
481 /* The connection should have vanished,
482 * but the previous connection remains.
489 pp = &p->hp_next; /* advance pp */
495 /* adjust orientations of connections to reflect newly added interfaces */
497 check_orientations(void)
499 /* try to orient all the unoriented connections */
501 struct connection *c = unoriented_connections;
503 unoriented_connections = NULL;
507 struct connection *nxt = c->hp_next;
510 connect_to_host_pair(c);
515 /* Check that no oriented connection has become double-oriented.
516 * In other words, the far side must not match one of our new interfaces.
521 for (i = interfaces; i != NULL; i = i->next)
523 if (i->change == IFN_ADD)
525 struct host_pair *hp;
527 for (hp = host_pairs; hp != NULL; hp = hp->next)
529 if (sameaddr(&hp->him.addr, &i->addr)
530 && (!no_klips || hp->him.port == pluto_port))
532 /* bad news: the whole chain of connections
533 * hanging off this host pair has both sides
534 * matching an interface.
535 * We'll get rid of them, using orient and
536 * connect_to_host_pair. But we'll be lazy
537 * and not ditch the host_pair itself (the
538 * cost of leaving it is slight and cannot
539 * be induced by a foe).
541 struct connection *c = hp->connections;
543 hp->connections = NULL;
546 struct connection *nxt = c->hp_next;
550 connect_to_host_pair(c);
561 default_end(struct end *e, ip_address *dflt_nexthop)
564 const struct af_info *afi = aftoinfo(addrtypeof(&e->host_addr));
567 return "unknown address family in default_end";
569 /* default ID to IP (but only if not NO_IP -- WildCard) */
570 if (e->id.kind == ID_NONE && !isanyaddr(&e->host_addr))
572 e->id.kind = afi->id_addr;
573 e->id.ip_addr = e->host_addr;
576 /* default nexthop to other side */
577 if (isanyaddr(&e->host_nexthop))
578 e->host_nexthop = *dflt_nexthop;
580 /* default client to subnet containing only self
581 * XXX This may mean that the client's address family doesn't match
582 * tunnel_addr_family.
585 ugh = initsubnet(&e->host_addr, afi->mask_cnt, '0', &e->client);
590 /* format the topology of an end, leaving out defaults
591 * Note: if that==NULL, skip nexthop
594 format_end(char *buf, size_t buf_len
595 , const struct end *this, const struct end *that, bool is_left)
597 char client[SUBNETTOT_BUF];
598 const char *client_sep = "";
599 char protoport[sizeof(":255/65535")];
600 char host[ADDRTOT_BUF];
601 char host_port[sizeof(":65535")];
602 char host_id[IDTOA_BUF + 2];
603 char hop[ADDRTOT_BUF];
604 const char *hop_sep = "";
605 const char *open_brackets = "";
606 const char *close_brackets = "";
612 if (is_virtual_end(this) && isanyaddr(&this->host_addr)) {
613 snprintf(host, sizeof(host), "%%virtual");
617 if (isanyaddr(&this->host_addr)
619 && subnetishost(&this->client)
620 && (networkof(&this->client, &net), isanyaddr(&net)))
622 /* %opportunistic subsumes client and host */
623 snprintf(host, sizeof(host), "%%opportunistic");
628 if (this->has_client)
630 subnettot(&this->client, 0, client, sizeof(client));
634 /* {client_subnet_wildcard} */
635 if (this->has_client_wildcard)
638 close_brackets = "}";
642 if (isanyaddr(&this->host_addr))
643 snprintf(host, sizeof(host), "%%any");
645 addrtot(&this->host_addr, 0, host, sizeof(host));
648 if (this->host_port != IKE_UDP_PORT)
649 snprintf(host_port, sizeof(host_port), ":%u"
652 /* payload portocol and port */
654 if (this->port || this->protocol)
655 snprintf(protoport, sizeof(protoport), ":%u/%u",
656 this->protocol, this->port);
658 /* id, if different from host */
660 if (!(this->id.kind == ID_NONE
661 || (id_is_ipaddr(&this->id) && sameaddr(&this->id.ip_addr, &this->host_addr))))
663 int len = idtoa(&this->id, host_id+1, sizeof(host_id)-2);
666 strcpy(&host_id[len < 0? (ptrdiff_t)sizeof(host_id)-2 : 1 + len], "]");
672 if (that != NULL && !sameaddr(&this->host_nexthop, &that->host_addr))
674 addrtot(&this->host_nexthop, 0, hop, sizeof(hop));
679 snprintf(buf, buf_len, "%s%s%s%s%s%s%s%s%s%s"
680 , open_brackets, client, close_brackets
681 , client_sep, host, host_port, host_id
682 , protoport, hop_sep, hop);
684 snprintf(buf, buf_len, "%s%s%s%s%s%s%s%s%s%s"
685 , hop, hop_sep, host, host_port, host_id
686 , protoport, client_sep
687 , open_brackets, client, close_brackets);
692 unshare_connection_strings(struct connection *c)
694 c->name = clone_str(c->name, "connection name");
695 c->dnshostname = clone_str(c->dnshostname, "connection dnshostname");
697 unshare_id_content(&c->this.id);
698 c->this.updown = clone_str(c->this.updown, "updown");
699 share_x509cert(c->this.cert);
700 unshare_id_content(&c->that.id);
701 c->that.updown = clone_str(c->that.updown, "updown");
702 share_x509cert(c->that.cert);
706 extract_end(struct end *dst, const struct whack_end *src, const char *which)
708 /* decode id, if any */
711 dst->id.kind = ID_NONE;
715 err_t ugh = atoid(src->id, &dst->id);
719 loglog(RC_BADID, "bad %s --id: %s (ignored)", which, ugh);
720 dst->id = empty_id; /* ignore bad one */
726 /* load local X.509 certificate, if any */
727 if (src->cert != NULL)
729 x509cert_t *cert = load_host_cert(src->cert);
733 bool copy_subject_dn = TRUE; /* ID is subject DN */
735 if (dst->id.kind != ID_NONE) /* check for matching subjectAltName */
737 generalName_t *gn = cert->subjectAltName;
741 struct id id = empty_id;
744 if (same_id(&id, &dst->id))
746 copy_subject_dn = FALSE; /* take subjectAltName instead */
754 if (dst->id.kind != ID_NONE && dst->id.kind != ID_DER_ASN1_DN)
758 idtoa(&dst->id, buf, IDTOA_BUF);
759 log(" no subjectAltName matches ID '%s', replaced by subject DN", buf);
761 dst->id.kind = ID_DER_ASN1_DN;
762 dst->id.name.len = cert->subject.len;
763 dst->id.name.ptr = temporary_cyclic_buffer();
764 memcpy(dst->id.name.ptr, cert->subject.ptr, cert->subject.len);
766 if (check_validity(cert))
768 add_x509_public_key(cert, DAL_LOCAL);
769 dst->cert = add_x509cert(cert);
775 log(" current time: %s", timetoa(¤t_time, TRUE));
776 log(" host certificate is invalid");
782 /* the rest is simple copying of corresponding fields */
783 dst->host_addr = src->host_addr;
784 dst->host_nexthop = src->host_nexthop;
785 dst->client = src->client;
786 dst->port = src->port;
787 dst->protocol = src->protocol;
789 dst->has_client = src->has_client;
790 dst->has_client_wildcard = src->has_client_wildcard;
791 dst->updown = src->updown;
792 dst->host_port = src->host_port;
796 check_connection_end(const struct whack_end *this, const struct whack_end *that
797 , const struct whack_message *wm)
799 if (wm->addr_family != addrtypeof(&this->host_addr)
800 || wm->addr_family != addrtypeof(&this->host_nexthop)
801 || (this->has_client? wm->tunnel_addr_family : wm->addr_family)
802 != subnettypeof(&this->client)
803 || subnettypeof(&this->client) != subnettypeof(&that->client))
805 /* this should have been diagnosed by whack, so we need not be clear
806 * !!! overloaded use of RC_CLASH
808 loglog(RC_CLASH, "address family inconsistency in connection");
812 if (isanyaddr(&that->host_addr))
814 /* other side is wildcard: we must check if other conditions met */
815 if (isanyaddr(&this->host_addr))
817 loglog(RC_ORIENT, "connection must specify host IP address for our side");
820 else if ((wm->policy & POLICY_AGGRESSIVE) == 0)
822 /* check that all main mode RW IKE policies agree because we must
823 * implement them before the correct connection is known.
824 * We cannot enforce this for other non-RW connections because
825 * differentiation is possible when a command specifies which
827 * aggressive mode IKE policies do not have to agree amongst
828 * themselves as the ID is known from the outset.
830 const struct connection *c = NULL;
832 c = find_host_pair_connections(&this->host_addr
833 , this->host_port, (const ip_address *)NULL, that->host_port);
835 for (; c != NULL; c = c->hp_next)
837 if (c->policy & POLICY_AGGRESSIVE)
839 if ((c->policy ^ wm->policy) & (POLICY_PSK | POLICY_RSASIG))
842 , "authentication method disagrees with \"%s\", which is also for an unspecified peer"
850 if ((this->virt) && (!isanyaddr(&this->host_addr) || this->has_client)) {
852 "virtual IP must only be used with %%any and without client");
856 return TRUE; /* happy */
860 add_connection(const struct whack_message *wm)
862 if (con_by_name(wm->name, FALSE) != NULL)
864 loglog(RC_DUPNAME, "attempt to redefine connection \"%s\"", wm->name);
866 else if ((wm->policy & POLICY_ID_AUTH_MASK) == LEMPTY)
868 /* this should have been diagnosed by whack, so we need not be clear
869 * !!! overloaded use of RC_CLASH
871 loglog(RC_CLASH, "must specify --rsasig or --psk for a connection");
873 else if (wm->right.protocol != wm->left.protocol)
875 /* this should haven been diagnosed by whack
876 * !!! overloaded use of RC_CLASH
878 loglog(RC_CLASH, "the protocol must be the same for leftport and rightport");
880 else if (check_connection_end(&wm->right, &wm->left, wm)
881 && check_connection_end(&wm->left, &wm->right, wm))
883 struct connection *c = alloc_thing(struct connection, "struct connection");
886 c->dnshostname = wm->dnshostname;
888 c->policy = wm->policy;
890 if ((c->policy & POLICY_COMPRESS) && !can_do_IPcomp)
892 , "ignoring --compress in \"%s\" because KLIPS is not configured to do IPCOMP"
895 #ifndef NO_KERNEL_ALG
899 DBG_log("from whack: got --esp=%s", wm->esp ? wm->esp: "NULL");
900 c->alg_info_esp= alg_info_esp_create_from_str(wm->esp? wm->esp : "", &ugh);
901 DBG(DBG_CRYPT|DBG_CONTROL,
902 static char buf[256]="<NULL>";
904 alg_info_snprint(buf, sizeof(buf),
905 (struct alg_info *)c->alg_info_esp);
906 DBG_log("esp string values: %s", buf);
908 if (c->alg_info_esp) {
909 if (c->alg_info_esp->alg_info_cnt==0) {
910 loglog(RC_LOG_SERIOUS
911 , "got 0 transforms for esp=\"%s\""
915 loglog(RC_LOG_SERIOUS
916 , "esp string error: %s"
917 , ugh? ugh : "Unknown");
925 DBG_log("from whack: got --ike=%s", wm->ike ? wm->ike: "NULL");
926 c->alg_info_ike= alg_info_ike_create_from_str(wm->ike? wm->ike : "", &ugh);
927 DBG(DBG_CRYPT|DBG_CONTROL,
928 static char buf[256]="<NULL>";
930 alg_info_snprint(buf, sizeof(buf),
931 (struct alg_info *)c->alg_info_ike);
932 DBG_log("ike string values: %s", buf);
934 if (c->alg_info_ike) {
935 if (c->alg_info_ike->alg_info_cnt==0) {
936 loglog(RC_LOG_SERIOUS
937 , "got 0 transforms for ike=\"%s\""
941 loglog(RC_LOG_SERIOUS
942 , "ike string error: %s"
943 , ugh? ugh : "Unknown");
947 c->sa_ike_life_seconds = wm->sa_ike_life_seconds;
948 c->sa_ipsec_life_seconds = wm->sa_ipsec_life_seconds;
949 c->sa_rekey_margin = wm->sa_rekey_margin;
950 c->sa_rekey_fuzz = wm->sa_rekey_fuzz;
951 c->sa_keying_tries = wm->sa_keying_tries;
952 c->retransmit_trigger = wm->retransmit_trigger;
953 c->dpd_delay = wm->dpd_delay;
954 c->dpd_timeout = wm->dpd_timeout;
955 c->algorithm_p1.cipher = wm->cipher_p1;
956 c->algorithm_p1.dhg = wm->dhg_p1;
957 c->algorithm_p1.hash = wm->hash_p1;
958 c->addr_family = wm->addr_family;
959 c->tunnel_addr_family = wm->tunnel_addr_family;
961 extract_end(&c->this, &wm->left, "left");
962 extract_end(&c->that, &wm->right, "right");
964 default_end(&c->this, &c->that.host_addr);
965 default_end(&c->that, &c->this.host_addr);
967 /* force any wildcard host IP address to that end */
968 if (isanyaddr(&c->this.host_addr) || c->this.has_client_wildcard)
970 struct end t = c->this;
972 DBG(DBG_CONTROL, DBG_log("add_connection - 1"));
977 /* set internal fields */
978 c->initiated = FALSE;
979 c->ac_next = connections;
982 c->routing = RT_UNROUTED;
983 c->newest_isakmp_sa = SOS_NOBODY;
984 c->newest_ipsec_sa = SOS_NOBODY;
985 c->eroute_owner = SOS_NOBODY;
987 c->kind = (isanyaddr(&c->that.host_addr) || c->that.has_client_wildcard) ?
988 CK_TEMPLATE : CK_PERMANENT;
991 c->extra_debugging = wm->debugging;
997 passert(!(wm->left.virt && wm->right.virt));
998 if (wm->left.virt || wm->right.virt) {
999 passert(isanyaddr(&c->that.host_addr));
1000 c->that.virt = create_virtual(c,
1001 wm->left.virt ? wm->left.virt : wm->right.virt);
1003 c->that.has_client = TRUE;
1007 unshare_connection_strings(c);
1008 #ifndef NO_KERNEL_ALG
1009 alg_info_addref((struct alg_info *)c->alg_info_esp);
1012 alg_info_addref((struct alg_info *)c->alg_info_ike);
1016 connect_to_host_pair(c);
1018 if (c->kind == CK_TEMPLATE && (c->policy & POLICY_OPPO))
1021 /* log all about this connection */
1022 log("added connection description \"%s\"", c->name);
1024 char lhs[SUBNETTOT_BUF + ADDRTOT_BUF + IDTOA_BUF + ADDRTOT_BUF];
1025 char rhs[SUBNETTOT_BUF + ADDRTOT_BUF + IDTOA_BUF + ADDRTOT_BUF];
1027 (void) format_end(lhs, sizeof(lhs), &c->this, &c->that, TRUE);
1028 (void) format_end(rhs, sizeof(rhs), &c->that, &c->this, FALSE);
1030 DBG_log("%s...%s", lhs, rhs);
1032 /* Make sure that address families can be correctly inferred
1033 * from printed ends.
1035 passert(c->addr_family == addrtypeof(&c->this.host_addr)
1036 && c->addr_family == addrtypeof(&c->this.host_nexthop)
1037 && (c->this.has_client? c->tunnel_addr_family : c->addr_family)
1038 == subnettypeof(&c->this.client)
1040 && c->addr_family == addrtypeof(&c->that.host_addr)
1041 && c->addr_family == addrtypeof(&c->that.host_nexthop)
1042 && (c->that.has_client? c->tunnel_addr_family : c->addr_family)
1043 == subnettypeof(&c->that.client));
1045 DBG_log("ike_life: %lus; ipsec_life: %lus; rekey_margin: %lus;"
1046 " rekey_fuzz: %lu%%; keyingtries: %lu; policy: %s"
1047 , (unsigned long) c->sa_ike_life_seconds
1048 , (unsigned long) c->sa_ipsec_life_seconds
1049 , (unsigned long) c->sa_rekey_margin
1050 , (unsigned long) c->sa_rekey_fuzz
1051 , (unsigned long) c->sa_keying_tries
1052 , bitnamesof(sa_policy_bit_names, c->policy));
1057 /* Common part of instantiating a Road Warrior or Opportunistic connection.
1058 * his_id can be used to carry over an ID discovered in Phase 1.
1059 * It must not disagree with the one in c, but if that is unspecified,
1060 * the new connection will use his_id.
1061 * If his_id is NULL, and c.that.id is uninstantiated (ID_NONE), the
1062 * new connection will continue to have an uninstantiated that.id.
1063 * Note: instantiation does not affect port numbers.
1065 static struct connection *
1066 instantiate(const struct connection *c, const ip_address *him
1067 #ifdef NAT_TRAVERSAL
1068 , u_int16_t his_port
1070 , const struct id *his_id)
1072 struct connection *d = clone_thing(*c, "temporary connection");
1074 passert(c->kind == CK_TEMPLATE);
1077 passert(d->that.id.kind == ID_NONE || same_id(&d->that.id, his_id));
1078 d->that.id = *his_id;
1080 unshare_connection_strings(d);
1081 #ifndef NO_KERNEL_ALG
1082 alg_info_addref((struct alg_info *)d->alg_info_esp);
1085 alg_info_addref((struct alg_info *)d->alg_info_ike);
1088 d->kind = CK_INSTANCE;
1090 passert(oriented(*d));
1091 d->that.host_addr = *him;
1092 #ifdef NAT_TRAVERSAL
1093 if (his_port) d->that.host_port = his_port;
1095 default_end(&d->that, &d->this.host_addr);
1097 /* We cannot guess what our next_hop should be, but if it was
1098 * explicitly specified as 0.0.0.0, we set it to be him.
1099 * (whack will not allow nexthop to be elided in RW case.)
1101 default_end(&d->this, &d->that.host_addr);
1103 /* set internal fields */
1104 d->ac_next = connections;
1106 d->routing = RT_UNROUTED;
1107 d->newest_isakmp_sa = SOS_NOBODY;
1108 d->newest_ipsec_sa = SOS_NOBODY;
1109 d->eroute_owner = SOS_NOBODY;
1111 connect_to_host_pair(d);
1117 rw_instantiate(const struct connection *c
1118 , const ip_address *him
1119 #ifdef NAT_TRAVERSAL
1120 , u_int16_t his_port
1123 , const ip_subnet *his_net
1125 , const struct id *his_id)
1127 #ifdef NAT_TRAVERSAL
1128 struct connection *d = instantiate(c, him, his_port, his_id);
1130 struct connection *d = instantiate(c, him, his_id);
1134 if (d && his_net && is_virtual_connection(c)) {
1135 d->that.client = *his_net;
1136 d->that.virt = NULL;
1137 if (subnetishost(his_net) && addrinsubnet(him, his_net))
1138 d->that.has_client = FALSE;
1143 , DBG_log("instantiated \"%s\" for %s" , d->name, ip_str(him)));
1148 oppo_instantiate(const struct connection *c
1149 , const ip_address *him
1150 , const struct id *his_id
1151 , struct gw_info *gw
1152 , const ip_address *our_client USED_BY_DEBUG
1153 , const ip_address *peer_client)
1155 #ifdef NAT_TRAVERSAL
1156 struct connection *d = instantiate(c, him, 0, his_id);
1158 struct connection *d = instantiate(c, him, his_id);
1161 /* fill in our client side */
1162 if (d->this.has_client)
1164 /* there was a client in the abstract connection
1165 * so we demand that the required client is within that subnet.
1167 passert(addrinsubnet(our_client, &d->this.client));
1168 happy(addrtosubnet(our_client, &d->this.client));
1172 /* there was no client in the abstract connection
1173 * so we demand that the required client be the host
1175 passert(sameaddr(our_client, &d->this.host_addr));
1178 /* fill in peer's client side.
1179 * If the client is the peer, excise the client from the connection.
1181 passert((d->policy & POLICY_OPPO) && HasWildcardClient(d));
1182 happy(addrtosubnet(peer_client, &d->that.client));
1184 if (sameaddr(peer_client, &d->that.host_addr))
1185 d->that.has_client = FALSE;
1187 passert(d->gw_info == NULL);
1192 char lhs[SUBNETTOT_BUF + ADDRTOT_BUF + IDTOA_BUF + ADDRTOT_BUF];
1193 char rhs[SUBNETTOT_BUF + ADDRTOT_BUF + IDTOA_BUF + ADDRTOT_BUF];
1195 (void) format_end(lhs, sizeof(lhs), &d->this, &d->that, TRUE);
1196 (void) format_end(rhs, sizeof(rhs), &d->that, &d->this, FALSE);
1198 DBG_log("instantiated \"%s\": %s...%s", d->name, lhs, rhs);
1203 /* Format any information needed to identify an instance of a connection.
1204 * Fills any needed information into buf which MUST be big enough.
1207 fmt_conn_instance(const struct connection *c, char buf[CONN_INST_BUF])
1210 if (c->kind == CK_INSTANCE)
1213 addrtot(&c->that.host_addr, 0, buf+1, ADDRTOT_BUF);
1214 #ifdef NAT_TRAVERSAL
1215 if (c->that.host_port != pluto_port) {
1216 size_t u = strlen(buf);
1218 sprintf(buf+u, ":%d", c->that.host_port);
1221 if (c->policy & POLICY_OPPO)
1223 size_t u = strlen(buf);
1226 subnettot(&c->that.client, 0, buf+u, SUBNETTOT_BUF);
1231 /* Find an existing connection for a trapped outbound packet.
1232 * This is attempted before we bother with gateway discovery.
1233 * + this connection is routed (i.e. approved for on-demand)
1234 * + this subnet contains our_client (or we are our_client)
1235 * + that subnet contains peer_client (or peer is peer_client)
1236 * + don't care about Phase 1 IDs (we don't know)
1237 * + require that the connection HAS_IPSEC_POLICY (duh: to serve clients)
1238 * Give preference to the first one that has an SA (either phase).
1239 * Otherwise, give preference to one with highest routing.
1241 static struct connection *
1242 find_connection_for_clients(const ip_address *our_client, const ip_address *peer_client)
1244 struct connection *c = connections
1247 passert(!isanyaddr(our_client) && !isanyaddr(peer_client));
1249 for (c = connections; c != NULL; c = c->ac_next)
1251 if (HAS_IPSEC_POLICY(c->policy)
1252 && routed(c->routing)
1253 && addrinsubnet(our_client, &c->this.client)
1254 && addrinsubnet(peer_client, &c->that.client))
1256 if ((best == NULL || best->routing <= c->routing))
1258 if (c->newest_isakmp_sa != SOS_NOBODY
1259 || c->newest_ipsec_sa != SOS_NOBODY)
1266 /* Find and instantiate a connection for an outgoing Opportunistic connection.
1267 * We've already discovered its gateway.
1268 * We look for a the connection such that:
1269 * + this is one of our interfaces
1270 * + this subnet contains our_client (or we are our_client)
1271 * (we will specialize the client). We prefer the smallest such subnet.
1272 * + is opportunistic
1273 * + that peer is NO_IP
1274 * + don't care about Phase 1 IDs (probably should be default)
1275 * We could look for a connection that already had the desired peer
1276 * (rather than NO_IP) specified, but it doesn't seem worth the
1280 build_outgoing_opportunistic_connection(struct gw_info *gw
1281 , const ip_address *our_client, const ip_address *peer_client)
1284 struct connection *best = NULL;
1286 passert(!isanyaddr(our_client) && !isanyaddr(peer_client));
1288 /* We don't know his ID yet, so gw id must be an ipaddr */
1289 passert(id_is_ipaddr(&gw->gw_id));
1291 /* for each of our addresses... */
1292 for (p = interfaces; p != NULL; p = p->next)
1294 /* go through those connections with our address and NO_IP as hosts
1295 * We cannot know what port the peer would use, so we assume
1296 * that it is pluto_port (makes debugging easier).
1298 struct connection *c = find_host_pair_connections(&p->addr
1299 , pluto_port, (ip_address *)NULL, pluto_port);
1301 for (; c != NULL; c = c->hp_next)
1302 if (c->kind == CK_TEMPLATE
1303 && addrinsubnet(our_client, &c->this.client)
1304 && (c->policy & POLICY_OPPO)
1305 && HAS_IPSEC_POLICY(c->policy)
1306 && (best == NULL || !subnetinsubnet(&best->this.client, &c->this.client)))
1309 return best == NULL? NULL
1310 : oppo_instantiate(best, &gw->gw_id.ip_addr, NULL, gw
1311 , our_client, peer_client);
1316 orient(struct connection *c)
1322 /* Note: this loop does not stop when it finds a match:
1323 * it continues checking to catch any ambiguity.
1325 for (p = interfaces; p != NULL; p = p->next)
1327 #ifdef NAT_TRAVERSAL
1328 if (p->ike_float) continue;
1332 /* check if this interface matches this end */
1333 if (sameaddr(&c->this.host_addr, &p->addr)
1334 && (!no_klips || c->this.host_port == pluto_port))
1338 if (c->interface == p)
1339 loglog(RC_LOG_SERIOUS
1340 , "both sides of \"%s\" are our interface %s!"
1341 , c->name, p->rname);
1343 loglog(RC_LOG_SERIOUS, "two interfaces match \"%s\" (%s, %s)"
1344 , c->name, c->interface->rname, p->rname);
1345 c->interface = NULL; /* withdraw orientation */
1351 /* done with this interface if it doesn't match that end */
1352 if (!(sameaddr(&c->that.host_addr, &p->addr)
1353 && (!no_klips || c->that.host_port == pluto_port)))
1356 /* swap ends and try again.
1357 * It is a little tricky to see that this loop will stop.
1358 * Only continue if the far side matches.
1359 * If both sides match, there is an error-out.
1362 struct end t = c->this;
1370 return oriented(*c);
1374 initiate_connection(const char *name, int whackfd)
1376 struct connection *c = con_by_name(name, TRUE);
1380 set_cur_connection(c);
1383 loglog(RC_ORIENT, "we have no ipsecN interface for either end of this connection");
1385 else if (c->kind != CK_PERMANENT)
1387 loglog(RC_NOPEERIP, "cannot initiate connection without knowing peer IP address");
1391 /* We will only request an IPsec SA if policy isn't empty
1392 * (ignoring Main Mode items).
1393 * This is a fudge, but not yet important.
1394 * If we are to proceed asynchronously, whackfd will be NULL_FD.
1396 c->initiated = TRUE;
1397 ipsecdoi_initiate(whackfd, c, c->policy, 1, SOS_NOBODY);
1398 whackfd = NULL_FD; /* protect from close */
1400 reset_cur_connection();
1405 void initiate_connections_by_peer(struct connection *c)
1407 struct connection *d;
1410 update_host_pairs();
1411 memcpy(&match, &c->that.host_addr, sizeof(ip_address));
1413 if (c->host_pair == NULL)
1415 d = c->host_pair->connections;
1416 for (; d != NULL; d = d->hp_next) {
1417 if (sameaddr(&d->that.host_addr, &match)) {
1418 initiate_connection(d->name, NULL_FD);
1423 /* opportunistic initiation is broken in two:
1424 * - everything up to Async DNS lookup (initiate_opportunistic)
1425 * - everyting after (until first IKE message sent) (continue_oppo)
1426 * Afterwards, regular state machinery carries negotiation forward.
1429 struct oppo_continuation {
1430 struct adns_continuation ac; /* common prefix */
1431 ip_address our_client; /* not pointer! */
1432 ip_address peer_client;
1438 cannot_oppo(const ip_address *our_client
1439 , const ip_address *peer_client, bool held USED_BY_KLIPS, err_t ugh)
1441 char pcb[ADDRTOT_BUF];
1442 char ocb[ADDRTOT_BUF];
1444 addrtot(peer_client, 0, pcb, sizeof(pcb));
1445 addrtot(our_client, 0, ocb, sizeof(ocb));
1447 loglog(RC_OPPOFAILURE
1448 , "Can't Opportunistically initiate for %s to %s: %s"
1454 /* Replace HOLD with PASS.
1455 * The type of replacement *ought* to be
1456 * specified by policy.
1458 (void) replace_bare_shunt(our_client, peer_client
1459 , SPI_PASS /* fail into PASS */
1460 , TRUE, "replace HOLD with PASS [no SG discovered]");
1464 static void continue_oppo(struct adns_continuation *acr, err_t ugh); /* forward */
1466 /* knowing clients (single IP addresses), try to build an SA */
1468 initiate_opportunistic(const ip_address *our_client
1469 , const ip_address *peer_client
1473 struct connection *c;
1475 /* What connection shall we use?
1476 * First try for one that explicitly handles the clients.
1478 DBG(DBG_CONTROL, DBG_log("not attempting to initiate opportunistic connection"));
1482 char ours[ADDRTOT_BUF];
1483 char his[ADDRTOT_BUF];
1485 addrtot(our_client, 0, ours, sizeof(ours));
1486 addrtot(peer_client, 0, his, sizeof(his));
1487 DBG_log("initiate on demand from %s to %s", ours, his);
1490 c = find_connection_for_clients(our_client, peer_client);
1493 /* We've found a connection that can serve.
1494 * Do we have to initiate it?
1495 * Not if there is currently an IPSEC SA.
1496 * But if there is an IPSEC SA, then KLIPS would not
1497 * have generated the acquire. So we assume that there isn't one.
1498 * This may be redundant if a non-opportunistic
1499 * negotiation is already being attempted.
1502 /* We will only request an IPsec SA if policy isn't empty
1503 * (ignoring Main Mode items).
1504 * This is a fudge, but not yet important.
1505 * If we are to proceed asynchronously, whackfd will be NULL_FD.
1508 passert(HAS_IPSEC_POLICY(c->policy));
1513 /* what should we do on failure? */
1514 (void) assign_hold(c, our_client, peer_client);
1517 ipsecdoi_initiate(whackfd, c, c->policy, 1, SOS_NOBODY);
1518 whackfd = NULL_FD; /* protect from close */
1520 else if (oppo_templates == 0)
1522 /* No connection explicitly handles the clients and there
1523 * are no Opportunistic connections -- whine and give up.
1525 cannot_oppo(our_client, peer_client, held, "no Opportunistic template");
1529 /* No connection explicitly handles the clients.
1530 * So we don't even know the peer:
1531 * try to discover peer via DNS query
1533 struct oppo_continuation *cr = alloc_thing(struct oppo_continuation
1534 , "opportunistic continuation");
1538 cr->our_client = *our_client;
1539 cr->peer_client = *peer_client;
1541 cr->whackfd = whackfd; /* hand-off */
1543 /* note: {unshare|free}_id_content not needed for id */
1544 iptoid(peer_client, &id);
1546 ugh = start_adns_query(&id
1547 , (const struct id *) NULL /* security gateway unconstrained */
1552 whackfd = NULL_FD; /* complete hand-off */
1554 cannot_oppo(our_client, peer_client, held, ugh);
1559 /* Continue opportunistic initiation now that DNS has answered.
1560 * List of gateways will be in gateways_from_dns -- we must manage the list.
1563 continue_oppo(struct adns_continuation *acr, err_t ugh)
1565 struct oppo_continuation *cr = (void *)acr; /* inherit! */
1566 const ip_address *our_client = &cr->our_client
1567 , *peer_client = &cr->peer_client;
1568 bool held = cr->held;
1569 int whackfd = cr->whackfd;
1571 /* note: cr->id has no resources; cr->sgw_id is id_none:
1572 * neither need freeing.
1574 whack_log_fd = whackfd;
1577 cannot_oppo(our_client, peer_client, held, ugh);
1581 /* !!! we need to randomize the entry in gw that we choose */
1582 struct connection *c = build_outgoing_opportunistic_connection(
1583 gateways_from_dns, our_client
1588 char ocb[ADDRTOT_BUF]
1592 addrtot(our_client, 0, ocb, sizeof(ocb));
1593 addrtot(peer_client, 0, pcb, sizeof(pcb));
1594 passert(id_is_ipaddr(&gateways_from_dns->gw_id));
1595 addrtot(&gateways_from_dns->gw_id.ip_addr, 0, pb, sizeof(pb));
1596 loglog(RC_OPPOFAILURE
1597 , "no suitable connection for opportunism"
1598 " between %s and %s with %s as peer"
1604 /* Replace HOLD with PASS.
1605 * The type of replacement *ought* to be
1606 * specified by policy.
1608 (void) replace_bare_shunt(our_client, peer_client
1609 , SPI_PASS /* fail into PASS */
1610 , TRUE, "replace HOLD with PASS [no suitable connection]");
1616 /* If we are to proceed asynchronously, whackfd will be NULL_FD. */
1617 passert(c->gw_info != NULL);
1618 passert(HAS_IPSEC_POLICY(c->policy));
1619 passert(c->routing == RT_UNROUTED);
1623 /* what should we do on failure? */
1624 (void) assign_hold(c, our_client, peer_client);
1627 c->gw_info->last_tried_time = now();
1628 ipsecdoi_initiate(whackfd, c, c->policy, 1, SOS_NOBODY);
1629 whackfd = NULL_FD; /* protect from close */
1632 gw_delref(&gateways_from_dns);
1633 whack_log_fd = NULL_FD;
1638 terminate_connection(const char *nm)
1640 /* Loop because more than one may match (master and instances)
1641 * But at least one is required (enforced by con_by_name).
1643 struct connection *c, *n;
1645 for (c = con_by_name(nm, TRUE); c != NULL; c = n)
1647 n = c->ac_next; /* grab this before c might disappear */
1648 if (streq(c->name, nm))
1650 set_cur_connection(c);
1651 log("terminating SAs using this connection");
1652 c->initiated = FALSE;
1653 delete_states_by_connection(c);
1654 reset_cur_connection();
1659 void terminate_connections_by_peer(struct connection *c)
1661 struct connection *d;
1663 d = c->host_pair->connections;
1665 for (; d != NULL; d = d->hp_next) {
1666 if (sameaddr(&d->that.host_addr, &c->that.host_addr)) {
1667 terminate_connection(d->name);
1672 /* check nexthop safety
1673 * Our nexthop must not be within a routed client subnet, and vice versa.
1674 * Note: we don't think this is true. We think that KLIPS will
1675 * not process a packet output by an eroute.
1679 //check_nexthop(const struct connection *c)
1681 // struct connection *d;
1683 // if (addrinsubnet(&c->this.host_nexthop, &c->that.client))
1685 // loglog(RC_LOG_SERIOUS, "cannot perform routing for connection \"%s\""
1686 // " because nexthop is within peer's client network",
1691 // for (d = connections; d != NULL; d = d->next)
1693 // if (d->routing != RT_UNROUTED)
1695 // if (addrinsubnet(&c->this.host_nexthop, &d->that.client))
1697 // loglog(RC_LOG_SERIOUS, "cannot do routing for connection \"%s\"
1698 // " because nexthop is contained in"
1699 // " existing routing for connection \"%s\"",
1700 // c->name, d->name);
1703 // if (addrinsubnet(&d->this.host_nexthop, &c->that.client))
1705 // loglog(RC_LOG_SERIOUS, "cannot do routing for connection \"%s\"
1706 // " because it contains nexthop of"
1707 // " existing routing for connection \"%s\"",
1708 // c->name, d->name);
1717 /* an ISAKMP SA has been established.
1718 * Note the serial number, and release any connections with
1719 * the same peer ID but different peer IP address.
1721 bool uniqueIDs = FALSE; /* --uniqueids? */
1724 ISAKMP_SA_established(struct connection *c, so_serial_t serial)
1726 c->newest_isakmp_sa = serial;
1730 /* for all connections: if the same Phase 1 peer ID is used
1731 * for a different IP address, unorient that connection.
1733 struct connection *d;
1735 for (d = connections; d != NULL; )
1737 struct connection *next = d->ac_next; /* might move underneath us */
1739 if (d->kind == CK_INSTANCE
1740 && same_id(&c->that.id, &d->that.id)
1741 && (c->newest_isakmp_sa > d->newest_isakmp_sa)) {
1744 st = state_with_serialno(d->newest_isakmp_sa);
1746 log("deleting state #%lu", st->st_serialno);
1750 #ifdef NAT_TRAVERSAL
1751 if (d->kind != CK_TEMPLATE
1752 && same_id(&c->that.id, &d->that.id)
1753 && (!sameaddr(&c->that.host_addr, &d->that.host_addr) ||
1754 (c->that.host_port != d->that.host_port)))
1756 if (d->kind != CK_TEMPLATE
1757 && same_id(&c->that.id, &d->that.id)
1758 && !sameaddr(&c->that.host_addr, &d->that.host_addr))
1761 release_connection(d);
1768 /* Find the connection to connection c's peer's client with the
1769 * largest value of .routing. All other things being equal,
1770 * preference is given to c. If none is routed, return NULL.
1772 * If erop is non-null, set *erop to a connection sharing both
1773 * our client subnet and peer's client subnet with the largest value
1774 * of .routing. If none is erouted, set *erop to NULL.
1776 * The return value is used to find other connections sharing a route.
1777 * *erop is used to find other connections sharing an eroute.
1780 route_owner(struct connection *c, struct connection **erop)
1782 struct connection *d
1785 const ip_subnet *cc = EffectivePeerClient(c);
1787 passert(oriented(*c));
1789 for (d = connections; d != NULL; d = d->ac_next)
1791 if (d->routing != RT_UNROUTED /* quick filter */
1792 && samesubnet(cc, EffectivePeerClient(d)))
1794 passert(oriented(*d));
1795 if (d->routing > bestro->routing)
1797 if (d->routing > bestero->routing
1798 && samesubnet(&c->this.client, &d->this.client))
1804 err_t m = builddiag("route owner of \"%s\" %s %s:"
1806 , enum_name(&connection_kind_names, c->kind)
1807 , enum_name(&routing_story, c->routing));
1809 if (!routed(bestro->routing))
1810 m = builddiag("%s NULL", m);
1811 else if (bestro == c)
1812 m = builddiag("%s self", m);
1814 m = builddiag("%s \"%s\" %s %s", m
1816 , enum_name(&connection_kind_names, bestro->kind)
1817 , enum_name(&routing_story, bestro->routing));
1821 m = builddiag("%s; eroute owner:", m);
1822 if (!erouted(bestero->routing))
1823 m = builddiag("%s NULL", m);
1824 else if (bestero == c)
1825 m = builddiag("%s self", m);
1827 m = builddiag("%s \"%s\" %s %s", m
1829 , enum_name(&connection_kind_names, bestero->kind)
1830 , enum_name(&routing_story, bestero->routing));
1836 *erop = erouted(bestero->routing)? bestero : NULL;
1837 return routed(bestro->routing)? bestro : NULL;
1840 /* Find a connection that owns the shunt eroute between subnets.
1841 * There ought to be only one.
1842 * This might get to be a bottleneck -- try hashing if it does.
1845 shunt_owner(const ip_subnet *ours, const ip_subnet *his)
1847 struct connection *c;
1849 for (c = connections; c != NULL; c = c->ac_next)
1851 if (shunt_erouted(c->routing)
1852 && samesubnet(ours, &c->this.client)
1853 && samesubnet(his, &c->that.client))
1859 /* Find some connection with this pair of hosts.
1860 * We don't know enough to chose amongst those available.
1861 * ??? no longer usefully different from find_host_pair_connections
1864 find_host_connection(const ip_address *me, u_int16_t my_port
1865 , const ip_address *him, u_int16_t his_port)
1867 return find_host_pair_connections(me, my_port, him, his_port);
1870 /* given an up-until-now satisfactory connection, find the best connection
1871 * now that we just got the Phase 1 Id Payload from the peer.
1873 * Comments in the code describe the (tricky!) matching criteria.
1874 * Although this routine could handle the initiator case,
1875 * it isn't currently called in this case.
1876 * This routine won't do anything interesting for Opportunistic Connections;
1877 * it's not clear that anything useful could be done.
1879 * In RFC 2409 "The Internet Key Exchange (IKE)",
1880 * in 5.1 "IKE Phase 1 Authenticated With Signatures", describing Main
1883 * Initiator Responder
1884 * ----------- -----------
1889 * HDR*, IDii, [ CERT, ] SIG_I -->
1890 * <-- HDR*, IDir, [ CERT, ] SIG_R
1892 * In 5.4 "Phase 1 Authenticated With a Pre-Shared Key":
1898 * HDR*, IDii, HASH_I -->
1899 * <-- HDR*, IDir, HASH_R
1901 * refine_host_connection could be called in two case:
1903 * - the Responder receives the IDii payload:
1904 * + [PSK] after using PSK to decode this message
1905 * + before sending its IDir payload
1906 * + before using its ID in HASH_R computation
1907 * + [DSig] before using its private key to sign SIG_R
1908 * + before using the Initiator's ID in HASH_I calculation
1909 * + [DSig] before using the Initiator's public key to check SIG_I
1911 * - the Initiator receives the IDir payload:
1912 * + [PSK] after using PSK to encode previous message and decode this message
1913 * + after sending its IDii payload
1914 * + after using its ID in HASH_I computation
1915 * + [DSig] after using its private key to sign SIG_I
1916 * + before using the Responder's ID to compute HASH_R
1917 * + [DSig] before using Responder's public key to check SIG_R
1919 * refine_host_connection can choose a different connection, as long as
1920 * nothing already used is changed.
1922 * In the Initiator case, the particular connection might have been
1923 * specified by whatever provoked Pluto to initiate. For example:
1924 * whack --initiate connection-name
1925 * The advantages of switching connections when we're the Initiator seem
1926 * less important than the disadvantages, so after FreeS/WAN 1.9, we
1930 refine_host_connection(const struct state *st, const struct id *peer_id
1931 , bool initiator, bool aggrmode)
1933 struct connection *c = st->st_connection;
1934 u_int16_t auth = st->st_oakley.auth;
1935 struct connection *d;
1936 const chunk_t *psk_check;
1938 lset_t p1mode_policy = aggrmode ? POLICY_AGGRESSIVE : LEMPTY;
1940 const struct RSA_private_key *my_RSA_pri = NULL;
1943 if (same_id(&c->that.id, peer_id))
1944 return c; /* peer ID matches current connection -- look no further */
1948 case OAKLEY_PRESHARED_KEY:
1949 DBG(DBG_CONTROL, DBG_log("refining connection with PSK"));
1950 auth_policy = POLICY_PSK;
1951 psk = get_preshared_secret(c);
1952 /* It should be virtually impossible to fail to find PSK:
1953 * we just used it to decode the current message!
1956 log("cannot determine PSK");
1957 return NULL; /* cannot determine PSK! */
1961 case OAKLEY_RSA_SIG:
1962 DBG(DBG_CONTROL, DBG_log("refining connection with RSA Sig"));
1963 auth_policy = POLICY_RSASIG;
1966 /* at this point, we've committed to our RSA private key:
1967 * we used it in our previous message.
1969 my_RSA_pri = get_RSA_private_key(c);
1970 if (my_RSA_pri == NULL)
1971 return NULL; /* cannot determine my RSA private key! */
1979 /* The current connection won't do: search for one that will.
1980 * First search for one with the same pair of hosts.
1981 * If that fails, search for one with a Road Warrior peer.
1983 * - peer_id (slightly complicated by instantiation)
1984 * - if PSK auth, the key must not change (we used it to decode message)
1985 * - policy-as-used must be acceptable to new connection
1986 * - if initiator, also:
1987 * + our ID must not change (we sent it in previous message)
1988 * + our RSA key must not change (we used in in previous message)
1990 d = c->host_pair->connections;
1991 DBG(DBG_CONTROL, DBG_log("trying to refine connection to an exact match"));
1992 for (rw = FALSE; ; rw = TRUE)
1994 struct connection *best_found = NULL;
1996 for (; d != NULL; d = d->hp_next)
1998 bool exact = same_id(peer_id, &d->that.id); /* exact peer ID match? */
2000 DBG(DBG_CONTROL, DBG_log("testing connection %s", d->name));
2001 #ifdef NAT_TRAVERSAL
2002 if ((c->that.host_port != d->that.host_port) &&
2003 (d->kind == CK_INSTANCE)) {
2004 DBG(DBG_CONTROL, DBG_log("instance port mismatch"));
2009 /* check if peer_id matches, exactly or after instantiation */
2010 if (!exact && !(rw && d->that.id.kind == ID_NONE)) {
2011 DBG(DBG_CONTROL, DBG_log("peer ID mismatch"));
2014 /* if initiator, our ID must match exactly */
2015 if (initiator && !same_id(&c->this.id, &d->this.id)) {
2016 DBG(DBG_CONTROL, DBG_log("our ID mismatch"));
2019 /* authentication used must fit policy of this connection */
2020 if ((d->policy & auth_policy) == LEMPTY) {
2021 DBG(DBG_CONTROL, DBG_log("auth mismatch"));
2022 continue; /* our auth isn't OK for this connection */
2024 if ((d->policy & POLICY_AGGRESSIVE) ^ p1mode_policy) {
2025 DBG(DBG_CONTROL, DBG_log("aggressive mode mismatch"));
2026 continue; /* disallow phase1 main/aggressive mode mismatch */
2030 case OAKLEY_PRESHARED_KEY:
2031 /* secret must match the one we already used */
2033 const chunk_t *dpsk = get_preshared_secret(d);
2035 DBG(DBG_CONTROL, DBG_log("testing PSK"));
2037 DBG(DBG_CONTROL, DBG_log("PSK not found"));
2038 continue; /* no secret */
2041 if (psk != dpsk && !aggrmode)
2042 if (psk->len != dpsk->len
2043 || memcmp(psk->ptr, dpsk->ptr, psk->len) != 0) {
2044 DBG(DBG_CONTROL, DBG_log("PSK mismatch"));
2045 continue; /* different secret */
2050 case OAKLEY_RSA_SIG:
2051 /* We must at least be able to find our private key.
2052 * If we initiated, it must match the one we
2053 * used in the SIG_I payload that we sent previously.
2056 const struct RSA_private_key *pri
2057 = get_RSA_private_key(d);
2059 DBG(DBG_CONTROL, DBG_log("testing RSA Sig"));
2062 && !same_RSA_public_key(&my_RSA_pri->pub, &pri->pub))) {
2063 DBG(DBG_CONTROL, DBG_log("RSA Sig mismatch"));
2074 DBG(DBG_CONTROL, DBG_log("connection %s matches exactly", d->name));
2075 return d; /* passed all the tests */
2077 DBG(DBG_CONTROL, DBG_log("changing best found to %s", d->name));
2078 best_found = d; /* passed tests, but peer_id was wildcarded */
2082 DBG(DBG_CONTROL, DBG_log("connection %s is best found", best_found->name));
2084 DBG(DBG_CONTROL, DBG_log("no connection"));
2086 return best_found; /* been around twice already */
2088 /* for second time around: figure out RW host pair's connections */
2089 d = find_host_pair_connections(&c->this.host_addr, c->this.host_port
2090 , (ip_address *)NULL, c->that.host_port);
2091 DBG(DBG_CONTROL, DBG_log("trying to refine connection to a wildcard match"));
2097 * With virtual addressing, we must not allow someone to use an already
2098 * used (by another id) addr/net.
2101 is_virtual_net_used(const ip_subnet *peer_net, const struct id *peer_id)
2103 struct connection *d;
2104 for (d = connections; d != NULL; d = d->ac_next)
2110 if ((subnetinsubnet(peer_net,&d->that.client) ||
2111 subnetinsubnet(&d->that.client,peer_net)) &&
2112 !same_id(&d->that.id, peer_id)) {
2113 char buf[IDTOA_BUF];
2114 char client[SUBNETTOT_BUF];
2115 subnettot(peer_net, 0, client, sizeof(client));
2116 idtoa(&d->that.id, buf, sizeof(buf));
2117 log("Virtual IP %s is already used by '%s'",
2119 idtoa(peer_id, buf, sizeof(buf));
2120 log("Your ID is '%s'", buf);
2121 return TRUE; /* already used by another one */
2129 return FALSE; /* you can safely use it */
2133 /* find_client_connection: given a connection suitable for ISAKMP
2134 * (i.e. the hosts match), find a one suitable for IPSEC
2135 * (i.e. with matching clients).
2137 * If we don't find an exact match (not even our current connection),
2138 * we try for one that still needs instantiation. Try Road Warrior
2139 * abstract connections and the Opportunistic abstract connections.
2140 * This requires inverse instantiation: abstraction.
2142 * After failing to find an exact match, we abstract the peer
2143 * to be NO_IP (the wildcard value). This enables matches with
2144 * Road Warrior and Opportunistic abstract connections.
2146 * After failing that search, we also abstract the Phase 1 peer ID
2147 * if possible. If the peer's ID was the peer's IP address, we make
2148 * it NO_ID; instantiation will make it the peer's IP address again.
2150 * If searching for a Road Warrior abstract connection fails,
2151 * and conditions are suitable, we search for an Opportunistic
2152 * abstract connection.
2154 * Note: in the end, both Phase 1 IDs must be preserved, after any
2155 * instantiation. They are the IDs that have been authenticated.
2158 /* fc_try: a helper function for find_client_connection */
2159 static struct connection *
2161 , const struct connection *c
2162 , struct host_pair *hp
2163 , const struct id *peer_id
2164 , const ip_subnet *our_net
2165 , const ip_subnet *peer_net
2166 , const u_int8_t our_protocol, const u_int16_t our_port
2167 , const u_int8_t peer_protocol, const u_int16_t peer_port)
2169 struct connection *d;
2170 struct connection *unrouted = NULL;
2171 const bool peer_net_is_host = subnetishost(peer_net)
2172 && addrinsubnet(&c->that.host_addr, peer_net);
2175 DBG_log("%s,%d: NULL pointer", __FILE__, __LINE__);
2179 for (d = hp->connections; d != NULL; d = d->hp_next)
2181 if (!same_peer_ids(c, d, peer_id))
2184 /* compare protocol and port, zero means 'any' and does always match */
2185 if ((d->this.protocol && d->this.protocol != our_protocol)
2186 || (d->this.port && d->this.port != our_port)
2187 || (d->that.protocol && d->that.protocol != peer_protocol)
2188 || (d->that.port && d->that.port != peer_port)
2189 || (our_protocol != peer_protocol))
2194 /* Opportunistic case:
2195 * our_net must be inside d->this.client
2196 * and d must have a Wildcard that.client.
2198 if (!subnetinsubnet(our_net, &d->this.client)
2199 || !HasWildcardClient(d))
2204 /* non-Opportunistic case:
2205 * our_client must match.
2207 * So must peer_client, but the testing is complicated
2208 * by the fact that the peer might be a wildcard
2209 * and if so, the default value of that.client
2210 * won't match the default peer_net. The appropriate test:
2212 * If d has a peer client, it must match peer_net.
2213 * If d has no peer client, peer_net must just have peer itself.
2215 if (!samesubnet(&d->this.client, our_net))
2218 if (d->that.has_client)
2220 if (d->that.has_client_wildcard) {
2221 if (!subnetinsubnet(peer_net, &d->that.client))
2225 if ((!samesubnet(&d->that.client, peer_net)) && (!is_virtual_connection(d)))
2227 if (!samesubnet(&d->that.client, peer_net))
2231 if ((is_virtual_connection(d)) &&
2232 ( (!is_virtual_net_allowed(d, peer_net, &c->that.host_addr)) ||
2233 (is_virtual_net_used(peer_net, peer_id?peer_id:&c->that.id)) ))
2240 if (!peer_net_is_host)
2245 /* we've run the gauntlet -- success */
2246 if (routed(d->routing))
2249 if (unrouted == NULL)
2256 find_client_connection(struct connection *c
2257 , const ip_subnet *our_net, const ip_subnet *peer_net
2258 , const u_int8_t our_protocol, const u_int16_t our_port
2259 , const u_int8_t peer_protocol, const u_int16_t peer_port)
2261 struct connection *d;
2263 /* give priority to current connection
2264 * but even greater priority to a routed concrete connection
2267 struct connection *unrouted = NULL;
2269 if (samesubnet(&c->this.client, our_net)
2270 && samesubnet(&c->that.client, peer_net)
2271 /* protocol and port must matcht, too */
2272 && (!c->this.protocol || c->this.protocol == our_protocol)
2273 && (!c->this.port || c->this.port == our_port)
2274 && (!c->that.protocol || c->that.protocol == peer_protocol)
2275 && (!c->that.port || c->that.port == peer_port)
2276 && (our_protocol == peer_protocol))
2278 passert(oriented(*c));
2279 if (routed(c->routing))
2286 d = fc_try(FALSE, c, c->host_pair, NULL, our_net, peer_net
2287 , our_protocol, our_port, peer_protocol, peer_port);
2294 /* look for an abstract connection to match */
2295 struct host_pair *const hp = find_host_pair(&c->this.host_addr
2296 , c->this.host_port, NULL, c->that.host_port);
2300 struct id abstract_peer_id;
2302 abstract_peer_id.kind = ID_NONE;
2304 /* RW match with actual peer_id? */
2305 d = fc_try(FALSE, c, hp, NULL, our_net, peer_net
2306 , our_protocol, our_port, peer_protocol, peer_port);
2308 if (d == NULL && his_id_was_instantiated(c))
2310 /* RW match with abstract peer_id?
2311 * Note that later instantiation will result in the same peer_id.
2313 d = fc_try(FALSE, c, hp, &abstract_peer_id, our_net, peer_net
2314 , our_protocol, our_port, peer_protocol, peer_port);
2318 && subnetishost(our_net)
2319 && subnetishost(peer_net))
2321 /* Opportunistic match?
2322 * Always use abstract peer_id.
2323 * Note that later instantiation will result in the same peer_id.
2325 d = fc_try(TRUE, c, hp, &abstract_peer_id, our_net, peer_net
2326 , our_protocol, our_port, peer_protocol, peer_port);
2335 show_connections_status(void)
2337 struct connection *c;
2339 for (c = connections; c != NULL; c = c->ac_next)
2341 const char *ifn = oriented(*c)? c->interface->rname : "";
2342 const char *instance = c->kind == CK_INSTANCE? " instance" : "";
2346 char lhs[SUBNETTOT_BUF + ADDRTOT_BUF + IDTOA_BUF + ADDRTOT_BUF];
2347 char rhs[SUBNETTOT_BUF + ADDRTOT_BUF + IDTOA_BUF + ADDRTOT_BUF];
2349 (void) format_end(lhs, sizeof(lhs), &c->this, &c->that, TRUE);
2350 (void) format_end(rhs, sizeof(rhs), &c->that, &c->this, FALSE);
2352 /* Display on one line.
2353 * We used to split the line if would be long, but that makes
2354 * output less consistent.
2356 whack_log(RC_COMMENT, "\"%s\"%s: %s...%s"
2357 , c->name, instance, lhs, rhs);
2360 whack_log(RC_COMMENT
2361 , "\"%s\"%s: ike_life: %lus; ipsec_life: %lus;"
2362 " rekey_margin: %lus; rekey_fuzz: %lu%%; keyingtries: %lu"
2365 , (unsigned long) c->sa_ike_life_seconds
2366 , (unsigned long) c->sa_ipsec_life_seconds
2367 , (unsigned long) c->sa_rekey_margin
2368 , (unsigned long) c->sa_rekey_fuzz
2369 , (unsigned long) c->sa_keying_tries);
2371 whack_log(RC_COMMENT
2372 , "\"%s\"%s: policy: %s; interface: %s; %s"
2375 , bitnamesof(sa_policy_bit_names, c->policy)
2377 , enum_name(&routing_story, c->routing));
2379 whack_log(RC_COMMENT
2380 , "\"%s\"%s: newest ISAKMP SA: #%ld; newest IPsec SA: #%ld; eroute owner: #%lu"
2383 , c->newest_isakmp_sa
2384 , c->newest_ipsec_sa
2387 ike_alg_show_connection(c, instance);
2389 #ifndef NO_KERNEL_ALG
2390 kernel_alg_show_connection(c, instance);
2395 /* Is c->that.client 0.0.0.0/32 (or IPV6 equivalent)?
2396 * This, along with c->that.host being 0.0.0.0 signifies Opportunism.
2399 HasWildcardClient(const struct connection *c)
2401 if (c->that.has_client && subnetishost(&c->that.client))
2405 networkof(&c->that.client, &addr);
2406 if (isanyaddr(&addr))
2412 /* peer client, but for wildcard, subrange containing all */
2414 EffectivePeerClient(const struct connection *c)
2416 return c->kind == CK_TEMPLATE && HasWildcardClient(c)
2417 ? aftoinfo(subnettypeof(&c->that.client))->all
2421 /* struct pending, the structure representing Quick Mode
2422 * negotiations delayed until a Keying Channel has been negotiated.
2423 * Essentially, a pending call to quick_outI1.
2428 struct state *isakmp_sa;
2429 struct connection *connection;
2432 so_serial_t replacing;
2434 struct pending *next;
2437 /* queue a Quick Mode negotiation pending completion of a suitable Main Mode */
2439 add_pending(int whack_sock
2440 , struct state *isakmp_sa
2441 , struct connection *c
2444 , so_serial_t replacing)
2446 struct pending *p = alloc_thing(struct pending, "struct pending");
2448 DBG(DBG_CONTROL, DBG_log("Queuing pending Quick Mode with %s \"%s\""
2449 , ip_str(&c->that.host_addr)
2451 p->whack_sock = whack_sock;
2452 p->isakmp_sa = isakmp_sa;
2456 p->replacing = replacing;
2457 p->next = c->host_pair->pending;
2458 c->host_pair->pending = p;
2461 /* Release all the whacks awaiting the completion of this state.
2462 * This is accomplished by closing all the whack socket file descriptors.
2463 * We go to a lot of trouble to tell each whack, but to not tell it twice.
2466 release_pending_whacks(struct state *st, err_t story)
2471 if (st->st_whack_sock == NULL_FD || fstat(st->st_whack_sock, &stst) != 0)
2472 zero(&stst); /* resulting st_dev/st_ino ought to be distinct */
2476 for (p = st->st_connection->host_pair->pending; p != NULL; p = p->next)
2478 if (p->isakmp_sa == st && p->whack_sock != NULL_FD)
2482 if (fstat(p->whack_sock, &pst) == 0
2483 && (stst.st_dev != pst.st_dev || stst.st_ino != pst.st_ino))
2485 passert(whack_log_fd == NULL_FD);
2486 whack_log_fd = p->whack_sock;
2487 whack_log(RC_COMMENT
2488 , "%s for ISAKMP SA, but releasing whack for pending IPSEC SA"
2490 whack_log_fd = NULL_FD;
2492 close(p->whack_sock);
2493 p->whack_sock = NULL_FD;
2499 delete_pending(struct pending **pp)
2501 struct pending *p = *pp;
2504 if (p->connection != NULL)
2505 connection_discard(p->connection);
2506 close_any(p->whack_sock);
2511 unpend(struct state *st)
2516 DBG(DBG_CONTROL, DBG_log("unpend - 1"));
2517 for (pp = &st->st_connection->host_pair->pending; (p = *pp) != NULL; )
2519 DBG(DBG_CONTROL, DBG_log("unpend - 2"));
2520 if (p->isakmp_sa == st)
2522 DBG(DBG_CONTROL, DBG_log("unqueuing pending Quick Mode with %s \"%s\""
2523 , ip_str(&p->connection->that.host_addr)
2524 , p->connection->name));
2525 DBG(DBG_CONTROL, DBG_log("unpend - 3"));
2526 (void) quick_outI1(p->whack_sock, st, p->connection, p->policy
2527 , p->try, p->replacing);
2528 p->whack_sock = NULL_FD; /* ownership transferred */
2529 p->connection = NULL; /* ownership transferred */
2539 /* a Main Mode negotiation has been replaced; update any pending */
2541 update_pending(struct state *os, struct state *ns)
2545 for (p = os->st_connection->host_pair->pending; p != NULL; p = p->next) {
2546 if (p->isakmp_sa == os)
2548 #ifdef NAT_TRAVERSAL
2549 if (p->connection->this.host_port != ns->st_connection->this.host_port) {
2550 p->connection->this.host_port = ns->st_connection->this.host_port;
2551 p->connection->that.host_port = ns->st_connection->that.host_port;
2557 /* a Main Mode negotiation has failed; discard any pending */
2559 flush_pending_by_state(struct state *st)
2561 struct host_pair *hp = st->st_connection->host_pair;
2568 for (pp = &hp->pending; (p = *pp) != NULL; )
2570 if (p->isakmp_sa == st)
2578 /* a connection has been deleted; discard any related pending */
2580 flush_pending_by_connection(struct connection *c)
2582 if (c->host_pair != NULL)
2587 for (pp = &c->host_pair->pending; (p = *pp) != NULL; )
2589 if (p->connection == c)
2591 p->connection = NULL; /* prevent delete_pending from releasing */
2602 /* Delete a connection if it is an instance and it is no longer in use.
2603 * We must be careful to avoid circularity:
2604 * we don't touch it if it is CK_GOING_AWAY.
2607 connection_discard(struct connection *c)
2609 if (c->kind == CK_INSTANCE)
2611 /* see if it is being used by a pending */
2614 for (p = c->host_pair->pending; p != NULL; p = p->next)
2615 if (p->connection == c)
2616 return; /* in use, so we're done */
2618 if (!states_use_connection(c))
2619 delete_connection(c);