home *** CD-ROM | disk | FTP | other *** search
/ RISC DISC 2 / RISC_DISC_2.iso / pd_share / utilities / cli / pgp2 / src / c / armor next >
Encoding:
Text File  |  1995-06-06  |  32.5 KB  |  1,226 lines

  1. /*      armor.c  - ASCII/binary encoding/decoding based partly on
  2.    PEM RFC1113 and MIME standards.
  3.    PGP: Pretty Good(tm) Privacy - public key cryptography for the masses.
  4.  
  5.    (c) Copyright 1990-1994 by Philip Zimmermann.  All rights reserved.
  6.    The author assumes no liability for damages resulting from the use
  7.    of this software, even if the damage results from defects in this
  8.    software.  No warranty is expressed or implied.
  9.  
  10.    Note that while most PGP source modules bear Philip Zimmermann's
  11.    copyright notice, many of them have been revised or entirely written
  12.    by contributors who frequently failed to put their names in their
  13.    code.  Code that has been incorporated into PGP from other authors
  14.    was either originally published in the public domain or is used with
  15.    permission from the various authors.
  16.  
  17.    PGP is available for free to the public under certain restrictions.
  18.    See the PGP User's Guide (included in the release package) for
  19.    important information about licensing, patent restrictions on
  20.    certain algorithms, trademarks, copyrights, and export controls.
  21.  */
  22. #include <ctype.h>
  23. #include <stdio.h>
  24. #include <string.h>
  25. #include "mpilib.h"
  26. #include "fileio.h"
  27. #include "mpiio.h"
  28. #include "language.h"
  29. #include "pgp.h"
  30. #include "crypto.h"
  31. #include "armor.h"
  32.  
  33. static int darmor_file(char *infile, char *outfile);
  34. /* Seems not to exist -- GJM
  35. static crcword crchware(byte ch, crcword poly, crcword accum);
  36. */
  37. static int armordecode(FILE * in, FILE * out, int *warned);
  38. static void mk_crctbl(crcword poly);
  39. static boolean is_armorfile(char *infile);
  40.  
  41. /*      Begin ASCII armor routines.
  42.    This converts a binary file into printable ASCII characters, in a
  43.    radix-64 form mostly compatible with the MIME format.
  44.    This makes it easier to send encrypted files over a 7-bit channel.
  45.  */
  46.  
  47. /* Index this array by a 6 bit value to get the character corresponding
  48.  * to that value.
  49.  */
  50. static
  51. unsigned char bintoasc[] =
  52.     "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  53.  
  54. /* Index this array by a 7 bit value to get the 6-bit binary field
  55.  * corresponding to that value.  Any illegal characters return high bit set.
  56.  */
  57. static
  58. unsigned char asctobin[] =
  59. {
  60.     0200, 0200, 0200, 0200, 0200, 0200, 0200, 0200,
  61.     0200, 0200, 0200, 0200, 0200, 0200, 0200, 0200,
  62.     0200, 0200, 0200, 0200, 0200, 0200, 0200, 0200,
  63.     0200, 0200, 0200, 0200, 0200, 0200, 0200, 0200,
  64.     0200, 0200, 0200, 0200, 0200, 0200, 0200, 0200,
  65.     0200, 0200, 0200, 0076, 0200, 0200, 0200, 0077,
  66.     0064, 0065, 0066, 0067, 0070, 0071, 0072, 0073,
  67.     0074, 0075, 0200, 0200, 0200, 0200, 0200, 0200,
  68.     0200, 0000, 0001, 0002, 0003, 0004, 0005, 0006,
  69.     0007, 0010, 0011, 0012, 0013, 0014, 0015, 0016,
  70.     0017, 0020, 0021, 0022, 0023, 0024, 0025, 0026,
  71.     0027, 0030, 0031, 0200, 0200, 0200, 0200, 0200,
  72.     0200, 0032, 0033, 0034, 0035, 0036, 0037, 0040,
  73.     0041, 0042, 0043, 0044, 0045, 0046, 0047, 0050,
  74.     0051, 0052, 0053, 0054, 0055, 0056, 0057, 0060,
  75.     0061, 0062, 0063, 0200, 0200, 0200, 0200, 0200
  76. };
  77.  
  78. /* Current line number for mult decodes */
  79. static long infile_line;
  80.  
  81. /************************************************************************/
  82.  
  83. /* CRC Routines. */
  84. /*      These CRC functions are derived from code in chapter 19 of the book
  85.  *    "C Programmer's Guide to Serial Communications", by Joe Campbell.
  86.  *      Generalized to any CRC width by Philip Zimmermann.
  87.  */
  88.  
  89. #define byte unsigned char
  90.  
  91. #define CRCBITS 24        /* may be 16, 24, or 32 */
  92. /* #define maskcrc(crc) ((crcword)(crc)) *//* if CRCBITS is 16 or 32 */
  93. #define maskcrc(crc) ((crc) & 0xffffffL)    /* if CRCBITS is 24 */
  94. #define CRCHIBIT ((crcword) (1L<<(CRCBITS-1)))    /* 0x8000 if CRCBITS is 16 */
  95. #define CRCSHIFTS (CRCBITS-8)
  96.  
  97. /*
  98.  * Notes on making a good 24-bit CRC--
  99.  * The primitive irreducible polynomial of degree 23 over GF(2),
  100.  * 040435651 (octal), comes from Appendix C of "Error Correcting Codes,
  101.  * 2nd edition" by Peterson and Weldon, page 490.  This polynomial was
  102.  * chosen for its uniform density of ones and zeros, which has better
  103.  * error detection properties than polynomials with a minimal number of
  104.  * nonzero terms.  Multiplying this primitive degree-23 polynomial by
  105.  * the polynomial x+1 yields the additional property of detecting any
  106.  * odd number of bits in error, which means it adds parity.  This
  107.  * approach was recommended by Neal Glover.
  108.  *
  109.  * To multiply the polynomial 040435651 by x+1, shift it left 1 bit and
  110.  * bitwise add (xor) the unshifted version back in.  Dropping the unused
  111.  * upper bit (bit 24) produces a CRC-24 generator bitmask of 041446373
  112.  * octal, or 0x864cfb hex.
  113.  *
  114.  * You can detect spurious leading zeros or framing errors in the
  115.  * message by initializing the CRC accumulator to some agreed-upon
  116.  * nonzero value, but the value used is a bit nonstandard.
  117.  */
  118.  
  119. #define CCITTCRC 0x1021        /* CCITT's 16-bit CRC generator polynomial */
  120. #define PRZCRC 0x864cfbL    /* PRZ's 24-bit CRC generator polynomial */
  121. #define CRCINIT 0xB704CEL    /* Init value for CRC accumulator */
  122.  
  123. static crcword crctable[256];    /* Table for speeding up CRC's */
  124.  
  125. /*
  126.  * mk_crctbl derives a CRC lookup table from the CRC polynomial.
  127.  * The table is used later by the crcbytes function given below.
  128.  * mk_crctbl only needs to be called once at the dawn of time.
  129.  *
  130.  * The theory behind mk_crctbl is that table[i] is initialized
  131.  * with the CRC of i, and this is related to the CRC of i>>1,
  132.  * so the CRC of i>>1 (pointed to by p) can be used to derive
  133.  * the CRC of i (pointed to by q).
  134.  */
  135. static void
  136. mk_crctbl(crcword poly)
  137. {
  138.     int i;
  139.     crcword t, *p, *q;
  140.     p = q = crctable;
  141.     *q++ = 0;
  142.     *q++ = poly;
  143.     for (i = 1; i < 128; i++) {
  144.     t = *++p;
  145.     if (t & CRCHIBIT) {
  146.         t <<= 1;
  147.         *q++ = t ^ poly;
  148.         *q++ = t;
  149.     } else {
  150.         t <<= 1;
  151.         *q++ = t;
  152.         *q++ = t ^ poly;
  153.     }
  154.     }
  155. }
  156.  
  157. /*
  158.  * Accumulate a buffer's worth of bytes into a CRC accumulator,
  159.  * returning the new CRC value.
  160.  */
  161. crcword
  162. crcbytes(byte * buf, unsigned len, register crcword accum)
  163. {
  164.     do {
  165.     accum = accum << 8 ^ crctable[(byte) (accum >> CRCSHIFTS) ^ *buf++];
  166.     } while (--len);
  167.     return maskcrc(accum);
  168. }                /* crcbytes */
  169.  
  170. /* Initialize the CRC table using our codes */
  171. void
  172. init_crc(void)
  173. {
  174.     mk_crctbl(PRZCRC);
  175. }
  176.  
  177.  
  178. /************************************************************************/
  179.  
  180.  
  181. /* ENC is the basic 1 character encoding function to make a char printing */
  182. #define ENC(c) ((int)bintoasc[((c) & 077)])
  183. #define PAD        '='
  184.  
  185. /*
  186.  * output one group of up to 3 bytes, pointed at by p, on file f.
  187.  * if fewer than 3 are present, the 1 or two extras must be zeros.
  188.  */
  189. static void
  190. outdec(char *p, FILE *f, int count)
  191. {
  192.     int c1, c2, c3, c4;
  193.  
  194.     c1 = *p >> 2;
  195.     c2 = ((*p << 4) & 060) | ((p[1] >> 4) & 017);
  196.     c3 = ((p[1] << 2) & 074) | ((p[2] >> 6) & 03);
  197.     c4 = p[2] & 077;
  198.     putc(ENC(c1), f);
  199.     putc(ENC(c2), f);
  200.     if (count == 1) {
  201.     putc(PAD, f);
  202.     putc(PAD, f);
  203.     } else {
  204.     putc(ENC(c3), f);
  205.     if (count == 2)
  206.         putc(PAD, f);
  207.     else
  208.         putc(ENC(c4), f);
  209.     }
  210. }                /* outdec */
  211.  
  212.  
  213. /* Output the CRC value, MSB first per normal CRC conventions */
  214. static void
  215. outcrc(word32 crc, FILE *outFile)
  216. {
  217.     char crcbuf[4];
  218.     crcbuf[0] = (crc >> 16) & 0xff;
  219.     crcbuf[1] = (crc >> 8) & 0xff;
  220.     crcbuf[2] = (crc >> 0) & 0xff;
  221.     putc(PAD, outFile);
  222.     outdec(crcbuf, outFile, 3);
  223.     putc('\n', outFile);
  224. }                /* outcrc */
  225.  
  226. /* Return filename for output (text mode), but replace last letter(s) of
  227.  * filename with the ascii for num.  It will use the appropriate number
  228.  * of digits for ofnum when converting num, so if ofnum < 10, use 1 digit,
  229.  * >= 10 and < 100 use 2 digits, >= 100 and < 1000 use 3 digits.  If its
  230.  * >= 1000, then we have other problems to worry about, and this might do
  231.  * weird things.
  232.  */
  233. static char *
  234. numFilename(char *fname, int num, int ofnum)
  235. {
  236.     static char fnamenum[MAX_PATH];
  237.     int len;
  238.     int offset = 1;
  239.  
  240.     strcpy(fnamenum, fname);
  241.     len = strlen(fnamenum);
  242.     do {
  243.     fnamenum[len - offset] = '0' + (num % 10);
  244.     num /= 10;
  245.     ofnum /= 10;
  246.     offset++;
  247.     } while (ofnum >= 1 && offset < 4);
  248.     return fnamenum;
  249. }
  250.  
  251. /*
  252.  * Reads and discards a line from the given file.  Returns -1 on error or
  253.  * EOF, 0 if the line is blank, and 1 if the line is not blank.
  254.  */
  255. static int
  256. skipline(FILE * f)
  257. {
  258.     int state, flag, c;
  259.  
  260.     state = 0;
  261.     flag = 0;
  262.     for (;;) {
  263.     c = getc(f);
  264.     if (c == '\n')
  265.         return flag;
  266.     if (state) {
  267.         ungetc(c, f);
  268.         return flag;
  269.     }
  270.     if (c == EOF)
  271.         return -1;
  272.     if (c == '\r')
  273.         state = 1;
  274.     else if (c != ' ')
  275.         flag = 1;
  276.     }
  277. }                /* skipline */
  278.  
  279.  
  280. /*
  281.  * Copies a line from the input file to the output.  Does NOT copy the
  282.  * trailing newline.  Returns -1 on EOF or error, 0 if the line was terminated
  283.  * by EOF, and 1 if the line was terminated with a newline sequence.
  284.  */
  285. static int
  286. copyline(FILE * in, FILE * out)
  287. {
  288.     int state, flag, c;
  289.  
  290.     state = 0;
  291.     for (;;) {
  292.     c = getc(in);
  293.     if (c == '\n')
  294.         return 1;
  295.     if (state) {
  296.         ungetc(c, in);
  297.         return 1;
  298.     }
  299.     if (c == EOF)
  300.         return 0;
  301.     if (c == '\r')
  302.         state = 1;
  303.     else
  304.         putc(c, out);
  305.     }
  306. }                /* copyline */
  307.  
  308. /*
  309.  * Reads a line from file f, up to the size of the buffer.  The line in the
  310.  * buffer will NOT include line termination, although any of (CR, LF, CRLF)
  311.  * is accepted on input.  The return value is -1 on error, 0 if the line
  312.  * was terminated abnormally (EOF, error, or out of buffer space), and
  313.  * 1 if the line was terminated normally.
  314.  *
  315.  * Passing in a buffer less than 2 characters long is not a terribly bright
  316.  * idea.
  317.  */
  318. static int
  319. getline(char *buf, int n, FILE * f)
  320. {
  321.     int state;
  322.     char *p;
  323.     int c;
  324.  
  325.     state = 0;
  326.     p = buf;
  327.     for (;;) {
  328.     c = getc(f);
  329.     if (c == '\n') {
  330.         *p = 0;
  331.         return 1;        /* Line terminated with \n or \r\n */
  332.     }
  333.     if (state) {
  334.         ungetc(c, f);
  335.         *p = 0;
  336.         return 1;        /* Line terminated with \r */
  337.     }
  338.     if (c == EOF) {
  339.         *p = 0;
  340.         return (p == buf) ? -1 : 0;        /* Error */
  341.     }
  342.     if (c == '\r')
  343.         state = 1;
  344.     else if (--n > 0) {
  345.         *p++ = c;
  346.     } else {
  347.         ungetc(c, f);
  348.         *p = 0;
  349.         return 0;        /* Out of buffer space */
  350.     }
  351.     }                /* for (;;) */
  352. }                /* getline */
  353.  
  354. #if 1
  355. /* This limit is advisory only; longer lines are handled properly.
  356.  * The only requirement is that this be at least as long as the longest
  357.  * delimiter string used by PGP
  358.  * (e.g. "-----BEGIN PGP MESSAGE, PART %02d/%02d-----\n")
  359.  */
  360. #define MAX_LINE_SIZE 80
  361. #else
  362. #ifdef MSDOS            /* limited stack space */
  363. #define MAX_LINE_SIZE    256
  364. #else
  365. #define MAX_LINE_SIZE    1024
  366. #endif
  367. #endif
  368.  
  369. /*
  370.  * Read a line from file f, buf must be able to hold at least MAX_LINE_SIZE
  371.  * characters.  Anything after that is ignored.  Strips trailing spaces and
  372.  * line terminator, can read LF, CRLF and CR textfiles.  It can't be ASCII
  373.  * armor anyway.
  374.  */
  375. static char *
  376. get_armor_line(char *buf, FILE * f)
  377. {
  378.     int c, n = MAX_LINE_SIZE-1;
  379.     char *p = buf;
  380.  
  381.     do {
  382.     c = getc(f);
  383.     if (c == '\n' || c == '\r' || c == EOF)
  384.         break;
  385.     *p++ = c;
  386.     } while (--n > 0);
  387.     if (p == buf && c == EOF) {
  388.     *buf = '\0';
  389.     return NULL;
  390.     }
  391.     /*
  392.      * Skip to end of line, setting n to non-zero if anything trailing is
  393.      * not a space (meaning that any trailing whitespace in the buffer is
  394.      * not trailing whitespace on the line and should not be stripped).
  395.      */
  396.     n = 0;
  397.     while (c != '\n' && c != '\r' && c != EOF) {
  398.         n |= c ^ ' ';
  399.     c = getc(f);
  400.     }
  401.     if (c == '\r' && (c = getc(f)) != '\n')
  402.     ungetc(c, f);
  403.     if (!n) {    /* Skip trailing whitespace, as described above */
  404.     while (p >= buf && p[-1] == ' ')
  405.         --p;
  406.     }
  407.     *p = '\0';
  408.     return buf;
  409. }
  410.  
  411.  
  412. /*
  413.  * Encode a file in sections.  64 ASCII bytes * 720 lines = 46K,
  414.  * recommended max.  Usenet message size is 50K so this leaves a nice
  415.  * margin for .signature.  In the interests of orthogonality and
  416.  * programmer laziness no check is made for a message containing only
  417.  * a few lines (or even just an 'end')  after a section break.
  418.  */
  419. #define LINE_LEN    48L
  420. int pem_lines = 720;
  421. #define BYTES_PER_SECTION    (LINE_LEN * pem_lines)
  422.  
  423. #ifndef VMS
  424. /* armored files are opened in binary mode so that CRLF/LF/CR files
  425.    can be handled by all systems */
  426. #define    FOPRARMOR    FOPRBIN
  427. #else
  428. #define    FOPRARMOR    FOPRTXT
  429. #endif
  430.  
  431. extern boolean verbose;        /* Undocumented command mode in PGP.C */
  432. extern boolean filter_mode;
  433.  
  434. /*
  435.  * Copy from infilename to outfilename, ASCII armoring as you go along,
  436.  * and with breaks every pem_lines lines.
  437.  * If clearfilename is non-NULL, first output that file preceded by a
  438.  * special delimiter line.  filename is the original filename, used
  439.  * only for debugging.
  440.  */
  441. int
  442. armor_file(char *infilename, char *outfilename, char *filename,
  443.     char *clearfilename)
  444. {
  445.     char buffer[MAX_LINE_SIZE];
  446.     int i, rc, bytesRead, lines = 0;
  447.     int noSections, currentSection = 1;
  448.     long fileLen;
  449.     crcword crc;
  450.     FILE *inFile, *outFile, *clearFile;
  451.     char *blocktype = "MESSAGE";
  452.  
  453.     if (verbose)
  454.     fprintf(pgpout,
  455. "armor_file: infile = %s, outfile = %s, filename = %s, clearname = %s\n",
  456.         infilename, outfilename, filename, clearfilename);
  457.  
  458.     /* open input file as binary */
  459.     if ((inFile = fopen(infilename, FOPRBIN)) == NULL)
  460.     return 1;
  461.  
  462.     if (!outfilename || pem_lines == 0) {
  463.     noSections = 1;
  464.     } else {
  465.     /* Evaluate how many parts this file will comprise */
  466.     fseek(inFile, 0L, SEEK_END);
  467.     fileLen = ftell(inFile);
  468.     rewind(inFile);
  469.     noSections = (fileLen + BYTES_PER_SECTION - 1) /
  470.         BYTES_PER_SECTION;
  471.     if (noSections > 99) {
  472.         pem_lines = ((fileLen + LINE_LEN - 1) / LINE_LEN + 98) / 99;
  473.         noSections = (fileLen + BYTES_PER_SECTION - 1) /
  474.         BYTES_PER_SECTION;
  475.         fprintf(pgpout,
  476.         "value for \"armorlines\" is too low, using %d\n", pem_lines);
  477.     }
  478.     }
  479.  
  480.     if (outfilename == NULL) {
  481.     outFile = stdout;
  482.     } else {
  483.     if (noSections > 1) {
  484.         force_extension(outfilename, ASC_EXTENSION);
  485.         outFile =
  486.         fopen(numFilename(outfilename, 1, noSections),
  487.               FOPWTXT);
  488.     } else {
  489.         outFile = fopen(outfilename, FOPWTXT);
  490.     }
  491.     }
  492.  
  493.     if (outFile == NULL) {
  494.     fclose(inFile);
  495.     return 1;
  496.     }
  497.     if (clearfilename) {
  498.     if ((clearFile = fopen(clearfilename, FOPRTXT)) == NULL) {
  499.         fclose(inFile);
  500.         if (outFile != stdout)
  501.         fclose(outFile);
  502.         return 1;
  503.     }
  504.     fprintf(outFile, "-----BEGIN PGP SIGNED MESSAGE-----\n\n");
  505.     while ((i = getline(buffer, sizeof buffer, clearFile)) >= 0) {
  506.         /* Quote lines beginning with '-' as per RFC1113;
  507.          * Also quote lines beginning with "From "; this is
  508.          * for Unix mailers which add ">" to such lines.
  509.          */
  510.         if (buffer[0] == '-' || strncmp(buffer, "From ", 5) == 0)
  511.         fputs("- ", outFile);
  512.         fputs(buffer, outFile);
  513.         /* If there is more on this line, copy it */
  514.         if (i == 0)
  515.         if (copyline(clearFile, outFile) <= 0)
  516.             break;
  517.         fputc('\n', outFile);
  518.     }
  519.     fclose(clearFile);
  520.     putc('\n', outFile);
  521.     blocktype = "SIGNATURE";
  522.     }
  523.     if (noSections == 1) {
  524.     byte ctb = 0;
  525.     ctb = getc(inFile);
  526.     if (is_ctb_type(ctb, CTB_CERT_PUBKEY_TYPE))
  527.         blocktype = "PUBLIC KEY BLOCK";
  528.     fprintf(outFile, "-----BEGIN PGP %s-----\n", blocktype);
  529.     rewind(inFile);
  530.     } else {
  531.     fprintf(outFile,
  532.         "-----BEGIN PGP MESSAGE, PART %02d/%02d-----\n",
  533.         1, noSections);
  534.     }
  535.     fprintf(outFile, "Version: %s\n", LANG(rel_version));
  536.     if (globalCommentString[0])
  537.     fprintf(outFile, "Comment: %s\n", globalCommentString);
  538.     fprintf(outFile, "\n");
  539.  
  540.     init_crc();
  541.     crc = CRCINIT;
  542.  
  543.     while ((bytesRead = fread(buffer, 1, LINE_LEN, inFile)) > 0) {
  544.     /* Munge up LINE_LEN characters */
  545.     if (bytesRead < LINE_LEN)
  546.         fill0(buffer + bytesRead, LINE_LEN - bytesRead);
  547.  
  548.     crc = crcbytes((byte *) buffer, bytesRead, crc);
  549.     for (i = 0; i < bytesRead - 3; i += 3)
  550.         outdec(buffer + i, outFile, 3);
  551.     outdec(buffer + i, outFile, bytesRead - i);
  552.     putc('\n', outFile);
  553.  
  554.     if (++lines == pem_lines && currentSection < noSections) {
  555.         lines = 0;
  556.         outcrc(crc, outFile);
  557.         fprintf(outFile,
  558.             "-----END PGP MESSAGE, PART %02d/%02d-----\n\n",
  559.             currentSection, noSections);
  560.         if (write_error(outFile)) {
  561.         fclose(outFile);
  562.         return -1;
  563.         }
  564.         fclose(outFile);
  565.         outFile = fopen(numFilename(outfilename,
  566.                     ++currentSection,
  567.                     noSections), FOPWTXT);
  568.         if (outFile == NULL) {
  569.         fclose(inFile);
  570.         return -1;
  571.         }
  572.         fprintf(outFile,
  573.             "-----BEGIN PGP MESSAGE, PART %02d/%02d-----\n",
  574.             currentSection, noSections);
  575.         fprintf(outFile, "\n");
  576.         crc = CRCINIT;
  577.     }
  578.     }
  579.     outcrc(crc, outFile);
  580.  
  581.     if (noSections == 1)
  582.     fprintf(outFile, "-----END PGP %s-----\n", blocktype);
  583.     else
  584.     fprintf(outFile, "-----END PGP MESSAGE, PART %02d/%02d-----\n",
  585.         noSections, noSections);
  586.  
  587.     /* Done */
  588.     fclose(inFile);
  589.     rc = write_error(outFile);
  590.     if (outFile == stdout)
  591.     return rc;
  592.     fclose(outFile);
  593.  
  594.     if (rc)
  595.     return -1;
  596.  
  597.     if (clearfilename) {
  598.     fprintf(pgpout,
  599.         LANG("\nClear signature file: %s\n"), outfilename);
  600.     } else if (noSections == 1) {
  601.     fprintf(pgpout,
  602.         LANG("\nTransport armor file: %s\n"), outfilename);
  603.     } else {
  604.     fprintf(pgpout, LANG("\nTransport armor files: "));
  605.     for (i = 1; i <= noSections; ++i)
  606.         fprintf(pgpout, "%s%s",
  607.             numFilename(outfilename, i, noSections),
  608.             i == noSections ? "\n" : ", ");
  609.     }
  610.     return 0;
  611. }                /* armor_file */
  612.  
  613. /*      End ASCII armor encode routines. */
  614.  
  615.  
  616. /*
  617.  * ASCII armor decode routines.
  618.  */
  619. static int
  620. darmor_buffer(char *inbuf, char *outbuf, int *outlength)
  621. {
  622.     unsigned char *bp;
  623.     int length;
  624.     unsigned int c1, c2, c3, c4;
  625.     register int j;
  626.  
  627.     length = 0;
  628.     bp = (unsigned char *) inbuf;
  629.  
  630.     /* FOUR input characters go into each THREE output charcters */
  631.  
  632.     while (*bp != '\0') {
  633.     if (*bp & 0x80 || (c1 = asctobin[*bp]) & 0x80)
  634.         return -1;
  635.     ++bp;
  636.     if (*bp & 0x80 || (c2 = asctobin[*bp]) & 0x80)
  637.         return -1;
  638.     if (*++bp == PAD) {
  639.         c3 = c4 = 0;
  640.         length += 1;
  641.         if (c2 & 15)
  642.         return -1;
  643.         if (strcmp((char *) bp, "==") == 0)
  644.         bp += 1;
  645.         else if (strcmp((char *) bp, "=3D=3D") == 0)
  646.         bp += 5;
  647.         else
  648.         return -1;
  649.     } else if (*bp & 0x80 || (c3 = asctobin[*bp]) & 0x80) {
  650.         return -1;
  651.     } else {
  652.         if (*++bp == PAD) {
  653.         c4 = 0;
  654.         length += 2;
  655.         if (c3 & 3)
  656.             return -1;
  657.         if (strcmp((char *) bp, "=") == 0);    /* All is well */
  658.         else if (strcmp((char *) bp, "=3D") == 0)
  659.             bp += 2;
  660.         else
  661.             return -1;
  662.         } else if (*bp & 0x80 || (c4 = asctobin[*bp]) & 0x80) {
  663.         return -1;
  664.         } else {
  665.         length += 3;
  666.         }
  667.     }
  668.     ++bp;
  669.     j = (c1 << 2) | (c2 >> 4);
  670.     *outbuf++ = j;
  671.     j = (c2 << 4) | (c3 >> 2);
  672.     *outbuf++ = j;
  673.     j = (c3 << 6) | c4;
  674.     *outbuf++ = j;
  675.     }
  676.  
  677.     *outlength = length;
  678.     return 0;            /* normal return */
  679.  
  680. }                /* darmor_buffer */
  681.  
  682. static char armorfilename[MAX_PATH];
  683. /*
  684.  * try to open the next file of a multi-part armored file
  685.  * the sequence number is expected at the end of the file name
  686.  */
  687. static FILE *
  688. open_next(void)
  689. {
  690.     char *p, *s, c;
  691.     FILE *fp;
  692.  
  693.     p = armorfilename + strlen(armorfilename);
  694.     while (--p >= armorfilename && isdigit(*p)) {
  695.     if (*p != '9') {
  696.         ++*p;
  697.         return fopen(armorfilename, FOPRARMOR);
  698.     }
  699.     *p = '0';
  700.     }
  701.  
  702.     /* need an extra digit */
  703.     if (p >= armorfilename) {
  704.     /* try replacing character ( .as0 -> .a10 ) */
  705.     c = *p;
  706.     *p = '1';
  707.     if ((fp = fopen(armorfilename, FOPRARMOR)) != NULL)
  708.         return fp;
  709.     *p = c;            /* restore original character */
  710.     }
  711.     ++p;
  712.     for (s = p + strlen(p); s >= p; --s)
  713.     s[1] = *s;
  714.     *p = '1';            /* insert digit ( fn0 -> fn10 ) */
  715.  
  716. #if defined(MSDOS) && !defined(MIT)
  717.     /* if the resulting filename has more than three
  718.        characters after the first dot, don't even try to open it */
  719.     s = strchr(armorfilename, '.');
  720.     if (s != NULL)
  721.        if (strlen(s) > 3)
  722.           return NULL;
  723. #endif /* MSDOS  ... this wasn't a comment before, bletch -- GJM */
  724.  
  725.     return fopen(armorfilename, FOPRARMOR);
  726. }
  727.  
  728. /*
  729.  * Returns -1 if the line given is does not begin as a valid ASCII
  730.  * armor header line (something of the form "Label: ", where "Label"
  731.  * must begin with a letter followed by letters, numbers, or hyphens,
  732.  * followed immediately by a colon and a space), 0 if it is a familiar
  733.  * label, and the length of the label if it is an unfamiliar label
  734.  * (E.g. not "Version" or "Comment");
  735.  */
  736. static int
  737. isheaderline(char const *buf)
  738. {
  739.     int i;
  740.  
  741.     if (!isalpha(*buf))
  742.         return -1;    /* Not a label */
  743.  
  744.     for (i = 1; isalnum(buf[i]) || i == '-'; i++)
  745.         ;
  746.     if (buf[i] != ':' || buf[i+1] != ' ')
  747.         return -1;    /* Not a label */
  748.  
  749.     if (memcmp(buf, "Version", i) == 0 ||
  750.         memcmp(buf, "Comment", i) == 0)
  751.         return 0;    /* Familiar label */
  752.     return i;    /* Unfamiliar label */
  753. }
  754.  
  755. /*
  756.  * Skips a bunch of headers, either returning 0, or printing
  757.  * an error message and returning -1.
  758.  * If it encounters an unfamiliar label and *warned is not set,
  759.  * prints a warning and sets *warned.
  760.  * NOTE that file read errors are NOT printed or reported in the
  761.  * return code.  It is assumed that the following read will
  762.  * notice the error and do something appropriate.
  763.  */
  764. static int
  765. skipheaders(FILE *in, char *buf, int *warned, int armorfollows)
  766. {
  767.     int label_seen = 0;
  768.     int i;
  769. #ifndef STRICT_ARMOR    /* Allow no space */
  770.     long fpos;
  771.     char outbuf[(MAX_LINE_SIZE*3+3)/4];
  772.     int n;
  773. #endif
  774.  
  775.     for (;;) {
  776.     ++infile_line;
  777. #ifndef STRICT_ARMOR
  778.     fpos = ftell(in);
  779. #endif
  780.     if (get_armor_line(buf, in) == NULL)    /* Error */
  781.         return 0;    /* See comment above */
  782.     if (buf[0] == '\0')    /* Blank line */
  783.         return 0;    /* Success */
  784.     if (label_seen && (buf[0] == ' ' || buf[0] == '\t'))
  785.         continue;    /* RFC-822-style continuation line */
  786.     i = isheaderline(buf);
  787.     if (i < 0) {    /* Not a legal header line */
  788. #ifndef STRICT_ARMOR    /* If it's as ASCII armor line, accept it */
  789.         if (armorfollows && darmor_buffer(buf, outbuf, &n) == 0 && n == 48)
  790.         {
  791.         fseek(in, fpos, SEEK_SET);
  792.         --infile_line;
  793.         return 0;    /* Consider this acceptable */
  794.         }
  795. #else
  796.         (void)armorfollows;    /* Stop compiler complaints */
  797. #endif
  798.         fprintf(pgpout,
  799. LANG("Invalid ASCII armor header line: \"%.40s\"\n\
  800. ASCII armor corrupted.\n"), buf);
  801.         return -1;
  802.     }
  803.     if (i > 0 && !*warned) {
  804.         fprintf(pgpout,
  805. LANG("Warning: Unrecognized ASCII armor header label \"%.*s:\" ignored.\n"),
  806.                 i, buf);
  807.         *warned = 1;
  808.     }
  809.     label_seen = 1;    /* Continuation lines are now legal */
  810.     }
  811. }
  812.  
  813. /*
  814.  * Copy from in to out, decoding as you go, with handling for multiple
  815.  * 500-line blocks of encoded data.  This function also knows how to
  816.  * go past the end of one part to the beginning of the next in a multi-part
  817.  * file.  (As you can see from some ugliness below, this is not the best
  818.  * place to do it, since the caller is responsible for closing the
  819.  * "original_in" file.)
  820.  */
  821. static int
  822. armordecode(FILE *original_in, FILE *out, int *warned)
  823. {
  824.     char inbuf[MAX_LINE_SIZE];
  825.     char outbuf[MAX_LINE_SIZE];
  826.  
  827.     int i, n, status;
  828.     int line;
  829.     int section, currentSection = 1;
  830.     int noSections = 0;
  831.     int gotcrc = 0;
  832.     long crc = CRCINIT, chkcrc = -1;
  833.     char crcbuf[4];
  834.     int ret_code = 0;
  835.     int end_of_message;
  836.     FILE *in = original_in;
  837.  
  838.     init_crc();
  839.  
  840.     for (line = 1;; line++) {    /* for each input line */
  841.     if (get_armor_line(inbuf, in) == NULL) {
  842.         end_of_message = 1;
  843.     } else {
  844.         end_of_message =
  845.         (strncmp(inbuf, "-----END PGP MESSAGE,", 21) == 0);
  846.         ++infile_line;
  847.     }
  848.  
  849.     if (currentSection != noSections && end_of_message) {
  850.         /* End of this section */
  851.         if (gotcrc) {
  852.         if (chkcrc != crc) {
  853.             fprintf(pgpout,
  854.  LANG("ERROR: Bad ASCII armor checksum in section %d.\n"), currentSection);
  855. /* continue with decoding to see if there are other bad parts */
  856.             ret_code = -1;
  857.         }
  858.         }
  859.         gotcrc = 0;
  860.         crc = CRCINIT;
  861.         section = 0;
  862.  
  863.         /* Try and find start of next section */
  864.         do {
  865.         if (get_armor_line(inbuf, in) == NULL) {
  866.             if (in != original_in)
  867.             fclose(in);
  868.             if ((in = open_next()) != NULL)
  869.             continue;    /* Keep working on new in */
  870.             fprintf(pgpout,
  871.             LANG("Can't find section %d.\n"), currentSection + 1);
  872.             return -1;
  873.         }
  874.         ++infile_line;
  875.         }
  876.         while (strncmp(inbuf, "-----BEGIN PGP MESSAGE", 22));
  877.  
  878.         /* Make sure this section is the correct one */
  879.         if (2 != sscanf(inbuf,
  880.                 "-----BEGIN PGP MESSAGE, PART %d/%d",
  881.                 §ion, &noSections)) {
  882.         fprintf(pgpout,
  883.             LANG("Badly formed section delimiter, part %d.\n"),
  884.             currentSection + 1);
  885.         goto error;
  886.         }
  887.         if (section != ++currentSection) {
  888.         fprintf(pgpout,
  889. LANG("Sections out of order, expected part %d"), currentSection);
  890.         if (section)
  891.             fprintf(pgpout,
  892.                 LANG(", got part %d\n"), section);
  893.         else
  894.             fputc('\n', pgpout);
  895.         goto error;
  896.         }
  897.         /* Skip header after BEGIN line */
  898.         if (skipheaders(in, inbuf, warned, 1) < 0)
  899.         goto error;
  900.         if (feof(in)) {
  901.         fprintf(pgpout,
  902.            LANG("ERROR: Hit EOF in header of section %d.\n"),
  903.             currentSection);
  904.         goto error;
  905.         }
  906.  
  907.         /* Continue decoding */
  908.         continue;
  909.     }
  910.  
  911. /* Quit when hit the -----END PGP MESSAGE----- line or a blank,
  912.  * or handle checksum
  913.  */
  914.     if (inbuf[0] == PAD) {    /* Checksum lines start
  915.                    with PAD char */
  916.         /* If the already-armored file is sent through MIME
  917.          * and gets armored again, '=' will become '=3D'.
  918.          * To make life easier, we detect and work around this
  919.          * idiosyncracy.
  920.          */
  921.         if (strlen(inbuf) == 7 &&
  922.         inbuf[1] == '3' && inbuf[2] == 'D')
  923.         status = darmor_buffer(inbuf + 3, crcbuf, &n);
  924.         else
  925.         status = darmor_buffer(inbuf + 1, crcbuf, &n);
  926.         if (status < 0 || n != 3) {
  927.         fprintf(pgpout,
  928. LANG("ERROR: Badly formed ASCII armor checksum, line %d.\n"), line);
  929.                 goto error;
  930.         }
  931.         chkcrc = (((long) crcbuf[0] << 16) & 0xff0000L) +
  932.         ((crcbuf[1] << 8) & 0xff00L) + (crcbuf[2] & 0xffL);
  933.         gotcrc = 1;
  934.         continue;
  935.     }
  936.     if (inbuf[0] == '\0') {
  937.         fprintf(pgpout,
  938.             LANG("WARNING: No ASCII armor `END' line.\n"));
  939.         break;
  940.     }
  941.     if (strncmp(inbuf, "-----END PGP ", 13) == 0)
  942.         break;
  943.  
  944.     status = darmor_buffer(inbuf, outbuf, &n);
  945.  
  946.     if (status == -1) {
  947.         fprintf(pgpout,
  948.          LANG("ERROR: Bad ASCII armor character, line %d.\n"), line);
  949.         gotcrc = 1;        /* this will print part number,
  950.                    continue with next part */
  951.         ret_code = -1;
  952.     }
  953.     if (n > sizeof outbuf) {
  954.         fprintf(pgpout,
  955.          LANG("ERROR: Bad ASCII armor line length %d on line %d.\n"),
  956.             n, line);
  957.         goto error;
  958.     }
  959.     crc = crcbytes((byte *) outbuf, n, crc);
  960.     if (fwrite(outbuf, 1, n, out) != n) {
  961.         ret_code = -1;
  962.         break;
  963.     }
  964.     }                /* line */
  965.  
  966.     if (gotcrc) {
  967.     if (chkcrc != crc) {
  968.         fprintf(pgpout,
  969.             LANG("ERROR: Bad ASCII armor checksum"));
  970.         if (noSections > 0)
  971.         fprintf(pgpout,
  972.             LANG(" in section %d"), noSections);
  973.         fputc('\n', pgpout);
  974.         goto error;
  975.     }
  976.     } else {
  977.     fprintf(pgpout,
  978.         LANG("Warning: Transport armor lacks a checksum.\n"));
  979.     }
  980.  
  981.     if (in != original_in)
  982.     fclose(in);
  983.     return ret_code;        /* normal return */
  984. error:
  985.     if (in != original_in)
  986.     fclose(in);
  987.     return -1;            /* error return */
  988. }                /* armordecode */
  989.  
  990. static boolean
  991. is_armorfile(char *infile)
  992. {
  993.     FILE *in;
  994.     char inbuf[MAX_LINE_SIZE];
  995.     char outbuf[MAX_LINE_SIZE];
  996.     int n;
  997.     long il;
  998.  
  999.     in = fopen(infile, FOPRARMOR);
  1000.     if (in == NULL)
  1001.     return FALSE;    /* can't open file */
  1002.  
  1003.     /* Read to infile_line before we begin looking */
  1004.     for (il = 0; il < infile_line; ++il) {
  1005.     if (get_armor_line(inbuf, in) == NULL) {
  1006.         fclose(in);
  1007.         return FALSE;
  1008.     }
  1009.     }
  1010.  
  1011.     /* search file for delimiter line */
  1012.     for (;;) {
  1013.     if (get_armor_line(inbuf, in) == NULL)
  1014.         break;
  1015.     if (strncmp(inbuf, "-----BEGIN PGP ", 15) == 0) {
  1016.         if (strncmp(inbuf,
  1017.             "-----BEGIN PGP SIGNED MESSAGE-----", 34) == 0) {
  1018.         fclose(in);
  1019.         return TRUE;
  1020.         }
  1021.         n = 1;    /* Don't print warnings yet */
  1022.         if (skipheaders(in, inbuf, &n, 1) < 0 ||
  1023.             get_armor_line(inbuf, in) == NULL ||
  1024.             darmor_buffer(inbuf, outbuf, &n) < 0)
  1025.         break;
  1026.         fclose(in);
  1027.         return TRUE;
  1028.     }
  1029.     }
  1030.  
  1031.     fclose(in);
  1032.     return FALSE;
  1033. }                /* is_armorfile */
  1034.  
  1035. static int
  1036. darmor_file(char *infile, char *outfile)
  1037. {
  1038.     FILE *in, *out;
  1039.     char buf[MAX_LINE_SIZE];
  1040.     char outbuf[(MAX_LINE_SIZE*3+3)/4];
  1041.     int status, n;
  1042.     long il, fpos;
  1043.     char *litfile = NULL;
  1044.     int header_warned = 0;    /* Complained about unknown header */
  1045.  
  1046.     if ((in = fopen(infile, FOPRARMOR)) == NULL) {
  1047.     fprintf(pgpout, LANG("ERROR: Can't find file %s\n"), infile);
  1048.     return 10;
  1049.     }
  1050.     strcpy(armorfilename, infile);    /* store filename for multi-parts */
  1051.  
  1052.     /* Skip to infile_line */
  1053.     for (il = 0; il < infile_line; ++il) {
  1054.     if (get_armor_line(buf, in) == NULL) {
  1055.         fclose(in);
  1056.         return -1;
  1057.     }
  1058.     }
  1059.  
  1060.     /* Loop through file, searching for delimiter.  Decode anything with a
  1061.        delimiter, complain if there were no delimiter. */
  1062.  
  1063.     /* search file for delimiter line */
  1064.     for (;;) {
  1065.     ++infile_line;
  1066.     if (get_armor_line(buf, in) == NULL) {
  1067.         fprintf(pgpout,
  1068.             LANG("ERROR: No ASCII armor `BEGIN' line!\n"));
  1069.         fclose(in);
  1070.         return 12;
  1071.     }
  1072.     if (strncmp(buf, "-----BEGIN PGP ", 15) == 0)
  1073.         break;
  1074.     }
  1075.     if (strncmp(buf, "-----BEGIN PGP SIGNED MESSAGE-----", 34) == 0) {
  1076.     FILE *litout;
  1077.     char *canonfile, *p;
  1078.     int nline;
  1079.  
  1080.     /*
  1081.      * It would be nice to allow headers here, as we could add
  1082.      * additional information to PGP messages, but it appears to
  1083.      * be too easy to spoof, given standard text viewers.  So,
  1084.      * forbid it outright until we sit down and figure out how to
  1085.      * thwart all the ways of faking an end-of-headers.  The
  1086.      * possibilities are:
  1087.      * - Enough trailing whitespace on a valid-looking line to force a
  1088.      *   line wrap.  The 80 column case is tricky, as the classical
  1089.      *   Big Iron IBM mainframe pads to 80 columns, and some terminal
  1090.      *   and text viewer combinations cause a blank line, while others
  1091.      *   don't.  A line that is exactly 80 columns wide but ends in
  1092.      *   a non-blank would do, too.
  1093.      * - A big pile of whitespace within a line, enough to
  1094.      *   produce something that looks like a blank line between
  1095.      *   the brginning and end parts.
  1096.      * - Various cursor-control sequences.
  1097.      * Basically, it's a nasty problem.  A very strong case can be made
  1098.      * for the argument that it's the text viewer's problem, and outside
  1099.      * PGP's jurisdiction, but that has a few conflicts with reality.
  1100.      */
  1101.     if (get_armor_line(buf, in) == NULL) {
  1102.         fprintf(pgpout,
  1103. LANG("ERROR: ASCII armor decode input ended unexpectedly!\n"));
  1104.         fclose(in);
  1105.         return 12;
  1106.     }
  1107.     if (buf[0] != '\0') {
  1108.         fprintf(pgpout,
  1109. LANG("ERROR: Header line added to ASCII armor: \"%s\"\n\
  1110. ASCII armor corrupted.\n"), buf);
  1111.         fclose(in);
  1112.         return -1;
  1113.  
  1114.     }
  1115.  
  1116.     litfile = tempfile(TMP_WIPE | TMP_TMPDIR);
  1117.     if ((litout = fopen(litfile, FOPWTXT)) == NULL) {
  1118.         fprintf(pgpout,
  1119. LANG("\n\007Unable to write ciphertext output file '%s'.\n"), litfile);
  1120.         fclose(in);
  1121.         return -1;
  1122.     }
  1123.  
  1124.     status = 0;
  1125.     for (;;) {
  1126.         ++infile_line;
  1127.         nline = status;
  1128.         status = getline(buf, sizeof buf, in);
  1129.         if (status < 0) {
  1130.         fprintf(pgpout,
  1131. LANG("ERROR: ASCII armor decode input ended unexpectedly!\n"));
  1132.         fclose(in);
  1133.         fclose(litout);
  1134.         rmtemp(litfile);
  1135.         return 12;
  1136.         }
  1137.         if (strncmp(buf, "-----BEGIN PGP ", 15) == 0)
  1138.         break;
  1139.         if (nline)
  1140.         putc('\n', litout);
  1141.         /* De-quote lines starting with '- ' */
  1142.         fputs(buf + ((buf[0] == '-' && buf[1] == ' ') ? 2 : 0), litout);
  1143.         /* Copy trailing part of line, if any. */
  1144.         if (!status)
  1145.         status = copyline(in, litout);
  1146.         /* Ignore error; getline will discover it again */
  1147.     }
  1148.     fflush(litout);
  1149.     if (ferror(litout)) {
  1150.         fclose(litout);
  1151.         fclose(in);
  1152.         rmtemp(litfile);
  1153.         return -1;
  1154.     }
  1155.     fclose(litout);
  1156.     canonfile = tempfile(TMP_WIPE | TMP_TMPDIR);
  1157.     strip_spaces = TRUE;
  1158.     make_canonical(litfile, canonfile);
  1159.     rmtemp(litfile);
  1160.     litfile = canonfile;
  1161.     }
  1162.     /* Skip header after BEGIN line */
  1163.     if (skipheaders(in, buf, &header_warned, 1) < 0) {
  1164.     fclose(in);
  1165.     return -1;
  1166.     }
  1167.     if (feof(in)) {
  1168.     fprintf(pgpout, LANG("ERROR: Hit EOF in header.\n"));
  1169.     fclose(in);
  1170.     return 13;
  1171.     }
  1172.  
  1173.     if ((out = fopen(outfile, FOPWBIN)) == NULL) {
  1174.     fprintf(pgpout,
  1175. LANG("\n\007Unable to write ciphertext output file '%s'.\n"), outfile);
  1176.     fclose(in);
  1177.     return -1;
  1178.     }
  1179.     status = armordecode(in, out, &header_warned);
  1180.  
  1181.     if (litfile) {
  1182.     /* Glue the literal file read above to the signature */
  1183.     char lit_mode = MODE_TEXT;
  1184.     word32 dummystamp = 0;
  1185.     FILE *f = fopen(litfile, FOPRBIN);
  1186.  
  1187.     write_ctb_len(out, CTB_LITERAL2_TYPE, fsize(f) + 6, FALSE);
  1188.     fwrite(&lit_mode, 1, 1, out);    /* write lit_mode */
  1189.     fputc('\0', out);    /* No filename */
  1190.     fwrite(&dummystamp, 1, sizeof(dummystamp), out);
  1191.     /* dummy timestamp */
  1192.     copyfile(f, out, -1L);    /* Append literal file */
  1193.     fclose(f);
  1194.     rmtemp(litfile);
  1195.     }
  1196.     if (write_error(out))
  1197.     status = -1;
  1198.     fclose(out);
  1199.     fclose(in);
  1200.     return status;
  1201. }                /* darmor_file */
  1202.  
  1203. /* Entry points for generic interface names */
  1204.  
  1205. int de_armor_file(char *infile, char *outfile, long *curline)
  1206. {
  1207.     int status;
  1208.  
  1209.     if (verbose)
  1210.     fprintf(pgpout,
  1211.          "de_armor_file: infile = %s, outfile = %s, curline = %ld\n",
  1212.         infile, outfile, *curline);
  1213.     infile_line = (curline ? *curline : 0);
  1214.     status = darmor_file(infile, outfile);
  1215.     if (curline)
  1216.     *curline = infile_line;
  1217.     return status;
  1218. }
  1219.  
  1220. boolean
  1221. is_armor_file(char *infile, long startline)
  1222. {
  1223.     infile_line = startline;
  1224.     return is_armorfile(infile);
  1225. }
  1226.