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