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