Back to index

lightning-sunbird  0.9+nobinonly
sdrtest.c
Go to the documentation of this file.
00001 /* ***** BEGIN LICENSE BLOCK *****
00002  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
00003  *
00004  * The contents of this file are subject to the Mozilla Public License Version
00005  * 1.1 (the "License"); you may not use this file except in compliance with
00006  * the License. You may obtain a copy of the License at
00007  * http://www.mozilla.org/MPL/
00008  *
00009  * Software distributed under the License is distributed on an "AS IS" basis,
00010  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
00011  * for the specific language governing rights and limitations under the
00012  * License.
00013  *
00014  * The Original Code is the Netscape security libraries.
00015  *
00016  * The Initial Developer of the Original Code is
00017  * Netscape Communications Corporation.
00018  * Portions created by the Initial Developer are Copyright (C) 1994-2000
00019  * the Initial Developer. All Rights Reserved.
00020  *
00021  * Contributor(s):
00022  *
00023  * Alternatively, the contents of this file may be used under the terms of
00024  * either the GNU General Public License Version 2 or later (the "GPL"), or
00025  * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
00026  * in which case the provisions of the GPL or the LGPL are applicable instead
00027  * of those above. If you wish to allow use of your version of this file only
00028  * under the terms of either the GPL or the LGPL, and not to allow others to
00029  * use your version of this file under the terms of the MPL, indicate your
00030  * decision by deleting the provisions above and replace them with the notice
00031  * and other provisions required by the GPL or the LGPL. If you do not delete
00032  * the provisions above, a recipient may use your version of this file under
00033  * the terms of any one of the MPL, the GPL or the LGPL.
00034  *
00035  * ***** END LICENSE BLOCK ***** */
00036 
00037 /*
00038  * Test program for SDR (Secret Decoder Ring) functions.
00039  *
00040  * $Id: sdrtest.c,v 1.13 2004/04/25 15:02:52 gerv%gerv.net Exp $
00041  */
00042 
00043 #include "nspr.h"
00044 #include "string.h"
00045 #include "nss.h"
00046 #include "secutil.h"
00047 #include "cert.h"
00048 #include "pk11func.h"
00049 
00050 #include "plgetopt.h"
00051 #include "pk11sdr.h"
00052 #include "nssb64.h"
00053 
00054 #define DEFAULT_VALUE "Test"
00055 static const char default_value[] = { DEFAULT_VALUE };
00056 
00057 PRFileDesc *pr_stderr;
00058 PRBool      verbose = PR_FALSE;
00059 
00060 static void
00061 synopsis (char *program_name)
00062 {
00063     PR_fprintf (pr_stderr, 
00064 "Usage: %s [-d <dir>] [-v] [-t <text>] [-a] -i <input-file>\n"
00065 "       %s [-d <dir>] [-v] [-t <text>] [-a] -o <output-file>\n",
00066        program_name, program_name);
00067 }
00068 
00069 static void
00070 short_usage (char *program_name)
00071 {
00072     PR_fprintf (pr_stderr,
00073               "Type %s -H for more detailed descriptions\n",
00074               program_name);
00075     synopsis (program_name);
00076 }
00077 
00078 
00079 static void
00080 long_usage (char *program_name)
00081 {
00082     synopsis (program_name);
00083     PR_fprintf (pr_stderr, "\nSecret Decoder Test:\n");
00084     PR_fprintf (pr_stderr,
00085               "  %-13s Read encrypted data from \"file\"\n",
00086               "-i file");
00087     PR_fprintf (pr_stderr,
00088               "  %-13s Write newly generated encrypted data to \"file\"\n",
00089               "-o file");
00090     PR_fprintf (pr_stderr,
00091               "  %-13s Use \"text\" as the plaintext for encryption and verification\n",
00092               "-t text");
00093     PR_fprintf (pr_stderr,
00094               "  %-13s Find security databases in \"dbdir\"\n",
00095               "-d dbdir");
00096 }
00097 
00098 int 
00099 readStdin(SECItem * result)
00100 {
00101   int bufsize = 0;
00102   int cc;
00103   int wanted  = 8192;
00104 
00105   result->len = 0;
00106   result->data = NULL;
00107   do {
00108     if (bufsize < wanted) {
00109       unsigned char * tmpData = (unsigned char *)realloc(result->data, wanted);
00110       if (!tmpData) {
00111        if (verbose) PR_fprintf(pr_stderr, "Allocation of buffer failed\n");
00112        return -1;
00113       }
00114       result->data = tmpData;
00115       bufsize = wanted;
00116     }
00117     cc = PR_Read(PR_STDIN, result->data + result->len, bufsize - result->len);
00118     if (cc > 0) {
00119       result->len += (unsigned)cc;
00120       if (result->len >= wanted) 
00121         wanted *= 2;
00122     }
00123   } while (cc > 0);
00124   return cc;
00125 }
00126 
00127 int
00128 readInputFile(const char * filename, SECItem * result)
00129 {
00130   PRFileDesc *file /* = PR_OpenFile(input_file, 0) */;
00131   PRFileInfo info;
00132   PRStatus s;
00133   PRInt32 count;
00134   int retval = -1;
00135 
00136   file = PR_Open(filename, PR_RDONLY, 0);
00137   if (!file) {
00138     if (verbose) PR_fprintf(pr_stderr, "Open of file %s failed\n", filename);
00139     goto loser;
00140   }
00141 
00142   s = PR_GetOpenFileInfo(file, &info);
00143   if (s != PR_SUCCESS) {
00144     if (verbose) PR_fprintf(pr_stderr, "File info operation failed\n");
00145     goto file_loser;
00146   }
00147 
00148   result->len = info.size;
00149   result->data = (unsigned char *)malloc(result->len);
00150   if (!result->data) {
00151     if (verbose) PR_fprintf(pr_stderr, "Allocation of buffer failed\n");
00152     goto file_loser;
00153   }
00154 
00155   count = PR_Read(file, result->data, result->len);
00156   if (count != result->len) {
00157     if (verbose) PR_fprintf(pr_stderr, "Read failed\n");
00158     goto file_loser;
00159   }
00160   retval = 0;
00161 
00162 file_loser:
00163   PR_Close(file);
00164 loser:
00165   return retval;
00166 }
00167 
00168 int
00169 main (int argc, char **argv)
00170 {
00171     int               retval = 0;  /* 0 - test succeeded.  -1 - test failed */
00172     SECStatus  rv;
00173     PLOptState       *optstate;
00174     PLOptStatus  optstatus;
00175     char      *program_name;
00176     const char  *input_file = NULL;       /* read encrypted data from here (or create) */
00177     const char  *output_file = NULL;      /* write new encrypted data here */
00178     const char  *value = default_value;   /* Use this for plaintext */
00179     SECItem     data;
00180     SECItem     result = {0, 0, 0};
00181     SECItem     text;
00182     PRBool      ascii = PR_FALSE;
00183 
00184     pr_stderr = PR_STDERR;
00185     result.data = 0;
00186     text.data = 0; text.len = 0;
00187 
00188     program_name = PL_strrchr(argv[0], '/');
00189     program_name = program_name ? (program_name + 1) : argv[0];
00190 
00191     optstate = PL_CreateOptState (argc, argv, "?Had:i:o:t:v");
00192     if (optstate == NULL) {
00193        SECU_PrintError (program_name, "PL_CreateOptState failed");
00194        return -1;
00195     }
00196 
00197     while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
00198        switch (optstate->option) {
00199          case '?':
00200            short_usage (program_name);
00201            return retval;
00202 
00203          case 'H':
00204            long_usage (program_name);
00205            return retval;
00206 
00207          case 'a':
00208            ascii = PR_TRUE;
00209            break;
00210 
00211          case 'd':
00212            SECU_ConfigDirectory(optstate->value);
00213            break;
00214 
00215           case 'i':
00216             input_file = optstate->value;
00217             break;
00218 
00219           case 'o':
00220             output_file = optstate->value;
00221             break;
00222 
00223           case 't':
00224             value = optstate->value;
00225             break;
00226 
00227           case 'v':
00228             verbose = PR_TRUE;
00229             break;
00230        }
00231     }
00232     PL_DestroyOptState(optstate);
00233     if (optstatus == PL_OPT_BAD) {
00234        short_usage (program_name);
00235        return -1;
00236     }
00237     if (!output_file && !input_file && value == default_value) {
00238        short_usage (program_name);
00239        PR_fprintf (pr_stderr, "Must specify at least one of -t, -i or -o \n");
00240        return -1;
00241     }
00242 
00243     /*
00244      * Initialize the Security libraries.
00245      */
00246     PK11_SetPasswordFunc(SECU_GetModulePassword);
00247 
00248     if (output_file) {
00249        rv = NSS_InitReadWrite(SECU_ConfigDirectory(NULL));
00250     } else {
00251        rv = NSS_Init(SECU_ConfigDirectory(NULL));
00252     }
00253     if (rv != SECSuccess) {
00254        SECU_PrintError(program_name, "NSS_Init failed");
00255        retval = -1;
00256        goto prdone;
00257     }
00258 
00259     /* Convert value into an item */
00260     data.data = (unsigned char *)value;
00261     data.len = strlen(value);
00262 
00263     /* Get the encrypted result, either from the input file
00264      * or from encrypting the plaintext value
00265      */
00266     if (input_file)
00267     {
00268       if (verbose) printf("Reading data from %s\n", input_file);
00269 
00270       if (!strcmp(input_file, "-")) {
00271        retval = readStdin(&result);
00272         ascii = PR_TRUE;
00273       } else {
00274         retval = readInputFile(input_file, &result);
00275       }
00276       if (retval != 0) 
00277        goto loser;
00278       if (ascii) {
00279        /* input was base64 encoded.  Decode it. */
00280        SECItem newResult = {0, 0, 0};
00281        SECItem *ok = NSSBase64_DecodeBuffer(NULL, &newResult, 
00282                               (const char *)result.data, result.len);
00283        if (!ok) {
00284          SECU_PrintError(program_name, "Base 64 decode failed");
00285          retval = -1;
00286          goto loser;
00287        }
00288        free(result.data);
00289        result = *ok;
00290       }
00291     }
00292     else
00293     {
00294       SECItem keyid = { 0, 0, 0 };
00295       SECItem outBuf = { 0, 0, 0 };
00296       PK11SlotInfo *slot = NULL;
00297 
00298       /* sigh, initialize the key database */
00299       slot = PK11_GetInternalKeySlot();
00300       if (slot && PK11_NeedUserInit(slot)) {
00301         rv = SECU_ChangePW(slot, "", 0);
00302         if (rv != SECSuccess) {
00303             SECU_PrintError(program_name, "Failed to initialize slot \"%s\"",
00304                                     PK11_GetSlotName(slot));
00305             return SECFailure;
00306         }
00307       }
00308       if (slot) {
00309        PK11_FreeSlot(slot);
00310       }
00311 
00312       rv = PK11SDR_Encrypt(&keyid, &data, &result, 0);
00313       if (rv != SECSuccess) {
00314         if (verbose) 
00315          SECU_PrintError(program_name, "Encrypt operation failed\n");
00316         retval = -1;
00317         goto loser;
00318       }
00319 
00320       if (verbose) printf("Encrypted result is %d bytes long\n", result.len);
00321 
00322       if (!strcmp(output_file, "-")) {
00323         ascii = PR_TRUE;
00324       }
00325 
00326       if (ascii) {
00327        /* base64 encode output. */
00328        char * newResult = NSSBase64_EncodeItem(NULL, NULL, 0, &result);
00329        if (!newResult) {
00330          SECU_PrintError(program_name, "Base 64 encode failed\n");
00331          retval = -1;
00332          goto loser;
00333        }
00334        outBuf.data = (unsigned char *)newResult;
00335        outBuf.len  = strlen(newResult);
00336        if (verbose) 
00337          printf("Base 64 encoded result is %d bytes long\n", outBuf.len);
00338       } else {
00339        outBuf = result;
00340       }
00341 
00342       /* -v printf("Result is %.*s\n", text.len, text.data); */
00343       if (output_file) {
00344          PRFileDesc *file;
00345          PRInt32 count;
00346 
00347          if (verbose) printf("Writing result to %s\n", output_file);
00348         if (!strcmp(output_file, "-")) {
00349           file = PR_STDOUT;
00350         } else {
00351           /* Write to file */
00352           file = PR_Open(output_file, PR_CREATE_FILE|PR_WRONLY, 0666);
00353         }
00354          if (!file) {
00355             if (verbose) 
00356               SECU_PrintError(program_name, 
00357                                 "Open of output file %s failed\n",
00358                                 output_file);
00359             retval = -1;
00360             goto loser;
00361          }
00362 
00363          count = PR_Write(file, outBuf.data, outBuf.len);
00364 
00365         if (file == PR_STDOUT) {
00366           puts("");
00367         } else {
00368           PR_Close(file);
00369         }
00370 
00371          if (count != outBuf.len) {
00372            if (verbose) SECU_PrintError(program_name, "Write failed\n");
00373            retval = -1;
00374            goto loser;
00375          }
00376         if (ascii) {
00377           free(outBuf.data);
00378         }
00379       }
00380     }
00381 
00382     /* Decrypt the value */
00383     rv = PK11SDR_Decrypt(&result, &text, 0);
00384     if (rv != SECSuccess) {
00385       if (verbose) SECU_PrintError(program_name, "Decrypt operation failed\n");
00386       retval = -1; 
00387       goto loser;
00388     }
00389 
00390     if (verbose) printf("Decrypted result is \"%.*s\"\n", text.len, text.data);
00391 
00392     /* Compare to required value */
00393     if (text.len != data.len || memcmp(data.data, text.data, text.len) != 0)
00394     {
00395       if (verbose) PR_fprintf(pr_stderr, "Comparison failed\n");
00396       retval = -1;
00397       goto loser;
00398     }
00399 
00400 loser:
00401     if (text.data) free(text.data);
00402     if (result.data) free(result.data);
00403     if (NSS_Shutdown() != SECSuccess) {
00404        exit(1);
00405     }
00406 
00407 prdone:
00408     PR_Cleanup ();
00409     return retval;
00410 }