home *** CD-ROM | disk | FTP | other *** search
/ Amiga MA Magazine 1998 #6 / amigamamagazinepolishissue1998.iso / varia / pgp / pgpamiga / source / armor.c < prev    next >
C/C++ Source or Header  |  1993-12-23  |  39KB  |  1,097 lines

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