1f47daf8fdd36d235367fb494c96797860c7662b
[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 * RCSID $Id: demux.c,v 1.14 2006/06/22 11:58:25 as Exp $
16 */
17
18 /* Ordering Constraints on Payloads
19 *
20 * rfc2409: The Internet Key Exchange (IKE)
21 *
22 * 5 Exchanges:
23 * "The SA payload MUST precede all other payloads in a phase 1 exchange."
24 *
25 * "Except where otherwise noted, there are no requirements for ISAKMP
26 * payloads in any message to be in any particular order."
27 *
28 * 5.3 Phase 1 Authenticated With a Revised Mode of Public Key Encryption:
29 *
30 * "If the HASH payload is sent it MUST be the first payload of the
31 * second message exchange and MUST be followed by the encrypted
32 * nonce. If the HASH payload is not sent, the first payload of the
33 * second message exchange MUST be the encrypted nonce."
34 *
35 * "Save the requirements on the location of the optional HASH payload
36 * and the mandatory nonce payload there are no further payload
37 * requirements. All payloads-- in whatever order-- following the
38 * encrypted nonce MUST be encrypted with Ke_i or Ke_r depending on the
39 * direction."
40 *
41 * 5.5 Phase 2 - Quick Mode
42 *
43 * "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
44 * header and a SA payload MUST immediately follow the HASH."
45 * [NOTE: there may be more than one SA payload, so this is not
46 * totally reasonable. Probably all SAs should be so constrained.]
47 *
48 * "If ISAKMP is acting as a client negotiator on behalf of another
49 * party, the identities of the parties MUST be passed as IDci and
50 * then IDcr."
51 *
52 * "With the exception of the HASH, SA, and the optional ID payloads,
53 * there are no payload ordering restrictions on Quick Mode."
54 */
55
56 /* Unfolding of Identity -- a central mystery
57 *
58 * This concerns Phase 1 identities, those of the IKE hosts.
59 * These are the only ones that are authenticated. Phase 2
60 * identities are for IPsec SAs.
61 *
62 * There are three case of interest:
63 *
64 * (1) We initiate, based on a whack command specifying a Connection.
65 * We know the identity of the peer from the Connection.
66 *
67 * (2) (to be implemented) we initiate based on a flow from our client
68 * to some IP address.
69 * We immediately know one of the peer's client IP addresses from
70 * the flow. We must use this to figure out the peer's IP address
71 * and Id. To be solved.
72 *
73 * (3) We respond to an IKE negotiation.
74 * We immediately know the peer's IP address.
75 * We get an ID Payload in Main I2.
76 *
77 * Unfortunately, this is too late for a number of things:
78 * - the ISAKMP SA proposals have already been made (Main I1)
79 * AND one accepted (Main R1)
80 * - the SA includes a specification of the type of ID
81 * authentication so this is negotiated without being told the ID.
82 * - with Preshared Key authentication, Main I2 is encrypted
83 * using the key, so it cannot be decoded to reveal the ID
84 * without knowing (or guessing) which key to use.
85 *
86 * There are three reasonable choices here for the responder:
87 * + assume that the initiator is making wise offers since it
88 * knows the IDs involved. We can balk later (but not gracefully)
89 * when we find the actual initiator ID
90 * + attempt to infer identity by IP address. Again, we can balk
91 * when the true identity is revealed. Actually, it is enough
92 * to infer properties of the identity (eg. SA properties and
93 * PSK, if needed).
94 * + make all properties universal so discrimination based on
95 * identity isn't required. For example, always accept the same
96 * kinds of encryption. Accept Public Key Id authentication
97 * since the Initiator presumably has our public key and thinks
98 * we must have / can find his. This approach is weakest
99 * for preshared key since the actual key must be known to
100 * decrypt the Initiator's ID Payload.
101 * These choices can be blended. For example, a class of Identities
102 * can be inferred, sufficient to select a preshared key but not
103 * sufficient to infer a unique identity.
104 */
105
106 #include <stdio.h>
107 #include <stdlib.h>
108 #include <stddef.h>
109 #include <string.h>
110 #include <unistd.h>
111 #include <errno.h>
112 #include <sys/types.h>
113 #include <sys/time.h> /* only used for belt-and-suspenders select call */
114 #include <sys/poll.h> /* only used for forensic poll call */
115 #include <sys/socket.h>
116 #include <sys/ioctl.h>
117 #include <netinet/in.h>
118 #include <arpa/inet.h>
119 #include <sys/queue.h>
120
121 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
122 # include <asm/types.h> /* for __u8, __u32 */
123 # include <linux/errqueue.h>
124 # include <sys/uio.h> /* struct iovec */
125 #endif
126
127 #include <freeswan.h>
128
129 #include "constants.h"
130 #include "defs.h"
131 #include "cookie.h"
132 #include "connections.h"
133 #include "state.h"
134 #include "packet.h"
135 #include "md5.h"
136 #include "sha1.h"
137 #include "crypto.h" /* requires sha1.h and md5.h */
138 #include "ike_alg.h"
139 #include "log.h"
140 #include "demux.h" /* needs packet.h */
141 #include "ipsec_doi.h" /* needs demux.h and state.h */
142 #include "timer.h"
143 #include "whack.h" /* requires connections.h */
144 #include "server.h"
145 #include "nat_traversal.h"
146 #include "vendor.h"
147 #include "modecfg.h"
148
149 /* This file does basic header checking and demux of
150 * incoming packets.
151 */
152
153 /* forward declarations */
154 static bool read_packet(struct msg_digest *md);
155 static void process_packet(struct msg_digest **mdp);
156
157 /* Reply messages are built in this buffer.
158 * Only one state transition function can be using it at a time
159 * so suspended STFs must save and restore it.
160 * It could be an auto variable of complete_state_transition except for the fact
161 * that when a suspended STF resumes, its reply message buffer
162 * must be at the same location -- there are pointers into it.
163 */
164 u_int8_t reply_buffer[MAX_OUTPUT_UDP_SIZE];
165
166 /* state_microcode is a tuple of information parameterizing certain
167 * centralized processing of a packet. For example, it roughly
168 * specifies what payloads are expected in this message.
169 * The microcode is selected primarily based on the state.
170 * In Phase 1, the payload structure often depends on the
171 * authentication technique, so that too plays a part in selecting
172 * the state_microcode to use.
173 */
174
175 struct state_microcode {
176 enum state_kind state, next_state;
177 lset_t flags;
178 lset_t req_payloads; /* required payloads (allows just one) */
179 lset_t opt_payloads; /* optional payloads (any mumber) */
180 /* if not ISAKMP_NEXT_NONE, process_packet will emit HDR with this as np */
181 u_int8_t first_out_payload;
182 enum event_type timeout_event;
183 state_transition_fn *processor;
184 };
185
186 /* State Microcode Flags, in several groups */
187
188 /* Oakley Auth values: to which auth values does this entry apply?
189 * Most entries will use SMF_ALL_AUTH because they apply to all.
190 * Note: SMF_ALL_AUTH matches 0 for those circumstances when no auth
191 * has been set.
192 */
193 #define SMF_ALL_AUTH LRANGE(0, OAKLEY_AUTH_ROOF-1)
194 #define SMF_PSK_AUTH LELEM(OAKLEY_PRESHARED_KEY)
195 #define SMF_DS_AUTH (LELEM(OAKLEY_DSS_SIG) | LELEM(OAKLEY_RSA_SIG))
196 #define SMF_PKE_AUTH (LELEM(OAKLEY_RSA_ENC) | LELEM(OAKLEY_ELGAMAL_ENC))
197 #define SMF_RPKE_AUTH (LELEM(OAKLEY_RSA_ENC_REV) | LELEM(OAKLEY_ELGAMAL_ENC_REV))
198
199 /* misc flags */
200
201 #define SMF_INITIATOR LELEM(OAKLEY_AUTH_ROOF + 0)
202 #define SMF_FIRST_ENCRYPTED_INPUT LELEM(OAKLEY_AUTH_ROOF + 1)
203 #define SMF_INPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 2)
204 #define SMF_OUTPUT_ENCRYPTED LELEM(OAKLEY_AUTH_ROOF + 3)
205 #define SMF_RETRANSMIT_ON_DUPLICATE LELEM(OAKLEY_AUTH_ROOF + 4)
206
207 #define SMF_ENCRYPTED (SMF_INPUT_ENCRYPTED | SMF_OUTPUT_ENCRYPTED)
208
209 /* this state generates a reply message */
210 #define SMF_REPLY LELEM(OAKLEY_AUTH_ROOF + 5)
211
212 /* this state completes P1, so any pending P2 negotiations should start */
213 #define SMF_RELEASE_PENDING_P2 LELEM(OAKLEY_AUTH_ROOF + 6)
214
215 /* end of flags */
216
217
218 static state_transition_fn /* forward declaration */
219 unexpected,
220 informational;
221
222 /* state_microcode_table is a table of all state_microcode tuples.
223 * It must be in order of state (the first element).
224 * After initialization, ike_microcode_index[s] points to the
225 * first entry in state_microcode_table for state s.
226 * Remember that each state name in Main or Quick Mode describes
227 * what has happened in the past, not what this message is.
228 */
229
230 static const struct state_microcode
231 *ike_microcode_index[STATE_IKE_ROOF - STATE_IKE_FLOOR];
232
233 static const struct state_microcode state_microcode_table[] = {
234 #define PT(n) ISAKMP_NEXT_##n
235 #define P(n) LELEM(PT(n))
236
237 /***** Phase 1 Main Mode *****/
238
239 /* No state for main_outI1: --> HDR, SA */
240
241 /* STATE_MAIN_R0: I1 --> R1
242 * HDR, SA --> HDR, SA
243 */
244 { STATE_MAIN_R0, STATE_MAIN_R1
245 , SMF_ALL_AUTH | SMF_REPLY
246 , P(SA), P(VID) | P(CR), PT(NONE)
247 , EVENT_RETRANSMIT, main_inI1_outR1},
248
249 /* STATE_MAIN_I1: R1 --> I2
250 * HDR, SA --> auth dependent
251 * SMF_PSK_AUTH, SMF_DS_AUTH: --> HDR, KE, Ni
252 * SMF_PKE_AUTH:
253 * --> HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
254 * SMF_RPKE_AUTH:
255 * --> HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
256 * Note: since we don't know auth at start, we cannot differentiate
257 * microcode entries based on it.
258 */
259 { STATE_MAIN_I1, STATE_MAIN_I2
260 , SMF_ALL_AUTH | SMF_INITIATOR | SMF_REPLY
261 , P(SA), P(VID) | P(CR), PT(NONE) /* don't know yet */
262 , EVENT_RETRANSMIT, main_inR1_outI2 },
263
264 /* STATE_MAIN_R1: I2 --> R2
265 * SMF_PSK_AUTH, SMF_DS_AUTH: HDR, KE, Ni --> HDR, KE, Nr
266 * SMF_PKE_AUTH: HDR, KE, [ HASH(1), ] <IDi1_b>PubKey_r, <Ni_b>PubKey_r
267 * --> HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
268 * SMF_RPKE_AUTH:
269 * HDR, [ HASH(1), ] <Ni_b>Pubkey_r, <KE_b>Ke_i, <IDi1_b>Ke_i [,<<Cert-I_b>Ke_i]
270 * --> HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
271 */
272 { STATE_MAIN_R1, STATE_MAIN_R2
273 , SMF_PSK_AUTH | SMF_DS_AUTH | SMF_REPLY
274 , P(KE) | P(NONCE), P(VID) | P(CR) | P(NATD_RFC), PT(KE)
275 , EVENT_RETRANSMIT, main_inI2_outR2 },
276
277 { STATE_MAIN_R1, STATE_UNDEFINED
278 , SMF_PKE_AUTH | SMF_REPLY
279 , P(KE) | P(ID) | P(NONCE), P(VID) | P(CR) | P(HASH), PT(KE)
280 , EVENT_RETRANSMIT, unexpected /* ??? not yet implemented */ },
281
282 { STATE_MAIN_R1, STATE_UNDEFINED
283 , SMF_RPKE_AUTH | SMF_REPLY
284 , P(NONCE) | P(KE) | P(ID), P(VID) | P(CR) | P(HASH) | P(CERT), PT(NONCE)
285 , EVENT_RETRANSMIT, unexpected /* ??? not yet implemented */ },
286
287 /* for states from here on, output message must be encrypted */
288
289 /* STATE_MAIN_I2: R2 --> I3
290 * SMF_PSK_AUTH: HDR, KE, Nr --> HDR*, IDi1, HASH_I
291 * SMF_DS_AUTH: HDR, KE, Nr --> HDR*, IDi1, [ CERT, ] SIG_I
292 * SMF_PKE_AUTH: HDR, KE, <IDr1_b>PubKey_i, <Nr_b>PubKey_i
293 * --> HDR*, HASH_I
294 * SMF_RPKE_AUTH: HDR, <Nr_b>PubKey_i, <KE_b>Ke_r, <IDr1_b>Ke_r
295 * --> HDR*, HASH_I
296 */
297 { STATE_MAIN_I2, STATE_MAIN_I3
298 , SMF_PSK_AUTH | SMF_DS_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY
299 , P(KE) | P(NONCE), P(VID) | P(CR) | P(NATD_RFC), PT(ID)
300 , EVENT_RETRANSMIT, main_inR2_outI3 },
301
302 { STATE_MAIN_I2, STATE_UNDEFINED
303 , SMF_PKE_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY
304 , P(KE) | P(ID) | P(NONCE), P(VID) | P(CR), PT(HASH)
305 , EVENT_RETRANSMIT, unexpected /* ??? not yet implemented */ },
306
307 { STATE_MAIN_I2, STATE_UNDEFINED
308 , SMF_ALL_AUTH | SMF_INITIATOR | SMF_OUTPUT_ENCRYPTED | SMF_REPLY
309 , P(NONCE) | P(KE) | P(ID), P(VID) | P(CR), PT(HASH)
310 , EVENT_RETRANSMIT, unexpected /* ??? not yet implemented */ },
311
312 /* for states from here on, input message must be encrypted */
313
314 /* STATE_MAIN_R2: I3 --> R3
315 * SMF_PSK_AUTH: HDR*, IDi1, HASH_I --> HDR*, IDr1, HASH_R
316 * SMF_DS_AUTH: HDR*, IDi1, [ CERT, ] SIG_I --> HDR*, IDr1, [ CERT, ] SIG_R
317 * SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_I --> HDR*, HASH_R
318 */
319 { STATE_MAIN_R2, STATE_MAIN_R3
320 , SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED
321 | SMF_REPLY | SMF_RELEASE_PENDING_P2
322 , P(ID) | P(HASH), P(VID) | P(CR), PT(NONE)
323 , EVENT_SA_REPLACE, main_inI3_outR3 },
324
325 { STATE_MAIN_R2, STATE_MAIN_R3
326 , SMF_DS_AUTH | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED
327 | SMF_REPLY | SMF_RELEASE_PENDING_P2
328 , P(ID) | P(SIG), P(VID) | P(CR) | P(CERT), PT(NONE)
329 , EVENT_SA_REPLACE, main_inI3_outR3 },
330
331 { STATE_MAIN_R2, STATE_UNDEFINED
332 , SMF_PKE_AUTH | SMF_RPKE_AUTH | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED
333 | SMF_REPLY | SMF_RELEASE_PENDING_P2
334 , P(HASH), P(VID) | P(CR), PT(NONE)
335 , EVENT_SA_REPLACE, unexpected /* ??? not yet implemented */ },
336
337 /* STATE_MAIN_I3: R3 --> done
338 * SMF_PSK_AUTH: HDR*, IDr1, HASH_R --> done
339 * SMF_DS_AUTH: HDR*, IDr1, [ CERT, ] SIG_R --> done
340 * SMF_PKE_AUTH, SMF_RPKE_AUTH: HDR*, HASH_R --> done
341 * May initiate quick mode by calling quick_outI1
342 */
343 { STATE_MAIN_I3, STATE_MAIN_I4
344 , SMF_PSK_AUTH | SMF_INITIATOR
345 | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2
346 , P(ID) | P(HASH), P(VID) | P(CR), PT(NONE)
347 , EVENT_SA_REPLACE, main_inR3 },
348
349 { STATE_MAIN_I3, STATE_MAIN_I4
350 , SMF_DS_AUTH | SMF_INITIATOR
351 | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2
352 , P(ID) | P(SIG), P(VID) | P(CR) | P(CERT), PT(NONE)
353 , EVENT_SA_REPLACE, main_inR3 },
354
355 { STATE_MAIN_I3, STATE_UNDEFINED
356 , SMF_PKE_AUTH | SMF_RPKE_AUTH | SMF_INITIATOR
357 | SMF_FIRST_ENCRYPTED_INPUT | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2
358 , P(HASH), P(VID) | P(CR), PT(NONE)
359 , EVENT_SA_REPLACE, unexpected /* ??? not yet implemented */ },
360
361 /* STATE_MAIN_R3: can only get here due to packet loss */
362 { STATE_MAIN_R3, STATE_UNDEFINED
363 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_RETRANSMIT_ON_DUPLICATE
364 , LEMPTY, LEMPTY
365 , PT(NONE), EVENT_NULL, unexpected },
366
367 /* STATE_MAIN_I4: can only get here due to packet loss */
368 { STATE_MAIN_I4, STATE_UNDEFINED
369 , SMF_ALL_AUTH | SMF_INITIATOR | SMF_ENCRYPTED
370 , LEMPTY, LEMPTY
371 , PT(NONE), EVENT_NULL, unexpected },
372
373
374 /***** Phase 2 Quick Mode *****/
375
376 /* No state for quick_outI1:
377 * --> HDR*, HASH(1), SA, Nr [, KE ] [, IDci, IDcr ]
378 */
379
380 /* STATE_QUICK_R0:
381 * HDR*, HASH(1), SA, Ni [, KE ] [, IDci, IDcr ] -->
382 * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ]
383 * Installs inbound IPsec SAs.
384 * Because it may suspend for asynchronous DNS, first_out_payload
385 * is set to NONE to suppress early emission of HDR*.
386 * ??? it is legal to have multiple SAs, but we don't support it yet.
387 */
388 { STATE_QUICK_R0, STATE_QUICK_R1
389 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY
390 , P(HASH) | P(SA) | P(NONCE), /* P(SA) | */ P(KE) | P(ID) | P(NATOA_RFC), PT(NONE)
391 , EVENT_RETRANSMIT, quick_inI1_outR1 },
392
393 /* STATE_QUICK_I1:
394 * HDR*, HASH(2), SA, Nr [, KE ] [, IDci, IDcr ] -->
395 * HDR*, HASH(3)
396 * Installs inbound and outbound IPsec SAs, routing, etc.
397 * ??? it is legal to have multiple SAs, but we don't support it yet.
398 */
399 { STATE_QUICK_I1, STATE_QUICK_I2
400 , SMF_ALL_AUTH | SMF_INITIATOR | SMF_ENCRYPTED | SMF_REPLY
401 , P(HASH) | P(SA) | P(NONCE), /* P(SA) | */ P(KE) | P(ID) | P(NATOA_RFC), PT(HASH)
402 , EVENT_SA_REPLACE, quick_inR1_outI2 },
403
404 /* STATE_QUICK_R1: HDR*, HASH(3) --> done
405 * Installs outbound IPsec SAs, routing, etc.
406 */
407 { STATE_QUICK_R1, STATE_QUICK_R2
408 , SMF_ALL_AUTH | SMF_ENCRYPTED
409 , P(HASH), LEMPTY, PT(NONE)
410 , EVENT_SA_REPLACE, quick_inI2 },
411
412 /* STATE_QUICK_I2: can only happen due to lost packet */
413 { STATE_QUICK_I2, STATE_UNDEFINED
414 , SMF_ALL_AUTH | SMF_INITIATOR | SMF_ENCRYPTED | SMF_RETRANSMIT_ON_DUPLICATE
415 , LEMPTY, LEMPTY, PT(NONE)
416 , EVENT_NULL, unexpected },
417
418 /* STATE_QUICK_R2: can only happen due to lost packet */
419 { STATE_QUICK_R2, STATE_UNDEFINED
420 , SMF_ALL_AUTH | SMF_ENCRYPTED
421 , LEMPTY, LEMPTY, PT(NONE)
422 , EVENT_NULL, unexpected },
423
424
425 /***** informational messages *****/
426
427 /* STATE_INFO: */
428 { STATE_INFO, STATE_UNDEFINED
429 , SMF_ALL_AUTH
430 , LEMPTY, LEMPTY, PT(NONE)
431 , EVENT_NULL, informational },
432
433 /* STATE_INFO_PROTECTED: */
434 { STATE_INFO_PROTECTED, STATE_UNDEFINED
435 , SMF_ALL_AUTH | SMF_ENCRYPTED
436 , P(HASH), LEMPTY, PT(NONE)
437 , EVENT_NULL, informational },
438
439 /* XAUTH state transitions */
440 { STATE_XAUTH_I0, STATE_XAUTH_I1
441 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY
442 , P(ATTR) | P(HASH), P(VID), PT(HASH)
443 , EVENT_RETRANSMIT, xauth_inI0 },
444
445 { STATE_XAUTH_R1, STATE_XAUTH_R2
446 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY
447 , P(ATTR) | P(HASH), P(VID), PT(HASH)
448 , EVENT_RETRANSMIT, xauth_inR1 },
449
450 { STATE_XAUTH_I1, STATE_XAUTH_I2
451 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2
452 , P(ATTR) | P(HASH), P(VID), PT(HASH)
453 , EVENT_SA_REPLACE, xauth_inI1 },
454
455 { STATE_XAUTH_R2, STATE_XAUTH_R3
456 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2
457 , P(ATTR) | P(HASH), P(VID), PT(NONE)
458 , EVENT_SA_REPLACE, xauth_inR2 },
459
460 { STATE_XAUTH_I2, STATE_UNDEFINED
461 , SMF_ALL_AUTH | SMF_ENCRYPTED
462 , LEMPTY, LEMPTY, PT(NONE)
463 , EVENT_NULL, unexpected },
464
465 { STATE_XAUTH_R3, STATE_UNDEFINED
466 , SMF_ALL_AUTH | SMF_ENCRYPTED
467 , LEMPTY, LEMPTY, PT(NONE)
468 , EVENT_NULL, unexpected },
469
470 /* ModeCfg pull mode state transitions */
471
472 { STATE_MODE_CFG_R0, STATE_MODE_CFG_R1
473 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2
474 , P(ATTR) | P(HASH), P(VID), PT(HASH)
475 , EVENT_SA_REPLACE, modecfg_inR0 },
476
477 { STATE_MODE_CFG_I1, STATE_MODE_CFG_I2
478 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2
479 , P(ATTR) | P(HASH), P(VID), PT(HASH)
480 , EVENT_SA_REPLACE, modecfg_inI1 },
481
482 { STATE_MODE_CFG_R1, STATE_UNDEFINED
483 , SMF_ALL_AUTH | SMF_ENCRYPTED
484 , LEMPTY, LEMPTY, PT(NONE)
485 , EVENT_NULL, unexpected },
486
487 { STATE_MODE_CFG_I2, STATE_UNDEFINED
488 , SMF_ALL_AUTH | SMF_ENCRYPTED
489 , LEMPTY, LEMPTY, PT(NONE)
490 , EVENT_NULL, unexpected },
491
492 /* ModeCfg push mode state transitions */
493
494 { STATE_MODE_CFG_I0, STATE_MODE_CFG_I3
495 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_REPLY | SMF_RELEASE_PENDING_P2
496 , P(ATTR) | P(HASH), P(VID), PT(HASH)
497 , EVENT_SA_REPLACE, modecfg_inI0 },
498
499 { STATE_MODE_CFG_R3, STATE_MODE_CFG_R4
500 , SMF_ALL_AUTH | SMF_ENCRYPTED | SMF_RELEASE_PENDING_P2
501 , P(ATTR) | P(HASH), P(VID), PT(HASH)
502 , EVENT_SA_REPLACE, modecfg_inR3 },
503
504 { STATE_MODE_CFG_I3, STATE_UNDEFINED
505 , SMF_ALL_AUTH | SMF_ENCRYPTED
506 , LEMPTY, LEMPTY, PT(NONE)
507 , EVENT_NULL, unexpected },
508
509 { STATE_MODE_CFG_R4, STATE_UNDEFINED
510 , SMF_ALL_AUTH | SMF_ENCRYPTED
511 , LEMPTY, LEMPTY, PT(NONE)
512 , EVENT_NULL, unexpected },
513
514 #undef P
515 #undef PT
516 };
517
518 void
519 init_demux(void)
520 {
521 /* fill ike_microcode_index:
522 * make ike_microcode_index[s] point to first entry in
523 * state_microcode_table for state s (backward scan makes this easier).
524 * Check that table is in order -- catch coding errors.
525 * For what it's worth, this routine is idempotent.
526 */
527 const struct state_microcode *t;
528
529 for (t = &state_microcode_table[elemsof(state_microcode_table) - 1];;)
530 {
531 passert(STATE_IKE_FLOOR <= t->state && t->state < STATE_IKE_ROOF);
532 ike_microcode_index[t->state - STATE_IKE_FLOOR] = t;
533 if (t == state_microcode_table)
534 break;
535 t--;
536 passert(t[0].state <= t[1].state);
537 }
538 }
539
540 /* Process any message on the MSG_ERRQUEUE
541 *
542 * This information is generated because of the IP_RECVERR socket option.
543 * The API is sparsely documented, and may be LINUX-only, and only on
544 * fairly recent versions at that (hence the conditional compilation).
545 *
546 * - ip(7) describes IP_RECVERR
547 * - recvmsg(2) describes MSG_ERRQUEUE
548 * - readv(2) describes iovec
549 * - cmsg(3) describes how to process auxilliary messages
550 *
551 * ??? we should link this message with one we've sent
552 * so that the diagnostic can refer to that negotiation.
553 *
554 * ??? how long can the messge be?
555 *
556 * ??? poll(2) has a very incomplete description of the POLL* events.
557 * We assume that POLLIN, POLLOUT, and POLLERR are all we need to deal with
558 * and that POLLERR will be on iff there is a MSG_ERRQUEUE message.
559 *
560 * We have to code around a couple of surprises:
561 *
562 * - Select can say that a socket is ready to read from, and
563 * yet a read will hang. It turns out that a message available on the
564 * MSG_ERRQUEUE will cause select to say something is pending, but
565 * a normal read will hang. poll(2) can tell when a MSG_ERRQUEUE
566 * message is pending.
567 *
568 * This is dealt with by calling check_msg_errqueue after select
569 * has indicated that there is something to read, but before the
570 * read is performed. check_msg_errqueue will return TRUE if there
571 * is something left to read.
572 *
573 * - A write to a socket may fail because there is a pending MSG_ERRQUEUE
574 * message, without there being anything wrong with the write. This
575 * makes for confusing diagnostics.
576 *
577 * To avoid this, we call check_msg_errqueue before a write. True,
578 * there is a race condition (a MSG_ERRQUEUE message might arrive
579 * between the check and the write), but we should eliminate many
580 * of the problematic events. To narrow the window, the poll(2)
581 * will await until an event happens (in the case or a write,
582 * POLLOUT; this should be benign for POLLIN).
583 */
584
585 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
586 static bool
587 check_msg_errqueue(const struct iface *ifp, short interest)
588 {
589 struct pollfd pfd;
590
591 pfd.fd = ifp->fd;
592 pfd.events = interest | POLLPRI | POLLOUT;
593
594 while (pfd.revents = 0
595 , poll(&pfd, 1, -1) > 0 && (pfd.revents & POLLERR))
596 {
597 u_int8_t buffer[3000]; /* hope that this is big enough */
598 union
599 {
600 struct sockaddr sa;
601 struct sockaddr_in sa_in4;
602 struct sockaddr_in6 sa_in6;
603 } from;
604
605 int from_len = sizeof(from);
606
607 int packet_len;
608
609 struct msghdr emh;
610 struct iovec eiov;
611 union {
612 /* force alignment (not documented as necessary) */
613 struct cmsghdr ecms;
614
615 /* how much space is enough? */
616 unsigned char space[256];
617 } ecms_buf;
618
619 struct cmsghdr *cm;
620 char fromstr[sizeof(" for message to port 65536") + INET6_ADDRSTRLEN];
621 struct state *sender = NULL;
622
623 zero(&from.sa);
624 from_len = sizeof(from);
625
626 emh.msg_name = &from.sa; /* ??? filled in? */
627 emh.msg_namelen = sizeof(from);
628 emh.msg_iov = &eiov;
629 emh.msg_iovlen = 1;
630 emh.msg_control = &ecms_buf;
631 emh.msg_controllen = sizeof(ecms_buf);
632 emh.msg_flags = 0;
633
634 eiov.iov_base = buffer; /* see readv(2) */
635 eiov.iov_len = sizeof(buffer);
636
637 packet_len = recvmsg(ifp->fd, &emh, MSG_ERRQUEUE);
638
639 if (packet_len == -1)
640 {
641 log_errno((e, "recvmsg(,, MSG_ERRQUEUE) on %s failed in comm_handle"
642 , ifp->rname));
643 break;
644 }
645 else if (packet_len == sizeof(buffer))
646 {
647 plog("MSG_ERRQUEUE message longer than %lu bytes; truncated"
648 , (unsigned long) sizeof(buffer));
649 }
650 else
651 {
652 sender = find_sender((size_t) packet_len, buffer);
653 }
654
655 DBG_cond_dump(DBG_ALL, "rejected packet:\n", buffer, packet_len);
656 DBG_cond_dump(DBG_ALL, "control:\n", emh.msg_control, emh.msg_controllen);
657 /* ??? Andi Kleen <ak@suse.de> and misc documentation
658 * suggests that name will have the original destination
659 * of the packet. We seem to see msg_namelen == 0.
660 * Andi says that this is a kernel bug and has fixed it.
661 * Perhaps in 2.2.18/2.4.0.
662 */
663 passert(emh.msg_name == &from.sa);
664 DBG_cond_dump(DBG_ALL, "name:\n", emh.msg_name
665 , emh.msg_namelen);
666
667 fromstr[0] = '\0'; /* usual case :-( */
668 switch (from.sa.sa_family)
669 {
670 char as[INET6_ADDRSTRLEN];
671
672 case AF_INET:
673 if (emh.msg_namelen == sizeof(struct sockaddr_in))
674 snprintf(fromstr, sizeof(fromstr)
675 , " for message to %s port %u"
676 , inet_ntop(from.sa.sa_family
677 , &from.sa_in4.sin_addr, as, sizeof(as))
678 , ntohs(from.sa_in4.sin_port));
679 break;
680 case AF_INET6:
681 if (emh.msg_namelen == sizeof(struct sockaddr_in6))
682 snprintf(fromstr, sizeof(fromstr)
683 , " for message to %s port %u"
684 , inet_ntop(from.sa.sa_family
685 , &from.sa_in6.sin6_addr, as, sizeof(as))
686 , ntohs(from.sa_in6.sin6_port));
687 break;
688 }
689
690 for (cm = CMSG_FIRSTHDR(&emh)
691 ; cm != NULL
692 ; cm = CMSG_NXTHDR(&emh,cm))
693 {
694 if (cm->cmsg_level == SOL_IP
695 && cm->cmsg_type == IP_RECVERR)
696 {
697 /* ip(7) and recvmsg(2) specify:
698 * ee_origin is SO_EE_ORIGIN_ICMP for ICMP
699 * or SO_EE_ORIGIN_LOCAL for locally generated errors.
700 * ee_type and ee_code are from the ICMP header.
701 * ee_info is the discovered MTU for EMSGSIZE errors
702 * ee_data is not used.
703 *
704 * ??? recvmsg(2) says "SOCK_EE_OFFENDER" but
705 * means "SO_EE_OFFENDER". The OFFENDER is really
706 * the router that complained. As such, the port
707 * is meaningless.
708 */
709
710 /* ??? cmsg(3) claims that CMSG_DATA returns
711 * void *, but RFC 2292 and /usr/include/bits/socket.h
712 * say unsigned char *. The manual is being fixed.
713 */
714 struct sock_extended_err *ee = (void *)CMSG_DATA(cm);
715 const char *offstr = "unspecified";
716 char offstrspace[INET6_ADDRSTRLEN];
717 char orname[50];
718
719 if (cm->cmsg_len > CMSG_LEN(sizeof(struct sock_extended_err)))
720 {
721 const struct sockaddr *offender = SO_EE_OFFENDER(ee);
722
723 switch (offender->sa_family)
724 {
725 case AF_INET:
726 offstr = inet_ntop(offender->sa_family
727 , &((const struct sockaddr_in *)offender)->sin_addr
728 , offstrspace, sizeof(offstrspace));
729 break;
730 case AF_INET6:
731 offstr = inet_ntop(offender->sa_family
732 , &((const struct sockaddr_in6 *)offender)->sin6_addr
733 , offstrspace, sizeof(offstrspace));
734 break;
735 default:
736 offstr = "unknown";
737 break;
738 }
739 }
740
741 switch (ee->ee_origin)
742 {
743 case SO_EE_ORIGIN_NONE:
744 snprintf(orname, sizeof(orname), "none");
745 break;
746 case SO_EE_ORIGIN_LOCAL:
747 snprintf(orname, sizeof(orname), "local");
748 break;
749 case SO_EE_ORIGIN_ICMP:
750 snprintf(orname, sizeof(orname)
751 , "ICMP type %d code %d (not authenticated)"
752 , ee->ee_type, ee->ee_code
753 );
754 break;
755 case SO_EE_ORIGIN_ICMP6:
756 snprintf(orname, sizeof(orname)
757 , "ICMP6 type %d code %d (not authenticated)"
758 , ee->ee_type, ee->ee_code
759 );
760 break;
761 default:
762 snprintf(orname, sizeof(orname), "invalid origin %lu"
763 , (unsigned long) ee->ee_origin);
764 break;
765 }
766
767 {
768 struct state *old_state = cur_state;
769
770 cur_state = sender;
771
772 /* note dirty trick to suppress ~ at start of format
773 * if we know what state to blame.
774 */
775 if ((packet_len == 1) && (buffer[0] = 0xff)
776 #ifdef DEBUG
777 && ((cur_debugging & DBG_NATT) == 0)
778 #endif
779 ) {
780 /* don't log NAT-T keepalive related errors unless NATT debug is
781 * enabled
782 */
783 }
784 else
785 plog((sender != NULL) + "~"
786 "ERROR: asynchronous network error report on %s"
787 "%s"
788 ", complainant %s"
789 ": %s"
790 " [errno %lu, origin %s"
791 /* ", pad %d, info %ld" */
792 /* ", data %ld" */
793 "]"
794 , ifp->rname
795 , fromstr
796 , offstr
797 , strerror(ee->ee_errno)
798 , (unsigned long) ee->ee_errno
799 , orname
800 /* , ee->ee_pad, (unsigned long)ee->ee_info */
801 /* , (unsigned long)ee->ee_data */
802 );
803 cur_state = old_state;
804 }
805 }
806 else
807 {
808 /* .cmsg_len is a kernel_size_t(!), but the value
809 * certainly ought to fit in an unsigned long.
810 */
811 plog("unknown cmsg: level %d, type %d, len %lu"
812 , cm->cmsg_level, cm->cmsg_type
813 , (unsigned long) cm->cmsg_len);
814 }
815 }
816 }
817 return (pfd.revents & interest) != 0;
818 }
819 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
820
821 bool
822 send_packet(struct state *st, const char *where)
823 {
824 struct connection *c = st->st_connection;
825 int port_buf;
826 bool err;
827 u_int8_t ike_pkt[MAX_OUTPUT_UDP_SIZE];
828 u_int8_t *ptr;
829 unsigned long len;
830
831 if (c->interface->ike_float && st->st_tpacket.len != 1)
832 {
833 if ((unsigned long) st->st_tpacket.len > (MAX_OUTPUT_UDP_SIZE-sizeof(u_int32_t)))
834 {
835 DBG_log("send_packet(): really too big");
836 return FALSE;
837 }
838 ptr = ike_pkt;
839 /** Add Non-ESP marker **/
840 memset(ike_pkt, 0, sizeof(u_int32_t));
841 memcpy(ike_pkt + sizeof(u_int32_t), st->st_tpacket.ptr,
842 (unsigned long)st->st_tpacket.len);
843 len = (unsigned long) st->st_tpacket.len + sizeof(u_int32_t);
844 }
845 else
846 {
847 ptr = st->st_tpacket.ptr;
848 len = (unsigned long) st->st_tpacket.len;
849 }
850
851 DBG(DBG_RAW,
852 {
853 DBG_log("sending %lu bytes for %s through %s to %s:%u:"
854 , (unsigned long) st->st_tpacket.len
855 , where
856 , c->interface->rname
857 , ip_str(&c->spd.that.host_addr)
858 , (unsigned)c->spd.that.host_port);
859 DBG_dump_chunk(NULL, st->st_tpacket);
860 });
861
862 /* XXX: Not very clean. We manipulate the port of the ip_address to
863 * have a port in the sockaddr*, but we retain the original port
864 * and restore it afterwards.
865 */
866
867 port_buf = portof(&c->spd.that.host_addr);
868 setportof(htons(c->spd.that.host_port), &c->spd.that.host_addr);
869
870 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
871 (void) check_msg_errqueue(c->interface, POLLOUT);
872 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
873
874 err = sendto(c->interface->fd
875 , ptr, len, 0
876 , sockaddrof(&c->spd.that.host_addr)
877 , sockaddrlenof(&c->spd.that.host_addr)) != (ssize_t)len;
878
879 /* restore port */
880 setportof(port_buf, &c->spd.that.host_addr);
881
882 if (err)
883 {
884 /* do not log NAT-T Keep Alive packets */
885 if (streq(where, "NAT-T Keep Alive"))
886 return FALSE;
887 log_errno((e, "sendto on %s to %s:%u failed in %s"
888 , c->interface->rname
889 , ip_str(&c->spd.that.host_addr)
890 , (unsigned)c->spd.that.host_port
891 , where));
892 return FALSE;
893 }
894 else
895 {
896 return TRUE;
897 }
898 }
899
900 static stf_status
901 unexpected(struct msg_digest *md)
902 {
903 loglog(RC_LOG_SERIOUS, "unexpected message received in state %s"
904 , enum_name(&state_names, md->st->st_state));
905 return STF_IGNORE;
906 }
907
908 static stf_status
909 informational(struct msg_digest *md UNUSED)
910 {
911 struct payload_digest *const n_pld = md->chain[ISAKMP_NEXT_N];
912
913 /* If the Notification Payload is not null... */
914 if (n_pld != NULL)
915 {
916 pb_stream *const n_pbs = &n_pld->pbs;
917 struct isakmp_notification *const n = &n_pld->payload.notification;
918 int disp_len;
919 char disp_buf[200];
920
921 /* Switch on Notification Type (enum) */
922 switch (n->isan_type)
923 {
924 case R_U_THERE:
925 return dpd_inI_outR(md->st, n, n_pbs);
926
927 case R_U_THERE_ACK:
928 return dpd_inR(md->st, n, n_pbs);
929 default:
930 if (pbs_left(n_pbs) >= sizeof(disp_buf)-1)
931 disp_len = sizeof(disp_buf)-1;
932 else
933 disp_len = pbs_left(n_pbs);
934 memcpy(disp_buf, n_pbs->cur, disp_len);
935 disp_buf[disp_len] = '\0';
936 break;
937 }
938 }
939 return STF_IGNORE;
940 }
941
942 /* message digest allocation and deallocation */
943
944 static struct msg_digest *md_pool = NULL;
945
946 /* free_md_pool is only used to avoid leak reports */
947 void
948 free_md_pool(void)
949 {
950 for (;;)
951 {
952 struct msg_digest *md = md_pool;
953
954 if (md == NULL)
955 break;
956 md_pool = md->next;
957 pfree(md);
958 }
959 }
960
961 static struct msg_digest *
962 alloc_md(void)
963 {
964 struct msg_digest *md = md_pool;
965
966 /* convenient initializer:
967 * - all pointers NULL
968 * - .note = NOTHING_WRONG
969 * - .encrypted = FALSE
970 */
971 static const struct msg_digest blank_md;
972
973 if (md == NULL)
974 md = alloc_thing(struct msg_digest, "msg_digest");
975 else
976 md_pool = md->next;
977
978 *md = blank_md;
979 md->digest_roof = md->digest;
980
981 /* note: although there may be multiple msg_digests at once
982 * (due to suspended state transitions), there is a single
983 * global reply_buffer. It will need to be saved and restored.
984 */
985 init_pbs(&md->reply, reply_buffer, sizeof(reply_buffer), "reply packet");
986
987 return md;
988 }
989
990 void
991 release_md(struct msg_digest *md)
992 {
993 freeanychunk(md->raw_packet);
994 pfreeany(md->packet_pbs.start);
995 md->packet_pbs.start = NULL;
996 md->next = md_pool;
997 md_pool = md;
998 }
999
1000 /* wrapper for read_packet and process_packet
1001 *
1002 * The main purpose of this wrapper is to factor out teardown code
1003 * from the many return points in process_packet. This amounts to
1004 * releasing the msg_digest and resetting global variables.
1005 *
1006 * When processing of a packet is suspended (STF_SUSPEND),
1007 * process_packet sets md to NULL to prevent the msg_digest being freed.
1008 * Someone else must ensure that msg_digest is freed eventually.
1009 *
1010 * read_packet is broken out to minimize the lifetime of the
1011 * enormous input packet buffer, an auto.
1012 */
1013 void
1014 comm_handle(const struct iface *ifp)
1015 {
1016 static struct msg_digest *md;
1017
1018 #if defined(IP_RECVERR) && defined(MSG_ERRQUEUE)
1019 /* Even though select(2) says that there is a message,
1020 * it might only be a MSG_ERRQUEUE message. At least
1021 * sometimes that leads to a hanging recvfrom. To avoid
1022 * what appears to be a kernel bug, check_msg_errqueue
1023 * uses poll(2) and tells us if there is anything for us
1024 * to read.
1025 *
1026 * This is early enough that teardown isn't required:
1027 * just return on failure.
1028 */
1029 if (!check_msg_errqueue(ifp, POLLIN))
1030 return; /* no normal message to read */
1031 #endif /* defined(IP_RECVERR) && defined(MSG_ERRQUEUE) */
1032
1033 md = alloc_md();
1034 md->iface = ifp;
1035
1036 if (read_packet(md))
1037 process_packet(&md);
1038
1039 if (md != NULL)
1040 release_md(md);
1041
1042 cur_state = NULL;
1043 reset_cur_connection();
1044 cur_from = NULL;
1045 }
1046
1047 /* read the message.
1048 * Since we don't know its size, we read it into
1049 * an overly large buffer and then copy it to a
1050 * new, properly sized buffer.
1051 */
1052 static bool
1053 read_packet(struct msg_digest *md)
1054 {
1055 const struct iface *ifp = md->iface;
1056 int packet_len;
1057 u_int8_t *buffer;
1058 u_int8_t *buffer_nat;
1059 union
1060 {
1061 struct sockaddr sa;
1062 struct sockaddr_in sa_in4;
1063 struct sockaddr_in6 sa_in6;
1064 } from;
1065 int from_len = sizeof(from);
1066 err_t from_ugh = NULL;
1067 static const char undisclosed[] = "unknown source";
1068
1069 happy(anyaddr(addrtypeof(&ifp->addr), &md->sender));
1070 zero(&from.sa);
1071 ioctl(ifp->fd, FIONREAD, &packet_len);
1072 buffer = alloc_bytes(packet_len, "buffer read packet");
1073 packet_len = recvfrom(ifp->fd, buffer, packet_len, 0
1074 , &from.sa, &from_len);
1075
1076 /* First: digest the from address.
1077 * We presume that nothing here disturbs errno.
1078 */
1079 if (packet_len == -1
1080 && from_len == sizeof(from)
1081 && all_zero((const void *)&from.sa, sizeof(from)))
1082 {
1083 /* "from" is untouched -- not set by recvfrom */
1084 from_ugh = undisclosed;
1085 }
1086 else if (from_len
1087 < (int) (offsetof(struct sockaddr, sa_family) + sizeof(from.sa.sa_family)))
1088 {
1089 from_ugh = "truncated";
1090 }
1091 else
1092 {
1093 const struct af_info *afi = aftoinfo(from.sa.sa_family);
1094
1095 if (afi == NULL)
1096 {
1097 from_ugh = "unexpected Address Family";
1098 }
1099 else if (from_len != (int)afi->sa_sz)
1100 {
1101 from_ugh = "wrong length";
1102 }
1103 else
1104 {
1105 switch (from.sa.sa_family)
1106 {
1107 case AF_INET:
1108 from_ugh = initaddr((void *) &from.sa_in4.sin_addr
1109 , sizeof(from.sa_in4.sin_addr), AF_INET, &md->sender);
1110 md->sender_port = ntohs(from.sa_in4.sin_port);
1111 break;
1112 case AF_INET6:
1113 from_ugh = initaddr((void *) &from.sa_in6.sin6_addr
1114 , sizeof(from.sa_in6.sin6_addr), AF_INET6, &md->sender);
1115 md->sender_port = ntohs(from.sa_in6.sin6_port);
1116 break;
1117 }
1118 }
1119 }
1120
1121 /* now we report any actual I/O error */
1122 if (packet_len == -1)
1123 {
1124 if (from_ugh == undisclosed
1125 && errno == ECONNREFUSED)
1126 {
1127 /* Tone down scary message for vague event:
1128 * We get "connection refused" in response to some
1129 * datagram we sent, but we cannot tell which one.
1130 */
1131 plog("some IKE message we sent has been rejected with ECONNREFUSED (kernel supplied no details)");
1132 }
1133 else if (from_ugh != NULL)
1134 {
1135 log_errno((e, "recvfrom on %s failed; Pluto cannot decode source sockaddr in rejection: %s"
1136 , ifp->rname, from_ugh));
1137 }
1138 else
1139 {
1140 log_errno((e, "recvfrom on %s from %s:%u failed"
1141 , ifp->rname
1142 , ip_str(&md->sender), (unsigned)md->sender_port));
1143 }
1144
1145 return FALSE;
1146 }
1147 else if (from_ugh != NULL)
1148 {
1149 plog("recvfrom on %s returned misformed source sockaddr: %s"
1150 , ifp->rname, from_ugh);
1151 return FALSE;
1152 }
1153 cur_from = &md->sender;
1154 cur_from_port = md->sender_port;
1155
1156 if (ifp->ike_float == TRUE)
1157 {
1158 u_int32_t non_esp;
1159
1160 if (packet_len < (int)sizeof(u_int32_t))
1161 {
1162 plog("recvfrom %s:%u too small packet (%d)"
1163 , ip_str(cur_from), (unsigned) cur_from_port, packet_len);
1164 return FALSE;
1165 }
1166 memcpy(&non_esp, buffer, sizeof(u_int32_t));
1167 if (non_esp != 0)
1168 {
1169 plog("recvfrom %s:%u has no Non-ESP marker"
1170 , ip_str(cur_from), (unsigned) cur_from_port);
1171 return FALSE;
1172 }
1173 packet_len -= sizeof(u_int32_t);
1174 buffer_nat = alloc_bytes(packet_len, "buffer read packet");
1175 memcpy(buffer_nat, buffer + sizeof(u_int32_t), packet_len);
1176 pfree(buffer);
1177 buffer = buffer_nat;
1178 }
1179
1180 /* Clone actual message contents
1181 * and set up md->packet_pbs to describe it.
1182 */
1183 init_pbs(&md->packet_pbs, buffer, packet_len, "packet");
1184
1185 DBG(DBG_RAW | DBG_CRYPT | DBG_PARSING | DBG_CONTROL,
1186 {
1187 DBG_log(BLANK_FORMAT);
1188 DBG_log("*received %d bytes from %s:%u on %s"
1189 , (int) pbs_room(&md->packet_pbs)
1190 , ip_str(cur_from), (unsigned) cur_from_port
1191 , ifp->rname);
1192 });
1193
1194 DBG(DBG_RAW,
1195 DBG_dump("", md->packet_pbs.start, pbs_room(&md->packet_pbs)));
1196
1197 if ((pbs_room(&md->packet_pbs)==1) && (md->packet_pbs.start[0]==0xff))
1198 {
1199 /**
1200 * NAT-T Keep-alive packets should be discared by kernel ESPinUDP
1201 * layer. But boggus keep-alive packets (sent with a non-esp marker)
1202 * can reach this point. Complain and discard them.
1203 */
1204 DBG(DBG_NATT,
1205 DBG_log("NAT-T keep-alive (boggus ?) should not reach this point. "
1206 "Ignored. Sender: %s:%u", ip_str(cur_from),
1207 (unsigned) cur_from_port);
1208 )
1209 return FALSE;
1210 }
1211
1212 #define IKEV2_VERSION_OFFSET 17
1213 #define IKEV2_VERSION 0x20
1214
1215 /* ignore IKEv2 packets - they will be handled by charon */
1216 if (pbs_room(&md->packet_pbs) > IKEV2_VERSION_OFFSET
1217 && md->packet_pbs.start[IKEV2_VERSION_OFFSET] == IKEV2_VERSION)
1218 {
1219 DBG(DBG_CONTROLMORE,
1220 DBG_log(" ignoring IKEv2 packet")
1221 )
1222 return FALSE;
1223 }
1224
1225 return TRUE;
1226 }
1227
1228 /* process an input packet, possibly generating a reply.
1229 *
1230 * If all goes well, this routine eventually calls a state-specific
1231 * transition function.
1232 */
1233 static void
1234 process_packet(struct msg_digest **mdp)
1235 {
1236 struct msg_digest *md = *mdp;
1237 const struct state_microcode *smc;
1238 bool new_iv_set = FALSE;
1239 bool restore_iv = FALSE;
1240 u_char new_iv[MAX_DIGEST_LEN];
1241 u_int new_iv_len = 0;
1242
1243 struct state *st = NULL;
1244 enum state_kind from_state = STATE_UNDEFINED; /* state we started in */
1245
1246 #define SEND_NOTIFICATION(t) { \
1247 if (st) send_notification_from_state(st, from_state, t); \
1248 else send_notification_from_md(md, t); }
1249
1250 if (!in_struct(&md->hdr, &isakmp_hdr_desc, &md->packet_pbs, &md->message_pbs))
1251 {
1252 /* Identify specific failures:
1253 * - bad ISAKMP major/minor version numbers
1254 */
1255 if (md->packet_pbs.roof - md->packet_pbs.cur >= (ptrdiff_t)isakmp_hdr_desc.size)
1256 {
1257 struct isakmp_hdr *hdr = (struct isakmp_hdr *)md->packet_pbs.cur;
1258 if ((hdr->isa_version >> ISA_MAJ_SHIFT) != ISAKMP_MAJOR_VERSION)
1259 {
1260 SEND_NOTIFICATION(INVALID_MAJOR_VERSION);
1261 return;
1262 }
1263 else if ((hdr->isa_version & ISA_MIN_MASK) != ISAKMP_MINOR_VERSION)
1264 {
1265 SEND_NOTIFICATION(INVALID_MINOR_VERSION);
1266 return;
1267 }
1268 }
1269 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
1270 return;
1271 }
1272
1273 if (md->packet_pbs.roof != md->message_pbs.roof)
1274 {
1275 plog("size (%u) differs from size specified in ISAKMP HDR (%u)"
1276 , (unsigned) pbs_room(&md->packet_pbs), md->hdr.isa_length);
1277 #ifdef CISCO_QUIRKS
1278 if (pbs_room(&md->packet_pbs) - md->hdr.isa_length == 16)
1279 plog("Cisco VPN client appends 16 surplus NULL bytes");
1280 else
1281 #endif
1282 return;
1283 }
1284
1285 switch (md->hdr.isa_xchg)
1286 {
1287 #ifdef NOTYET
1288 case ISAKMP_XCHG_NONE:
1289 case ISAKMP_XCHG_BASE:
1290 #endif
1291
1292 case ISAKMP_XCHG_IDPROT: /* part of a Main Mode exchange */
1293 if (md->hdr.isa_msgid != MAINMODE_MSGID)
1294 {
1295 plog("Message ID was 0x%08lx but should be zero in Main Mode",
1296 (unsigned long) md->hdr.isa_msgid);
1297 SEND_NOTIFICATION(INVALID_MESSAGE_ID);
1298 return;
1299 }
1300
1301 if (is_zero_cookie(md->hdr.isa_icookie))
1302 {
1303 plog("Initiator Cookie must not be zero in Main Mode message");
1304 SEND_NOTIFICATION(INVALID_COOKIE);
1305 return;
1306 }
1307
1308 if (is_zero_cookie(md->hdr.isa_rcookie))
1309 {
1310 /* initial message from initiator
1311 * ??? what if this is a duplicate of another message?
1312 */
1313 if (md->hdr.isa_flags & ISAKMP_FLAG_ENCRYPTION)
1314 {
1315 plog("initial Main Mode message is invalid:"
1316 " its Encrypted Flag is on");
1317 SEND_NOTIFICATION(INVALID_FLAGS);
1318 return;
1319 }
1320
1321 /* don't build a state until the message looks tasty */
1322 from_state = STATE_MAIN_R0;
1323 }
1324 else
1325 {
1326 /* not an initial message */
1327
1328 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1329 , &md->sender, md->hdr.isa_msgid);
1330
1331 if (st == NULL)
1332 {
1333 /* perhaps this is a first message from the responder
1334 * and contains a responder cookie that we've not yet seen.
1335 */
1336 st = find_state(md->hdr.isa_icookie, zero_cookie
1337 , &md->sender, md->hdr.isa_msgid);
1338
1339 if (st == NULL)
1340 {
1341 plog("Main Mode message is part of an unknown exchange");
1342 /* XXX Could send notification back */
1343 return;
1344 }
1345 }
1346 set_cur_state(st);
1347 from_state = st->st_state;
1348 }
1349 break;
1350
1351 #ifdef NOTYET
1352 case ISAKMP_XCHG_AO:
1353 case ISAKMP_XCHG_AGGR:
1354 #endif
1355
1356 case ISAKMP_XCHG_INFO: /* an informational exchange */
1357 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1358 , &md->sender, MAINMODE_MSGID);
1359
1360 if (st != NULL)
1361 set_cur_state(st);
1362
1363 if (md->hdr.isa_flags & ISAKMP_FLAG_ENCRYPTION)
1364 {
1365 if (st == NULL)
1366 {
1367 plog("Informational Exchange is for an unknown (expired?) SA");
1368 /* XXX Could send notification back */
1369 return;
1370 }
1371
1372 if (!IS_ISAKMP_ENCRYPTED(st->st_state))
1373 {
1374 loglog(RC_LOG_SERIOUS, "encrypted Informational Exchange message is invalid"
1375 " because no key is known");
1376 /* XXX Could send notification back */
1377 return;
1378 }
1379
1380 if (md->hdr.isa_msgid == MAINMODE_MSGID)
1381 {
1382 loglog(RC_LOG_SERIOUS, "Informational Exchange message is invalid because"
1383 " it has a Message ID of 0");
1384 /* XXX Could send notification back */
1385 return;
1386 }
1387
1388 if (!reserve_msgid(st, md->hdr.isa_msgid))
1389 {
1390 loglog(RC_LOG_SERIOUS, "Informational Exchange message is invalid because"
1391 " it has a previously used Message ID (0x%08lx)"
1392 , (unsigned long)md->hdr.isa_msgid);
1393 /* XXX Could send notification back */
1394 return;
1395 }
1396
1397 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1398 {
1399 memcpy(st->st_ph1_iv, st->st_new_iv, st->st_new_iv_len);
1400 st->st_ph1_iv_len = st->st_new_iv_len;
1401
1402 /* backup new_iv */
1403 new_iv_len = st->st_new_iv_len;
1404 passert(new_iv_len <= MAX_DIGEST_LEN)
1405 memcpy(new_iv, st->st_new_iv, new_iv_len);
1406 restore_iv = TRUE;
1407 }
1408 init_phase2_iv(st, &md->hdr.isa_msgid);
1409 new_iv_set = TRUE;
1410
1411 from_state = STATE_INFO_PROTECTED;
1412 }
1413 else
1414 {
1415 if (st != NULL && IS_ISAKMP_ENCRYPTED(st->st_state))
1416 {
1417 loglog(RC_LOG_SERIOUS, "Informational Exchange message"
1418 " must be encrypted");
1419 /* XXX Could send notification back */
1420 return;
1421 }
1422 from_state = STATE_INFO;
1423 }
1424 break;
1425
1426 case ISAKMP_XCHG_QUICK: /* part of a Quick Mode exchange */
1427 if (is_zero_cookie(md->hdr.isa_icookie))
1428 {
1429 plog("Quick Mode message is invalid because"
1430 " it has an Initiator Cookie of 0");
1431 SEND_NOTIFICATION(INVALID_COOKIE);
1432 return;
1433 }
1434
1435 if (is_zero_cookie(md->hdr.isa_rcookie))
1436 {
1437 plog("Quick Mode message is invalid because"
1438 " it has a Responder Cookie of 0");
1439 SEND_NOTIFICATION(INVALID_COOKIE);
1440 return;
1441 }
1442
1443 if (md->hdr.isa_msgid == MAINMODE_MSGID)
1444 {
1445 plog("Quick Mode message is invalid because"
1446 " it has a Message ID of 0");
1447 SEND_NOTIFICATION(INVALID_MESSAGE_ID);
1448 return;
1449 }
1450
1451 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1452 , &md->sender, md->hdr.isa_msgid);
1453
1454 if (st == NULL)
1455 {
1456 /* No appropriate Quick Mode state.
1457 * See if we have a Main Mode state.
1458 * ??? what if this is a duplicate of another message?
1459 */
1460 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1461 , &md->sender, MAINMODE_MSGID);
1462
1463 if (st == NULL)
1464 {
1465 plog("Quick Mode message is for a non-existent (expired?)"
1466 " ISAKMP SA");
1467 /* XXX Could send notification back */
1468 return;
1469 }
1470
1471 set_cur_state(st);
1472
1473 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1474 {
1475 loglog(RC_LOG_SERIOUS, "Quick Mode message is unacceptable because"
1476 " it is for an incomplete ISAKMP SA");
1477 SEND_NOTIFICATION(PAYLOAD_MALFORMED /* XXX ? */);
1478 return;
1479 }
1480
1481 /* only accept this new Quick Mode exchange if it has a unique message ID */
1482 if (!reserve_msgid(st, md->hdr.isa_msgid))
1483 {
1484 loglog(RC_LOG_SERIOUS, "Quick Mode I1 message is unacceptable because"
1485 " it uses a previously used Message ID 0x%08lx"
1486 " (perhaps this is a duplicated packet)"
1487 , (unsigned long) md->hdr.isa_msgid);
1488 SEND_NOTIFICATION(INVALID_MESSAGE_ID);
1489 return;
1490 }
1491
1492 /* Quick Mode Initial IV */
1493 init_phase2_iv(st, &md->hdr.isa_msgid);
1494 new_iv_set = TRUE;
1495
1496 from_state = STATE_QUICK_R0;
1497 }
1498 else
1499 {
1500 set_cur_state(st);
1501 from_state = st->st_state;
1502 }
1503
1504 break;
1505
1506 case ISAKMP_XCHG_MODE_CFG:
1507 if (is_zero_cookie(md->hdr.isa_icookie))
1508 {
1509 plog("ModeCfg message is invalid because"
1510 " it has an Initiator Cookie of 0");
1511 /* XXX Could send notification back */
1512 return;
1513 }
1514
1515 if (is_zero_cookie(md->hdr.isa_rcookie))
1516 {
1517 plog("ModeCfg message is invalid because"
1518 " it has a Responder Cookie of 0");
1519 /* XXX Could send notification back */
1520 return;
1521 }
1522
1523 if (md->hdr.isa_msgid == 0)
1524 {
1525 plog("ModeCfg message is invalid because"
1526 " it has a Message ID of 0");
1527 /* XXX Could send notification back */
1528 return;
1529 }
1530
1531 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1532 , &md->sender, md->hdr.isa_msgid);
1533
1534 if (st == NULL)
1535 {
1536 bool has_xauth_policy;
1537
1538 /* No appropriate ModeCfg state.
1539 * See if we have a Main Mode state.
1540 * ??? what if this is a duplicate of another message?
1541 */
1542 st = find_state(md->hdr.isa_icookie, md->hdr.isa_rcookie
1543 , &md->sender, 0);
1544
1545 if (st == NULL)
1546 {
1547 plog("ModeCfg message is for a non-existent (expired?)"
1548 " ISAKMP SA");
1549 /* XXX Could send notification back */
1550 return;
1551 }
1552
1553 set_cur_state(st);
1554
1555 if (!IS_ISAKMP_SA_ESTABLISHED(st->st_state))
1556 {
1557 loglog(RC_LOG_SERIOUS, "ModeCfg message is unacceptable because"
1558 " it is for an incomplete ISAKMP SA (state=%s)"
1559 , enum_name(&state_names, st->st_state));
1560 /* XXX Could send notification back */
1561 return;
1562 }
1563 init_phase2_iv(st, &md->hdr.isa_msgid);
1564 new_iv_set = TRUE;
1565
1566 /*
1567 * okay, now we have to figure out if we are receiving a bogus
1568 * new message in an oustanding XAUTH server conversation
1569 * (i.e. a reply to our challenge)
1570 * (this occurs with some broken other implementations).
1571 *
1572 * or if receiving for the first time, an XAUTH challenge.
1573 *
1574 * or if we are getting a MODECFG request.
1575 *
1576 * we distinguish these states because we can not both be an
1577 * XAUTH server and client, and our policy tells us which
1578 * one we are.
1579 *
1580 * to complicate further, it is normal to start a new msgid
1581 * when going from one state to another, or when restarting
1582 * the challenge.
1583 *
1584 */
1585
1586 has_xauth_policy = (st->st_connection->policy
1587 & (POLICY_XAUTH_RSASIG | POLICY_XAUTH_PSK))
1588 != LEMPTY;
1589
1590 if (has_xauth_policy && !st->st_xauth.started
1591 && IS_PHASE1(st->st_state))
1592 {
1593 from_state = STATE_XAUTH_I0;
1594 }
1595 else if (st->st_connection->spd.that.modecfg
1596 && IS_PHASE1(st->st_state))
1597 {
1598 from_state = STATE_MODE_CFG_R0;
1599 }
1600 else if (st->st_connection->spd.this.modecfg
1601 && IS_PHASE1(st->st_state))
1602 {
1603 from_state = STATE_MODE_CFG_I0;
1604 }
1605 else
1606 {
1607 /* XXX check if we are being a mode config server here */
1608 plog("received ModeCfg message when in state %s, and we aren't mode config client"
1609 , enum_name(&state_names, st->st_state));
1610 return;
1611 }
1612 }
1613 else
1614 {
1615 set_cur_state(st);
1616 from_state = st->st_state;
1617 }
1618 break;
1619
1620 #ifdef NOTYET
1621 case ISAKMP_XCHG_NGRP:
1622 case ISAKMP_XCHG_ACK_INFO:
1623 #endif
1624
1625 default:
1626 plog("unsupported exchange type %s in message"
1627 , enum_show(&exchange_names, md->hdr.isa_xchg));
1628 SEND_NOTIFICATION(UNSUPPORTED_EXCHANGE_TYPE);
1629 return;
1630 }
1631
1632 /* We have found a from_state, and perhaps a state object.
1633 * If we need to build a new state object,
1634 * we wait until the packet has been sanity checked.
1635 */
1636
1637 /* We don't support the Commit Flag. It is such a bad feature.
1638 * It isn't protected -- neither encrypted nor authenticated.
1639 * A man in the middle turns it on, leading to DoS.
1640 * We just ignore it, with a warning.
1641 * By placing the check here, we could easily add a policy bit
1642 * to a connection to suppress the warning. This might be useful
1643 * because the Commit Flag is expected from some peers.
1644 */
1645 if (md->hdr.isa_flags & ISAKMP_FLAG_COMMIT)
1646 {
1647 plog("IKE message has the Commit Flag set but Pluto doesn't implement this feature; ignoring flag");
1648 }
1649
1650 /* Set smc to describe this state's properties.
1651 * Look up the appropriate microcode based on state and
1652 * possibly Oakley Auth type.
1653 */
1654 passert(STATE_IKE_FLOOR <= from_state && from_state <= STATE_IKE_ROOF);
1655 smc = ike_microcode_index[from_state - STATE_IKE_FLOOR];
1656
1657 if (st != NULL)
1658 {
1659 u_int16_t auth;
1660
1661 switch (st->st_oakley.auth)
1662 {
1663 case XAUTHInitPreShared:
1664 case XAUTHRespPreShared:
1665 auth = OAKLEY_PRESHARED_KEY;
1666 break;
1667 case XAUTHInitRSA:
1668 case XAUTHRespRSA:
1669 auth = OAKLEY_RSA_SIG;
1670 break;
1671 default:
1672 auth = st->st_oakley.auth;
1673 }
1674
1675 while (!LHAS(smc->flags, auth))
1676 {
1677 smc++;
1678 passert(smc->state == from_state);
1679 }
1680 }
1681
1682 /* Ignore a packet if the state has a suspended state transition
1683 * Probably a duplicated packet but the original packet is not yet
1684 * recorded in st->st_rpacket, so duplicate checking won't catch.
1685 * ??? Should the packet be recorded earlier to improve diagnosis?
1686 */
1687 if (st != NULL && st->st_suspended_md != NULL)
1688 {
1689 loglog(RC_LOG, "discarding packet received during DNS lookup in %s"
1690 , enum_name(&state_names, st->st_state));
1691 return;
1692 }
1693
1694 /* Detect and handle duplicated packets.
1695 * This won't work for the initial packet of an exchange
1696 * because we won't have a state object to remember it.
1697 * If we are in a non-receiving state (terminal), and the preceding
1698 * state did transmit, then the duplicate may indicate that that
1699 * transmission wasn't received -- retransmit it.
1700 * Otherwise, just discard it.
1701 * ??? Notification packets are like exchanges -- I hope that
1702 * they are idempotent!
1703 */
1704 if (st != NULL
1705 && st->st_rpacket.ptr != NULL
1706 && st->st_rpacket.len == pbs_room(&md->packet_pbs)
1707 && memcmp(st->st_rpacket.ptr, md->packet_pbs.start, st->st_rpacket.len) == 0)
1708 {
1709 if (smc->flags & SMF_RETRANSMIT_ON_DUPLICATE)
1710 {
1711 if (st->st_retransmit < MAXIMUM_RETRANSMISSIONS)
1712 {
1713 st->st_retransmit++;
1714 loglog(RC_RETRANSMISSION
1715 , "retransmitting in response to duplicate packet; already %s"
1716 , enum_name(&state_names, st->st_state));
1717 send_packet(st, "retransmit in response to duplicate");
1718 }
1719 else
1720 {
1721 loglog(RC_LOG_SERIOUS, "discarding duplicate packet -- exhausted retransmission; already %s"
1722 , enum_name(&state_names, st->st_state));
1723 }
1724 }
1725 else
1726 {
1727 loglog(RC_LOG_SERIOUS, "discarding duplicate packet; already %s"
1728 , enum_name(&state_names, st->st_state));
1729 }
1730 return;
1731 }
1732
1733 if (md->hdr.isa_flags & ISAKMP_FLAG_ENCRYPTION)
1734 {
1735 DBG(DBG_CRYPT, DBG_log("received encrypted packet from %s:%u"
1736 , ip_str(&md->sender), (unsigned)md->sender_port));
1737
1738 if (st == NULL)
1739 {
1740 plog("discarding encrypted message for an unknown ISAKMP SA");
1741 SEND_NOTIFICATION(PAYLOAD_MALFORMED /* XXX ? */);
1742 return;
1743 }
1744 if (st->st_skeyid_e.ptr == (u_char *) NULL)
1745 {
1746 loglog(RC_LOG_SERIOUS, "discarding encrypted message"
1747 " because we haven't yet negotiated keying materiel");
1748 SEND_NOTIFICATION(INVALID_FLAGS);
1749 return;
1750 }
1751
1752 /* Mark as encrypted */
1753 md->encrypted = TRUE;
1754
1755 DBG(DBG_CRYPT, DBG_log("decrypting %u bytes using algorithm %s"
1756 , (unsigned) pbs_left(&md->message_pbs)
1757 , enum_show(&oakley_enc_names, st->st_oakley.encrypt)));
1758
1759 /* do the specified decryption
1760 *
1761 * IV is from st->st_iv or (if new_iv_set) st->st_new_iv.
1762 * The new IV is placed in st->st_new_iv
1763 *
1764 * See RFC 2409 "IKE" Appendix B
1765 *
1766 * XXX The IV should only be updated really if the packet
1767 * is successfully processed.
1768 * We should keep this value, check for a success return
1769 * value from the parsing routines and then replace.
1770 *
1771 * Each post phase 1 exchange generates IVs from
1772 * the last phase 1 block, not the last block sent.
1773 */
1774 {
1775 const struct encrypt_desc *e = st->st_oakley.encrypter;
1776
1777 if (pbs_left(&md->message_pbs) % e->enc_blocksize != 0)
1778 {
1779 loglog(RC_LOG_SERIOUS, "malformed message: not a multiple of encryption blocksize");
1780 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
1781 return;
1782 }
1783
1784 /* XXX Detect weak keys */
1785
1786 /* grab a copy of raw packet (for duplicate packet detection) */
1787 clonetochunk(md->raw_packet, md->packet_pbs.start
1788 , pbs_room(&md->packet_pbs), "raw packet");
1789
1790 /* Decrypt everything after header */
1791 if (!new_iv_set)
1792 {
1793 /* use old IV */
1794 passert(st->st_iv_len <= sizeof(st->st_new_iv));
1795 st->st_new_iv_len = st->st_iv_len;
1796 memcpy(st->st_new_iv, st->st_iv, st->st_new_iv_len);
1797 }
1798 crypto_cbc_encrypt(e, FALSE, md->message_pbs.cur,
1799 pbs_left(&md->message_pbs) , st);
1800 if (restore_iv)
1801 {
1802 memcpy(st->st_new_iv, new_iv, new_iv_len);
1803 st->st_new_iv_len = new_iv_len;
1804 }
1805 }
1806
1807 DBG_cond_dump(DBG_CRYPT, "decrypted:\n", md->message_pbs.cur
1808 , md->message_pbs.roof - md->message_pbs.cur);
1809
1810 DBG_cond_dump(DBG_CRYPT, "next IV:"
1811 , st->st_new_iv, st->st_new_iv_len);
1812 }
1813 else
1814 {
1815 /* packet was not encryped -- should it have been? */
1816
1817 if (smc->flags & SMF_INPUT_ENCRYPTED)
1818 {
1819 loglog(RC_LOG_SERIOUS, "packet rejected: should have been encrypted");
1820 SEND_NOTIFICATION(INVALID_FLAGS);
1821 return;
1822 }
1823 }
1824
1825 /* Digest the message.
1826 * Padding must be removed to make hashing work.
1827 * Padding comes from encryption (so this code must be after decryption).
1828 * Padding rules are described before the definition of
1829 * struct isakmp_hdr in packet.h.
1830 */
1831 {
1832 struct payload_digest *pd = md->digest;
1833 int np = md->hdr.isa_np;
1834 lset_t needed = smc->req_payloads;
1835 const char *excuse
1836 = LIN(SMF_PSK_AUTH | SMF_FIRST_ENCRYPTED_INPUT, smc->flags)
1837 ? "probable authentication failure (mismatch of preshared secrets?): "
1838 : "";
1839
1840 while (np != ISAKMP_NEXT_NONE)
1841 {
1842 struct_desc *sd = np < ISAKMP_NEXT_ROOF? payload_descs[np] : NULL;
1843
1844 if (pd == &md->digest[PAYLIMIT])
1845 {
1846 loglog(RC_LOG_SERIOUS, "more than %d payloads in message; ignored", PAYLIMIT);
1847 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
1848 return;
1849 }
1850
1851 switch (np)
1852 {
1853 case ISAKMP_NEXT_NATD_RFC:
1854 case ISAKMP_NEXT_NATOA_RFC:
1855 if (!st || !(st->nat_traversal & NAT_T_WITH_RFC_VALUES))
1856 {
1857 /*
1858 * don't accept NAT-D/NAT-OA reloc directly in message, unless
1859 * we're using NAT-T RFC
1860 */
1861 sd = NULL;
1862 }
1863 break;
1864 }
1865
1866 if (sd == NULL)
1867 {
1868 /* payload type is out of range or requires special handling */
1869 switch (np)
1870 {
1871 case ISAKMP_NEXT_ID:
1872 sd = IS_PHASE1(from_state)
1873 ? &isakmp_identification_desc : &isakmp_ipsec_identification_desc;
1874 break;
1875 case ISAKMP_NEXT_NATD_DRAFTS:
1876 np = ISAKMP_NEXT_NATD_RFC; /* NAT-D relocated */
1877 sd = payload_descs[np];
1878 break;
1879 case ISAKMP_NEXT_NATOA_DRAFTS:
1880 np = ISAKMP_NEXT_NATOA_RFC; /* NAT-OA relocated */
1881 sd = payload_descs[np];
1882 break;
1883 default:
1884 loglog(RC_LOG_SERIOUS, "%smessage ignored because it contains an unknown or"
1885 " unexpected payload type (%s) at the outermost level"
1886 , excuse, enum_show(&payload_names, np));
1887 SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE);
1888 return;
1889 }
1890 }
1891
1892 {
1893 lset_t s = LELEM(np);
1894
1895 if (LDISJOINT(s
1896 , needed | smc->opt_payloads| LELEM(ISAKMP_NEXT_N) | LELEM(ISAKMP_NEXT_D)))
1897 {
1898 loglog(RC_LOG_SERIOUS, "%smessage ignored because it "
1899 "contains an unexpected payload type (%s)"
1900 , excuse, enum_show(&payload_names, np));
1901 SEND_NOTIFICATION(INVALID_PAYLOAD_TYPE);
1902 return;
1903 }
1904 needed &= ~s;
1905 }
1906
1907 if (!in_struct(&pd->payload, sd, &md->message_pbs, &pd->pbs))
1908 {
1909 loglog(RC_LOG_SERIOUS, "%smalformed payload in packet", excuse);
1910 if (md->hdr.isa_xchg != ISAKMP_XCHG_INFO)
1911 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
1912 return;
1913 }
1914
1915 /* place this payload at the end of the chain for this type */
1916 {
1917 struct payload_digest **p;
1918
1919 for (p = &md->chain[np]; *p != NULL; p = &(*p)->next)
1920 ;
1921 *p = pd;
1922 pd->next = NULL;
1923 }
1924
1925 np = pd->payload.generic.isag_np;
1926 pd++;
1927
1928 /* since we've digested one payload happily, it is probably
1929 * the case that any decryption worked. So we will not suggest
1930 * encryption failure as an excuse for subsequent payload
1931 * problems.
1932 */
1933 excuse = "";
1934 }
1935
1936 md->digest_roof = pd;
1937
1938 DBG(DBG_PARSING,
1939 if (pbs_left(&md->message_pbs) != 0)
1940 DBG_log("removing %d bytes of padding", (int) pbs_left(&md->message_pbs)));
1941
1942 md->message_pbs.roof = md->message_pbs.cur;
1943
1944 /* check that all mandatory payloads appeared */
1945
1946 if (needed != 0)
1947 {
1948 loglog(RC_LOG_SERIOUS, "message for %s is missing payloads %s"
1949 , enum_show(&state_names, from_state)
1950 , bitnamesof(payload_name, needed));
1951 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
1952 return;
1953 }
1954 }
1955
1956 /* more sanity checking: enforce most ordering constraints */
1957
1958 if (IS_PHASE1(from_state))
1959 {
1960 /* rfc2409: The Internet Key Exchange (IKE), 5 Exchanges:
1961 * "The SA payload MUST precede all other payloads in a phase 1 exchange."
1962 */
1963 if (md->chain[ISAKMP_NEXT_SA] != NULL
1964 && md->hdr.isa_np != ISAKMP_NEXT_SA)
1965 {
1966 loglog(RC_LOG_SERIOUS, "malformed Phase 1 message: does not start with an SA payload");
1967 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
1968 return;
1969 }
1970 }
1971 else if (IS_QUICK(from_state))
1972 {
1973 /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode
1974 *
1975 * "In Quick Mode, a HASH payload MUST immediately follow the ISAKMP
1976 * header and a SA payload MUST immediately follow the HASH."
1977 * [NOTE: there may be more than one SA payload, so this is not
1978 * totally reasonable. Probably all SAs should be so constrained.]
1979 *
1980 * "If ISAKMP is acting as a client negotiator on behalf of another
1981 * party, the identities of the parties MUST be passed as IDci and
1982 * then IDcr."
1983 *
1984 * "With the exception of the HASH, SA, and the optional ID payloads,
1985 * there are no payload ordering restrictions on Quick Mode."
1986 */
1987
1988 if (md->hdr.isa_np != ISAKMP_NEXT_HASH)
1989 {
1990 loglog(RC_LOG_SERIOUS, "malformed Quick Mode message: does not start with a HASH payload");
1991 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
1992 return;
1993 }
1994
1995 {
1996 struct payload_digest *p;
1997 int i;
1998
1999 for (p = md->chain[ISAKMP_NEXT_SA], i = 1; p != NULL
2000 ; p = p->next, i++)
2001 {
2002 if (p != &md->digest[i])
2003 {
2004 loglog(RC_LOG_SERIOUS, "malformed Quick Mode message: SA payload is in wrong position");
2005 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
2006 return;
2007 }
2008 }
2009 }
2010
2011 /* rfc2409: The Internet Key Exchange (IKE), 5.5 Phase 2 - Quick Mode:
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 {
2017 struct payload_digest *id = md->chain[ISAKMP_NEXT_ID];
2018
2019 if (id != NULL)
2020 {
2021 if (id->next == NULL || id->next->next != NULL)
2022 {
2023 loglog(RC_LOG_SERIOUS, "malformed Quick Mode message:"
2024 " if any ID payload is present,"
2025 " there must be exactly two");
2026 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
2027 return;
2028 }
2029 if (id+1 != id->next)
2030 {
2031 loglog(RC_LOG_SERIOUS, "malformed Quick Mode message:"
2032 " the ID payloads are not adjacent");
2033 SEND_NOTIFICATION(PAYLOAD_MALFORMED);
2034 return;
2035 }
2036 }
2037 }
2038 }
2039
2040 /* Ignore payloads that we don't handle:
2041 * Delete, Notification, VendorID
2042 */
2043 /* XXX Handle deletions */
2044 /* XXX Handle Notifications */
2045 /* XXX Handle VID payloads */
2046 {
2047 struct payload_digest *p;
2048
2049 for (p = md->chain[ISAKMP_NEXT_N]; p != NULL; p = p->next)
2050 {
2051 if (p->payload.notification.isan_type != R_U_THERE
2052 && p->payload.notification.isan_type != R_U_THERE_ACK)
2053 {
2054 loglog(RC_LOG_SERIOUS, "ignoring informational payload, type %s"
2055 , enum_show(&notification_names, p->payload.notification.isan_type));
2056 }
2057 DBG_cond_dump(DBG_PARSING, "info:", p->pbs.cur, pbs_left(&p->pbs));
2058 }
2059
2060 for (p = md->chain[ISAKMP_NEXT_D]; p != NULL; p = p->next)
2061 {
2062 accept_delete(st, md, p);
2063 DBG_cond_dump(DBG_PARSING, "del:", p->pbs.cur, pbs_left(&p->pbs));
2064 }
2065
2066 for (p = md->chain[ISAKMP_NEXT_VID]; p != NULL; p = p->next)
2067 {
2068 handle_vendorid(md, p->pbs.cur, pbs_left(&p->pbs));
2069 }
2070 }
2071 md->from_state = from_state;
2072 md->smc = smc;
2073 md->st = st;
2074
2075 /* possibly fill in hdr */
2076 if (smc->first_out_payload != ISAKMP_NEXT_NONE)
2077 echo_hdr(md, (smc->flags & SMF_OUTPUT_ENCRYPTED) != 0
2078 , smc->first_out_payload);
2079
2080 complete_state_transition(mdp, smc->processor(md));
2081 }
2082
2083 /* complete job started by the state-specific state transition function */
2084
2085 void
2086 complete_state_transition(struct msg_digest **mdp, stf_status result)
2087 {
2088 bool has_xauth_policy;
2089 bool is_xauth_server;
2090 struct msg_digest *md = *mdp;
2091 const struct state_microcode *smc = md->smc;
2092 enum state_kind from_state = md->from_state;
2093 struct state *st;
2094
2095 cur_state = st = md->st; /* might have changed */
2096
2097 /* If state has DPD support, import it */
2098 if (st && md->dpd)
2099 st->st_dpd = TRUE;
2100
2101 switch (result)
2102 {
2103 case STF_IGNORE:
2104 break;
2105
2106 case STF_SUSPEND:
2107 /* the stf didn't complete its job: don't relase md */
2108 *mdp = NULL;
2109 break;
2110
2111 case STF_OK:
2112 /* advance the state */
2113 st->st_state = smc->next_state;
2114
2115 /* Delete previous retransmission event.
2116 * New event will be scheduled below.
2117 */
2118 delete_event(st);
2119
2120 /* replace previous receive packet with latest */
2121
2122 pfreeany(st->st_rpacket.ptr);
2123
2124 if (md->encrypted)
2125 {
2126 /* if encrypted, duplication already done */
2127 st->st_rpacket = md->raw_packet;
2128 md->raw_packet.ptr = NULL;
2129 }
2130 else
2131 {
2132 clonetochunk(st->st_rpacket
2133 , md->packet_pbs.start
2134 , pbs_room(&md->packet_pbs), "raw packet");
2135 }
2136
2137 /* free previous transmit packet */
2138 freeanychunk(st->st_tpacket);
2139
2140 /* if requested, send the new reply packet */
2141 if (smc->flags & SMF_REPLY)
2142 {
2143 close_output_pbs(&md->reply); /* good form, but actually a no-op */
2144
2145 clonetochunk(st->st_tpacket, md->reply.start
2146 , pbs_offset(&md->reply), "reply packet");
2147
2148 if (nat_traversal_enabled)
2149 nat_traversal_change_port_lookup(md, md->st);
2150
2151 /* actually send the packet
2152 * Note: this is a great place to implement "impairments"
2153 * for testing purposes. Suppress or duplicate the
2154 * send_packet call depending on st->st_state.
2155 */
2156 send_packet(st, enum_name(&state_names, from_state));
2157 }
2158
2159 /* Schedule for whatever timeout is specified */
2160 {
2161 time_t delay;
2162 enum event_type kind = smc->timeout_event;
2163 bool agreed_time = FALSE;
2164 struct connection *c = st->st_connection;
2165
2166 switch (kind)
2167 {
2168 case EVENT_RETRANSMIT: /* Retransmit packet */
2169 delay = EVENT_RETRANSMIT_DELAY_0;
2170 break;
2171
2172 case EVENT_SA_REPLACE: /* SA replacement event */
2173 if (IS_PHASE1(st->st_state))
2174 {
2175 /* Note: we will defer to the "negotiated" (dictated)
2176 * lifetime if we are POLICY_DONT_REKEY.
2177 * This allows the other side to dictate
2178 * a time we would not otherwise accept
2179 * but it prevents us from having to initiate
2180 * rekeying. The negative consequences seem
2181 * minor.
2182 */
2183 delay = c->sa_ike_life_seconds;
2184 if ((c->policy & POLICY_DONT_REKEY)
2185 || delay >= st->st_oakley.life_seconds)
2186 {
2187 agreed_time = TRUE;
2188 delay = st->st_oakley.life_seconds;
2189 }
2190 }
2191 else
2192 {
2193 /* Delay is min of up to four things:
2194 * each can limit the lifetime.
2195 */
2196 delay = c->sa_ipsec_life_seconds;
2197 if (st->st_ah.present
2198 && delay >= st->st_ah.attrs.life_seconds)
2199 {
2200 agreed_time = TRUE;
2201 delay = st->st_ah.attrs.life_seconds;
2202 }
2203 if (st->st_esp.present
2204 && delay >= st->st_esp.attrs.life_seconds)
2205 {
2206 agreed_time = TRUE;
2207 delay = st->st_esp.attrs.life_seconds;
2208 }
2209 if (st->st_ipcomp.present
2210 && delay >= st->st_ipcomp.attrs.life_seconds)
2211 {
2212 agreed_time = TRUE;
2213 delay = st->st_ipcomp.attrs.life_seconds;
2214 }
2215 }
2216
2217 /* By default, we plan to rekey.
2218 *
2219 * If there isn't enough time to rekey, plan to
2220 * expire.
2221 *
2222 * If we are --dontrekey, a lot more rules apply.
2223 * If we are the Initiator, use REPLACE_IF_USED.
2224 * If we are the Responder, and the dictated time
2225 * was unacceptable (too large), plan to REPLACE
2226 * (the only way to ratchet down the time).
2227 * If we are the Responder, and the dictated time
2228 * is acceptable, plan to EXPIRE.
2229 *
2230 * Important policy lies buried here.
2231 * For example, we favour the initiator over the
2232 * responder by making the initiator start rekeying
2233 * sooner. Also, fuzz is only added to the
2234 * initiator's margin.
2235 *
2236 * Note: for ISAKMP SA, we let the negotiated
2237 * time stand (implemented by earlier logic).
2238 */
2239 if (agreed_time
2240 && (c->policy & POLICY_DONT_REKEY))
2241 {
2242 kind = (smc->flags & SMF_INITIATOR)
2243 ? EVENT_SA_REPLACE_IF_USED
2244 : EVENT_SA_EXPIRE;
2245 }
2246 if (kind != EVENT_SA_EXPIRE)
2247 {
2248 unsigned long marg = c->sa_rekey_margin;
2249
2250 if (smc->flags & SMF_INITIATOR)
2251 marg += marg
2252 * c->sa_rekey_fuzz / 100.E0
2253 * (rand() / (RAND_MAX + 1.E0));
2254 else
2255 marg /= 2;
2256
2257 if ((unsigned long)delay > marg)
2258 {
2259 delay -= marg;
2260 st->st_margin = marg;
2261 }
2262 else
2263 {
2264 kind = EVENT_SA_EXPIRE;
2265 }
2266 }
2267 break;
2268
2269 case EVENT_NULL: /* non-event */
2270 case EVENT_REINIT_SECRET: /* Refresh cookie secret */
2271 default:
2272 bad_case(kind);
2273 }
2274 event_schedule(kind, delay, st);
2275 }
2276
2277 /* tell whack and log of progress */
2278 {
2279 const char *story = state_story[st->st_state - STATE_MAIN_R0];
2280 enum rc_type w = RC_NEW_STATE + st->st_state;
2281 char sadetails[128];
2282
2283 sadetails[0]='\0';
2284
2285 if (IS_IPSEC_SA_ESTABLISHED(st->st_state))
2286 {
2287 char *b = sadetails;
2288 const char *ini = " {";
2289 const char *fin = "";
2290
2291 /* -1 is to leave space for "fin" */
2292
2293 if (st->st_esp.present)
2294 {
2295 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2296 , "%sESP=>0x%08x <0x%08x"
2297 , ini
2298 , ntohl(st->st_esp.attrs.spi)
2299 , ntohl(st->st_esp.our_spi));
2300 ini = " ";
2301 fin = "}";
2302 }
2303 /* advance b to end of string */
2304 b = b + strlen(b);
2305
2306 if (st->st_ah.present)
2307 {
2308 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2309 , "%sAH=>0x%08x <0x%08x"
2310 , ini
2311 , ntohl(st->st_ah.attrs.spi)
2312 , ntohl(st->st_ah.our_spi));
2313 ini = " ";
2314 fin = "}";
2315 }
2316 /* advance b to end of string */
2317 b = b + strlen(b);
2318
2319 if (st->st_ipcomp.present)
2320 {
2321 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2322 , "%sIPCOMP=>0x%08x <0x%08x"
2323 , ini
2324 , ntohl(st->st_ipcomp.attrs.spi)
2325 , ntohl(st->st_ipcomp.our_spi));
2326 ini = " ";
2327 fin = "}";
2328 }
2329 /* advance b to end of string */
2330 b = b + strlen(b);
2331
2332 if (st->nat_traversal)
2333 {
2334 char oa[ADDRTOT_BUF];
2335 addrtot(&st->nat_oa, 0, oa, sizeof(oa));
2336 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2337 , "%sNATOA=%s"
2338 , ini, oa);
2339 ini = " ";
2340 fin = "}";
2341 }
2342
2343 /* advance b to end of string */
2344 b = b + strlen(b);
2345
2346 if (st->st_dpd)
2347 {
2348 snprintf(b, sizeof(sadetails)-(b-sadetails)-1
2349 , "%sDPD"
2350 , ini);
2351 ini = " ";
2352 fin = "}";
2353 }
2354
2355 strcat(b, fin);
2356 }
2357
2358 if (IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2359 || IS_IPSEC_SA_ESTABLISHED(st->st_state))
2360 {
2361 /* log our success */
2362 plog("%s%s", story, sadetails);
2363 w = RC_SUCCESS;
2364 }
2365
2366 /* tell whack our progress */
2367 whack_log(w
2368 , "%s: %s%s"
2369 , enum_name(&state_names, st->st_state)
2370 , story, sadetails);
2371 }
2372
2373 has_xauth_policy = (st->st_connection->policy
2374 & (POLICY_XAUTH_RSASIG | POLICY_XAUTH_PSK))
2375 != LEMPTY;
2376 is_xauth_server = (st->st_connection->policy
2377 & POLICY_XAUTH_SERVER)
2378 != LEMPTY;
2379
2380 /* Should we start XAUTH as a server */
2381 if (has_xauth_policy && is_xauth_server
2382 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2383 && !st->st_xauth.started)
2384 {
2385 DBG(DBG_CONTROL,
2386 DBG_log("starting XAUTH server")
2387 )
2388 xauth_send_request(st);
2389 break;
2390 }
2391
2392 /* Wait for XAUTH request from server */
2393 if (has_xauth_policy && !is_xauth_server
2394 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2395 && !st->st_xauth.started)
2396 {
2397 DBG(DBG_CONTROL,
2398 DBG_log("waiting for XAUTH request from server")
2399 )
2400 break;
2401 }
2402
2403 /* Should we start ModeConfig as a client? */
2404 if (st->st_connection->spd.this.modecfg
2405 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2406 && !(st->st_connection->policy & POLICY_MODECFG_PUSH)
2407 && !st->st_modecfg.started)
2408 {
2409 DBG(DBG_CONTROL,
2410 DBG_log("starting ModeCfg client in pull mode")
2411 )
2412 modecfg_send_request(st);
2413 break;
2414 }
2415
2416 /* Should we start ModeConfig as a server? */
2417 if (st->st_connection->spd.that.modecfg
2418 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2419 && !st->st_modecfg.started
2420 && (st->st_connection->policy & POLICY_MODECFG_PUSH))
2421 {
2422 DBG(DBG_CONTROL,
2423 DBG_log("starting ModeCfg server in push mode")
2424 )
2425 modecfg_send_set(st);
2426 break;
2427 }
2428
2429 /* Wait for ModeConfig set from server */
2430 if (st->st_connection->spd.this.modecfg
2431 && IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2432 && !st->st_modecfg.vars_set)
2433 {
2434 DBG(DBG_CONTROL,
2435 DBG_log("waiting for ModeCfg set from server")
2436 )
2437 break;
2438 }
2439
2440 if (smc->flags & SMF_RELEASE_PENDING_P2)
2441 {
2442 /* Initiate any Quick Mode negotiations that
2443 * were waiting to piggyback on this Keying Channel.
2444 *
2445 * ??? there is a potential race condition
2446 * if we are the responder: the initial Phase 2
2447 * message might outrun the final Phase 1 message.
2448 * I think that retransmission will recover.
2449 */
2450 unpend(st);
2451 }
2452
2453 if (IS_ISAKMP_SA_ESTABLISHED(st->st_state)
2454 || IS_IPSEC_SA_ESTABLISHED(st->st_state))
2455 release_whack(st);
2456 break;
2457
2458 case STF_INTERNAL_ERROR:
2459 whack_log(RC_INTERNALERR + md->note
2460 , "%s: internal error"
2461 , enum_name(&state_names, st->st_state));
2462
2463 DBG(DBG_CONTROL,
2464 DBG_log("state transition function for %s had internal error"
2465 , enum_name(&state_names, from_state)));
2466 break;
2467
2468 default: /* a shortcut to STF_FAIL, setting md->note */
2469 passert(result > STF_FAIL);
2470 md->note = result - STF_FAIL;
2471 result = STF_FAIL;
2472 /* FALL THROUGH ... */
2473 case STF_FAIL:
2474 /* As it is, we act as if this message never happened:
2475 * whatever retrying was in place, remains in place.
2476 */
2477 whack_log(RC_NOTIFICATION + md->note
2478 , "%s: %s"
2479 , enum_name(&state_names, (st == NULL)? STATE_MAIN_R0:st->st_state)
2480 , enum_name(&notification_names, md->note));
2481
2482 SEND_NOTIFICATION(md->note);
2483
2484 DBG(DBG_CONTROL,
2485 DBG_log("state transition function for %s failed: %s"
2486 , enum_name(&state_names, from_state)
2487 , enum_name(&notification_names, md->note)));
2488 break;
2489 }
2490 }