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