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