source: zcrypt.c @ 6425d43

release-1.10release-1.7release-1.8release-1.9
Last change on this file since 6425d43 was 3c2c7fc, checked in by Nelson Elhage <nelhage@mit.edu>, 14 years ago
zcrypt.c: Clean up some clang-detected warnings.
  • Property mode set to 100644
File size: 20.6 KB
RevLine 
[edae037]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>
[6b1c3b6]10
[edae037]11#include <unistd.h>
12#include <sys/types.h>
13#include <zephyr/zephyr.h>
[6b1c3b6]14#include <glib.h>
[356465e]15#include <string.h>
16#include <stdlib.h>
17#include <sys/wait.h>
[8bd190d]18#include <ctype.h>
[edae037]19
[b094191]20#include "config.h"
21
[49bc81e]22#ifdef HAVE_KERBEROS_IV
23#include <kerberosIV/des.h>
24#else
25#include <openssl/des.h>
26#endif
27
[8bd190d]28#include "filterproc.h"
29
30#define MAX_KEY      128
31#define MAX_LINE     128
32#define MAX_RESULT   4096
[edae037]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  char *signature;
53  char *message;
54} ZWRITEOPTIONS;
55
[e832a52]56char *GetZephyrVarKeyFile(const char *whoami, const char *class, const char *instance);
57int ParseCryptSpec(const char *spec, const char **keyfile);
[edae037]58char *BuildArgString(char **argv, int start, int end);
[e832a52]59char *read_keystring(const char *keyfile);
[8bd190d]60
[e832a52]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);
[8bd190d]65
[e832a52]66int do_decrypt(const char *keyfile, int cipher);
67int do_decrypt_aes(const char *keyfile);
68int do_decrypt_des(const char *keyfile);
[8bd190d]69
[edae037]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
[6d7f2a8]78enum cipher_algo {
79  CIPHER_DES,
80  CIPHER_AES,
81  NCIPHER
82};
83
84typedef struct {
[e832a52]85  int (*encrypt)(const char *keyfile, const char *in, int len, FILE *out);
86  int (*decrypt)(const char *keyfile);
[6d7f2a8]87} cipher_pair;
88
89cipher_pair ciphers[NCIPHER] = {
[3c2c7fc]90  [CIPHER_DES] = { do_encrypt_des, do_decrypt_des},
91  [CIPHER_AES] = { do_encrypt_aes, do_decrypt_aes},
[6d7f2a8]92};
[9a4077c]93
[c836519]94static void owl_zcrypt_string_to_schedule(char *keystring, des_key_schedule *schedule) {
[356465e]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);
[c836519]102  des_key_sched(key, *schedule);
[356465e]103}
104
105int main(int argc, char *argv[])
[edae037]106{
[9a4077c]107  char *cryptspec = NULL;
[e832a52]108  const char *keyfile;
[9a4077c]109  int cipher;
[edae037]110  int error = FALSE;
111  int zephyr = FALSE;
112  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;
[f7f35c0]128        break;
[edae037]129      case 'D':
130        /* Decrypt */
[f7f35c0]131        mode = M_DECRYPT;
132        break;
[edae037]133      case 'E':
[f7f35c0]134        /* Encrypt */
135        mode = M_ENCRYPT;
136        break;
[edae037]137      case 'R':
[f7f35c0]138        /* Randomize the keyfile */
139        mode = M_RANDOMIZE;
140        break;
[edae037]141      case 'S':
[f7f35c0]142        /* Set a new key value from stdin */
143        mode = M_SETKEY;
144        break;
[edae037]145      case 'F':
[f7f35c0]146        /* Specify the keyfile explicitly */
[9a4077c]147        if (cryptspec != NULL) error = TRUE;
148        cryptspec = optarg;
[f7f35c0]149        break;
[edae037]150      case 'c':
[f7f35c0]151        /* Zwrite/zcrypt: class name */
152        if (class != NULL) error = TRUE;
153        class = optarg;
154        break;
[edae037]155      case 'i':
[f7f35c0]156        /* Zwrite/zcrypt: instance name */
157        if (instance != NULL) error = TRUE;
158        instance = optarg;
159        break;
[edae037]160      case 'a':
[f7f35c0]161        /* Zwrite: authenticate (default) */
162        zoptions.flags &= ~ZWRITE_OPT_NOAUTH;
163        break;
[edae037]164      case 'd':
[f7f35c0]165        /* Zwrite: do not authenticate */
166        zoptions.flags |= ZWRITE_OPT_NOAUTH;
167        break;
[edae037]168      case 'v':
[f7f35c0]169        /* Zwrite: verbose */
170        zoptions.flags |= ZWRITE_OPT_VERBOSE;
171        break;
[edae037]172      case 'q':
[f7f35c0]173        /* Zwrite: quiet */
174        zoptions.flags |= ZWRITE_OPT_QUIET;
175        break;
[edae037]176      case 't':
[f7f35c0]177        /* Zwrite: no expand tabs (ignored) */
178        break;
[edae037]179      case 'l':
[f7f35c0]180        /* Zwrite: ignore '.' on a line by itself (ignored) */
181        zoptions.flags |= ZCRYPT_OPT_IGNOREDOT;
182        break;
[edae037]183      case 'u':
[f7f35c0]184        /* Zwrite: urgent message */
185        instance = "URGENT";
186        break;
[edae037]187      case 'o':
[f7f35c0]188        /* Zwrite: ignore zephyr variables zwrite-class, zwrite-inst, */
189        /*         zwrite-opcode */
190        zoptions.flags |= ZWRITE_OPT_IGNOREVARS;
191        break;
[edae037]192      case 'n':
[f7f35c0]193        /* Zwrite: prevent PING message (always used) */
194        break;
[edae037]195      case 's':
[f7f35c0]196        /* Zwrite: signature */
197        zoptions.flags |= ZWRITE_OPT_SIGNATURE;
198        zoptions.signature = optarg;
199        break;
[edae037]200      case 'f':
[f7f35c0]201        /* Zwrite: file system specification (ignored) */
202        break;
[edae037]203      case 'm':
[f7f35c0]204        /* Message on rest of line*/
205        messageflag = TRUE;
206        break;
[edae037]207      case '?':
[f7f35c0]208        error = TRUE;
209        break;
[edae037]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    {
[a08bfc3]224      fprintf(stderr, "Memory allocation error.\n");
[edae037]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
[9a4077c]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
[7ba7d66]254  if (error || !cryptspec)
[edae037]255  {
[a08bfc3]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");
[4133e34]259    exit(1);
260  }
[9a4077c]261
262  cipher = ParseCryptSpec(cryptspec, &keyfile);
263  if(cipher < 0) {
264    fprintf(stderr, "Invalid cipher specification: %s\n", cryptspec);
[4133e34]265    exit(1);
[edae037]266  }
[9a4077c]267
268
269  if (mode == M_RANDOMIZE)
[edae037]270  {
[9a4077c]271    /* Choose a new, random key */
272    /*
[edae037]273      FILE *fkey = fopen(fname, "w");
274      if (!fkey)
[9a4077c]275      printf("Could not open key file for writing: %s\n", fname);
[edae037]276      else
277      {
[9a4077c]278      char string[100];
279      fputs(fkey, string);
280      fclose(fkey);
[356465e]281      }
[9a4077c]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;
[edae037]290
[9a4077c]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;
[edae037]299    }
[9a4077c]300
301    fkey = fopen(keyfile, "w");
302    if (!fkey)
303      fprintf(stderr, "Could not open key file for writing: %s\n", keyfile);
[edae037]304    else
305    {
[9a4077c]306      if (fputs(newkey, fkey) != strlen(newkey) || putc('\n', fkey) != '\n')
307      {
308        fprintf(stderr, "Error writing to key file.\n");
309        fclose(fkey);
[4133e34]310        exit(1);
311      }
[edae037]312      else
313      {
[f7f35c0]314        fclose(fkey);
[9a4077c]315        fprintf(stderr, "Key update complete.\n");
[edae037]316      }
317    }
318  }
[9a4077c]319  else
320  {
321    if (mode == M_ZEPHYR_ENCRYPT || mode == M_ENCRYPT)
[8bd190d]322      error = !do_encrypt((mode == M_ZEPHYR_ENCRYPT), class, instance,
323                          &zoptions, keyfile, cipher);
[9a4077c]324    else
[8bd190d]325      error = !do_decrypt(keyfile, cipher);
[9a4077c]326  }
[edae037]327
328  /* Always print the **END** message if -D is specified. */
329  if (mode == M_DECRYPT)
330    printf("**END**\n");
[8bd190d]331
332  return error;
[edae037]333}
334
[e832a52]335int ParseCryptSpec(const char *spec, const char **keyfile) {
[8bd190d]336  int cipher = CIPHER_DES;
337  char *cipher_name = strdup(spec);
338  char *colon = strchr(cipher_name, ':');
339
[9a4077c]340  *keyfile = spec;
[8bd190d]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;
[9a4077c]363}
364
[edae037]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)
[f7f35c0]391        *ptr++ = ' ';
[edae037]392      /* Copy argv[i], leaving ptr pointing to the '\0' copied from temp */
[356465e]393      while ((*ptr = *temp++))
[f7f35c0]394        ptr++;
[edae037]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 */
[e832a52]404char *GetZephyrVarKeyFile(const char *whoami, const char *class, const char *instance)
[edae037]405{
[356465e]406  char *keyfile = NULL;
[6b1c3b6]407  char *varname[MAX_SEARCH];
[edae037]408  int length[MAX_SEARCH], i;
409  char buffer[MAX_BUFF];
[6b1c3b6]410  char *filename;
[edae037]411  char result[MAX_SEARCH][MAX_BUFF];
412  int numsearch = 0;
413  FILE *fsearch;
414
[6b1c3b6]415  memset(varname, 0, sizeof(varname));
416
[edae037]417  /* Determine names to look for in .crypt-table */
418  if (instance)
[6b1c3b6]419    varname[numsearch++] = g_strdup_printf("crypt-%s-%s:", (class?class:"message"), instance);
[edae037]420  if (class)
[6b1c3b6]421    varname[numsearch++] = g_strdup_printf("crypt-%s:", class);
422  varname[numsearch++] = g_strdup("crypt-default:");
[edae037]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 */
[6b1c3b6]432  filename = g_strdup_printf("%s/.crypt-table", getenv("HOME"));
[edae037]433  fsearch = fopen(filename, "r");
434  if (fsearch)
435  {
436    /* Scan file for a match */
437    while (!feof(fsearch))
438    {
[356465e]439      if (!fgets(buffer, MAX_BUFF - 3, fsearch)) break;
[edae037]440      for (i = 0; i < numsearch; i++)
[f7f35c0]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        }
[edae037]451    }
452
453    /* Pick the "best" match found */
454    keyfile = NULL;
455    for (i = 0; i < numsearch; i++)
456      if (*result[i])
457      {
[f7f35c0]458        keyfile = result[i];
459        break;
[edae037]460      }
461
[9a4077c]462    if (keyfile != NULL)
[edae037]463    {
464      /* Prepare result to be returned */
465      char *temp = keyfile;
466      keyfile = (char *)malloc(strlen(temp) + 1);
467      if (keyfile)
[f7f35c0]468        strcpy(keyfile, temp);
[edae037]469      else
[f7f35c0]470        fprintf(stderr, "Memory allocation error.\n");
[edae037]471    }
472    fclose(fsearch);
473  }
474  else
[a08bfc3]475    fprintf(stderr, "Could not open key table file: %s\n", filename);
[edae037]476
[6b1c3b6]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
[edae037]487  return keyfile;
488}
489
490static pid_t zephyrpipe_pid = 0;
491
492/* Open a pipe to zwrite */
[e832a52]493FILE *GetZephyrPipe(const char *class, const char *instance, const ZWRITEOPTIONS *zoptions)
[edae037]494{
495  int fildes[2];
496  pid_t pid;
497  FILE *result;
[e832a52]498  const char *argv[20];
[356465e]499  int argc = 0;
[edae037]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)
[f7f35c0]545        exit(0);
[edae037]546      close(fildes[0]);
547    }
548    close(fildes[0]);
[e832a52]549    execvp(argv[0], (char **)argv);
[a08bfc3]550    fprintf(stderr, "Exec error: could not run zwrite\n");
[edae037]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 */
[356465e]565void CloseZephyrPipe(FILE *pipe)
[edae037]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
[356465e]576void block_to_ascii(unsigned char *output, FILE *outfile)
[edae037]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
[8bd190d]586char *slurp_stdin(int ignoredot, int *length) {
[9a4077c]587  char *buf;
588  char *inptr;
[edae037]589
[8bd190d]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
[9a4077c]621  if (zoptions->flags & ZCRYPT_OPT_MESSAGE)
[edae037]622  {
[9a4077c]623    /* Use the -m message */
624    buf = strdup(zoptions->message);
625    *length = strlen(buf);
626  }
627  else
628  {
629    if (isatty(0)) {
[edae037]630      /* tty input, so show the "Type your message now..." message */
631      if (zoptions->flags & ZCRYPT_OPT_IGNOREDOT)
[f7f35c0]632        printf("Type your message now.  End with the end-of-file character.\n");
[edae037]633      else
[f7f35c0]634        printf("Type your message now.  End with control-D or a dot on a line by itself.\n");
[9a4077c]635    } else {
636      zoptions->flags |= ZCRYPT_OPT_IGNOREDOT;
637    }
638
[8bd190d]639    buf = slurp_stdin(zoptions->flags & ZCRYPT_OPT_IGNOREDOT, length);
[9a4077c]640  }
641  return buf;
642}
643
[e832a52]644char *read_keystring(const char *keyfile) {
[9a4077c]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. */
[e832a52]663int do_encrypt(int zephyr, const char *class, const char *instance,
664               ZWRITEOPTIONS *zoptions, const char *keyfile, int cipher)
[9a4077c]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  }
[edae037]677
[9a4077c]678  if (zephyr) {
[edae037]679    outfile = GetZephyrPipe(class, instance, zoptions);
680    if (!outfile)
681    {
[a08bfc3]682      fprintf(stderr, "Could not run zwrite\n");
[9a4077c]683      if (inbuff)
[f7f35c0]684        free(inbuff);
[edae037]685      return FALSE;
686    }
687  }
688
[6d7f2a8]689  out = ciphers[cipher].encrypt(keyfile, inbuff, buflen, outfile);
[9a4077c]690
691  if (zephyr)
692    CloseZephyrPipe(outfile);
693
694  free(inbuff);
695  return out;
696}
697
[e832a52]698int do_encrypt_des(const char *keyfile, const char *in, int length, FILE *outfile)
[9a4077c]699{
700  des_key_schedule schedule;
701  unsigned char input[8], output[8];
[e832a52]702  const char *inptr;
[9a4077c]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
[c836519]712  owl_zcrypt_string_to_schedule(keystring, &schedule);
[9a4077c]713  free(keystring);
714
715  inptr = in;
716  num_blocks = (length + 7) / 8;
717  last_block_size = ((length + 7) % 8) + 1;
[edae037]718
719  /* Encrypt the input (inbuff or stdin) and send it to outfile */
720  while (TRUE)
721  {
[9a4077c]722    /* Get 8 bytes from buffer */
723    if (num_blocks > 1)
[edae037]724    {
[9a4077c]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--;
[edae037]735    }
736    else
[9a4077c]737      size = 0;
[edae037]738
739    /* Check for EOF and pad the string to 8 chars, if needed */
740    if (size == 0)
[9a4077c]741      break;
[edae037]742    if (size < 8)
743      memset(input + size, 0, 8 - size);
744
745    /* Encrypt and output the block */
[356465e]746    des_ecb_encrypt(&input, &output, schedule, TRUE);
[edae037]747    block_to_ascii(output, outfile);
748
749    if (size < 8)
750      break;
751  }
752
[9a4077c]753  putc('\n', outfile);
[edae037]754
[9a4077c]755  return TRUE;
[edae037]756}
757
[e832a52]758int do_encrypt_aes(const char *keyfile, const char *in, int length, FILE *outfile)
[8bd190d]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
[edae037]783/* Read a half-byte from stdin, skipping invalid characters.  Returns -1
784   if at EOF or file error */
[356465e]785int read_ascii_nybble(void)
[edae037]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. */
[356465e]800int read_ascii_byte(void)
[edae037]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 */
[356465e]816int read_ascii_block(unsigned char *input)
[edae037]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 */
[e832a52]834int do_decrypt(const char *keyfile, int cipher)
[edae037]835{
[6d7f2a8]836  return ciphers[cipher].decrypt(keyfile);
[8bd190d]837}
838
[e832a52]839int do_decrypt_aes(const char *keyfile) {
[8bd190d]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
[e832a52]867int do_decrypt_des(const char *keyfile) {
[edae037]868  des_key_schedule schedule;
[356465e]869  unsigned char input[8], output[8];
[60fcd71]870  char tmp[9];
[8bd190d]871  char *keystring;
[edae037]872
[60fcd71]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);
[edae037]886
[8bd190d]887  keystring = read_keystring(keyfile);
888  if(!keystring) return FALSE;
889
[c836519]890  owl_zcrypt_string_to_schedule(keystring, &schedule);
[edae037]891
[8bd190d]892  free(keystring);
893
[edae037]894  while (read_ascii_block(input))
895  {
[356465e]896    des_ecb_encrypt(&input, &output, schedule, FALSE);
[60fcd71]897    memcpy(tmp, output, 8);
898    printf("%s", tmp);
[edae037]899  }
900
[60fcd71]901  if (!tmp[0] || tmp[strlen(tmp) - 1] != '\n')
[edae037]902      printf("\n");
[9a4077c]903  return TRUE;
[edae037]904}
Note: See TracBrowser for help on using the repository browser.