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