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