OSDN Git Service

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