source: zcrypt.c @ 6829afc

release-1.10release-1.8release-1.9
Last change on this file since 6829afc was 6829afc, checked in by David Benjamin <davidben@mit.edu>, 13 years ago
Define CALLER_OWN macro Replace our exising uses of G_GNUC_WARN_UNUSED_RESULT with it. The old macro is just way too long. This also more clearly specifies the intent.
  • Property mode set to 100644
File size: 20.8 KB
Line 
1/* zcrypt.c -- Read in a data stream from stdin & dump a decrypted/encrypted *
2 *   datastream.  Reads the string to make the key from from the first       *
3 *   parameter.  Encrypts or decrypts according to -d or -e flag.  (-e is    *
4 *   default.)  Will invoke zwrite if the -c option is provided for          *
5 *   encryption.  If a zephyr class is specified & the keyfile name omitted  *
6 *   the ~/.crypt-table will be checked for "crypt-classname" and then       *
7 *   "crypt-default" for the keyfile name.                                   */
8
9#include <stdio.h>
10
11#include <unistd.h>
12#include <sys/types.h>
13#include <glib.h>
14#include <string.h>
15#include <stdlib.h>
16#include <sys/wait.h>
17#include <ctype.h>
18
19#include "config.h"
20
21#ifdef HAVE_KERBEROS_IV
22#include <kerberosIV/des.h>
23#else
24#include <openssl/des.h>
25#endif
26
27#include "filterproc.h"
28
29/* Annotate functions in which the caller owns the return value and is
30 * responsible for ensuring it is freed. */
31#define CALLER_OWN G_GNUC_WARN_UNUSED_RESULT
32
33#define MAX_KEY      128
34#define MAX_LINE     128
35#define MAX_RESULT   4096
36
37#ifndef TRUE
38#define TRUE -1
39#endif
40#ifndef FALSE
41#define FALSE 0
42#endif
43
44#define ZWRITE_OPT_NOAUTH     (1<<0)
45#define ZWRITE_OPT_SIGNATURE  (1<<1)
46#define ZWRITE_OPT_IGNOREVARS (1<<2)
47#define ZWRITE_OPT_VERBOSE    (1<<3)
48#define ZWRITE_OPT_QUIET      (1<<4)
49#define ZCRYPT_OPT_MESSAGE    (1<<5)
50#define ZCRYPT_OPT_IGNOREDOT  (1<<6)
51
52typedef struct
53{
54  int flags;
55  const char *signature;
56  char *message;
57} ZWRITEOPTIONS;
58
59CALLER_OWN char *GetZephyrVarKeyFile(const char *whoami, const char *class, const char *instance);
60int ParseCryptSpec(const char *spec, const char **keyfile);
61CALLER_OWN char *BuildArgString(char **argv, int start, int end);
62CALLER_OWN char *read_keystring(const char *keyfile);
63
64int do_encrypt(int zephyr, const char *class, const char *instance,
65               ZWRITEOPTIONS *zoptions, const char* keyfile, int cipher);
66int do_encrypt_des(const char *keyfile, const char *in, int len, FILE *out);
67int do_encrypt_aes(const char *keyfile, const char *in, int len, FILE *out);
68
69int do_decrypt(const char *keyfile, int cipher);
70int do_decrypt_aes(const char *keyfile);
71int do_decrypt_des(const char *keyfile);
72
73
74#define M_NONE            0
75#define M_ZEPHYR_ENCRYPT  1
76#define M_DECRYPT         2
77#define M_ENCRYPT         3
78#define M_RANDOMIZE       4
79#define M_SETKEY          5
80
81enum cipher_algo {
82  CIPHER_DES,
83  CIPHER_AES,
84  NCIPHER
85};
86
87typedef struct {
88  int (*encrypt)(const char *keyfile, const char *in, int len, FILE *out);
89  int (*decrypt)(const char *keyfile);
90} cipher_pair;
91
92cipher_pair ciphers[NCIPHER] = {
93  [CIPHER_DES] = { do_encrypt_des, do_decrypt_des},
94  [CIPHER_AES] = { do_encrypt_aes, do_decrypt_aes},
95};
96
97static void owl_zcrypt_string_to_schedule(char *keystring, des_key_schedule *schedule) {
98#ifdef HAVE_KERBEROS_IV
99  des_cblock key;
100#else
101  des_cblock _key, *key = &_key;
102#endif
103
104  des_string_to_key(keystring, key);
105  des_key_sched(key, *schedule);
106}
107
108int main(int argc, char *argv[])
109{
110  char *cryptspec = NULL;
111  const char *keyfile;
112  int cipher;
113  int error = FALSE;
114  int zephyr = FALSE;
115  const char *class = NULL, *instance = NULL;
116  int mode = M_NONE;
117
118  char c;
119
120  int messageflag = FALSE;
121  ZWRITEOPTIONS zoptions;
122  zoptions.flags = 0;
123
124  while ((c = getopt(argc, argv, "ZDERSF:c:i:advqtluons:f:m")) != (char)EOF)
125  {
126    switch(c)
127    {
128      case 'Z':
129        /* Zephyr encrypt */
130        mode = M_ZEPHYR_ENCRYPT;
131        break;
132      case 'D':
133        /* Decrypt */
134        mode = M_DECRYPT;
135        break;
136      case 'E':
137        /* Encrypt */
138        mode = M_ENCRYPT;
139        break;
140      case 'R':
141        /* Randomize the keyfile */
142        mode = M_RANDOMIZE;
143        break;
144      case 'S':
145        /* Set a new key value from stdin */
146        mode = M_SETKEY;
147        break;
148      case 'F':
149        /* Specify the keyfile explicitly */
150        if (cryptspec != NULL) error = TRUE;
151        cryptspec = optarg;
152        break;
153      case 'c':
154        /* Zwrite/zcrypt: class name */
155        if (class != NULL) error = TRUE;
156        class = optarg;
157        break;
158      case 'i':
159        /* Zwrite/zcrypt: instance name */
160        if (instance != NULL) error = TRUE;
161        instance = optarg;
162        break;
163      case 'a':
164        /* Zwrite: authenticate (default) */
165        zoptions.flags &= ~ZWRITE_OPT_NOAUTH;
166        break;
167      case 'd':
168        /* Zwrite: do not authenticate */
169        zoptions.flags |= ZWRITE_OPT_NOAUTH;
170        break;
171      case 'v':
172        /* Zwrite: verbose */
173        zoptions.flags |= ZWRITE_OPT_VERBOSE;
174        break;
175      case 'q':
176        /* Zwrite: quiet */
177        zoptions.flags |= ZWRITE_OPT_QUIET;
178        break;
179      case 't':
180        /* Zwrite: no expand tabs (ignored) */
181        break;
182      case 'l':
183        /* Zwrite: ignore '.' on a line by itself (ignored) */
184        zoptions.flags |= ZCRYPT_OPT_IGNOREDOT;
185        break;
186      case 'u':
187        /* Zwrite: urgent message */
188        instance = "URGENT";
189        break;
190      case 'o':
191        /* Zwrite: ignore zephyr variables zwrite-class, zwrite-inst, */
192        /*         zwrite-opcode */
193        zoptions.flags |= ZWRITE_OPT_IGNOREVARS;
194        break;
195      case 'n':
196        /* Zwrite: prevent PING message (always used) */
197        break;
198      case 's':
199        /* Zwrite: signature */
200        zoptions.flags |= ZWRITE_OPT_SIGNATURE;
201        zoptions.signature = optarg;
202        break;
203      case 'f':
204        /* Zwrite: file system specification (ignored) */
205        break;
206      case 'm':
207        /* Message on rest of line*/
208        messageflag = TRUE;
209        break;
210      case '?':
211        error = TRUE;
212        break;
213    }
214    if (error || messageflag)
215      break;
216  }
217
218  if (class != NULL || instance != NULL)
219    zephyr = TRUE;
220
221  if (messageflag)
222  {
223    zoptions.flags |= ZCRYPT_OPT_MESSAGE;
224    zoptions.message = BuildArgString(argv, optind, argc);
225    if (!zoptions.message)
226    {
227      fprintf(stderr, "Memory allocation error.\n");
228      error = TRUE;
229    }
230  }
231  else if (optind < argc)
232  {
233    error = TRUE;
234  }
235
236  if (mode == M_NONE)
237    mode = (zephyr?M_ZEPHYR_ENCRYPT:M_ENCRYPT);
238
239  if (mode == M_ZEPHYR_ENCRYPT && !zephyr)
240    error = TRUE;
241
242  if (!error && cryptspec == NULL && (class != NULL || instance != NULL)) {
243    cryptspec = GetZephyrVarKeyFile(argv[0], class, instance);
244    if(!cryptspec) {
245      fprintf(stderr, "Unable to find keyfile for ");
246      if(class != NULL) {
247        fprintf(stderr, "-c %s ", class);
248      }
249      if(instance != NULL) {
250        fprintf(stderr, "-i %s ", instance);
251      }
252      fprintf(stderr, "\n");
253      exit(-1);
254    }
255  }
256
257  if (error || !cryptspec)
258  {
259    fprintf(stderr, "Usage: %s [-Z|-D|-E|-R|-S] [-F Keyfile] [-c class] [-i instance]\n", argv[0]);
260    fprintf(stderr, "       [-advqtluon] [-s signature] [-f arg] [-m message]\n");
261    fprintf(stderr, "  One or more of class, instance, and keyfile must be specified.\n");
262    exit(1);
263  }
264
265  cipher = ParseCryptSpec(cryptspec, &keyfile);
266  if(cipher < 0) {
267    fprintf(stderr, "Invalid cipher specification: %s\n", cryptspec);
268    exit(1);
269  }
270
271
272  if (mode == M_RANDOMIZE)
273  {
274    /* Choose a new, random key */
275    /*
276      FILE *fkey = fopen(fname, "w");
277      if (!fkey)
278      printf("Could not open key file for writing: %s\n", fname);
279      else
280      {
281      char string[100];
282      fputs(fkey, string);
283      fclose(fkey);
284      }
285    */
286    fprintf(stderr, "Feature not yet implemented.\n");
287  }
288  else if (mode == M_SETKEY)
289  {
290    /* Set a new, user-entered key */
291    char newkey[MAX_KEY];
292    FILE *fkey;
293
294    if (isatty(0))
295    {
296      printf("Enter new key: ");
297      /* Really should read without echo!!! */
298    }
299    if(!fgets(newkey, MAX_KEY - 1, stdin)) {
300      fprintf(stderr, "Error reading key.\n");
301      return 1;
302    }
303
304    fkey = fopen(keyfile, "w");
305    if (!fkey)
306      fprintf(stderr, "Could not open key file for writing: %s\n", keyfile);
307    else
308    {
309      if (fputs(newkey, fkey) != strlen(newkey) || putc('\n', fkey) != '\n')
310      {
311        fprintf(stderr, "Error writing to key file.\n");
312        fclose(fkey);
313        exit(1);
314      }
315      else
316      {
317        fclose(fkey);
318        fprintf(stderr, "Key update complete.\n");
319      }
320    }
321  }
322  else
323  {
324    if (mode == M_ZEPHYR_ENCRYPT || mode == M_ENCRYPT)
325      error = !do_encrypt((mode == M_ZEPHYR_ENCRYPT), class, instance,
326                          &zoptions, keyfile, cipher);
327    else
328      error = !do_decrypt(keyfile, cipher);
329  }
330
331  /* Always print the **END** message if -D is specified. */
332  if (mode == M_DECRYPT)
333    printf("**END**\n");
334
335  return error;
336}
337
338int ParseCryptSpec(const char *spec, const char **keyfile) {
339  int cipher = CIPHER_DES;
340  char *cipher_name = strdup(spec);
341  char *colon = strchr(cipher_name, ':');
342
343  *keyfile = spec;
344
345  if (colon) {
346    char *rest = strchr(spec, ':') + 1;
347    while(isspace(*rest)) rest++;
348
349    *colon-- = '\0';
350    while (colon >= cipher_name && isspace(*colon)) {
351      *colon = '\0';
352    }
353
354    if(strcmp(cipher_name, "AES") == 0) {
355      cipher = CIPHER_AES;
356      *keyfile = rest;
357    } else if(strcmp(cipher_name, "DES") == 0) {
358      cipher = CIPHER_DES;
359      *keyfile = rest;
360    }
361  }
362
363  free(cipher_name);
364
365  return cipher;
366}
367
368/* Build a space-separated string from argv from elements between start  *
369 * and end - 1.  malloc()'s the returned string. */
370CALLER_OWN char *BuildArgString(char **argv, int start, int end)
371{
372  int len = 1;
373  int i;
374  char *result;
375
376  /* Compute the length of the string.  (Plus 1 or 2) */
377  for (i = start; i < end; i++)
378    len += strlen(argv[i]) + 1;
379
380  /* Allocate memory */
381  result = (char *)malloc(len);
382  if (result)
383  {
384    /* Build the string */
385    char *ptr = result;
386    /* Start with an empty string, in case nothing is copied. */
387    *ptr = '\0';
388    /* Copy the arguments */
389    for (i = start; i < end; i++)
390    {
391      char *temp = argv[i];
392      /* Add a space, if not the first argument */
393      if (i != start)
394        *ptr++ = ' ';
395      /* Copy argv[i], leaving ptr pointing to the '\0' copied from temp */
396      while ((*ptr = *temp++))
397        ptr++;
398    }
399  }
400
401  return result;
402}
403
404#define MAX_BUFF 258
405#define MAX_SEARCH 3
406/* Find the class/instance in the .crypt-table */
407CALLER_OWN char *GetZephyrVarKeyFile(const char *whoami, const char *class, const char *instance)
408{
409  char *keyfile = NULL;
410  char *varname[MAX_SEARCH];
411  int length[MAX_SEARCH], i;
412  char buffer[MAX_BUFF];
413  char *filename;
414  char result[MAX_SEARCH][MAX_BUFF];
415  int numsearch = 0;
416  FILE *fsearch;
417
418  memset(varname, 0, sizeof(varname));
419
420  /* Determine names to look for in .crypt-table */
421  if (instance)
422    varname[numsearch++] = g_strdup_printf("crypt-%s-%s:", (class?class:"message"), instance);
423  if (class)
424    varname[numsearch++] = g_strdup_printf("crypt-%s:", class);
425  varname[numsearch++] = g_strdup("crypt-default:");
426
427  /* Setup the result array, and determine string lengths */
428  for (i = 0; i < numsearch; i++)
429  {
430    result[i][0] = '\0';
431    length[i] = strlen(varname[i]);
432  }
433
434  /* Open~/.crypt-table */
435  filename = g_strdup_printf("%s/.crypt-table", getenv("HOME"));
436  fsearch = fopen(filename, "r");
437  if (fsearch)
438  {
439    /* Scan file for a match */
440    while (!feof(fsearch))
441    {
442      if (!fgets(buffer, MAX_BUFF - 3, fsearch)) break;
443      for (i = 0; i < numsearch; i++)
444        if (strncasecmp(varname[i], buffer, length[i]) == 0)
445        {
446          int j;
447          for (j = length[i]; buffer[j] == ' '; j++)
448            ;
449          strcpy(result[i], &buffer[j]);
450          if (*result[i])
451            if (result[i][strlen(result[i])-1] == '\n')
452              result[i][strlen(result[i])-1] = '\0';
453        }
454    }
455
456    /* Pick the "best" match found */
457    keyfile = NULL;
458    for (i = 0; i < numsearch; i++)
459      if (*result[i])
460      {
461        keyfile = result[i];
462        break;
463      }
464
465    if (keyfile != NULL)
466    {
467      /* Prepare result to be returned */
468      char *temp = keyfile;
469      keyfile = (char *)malloc(strlen(temp) + 1);
470      if (keyfile)
471        strcpy(keyfile, temp);
472      else
473        fprintf(stderr, "Memory allocation error.\n");
474    }
475    fclose(fsearch);
476  }
477  else
478    fprintf(stderr, "Could not open key table file: %s\n", filename);
479
480  for(i = 0; i < MAX_SEARCH; i++) {
481    g_free(varname[i]);
482  }
483
484  g_free(filename);
485
486  return keyfile;
487}
488
489static pid_t zephyrpipe_pid = 0;
490
491/* Open a pipe to zwrite */
492FILE *GetZephyrPipe(const char *class, const char *instance, const ZWRITEOPTIONS *zoptions)
493{
494  int fildes[2];
495  pid_t pid;
496  FILE *result;
497  const char *argv[20];
498  int argc = 0;
499
500  if (pipe(fildes) < 0)
501    return NULL;
502  pid = fork();
503
504  if (pid < 0)
505  {
506    /* Error: clean up */
507    close(fildes[0]);
508    close(fildes[1]);
509    result = NULL;
510  }
511  else if (pid == 0)
512  {
513    /* Setup child process */
514    argv[argc++] = "zwrite";
515    argv[argc++] = "-n";     /* Always send without ping */
516    if (class)
517    {
518      argv[argc++] = "-c";
519      argv[argc++] = class;
520    }
521    if (instance)
522    {
523      argv[argc++] = "-i";
524      argv[argc++] = instance;
525    }
526    if (zoptions->flags & ZWRITE_OPT_NOAUTH)
527      argv[argc++] = "-d";
528    if (zoptions->flags & ZWRITE_OPT_QUIET)
529      argv[argc++] = "-q";
530    if (zoptions->flags & ZWRITE_OPT_VERBOSE)
531      argv[argc++] = "-v";
532    if (zoptions->flags & ZWRITE_OPT_SIGNATURE)
533    {
534      argv[argc++] = "-s";
535      argv[argc++] = zoptions->signature;
536    }
537    argv[argc++] = "-O";
538    argv[argc++] = "crypt";
539    argv[argc] = NULL;
540    close(fildes[1]);
541    if (fildes[0] != STDIN_FILENO)
542    {
543      if (dup2(fildes[0], STDIN_FILENO) != STDIN_FILENO)
544        exit(0);
545      close(fildes[0]);
546    }
547    close(fildes[0]);
548    execvp(argv[0], (char **)argv);
549    fprintf(stderr, "Exec error: could not run zwrite\n");
550    exit(0);
551  }
552  else
553  {
554    close(fildes[0]);
555    /* Create a FILE * for the zwrite pipe */
556    result = (FILE *)fdopen(fildes[1], "w");
557    zephyrpipe_pid = pid;
558  }
559
560  return result;
561}
562
563/* Close the pipe to zwrite */
564void CloseZephyrPipe(FILE *pipe)
565{
566  fclose(pipe);
567  waitpid(zephyrpipe_pid, NULL, 0);
568  zephyrpipe_pid = 0;
569}
570
571#define BASE_CODE 70
572#define LAST_CODE (BASE_CODE + 15)
573#define OUTPUT_BLOCK_SIZE 16
574
575void block_to_ascii(unsigned char *output, FILE *outfile)
576{
577  int i;
578  for (i = 0; i < 8; i++)
579  {
580    putc(((output[i] & 0xf0) >> 4) + BASE_CODE, outfile);
581    putc( (output[i] & 0x0f)       + BASE_CODE, outfile);
582  }
583}
584
585CALLER_OWN char *slurp_stdin(int ignoredot, int *length) {
586  char *buf;
587  char *inptr;
588
589  if ((inptr = buf = (char *)malloc(MAX_RESULT)) == NULL)
590  {
591    fprintf(stderr, "Memory allocation error\n");
592    return NULL;
593  }
594  while (inptr - buf < MAX_RESULT - MAX_LINE - 20)
595  {
596    if (fgets(inptr, MAX_LINE, stdin) == NULL)
597      break;
598
599    if (inptr[0])
600    {
601      if (inptr[0] == '.' && inptr[1] == '\n' && !ignoredot)
602      {
603        inptr[0] = '\0';
604        break;
605      }
606      else
607        inptr += strlen(inptr);
608    }
609    else
610      break;
611  }
612  *length = inptr - buf;
613
614  return buf;
615}
616
617CALLER_OWN char *GetInputBuffer(ZWRITEOPTIONS *zoptions, int *length) {
618  char *buf;
619
620  if (zoptions->flags & ZCRYPT_OPT_MESSAGE)
621  {
622    /* Use the -m message */
623    buf = strdup(zoptions->message);
624    *length = strlen(buf);
625  }
626  else
627  {
628    if (isatty(0)) {
629      /* tty input, so show the "Type your message now..." message */
630      if (zoptions->flags & ZCRYPT_OPT_IGNOREDOT)
631        printf("Type your message now.  End with the end-of-file character.\n");
632      else
633        printf("Type your message now.  End with control-D or a dot on a line by itself.\n");
634    } else {
635      zoptions->flags |= ZCRYPT_OPT_IGNOREDOT;
636    }
637
638    buf = slurp_stdin(zoptions->flags & ZCRYPT_OPT_IGNOREDOT, length);
639  }
640  return buf;
641}
642
643CALLER_OWN char *read_keystring(const char *keyfile) {
644  char *keystring;
645  FILE *fkey = fopen(keyfile, "r");
646  if(!fkey) {
647    fprintf(stderr, "Unable to open keyfile %s\n", keyfile);
648    return NULL;
649  }
650  keystring = malloc(MAX_KEY);
651  if(!fgets(keystring, MAX_KEY-1, fkey)) {
652    fprintf(stderr, "Unable to read from keyfile: %s\n", keyfile);
653    free(keystring);
654    keystring = NULL;
655  }
656  fclose(fkey);
657  return keystring;
658}
659
660/* Encrypt stdin, with prompt if isatty, and send to stdout, or to zwrite
661   if zephyr is set. */
662int do_encrypt(int zephyr, const char *class, const char *instance,
663               ZWRITEOPTIONS *zoptions, const char *keyfile, int cipher)
664{
665  FILE *outfile = stdout;
666  char *inbuff = NULL;
667  int buflen;
668  int out = TRUE;
669
670  inbuff = GetInputBuffer(zoptions, &buflen);
671
672  if(!inbuff) {
673    fprintf(stderr, "Error reading zcrypt input!\n");
674    return FALSE;
675  }
676
677  if (zephyr) {
678    outfile = GetZephyrPipe(class, instance, zoptions);
679    if (!outfile)
680    {
681      fprintf(stderr, "Could not run zwrite\n");
682      if (inbuff)
683        free(inbuff);
684      return FALSE;
685    }
686  }
687
688  out = ciphers[cipher].encrypt(keyfile, inbuff, buflen, outfile);
689
690  if (zephyr)
691    CloseZephyrPipe(outfile);
692
693  free(inbuff);
694  return out;
695}
696
697int do_encrypt_des(const char *keyfile, const char *in, int length, FILE *outfile)
698{
699  des_key_schedule schedule;
700  unsigned char input[8], output[8];
701  const char *inptr;
702  int num_blocks, last_block_size;
703  char *keystring;
704  int size;
705
706  keystring = read_keystring(keyfile);
707  if(!keystring) {
708    return FALSE;
709  }
710
711  owl_zcrypt_string_to_schedule(keystring, &schedule);
712  free(keystring);
713
714  inptr = in;
715  num_blocks = (length + 7) / 8;
716  last_block_size = ((length + 7) % 8) + 1;
717
718  /* Encrypt the input (inbuff or stdin) and send it to outfile */
719  while (TRUE)
720  {
721    /* Get 8 bytes from buffer */
722    if (num_blocks > 1)
723    {
724      size = 8;
725      memcpy(input, inptr, size);
726      inptr += 8;
727      num_blocks--;
728    }
729    else if (num_blocks == 1)
730    {
731      size = last_block_size;
732      memcpy(input, inptr, size);
733      num_blocks--;
734    }
735    else
736      size = 0;
737
738    /* Check for EOF and pad the string to 8 chars, if needed */
739    if (size == 0)
740      break;
741    if (size < 8)
742      memset(input + size, 0, 8 - size);
743
744    /* Encrypt and output the block */
745    des_ecb_encrypt(&input, &output, schedule, TRUE);
746    block_to_ascii(output, outfile);
747
748    if (size < 8)
749      break;
750  }
751
752  putc('\n', outfile);
753
754  return TRUE;
755}
756
757int do_encrypt_aes(const char *keyfile, const char *in, int length, FILE *outfile)
758{
759  char *out;
760  int err, status;
761  const char *argv[] = {
762    "gpg",
763    "--symmetric",
764    "--batch",
765    "--quiet",
766    "--no-use-agent",
767    "--armor",
768    "--cipher-algo", "AES",
769    "--passphrase-file", keyfile,
770    NULL
771  };
772  err = call_filter("gpg", argv, in, &out, &status);
773  if(err || status) {
774    g_free(out);
775    return FALSE;
776  }
777  fwrite(out, strlen(out), 1, outfile);
778  g_free(out);
779  return TRUE;
780}
781
782/* Read a half-byte from stdin, skipping invalid characters.  Returns -1
783   if at EOF or file error */
784int read_ascii_nybble(void)
785{
786  char c;
787
788  while (TRUE)
789  {
790    if (fread(&c, 1, 1, stdin) == 0)
791      return -1;
792    else if (c >= BASE_CODE && c <= LAST_CODE)
793      return c - BASE_CODE;
794  }
795}
796
797/* Read both halves of the byte and return the single byte.  Returns -1
798   if at EOF or file error. */
799int read_ascii_byte(void)
800{
801  int c1, c2;
802  c1 = read_ascii_nybble();
803  if (c1 >= 0)
804  {
805    c2 = read_ascii_nybble();
806    if (c2 >= 0)
807    {
808      return c1 * 0x10 + c2;
809    }
810  }
811  return -1;
812}
813
814/* Read an 8-byte DES block from stdin */
815int read_ascii_block(unsigned char *input)
816{
817  int c;
818
819  int i;
820  for (i = 0; i < 8; i++)
821  {
822    c = read_ascii_byte();
823    if (c < 0)
824      return FALSE;
825
826    input[i] = c;
827  }
828
829  return TRUE;
830}
831
832/* Decrypt stdin */
833int do_decrypt(const char *keyfile, int cipher)
834{
835  return ciphers[cipher].decrypt(keyfile);
836}
837
838int do_decrypt_aes(const char *keyfile) {
839  char *in, *out;
840  int length;
841  const char *argv[] = {
842    "gpg",
843    "--decrypt",
844    "--batch",
845    "--no-use-agent",
846    "--quiet",
847    "--passphrase-file", keyfile,
848    NULL
849  };
850  int err, status;
851
852  in = slurp_stdin(TRUE, &length);
853  if(!in) return FALSE;
854
855  err = call_filter("gpg", argv, in, &out, &status);
856  if(err || status) {
857    g_free(out);
858    return FALSE;
859  }
860  fwrite(out, strlen(out), 1, stdout);
861  g_free(out);
862
863  return TRUE;
864}
865
866int do_decrypt_des(const char *keyfile) {
867  des_key_schedule schedule;
868  unsigned char input[8], output[8];
869  char tmp[9];
870  char *keystring;
871
872  /*
873    DES decrypts 8 bytes at a time. We copy those over into the 9-byte
874    'tmp', which has the final byte zeroed, to ensure that we always
875    have a NULL-terminated string we can call printf/strlen on.
876
877    We don't pass 'tmp' to des_ecb_encrypt directly, because it's
878    prototyped as taking 'unsigned char[8]', and this avoids a stupid
879    cast.
880
881    We zero 'tmp' entirely, not just the final byte, in case there are
882    no input blocks.
883  */
884  memset(tmp, 0, sizeof tmp);
885
886  keystring = read_keystring(keyfile);
887  if(!keystring) return FALSE;
888
889  owl_zcrypt_string_to_schedule(keystring, &schedule);
890
891  free(keystring);
892
893  while (read_ascii_block(input))
894  {
895    des_ecb_encrypt(&input, &output, schedule, FALSE);
896    memcpy(tmp, output, 8);
897    printf("%s", tmp);
898  }
899
900  if (!tmp[0] || tmp[strlen(tmp) - 1] != '\n')
901      printf("\n");
902  return TRUE;
903}
Note: See TracBrowser for help on using the repository browser.