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