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