0590a3585d6a108a5ccab055f583290cae991021
[strongswan.git] / src / pluto / demux.c
1 /* demultiplex incoming IKE messages
2 * Copyright (C) 1997 Angelos D. Keromytis.
3 * Copyright (C) 1998-2002 D. Hugh Redelmeier.
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; either version 2 of the License, or (at your
8 * option) any later version. See <http://www.fsf.org/copyleft/gpl.txt>.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * for more details.
14 */
15
16 /* Ordering Constraints on Payloads
17 *
18 * rfc2409: The Internet Key Exchange (IKE)
19 *
20 * 5 Exchanges:
21 * "The SA payload MUST precede all other payloads in a phase 1 exchange."
22 *
23 * "Except where otherwise noted, there are no requirements for ISAKMP
24 * payloads in any message to be in any particular order."
25 *
26 * 5.3 Phase 1 Authenticated With a Revised Mode of Public Key Encryption:
27 *
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."
32 *
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
37 * direction."
38 *
39 * 5.5 Phase 2 - Quick Mode
40 *
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.]
45 *
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
48 * then IDcr."
49 *
50 * "With the exception of the HASH, SA, and the optional ID payloads,
51 * there are no payload ordering restrictions on Quick Mode."
52 */
53
54 /* Unfolding of Identity -- a central mystery
55 *
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.
59 *
60 * There are three case of interest:
61 *
62 * (1) We initiate, based on a whack command specifying a Connection.
63 * We know the identity of the peer from the Connection.
64 *
65 * (2) (to be implemented) we initiate based on a flow from our client
66 * to some IP address.
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.
70 *
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.
74 *
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.
83 *
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
91 * PSK, if needed).
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.
102 */
103
104 #include <stdio.h>
105 #include <stdlib.h>
106 #include <stddef.h>
107 #include <string.h>
108 #include <unistd.h>
109 #include <errno.h>
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>
118
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 */
123 #endif
124
125 #include <freeswan.h>
126
127 #include "constants.h"
128 #include "defs.h"
129 #include "cookie.h"
130 #include "connections.h"
131 #include "state.h"
132 #include "packet.h"
133 #include "crypto.h"
134 #include "ike_alg.h"
135 #include "log.h"
136 #include "demux.h" /* needs packet.h */
137 #include "ipsec_doi.h" /* needs demux.h and state.h */
138 #include "timer.h"
139 #include "whack.h" /* requires connections.h */
140 #include "server.h"
141 #include "nat_traversal.h"
142 #include "vendor.h"
143 #include "modecfg.h"
144
145 /* This file does basic header checking and demux of
146 * incoming packets.
147 */
148
149 /* forward declarations */
150 static bool read_packet(struct msg_digest *md);
151 static void process_packet(struct msg_digest **mdp);
152
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.
159 */
160 u_int8_t reply_buffer[MAX_OUTPUT_UDP_SIZE];
161
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.
169 */
170
171 struct state_microcode {
172 enum state_kind state, next_state;
173 lset_t flags;
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;
180 };
181
182 /* State Microcode Flags, in several groups */
183
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
187 * has been set.
188 */
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))
196
197 /* misc flags */
198
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)
204
205 #define SMF_ENCRYPTED (SMF_INPUT_ENCRYPTED | SMF_OUTPUT_ENCRYPTED)
206
207 /* this state generates a reply message */
208 #define SMF_REPLY LELEM(OAKLEY_AUTH_ROOF + 5)
209
210 /* this state completes P1, so any pending P2 negotiations should start */
211 #define SMF_RELEASE_PENDING_P2 LELEM(OAKLEY_AUTH_ROOF + 6)
212
213 /* end of flags */
214
215
216 static state_transition_fn /* forward declaration */
217 unexpected,
218 informational;
219
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.
226 */
227
228 static const struct state_microcode
229 *ike_microcode_index[STATE_IKE_ROOF - STATE_IKE_FLOOR];
230
231 static const struct state_microcode state_microcode_table[] = {
232 #define PT(n) ISAKMP_NEXT_##n
233 #define P(n) LELEM(PT(n))
234
235 /***** Phase 1 Main Mode *****/
236
237 /* No state for main_outI1: --> HDR, SA */
238
239 /* STATE_MAIN_R0: I1 --> R1
240 * HDR, SA --> HDR, SA
241 */
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},
246
247 /* STATE_MAIN_I1: R1 --> I2
248 * HDR, SA --> auth dependent
249 * SMF_PSK_AUTH, SMF_DS_AUTH: --> HDR, KE, Ni
250 * SMF_PKE_AUTH:
251 * --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
252 * SMF_RPKE_AUTH:
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.
256 */
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 },
261
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
266 * SMF_RPKE_AUTH:
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
269 */
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 },
274
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 */ },
279
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 */ },
284
285 /* for states from here on, output message must be encrypted */
286
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
291 * --> HDR*, HASH_I
292 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
293 * --> HDR*, HASH_I
294 */
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 },
299
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 */ },
304
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 */ },
309
310 /* for states from here on, input message must be encrypted */
311
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
316 */
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 },
322
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 },
328
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 */ },
334
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
340 */
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 },
346
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 },
352
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 */ },
358
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
362 , LEMPTY, LEMPTY
363 , PT(NONE), EVENT_NULL, unexpected },
364
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
368 , LEMPTY, LEMPTY
369 , PT(NONE), EVENT_NULL, unexpected },
370
371
372 /***** Phase 2 Quick Mode *****/
373
374 /* No state for quick_outI1:
375 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
376 */
377
378 /* STATE_QUICK_R0:
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.
385 */
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 },
390
391 /* STATE_QUICK_I1:
392 * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ] -->
393 * HDR*, HASH(3)
394 * Installs inbound and outbound IPsec SAs, routing, etc.
395 * ??? it is legal to have multiple SAs, but we don't support it yet.
396 */
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 },
401
402 /* STATE_QUICK_R1: HDR*, HASH(3) --> done
403 * Installs outbound IPsec SAs, routing, etc.
404 */
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 },
409
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 },
415
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 },
421
422
423 /***** informational messages *****/
424
425 /* STATE_INFO: */
426 { STATE_INFO, STATE_UNDEFINED
427 , SMF_ALL_AUTH
428 , LEMPTY, LEMPTY, PT(NONE)
429 , EVENT_NULL, informational },
430
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 },
436
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 },
442
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 },
447
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 },
452
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 },
457
458 { STATE_XAUTH_I2, STATE_UNDEFINED
459 , SMF_ALL_AUTH | SMF_ENCRYPTED
460 , LEMPTY, LEMPTY, PT(NONE)
461 , EVENT_NULL, unexpected },
462
463 { STATE_XAUTH_R3, STATE_UNDEFINED
464 , SMF_ALL_AUTH | SMF_ENCRYPTED
465 , LEMPTY, LEMPTY, PT(NONE)
466 , EVENT_NULL, unexpected },
467
468 /* ModeCfg pull mode state transitions */
469
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 },
474
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 },
479
480 { STATE_MODE_CFG_R1, STATE_UNDEFINED
481 , SMF_ALL_AUTH | SMF_ENCRYPTED
482 , LEMPTY, LEMPTY, PT(NONE)
483 , EVENT_NULL, unexpected },
484
485 { STATE_MODE_CFG_I2, STATE_UNDEFINED
486 , SMF_ALL_AUTH | SMF_ENCRYPTED
487 , LEMPTY, LEMPTY, PT(NONE)
488 , EVENT_NULL, unexpected },
489
490 /* ModeCfg push mode state transitions */
491
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 },
496
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 },
501
502 { STATE_MODE_CFG_I3, STATE_UNDEFINED
503 , SMF_ALL_AUTH | SMF_ENCRYPTED
504 , LEMPTY, LEMPTY, PT(NONE)
505 , EVENT_NULL, unexpected },
506
507 { STATE_MODE_CFG_R4, STATE_UNDEFINED
508 , SMF_ALL_AUTH | SMF_ENCRYPTED
509 , LEMPTY, LEMPTY, PT(NONE)
510 , EVENT_NULL, unexpected },
511
512 #undef P
513 #undef PT
514 };
515
516 void
517 init_demux(void)
518 {
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.
524 */
525 const struct state_microcode *t;
526
527 for (t = &state_microcode_table[countof(state_microcode_table) - 1];;)
528 {
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)
532 break;
533 t--;
534 passert(t[0].state <= t[1].state);
535 }
536 }
537
538 /* Process any message on the MSG_ERRQUEUE
539 *
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).
543 *
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
548 *
549 * ??? we should link this message with one we've sent
550 * so that the diagnostic can refer to that negotiation.
551 *
552 * ??? how long can the messge be?
553 *
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.
557 *
558 * We have to code around a couple of surprises:
559 *
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.
565 *
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.
570 *
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.
574 *
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).
581 */
582
583 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
584 static bool
585 check_msg_errqueue(const struct iface *ifp, short interest)
586 {
587 struct pollfd pfd;
588
589 pfd.fd = ifp->fd;
590 pfd.events = interest | POLLPRI | POLLOUT;
591
592 while (pfd.revents = 0
593 , poll(&pfd, 1, -1) > 0 && (pfd.revents & POLLERR))
594 {
595 u_int8_t buffer[3000]; /* hope that this is big enough */
596 union
597 {
598 struct sockaddr sa;
599 struct sockaddr_in sa_in4;
600 struct sockaddr_in6 sa_in6;
601 } from;
602
603 int from_len = sizeof(from);
604
605 int packet_len;
606
607 struct msghdr emh;
608 struct iovec eiov;
609 union {
610 /* force alignment (not documented as necessary) */
611 struct cmsghdr ecms;
612
613 /* how much space is enough? */
614 unsigned char space[256];
615 } ecms_buf;
616
617 struct cmsghdr *cm;
618 char fromstr[sizeof(" for message to port 65536") + INET6_ADDRSTRLEN];
619 struct state *sender = NULL;
620
621 zero(&from.sa);
622 from_len = sizeof(from);
623
624 emh.msg_name = &from.sa; /* ??? filled in? */
625 emh.msg_namelen = sizeof(from);
626 emh.msg_iov = &eiov;
627 emh.msg_iovlen = 1;
628 emh.msg_control = &ecms_buf;
629 emh.msg_controllen = sizeof(ecms_buf);
630 emh.msg_flags = 0;
631
632 eiov.iov_base = buffer; /* see readv(2) */
633 eiov.iov_len = sizeof(buffer);
634
635 packet_len = recvmsg(ifp->fd, &emh, MSG_ERRQUEUE);
636
637 if (packet_len == -1)
638 {
639 log_errno((e, "recvmsg(,, MSG_ERRQUEUE) on %s failed in comm_handle"
640 , ifp->rname));
641 break;
642 }
643 else if (packet_len == sizeof(buffer))
644 {
645 plog("MSG_ERRQUEUE message longer than %lu bytes; truncated"
646 , (unsigned long) sizeof(buffer));
647 }
648 else
649 {
650 sender = find_sender((size_t) packet_len, buffer);
651 }
652
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.
660 */
661 passert(emh.msg_name == &from.sa);
662 DBG_cond_dump(DBG_ALL, "name:\n", emh.msg_name
663 , emh.msg_namelen);
664
665 fromstr[0] = '\0'; /* usual case :-( */
666 switch (from.sa.sa_family)
667 {
668 char as[INET6_ADDRSTRLEN];
669
670 case AF_INET:
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));
677 break;
678 case AF_INET6:
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));
685 break;
686 }
687
688 for (cm = CMSG_FIRSTHDR(&emh)
689 ; cm != NULL
690 ; cm = CMSG_NXTHDR(&emh,cm))
691 {
692 if (cm->cmsg_level == SOL_IP
693 && cm->cmsg_type == IP_RECVERR)
694 {
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.
701 *
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
705 * is meaningless.
706 */
707
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.
711 */
712 struct sock_extended_err *ee = (void *)CMSG_DATA(cm);
713 const char *offstr = "unspecified";
714 char offstrspace[INET6_ADDRSTRLEN];
715 char orname[50];
716
717 if (cm->cmsg_len > CMSG_LEN(sizeof(struct sock_extended_err)))
718 {
719 const struct sockaddr *offender = SO_EE_OFFENDER(ee);
720
721 switch (offender->sa_family)
722 {
723 case AF_INET:
724 offstr = inet_ntop(offender->sa_family
725 , &((const struct sockaddr_in *)offender)->sin_addr
726 , offstrspace, sizeof(offstrspace));
727 break;
728 case AF_INET6:
729 offstr = inet_ntop(offender->sa_family
730 , &((const struct sockaddr_in6 *)offender)->sin6_addr
731 , offstrspace, sizeof(offstrspace));
732 break;
733 default:
734 offstr = "unknown";
735 break;
736 }
737 }
738
739 switch (ee->ee_origin)
740 {
741 case SO_EE_ORIGIN_NONE:
742 snprintf(orname, sizeof(orname), "none");
743 break;
744 case SO_EE_ORIGIN_LOCAL:
745 snprintf(orname, sizeof(orname), "local");
746 break;
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
751 );
752 break;
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
757 );
758 break;
759 default:
760 snprintf(orname, sizeof(orname), "invalid origin %lu"
761 , (unsigned long) ee->ee_origin);
762 break;
763 }
764
765 {
766 struct state *old_state = cur_state;
767
768 cur_state = sender;
769
770 /* note dirty trick to suppress ~ at start of format
771 * if we know what state to blame.
772 */
773 if ((packet_len == 1) && (buffer[0] = 0xff)
774 #ifdef DEBUG
775 && ((cur_debugging & DBG_NATT) == 0)
776 #endif
777 ) {
778 /* don't log NAT-T keepalive related errors unless NATT debug is
779 * enabled
780 */
781 }
782 else
783 plog((sender != NULL) + "~"
784 "ERROR: asynchronous network error report on %s"
785 "%s"
786 ", complainant %s"
787 ": %s"
788 " [errno %lu, origin %s"
789 /* ", pad %d, info %ld" */
790 /* ", data %ld" */
791 "]"
792 , ifp->rname
793 , fromstr
794 , offstr
795 , strerror(ee->ee_errno)
796 , (unsigned long) ee->ee_errno
797 , orname
798 /* , ee->ee_pad, (unsigned long)ee->ee_info */
799 /* , (unsigned long)ee->ee_data */
800 );
801 cur_state = old_state;
802 }
803 }
804 else
805 {
806 /* .cmsg_len is a kernel_size_t(!), but the value
807 * certainly ought to fit in an unsigned long.
808 */
809 plog("unknown cmsg: level %d, type %d, len %lu"
810 , cm->cmsg_level, cm->cmsg_type
811 , (unsigned long) cm->cmsg_len);
812 }
813 }
814 }
815 return (pfd.revents & interest) != 0;
816 }
817 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
818
819 bool
820 send_packet(struct state *st, const char *where)
821 {
822 connection_t *c = st->st_connection;
823 int port_buf;
824 bool err;
825 u_int8_t ike_pkt[MAX_OUTPUT_UDP_SIZE];
826 u_int8_t *ptr;
827 unsigned long len;
828
829 if (c->interface->ike_float && st->st_tpacket.len != 1)
830 {
831 if ((unsigned long) st->st_tpacket.len > (MAX_OUTPUT_UDP_SIZE-sizeof(u_int32_t)))
832 {
833 DBG_log("send_packet(): really too big");
834 return FALSE;
835 }
836 ptr = ike_pkt;
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);
842 }
843 else
844 {
845 ptr = st->st_tpacket.ptr;
846 len = (unsigned long) st->st_tpacket.len;
847 }
848
849 DBG(DBG_RAW,
850 {
851 DBG_log("sending %lu bytes for %s through %s to %s:%u:"
852 , (unsigned long) st->st_tpacket.len
853 , where
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);
858 });
859
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.
863 */
864
865 port_buf = portof(&c->spd.that.host_addr);
866 setportof(htons(c->spd.that.host_port), &c->spd.that.host_addr);
867
868 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
869 (void) check_msg_errqueue(c->interface, POLLOUT);
870 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
871
872 err = sendto(c->interface->fd
873 , ptr, len, 0
874 , sockaddrof(&c->spd.that.host_addr)
875 , sockaddrlenof(&c->spd.that.host_addr)) != (ssize_t)len;
876
877 /* restore port */
878 setportof(port_buf, &c->spd.that.host_addr);
879
880 if (err)
881 {
882 /* do not log NAT-T Keep Alive packets */
883 if (streq(where, "NAT-T Keep Alive"))
884 return FALSE;
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
889 , where));
890 return FALSE;
891 }
892 else
893 {
894 return TRUE;
895 }
896 }
897
898 static stf_status
899 unexpected(struct msg_digest *md)
900 {
901 loglog(RC_LOG_SERIOUS, "unexpected message received in state %s"
902 , enum_name(&state_names, md->st->st_state));
903 return STF_IGNORE;
904 }
905
906 static stf_status
907 informational(struct msg_digest *md UNUSED)
908 {
909 struct payload_digest *const n_pld = md->chain[ISAKMP_NEXT_N];
910
911 /* If the Notification Payload is not null... */
912 if (n_pld != NULL)
913 {
914 pb_stream *const n_pbs = &n_pld->pbs;
915 struct isakmp_notification *const n = &n_pld->payload.notification;
916 int disp_len;
917 char disp_buf[200];
918
919 /* Switch on Notification Type (enum) */
920 switch (n->isan_type)
921 {
922 case R_U_THERE:
923 return dpd_inI_outR(md->st, n, n_pbs);
924
925 case R_U_THERE_ACK:
926 return dpd_inR(md->st, n, n_pbs);
927 default:
928 if (pbs_left(n_pbs) >= sizeof(disp_buf)-1)
929 disp_len = sizeof(disp_buf)-1;
930 else
931 disp_len = pbs_left(n_pbs);
932 memcpy(disp_buf, n_pbs->cur, disp_len);
933 disp_buf[disp_len] = '\0';
934 break;
935 }
936 }
937 return STF_IGNORE;
938 }
939
940 /* message digest allocation and deallocation */
941
942 static struct msg_digest *md_pool = NULL;
943
944 /* free_md_pool is only used to avoid leak reports */
945 void
946 free_md_pool(void)
947 {
948 for (;;)
949 {
950 struct msg_digest *md = md_pool;
951
952 if (md == NULL)
953 break;
954 md_pool = md->next;
955 free(md);
956 }
957 }
958
959 static struct msg_digest *
960 malloc_md(void)
961 {
962 struct msg_digest *md = md_pool;
963
964 /* convenient initializer:
965 * - all pointers NULL
966 * - .note = NOTHING_WRONG
967 * - .encrypted = FALSE
968 */
969 static const struct msg_digest blank_md;
970
971 if (md == NULL)
972 {
973 md = malloc_thing(struct msg_digest);
974 zero(md);
975 }
976 else
977 md_pool = md->next;
978
979 *md = blank_md;
980 md->digest_roof = md->digest;
981
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.
985 */
986 init_pbs(&md->reply, reply_buffer, sizeof(reply_buffer), "reply packet");
987
988 return md;
989 }
990
991 void
992 release_md(struct msg_digest *md)
993 {
994 chunk_free(&md->raw_packet);
995 free(md->packet_pbs.start);
996 md->packet_pbs.start = NULL;
997 md->next = md_pool;
998 md_pool = md;
999 }
1000
1001 /* wrapper for read_packet and process_packet
1002 *
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.
1006 *
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.
1010 *
1011 * read_packet is broken out to minimize the lifetime of the
1012 * enormous input packet buffer, an auto.
1013 */
1014 void
1015 comm_handle(const struct iface *ifp)
1016 {
1017 static struct msg_digest *md;
1018
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
1025 * to read.
1026 *
1027 * This is early enough that teardown isn't required:
1028 * just return on failure.
1029 */
1030 if (!check_msg_errqueue(ifp, POLLIN))
1031 return; /* no normal message to read */
1032 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
1033
1034 md = malloc_md();
1035 md->iface = ifp;
1036
1037 if (read_packet(md))
1038 process_packet(&md);
1039
1040 if (md != NULL)
1041 release_md(md);
1042
1043 cur_state = NULL;
1044 reset_cur_connection();
1045 cur_from = NULL;
1046 }
1047
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.
1052 */
1053 static bool
1054 read_packet(struct msg_digest *md)
1055 {
1056 const struct iface *ifp = md->iface;
1057 int packet_len;
1058 u_int8_t *buffer;
1059 u_int8_t *buffer_nat;
1060 union
1061 {
1062 struct sockaddr sa;
1063 struct sockaddr_in sa_in4;
1064 struct sockaddr_in6 sa_in6;
1065 } from;
1066 int from_len = sizeof(from);
1067 err_t from_ugh = NULL;
1068 static const char undisclosed[] = "unknown source";
1069
1070 happy(anyaddr(addrtypeof(&ifp->addr), &md->sender));
1071 zero(&from.sa);
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);
1076
1077 /* First: digest the from address.
1078 * We presume that nothing here disturbs errno.
1079 */
1080 if (packet_len == -1
1081 && from_len == sizeof(from)
1082 && all_zero((const void *)&from.sa, sizeof(from)))
1083 {
1084 /* "from" is untouched -- not set by recvfrom */
1085 from_ugh = undisclosed;
1086 }
1087 else if (from_len
1088 < (int) (offsetof(struct sockaddr, sa_family) + sizeof(from.sa.sa_family)))
1089 {
1090 from_ugh = "truncated";
1091 }
1092 else
1093 {
1094 const struct af_info *afi = aftoinfo(from.sa.sa_family);
1095
1096 if (afi == NULL)
1097 {
1098 from_ugh = "unexpected Address Family";
1099 }
1100 else if (from_len != (int)afi->sa_sz)
1101 {
1102 from_ugh = "wrong length";
1103 }
1104 else
1105 {
1106 switch (from.sa.sa_family)
1107 {
1108 case AF_INET:
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);
1112 break;
1113 case AF_INET6:
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);
1117 break;
1118 }
1119 }
1120 }
1121
1122 /* now we report any actual I/O error */
1123 if (packet_len == -1)
1124 {
1125 if (from_ugh == undisclosed
1126 && errno == ECONNREFUSED)
1127 {
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.
1131 */
1132 plog("some IKE message we sent has been rejected with ECONNREFUSED (kernel supplied no details)");
1133 }
1134 else if (from_ugh != NULL)
1135 {
1136 log_errno((e, "recvfrom on %s failed; Pluto cannot decode source sockaddr in rejection: %s"
1137 , ifp->rname, from_ugh));
1138 }
1139 else
1140 {
1141 log_errno((e, "recvfrom on %s from %s:%u failed"
1142 , ifp->rname
1143 , ip_str(&md->sender), (unsigned)md->sender_port));
1144 }
1145
1146 return FALSE;
1147 }
1148 else if (from_ugh != NULL)
1149 {
1150 plog("recvfrom on %s returned misformed source sockaddr: %s"
1151 , ifp->rname, from_ugh);
1152 return FALSE;
1153 }
1154 cur_from = &md->sender;
1155 cur_from_port = md->sender_port;
1156
1157 if (ifp->ike_float == TRUE)
1158 {
1159 u_int32_t non_esp;
1160
1161 if (packet_len < (int)sizeof(u_int32_t))
1162 {
1163 plog("recvfrom %s:%u too small packet (%d)"
1164 , ip_str(cur_from), (unsigned) cur_from_port, packet_len);
1165 return FALSE;
1166 }
1167 memcpy(&non_esp, buffer, sizeof(u_int32_t));
1168 if (non_esp != 0)
1169 {
1170 plog("recvfrom %s:%u has no Non-ESP marker"
1171 , ip_str(cur_from), (unsigned) cur_from_port);
1172 return FALSE;
1173 }
1174 packet_len -= sizeof(u_int32_t);
1175 buffer_nat = malloc(packet_len);
1176 memcpy(buffer_nat, buffer + sizeof(u_int32_t), packet_len);
1177 free(buffer);
1178 buffer = buffer_nat;
1179 }
1180
1181 /* Clone actual message contents
1182 * and set up md->packet_pbs to describe it.
1183 */
1184 init_pbs(&md->packet_pbs, buffer, packet_len, "packet");
1185
1186 DBG(DBG_RAW | DBG_CRYPT | DBG_PARSING | DBG_CONTROL,
1187 {
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
1192 , ifp->rname);
1193 });
1194
1195 DBG(DBG_RAW,
1196 DBG_dump("", md->packet_pbs.start, pbs_room(&md->packet_pbs)));
1197
1198 if ((pbs_room(&md->packet_pbs)==1) && (md->packet_pbs.start[0]==0xff))
1199 {
1200 /**
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.
1204 */
1205 DBG(DBG_NATT,
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);
1209 )
1210 return FALSE;
1211 }
1212
1213 #define IKEV2_VERSION_OFFSET 17
1214 #define IKEV2_VERSION 0x20
1215
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)
1219 {
1220 DBG(DBG_CONTROLMORE,
1221 DBG_log(" ignoring IKEv2 packet")
1222 )
1223 return FALSE;
1224 }
1225
1226 return TRUE;
1227 }
1228
1229 /* process an input packet, possibly generating a reply.
1230 *
1231 * If all goes well, this routine eventually calls a state-specific
1232 * transition function.
1233 */
1234 static void
1235 process_packet(struct msg_digest **mdp)
1236 {
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;
1243
1244 struct state *st = NULL;
1245 enum state_kind from_state = STATE_UNDEFINED; /* state we started in */
1246
1247 #define SEND_NOTIFICATION(t) { \
1248 if (st) send_notification_from_state(st, from_state, t); \
1249 else send_notification_from_md(md, t); }
1250
1251 if (!in_struct(&md->hdr, &isakmp_hdr_desc, &md->packet_pbs, &md->message_pbs))
1252 {
1253 /* Identify specific failures:
1254 * - bad ISAKMP major/minor version numbers
1255 */
1256 if (md->packet_pbs.roof - md->packet_pbs.cur >= (ptrdiff_t)isakmp_hdr_desc.size)
1257 {
1258 struct isakmp_hdr *hdr = (struct isakmp_hdr *)md->packet_pbs.cur;
1259 if ((hdr->isa_version >> ISA_MAJ_SHIFT) != ISAKMP_MAJOR_VERSION)
1260 {
1261 SEND_NOTIFICATION(ISAKMP_INVALID_MAJOR_VERSION);
1262 return;
1263 }
1264 else if ((hdr->isa_version & ISA_MIN_MASK) != ISAKMP_MINOR_VERSION)
1265 {
1266 SEND_NOTIFICATION(ISAKMP_INVALID_MINOR_VERSION);
1267 return;
1268 }
1269 }
1270 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
1271 return;
1272 }
1273
1274 if (md->packet_pbs.roof != md->message_pbs.roof)
1275 {
1276 plog("size (%u) differs from size specified in ISAKMP HDR (%u)"
1277 , (unsigned) pbs_room(&md->packet_pbs), md->hdr.isa_length);
1278 #ifdef CISCO_QUIRKS
1279 if (pbs_room(&md->packet_pbs) - md->hdr.isa_length == 16)
1280 plog("Cisco VPN client appends 16 surplus NULL bytes");
1281 else
1282 #endif
1283 return;
1284 }
1285
1286 switch (md->hdr.isa_xchg)
1287 {
1288 #ifdef NOTYET
1289 case ISAKMP_XCHG_NONE:
1290 case ISAKMP_XCHG_BASE:
1291 #endif
1292
1293 case ISAKMP_XCHG_IDPROT: /* part of a Main Mode exchange */
1294 if (md->hdr.isa_msgid != MAINMODE_MSGID)
1295 {
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);
1299 return;
1300 }
1301
1302 if (is_zero_cookie(md->hdr.isa_icookie))
1303 {
1304 plog("Initiator Cookie must not be zero in Main Mode message");
1305 SEND_NOTIFICATION(ISAKMP_INVALID_COOKIE);
1306 return;
1307 }
1308
1309 if (is_zero_cookie(md->hdr.isa_rcookie))
1310 {
1311 /* initial message from initiator
1312 * ??? what if this is a duplicate of another message?
1313 */
1314 if (md->hdr.isa_flags & ISAKMP_FLAG_ENCRYPTION)
1315 {
1316 plog("initial Main Mode message is invalid:"
1317 " its Encrypted Flag is on");
1318 SEND_NOTIFICATION(ISAKMP_INVALID_FLAGS);
1319 return;
1320 }
1321
1322 /* don't build a state until the message looks tasty */
1323 from_state = STATE_MAIN_R0;
1324 }
1325 else
1326 {
1327 /* not an initial message */
1328
1329 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1330 , &md->sender, md->hdr.isa_msgid);
1331
1332 if (st == NULL)
1333 {
1334 /* perhaps this is a first message from the responder
1335 * and contains a responder cookie that we've not yet seen.
1336 */
1337 st = find_state(md->hdr.isa_icookie, zero_cookie
1338 , &md->sender, md->hdr.isa_msgid);
1339
1340 if (st == NULL)
1341 {
1342 plog("Main Mode message is part of an unknown exchange");
1343 /* XXX Could send notification back */
1344 return;
1345 }
1346 }
1347 set_cur_state(st);
1348 from_state = st->st_state;
1349 }
1350 break;
1351
1352 #ifdef NOTYET
1353 case ISAKMP_XCHG_AO:
1354 case ISAKMP_XCHG_AGGR:
1355 #endif
1356
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);
1360
1361 if (st != NULL)
1362 set_cur_state(st);
1363
1364 if (md->hdr.isa_flags & ISAKMP_FLAG_ENCRYPTION)
1365 {
1366 if (st == NULL)
1367 {
1368 plog("Informational Exchange is for an unknown (expired?) SA");
1369 /* XXX Could send notification back */
1370 return;
1371 }
1372
1373 if (!IS_ISAKMP_ENCRYPTED(st->st_state))
1374 {
1375 loglog(RC_LOG_SERIOUS, "encrypted Informational Exchange message is invalid"
1376 " because no key is known");
1377 /* XXX Could send notification back */
1378 return;
1379 }
1380
1381 if (md->hdr.isa_msgid == MAINMODE_MSGID)
1382 {
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 */
1386 return;
1387 }
1388
1389 if (!reserve_msgid(st, md->hdr.isa_msgid))
1390 {
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 */
1395 return;
1396 }
1397
1398 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1399 {
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;
1402
1403 /* backup new_iv */
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);
1407 restore_iv = TRUE;
1408 }
1409 init_phase2_iv(st, &md->hdr.isa_msgid);
1410 new_iv_set = TRUE;
1411
1412 from_state = STATE_INFO_PROTECTED;
1413 }
1414 else
1415 {
1416 if (st != NULL && IS_ISAKMP_ENCRYPTED(st->st_state))
1417 {
1418 loglog(RC_LOG_SERIOUS, "Informational Exchange message"
1419 " must be encrypted");
1420 /* XXX Could send notification back */
1421 return;
1422 }
1423 from_state = STATE_INFO;
1424 }
1425 break;
1426
1427 case ISAKMP_XCHG_QUICK: /* part of a Quick Mode exchange */
1428 if (is_zero_cookie(md->hdr.isa_icookie))
1429 {
1430 plog("Quick Mode message is invalid because"
1431 " it has an Initiator Cookie of 0");
1432 SEND_NOTIFICATION(ISAKMP_INVALID_COOKIE);
1433 return;
1434 }
1435
1436 if (is_zero_cookie(md->hdr.isa_rcookie))
1437 {
1438 plog("Quick Mode message is invalid because"
1439 " it has a Responder Cookie of 0");
1440 SEND_NOTIFICATION(ISAKMP_INVALID_COOKIE);
1441 return;
1442 }
1443
1444 if (md->hdr.isa_msgid == MAINMODE_MSGID)
1445 {
1446 plog("Quick Mode message is invalid because"
1447 " it has a Message ID of 0");
1448 SEND_NOTIFICATION(ISAKMP_INVALID_MESSAGE_ID);
1449 return;
1450 }
1451
1452 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1453 , &md->sender, md->hdr.isa_msgid);
1454
1455 if (st == NULL)
1456 {
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?
1460 */
1461 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1462 , &md->sender, MAINMODE_MSGID);
1463
1464 if (st == NULL)
1465 {
1466 plog("Quick Mode message is for a non-existent (expired?)"
1467 " ISAKMP SA");
1468 /* XXX Could send notification back */
1469 return;
1470 }
1471
1472 set_cur_state(st);
1473
1474 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1475 {
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 ? */);
1479 return;
1480 }
1481
1482 /* only accept this new Quick Mode exchange if it has a unique message ID */
1483 if (!reserve_msgid(st, md->hdr.isa_msgid))
1484 {
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);
1490 return;
1491 }
1492
1493 /* Quick Mode Initial IV */
1494 init_phase2_iv(st, &md->hdr.isa_msgid);
1495 new_iv_set = TRUE;
1496
1497 from_state = STATE_QUICK_R0;
1498 }
1499 else
1500 {
1501 set_cur_state(st);
1502 from_state = st->st_state;
1503 }
1504
1505 break;
1506
1507 case ISAKMP_XCHG_MODE_CFG:
1508 if (is_zero_cookie(md->hdr.isa_icookie))
1509 {
1510 plog("ModeCfg message is invalid because"
1511 " it has an Initiator Cookie of 0");
1512 /* XXX Could send notification back */
1513 return;
1514 }
1515
1516 if (is_zero_cookie(md->hdr.isa_rcookie))
1517 {
1518 plog("ModeCfg message is invalid because"
1519 " it has a Responder Cookie of 0");
1520 /* XXX Could send notification back */
1521 return;
1522 }
1523
1524 if (md->hdr.isa_msgid == 0)
1525 {
1526 plog("ModeCfg message is invalid because"
1527 " it has a Message ID of 0");
1528 /* XXX Could send notification back */
1529 return;
1530 }
1531
1532 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1533 , &md->sender, md->hdr.isa_msgid);
1534
1535 if (st == NULL)
1536 {
1537 bool has_xauth_policy;
1538
1539 /* No appropriate ModeCfg state.
1540 * See if we have a Main Mode state.
1541 * ??? what if this is a duplicate of another message?
1542 */
1543 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1544 , &md->sender, 0);
1545
1546 if (st == NULL)
1547 {
1548 plog("ModeCfg message is for a non-existent (expired?)"
1549 " ISAKMP SA");
1550 /* XXX Could send notification back */
1551 return;
1552 }
1553
1554 set_cur_state(st);
1555
1556 /* the XAUTH_STATUS message might have a new msgid */
1557 if (st->st_state == STATE_XAUTH_I1)
1558 {
1559 init_phase2_iv(st, &md->hdr.isa_msgid);
1560 new_iv_set = TRUE;
1561 from_state = st->st_state;
1562 break;
1563 }
1564
1565 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1566 {
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 */
1571 return;
1572 }
1573 init_phase2_iv(st, &md->hdr.isa_msgid);
1574 new_iv_set = TRUE;
1575
1576 /*
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).
1581 *
1582 * or if receiving for the first time, an XAUTH challenge.
1583 *
1584 * or if we are getting a MODECFG request.
1585 *
1586 * we distinguish these states because we can not both be an
1587 * XAUTH server and client, and our policy tells us which
1588 * one we are.
1589 *
1590 * to complicate further, it is normal to start a new msgid
1591 * when going from one state to another, or when restarting
1592 * the challenge.
1593 *
1594 */
1595
1596 has_xauth_policy = (st->st_connection->policy
1597 & (POLICY_XAUTH_RSASIG | POLICY_XAUTH_PSK))
1598 != LEMPTY;
1599
1600 if (has_xauth_policy && !st->st_xauth.started
1601 && IS_PHASE1(st->st_state))
1602 {
1603 from_state = STATE_XAUTH_I0;
1604 }
1605 else if (st->st_connection->spd.that.modecfg
1606 && IS_PHASE1(st->st_state))
1607 {
1608 from_state = STATE_MODE_CFG_R0;
1609 }
1610 else if (st->st_connection->spd.this.modecfg
1611 && IS_PHASE1(st->st_state))
1612 {
1613 from_state = STATE_MODE_CFG_I0;
1614 }
1615 else
1616 {
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));
1620 return;
1621 }
1622 }
1623 else
1624 {
1625 set_cur_state(st);
1626 from_state = st->st_state;
1627 }
1628 break;
1629
1630 #ifdef NOTYET
1631 case ISAKMP_XCHG_NGRP:
1632 case ISAKMP_XCHG_ACK_INFO:
1633 #endif
1634
1635 default:
1636 plog("unsupported exchange type %s in message"
1637 , enum_show(&exchange_names, md->hdr.isa_xchg));
1638 SEND_NOTIFICATION(ISAKMP_UNSUPPORTED_EXCHANGE_TYPE);
1639 return;
1640 }
1641
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.
1645 */
1646
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.
1654 */
1655 if (md->hdr.isa_flags & ISAKMP_FLAG_COMMIT)
1656 {
1657 plog("IKE message has the Commit Flag set but Pluto doesn't implement this feature; ignoring flag");
1658 }
1659
1660 /* Set smc to describe this state's properties.
1661 * Look up the appropriate microcode based on state and
1662 * possibly Oakley Auth type.
1663 */
1664 passert(STATE_IKE_FLOOR <= from_state && from_state <= STATE_IKE_ROOF);
1665 smc = ike_microcode_index[from_state - STATE_IKE_FLOOR];
1666
1667 if (st != NULL)
1668 {
1669 u_int16_t auth;
1670
1671 switch (st->st_oakley.auth)
1672 {
1673 case XAUTHInitPreShared:
1674 case XAUTHRespPreShared:
1675 auth = OAKLEY_PRESHARED_KEY;
1676 break;
1677 case XAUTHInitRSA:
1678 case XAUTHRespRSA:
1679 auth = OAKLEY_RSA_SIG;
1680 break;
1681 default:
1682 auth = st->st_oakley.auth;
1683 }
1684
1685 while (!LHAS(smc->flags, auth))
1686 {
1687 smc++;
1688 passert(smc->state == from_state);
1689 }
1690 }
1691
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?
1696 */
1697 if (st != NULL && st->st_suspended_md != NULL)
1698 {
1699 loglog(RC_LOG, "discarding packet received during DNS lookup in %s"
1700 , enum_name(&state_names, st->st_state));
1701 return;
1702 }
1703
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!
1713 */
1714 if (st != NULL
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))
1718 {
1719 if (smc->flags & SMF_RETRANSMIT_ON_DUPLICATE)
1720 {
1721 if (st->st_retransmit < MAXIMUM_RETRANSMISSIONS)
1722 {
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");
1728 }
1729 else
1730 {
1731 loglog(RC_LOG_SERIOUS, "discarding duplicate packet -- exhausted retransmission; already %s"
1732 , enum_name(&state_names, st->st_state));
1733 }
1734 }
1735 else
1736 {
1737 loglog(RC_LOG_SERIOUS, "discarding duplicate packet; already %s"
1738 , enum_name(&state_names, st->st_state));
1739 }
1740 return;
1741 }
1742
1743 if (md->hdr.isa_flags & ISAKMP_FLAG_ENCRYPTION)
1744 {
1745 DBG(DBG_CRYPT, DBG_log("received encrypted packet from %s:%u"
1746 , ip_str(&md->sender), (unsigned)md->sender_port));
1747
1748 if (st == NULL)
1749 {
1750 plog("discarding encrypted message for an unknown ISAKMP SA");
1751 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED /* XXX ? */);
1752 return;
1753 }
1754 if (st->st_skeyid_e.ptr == (u_char *) NULL)
1755 {
1756 loglog(RC_LOG_SERIOUS, "discarding encrypted message"
1757 " because we haven't yet negotiated keying materiel");
1758 SEND_NOTIFICATION(ISAKMP_INVALID_FLAGS);
1759 return;
1760 }
1761
1762 /* Mark as encrypted */
1763 md->encrypted = TRUE;
1764
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)));
1768
1769 /* do the specified decryption
1770 *
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
1773 *
1774 * See RFC 2409 "IKE" Appendix B
1775 *
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.
1780 *
1781 * Each post phase 1 exchange generates IVs from
1782 * the last phase 1 block, not the last block sent.
1783 */
1784 {
1785 size_t crypter_block_size, crypter_iv_size;
1786 encryption_algorithm_t enc_alg;
1787 crypter_t *crypter;
1788 chunk_t data, iv;
1789 char *new_iv;
1790
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);
1794 crypter_iv_size = crypter->get_iv_size(crypter);
1795
1796 if (pbs_left(&md->message_pbs) % crypter_block_size != 0)
1797 {
1798 loglog(RC_LOG_SERIOUS, "malformed message: not a multiple of encryption blocksize");
1799 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
1800 return;
1801 }
1802
1803 /* XXX Detect weak keys */
1804
1805 /* grab a copy of raw packet (for duplicate packet detection) */
1806 md->raw_packet = chunk_create(md->packet_pbs.start, pbs_room(&md->packet_pbs));
1807 md->raw_packet = chunk_clone(md->raw_packet);
1808
1809 data = chunk_create(md->message_pbs.cur, pbs_left(&md->message_pbs));
1810
1811 /* Decrypt everything after header */
1812 if (!new_iv_set)
1813 {
1814 /* use old IV */
1815 passert(st->st_iv_len <= sizeof(st->st_new_iv));
1816 st->st_new_iv_len = st->st_iv_len;
1817 memcpy(st->st_new_iv, st->st_iv, st->st_new_iv_len);
1818 }
1819
1820 /* form iv by truncation */
1821 st->st_new_iv_len = crypter_iv_size;
1822 iv = chunk_create(st->st_new_iv, st->st_new_iv_len);
1823 new_iv = alloca(crypter_iv_size);
1824 memcpy(new_iv, data.ptr + data.len - crypter_iv_size,
1825 crypter_iv_size);
1826
1827 crypter->set_key(crypter, st->st_enc_key);
1828 crypter->decrypt(crypter, data, iv, NULL);
1829 crypter->destroy(crypter);
1830
1831 memcpy(st->st_new_iv, new_iv, crypter_iv_size);
1832 if (restore_iv)
1833 {
1834 memcpy(st->st_new_iv, new_iv, new_iv_len);
1835 st->st_new_iv_len = new_iv_len;
1836 }
1837 }
1838
1839 DBG_cond_dump(DBG_CRYPT, "decrypted:\n", md->message_pbs.cur
1840 , md->message_pbs.roof - md->message_pbs.cur);
1841
1842 DBG_cond_dump(DBG_CRYPT, "next IV:"
1843 , st->st_new_iv, st->st_new_iv_len);
1844 }
1845 else
1846 {
1847 /* packet was not encryped -- should it have been? */
1848
1849 if (smc->flags & SMF_INPUT_ENCRYPTED)
1850 {
1851 loglog(RC_LOG_SERIOUS, "packet rejected: should have been encrypted");
1852 SEND_NOTIFICATION(ISAKMP_INVALID_FLAGS);
1853 return;
1854 }
1855 }
1856
1857 /* Digest the message.
1858 * Padding must be removed to make hashing work.
1859 * Padding comes from encryption (so this code must be after decryption).
1860 * Padding rules are described before the definition of
1861 * struct isakmp_hdr in packet.h.
1862 */
1863 {
1864 struct payload_digest *pd = md->digest;
1865 int np = md->hdr.isa_np;
1866 lset_t needed = smc->req_payloads;
1867 const char *excuse
1868 = LIN(SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT, smc->flags)
1869 ? "probable authentication failure (mismatch of preshared secrets?): "
1870 : "";
1871
1872 while (np != ISAKMP_NEXT_NONE)
1873 {
1874 struct_desc *sd = np < ISAKMP_NEXT_ROOF? payload_descs[np] : NULL;
1875
1876 if (pd == &md->digest[PAYLIMIT])
1877 {
1878 loglog(RC_LOG_SERIOUS, "more than %d payloads in message; ignored", PAYLIMIT);
1879 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
1880 return;
1881 }
1882
1883 switch (np)
1884 {
1885 case ISAKMP_NEXT_NATD_RFC:
1886 case ISAKMP_NEXT_NATOA_RFC:
1887 if (!st || !(st->nat_traversal & NAT_T_WITH_RFC_VALUES))
1888 {
1889 /*
1890 * don't accept NAT-D/NAT-OA reloc directly in message, unless
1891 * we're using NAT-T RFC
1892 */
1893 sd = NULL;
1894 }
1895 break;
1896 }
1897
1898 if (sd == NULL)
1899 {
1900 /* payload type is out of range or requires special handling */
1901 switch (np)
1902 {
1903 case ISAKMP_NEXT_ID:
1904 sd = IS_PHASE1(from_state)
1905 ? &isakmp_identification_desc : &isakmp_ipsec_identification_desc;
1906 break;
1907 case ISAKMP_NEXT_NATD_DRAFTS:
1908 np = ISAKMP_NEXT_NATD_RFC; /* NAT-D relocated */
1909 sd = payload_descs[np];
1910 break;
1911 case ISAKMP_NEXT_NATOA_DRAFTS:
1912 np = ISAKMP_NEXT_NATOA_RFC; /* NAT-OA relocated */
1913 sd = payload_descs[np];
1914 break;
1915 default:
1916 loglog(RC_LOG_SERIOUS, "%smessage ignored because it contains an unknown or"
1917 " unexpected payload type (%s) at the outermost level"
1918 , excuse, enum_show(&payload_names, np));
1919 SEND_NOTIFICATION(ISAKMP_INVALID_PAYLOAD_TYPE);
1920 return;
1921 }
1922 }
1923
1924 {
1925 lset_t s = LELEM(np);
1926
1927 if (LDISJOINT(s
1928 , needed | smc->opt_payloads| LELEM(ISAKMP_NEXT_N) | LELEM(ISAKMP_NEXT_D)))
1929 {
1930 loglog(RC_LOG_SERIOUS, "%smessage ignored because it "
1931 "contains an unexpected payload type (%s)"
1932 , excuse, enum_show(&payload_names, np));
1933 SEND_NOTIFICATION(ISAKMP_INVALID_PAYLOAD_TYPE);
1934 return;
1935 }
1936 needed &= ~s;
1937 }
1938
1939 if (!in_struct(&pd->payload, sd, &md->message_pbs, &pd->pbs))
1940 {
1941 loglog(RC_LOG_SERIOUS, "%smalformed payload in packet", excuse);
1942 if (md->hdr.isa_xchg != ISAKMP_XCHG_INFO)
1943 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
1944 return;
1945 }
1946
1947 /* place this payload at the end of the chain for this type */
1948 {
1949 struct payload_digest **p;
1950
1951 for (p = &md->chain[np]; *p != NULL; p = &(*p)->next)
1952 ;
1953 *p = pd;
1954 pd->next = NULL;
1955 }
1956
1957 np = pd->payload.generic.isag_np;
1958 pd++;
1959
1960 /* since we've digested one payload happily, it is probably
1961 * the case that any decryption worked. So we will not suggest
1962 * encryption failure as an excuse for subsequent payload
1963 * problems.
1964 */
1965 excuse = "";
1966 }
1967
1968 md->digest_roof = pd;
1969
1970 DBG(DBG_PARSING,
1971 if (pbs_left(&md->message_pbs) != 0)
1972 DBG_log("removing %d bytes of padding", (int) pbs_left(&md->message_pbs)));
1973
1974 md->message_pbs.roof = md->message_pbs.cur;
1975
1976 /* check that all mandatory payloads appeared */
1977
1978 if (needed != 0)
1979 {
1980 loglog(RC_LOG_SERIOUS, "message for %s is missing payloads %s"
1981 , enum_show(&state_names, from_state)
1982 , bitnamesof(payload_name, needed));
1983 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
1984 return;
1985 }
1986 }
1987
1988 /* more sanity checking: enforce most ordering constraints */
1989
1990 if (IS_PHASE1(from_state))
1991 {
1992 /* rfc2409: The Internet Key Exchange (IKE), 5 Exchanges:
1993 * "The SA payload MUST precede all other payloads in a phase 1 exchange."
1994 */
1995 if (md->chain[ISAKMP_NEXT_SA] != NULL
1996 && md->hdr.isa_np != ISAKMP_NEXT_SA)
1997 {
1998 loglog(RC_LOG_SERIOUS, "malformed Phase 1 message: does not start with an SA payload");
1999 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
2000 return;
2001 }
2002 }
2003 else if (IS_QUICK(from_state))
2004 {
2005 /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode
2006 *
2007 * "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
2008 * header and a SA payload MUST immediately follow the HASH."
2009 * [NOTE: there may be more than one SA payload, so this is not
2010 * totally reasonable. Probably all SAs should be so constrained.]
2011 *
2012 * "If ISAKMP is acting as a client negotiator on behalf of another
2013 * party, the identities of the parties MUST be passed as IDci and
2014 * then IDcr."
2015 *
2016 * "With the exception of the HASH, SA, and the optional ID payloads,
2017 * there are no payload ordering restrictions on Quick Mode."
2018 */
2019
2020 if (md->hdr.isa_np != ISAKMP_NEXT_HASH)
2021 {
2022 loglog(RC_LOG_SERIOUS, "malformed Quick Mode message: does not start with a HASH payload");
2023 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
2024 return;
2025 }
2026
2027 {
2028 struct payload_digest *p;
2029 int i;
2030
2031 for (p = md->chain[ISAKMP_NEXT_SA], i = 1; p != NULL
2032 ; p = p->next, i++)
2033 {
2034 if (p != &md->digest[i])
2035 {
2036 loglog(RC_LOG_SERIOUS, "malformed Quick Mode message: SA payload is in wrong position");
2037 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
2038 return;
2039 }
2040 }
2041 }
2042
2043 /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode:
2044 * "If ISAKMP is acting as a client negotiator on behalf of another
2045 * party, the identities of the parties MUST be passed as IDci and
2046 * then IDcr."
2047 */
2048 {
2049 struct payload_digest *id = md->chain[ISAKMP_NEXT_ID];
2050
2051 if (id != NULL)
2052 {
2053 if (id->next == NULL || id->next->next != NULL)
2054 {
2055 loglog(RC_LOG_SERIOUS, "malformed Quick Mode message:"
2056 " if any ID payload is present,"
2057 " there must be exactly two");
2058 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
2059 return;
2060 }
2061 if (id+1 != id->next)
2062 {
2063 loglog(RC_LOG_SERIOUS, "malformed Quick Mode message:"
2064 " the ID payloads are not adjacent");
2065 SEND_NOTIFICATION(ISAKMP_PAYLOAD_MALFORMED);
2066 return;
2067 }
2068 }
2069 }
2070 }
2071
2072 /* Ignore payloads that we don't handle:
2073 * Delete, Notification, VendorID
2074 */
2075 /* XXX Handle deletions */
2076 /* XXX Handle Notifications */
2077 /* XXX Handle VID payloads */
2078 {
2079 struct payload_digest *p;
2080
2081 for (p = md->chain[ISAKMP_NEXT_N]; p != NULL; p = p->next)
2082 {
2083 if (p->payload.notification.isan_type != R_U_THERE
2084 && p->payload.notification.isan_type != R_U_THERE_ACK)
2085 {
2086 loglog(RC_LOG_SERIOUS, "ignoring informational payload, type %s"
2087 , enum_show(&notification_names, p->payload.notification.isan_type));
2088 }
2089 DBG_cond_dump(DBG_PARSING, "info:", p->pbs.cur, pbs_left(&p->pbs));
2090 }
2091
2092 for (p = md->chain[ISAKMP_NEXT_D]; p != NULL; p = p->next)
2093 {
2094 accept_delete(st, md, p);
2095 DBG_cond_dump(DBG_PARSING, "del:", p->pbs.cur, pbs_left(&p->pbs));
2096 }
2097
2098 for (p = md->chain[ISAKMP_NEXT_VID]; p != NULL; p = p->next)
2099 {
2100 handle_vendorid(md, p->pbs.cur, pbs_left(&p->pbs));
2101 }
2102 }
2103 md->from_state = from_state;
2104 md->smc = smc;
2105 md->st = st;
2106
2107 /* possibly fill in hdr */
2108 if (smc->first_out_payload != ISAKMP_NEXT_NONE)
2109 echo_hdr(md, (smc->flags & SMF_OUTPUT_ENCRYPTED) != 0
2110 , smc->first_out_payload);
2111
2112 complete_state_transition(mdp, smc->processor(md));
2113 }
2114
2115 /* complete job started by the state-specific state transition function */
2116
2117 void
2118 complete_state_transition(struct msg_digest **mdp, stf_status result)
2119 {
2120 bool has_xauth_policy;
2121 bool is_xauth_server;
2122 struct msg_digest *md = *mdp;
2123 const struct state_microcode *smc = md->smc;
2124 enum state_kind from_state = md->from_state;
2125 struct state *st;
2126
2127 cur_state = st = md->st; /* might have changed */
2128
2129 /* If state has DPD support, import it */
2130 if (st && md->dpd)
2131 st->st_dpd = TRUE;
2132
2133 switch (result)
2134 {
2135 case STF_IGNORE:
2136 break;
2137
2138 case STF_SUSPEND:
2139 /* the stf didn't complete its job: don't relase md */
2140 *mdp = NULL;
2141 break;
2142
2143 case STF_OK:
2144 /* advance the state */
2145 st->st_state = smc->next_state;
2146
2147 /* Delete previous retransmission event.
2148 * New event will be scheduled below.
2149 */
2150 delete_event(st);
2151
2152 /* replace previous receive packet with latest */
2153
2154 free(st->st_rpacket.ptr);
2155
2156 if (md->encrypted)
2157 {
2158 /* if encrypted, duplication already done */
2159 st->st_rpacket = md->raw_packet;
2160 md->raw_packet.ptr = NULL;
2161 }
2162 else
2163 {
2164 st->st_rpacket = chunk_create(md->packet_pbs.start,
2165 pbs_room(&md->packet_pbs));
2166 st->st_rpacket = chunk_clone(st->st_rpacket);
2167 }
2168
2169 /* free previous transmit packet */
2170 chunk_free(&st->st_tpacket);
2171
2172 /* if requested, send the new reply packet */
2173 if (smc->flags & SMF_REPLY)
2174 {
2175 close_output_pbs(&md->reply); /* good form, but actually a no-op */
2176
2177 st->st_tpacket = chunk_create(md->reply.start, pbs_offset(&md->reply));
2178 st->st_tpacket = chunk_clone(st->st_tpacket);
2179
2180 if (nat_traversal_enabled)
2181 nat_traversal_change_port_lookup(md, md->st);
2182
2183 /* actually send the packet
2184 * Note: this is a great place to implement "impairments"
2185 * for testing purposes. Suppress or duplicate the
2186 * send_packet call depending on st->st_state.
2187 */
2188 send_packet(st, enum_name(&state_names, from_state));
2189 }
2190
2191 /* Schedule for whatever timeout is specified */
2192 {
2193 time_t delay = UNDEFINED_TIME;
2194 enum event_type kind = smc->timeout_event;
2195 bool agreed_time = FALSE;
2196 connection_t *c = st->st_connection;
2197
2198 switch (kind)
2199 {
2200 case EVENT_RETRANSMIT: /* Retransmit packet */
2201 delay = EVENT_RETRANSMIT_DELAY_0;
2202 break;
2203
2204 case EVENT_SA_REPLACE: /* SA replacement event */
2205 if (IS_PHASE1(st->st_state))
2206 {
2207 /* Note: we will defer to the "negotiated" (dictated)
2208 * lifetime if we are POLICY_DONT_REKEY.
2209 * This allows the other side to dictate
2210 * a time we would not otherwise accept
2211 * but it prevents us from having to initiate
2212 * rekeying. The negative consequences seem
2213 * minor.
2214 */
2215 delay = c->sa_ike_life_seconds;
2216 if ((c->policy & POLICY_DONT_REKEY)
2217 || delay >= st->st_oakley.life_seconds)
2218 {
2219 agreed_time = TRUE;
2220 delay = st->st_oakley.life_seconds;
2221 }
2222 }
2223 else
2224 {
2225 /* Delay is min of up to four things:
2226 * each can limit the lifetime.
2227 */
2228 delay = c->sa_ipsec_life_seconds;
2229 if (st->st_ah.present
2230 && delay >= st->st_ah.attrs.life_seconds)
2231 {
2232 agreed_time = TRUE;
2233 delay = st->st_ah.attrs.life_seconds;
2234 }
2235 if (st->st_esp.present
2236 && delay >= st->st_esp.attrs.life_seconds)
2237 {
2238 agreed_time = TRUE;
2239 delay = st->st_esp.attrs.life_seconds;
2240 }
2241 if (st->st_ipcomp.present
2242 && delay >= st->st_ipcomp.attrs.life_seconds)
2243 {
2244 agreed_time = TRUE;
2245 delay = st->st_ipcomp.attrs.life_seconds;
2246 }
2247 }
2248
2249 /* By default, we plan to rekey.
2250 *
2251 * If there isn't enough time to rekey, plan to
2252 * expire.
2253 *
2254 * If we are --dontrekey, a lot more rules apply.
2255 * If we are the Initiator, use REPLACE_IF_USED.
2256 * If we are the Responder, and the dictated time
2257 * was unacceptable (too large), plan to REPLACE
2258 * (the only way to ratchet down the time).
2259 * If we are the Responder, and the dictated time
2260 * is acceptable, plan to EXPIRE.
2261 *
2262 * Important policy lies buried here.
2263 * For example, we favour the initiator over the
2264 * responder by making the initiator start rekeying
2265 * sooner. Also, fuzz is only added to the
2266 * initiator's margin.
2267 *
2268 * Note: for ISAKMP SA, we let the negotiated
2269 * time stand (implemented by earlier logic).
2270 */
2271 if (agreed_time
2272 && (c->policy & POLICY_DONT_REKEY))
2273 {
2274 kind = (smc->flags & SMF_INITIATOR)
2275 ? EVENT_SA_REPLACE_IF_USED
2276 : EVENT_SA_EXPIRE;
2277 }
2278 if (kind != EVENT_SA_EXPIRE)
2279 {
2280 unsigned long marg = c->sa_rekey_margin;
2281
2282 if (smc->flags & SMF_INITIATOR)
2283 marg += marg
2284 * c->sa_rekey_fuzz / 100.E0
2285 * (rand() / (RAND_MAX + 1.E0));
2286 else
2287 marg /= 2;
2288
2289 if ((unsigned long)delay > marg)
2290 {
2291 delay -= marg;
2292 st->st_margin = marg;
2293 }
2294 else
2295 {
2296 kind = EVENT_SA_EXPIRE;
2297 }
2298 }
2299 break;
2300
2301 case EVENT_NULL: /* non-event */
2302 case EVENT_REINIT_SECRET: /* Refresh cookie secret */
2303 default:
2304 bad_case(kind);
2305 }
2306 event_schedule(kind, delay, st);
2307 }
2308
2309 /* tell whack and log of progress */
2310 {
2311 const char *story = state_story[st->st_state];
2312 enum rc_type w = RC_NEW_STATE + st->st_state;
2313 char sadetails[128];
2314
2315 sadetails[0]='\0';
2316
2317 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
2318 {
2319 char *b = sadetails;
2320 const char *ini = " {";
2321 const char *fin = "";
2322
2323 /* -1 is to leave space for "fin" */
2324
2325 if (st->st_esp.present)
2326 {
2327 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2328 , "%sESP=>0x%08x <0x%08x"
2329 , ini
2330 , ntohl(st->st_esp.attrs.spi)
2331 , ntohl(st->st_esp.our_spi));
2332 ini = " ";
2333 fin = "}";
2334 }
2335 /* advance b to end of string */
2336 b = b + strlen(b);
2337
2338 if (st->st_ah.present)
2339 {
2340 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2341 , "%sAH=>0x%08x <0x%08x"
2342 , ini
2343 , ntohl(st->st_ah.attrs.spi)
2344 , ntohl(st->st_ah.our_spi));
2345 ini = " ";
2346 fin = "}";
2347 }
2348 /* advance b to end of string */
2349 b = b + strlen(b);
2350
2351 if (st->st_ipcomp.present)
2352 {
2353 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2354 , "%sIPCOMP=>0x%08x <0x%08x"
2355 , ini
2356 , ntohl(st->st_ipcomp.attrs.spi)
2357 , ntohl(st->st_ipcomp.our_spi));
2358 ini = " ";
2359 fin = "}";
2360 }
2361 /* advance b to end of string */
2362 b = b + strlen(b);
2363
2364 if (st->nat_traversal)
2365 {
2366 char oa[ADDRTOT_BUF];
2367 addrtot(&st->nat_oa, 0, oa, sizeof(oa));
2368 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2369 , "%sNATOA=%s"
2370 , ini, oa);
2371 ini = " ";
2372 fin = "}";
2373 }
2374
2375 /* advance b to end of string */
2376 b = b + strlen(b);
2377
2378 if (st->st_dpd)
2379 {
2380 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2381 , "%sDPD"
2382 , ini);
2383 ini = " ";
2384 fin = "}";
2385 }
2386
2387 strcat(b, fin);
2388 }
2389
2390 if (IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2391 || IS_IPSEC_SA_ESTABLISHED(st->st_state))
2392 {
2393 /* log our success */
2394 plog("%s%s", story, sadetails);
2395 w = RC_SUCCESS;
2396 }
2397
2398 /* tell whack our progress */
2399 whack_log(w
2400 , "%s: %s%s"
2401 , enum_name(&state_names, st->st_state)
2402 , story, sadetails);
2403 }
2404
2405 has_xauth_policy = (st->st_connection->policy
2406 & (POLICY_XAUTH_RSASIG | POLICY_XAUTH_PSK))
2407 != LEMPTY;
2408 is_xauth_server = (st->st_connection->policy
2409 & POLICY_XAUTH_SERVER)
2410 != LEMPTY;
2411
2412 /* Should we start XAUTH as a server */
2413 if (has_xauth_policy && is_xauth_server
2414 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2415 && !st->st_xauth.started)
2416 {
2417 DBG(DBG_CONTROL,
2418 DBG_log("starting XAUTH server")
2419 )
2420 xauth_send_request(st);
2421 break;
2422 }
2423
2424 /* Wait for XAUTH request from server */
2425 if (has_xauth_policy && !is_xauth_server
2426 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2427 && !st->st_xauth.started)
2428 {
2429 DBG(DBG_CONTROL,
2430 DBG_log("waiting for XAUTH request from server")
2431 )
2432 break;
2433 }
2434
2435 /* Should we start ModeConfig as a client? */
2436 if (st->st_connection->spd.this.modecfg
2437 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2438 && !(st->st_connection->policy & POLICY_MODECFG_PUSH)
2439 && !st->st_modecfg.started)
2440 {
2441 DBG(DBG_CONTROL,
2442 DBG_log("starting ModeCfg client in pull mode")
2443 )
2444 modecfg_send_request(st);
2445 break;
2446 }
2447
2448 /* Should we start ModeConfig as a server? */
2449 if (st->st_connection->spd.that.modecfg
2450 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2451 && !st->st_modecfg.started
2452 && (st->st_connection->policy & POLICY_MODECFG_PUSH))
2453 {
2454 DBG(DBG_CONTROL,
2455 DBG_log("starting ModeCfg server in push mode")
2456 )
2457 modecfg_send_set(st);
2458 break;
2459 }
2460
2461 /* Wait for ModeConfig set from server */
2462 if (st->st_connection->spd.this.modecfg
2463 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2464 && !st->st_modecfg.vars_set)
2465 {
2466 DBG(DBG_CONTROL,
2467 DBG_log("waiting for ModeCfg set from server")
2468 )
2469 break;
2470 }
2471
2472 if (smc->flags & SMF_RELEASE_PENDING_P2)
2473 {
2474 /* Initiate any Quick Mode negotiations that
2475 * were waiting to piggyback on this Keying Channel.
2476 *
2477 * ??? there is a potential race condition
2478 * if we are the responder: the initial Phase 2
2479 * message might outrun the final Phase 1 message.
2480 * I think that retransmission will recover.
2481 */
2482 unpend(st);
2483 }
2484
2485 if (IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2486 || IS_IPSEC_SA_ESTABLISHED(st->st_state))
2487 release_whack(st);
2488 break;
2489
2490 case STF_INTERNAL_ERROR:
2491 whack_log(RC_INTERNALERR + md->note
2492 , "%s: internal error"
2493 , enum_name(&state_names, st->st_state));
2494
2495 DBG(DBG_CONTROL,
2496 DBG_log("state transition function for %s had internal error"
2497 , enum_name(&state_names, from_state)));
2498 break;
2499
2500 default: /* a shortcut to STF_FAIL, setting md->note */
2501 passert(result > STF_FAIL);
2502 md->note = result - STF_FAIL;
2503 result = STF_FAIL;
2504 /* FALL THROUGH ... */
2505 case STF_FAIL:
2506 /* As it is, we act as if this message never happened:
2507 * whatever retrying was in place, remains in place.
2508 */
2509 whack_log(RC_NOTIFICATION + md->note
2510 , "%s: %s"
2511 , enum_name(&state_names, (st == NULL)? STATE_MAIN_R0:st->st_state)
2512 , enum_name(&notification_names, md->note));
2513
2514 SEND_NOTIFICATION(md->note);
2515
2516 DBG(DBG_CONTROL,
2517 DBG_log("state transition function for %s failed: %s"
2518 , enum_name(&state_names, from_state)
2519 , enum_name(&notification_names, md->note)));
2520 break;
2521 }
2522 }