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