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