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