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
16 /* Ordering Constraints on Payloads
18 * rfc2409: The Internet Key Exchange (IKE)
21 * "The SA payload MUST precede all other payloads in a phase 1 exchange."
23 * "Except where otherwise noted, there are no requirements for ISAKMP
24 * payloads in any message to be in any particular order."
26 * 5.3 Phase 1 Authenticated With a Revised Mode of Public Key Encryption:
28 * "If the HASH payload is sent it MUST be the first payload of the
29 * second message exchange and MUST be followed by the encrypted
30 * nonce. If the HASH payload is not sent, the first payload of the
31 * second message exchange MUST be the encrypted nonce."
33 * "Save the requirements on the location of the optional HASH payload
34 * and the mandatory nonce payload there are no further payload
35 * requirements. All payloads-- in whatever order-- following the
36 * encrypted nonce MUST be encrypted with Ke_i or Ke_r depending on the
39 * 5.5 Phase 2 - Quick Mode
41 * "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
42 * header and a SA payload MUST immediately follow the HASH."
43 * [NOTE: there may be more than one SA payload, so this is not
44 * totally reasonable. Probably all SAs should be so constrained.]
46 * "If ISAKMP is acting as a client negotiator on behalf of another
47 * party, the identities of the parties MUST be passed as IDci and
50 * "With the exception of the HASH, SA, and the optional ID payloads,
51 * there are no payload ordering restrictions on Quick Mode."
54 /* Unfolding of Identity -- a central mystery
56 * This concerns Phase 1 identities, those of the IKE hosts.
57 * These are the only ones that are authenticated. Phase 2
58 * identities are for IPsec SAs.
60 * There are three case of interest:
62 * (1) We initiate, based on a whack command specifying a Connection.
63 * We know the identity of the peer from the Connection.
65 * (2) (to be implemented) we initiate based on a flow from our client
67 * We immediately know one of the peer's client IP addresses from
68 * the flow. We must use this to figure out the peer's IP address
69 * and Id. To be solved.
71 * (3) We respond to an IKE negotiation.
72 * We immediately know the peer's IP address.
73 * We get an ID Payload in Main I2.
75 * Unfortunately, this is too late for a number of things:
76 * - the ISAKMP SA proposals have already been made (Main I1)
77 * AND one accepted (Main R1)
78 * - the SA includes a specification of the type of ID
79 * authentication so this is negotiated without being told the ID.
80 * - with Preshared Key authentication, Main I2 is encrypted
81 * using the key, so it cannot be decoded to reveal the ID
82 * without knowing (or guessing) which key to use.
84 * There are three reasonable choices here for the responder:
85 * + assume that the initiator is making wise offers since it
86 * knows the IDs involved. We can balk later (but not gracefully)
87 * when we find the actual initiator ID
88 * + attempt to infer identity by IP address. Again, we can balk
89 * when the true identity is revealed. Actually, it is enough
90 * to infer properties of the identity (eg. SA properties and
92 * + make all properties universal so discrimination based on
93 * identity isn't required. For example, always accept the same
94 * kinds of encryption. Accept Public Key Id authentication
95 * since the Initiator presumably has our public key and thinks
96 * we must have / can find his. This approach is weakest
97 * for preshared key since the actual key must be known to
98 * decrypt the Initiator's ID Payload.
99 * These choices can be blended. For example, a class of Identities
100 * can be inferred, sufficient to select a preshared key but not
101 * sufficient to infer a unique identity.
110 #include <sys/types.h>
111 #include <sys/time.h> /* only used for belt-and-suspenders select call */
112 #include <sys/poll.h> /* only used for forensic poll call */
113 #include <sys/socket.h>
114 #include <sys/ioctl.h>
115 #include <netinet/in.h>
116 #include <arpa/inet.h>
117 #include <sys/queue.h>
119 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
120 # include <asm/types.h> /* for __u8, __u32 */
121 # include <linux/errqueue.h>
122 # include <sys/uio.h> /* struct iovec */
125 #include <freeswan.h>
127 #include "constants.h"
130 #include "connections.h"
136 #include "demux.h" /* needs packet.h */
137 #include "ipsec_doi.h" /* needs demux.h and state.h */
139 #include "whack.h" /* requires connections.h */
141 #include "nat_traversal.h"
145 /* This file does basic header checking and demux of
149 /* forward declarations */
150 static bool read_packet(struct msg_digest
*md
);
151 static void process_packet(struct msg_digest
**mdp
);
153 /* Reply messages are built in this buffer.
154 * Only one state transition function can be using it at a time
155 * so suspended STFs must save and restore it.
156 * It could be an auto variable of complete_state_transition except for the fact
157 * that when a suspended STF resumes, its reply message buffer
158 * must be at the same location -- there are pointers into it.
160 u_int8_t reply_buffer
[MAX_OUTPUT_UDP_SIZE
];
162 /* state_microcode is a tuple of information parameterizing certain
163 * centralized processing of a packet. For example, it roughly
164 * specifies what payloads are expected in this message.
165 * The microcode is selected primarily based on the state.
166 * In Phase 1, the payload structure often depends on the
167 * authentication technique, so that too plays a part in selecting
168 * the state_microcode to use.
171 struct state_microcode
{
172 enum state_kind state
, next_state
;
174 lset_t req_payloads
; /* required payloads (allows just one) */
175 lset_t opt_payloads
; /* optional payloads (any mumber) */
176 /* if not ISAKMP_NEXT_NONE, process_packet will emit HDR with this as np */
177 u_int8_t first_out_payload
;
178 enum event_type timeout_event
;
179 state_transition_fn
*processor
;
182 /* State Microcode Flags, in several groups */
184 /* Oakley Auth values: to which auth values does this entry apply?
185 * Most entries will use SMF_ALL_AUTH because they apply to all.
186 * Note: SMF_ALL_AUTH matches 0 for those circumstances when no auth
189 #define SMF_ALL_AUTH LRANGE(0, OAKLEY_AUTH_ROOF-1)
190 #define SMF_PSK_AUTH LELEM(OAKLEY_PRESHARED_KEY)
191 #define SMF_DS_AUTH (LELEM(OAKLEY_DSS_SIG) | LELEM(OAKLEY_RSA_SIG) | \
192 LELEM(OAKLEY_ECDSA_SIG) | LELEM(OAKLEY_ECDSA_256) | \
193 LELEM(OAKLEY_ECDSA_384) | LELEM(OAKLEY_ECDSA_521))
194 #define SMF_PKE_AUTH (LELEM(OAKLEY_RSA_ENC) | LELEM(OAKLEY_ELGAMAL_ENC))
195 #define SMF_RPKE_AUTH (LELEM(OAKLEY_RSA_ENC_REV) | LELEM(OAKLEY_ELGAMAL_ENC_REV))
199 #define SMF_INITIATOR LELEM(OAKLEY_AUTH_ROOF + 0)
200 #define SMF_FIRST_ENCRYPTED_INPUT LELEM(OAKLEY_AUTH_ROOF + 1)
201 #define SMF_INPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 2)
202 #define SMF_OUTPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 3)
203 #define SMF_RETRANSMIT_ON_DUPLICATE LELEM(OAKLEY_AUTH_ROOF + 4)
205 #define SMF_ENCRYPTED (SMF_INPUT_ENCRYPTED | SMF_OUTPUT_ENCRYPTED)
207 /* this state generates a reply message */
208 #define SMF_REPLY LELEM(OAKLEY_AUTH_ROOF + 5)
210 /* this state completes P1, so any pending P2 negotiations should start */
211 #define SMF_RELEASE_PENDING_P2 LELEM(OAKLEY_AUTH_ROOF + 6)
216 static state_transition_fn
/* forward declaration */
220 /* state_microcode_table is a table of all state_microcode tuples.
221 * It must be in order of state (the first element).
222 * After initialization, ike_microcode_index[s] points to the
223 * first entry in state_microcode_table for state s.
224 * Remember that each state name in Main or Quick Mode describes
225 * what has happened in the past, not what this message is.
228 static const struct state_microcode
229 *ike_microcode_index
[STATE_IKE_ROOF
- STATE_IKE_FLOOR
];
231 static const struct state_microcode state_microcode_table
[] = {
232 #define PT(n) ISAKMP_NEXT_##n
233 #define P(n) LELEM(PT(n))
235 /***** Phase 1 Main Mode *****/
237 /* No state for main_outI1: --> HDR, SA */
239 /* STATE_MAIN_R0: I1 --> R1
240 * HDR, SA --> HDR, SA
242 { STATE_MAIN_R0
, STATE_MAIN_R1
243 , SMF_ALL_AUTH
| SMF_REPLY
244 , P(SA
), P(VID
) | P(CR
), PT(NONE
)
245 , EVENT_RETRANSMIT
, main_inI1_outR1
},
247 /* STATE_MAIN_I1: R1 --> I2
248 * HDR, SA --> auth dependent
249 * SMF_PSK_AUTH, SMF_DS_AUTH: --> HDR, KE, Ni
251 * --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
253 * --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
254 * Note: since we don't know auth at start, we cannot differentiate
255 * microcode entries based on it.
257 { STATE_MAIN_I1
, STATE_MAIN_I2
258 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_REPLY
259 , P(SA
), P(VID
) | P(CR
), PT(NONE
) /* don't know yet */
260 , EVENT_RETRANSMIT
, main_inR1_outI2
},
262 /* STATE_MAIN_R1: I2 --> R2
263 * SMF_PSK_AUTH, SMF_DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
264 * SMF_PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
265 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
267 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
268 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
270 { STATE_MAIN_R1
, STATE_MAIN_R2
271 , SMF_PSK_AUTH
| SMF_DS_AUTH
| SMF_REPLY
272 , P(KE
) | P(NONCE
), P(VID
) | P(CR
) | P(NATD_RFC
), PT(KE
)
273 , EVENT_RETRANSMIT
, main_inI2_outR2
},
275 { STATE_MAIN_R1
, STATE_UNDEFINED
276 , SMF_PKE_AUTH
| SMF_REPLY
277 , P(KE
) | P(ID
) | P(NONCE
), P(VID
) | P(CR
) | P(HASH
), PT(KE
)
278 , EVENT_RETRANSMIT
, unexpected
/* ??? not yet implemented */ },
280 { STATE_MAIN_R1
, STATE_UNDEFINED
281 , SMF_RPKE_AUTH
| SMF_REPLY
282 , P(NONCE
) | P(KE
) | P(ID
), P(VID
) | P(CR
) | P(HASH
) | P(CERT
), PT(NONCE
)
283 , EVENT_RETRANSMIT
, unexpected
/* ??? not yet implemented */ },
285 /* for states from here on, output message must be encrypted */
287 /* STATE_MAIN_I2: R2 --> I3
288 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
289 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
290 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
292 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
295 { STATE_MAIN_I2
, STATE_MAIN_I3
296 , SMF_PSK_AUTH
| SMF_DS_AUTH
| SMF_INITIATOR
| SMF_OUTPUT_ENCRYPTED
| SMF_REPLY
297 , P(KE
) | P(NONCE
), P(VID
) | P(CR
) | P(NATD_RFC
), PT(ID
)
298 , EVENT_RETRANSMIT
, main_inR2_outI3
},
300 { STATE_MAIN_I2
, STATE_UNDEFINED
301 , SMF_PKE_AUTH
| SMF_INITIATOR
| SMF_OUTPUT_ENCRYPTED
| SMF_REPLY
302 , P(KE
) | P(ID
) | P(NONCE
), P(VID
) | P(CR
), PT(HASH
)
303 , EVENT_RETRANSMIT
, unexpected
/* ??? not yet implemented */ },
305 { STATE_MAIN_I2
, STATE_UNDEFINED
306 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_OUTPUT_ENCRYPTED
| SMF_REPLY
307 , P(NONCE
) | P(KE
) | P(ID
), P(VID
) | P(CR
), PT(HASH
)
308 , EVENT_RETRANSMIT
, unexpected
/* ??? not yet implemented */ },
310 /* for states from here on, input message must be encrypted */
312 /* STATE_MAIN_R2: I3 --> R3
313 * SMF_PSK_AUTH: HDR*, IDi1, HASH_I --> HDR*, IDr1, HASH_R
314 * SMF_DS_AUTH: HDR*, IDi1, [ CERT, ] SIG_I --> HDR*, IDr1, [ CERT, ] SIG_R
315 * SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_I --> HDR*, HASH_R
317 { STATE_MAIN_R2
, STATE_MAIN_R3
318 , SMF_PSK_AUTH
| SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
319 | SMF_REPLY
| SMF_RELEASE_PENDING_P2
320 , P(ID
) | P(HASH
), P(VID
) | P(CR
), PT(NONE
)
321 , EVENT_SA_REPLACE
, main_inI3_outR3
},
323 { STATE_MAIN_R2
, STATE_MAIN_R3
324 , SMF_DS_AUTH
| SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
325 | SMF_REPLY
| SMF_RELEASE_PENDING_P2
326 , P(ID
) | P(SIG
), P(VID
) | P(CR
) | P(CERT
), PT(NONE
)
327 , EVENT_SA_REPLACE
, main_inI3_outR3
},
329 { STATE_MAIN_R2
, STATE_UNDEFINED
330 , SMF_PKE_AUTH
| SMF_RPKE_AUTH
| SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
331 | SMF_REPLY
| SMF_RELEASE_PENDING_P2
332 , P(HASH
), P(VID
) | P(CR
), PT(NONE
)
333 , EVENT_SA_REPLACE
, unexpected
/* ??? not yet implemented */ },
335 /* STATE_MAIN_I3: R3 --> done
336 * SMF_PSK_AUTH: HDR*, IDr1, HASH_R --> done
337 * SMF_DS_AUTH: HDR*, IDr1, [ CERT, ] SIG_R --> done
338 * SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_R --> done
339 * May initiate quick mode by calling quick_outI1
341 { STATE_MAIN_I3
, STATE_MAIN_I4
342 , SMF_PSK_AUTH
| SMF_INITIATOR
343 | SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
344 , P(ID
) | P(HASH
), P(VID
) | P(CR
), PT(NONE
)
345 , EVENT_SA_REPLACE
, main_inR3
},
347 { STATE_MAIN_I3
, STATE_MAIN_I4
348 , SMF_DS_AUTH
| SMF_INITIATOR
349 | SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
350 , P(ID
) | P(SIG
), P(VID
) | P(CR
) | P(CERT
), PT(NONE
)
351 , EVENT_SA_REPLACE
, main_inR3
},
353 { STATE_MAIN_I3
, STATE_UNDEFINED
354 , SMF_PKE_AUTH
| SMF_RPKE_AUTH
| SMF_INITIATOR
355 | SMF_FIRST_ENCRYPTED_INPUT
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
356 , P(HASH
), P(VID
) | P(CR
), PT(NONE
)
357 , EVENT_SA_REPLACE
, unexpected
/* ??? not yet implemented */ },
359 /* STATE_MAIN_R3: can only get here due to packet loss */
360 { STATE_MAIN_R3
, STATE_UNDEFINED
361 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_RETRANSMIT_ON_DUPLICATE
363 , PT(NONE
), EVENT_NULL
, unexpected
},
365 /* STATE_MAIN_I4: can only get here due to packet loss */
366 { STATE_MAIN_I4
, STATE_UNDEFINED
367 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_ENCRYPTED
369 , PT(NONE
), EVENT_NULL
, unexpected
},
372 /***** Phase 2 Quick Mode *****/
374 /* No state for quick_outI1:
375 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
379 * HDR*, HASH(1), SA, Ni [, KE ] [, IDci, IDcr ] -->
380 * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ]
381 * Installs inbound IPsec SAs.
382 * Because it may suspend for asynchronous DNS, first_out_payload
383 * is set to NONE to suppress early emission of HDR*.
384 * ??? it is legal to have multiple SAs, but we don't support it yet.
386 { STATE_QUICK_R0
, STATE_QUICK_R1
387 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_REPLY
388 , P(HASH
) | P(SA
) | P(NONCE
), /* P(SA) | */ P(KE
) | P(ID
) | P(NATOA_RFC
), PT(NONE
)
389 , EVENT_RETRANSMIT
, quick_inI1_outR1
},
392 * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ] -->
394 * Installs inbound and outbound IPsec SAs, routing, etc.
395 * ??? it is legal to have multiple SAs, but we don't support it yet.
397 { STATE_QUICK_I1
, STATE_QUICK_I2
398 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_ENCRYPTED
| SMF_REPLY
399 , P(HASH
) | P(SA
) | P(NONCE
), /* P(SA) | */ P(KE
) | P(ID
) | P(NATOA_RFC
), PT(HASH
)
400 , EVENT_SA_REPLACE
, quick_inR1_outI2
},
402 /* STATE_QUICK_R1: HDR*, HASH(3) --> done
403 * Installs outbound IPsec SAs, routing, etc.
405 { STATE_QUICK_R1
, STATE_QUICK_R2
406 , SMF_ALL_AUTH
| SMF_ENCRYPTED
407 , P(HASH
), LEMPTY
, PT(NONE
)
408 , EVENT_SA_REPLACE
, quick_inI2
},
410 /* STATE_QUICK_I2: can only happen due to lost packet */
411 { STATE_QUICK_I2
, STATE_UNDEFINED
412 , SMF_ALL_AUTH
| SMF_INITIATOR
| SMF_ENCRYPTED
| SMF_RETRANSMIT_ON_DUPLICATE
413 , LEMPTY
, LEMPTY
, PT(NONE
)
414 , EVENT_NULL
, unexpected
},
416 /* STATE_QUICK_R2: can only happen due to lost packet */
417 { STATE_QUICK_R2
, STATE_UNDEFINED
418 , SMF_ALL_AUTH
| SMF_ENCRYPTED
419 , LEMPTY
, LEMPTY
, PT(NONE
)
420 , EVENT_NULL
, unexpected
},
423 /***** informational messages *****/
426 { STATE_INFO
, STATE_UNDEFINED
428 , LEMPTY
, LEMPTY
, PT(NONE
)
429 , EVENT_NULL
, informational
},
431 /* STATE_INFO_PROTECTED: */
432 { STATE_INFO_PROTECTED
, STATE_UNDEFINED
433 , SMF_ALL_AUTH
| SMF_ENCRYPTED
434 , P(HASH
), LEMPTY
, PT(NONE
)
435 , EVENT_NULL
, informational
},
437 /* XAUTH state transitions */
438 { STATE_XAUTH_I0
, STATE_XAUTH_I1
439 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_REPLY
440 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
441 , EVENT_RETRANSMIT
, xauth_inI0
},
443 { STATE_XAUTH_R1
, STATE_XAUTH_R2
444 , SMF_ALL_AUTH
| SMF_ENCRYPTED
445 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
446 , EVENT_RETRANSMIT
, xauth_inR1
},
448 { STATE_XAUTH_I1
, STATE_XAUTH_I2
449 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_REPLY
| SMF_RELEASE_PENDING_P2
450 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
451 , EVENT_SA_REPLACE
, xauth_inI1
},
453 { STATE_XAUTH_R2
, STATE_XAUTH_R3
454 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
455 , P(ATTR
) | P(HASH
), P(VID
), PT(NONE
)
456 , EVENT_SA_REPLACE
, xauth_inR2
},
458 { STATE_XAUTH_I2
, STATE_UNDEFINED
459 , SMF_ALL_AUTH
| SMF_ENCRYPTED
460 , LEMPTY
, LEMPTY
, PT(NONE
)
461 , EVENT_NULL
, unexpected
},
463 { STATE_XAUTH_R3
, STATE_UNDEFINED
464 , SMF_ALL_AUTH
| SMF_ENCRYPTED
465 , LEMPTY
, LEMPTY
, PT(NONE
)
466 , EVENT_NULL
, unexpected
},
468 /* ModeCfg pull mode state transitions */
470 { STATE_MODE_CFG_R0
, STATE_MODE_CFG_R1
471 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_REPLY
| SMF_RELEASE_PENDING_P2
472 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
473 , EVENT_SA_REPLACE
, modecfg_inR0
},
475 { STATE_MODE_CFG_I1
, STATE_MODE_CFG_I2
476 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
477 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
478 , EVENT_SA_REPLACE
, modecfg_inI1
},
480 { STATE_MODE_CFG_R1
, STATE_UNDEFINED
481 , SMF_ALL_AUTH
| SMF_ENCRYPTED
482 , LEMPTY
, LEMPTY
, PT(NONE
)
483 , EVENT_NULL
, unexpected
},
485 { STATE_MODE_CFG_I2
, STATE_UNDEFINED
486 , SMF_ALL_AUTH
| SMF_ENCRYPTED
487 , LEMPTY
, LEMPTY
, PT(NONE
)
488 , EVENT_NULL
, unexpected
},
490 /* ModeCfg push mode state transitions */
492 { STATE_MODE_CFG_I0
, STATE_MODE_CFG_I3
493 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_REPLY
| SMF_RELEASE_PENDING_P2
494 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
495 , EVENT_SA_REPLACE
, modecfg_inI0
},
497 { STATE_MODE_CFG_R3
, STATE_MODE_CFG_R4
498 , SMF_ALL_AUTH
| SMF_ENCRYPTED
| SMF_RELEASE_PENDING_P2
499 , P(ATTR
) | P(HASH
), P(VID
), PT(HASH
)
500 , EVENT_SA_REPLACE
, modecfg_inR3
},
502 { STATE_MODE_CFG_I3
, STATE_UNDEFINED
503 , SMF_ALL_AUTH
| SMF_ENCRYPTED
504 , LEMPTY
, LEMPTY
, PT(NONE
)
505 , EVENT_NULL
, unexpected
},
507 { STATE_MODE_CFG_R4
, STATE_UNDEFINED
508 , SMF_ALL_AUTH
| SMF_ENCRYPTED
509 , LEMPTY
, LEMPTY
, PT(NONE
)
510 , EVENT_NULL
, unexpected
},
519 /* fill ike_microcode_index:
520 * make ike_microcode_index[s] point to first entry in
521 * state_microcode_table for state s (backward scan makes this easier).
522 * Check that table is in order -- catch coding errors.
523 * For what it's worth, this routine is idempotent.
525 const struct state_microcode
*t
;
527 for (t
= &state_microcode_table
[countof(state_microcode_table
) - 1];;)
529 passert(STATE_IKE_FLOOR
<= t
->state
&& t
->state
< STATE_IKE_ROOF
);
530 ike_microcode_index
[t
->state
- STATE_IKE_FLOOR
] = t
;
531 if (t
== state_microcode_table
)
534 passert(t
[0].state
<= t
[1].state
);
538 /* Process any message on the MSG_ERRQUEUE
540 * This information is generated because of the IP_RECVERR socket option.
541 * The API is sparsely documented, and may be LINUX-only, and only on
542 * fairly recent versions at that (hence the conditional compilation).
544 * - ip(7) describes IP_RECVERR
545 * - recvmsg(2) describes MSG_ERRQUEUE
546 * - readv(2) describes iovec
547 * - cmsg(3) describes how to process auxilliary messages
549 * ??? we should link this message with one we've sent
550 * so that the diagnostic can refer to that negotiation.
552 * ??? how long can the messge be?
554 * ??? poll(2) has a very incomplete description of the POLL* events.
555 * We assume that POLLIN, POLLOUT, and POLLERR are all we need to deal with
556 * and that POLLERR will be on iff there is a MSG_ERRQUEUE message.
558 * We have to code around a couple of surprises:
560 * - Select can say that a socket is ready to read from, and
561 * yet a read will hang. It turns out that a message available on the
562 * MSG_ERRQUEUE will cause select to say something is pending, but
563 * a normal read will hang. poll(2) can tell when a MSG_ERRQUEUE
564 * message is pending.
566 * This is dealt with by calling check_msg_errqueue after select
567 * has indicated that there is something to read, but before the
568 * read is performed. check_msg_errqueue will return TRUE if there
569 * is something left to read.
571 * - A write to a socket may fail because there is a pending MSG_ERRQUEUE
572 * message, without there being anything wrong with the write. This
573 * makes for confusing diagnostics.
575 * To avoid this, we call check_msg_errqueue before a write. True,
576 * there is a race condition (a MSG_ERRQUEUE message might arrive
577 * between the check and the write), but we should eliminate many
578 * of the problematic events. To narrow the window, the poll(2)
579 * will await until an event happens (in the case or a write,
580 * POLLOUT; this should be benign for POLLIN).
583 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
585 check_msg_errqueue(const struct iface
*ifp
, short interest
)
590 pfd
.events
= interest
| POLLPRI
| POLLOUT
;
592 while (pfd
.revents
= 0
593 , poll(&pfd
, 1, -1) > 0 && (pfd
.revents
& POLLERR
))
595 u_int8_t buffer
[3000]; /* hope that this is big enough */
599 struct sockaddr_in sa_in4
;
600 struct sockaddr_in6 sa_in6
;
603 int from_len
= sizeof(from
);
610 /* force alignment (not documented as necessary) */
613 /* how much space is enough? */
614 unsigned char space
[256];
618 char fromstr
[sizeof(" for message to port 65536") + INET6_ADDRSTRLEN
];
619 struct state
*sender
= NULL
;
622 from_len
= sizeof(from
);
624 emh
.msg_name
= &from
.sa
; /* ??? filled in? */
625 emh
.msg_namelen
= sizeof(from
);
628 emh
.msg_control
= &ecms_buf
;
629 emh
.msg_controllen
= sizeof(ecms_buf
);
632 eiov
.iov_base
= buffer
; /* see readv(2) */
633 eiov
.iov_len
= sizeof(buffer
);
635 packet_len
= recvmsg(ifp
->fd
, &emh
, MSG_ERRQUEUE
);
637 if (packet_len
== -1)
639 log_errno((e
, "recvmsg(,, MSG_ERRQUEUE) on %s failed in comm_handle"
643 else if (packet_len
== sizeof(buffer
))
645 plog("MSG_ERRQUEUE message longer than %lu bytes; truncated"
646 , (unsigned long) sizeof(buffer
));
650 sender
= find_sender((size_t) packet_len
, buffer
);
653 DBG_cond_dump(DBG_ALL
, "rejected packet:\n", buffer
, packet_len
);
654 DBG_cond_dump(DBG_ALL
, "control:\n", emh
.msg_control
, emh
.msg_controllen
);
655 /* ??? Andi Kleen <ak@suse.de> and misc documentation
656 * suggests that name will have the original destination
657 * of the packet. We seem to see msg_namelen == 0.
658 * Andi says that this is a kernel bug and has fixed it.
659 * Perhaps in 2.2.18/2.4.0.
661 passert(emh
.msg_name
== &from
.sa
);
662 DBG_cond_dump(DBG_ALL
, "name:\n", emh
.msg_name
665 fromstr
[0] = '\0'; /* usual case :-( */
666 switch (from
.sa
.sa_family
)
668 char as
[INET6_ADDRSTRLEN
];
671 if (emh
.msg_namelen
== sizeof(struct sockaddr_in
))
672 snprintf(fromstr
, sizeof(fromstr
)
673 , " for message to %s port %u"
674 , inet_ntop(from
.sa
.sa_family
675 , &from
.sa_in4
.sin_addr
, as
, sizeof(as
))
676 , ntohs(from
.sa_in4
.sin_port
));
679 if (emh
.msg_namelen
== sizeof(struct sockaddr_in6
))
680 snprintf(fromstr
, sizeof(fromstr
)
681 , " for message to %s port %u"
682 , inet_ntop(from
.sa
.sa_family
683 , &from
.sa_in6
.sin6_addr
, as
, sizeof(as
))
684 , ntohs(from
.sa_in6
.sin6_port
));
688 for (cm
= CMSG_FIRSTHDR(&emh
)
690 ; cm
= CMSG_NXTHDR(&emh
,cm
))
692 if (cm
->cmsg_level
== SOL_IP
693 && cm
->cmsg_type
== IP_RECVERR
)
695 /* ip(7) and recvmsg(2) specify:
696 * ee_origin is SO_EE_ORIGIN_ICMP for ICMP
697 * or SO_EE_ORIGIN_LOCAL for locally generated errors.
698 * ee_type and ee_code are from the ICMP header.
699 * ee_info is the discovered MTU for EMSGSIZE errors
700 * ee_data is not used.
702 * ??? recvmsg(2) says "SOCK_EE_OFFENDER" but
703 * means "SO_EE_OFFENDER". The OFFENDER is really
704 * the router that complained. As such, the port
708 /* ??? cmsg(3) claims that CMSG_DATA returns
709 * void *, but RFC 2292 and /usr/include/bits/socket.h
710 * say unsigned char *. The manual is being fixed.
712 struct sock_extended_err
*ee
= (void *)CMSG_DATA(cm
);
713 const char *offstr
= "unspecified";
714 char offstrspace
[INET6_ADDRSTRLEN
];
717 if (cm
->cmsg_len
> CMSG_LEN(sizeof(struct sock_extended_err
)))
719 const struct sockaddr
*offender
= SO_EE_OFFENDER(ee
);
721 switch (offender
->sa_family
)
724 offstr
= inet_ntop(offender
->sa_family
725 , &((const struct sockaddr_in
*)offender
)->sin_addr
726 , offstrspace
, sizeof(offstrspace
));
729 offstr
= inet_ntop(offender
->sa_family
730 , &((const struct sockaddr_in6
*)offender
)->sin6_addr
731 , offstrspace
, sizeof(offstrspace
));
739 switch (ee
->ee_origin
)
741 case SO_EE_ORIGIN_NONE
:
742 snprintf(orname
, sizeof(orname
), "none");
744 case SO_EE_ORIGIN_LOCAL
:
745 snprintf(orname
, sizeof(orname
), "local");
747 case SO_EE_ORIGIN_ICMP
:
748 snprintf(orname
, sizeof(orname
)
749 , "ICMP type %d code %d (not authenticated)"
750 , ee
->ee_type
, ee
->ee_code
753 case SO_EE_ORIGIN_ICMP6
:
754 snprintf(orname
, sizeof(orname
)
755 , "ICMP6 type %d code %d (not authenticated)"
756 , ee
->ee_type
, ee
->ee_code
760 snprintf(orname
, sizeof(orname
), "invalid origin %lu"
761 , (unsigned long) ee
->ee_origin
);
766 struct state
*old_state
= cur_state
;
770 /* note dirty trick to suppress ~ at start of format
771 * if we know what state to blame.
773 if ((packet_len
== 1) && (buffer
[0] = 0xff)
775 && ((cur_debugging
& DBG_NATT
) == 0)
778 /* don't log NAT-T keepalive related errors unless NATT debug is
783 plog((sender
!= NULL
) + "~"
784 "ERROR: asynchronous network error report on %s"
788 " [errno %lu, origin %s"
789 /* ", pad %d, info %ld" */
795 , strerror(ee
->ee_errno
)
796 , (unsigned long) ee
->ee_errno
798 /* , ee->ee_pad, (unsigned long)ee->ee_info */
799 /* , (unsigned long)ee->ee_data */
801 cur_state
= old_state
;
806 /* .cmsg_len is a kernel_size_t(!), but the value
807 * certainly ought to fit in an unsigned long.
809 plog("unknown cmsg: level %d, type %d, len %lu"
810 , cm
->cmsg_level
, cm
->cmsg_type
811 , (unsigned long) cm
->cmsg_len
);
815 return (pfd
.revents
& interest
) != 0;
817 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
820 send_packet(struct state
*st
, const char *where
)
822 connection_t
*c
= st
->st_connection
;
825 u_int8_t ike_pkt
[MAX_OUTPUT_UDP_SIZE
];
829 if (c
->interface
->ike_float
&& st
->st_tpacket
.len
!= 1)
831 if ((unsigned long) st
->st_tpacket
.len
> (MAX_OUTPUT_UDP_SIZE
-sizeof(u_int32_t
)))
833 DBG_log("send_packet(): really too big");
837 /** Add Non-ESP marker **/
838 memset(ike_pkt
, 0, sizeof(u_int32_t
));
839 memcpy(ike_pkt
+ sizeof(u_int32_t
), st
->st_tpacket
.ptr
,
840 (unsigned long)st
->st_tpacket
.len
);
841 len
= (unsigned long) st
->st_tpacket
.len
+ sizeof(u_int32_t
);
845 ptr
= st
->st_tpacket
.ptr
;
846 len
= (unsigned long) st
->st_tpacket
.len
;
851 DBG_log("sending %lu bytes for %s through %s to %s:%u:"
852 , (unsigned long) st
->st_tpacket
.len
854 , c
->interface
->rname
855 , ip_str(&c
->spd
.that
.host_addr
)
856 , (unsigned)c
->spd
.that
.host_port
);
857 DBG_dump_chunk(NULL
, st
->st_tpacket
);
860 /* XXX: Not very clean. We manipulate the port of the ip_address to
861 * have a port in the sockaddr*, but we retain the original port
862 * and restore it afterwards.
865 port_buf
= portof(&c
->spd
.that
.host_addr
);
866 setportof(htons(c
->spd
.that
.host_port
), &c
->spd
.that
.host_addr
);
868 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
869 (void) check_msg_errqueue(c
->interface
, POLLOUT
);
870 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
872 err
= sendto(c
->interface
->fd
874 , sockaddrof(&c
->spd
.that
.host_addr
)
875 , sockaddrlenof(&c
->spd
.that
.host_addr
)) != (ssize_t
)len
;
878 setportof(port_buf
, &c
->spd
.that
.host_addr
);
882 /* do not log NAT-T Keep Alive packets */
883 if (streq(where
, "NAT-T Keep Alive"))
885 log_errno((e
, "sendto on %s to %s:%u failed in %s"
886 , c
->interface
->rname
887 , ip_str(&c
->spd
.that
.host_addr
)
888 , (unsigned)c
->spd
.that
.host_port
899 unexpected(struct msg_digest
*md
)
901 loglog(RC_LOG_SERIOUS
, "unexpected message received in state %s"
902 , enum_name(&state_names
, md
->st
->st_state
));
907 informational(struct msg_digest
*md UNUSED
)
909 struct payload_digest
*const n_pld
= md
->chain
[ISAKMP_NEXT_N
];
911 /* If the Notification Payload is not null... */
914 pb_stream
*const n_pbs
= &n_pld
->pbs
;
915 struct isakmp_notification
*const n
= &n_pld
->payload
.notification
;
919 /* Switch on Notification Type (enum) */
920 switch (n
->isan_type
)
923 return dpd_inI_outR(md
->st
, n
, n_pbs
);
926 return dpd_inR(md
->st
, n
, n_pbs
);
928 if (pbs_left(n_pbs
) >= sizeof(disp_buf
)-1)
929 disp_len
= sizeof(disp_buf
)-1;
931 disp_len
= pbs_left(n_pbs
);
932 memcpy(disp_buf
, n_pbs
->cur
, disp_len
);
933 disp_buf
[disp_len
] = '\0';
940 /* message digest allocation and deallocation */
942 static struct msg_digest
*md_pool
= NULL
;
944 /* free_md_pool is only used to avoid leak reports */
950 struct msg_digest
*md
= md_pool
;
959 static struct msg_digest
*
962 struct msg_digest
*md
= md_pool
;
964 /* convenient initializer:
965 * - all pointers NULL
966 * - .note = NOTHING_WRONG
967 * - .encrypted = FALSE
969 static const struct msg_digest blank_md
;
973 md
= malloc_thing(struct msg_digest
);
980 md
->digest_roof
= md
->digest
;
982 /* note: although there may be multiple msg_digests at once
983 * (due to suspended state transitions), there is a single
984 * global reply_buffer. It will need to be saved and restored.
986 init_pbs(&md
->reply
, reply_buffer
, sizeof(reply_buffer
), "reply packet");
992 release_md(struct msg_digest
*md
)
994 chunk_free(&md
->raw_packet
);
995 free(md
->packet_pbs
.start
);
996 md
->packet_pbs
.start
= NULL
;
1001 /* wrapper for read_packet and process_packet
1003 * The main purpose of this wrapper is to factor out teardown code
1004 * from the many return points in process_packet. This amounts to
1005 * releasing the msg_digest and resetting global variables.
1007 * When processing of a packet is suspended (STF_SUSPEND),
1008 * process_packet sets md to NULL to prevent the msg_digest being freed.
1009 * Someone else must ensure that msg_digest is freed eventually.
1011 * read_packet is broken out to minimize the lifetime of the
1012 * enormous input packet buffer, an auto.
1015 comm_handle(const struct iface
*ifp
)
1017 static struct msg_digest
*md
;
1019 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
1020 /* Even though select(2) says that there is a message,
1021 * it might only be a MSG_ERRQUEUE message. At least
1022 * sometimes that leads to a hanging recvfrom. To avoid
1023 * what appears to be a kernel bug, check_msg_errqueue
1024 * uses poll(2) and tells us if there is anything for us
1027 * This is early enough that teardown isn't required:
1028 * just return on failure.
1030 if (!check_msg_errqueue(ifp
, POLLIN
))
1031 return; /* no normal message to read */
1032 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
1037 if (read_packet(md
))
1038 process_packet(&md
);
1044 reset_cur_connection();
1048 /* read the message.
1049 * Since we don't know its size, we read it into
1050 * an overly large buffer and then copy it to a
1051 * new, properly sized buffer.
1054 read_packet(struct msg_digest
*md
)
1056 const struct iface
*ifp
= md
->iface
;
1059 u_int8_t
*buffer_nat
;
1063 struct sockaddr_in sa_in4
;
1064 struct sockaddr_in6 sa_in6
;
1066 int from_len
= sizeof(from
);
1067 err_t from_ugh
= NULL
;
1068 static const char undisclosed
[] = "unknown source";
1070 happy(anyaddr(addrtypeof(&ifp
->addr
), &md
->sender
));
1072 ioctl(ifp
->fd
, FIONREAD
, &packet_len
);
1073 buffer
= malloc(packet_len
);
1074 packet_len
= recvfrom(ifp
->fd
, buffer
, packet_len
, 0
1075 , &from
.sa
, &from_len
);
1077 /* First: digest the from address.
1078 * We presume that nothing here disturbs errno.
1080 if (packet_len
== -1
1081 && from_len
== sizeof(from
)
1082 && all_zero((const void *)&from
.sa
, sizeof(from
)))
1084 /* "from" is untouched -- not set by recvfrom */
1085 from_ugh
= undisclosed
;
1088 < (int) (offsetof(struct sockaddr
, sa_family
) + sizeof(from
.sa
.sa_family
)))
1090 from_ugh
= "truncated";
1094 const struct af_info
*afi
= aftoinfo(from
.sa
.sa_family
);
1098 from_ugh
= "unexpected Address Family";
1100 else if (from_len
!= (int)afi
->sa_sz
)
1102 from_ugh
= "wrong length";
1106 switch (from
.sa
.sa_family
)
1109 from_ugh
= initaddr((void *) &from
.sa_in4
.sin_addr
1110 , sizeof(from
.sa_in4
.sin_addr
), AF_INET
, &md
->sender
);
1111 md
->sender_port
= ntohs(from
.sa_in4
.sin_port
);
1114 from_ugh
= initaddr((void *) &from
.sa_in6
.sin6_addr
1115 , sizeof(from
.sa_in6
.sin6_addr
), AF_INET6
, &md
->sender
);
1116 md
->sender_port
= ntohs(from
.sa_in6
.sin6_port
);
1122 /* now we report any actual I/O error */
1123 if (packet_len
== -1)
1125 if (from_ugh
== undisclosed
1126 && errno
== ECONNREFUSED
)
1128 /* Tone down scary message for vague event:
1129 * We get "connection refused" in response to some
1130 * datagram we sent, but we cannot tell which one.
1132 plog("some IKE message we sent has been rejected with ECONNREFUSED (kernel supplied no details)");
1134 else if (from_ugh
!= NULL
)
1136 log_errno((e
, "recvfrom on %s failed; Pluto cannot decode source sockaddr in rejection: %s"
1137 , ifp
->rname
, from_ugh
));
1141 log_errno((e
, "recvfrom on %s from %s:%u failed"
1143 , ip_str(&md
->sender
), (unsigned)md
->sender_port
));
1148 else if (from_ugh
!= NULL
)
1150 plog("recvfrom on %s returned misformed source sockaddr: %s"
1151 , ifp
->rname
, from_ugh
);
1154 cur_from
= &md
->sender
;
1155 cur_from_port
= md
->sender_port
;
1157 if (ifp
->ike_float
== TRUE
)
1161 if (packet_len
< (int)sizeof(u_int32_t
))
1163 plog("recvfrom %s:%u too small packet (%d)"
1164 , ip_str(cur_from
), (unsigned) cur_from_port
, packet_len
);
1167 memcpy(&non_esp
, buffer
, sizeof(u_int32_t
));
1170 plog("recvfrom %s:%u has no Non-ESP marker"
1171 , ip_str(cur_from
), (unsigned) cur_from_port
);
1174 packet_len
-= sizeof(u_int32_t
);
1175 buffer_nat
= malloc(packet_len
);
1176 memcpy(buffer_nat
, buffer
+ sizeof(u_int32_t
), packet_len
);
1178 buffer
= buffer_nat
;
1181 /* Clone actual message contents
1182 * and set up md->packet_pbs to describe it.
1184 init_pbs(&md
->packet_pbs
, buffer
, packet_len
, "packet");
1186 DBG(DBG_RAW
| DBG_CRYPT
| DBG_PARSING
| DBG_CONTROL
,
1188 DBG_log(BLANK_FORMAT
);
1189 DBG_log("*received %d bytes from %s:%u on %s"
1190 , (int) pbs_room(&md
->packet_pbs
)
1191 , ip_str(cur_from
), (unsigned) cur_from_port
1196 DBG_dump("", md
->packet_pbs
.start
, pbs_room(&md
->packet_pbs
)));
1198 if ((pbs_room(&md
->packet_pbs
)==1) && (md
->packet_pbs
.start
[0]==0xff))
1201 * NAT-T Keep-alive packets should be discarded by kernel ESPinUDP
1202 * layer. But bogus keep-alive packets (sent with a non-esp marker)
1203 * can reach this point. Complain and discard them.
1206 DBG_log("NAT-T keep-alive (bogus ?) should not reach this point. "
1207 "Ignored. Sender: %s:%u", ip_str(cur_from
),
1208 (unsigned) cur_from_port
);
1213 #define IKEV2_VERSION_OFFSET 17
1214 #define IKEV2_VERSION 0x20
1216 /* ignore IKEv2 packets - they will be handled by charon */
1217 if (pbs_room(&md
->packet_pbs
) > IKEV2_VERSION_OFFSET
1218 && (md
->packet_pbs
.start
[IKEV2_VERSION_OFFSET
] & 0xF0) == IKEV2_VERSION
)
1220 DBG(DBG_CONTROLMORE
,
1221 DBG_log(" ignoring IKEv2 packet")
1229 /* process an input packet, possibly generating a reply.
1231 * If all goes well, this routine eventually calls a state-specific
1232 * transition function.
1235 process_packet(struct msg_digest
**mdp
)
1237 struct msg_digest
*md
= *mdp
;
1238 const struct state_microcode
*smc
;
1239 bool new_iv_set
= FALSE
;
1240 bool restore_iv
= FALSE
;
1241 u_char new_iv
[MAX_DIGEST_LEN
];
1242 u_int new_iv_len
= 0;
1244 struct state
*st
= NULL
;
1245 enum state_kind from_state
= STATE_UNDEFINED
; /* state we started in */
1247 #define SEND_NOTIFICATION(t) { \
1248 if (st) send_notification_from_state(st, from_state, t); \
1249 else send_notification_from_md(md, t); }
1251 if (!in_struct(&md
->hdr
, &isakmp_hdr_desc
, &md
->packet_pbs
, &md
->message_pbs
))
1253 /* Identify specific failures:
1254 * - bad ISAKMP major/minor version numbers
1256 if (md
->packet_pbs
.roof
- md
->packet_pbs
.cur
>= (ptrdiff_t)isakmp_hdr_desc
.size
)
1258 struct isakmp_hdr
*hdr
= (struct isakmp_hdr
*)md
->packet_pbs
.cur
;
1259 if ((hdr
->isa_version
>> ISA_MAJ_SHIFT
) != ISAKMP_MAJOR_VERSION
)
1261 SEND_NOTIFICATION(ISAKMP_INVALID_MAJOR_VERSION
);
1264 else if ((hdr
->isa_version
& ISA_MIN_MASK
) != ISAKMP_MINOR_VERSION
)
1266 SEND_NOTIFICATION(ISAKMP_INVALID_MINOR_VERSION
);
1270 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
1274 if (md
->packet_pbs
.roof
!= md
->message_pbs
.roof
)
1276 plog("size (%u) differs from size specified in ISAKMP HDR (%u)"
1277 , (unsigned) pbs_room(&md
->packet_pbs
), md
->hdr
.isa_length
);
1279 if (pbs_room(&md
->packet_pbs
) - md
->hdr
.isa_length
== 16)
1280 plog("Cisco VPN client appends 16 surplus NULL bytes");
1286 switch (md
->hdr
.isa_xchg
)
1289 case ISAKMP_XCHG_NONE
:
1290 case ISAKMP_XCHG_BASE
:
1293 case ISAKMP_XCHG_IDPROT
: /* part of a Main Mode exchange */
1294 if (md
->hdr
.isa_msgid
!= MAINMODE_MSGID
)
1296 plog("Message ID was 0x%08lx but should be zero in Main Mode",
1297 (unsigned long) md
->hdr
.isa_msgid
);
1298 SEND_NOTIFICATION(ISAKMP_INVALID_MESSAGE_ID
);
1302 if (is_zero_cookie(md
->hdr
.isa_icookie
))
1304 plog("Initiator Cookie must not be zero in Main Mode message");
1305 SEND_NOTIFICATION(ISAKMP_INVALID_COOKIE
);
1309 if (is_zero_cookie(md
->hdr
.isa_rcookie
))
1311 /* initial message from initiator
1312 * ??? what if this is a duplicate of another message?
1314 if (md
->hdr
.isa_flags
& ISAKMP_FLAG_ENCRYPTION
)
1316 plog("initial Main Mode message is invalid:"
1317 " its Encrypted Flag is on");
1318 SEND_NOTIFICATION(ISAKMP_INVALID_FLAGS
);
1322 /* don't build a state until the message looks tasty */
1323 from_state
= STATE_MAIN_R0
;
1327 /* not an initial message */
1329 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1330 , &md
->sender
, md
->hdr
.isa_msgid
);
1334 /* perhaps this is a first message from the responder
1335 * and contains a responder cookie that we've not yet seen.
1337 st
= find_state(md
->hdr
.isa_icookie
, zero_cookie
1338 , &md
->sender
, md
->hdr
.isa_msgid
);
1342 plog("Main Mode message is part of an unknown exchange");
1343 /* XXX Could send notification back */
1348 from_state
= st
->st_state
;
1353 case ISAKMP_XCHG_AO
:
1354 case ISAKMP_XCHG_AGGR
:
1357 case ISAKMP_XCHG_INFO
: /* an informational exchange */
1358 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1359 , &md
->sender
, MAINMODE_MSGID
);
1364 if (md
->hdr
.isa_flags
& ISAKMP_FLAG_ENCRYPTION
)
1368 plog("Informational Exchange is for an unknown (expired?) SA");
1369 /* XXX Could send notification back */
1373 if (!IS_ISAKMP_ENCRYPTED(st
->st_state
))
1375 loglog(RC_LOG_SERIOUS
, "encrypted Informational Exchange message is invalid"
1376 " because no key is known");
1377 /* XXX Could send notification back */
1381 if (md
->hdr
.isa_msgid
== MAINMODE_MSGID
)
1383 loglog(RC_LOG_SERIOUS
, "Informational Exchange message is invalid because"
1384 " it has a Message ID of 0");
1385 /* XXX Could send notification back */
1389 if (!reserve_msgid(st
, md
->hdr
.isa_msgid
))
1391 loglog(RC_LOG_SERIOUS
, "Informational Exchange message is invalid because"
1392 " it has a previously used Message ID (0x%08lx)"
1393 , (unsigned long)md
->hdr
.isa_msgid
);
1394 /* XXX Could send notification back */
1398 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1400 memcpy(st
->st_ph1_iv
, st
->st_new_iv
, st
->st_new_iv_len
);
1401 st
->st_ph1_iv_len
= st
->st_new_iv_len
;
1404 new_iv_len
= st
->st_new_iv_len
;
1405 passert(new_iv_len
<= MAX_DIGEST_LEN
)
1406 memcpy(new_iv
, st
->st_new_iv
, new_iv_len
);
1409 init_phase2_iv(st
, &md
->hdr
.isa_msgid
);
1412 from_state
= STATE_INFO_PROTECTED
;
1416 if (st
!= NULL
&& IS_ISAKMP_ENCRYPTED(st
->st_state
))
1418 loglog(RC_LOG_SERIOUS
, "Informational Exchange message"
1419 " must be encrypted");
1420 /* XXX Could send notification back */
1423 from_state
= STATE_INFO
;
1427 case ISAKMP_XCHG_QUICK
: /* part of a Quick Mode exchange */
1428 if (is_zero_cookie(md
->hdr
.isa_icookie
))
1430 plog("Quick Mode message is invalid because"
1431 " it has an Initiator Cookie of 0");
1432 SEND_NOTIFICATION(ISAKMP_INVALID_COOKIE
);
1436 if (is_zero_cookie(md
->hdr
.isa_rcookie
))
1438 plog("Quick Mode message is invalid because"
1439 " it has a Responder Cookie of 0");
1440 SEND_NOTIFICATION(ISAKMP_INVALID_COOKIE
);
1444 if (md
->hdr
.isa_msgid
== MAINMODE_MSGID
)
1446 plog("Quick Mode message is invalid because"
1447 " it has a Message ID of 0");
1448 SEND_NOTIFICATION(ISAKMP_INVALID_MESSAGE_ID
);
1452 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1453 , &md
->sender
, md
->hdr
.isa_msgid
);
1457 /* No appropriate Quick Mode state.
1458 * See if we have a Main Mode state.
1459 * ??? what if this is a duplicate of another message?
1461 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1462 , &md
->sender
, MAINMODE_MSGID
);
1466 plog("Quick Mode message is for a non-existent (expired?)"
1468 /* XXX Could send notification back */
1474 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1476 loglog(RC_LOG_SERIOUS
, "Quick Mode message is unacceptable because"
1477 " it is for an incomplete ISAKMP SA");
1478 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
/* XXX ? */);
1482 /* only accept this new Quick Mode exchange if it has a unique message ID */
1483 if (!reserve_msgid(st
, md
->hdr
.isa_msgid
))
1485 loglog(RC_LOG_SERIOUS
, "Quick Mode I1 message is unacceptable because"
1486 " it uses a previously used Message ID 0x%08lx"
1487 " (perhaps this is a duplicated packet)"
1488 , (unsigned long) md
->hdr
.isa_msgid
);
1489 SEND_NOTIFICATION(ISAKMP_INVALID_MESSAGE_ID
);
1493 /* Quick Mode Initial IV */
1494 init_phase2_iv(st
, &md
->hdr
.isa_msgid
);
1497 from_state
= STATE_QUICK_R0
;
1502 from_state
= st
->st_state
;
1507 case ISAKMP_XCHG_MODE_CFG
:
1508 if (is_zero_cookie(md
->hdr
.isa_icookie
))
1510 plog("ModeCfg message is invalid because"
1511 " it has an Initiator Cookie of 0");
1512 /* XXX Could send notification back */
1516 if (is_zero_cookie(md
->hdr
.isa_rcookie
))
1518 plog("ModeCfg message is invalid because"
1519 " it has a Responder Cookie of 0");
1520 /* XXX Could send notification back */
1524 if (md
->hdr
.isa_msgid
== 0)
1526 plog("ModeCfg message is invalid because"
1527 " it has a Message ID of 0");
1528 /* XXX Could send notification back */
1532 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1533 , &md
->sender
, md
->hdr
.isa_msgid
);
1537 bool has_xauth_policy
;
1539 /* No appropriate ModeCfg state.
1540 * See if we have a Main Mode state.
1541 * ??? what if this is a duplicate of another message?
1543 st
= find_state(md
->hdr
.isa_icookie
, md
->hdr
.isa_rcookie
1548 plog("ModeCfg message is for a non-existent (expired?)"
1550 /* XXX Could send notification back */
1556 /* the XAUTH_STATUS message might have a new msgid */
1557 if (st
->st_state
== STATE_XAUTH_I1
)
1559 init_phase2_iv(st
, &md
->hdr
.isa_msgid
);
1561 from_state
= st
->st_state
;
1565 if (!IS_ISAKMP_SA_ESTABLISHED(st
->st_state
))
1567 loglog(RC_LOG_SERIOUS
, "ModeCfg message is unacceptable because"
1568 " it is for an incomplete ISAKMP SA (state=%s)"
1569 , enum_name(&state_names
, st
->st_state
));
1570 /* XXX Could send notification back */
1573 init_phase2_iv(st
, &md
->hdr
.isa_msgid
);
1577 * okay, now we have to figure out if we are receiving a bogus
1578 * new message in an oustanding XAUTH server conversation
1579 * (i.e. a reply to our challenge)
1580 * (this occurs with some broken other implementations).
1582 * or if receiving for the first time, an XAUTH challenge.
1584 * or if we are getting a MODECFG request.
1586 * we distinguish these states because we can not both be an
1587 * XAUTH server and client, and our policy tells us which
1590 * to complicate further, it is normal to start a new msgid
1591 * when going from one state to another, or when restarting
1596 has_xauth_policy
= (st
->st_connection
->policy
1597 & (POLICY_XAUTH_RSASIG
| POLICY_XAUTH_PSK
))
1600 if (has_xauth_policy
&& !st
->st_xauth
.started
1601 && IS_PHASE1(st
->st_state
))
1603 from_state
= STATE_XAUTH_I0
;
1605 else if (st
->st_connection
->spd
.that
.modecfg
1606 && IS_PHASE1(st
->st_state
))
1608 from_state
= STATE_MODE_CFG_R0
;
1610 else if (st
->st_connection
->spd
.this.modecfg
1611 && IS_PHASE1(st
->st_state
))
1613 from_state
= STATE_MODE_CFG_I0
;
1617 /* XXX check if we are being a mode config server here */
1618 plog("received ModeCfg message when in state %s, and we aren't mode config client"
1619 , enum_name(&state_names
, st
->st_state
));
1626 from_state
= st
->st_state
;
1631 case ISAKMP_XCHG_NGRP
:
1632 case ISAKMP_XCHG_ACK_INFO
:
1636 plog("unsupported exchange type %s in message"
1637 , enum_show(&exchange_names
, md
->hdr
.isa_xchg
));
1638 SEND_NOTIFICATION(ISAKMP_UNSUPPORTED_EXCHANGE_TYPE
);
1642 /* We have found a from_state, and perhaps a state object.
1643 * If we need to build a new state object,
1644 * we wait until the packet has been sanity checked.
1647 /* We don't support the Commit Flag. It is such a bad feature.
1648 * It isn't protected -- neither encrypted nor authenticated.
1649 * A man in the middle turns it on, leading to DoS.
1650 * We just ignore it, with a warning.
1651 * By placing the check here, we could easily add a policy bit
1652 * to a connection to suppress the warning. This might be useful
1653 * because the Commit Flag is expected from some peers.
1655 if (md
->hdr
.isa_flags
& ISAKMP_FLAG_COMMIT
)
1657 plog("IKE message has the Commit Flag set but Pluto doesn't implement this feature; ignoring flag");
1660 /* Set smc to describe this state's properties.
1661 * Look up the appropriate microcode based on state and
1662 * possibly Oakley Auth type.
1664 passert(STATE_IKE_FLOOR
<= from_state
&& from_state
<= STATE_IKE_ROOF
);
1665 smc
= ike_microcode_index
[from_state
- STATE_IKE_FLOOR
];
1671 switch (st
->st_oakley
.auth
)
1673 case XAUTHInitPreShared
:
1674 case XAUTHRespPreShared
:
1675 auth
= OAKLEY_PRESHARED_KEY
;
1679 auth
= OAKLEY_RSA_SIG
;
1682 auth
= st
->st_oakley
.auth
;
1685 while (!LHAS(smc
->flags
, auth
))
1688 passert(smc
->state
== from_state
);
1692 /* Ignore a packet if the state has a suspended state transition
1693 * Probably a duplicated packet but the original packet is not yet
1694 * recorded in st->st_rpacket, so duplicate checking won't catch.
1695 * ??? Should the packet be recorded earlier to improve diagnosis?
1697 if (st
!= NULL
&& st
->st_suspended_md
!= NULL
)
1699 loglog(RC_LOG
, "discarding packet received during DNS lookup in %s"
1700 , enum_name(&state_names
, st
->st_state
));
1704 /* Detect and handle duplicated packets.
1705 * This won't work for the initial packet of an exchange
1706 * because we won't have a state object to remember it.
1707 * If we are in a non-receiving state (terminal), and the preceding
1708 * state did transmit, then the duplicate may indicate that that
1709 * transmission wasn't received -- retransmit it.
1710 * Otherwise, just discard it.
1711 * ??? Notification packets are like exchanges -- I hope that
1712 * they are idempotent!
1715 && st
->st_rpacket
.ptr
!= NULL
1716 && st
->st_rpacket
.len
== pbs_room(&md
->packet_pbs
)
1717 && memeq(st
->st_rpacket
.ptr
, md
->packet_pbs
.start
, st
->st_rpacket
.len
))
1719 if (smc
->flags
& SMF_RETRANSMIT_ON_DUPLICATE
)
1721 if (st
->st_retransmit
< MAXIMUM_RETRANSMISSIONS
)
1723 st
->st_retransmit
++;
1724 loglog(RC_RETRANSMISSION
1725 , "retransmitting in response to duplicate packet; already %s"
1726 , enum_name(&state_names
, st
->st_state
));
1727 send_packet(st
, "retransmit in response to duplicate");
1731 loglog(RC_LOG_SERIOUS
, "discarding duplicate packet -- exhausted retransmission; already %s"
1732 , enum_name(&state_names
, st
->st_state
));
1737 loglog(RC_LOG_SERIOUS
, "discarding duplicate packet; already %s"
1738 , enum_name(&state_names
, st
->st_state
));
1743 if (md
->hdr
.isa_flags
& ISAKMP_FLAG_ENCRYPTION
)
1745 DBG(DBG_CRYPT
, DBG_log("received encrypted packet from %s:%u"
1746 , ip_str(&md
->sender
), (unsigned)md
->sender_port
));
1750 plog("discarding encrypted message for an unknown ISAKMP SA");
1751 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
/* XXX ? */);
1754 if (st
->st_skeyid_e
.ptr
== (u_char
*) NULL
)
1756 loglog(RC_LOG_SERIOUS
, "discarding encrypted message"
1757 " because we haven't yet negotiated keying materiel");
1758 SEND_NOTIFICATION(ISAKMP_INVALID_FLAGS
);
1762 /* Mark as encrypted */
1763 md
->encrypted
= TRUE
;
1765 DBG(DBG_CRYPT
, DBG_log("decrypting %u bytes using algorithm %s"
1766 , (unsigned) pbs_left(&md
->message_pbs
)
1767 , enum_show(&oakley_enc_names
, st
->st_oakley
.encrypt
)));
1769 /* do the specified decryption
1771 * IV is from st->st_iv or (if new_iv_set) st->st_new_iv.
1772 * The new IV is placed in st->st_new_iv
1774 * See RFC 2409 "IKE" Appendix B
1776 * XXX The IV should only be updated really if the packet
1777 * is successfully processed.
1778 * We should keep this value, check for a success return
1779 * value from the parsing routines and then replace.
1781 * Each post phase 1 exchange generates IVs from
1782 * the last phase 1 block, not the last block sent.
1785 size_t crypter_block_size
;
1786 encryption_algorithm_t enc_alg
;
1791 enc_alg
= oakley_to_encryption_algorithm(st
->st_oakley
.encrypt
);
1792 crypter
= lib
->crypto
->create_crypter(lib
->crypto
, enc_alg
, st
->st_enc_key
.len
);
1793 crypter_block_size
= crypter
->get_block_size(crypter
);
1795 if (pbs_left(&md
->message_pbs
) % crypter_block_size
!= 0)
1797 loglog(RC_LOG_SERIOUS
, "malformed message: not a multiple of encryption blocksize");
1798 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
1802 /* XXX Detect weak keys */
1804 /* grab a copy of raw packet (for duplicate packet detection) */
1805 md
->raw_packet
= chunk_create(md
->packet_pbs
.start
, pbs_room(&md
->packet_pbs
));
1806 md
->raw_packet
= chunk_clone(md
->raw_packet
);
1808 data
= chunk_create(md
->message_pbs
.cur
, pbs_left(&md
->message_pbs
));
1810 /* Decrypt everything after header */
1814 passert(st
->st_iv_len
<= sizeof(st
->st_new_iv
));
1815 st
->st_new_iv_len
= st
->st_iv_len
;
1816 memcpy(st
->st_new_iv
, st
->st_iv
, st
->st_new_iv_len
);
1819 /* form iv by truncation */
1820 st
->st_new_iv_len
= crypter_block_size
;
1821 iv
= chunk_create(st
->st_new_iv
, st
->st_new_iv_len
);
1822 new_iv
= alloca(crypter_block_size
);
1823 memcpy(new_iv
, data
.ptr
+ data
.len
- crypter_block_size
,
1824 crypter_block_size
);
1826 crypter
->set_key(crypter
, st
->st_enc_key
);
1827 crypter
->decrypt(crypter
, data
, iv
, NULL
);
1828 crypter
->destroy(crypter
);
1830 memcpy(st
->st_new_iv
, new_iv
, crypter_block_size
);
1833 memcpy(st
->st_new_iv
, new_iv
, new_iv_len
);
1834 st
->st_new_iv_len
= new_iv_len
;
1838 DBG_cond_dump(DBG_CRYPT
, "decrypted:\n", md
->message_pbs
.cur
1839 , md
->message_pbs
.roof
- md
->message_pbs
.cur
);
1841 DBG_cond_dump(DBG_CRYPT
, "next IV:"
1842 , st
->st_new_iv
, st
->st_new_iv_len
);
1846 /* packet was not encryped -- should it have been? */
1848 if (smc
->flags
& SMF_INPUT_ENCRYPTED
)
1850 loglog(RC_LOG_SERIOUS
, "packet rejected: should have been encrypted");
1851 SEND_NOTIFICATION(ISAKMP_INVALID_FLAGS
);
1856 /* Digest the message.
1857 * Padding must be removed to make hashing work.
1858 * Padding comes from encryption (so this code must be after decryption).
1859 * Padding rules are described before the definition of
1860 * struct isakmp_hdr in packet.h.
1863 struct payload_digest
*pd
= md
->digest
;
1864 int np
= md
->hdr
.isa_np
;
1865 lset_t needed
= smc
->req_payloads
;
1867 = LIN(SMF_PSK_AUTH
| SMF_FIRST_ENCRYPTED_INPUT
, smc
->flags
)
1868 ?
"probable authentication failure (mismatch of preshared secrets?): "
1871 while (np
!= ISAKMP_NEXT_NONE
)
1873 struct_desc
*sd
= np
< ISAKMP_NEXT_ROOF? payload_descs
[np
] : NULL
;
1875 if (pd
== &md
->digest
[PAYLIMIT
])
1877 loglog(RC_LOG_SERIOUS
, "more than %d payloads in message; ignored", PAYLIMIT
);
1878 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
1884 case ISAKMP_NEXT_NATD_RFC
:
1885 case ISAKMP_NEXT_NATOA_RFC
:
1886 if (!st
|| !(st
->nat_traversal
& NAT_T_WITH_RFC_VALUES
))
1889 * don't accept NAT-D/NAT-OA reloc directly in message, unless
1890 * we're using NAT-T RFC
1899 /* payload type is out of range or requires special handling */
1902 case ISAKMP_NEXT_ID
:
1903 sd
= IS_PHASE1(from_state
)
1904 ?
&isakmp_identification_desc
: &isakmp_ipsec_identification_desc
;
1906 case ISAKMP_NEXT_NATD_DRAFTS
:
1907 np
= ISAKMP_NEXT_NATD_RFC
; /* NAT-D relocated */
1908 sd
= payload_descs
[np
];
1910 case ISAKMP_NEXT_NATOA_DRAFTS
:
1911 np
= ISAKMP_NEXT_NATOA_RFC
; /* NAT-OA relocated */
1912 sd
= payload_descs
[np
];
1915 loglog(RC_LOG_SERIOUS
, "%smessage ignored because it contains an unknown or"
1916 " unexpected payload type (%s) at the outermost level"
1917 , excuse
, enum_show(&payload_names
, np
));
1918 SEND_NOTIFICATION(ISAKMP_INVALID_PAYLOAD_TYPE
);
1924 lset_t s
= LELEM(np
);
1927 , needed
| smc
->opt_payloads
| LELEM(ISAKMP_NEXT_N
) | LELEM(ISAKMP_NEXT_D
)))
1929 loglog(RC_LOG_SERIOUS
, "%smessage ignored because it "
1930 "contains an unexpected payload type (%s)"
1931 , excuse
, enum_show(&payload_names
, np
));
1932 SEND_NOTIFICATION(ISAKMP_INVALID_PAYLOAD_TYPE
);
1938 if (!in_struct(&pd
->payload
, sd
, &md
->message_pbs
, &pd
->pbs
))
1940 loglog(RC_LOG_SERIOUS
, "%smalformed payload in packet", excuse
);
1941 if (md
->hdr
.isa_xchg
!= ISAKMP_XCHG_INFO
)
1942 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
1946 /* place this payload at the end of the chain for this type */
1948 struct payload_digest
**p
;
1950 for (p
= &md
->chain
[np
]; *p
!= NULL
; p
= &(*p
)->next
)
1956 np
= pd
->payload
.generic
.isag_np
;
1959 /* since we've digested one payload happily, it is probably
1960 * the case that any decryption worked. So we will not suggest
1961 * encryption failure as an excuse for subsequent payload
1967 md
->digest_roof
= pd
;
1970 if (pbs_left(&md
->message_pbs
) != 0)
1971 DBG_log("removing %d bytes of padding", (int) pbs_left(&md
->message_pbs
)));
1973 md
->message_pbs
.roof
= md
->message_pbs
.cur
;
1975 /* check that all mandatory payloads appeared */
1979 loglog(RC_LOG_SERIOUS
, "message for %s is missing payloads %s"
1980 , enum_show(&state_names
, from_state
)
1981 , bitnamesof(payload_name
, needed
));
1982 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
1987 /* more sanity checking: enforce most ordering constraints */
1989 if (IS_PHASE1(from_state
))
1991 /* rfc2409: The Internet Key Exchange (IKE), 5 Exchanges:
1992 * "The SA payload MUST precede all other payloads in a phase 1 exchange."
1994 if (md
->chain
[ISAKMP_NEXT_SA
] != NULL
1995 && md
->hdr
.isa_np
!= ISAKMP_NEXT_SA
)
1997 loglog(RC_LOG_SERIOUS
, "malformed Phase 1 message: does not start with an SA payload");
1998 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
2002 else if (IS_QUICK(from_state
))
2004 /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode
2006 * "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
2007 * header and a SA payload MUST immediately follow the HASH."
2008 * [NOTE: there may be more than one SA payload, so this is not
2009 * totally reasonable. Probably all SAs should be so constrained.]
2011 * "If ISAKMP is acting as a client negotiator on behalf of another
2012 * party, the identities of the parties MUST be passed as IDci and
2015 * "With the exception of the HASH, SA, and the optional ID payloads,
2016 * there are no payload ordering restrictions on Quick Mode."
2019 if (md
->hdr
.isa_np
!= ISAKMP_NEXT_HASH
)
2021 loglog(RC_LOG_SERIOUS
, "malformed Quick Mode message: does not start with a HASH payload");
2022 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
2027 struct payload_digest
*p
;
2030 for (p
= md
->chain
[ISAKMP_NEXT_SA
], i
= 1; p
!= NULL
2033 if (p
!= &md
->digest
[i
])
2035 loglog(RC_LOG_SERIOUS
, "malformed Quick Mode message: SA payload is in wrong position");
2036 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
2042 /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode:
2043 * "If ISAKMP is acting as a client negotiator on behalf of another
2044 * party, the identities of the parties MUST be passed as IDci and
2048 struct payload_digest
*id
= md
->chain
[ISAKMP_NEXT_ID
];
2052 if (id
->next
== NULL
|| id
->next
->next
!= NULL
)
2054 loglog(RC_LOG_SERIOUS
, "malformed Quick Mode message:"
2055 " if any ID payload is present,"
2056 " there must be exactly two");
2057 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
2060 if (id
+1 != id
->next
)
2062 loglog(RC_LOG_SERIOUS
, "malformed Quick Mode message:"
2063 " the ID payloads are not adjacent");
2064 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED
);
2071 /* Ignore payloads that we don't handle:
2072 * Delete, Notification, VendorID
2074 /* XXX Handle deletions */
2075 /* XXX Handle Notifications */
2076 /* XXX Handle VID payloads */
2078 struct payload_digest
*p
;
2080 for (p
= md
->chain
[ISAKMP_NEXT_N
]; p
!= NULL
; p
= p
->next
)
2082 if (p
->payload
.notification
.isan_type
!= R_U_THERE
2083 && p
->payload
.notification
.isan_type
!= R_U_THERE_ACK
)
2085 loglog(RC_LOG_SERIOUS
, "ignoring informational payload, type %s"
2086 , enum_show(¬ification_names
, p
->payload
.notification
.isan_type
));
2088 DBG_cond_dump(DBG_PARSING
, "info:", p
->pbs
.cur
, pbs_left(&p
->pbs
));
2091 for (p
= md
->chain
[ISAKMP_NEXT_D
]; p
!= NULL
; p
= p
->next
)
2093 accept_delete(st
, md
, p
);
2094 DBG_cond_dump(DBG_PARSING
, "del:", p
->pbs
.cur
, pbs_left(&p
->pbs
));
2097 for (p
= md
->chain
[ISAKMP_NEXT_VID
]; p
!= NULL
; p
= p
->next
)
2099 handle_vendorid(md
, p
->pbs
.cur
, pbs_left(&p
->pbs
));
2102 md
->from_state
= from_state
;
2106 /* possibly fill in hdr */
2107 if (smc
->first_out_payload
!= ISAKMP_NEXT_NONE
)
2108 echo_hdr(md
, (smc
->flags
& SMF_OUTPUT_ENCRYPTED
) != 0
2109 , smc
->first_out_payload
);
2111 complete_state_transition(mdp
, smc
->processor(md
));
2114 /* complete job started by the state-specific state transition function */
2117 complete_state_transition(struct msg_digest
**mdp
, stf_status result
)
2119 bool has_xauth_policy
;
2120 bool is_xauth_server
;
2121 struct msg_digest
*md
= *mdp
;
2122 const struct state_microcode
*smc
= md
->smc
;
2123 enum state_kind from_state
= md
->from_state
;
2126 cur_state
= st
= md
->st
; /* might have changed */
2128 /* If state has DPD support, import it */
2138 /* the stf didn't complete its job: don't relase md */
2143 /* advance the state */
2144 st
->st_state
= smc
->next_state
;
2146 /* Delete previous retransmission event.
2147 * New event will be scheduled below.
2151 /* replace previous receive packet with latest */
2153 free(st
->st_rpacket
.ptr
);
2157 /* if encrypted, duplication already done */
2158 st
->st_rpacket
= md
->raw_packet
;
2159 md
->raw_packet
.ptr
= NULL
;
2163 st
->st_rpacket
= chunk_create(md
->packet_pbs
.start
,
2164 pbs_room(&md
->packet_pbs
));
2165 st
->st_rpacket
= chunk_clone(st
->st_rpacket
);
2168 /* free previous transmit packet */
2169 chunk_free(&st
->st_tpacket
);
2171 /* if requested, send the new reply packet */
2172 if (smc
->flags
& SMF_REPLY
)
2174 close_output_pbs(&md
->reply
); /* good form, but actually a no-op */
2176 st
->st_tpacket
= chunk_create(md
->reply
.start
, pbs_offset(&md
->reply
));
2177 st
->st_tpacket
= chunk_clone(st
->st_tpacket
);
2179 if (nat_traversal_enabled
)
2180 nat_traversal_change_port_lookup(md
, md
->st
);
2182 /* actually send the packet
2183 * Note: this is a great place to implement "impairments"
2184 * for testing purposes. Suppress or duplicate the
2185 * send_packet call depending on st->st_state.
2187 send_packet(st
, enum_name(&state_names
, from_state
));
2190 /* Schedule for whatever timeout is specified */
2192 time_t delay
= UNDEFINED_TIME
;
2193 enum event_type kind
= smc
->timeout_event
;
2194 bool agreed_time
= FALSE
;
2195 connection_t
*c
= st
->st_connection
;
2199 case EVENT_RETRANSMIT
: /* Retransmit packet */
2200 delay
= EVENT_RETRANSMIT_DELAY_0
;
2203 case EVENT_SA_REPLACE
: /* SA replacement event */
2204 if (IS_PHASE1(st
->st_state
))
2206 /* Note: we will defer to the "negotiated" (dictated)
2207 * lifetime if we are POLICY_DONT_REKEY.
2208 * This allows the other side to dictate
2209 * a time we would not otherwise accept
2210 * but it prevents us from having to initiate
2211 * rekeying. The negative consequences seem
2214 delay
= c
->sa_ike_life_seconds
;
2215 if ((c
->policy
& POLICY_DONT_REKEY
)
2216 || delay
>= st
->st_oakley
.life_seconds
)
2219 delay
= st
->st_oakley
.life_seconds
;
2224 /* Delay is min of up to four things:
2225 * each can limit the lifetime.
2227 delay
= c
->sa_ipsec_life_seconds
;
2228 if (st
->st_ah
.present
2229 && delay
>= st
->st_ah
.attrs
.life_seconds
)
2232 delay
= st
->st_ah
.attrs
.life_seconds
;
2234 if (st
->st_esp
.present
2235 && delay
>= st
->st_esp
.attrs
.life_seconds
)
2238 delay
= st
->st_esp
.attrs
.life_seconds
;
2240 if (st
->st_ipcomp
.present
2241 && delay
>= st
->st_ipcomp
.attrs
.life_seconds
)
2244 delay
= st
->st_ipcomp
.attrs
.life_seconds
;
2248 /* By default, we plan to rekey.
2250 * If there isn't enough time to rekey, plan to
2253 * If we are --dontrekey, a lot more rules apply.
2254 * If we are the Initiator, use REPLACE_IF_USED.
2255 * If we are the Responder, and the dictated time
2256 * was unacceptable (too large), plan to REPLACE
2257 * (the only way to ratchet down the time).
2258 * If we are the Responder, and the dictated time
2259 * is acceptable, plan to EXPIRE.
2261 * Important policy lies buried here.
2262 * For example, we favour the initiator over the
2263 * responder by making the initiator start rekeying
2264 * sooner. Also, fuzz is only added to the
2265 * initiator's margin.
2267 * Note: for ISAKMP SA, we let the negotiated
2268 * time stand (implemented by earlier logic).
2271 && (c
->policy
& POLICY_DONT_REKEY
))
2273 kind
= (smc
->flags
& SMF_INITIATOR
)
2274 ? EVENT_SA_REPLACE_IF_USED
2277 if (kind
!= EVENT_SA_EXPIRE
)
2279 unsigned long marg
= c
->sa_rekey_margin
;
2281 if (smc
->flags
& SMF_INITIATOR
)
2283 * c
->sa_rekey_fuzz
/ 100.E0
2284 * (rand() / (RAND_MAX
+ 1.E0
));
2288 if ((unsigned long)delay
> marg
)
2291 st
->st_margin
= marg
;
2295 kind
= EVENT_SA_EXPIRE
;
2300 case EVENT_NULL
: /* non-event */
2301 case EVENT_REINIT_SECRET
: /* Refresh cookie secret */
2305 event_schedule(kind
, delay
, st
);
2308 /* tell whack and log of progress */
2310 const char *story
= state_story
[st
->st_state
- STATE_MAIN_R0
];
2311 enum rc_type w
= RC_NEW_STATE
+ st
->st_state
;
2312 char sadetails
[128];
2316 if (IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
2318 char *b
= sadetails
;
2319 const char *ini
= " {";
2320 const char *fin
= "";
2322 /* -1 is to leave space for "fin" */
2324 if (st
->st_esp
.present
)
2326 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2327 , "%sESP=>0x%08x <0x%08x"
2329 , ntohl(st
->st_esp
.attrs
.spi
)
2330 , ntohl(st
->st_esp
.our_spi
));
2334 /* advance b to end of string */
2337 if (st
->st_ah
.present
)
2339 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2340 , "%sAH=>0x%08x <0x%08x"
2342 , ntohl(st
->st_ah
.attrs
.spi
)
2343 , ntohl(st
->st_ah
.our_spi
));
2347 /* advance b to end of string */
2350 if (st
->st_ipcomp
.present
)
2352 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2353 , "%sIPCOMP=>0x%08x <0x%08x"
2355 , ntohl(st
->st_ipcomp
.attrs
.spi
)
2356 , ntohl(st
->st_ipcomp
.our_spi
));
2360 /* advance b to end of string */
2363 if (st
->nat_traversal
)
2365 char oa
[ADDRTOT_BUF
];
2366 addrtot(&st
->nat_oa
, 0, oa
, sizeof(oa
));
2367 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2374 /* advance b to end of string */
2379 snprintf(b
, sizeof(sadetails
)-(b
-sadetails
)-1
2389 if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2390 || IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
2392 /* log our success */
2393 plog("%s%s", story
, sadetails
);
2397 /* tell whack our progress */
2400 , enum_name(&state_names
, st
->st_state
)
2401 , story
, sadetails
);
2404 has_xauth_policy
= (st
->st_connection
->policy
2405 & (POLICY_XAUTH_RSASIG
| POLICY_XAUTH_PSK
))
2407 is_xauth_server
= (st
->st_connection
->policy
2408 & POLICY_XAUTH_SERVER
)
2411 /* Should we start XAUTH as a server */
2412 if (has_xauth_policy
&& is_xauth_server
2413 && IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2414 && !st
->st_xauth
.started
)
2417 DBG_log("starting XAUTH server")
2419 xauth_send_request(st
);
2423 /* Wait for XAUTH request from server */
2424 if (has_xauth_policy
&& !is_xauth_server
2425 && IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2426 && !st
->st_xauth
.started
)
2429 DBG_log("waiting for XAUTH request from server")
2434 /* Should we start ModeConfig as a client? */
2435 if (st
->st_connection
->spd
.this.modecfg
2436 && IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2437 && !(st
->st_connection
->policy
& POLICY_MODECFG_PUSH
)
2438 && !st
->st_modecfg
.started
)
2441 DBG_log("starting ModeCfg client in pull mode")
2443 modecfg_send_request(st
);
2447 /* Should we start ModeConfig as a server? */
2448 if (st
->st_connection
->spd
.that
.modecfg
2449 && IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2450 && !st
->st_modecfg
.started
2451 && (st
->st_connection
->policy
& POLICY_MODECFG_PUSH
))
2454 DBG_log("starting ModeCfg server in push mode")
2456 modecfg_send_set(st
);
2460 /* Wait for ModeConfig set from server */
2461 if (st
->st_connection
->spd
.this.modecfg
2462 && IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2463 && !st
->st_modecfg
.vars_set
)
2466 DBG_log("waiting for ModeCfg set from server")
2471 if (smc
->flags
& SMF_RELEASE_PENDING_P2
)
2473 /* Initiate any Quick Mode negotiations that
2474 * were waiting to piggyback on this Keying Channel.
2476 * ??? there is a potential race condition
2477 * if we are the responder: the initial Phase 2
2478 * message might outrun the final Phase 1 message.
2479 * I think that retransmission will recover.
2484 if (IS_ISAKMP_SA_ESTABLISHED(st
->st_state
)
2485 || IS_IPSEC_SA_ESTABLISHED(st
->st_state
))
2489 case STF_INTERNAL_ERROR
:
2490 whack_log(RC_INTERNALERR
+ md
->note
2491 , "%s: internal error"
2492 , enum_name(&state_names
, st
->st_state
));
2495 DBG_log("state transition function for %s had internal error"
2496 , enum_name(&state_names
, from_state
)));
2499 default: /* a shortcut to STF_FAIL, setting md->note */
2500 passert(result
> STF_FAIL
);
2501 md
->note
= result
- STF_FAIL
;
2503 /* FALL THROUGH ... */
2505 /* As it is, we act as if this message never happened:
2506 * whatever retrying was in place, remains in place.
2508 whack_log(RC_NOTIFICATION
+ md
->note
2510 , enum_name(&state_names
, (st
== NULL
)? STATE_MAIN_R0
:st
->st_state
)
2511 , enum_name(¬ification_names
, md
->note
));
2513 SEND_NOTIFICATION(md
->note
);
2516 DBG_log("state transition function for %s failed: %s"
2517 , enum_name(&state_names
, from_state
)
2518 , enum_name(¬ification_names
, md
->note
)));