xref: /freebsd/sys/netgraph/ng_mppc.c (revision 77a0943ded95b9e6438f7db70c4a28e4d93946d4)
1 
2 /*
3  * ng_mppc.c
4  *
5  * Copyright (c) 1996-2000 Whistle Communications, Inc.
6  * All rights reserved.
7  *
8  * Subject to the following obligations and disclaimer of warranty, use and
9  * redistribution of this software, in source or object code forms, with or
10  * without modifications are expressly permitted by Whistle Communications;
11  * provided, however, that:
12  * 1. Any and all reproductions of the source or object code must include the
13  *    copyright notice above and the following disclaimer of warranties; and
14  * 2. No rights are granted, in any manner or form, to use Whistle
15  *    Communications, Inc. trademarks, including the mark "WHISTLE
16  *    COMMUNICATIONS" on advertising, endorsements, or otherwise except as
17  *    such appears in the above copyright notice or in the software.
18  *
19  * THIS SOFTWARE IS BEING PROVIDED BY WHISTLE COMMUNICATIONS "AS IS", AND
20  * TO THE MAXIMUM EXTENT PERMITTED BY LAW, WHISTLE COMMUNICATIONS MAKES NO
21  * REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING THIS SOFTWARE,
22  * INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
24  * WHISTLE COMMUNICATIONS DOES NOT WARRANT, GUARANTEE, OR MAKE ANY
25  * REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS OF THE USE OF THIS
26  * SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY, RELIABILITY OR OTHERWISE.
27  * IN NO EVENT SHALL WHISTLE COMMUNICATIONS BE LIABLE FOR ANY DAMAGES
28  * RESULTING FROM OR ARISING OUT OF ANY USE OF THIS SOFTWARE, INCLUDING
29  * WITHOUT LIMITATION, ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
30  * PUNITIVE, OR CONSEQUENTIAL DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR
31  * SERVICES, LOSS OF USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER ANY
32  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
33  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
34  * THIS SOFTWARE, EVEN IF WHISTLE COMMUNICATIONS IS ADVISED OF THE POSSIBILITY
35  * OF SUCH DAMAGE.
36  *
37  * Author: Archie Cobbs <archie@freebsd.org>
38  *
39  * $Whistle: ng_mppc.c,v 1.4 1999/11/25 00:10:12 archie Exp $
40  * $FreeBSD$
41  */
42 
43 /*
44  * Microsoft PPP compression (MPPC) and encryption (MPPE) netgraph node type.
45  *
46  * You must define one or both of the NETGRAPH_MPPC_COMPRESSION and/or
47  * NETGRAPH_MPPC_ENCRYPTION options for this node type to be useful.
48  */
49 
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/kernel.h>
53 #include <sys/mbuf.h>
54 #include <sys/malloc.h>
55 #include <sys/errno.h>
56 #include <sys/syslog.h>
57 
58 #include <netgraph/ng_message.h>
59 #include <netgraph/netgraph.h>
60 #include <netgraph/ng_mppc.h>
61 
62 #include "opt_netgraph.h"
63 
64 #if !defined(NETGRAPH_MPPC_COMPRESSION) && !defined(NETGRAPH_MPPC_ENCRYPTION)
65 #error Need either NETGRAPH_MPPC_COMPRESSION or NETGRAPH_MPPC_ENCRYPTION
66 #endif
67 
68 #ifdef NETGRAPH_MPPC_COMPRESSION
69 /* XXX this file doesn't exist yet, but hopefully someday it will... */
70 #include <net/mppc.h>
71 #endif
72 #ifdef NETGRAPH_MPPC_ENCRYPTION
73 #include <crypto/rc4/rc4.h>
74 #endif
75 #include <crypto/sha1.h>
76 
77 /* Decompression blowup */
78 #define MPPC_DECOMP_BUFSIZE	8092            /* allocate buffer this big */
79 #define MPPC_DECOMP_SAFETY	100             /*   plus this much margin */
80 
81 /* MPPC/MPPE header length */
82 #define MPPC_HDRLEN		2
83 
84 /* Key length */
85 #define KEYLEN(b)		(((b) & MPPE_128) ? 16 : 8)
86 
87 /* What sequence number jump is too far */
88 #define MPPC_INSANE_JUMP	256
89 
90 /* MPPC packet header bits */
91 #define MPPC_FLAG_FLUSHED	0x8000		/* xmitter reset state */
92 #define MPPC_FLAG_RESTART	0x4000		/* compress history restart */
93 #define MPPC_FLAG_COMPRESSED	0x2000		/* packet is compresed */
94 #define MPPC_FLAG_ENCRYPTED	0x1000		/* packet is encrypted */
95 #define MPPC_CCOUNT_MASK	0x0fff		/* sequence number mask */
96 
97 #define MPPE_UPDATE_MASK	0xff		/* coherency count when we're */
98 #define MPPE_UPDATE_FLAG	0xff		/*   supposed to update key */
99 
100 #define MPPC_COMP_OK		0x05
101 #define MPPC_DECOMP_OK		0x05
102 
103 /* Per direction info */
104 struct ng_mppc_dir {
105 	struct ng_mppc_config	cfg;		/* configuration */
106 	hook_p			hook;		/* netgraph hook */
107 	u_int16_t		cc:12;		/* coherency count */
108 	u_char			flushed;	/* clean history (xmit only) */
109 #ifdef NETGRAPH_MPPC_COMPRESSION
110 	u_char			*history;	/* compression history */
111 #endif
112 #ifdef NETGRAPH_MPPC_ENCRYPTION
113 	u_char			key[MPPE_KEY_LEN];	/* session key */
114 	struct rc4_state	rc4;			/* rc4 state */
115 #endif
116 };
117 
118 /* Node private data */
119 struct ng_mppc_private {
120 	struct ng_mppc_dir	xmit;		/* compress/encrypt config */
121 	struct ng_mppc_dir	recv;		/* decompress/decrypt config */
122 	char			*ctrlpath;	/* path to controlling node */
123 };
124 typedef struct ng_mppc_private *priv_p;
125 
126 /* Netgraph node methods */
127 static ng_constructor_t	ng_mppc_constructor;
128 static ng_rcvmsg_t	ng_mppc_rcvmsg;
129 static ng_shutdown_t	ng_mppc_rmnode;
130 static ng_newhook_t	ng_mppc_newhook;
131 static ng_rcvdata_t	ng_mppc_rcvdata;
132 static ng_disconnect_t	ng_mppc_disconnect;
133 
134 /* Helper functions */
135 static int	ng_mppc_compress(node_p node,
136 			struct mbuf *m, struct mbuf **resultp);
137 static int	ng_mppc_decompress(node_p node,
138 			struct mbuf *m, struct mbuf **resultp);
139 static void	ng_mppc_getkey(const u_char *h, u_char *h2, int len);
140 static void	ng_mppc_updatekey(u_int32_t bits,
141 			u_char *key0, u_char *key, struct rc4_state *rc4);
142 static void	ng_mppc_reset_req(node_p node);
143 
144 /* Node type descriptor */
145 static struct ng_type ng_mppc_typestruct = {
146 	NG_VERSION,
147 	NG_MPPC_NODE_TYPE,
148 	NULL,
149 	ng_mppc_constructor,
150 	ng_mppc_rcvmsg,
151 	ng_mppc_rmnode,
152 	ng_mppc_newhook,
153 	NULL,
154 	NULL,
155 	ng_mppc_rcvdata,
156 	ng_mppc_rcvdata,
157 	ng_mppc_disconnect,
158 	NULL
159 };
160 NETGRAPH_INIT(mppc, &ng_mppc_typestruct);
161 
162 /* Fixed bit pattern to weaken keysize down to 40 bits */
163 static const u_char ng_mppe_weakenkey[3] = { 0xd1, 0x26, 0x9e };
164 
165 #define ERROUT(x)	do { error = (x); goto done; } while (0)
166 
167 /************************************************************************
168 			NETGRAPH NODE STUFF
169  ************************************************************************/
170 
171 /*
172  * Node type constructor
173  */
174 static int
175 ng_mppc_constructor(node_p *nodep)
176 {
177 	priv_p priv;
178 	int error;
179 
180 	/* Allocate private structure */
181 	MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH, M_NOWAIT | M_ZERO);
182 	if (priv == NULL)
183 		return (ENOMEM);
184 
185 	/* Call generic node constructor */
186 	if ((error = ng_make_node_common(&ng_mppc_typestruct, nodep))) {
187 		FREE(priv, M_NETGRAPH);
188 		return (error);
189 	}
190 	(*nodep)->private = priv;
191 
192 	/* Done */
193 	return (0);
194 }
195 
196 /*
197  * Give our OK for a hook to be added
198  */
199 static int
200 ng_mppc_newhook(node_p node, hook_p hook, const char *name)
201 {
202 	const priv_p priv = node->private;
203 	hook_p *hookPtr;
204 
205 	/* Check hook name */
206 	if (strcmp(name, NG_MPPC_HOOK_COMP) == 0)
207 		hookPtr = &priv->xmit.hook;
208 	else if (strcmp(name, NG_MPPC_HOOK_DECOMP) == 0)
209 		hookPtr = &priv->recv.hook;
210 	else
211 		return (EINVAL);
212 
213 	/* See if already connected */
214 	if (*hookPtr != NULL)
215 		return (EISCONN);
216 
217 	/* OK */
218 	*hookPtr = hook;
219 	return (0);
220 }
221 
222 /*
223  * Receive a control message
224  */
225 static int
226 ng_mppc_rcvmsg(node_p node, struct ng_mesg *msg,
227 	      const char *raddr, struct ng_mesg **rptr, hook_p lasthook)
228 {
229 	const priv_p priv = node->private;
230 	struct ng_mesg *resp = NULL;
231 	int error = 0;
232 
233 	switch (msg->header.typecookie) {
234 	case NGM_MPPC_COOKIE:
235 		switch (msg->header.cmd) {
236 		case NGM_MPPC_CONFIG_COMP:
237 		case NGM_MPPC_CONFIG_DECOMP:
238 		    {
239 			struct ng_mppc_config *const cfg
240 			    = (struct ng_mppc_config *)msg->data;
241 			const int isComp =
242 			    msg->header.cmd == NGM_MPPC_CONFIG_COMP;
243 			struct ng_mppc_dir *const d = isComp ?
244 			    &priv->xmit : &priv->recv;
245 
246 			/* Check configuration */
247 			if (msg->header.arglen != sizeof(*cfg))
248 				ERROUT(EINVAL);
249 			if (cfg->enable) {
250 				if ((cfg->bits & ~MPPC_VALID_BITS) != 0)
251 					ERROUT(EINVAL);
252 #ifndef NETGRAPH_MPPC_COMPRESSION
253 				if ((cfg->bits & MPPC_BIT) != 0)
254 					ERROUT(EPROTONOSUPPORT);
255 #endif
256 #ifndef NETGRAPH_MPPC_ENCRYPTION
257 				if ((cfg->bits & MPPE_BITS) != 0)
258 					ERROUT(EPROTONOSUPPORT);
259 #endif
260 			} else
261 				cfg->bits = 0;
262 
263 			/* Save return address so we can send reset-req's */
264 			if (priv->ctrlpath != NULL) {
265 				FREE(priv->ctrlpath, M_NETGRAPH);
266 				priv->ctrlpath = NULL;
267 			}
268 			if (!isComp && raddr != NULL) {
269 				MALLOC(priv->ctrlpath, char *,
270 				    strlen(raddr) + 1, M_NETGRAPH, M_NOWAIT);
271 				if (priv->ctrlpath == NULL)
272 					ERROUT(ENOMEM);
273 				strcpy(priv->ctrlpath, raddr);
274 			}
275 
276 			/* Configuration is OK, reset to it */
277 			d->cfg = *cfg;
278 
279 #ifdef NETGRAPH_MPPC_COMPRESSION
280 			/* Initialize state buffers for compression */
281 			if (d->history != NULL) {
282 				FREE(d->history, M_NETGRAPH);
283 				d->history = NULL;
284 			}
285 			if ((cfg->bits & MPPC_BIT) != 0) {
286 				MALLOC(d->history, u_char *,
287 				    isComp ? MPPC_SizeOfCompressionHistory() :
288 				    MPPC_SizeOfDecompressionHistory(),
289 				    M_NETGRAPH, M_NOWAIT);
290 				if (d->history == NULL)
291 					ERROUT(ENOMEM);
292 				if (isComp)
293 					MPPC_InitCompressionHistory(d->history);
294 				else {
295 					MPPC_InitDecompressionHistory(
296 					    d->history);
297 				}
298 			}
299 #endif
300 
301 #ifdef NETGRAPH_MPPC_ENCRYPTION
302 			/* Generate initial session keys for encryption */
303 			if ((cfg->bits & MPPE_BITS) != 0) {
304 				const int keylen = KEYLEN(cfg->bits);
305 
306 				bcopy(cfg->startkey, d->key, keylen);
307 				ng_mppc_getkey(cfg->startkey, d->key, keylen);
308 				if ((cfg->bits & MPPE_128) == 0) {
309 					bcopy(&ng_mppe_weakenkey, d->key,
310 					    sizeof(ng_mppe_weakenkey));
311 				}
312 				rc4_init(&d->rc4, d->key, keylen);
313 			}
314 #endif
315 
316 			/* Initialize other state */
317 			d->cc = 0;
318 			d->flushed = 0;
319 			break;
320 		    }
321 
322 		case NGM_MPPC_RESETREQ:
323 			ng_mppc_reset_req(node);
324 			break;
325 
326 		default:
327 			error = EINVAL;
328 			break;
329 		}
330 		break;
331 	default:
332 		error = EINVAL;
333 		break;
334 	}
335 	if (rptr)
336 		*rptr = resp;
337 	else if (resp)
338 		FREE(resp, M_NETGRAPH);
339 
340 done:
341 	FREE(msg, M_NETGRAPH);
342 	return (error);
343 }
344 
345 /*
346  * Receive incoming data on our hook.
347  */
348 static int
349 ng_mppc_rcvdata(hook_p hook, struct mbuf *m, meta_p meta,
350 		struct mbuf **ret_m, meta_p *ret_meta)
351 {
352 	const node_p node = hook->node;
353 	const priv_p priv = node->private;
354 	struct mbuf *out;
355 	int error;
356 
357 	/* Compress and/or encrypt */
358 	if (hook == priv->xmit.hook) {
359 		if (!priv->xmit.cfg.enable) {
360 			NG_FREE_DATA(m, meta);
361 			return (ENXIO);
362 		}
363 		if ((error = ng_mppc_compress(node, m, &out)) != 0) {
364 			NG_FREE_DATA(m, meta);
365 			return(error);
366 		}
367 		m_freem(m);
368 		NG_SEND_DATA(error, priv->xmit.hook, out, meta);
369 		return (error);
370 	}
371 
372 	/* Decompress and/or decrypt */
373 	if (hook == priv->recv.hook) {
374 		if (!priv->recv.cfg.enable) {
375 			NG_FREE_DATA(m, meta);
376 			return (ENXIO);
377 		}
378 		if ((error = ng_mppc_decompress(node, m, &out)) != 0) {
379 			NG_FREE_DATA(m, meta);
380 			if (error == EINVAL && priv->ctrlpath != NULL) {
381 				struct ng_mesg *msg;
382 
383 				/* Need to send a reset-request */
384 				NG_MKMESSAGE(msg, NGM_MPPC_COOKIE,
385 				    NGM_MPPC_RESETREQ, 0, M_NOWAIT);
386 				if (msg == NULL)
387 					return (error);
388 				ng_send_msg(node, msg, priv->ctrlpath, NULL);
389 			}
390 			return (error);
391 		}
392 		m_freem(m);
393 		NG_SEND_DATA(error, priv->recv.hook, out, meta);
394 		return (error);
395 	}
396 
397 	/* Oops */
398 	panic("%s: unknown hook", __FUNCTION__);
399 }
400 
401 /*
402  * Destroy node
403  */
404 static int
405 ng_mppc_rmnode(node_p node)
406 {
407 	const priv_p priv = node->private;
408 
409 	/* Take down netgraph node */
410 	node->flags |= NG_INVALID;
411 	ng_cutlinks(node);
412 	ng_unname(node);
413 	if (priv->ctrlpath != NULL)
414 		FREE(priv->ctrlpath, M_NETGRAPH);
415 #ifdef NETGRAPH_MPPC_COMPRESSION
416 	if (priv->xmit.history != NULL)
417 		FREE(priv->xmit.history, M_NETGRAPH);
418 	if (priv->recv.history != NULL)
419 		FREE(priv->recv.history, M_NETGRAPH);
420 #endif
421 	bzero(priv, sizeof(*priv));
422 	FREE(priv, M_NETGRAPH);
423 	node->private = NULL;
424 	ng_unref(node);		/* let the node escape */
425 	return (0);
426 }
427 
428 /*
429  * Hook disconnection
430  */
431 static int
432 ng_mppc_disconnect(hook_p hook)
433 {
434 	const node_p node = hook->node;
435 	const priv_p priv = node->private;
436 
437 	/* Zero out hook pointer */
438 	if (hook == priv->xmit.hook)
439 		priv->xmit.hook = NULL;
440 	if (hook == priv->recv.hook)
441 		priv->recv.hook = NULL;
442 
443 	/* Go away if no longer connected */
444 	if (node->numhooks == 0)
445 		ng_rmnode(node);
446 	return (0);
447 }
448 
449 /************************************************************************
450 			HELPER STUFF
451  ************************************************************************/
452 
453 /*
454  * Compress/encrypt a packet and put the result in a new mbuf at *resultp.
455  * The original mbuf is not free'd.
456  */
457 static int
458 ng_mppc_compress(node_p node, struct mbuf *m, struct mbuf **resultp)
459 {
460 	const priv_p priv = node->private;
461 	struct ng_mppc_dir *const d = &priv->xmit;
462 	u_char *inbuf, *outbuf;
463 	int outlen, inlen;
464 	u_int16_t header;
465 
466 	/* Initialize */
467 	*resultp = NULL;
468 	header = d->cc;
469 	if (d->flushed) {
470 		header |= MPPC_FLAG_FLUSHED;
471 		d->flushed = 0;
472 	}
473 
474 	/* Work with contiguous regions of memory */
475 	inlen = m->m_pkthdr.len;
476 	MALLOC(inbuf, u_char *, inlen, M_NETGRAPH, M_NOWAIT);
477 	if (inbuf == NULL)
478 		return (ENOMEM);
479 	m_copydata(m, 0, inlen, (caddr_t)inbuf);
480 	if ((d->cfg.bits & MPPC_BIT) != 0)
481 		outlen = MPPC_MAX_BLOWUP(inlen);
482 	else
483 		outlen = MPPC_HDRLEN + inlen;
484 	MALLOC(outbuf, u_char *, outlen, M_NETGRAPH, M_NOWAIT);
485 	if (outbuf == NULL) {
486 		FREE(inbuf, M_NETGRAPH);
487 		return (ENOMEM);
488 	}
489 
490 	/* Compress "inbuf" into "outbuf" (if compression enabled) */
491 #ifdef NETGRAPH_MPPC_COMPRESSION
492 	if ((d->cfg.bits & MPPC_BIT) != 0) {
493 		u_short flags = MPPC_MANDATORY_COMPRESS_FLAGS;
494 		u_char *source, *dest;
495 		u_long sourceCnt, destCnt;
496 		int rtn;
497 
498 		/* Prepare to compress */
499 		source = inbuf;
500 		sourceCnt = inlen;
501 		dest = outbuf + MPPC_HDRLEN;
502 		destCnt = outlen - MPPC_HDRLEN;
503 		if ((d->cfg.bits & MPPE_STATELESS) == 0)
504 			flags |= MPPC_SAVE_HISTORY;
505 
506 		/* Compress */
507 		rtn = MPPC_Compress(&source, &dest, &sourceCnt,
508 			&destCnt, d->history, flags, 0);
509 
510 		/* Check return value */
511 		KASSERT(rtn != MPPC_INVALID, ("%s: invalid", __FUNCTION__));
512 		if ((rtn & MPPC_EXPANDED) == 0
513 		    && (rtn & MPPC_COMP_OK) == MPPC_COMP_OK) {
514 			outlen -= destCnt;
515 			header |= MPPC_FLAG_COMPRESSED;
516 			if ((rtn & MPPC_RESTART_HISTORY) != 0)
517 				header |= MPPC_FLAG_RESTART;
518 		}
519 		d->flushed = (rtn & MPPC_EXPANDED) != 0
520 		    || (flags & MPPC_SAVE_HISTORY) == 0;
521 	}
522 #endif
523 
524 	/* If we did not compress this packet, copy it to output buffer */
525 	if ((header & MPPC_FLAG_COMPRESSED) == 0) {
526 		bcopy(inbuf, outbuf + MPPC_HDRLEN, inlen);
527 		outlen = MPPC_HDRLEN + inlen;
528 	}
529 	FREE(inbuf, M_NETGRAPH);
530 
531 	/* Always set the flushed bit in stateless mode */
532 	if ((d->cfg.bits & MPPE_STATELESS) != 0)
533 		header |= MPPC_FLAG_FLUSHED;
534 
535 	/* Now encrypt packet (if encryption enabled) */
536 #ifdef NETGRAPH_MPPC_ENCRYPTION
537 	if ((d->cfg.bits & MPPE_BITS) != 0) {
538 
539 		/* Set header bits; need to reset key if we say we did */
540 		header |= MPPC_FLAG_ENCRYPTED;
541 		if ((header & MPPC_FLAG_FLUSHED) != 0)
542 			rc4_init(&d->rc4, d->key, KEYLEN(d->cfg.bits));
543 
544 		/* Update key if it's time */
545 		if ((d->cfg.bits & MPPE_STATELESS) != 0
546 		    || (d->cc & MPPE_UPDATE_MASK) == MPPE_UPDATE_FLAG) {
547 			  ng_mppc_updatekey(d->cfg.bits,
548 			      d->cfg.startkey, d->key, &d->rc4);
549 		}
550 
551 		/* Encrypt packet */
552 		rc4_crypt(&d->rc4, outbuf + MPPC_HDRLEN,
553 			outbuf + MPPC_HDRLEN, outlen - MPPC_HDRLEN);
554 	}
555 #endif
556 
557 	/* Update sequence number */
558 	d->cc++;
559 
560 	/* Install header */
561 	*((u_int16_t *)outbuf) = htons(header);
562 
563 	/* Return packet in an mbuf */
564 	*resultp = m_devget((caddr_t)outbuf, outlen, 0, NULL, NULL);
565 	FREE(outbuf, M_NETGRAPH);
566 	return (*resultp == NULL ? ENOBUFS : 0);
567 }
568 
569 /*
570  * Decompress/decrypt packet and put the result in a new mbuf at *resultp.
571  * The original mbuf is not free'd.
572  */
573 static int
574 ng_mppc_decompress(node_p node, struct mbuf *m, struct mbuf **resultp)
575 {
576 	const priv_p priv = node->private;
577 	struct ng_mppc_dir *const d = &priv->recv;
578 	u_int16_t header, cc, numLost;
579 	u_char *buf;
580 	int len;
581 
582 	/* Pull off header */
583 	if (m->m_pkthdr.len < MPPC_HDRLEN)
584 		return (EINVAL);
585 	m_copydata(m, 0, MPPC_HDRLEN, (caddr_t)&header);
586 	NTOHS(header);
587 	cc = (header & MPPC_CCOUNT_MASK);
588 
589 	/* Copy payload into a contiguous region of memory */
590 	len = m->m_pkthdr.len - MPPC_HDRLEN;
591 	MALLOC(buf, u_char *, len, M_NETGRAPH, M_NOWAIT);
592 	if (buf == NULL)
593 		return (ENOMEM);
594 	m_copydata(m, MPPC_HDRLEN, len, (caddr_t)buf);
595 
596 	/* Check for insane jumps in sequence numbering (D.O.S. attack) */
597 	numLost = ((cc - d->cc) & MPPC_CCOUNT_MASK);
598 	if (numLost >= MPPC_INSANE_JUMP) {
599 		log(LOG_ERR, "%s: insane jump %d", __FUNCTION__, numLost);
600 		priv->recv.cfg.enable = 0;
601 		goto failed;
602 	}
603 
604 	/* If flushed bit set, we can always handle packet */
605 	if ((header & MPPC_FLAG_FLUSHED) != 0) {
606 #ifdef NETGRAPH_MPPC_COMPRESSION
607 		if (d->history != NULL)
608 			MPPC_InitDecompressionHistory(d->history);
609 #endif
610 #ifdef NETGRAPH_MPPC_ENCRYPTION
611 		if ((d->cfg.bits & MPPE_BITS) != 0) {
612 
613 			/* Resync as necessary, skipping lost packets */
614 			while (d->cc != cc) {
615 				if ((d->cfg.bits & MPPE_STATELESS)
616 				    || (d->cc & MPPE_UPDATE_MASK)
617 				      == MPPE_UPDATE_FLAG) {
618 					ng_mppc_updatekey(d->cfg.bits,
619 					    d->cfg.startkey, d->key, &d->rc4);
620 				}
621 				d->cc++;
622 			}
623 
624 			/* Reset key (except in stateless mode, see below) */
625 			if ((d->cfg.bits & MPPE_STATELESS) == 0)
626 				rc4_init(&d->rc4, d->key, KEYLEN(d->cfg.bits));
627 		}
628 #endif
629 		d->cc = cc;		/* skip over lost seq numbers */
630 		numLost = 0;		/* act like no packets were lost */
631 	}
632 
633 	/* Can't decode non-sequential packets without a flushed bit */
634 	if (numLost != 0)
635 		goto failed;
636 
637 	/* Decrypt packet */
638 	if ((header & MPPC_FLAG_ENCRYPTED) != 0) {
639 
640 		/* Are we not expecting encryption? */
641 		if ((d->cfg.bits & MPPE_BITS) == 0) {
642 			log(LOG_ERR, "%s: rec'd unexpectedly %s packet",
643 				__FUNCTION__, "encrypted");
644 			goto failed;
645 		}
646 
647 #ifdef NETGRAPH_MPPC_ENCRYPTION
648 		/* Update key if it's time (always in stateless mode) */
649 		if ((d->cfg.bits & MPPE_STATELESS) != 0
650 		    || (d->cc & MPPE_UPDATE_MASK) == MPPE_UPDATE_FLAG) {
651 			ng_mppc_updatekey(d->cfg.bits,
652 			    d->cfg.startkey, d->key, &d->rc4);
653 		}
654 
655 		/* Decrypt packet */
656 		rc4_crypt(&d->rc4, buf, buf, len);
657 #endif
658 	} else {
659 
660 		/* Are we expecting encryption? */
661 		if ((d->cfg.bits & MPPE_BITS) != 0) {
662 			log(LOG_ERR, "%s: rec'd unexpectedly %s packet",
663 				__FUNCTION__, "unencrypted");
664 			goto failed;
665 		}
666 	}
667 
668 	/* Update coherency count for next time (12 bit arithmetic) */
669 	d->cc++;
670 
671 	/* Check for unexpected compressed packet */
672 	if ((header & MPPC_FLAG_COMPRESSED) != 0
673 	    && (d->cfg.bits & MPPC_BIT) == 0) {
674 		log(LOG_ERR, "%s: rec'd unexpectedly %s packet",
675 			__FUNCTION__, "compressed");
676 failed:
677 		FREE(buf, M_NETGRAPH);
678 		return (EINVAL);
679 	}
680 
681 #ifdef NETGRAPH_MPPC_COMPRESSION
682 	/* Decompress packet */
683 	if ((header & MPPC_FLAG_COMPRESSED) != 0) {
684 		int flags = MPPC_MANDATORY_DECOMPRESS_FLAGS;
685 		u_char *decompbuf, *source, *dest;
686 		u_long sourceCnt, destCnt;
687 		int decomplen, rtn;
688 
689 		/* Allocate a buffer for decompressed data */
690 		MALLOC(decompbuf, u_char *, MPPC_DECOMP_BUFSIZE
691 		    + MPPC_DECOMP_SAFETY, M_NETGRAPH, M_NOWAIT);
692 		if (decompbuf == NULL) {
693 			FREE(buf, M_NETGRAPH);
694 			return (ENOMEM);
695 		}
696 		decomplen = MPPC_DECOMP_BUFSIZE;
697 
698 		/* Prepare to decompress */
699 		source = buf;
700 		sourceCnt = len;
701 		dest = decompbuf;
702 		destCnt = decomplen;
703 		if ((header & MPPC_FLAG_RESTART) != 0)
704 			flags |= MPPC_RESTART_HISTORY;
705 
706 		/* Decompress */
707 		rtn = MPPC_Decompress(&source, &dest,
708 			&sourceCnt, &destCnt, d->history, flags);
709 
710 		/* Check return value */
711 		KASSERT(rtn != MPPC_INVALID, ("%s: invalid", __FUNCTION__));
712 		if ((rtn & MPPC_DEST_EXHAUSTED) != 0
713 		    || (rtn & MPPC_DECOMP_OK) != MPPC_DECOMP_OK) {
714 			log(LOG_ERR, "%s: decomp returned 0x%x",
715 			    __FUNCTION__, rtn);
716 			FREE(decompbuf, M_NETGRAPH);
717 			goto failed;
718 		}
719 
720 		/* Replace compressed data with decompressed data */
721 		FREE(buf, M_NETGRAPH);
722 		buf = decompbuf;
723 		len = decomplen - destCnt;
724 	}
725 #endif
726 
727 	/* Return result in an mbuf */
728 	*resultp = m_devget((caddr_t)buf, len, 0, NULL, NULL);
729 	FREE(buf, M_NETGRAPH);
730 	return (*resultp == NULL ? ENOBUFS : 0);
731 }
732 
733 /*
734  * The peer has sent us a CCP ResetRequest, so reset our transmit state.
735  */
736 static void
737 ng_mppc_reset_req(node_p node)
738 {
739 	const priv_p priv = node->private;
740 	struct ng_mppc_dir *const d = &priv->xmit;
741 
742 #ifdef NETGRAPH_MPPC_COMPRESSION
743 	if (d->history != NULL)
744 		MPPC_InitCompressionHistory(d->history);
745 #endif
746 #ifdef NETGRAPH_MPPC_ENCRYPTION
747 	if ((d->cfg.bits & MPPE_STATELESS) == 0)
748 		rc4_init(&d->rc4, d->key, KEYLEN(d->cfg.bits));
749 #endif
750 	d->flushed = 1;
751 }
752 
753 /*
754  * Generate a new encryption key
755  */
756 static void
757 ng_mppc_getkey(const u_char *h, u_char *h2, int len)
758 {
759 	static const u_char pad1[10] =
760 	    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
761 	static const u_char pad2[10] =
762 	    { 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, };
763 	u_char hash[20];
764 	SHA1_CTX c;
765 	int k;
766 
767 	bzero(&hash, sizeof(hash));
768 	SHA1Init(&c);
769 	SHA1Update(&c, h, len);
770 	for (k = 0; k < 4; k++)
771 		SHA1Update(&c, pad1, sizeof(pad2));
772 	SHA1Update(&c, h2, len);
773 	for (k = 0; k < 4; k++)
774 		SHA1Update(&c, pad2, sizeof(pad2));
775 	SHA1Final(hash, &c);
776 	bcopy(hash, h2, len);
777 }
778 
779 /*
780  * Update the encryption key
781  */
782 static void
783 ng_mppc_updatekey(u_int32_t bits,
784 	u_char *key0, u_char *key, struct rc4_state *rc4)
785 {
786 	const int keylen = KEYLEN(bits);
787 
788 	ng_mppc_getkey(key0, key, keylen);
789 	rc4_init(rc4, key, keylen);
790 	rc4_crypt(rc4, key, key, keylen);
791 	if ((bits & MPPE_128) == 0)
792 		bcopy(&ng_mppe_weakenkey, key, sizeof(ng_mppe_weakenkey));
793 	rc4_init(rc4, key, keylen);
794 }
795 
796