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