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