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