source: zcrypt.c @ 4fd211f

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