Exemplo n.º 1
0
bool prompt_kek(char *prompt, kdfp *kdfp, uint8_t *kek, size_t len, bool verify) {
  char passwd[PASSWD_MAX];
  bool ok = false;

  if (!EVP_read_pw_string(passwd, PASSWD_MAX - 1, prompt, verify)) {
      ok = derive_kek((uint8_t *) passwd, strlen(passwd), kdfp, kek, len);
  }
  OPENSSL_cleanse(passwd, PASSWD_MAX);

  return ok;
}
Exemplo n.º 2
0
static int
AskPassFunction(char *buf, size_t sz, const char *prompt)
{
	if ( AskPassFunction_ != NULL ) {
		return AskPassFunction_(buf, sz, prompt);
	} else if (isatty(STDIN_FILENO)){
		if (EVP_read_pw_string(buf, sz, prompt, 0) == 0) {
			return strlen(buf);
		}
	}
	return -1;
}
Exemplo n.º 3
0
static bool get_password(std::string& password, bool verify) {
  char pwd[1024];
  int len = sizeof(pwd);
  int j, r;
  char prompt[128];
  for(;;) {
    snprintf(prompt, sizeof(prompt), "Enter password for Username Token: "); 
    r = EVP_read_pw_string(pwd, len, prompt, 0);
    if(r != 0) {
      std::cerr<<"Failed to read read input password"<<std::endl;
      memset(pwd,0,(unsigned int)len);
      return false;
    }
    j = strlen(pwd);
    if(j < PASS_MIN_LENGTH) {
      std::cerr<<"Input phrase is too short (must be at least "<<PASS_MIN_LENGTH<<" chars)"<<std::endl;
    }
    else if(!verify) {
      password=pwd;
      return true;
    } 
    else {
      snprintf(prompt, sizeof(prompt), "Enter password again: ");
      char buf[1024];
      r = EVP_read_pw_string(buf, len, prompt, 0);
      if(r != 0) {
        std::cerr<<"Failed to read input password"<<std::endl;
        return false;
      }
      if(strcmp(pwd, buf) != 0) {
        std::cerr<<"Two input passwords do not match, try again"<<std::endl;    
      }
      else {
        password=pwd;
        return true;
      }
    }//end else
  }//end for  
  return false;
}
Exemplo n.º 4
0
int
sc_init_open_login(
    CK_SESSION_HANDLE_PTR               PsessionHandle,
    CK_SLOT_ID_PTR                      pslot,
    char *                              ppin,
    CK_USER_TYPE                        userType)
{
  CK_RV                               status;
  char *                              pin;
  char                                rpin[256];
  /* could also add CKF_EXCLUSIVE_SESSION */
  int                                 flags =
    CKF_RW_SESSION | CKF_SERIAL_SESSION ;

  status = (*(pFunctionList->C_OpenSession))(*pslot, 
                                             flags, 0, NULL, PsessionHandle);
  if (status != CKR_OK) {
    SCerr(SCERR_F_SCINIT,SCERR_R_OPENSESSION);
    ERR_add_error_data(1,sc_ERR_code(status));
    return SCERR_R_OPENSESSION;
  }
	
  if (ppin) /* did user provide the pin? */ { 
    pin = ppin; 
  }
  else {
    pin = rpin;
    memset(rpin,0,sizeof(rpin));
#ifdef WIN32
    read_passphrase_win32_prompt(
                                 (userType == CKU_USER) ?
                                 "Smart Card User PIN:" : "Smart Card SO PIN:",0);
    read_passphrase_win32(rpin,sizeof(rpin),0);
#else
    EVP_read_pw_string(rpin,sizeof(rpin),
                       (userType == CKU_USER) ? 
                       "Smart Card User PIN:" : "Smart Card SO PIN:",0);
#endif			
    /*DEE should test this too */
  }

  status = (*(pFunctionList->C_Login))(*PsessionHandle, userType,
                                       (CK_CHAR_PTR)pin, strlen(pin));
  memset(rpin,0,sizeof(rpin));
  if (status != CKR_OK) {
    SCerr(SCERR_F_SCINIT,SCERR_R_LOGIN);
    ERR_add_error_data(1,sc_ERR_code(status));
    return SCERR_R_LOGIN;
  }

  return 0;
}
static int
ssl_pass_cb(char *buf, int size, int rwflag, void *u)
{

	if (EVP_read_pw_string(buf, size, "Passphrase :", 0)) {
#if OPENSSL_VERSION >= 0x0090608fL
		OPENSSL_cleanse(buf, size);
#else
		memset(buf, 0, size);
#endif
		return 0;
	}
	return strlen(buf);
}
Exemplo n.º 6
0
int passphrase_callback(char* buf, int size, int /* rwflag */, void *) {
  int len;
  char prompt[128];
  snprintf(prompt, sizeof(prompt), "Enter passphrase for the key file: \n");
  int r = EVP_read_pw_string(buf, size, prompt, 0);
  if(r != 0) {
    std::cerr<<"Failed to read passphrase from stdin"<<std::endl;
    return -1;
  }
  len = strlen(buf);
  if(buf[len-1] == '\n') {
    buf[len-1] = '\0';
    len--;
  }
  return len;
}
Exemplo n.º 7
0
/* Simple echo password prompting */
int SSL_password_prompt(tcn_pass_cb_t *data)
{
    int rv = 0;
    data->password[0] = '\0';
    if (data->cb.obj) {
        JNIEnv *e;
        jobject  o;
        jstring  prompt;
        tcn_get_java_env(&e);
        prompt = AJP_TO_JSTRING(data->prompt);
        if ((o = (*e)->CallObjectMethod(e, data->cb.obj,
                            data->cb.mid[0], prompt))) {
            TCN_ALLOC_CSTRING(o);
            if (J2S(o)) {
                strncpy(data->password, J2S(o), SSL_MAX_PASSWORD_LEN);
                data->password[SSL_MAX_PASSWORD_LEN-1] = '\0';
                rv = (int)strlen(data->password);
            }
            TCN_FREE_CSTRING(o);
        }
    }
    else {
#ifdef WIN32
        rv = WIN32_SSL_password_prompt(data);
#else
        EVP_read_pw_string(data->password, SSL_MAX_PASSWORD_LEN,
                           data->prompt, 0);
#endif
        rv = (int)strlen(data->password);
    }
    if (rv > 0) {
        /* Remove LF char if present */
        char *r = strchr(data->password, '\n');
        if (r) {
            *r = '\0';
            rv--;
        }
#ifdef WIN32
        if ((r = strchr(data->password, '\r'))) {
            *r = '\0';
            rv--;
        }
#endif
    }
    return rv;
}
Exemplo n.º 8
0
int PEM_def_callback(char *buf, int num, int w, void *key)
  {
#ifdef OPENSSL_NO_FP_API
  /* We should not ever call the default callback routine from
   * windows. */
  PEMerr(PEM_F_PEM_DEF_CALLBACK,ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
  return(-1);
#else
  int i,j;
  const char *prompt;
  if(key) {
    i=strlen(key);
    i=(i > num)?num:i;
    memcpy(buf,key,i);
    return(i);
  }

  prompt=EVP_get_pw_prompt();
  if (prompt == NULL)
    prompt="Enter PEM pass phrase:";

  for (;;)
    {
    i=EVP_read_pw_string(buf,num,prompt,w);
    if (i != 0)
      {
      PEMerr(PEM_F_PEM_DEF_CALLBACK,PEM_R_PROBLEMS_GETTING_PASSWORD);
      memset(buf,0,(unsigned int)num);
      return(-1);
      }
    j=strlen(buf);
    if (j < MIN_LENGTH)
      {
      fprintf(stderr,"phrase is too short, needs to be at least %d chars\n",MIN_LENGTH);
      }
    else
      break;
    }
  return(j);
#endif
  }
Exemplo n.º 9
0
bool read_pw(const char *name, char *pwbuf, size_t pwbuflen, int verify) {
  #define READ_PW_PROMPT_BASE "Enter %s: "
  char prompt[sizeof(READ_PW_PROMPT_BASE) + 32] = {0};
  int ret;

  if (pwbuflen < 1) {
    fprintf(stderr, "Failed to read %s: buffer too small.", name);
    return false;
  }

  ret = snprintf(prompt, sizeof(prompt), READ_PW_PROMPT_BASE, name);
  if (ret < 0 || ((unsigned int) ret) > (sizeof(prompt)-1)) {
    fprintf(stderr, "Failed to read %s: snprintf failed.\n", name);
    return false;
  }

  if (0 != EVP_read_pw_string(pwbuf, pwbuflen-1, prompt, verify)) {
    fprintf(stderr, "Retrieving %s failed.\n", name);
    return false;
  }
  return true;
}
Exemplo n.º 10
0
int pkcs8_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    ENGINE *e = NULL;
    EVP_PKEY *pkey = NULL;
    PKCS8_PRIV_KEY_INFO *p8inf = NULL;
    X509_SIG *p8 = NULL;
    const EVP_CIPHER *cipher = NULL;
    char *infile = NULL, *outfile = NULL;
    char *passinarg = NULL, *passoutarg = NULL, *prog;
    char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL;
    OPTION_CHOICE o;
    int nocrypt = 0, ret = 1, iter = PKCS12_DEFAULT_ITER, p8_broken = PKCS8_OK;
    int informat = FORMAT_PEM, outformat = FORMAT_PEM, topk8 = 0, pbe_nid = -1;

    prog = opt_init(argc, argv, pkcs8_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(pkcs8_options);
            ret = 0;
            goto end;
        case OPT_INFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &informat))
                goto opthelp;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUTFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PEMDER, &outformat))
                goto opthelp;
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_TOPK8:
            topk8 = 1;
            break;
        case OPT_NOITER:
            iter = 1;
            break;
        case OPT_NOCRYPT:
            nocrypt = 1;
            break;
        case OPT_NOOCT:
            p8_broken = PKCS8_NO_OCTET;
            break;
        case OPT_NSDB:
            p8_broken = PKCS8_NS_DB;
            break;
        case OPT_EMBED:
            p8_broken = PKCS8_EMBEDDED_PARAM;
            break;
        case OPT_V2:
            if (!opt_cipher(opt_arg(), &cipher))
                goto opthelp;
            break;
        case OPT_V1:
            pbe_nid = OBJ_txt2nid(opt_arg());
            if (pbe_nid == NID_undef) {
                BIO_printf(bio_err,
                           "%s: Unknown PBE algorithm %s\n", prog, opt_arg());
                goto opthelp;
            }
            break;
        case OPT_V2PRF:
            pbe_nid = OBJ_txt2nid(opt_arg());
            if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0)) {
                BIO_printf(bio_err,
                           "%s: Unknown PRF algorithm %s\n", prog, opt_arg());
                goto opthelp;
            }
            break;
        case OPT_ITER:
            if (!opt_int(opt_arg(), &iter))
                goto opthelp;
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PASSOUT:
            passoutarg = opt_arg();
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
        BIO_printf(bio_err, "Error getting passwords\n");
        goto end;
    }

    if ((pbe_nid == -1) && !cipher)
        pbe_nid = NID_pbeWithMD5AndDES_CBC;

    in = bio_open_default(infile, "rb");
    if (in == NULL)
        goto end;
    out = bio_open_default(outfile, "wb");
    if (out == NULL)
        goto end;
    if (topk8) {
        pkey = load_key(infile, informat, 1, passin, e, "key");
        if (!pkey)
            goto end;
        if (!(p8inf = EVP_PKEY2PKCS8_broken(pkey, p8_broken))) {
            BIO_printf(bio_err, "Error converting key\n");
            ERR_print_errors(bio_err);
            goto end;
        }
        if (nocrypt) {
            if (outformat == FORMAT_PEM)
                PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
            else if (outformat == FORMAT_ASN1)
                i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
            else {
                BIO_printf(bio_err, "Bad format specified for key\n");
                goto end;
            }
        } else {
            if (passout)
                p8pass = passout;
            else {
                p8pass = pass;
                if (EVP_read_pw_string
                    (pass, sizeof pass, "Enter Encryption Password:"******"Error encrypting key\n");
                ERR_print_errors(bio_err);
                goto end;
            }
            app_RAND_write_file(NULL);
            if (outformat == FORMAT_PEM)
                PEM_write_bio_PKCS8(out, p8);
            else if (outformat == FORMAT_ASN1)
                i2d_PKCS8_bio(out, p8);
            else {
                BIO_printf(bio_err, "Bad format specified for key\n");
                goto end;
            }
        }

        ret = 0;
        goto end;
    }

    if (nocrypt) {
        if (informat == FORMAT_PEM)
            p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in, NULL, NULL, NULL);
        else if (informat == FORMAT_ASN1)
            p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
        else {
            BIO_printf(bio_err, "Bad format specified for key\n");
            goto end;
        }
    } else {
        if (informat == FORMAT_PEM)
            p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
        else if (informat == FORMAT_ASN1)
            p8 = d2i_PKCS8_bio(in, NULL);
        else {
            BIO_printf(bio_err, "Bad format specified for key\n");
            goto end;
        }

        if (!p8) {
            BIO_printf(bio_err, "Error reading key\n");
            ERR_print_errors(bio_err);
            goto end;
        }
        if (passin)
            p8pass = passin;
        else {
            p8pass = pass;
            EVP_read_pw_string(pass, sizeof pass, "Enter Password:"******"Error decrypting key\n");
        ERR_print_errors(bio_err);
        goto end;
    }

    if (!(pkey = EVP_PKCS82PKEY(p8inf))) {
        BIO_printf(bio_err, "Error converting key\n");
        ERR_print_errors(bio_err);
        goto end;
    }

    if (p8inf->broken) {
        BIO_printf(bio_err, "Warning: broken key encoding: ");
        switch (p8inf->broken) {
        case PKCS8_NO_OCTET:
            BIO_printf(bio_err, "No Octet String in PrivateKey\n");
            break;

        case PKCS8_EMBEDDED_PARAM:
            BIO_printf(bio_err, "DSA parameters included in PrivateKey\n");
            break;

        case PKCS8_NS_DB:
            BIO_printf(bio_err, "DSA public key include in PrivateKey\n");
            break;

        case PKCS8_NEG_PRIVKEY:
            BIO_printf(bio_err, "DSA private key value is negative\n");
            break;

        default:
            BIO_printf(bio_err, "Unknown broken type\n");
            break;
        }
    }

    if (outformat == FORMAT_PEM)
        PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout);
    else if (outformat == FORMAT_ASN1)
        i2d_PrivateKey_bio(out, pkey);
    else {
        BIO_printf(bio_err, "Bad format specified for key\n");
        goto end;
    }
    ret = 0;

 end:
    X509_SIG_free(p8);
    PKCS8_PRIV_KEY_INFO_free(p8inf);
    EVP_PKEY_free(pkey);
    BIO_free_all(out);
    BIO_free(in);
    OPENSSL_free(passin);
    OPENSSL_free(passout);

    return ret;
}
Exemplo n.º 11
0
int MAIN(int argc, char **argv)
	{
	static const char magic[]="Salted__";
	char mbuf[8];	/* should be 1 smaller than magic */
	char *strbuf=NULL;
	unsigned char *buff=NULL,*bufsize=NULL;
	int bsize=BSIZE,verbose=0;
	int ret=1,inl;
	unsigned char key[24],iv[MD5_DIGEST_LENGTH];
	unsigned char salt[PKCS5_SALT_LEN];
	char *str=NULL, *passarg = NULL, *pass = NULL;
	char *hkey=NULL,*hiv=NULL,*hsalt = NULL;
	int enc=1,printkey=0,i,base64=0;
	int debug=0,olb64=0,nosalt=0;
	const EVP_CIPHER *cipher=NULL,*c;
	char *inf=NULL,*outf=NULL;
	BIO *in=NULL,*out=NULL,*b64=NULL,*benc=NULL,*rbio=NULL,*wbio=NULL;
#define PROG_NAME_SIZE  39
	char pname[PROG_NAME_SIZE+1];

	apps_startup();

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

	/* first check the program name */
	program_name(argv[0],pname,PROG_NAME_SIZE);
	if (strcmp(pname,"base64") == 0)
		base64=1;

	cipher=EVP_get_cipherbyname(pname);
	if (!base64 && (cipher == NULL) && (strcmp(pname,"enc") != 0))
		{
		BIO_printf(bio_err,"%s is an unknown cipher\n",pname);
		goto bad;
		}

	argc--;
	argv++;
	while (argc >= 1)
		{
		if	(strcmp(*argv,"-e") == 0)
			enc=1;
		else if (strcmp(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			inf= *(++argv);
			}
		else if (strcmp(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outf= *(++argv);
			}
		else if (strcmp(*argv,"-pass") == 0)
			{
			if (--argc < 1) goto bad;
			passarg= *(++argv);
			}
		else if	(strcmp(*argv,"-d") == 0)
			enc=0;
		else if	(strcmp(*argv,"-p") == 0)
			printkey=1;
		else if	(strcmp(*argv,"-v") == 0)
			verbose=1;
		else if	(strcmp(*argv,"-salt") == 0)
			nosalt=0;
		else if	(strcmp(*argv,"-nosalt") == 0)
			nosalt=1;
		else if	(strcmp(*argv,"-debug") == 0)
			debug=1;
		else if	(strcmp(*argv,"-P") == 0)
			printkey=2;
		else if	(strcmp(*argv,"-A") == 0)
			olb64=1;
		else if	(strcmp(*argv,"-a") == 0)
			base64=1;
		else if	(strcmp(*argv,"-base64") == 0)
			base64=1;
		else if (strcmp(*argv,"-bufsize") == 0)
			{
			if (--argc < 1) goto bad;
			bufsize=(unsigned char *)*(++argv);
			}
		else if (strcmp(*argv,"-k") == 0)
			{
			if (--argc < 1) goto bad;
			str= *(++argv);
			}
		else if (strcmp(*argv,"-kfile") == 0)
			{
			static char buf[128];
			FILE *infile;
			char *file;

			if (--argc < 1) goto bad;
			file= *(++argv);
			infile=fopen(file,"r");
			if (infile == NULL)
				{
				BIO_printf(bio_err,"unable to read key from '%s'\n",
					file);
				goto bad;
				}
			buf[0]='\0';
			fgets(buf,128,infile);
			fclose(infile);
			i=strlen(buf);
			if ((i > 0) &&
				((buf[i-1] == '\n') || (buf[i-1] == '\r')))
				buf[--i]='\0';
			if ((i > 0) &&
				((buf[i-1] == '\n') || (buf[i-1] == '\r')))
				buf[--i]='\0';
			if (i < 1)
				{
				BIO_printf(bio_err,"zero length password\n");
				goto bad;
				}
			str=buf;
			}
		else if (strcmp(*argv,"-K") == 0)
			{
			if (--argc < 1) goto bad;
			hkey= *(++argv);
			}
		else if (strcmp(*argv,"-S") == 0)
			{
			if (--argc < 1) goto bad;
			hsalt= *(++argv);
			}
		else if (strcmp(*argv,"-iv") == 0)
			{
			if (--argc < 1) goto bad;
			hiv= *(++argv);
			}
		else if	((argv[0][0] == '-') &&
			((c=EVP_get_cipherbyname(&(argv[0][1]))) != NULL))
			{
			cipher=c;
			}
		else if (strcmp(*argv,"-none") == 0)
			cipher=NULL;
		else
			{
			BIO_printf(bio_err,"unknown option '%s'\n",*argv);
bad:
			BIO_printf(bio_err,"options are\n");
			BIO_printf(bio_err,"%-14s input file\n","-in <file>");
			BIO_printf(bio_err,"%-14s output file\n","-out <file>");
			BIO_printf(bio_err,"%-14s pass phrase source\n","-pass <arg>");
			BIO_printf(bio_err,"%-14s encrypt\n","-e");
			BIO_printf(bio_err,"%-14s decrypt\n","-d");
			BIO_printf(bio_err,"%-14s base64 encode/decode, depending on encryption flag\n","-a/-base64");
			BIO_printf(bio_err,"%-14s key is the next argument\n","-k");
			BIO_printf(bio_err,"%-14s key is the first line of the file argument\n","-kfile");
			BIO_printf(bio_err,"%-14s key/iv in hex is the next argument\n","-K/-iv");
			BIO_printf(bio_err,"%-14s print the iv/key (then exit if -P)\n","-[pP]");
			BIO_printf(bio_err,"%-14s buffer size\n","-bufsize <n>");

			BIO_printf(bio_err,"Cipher Types\n");
			BIO_printf(bio_err,"des     : 56 bit key DES encryption\n");
			BIO_printf(bio_err,"des_ede :112 bit key ede DES encryption\n");
			BIO_printf(bio_err,"des_ede3:168 bit key ede DES encryption\n");
#ifndef NO_IDEA
			BIO_printf(bio_err,"idea    :128 bit key IDEA encryption\n");
#endif
#ifndef NO_RC4
			BIO_printf(bio_err,"rc2     :128 bit key RC2 encryption\n");
#endif
#ifndef NO_BF
			BIO_printf(bio_err,"bf      :128 bit key Blowfish encryption\n");
#endif
#ifndef NO_RC4
			BIO_printf(bio_err," -%-5s :128 bit key RC4 encryption\n",
				LN_rc4);
#endif

			BIO_printf(bio_err," -%-12s -%-12s -%-12s -%-12s",
				LN_des_ecb,LN_des_cbc,
				LN_des_cfb64,LN_des_ofb64);
			BIO_printf(bio_err," -%-4s (%s)\n",
				"des", LN_des_cbc);

			BIO_printf(bio_err," -%-12s -%-12s -%-12s -%-12s",
				LN_des_ede,LN_des_ede_cbc,
				LN_des_ede_cfb64,LN_des_ede_ofb64);
			BIO_printf(bio_err," -desx -none\n");


			BIO_printf(bio_err," -%-12s -%-12s -%-12s -%-12s",
				LN_des_ede3,LN_des_ede3_cbc,
				LN_des_ede3_cfb64,LN_des_ede3_ofb64);
			BIO_printf(bio_err," -%-4s (%s)\n",
				"des3", LN_des_ede3_cbc);

#ifndef NO_IDEA
			BIO_printf(bio_err," -%-12s -%-12s -%-12s -%-12s",
				LN_idea_ecb, LN_idea_cbc,
				LN_idea_cfb64, LN_idea_ofb64);
			BIO_printf(bio_err," -%-4s (%s)\n","idea",LN_idea_cbc);
#endif
#ifndef NO_RC2
			BIO_printf(bio_err," -%-12s -%-12s -%-12s -%-12s",
				LN_rc2_ecb, LN_rc2_cbc,
				LN_rc2_cfb64, LN_rc2_ofb64);
			BIO_printf(bio_err," -%-4s (%s)\n","rc2", LN_rc2_cbc);
#endif
#ifndef NO_BF
			BIO_printf(bio_err," -%-12s -%-12s -%-12s -%-12s",
				LN_bf_ecb, LN_bf_cbc,
				LN_bf_cfb64, LN_bf_ofb64);
			BIO_printf(bio_err," -%-4s (%s)\n","bf", LN_bf_cbc);
#endif
#ifndef NO_CAST
			BIO_printf(bio_err," -%-12s -%-12s -%-12s -%-12s",
				LN_cast5_ecb, LN_cast5_cbc,
				LN_cast5_cfb64, LN_cast5_ofb64);
			BIO_printf(bio_err," -%-4s (%s)\n","cast", LN_cast5_cbc);
#endif
#ifndef NO_RC5
			BIO_printf(bio_err," -%-12s -%-12s -%-12s -%-12s",
				LN_rc5_ecb, LN_rc5_cbc,
				LN_rc5_cfb64, LN_rc5_ofb64);
			BIO_printf(bio_err," -%-4s (%s)\n","rc5", LN_rc5_cbc);
#endif
			goto end;
			}
		argc--;
		argv++;
		}

	if (bufsize != NULL)
		{
		unsigned long n;

		for (n=0; *bufsize; bufsize++)
			{
			i= *bufsize;
			if ((i <= '9') && (i >= '0'))
				n=n*10+i-'0';
			else if (i == 'k')
				{
				n*=1024;
				bufsize++;
				break;
				}
			}
		if (*bufsize != '\0')
			{
			BIO_printf(bio_err,"invalid 'bufsize' specified.\n");
			goto end;
			}

		/* It must be large enough for a base64 encoded line */
		if (n < 80) n=80;

		bsize=(int)n;
		if (verbose) BIO_printf(bio_err,"bufsize=%d\n",bsize);
		}

	strbuf=OPENSSL_malloc(SIZE);
	buff=(unsigned char *)OPENSSL_malloc(EVP_ENCODE_LENGTH(bsize));
	if ((buff == NULL) || (strbuf == NULL))
		{
		BIO_printf(bio_err,"OPENSSL_malloc failure %ld\n",(long)EVP_ENCODE_LENGTH(bsize));
		goto end;
		}

	in=BIO_new(BIO_s_file());
	out=BIO_new(BIO_s_file());
	if ((in == NULL) || (out == NULL))
		{
		ERR_print_errors(bio_err);
		goto end;
		}
	if (debug)
		{
		BIO_set_callback(in,BIO_debug_callback);
		BIO_set_callback(out,BIO_debug_callback);
		BIO_set_callback_arg(in,bio_err);
		BIO_set_callback_arg(out,bio_err);
		}

	if (inf == NULL)
		BIO_set_fp(in,stdin,BIO_NOCLOSE);
	else
		{
		if (BIO_read_filename(in,inf) <= 0)
			{
			perror(inf);
			goto end;
			}
		}

	if(!str && passarg) {
		if(!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
			BIO_printf(bio_err, "Error getting password\n");
			goto end;
		}
		str = pass;
	}

	if ((str == NULL) && (cipher != NULL) && (hkey == NULL))
		{
		for (;;)
			{
			char buf[200];

			sprintf(buf,"enter %s %s password:"******"encryption":"decryption");
			strbuf[0]='\0';
			i=EVP_read_pw_string((char *)strbuf,SIZE,buf,enc);
			if (i == 0)
				{
				if (strbuf[0] == '\0')
					{
					ret=1;
					goto end;
					}
				str=strbuf;
				break;
				}
			if (i < 0)
				{
				BIO_printf(bio_err,"bad password read\n");
				goto end;
				}
			}
		}


	if (outf == NULL)
		{
		BIO_set_fp(out,stdout,BIO_NOCLOSE);
#ifdef VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outf) <= 0)
			{
			perror(outf);
			goto end;
			}
		}

	rbio=in;
	wbio=out;

	if (base64)
		{
		if ((b64=BIO_new(BIO_f_base64())) == NULL)
			goto end;
		if (debug)
			{
			BIO_set_callback(b64,BIO_debug_callback);
			BIO_set_callback_arg(b64,bio_err);
			}
		if (olb64)
			BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL);
		if (enc)
			wbio=BIO_push(b64,wbio);
		else
			rbio=BIO_push(b64,rbio);
		}

	if (cipher != NULL)
		{
		if (str != NULL)
			{
			/* Salt handling: if encrypting generate a salt and
			 * write to output BIO. If decrypting read salt from
			 * input BIO.
			 */
			unsigned char *sptr;
			if(nosalt) sptr = NULL;
			else {
				if(enc) {
					if(hsalt) {
						if(!set_hex(hsalt,salt,PKCS5_SALT_LEN)) {
							BIO_printf(bio_err,
								"invalid hex salt value\n");
							goto end;
						}
					} else if (RAND_pseudo_bytes(salt, PKCS5_SALT_LEN) < 0)
						goto end;
					/* If -P option then don't bother writing */
					if((printkey != 2)
					   && (BIO_write(wbio,magic,
							 sizeof magic-1) != sizeof magic-1
					       || BIO_write(wbio,
							    (char *)salt,
							    PKCS5_SALT_LEN) != PKCS5_SALT_LEN)) {
						BIO_printf(bio_err,"error writing output file\n");
						goto end;
					}
				} else if(BIO_read(rbio,mbuf,sizeof mbuf) != sizeof mbuf
					  || BIO_read(rbio,
						      (unsigned char *)salt,
				    PKCS5_SALT_LEN) != PKCS5_SALT_LEN) {
					BIO_printf(bio_err,"error reading input file\n");
					goto end;
				} else if(memcmp(mbuf,magic,sizeof magic-1)) {
				    BIO_printf(bio_err,"bad magic number\n");
				    goto end;
				}

				sptr = salt;
			}

			EVP_BytesToKey(cipher,EVP_md5(),sptr,
				(unsigned char *)str,
				strlen(str),1,key,iv);
			/* zero the complete buffer or the string
			 * passed from the command line
			 * bug picked up by
			 * Larry J. Hughes Jr. <*****@*****.**> */
			if (str == strbuf)
				OPENSSL_cleanse(str,SIZE);
			else
				OPENSSL_cleanse(str,strlen(str));
			}
		if ((hiv != NULL) && !set_hex(hiv,iv,8))
			{
			BIO_printf(bio_err,"invalid hex iv value\n");
			goto end;
			}
		if ((hiv == NULL) && (str == NULL))
			{
			/* No IV was explicitly set and no IV was generated
			 * during EVP_BytesToKey. Hence the IV is undefined,
			 * making correct decryption impossible. */
			BIO_printf(bio_err, "iv undefined\n");
			goto end;
			}
		if ((hkey != NULL) && !set_hex(hkey,key,24))
			{
			BIO_printf(bio_err,"invalid hex key value\n");
			goto end;
			}

		if ((benc=BIO_new(BIO_f_cipher())) == NULL)
			goto end;
		BIO_set_cipher(benc,cipher,key,iv,enc);
		if (debug)
			{
			BIO_set_callback(benc,BIO_debug_callback);
			BIO_set_callback_arg(benc,bio_err);
			}

		if (printkey)
			{
			if (!nosalt)
				{
				printf("salt=");
				for (i=0; i<PKCS5_SALT_LEN; i++)
					printf("%02X",salt[i]);
				printf("\n");
				}
			if (cipher->key_len > 0)
				{
				printf("key=");
				for (i=0; i<cipher->key_len; i++)
					printf("%02X",key[i]);
				printf("\n");
				}
			if (cipher->iv_len > 0)
				{
				printf("iv =");
				for (i=0; i<cipher->iv_len; i++)
					printf("%02X",iv[i]);
				printf("\n");
				}
			if (printkey == 2)
				{
				ret=0;
				goto end;
				}
			}
		}

	/* Only encrypt/decrypt as we write the file */
	if (benc != NULL)
		wbio=BIO_push(benc,wbio);

	for (;;)
		{
		inl=BIO_read(rbio,(char *)buff,bsize);
		if (inl <= 0) break;
		if (BIO_write(wbio,(char *)buff,inl) != inl)
			{
			BIO_printf(bio_err,"error writing output file\n");
			goto end;
			}
		}
	if (!BIO_flush(wbio))
		{
		BIO_printf(bio_err,"bad decrypt\n");
		goto end;
		}

	ret=0;
	if (verbose)
		{
		BIO_printf(bio_err,"bytes read   :%8ld\n",BIO_number_read(in));
		BIO_printf(bio_err,"bytes written:%8ld\n",BIO_number_written(out));
		}
end:
	ERR_print_errors(bio_err);
	if (strbuf != NULL) OPENSSL_free(strbuf);
	if (buff != NULL) OPENSSL_free(buff);
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	if (benc != NULL) BIO_free(benc);
	if (b64 != NULL) BIO_free(b64);
	if(pass) OPENSSL_free(pass);
	OPENSSL_EXIT(ret);
	}
Exemplo n.º 12
0
int MAIN(int argc, char **argv)
	{
	static const char magic[]="Salted__";
	char mbuf[sizeof magic-1];
	char *strbuf=NULL;
	unsigned char *buff=NULL,*bufsize=NULL;
	int bsize=BSIZE,verbose=0;
	int ret=1,inl;
	int nopad = 0;
	unsigned char key[EVP_MAX_KEY_LENGTH],iv[EVP_MAX_IV_LENGTH];
	unsigned char salt[PKCS5_SALT_LEN];
	char *str=NULL, *passarg = NULL, *pass = NULL;
	char *hkey=NULL,*hiv=NULL,*hsalt = NULL;
	char *md=NULL;
	int enc=1,printkey=0,i,base64=0;
#ifdef ZLIB
	int do_zlib=0;
	BIO *bzl = NULL;
#endif
	int debug=0,olb64=0,nosalt=0;
	const EVP_CIPHER *cipher=NULL,*c;
	EVP_CIPHER_CTX *ctx = NULL;
	char *inf=NULL,*outf=NULL;
	BIO *in=NULL,*out=NULL,*b64=NULL,*benc=NULL,*rbio=NULL,*wbio=NULL;
#define PROG_NAME_SIZE  39
	char pname[PROG_NAME_SIZE+1];
#ifndef OPENSSL_NO_ENGINE
	char *engine = NULL;
#endif
	const EVP_MD *dgst=NULL;
	int non_fips_allow = 0;

	apps_startup();

	if (bio_err == NULL)
		if ((bio_err=BIO_new(BIO_s_file())) != NULL)
			BIO_set_fp(bio_err,stderr,BIO_NOCLOSE|BIO_FP_TEXT);

	if (!load_config(bio_err, NULL))
		goto end;

	/* first check the program name */
	program_name(argv[0],pname,sizeof pname);
	if (strcmp(pname,"base64") == 0)
		base64=1;
#ifdef ZLIB
	if (strcmp(pname,"zlib") == 0)
		do_zlib=1;
#endif

	cipher=EVP_get_cipherbyname(pname);
#ifdef ZLIB
	if (!do_zlib && !base64 && (cipher == NULL)
				&& (strcmp(pname,"enc") != 0))
#else
	if (!base64 && (cipher == NULL) && (strcmp(pname,"enc") != 0))
#endif
		{
		BIO_printf(bio_err,"%s is an unknown cipher\n",pname);
		goto bad;
		}

	argc--;
	argv++;
	while (argc >= 1)
		{
		if	(strcmp(*argv,"-e") == 0)
			enc=1;
		else if (strcmp(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			inf= *(++argv);
			}
		else if (strcmp(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outf= *(++argv);
			}
		else if (strcmp(*argv,"-pass") == 0)
			{
			if (--argc < 1) goto bad;
			passarg= *(++argv);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*argv,"-engine") == 0)
			{
			if (--argc < 1) goto bad;
			engine= *(++argv);
			}
#endif
		else if	(strcmp(*argv,"-d") == 0)
			enc=0;
		else if	(strcmp(*argv,"-p") == 0)
			printkey=1;
		else if	(strcmp(*argv,"-v") == 0)
			verbose=1;
		else if	(strcmp(*argv,"-nopad") == 0)
			nopad=1;
		else if	(strcmp(*argv,"-salt") == 0)
			nosalt=0;
		else if	(strcmp(*argv,"-nosalt") == 0)
			nosalt=1;
		else if	(strcmp(*argv,"-debug") == 0)
			debug=1;
		else if	(strcmp(*argv,"-P") == 0)
			printkey=2;
		else if	(strcmp(*argv,"-A") == 0)
			olb64=1;
		else if	(strcmp(*argv,"-a") == 0)
			base64=1;
		else if	(strcmp(*argv,"-base64") == 0)
			base64=1;
#ifdef ZLIB
		else if	(strcmp(*argv,"-z") == 0)
			do_zlib=1;
#endif
		else if (strcmp(*argv,"-bufsize") == 0)
			{
			if (--argc < 1) goto bad;
			bufsize=(unsigned char *)*(++argv);
			}
		else if (strcmp(*argv,"-k") == 0)
			{
			if (--argc < 1) goto bad;
			str= *(++argv);
			}
		else if (strcmp(*argv,"-kfile") == 0)
			{
			static char buf[128];
			FILE *infile;
			char *file;

			if (--argc < 1) goto bad;
			file= *(++argv);
			infile=fopen(file,"r");
			if (infile == NULL)
				{
				BIO_printf(bio_err,"unable to read key from '%s'\n",
					file);
				goto bad;
				}
			buf[0]='\0';
			if (!fgets(buf,sizeof buf,infile))
				{
				BIO_printf(bio_err,"unable to read key from '%s'\n",
					file);
				goto bad;
				}
			fclose(infile);
			i=strlen(buf);
			if ((i > 0) &&
				((buf[i-1] == '\n') || (buf[i-1] == '\r')))
				buf[--i]='\0';
			if ((i > 0) &&
				((buf[i-1] == '\n') || (buf[i-1] == '\r')))
				buf[--i]='\0';
			if (i < 1)
				{
				BIO_printf(bio_err,"zero length password\n");
				goto bad;
				}
			str=buf;
			}
		else if (strcmp(*argv,"-K") == 0)
			{
			if (--argc < 1) goto bad;
			hkey= *(++argv);
			}
		else if (strcmp(*argv,"-S") == 0)
			{
			if (--argc < 1) goto bad;
			hsalt= *(++argv);
			}
		else if (strcmp(*argv,"-iv") == 0)
			{
			if (--argc < 1) goto bad;
			hiv= *(++argv);
			}
		else if (strcmp(*argv,"-md") == 0)
			{
			if (--argc < 1) goto bad;
			md= *(++argv);
			}
		else if (strcmp(*argv,"-non-fips-allow") == 0)
			non_fips_allow = 1;
		else if	((argv[0][0] == '-') &&
			((c=EVP_get_cipherbyname(&(argv[0][1]))) != NULL))
			{
			cipher=c;
			}
		else if (strcmp(*argv,"-none") == 0)
			cipher=NULL;
		else
			{
			BIO_printf(bio_err,"unknown option '%s'\n",*argv);
bad:
			BIO_printf(bio_err,"options are\n");
			BIO_printf(bio_err,"%-14s input file\n","-in <file>");
			BIO_printf(bio_err,"%-14s output file\n","-out <file>");
			BIO_printf(bio_err,"%-14s pass phrase source\n","-pass <arg>");
			BIO_printf(bio_err,"%-14s encrypt\n","-e");
			BIO_printf(bio_err,"%-14s decrypt\n","-d");
			BIO_printf(bio_err,"%-14s base64 encode/decode, depending on encryption flag\n","-a/-base64");
			BIO_printf(bio_err,"%-14s passphrase is the next argument\n","-k");
			BIO_printf(bio_err,"%-14s passphrase is the first line of the file argument\n","-kfile");
			BIO_printf(bio_err,"%-14s the next argument is the md to use to create a key\n","-md");
			BIO_printf(bio_err,"%-14s   from a passphrase.  One of md2, md5, sha or sha1\n","");
			BIO_printf(bio_err,"%-14s salt in hex is the next argument\n","-S");
			BIO_printf(bio_err,"%-14s key/iv in hex is the next argument\n","-K/-iv");
			BIO_printf(bio_err,"%-14s print the iv/key (then exit if -P)\n","-[pP]");
			BIO_printf(bio_err,"%-14s buffer size\n","-bufsize <n>");
			BIO_printf(bio_err,"%-14s disable standard block padding\n","-nopad");
#ifndef OPENSSL_NO_ENGINE
			BIO_printf(bio_err,"%-14s use engine e, possibly a hardware device.\n","-engine e");
#endif

			BIO_printf(bio_err,"Cipher Types\n");
			OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
					       show_ciphers,
					       bio_err);
			BIO_printf(bio_err,"\n");

			goto end;
			}
		argc--;
		argv++;
		}

#ifndef OPENSSL_NO_ENGINE
        setup_engine(bio_err, engine, 0);
#endif

	if (md && (dgst=EVP_get_digestbyname(md)) == NULL)
		{
		BIO_printf(bio_err,"%s is an unsupported message digest type\n",md);
		goto end;
		}

	if (dgst == NULL)
		{
		dgst = EVP_md5();
		}

	if (bufsize != NULL)
		{
		unsigned long n;

		for (n=0; *bufsize; bufsize++)
			{
			i= *bufsize;
			if ((i <= '9') && (i >= '0'))
				n=n*10+i-'0';
			else if (i == 'k')
				{
				n*=1024;
				bufsize++;
				break;
				}
			}
		if (*bufsize != '\0')
			{
			BIO_printf(bio_err,"invalid 'bufsize' specified.\n");
			goto end;
			}

		/* It must be large enough for a base64 encoded line */
		if (base64 && n < 80) n=80;

		bsize=(int)n;
		if (verbose) BIO_printf(bio_err,"bufsize=%d\n",bsize);
		}

	strbuf=OPENSSL_malloc(SIZE);
	buff=(unsigned char *)OPENSSL_malloc(EVP_ENCODE_LENGTH(bsize));
	if ((buff == NULL) || (strbuf == NULL))
		{
		BIO_printf(bio_err,"OPENSSL_malloc failure %ld\n",(long)EVP_ENCODE_LENGTH(bsize));
		goto end;
		}

	in=BIO_new(BIO_s_file());
	out=BIO_new(BIO_s_file());
	if ((in == NULL) || (out == NULL))
		{
		ERR_print_errors(bio_err);
		goto end;
		}
	if (debug)
		{
		BIO_set_callback(in,BIO_debug_callback);
		BIO_set_callback(out,BIO_debug_callback);
		BIO_set_callback_arg(in,(char *)bio_err);
		BIO_set_callback_arg(out,(char *)bio_err);
		}

	if (inf == NULL)
	        {
#ifndef OPENSSL_NO_SETVBUF_IONBF
		if (bufsize != NULL)
			setvbuf(stdin, (char *)NULL, _IONBF, 0);
#endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
		BIO_set_fp(in,stdin,BIO_NOCLOSE);
	        }
	else
		{
		if (BIO_read_filename(in,inf) <= 0)
			{
			perror(inf);
			goto end;
			}
		}

	if(!str && passarg) {
		if(!app_passwd(bio_err, passarg, NULL, &pass, NULL)) {
			BIO_printf(bio_err, "Error getting password\n");
			goto end;
		}
		str = pass;
	}

	if ((str == NULL) && (cipher != NULL) && (hkey == NULL))
		{
		for (;;)
			{
			char buf[200];

			BIO_snprintf(buf,sizeof buf,"enter %s %s password:"******"encryption":"decryption");
			strbuf[0]='\0';
			i=EVP_read_pw_string((char *)strbuf,SIZE,buf,enc);
			if (i == 0)
				{
				if (strbuf[0] == '\0')
					{
					ret=1;
					goto end;
					}
				str=strbuf;
				break;
				}
			if (i < 0)
				{
				BIO_printf(bio_err,"bad password read\n");
				goto end;
				}
			}
		}


	if (outf == NULL)
		{
		BIO_set_fp(out,stdout,BIO_NOCLOSE);
#ifndef OPENSSL_NO_SETVBUF_IONBF
		if (bufsize != NULL)
			setvbuf(stdout, (char *)NULL, _IONBF, 0);
#endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
#ifdef OPENSSL_SYS_VMS
		{
		BIO *tmpbio = BIO_new(BIO_f_linebuffer());
		out = BIO_push(tmpbio, out);
		}
#endif
		}
	else
		{
		if (BIO_write_filename(out,outf) <= 0)
			{
			perror(outf);
			goto end;
			}
		}

	rbio=in;
	wbio=out;

#ifdef ZLIB

	if (do_zlib)
		{
		if ((bzl=BIO_new(BIO_f_zlib())) == NULL)
			goto end;
		if (enc)
			wbio=BIO_push(bzl,wbio);
		else
			rbio=BIO_push(bzl,rbio);
		}
#endif

	if (base64)
		{
		if ((b64=BIO_new(BIO_f_base64())) == NULL)
			goto end;
		if (debug)
			{
			BIO_set_callback(b64,BIO_debug_callback);
			BIO_set_callback_arg(b64,(char *)bio_err);
			}
		if (olb64)
			BIO_set_flags(b64,BIO_FLAGS_BASE64_NO_NL);
		if (enc)
			wbio=BIO_push(b64,wbio);
		else
			rbio=BIO_push(b64,rbio);
		}

	if (cipher != NULL)
		{
		/* Note that str is NULL if a key was passed on the command
		 * line, so we get no salt in that case. Is this a bug?
		 */
		if (str != NULL)
			{
			/* Salt handling: if encrypting generate a salt and
			 * write to output BIO. If decrypting read salt from
			 * input BIO.
			 */
			unsigned char *sptr;
			if(nosalt) sptr = NULL;
			else {
				if(enc) {
					if(hsalt) {
						if(!set_hex(hsalt,salt,sizeof salt)) {
							BIO_printf(bio_err,
								"invalid hex salt value\n");
							goto end;
						}
					} else if (RAND_pseudo_bytes(salt, sizeof salt) < 0)
						goto end;
					/* If -P option then don't bother writing */
					if((printkey != 2)
					   && (BIO_write(wbio,magic,
							 sizeof magic-1) != sizeof magic-1
					       || BIO_write(wbio,
							    (char *)salt,
							    sizeof salt) != sizeof salt)) {
						BIO_printf(bio_err,"error writing output file\n");
						goto end;
					}
				} else if(BIO_read(rbio,mbuf,sizeof mbuf) != sizeof mbuf
					  || BIO_read(rbio,
						      (unsigned char *)salt,
				    sizeof salt) != sizeof salt) {
					BIO_printf(bio_err,"error reading input file\n");
					goto end;
				} else if(memcmp(mbuf,magic,sizeof magic-1)) {
				    BIO_printf(bio_err,"bad magic number\n");
				    goto end;
				}

				sptr = salt;
			}

			EVP_BytesToKey(cipher,dgst,sptr,
				(unsigned char *)str,
				strlen(str),1,key,iv);
			/* zero the complete buffer or the string
			 * passed from the command line
			 * bug picked up by
			 * Larry J. Hughes Jr. <*****@*****.**> */
			if (str == strbuf)
				OPENSSL_cleanse(str,SIZE);
			else
				OPENSSL_cleanse(str,strlen(str));
			}
		if ((hiv != NULL) && !set_hex(hiv,iv,sizeof iv))
			{
			BIO_printf(bio_err,"invalid hex iv value\n");
			goto end;
			}
		if ((hiv == NULL) && (str == NULL)
		    && EVP_CIPHER_iv_length(cipher) != 0)
			{
			/* No IV was explicitly set and no IV was generated
			 * during EVP_BytesToKey. Hence the IV is undefined,
			 * making correct decryption impossible. */
			BIO_printf(bio_err, "iv undefined\n");
			goto end;
			}
		if ((hkey != NULL) && !set_hex(hkey,key,sizeof key))
			{
			BIO_printf(bio_err,"invalid hex key value\n");
			goto end;
			}

		if ((benc=BIO_new(BIO_f_cipher())) == NULL)
			goto end;

		/* Since we may be changing parameters work on the encryption
		 * context rather than calling BIO_set_cipher().
		 */

		BIO_get_cipher_ctx(benc, &ctx);

		if (non_fips_allow)
			EVP_CIPHER_CTX_set_flags(ctx,
				EVP_CIPH_FLAG_NON_FIPS_ALLOW);

		if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc))
			{
			BIO_printf(bio_err, "Error setting cipher %s\n",
				EVP_CIPHER_name(cipher));
			ERR_print_errors(bio_err);
			goto end;
			}

		if (nopad)
			EVP_CIPHER_CTX_set_padding(ctx, 0);

		if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc))
			{
			BIO_printf(bio_err, "Error setting cipher %s\n",
				EVP_CIPHER_name(cipher));
			ERR_print_errors(bio_err);
			goto end;
			}

		if (debug)
			{
			BIO_set_callback(benc,BIO_debug_callback);
			BIO_set_callback_arg(benc,(char *)bio_err);
			}

		if (printkey)
			{
			if (!nosalt)
				{
				printf("salt=");
				for (i=0; i<(int)sizeof(salt); i++)
					printf("%02X",salt[i]);
				printf("\n");
				}
			if (cipher->key_len > 0)
				{
				printf("key=");
				for (i=0; i<cipher->key_len; i++)
					printf("%02X",key[i]);
				printf("\n");
				}
			if (cipher->iv_len > 0)
				{
				printf("iv =");
				for (i=0; i<cipher->iv_len; i++)
					printf("%02X",iv[i]);
				printf("\n");
				}
			if (printkey == 2)
				{
				ret=0;
				goto end;
				}
			}
		}

	/* Only encrypt/decrypt as we write the file */
	if (benc != NULL)
		wbio=BIO_push(benc,wbio);

	for (;;)
		{
		inl=BIO_read(rbio,(char *)buff,bsize);
		if (inl <= 0) break;
		if (BIO_write(wbio,(char *)buff,inl) != inl)
			{
			BIO_printf(bio_err,"error writing output file\n");
			goto end;
			}
		}
	if (!BIO_flush(wbio))
		{
		BIO_printf(bio_err,"bad decrypt\n");
		goto end;
		}

	ret=0;
	if (verbose)
		{
		BIO_printf(bio_err,"bytes read   :%8ld\n",BIO_number_read(in));
		BIO_printf(bio_err,"bytes written:%8ld\n",BIO_number_written(out));
		}
end:
	ERR_print_errors(bio_err);
	if (strbuf != NULL) OPENSSL_free(strbuf);
	if (buff != NULL) OPENSSL_free(buff);
	if (in != NULL) BIO_free(in);
	if (out != NULL) BIO_free_all(out);
	if (benc != NULL) BIO_free(benc);
	if (b64 != NULL) BIO_free(b64);
#ifdef ZLIB
	if (bzl != NULL) BIO_free(bzl);
#endif
	if(pass) OPENSSL_free(pass);
	apps_shutdown();
	OPENSSL_EXIT(ret);
	}
Exemplo n.º 13
0
int main(int argc, char *argv[])
{
    FILE *in=NULL,*out=NULL;
    char *infile=NULL,*outfile=NULL,*keystr=NULL;
    RC4_KEY key;
    char buf[BUFSIZ];
    int badops=0,i;
    char **pp;
    unsigned char md[MD5_DIGEST_LENGTH];

    argc--;
    argv++;
    while (argc >= 1)
    {
        if 	(strcmp(*argv,"-in") == 0)
        {
            if (--argc < 1) goto bad;
            infile= *(++argv);
        }
        else if (strcmp(*argv,"-out") == 0)
        {
            if (--argc < 1) goto bad;
            outfile= *(++argv);
        }
        else if (strcmp(*argv,"-key") == 0)
        {
            if (--argc < 1) goto bad;
            keystr= *(++argv);
        }
        else
        {
            fprintf(stderr,"unknown option %s\n",*argv);
            badops=1;
            break;
        }
        argc--;
        argv++;
    }

    if (badops)
    {
bad:
        for (pp=usage; (*pp != NULL); pp++)
            fprintf(stderr,"%s",*pp);
        exit(1);
    }

    if (infile == NULL)
        in=stdin;
    else
    {
        in=fopen(infile,"r");
        if (in == NULL)
        {
            perror("open");
            exit(1);
        }

    }
    if (outfile == NULL)
        out=stdout;
    else
    {
        out=fopen(outfile,"w");
        if (out == NULL)
        {
            perror("open");
            exit(1);
        }
    }

#ifdef OPENSSL_SYS_MSDOS
    /* This should set the file to binary mode. */
    {
#include <fcntl.h>
        setmode(fileno(in),O_BINARY);
        setmode(fileno(out),O_BINARY);
    }
#endif

    if (keystr == NULL)
    {   /* get key */
        i=EVP_read_pw_string(buf,BUFSIZ,"Enter RC4 password:"******"bad password read\n");
            exit(1);
        }
        keystr=buf;
    }

    EVP_Digest((unsigned char *)keystr,strlen(keystr),md,NULL,EVP_md5(),NULL);
    OPENSSL_cleanse(keystr,strlen(keystr));
    RC4_set_key(&key,MD5_DIGEST_LENGTH,md);

    for(;;)
    {
        i=fread(buf,1,BUFSIZ,in);
        if (i == 0) break;
        if (i < 0)
        {
            perror("read");
            exit(1);
        }
        RC4(&key,(unsigned int)i,(unsigned char *)buf,
            (unsigned char *)buf);
        i=fwrite(buf,(unsigned int)i,1,out);
        if (i != 1)
        {
            perror("write");
            exit(1);
        }
    }
    fclose(out);
    fclose(in);
    exit(0);
    return(1);
}
Exemplo n.º 14
0
int MAIN(int argc, char **argv)
{
    ENGINE *e = NULL;
    char *infile=NULL, *outfile=NULL, *keyname = NULL;	
    char *certfile=NULL;
    BIO *in=NULL, *out = NULL;
    char **args;
    char *name = NULL;
    char *csp_name = NULL;
    PKCS12 *p12 = NULL;
    char pass[50], macpass[50];
    int export_cert = 0;
    int options = 0;
    int chain = 0;
    int badarg = 0;
    int iter = PKCS12_DEFAULT_ITER;
    int maciter = PKCS12_DEFAULT_ITER;
    int twopass = 0;
    int keytype = 0;
    int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
    int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
    int ret = 1;
    int macver = 1;
    int noprompt = 0;
    STACK *canames = NULL;
    char *cpass = NULL, *mpass = NULL;
    char *passargin = NULL, *passargout = NULL, *passarg = NULL;
    char *passin = NULL, *passout = NULL;
    char *inrand = NULL;
    char *CApath = NULL, *CAfile = NULL;
    char *engine=NULL;

    apps_startup();

    enc = EVP_des_ede3_cbc();
    if (bio_err == NULL ) bio_err = BIO_new_fp (stderr, BIO_NOCLOSE);

	if (!load_config(bio_err, NULL))
		goto end;

    args = argv + 1;


    while (*args) {
	if (*args[0] == '-') {
		if (!strcmp (*args, "-nokeys")) options |= NOKEYS;
		else if (!strcmp (*args, "-keyex")) keytype = KEY_EX;
		else if (!strcmp (*args, "-keysig")) keytype = KEY_SIG;
		else if (!strcmp (*args, "-nocerts")) options |= NOCERTS;
		else if (!strcmp (*args, "-clcerts")) options |= CLCERTS;
		else if (!strcmp (*args, "-cacerts")) options |= CACERTS;
		else if (!strcmp (*args, "-noout")) options |= (NOKEYS|NOCERTS);
		else if (!strcmp (*args, "-info")) options |= INFO;
		else if (!strcmp (*args, "-chain")) chain = 1;
		else if (!strcmp (*args, "-twopass")) twopass = 1;
		else if (!strcmp (*args, "-nomacver")) macver = 0;
		else if (!strcmp (*args, "-descert"))
    			cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
		else if (!strcmp (*args, "-export")) export_cert = 1;
		else if (!strcmp (*args, "-des")) enc=EVP_des_cbc();
#ifndef OPENSSL_NO_IDEA
		else if (!strcmp (*args, "-idea")) enc=EVP_idea_cbc();
#endif
		else if (!strcmp (*args, "-des3")) enc = EVP_des_ede3_cbc();
#ifndef OPENSSL_NO_AES
		else if (!strcmp(*args,"-aes128")) enc=EVP_aes_128_cbc();
		else if (!strcmp(*args,"-aes192")) enc=EVP_aes_192_cbc();
		else if (!strcmp(*args,"-aes256")) enc=EVP_aes_256_cbc();
#endif
		else if (!strcmp (*args, "-noiter")) iter = 1;
		else if (!strcmp (*args, "-maciter"))
					 maciter = PKCS12_DEFAULT_ITER;
		else if (!strcmp (*args, "-nomaciter"))
					 maciter = 1;
		else if (!strcmp (*args, "-nodes")) enc=NULL;
		else if (!strcmp (*args, "-certpbe")) {
			if (args[1]) {
				args++;
				cert_pbe=OBJ_txt2nid(*args);
				if(cert_pbe == NID_undef) {
					BIO_printf(bio_err,
						 "Unknown PBE algorithm %s\n", *args);
					badarg = 1;
				}
			} else badarg = 1;
		} else if (!strcmp (*args, "-keypbe")) {
			if (args[1]) {
				args++;
				key_pbe=OBJ_txt2nid(*args);
				if(key_pbe == NID_undef) {
					BIO_printf(bio_err,
						 "Unknown PBE algorithm %s\n", *args);
					badarg = 1;
				}
			} else badarg = 1;
		} else if (!strcmp (*args, "-rand")) {
		    if (args[1]) {
			args++;	
			inrand = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-inkey")) {
		    if (args[1]) {
			args++;	
			keyname = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-certfile")) {
		    if (args[1]) {
			args++;	
			certfile = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-name")) {
		    if (args[1]) {
			args++;	
			name = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-CSP")) {
		    if (args[1]) {
			args++;	
			csp_name = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-caname")) {
		    if (args[1]) {
			args++;	
			if (!canames) canames = sk_new_null();
			sk_push(canames, *args);
		    } else badarg = 1;
		} else if (!strcmp (*args, "-in")) {
		    if (args[1]) {
			args++;	
			infile = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-out")) {
		    if (args[1]) {
			args++;	
			outfile = *args;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-passin")) {
		    if (args[1]) {
			args++;	
			passargin = *args;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-passout")) {
		    if (args[1]) {
			args++;	
			passargout = *args;
		    } else badarg = 1;
		} else if (!strcmp (*args, "-password")) {
		    if (args[1]) {
			args++;	
			passarg = *args;
		    	noprompt = 1;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-CApath")) {
		    if (args[1]) {
			args++;	
			CApath = *args;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-CAfile")) {
		    if (args[1]) {
			args++;	
			CAfile = *args;
		    } else badarg = 1;
		} else if (!strcmp(*args,"-engine")) {
		    if (args[1]) {
			args++;	
			engine = *args;
		    } else badarg = 1;
		} else badarg = 1;

	} else badarg = 1;
	args++;
    }

    if (badarg) {
	BIO_printf (bio_err, "Usage: pkcs12 [options]\n");
	BIO_printf (bio_err, "where options are\n");
	BIO_printf (bio_err, "-export       output PKCS12 file\n");
	BIO_printf (bio_err, "-chain        add certificate chain\n");
	BIO_printf (bio_err, "-inkey file   private key if not infile\n");
	BIO_printf (bio_err, "-certfile f   add all certs in f\n");
	BIO_printf (bio_err, "-CApath arg   - PEM format directory of CA's\n");
	BIO_printf (bio_err, "-CAfile arg   - PEM format file of CA's\n");
	BIO_printf (bio_err, "-name \"name\"  use name as friendly name\n");
	BIO_printf (bio_err, "-caname \"nm\"  use nm as CA friendly name (can be used more than once).\n");
	BIO_printf (bio_err, "-in  infile   input filename\n");
	BIO_printf (bio_err, "-out outfile  output filename\n");
	BIO_printf (bio_err, "-noout        don't output anything, just verify.\n");
	BIO_printf (bio_err, "-nomacver     don't verify MAC.\n");
	BIO_printf (bio_err, "-nocerts      don't output certificates.\n");
	BIO_printf (bio_err, "-clcerts      only output client certificates.\n");
	BIO_printf (bio_err, "-cacerts      only output CA certificates.\n");
	BIO_printf (bio_err, "-nokeys       don't output private keys.\n");
	BIO_printf (bio_err, "-info         give info about PKCS#12 structure.\n");
	BIO_printf (bio_err, "-des          encrypt private keys with DES\n");
	BIO_printf (bio_err, "-des3         encrypt private keys with triple DES (default)\n");
#ifndef OPENSSL_NO_IDEA
	BIO_printf (bio_err, "-idea         encrypt private keys with idea\n");
#endif
#ifndef OPENSSL_NO_AES
	BIO_printf (bio_err, "-aes128, -aes192, -aes256\n");
	BIO_printf (bio_err, "              encrypt PEM output with cbc aes\n");
#endif
	BIO_printf (bio_err, "-nodes        don't encrypt private keys\n");
	BIO_printf (bio_err, "-noiter       don't use encryption iteration\n");
	BIO_printf (bio_err, "-maciter      use MAC iteration\n");
	BIO_printf (bio_err, "-twopass      separate MAC, encryption passwords\n");
	BIO_printf (bio_err, "-descert      encrypt PKCS#12 certificates with triple DES (default RC2-40)\n");
	BIO_printf (bio_err, "-certpbe alg  specify certificate PBE algorithm (default RC2-40)\n");
	BIO_printf (bio_err, "-keypbe alg   specify private key PBE algorithm (default 3DES)\n");
	BIO_printf (bio_err, "-keyex        set MS key exchange type\n");
	BIO_printf (bio_err, "-keysig       set MS key signature type\n");
	BIO_printf (bio_err, "-password p   set import/export password source\n");
	BIO_printf (bio_err, "-passin p     input file pass phrase source\n");
	BIO_printf (bio_err, "-passout p    output file pass phrase source\n");
	BIO_printf (bio_err, "-engine e     use engine e, possibly a hardware device.\n");
	BIO_printf(bio_err,  "-rand file%cfile%c...\n", LIST_SEPARATOR_CHAR, LIST_SEPARATOR_CHAR);
	BIO_printf(bio_err,  "              load the file (or the files in the directory) into\n");
	BIO_printf(bio_err,  "              the random number generator\n");
    	goto end;
    }

    e = setup_engine(bio_err, engine, 0);

    if(passarg) {
	if(export_cert) passargout = passarg;
	else passargin = passarg;
    }

    if(!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
	BIO_printf(bio_err, "Error getting passwords\n");
	goto end;
    }

    if(!cpass) {
    	if(export_cert) cpass = passout;
    	else cpass = passin;
    }

    if(cpass) {
	mpass = cpass;
	noprompt = 1;
    } else {
	cpass = pass;
	mpass = macpass;
    }

    if(export_cert || inrand) {
    	app_RAND_load_file(NULL, bio_err, (inrand != NULL));
        if (inrand != NULL)
		BIO_printf(bio_err,"%ld semi-random bytes loaded\n",
			app_RAND_load_files(inrand));
    }
    ERR_load_crypto_strings();

#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("read files");
#endif

    if (!infile) in = BIO_new_fp(stdin, BIO_NOCLOSE);
    else in = BIO_new_file(infile, "rb");
    if (!in) {
	    BIO_printf(bio_err, "Error opening input file %s\n",
						infile ? infile : "<stdin>");
	    perror (infile);
	    goto end;
   }

#if 0
   if (certfile) {
    	if(!(certsin = BIO_new_file(certfile, "r"))) {
	    BIO_printf(bio_err, "Can't open certificate file %s\n", certfile);
	    perror (certfile);
	    goto end;
	}
    }

    if (keyname) {
    	if(!(inkey = BIO_new_file(keyname, "r"))) {
	    BIO_printf(bio_err, "Can't key certificate file %s\n", keyname);
	    perror (keyname);
	    goto end;
	}
     }
#endif

#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
    CRYPTO_push_info("write files");
#endif

    if (!outfile) {
	out = BIO_new_fp(stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
	{
	    BIO *tmpbio = BIO_new(BIO_f_linebuffer());
	    out = BIO_push(tmpbio, out);
	}
#endif
    } else out = BIO_new_file(outfile, "wb");
    if (!out) {
	BIO_printf(bio_err, "Error opening output file %s\n",
						outfile ? outfile : "<stdout>");
	perror (outfile);
	goto end;
    }
    if (twopass) {
#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("read MAC password");
#endif
	if(EVP_read_pw_string (macpass, sizeof macpass, "Enter MAC Password:"******"Can't read Password\n");
    	    goto end;
       	}
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif
    }

    if (export_cert) {
	EVP_PKEY *key = NULL;
	STACK_OF(PKCS12_SAFEBAG) *bags = NULL;
	STACK_OF(PKCS7) *safes = NULL;
	PKCS12_SAFEBAG *bag = NULL;
	PKCS8_PRIV_KEY_INFO *p8 = NULL;
	PKCS7 *authsafe = NULL;
	X509 *ucert = NULL;
	STACK_OF(X509) *certs=NULL;
	char *catmp = NULL;
	int i;
	unsigned char keyid[EVP_MAX_MD_SIZE];
	unsigned int keyidlen = 0;

#ifdef CRYPTO_MDEBUG
	CRYPTO_push_info("process -export_cert");
	CRYPTO_push_info("reading private key");
#endif
	key = load_key(bio_err, keyname ? keyname : infile, FORMAT_PEM, 1,
		passin, e, "private key");
	if (!key) {
		goto export_end;
	}

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("reading certs from input");
#endif

	/* Load in all certs in input file */
	if(!(certs = load_certs(bio_err, infile, FORMAT_PEM, NULL, e,
		"certificates"))) {
		goto export_end;
	}

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("reading certs from input 2");
#endif

	for(i = 0; i < sk_X509_num(certs); i++) {
		ucert = sk_X509_value(certs, i);
		if(X509_check_private_key(ucert, key)) {
			X509_digest(ucert, EVP_sha1(), keyid, &keyidlen);
			break;
		}
	}
	if(!keyidlen) {
		ucert = NULL;
		BIO_printf(bio_err, "No certificate matches private key\n");
		goto export_end;
	}
	
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("reading certs from certfile");
#endif

	bags = sk_PKCS12_SAFEBAG_new_null ();

	/* Add any more certificates asked for */
	if (certfile) {
		STACK_OF(X509) *morecerts=NULL;
		if(!(morecerts = load_certs(bio_err, certfile, FORMAT_PEM,
					    NULL, e,
					    "certificates from certfile"))) {
			goto export_end;
		}
		while(sk_X509_num(morecerts) > 0) {
			sk_X509_push(certs, sk_X509_shift(morecerts));
		}
		sk_X509_free(morecerts);
 	}

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("building chain");
#endif

	/* If chaining get chain from user cert */
	if (chain) {
        	int vret;
		STACK_OF(X509) *chain2;
		X509_STORE *store = X509_STORE_new();
		if (!store)
			{
			BIO_printf (bio_err, "Memory allocation error\n");
			goto export_end;
			}
		if (!X509_STORE_load_locations(store, CAfile, CApath))
			X509_STORE_set_default_paths (store);

		vret = get_cert_chain (ucert, store, &chain2);
		X509_STORE_free(store);

		if (!vret) {
		    /* Exclude verified certificate */
		    for (i = 1; i < sk_X509_num (chain2) ; i++) 
			sk_X509_push(certs, sk_X509_value (chain2, i));
		    /* Free first certificate */
		    X509_free(sk_X509_value(chain2, 0));
		    sk_X509_free(chain2);
		} else {
			BIO_printf (bio_err, "Error %s getting chain.\n",
					X509_verify_cert_error_string(vret));
			goto export_end;
		}			
    	}

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("building bags");
#endif

	/* We now have loads of certificates: include them all */
	for(i = 0; i < sk_X509_num(certs); i++) {
		X509 *cert = NULL;
		cert = sk_X509_value(certs, i);
		bag = PKCS12_x5092certbag(cert);
		/* If it matches private key set id */
		if(cert == ucert) {
			if(name) PKCS12_add_friendlyname(bag, name, -1);
			PKCS12_add_localkeyid(bag, keyid, keyidlen);
		} else if((catmp = sk_shift(canames))) 
				PKCS12_add_friendlyname(bag, catmp, -1);
		sk_PKCS12_SAFEBAG_push(bags, bag);
	}
	sk_X509_pop_free(certs, X509_free);
	certs = NULL;

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("encrypting bags");
#endif

	if(!noprompt &&
		EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:"******"Can't read Password\n");
	    goto export_end;
        }
	if (!twopass) strcpy(macpass, pass);
	/* Turn certbags into encrypted authsafe */
	authsafe = PKCS12_pack_p7encdata(cert_pbe, cpass, -1, NULL, 0,
								 iter, bags);
	sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
	bags = NULL;

	if (!authsafe) {
		ERR_print_errors (bio_err);
		goto export_end;
	}

	safes = sk_PKCS7_new_null ();
	sk_PKCS7_push (safes, authsafe);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("building shrouded key bag");
#endif

	/* Make a shrouded key bag */
	p8 = EVP_PKEY2PKCS8 (key);
	if(keytype) PKCS8_add_keyusage(p8, keytype);
	bag = PKCS12_MAKE_SHKEYBAG(key_pbe, cpass, -1, NULL, 0, iter, p8);
	PKCS8_PRIV_KEY_INFO_free(p8);
	p8 = NULL;
        if (name) PKCS12_add_friendlyname (bag, name, -1);
	if(csp_name) PKCS12_add_CSPName_asc(bag, csp_name, -1);
	PKCS12_add_localkeyid (bag, keyid, keyidlen);
	bags = sk_PKCS12_SAFEBAG_new_null();
	sk_PKCS12_SAFEBAG_push (bags, bag);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("encrypting shrouded key bag");
#endif

	/* Turn it into unencrypted safe bag */
	authsafe = PKCS12_pack_p7data (bags);
	sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);
	bags = NULL;
	sk_PKCS7_push (safes, authsafe);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("building pkcs12");
#endif

	p12 = PKCS12_init(NID_pkcs7_data);

	PKCS12_pack_authsafes(p12, safes);

	sk_PKCS7_pop_free(safes, PKCS7_free);
	safes = NULL;

	PKCS12_set_mac (p12, mpass, -1, NULL, 0, maciter, NULL);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("writing pkcs12");
#endif

	i2d_PKCS12_bio (out, p12);

	ret = 0;

    export_end:
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_pop_info();
	CRYPTO_push_info("process -export_cert: freeing");
#endif

	if (key) EVP_PKEY_free(key);
	if (certs) sk_X509_pop_free(certs, X509_free);
	if (safes) sk_PKCS7_pop_free(safes, PKCS7_free);
	if (bags) sk_PKCS12_SAFEBAG_pop_free(bags, PKCS12_SAFEBAG_free);

#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
#endif
	goto end;
	
    }

    if (!(p12 = d2i_PKCS12_bio (in, NULL))) {
	ERR_print_errors(bio_err);
	goto end;
    }

#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("read import password");
#endif
    if(!noprompt && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:"******"Can't read Password\n");
	goto end;
    }
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif

    if (!twopass) strcpy(macpass, pass);

    if (options & INFO) BIO_printf (bio_err, "MAC Iteration %ld\n", p12->mac->iter ? ASN1_INTEGER_get (p12->mac->iter) : 1);
    if(macver) {
#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("verify MAC");
#endif
	/* If we enter empty password try no password first */
	if(!macpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
		/* If mac and crypto pass the same set it to NULL too */
		if(!twopass) cpass = NULL;
	} else if (!PKCS12_verify_mac(p12, mpass, -1)) {
	    BIO_printf (bio_err, "Mac verify error: invalid password?\n");
	    ERR_print_errors (bio_err);
	    goto end;
	}
	BIO_printf (bio_err, "MAC verified OK\n");
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif
    }

#ifdef CRYPTO_MDEBUG
    CRYPTO_push_info("output keys and certificates");
#endif
    if (!dump_certs_keys_p12 (out, p12, cpass, -1, options, passout)) {
	BIO_printf(bio_err, "Error outputting keys and certificates\n");
	ERR_print_errors (bio_err);
	goto end;
    }
#ifdef CRYPTO_MDEBUG
    CRYPTO_pop_info();
#endif
    ret = 0;
 end:
    if (p12) PKCS12_free(p12);
    if(export_cert || inrand) app_RAND_write_file(NULL, bio_err);
#ifdef CRYPTO_MDEBUG
    CRYPTO_remove_all_info();
#endif
    BIO_free(in);
    BIO_free_all(out);
    if (canames) sk_free(canames);
    if(passin) OPENSSL_free(passin);
    if(passout) OPENSSL_free(passout);
    apps_shutdown();
    OPENSSL_EXIT(ret);
}
Exemplo n.º 15
0
int main(int argc, char **argv)
{
	TSS_HCONTEXT	hContext;
	TSS_FLAG	initFlags = TSS_KEY_TYPE_LEGACY | TSS_KEY_VOLATILE;
	TSS_HKEY	hKey;
	TSS_HKEY	hSRK;
	TSS_RESULT	result;
	TSS_HPOLICY	srkUsagePolicy, keyUsagePolicy, keyMigrationPolicy;
	BYTE		*blob;
	UINT32		blob_size, srk_authusage;
	BIO		*outb;
	ASN1_OCTET_STRING *blob_str;
	unsigned char	*blob_asn1 = NULL;
	int		asn1_len;
	char		*filename, c, *openssl_key = NULL;
	int		option_index, auth = 0, popup = 0, wrap = 0, well_known = 0;
	UINT32		enc_scheme = TSS_ES_RSAESPKCSV15;
	UINT32		sig_scheme = TSS_SS_RSASSAPKCS1V15_DER;
	UINT32		key_size = 2048;
	RSA		*rsa;

	while (1) {
		option_index = 0;
		c = getopt_long(argc, argv, "pe:q:s:azhw:",
				long_options, &option_index);
		if (c == -1)
			break;

		switch (c) {
			case 'a':
				initFlags |= TSS_KEY_AUTHORIZATION;
				auth = 1;
				break;
			case 'h':
				usage(argv[0]);
				break;
			case 's':
				key_size = atoi(optarg);
				break;
			case 'e':
				if (!strncasecmp("oaep", optarg, 4)) {
					enc_scheme = TSS_ES_RSAESOAEP_SHA1_MGF1;
				} else if (strncasecmp("pkcs", optarg, 4)) {
					usage(argv[0]);
				}
				break;
			case 'q':
				if (!strncasecmp("der", optarg, 3)) {
					sig_scheme = TSS_SS_RSASSAPKCS1V15_SHA1;
				} else if (strncasecmp("sha", optarg, 3)) {
					usage(argv[0]);
				}
				break;
			case 'p':
				initFlags |= TSS_KEY_AUTHORIZATION;
				auth = 1;
				popup = 1;
				break;
			case 'w':
				initFlags |= TSS_KEY_MIGRATABLE;
				wrap = 1;
				openssl_key = optarg;
				break;
			case 'z':
				well_known = 1;
				break;
			default:
				usage(argv[0]);
				break;
		}
	}

	/* set up the key option flags */
	switch (key_size) {
		case 512:
			initFlags |= TSS_KEY_SIZE_512;
			break;
		case 1024:
			initFlags |= TSS_KEY_SIZE_1024;
			break;
		case 2048:
			initFlags |= TSS_KEY_SIZE_2048;
			break;
		case 4096:
			initFlags |= TSS_KEY_SIZE_4096;
			break;
		case 8192:
			initFlags |= TSS_KEY_SIZE_8192;
			break;
		case 16384:
			initFlags |= TSS_KEY_SIZE_16384;
			break;
		default:
			usage(argv[0]);
			break;
	}
#if 0
	while (argc--) {
		printf("argv[%d] = \"%s\"\n", argc, argv[argc]);
	}
	exit(1);
#endif
	filename = argv[argc - 1];
	if (argc < 2 || filename[0] == '-')
		usage(argv[0]);

		//Create Context
	if ((result = Tspi_Context_Create(&hContext))) {
		print_error("Tspi_Context_Create", result);
		exit(result);
	}
		//Connect Context
	if ((result = Tspi_Context_Connect(hContext, NULL))) {
		print_error("Tspi_Context_Connect", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}

		//Create Object
	if ((result = Tspi_Context_CreateObject(hContext,
						TSS_OBJECT_TYPE_RSAKEY,
						initFlags, &hKey))) {
		print_error("Tspi_Context_CreateObject", result);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	if ((result = Tspi_SetAttribUint32(hKey, TSS_TSPATTRIB_KEY_INFO,
					   TSS_TSPATTRIB_KEYINFO_SIGSCHEME,
					   sig_scheme))) {
		print_error("Tspi_SetAttribUint32", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	if ((result = Tspi_SetAttribUint32(hKey, TSS_TSPATTRIB_KEY_INFO,
					   TSS_TSPATTRIB_KEYINFO_ENCSCHEME,
					   enc_scheme))) {
		print_error("Tspi_SetAttribUint32", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}

		//Load Key By UUID
	if ((result = Tspi_Context_LoadKeyByUUID(hContext, TSS_PS_TYPE_SYSTEM,
						 SRK_UUID, &hSRK))) {
		print_error("Tspi_Context_LoadKeyByUUID", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	if ((result = Tspi_GetAttribUint32(hSRK, TSS_TSPATTRIB_KEY_INFO,
					   TSS_TSPATTRIB_KEYINFO_AUTHUSAGE,
					   &srk_authusage))) {
		print_error("Tspi_GetAttribUint32", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	if (srk_authusage) {

		if ((result = Tspi_GetPolicyObject(hSRK, TSS_POLICY_USAGE,
						   &srkUsagePolicy))) {
			print_error("Tspi_GetPolicyObject", result);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}

		if (well_known) {

			BYTE well_known_secret[] = TSS_WELL_KNOWN_SECRET;

			//Set Well Known Secret
			if ((result = Tspi_Policy_SetSecret(srkUsagePolicy,
							TSS_SECRET_MODE_SHA1,
							sizeof(well_known_secret),
							(BYTE *)well_known_secret))) {
				print_error("Tspi_Policy_SetSecret", result);
				Tspi_Context_Close(hContext);
				exit(result);
			}
		} else {

			char *authdata = calloc(1, 128);

			if (!authdata) {
				fprintf(stderr, "malloc failed.\n");
				Tspi_Context_Close(hContext);
				exit(result);
			}

			if (EVP_read_pw_string(authdata, 128, "SRK Password: "******"Tspi_Policy_SetSecret", result);
				free(authdata);
				Tspi_Context_Close(hContext);
				exit(result);
			}

			free(authdata);
		}
	}

	if (auth) {
		if ((result = Tspi_Context_CreateObject(hContext,
							TSS_OBJECT_TYPE_POLICY,
							TSS_POLICY_USAGE,
							&keyUsagePolicy))) {
			print_error("Tspi_Context_CreateObject", result);
			Tspi_Context_Close(hContext);
			exit(result);
		}

		if (popup) {
			//Set Secret
			if ((result = Tspi_Policy_SetSecret(keyUsagePolicy,
							    TSS_SECRET_MODE_POPUP,
							    0, NULL))) {
				print_error("Tspi_Policy_SetSecret", result);
				Tspi_Context_Close(hContext);
				exit(result);
			}
		} else {
			char *authdata = calloc(1, 128);

			if (!authdata) {
				fprintf(stderr, "malloc failed.\n");
				Tspi_Context_Close(hContext);
				exit(result);
			}

			if (EVP_read_pw_string(authdata, 128,
						"Enter Key Usage Password: "******"Passwords do not match.\n");
				free(authdata);
				Tspi_Context_Close(hContext);
				exit(result);
			}

			//Set Secret
			if ((result = Tspi_Policy_SetSecret(keyUsagePolicy,
							    TSS_SECRET_MODE_PLAIN,
							    strlen(authdata),
							    (BYTE *)authdata))) {
				print_error("Tspi_Policy_SetSecret", result);
				free(authdata);
				Tspi_Context_Close(hContext);
				exit(result);
			}

			free(authdata);
		}

		if ((result = Tspi_Policy_AssignToObject(keyUsagePolicy, hKey))) {
			print_error("Tspi_Policy_AssignToObject", result);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}
	}

	// Create or Wrap Key
	if (wrap) {
		char n[256], p[128];
		unsigned int size_n, size_p;
		BYTE *pubSRK;

		/*Set migration policy needed to wrap the key*/
		if ((result = Tspi_Context_CreateObject(hContext,
						TSS_OBJECT_TYPE_POLICY,
						TSS_POLICY_MIGRATION,
						&keyMigrationPolicy))) {
			print_error("Tspi_Context_CreateObject", result);
			Tspi_Context_Close(hContext);
			exit(result);
		}
		if (auth) {
			char *authdata = calloc(1, 128);

			if (!authdata) {
				fprintf(stderr, "malloc failed.\n");
				Tspi_Context_Close(hContext);
				exit(result);
			}

			if (EVP_read_pw_string(authdata, 128,
						"Enter Key Migration Password: "******"Passwords do not match.\n");
				free(authdata);
				Tspi_Context_Close(hContext);
				exit(result);
			}

			if ((result = Tspi_Policy_SetSecret(keyMigrationPolicy,
							    TSS_SECRET_MODE_PLAIN,
							    strlen(authdata),
							    (BYTE *)authdata))) {
				print_error("Tspi_Policy_SetSecret", result);
				Tspi_Context_Close(hContext);
				exit(result);
			}

			free(authdata);
		}

		if ((result = Tspi_Policy_AssignToObject(keyMigrationPolicy, hKey))) {
			print_error("Tspi_Policy_AssignToObject", result);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}

		/* Pull the PubKRK out of the TPM */
		if ((result = Tspi_Key_GetPubKey(hSRK, &size_n, &pubSRK))) {
			print_error("Tspi_Key_WrapKey", result);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}
		Tspi_Context_FreeMemory(hContext, pubSRK);

		if ((rsa = openssl_read_key(openssl_key)) == NULL) {
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(-1);
		}

		if (RSA_size(rsa) != key_size / 8) {
			fprintf(stderr,
				"Error, key size is incorrect, please use the '-s' option\n");
			RSA_free(rsa);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(-1);
		}

		if (openssl_get_modulus_and_prime(rsa, &size_n, (unsigned char *)n,
						  &size_p, (unsigned char *)p)) {
			fprintf(stderr, "Error getting modulus and prime!\n");
			RSA_free(rsa);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(-1);
		}

		if ((result = Tspi_SetAttribData(hKey, TSS_TSPATTRIB_RSAKEY_INFO,
						 TSS_TSPATTRIB_KEYINFO_RSA_MODULUS,
						 size_n, (BYTE *)n))) {
			print_error("Tspi_SetAttribData (RSA modulus)", result);
			RSA_free(rsa);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(-1);
		}

		if ((result = Tspi_SetAttribData(hKey, TSS_TSPATTRIB_KEY_BLOB,
						 TSS_TSPATTRIB_KEYBLOB_PRIVATE_KEY,
						 size_p, (BYTE *)p))) {
			print_error("Tspi_SetAttribData (private key)", result);
			RSA_free(rsa);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(-1);
		}

		if ((result = Tspi_Key_WrapKey(hKey, hSRK, 0))) {
			print_error("Tspi_Key_WrapKey", result);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}
	} else {
		if ((result = Tspi_Key_CreateKey(hKey, hSRK, 0))) {
			print_error("Tspi_Key_CreateKey", result);
			Tspi_Context_CloseObject(hContext, hKey);
			Tspi_Context_Close(hContext);
			exit(result);
		}
	}

	if ((result = Tspi_GetAttribData(hKey, TSS_TSPATTRIB_KEY_BLOB,
					 TSS_TSPATTRIB_KEYBLOB_BLOB,
					 &blob_size, &blob))) {
		print_error("Tspi_GetAttribData", result);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(result);
	}

	if ((outb = BIO_new_file(filename, "w")) == NULL) {
                fprintf(stderr, "Error opening file for write: %s\n", filename);
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(-1);
	}
	blob_str = ASN1_OCTET_STRING_new();
	if (!blob_str) {
                fprintf(stderr, "Error allocating ASN1_OCTET_STRING\n");
		Tspi_Context_CloseObject(hContext, hKey);
		Tspi_Context_Close(hContext);
		exit(-1);
	}		

	ASN1_STRING_set(blob_str, blob, blob_size);
	asn1_len = i2d_ASN1_OCTET_STRING(blob_str, &blob_asn1);
	PEM_write_bio(outb, "TSS KEY BLOB", "", blob_asn1, asn1_len);

	BIO_free(outb);
	Tspi_Context_Close(hContext);

	printf("Success.\n");

	return 0;
}
Exemplo n.º 16
0
int MAIN(int argc, char **argv)
	{
	ENGINE *e = NULL;
	char **args, *infile = NULL, *outfile = NULL;
	char *passargin = NULL, *passargout = NULL;
	BIO *in = NULL, *out = NULL;
	int topk8 = 0;
	int pbe_nid = -1;
	const EVP_CIPHER *cipher = NULL;
	int iter = PKCS12_DEFAULT_ITER;
	int informat, outformat;
	int p8_broken = PKCS8_OK;
	int nocrypt = 0;
	X509_SIG *p8 = NULL;
	PKCS8_PRIV_KEY_INFO *p8inf = NULL;
	EVP_PKEY *pkey=NULL;
	char pass[50], *passin = NULL, *passout = NULL, *p8pass = NULL;
	int badarg = 0;
	int ret = 1;
#ifndef OPENSSL_NO_ENGINE
	char *engine=NULL;
#endif

	if (bio_err == NULL) bio_err = BIO_new_fp (stderr, BIO_NOCLOSE);

	if (!load_config(bio_err, NULL))
		goto end;

	informat=FORMAT_PEM;
	outformat=FORMAT_PEM;

	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	args = argv + 1;
	while (!badarg && *args && *args[0] == '-')
		{
		if (!strcmp(*args,"-v2"))
			{
			if (args[1])
				{
				args++;
				cipher=EVP_get_cipherbyname(*args);
				if (!cipher)
					{
					BIO_printf(bio_err,
						 "Unknown cipher %s\n", *args);
					badarg = 1;
					}
				}
			else
				badarg = 1;
			}
		else if (!strcmp(*args,"-v1"))
			{
			if (args[1])
				{
				args++;
				pbe_nid=OBJ_txt2nid(*args);
				if (pbe_nid == NID_undef)
					{
					BIO_printf(bio_err,
						 "Unknown PBE algorithm %s\n", *args);
					badarg = 1;
					}
				}
			else
				badarg = 1;
			}
		else if (!strcmp(*args,"-v2prf"))
			{
			if (args[1])
				{
				args++;
				pbe_nid=OBJ_txt2nid(*args);
				if (!EVP_PBE_find(EVP_PBE_TYPE_PRF, pbe_nid, NULL, NULL, 0))
					{
					BIO_printf(bio_err,
						 "Unknown PRF algorithm %s\n", *args);
					badarg = 1;
					}
				}
			else
				badarg = 1;
			}
		else if (!strcmp(*args,"-inform"))
			{
			if (args[1])
				{
				args++;
				informat=str2fmt(*args);
				}
			else badarg = 1;
			}
		else if (!strcmp(*args,"-outform"))
			{
			if (args[1])
				{
				args++;
				outformat=str2fmt(*args);
				}
			else badarg = 1;
			}
		else if (!strcmp (*args, "-topk8"))
			topk8 = 1;
		else if (!strcmp (*args, "-noiter"))
			iter = 1;
        	else if (!strcmp (*args, "-iter"))
		{
		if (!args[1]) goto bad;
		iter = atoi(*(++args));
		if (iter <= 0) goto bad;
		}
		else if (!strcmp (*args, "-nocrypt"))
			nocrypt = 1;
		else if (!strcmp (*args, "-nooct"))
			p8_broken = PKCS8_NO_OCTET;
		else if (!strcmp (*args, "-nsdb"))
			p8_broken = PKCS8_NS_DB;
		else if (!strcmp (*args, "-embed"))
			p8_broken = PKCS8_EMBEDDED_PARAM;
		else if (!strcmp(*args,"-passin"))
			{
			if (!args[1]) goto bad;
			passargin= *(++args);
			}
		else if (!strcmp(*args,"-passout"))
			{
			if (!args[1]) goto bad;
			passargout= *(++args);
			}
#ifndef OPENSSL_NO_ENGINE
		else if (strcmp(*args,"-engine") == 0)
			{
			if (!args[1]) goto bad;
			engine= *(++args);
			}
#endif
		else if (!strcmp (*args, "-in"))
			{
			if (args[1])
				{
				args++;
				infile = *args;
				}
			else badarg = 1;
			}
		else if (!strcmp (*args, "-out"))
			{
			if (args[1])
				{
				args++;
				outfile = *args;
				}
			else badarg = 1;
			}
		else badarg = 1;
		args++;
		}

	if (badarg)
		{
		bad:
		BIO_printf(bio_err, "Usage pkcs8 [options]\n");
		BIO_printf(bio_err, "where options are\n");
		BIO_printf(bio_err, "-in file        input file\n");
		BIO_printf(bio_err, "-inform X       input format (DER or PEM)\n");
		BIO_printf(bio_err, "-passin arg     input file pass phrase source\n");
		BIO_printf(bio_err, "-outform X      output format (DER or PEM)\n");
		BIO_printf(bio_err, "-out file       output file\n");
		BIO_printf(bio_err, "-passout arg    output file pass phrase source\n");
		BIO_printf(bio_err, "-topk8          output PKCS8 file\n");
		BIO_printf(bio_err, "-nooct          use (nonstandard) no octet format\n");
		BIO_printf(bio_err, "-embed          use (nonstandard) embedded DSA parameters format\n");
		BIO_printf(bio_err, "-nsdb           use (nonstandard) DSA Netscape DB format\n");
		BIO_printf(bio_err, "-iter count     use count as iteration count\n");
		BIO_printf(bio_err, "-noiter         use 1 as iteration count\n");
		BIO_printf(bio_err, "-nocrypt        use or expect unencrypted private key\n");
		BIO_printf(bio_err, "-v2 alg         use PKCS#5 v2.0 and cipher \"alg\"\n");
		BIO_printf(bio_err, "-v1 obj         use PKCS#5 v1.5 and cipher \"alg\"\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err," -engine e       use engine e, possibly a hardware device.\n");
#endif
		goto end;
		}

#ifndef OPENSSL_NO_ENGINE
        e = setup_engine(bio_err, engine, 0);
#endif

	if (!app_passwd(bio_err, passargin, passargout, &passin, &passout))
		{
		BIO_printf(bio_err, "Error getting passwords\n");
		goto end;
		}

	if ((pbe_nid == -1) && !cipher)
		pbe_nid = NID_pbeWithMD5AndDES_CBC;

	if (infile)
		{
		if (!(in = BIO_new_file(infile, "rb")))
			{
			BIO_printf(bio_err,
				 "Can't open input file %s\n", infile);
			goto end;
			}
		}
	else
		in = BIO_new_fp (stdin, BIO_NOCLOSE);

	if (outfile)
		{
		if (!(out = BIO_new_file (outfile, "wb")))
			{
			BIO_printf(bio_err,
				 "Can't open output file %s\n", outfile);
			goto end;
			}
		}
	else
		{
		out = BIO_new_fp (stdout, BIO_NOCLOSE);
#ifdef OPENSSL_SYS_VMS
			{
			BIO *tmpbio = BIO_new(BIO_f_linebuffer());
			out = BIO_push(tmpbio, out);
			}
#endif
		}
	if (topk8)
		{
		pkey = load_key(bio_err, infile, informat, 1,
			passin, e, "key");
		if (!pkey)
			goto end;
		if (!(p8inf = EVP_PKEY2PKCS8_broken(pkey, p8_broken)))
			{
			BIO_printf(bio_err, "Error converting key\n");
			ERR_print_errors(bio_err);
			goto end;
			}
		if (nocrypt)
			{
			if (outformat == FORMAT_PEM) 
				PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8inf);
			else if (outformat == FORMAT_ASN1)
				i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8inf);
			else
				{
				BIO_printf(bio_err, "Bad format specified for key\n");
				goto end;
				}
			}
		else
			{
			if (passout)
				p8pass = passout;
			else
				{
				p8pass = pass;
				if (EVP_read_pw_string(pass, sizeof pass, "Enter Encryption Password:"******"Error encrypting key\n");
				ERR_print_errors(bio_err);
				goto end;
				}
			app_RAND_write_file(NULL, bio_err);
			if (outformat == FORMAT_PEM) 
				PEM_write_bio_PKCS8(out, p8);
			else if (outformat == FORMAT_ASN1)
				i2d_PKCS8_bio(out, p8);
			else
				{
				BIO_printf(bio_err, "Bad format specified for key\n");
				goto end;
				}
			}

		ret = 0;
		goto end;
		}

	if (nocrypt)
		{
		if (informat == FORMAT_PEM) 
			p8inf = PEM_read_bio_PKCS8_PRIV_KEY_INFO(in,NULL,NULL, NULL);
		else if (informat == FORMAT_ASN1)
			p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(in, NULL);
		else
			{
			BIO_printf(bio_err, "Bad format specified for key\n");
			goto end;
			}
		}
	else
		{
		if (informat == FORMAT_PEM) 
			p8 = PEM_read_bio_PKCS8(in, NULL, NULL, NULL);
		else if (informat == FORMAT_ASN1)
			p8 = d2i_PKCS8_bio(in, NULL);
		else
			{
			BIO_printf(bio_err, "Bad format specified for key\n");
			goto end;
			}

		if (!p8)
			{
			BIO_printf (bio_err, "Error reading key\n");
			ERR_print_errors(bio_err);
			goto end;
			}
		if (passin)
			p8pass = passin;
		else
			{
			p8pass = pass;
			EVP_read_pw_string(pass, sizeof pass, "Enter Password:"******"Error decrypting key\n");
		ERR_print_errors(bio_err);
		goto end;
		}

	if (!(pkey = EVP_PKCS82PKEY(p8inf)))
		{
		BIO_printf(bio_err, "Error converting key\n");
		ERR_print_errors(bio_err);
		goto end;
		}
	
	if (p8inf->broken)
		{
		BIO_printf(bio_err, "Warning: broken key encoding: ");
		switch (p8inf->broken)
			{
			case PKCS8_NO_OCTET:
			BIO_printf(bio_err, "No Octet String in PrivateKey\n");
			break;

			case PKCS8_EMBEDDED_PARAM:
			BIO_printf(bio_err, "DSA parameters included in PrivateKey\n");
			break;

			case PKCS8_NS_DB:
			BIO_printf(bio_err, "DSA public key include in PrivateKey\n");
			break;

			case PKCS8_NEG_PRIVKEY:
			BIO_printf(bio_err, "DSA private key value is negative\n");
			break;

			default:
			BIO_printf(bio_err, "Unknown broken type\n");
			break;
		}
	}
	
	if (outformat == FORMAT_PEM) 
		PEM_write_bio_PrivateKey(out, pkey, NULL, NULL, 0, NULL, passout);
	else if (outformat == FORMAT_ASN1)
		i2d_PrivateKey_bio(out, pkey);
	else
		{
		BIO_printf(bio_err, "Bad format specified for key\n");
			goto end;
		}
	ret = 0;

	end:
	X509_SIG_free(p8);
	PKCS8_PRIV_KEY_INFO_free(p8inf);
	EVP_PKEY_free(pkey);
	BIO_free_all(out);
	BIO_free(in);
	if (passin)
		OPENSSL_free(passin);
	if (passout)
		OPENSSL_free(passout);

	return ret;
	}
Exemplo n.º 17
0
int
enc_main(int argc, char **argv)
{
	static const char magic[] = "Salted__";
	char mbuf[sizeof magic - 1];
	char *strbuf = NULL, *pass = NULL;
	unsigned char *buff = NULL;
	int bsize = BSIZE;
	int ret = 1, inl;
	unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
	unsigned char salt[PKCS5_SALT_LEN];
#ifdef ZLIB
	BIO *bzl = NULL;
#endif
	EVP_CIPHER_CTX *ctx = NULL;
	const EVP_MD *dgst = NULL;
	BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL;
	BIO *rbio = NULL, *wbio = NULL;
#define PROG_NAME_SIZE  39
	char pname[PROG_NAME_SIZE + 1];
	int i;

	if (single_execution) {
		if (pledge("stdio rpath wpath cpath tty", NULL) == -1) {
			perror("pledge");
			exit(1);
		}
	}

	memset(&enc_config, 0, sizeof(enc_config));
	enc_config.enc = 1;

	/* first check the program name */
	program_name(argv[0], pname, sizeof(pname));

	if (strcmp(pname, "base64") == 0)
		enc_config.base64 = 1;

#ifdef ZLIB
	if (strcmp(pname, "zlib") == 0)
		enc_config.do_zlib = 1;
#endif

	enc_config.cipher = EVP_get_cipherbyname(pname);

#ifdef ZLIB
	if (!enc_config.do_zlib && !enc_config.base64 &&
	    enc_config.cipher == NULL && strcmp(pname, "enc") != 0)
#else
	if (!enc_config.base64 && enc_config.cipher == NULL &&
	    strcmp(pname, "enc") != 0)
#endif
	{
		BIO_printf(bio_err, "%s is an unknown cipher\n", pname);
		goto end;
	}

	if (options_parse(argc, argv, enc_options, NULL, NULL) != 0) {
		enc_usage();
		goto end;
	}

	if (enc_config.keyfile != NULL) {
		static char buf[128];
		FILE *infile;

		infile = fopen(enc_config.keyfile, "r");
		if (infile == NULL) {
			BIO_printf(bio_err, "unable to read key from '%s'\n",
			    enc_config.keyfile);
			goto end;
		}
		buf[0] = '\0';
		if (!fgets(buf, sizeof buf, infile)) {
			BIO_printf(bio_err, "unable to read key from '%s'\n",
			    enc_config.keyfile);
			fclose(infile);
			goto end;
		}
		fclose(infile);
		i = strlen(buf);
		if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r')))
			buf[--i] = '\0';
		if ((i > 0) && ((buf[i - 1] == '\n') || (buf[i - 1] == '\r')))
			buf[--i] = '\0';
		if (i < 1) {
			BIO_printf(bio_err, "zero length password\n");
			goto end;
		}
		enc_config.keystr = buf;
	}

	if (enc_config.md != NULL &&
	    (dgst = EVP_get_digestbyname(enc_config.md)) == NULL) {
		BIO_printf(bio_err,
		    "%s is an unsupported message digest type\n",
		    enc_config.md);
		goto end;
	}
	if (dgst == NULL) {
		dgst = EVP_md5();	/* XXX */
	}

	if (enc_config.bufsize != NULL) {
		char *p = enc_config.bufsize;
		unsigned long n;

		/* XXX - provide an OPTION_ARG_DISKUNIT. */
		for (n = 0; *p != '\0'; p++) {
			i = *p;
			if ((i <= '9') && (i >= '0'))
				n = n * 10 + i - '0';
			else if (i == 'k') {
				n *= 1024;
				p++;
				break;
			}
		}
		if (*p != '\0') {
			BIO_printf(bio_err, "invalid 'bufsize' specified.\n");
			goto end;
		}
		/* It must be large enough for a base64 encoded line. */
		if (enc_config.base64 && n < 80)
			n = 80;

		bsize = (int)n;
		if (enc_config.verbose)
			BIO_printf(bio_err, "bufsize=%d\n", bsize);
	}
	strbuf = malloc(SIZE);
	buff = malloc(EVP_ENCODE_LENGTH(bsize));
	if ((buff == NULL) || (strbuf == NULL)) {
		BIO_printf(bio_err, "malloc failure %ld\n", (long) EVP_ENCODE_LENGTH(bsize));
		goto end;
	}
	in = BIO_new(BIO_s_file());
	out = BIO_new(BIO_s_file());
	if ((in == NULL) || (out == NULL)) {
		ERR_print_errors(bio_err);
		goto end;
	}
	if (enc_config.debug) {
		BIO_set_callback(in, BIO_debug_callback);
		BIO_set_callback(out, BIO_debug_callback);
		BIO_set_callback_arg(in, (char *) bio_err);
		BIO_set_callback_arg(out, (char *) bio_err);
	}
	if (enc_config.inf == NULL) {
		if (enc_config.bufsize != NULL)
			setvbuf(stdin, (char *) NULL, _IONBF, 0);
		BIO_set_fp(in, stdin, BIO_NOCLOSE);
	} else {
		if (BIO_read_filename(in, enc_config.inf) <= 0) {
			perror(enc_config.inf);
			goto end;
		}
	}

	if (!enc_config.keystr && enc_config.passarg) {
		if (!app_passwd(bio_err, enc_config.passarg, NULL,
		    &pass, NULL)) {
			BIO_printf(bio_err, "Error getting password\n");
			goto end;
		}
		enc_config.keystr = pass;
	}
	if (enc_config.keystr == NULL && enc_config.cipher != NULL &&
	    enc_config.hkey == NULL) {
		for (;;) {
			char buf[200];
			int retval;

			retval = snprintf(buf, sizeof buf,
			    "enter %s %s password:"******"encryption" : "decryption");
			if ((size_t)retval >= sizeof buf) {
				BIO_printf(bio_err,
				    "Password prompt too long\n");
				goto end;
			}
			strbuf[0] = '\0';
			i = EVP_read_pw_string((char *)strbuf, SIZE, buf,
			    enc_config.enc);
			if (i == 0) {
				if (strbuf[0] == '\0') {
					ret = 1;
					goto end;
				}
				enc_config.keystr = strbuf;
				break;
			}
			if (i < 0) {
				BIO_printf(bio_err, "bad password read\n");
				goto end;
			}
		}
	}
	if (enc_config.outf == NULL) {
		BIO_set_fp(out, stdout, BIO_NOCLOSE);
		if (enc_config.bufsize != NULL)
			setvbuf(stdout, (char *)NULL, _IONBF, 0);
	} else {
		if (BIO_write_filename(out, enc_config.outf) <= 0) {
			perror(enc_config.outf);
			goto end;
		}
	}

	rbio = in;
	wbio = out;

#ifdef ZLIB
	if (do_zlib) {
		if ((bzl = BIO_new(BIO_f_zlib())) == NULL)
			goto end;
		if (enc)
			wbio = BIO_push(bzl, wbio);
		else
			rbio = BIO_push(bzl, rbio);
	}
#endif

	if (enc_config.base64) {
		if ((b64 = BIO_new(BIO_f_base64())) == NULL)
			goto end;
		if (enc_config.debug) {
			BIO_set_callback(b64, BIO_debug_callback);
			BIO_set_callback_arg(b64, (char *) bio_err);
		}
		if (enc_config.olb64)
			BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
		if (enc_config.enc)
			wbio = BIO_push(b64, wbio);
		else
			rbio = BIO_push(b64, rbio);
	}
	if (enc_config.cipher != NULL) {
		/*
		 * Note that keystr is NULL if a key was passed on the command
		 * line, so we get no salt in that case. Is this a bug?
		 */
		if (enc_config.keystr != NULL) {
			/*
			 * Salt handling: if encrypting generate a salt and
			 * write to output BIO. If decrypting read salt from
			 * input BIO.
			 */
			unsigned char *sptr;
			if (enc_config.nosalt)
				sptr = NULL;
			else {
				if (enc_config.enc) {
					if (enc_config.hsalt) {
						if (!set_hex(enc_config.hsalt, salt, sizeof salt)) {
							BIO_printf(bio_err,
							    "invalid hex salt value\n");
							goto end;
						}
					} else
						arc4random_buf(salt,
						    sizeof(salt));
					/*
					 * If -P option then don't bother
					 * writing
					 */
					if ((enc_config.printkey != 2)
					    && (BIO_write(wbio, magic,
						    sizeof magic - 1) != sizeof magic - 1
						|| BIO_write(wbio,
						    (char *) salt,
						    sizeof salt) != sizeof salt)) {
						BIO_printf(bio_err, "error writing output file\n");
						goto end;
					}
				} else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf
					    || BIO_read(rbio,
						(unsigned char *) salt,
					sizeof salt) != sizeof salt) {
					BIO_printf(bio_err, "error reading input file\n");
					goto end;
				} else if (memcmp(mbuf, magic, sizeof magic - 1)) {
					BIO_printf(bio_err, "bad magic number\n");
					goto end;
				}
				sptr = salt;
			}

			EVP_BytesToKey(enc_config.cipher, dgst, sptr,
			    (unsigned char *)enc_config.keystr,
			    strlen(enc_config.keystr), 1, key, iv);
			/*
			 * zero the complete buffer or the string passed from
			 * the command line bug picked up by Larry J. Hughes
			 * Jr. <*****@*****.**>
			 */
			if (enc_config.keystr == strbuf)
				explicit_bzero(enc_config.keystr, SIZE);
			else
				explicit_bzero(enc_config.keystr,
				    strlen(enc_config.keystr));
		}
		if (enc_config.hiv != NULL &&
		    !set_hex(enc_config.hiv, iv, sizeof iv)) {
			BIO_printf(bio_err, "invalid hex iv value\n");
			goto end;
		}
		if (enc_config.hiv == NULL && enc_config.keystr == NULL &&
		    EVP_CIPHER_iv_length(enc_config.cipher) != 0) {
			/*
			 * No IV was explicitly set and no IV was generated
			 * during EVP_BytesToKey. Hence the IV is undefined,
			 * making correct decryption impossible.
			 */
			BIO_printf(bio_err, "iv undefined\n");
			goto end;
		}
		if (enc_config.hkey != NULL &&
		    !set_hex(enc_config.hkey, key, sizeof key)) {
			BIO_printf(bio_err, "invalid hex key value\n");
			goto end;
		}
		if ((benc = BIO_new(BIO_f_cipher())) == NULL)
			goto end;

		/*
		 * Since we may be changing parameters work on the encryption
		 * context rather than calling BIO_set_cipher().
		 */

		BIO_get_cipher_ctx(benc, &ctx);

		if (!EVP_CipherInit_ex(ctx, enc_config.cipher, NULL, NULL,
		    NULL, enc_config.enc)) {
			BIO_printf(bio_err, "Error setting cipher %s\n",
			    EVP_CIPHER_name(enc_config.cipher));
			ERR_print_errors(bio_err);
			goto end;
		}
		if (enc_config.nopad)
			EVP_CIPHER_CTX_set_padding(ctx, 0);

		if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv,
		    enc_config.enc)) {
			BIO_printf(bio_err, "Error setting cipher %s\n",
			    EVP_CIPHER_name(enc_config.cipher));
			ERR_print_errors(bio_err);
			goto end;
		}
		if (enc_config.debug) {
			BIO_set_callback(benc, BIO_debug_callback);
			BIO_set_callback_arg(benc, (char *) bio_err);
		}
		if (enc_config.printkey) {
			if (!enc_config.nosalt) {
				printf("salt=");
				for (i = 0; i < (int) sizeof(salt); i++)
					printf("%02X", salt[i]);
				printf("\n");
			}
			if (enc_config.cipher->key_len > 0) {
				printf("key=");
				for (i = 0; i < enc_config.cipher->key_len; i++)
					printf("%02X", key[i]);
				printf("\n");
			}
			if (enc_config.cipher->iv_len > 0) {
				printf("iv =");
				for (i = 0; i < enc_config.cipher->iv_len; i++)
					printf("%02X", iv[i]);
				printf("\n");
			}
			if (enc_config.printkey == 2) {
				ret = 0;
				goto end;
			}
		}
	}
	/* Only encrypt/decrypt as we write the file */
	if (benc != NULL)
		wbio = BIO_push(benc, wbio);

	for (;;) {
		inl = BIO_read(rbio, (char *) buff, bsize);
		if (inl <= 0)
			break;
		if (BIO_write(wbio, (char *) buff, inl) != inl) {
			BIO_printf(bio_err, "error writing output file\n");
			goto end;
		}
	}
	if (!BIO_flush(wbio)) {
		BIO_printf(bio_err, "bad decrypt\n");
		goto end;
	}
	ret = 0;
	if (enc_config.verbose) {
		BIO_printf(bio_err, "bytes read   :%8ld\n", BIO_number_read(in));
		BIO_printf(bio_err, "bytes written:%8ld\n", BIO_number_written(out));
	}
end:
	ERR_print_errors(bio_err);
	free(strbuf);
	free(buff);
	BIO_free(in);
	if (out != NULL)
		BIO_free_all(out);
	BIO_free(benc);
	BIO_free(b64);
#ifdef ZLIB
	BIO_free(bzl);
#endif
	free(pass);

	return (ret);
}
Exemplo n.º 18
0
int pkcs12_main(int argc, char **argv)
{
    char *infile = NULL, *outfile = NULL, *keyname = NULL, *certfile = NULL;
    char *name = NULL, *csp_name = NULL;
    char pass[50], macpass[50];
    int export_cert = 0, options = 0, chain = 0, twopass = 0, keytype = 0;
    int iter = PKCS12_DEFAULT_ITER, maciter = PKCS12_DEFAULT_ITER;
# ifndef OPENSSL_NO_RC2
    int cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;
# else
    int cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
# endif
    int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
    int ret = 1, macver = 1, noprompt = 0, add_lmk = 0;
    char *passinarg = NULL, *passoutarg = NULL, *passarg = NULL;
    char *passin = NULL, *passout = NULL, *inrand = NULL, *macalg = NULL;
    char *cpass = NULL, *mpass = NULL, *CApath = NULL, *CAfile = NULL;
    char *prog;
    ENGINE *e = NULL;
    BIO *in = NULL, *out = NULL;
    PKCS12 *p12 = NULL;
    STACK_OF(OPENSSL_STRING) *canames = NULL;
    const EVP_CIPHER *enc = EVP_des_ede3_cbc();
    OPTION_CHOICE o;

    prog = opt_init(argc, argv, pkcs12_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(pkcs12_options);
            ret = 0;
            goto end;
        case OPT_NOKEYS:
            options |= NOKEYS;
            break;
        case OPT_KEYEX:
            keytype = KEY_EX;
            break;
        case OPT_KEYSIG:
            keytype = KEY_SIG;
            break;
        case OPT_NOCERTS:
            options |= NOCERTS;
            break;
        case OPT_CLCERTS:
            options |= CLCERTS;
            break;
        case OPT_CACERTS:
            options |= CACERTS;
            break;
        case OPT_NOOUT:
            options |= (NOKEYS | NOCERTS);
            break;
        case OPT_INFO:
            options |= INFO;
            break;
        case OPT_CHAIN:
            chain = 1;
            break;
        case OPT_TWOPASS:
            twopass = 1;
            break;
        case OPT_NOMACVER:
            macver = 0;
            break;
        case OPT_DESCERT:
            cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
            break;
        case OPT_EXPORT:
            export_cert = 1;
            break;
        case OPT_CIPHER:
            if (!opt_cipher(opt_unknown(), &enc))
                goto opthelp;
            break;
        case OPT_NOITER:
            iter = 1;
            break;
        case OPT_MACITER:
            maciter = PKCS12_DEFAULT_ITER;
            break;
        case OPT_NOMACITER:
            maciter = 1;
            break;
        case OPT_NOMAC:
            maciter = -1;
            break;
        case OPT_MACALG:
            macalg = opt_arg();
            break;
        case OPT_NODES:
            enc = NULL;
            break;
        case OPT_CERTPBE:
            if (!set_pbe(&cert_pbe, opt_arg()))
                goto opthelp;
            break;
        case OPT_KEYPBE:
            if (!set_pbe(&key_pbe, opt_arg()))
                goto opthelp;
            break;
        case OPT_RAND:
            inrand = opt_arg();
            break;
        case OPT_INKEY:
            keyname = opt_arg();
            break;
        case OPT_CERTFILE:
            certfile = opt_arg();
            break;
        case OPT_NAME:
            name = opt_arg();
            break;
        case OPT_LMK:
            add_lmk = 1;
            break;
        case OPT_CSP:
            csp_name = opt_arg();
            break;
        case OPT_CANAME:
            if (canames == NULL
                && (canames = sk_OPENSSL_STRING_new_null()) == NULL)
                goto end;
            sk_OPENSSL_STRING_push(canames, opt_arg());
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PASSOUT:
            passoutarg = opt_arg();
            break;
        case OPT_PASSWORD:
            passarg = opt_arg();
            break;
        case OPT_CAPATH:
            CApath = opt_arg();
            break;
        case OPT_CAFILE:
            CAfile = opt_arg();
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (passarg) {
        if (export_cert)
            passoutarg = passarg;
        else
            passinarg = passarg;
    }

    if (!app_passwd(passinarg, passoutarg, &passin, &passout)) {
        BIO_printf(bio_err, "Error getting passwords\n");
        goto end;
    }

    if (!cpass) {
        if (export_cert)
            cpass = passout;
        else
            cpass = passin;
    }

    if (cpass) {
        mpass = cpass;
        noprompt = 1;
    } else {
        cpass = pass;
        mpass = macpass;
    }

    if (export_cert || inrand) {
        app_RAND_load_file(NULL, (inrand != NULL));
        if (inrand != NULL)
            BIO_printf(bio_err, "%ld semi-random bytes loaded\n",
                       app_RAND_load_files(inrand));
    }

    in = bio_open_default(infile, "rb");
    if (in == NULL)
        goto end;

    out = bio_open_default(outfile, "wb");
    if (out == NULL)
        goto end;

    if (twopass) {
        if (EVP_read_pw_string
            (macpass, sizeof macpass, "Enter MAC Password:"******"Can't read Password\n");
            goto end;
        }
    }

    if (export_cert) {
        EVP_PKEY *key = NULL;
        X509 *ucert = NULL, *x = NULL;
        STACK_OF(X509) *certs = NULL;
        const EVP_MD *macmd = NULL;
        unsigned char *catmp = NULL;
        int i;

        if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
            BIO_printf(bio_err, "Nothing to do!\n");
            goto export_end;
        }

        if (options & NOCERTS)
            chain = 0;

        if (!(options & NOKEYS)) {
            key = load_key(keyname ? keyname : infile,
                           FORMAT_PEM, 1, passin, e, "private key");
            if (!key)
                goto export_end;
        }

        /* Load in all certs in input file */
        if (!(options & NOCERTS)) {
            certs = load_certs(infile, FORMAT_PEM, NULL, e,
                               "certificates");
            if (!certs)
                goto export_end;

            if (key) {
                /* Look for matching private key */
                for (i = 0; i < sk_X509_num(certs); i++) {
                    x = sk_X509_value(certs, i);
                    if (X509_check_private_key(x, key)) {
                        ucert = x;
                        /* Zero keyid and alias */
                        X509_keyid_set1(ucert, NULL, 0);
                        X509_alias_set1(ucert, NULL, 0);
                        /* Remove from list */
                        (void)sk_X509_delete(certs, i);
                        break;
                    }
                }
                if (!ucert) {
                    BIO_printf(bio_err,
                               "No certificate matches private key\n");
                    goto export_end;
                }
            }

        }

        /* Add any more certificates asked for */
        if (certfile) {
            STACK_OF(X509) *morecerts = NULL;
            if (!(morecerts = load_certs(certfile, FORMAT_PEM, NULL, e,
                                         "certificates from certfile")))
                goto export_end;
            while (sk_X509_num(morecerts) > 0)
                sk_X509_push(certs, sk_X509_shift(morecerts));
            sk_X509_free(morecerts);
        }

        /* If chaining get chain from user cert */
        if (chain) {
            int vret;
            STACK_OF(X509) *chain2;
            X509_STORE *store;
            if (!(store = setup_verify(CAfile, CApath)))
                goto export_end;

            vret = get_cert_chain(ucert, store, &chain2);
            X509_STORE_free(store);

            if (!vret) {
                /* Exclude verified certificate */
                for (i = 1; i < sk_X509_num(chain2); i++)
                    sk_X509_push(certs, sk_X509_value(chain2, i));
                /* Free first certificate */
                X509_free(sk_X509_value(chain2, 0));
                sk_X509_free(chain2);
            } else {
                if (vret >= 0)
                    BIO_printf(bio_err, "Error %s getting chain.\n",
                               X509_verify_cert_error_string(vret));
                else
                    ERR_print_errors(bio_err);
                goto export_end;
            }
        }

        /* Add any CA names */

        for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
            catmp = (unsigned char *)sk_OPENSSL_STRING_value(canames, i);
            X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
        }

        if (csp_name && key)
            EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
                                      MBSTRING_ASC, (unsigned char *)csp_name,
                                      -1);

        if (add_lmk && key)
            EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);

        if (!noprompt &&
            EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:"******"Can't read Password\n");
            goto export_end;
        }
        if (!twopass)
            BUF_strlcpy(macpass, pass, sizeof macpass);

        p12 = PKCS12_create(cpass, name, key, ucert, certs,
                            key_pbe, cert_pbe, iter, -1, keytype);

        if (!p12) {
            ERR_print_errors(bio_err);
            goto export_end;
        }

        if (macalg) {
            if (!opt_md(macalg, &macmd))
                goto opthelp;
        }

        if (maciter != -1)
            PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);

        i2d_PKCS12_bio(out, p12);

        ret = 0;

 export_end:

        EVP_PKEY_free(key);
        if (certs)
            sk_X509_pop_free(certs, X509_free);
        if (ucert)
            X509_free(ucert);

        goto end;

    }

    if (!(p12 = d2i_PKCS12_bio(in, NULL))) {
        ERR_print_errors(bio_err);
        goto end;
    }

    if (!noprompt
        && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:"******"Can't read Password\n");
        goto end;
    }

    if (!twopass)
        BUF_strlcpy(macpass, pass, sizeof macpass);

    if ((options & INFO) && p12->mac)
        BIO_printf(bio_err, "MAC Iteration %ld\n",
                   p12->mac->iter ? ASN1_INTEGER_get(p12->mac->iter) : 1);
    if (macver) {
        /* If we enter empty password try no password first */
        if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
            /* If mac and crypto pass the same set it to NULL too */
            if (!twopass)
                cpass = NULL;
        } else if (!PKCS12_verify_mac(p12, mpass, -1)) {
            BIO_printf(bio_err, "Mac verify error: invalid password?\n");
            ERR_print_errors(bio_err);
            goto end;
        }
    }

    if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout, enc)) {
        BIO_printf(bio_err, "Error outputting keys and certificates\n");
        ERR_print_errors(bio_err);
        goto end;
    }
    ret = 0;
 end:
    PKCS12_free(p12);
    if (export_cert || inrand)
        app_RAND_write_file(NULL);
    BIO_free(in);
    BIO_free_all(out);
    if (canames)
        sk_OPENSSL_STRING_free(canames);
    if (passin)
        OPENSSL_free(passin);
    if (passout)
        OPENSSL_free(passout);
    return (ret);
}
Exemplo n.º 19
0
int
pkcs12_main(int argc, char **argv)
{
	ENGINE *e = NULL;
	char *infile = NULL, *outfile = NULL, *keyname = NULL;
	char *certfile = NULL;
	BIO *in = NULL, *out = NULL;
	char **args;
	char *name = NULL;
	char *csp_name = NULL;
	int add_lmk = 0;
	PKCS12 *p12 = NULL;
	char pass[50], macpass[50];
	int export_cert = 0;
	int options = 0;
	int chain = 0;
	int badarg = 0;
	int iter = PKCS12_DEFAULT_ITER;
	int maciter = PKCS12_DEFAULT_ITER;
	int twopass = 0;
	int keytype = 0;
	int cert_pbe;
	int key_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
	int ret = 1;
	int macver = 1;
	int noprompt = 0;
	STACK_OF(OPENSSL_STRING) * canames = NULL;
	char *cpass = NULL, *mpass = NULL;
	char *passargin = NULL, *passargout = NULL, *passarg = NULL;
	char *passin = NULL, *passout = NULL;
	char *inrand = NULL;
	char *macalg = NULL;
	char *CApath = NULL, *CAfile = NULL;
#ifndef OPENSSL_NO_ENGINE
	char *engine = NULL;
#endif

	signal(SIGPIPE, SIG_IGN);

	cert_pbe = NID_pbe_WithSHA1And40BitRC2_CBC;

	enc = EVP_des_ede3_cbc();
	if (bio_err == NULL)
		bio_err = BIO_new_fp(stderr, BIO_NOCLOSE);

	if (!load_config(bio_err, NULL))
		goto end;

	args = argv + 1;


	while (*args) {
		if (*args[0] == '-') {
			if (!strcmp(*args, "-nokeys"))
				options |= NOKEYS;
			else if (!strcmp(*args, "-keyex"))
				keytype = KEY_EX;
			else if (!strcmp(*args, "-keysig"))
				keytype = KEY_SIG;
			else if (!strcmp(*args, "-nocerts"))
				options |= NOCERTS;
			else if (!strcmp(*args, "-clcerts"))
				options |= CLCERTS;
			else if (!strcmp(*args, "-cacerts"))
				options |= CACERTS;
			else if (!strcmp(*args, "-noout"))
				options |= (NOKEYS | NOCERTS);
			else if (!strcmp(*args, "-info"))
				options |= INFO;
			else if (!strcmp(*args, "-chain"))
				chain = 1;
			else if (!strcmp(*args, "-twopass"))
				twopass = 1;
			else if (!strcmp(*args, "-nomacver"))
				macver = 0;
			else if (!strcmp(*args, "-descert"))
				cert_pbe = NID_pbe_WithSHA1And3_Key_TripleDES_CBC;
			else if (!strcmp(*args, "-export"))
				export_cert = 1;
			else if (!strcmp(*args, "-des"))
				enc = EVP_des_cbc();
			else if (!strcmp(*args, "-des3"))
				enc = EVP_des_ede3_cbc();
#ifndef OPENSSL_NO_IDEA
			else if (!strcmp(*args, "-idea"))
				enc = EVP_idea_cbc();
#endif
#ifndef OPENSSL_NO_SEED
			else if (!strcmp(*args, "-seed"))
				enc = EVP_seed_cbc();
#endif
#ifndef OPENSSL_NO_AES
			else if (!strcmp(*args, "-aes128"))
				enc = EVP_aes_128_cbc();
			else if (!strcmp(*args, "-aes192"))
				enc = EVP_aes_192_cbc();
			else if (!strcmp(*args, "-aes256"))
				enc = EVP_aes_256_cbc();
#endif
#ifndef OPENSSL_NO_CAMELLIA
			else if (!strcmp(*args, "-camellia128"))
				enc = EVP_camellia_128_cbc();
			else if (!strcmp(*args, "-camellia192"))
				enc = EVP_camellia_192_cbc();
			else if (!strcmp(*args, "-camellia256"))
				enc = EVP_camellia_256_cbc();
#endif
			else if (!strcmp(*args, "-noiter"))
				iter = 1;
			else if (!strcmp(*args, "-maciter"))
				maciter = PKCS12_DEFAULT_ITER;
			else if (!strcmp(*args, "-nomaciter"))
				maciter = 1;
			else if (!strcmp(*args, "-nomac"))
				maciter = -1;
			else if (!strcmp(*args, "-macalg"))
				if (args[1]) {
					args++;
					macalg = *args;
				} else
					badarg = 1;
			else if (!strcmp(*args, "-nodes"))
				enc = NULL;
			else if (!strcmp(*args, "-certpbe")) {
				if (!set_pbe(bio_err, &cert_pbe, *++args))
					badarg = 1;
			} else if (!strcmp(*args, "-keypbe")) {
				if (!set_pbe(bio_err, &key_pbe, *++args))
					badarg = 1;
			} else if (!strcmp(*args, "-rand")) {
				if (args[1]) {
					args++;
					inrand = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-inkey")) {
				if (args[1]) {
					args++;
					keyname = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-certfile")) {
				if (args[1]) {
					args++;
					certfile = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-name")) {
				if (args[1]) {
					args++;
					name = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-LMK"))
				add_lmk = 1;
			else if (!strcmp(*args, "-CSP")) {
				if (args[1]) {
					args++;
					csp_name = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-caname")) {
				if (args[1]) {
					args++;
					if (!canames)
						canames = sk_OPENSSL_STRING_new_null();
					sk_OPENSSL_STRING_push(canames, *args);
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-in")) {
				if (args[1]) {
					args++;
					infile = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-out")) {
				if (args[1]) {
					args++;
					outfile = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-passin")) {
				if (args[1]) {
					args++;
					passargin = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-passout")) {
				if (args[1]) {
					args++;
					passargout = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-password")) {
				if (args[1]) {
					args++;
					passarg = *args;
					noprompt = 1;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-CApath")) {
				if (args[1]) {
					args++;
					CApath = *args;
				} else
					badarg = 1;
			} else if (!strcmp(*args, "-CAfile")) {
				if (args[1]) {
					args++;
					CAfile = *args;
				} else
					badarg = 1;
#ifndef OPENSSL_NO_ENGINE
			} else if (!strcmp(*args, "-engine")) {
				if (args[1]) {
					args++;
					engine = *args;
				} else
					badarg = 1;
#endif
			} else
				badarg = 1;

		} else
			badarg = 1;
		args++;
	}

	if (badarg) {
		BIO_printf(bio_err, "Usage: pkcs12 [options]\n");
		BIO_printf(bio_err, "where options are\n");
		BIO_printf(bio_err, "-export       output PKCS12 file\n");
		BIO_printf(bio_err, "-chain        add certificate chain\n");
		BIO_printf(bio_err, "-inkey file   private key if not infile\n");
		BIO_printf(bio_err, "-certfile f   add all certs in f\n");
		BIO_printf(bio_err, "-CApath arg   - PEM format directory of CA's\n");
		BIO_printf(bio_err, "-CAfile arg   - PEM format file of CA's\n");
		BIO_printf(bio_err, "-name \"name\"  use name as friendly name\n");
		BIO_printf(bio_err, "-caname \"nm\"  use nm as CA friendly name (can be used more than once).\n");
		BIO_printf(bio_err, "-in  infile   input filename\n");
		BIO_printf(bio_err, "-out outfile  output filename\n");
		BIO_printf(bio_err, "-noout        don't output anything, just verify.\n");
		BIO_printf(bio_err, "-nomacver     don't verify MAC.\n");
		BIO_printf(bio_err, "-nocerts      don't output certificates.\n");
		BIO_printf(bio_err, "-clcerts      only output client certificates.\n");
		BIO_printf(bio_err, "-cacerts      only output CA certificates.\n");
		BIO_printf(bio_err, "-nokeys       don't output private keys.\n");
		BIO_printf(bio_err, "-info         give info about PKCS#12 structure.\n");
		BIO_printf(bio_err, "-des          encrypt private keys with DES\n");
		BIO_printf(bio_err, "-des3         encrypt private keys with triple DES (default)\n");
#ifndef OPENSSL_NO_IDEA
		BIO_printf(bio_err, "-idea         encrypt private keys with idea\n");
#endif
#ifndef OPENSSL_NO_SEED
		BIO_printf(bio_err, "-seed         encrypt private keys with seed\n");
#endif
#ifndef OPENSSL_NO_AES
		BIO_printf(bio_err, "-aes128, -aes192, -aes256\n");
		BIO_printf(bio_err, "              encrypt PEM output with cbc aes\n");
#endif
#ifndef OPENSSL_NO_CAMELLIA
		BIO_printf(bio_err, "-camellia128, -camellia192, -camellia256\n");
		BIO_printf(bio_err, "              encrypt PEM output with cbc camellia\n");
#endif
		BIO_printf(bio_err, "-nodes        don't encrypt private keys\n");
		BIO_printf(bio_err, "-noiter       don't use encryption iteration\n");
		BIO_printf(bio_err, "-nomaciter    don't use MAC iteration\n");
		BIO_printf(bio_err, "-maciter      use MAC iteration\n");
		BIO_printf(bio_err, "-nomac        don't generate MAC\n");
		BIO_printf(bio_err, "-twopass      separate MAC, encryption passwords\n");
		BIO_printf(bio_err, "-descert      encrypt PKCS#12 certificates with triple DES (default RC2-40)\n");
		BIO_printf(bio_err, "-certpbe alg  specify certificate PBE algorithm (default RC2-40)\n");
		BIO_printf(bio_err, "-keypbe alg   specify private key PBE algorithm (default 3DES)\n");
		BIO_printf(bio_err, "-macalg alg   digest algorithm used in MAC (default SHA1)\n");
		BIO_printf(bio_err, "-keyex        set MS key exchange type\n");
		BIO_printf(bio_err, "-keysig       set MS key signature type\n");
		BIO_printf(bio_err, "-password p   set import/export password source\n");
		BIO_printf(bio_err, "-passin p     input file pass phrase source\n");
		BIO_printf(bio_err, "-passout p    output file pass phrase source\n");
#ifndef OPENSSL_NO_ENGINE
		BIO_printf(bio_err, "-engine e     use engine e, possibly a hardware device.\n");
#endif
		BIO_printf(bio_err, "-rand file:file:...\n");
		BIO_printf(bio_err, "              load the file (or the files in the directory) into\n");
		BIO_printf(bio_err, "              the random number generator\n");
		BIO_printf(bio_err, "-CSP name     Microsoft CSP name\n");
		BIO_printf(bio_err, "-LMK          Add local machine keyset attribute to private key\n");
		goto end;
	}
#ifndef OPENSSL_NO_ENGINE
	e = setup_engine(bio_err, engine, 0);
#endif

	if (passarg) {
		if (export_cert)
			passargout = passarg;
		else
			passargin = passarg;
	}
	if (!app_passwd(bio_err, passargin, passargout, &passin, &passout)) {
		BIO_printf(bio_err, "Error getting passwords\n");
		goto end;
	}
	if (!cpass) {
		if (export_cert)
			cpass = passout;
		else
			cpass = passin;
	}
	if (cpass) {
		mpass = cpass;
		noprompt = 1;
	} else {
		cpass = pass;
		mpass = macpass;
	}

	ERR_load_crypto_strings();

#ifdef CRYPTO_MDEBUG
	CRYPTO_push_info("read files");
#endif

	if (!infile)
		in = BIO_new_fp(stdin, BIO_NOCLOSE);
	else
		in = BIO_new_file(infile, "rb");
	if (!in) {
		BIO_printf(bio_err, "Error opening input file %s\n",
		    infile ? infile : "<stdin>");
		perror(infile);
		goto end;
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
	CRYPTO_push_info("write files");
#endif

	if (!outfile) {
		out = BIO_new_fp(stdout, BIO_NOCLOSE);
	} else
		out = BIO_new_file(outfile, "wb");
	if (!out) {
		BIO_printf(bio_err, "Error opening output file %s\n",
		    outfile ? outfile : "<stdout>");
		perror(outfile);
		goto end;
	}
	if (twopass) {
#ifdef CRYPTO_MDEBUG
		CRYPTO_push_info("read MAC password");
#endif
		if (EVP_read_pw_string(macpass, sizeof macpass, "Enter MAC Password:"******"Can't read Password\n");
			goto end;
		}
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
#endif
	}
	if (export_cert) {
		EVP_PKEY *key = NULL;
		X509 *ucert = NULL, *x = NULL;
		STACK_OF(X509) * certs = NULL;
		const EVP_MD *macmd = NULL;
		unsigned char *catmp = NULL;
		int i;

		if ((options & (NOCERTS | NOKEYS)) == (NOCERTS | NOKEYS)) {
			BIO_printf(bio_err, "Nothing to do!\n");
			goto export_end;
		}
		if (options & NOCERTS)
			chain = 0;

#ifdef CRYPTO_MDEBUG
		CRYPTO_push_info("process -export_cert");
		CRYPTO_push_info("reading private key");
#endif
		if (!(options & NOKEYS)) {
			key = load_key(bio_err, keyname ? keyname : infile,
			    FORMAT_PEM, 1, passin, e, "private key");
			if (!key)
				goto export_end;
		}
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("reading certs from input");
#endif

		/* Load in all certs in input file */
		if (!(options & NOCERTS)) {
			certs = load_certs(bio_err, infile, FORMAT_PEM, NULL, e,
			    "certificates");
			if (!certs)
				goto export_end;

			if (key) {
				/* Look for matching private key */
				for (i = 0; i < sk_X509_num(certs); i++) {
					x = sk_X509_value(certs, i);
					if (X509_check_private_key(x, key)) {
						ucert = x;
						/* Zero keyid and alias */
						X509_keyid_set1(ucert, NULL, 0);
						X509_alias_set1(ucert, NULL, 0);
						/* Remove from list */
						(void) sk_X509_delete(certs, i);
						break;
					}
				}
				if (!ucert) {
					BIO_printf(bio_err, "No certificate matches private key\n");
					goto export_end;
				}
			}
		}
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("reading certs from input 2");
#endif

		/* Add any more certificates asked for */
		if (certfile) {
			STACK_OF(X509) * morecerts = NULL;
			if (!(morecerts = load_certs(bio_err, certfile, FORMAT_PEM,
				    NULL, e,
				    "certificates from certfile")))
				goto export_end;
			while (sk_X509_num(morecerts) > 0)
				sk_X509_push(certs, sk_X509_shift(morecerts));
			sk_X509_free(morecerts);
		}
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("reading certs from certfile");
#endif

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("building chain");
#endif

		/* If chaining get chain from user cert */
		if (chain) {
			int vret;
			STACK_OF(X509) * chain2;
			X509_STORE *store = X509_STORE_new();
			if (!store) {
				BIO_printf(bio_err, "Memory allocation error\n");
				goto export_end;
			}
			if (!X509_STORE_load_locations(store, CAfile, CApath))
				X509_STORE_set_default_paths(store);

			vret = get_cert_chain(ucert, store, &chain2);
			X509_STORE_free(store);

			if (!vret) {
				/* Exclude verified certificate */
				for (i = 1; i < sk_X509_num(chain2); i++)
					sk_X509_push(certs, sk_X509_value(chain2, i));
				/* Free first certificate */
				X509_free(sk_X509_value(chain2, 0));
				sk_X509_free(chain2);
			} else {
				if (vret >= 0)
					BIO_printf(bio_err, "Error %s getting chain.\n",
					    X509_verify_cert_error_string(vret));
				else
					ERR_print_errors(bio_err);
				goto export_end;
			}
		}
		/* Add any CA names */

		for (i = 0; i < sk_OPENSSL_STRING_num(canames); i++) {
			catmp = (unsigned char *) sk_OPENSSL_STRING_value(canames, i);
			X509_alias_set1(sk_X509_value(certs, i), catmp, -1);
		}

		if (csp_name && key)
			EVP_PKEY_add1_attr_by_NID(key, NID_ms_csp_name,
			    MBSTRING_ASC, (unsigned char *) csp_name, -1);

		if (add_lmk && key)
			EVP_PKEY_add1_attr_by_NID(key, NID_LocalKeySet, 0, NULL, -1);

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("reading password");
#endif

		if (!noprompt &&
		    EVP_read_pw_string(pass, sizeof pass, "Enter Export Password:"******"Can't read Password\n");
			goto export_end;
		}
		if (!twopass)
			strlcpy(macpass, pass, sizeof macpass);

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("creating PKCS#12 structure");
#endif

		p12 = PKCS12_create(cpass, name, key, ucert, certs,
		    key_pbe, cert_pbe, iter, -1, keytype);

		if (!p12) {
			ERR_print_errors(bio_err);
			goto export_end;
		}
		if (macalg) {
			macmd = EVP_get_digestbyname(macalg);
			if (!macmd) {
				BIO_printf(bio_err, "Unknown digest algorithm %s\n",
				    macalg);
			}
		}
		if (maciter != -1)
			PKCS12_set_mac(p12, mpass, -1, NULL, 0, maciter, macmd);

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_push_info("writing pkcs12");
#endif

		i2d_PKCS12_bio(out, p12);

		ret = 0;

export_end:
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
		CRYPTO_pop_info();
		CRYPTO_push_info("process -export_cert: freeing");
#endif

		if (key)
			EVP_PKEY_free(key);
		if (certs)
			sk_X509_pop_free(certs, X509_free);
		if (ucert)
			X509_free(ucert);

#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
#endif
		goto end;

	}
	if (!(p12 = d2i_PKCS12_bio(in, NULL))) {
		ERR_print_errors(bio_err);
		goto end;
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_push_info("read import password");
#endif
	if (!noprompt && EVP_read_pw_string(pass, sizeof pass, "Enter Import Password:"******"Can't read Password\n");
		goto end;
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
#endif

	if (!twopass)
		strlcpy(macpass, pass, sizeof macpass);

	if ((options & INFO) && p12->mac)
		BIO_printf(bio_err, "MAC Iteration %ld\n", p12->mac->iter ? ASN1_INTEGER_get(p12->mac->iter) : 1);
	if (macver) {
#ifdef CRYPTO_MDEBUG
		CRYPTO_push_info("verify MAC");
#endif
		/* If we enter empty password try no password first */
		if (!mpass[0] && PKCS12_verify_mac(p12, NULL, 0)) {
			/* If mac and crypto pass the same set it to NULL too */
			if (!twopass)
				cpass = NULL;
		} else if (!PKCS12_verify_mac(p12, mpass, -1)) {
			BIO_printf(bio_err, "Mac verify error: invalid password?\n");
			ERR_print_errors(bio_err);
			goto end;
		}
		BIO_printf(bio_err, "MAC verified OK\n");
#ifdef CRYPTO_MDEBUG
		CRYPTO_pop_info();
#endif
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_push_info("output keys and certificates");
#endif
	if (!dump_certs_keys_p12(out, p12, cpass, -1, options, passout)) {
		BIO_printf(bio_err, "Error outputting keys and certificates\n");
		ERR_print_errors(bio_err);
		goto end;
	}
#ifdef CRYPTO_MDEBUG
	CRYPTO_pop_info();
#endif
	ret = 0;
end:
	if (p12)
		PKCS12_free(p12);
#ifdef CRYPTO_MDEBUG
	CRYPTO_remove_all_info();
#endif
	BIO_free(in);
	BIO_free_all(out);
	if (canames)
		sk_OPENSSL_STRING_free(canames);
	if (passin)
		free(passin);
	if (passout)
		free(passout);
	
	return (ret);
}
Exemplo n.º 20
0
int enc_main(int argc, char **argv)
{
    static char buf[128];
    static const char magic[] = "Salted__";
    BIO *in = NULL, *out = NULL, *b64 = NULL, *benc = NULL, *rbio =
                                            NULL, *wbio = NULL;
    EVP_CIPHER_CTX *ctx = NULL;
    const EVP_CIPHER *cipher = NULL, *c;
    const EVP_MD *dgst = NULL;
    char *hkey = NULL, *hiv = NULL, *hsalt = NULL, *p;
    char *infile = NULL, *outfile = NULL, *prog;
    char *str = NULL, *passarg = NULL, *pass = NULL, *strbuf = NULL;
    char mbuf[sizeof magic - 1];
    OPTION_CHOICE o;
    int bsize = BSIZE, verbose = 0, debug = 0, olb64 = 0, nosalt = 0;
    int enc = 1, printkey = 0, i, k;
    int base64 = 0, informat = FORMAT_BINARY, outformat = FORMAT_BINARY;
    int ret = 1, inl, nopad = 0, non_fips_allow = 0;
    unsigned char key[EVP_MAX_KEY_LENGTH], iv[EVP_MAX_IV_LENGTH];
    unsigned char *buff = NULL, salt[PKCS5_SALT_LEN];
    unsigned long n;
#ifdef ZLIB
    int do_zlib = 0;
    BIO *bzl = NULL;
#endif

    /* first check the program name */
    prog = opt_progname(argv[0]);
    if (strcmp(prog, "base64") == 0)
        base64 = 1;
#ifdef ZLIB
    else if (strcmp(prog, "zlib") == 0)
        do_zlib = 1;
#endif
    else {
        cipher = EVP_get_cipherbyname(prog);
        if (cipher == NULL && strcmp(prog, "enc") != 0) {
            BIO_printf(bio_err, "%s is not a known cipher\n", prog);
            goto end;
        }
    }

    prog = opt_init(argc, argv, enc_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(enc_options);
            ret = 0;
            BIO_printf(bio_err, "Cipher Types\n");
            OBJ_NAME_do_all_sorted(OBJ_NAME_TYPE_CIPHER_METH,
                                   show_ciphers, bio_err);
            BIO_printf(bio_err, "\n");
            goto end;
        case OPT_E:
            enc = 1;
            break;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_PASS:
            passarg = opt_arg();
            break;
        case OPT_ENGINE:
            (void)setup_engine(opt_arg(), 0);
            break;
        case OPT_D:
            enc = 0;
            break;
        case OPT_P:
            printkey = 1;
            break;
        case OPT_V:
            verbose = 1;
            break;
        case OPT_NOPAD:
            nopad = 1;
            break;
        case OPT_SALT:
            nosalt = 0;
            break;
        case OPT_NOSALT:
            nosalt = 1;
            break;
        case OPT_DEBUG:
            debug = 1;
            break;
        case OPT_UPPER_P:
            printkey = 2;
            break;
        case OPT_UPPER_A:
            olb64 = 1;
            break;
        case OPT_A:
            base64 = 1;
            break;
        case OPT_Z:
#ifdef ZLIB
            do_zlib = 1;
#endif
            break;
        case OPT_BUFSIZE:
            p = opt_arg();
            i = (int)strlen(p) - 1;
            k = i >= 1 && p[i] == 'k';
            if (k)
                p[i] = '\0';
            if (!opt_ulong(opt_arg(), &n))
                goto opthelp;
            if (k)
                n *= 1024;
            bsize = (int)n;
            break;
        case OPT_K:
            str = opt_arg();
            break;
        case OPT_KFILE:
            in = bio_open_default(opt_arg(), 'r', FORMAT_TEXT);
            if (in == NULL)
                goto opthelp;
            i = BIO_gets(in, buf, sizeof buf);
            BIO_free(in);
            in = NULL;
            if (i <= 0) {
                BIO_printf(bio_err,
                           "%s Can't read key from %s\n", prog, opt_arg());
                goto opthelp;
            }
            while (--i > 0 && (buf[i] == '\r' || buf[i] == '\n'))
                buf[i] = '\0';
            if (i <= 0) {
                BIO_printf(bio_err, "%s: zero length password\n", prog);
                goto opthelp;
            }
            str = buf;
            break;
        case OPT_UPPER_K:
            hkey = opt_arg();
            break;
        case OPT_UPPER_S:
            hsalt = opt_arg();
            break;
        case OPT_IV:
            hiv = opt_arg();
            break;
        case OPT_MD:
            if (!opt_md(opt_arg(), &dgst))
                goto opthelp;
            break;
        case OPT_NON_FIPS_ALLOW:
            non_fips_allow = 1;
            break;
        case OPT_CIPHER:
            if (!opt_cipher(opt_unknown(), &c))
                goto opthelp;
            cipher = c;
            break;
        case OPT_NONE:
            cipher = NULL;
            break;
        }
    }
    argc = opt_num_rest();
    argv = opt_rest();

    if (cipher && EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) {
        BIO_printf(bio_err, "%s: AEAD ciphers not supported\n", prog);
        goto end;
    }

    if (cipher && (EVP_CIPHER_mode(cipher) == EVP_CIPH_XTS_MODE)) {
        BIO_printf(bio_err, "%s XTS ciphers not supported\n", prog);
        goto end;
    }

    if (dgst == NULL)
        dgst = EVP_sha256();

    /* It must be large enough for a base64 encoded line */
    if (base64 && bsize < 80)
        bsize = 80;
    if (verbose)
        BIO_printf(bio_err, "bufsize=%d\n", bsize);

    if (base64) {
        if (enc)
            outformat = FORMAT_BASE64;
        else
            informat = FORMAT_BASE64;
    }

    strbuf = app_malloc(SIZE, "strbuf");
    buff = app_malloc(EVP_ENCODE_LENGTH(bsize), "evp buffer");

    if (debug) {
        BIO_set_callback(in, BIO_debug_callback);
        BIO_set_callback(out, BIO_debug_callback);
        BIO_set_callback_arg(in, (char *)bio_err);
        BIO_set_callback_arg(out, (char *)bio_err);
    }

    if (infile == NULL) {
        unbuffer(stdin);
        in = dup_bio_in(informat);
    } else
        in = bio_open_default(infile, 'r', informat);
    if (in == NULL)
        goto end;

    if (!str && passarg) {
        if (!app_passwd(passarg, NULL, &pass, NULL)) {
            BIO_printf(bio_err, "Error getting password\n");
            goto end;
        }
        str = pass;
    }

    if ((str == NULL) && (cipher != NULL) && (hkey == NULL)) {
        for (;;) {
            char prompt[200];

            BIO_snprintf(prompt, sizeof prompt, "enter %s %s password:"******"encryption" : "decryption");
            strbuf[0] = '\0';
            i = EVP_read_pw_string((char *)strbuf, SIZE, prompt, enc);
            if (i == 0) {
                if (strbuf[0] == '\0') {
                    ret = 1;
                    goto end;
                }
                str = strbuf;
                break;
            }
            if (i < 0) {
                BIO_printf(bio_err, "bad password read\n");
                goto end;
            }
        }
    }

    out = bio_open_default(outfile, 'w', outformat);
    if (out == NULL)
        goto end;

    rbio = in;
    wbio = out;

#ifdef ZLIB
    if (do_zlib) {
        if ((bzl = BIO_new(BIO_f_zlib())) == NULL)
            goto end;
        if (enc)
            wbio = BIO_push(bzl, wbio);
        else
            rbio = BIO_push(bzl, rbio);
    }
#endif

    if (base64) {
        if ((b64 = BIO_new(BIO_f_base64())) == NULL)
            goto end;
        if (debug) {
            BIO_set_callback(b64, BIO_debug_callback);
            BIO_set_callback_arg(b64, (char *)bio_err);
        }
        if (olb64)
            BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
        if (enc)
            wbio = BIO_push(b64, wbio);
        else
            rbio = BIO_push(b64, rbio);
    }

    if (cipher != NULL) {
        /*
         * Note that str is NULL if a key was passed on the command line, so
         * we get no salt in that case. Is this a bug?
         */
        if (str != NULL) {
            /*
             * Salt handling: if encrypting generate a salt and write to
             * output BIO. If decrypting read salt from input BIO.
             */
            unsigned char *sptr;
            if (nosalt)
                sptr = NULL;
            else {
                if (enc) {
                    if (hsalt) {
                        if (!set_hex(hsalt, salt, sizeof salt)) {
                            BIO_printf(bio_err, "invalid hex salt value\n");
                            goto end;
                        }
                    } else if (RAND_bytes(salt, sizeof salt) <= 0)
                        goto end;
                    /*
                     * If -P option then don't bother writing
                     */
                    if ((printkey != 2)
                            && (BIO_write(wbio, magic,
                                          sizeof magic - 1) != sizeof magic - 1
                                || BIO_write(wbio,
                                             (char *)salt,
                                             sizeof salt) != sizeof salt)) {
                        BIO_printf(bio_err, "error writing output file\n");
                        goto end;
                    }
                } else if (BIO_read(rbio, mbuf, sizeof mbuf) != sizeof mbuf
                           || BIO_read(rbio,
                                       (unsigned char *)salt,
                                       sizeof salt) != sizeof salt) {
                    BIO_printf(bio_err, "error reading input file\n");
                    goto end;
                } else if (memcmp(mbuf, magic, sizeof magic - 1)) {
                    BIO_printf(bio_err, "bad magic number\n");
                    goto end;
                }

                sptr = salt;
            }

            if (!EVP_BytesToKey(cipher, dgst, sptr,
                                (unsigned char *)str,
                                strlen(str), 1, key, iv)) {
                BIO_printf(bio_err, "EVP_BytesToKey failed\n");
                goto end;
            }
            /*
             * zero the complete buffer or the string passed from the command
             * line bug picked up by Larry J. Hughes Jr. <*****@*****.**>
             */
            if (str == strbuf)
                OPENSSL_cleanse(str, SIZE);
            else
                OPENSSL_cleanse(str, strlen(str));
        }
        if (hiv != NULL) {
            int siz = EVP_CIPHER_iv_length(cipher);
            if (siz == 0) {
                BIO_printf(bio_err, "warning: iv not use by this cipher\n");
            } else if (!set_hex(hiv, iv, sizeof iv)) {
                BIO_printf(bio_err, "invalid hex iv value\n");
                goto end;
            }
        }
        if ((hiv == NULL) && (str == NULL)
                && EVP_CIPHER_iv_length(cipher) != 0) {
            /*
             * No IV was explicitly set and no IV was generated during
             * EVP_BytesToKey. Hence the IV is undefined, making correct
             * decryption impossible.
             */
            BIO_printf(bio_err, "iv undefined\n");
            goto end;
        }
        if ((hkey != NULL) && !set_hex(hkey, key, EVP_CIPHER_key_length(cipher))) {
            BIO_printf(bio_err, "invalid hex key value\n");
            goto end;
        }

        if ((benc = BIO_new(BIO_f_cipher())) == NULL)
            goto end;

        /*
         * Since we may be changing parameters work on the encryption context
         * rather than calling BIO_set_cipher().
         */

        BIO_get_cipher_ctx(benc, &ctx);

        if (non_fips_allow)
            EVP_CIPHER_CTX_set_flags(ctx, EVP_CIPH_FLAG_NON_FIPS_ALLOW);

        if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, enc)) {
            BIO_printf(bio_err, "Error setting cipher %s\n",
                       EVP_CIPHER_name(cipher));
            ERR_print_errors(bio_err);
            goto end;
        }

        if (nopad)
            EVP_CIPHER_CTX_set_padding(ctx, 0);

        if (!EVP_CipherInit_ex(ctx, NULL, NULL, key, iv, enc)) {
            BIO_printf(bio_err, "Error setting cipher %s\n",
                       EVP_CIPHER_name(cipher));
            ERR_print_errors(bio_err);
            goto end;
        }

        if (debug) {
            BIO_set_callback(benc, BIO_debug_callback);
            BIO_set_callback_arg(benc, (char *)bio_err);
        }

        if (printkey) {
            if (!nosalt) {
                printf("salt=");
                for (i = 0; i < (int)sizeof(salt); i++)
                    printf("%02X", salt[i]);
                printf("\n");
            }
            if (cipher->key_len > 0) {
                printf("key=");
                for (i = 0; i < cipher->key_len; i++)
                    printf("%02X", key[i]);
                printf("\n");
            }
            if (cipher->iv_len > 0) {
                printf("iv =");
                for (i = 0; i < cipher->iv_len; i++)
                    printf("%02X", iv[i]);
                printf("\n");
            }
            if (printkey == 2) {
                ret = 0;
                goto end;
            }
        }
    }

    /* Only encrypt/decrypt as we write the file */
    if (benc != NULL)
        wbio = BIO_push(benc, wbio);

    for (;;) {
        inl = BIO_read(rbio, (char *)buff, bsize);
        if (inl <= 0)
            break;
        if (BIO_write(wbio, (char *)buff, inl) != inl) {
            BIO_printf(bio_err, "error writing output file\n");
            goto end;
        }
    }
    if (!BIO_flush(wbio)) {
        BIO_printf(bio_err, "bad decrypt\n");
        goto end;
    }

    ret = 0;
    if (verbose) {
        BIO_printf(bio_err, "bytes read   :%8"PRIu64"\n", BIO_number_read(in));
        BIO_printf(bio_err, "bytes written:%8"PRIu64"\n", BIO_number_written(out));
    }
end:
    ERR_print_errors(bio_err);
    OPENSSL_free(strbuf);
    OPENSSL_free(buff);
    BIO_free(in);
    BIO_free_all(out);
    BIO_free(benc);
    BIO_free(b64);
#ifdef ZLIB
    BIO_free(bzl);
#endif
    OPENSSL_free(pass);
    return (ret);
}
Exemplo n.º 21
0
int main(int argc, char **argv) {
	if(argc != 4)
		usageError();
/* 
 * Encrypted Data Scheme:
 * ---------------------------------
 * | Data       | Salt | IV | HMAC |
 * ---------------------------------
 *
 *  PBKDF2 creates with SALT and PASSWORD a key.
 *  The key is divided into 2 subkeys.
 *      first part is used for fileencryption (EVP_CipherInit_ex)
 *      second part is used for HMAC 
 *	Both, the encrypted and the decrypted files are stored (chmod) 600
 *
 * */
	
	char password[PWLEN];           // user pw 
	unsigned char salt[SALTLEN];    // random generated salt
	unsigned char iv[IVLEN];        // IV 
	unsigned char 
		completeKey[AESKEYLEN +
			        HMACKEYLEN];    // stores the complete key generated by PBKDF2; Will be divided into 2 subkeys
	unsigned char key1[AESKEYLEN];  // first part of completeKey 
	unsigned char key2[HMACKEYLEN]; // second part
	EVP_CIPHER_CTX cctx;
	unsigned char *dataToEnc = NULL;
	unsigned char *dataToDec = NULL;
	struct stat file;
	int fileSize;
	int passwordLen = 0;

	if(0 != stat(argv[2], &file)) {
		perror("stat");
		exit(EXIT_FAILURE);
	}
	fileSize = file.st_size;
	int fildes = 0;
	if(-1 == (fildes = open(argv[2], O_RDONLY))) {
		perror("open");
		exit(EXIT_FAILURE);
	}


	if(0 == strcmp(argv[1], "enc")) {
		unsigned char dataEnc[fileSize];
		unsigned char encHeader[fileSize+SALTLEN+IVLEN];
		unsigned char *hmac = NULL;

		/* get enc file and map into address space */
		dataToEnc = mmap(NULL, fileSize, PROT_READ, MAP_SHARED, fildes, 0);
		if(NULL == dataToEnc) {
			fprintf(stderr, "Couldn't map input file\n");
			exit(EXIT_FAILURE);
		}
		
		/* read password, provided by user*/
		if(0 != EVP_read_pw_string(password, PWLEN, "Enter Password: "******"EVP_read_pw_string");
			exit(EXIT_FAILURE);
		}
		for(; password[passwordLen] != '\0'; passwordLen++);

		/* fill SALT with (strong) Random */
		if(1 != RAND_bytes(salt, SALTLEN)) {
			perror("RAND_bytes");
			exit(EXIT_FAILURE);
		}
		/* create the key used for encryption and MAC */
		if(1 != PKCS5_PBKDF2_HMAC_SHA1(password, passwordLen, salt, SALTLEN, PBKDF2ITERATIONS, HMACKEYLEN + AESKEYLEN, completeKey)) {
			perror("PKCS5_PBKDF2_HMAC_SHA1");
			exit(EXIT_FAILURE);
		}

		/* split the key into 2 subkeys, used for HMAC and as part of IV */
		memcpy(key1, completeKey, AESKEYLEN);
		memcpy(key2, completeKey+AESKEYLEN, HMACKEYLEN);

		/* fill iv with random data */
		if(1 != RAND_bytes(iv, IVLEN)) {
			perror("RAND_bytes");
			exit(EXIT_FAILURE);
		}
		/* init aes encryption */
		EVP_CIPHER_CTX_init(&cctx);
		if(0 == EVP_CipherInit_ex(&cctx, EVP_aes_256_ofb(), NULL, key1, iv, 1)) {
			perror("EVP_CipherInit_ex");
			exit(EXIT_FAILURE);
		}
		if(0 == EVP_CipherUpdate(&cctx, dataEnc, &fileSize, dataToEnc, fileSize)) {
			EVP_CIPHER_CTX_cleanup(&cctx);
			perror("EVP_CipherUpdate");
			exit(EXIT_FAILURE);
		}
		EVP_CIPHER_CTX_cleanup(&cctx);
		
		/* prepare write to disk */
		int encFileOut = 0;
		if(-1 == (encFileOut = open(argv[3], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR))) {
			perror("open write");
			exit(EXIT_FAILURE);
		}
		/* store the IV and Salt in the encryption Header */
		memcpy(encHeader, dataEnc, fileSize);
		memcpy(encHeader+fileSize, salt, SALTLEN);
		memcpy(encHeader+fileSize+SALTLEN, iv, IVLEN);


		/* create the MAC */
		hmac = HMAC(EVP_sha1(), key2, HMACKEYLEN, encHeader, fileSize+SALTLEN+IVLEN, NULL, NULL); 
		if(hmac == NULL) {
			fprintf(stderr, "Creating HMAC failed");
			exit(EXIT_FAILURE);
		}

		/* write encrypted Data and Header to disk  */
		write(encFileOut, encHeader, fileSize+SALTLEN+IVLEN);
		write(encFileOut, hmac, HMACLEN); 

		close(fildes);
		close(encFileOut);

	} else if (0 == strcmp(argv[1], "dec")) {

		unsigned char dataDec[fileSize-HMACLEN-IVLEN-SALTLEN];
		unsigned char encData[fileSize-HMACLEN-IVLEN-SALTLEN];
		unsigned char encHMAC[HMACLEN];
		unsigned char *hmac = NULL;
		
		dataToDec = mmap(NULL, fileSize, PROT_READ, MAP_SHARED, fildes, 0);
		if(NULL == dataToDec) {
			fprintf(stderr, "Couldn't map Input File\n");
			exit(EXIT_FAILURE);
		}
	

		/* extract "header" from the enc file */
		int offset = fileSize-HMACLEN;
		memcpy(encHMAC, dataToDec+offset, HMACLEN);     /* | data | salt | iv | hmac    */
		offset -= IVLEN;
		memcpy(iv, dataToDec+offset, IVLEN);            /* | data | salt | iv           */
		offset -= SALTLEN;
		memcpy(salt, dataToDec+offset, SALTLEN);        /* | data | salt                */
		memcpy(encData, dataToDec, offset);             /* | data                       */

		/* read password */
		if(0 != EVP_read_pw_string(password, PWLEN, "Enter Password: "******"EVP_read_pw_string");
			exit(EXIT_FAILURE);
		}
		for(; password[passwordLen] != '\0'; passwordLen++);
		
		if(1 != PKCS5_PBKDF2_HMAC_SHA1(password, passwordLen, salt, SALTLEN, PBKDF2ITERATIONS, HMACKEYLEN + AESKEYLEN, completeKey)) {
			perror("PKCS5_PBKDF2_HMAC_SHA1");
			exit(EXIT_FAILURE);
		}

		memcpy(key1, completeKey, AESKEYLEN);
		memcpy(key2, completeKey+AESKEYLEN, HMACKEYLEN);
		
		hmac = HMAC(EVP_sha1(), key2, HMACKEYLEN, dataToDec, offset+IVLEN+SALTLEN, NULL, NULL); 
		if(hmac == NULL) {
			fprintf(stderr, "Creating HMAC failed");
			exit(EXIT_FAILURE);
		}
		/* DEBUG
		printf("generated HMAC: ");
		for(int i = 0; i < HMACLEN; i++) 
			printf("%X", hmac[i]);

		printf("\nfile HMAC:      ");
		for(int i = 0; i < HMACLEN; i++) 
			printf("%X", encHMAC[i]); 
		*/

		/* compare generated HMAC with stored HMAC */
		if(0 != memcmp(encHMAC, hmac, HMACLEN)) {
			fprintf(stderr,"Wrong Password\n");
			exit(EXIT_FAILURE);
		}

		EVP_CIPHER_CTX_init(&cctx);
		if(0 == EVP_CipherInit_ex(&cctx, EVP_aes_256_ofb(), NULL, key1, iv, 0)) {
			perror("EVP_CipherInit_ex");
			exit(EXIT_FAILURE);
		}
		if(0 == EVP_CipherUpdate(&cctx, dataDec, &offset, encData, offset)) {
			EVP_CIPHER_CTX_cleanup(&cctx);
			perror("EVP_CipherUpdate");
			exit(EXIT_FAILURE);
		}
		EVP_CIPHER_CTX_cleanup(&cctx);

		int encFileOut = 0;
		if(-1 == (encFileOut = open(argv[3], O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR))) {
			perror("open write");
			exit(EXIT_FAILURE);
		}
		write(encFileOut, dataDec, offset); 

		close(encFileOut);
		close(fildes);
	} else 
		usageError();

	return 0;
}
Exemplo n.º 22
0
int main(int argc, char *argv[])
	{
	TINYCLR_SSL_FILE *in=NULL,*out=NULL;
	char *infile=NULL,*outfile=NULL,*keystr=NULL;
	RC4_KEY key;
	char buf[BUFSIZ];
	int badops=0,i;
	char **pp;
	unsigned char md[MD5_DIGEST_LENGTH];

	argc--;
	argv++;
	while (argc >= 1)
		{
		if 	(TINYCLR_SSL_STRCMP(*argv,"-in") == 0)
			{
			if (--argc < 1) goto bad;
			infile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-out") == 0)
			{
			if (--argc < 1) goto bad;
			outfile= *(++argv);
			}
		else if (TINYCLR_SSL_STRCMP(*argv,"-key") == 0)
			{
			if (--argc < 1) goto bad;
			keystr= *(++argv);
			}
		else
			{
			TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"unknown option %s\n",*argv);
			badops=1;
			break;
			}
		argc--;
		argv++;
		}

	if (badops)
		{
bad:
		for (pp=usage; (*pp != NULL); pp++)
			TINYCLR_SSL_FPRINTF(OPENSSL_TYPE__FILE_STDERR,"%s",*pp);
		TINYCLR_SSL_EXIT(1);
		}

	if (infile == NULL)
		in=OPENSSL_TYPE__FILE_STDIN;
	else
		{
		in=TINYCLR_SSL_FOPEN(infile,"r");
		if (in == NULL)
			{
			TINYCLR_SSL_PERROR("open");
			TINYCLR_SSL_EXIT(1);
			}

		}
	if (outfile == NULL)
		out=OPENSSL_TYPE__FILE_STDOUT;
	else
		{
		out=TINYCLR_SSL_FOPEN(outfile,"w");
		if (out == NULL)
			{
			TINYCLR_SSL_PERROR("open");
			TINYCLR_SSL_EXIT(1);
			}
		}
		
#ifdef OPENSSL_SYS_MSDOS
	/* This should set the file to binary mode. */
	{
#include <fcntl.h>
	setmode(TINYCLR_SSL_FILENO(in),O_BINARY);
	setmode(TINYCLR_SSL_FILENO(out),O_BINARY);
	}
#endif

	if (keystr == NULL)
		{ /* get key */
		i=EVP_read_pw_string(buf,BUFSIZ,"Enter RC4 password:"******"bad password read\n");
			TINYCLR_SSL_EXIT(1);
			}
		keystr=buf;
		}

	EVP_Digest((unsigned char *)keystr,TINYCLR_SSL_STRLEN(keystr),md,NULL,EVP_md5(),NULL);
	OPENSSL_cleanse(keystr,TINYCLR_SSL_STRLEN(keystr));
	RC4_set_key(&key,MD5_DIGEST_LENGTH,md);
	
	for(;;)
		{
		i=TINYCLR_SSL_FREAD(buf,1,BUFSIZ,in);
		if (i == 0) break;
		if (i < 0)
			{
			TINYCLR_SSL_PERROR("read");
			TINYCLR_SSL_EXIT(1);
			}
		RC4(&key,(unsigned int)i,(unsigned char *)buf,
			(unsigned char *)buf);
		i=TINYCLR_SSL_FWRITE(buf,(unsigned int)i,1,out);
		if (i != 1)
			{
			TINYCLR_SSL_PERROR("write");
			TINYCLR_SSL_EXIT(1);
			}
		}
	TINYCLR_SSL_FCLOSE(out);
	TINYCLR_SSL_FCLOSE(in);
	TINYCLR_SSL_EXIT(0);
	return(1);
	}
Exemplo n.º 23
0
int single_request(char *hostname, int port)
{
    int sockfd;
    int status;

    struct sockaddr_in server_addr;
    struct hostent *hostp = NULL;
    //Linux manpage says socklen_t, Solaris says size_t
    //socklen_t sockaddrsize = sizeof(struct sockaddr);
    size_t sockaddrsize = sizeof(struct sockaddr);

    char buf[1024];
    int buflen = 1024;
    int len;
    char *servername;
    char *ptr;
    int i;

    printf("opening socket...\n");
    sockfd = socket(PF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
	perror("socket");
	return(-1);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(port);

    hostp = gethostbyname(hostname);
    if (NULL == hostp) {
	hostp = gethostbyaddr(hostname, strlen(hostname), AF_INET);
	if (NULL == hostp) {
	    perror("Error resolving server address");
	    return(-1);
	}
    }

    server_addr.sin_addr = *((struct in_addr *)hostp->h_addr);

    printf("connecting...\n");
    status = connect(sockfd, (struct sockaddr *) &server_addr, sockaddrsize);
    if (-1 == status) {
        perror("connect");
	return(-1);
    }

    ssl = SSL_new(ssl_ctx);
    if (!ssl) {
	fprintf(stderr, "SSL_new: failure\n");
	return(-1);
    }

    status = SSL_set_fd(ssl, sockfd);
    if (!status) {
	fprintf(stderr, "SSL_set_fd: failure\n");
	return(-1);
    }

    status = SSL_connect(ssl);
    if (status != 1) {
	fprintf(stderr, "SSL_connect: failure\n");

	printf("status %d\n", status);
	SSL_load_error_strings();
	printf("%d: ", SSL_get_error(ssl, status));
	printf("%s\n", ERR_error_string(SSL_get_error(ssl, status), NULL));

	return(-1);
    }

    //XXX: odd hack
    write_string("GET /\n");
	
    for (;;) {
	char marker[] = "<!-- PKG: ";
	i = strlen(marker);
	len = myssl_readline(ssl, buf, buflen);
	if (len <= 0) {
	    fprintf(stderr, "Doesn't seem to be a PKG\n");
	    return(-1);
	}
	if (!strncmp(buf, marker, i)) break;
    }

    servername = &buf[i];
    ptr = strstr(servername, " -->");
    if (ptr) ptr[0] = 0;

    SSL_shutdown(ssl);
    shutdown(sockfd, 2);

    printf("server name: %s\n", servername);
    sockfd = socket(PF_INET, SOCK_STREAM, 0);
    if (sockfd == -1) {
	perror("socket");
	return(-1);
    }

    status = connect(sockfd, (struct sockaddr *) &server_addr, sockaddrsize);
    if (-1 == status) {
        perror("connect");
	return(-1);
    }

    status = SSL_set_fd(ssl, sockfd);
    if (!status) {
	fprintf(stderr, "SSL_set_fd: failure\n");
	return(-1);
    }

    status = SSL_connect(ssl);
    if (status != 1) {
	fprintf(stderr, "SSL_connect: failure\n");
	return(-1);
    }

    status = EVP_read_pw_string(password, 100, "share password: "******"error reading password\n");
	return 1;
    }

    write_string("POST /\n");
    write_string("Content-Length: ");

    //Windows doesn't have snprintf?

    sprintf(buf, "%d\n\n", 16 + strlen(emailaddr) + strlen(password));

    write_string(buf);

    sprintf(buf, "mail=%s&password=%s\n", emailaddr, password);

    write_string(buf);

    for (;;) {
	len = myssl_readline(ssl, buf, buflen);
	if (len <= 0) break;
	printf("server: %s", buf);
    }
    status = SSL_shutdown(ssl);
    if (status != 1) {
	fprintf(stderr, "SSL_shutdown: failure\n");
	printf("status %d\n", status);
	SSL_load_error_strings();
	printf("%d: ", SSL_get_error(ssl, status));
	printf("%s\n", ERR_error_string(SSL_get_error(ssl, status), NULL));
    }

    return 1;
}
Exemplo n.º 24
0
int pkeyutl_main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL;
    ENGINE *e = NULL;
    EVP_PKEY_CTX *ctx = NULL;
    EVP_PKEY *pkey = NULL;
    char *infile = NULL, *outfile = NULL, *sigfile = NULL, *passinarg = NULL;
    char hexdump = 0, asn1parse = 0, rev = 0, *prog;
    unsigned char *buf_in = NULL, *buf_out = NULL, *sig = NULL;
    OPTION_CHOICE o;
    int buf_inlen = 0, siglen = -1, keyform = FORMAT_PEM, peerform = FORMAT_PEM;
    int keysize = -1, pkey_op = EVP_PKEY_OP_SIGN, key_type = KEY_PRIVKEY;
    int engine_impl = 0;
    int ret = 1, rv = -1;
    size_t buf_outlen;
    const char *inkey = NULL;
    const char *peerkey = NULL;
    const char *kdfalg = NULL;
    int kdflen = 0;
    STACK_OF(OPENSSL_STRING) *pkeyopts = NULL;
    STACK_OF(OPENSSL_STRING) *pkeyopts_passin = NULL;
    int rawin = 0;
    const EVP_MD *md = NULL;

    prog = opt_init(argc, argv, pkeyutl_options);
    while ((o = opt_next()) != OPT_EOF) {
        switch (o) {
        case OPT_EOF:
        case OPT_ERR:
 opthelp:
            BIO_printf(bio_err, "%s: Use -help for summary.\n", prog);
            goto end;
        case OPT_HELP:
            opt_help(pkeyutl_options);
            ret = 0;
            goto end;
        case OPT_IN:
            infile = opt_arg();
            break;
        case OPT_OUT:
            outfile = opt_arg();
            break;
        case OPT_SIGFILE:
            sigfile = opt_arg();
            break;
        case OPT_ENGINE_IMPL:
            engine_impl = 1;
            break;
        case OPT_INKEY:
            inkey = opt_arg();
            break;
        case OPT_PEERKEY:
            peerkey = opt_arg();
            break;
        case OPT_PASSIN:
            passinarg = opt_arg();
            break;
        case OPT_PEERFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDE, &peerform))
                goto opthelp;
            break;
        case OPT_KEYFORM:
            if (!opt_format(opt_arg(), OPT_FMT_PDE, &keyform))
                goto opthelp;
            break;
        case OPT_R_CASES:
            if (!opt_rand(o))
                goto end;
            break;
        case OPT_ENGINE:
            e = setup_engine(opt_arg(), 0);
            break;
        case OPT_PUBIN:
            key_type = KEY_PUBKEY;
            break;
        case OPT_CERTIN:
            key_type = KEY_CERT;
            break;
        case OPT_ASN1PARSE:
            asn1parse = 1;
            break;
        case OPT_HEXDUMP:
            hexdump = 1;
            break;
        case OPT_SIGN:
            pkey_op = EVP_PKEY_OP_SIGN;
            break;
        case OPT_VERIFY:
            pkey_op = EVP_PKEY_OP_VERIFY;
            break;
        case OPT_VERIFYRECOVER:
            pkey_op = EVP_PKEY_OP_VERIFYRECOVER;
            break;
        case OPT_ENCRYPT:
            pkey_op = EVP_PKEY_OP_ENCRYPT;
            break;
        case OPT_DECRYPT:
            pkey_op = EVP_PKEY_OP_DECRYPT;
            break;
        case OPT_DERIVE:
            pkey_op = EVP_PKEY_OP_DERIVE;
            break;
        case OPT_KDF:
            pkey_op = EVP_PKEY_OP_DERIVE;
            key_type = KEY_NONE;
            kdfalg = opt_arg();
            break;
        case OPT_KDFLEN:
            kdflen = atoi(opt_arg());
            break;
        case OPT_REV:
            rev = 1;
            break;
        case OPT_PKEYOPT:
            if ((pkeyopts == NULL &&
                 (pkeyopts = sk_OPENSSL_STRING_new_null()) == NULL) ||
                sk_OPENSSL_STRING_push(pkeyopts, opt_arg()) == 0) {
                BIO_puts(bio_err, "out of memory\n");
                goto end;
            }
            break;
        case OPT_PKEYOPT_PASSIN:
            if ((pkeyopts_passin == NULL &&
                 (pkeyopts_passin = sk_OPENSSL_STRING_new_null()) == NULL) ||
                sk_OPENSSL_STRING_push(pkeyopts_passin, opt_arg()) == 0) {
                BIO_puts(bio_err, "out of memory\n");
                goto end;
            }
            break;
        case OPT_RAWIN:
            rawin = 1;
            break;
        case OPT_DIGEST:
            if (!opt_md(opt_arg(), &md))
                goto end;
            break;
        }
    }
    argc = opt_num_rest();
    if (argc != 0)
        goto opthelp;

    if (rawin && pkey_op != EVP_PKEY_OP_SIGN && pkey_op != EVP_PKEY_OP_VERIFY) {
        BIO_printf(bio_err,
                   "%s: -rawin can only be used with -sign or -verify\n",
                   prog);
        goto opthelp;
    }

    if (md != NULL && !rawin) {
        BIO_printf(bio_err,
                   "%s: -digest can only be used with -rawin\n",
                   prog);
        goto opthelp;
    }

    if (rawin && rev) {
        BIO_printf(bio_err, "%s: -rev cannot be used with raw input\n",
                   prog);
        goto opthelp;
    }

    if (kdfalg != NULL) {
        if (kdflen == 0) {
            BIO_printf(bio_err,
                       "%s: no KDF length given (-kdflen parameter).\n", prog);
            goto opthelp;
        }
    } else if (inkey == NULL) {
        BIO_printf(bio_err,
                   "%s: no private key given (-inkey parameter).\n", prog);
        goto opthelp;
    } else if (peerkey != NULL && pkey_op != EVP_PKEY_OP_DERIVE) {
        BIO_printf(bio_err,
                   "%s: no peer key given (-peerkey parameter).\n", prog);
        goto opthelp;
    }
    ctx = init_ctx(kdfalg, &keysize, inkey, keyform, key_type,
                   passinarg, pkey_op, e, engine_impl, &pkey);
    if (ctx == NULL) {
        BIO_printf(bio_err, "%s: Error initializing context\n", prog);
        ERR_print_errors(bio_err);
        goto end;
    }
    if (peerkey != NULL && !setup_peer(ctx, peerform, peerkey, e)) {
        BIO_printf(bio_err, "%s: Error setting up peer key\n", prog);
        ERR_print_errors(bio_err);
        goto end;
    }
    if (pkeyopts != NULL) {
        int num = sk_OPENSSL_STRING_num(pkeyopts);
        int i;

        for (i = 0; i < num; ++i) {
            const char *opt = sk_OPENSSL_STRING_value(pkeyopts, i);

            if (pkey_ctrl_string(ctx, opt) <= 0) {
                BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
                           prog, opt);
                ERR_print_errors(bio_err);
                goto end;
            }
        }
    }
    if (pkeyopts_passin != NULL) {
        int num = sk_OPENSSL_STRING_num(pkeyopts_passin);
        int i;

        for (i = 0; i < num; i++) {
            char *opt = sk_OPENSSL_STRING_value(pkeyopts_passin, i);
            char *passin = strchr(opt, ':');
            char *passwd;

            if (passin == NULL) {
                /* Get password interactively */
                char passwd_buf[4096];
                BIO_snprintf(passwd_buf, sizeof(passwd_buf), "Enter %s: ", opt);
                EVP_read_pw_string(passwd_buf, sizeof(passwd_buf) - 1,
                                   passwd_buf, 0);
                passwd = OPENSSL_strdup(passwd_buf);
                if (passwd == NULL) {
                    BIO_puts(bio_err, "out of memory\n");
                    goto end;
                }
            } else {
                /* Get password as a passin argument: First split option name
                 * and passphrase argument into two strings */
                *passin = 0;
                passin++;
                if (app_passwd(passin, NULL, &passwd, NULL) == 0) {
                    BIO_printf(bio_err, "failed to get '%s'\n", opt);
                    goto end;
                }
            }

            if (EVP_PKEY_CTX_ctrl_str(ctx, opt, passwd) <= 0) {
                BIO_printf(bio_err, "%s: Can't set parameter \"%s\":\n",
                           prog, opt);
                goto end;
            }
            OPENSSL_free(passwd);
        }
    }

    if (sigfile != NULL && (pkey_op != EVP_PKEY_OP_VERIFY)) {
        BIO_printf(bio_err,
                   "%s: Signature file specified for non verify\n", prog);
        goto end;
    }

    if (sigfile == NULL && (pkey_op == EVP_PKEY_OP_VERIFY)) {
        BIO_printf(bio_err,
                   "%s: No signature file specified for verify\n", prog);
        goto end;
    }

    if (pkey_op != EVP_PKEY_OP_DERIVE) {
        in = bio_open_default(infile, 'r', FORMAT_BINARY);
        if (in == NULL)
            goto end;
    }
    out = bio_open_default(outfile, 'w', FORMAT_BINARY);
    if (out == NULL)
        goto end;

    if (sigfile != NULL) {
        BIO *sigbio = BIO_new_file(sigfile, "rb");

        if (sigbio == NULL) {
            BIO_printf(bio_err, "Can't open signature file %s\n", sigfile);
            goto end;
        }
        siglen = bio_to_mem(&sig, keysize * 10, sigbio);
        BIO_free(sigbio);
        if (siglen < 0) {
            BIO_printf(bio_err, "Error reading signature data\n");
            goto end;
        }
    }

    /* Raw input data is handled elsewhere */
    if (in != NULL && !rawin) {
        /* Read the input data */
        buf_inlen = bio_to_mem(&buf_in, keysize * 10, in);
        if (buf_inlen < 0) {
            BIO_printf(bio_err, "Error reading input Data\n");
            goto end;
        }
        if (rev) {
            size_t i;
            unsigned char ctmp;
            size_t l = (size_t)buf_inlen;
            for (i = 0; i < l / 2; i++) {
                ctmp = buf_in[i];
                buf_in[i] = buf_in[l - 1 - i];
                buf_in[l - 1 - i] = ctmp;
            }
        }
    }

    /* Sanity check the input if the input is not raw */
    if (!rawin
            && buf_inlen > EVP_MAX_MD_SIZE
            && (pkey_op == EVP_PKEY_OP_SIGN
                || pkey_op == EVP_PKEY_OP_VERIFY
                || pkey_op == EVP_PKEY_OP_VERIFYRECOVER)) {
        BIO_printf(bio_err,
                   "Error: The input data looks too long to be a hash\n");
        goto end;
    }

    if (pkey_op == EVP_PKEY_OP_VERIFY) {
        if (rawin) {
            rv = do_raw_keyop(pkey_op, ctx, md, pkey, in, sig, siglen,
                              NULL, 0);
        } else {
            rv = EVP_PKEY_verify(ctx, sig, (size_t)siglen,
                                 buf_in, (size_t)buf_inlen);
        }
        if (rv == 1) {
            BIO_puts(out, "Signature Verified Successfully\n");
            ret = 0;
        } else {
            BIO_puts(out, "Signature Verification Failure\n");
        }
        goto end;
    }
    if (kdflen != 0) {
        buf_outlen = kdflen;
        rv = 1;
    } else {
        if (rawin) {
            /* rawin allocates the buffer in do_raw_keyop() */
            rv = do_raw_keyop(pkey_op, ctx, md, pkey, in, NULL, 0,
                              &buf_out, (size_t *)&buf_outlen);
        } else {
            rv = do_keyop(ctx, pkey_op, NULL, (size_t *)&buf_outlen,
                          buf_in, (size_t)buf_inlen);
            if (rv > 0 && buf_outlen != 0) {
                buf_out = app_malloc(buf_outlen, "buffer output");
                rv = do_keyop(ctx, pkey_op,
                              buf_out, (size_t *)&buf_outlen,
                              buf_in, (size_t)buf_inlen);
            }
        }
    }
    if (rv <= 0) {
        if (pkey_op != EVP_PKEY_OP_DERIVE) {
            BIO_puts(bio_err, "Public Key operation error\n");
        } else {
            BIO_puts(bio_err, "Key derivation failed\n");
        }
        ERR_print_errors(bio_err);
        goto end;
    }
    ret = 0;

    if (asn1parse) {
        if (!ASN1_parse_dump(out, buf_out, buf_outlen, 1, -1))
            ERR_print_errors(bio_err);
    } else if (hexdump) {
        BIO_dump(out, (char *)buf_out, buf_outlen);
    } else {
        BIO_write(out, buf_out, buf_outlen);
    }

 end:
    EVP_PKEY_CTX_free(ctx);
    release_engine(e);
    BIO_free(in);
    BIO_free_all(out);
    OPENSSL_free(buf_in);
    OPENSSL_free(buf_out);
    OPENSSL_free(sig);
    sk_OPENSSL_STRING_free(pkeyopts);
    sk_OPENSSL_STRING_free(pkeyopts_passin);
    return ret;
}