cbc.c revision 90109
1247738Sbapt/* cbc.c: This file contains the encryption routines for the ed line editor */
2247738Sbapt/*-
3247738Sbapt * Copyright (c) 1993 The Regents of the University of California.
4247738Sbapt * All rights reserved.
5247738Sbapt *
6247738Sbapt * Copyright (c) 1993 Andrew Moore, Talke Studio.
7247738Sbapt * All rights reserved.
8247738Sbapt *
9247738Sbapt * Redistribution and use in source and binary forms, with or without
10247738Sbapt * modification, are permitted provided that the following conditions
11247738Sbapt * are met:
12247738Sbapt * 1. Redistributions of source code must retain the above copyright
13247738Sbapt *    notice, this list of conditions and the following disclaimer.
14247738Sbapt * 2. Redistributions in binary form must reproduce the above copyright
15247738Sbapt *    notice, this list of conditions and the following disclaimer in the
16247738Sbapt *    documentation and/or other materials provided with the distribution.
17247738Sbapt * 3. All advertising materials mentioning features or use of this software
18247738Sbapt *    must display the following acknowledgement:
19247738Sbapt *	This product includes software developed by the University of
20247738Sbapt *	California, Berkeley and its contributors.
21247738Sbapt * 4. Neither the name of the University nor the names of its contributors
22247738Sbapt *    may be used to endorse or promote products derived from this software
23247738Sbapt *    without specific prior written permission.
24247738Sbapt *
25247738Sbapt * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26247738Sbapt * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27247738Sbapt * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28247738Sbapt * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29247738Sbapt * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30247738Sbapt * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31247738Sbapt * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32247738Sbapt * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33247738Sbapt * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34247738Sbapt * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35247738Sbapt * SUCH DAMAGE.
36247738Sbapt */
37247738Sbapt
38247738Sbapt#ifndef lint
39247738Sbaptstatic const char rcsid[] =
40247738Sbapt  "$FreeBSD: head/bin/ed/cbc.c 90109 2002-02-02 06:36:49Z imp $";
41247738Sbapt#endif /* not lint */
42247738Sbapt
43247738Sbapt#include <sys/types.h>
44247738Sbapt#include <errno.h>
45247738Sbapt#include <pwd.h>
46247738Sbapt#ifdef DES
47247738Sbapt#include <time.h>
48247738Sbapt#endif
49247738Sbapt
50247738Sbapt#include "ed.h"
51247738Sbapt
52247738Sbapt
53247738Sbapt/*
54247738Sbapt * BSD and System V systems offer special library calls that do
55247738Sbapt * block move_liness and fills, so if possible we take advantage of them
56247738Sbapt */
57247738Sbapt#define	MEMCPY(dest,src,len)	memcpy((dest),(src),(len))
58247738Sbapt#define	MEMZERO(dest,len)	memset((dest), 0, (len))
59247738Sbapt
60247738Sbapt/* Hide the calls to the primitive encryption routines. */
61247738Sbapt#define	DES_KEY(buf) \
62247738Sbapt	if (des_setkey(buf)) \
63247738Sbapt		des_error("des_setkey");
64247738Sbapt#define	DES_XFORM(buf) \
65247738Sbapt	if (des_cipher(buf, buf, 0L, (inverse ? -1 : 1))) \
66247738Sbapt		des_error("des_cipher");
67247738Sbapt
68247738Sbapt/*
69247738Sbapt * read/write - no error checking
70247738Sbapt */
71247738Sbapt#define	READ(buf, n, fp)	fread(buf, sizeof(char), n, fp)
72247738Sbapt#define WRITE(buf, n, fp)	fwrite(buf, sizeof(char), n, fp)
73247738Sbapt
74247738Sbapt/*
75247738Sbapt * some things to make references easier
76247738Sbapt */
77247738Sbapttypedef char Desbuf[8];
78247738Sbapt#define	CHAR(x,i)	(x[i])
79247738Sbapt#define	UCHAR(x,i)	(x[i])
80247738Sbapt#define	BUFFER(x)	(x)
81247738Sbapt#define	UBUFFER(x)	(x)
82247738Sbapt
83247738Sbapt/*
84247738Sbapt * global variables and related macros
85247738Sbapt */
86247738Sbapt
87247738Sbaptenum { 					/* encrypt, decrypt, authenticate */
88247738Sbapt	MODE_ENCRYPT, MODE_DECRYPT, MODE_AUTHENTICATE
89247738Sbapt} mode = MODE_ENCRYPT;
90247738Sbapt
91247738SbaptDesbuf ivec;				/* initialization vector */
92Desbuf pvec;				/* padding vector */
93char bits[] = {				/* used to extract bits from a char */
94	'\200', '\100', '\040', '\020', '\010', '\004', '\002', '\001'
95};
96int pflag;				/* 1 to preserve parity bits */
97
98unsigned char des_buf[8];	/* shared buffer for get_des_char/put_des_char */
99int des_ct = 0;			/* count for get_des_char/put_des_char */
100int des_n = 0;			/* index for put_des_char/get_des_char */
101
102
103/* init_des_cipher: initialize DES */
104void
105init_des_cipher(void)
106{
107#ifdef DES
108	int i;
109
110	des_ct = des_n = 0;
111
112	/* initialize the initialization vector */
113	MEMZERO(ivec, 8);
114
115	/* initialize the padding vector */
116	for (i = 0; i < 8; i++)
117		CHAR(pvec, i) = (char) (arc4random() % 256);
118#endif
119}
120
121
122/* get_des_char: return next char in an encrypted file */
123int
124get_des_char(FILE *fp)
125{
126#ifdef DES
127	if (des_n >= des_ct) {
128		des_n = 0;
129		des_ct = cbc_decode(des_buf, fp);
130	}
131	return (des_ct > 0) ? des_buf[des_n++] : EOF;
132#else
133	return (getc(fp));
134#endif
135}
136
137
138/* put_des_char: write a char to an encrypted file; return char written */
139int
140put_des_char(int c, 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) ? (des_buf[des_n++] = c) : EOF;
148#else
149	return (fputc(c, fp));
150#endif
151}
152
153
154/* flush_des_file: flush an encrypted file's output; return status */
155int
156flush_des_file(FILE *fp)
157{
158#ifdef DES
159	if (des_n == sizeof des_buf) {
160		des_ct = cbc_encode(des_buf, des_n, fp);
161		des_n = 0;
162	}
163	return (des_ct >= 0 && cbc_encode(des_buf, des_n, fp) >= 0) ? 0 : EOF;
164#else
165	return (fflush(fp));
166#endif
167}
168
169#ifdef DES
170/*
171 * get keyword from tty or stdin
172 */
173int
174get_keyword(void)
175{
176	char *p;			/* used to obtain the key */
177	Desbuf msgbuf;			/* I/O buffer */
178
179	/*
180	 * get the key
181	 */
182	if (*(p = getpass("Enter key: "))) {
183
184		/*
185		 * copy it, nul-padded, into the key area
186		 */
187		expand_des_key(BUFFER(msgbuf), p);
188		MEMZERO(p, _PASSWORD_LEN);
189		set_des_key(msgbuf);
190		MEMZERO(msgbuf, sizeof msgbuf);
191		return 1;
192	}
193	return 0;
194}
195
196
197/*
198 * print a warning message and, possibly, terminate
199 */
200void
201des_error(const char *s)
202{
203	errmsg = s ? s : strerror(errno);
204}
205
206/*
207 * map a hex character to an integer
208 */
209int
210hex_to_binary(int c, int radix)
211{
212	switch(c) {
213	case '0':		return(0x0);
214	case '1':		return(0x1);
215	case '2':		return(radix > 2 ? 0x2 : -1);
216	case '3':		return(radix > 3 ? 0x3 : -1);
217	case '4':		return(radix > 4 ? 0x4 : -1);
218	case '5':		return(radix > 5 ? 0x5 : -1);
219	case '6':		return(radix > 6 ? 0x6 : -1);
220	case '7':		return(radix > 7 ? 0x7 : -1);
221	case '8':		return(radix > 8 ? 0x8 : -1);
222	case '9':		return(radix > 9 ? 0x9 : -1);
223	case 'A': case 'a':	return(radix > 10 ? 0xa : -1);
224	case 'B': case 'b':	return(radix > 11 ? 0xb : -1);
225	case 'C': case 'c':	return(radix > 12 ? 0xc : -1);
226	case 'D': case 'd':	return(radix > 13 ? 0xd : -1);
227	case 'E': case 'e':	return(radix > 14 ? 0xe : -1);
228	case 'F': case 'f':	return(radix > 15 ? 0xf : -1);
229	}
230	/*
231	 * invalid character
232	 */
233	return(-1);
234}
235
236/*
237 * convert the key to a bit pattern
238 *	obuf		bit pattern
239 *	kbuf		the key itself
240 */
241void
242expand_des_key(char *obuf, char *kbuf)
243{
244	int i, j;			/* counter in a for loop */
245	int nbuf[64];			/* used for hex/key translation */
246
247	/*
248	 * leading '0x' or '0X' == hex key
249	 */
250	if (kbuf[0] == '0' && (kbuf[1] == 'x' || kbuf[1] == 'X')) {
251		kbuf = &kbuf[2];
252		/*
253		 * now translate it, bombing on any illegal hex digit
254		 */
255		for (i = 0; kbuf[i] && i < 16; i++)
256			if ((nbuf[i] = hex_to_binary((int) kbuf[i], 16)) == -1)
257				des_error("bad hex digit in key");
258		while (i < 16)
259			nbuf[i++] = 0;
260		for (i = 0; i < 8; i++)
261			obuf[i] =
262			    ((nbuf[2*i]&0xf)<<4) | (nbuf[2*i+1]&0xf);
263		/* preserve parity bits */
264		pflag = 1;
265		return;
266	}
267	/*
268	 * leading '0b' or '0B' == binary key
269	 */
270	if (kbuf[0] == '0' && (kbuf[1] == 'b' || kbuf[1] == 'B')) {
271		kbuf = &kbuf[2];
272		/*
273		 * now translate it, bombing on any illegal binary digit
274		 */
275		for (i = 0; kbuf[i] && i < 16; i++)
276			if ((nbuf[i] = hex_to_binary((int) kbuf[i], 2)) == -1)
277				des_error("bad binary digit in key");
278		while (i < 64)
279			nbuf[i++] = 0;
280		for (i = 0; i < 8; i++)
281			for (j = 0; j < 8; j++)
282				obuf[i] = (obuf[i]<<1)|nbuf[8*i+j];
283		/* preserve parity bits */
284		pflag = 1;
285		return;
286	}
287	/*
288	 * no special leader -- ASCII
289	 */
290	(void)strncpy(obuf, kbuf, 8);
291}
292
293/*****************
294 * DES FUNCTIONS *
295 *****************/
296/*
297 * This sets the DES key and (if you're using the deszip version)
298 * the direction of the transformation.  This uses the Sun
299 * to map the 64-bit key onto the 56 bits that the key schedule
300 * generation routines use: the old way, which just uses the user-
301 * supplied 64 bits as is, and the new way, which resets the parity
302 * bit to be the same as the low-order bit in each character.  The
303 * new way generates a greater variety of key schedules, since many
304 * systems set the parity (high) bit of each character to 0, and the
305 * DES ignores the low order bit of each character.
306 */
307void
308set_des_key(Desbuf buf)				/* key block */
309{
310	int i, j;				/* counter in a for loop */
311	int par;				/* parity counter */
312
313	/*
314	 * if the parity is not preserved, flip it
315	 */
316	if (!pflag) {
317		for (i = 0; i < 8; i++) {
318			par = 0;
319			for (j = 1; j < 8; j++)
320				if ((bits[j]&UCHAR(buf, i)) != 0)
321					par++;
322			if ((par&01) == 01)
323				UCHAR(buf, i) = UCHAR(buf, i)&0177;
324			else
325				UCHAR(buf, i) = (UCHAR(buf, i)&0177)|0200;
326		}
327	}
328
329	DES_KEY(UBUFFER(buf));
330}
331
332
333/*
334 * This encrypts using the Cipher Block Chaining mode of DES
335 */
336int
337cbc_encode(char *msgbuf, int n, FILE *fp)
338{
339	int inverse = 0;	/* 0 to encrypt, 1 to decrypt */
340
341	/*
342	 * do the transformation
343	 */
344	if (n == 8) {
345		for (n = 0; n < 8; n++)
346			CHAR(msgbuf, n) ^= CHAR(ivec, n);
347		DES_XFORM(UBUFFER(msgbuf));
348		MEMCPY(BUFFER(ivec), BUFFER(msgbuf), 8);
349		return WRITE(BUFFER(msgbuf), 8, fp);
350	}
351	/*
352	 * at EOF or last block -- in either case, the last byte contains
353	 * the character representation of the number of bytes in it
354	 */
355/*
356	MEMZERO(msgbuf +  n, 8 - n);
357*/
358	/*
359	 *  Pad the last block randomly
360	 */
361	(void)MEMCPY(BUFFER(msgbuf + n), BUFFER(pvec), 8 - n);
362	CHAR(msgbuf, 7) = n;
363	for (n = 0; n < 8; n++)
364		CHAR(msgbuf, n) ^= CHAR(ivec, n);
365	DES_XFORM(UBUFFER(msgbuf));
366	return WRITE(BUFFER(msgbuf), 8, fp);
367}
368
369/*
370 * This decrypts using the Cipher Block Chaining mode of DES
371 *	msgbuf	I/O buffer
372 *	fp	input file descriptor
373 */
374int
375cbc_decode(char *msgbuf, FILE *fp)
376{
377	Desbuf tbuf;	/* temp buffer for initialization vector */
378	int n;			/* number of bytes actually read */
379	int c;			/* used to test for EOF */
380	int inverse = 1;	/* 0 to encrypt, 1 to decrypt */
381
382	if ((n = READ(BUFFER(msgbuf), 8, fp)) == 8) {
383		/*
384		 * do the transformation
385		 */
386		MEMCPY(BUFFER(tbuf), BUFFER(msgbuf), 8);
387		DES_XFORM(UBUFFER(msgbuf));
388		for (c = 0; c < 8; c++)
389			UCHAR(msgbuf, c) ^= UCHAR(ivec, c);
390		MEMCPY(BUFFER(ivec), BUFFER(tbuf), 8);
391		/*
392		 * if the last one, handle it specially
393		 */
394		if ((c = fgetc(fp)) == EOF) {
395			n = CHAR(msgbuf, 7);
396			if (n < 0 || n > 7) {
397				des_error("decryption failed (block corrupted)");
398				return EOF;
399			}
400		} else
401			(void)ungetc(c, fp);
402		return n;
403	}
404	if (n > 0)
405		des_error("decryption failed (incomplete block)");
406	else if (n < 0)
407		des_error("cannot read file");
408	return EOF;
409}
410#endif	/* DES */
411