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