Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / bin / ed / cbc.c
1 /* cbc.c: This file contains the encryption routines for the ed line editor */
2 /*-
3  * Copyright (c) 1993 The Regents of the University of California.
4  * All rights reserved.
5  *
6  * Copyright (c) 1993 Andrew Moore, Talke Studio.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by the University of
20  *      California, Berkeley and its contributors.
21  * 4. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *      from: @(#)bdes.c        5.5 (Berkeley) 6/27/91
38  *
39  * @(#)cbc.c,v 1.2 1994/02/01 00:34:36 alm Exp
40  * $FreeBSD: src/bin/ed/cbc.c,v 1.12.2.1 2001/07/04 22:32:18 kris Exp $
41  * $DragonFly: src/bin/ed/cbc.c,v 1.2 2003/06/17 04:22:49 dillon Exp $
42  */
43
44 #include <sys/types.h>
45 #include <errno.h>
46 #include <pwd.h>
47 #ifdef DES
48 #include <time.h>
49 #endif
50
51 #include "ed.h"
52
53
54 /*
55  * BSD and System V systems offer special library calls that do
56  * block move_liness and fills, so if possible we take advantage of them
57  */
58 #define MEMCPY(dest,src,len)    memcpy((dest),(src),(len))
59 #define MEMZERO(dest,len)       memset((dest), 0, (len))
60
61 /* Hide the calls to the primitive encryption routines. */
62 #define DES_KEY(buf) \
63         if (des_setkey(buf)) \
64                 des_error("des_setkey");
65 #define DES_XFORM(buf) \
66         if (des_cipher(buf, buf, 0L, (inverse ? -1 : 1))) \
67                 des_error("des_cipher");
68
69 /*
70  * read/write - no error checking
71  */
72 #define READ(buf, n, fp)        fread(buf, sizeof(char), n, fp)
73 #define WRITE(buf, n, fp)       fwrite(buf, sizeof(char), n, fp)
74
75 /*
76  * some things to make references easier
77  */
78 typedef char Desbuf[8];
79 #define CHAR(x,i)       (x[i])
80 #define UCHAR(x,i)      (x[i])
81 #define BUFFER(x)       (x)
82 #define UBUFFER(x)      (x)
83
84 /*
85  * global variables and related macros
86  */
87
88 enum {                                  /* encrypt, decrypt, authenticate */
89         MODE_ENCRYPT, MODE_DECRYPT, MODE_AUTHENTICATE
90 } mode = MODE_ENCRYPT;
91
92 Desbuf ivec;                            /* initialization vector */
93 Desbuf pvec;                            /* padding vector */
94 char bits[] = {                         /* used to extract bits from a char */
95         '\200', '\100', '\040', '\020', '\010', '\004', '\002', '\001'
96 };
97 int pflag;                              /* 1 to preserve parity bits */
98
99 unsigned char des_buf[8];       /* shared buffer for get_des_char/put_des_char */
100 int des_ct = 0;                 /* count for get_des_char/put_des_char */
101 int des_n = 0;                  /* index for put_des_char/get_des_char */
102
103
104 /* init_des_cipher: initialize DES */
105 void
106 init_des_cipher()
107 {
108 #ifdef DES
109         int i;
110
111         des_ct = des_n = 0;
112
113         /* initialize the initialization vector */
114         MEMZERO(ivec, 8);
115
116         /* initialize the padding vector */
117         for (i = 0; i < 8; i++)
118                 CHAR(pvec, i) = (char) (arc4random() % 256);
119 #endif
120 }
121
122
123 /* get_des_char: return next char in an encrypted file */
124 int
125 get_des_char(fp)
126         FILE *fp;
127 {
128 #ifdef DES
129         if (des_n >= des_ct) {
130                 des_n = 0;
131                 des_ct = cbc_decode(des_buf, fp);
132         }
133         return (des_ct > 0) ? des_buf[des_n++] : EOF;
134 #else
135         return (getc(fp));
136 #endif
137 }
138
139
140 /* put_des_char: write a char to an encrypted file; return char written */
141 int
142 put_des_char(c, fp)
143         int c;
144         FILE *fp;
145 {
146 #ifdef DES
147         if (des_n == sizeof des_buf) {
148                 des_ct = cbc_encode(des_buf, des_n, fp);
149                 des_n = 0;
150         }
151         return (des_ct >= 0) ? (des_buf[des_n++] = c) : EOF;
152 #else
153         return (fputc(c, fp));
154 #endif
155 }
156
157
158 /* flush_des_file: flush an encrypted file's output; return status */
159 int
160 flush_des_file(fp)
161         FILE *fp;
162 {
163 #ifdef DES
164         if (des_n == sizeof des_buf) {
165                 des_ct = cbc_encode(des_buf, des_n, fp);
166                 des_n = 0;
167         }
168         return (des_ct >= 0 && cbc_encode(des_buf, des_n, fp) >= 0) ? 0 : EOF;
169 #else
170         return (fflush(fp));
171 #endif
172 }
173
174 #ifdef DES
175 /*
176  * get keyword from tty or stdin
177  */
178 int
179 get_keyword()
180 {
181         register char *p;               /* used to obtain the key */
182         Desbuf msgbuf;                  /* I/O buffer */
183
184         /*
185          * get the key
186          */
187         if (*(p = getpass("Enter key: "))) {
188
189                 /*
190                  * copy it, nul-padded, into the key area
191                  */
192                 expand_des_key(BUFFER(msgbuf), p);
193                 MEMZERO(p, _PASSWORD_LEN);
194                 set_des_key(msgbuf);
195                 MEMZERO(msgbuf, sizeof msgbuf);
196                 return 1;
197         }
198         return 0;
199 }
200
201
202 /*
203  * print a warning message and, possibly, terminate
204  */
205 void
206 des_error(s)
207         char *s;                /* the message */
208 {
209         (void)sprintf(errmsg, "%s", s ? s : strerror(errno));
210 }
211
212 /*
213  * map a hex character to an integer
214  */
215 int
216 hex_to_binary(c, radix)
217         int c;                  /* char to be converted */
218         int radix;              /* base (2 to 16) */
219 {
220         switch(c) {
221         case '0':               return(0x0);
222         case '1':               return(0x1);
223         case '2':               return(radix > 2 ? 0x2 : -1);
224         case '3':               return(radix > 3 ? 0x3 : -1);
225         case '4':               return(radix > 4 ? 0x4 : -1);
226         case '5':               return(radix > 5 ? 0x5 : -1);
227         case '6':               return(radix > 6 ? 0x6 : -1);
228         case '7':               return(radix > 7 ? 0x7 : -1);
229         case '8':               return(radix > 8 ? 0x8 : -1);
230         case '9':               return(radix > 9 ? 0x9 : -1);
231         case 'A': case 'a':     return(radix > 10 ? 0xa : -1);
232         case 'B': case 'b':     return(radix > 11 ? 0xb : -1);
233         case 'C': case 'c':     return(radix > 12 ? 0xc : -1);
234         case 'D': case 'd':     return(radix > 13 ? 0xd : -1);
235         case 'E': case 'e':     return(radix > 14 ? 0xe : -1);
236         case 'F': case 'f':     return(radix > 15 ? 0xf : -1);
237         }
238         /*
239          * invalid character
240          */
241         return(-1);
242 }
243
244 /*
245  * convert the key to a bit pattern
246  */
247 void
248 expand_des_key(obuf, ibuf)
249         char *obuf;                     /* bit pattern */
250         char *ibuf;                     /* the key itself */
251 {
252         register int i, j;              /* counter in a for loop */
253         int nbuf[64];                   /* used for hex/key translation */
254
255         /*
256          * leading '0x' or '0X' == hex key
257          */
258         if (ibuf[0] == '0' && (ibuf[1] == 'x' || ibuf[1] == 'X')) {
259                 ibuf = &ibuf[2];
260                 /*
261                  * now translate it, bombing on any illegal hex digit
262                  */
263                 for (i = 0; ibuf[i] && i < 16; i++)
264                         if ((nbuf[i] = hex_to_binary((int) ibuf[i], 16)) == -1)
265                                 des_error("bad hex digit in key");
266                 while (i < 16)
267                         nbuf[i++] = 0;
268                 for (i = 0; i < 8; i++)
269                         obuf[i] =
270                             ((nbuf[2*i]&0xf)<<4) | (nbuf[2*i+1]&0xf);
271                 /* preserve parity bits */
272                 pflag = 1;
273                 return;
274         }
275         /*
276          * leading '0b' or '0B' == binary key
277          */
278         if (ibuf[0] == '0' && (ibuf[1] == 'b' || ibuf[1] == 'B')) {
279                 ibuf = &ibuf[2];
280                 /*
281                  * now translate it, bombing on any illegal binary digit
282                  */
283                 for (i = 0; ibuf[i] && i < 16; i++)
284                         if ((nbuf[i] = hex_to_binary((int) ibuf[i], 2)) == -1)
285                                 des_error("bad binary digit in key");
286                 while (i < 64)
287                         nbuf[i++] = 0;
288                 for (i = 0; i < 8; i++)
289                         for (j = 0; j < 8; j++)
290                                 obuf[i] = (obuf[i]<<1)|nbuf[8*i+j];
291                 /* preserve parity bits */
292                 pflag = 1;
293                 return;
294         }
295         /*
296          * no special leader -- ASCII
297          */
298         (void)strncpy(obuf, ibuf, 8);
299 }
300
301 /*****************
302  * DES FUNCTIONS *
303  *****************/
304 /*
305  * This sets the DES key and (if you're using the deszip version)
306  * the direction of the transformation.  This uses the Sun
307  * to map the 64-bit key onto the 56 bits that the key schedule
308  * generation routines use: the old way, which just uses the user-
309  * supplied 64 bits as is, and the new way, which resets the parity
310  * bit to be the same as the low-order bit in each character.  The
311  * new way generates a greater variety of key schedules, since many
312  * systems set the parity (high) bit of each character to 0, and the
313  * DES ignores the low order bit of each character.
314  */
315 void
316 set_des_key(buf)
317         Desbuf buf;                             /* key block */
318 {
319         register int i, j;                      /* counter in a for loop */
320         register int par;                       /* parity counter */
321
322         /*
323          * if the parity is not preserved, flip it
324          */
325         if (!pflag) {
326                 for (i = 0; i < 8; i++) {
327                         par = 0;
328                         for (j = 1; j < 8; j++)
329                                 if ((bits[j]&UCHAR(buf, i)) != 0)
330                                         par++;
331                         if ((par&01) == 01)
332                                 UCHAR(buf, i) = UCHAR(buf, i)&0177;
333                         else
334                                 UCHAR(buf, i) = (UCHAR(buf, i)&0177)|0200;
335                 }
336         }
337
338         DES_KEY(UBUFFER(buf));
339 }
340
341
342 /*
343  * This encrypts using the Cipher Block Chaining mode of DES
344  */
345 int
346 cbc_encode(msgbuf, n, fp)
347         char *msgbuf;
348         int n;
349         FILE *fp;
350 {
351         int inverse = 0;        /* 0 to encrypt, 1 to decrypt */
352
353         /*
354          * do the transformation
355          */
356         if (n == 8) {
357                 for (n = 0; n < 8; n++)
358                         CHAR(msgbuf, n) ^= CHAR(ivec, n);
359                 DES_XFORM(UBUFFER(msgbuf));
360                 MEMCPY(BUFFER(ivec), BUFFER(msgbuf), 8);
361                 return WRITE(BUFFER(msgbuf), 8, fp);
362         }
363         /*
364          * at EOF or last block -- in either case, the last byte contains
365          * the character representation of the number of bytes in it
366          */
367 /*
368         MEMZERO(msgbuf +  n, 8 - n);
369 */
370         /*
371          *  Pad the last block randomly
372          */
373         (void)MEMCPY(BUFFER(msgbuf + n), BUFFER(pvec), 8 - n);
374         CHAR(msgbuf, 7) = n;
375         for (n = 0; n < 8; n++)
376                 CHAR(msgbuf, n) ^= CHAR(ivec, n);
377         DES_XFORM(UBUFFER(msgbuf));
378         return WRITE(BUFFER(msgbuf), 8, fp);
379 }
380
381 /*
382  * This decrypts using the Cipher Block Chaining mode of DES
383  */
384 int
385 cbc_decode(msgbuf, fp)
386         char *msgbuf;           /* I/O buffer */
387         FILE *fp;                       /* input file descriptor */
388 {
389         Desbuf ibuf;    /* temp buffer for initialization vector */
390         register int n;         /* number of bytes actually read */
391         register int c;         /* used to test for EOF */
392         int inverse = 1;        /* 0 to encrypt, 1 to decrypt */
393
394         if ((n = READ(BUFFER(msgbuf), 8, fp)) == 8) {
395                 /*
396                  * do the transformation
397                  */
398                 MEMCPY(BUFFER(ibuf), BUFFER(msgbuf), 8);
399                 DES_XFORM(UBUFFER(msgbuf));
400                 for (c = 0; c < 8; c++)
401                         UCHAR(msgbuf, c) ^= UCHAR(ivec, c);
402                 MEMCPY(BUFFER(ivec), BUFFER(ibuf), 8);
403                 /*
404                  * if the last one, handle it specially
405                  */
406                 if ((c = fgetc(fp)) == EOF) {
407                         n = CHAR(msgbuf, 7);
408                         if (n < 0 || n > 7) {
409                                 des_error("decryption failed (block corrupted)");
410                                 return EOF;
411                         }
412                 } else
413                         (void)ungetc(c, fp);
414                 return n;
415         }
416         if (n > 0)
417                 des_error("decryption failed (incomplete block)");
418         else if (n < 0)
419                 des_error("cannot read file");
420         return EOF;
421 }
422 #endif  /* DES */