ng_mppc.c revision 70700
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: head/sys/netgraph/ng_mppc.c 70700 2001-01-06 00:46:47Z julian $
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 */
104struct 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 */
119struct ng_mppc_private {
120	struct ng_mppc_dir	xmit;		/* compress/encrypt config */
121	struct ng_mppc_dir	recv;		/* decompress/decrypt config */
122	ng_ID_t			ctrlnode;	/* path to controlling node */
123};
124typedef struct ng_mppc_private *priv_p;
125
126/* Netgraph node methods */
127static ng_constructor_t	ng_mppc_constructor;
128static ng_rcvmsg_t	ng_mppc_rcvmsg;
129static ng_shutdown_t	ng_mppc_shutdown;
130static ng_newhook_t	ng_mppc_newhook;
131static ng_rcvdata_t	ng_mppc_rcvdata;
132static ng_disconnect_t	ng_mppc_disconnect;
133
134/* Helper functions */
135static int	ng_mppc_compress(node_p node,
136			struct mbuf *m, struct mbuf **resultp);
137static int	ng_mppc_decompress(node_p node,
138			struct mbuf *m, struct mbuf **resultp);
139static void	ng_mppc_getkey(const u_char *h, u_char *h2, int len);
140static void	ng_mppc_updatekey(u_int32_t bits,
141			u_char *key0, u_char *key, struct rc4_state *rc4);
142static void	ng_mppc_reset_req(node_p node);
143
144/* Node type descriptor */
145static struct ng_type ng_mppc_typestruct = {
146	NG_ABI_VERSION,
147	NG_MPPC_NODE_TYPE,
148	NULL,
149	ng_mppc_constructor,
150	ng_mppc_rcvmsg,
151	ng_mppc_shutdown,
152	ng_mppc_newhook,
153	NULL,
154	NULL,
155	ng_mppc_rcvdata,
156	ng_mppc_disconnect,
157	NULL
158};
159NETGRAPH_INIT(mppc, &ng_mppc_typestruct);
160
161/* Fixed bit pattern to weaken keysize down to 40 bits */
162static const u_char ng_mppe_weakenkey[3] = { 0xd1, 0x26, 0x9e };
163
164#define ERROUT(x)	do { error = (x); goto done; } while (0)
165
166/************************************************************************
167			NETGRAPH NODE STUFF
168 ************************************************************************/
169
170/*
171 * Node type constructor
172 */
173static int
174ng_mppc_constructor(node_p node)
175{
176	priv_p priv;
177
178	/* Allocate private structure */
179	MALLOC(priv, priv_p, sizeof(*priv), M_NETGRAPH, M_NOWAIT | M_ZERO);
180	if (priv == NULL)
181		return (ENOMEM);
182
183	node->private = priv;
184
185	/* Done */
186	return (0);
187}
188
189/*
190 * Give our OK for a hook to be added
191 */
192static int
193ng_mppc_newhook(node_p node, hook_p hook, const char *name)
194{
195	const priv_p priv = node->private;
196	hook_p *hookPtr;
197
198	/* Check hook name */
199	if (strcmp(name, NG_MPPC_HOOK_COMP) == 0)
200		hookPtr = &priv->xmit.hook;
201	else if (strcmp(name, NG_MPPC_HOOK_DECOMP) == 0)
202		hookPtr = &priv->recv.hook;
203	else
204		return (EINVAL);
205
206	/* See if already connected */
207	if (*hookPtr != NULL)
208		return (EISCONN);
209
210	/* OK */
211	*hookPtr = hook;
212	return (0);
213}
214
215/*
216 * Receive a control message
217 */
218static int
219ng_mppc_rcvmsg(node_p node, item_p item, hook_p lasthook)
220{
221	const priv_p priv = node->private;
222	struct ng_mesg *resp = NULL;
223	int error = 0;
224	struct ng_mesg *msg;
225
226	NGI_GET_MSG(item, msg);
227	switch (msg->header.typecookie) {
228	case NGM_MPPC_COOKIE:
229		switch (msg->header.cmd) {
230		case NGM_MPPC_CONFIG_COMP:
231		case NGM_MPPC_CONFIG_DECOMP:
232		    {
233			struct ng_mppc_config *const cfg
234			    = (struct ng_mppc_config *)msg->data;
235			const int isComp =
236			    msg->header.cmd == NGM_MPPC_CONFIG_COMP;
237			struct ng_mppc_dir *const d = isComp ?
238			    &priv->xmit : &priv->recv;
239
240			/* Check configuration */
241			if (msg->header.arglen != sizeof(*cfg))
242				ERROUT(EINVAL);
243			if (cfg->enable) {
244				if ((cfg->bits & ~MPPC_VALID_BITS) != 0)
245					ERROUT(EINVAL);
246#ifndef NETGRAPH_MPPC_COMPRESSION
247				if ((cfg->bits & MPPC_BIT) != 0)
248					ERROUT(EPROTONOSUPPORT);
249#endif
250#ifndef NETGRAPH_MPPC_ENCRYPTION
251				if ((cfg->bits & MPPE_BITS) != 0)
252					ERROUT(EPROTONOSUPPORT);
253#endif
254			} else
255				cfg->bits = 0;
256
257			/* Save return address so we can send reset-req's */
258			priv->ctrlnode = NGI_RETADDR(item);
259
260			/* Configuration is OK, reset to it */
261			d->cfg = *cfg;
262
263#ifdef NETGRAPH_MPPC_COMPRESSION
264			/* Initialize state buffers for compression */
265			if (d->history != NULL) {
266				FREE(d->history, M_NETGRAPH);
267				d->history = NULL;
268			}
269			if ((cfg->bits & MPPC_BIT) != 0) {
270				MALLOC(d->history, u_char *,
271				    isComp ? MPPC_SizeOfCompressionHistory() :
272				    MPPC_SizeOfDecompressionHistory(),
273				    M_NETGRAPH, M_NOWAIT);
274				if (d->history == NULL)
275					ERROUT(ENOMEM);
276				if (isComp)
277					MPPC_InitCompressionHistory(d->history);
278				else {
279					MPPC_InitDecompressionHistory(
280					    d->history);
281				}
282			}
283#endif
284
285#ifdef NETGRAPH_MPPC_ENCRYPTION
286			/* Generate initial session keys for encryption */
287			if ((cfg->bits & MPPE_BITS) != 0) {
288				const int keylen = KEYLEN(cfg->bits);
289
290				bcopy(cfg->startkey, d->key, keylen);
291				ng_mppc_getkey(cfg->startkey, d->key, keylen);
292				if ((cfg->bits & MPPE_128) == 0) {
293					bcopy(&ng_mppe_weakenkey, d->key,
294					    sizeof(ng_mppe_weakenkey));
295				}
296				rc4_init(&d->rc4, d->key, keylen);
297			}
298#endif
299
300			/* Initialize other state */
301			d->cc = 0;
302			d->flushed = 0;
303			break;
304		    }
305
306		case NGM_MPPC_RESETREQ:
307			ng_mppc_reset_req(node);
308			break;
309
310		default:
311			error = EINVAL;
312			break;
313		}
314		break;
315	default:
316		error = EINVAL;
317		break;
318	}
319done:
320	NG_RESPOND_MSG(error, node, item, resp);
321	NG_FREE_MSG(msg);
322	return (error);
323}
324
325/*
326 * Receive incoming data on our hook.
327 */
328static int
329ng_mppc_rcvdata(hook_p hook, item_p item)
330{
331	const node_p node = hook->node;
332	const priv_p priv = node->private;
333	struct mbuf *out;
334	int error;
335	struct mbuf *m;
336
337	NGI_GET_M(item, m);
338	/* Compress and/or encrypt */
339	if (hook == priv->xmit.hook) {
340		if (!priv->xmit.cfg.enable) {
341			NG_FREE_M(m);
342			NG_FREE_ITEM(item);
343			return (ENXIO);
344		}
345		if ((error = ng_mppc_compress(node, m, &out)) != 0) {
346			NG_FREE_M(m);
347			NG_FREE_ITEM(item);
348			return(error);
349		}
350		NG_FREE_M(m);
351		NG_FWD_NEW_DATA(error, item, priv->xmit.hook, out);
352		return (error);
353	}
354
355	/* Decompress and/or decrypt */
356	if (hook == priv->recv.hook) {
357		if (!priv->recv.cfg.enable) {
358			NG_FREE_M(m);
359			NG_FREE_ITEM(item);
360			return (ENXIO);
361		}
362		if ((error = ng_mppc_decompress(node, m, &out)) != 0) {
363			NG_FREE_M(m);
364			NG_FREE_ITEM(item);
365			if (error == EINVAL && priv->ctrlnode != NULL) {
366				struct ng_mesg *msg;
367
368				/* Need to send a reset-request */
369				NG_MKMESSAGE(msg, NGM_MPPC_COOKIE,
370				    NGM_MPPC_RESETREQ, 0, M_NOWAIT);
371				if (msg == NULL)
372					return (error);
373				NG_SEND_MSG_ID(error, node, msg,
374					priv->ctrlnode, NULL);
375			}
376			return (error);
377		}
378		NG_FREE_M(m);
379		NG_FWD_NEW_DATA(error, item, priv->recv.hook, out);
380		return (error);
381	}
382
383	/* Oops */
384	panic("%s: unknown hook", __FUNCTION__);
385}
386
387/*
388 * Destroy node
389 */
390static int
391ng_mppc_shutdown(node_p node)
392{
393	const priv_p priv = node->private;
394
395	/* Take down netgraph node */
396	node->flags |= NG_INVALID;
397#ifdef NETGRAPH_MPPC_COMPRESSION
398	if (priv->xmit.history != NULL)
399		FREE(priv->xmit.history, M_NETGRAPH);
400	if (priv->recv.history != NULL)
401		FREE(priv->recv.history, M_NETGRAPH);
402#endif
403	bzero(priv, sizeof(*priv));
404	FREE(priv, M_NETGRAPH);
405	node->private = NULL;
406	ng_unref(node);		/* let the node escape */
407	return (0);
408}
409
410/*
411 * Hook disconnection
412 */
413static int
414ng_mppc_disconnect(hook_p hook)
415{
416	const node_p node = hook->node;
417	const priv_p priv = node->private;
418
419	/* Zero out hook pointer */
420	if (hook == priv->xmit.hook)
421		priv->xmit.hook = NULL;
422	if (hook == priv->recv.hook)
423		priv->recv.hook = NULL;
424
425	/* Go away if no longer connected */
426	if ((node->numhooks == 0)
427	&& ((node->flags & NG_INVALID) == 0))
428		ng_rmnode_self(node);
429	return (0);
430}
431
432/************************************************************************
433			HELPER STUFF
434 ************************************************************************/
435
436/*
437 * Compress/encrypt a packet and put the result in a new mbuf at *resultp.
438 * The original mbuf is not free'd.
439 */
440static int
441ng_mppc_compress(node_p node, struct mbuf *m, struct mbuf **resultp)
442{
443	const priv_p priv = node->private;
444	struct ng_mppc_dir *const d = &priv->xmit;
445	u_char *inbuf, *outbuf;
446	int outlen, inlen;
447	u_int16_t header;
448
449	/* Initialize */
450	*resultp = NULL;
451	header = d->cc;
452	if (d->flushed) {
453		header |= MPPC_FLAG_FLUSHED;
454		d->flushed = 0;
455	}
456
457	/* Work with contiguous regions of memory */
458	inlen = m->m_pkthdr.len;
459	MALLOC(inbuf, u_char *, inlen, M_NETGRAPH, M_NOWAIT);
460	if (inbuf == NULL)
461		return (ENOMEM);
462	m_copydata(m, 0, inlen, (caddr_t)inbuf);
463	if ((d->cfg.bits & MPPC_BIT) != 0)
464		outlen = MPPC_MAX_BLOWUP(inlen);
465	else
466		outlen = MPPC_HDRLEN + inlen;
467	MALLOC(outbuf, u_char *, outlen, M_NETGRAPH, M_NOWAIT);
468	if (outbuf == NULL) {
469		FREE(inbuf, M_NETGRAPH);
470		return (ENOMEM);
471	}
472
473	/* Compress "inbuf" into "outbuf" (if compression enabled) */
474#ifdef NETGRAPH_MPPC_COMPRESSION
475	if ((d->cfg.bits & MPPC_BIT) != 0) {
476		u_short flags = MPPC_MANDATORY_COMPRESS_FLAGS;
477		u_char *source, *dest;
478		u_long sourceCnt, destCnt;
479		int rtn;
480
481		/* Prepare to compress */
482		source = inbuf;
483		sourceCnt = inlen;
484		dest = outbuf + MPPC_HDRLEN;
485		destCnt = outlen - MPPC_HDRLEN;
486		if ((d->cfg.bits & MPPE_STATELESS) == 0)
487			flags |= MPPC_SAVE_HISTORY;
488
489		/* Compress */
490		rtn = MPPC_Compress(&source, &dest, &sourceCnt,
491			&destCnt, d->history, flags, 0);
492
493		/* Check return value */
494		KASSERT(rtn != MPPC_INVALID, ("%s: invalid", __FUNCTION__));
495		if ((rtn & MPPC_EXPANDED) == 0
496		    && (rtn & MPPC_COMP_OK) == MPPC_COMP_OK) {
497			outlen -= destCnt;
498			header |= MPPC_FLAG_COMPRESSED;
499			if ((rtn & MPPC_RESTART_HISTORY) != 0)
500				header |= MPPC_FLAG_RESTART;
501		}
502		d->flushed = (rtn & MPPC_EXPANDED) != 0
503		    || (flags & MPPC_SAVE_HISTORY) == 0;
504	}
505#endif
506
507	/* If we did not compress this packet, copy it to output buffer */
508	if ((header & MPPC_FLAG_COMPRESSED) == 0) {
509		bcopy(inbuf, outbuf + MPPC_HDRLEN, inlen);
510		outlen = MPPC_HDRLEN + inlen;
511	}
512	FREE(inbuf, M_NETGRAPH);
513
514	/* Always set the flushed bit in stateless mode */
515	if ((d->cfg.bits & MPPE_STATELESS) != 0)
516		header |= MPPC_FLAG_FLUSHED;
517
518	/* Now encrypt packet (if encryption enabled) */
519#ifdef NETGRAPH_MPPC_ENCRYPTION
520	if ((d->cfg.bits & MPPE_BITS) != 0) {
521
522		/* Set header bits; need to reset key if we say we did */
523		header |= MPPC_FLAG_ENCRYPTED;
524		if ((header & MPPC_FLAG_FLUSHED) != 0)
525			rc4_init(&d->rc4, d->key, KEYLEN(d->cfg.bits));
526
527		/* Update key if it's time */
528		if ((d->cfg.bits & MPPE_STATELESS) != 0
529		    || (d->cc & MPPE_UPDATE_MASK) == MPPE_UPDATE_FLAG) {
530			  ng_mppc_updatekey(d->cfg.bits,
531			      d->cfg.startkey, d->key, &d->rc4);
532		}
533
534		/* Encrypt packet */
535		rc4_crypt(&d->rc4, outbuf + MPPC_HDRLEN,
536			outbuf + MPPC_HDRLEN, outlen - MPPC_HDRLEN);
537	}
538#endif
539
540	/* Update sequence number */
541	d->cc++;
542
543	/* Install header */
544	*((u_int16_t *)outbuf) = htons(header);
545
546	/* Return packet in an mbuf */
547	*resultp = m_devget((caddr_t)outbuf, outlen, 0, NULL, NULL);
548	FREE(outbuf, M_NETGRAPH);
549	return (*resultp == NULL ? ENOBUFS : 0);
550}
551
552/*
553 * Decompress/decrypt packet and put the result in a new mbuf at *resultp.
554 * The original mbuf is not free'd.
555 */
556static int
557ng_mppc_decompress(node_p node, struct mbuf *m, struct mbuf **resultp)
558{
559	const priv_p priv = node->private;
560	struct ng_mppc_dir *const d = &priv->recv;
561	u_int16_t header, cc, numLost;
562	u_char *buf;
563	int len;
564
565	/* Pull off header */
566	if (m->m_pkthdr.len < MPPC_HDRLEN)
567		return (EINVAL);
568	m_copydata(m, 0, MPPC_HDRLEN, (caddr_t)&header);
569	NTOHS(header);
570	cc = (header & MPPC_CCOUNT_MASK);
571
572	/* Copy payload into a contiguous region of memory */
573	len = m->m_pkthdr.len - MPPC_HDRLEN;
574	MALLOC(buf, u_char *, len, M_NETGRAPH, M_NOWAIT);
575	if (buf == NULL)
576		return (ENOMEM);
577	m_copydata(m, MPPC_HDRLEN, len, (caddr_t)buf);
578
579	/* Check for insane jumps in sequence numbering (D.O.S. attack) */
580	numLost = ((cc - d->cc) & MPPC_CCOUNT_MASK);
581	if (numLost >= MPPC_INSANE_JUMP) {
582		log(LOG_ERR, "%s: insane jump %d", __FUNCTION__, numLost);
583		priv->recv.cfg.enable = 0;
584		goto failed;
585	}
586
587	/* If flushed bit set, we can always handle packet */
588	if ((header & MPPC_FLAG_FLUSHED) != 0) {
589#ifdef NETGRAPH_MPPC_COMPRESSION
590		if (d->history != NULL)
591			MPPC_InitDecompressionHistory(d->history);
592#endif
593#ifdef NETGRAPH_MPPC_ENCRYPTION
594		if ((d->cfg.bits & MPPE_BITS) != 0) {
595
596			/* Resync as necessary, skipping lost packets */
597			while (d->cc != cc) {
598				if ((d->cfg.bits & MPPE_STATELESS)
599				    || (d->cc & MPPE_UPDATE_MASK)
600				      == MPPE_UPDATE_FLAG) {
601					ng_mppc_updatekey(d->cfg.bits,
602					    d->cfg.startkey, d->key, &d->rc4);
603				}
604				d->cc++;
605			}
606
607			/* Reset key (except in stateless mode, see below) */
608			if ((d->cfg.bits & MPPE_STATELESS) == 0)
609				rc4_init(&d->rc4, d->key, KEYLEN(d->cfg.bits));
610		}
611#endif
612		d->cc = cc;		/* skip over lost seq numbers */
613		numLost = 0;		/* act like no packets were lost */
614	}
615
616	/* Can't decode non-sequential packets without a flushed bit */
617	if (numLost != 0)
618		goto failed;
619
620	/* Decrypt packet */
621	if ((header & MPPC_FLAG_ENCRYPTED) != 0) {
622
623		/* Are we not expecting encryption? */
624		if ((d->cfg.bits & MPPE_BITS) == 0) {
625			log(LOG_ERR, "%s: rec'd unexpectedly %s packet",
626				__FUNCTION__, "encrypted");
627			goto failed;
628		}
629
630#ifdef NETGRAPH_MPPC_ENCRYPTION
631		/* Update key if it's time (always in stateless mode) */
632		if ((d->cfg.bits & MPPE_STATELESS) != 0
633		    || (d->cc & MPPE_UPDATE_MASK) == MPPE_UPDATE_FLAG) {
634			ng_mppc_updatekey(d->cfg.bits,
635			    d->cfg.startkey, d->key, &d->rc4);
636		}
637
638		/* Decrypt packet */
639		rc4_crypt(&d->rc4, buf, buf, len);
640#endif
641	} else {
642
643		/* Are we expecting encryption? */
644		if ((d->cfg.bits & MPPE_BITS) != 0) {
645			log(LOG_ERR, "%s: rec'd unexpectedly %s packet",
646				__FUNCTION__, "unencrypted");
647			goto failed;
648		}
649	}
650
651	/* Update coherency count for next time (12 bit arithmetic) */
652	d->cc++;
653
654	/* Check for unexpected compressed packet */
655	if ((header & MPPC_FLAG_COMPRESSED) != 0
656	    && (d->cfg.bits & MPPC_BIT) == 0) {
657		log(LOG_ERR, "%s: rec'd unexpectedly %s packet",
658			__FUNCTION__, "compressed");
659failed:
660		FREE(buf, M_NETGRAPH);
661		return (EINVAL);
662	}
663
664#ifdef NETGRAPH_MPPC_COMPRESSION
665	/* Decompress packet */
666	if ((header & MPPC_FLAG_COMPRESSED) != 0) {
667		int flags = MPPC_MANDATORY_DECOMPRESS_FLAGS;
668		u_char *decompbuf, *source, *dest;
669		u_long sourceCnt, destCnt;
670		int decomplen, rtn;
671
672		/* Allocate a buffer for decompressed data */
673		MALLOC(decompbuf, u_char *, MPPC_DECOMP_BUFSIZE
674		    + MPPC_DECOMP_SAFETY, M_NETGRAPH, M_NOWAIT);
675		if (decompbuf == NULL) {
676			FREE(buf, M_NETGRAPH);
677			return (ENOMEM);
678		}
679		decomplen = MPPC_DECOMP_BUFSIZE;
680
681		/* Prepare to decompress */
682		source = buf;
683		sourceCnt = len;
684		dest = decompbuf;
685		destCnt = decomplen;
686		if ((header & MPPC_FLAG_RESTART) != 0)
687			flags |= MPPC_RESTART_HISTORY;
688
689		/* Decompress */
690		rtn = MPPC_Decompress(&source, &dest,
691			&sourceCnt, &destCnt, d->history, flags);
692
693		/* Check return value */
694		KASSERT(rtn != MPPC_INVALID, ("%s: invalid", __FUNCTION__));
695		if ((rtn & MPPC_DEST_EXHAUSTED) != 0
696		    || (rtn & MPPC_DECOMP_OK) != MPPC_DECOMP_OK) {
697			log(LOG_ERR, "%s: decomp returned 0x%x",
698			    __FUNCTION__, rtn);
699			FREE(decompbuf, M_NETGRAPH);
700			goto failed;
701		}
702
703		/* Replace compressed data with decompressed data */
704		FREE(buf, M_NETGRAPH);
705		buf = decompbuf;
706		len = decomplen - destCnt;
707	}
708#endif
709
710	/* Return result in an mbuf */
711	*resultp = m_devget((caddr_t)buf, len, 0, NULL, NULL);
712	FREE(buf, M_NETGRAPH);
713	return (*resultp == NULL ? ENOBUFS : 0);
714}
715
716/*
717 * The peer has sent us a CCP ResetRequest, so reset our transmit state.
718 */
719static void
720ng_mppc_reset_req(node_p node)
721{
722	const priv_p priv = node->private;
723	struct ng_mppc_dir *const d = &priv->xmit;
724
725#ifdef NETGRAPH_MPPC_COMPRESSION
726	if (d->history != NULL)
727		MPPC_InitCompressionHistory(d->history);
728#endif
729#ifdef NETGRAPH_MPPC_ENCRYPTION
730	if ((d->cfg.bits & MPPE_STATELESS) == 0)
731		rc4_init(&d->rc4, d->key, KEYLEN(d->cfg.bits));
732#endif
733	d->flushed = 1;
734}
735
736/*
737 * Generate a new encryption key
738 */
739static void
740ng_mppc_getkey(const u_char *h, u_char *h2, int len)
741{
742	static const u_char pad1[10] =
743	    { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
744	static const u_char pad2[10] =
745	    { 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, 0xF2, };
746	u_char hash[20];
747	SHA1_CTX c;
748	int k;
749
750	bzero(&hash, sizeof(hash));
751	SHA1Init(&c);
752	SHA1Update(&c, h, len);
753	for (k = 0; k < 4; k++)
754		SHA1Update(&c, pad1, sizeof(pad2));
755	SHA1Update(&c, h2, len);
756	for (k = 0; k < 4; k++)
757		SHA1Update(&c, pad2, sizeof(pad2));
758	SHA1Final(hash, &c);
759	bcopy(hash, h2, len);
760}
761
762/*
763 * Update the encryption key
764 */
765static void
766ng_mppc_updatekey(u_int32_t bits,
767	u_char *key0, u_char *key, struct rc4_state *rc4)
768{
769	const int keylen = KEYLEN(bits);
770
771	ng_mppc_getkey(key0, key, keylen);
772	rc4_init(rc4, key, keylen);
773	rc4_crypt(rc4, key, key, keylen);
774	if ((bits & MPPE_128) == 0)
775		bcopy(&ng_mppe_weakenkey, key, sizeof(ng_mppe_weakenkey));
776	rc4_init(rc4, key, keylen);
777}
778
779