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