1 /* demultiplex incoming IKE messages
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
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>.
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
15 * RCSID $Id: demux.c,v 1.14 2006/06/22 11:58:25 as Exp $
18 /* Ordering Constraints on Payloads
20 * rfc2409: The Internet Key Exchange (IKE)
23 * "The SA payload MUST precede all other payloads in a phase 1 exchange."
25 * "Except where otherwise noted, there are no requirements for ISAKMP
26 * payloads in any message to be in any particular order."
28 * 5.3 Phase 1 Authenticated With a Revised Mode of Public Key Encryption:
30 * "If the HASH payload is sent it MUST be the first payload of the
31 * second message exchange and MUST be followed by the encrypted
32 * nonce. If the HASH payload is not sent, the first payload of the
33 * second message exchange MUST be the encrypted nonce."
35 * "Save the requirements on the location of the optional HASH payload
36 * and the mandatory nonce payload there are no further payload
37 * requirements. All payloads-- in whatever order-- following the
38 * encrypted nonce MUST be encrypted with Ke_i or Ke_r depending on the
41 * 5.5 Phase 2 - Quick Mode
43 * "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
44 * header and a SA payload MUST immediately follow the HASH."
45 * [NOTE: there may be more than one SA payload, so this is not
46 * totally reasonable. Probably all SAs should be so constrained.]
48 * "If ISAKMP is acting as a client negotiator on behalf of another
49 * party, the identities of the parties MUST be passed as IDci and
52 * "With the exception of the HASH, SA, and the optional ID payloads,
53 * there are no payload ordering restrictions on Quick Mode."
56 /* Unfolding of Identity -- a central mystery
58 * This concerns Phase 1 identities, those of the IKE hosts.
59 * These are the only ones that are authenticated. Phase 2
60 * identities are for IPsec SAs.
62 * There are three case of interest:
64 * (1) We initiate, based on a whack command specifying a Connection.
65 * We know the identity of the peer from the Connection.
67 * (2) (to be implemented) we initiate based on a flow from our client
69 * We immediately know one of the peer's client IP addresses from
70 * the flow. We must use this to figure out the peer's IP address
71 * and Id. To be solved.
73 * (3) We respond to an IKE negotiation.
74 * We immediately know the peer's IP address.
75 * We get an ID Payload in Main I2.
77 * Unfortunately, this is too late for a number of things:
78 * - the ISAKMP SA proposals have already been made (Main I1)
79 * AND one accepted (Main R1)
80 * - the SA includes a specification of the type of ID
81 * authentication so this is negotiated without being told the ID.
82 * - with Preshared Key authentication, Main I2 is encrypted
83 * using the key, so it cannot be decoded to reveal the ID
84 * without knowing (or guessing) which key to use.
86 * There are three reasonable choices here for the responder:
87 * + assume that the initiator is making wise offers since it
88 * knows the IDs involved. We can balk later (but not gracefully)
89 * when we find the actual initiator ID
90 * + attempt to infer identity by IP address. Again, we can balk
91 * when the true identity is revealed. Actually, it is enough
92 * to infer properties of the identity (eg. SA properties and
94 * + make all properties universal so discrimination based on
95 * identity isn't required. For example, always accept the same
96 * kinds of encryption. Accept Public Key Id authentication
97 * since the Initiator presumably has our public key and thinks
98 * we must have / can find his. This approach is weakest
99 * for preshared key since the actual key must be known to
100 * decrypt the Initiator's ID Payload.
101 * These choices can be blended. For example, a class of Identities
102 * can be inferred, sufficient to select a preshared key but not
103 * sufficient to infer a unique identity.
112 #include <sys/types.h>
113 #include <sys/time.h> /* only used for belt-and-suspenders select call */
114 #include <sys/poll.h> /* only used for forensic poll call */
115 #include <sys/socket.h>
116 #include <sys/ioctl.h>
117 #include <netinet/in.h>
118 #include <arpa/inet.h>
119 #include <sys/queue.h>
121 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
122 # include <asm/types.h> /* for __u8, __u32 */
123 # include <linux/errqueue.h>
124 # include <sys/uio.h> /* struct iovec */
127 #include <freeswan.h>
129 #include "constants.h"
132 #include "connections.h"
137 #include "crypto.h" /* requires sha1.h and md5.h */
140 #include "demux.h" /* needs packet.h */
141 #include "ipsec_doi.h" /* needs demux.h and state.h */
143 #include "whack.h" /* requires connections.h */
145 #include "nat_traversal.h"
149 /* This file does basic header checking and demux of
153 /* forward declarations */
154 static bool read_packet(struct msg_digest
*md
);
155 static void process_packet(struct msg_digest
**mdp
);
157 /* Reply messages are built in this buffer.
158 * Only one state transition function can be using it at a time
159 * so suspended STFs must save and restore it.
160 * It could be an auto variable of complete_state_transition except for the fact
161 * that when a suspended STF resumes, its reply message buffer
162 * must be at the same location -- there are pointers into it.
164 u_int8_t reply_buffer
[MAX_OUTPUT_UDP_SIZE
];
166 /* state_microcode is a tuple of information parameterizing certain
167 * centralized processing of a packet. For example, it roughly
168 * specifies what payloads are expected in this message.
169 * The microcode is selected primarily based on the state.
170 * In Phase 1, the payload structure often depends on the
171 * authentication technique, so that too plays a part in selecting
172 * the state_microcode to use.
175 struct state_microcode
{
176 enum state_kind state
, next_state
;
178 lset_t req_payloads
; /* required payloads (allows just one) */
179 lset_t opt_payloads
; /* optional payloads (any mumber) */
180 /* if not ISAKMP_NEXT_NONE, process_packet will emit HDR with this as np */
181 u_int8_t first_out_payload
;
182 enum event_type timeout_event
;
183 state_transition_fn
*processor
;
186 /* State Microcode Flags, in several groups */
188 /* Oakley Auth values: to which auth values does this entry apply?
189 * Most entries will use SMF_ALL_AUTH because they apply to all.
190 * Note: SMF_ALL_AUTH matches 0 for those circumstances when no auth
193 #define SMF_ALL_AUTH LRANGE(0, OAKLEY_AUTH_ROOF-1)
194 #define SMF_PSK_AUTH LELEM(OAKLEY_PRESHARED_KEY)
195 #define SMF_DS_AUTH (LELEM(OAKLEY_DSS_SIG) | LELEM(OAKLEY_RSA_SIG))
196 #define SMF_PKE_AUTH (LELEM(OAKLEY_RSA_ENC) | LELEM(OAKLEY_ELGAMAL_ENC))
197 #define SMF_RPKE_AUTH (LELEM(OAKLEY_RSA_ENC_REV) | LELEM(OAKLEY_ELGAMAL_ENC_REV))
201 #define SMF_INITIATOR LELEM(OAKLEY_AUTH_ROOF + 0)
202 #define SMF_FIRST_ENCRYPTED_INPUT LELEM(OAKLEY_AUTH_ROOF + 1)
203 #define SMF_INPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 2)
204 #define SMF_OUTPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 3)
205 #define SMF_RETRANSMIT_ON_DUPLICATE LELEM(OAKLEY_AUTH_ROOF + 4)
207 #define SMF_ENCRYPTED (SMF_INPUT_ENCRYPTED | SMF_OUTPUT_ENCRYPTED)
209 /* this state generates a reply message */
210 #define SMF_REPLY LELEM(OAKLEY_AUTH_ROOF + 5)
212 /* this state completes P1, so any pending P2 negotiations should start */
213 #define SMF_RELEASE_PENDING_P2 LELEM(OAKLEY_AUTH_ROOF + 6)
218 static state_transition_fn
/* forward declaration */
222 /* state_microcode_table is a table of all state_microcode tuples.
223 * It must be in order of state (the first element).
224 * After initialization, ike_microcode_index[s] points to the
225 * first entry in state_microcode_table for state s.
226 * Remember that each state name in Main or Quick Mode describes
227 * what has happened in the past, not what this message is.
230 static const struct state_microcode
231 *ike_microcode_index
[STATE_IKE_ROOF
- STATE_IKE_FLOOR
];
233 static const struct state_microcode state_microcode_table
[] = {
234 #define PT(n) ISAKMP_NEXT_##n
235 #define P(n) LELEM(PT(n))
237 /***** Phase 1 Main Mode *****/
239 /* No state for main_outI1: --> HDR, SA */
241 /* STATE_MAIN_R0: I1 --> R1
242 * HDR, SA --> HDR, SA
244 { STATE_MAIN_R0
, STATE_MAIN_R1
245 , SMF_ALL_AUTH
| SMF_REPLY
246 , P(SA
), P(VID
) | P(CR
), PT(NONE
)
247 , EVENT_RETRANSMIT
, main_inI1_outR1
},
249 /* STATE_MAIN_I1: R1 --> I2
250 * HDR, SA --> auth dependent
251 * SMF_PSK_AUTH, SMF_DS_AUTH: --> HDR, KE, Ni
253 * --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
255 * --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
256 * Note: since we don't know auth at start, we cannot differentiate
257 * microcode entries based on it.
259 { STATE_MAIN_I1
, STATE_MAIN_I2
260 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_REPLY
261 , P(SA
), P(VID
) | P(CR
), PT(NONE
) /* don't know yet */
262 , EVENT_RETRANSMIT
, main_inR1_outI2
},
264 /* STATE_MAIN_R1: I2 --> R2
265 * SMF_PSK_AUTH, SMF_DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
266 * SMF_PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
267 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
269 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
270 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
272 { STATE_MAIN_R1
, STATE_MAIN_R2
273 , SMF_PSK_AUTH
| SMF_DS_AUTH
| SMF_REPLY
274 , P(KE
) | P(NONCE
), P(VID
) | P(CR
) | P(NATD_RFC
), PT(KE
)
275 , EVENT_RETRANSMIT
, main_inI2_outR2
},
277 { STATE_MAIN_R1
, STATE_UNDEFINED
278 , SMF_PKE_AUTH
| SMF_REPLY
279 , P(KE
) | P(ID
) | P(NONCE
), P(VID
) | P(CR
) | P(HASH
), PT(KE
)
280 , EVENT_RETRANSMIT
, unexpected
/* ??? not yet implemented */ },
282 { STATE_MAIN_R1
, STATE_UNDEFINED
283 , SMF_RPKE_AUTH
| SMF_REPLY
284 , P(NONCE
) | P(KE
) | P(ID
), P(VID
) | P(CR
) | P(HASH
) | P(CERT
), PT(NONCE
)
285 , EVENT_RETRANSMIT
, unexpected
/* ??? not yet implemented */ },
287 /* for states from here on, output message must be encrypted */
289 /* STATE_MAIN_I2: R2 --> I3
290 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
291 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
292 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
294 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
297 { STATE_MAIN_I2
, STATE_MAIN_I3
298 , SMF_PSK_AUTH
| SMF_DS_AUTH
| SMF_INITIATOR
| SMF_OUTPUT_ENCRYPTED
| SMF_REPLY
299 , P(KE
) | P(NONCE
), P(VID
) | P(CR
) | P(NATD_RFC
), PT(ID
)
300 , EVENT_RETRANSMIT
, main_inR2_outI3
},
302 { STATE_MAIN_I2
, STATE_UNDEFINED
303 , SMF_PKE_AUTH
| SMF_INITIATOR
| SMF_OUTPUT_ENCRYPTED
| SMF_REPLY
304 , P(KE
) | P(ID
) | P(NONCE
), P(VID
) | P(CR
), PT(HASH
)
305 , EVENT_RETRANSMIT
, unexpected
/* ??? not yet implemented */ },
307 { STATE_MAIN_I2
, STATE_UNDEFINED
308 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_OUTPUT_ENCRYPTED
| SMF_REPLY
309 , P(NONCE
) | P(KE
) | P(ID
), P(VID
) | P(CR
), PT(HASH
)
310 , EVENT_RETRANSMIT
, unexpected
/* ??? not yet implemented */ },
312 /* for states from here on, input message must be encrypted */
314 /* STATE_MAIN_R2: I3 --> R3
315 * SMF_PSK_AUTH: HDR*, IDi1, HASH_I --> HDR*, IDr1, HASH_R
316 * SMF_DS_AUTH: HDR*, IDi1, [ CERT, ] SIG_I --> HDR*, IDr1, [ CERT, ] SIG_R
317 * SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_I --> HDR*, HASH_R
319 { STATE_MAIN_R2
, STATE_MAIN_R3
320 , SMF_PSK_AUTH
| SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
321 | SMF_REPLY
| SMF_RELEASE_PENDING_P2
322 , P(ID
) | P(HASH
), P(VID
) | P(CR
), PT(NONE
)
323 , EVENT_SA_REPLACE
, main_inI3_outR3
},
325 { STATE_MAIN_R2
, STATE_MAIN_R3
326 , SMF_DS_AUTH
| SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
327 | SMF_REPLY
| SMF_RELEASE_PENDING_P2
328 , P(ID
) | P(SIG
), P(VID
) | P(CR
) | P(CERT
), PT(NONE
)
329 , EVENT_SA_REPLACE
, main_inI3_outR3
},
331 { STATE_MAIN_R2
, STATE_UNDEFINED
332 , SMF_PKE_AUTH
| SMF_RPKE_AUTH
| SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
333 | SMF_REPLY
| SMF_RELEASE_PENDING_P2
334 , P(HASH
), P(VID
) | P(CR
), PT(NONE
)
335 , EVENT_SA_REPLACE
, unexpected
/* ??? not yet implemented */ },
337 /* STATE_MAIN_I3: R3 --> done
338 * SMF_PSK_AUTH: HDR*, IDr1, HASH_R --> done
339 * SMF_DS_AUTH: HDR*, IDr1, [ CERT, ] SIG_R --> done
340 * SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_R --> done
341 * May initiate quick mode by calling quick_outI1
343 { STATE_MAIN_I3
, STATE_MAIN_I4
344 , SMF_PSK_AUTH
| SMF_INITIATOR
345 | SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
346 , P(ID
) | P(HASH
), P(VID
) | P(CR
), PT(NONE
)
347 , EVENT_SA_REPLACE
, main_inR3
},
349 { STATE_MAIN_I3
, STATE_MAIN_I4
350 , SMF_DS_AUTH
| SMF_INITIATOR
351 | SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
352 , P(ID
) | P(SIG
), P(VID
) | P(CR
) | P(CERT
), PT(NONE
)
353 , EVENT_SA_REPLACE
, main_inR3
},
355 { STATE_MAIN_I3
, STATE_UNDEFINED
356 , SMF_PKE_AUTH
| SMF_RPKE_AUTH
| SMF_INITIATOR
357 | SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
358 , P(HASH
), P(VID
) | P(CR
), PT(NONE
)
359 , EVENT_SA_REPLACE
, unexpected
/* ??? not yet implemented */ },
361 /* STATE_MAIN_R3: can only get here due to packet loss */
362 { STATE_MAIN_R3
, STATE_UNDEFINED
363 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_RETRANSMIT_ON_DUPLICATE
365 , PT(NONE
), EVENT_NULL
, unexpected
},
367 /* STATE_MAIN_I4: can only get here due to packet loss */
368 { STATE_MAIN_I4
, STATE_UNDEFINED
369 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_ENCRYPTED
371 , PT(NONE
), EVENT_NULL
, unexpected
},
374 /***** Phase 2 Quick Mode *****/
376 /* No state for quick_outI1:
377 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
381 * HDR*, HASH(1), SA, Ni [, KE ] [, IDci, IDcr ] -->
382 * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ]
383 * Installs inbound IPsec SAs.
384 * Because it may suspend for asynchronous DNS, first_out_payload
385 * is set to NONE to suppress early emission of HDR*.
386 * ??? it is legal to have multiple SAs, but we don't support it yet.
388 { STATE_QUICK_R0
, STATE_QUICK_R1
389 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_REPLY
390 , P(HASH
) | P(SA
) | P(NONCE
), /* P(SA) | */ P(KE
) | P(ID
) | P(NATOA_RFC
), PT(NONE
)
391 , EVENT_RETRANSMIT
, quick_inI1_outR1
},
394 * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ] -->
396 * Installs inbound and outbound IPsec SAs, routing, etc.
397 * ??? it is legal to have multiple SAs, but we don't support it yet.
399 { STATE_QUICK_I1
, STATE_QUICK_I2
400 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_ENCRYPTED
| SMF_REPLY
401 , P(HASH
) | P(SA
) | P(NONCE
), /* P(SA) | */ P(KE
) | P(ID
) | P(NATOA_RFC
), PT(HASH
)
402 , EVENT_SA_REPLACE
, quick_inR1_outI2
},
404 /* STATE_QUICK_R1: HDR*, HASH(3) --> done
405 * Installs outbound IPsec SAs, routing, etc.
407 { STATE_QUICK_R1
, STATE_QUICK_R2
408 , SMF_ALL_AUTH
| SMF_ENCRYPTED
409 , P(HASH
), LEMPTY
, PT(NONE
)
410 , EVENT_SA_REPLACE
, quick_inI2
},
412 /* STATE_QUICK_I2: can only happen due to lost packet */
413 { STATE_QUICK_I2
, STATE_UNDEFINED
414 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_ENCRYPTED
| SMF_RETRANSMIT_ON_DUPLICATE
415 , LEMPTY
, LEMPTY
, PT(NONE
)
416 , EVENT_NULL
, unexpected
},
418 /* STATE_QUICK_R2: can only happen due to lost packet */
419 { STATE_QUICK_R2
, STATE_UNDEFINED
420 , SMF_ALL_AUTH
| SMF_ENCRYPTED
421 , LEMPTY
, LEMPTY
, PT(NONE
)
422 , EVENT_NULL
, unexpected
},
425 /***** informational messages *****/
428 { STATE_INFO
, STATE_UNDEFINED
430 , LEMPTY
, LEMPTY
, PT(NONE
)
431 , EVENT_NULL
, informational
},
433 /* STATE_INFO_PROTECTED: */
434 { STATE_INFO_PROTECTED
, STATE_UNDEFINED
435 , SMF_ALL_AUTH
| SMF_ENCRYPTED
436 , P(HASH
), LEMPTY
, PT(NONE
)
437 , EVENT_NULL
, informational
},
440 * Case R0: Responder -> Initiator
444 * Case R1: Set(addr=x) ->
448 { STATE_MODE_CFG_R0
, STATE_MODE_CFG_R1
449 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_REPLY
450 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
451 , EVENT_SA_REPLACE
, modecfg_inR0
},
453 { STATE_MODE_CFG_R1
, STATE_MODE_CFG_R2
454 , SMF_ALL_AUTH
| SMF_ENCRYPTED
455 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
456 , EVENT_SA_REPLACE
, modecfg_inR1
},
458 { STATE_MODE_CFG_R2
, STATE_UNDEFINED
459 , SMF_ALL_AUTH
| SMF_ENCRYPTED
460 , LEMPTY
, LEMPTY
, PT(NONE
)
461 , EVENT_NULL
, unexpected
},
463 { STATE_MODE_CFG_I1
, STATE_MODE_CFG_I2
464 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
465 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
466 , EVENT_SA_REPLACE
, modecfg_inI1
},
468 { STATE_MODE_CFG_I2
, STATE_MODE_CFG_I3
469 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_REPLY
| SMF_RELEASE_PENDING_P2
470 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
471 , EVENT_SA_REPLACE
, modecfg_inI2
},
473 { STATE_MODE_CFG_I3
, STATE_UNDEFINED
474 , SMF_ALL_AUTH
| SMF_ENCRYPTED
475 , LEMPTY
, LEMPTY
, PT(NONE
)
476 , EVENT_NULL
, unexpected
},
485 /* fill ike_microcode_index:
486 * make ike_microcode_index[s] point to first entry in
487 * state_microcode_table for state s (backward scan makes this easier).
488 * Check that table is in order -- catch coding errors.
489 * For what it's worth, this routine is idempotent.
491 const struct state_microcode
*t
;
493 for (t
= &state_microcode_table
[elemsof(state_microcode_table
) - 1];;)
495 passert(STATE_IKE_FLOOR
<= t
->state
&& t
->state
< STATE_IKE_ROOF
);
496 ike_microcode_index
[t
->state
- STATE_IKE_FLOOR
] = t
;
497 if (t
== state_microcode_table
)
500 passert(t
[0].state
<= t
[1].state
);
504 /* Process any message on the MSG_ERRQUEUE
506 * This information is generated because of the IP_RECVERR socket option.
507 * The API is sparsely documented, and may be LINUX-only, and only on
508 * fairly recent versions at that (hence the conditional compilation).
510 * - ip(7) describes IP_RECVERR
511 * - recvmsg(2) describes MSG_ERRQUEUE
512 * - readv(2) describes iovec
513 * - cmsg(3) describes how to process auxilliary messages
515 * ??? we should link this message with one we've sent
516 * so that the diagnostic can refer to that negotiation.
518 * ??? how long can the messge be?
520 * ??? poll(2) has a very incomplete description of the POLL* events.
521 * We assume that POLLIN, POLLOUT, and POLLERR are all we need to deal with
522 * and that POLLERR will be on iff there is a MSG_ERRQUEUE message.
524 * We have to code around a couple of surprises:
526 * - Select can say that a socket is ready to read from, and
527 * yet a read will hang. It turns out that a message available on the
528 * MSG_ERRQUEUE will cause select to say something is pending, but
529 * a normal read will hang. poll(2) can tell when a MSG_ERRQUEUE
530 * message is pending.
532 * This is dealt with by calling check_msg_errqueue after select
533 * has indicated that there is something to read, but before the
534 * read is performed. check_msg_errqueue will return TRUE if there
535 * is something left to read.
537 * - A write to a socket may fail because there is a pending MSG_ERRQUEUE
538 * message, without there being anything wrong with the write. This
539 * makes for confusing diagnostics.
541 * To avoid this, we call check_msg_errqueue before a write. True,
542 * there is a race condition (a MSG_ERRQUEUE message might arrive
543 * between the check and the write), but we should eliminate many
544 * of the problematic events. To narrow the window, the poll(2)
545 * will await until an event happens (in the case or a write,
546 * POLLOUT; this should be benign for POLLIN).
549 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
551 check_msg_errqueue(const struct iface
*ifp
, short interest
)
556 pfd
.events
= interest
| POLLPRI
| POLLOUT
;
558 while (pfd
.revents
= 0
559 , poll(&pfd
, 1, -1) > 0 && (pfd
.revents
& POLLERR
))
561 u_int8_t buffer
[3000]; /* hope that this is big enough */
565 struct sockaddr_in sa_in4
;
566 struct sockaddr_in6 sa_in6
;
569 int from_len
= sizeof(from
);
576 /* force alignment (not documented as necessary) */
579 /* how much space is enough? */
580 unsigned char space
[256];
584 char fromstr
[sizeof(" for message to port 65536") + INET6_ADDRSTRLEN
];
585 struct state
*sender
= NULL
;
588 from_len
= sizeof(from
);
590 emh
.msg_name
= &from
.sa
; /* ??? filled in? */
591 emh
.msg_namelen
= sizeof(from
);
594 emh
.msg_control
= &ecms_buf
;
595 emh
.msg_controllen
= sizeof(ecms_buf
);
598 eiov
.iov_base
= buffer
; /* see readv(2) */
599 eiov
.iov_len
= sizeof(buffer
);
601 packet_len
= recvmsg(ifp
->fd
, &emh
, MSG_ERRQUEUE
);
603 if (packet_len
== -1)
605 log_errno((e
, "recvmsg(,, MSG_ERRQUEUE) on %s failed in comm_handle"
609 else if (packet_len
== sizeof(buffer
))
611 plog("MSG_ERRQUEUE message longer than %lu bytes; truncated"
612 , (unsigned long) sizeof(buffer
));
616 sender
= find_sender((size_t) packet_len
, buffer
);
619 DBG_cond_dump(DBG_ALL
, "rejected packet:\n", buffer
, packet_len
);
620 DBG_cond_dump(DBG_ALL
, "control:\n", emh
.msg_control
, emh
.msg_controllen
);
621 /* ??? Andi Kleen <ak@suse.de> and misc documentation
622 * suggests that name will have the original destination
623 * of the packet. We seem to see msg_namelen == 0.
624 * Andi says that this is a kernel bug and has fixed it.
625 * Perhaps in 2.2.18/2.4.0.
627 passert(emh
.msg_name
== &from
.sa
);
628 DBG_cond_dump(DBG_ALL
, "name:\n", emh
.msg_name
631 fromstr
[0] = '\0'; /* usual case :-( */
632 switch (from
.sa
.sa_family
)
634 char as
[INET6_ADDRSTRLEN
];
637 if (emh
.msg_namelen
== sizeof(struct sockaddr_in
))
638 snprintf(fromstr
, sizeof(fromstr
)
639 , " for message to %s port %u"
640 , inet_ntop(from
.sa
.sa_family
641 , &from
.sa_in4
.sin_addr
, as
, sizeof(as
))
642 , ntohs(from
.sa_in4
.sin_port
));
645 if (emh
.msg_namelen
== sizeof(struct sockaddr_in6
))
646 snprintf(fromstr
, sizeof(fromstr
)
647 , " for message to %s port %u"
648 , inet_ntop(from
.sa
.sa_family
649 , &from
.sa_in6
.sin6_addr
, as
, sizeof(as
))
650 , ntohs(from
.sa_in6
.sin6_port
));
654 for (cm
= CMSG_FIRSTHDR(&emh
)
656 ; cm
= CMSG_NXTHDR(&emh
,cm
))
658 if (cm
->cmsg_level
== SOL_IP
659 && cm
->cmsg_type
== IP_RECVERR
)
661 /* ip(7) and recvmsg(2) specify:
662 * ee_origin is SO_EE_ORIGIN_ICMP for ICMP
663 * or SO_EE_ORIGIN_LOCAL for locally generated errors.
664 * ee_type and ee_code are from the ICMP header.
665 * ee_info is the discovered MTU for EMSGSIZE errors
666 * ee_data is not used.
668 * ??? recvmsg(2) says "SOCK_EE_OFFENDER" but
669 * means "SO_EE_OFFENDER". The OFFENDER is really
670 * the router that complained. As such, the port
674 /* ??? cmsg(3) claims that CMSG_DATA returns
675 * void *, but RFC 2292 and /usr/include/bits/socket.h
676 * say unsigned char *. The manual is being fixed.
678 struct sock_extended_err
*ee
= (void *)CMSG_DATA(cm
);
679 const char *offstr
= "unspecified";
680 char offstrspace
[INET6_ADDRSTRLEN
];
683 if (cm
->cmsg_len
> CMSG_LEN(sizeof(struct sock_extended_err
)))
685 const struct sockaddr
*offender
= SO_EE_OFFENDER(ee
);
687 switch (offender
->sa_family
)
690 offstr
= inet_ntop(offender
->sa_family
691 , &((const struct sockaddr_in
*)offender
)->sin_addr
692 , offstrspace
, sizeof(offstrspace
));
695 offstr
= inet_ntop(offender
->sa_family
696 , &((const struct sockaddr_in6
*)offender
)->sin6_addr
697 , offstrspace
, sizeof(offstrspace
));
705 switch (ee
->ee_origin
)
707 case SO_EE_ORIGIN_NONE
:
708 snprintf(orname
, sizeof(orname
), "none");
710 case SO_EE_ORIGIN_LOCAL
:
711 snprintf(orname
, sizeof(orname
), "local");
713 case SO_EE_ORIGIN_ICMP
:
714 snprintf(orname
, sizeof(orname
)
715 , "ICMP type %d code %d (not authenticated)"
716 , ee
->ee_type
, ee
->ee_code
719 case SO_EE_ORIGIN_ICMP6
:
720 snprintf(orname
, sizeof(orname
)
721 , "ICMP6 type %d code %d (not authenticated)"
722 , ee
->ee_type
, ee
->ee_code
726 snprintf(orname
, sizeof(orname
), "invalid origin %lu"
727 , (unsigned long) ee
->ee_origin
);
732 struct state
*old_state
= cur_state
;
736 /* note dirty trick to suppress ~ at start of format
737 * if we know what state to blame.
739 if ((packet_len
== 1) && (buffer
[0] = 0xff)
741 && ((cur_debugging
& DBG_NATT
) == 0)
744 /* don't log NAT-T keepalive related errors unless NATT debug is
749 plog((sender
!= NULL
) + "~"
750 "ERROR: asynchronous network error report on %s"
754 " [errno %lu, origin %s"
755 /* ", pad %d, info %ld" */
761 , strerror(ee
->ee_errno
)
762 , (unsigned long) ee
->ee_errno
764 /* , ee->ee_pad, (unsigned long)ee->ee_info */
765 /* , (unsigned long)ee->ee_data */
767 cur_state
= old_state
;
772 /* .cmsg_len is a kernel_size_t(!), but the value
773 * certainly ought to fit in an unsigned long.
775 plog("unknown cmsg: level %d, type %d, len %lu"
776 , cm
->cmsg_level
, cm
->cmsg_type
777 , (unsigned long) cm
->cmsg_len
);
781 return (pfd
.revents
& interest
) != 0;
783 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
786 send_packet(struct state
*st
, const char *where
)
788 struct connection
*c
= st
->st_connection
;
791 u_int8_t ike_pkt
[MAX_OUTPUT_UDP_SIZE
];
795 if (c
->interface
->ike_float
&& st
->st_tpacket
.len
!= 1)
797 if ((unsigned long) st
->st_tpacket
.len
> (MAX_OUTPUT_UDP_SIZE
-sizeof(u_int32_t
)))
799 DBG_log("send_packet(): really too big");
803 /** Add Non-ESP marker **/
804 memset(ike_pkt
, 0, sizeof(u_int32_t
));
805 memcpy(ike_pkt
+ sizeof(u_int32_t
), st
->st_tpacket
.ptr
,
806 (unsigned long)st
->st_tpacket
.len
);
807 len
= (unsigned long) st
->st_tpacket
.len
+ sizeof(u_int32_t
);
811 ptr
= st
->st_tpacket
.ptr
;
812 len
= (unsigned long) st
->st_tpacket
.len
;
817 DBG_log("sending %lu bytes for %s through %s to %s:%u:"
818 , (unsigned long) st
->st_tpacket
.len
820 , c
->interface
->rname
821 , ip_str(&c
->spd
.that
.host_addr
)
822 , (unsigned)c
->spd
.that
.host_port
);
823 DBG_dump_chunk(NULL
, st
->st_tpacket
);
826 /* XXX: Not very clean. We manipulate the port of the ip_address to
827 * have a port in the sockaddr*, but we retain the original port
828 * and restore it afterwards.
831 port_buf
= portof(&c
->spd
.that
.host_addr
);
832 setportof(htons(c
->spd
.that
.host_port
), &c
->spd
.that
.host_addr
);
834 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
835 (void) check_msg_errqueue(c
->interface
, POLLOUT
);
836 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
838 err
= sendto(c
->interface
->fd
840 , sockaddrof(&c
->spd
.that
.host_addr
)
841 , sockaddrlenof(&c
->spd
.that
.host_addr
)) != (ssize_t
)len
;
844 setportof(port_buf
, &c
->spd
.that
.host_addr
);
848 /* do not log NAT-T Keep Alive packets */
849 if (streq(where
, "NAT-T Keep Alive"))
851 log_errno((e
, "sendto on %s to %s:%u failed in %s"
852 , c
->interface
->rname
853 , ip_str(&c
->spd
.that
.host_addr
)
854 , (unsigned)c
->spd
.that
.host_port
865 unexpected(struct msg_digest
*md
)
867 loglog(RC_LOG_SERIOUS
, "unexpected message received in state %s"
868 , enum_name(&state_names
, md
->st
->st_state
));
873 informational(struct msg_digest
*md UNUSED
)
875 struct payload_digest
*const n_pld
= md
->chain
[ISAKMP_NEXT_N
];
877 /* If the Notification Payload is not null... */
880 pb_stream
*const n_pbs
= &n_pld
->pbs
;
881 struct isakmp_notification
*const n
= &n_pld
->payload
.notification
;
885 /* Switch on Notification Type (enum) */
886 switch (n
->isan_type
)
889 return dpd_inI_outR(md
->st
, n
, n_pbs
);
892 return dpd_inR(md
->st
, n
, n_pbs
);
894 if (pbs_left(n_pbs
) >= sizeof(disp_buf
)-1)
895 disp_len
= sizeof(disp_buf
)-1;
897 disp_len
= pbs_left(n_pbs
);
898 memcpy(disp_buf
, n_pbs
->cur
, disp_len
);
899 disp_buf
[disp_len
] = '\0';
906 /* message digest allocation and deallocation */
908 static struct msg_digest
*md_pool
= NULL
;
910 /* free_md_pool is only used to avoid leak reports */
916 struct msg_digest
*md
= md_pool
;
925 static struct msg_digest
*
928 struct msg_digest
*md
= md_pool
;
930 /* convenient initializer:
931 * - all pointers NULL
932 * - .note = NOTHING_WRONG
933 * - .encrypted = FALSE
935 static const struct msg_digest blank_md
;
938 md
= alloc_thing(struct msg_digest
, "msg_digest");
943 md
->digest_roof
= md
->digest
;
945 /* note: although there may be multiple msg_digests at once
946 * (due to suspended state transitions), there is a single
947 * global reply_buffer. It will need to be saved and restored.
949 init_pbs(&md
->reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
955 release_md(struct msg_digest
*md
)
957 freeanychunk(md
->raw_packet
);
958 pfreeany(md
->packet_pbs
.start
);
959 md
->packet_pbs
.start
= NULL
;
964 /* wrapper for read_packet and process_packet
966 * The main purpose of this wrapper is to factor out teardown code
967 * from the many return points in process_packet. This amounts to
968 * releasing the msg_digest and resetting global variables.
970 * When processing of a packet is suspended (STF_SUSPEND),
971 * process_packet sets md to NULL to prevent the msg_digest being freed.
972 * Someone else must ensure that msg_digest is freed eventually.
974 * read_packet is broken out to minimize the lifetime of the
975 * enormous input packet buffer, an auto.
978 comm_handle(const struct iface
*ifp
)
980 static struct msg_digest
*md
;
982 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
983 /* Even though select(2) says that there is a message,
984 * it might only be a MSG_ERRQUEUE message. At least
985 * sometimes that leads to a hanging recvfrom. To avoid
986 * what appears to be a kernel bug, check_msg_errqueue
987 * uses poll(2) and tells us if there is anything for us
990 * This is early enough that teardown isn't required:
991 * just return on failure.
993 if (!check_msg_errqueue(ifp
, POLLIN
))
994 return; /* no normal message to read */
995 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
1000 if (read_packet(md
))
1001 process_packet(&md
);
1007 reset_cur_connection();
1011 /* read the message.
1012 * Since we don't know its size, we read it into
1013 * an overly large buffer and then copy it to a
1014 * new, properly sized buffer.
1017 read_packet(struct msg_digest
*md
)
1019 const struct iface
*ifp
= md
->iface
;
1022 u_int8_t
*buffer_nat
;
1026 struct sockaddr_in sa_in4
;
1027 struct sockaddr_in6 sa_in6
;
1029 int from_len
= sizeof(from
);
1030 err_t from_ugh
= NULL
;
1031 static const char undisclosed
[] = "unknown source";
1033 happy(anyaddr(addrtypeof(&ifp
->addr
), &md
->sender
));
1035 ioctl(ifp
->fd
, FIONREAD
, &packet_len
);
1036 buffer
= alloc_bytes(packet_len
, "buffer read packet");
1037 packet_len
= recvfrom(ifp
->fd
, buffer
, packet_len
, 0
1038 , &from
.sa
, &from_len
);
1040 /* First: digest the from address.
1041 * We presume that nothing here disturbs errno.
1043 if (packet_len
== -1
1044 && from_len
== sizeof(from
)
1045 && all_zero((const void *)&from
.sa
, sizeof(from
)))
1047 /* "from" is untouched -- not set by recvfrom */
1048 from_ugh
= undisclosed
;
1051 < (int) (offsetof(struct sockaddr
, sa_family
) + sizeof(from
.sa
.sa_family
)))
1053 from_ugh
= "truncated";
1057 const struct af_info
*afi
= aftoinfo(from
.sa
.sa_family
);
1061 from_ugh
= "unexpected Address Family";
1063 else if (from_len
!= (int)afi
->sa_sz
)
1065 from_ugh
= "wrong length";
1069 switch (from
.sa
.sa_family
)
1072 from_ugh
= initaddr((void *) &from
.sa_in4
.sin_addr
1073 , sizeof(from
.sa_in4
.sin_addr
), AF_INET
, &md
->sender
);
1074 md
->sender_port
= ntohs(from
.sa_in4
.sin_port
);
1077 from_ugh
= initaddr((void *) &from
.sa_in6
.sin6_addr
1078 , sizeof(from
.sa_in6
.sin6_addr
), AF_INET6
, &md
->sender
);
1079 md
->sender_port
= ntohs(from
.sa_in6
.sin6_port
);
1085 /* now we report any actual I/O error */
1086 if (packet_len
== -1)
1088 if (from_ugh
== undisclosed
1089 && errno
== ECONNREFUSED
)
1091 /* Tone down scary message for vague event:
1092 * We get "connection refused" in response to some
1093 * datagram we sent, but we cannot tell which one.
1095 plog("some IKE message we sent has been rejected with ECONNREFUSED (kernel supplied no details)");
1097 else if (from_ugh
!= NULL
)
1099 log_errno((e
, "recvfrom on %s failed; Pluto cannot decode source sockaddr in rejection: %s"
1100 , ifp
->rname
, from_ugh
));
1104 log_errno((e
, "recvfrom on %s from %s:%u failed"
1106 , ip_str(&md
->sender
), (unsigned)md
->sender_port
));
1111 else if (from_ugh
!= NULL
)
1113 plog("recvfrom on %s returned misformed source sockaddr: %s"
1114 , ifp
->rname
, from_ugh
);
1117 cur_from
= &md
->sender
;
1118 cur_from_port
= md
->sender_port
;
1120 if (ifp
->ike_float
== TRUE
)
1124 if (packet_len
< (int)sizeof(u_int32_t
))
1126 plog("recvfrom %s:%u too small packet (%d)"
1127 , ip_str(cur_from
), (unsigned) cur_from_port
, packet_len
);
1130 memcpy(&non_esp
, buffer
, sizeof(u_int32_t
));
1133 plog("recvfrom %s:%u has no Non-ESP marker"
1134 , ip_str(cur_from
), (unsigned) cur_from_port
);
1137 packet_len
-= sizeof(u_int32_t
);
1138 buffer_nat
= alloc_bytes(packet_len
, "buffer read packet");
1139 memcpy(buffer_nat
, buffer
+ sizeof(u_int32_t
), packet_len
);
1141 buffer
= buffer_nat
;
1144 /* Clone actual message contents
1145 * and set up md->packet_pbs to describe it.
1147 init_pbs(&md
->packet_pbs
, buffer
, packet_len
, "packet");
1149 DBG(DBG_RAW
| DBG_CRYPT
| DBG_PARSING
| DBG_CONTROL
,
1151 DBG_log(BLANK_FORMAT
);
1152 DBG_log("*received %d bytes from %s:%u on %s"
1153 , (int) pbs_room(&md
->packet_pbs
)
1154 , ip_str(cur_from
), (unsigned) cur_from_port
1159 DBG_dump("", md
->packet_pbs
.start
, pbs_room(&md
->packet_pbs
)));
1161 if ((pbs_room(&md
->packet_pbs
)==1) && (md
->packet_pbs
.start
[0]==0xff))
1164 * NAT-T Keep-alive packets should be discared by kernel ESPinUDP
1165 * layer. But boggus keep-alive packets (sent with a non-esp marker)
1166 * can reach this point. Complain and discard them.
1169 DBG_log("NAT-T keep-alive (boggus ?) should not reach this point. "
1170 "Ignored. Sender: %s:%u", ip_str(cur_from
),
1171 (unsigned) cur_from_port
);
1176 #define IKEV2_VERSION_OFFSET 17
1177 #define IKEV2_VERSION 0x20
1179 /* ignore IKEv2 packets - they will be handled by charon */
1180 if (pbs_room(&md
->packet_pbs
) > IKEV2_VERSION_OFFSET
1181 && md
->packet_pbs
.start
[IKEV2_VERSION_OFFSET
] == IKEV2_VERSION
)
1183 DBG(DBG_CONTROLMORE
,
1184 DBG_log(" ignoring IKEv2 packet")
1192 /* process an input packet, possibly generating a reply.
1194 * If all goes well, this routine eventually calls a state-specific
1195 * transition function.
1198 process_packet(struct msg_digest
**mdp
)
1200 struct msg_digest
*md
= *mdp
;
1201 const struct state_microcode
*smc
;
1202 bool new_iv_set
= FALSE
;
1203 bool restore_iv
= FALSE
;
1204 u_char new_iv
[MAX_DIGEST_LEN
];
1205 u_int new_iv_len
= 0;
1207 struct state
*st
= NULL
;
1208 enum state_kind from_state
= STATE_UNDEFINED
; /* state we started in */
1210 #define SEND_NOTIFICATION(t) { \
1211 if (st) send_notification_from_state(st, from_state, t); \
1212 else send_notification_from_md(md, t); }
1214 if (!in_struct(&md
->hdr
, &isakmp_hdr_desc
, &md
->packet_pbs
, &md
->message_pbs
))
1216 /* Identify specific failures:
1217 * - bad ISAKMP major/minor version numbers
1219 if (md
->packet_pbs
.roof
- md
->packet_pbs
.cur
>= (ptrdiff_t)isakmp_hdr_desc
.size
)
1221 struct isakmp_hdr
*hdr
= (struct isakmp_hdr
*)md
->packet_pbs
.cur
;
1222 if ((hdr
->isa_version
>> ISA_MAJ_SHIFT
) != ISAKMP_MAJOR_VERSION
)
1224 SEND_NOTIFICATION(INVALID_MAJOR_VERSION
);
1227 else if ((hdr
->isa_version
& ISA_MIN_MASK
) != ISAKMP_MINOR_VERSION
)
1229 SEND_NOTIFICATION(INVALID_MINOR_VERSION
);
1233 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1237 if (md
->packet_pbs
.roof
!= md
->message_pbs
.roof
)
1239 plog("size (%u) differs from size specified in ISAKMP HDR (%u)"
1240 , (unsigned) pbs_room(&md
->packet_pbs
), md
->hdr
.isa_length
);
1244 switch (md
->hdr
.isa_xchg
)
1247 case ISAKMP_XCHG_NONE
:
1248 case ISAKMP_XCHG_BASE
:
1251 case ISAKMP_XCHG_IDPROT
: /* part of a Main Mode exchange */
1252 if (md
->hdr
.isa_msgid
!= MAINMODE_MSGID
)
1254 plog("Message ID was 0x%08lx but should be zero in Main Mode",
1255 (unsigned long) md
->hdr
.isa_msgid
);
1256 SEND_NOTIFICATION(INVALID_MESSAGE_ID
);
1260 if (is_zero_cookie(md
->hdr
.isa_icookie
))
1262 plog("Initiator Cookie must not be zero in Main Mode message");
1263 SEND_NOTIFICATION(INVALID_COOKIE
);
1267 if (is_zero_cookie(md
->hdr
.isa_rcookie
))
1269 /* initial message from initiator
1270 * ??? what if this is a duplicate of another message?
1272 if (md
->hdr
.isa_flags
& ISAKMP_FLAG_ENCRYPTION
)
1274 plog("initial Main Mode message is invalid:"
1275 " its Encrypted Flag is on");
1276 SEND_NOTIFICATION(INVALID_FLAGS
);
1280 /* don't build a state until the message looks tasty */
1281 from_state
= STATE_MAIN_R0
;
1285 /* not an initial message */
1287 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1288 , &md
->sender
, md
->hdr
.isa_msgid
);
1292 /* perhaps this is a first message from the responder
1293 * and contains a responder cookie that we've not yet seen.
1295 st
= find_state(md
->hdr
.isa_icookie
, zero_cookie
1296 , &md
->sender
, md
->hdr
.isa_msgid
);
1300 plog("Main Mode message is part of an unknown exchange");
1301 /* XXX Could send notification back */
1306 from_state
= st
->st_state
;
1311 case ISAKMP_XCHG_AO
:
1312 case ISAKMP_XCHG_AGGR
:
1315 case ISAKMP_XCHG_INFO
: /* an informational exchange */
1316 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1317 , &md
->sender
, MAINMODE_MSGID
);
1322 if (md
->hdr
.isa_flags
& ISAKMP_FLAG_ENCRYPTION
)
1326 plog("Informational Exchange is for an unknown (expired?) SA");
1327 /* XXX Could send notification back */
1331 if (!IS_ISAKMP_ENCRYPTED(st
->st_state
))
1333 loglog(RC_LOG_SERIOUS
, "encrypted Informational Exchange message is invalid"
1334 " because no key is known");
1335 /* XXX Could send notification back */
1339 if (md
->hdr
.isa_msgid
== MAINMODE_MSGID
)
1341 loglog(RC_LOG_SERIOUS
, "Informational Exchange message is invalid because"
1342 " it has a Message ID of 0");
1343 /* XXX Could send notification back */
1347 if (!reserve_msgid(st
, md
->hdr
.isa_msgid
))
1349 loglog(RC_LOG_SERIOUS
, "Informational Exchange message is invalid because"
1350 " it has a previously used Message ID (0x%08lx)"
1351 , (unsigned long)md
->hdr
.isa_msgid
);
1352 /* XXX Could send notification back */
1356 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1358 memcpy(st
->st_ph1_iv
, st
->st_new_iv
, st
->st_new_iv_len
);
1359 st
->st_ph1_iv_len
= st
->st_new_iv_len
;
1362 new_iv_len
= st
->st_new_iv_len
;
1363 passert(new_iv_len
<= MAX_DIGEST_LEN
)
1364 memcpy(new_iv
, st
->st_new_iv
, new_iv_len
);
1367 init_phase2_iv(st
, &md
->hdr
.isa_msgid
);
1370 from_state
= STATE_INFO_PROTECTED
;
1374 if (st
!= NULL
&& IS_ISAKMP_ENCRYPTED(st
->st_state
))
1376 loglog(RC_LOG_SERIOUS
, "Informational Exchange message"
1377 " must be encrypted");
1378 /* XXX Could send notification back */
1381 from_state
= STATE_INFO
;
1385 case ISAKMP_XCHG_QUICK
: /* part of a Quick Mode exchange */
1386 if (is_zero_cookie(md
->hdr
.isa_icookie
))
1388 plog("Quick Mode message is invalid because"
1389 " it has an Initiator Cookie of 0");
1390 SEND_NOTIFICATION(INVALID_COOKIE
);
1394 if (is_zero_cookie(md
->hdr
.isa_rcookie
))
1396 plog("Quick Mode message is invalid because"
1397 " it has a Responder Cookie of 0");
1398 SEND_NOTIFICATION(INVALID_COOKIE
);
1402 if (md
->hdr
.isa_msgid
== MAINMODE_MSGID
)
1404 plog("Quick Mode message is invalid because"
1405 " it has a Message ID of 0");
1406 SEND_NOTIFICATION(INVALID_MESSAGE_ID
);
1410 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1411 , &md
->sender
, md
->hdr
.isa_msgid
);
1415 /* No appropriate Quick Mode state.
1416 * See if we have a Main Mode state.
1417 * ??? what if this is a duplicate of another message?
1419 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1420 , &md
->sender
, MAINMODE_MSGID
);
1424 plog("Quick Mode message is for a non-existent (expired?)"
1426 /* XXX Could send notification back */
1430 if (st
->st_state
== STATE_MODE_CFG_R2
) /* Have we just give an IP address to peer? */
1432 st
->st_state
= STATE_MAIN_R3
; /* ISAKMP is up... */
1437 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1439 loglog(RC_LOG_SERIOUS
, "Quick Mode message is unacceptable because"
1440 " it is for an incomplete ISAKMP SA");
1441 SEND_NOTIFICATION(PAYLOAD_MALFORMED
/* XXX ? */);
1445 /* only accept this new Quick Mode exchange if it has a unique message ID */
1446 if (!reserve_msgid(st
, md
->hdr
.isa_msgid
))
1448 loglog(RC_LOG_SERIOUS
, "Quick Mode I1 message is unacceptable because"
1449 " it uses a previously used Message ID 0x%08lx"
1450 " (perhaps this is a duplicated packet)"
1451 , (unsigned long) md
->hdr
.isa_msgid
);
1452 SEND_NOTIFICATION(INVALID_MESSAGE_ID
);
1456 /* Quick Mode Initial IV */
1457 init_phase2_iv(st
, &md
->hdr
.isa_msgid
);
1460 from_state
= STATE_QUICK_R0
;
1465 from_state
= st
->st_state
;
1470 case ISAKMP_XCHG_MODE_CFG
:
1471 if (is_zero_cookie(md
->hdr
.isa_icookie
))
1473 plog("Mode Config message is invalid because"
1474 " it has an Initiator Cookie of 0");
1475 /* XXX Could send notification back */
1479 if (is_zero_cookie(md
->hdr
.isa_rcookie
))
1481 plog("Mode Config message is invalid because"
1482 " it has a Responder Cookie of 0");
1483 /* XXX Could send notification back */
1487 if (md
->hdr
.isa_msgid
== 0)
1489 plog("Mode Config message is invalid because"
1490 " it has a Message ID of 0");
1491 /* XXX Could send notification back */
1495 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1496 , &md
->sender
, md
->hdr
.isa_msgid
);
1500 /* No appropriate Mode Config state.
1501 * See if we have a Main Mode state.
1502 * ??? what if this is a duplicate of another message?
1504 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1509 plog("Mode Config message is for a non-existent (expired?)"
1511 /* XXX Could send notification back */
1517 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1519 loglog(RC_LOG_SERIOUS
, "Mode Config message is unacceptable because"
1520 " it is for an incomplete ISAKMP SA (state=%s)"
1521 , enum_name(&state_names
, st
->st_state
));
1522 /* XXX Could send notification back */
1525 init_phase2_iv(st
, &md
->hdr
.isa_msgid
);
1529 * okay, now we have to figure out if we are receiving a bogus
1530 * new message in an oustanding XAUTH server conversation
1531 * (i.e. a reply to our challenge)
1532 * (this occurs with some broken other implementations).
1534 * or if receiving for the first time, an XAUTH challenge.
1536 * or if we are getting a MODECFG request.
1538 * we distinguish these states because we can not both be an
1539 * XAUTH server and client, and our policy tells us which
1542 * to complicate further, it is normal to start a new msgid
1543 * when going from one state to another, or when restarting
1548 if (st
->st_connection
->spd
.that
.modecfg
1549 && IS_PHASE1(st
->st_state
))
1551 from_state
= STATE_MODE_CFG_R0
;
1553 else if (st
->st_connection
->spd
.this.modecfg
1554 && IS_PHASE1(st
->st_state
))
1556 from_state
= STATE_MODE_CFG_I2
;
1560 /* XXX check if we are being a mode config server here */
1561 plog("received MODECFG message when in state %s, and we aren't mode config client"
1562 , enum_name(&state_names
, st
->st_state
));
1569 from_state
= st
->st_state
;
1575 case ISAKMP_XCHG_NGRP
:
1576 case ISAKMP_XCHG_ACK_INFO
:
1580 plog("unsupported exchange type %s in message"
1581 , enum_show(&exchange_names
, md
->hdr
.isa_xchg
));
1582 SEND_NOTIFICATION(UNSUPPORTED_EXCHANGE_TYPE
);
1586 /* We have found a from_state, and perhaps a state object.
1587 * If we need to build a new state object,
1588 * we wait until the packet has been sanity checked.
1591 /* We don't support the Commit Flag. It is such a bad feature.
1592 * It isn't protected -- neither encrypted nor authenticated.
1593 * A man in the middle turns it on, leading to DoS.
1594 * We just ignore it, with a warning.
1595 * By placing the check here, we could easily add a policy bit
1596 * to a connection to suppress the warning. This might be useful
1597 * because the Commit Flag is expected from some peers.
1599 if (md
->hdr
.isa_flags
& ISAKMP_FLAG_COMMIT
)
1601 plog("IKE message has the Commit Flag set but Pluto doesn't implement this feature; ignoring flag");
1604 /* Set smc to describe this state's properties.
1605 * Look up the appropriate microcode based on state and
1606 * possibly Oakley Auth type.
1608 passert(STATE_IKE_FLOOR
<= from_state
&& from_state
<= STATE_IKE_ROOF
);
1609 smc
= ike_microcode_index
[from_state
- STATE_IKE_FLOOR
];
1613 while (!LHAS(smc
->flags
, st
->st_oakley
.auth
))
1616 passert(smc
->state
== from_state
);
1620 /* Ignore a packet if the state has a suspended state transition
1621 * Probably a duplicated packet but the original packet is not yet
1622 * recorded in st->st_rpacket, so duplicate checking won't catch.
1623 * ??? Should the packet be recorded earlier to improve diagnosis?
1625 if (st
!= NULL
&& st
->st_suspended_md
!= NULL
)
1627 loglog(RC_LOG
, "discarding packet received during DNS lookup in %s"
1628 , enum_name(&state_names
, st
->st_state
));
1632 /* Detect and handle duplicated packets.
1633 * This won't work for the initial packet of an exchange
1634 * because we won't have a state object to remember it.
1635 * If we are in a non-receiving state (terminal), and the preceding
1636 * state did transmit, then the duplicate may indicate that that
1637 * transmission wasn't received -- retransmit it.
1638 * Otherwise, just discard it.
1639 * ??? Notification packets are like exchanges -- I hope that
1640 * they are idempotent!
1643 && st
->st_rpacket
.ptr
!= NULL
1644 && st
->st_rpacket
.len
== pbs_room(&md
->packet_pbs
)
1645 && memcmp(st
->st_rpacket
.ptr
, md
->packet_pbs
.start
, st
->st_rpacket
.len
) == 0)
1647 if (smc
->flags
& SMF_RETRANSMIT_ON_DUPLICATE
)
1649 if (st
->st_retransmit
< MAXIMUM_RETRANSMISSIONS
)
1651 st
->st_retransmit
++;
1652 loglog(RC_RETRANSMISSION
1653 , "retransmitting in response to duplicate packet; already %s"
1654 , enum_name(&state_names
, st
->st_state
));
1655 send_packet(st
, "retransmit in response to duplicate");
1659 loglog(RC_LOG_SERIOUS
, "discarding duplicate packet -- exhausted retransmission; already %s"
1660 , enum_name(&state_names
, st
->st_state
));
1665 loglog(RC_LOG_SERIOUS
, "discarding duplicate packet; already %s"
1666 , enum_name(&state_names
, st
->st_state
));
1671 if (md
->hdr
.isa_flags
& ISAKMP_FLAG_ENCRYPTION
)
1673 DBG(DBG_CRYPT
, DBG_log("received encrypted packet from %s:%u"
1674 , ip_str(&md
->sender
), (unsigned)md
->sender_port
));
1678 plog("discarding encrypted message for an unknown ISAKMP SA");
1679 SEND_NOTIFICATION(PAYLOAD_MALFORMED
/* XXX ? */);
1682 if (st
->st_skeyid_e
.ptr
== (u_char
*) NULL
)
1684 loglog(RC_LOG_SERIOUS
, "discarding encrypted message"
1685 " because we haven't yet negotiated keying materiel");
1686 SEND_NOTIFICATION(INVALID_FLAGS
);
1690 /* Mark as encrypted */
1691 md
->encrypted
= TRUE
;
1693 DBG(DBG_CRYPT
, DBG_log("decrypting %u bytes using algorithm %s"
1694 , (unsigned) pbs_left(&md
->message_pbs
)
1695 , enum_show(&oakley_enc_names
, st
->st_oakley
.encrypt
)));
1697 /* do the specified decryption
1699 * IV is from st->st_iv or (if new_iv_set) st->st_new_iv.
1700 * The new IV is placed in st->st_new_iv
1702 * See RFC 2409 "IKE" Appendix B
1704 * XXX The IV should only be updated really if the packet
1705 * is successfully processed.
1706 * We should keep this value, check for a success return
1707 * value from the parsing routines and then replace.
1709 * Each post phase 1 exchange generates IVs from
1710 * the last phase 1 block, not the last block sent.
1713 const struct encrypt_desc
*e
= st
->st_oakley
.encrypter
;
1715 if (pbs_left(&md
->message_pbs
) % e
->enc_blocksize
!= 0)
1717 loglog(RC_LOG_SERIOUS
, "malformed message: not a multiple of encryption blocksize");
1718 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1722 /* XXX Detect weak keys */
1724 /* grab a copy of raw packet (for duplicate packet detection) */
1725 clonetochunk(md
->raw_packet
, md
->packet_pbs
.start
1726 , pbs_room(&md
->packet_pbs
), "raw packet");
1728 /* Decrypt everything after header */
1732 passert(st
->st_iv_len
<= sizeof(st
->st_new_iv
));
1733 st
->st_new_iv_len
= st
->st_iv_len
;
1734 memcpy(st
->st_new_iv
, st
->st_iv
, st
->st_new_iv_len
);
1736 crypto_cbc_encrypt(e
, FALSE
, md
->message_pbs
.cur
,
1737 pbs_left(&md
->message_pbs
) , st
);
1740 memcpy(st
->st_new_iv
, new_iv
, new_iv_len
);
1741 st
->st_new_iv_len
= new_iv_len
;
1745 DBG_cond_dump(DBG_CRYPT
, "decrypted:\n", md
->message_pbs
.cur
1746 , md
->message_pbs
.roof
- md
->message_pbs
.cur
);
1748 DBG_cond_dump(DBG_CRYPT
, "next IV:"
1749 , st
->st_new_iv
, st
->st_new_iv_len
);
1753 /* packet was not encryped -- should it have been? */
1755 if (smc
->flags
& SMF_INPUT_ENCRYPTED
)
1757 loglog(RC_LOG_SERIOUS
, "packet rejected: should have been encrypted");
1758 SEND_NOTIFICATION(INVALID_FLAGS
);
1763 /* Digest the message.
1764 * Padding must be removed to make hashing work.
1765 * Padding comes from encryption (so this code must be after decryption).
1766 * Padding rules are described before the definition of
1767 * struct isakmp_hdr in packet.h.
1770 struct payload_digest
*pd
= md
->digest
;
1771 int np
= md
->hdr
.isa_np
;
1772 lset_t needed
= smc
->req_payloads
;
1774 = LIN(SMF_PSK_AUTH
| SMF_FIRST_ENCRYPTED_INPUT
, smc
->flags
)
1775 ?
"probable authentication failure (mismatch of preshared secrets?): "
1778 while (np
!= ISAKMP_NEXT_NONE
)
1780 struct_desc
*sd
= np
< ISAKMP_NEXT_ROOF? payload_descs
[np
] : NULL
;
1782 if (pd
== &md
->digest
[PAYLIMIT
])
1784 loglog(RC_LOG_SERIOUS
, "more than %d payloads in message; ignored", PAYLIMIT
);
1785 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1791 case ISAKMP_NEXT_NATD_RFC
:
1792 case ISAKMP_NEXT_NATOA_RFC
:
1793 if (!st
|| !(st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
))
1796 * don't accept NAT-D/NAT-OA reloc directly in message, unless
1797 * we're using NAT-T RFC
1806 /* payload type is out of range or requires special handling */
1809 case ISAKMP_NEXT_ID
:
1810 sd
= IS_PHASE1(from_state
)
1811 ?
&isakmp_identification_desc
: &isakmp_ipsec_identification_desc
;
1813 case ISAKMP_NEXT_NATD_DRAFTS
:
1814 np
= ISAKMP_NEXT_NATD_RFC
; /* NAT-D relocated */
1815 sd
= payload_descs
[np
];
1817 case ISAKMP_NEXT_NATOA_DRAFTS
:
1818 np
= ISAKMP_NEXT_NATOA_RFC
; /* NAT-OA relocated */
1819 sd
= payload_descs
[np
];
1822 loglog(RC_LOG_SERIOUS
, "%smessage ignored because it contains an unknown or"
1823 " unexpected payload type (%s) at the outermost level"
1824 , excuse
, enum_show(&payload_names
, np
));
1825 SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE
);
1831 lset_t s
= LELEM(np
);
1834 , needed
| smc
->opt_payloads
| LELEM(ISAKMP_NEXT_N
) | LELEM(ISAKMP_NEXT_D
)))
1836 loglog(RC_LOG_SERIOUS
, "%smessage ignored because it "
1837 "contains an unexpected payload type (%s)"
1838 , excuse
, enum_show(&payload_names
, np
));
1839 SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE
);
1845 if (!in_struct(&pd
->payload
, sd
, &md
->message_pbs
, &pd
->pbs
))
1847 loglog(RC_LOG_SERIOUS
, "%smalformed payload in packet", excuse
);
1848 if (md
->hdr
.isa_xchg
!= ISAKMP_XCHG_INFO
)
1849 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1853 /* place this payload at the end of the chain for this type */
1855 struct payload_digest
**p
;
1857 for (p
= &md
->chain
[np
]; *p
!= NULL
; p
= &(*p
)->next
)
1863 np
= pd
->payload
.generic
.isag_np
;
1866 /* since we've digested one payload happily, it is probably
1867 * the case that any decryption worked. So we will not suggest
1868 * encryption failure as an excuse for subsequent payload
1874 md
->digest_roof
= pd
;
1877 if (pbs_left(&md
->message_pbs
) != 0)
1878 DBG_log("removing %d bytes of padding", (int) pbs_left(&md
->message_pbs
)));
1880 md
->message_pbs
.roof
= md
->message_pbs
.cur
;
1882 /* check that all mandatory payloads appeared */
1886 loglog(RC_LOG_SERIOUS
, "message for %s is missing payloads %s"
1887 , enum_show(&state_names
, from_state
)
1888 , bitnamesof(payload_name
, needed
));
1889 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1894 /* more sanity checking: enforce most ordering constraints */
1896 if (IS_PHASE1(from_state
))
1898 /* rfc2409: The Internet Key Exchange (IKE), 5 Exchanges:
1899 * "The SA payload MUST precede all other payloads in a phase 1 exchange."
1901 if (md
->chain
[ISAKMP_NEXT_SA
] != NULL
1902 && md
->hdr
.isa_np
!= ISAKMP_NEXT_SA
)
1904 loglog(RC_LOG_SERIOUS
, "malformed Phase 1 message: does not start with an SA payload");
1905 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1909 else if (IS_QUICK(from_state
))
1911 /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode
1913 * "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
1914 * header and a SA payload MUST immediately follow the HASH."
1915 * [NOTE: there may be more than one SA payload, so this is not
1916 * totally reasonable. Probably all SAs should be so constrained.]
1918 * "If ISAKMP is acting as a client negotiator on behalf of another
1919 * party, the identities of the parties MUST be passed as IDci and
1922 * "With the exception of the HASH, SA, and the optional ID payloads,
1923 * there are no payload ordering restrictions on Quick Mode."
1926 if (md
->hdr
.isa_np
!= ISAKMP_NEXT_HASH
)
1928 loglog(RC_LOG_SERIOUS
, "malformed Quick Mode message: does not start with a HASH payload");
1929 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1934 struct payload_digest
*p
;
1937 for (p
= md
->chain
[ISAKMP_NEXT_SA
], i
= 1; p
!= NULL
1940 if (p
!= &md
->digest
[i
])
1942 loglog(RC_LOG_SERIOUS
, "malformed Quick Mode message: SA payload is in wrong position");
1943 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1949 /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode:
1950 * "If ISAKMP is acting as a client negotiator on behalf of another
1951 * party, the identities of the parties MUST be passed as IDci and
1955 struct payload_digest
*id
= md
->chain
[ISAKMP_NEXT_ID
];
1959 if (id
->next
== NULL
|| id
->next
->next
!= NULL
)
1961 loglog(RC_LOG_SERIOUS
, "malformed Quick Mode message:"
1962 " if any ID payload is present,"
1963 " there must be exactly two");
1964 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1967 if (id
+1 != id
->next
)
1969 loglog(RC_LOG_SERIOUS
, "malformed Quick Mode message:"
1970 " the ID payloads are not adjacent");
1971 SEND_NOTIFICATION(PAYLOAD_MALFORMED
);
1978 /* Ignore payloads that we don't handle:
1979 * Delete, Notification, VendorID
1981 /* XXX Handle deletions */
1982 /* XXX Handle Notifications */
1983 /* XXX Handle VID payloads */
1985 struct payload_digest
*p
;
1987 for (p
= md
->chain
[ISAKMP_NEXT_N
]; p
!= NULL
; p
= p
->next
)
1989 if (p
->payload
.notification
.isan_type
!= R_U_THERE
1990 && p
->payload
.notification
.isan_type
!= R_U_THERE_ACK
)
1992 loglog(RC_LOG_SERIOUS
, "ignoring informational payload, type %s"
1993 , enum_show(¬ification_names
, p
->payload
.notification
.isan_type
));
1995 DBG_cond_dump(DBG_PARSING
, "info:", p
->pbs
.cur
, pbs_left(&p
->pbs
));
1998 for (p
= md
->chain
[ISAKMP_NEXT_D
]; p
!= NULL
; p
= p
->next
)
2000 accept_delete(st
, md
, p
);
2001 DBG_cond_dump(DBG_PARSING
, "del:", p
->pbs
.cur
, pbs_left(&p
->pbs
));
2004 for (p
= md
->chain
[ISAKMP_NEXT_VID
]; p
!= NULL
; p
= p
->next
)
2006 handle_vendorid(md
, p
->pbs
.cur
, pbs_left(&p
->pbs
));
2009 md
->from_state
= from_state
;
2013 /* possibly fill in hdr */
2014 if (smc
->first_out_payload
!= ISAKMP_NEXT_NONE
)
2015 echo_hdr(md
, (smc
->flags
& SMF_OUTPUT_ENCRYPTED
) != 0
2016 , smc
->first_out_payload
);
2018 complete_state_transition(mdp
, smc
->processor(md
));
2021 /* complete job started by the state-specific state transition function */
2024 complete_state_transition(struct msg_digest
**mdp
, stf_status result
)
2026 struct msg_digest
*md
= *mdp
;
2027 const struct state_microcode
*smc
= md
->smc
;
2028 enum state_kind from_state
= md
->from_state
;
2031 cur_state
= st
= md
->st
; /* might have changed */
2033 /* If state has DPD support, import it */
2043 /* the stf didn't complete its job: don't relase md */
2048 /* advance the state */
2049 st
->st_state
= smc
->next_state
;
2051 /* Delete previous retransmission event.
2052 * New event will be scheduled below.
2056 /* replace previous receive packet with latest */
2058 pfreeany(st
->st_rpacket
.ptr
);
2062 /* if encrypted, duplication already done */
2063 st
->st_rpacket
= md
->raw_packet
;
2064 md
->raw_packet
.ptr
= NULL
;
2068 clonetochunk(st
->st_rpacket
2069 , md
->packet_pbs
.start
2070 , pbs_room(&md
->packet_pbs
), "raw packet");
2073 /* free previous transmit packet */
2074 freeanychunk(st
->st_tpacket
);
2076 /* if requested, send the new reply packet */
2077 if (smc
->flags
& SMF_REPLY
)
2079 close_output_pbs(&md
->reply
); /* good form, but actually a no-op */
2081 clonetochunk(st
->st_tpacket
, md
->reply
.start
2082 , pbs_offset(&md
->reply
), "reply packet");
2084 if (nat_traversal_enabled
)
2085 nat_traversal_change_port_lookup(md
, md
->st
);
2087 /* actually send the packet
2088 * Note: this is a great place to implement "impairments"
2089 * for testing purposes. Suppress or duplicate the
2090 * send_packet call depending on st->st_state.
2092 send_packet(st
, enum_name(&state_names
, from_state
));
2095 /* Schedule for whatever timeout is specified */
2098 enum event_type kind
= smc
->timeout_event
;
2099 bool agreed_time
= FALSE
;
2100 struct connection
*c
= st
->st_connection
;
2104 case EVENT_RETRANSMIT
: /* Retransmit packet */
2105 delay
= EVENT_RETRANSMIT_DELAY_0
;
2108 case EVENT_SA_REPLACE
: /* SA replacement event */
2109 if (IS_PHASE1(st
->st_state
))
2111 /* Note: we will defer to the "negotiated" (dictated)
2112 * lifetime if we are POLICY_DONT_REKEY.
2113 * This allows the other side to dictate
2114 * a time we would not otherwise accept
2115 * but it prevents us from having to initiate
2116 * rekeying. The negative consequences seem
2119 delay
= c
->sa_ike_life_seconds
;
2120 if ((c
->policy
& POLICY_DONT_REKEY
)
2121 || delay
>= st
->st_oakley
.life_seconds
)
2124 delay
= st
->st_oakley
.life_seconds
;
2129 /* Delay is min of up to four things:
2130 * each can limit the lifetime.
2132 delay
= c
->sa_ipsec_life_seconds
;
2133 if (st
->st_ah
.present
2134 && delay
>= st
->st_ah
.attrs
.life_seconds
)
2137 delay
= st
->st_ah
.attrs
.life_seconds
;
2139 if (st
->st_esp
.present
2140 && delay
>= st
->st_esp
.attrs
.life_seconds
)
2143 delay
= st
->st_esp
.attrs
.life_seconds
;
2145 if (st
->st_ipcomp
.present
2146 && delay
>= st
->st_ipcomp
.attrs
.life_seconds
)
2149 delay
= st
->st_ipcomp
.attrs
.life_seconds
;
2153 /* By default, we plan to rekey.
2155 * If there isn't enough time to rekey, plan to
2158 * If we are --dontrekey, a lot more rules apply.
2159 * If we are the Initiator, use REPLACE_IF_USED.
2160 * If we are the Responder, and the dictated time
2161 * was unacceptable (too large), plan to REPLACE
2162 * (the only way to ratchet down the time).
2163 * If we are the Responder, and the dictated time
2164 * is acceptable, plan to EXPIRE.
2166 * Important policy lies buried here.
2167 * For example, we favour the initiator over the
2168 * responder by making the initiator start rekeying
2169 * sooner. Also, fuzz is only added to the
2170 * initiator's margin.
2172 * Note: for ISAKMP SA, we let the negotiated
2173 * time stand (implemented by earlier logic).
2176 && (c
->policy
& POLICY_DONT_REKEY
))
2178 kind
= (smc
->flags
& SMF_INITIATOR
)
2179 ? EVENT_SA_REPLACE_IF_USED
2182 if (kind
!= EVENT_SA_EXPIRE
)
2184 unsigned long marg
= c
->sa_rekey_margin
;
2186 if (smc
->flags
& SMF_INITIATOR
)
2188 * c
->sa_rekey_fuzz
/ 100.E0
2189 * (rand() / (RAND_MAX
+ 1.E0
));
2193 if ((unsigned long)delay
> marg
)
2196 st
->st_margin
= marg
;
2200 kind
= EVENT_SA_EXPIRE
;
2205 case EVENT_NULL
: /* non-event */
2206 case EVENT_REINIT_SECRET
: /* Refresh cookie secret */
2210 event_schedule(kind
, delay
, st
);
2213 /* tell whack and log of progress */
2215 const char *story
= state_story
[st
->st_state
- STATE_MAIN_R0
];
2216 enum rc_type w
= RC_NEW_STATE
+ st
->st_state
;
2217 char sadetails
[128];
2221 if (IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
2223 char *b
= sadetails
;
2224 const char *ini
= " {";
2225 const char *fin
= "";
2227 /* -1 is to leave space for "fin" */
2229 if (st
->st_esp
.present
)
2231 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2232 , "%sESP=>0x%08x <0x%08x"
2234 , ntohl(st
->st_esp
.attrs
.spi
)
2235 , ntohl(st
->st_esp
.our_spi
));
2239 /* advance b to end of string */
2242 if (st
->st_ah
.present
)
2244 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2245 , "%sAH=>0x%08x <0x%08x"
2247 , ntohl(st
->st_ah
.attrs
.spi
)
2248 , ntohl(st
->st_ah
.our_spi
));
2252 /* advance b to end of string */
2255 if (st
->st_ipcomp
.present
)
2257 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2258 , "%sIPCOMP=>0x%08x <0x%08x"
2260 , ntohl(st
->st_ipcomp
.attrs
.spi
)
2261 , ntohl(st
->st_ipcomp
.our_spi
));
2265 /* advance b to end of string */
2268 if (st
->nat_traversal
)
2270 char oa
[ADDRTOT_BUF
];
2271 addrtot(&st
->nat_oa
, 0, oa
, sizeof(oa
));
2272 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2279 /* advance b to end of string */
2284 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2294 if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2295 || IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
2297 /* log our success */
2298 plog("%s%s", story
, sadetails
);
2302 /* tell whack our progress */
2305 , enum_name(&state_names
, st
->st_state
)
2306 , story
, sadetails
);
2309 /* Should we start ModeConfig as a client? */
2310 if (st
->st_connection
->spd
.this.modecfg
2311 && IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2312 && !(st
->st_connection
->policy
& POLICY_MODECFG_PUSH
)
2313 && !st
->st_modecfg
.started
)
2316 DBG_log("starting ModeCfg client in pull mode")
2318 modecfg_send_request(st
);
2322 /* Should we start ModeConfig as a server? */
2323 if (st
->st_connection
->spd
.that
.modecfg
2324 && IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2325 && !st
->st_modecfg
.started
2326 && (st
->st_connection
->policy
& POLICY_MODECFG_PUSH
))
2329 DBG_log("starting ModeCfg server in push mode")
2331 modecfg_send_set(st
);
2335 /* Wait for ModeConfig set from server */
2336 if (st
->st_connection
->spd
.this.modecfg
2337 && IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2338 && !st
->st_modecfg
.vars_set
)
2341 DBG_log("waiting for ModeCfg set from server")
2346 if (smc
->flags
& SMF_RELEASE_PENDING_P2
)
2348 /* Initiate any Quick Mode negotiations that
2349 * were waiting to piggyback on this Keying Channel.
2351 * ??? there is a potential race condition
2352 * if we are the responder: the initial Phase 2
2353 * message might outrun the final Phase 1 message.
2354 * I think that retransmission will recover.
2359 if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2360 || IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
2364 case STF_INTERNAL_ERROR
:
2365 whack_log(RC_INTERNALERR
+ md
->note
2366 , "%s: internal error"
2367 , enum_name(&state_names
, st
->st_state
));
2370 DBG_log("state transition function for %s had internal error"
2371 , enum_name(&state_names
, from_state
)));
2374 default: /* a shortcut to STF_FAIL, setting md->note */
2375 passert(result
> STF_FAIL
);
2376 md
->note
= result
- STF_FAIL
;
2378 /* FALL THROUGH ... */
2380 /* As it is, we act as if this message never happened:
2381 * whatever retrying was in place, remains in place.
2383 whack_log(RC_NOTIFICATION
+ md
->note
2385 , enum_name(&state_names
, (st
== NULL
)? STATE_MAIN_R0
:st
->st_state
)
2386 , enum_name(¬ification_names
, md
->note
));
2388 SEND_NOTIFICATION(md
->note
);
2391 DBG_log("state transition function for %s failed: %s"
2392 , enum_name(&state_names
, from_state
)
2393 , enum_name(¬ification_names
, md
->note
)));