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