Exemplo n.º 1
0
int main(int argc, char *argv[])
{
  char  *delegation_id = "", *reqtxt, *certtxt, *valid = NULL, 
        *cert = NULL, *key = NULL, *capath = NULL, *keycert, timestr[81],
        *vomsdir = "/etc/grid-security/vomsdir",
        *executable, *keytxt, *proxychain, *ptr, *p;
  struct ns__putProxyResponse *unused = NULL;
  struct tm *finish_tm;
  int    option_index, c, noverify = 0, i, ret,
         method = HTPROXY_PUT, verbose = 0, fd, minutes;
  struct soap soap_get, soap_put;
  struct ns__getNewProxyReqResponse     getNewProxyReqResponse;
  struct ns__renewProxyReqResponse      renewProxyReqResponse;
  struct ns__destroyResponse            destroyResponse;
  struct ns__getTerminationTimeResponse getTerminationTimeResponse;
  FILE   *ifp, *ofp;
  STACK_OF(X509) *x509_certstack;
  X509   *x509_cert;
  BIO    *certmem;
  GRSTx509Chain *grst_chain = NULL;
  GRSTx509Cert  *grst_cert = NULL;
  long   ptrlen;
  struct stat statbuf;
  struct passwd *userpasswd; 
  struct option long_options[] = {      {"verbose",     0, 0, 'v'},
                                        {"cert",        1, 0, 0},
                                        {"key",         1, 0, 0},
                                        {"capath",      1, 0, 0},
                                        {"destroy",     0, 0, 0},
                                        {"time",        0, 0, 0},
                                        {"no-verify",   0, 0, 0},
                                        {"valid",       1, 0, 0},
                                        {"delegation-id",1, 0, 0},
                                        {"put",         0, 0, 0},
                                        {"renew",       0, 0, 0},
                                        {"unixtime",	0, 0, 0},
                                        {"make",	0, 0, 0},
                                        {"info",	0, 0, 0},
                                        {0, 0, 0, 0}  };

  if (argc == 1)
    {
      printsyntax(argv[0]);
      return 0;
    }

  while (1)
       {
         option_index = 0;
                                                                                
         c = getopt_long(argc, argv, "v", long_options, &option_index);

         if      (c == -1) break;
         else if (c == 0)
           {
             if      (option_index ==  1) cert            = optarg;
             else if (option_index ==  2) key             = optarg;
             else if (option_index ==  3) capath          = optarg;
             else if (option_index ==  4) method          = HTPROXY_DESTROY;
             else if (option_index ==  5) method          = HTPROXY_TIME;
             else if (option_index ==  6) noverify        = 1;
             else if (option_index ==  7) valid           = optarg;
             else if (option_index ==  8) delegation_id   = optarg;
             else if (option_index ==  9) method          = HTPROXY_PUT;
             else if (option_index == 10) method          = HTPROXY_RENEW;
             else if (option_index == 11) method          = HTPROXY_UNIXTIME;
             else if (option_index == 12) method          = HTPROXY_MAKE;
             else if (option_index == 13) method          = HTPROXY_INFO;
           }
         else if (c == 'v') 
                {
                  GRSTerrorLogFunc = htproxy_logfunc;
                  ++verbose;
                }
       }

  executable = rindex(argv[0], '/');
  if (executable != NULL) executable++;
  else                    executable = argv[0];
  
  if    (strcmp(executable, "htproxydestroy") == 0) method = HTPROXY_DESTROY;
  else if (strcmp(executable, "htproxyrenew") == 0) method = HTPROXY_RENEW;
  else if (strcmp(executable, "htproxytime") == 0)  method = HTPROXY_TIME;
  else if (strcmp(executable, "htproxyunixtime") == 0) 
                                                    method = HTPROXY_UNIXTIME;
  else if (strcmp(executable, "htproxymake") == 0)  method = HTPROXY_MAKE;
  else if (strcmp(executable, "htproxyinfo") == 0)  method = HTPROXY_INFO;

  if ((method != HTPROXY_MAKE) && 
      (method != HTPROXY_INFO) && (optind + 1 != argc))
    {
      fprintf(stderr, "Must specify a delegation service URL!\n");
      return 1;
    }

  if ((method == HTPROXY_RENEW) && (delegation_id[0] == '\0'))
    {
      fprintf(stderr, "Must give a Delegation ID when renewing\n");
      return 1;
    }
    
  if (valid == NULL) minutes = 60 * 12;
  else minutes = atoi(valid);
  
  if (verbose) fprintf(stderr, "Proxy valid for %d minutes\n", minutes);
 
  ERR_load_crypto_strings ();
  OpenSSL_add_all_algorithms();

  if      ((cert == NULL) && (key != NULL)) cert = key;
  else if ((cert != NULL) && (key == NULL)) key = cert;
  else if ((cert == NULL) && (key == NULL))
    {
      if (method != HTPROXY_MAKE) cert = getenv("X509_USER_PROXY");

      if (cert != NULL) key = cert;
      else
        {
          if (method != HTPROXY_MAKE) 
               asprintf(&(cert), "/tmp/x509up_u%d", geteuid());

          /* one fine day, we will check the proxy file for 
             expiry too to avoid suprises when we try to use it ... */

          if (stat(cert, &statbuf) == 0) key = cert;
          else if (method != HTPROXY_INFO)
            {
              cert = getenv("X509_USER_CERT");
              key  = getenv("X509_USER_KEY");
                                                                                
              userpasswd = getpwuid(geteuid());
                                                                                
              if ((cert == NULL) &&
                  (userpasswd != NULL) &&
                  (userpasswd->pw_dir != NULL))
                asprintf(&(cert), "%s/.globus/usercert.pem",
                                                    userpasswd->pw_dir);
                                                                                
              if ((key == NULL) &&
                  (userpasswd != NULL) &&
                  (userpasswd->pw_dir != NULL))
                asprintf(&(key), "%s/.globus/userkey.pem",
                                                    userpasswd->pw_dir);
                                                                                
            }
        }
    }
                                                                                
  if (capath == NULL) capath = getenv("X509_CERT_DIR");
  if (capath == NULL) capath = "/etc/grid-security/certificates";

  if (verbose) fprintf(stderr, "key=%s\ncert=%s\ncapath=%s\n",
                       key, cert, capath);

  if ((key != NULL) && (cert != NULL) &&
      (strcmp(key, cert) != 0)) /* we have to concatenate for gSOAP */
    {
      keycert = strdup("/tmp/.XXXXXX");
        
      fd = mkstemp(keycert);
      ofp = fdopen(fd, "w");
      if (!ofp)
      {
          fprintf(stderr, "Cannot open tmp file for the key\n");
          return 1;
      }
          
      ifp = fopen(key, "r");          
      {
          fprintf(stderr, "Cannot open the file with the key\n");
          return 1;
      }
      while ((c = fgetc(ifp)) != EOF) fputc(c, ofp);          
      fclose(ifp);
          
      ifp = fopen(cert, "r");          
      {
          fprintf(stderr, "Cannot open the file with the cert\n");
          return 1;
      }
      while ((c = fgetc(ifp)) != EOF) fputc(c, ofp);          
      fclose(ifp);
          
      fclose(ofp);       
          
      if (verbose) fprintf(stderr, "Created %s key/cert file\n", keycert);
    }
  else keycert = key;

  if ((method == HTPROXY_PUT) || (method == HTPROXY_RENEW))
    {
      if (verbose) 
        {
          fprintf(stderr, "Using SOAP delegation protocol\n");
          fprintf(stderr, "Delegation-ID: %s\n", delegation_id);
        }

      soap_init(&soap_get);
  
      if (soap_ssl_client_context(&soap_get,
                                  SOAP_SSL_DEFAULT,
                                  keycert, 
                                  "",
                                  NULL,
                                  capath,
                                  NULL))
        {
          soap_print_fault(&soap_get, stderr);
          return 1;
        } 

      if ((method == HTPROXY_RENEW) && (delegation_id[0] != '\0'))
        {
          if (verbose) fprintf(stderr, "Send renewProxyReq to service\n");

          soap_call_ns__renewProxyReq(&soap_get, 
                                argv[optind],	/* HTTPS url of service */
                                "http://www.gridsite.org/namespaces/delegation-1",
                                delegation_id, 
                                &renewProxyReqResponse);
      
          if (soap_get.error)
            {
              soap_print_fault(&soap_get, stderr);
              return 1;        
            }
       
          reqtxt = renewProxyReqResponse._renewProxyReqReturn;
        }
      else
        {
          if (verbose) fprintf(stderr, "Send getNewProxyReq to service\n");

          soap_call_ns__getNewProxyReq(&soap_get,
                            argv[optind],	/* HTTPS url of service */
                            "http://www.gridsite.org/namespaces/delegation-1",
                            &getNewProxyReqResponse);

          if (soap_get.error)
            {
              soap_print_fault(&soap_get, stderr);
              return 1;        
            }

          if (!getNewProxyReqResponse.getNewProxyReqReturn)
            {
              fprintf(stderr, "Empty response from getNewProxyReq\n");
              return 1;
            }

          reqtxt = getNewProxyReqResponse.getNewProxyReqReturn->proxyRequest;
          delegation_id = 
                   getNewProxyReqResponse.getNewProxyReqReturn->delegationID;
        }
 
      if (verbose) fprintf(stderr, "reqtxt:\n%s", reqtxt);
      
      if (GRSTx509MakeProxyCert(&certtxt, stderr, reqtxt, cert, key, minutes) 
          != GRST_RET_OK)
        {
          return 1;
        }

      soap_init(&soap_put);
  
      if (verbose) fprintf(stderr, "Send putProxy to service:\n%s\n", certtxt);

      if (soap_ssl_client_context(&soap_put,
                                  SOAP_SSL_DEFAULT,
                                  keycert, 
                                  "",
                                  NULL,
                                  capath,
                                  NULL))
        {
          soap_print_fault(&soap_put, stderr);
          return 1;
        } 

      soap_call_ns__putProxy(&soap_put, argv[optind],
                             "http://www.gridsite.org/namespaces/delegation-1",
                             delegation_id, 
                             certtxt, unused);      
      if (soap_put.error)
        {
          soap_print_fault(&soap_put, stderr);
          return 1;        
        }

      puts(delegation_id);

      return 0;
    }  
  else if (method == HTPROXY_DESTROY)
    {
      if (verbose) 
        {
          fprintf(stderr, "Using SOAP proxy destroy protocol\n");
          fprintf(stderr, "Delegation-ID: %s\n", delegation_id);
        }

      soap_init(&soap_put);
  
      if (verbose) fprintf(stderr, "Send destroy to service:\n");

      if (soap_ssl_client_context(&soap_put,
                                  SOAP_SSL_DEFAULT,
                                  keycert, 
                                  "",
                                  NULL,
                                  capath,
                                  NULL))
        {
          soap_print_fault(&soap_put, stderr);
          return 1;
        } 

      soap_call_ns__destroy(&soap_put, argv[optind],
                             "http://www.gridsite.org/namespaces/delegation-1",
                             delegation_id, 
                             &destroyResponse);
      if (soap_put.error)
        {
          soap_print_fault(&soap_put, stderr);
          return 1;        
        }

      return 0;
    }  
  else if ((method == HTPROXY_TIME) || (method == HTPROXY_UNIXTIME))
    {
      if (verbose) 
        {
          fprintf(stderr, "Using SOAP proxy get expiration time protocol\n");
          fprintf(stderr, "Delegation-ID: %s\n", delegation_id);
        }

      soap_init(&soap_put);
  
      if (verbose) fprintf(stderr, "Send get time to service:\n");

      if (soap_ssl_client_context(&soap_put,
                                  SOAP_SSL_DEFAULT,
                                  keycert, 
                                  "",
                                  NULL,
                                  capath,
                                  NULL))
        {
          soap_print_fault(&soap_put, stderr);
          return 1;
        } 

      soap_call_ns__getTerminationTime(&soap_put, argv[optind],
                             "http://www.gridsite.org/namespaces/delegation-1",
                             delegation_id, 
                             &getTerminationTimeResponse);
      if (soap_put.error)
        {
          soap_print_fault(&soap_put, stderr);
          return 1;        
        }


      if (method == HTPROXY_UNIXTIME)
       printf("%ld\n", getTerminationTimeResponse._getTerminationTimeReturn);
      else
        {
          finish_tm = 
           localtime(&(getTerminationTimeResponse._getTerminationTimeReturn));

          strftime(timestr, sizeof(timestr),
                       "%a %b %e %H:%M:%S %Z %Y\n", finish_tm);
                       
          fputs(timestr, stdout);
        }
        
      return 0;
    }  
  else if (method == HTPROXY_MAKE)
#ifdef HT_LEAK_TEST
    {
    int ii;
    FILE *ffpp;
    char lineline[80];
    for (ii=0; ii < 1000; ++ii)
#endif
    {
      if (GRSTx509CreateProxyRequestKS(&reqtxt, &keytxt, NULL, 0) != GRST_RET_OK)
        {
          fprintf(stderr, "Failed to create internal proxy cert request\n");
          return 1;
        }
      
#ifdef HT_LEAK_TEST      
     ffpp = fopen("/proc/self/statm", "r");
     fgets(lineline, sizeof(lineline), ffpp);
     fprintf(stderr, "%d a %s", ii, lineline);
     fclose(ffpp);
#endif
      if (GRSTx509MakeProxyCert(&proxychain, NULL, reqtxt, cert, key, minutes)
            != GRST_RET_OK)
        {
          fprintf(stderr, "Failed to sign internal proxy cert request\n");
          return 2;
        }
        
#ifdef HT_LEAK_TEST      
     ffpp = fopen("/proc/self/statm", "r");
     fgets(lineline, sizeof(lineline), ffpp);
     fprintf(stderr, "%d b %s", ii, lineline);
     fclose(ffpp);
#endif

      /* convert back to cert stack so can output in the right order */
      if (GRSTx509StringToChain(&x509_certstack, proxychain) != GRST_RET_OK)
        {
          fprintf(stderr, "Failed to convert internal proxy chain\n");
          return 3;
        }
        
#ifdef HT_LEAK_TEST      
     ffpp = fopen("/proc/self/statm", "r");
     fgets(lineline, sizeof(lineline), ffpp);
     fprintf(stderr, "%d c %s", ii, lineline);
     fclose(ffpp);
#endif

      /* just the proxy certificate we have created */
      if ((x509_cert = sk_X509_value(x509_certstack, 0)))
        {
          certmem = BIO_new(BIO_s_mem());
          if (PEM_write_bio_X509(certmem, x509_cert) == 1)
            {
              ptrlen = BIO_get_mem_data(certmem, &ptr);
              fwrite(ptr, 1, ptrlen, stdout);
            }
                                                          
          BIO_free(certmem);
        }
                                                                    
#ifdef HT_LEAK_TEST      
     ffpp = fopen("/proc/self/statm", "r");
     fgets(lineline, sizeof(lineline), ffpp);
     fprintf(stderr, "%d d %s", ii, lineline);
     fclose(ffpp);
#endif
      /* then the private key */ 
      fputs(keytxt, stdout);
      
      /* and only now the rest of the certificates */
      for (i=1; i <= sk_X509_num(x509_certstack) - 1; ++i)
        /* loop through the proxy chain starting at 2nd most recent proxy */
         {
           if ((x509_cert = sk_X509_value(x509_certstack, i)))
             {
               certmem = BIO_new(BIO_s_mem());
               if (PEM_write_bio_X509(certmem, x509_cert) == 1)
                 {
                   ptrlen = BIO_get_mem_data(certmem, &ptr);
                   fwrite(ptr, 1, ptrlen, stdout);
                 }

               BIO_free(certmem);
             }
         }

 
#ifdef HT_LEAK_TEST      
     ffpp = fopen("/proc/self/statm", "r");
     fgets(lineline, sizeof(lineline), ffpp);
     fprintf(stderr, "%d e %s", ii, lineline);
     fclose(ffpp);
#endif
      free(proxychain);
      free(keytxt);
      free(reqtxt);
      sk_X509_free(x509_certstack);
      
#ifdef HT_LEAK_TEST      
     ffpp = fopen("/proc/self/statm", "r");
     fgets(lineline, sizeof(lineline), ffpp);
     fprintf(stderr, "%d f %s", ii, lineline);
     fclose(ffpp);
    }
#endif
      return 0;
    }
  else if (method == HTPROXY_INFO)
    {
      if (cert != NULL) 
        {
          if (verbose) fprintf(stderr, "Getting proxy info from %s\n", cert);
    
          ifp = fopen(cert, "r");
          if (ifp == NULL)
            {
              fprintf(stderr, "Failed to open proxy file\n");
              return 2;              
            }
        }
      else  
        {
          if (verbose) fprintf(stderr, "Getting proxy info from stdin\n");
          ifp = stdin;
        }
      
      ptrlen = 4096;
      ptr = malloc(ptrlen);
      i = 0;
      
      while ((c = fgetc(ifp)) != EOF)
           {
             ptr[i] = c;
             ++i;
             
             if (i >= ptrlen) 
               {
                 ptrlen += 4096;
                 ptr = realloc(ptr, ptrlen);
               }
           }
           
      ptr[i] = '\0';
      if (cert != NULL) fclose(ifp);
      
      if ((GRSTx509StringToChain(&x509_certstack, ptr) != GRST_RET_OK) ||
          (x509_certstack == NULL))
        {
          fprintf(stderr, "Failed to parse proxy file for certificate chain\n");
          free(ptr);
          return 2;
        }

      free(ptr);

      if (verbose) fprintf(stderr, "Parsing certificate chain\n");
      
      ret = GRSTx509ChainLoadCheck(&grst_chain, x509_certstack, NULL,  
                                   capath, vomsdir);
      
      if ((ret != GRST_RET_OK) || 
          (grst_chain == NULL) || (grst_chain->firstcert == NULL))
        {
          fprintf(stderr, "Failed parsing certificate chain\n");
          return 3;
        }
      
      grst_cert = grst_chain->firstcert;

      for (i=0; grst_cert != NULL; grst_cert = grst_cert->next, ++i)
         {
           if      (grst_cert->type == GRST_CERT_TYPE_CA)    p = "(CA) ";
           else if (grst_cert->type == GRST_CERT_TYPE_EEC)   p = "(EEC) ";
           else if (grst_cert->type == GRST_CERT_TYPE_PROXY) p = "(PC) ";
           else if (grst_cert->type == GRST_CERT_TYPE_VOMS)  p = "(AC) ";
           else p = "";
                              
           printf("%d %s%s\n", i, p,
                  (grst_cert->type == GRST_CERT_TYPE_VOMS) 
                    ? grst_cert->value : grst_cert->dn);
 
           printf(" Status     : %d ( %s%s%s%s%s%s)\n", grst_cert->errors,
                 (grst_cert->errors == 0) ? "OK " : "",
                 (grst_cert->errors & GRST_CERT_BAD_FORMAT) ? "BAD_FORMAT ":"",
                 (grst_cert->errors & GRST_CERT_BAD_CHAIN)  ? "BAD_CHAIN ":"",
                 (grst_cert->errors & GRST_CERT_BAD_SIG)    ? "BAD_SIG ":"",
                 (grst_cert->errors & GRST_CERT_BAD_TIME)   ? "BAD_TIME ":"",
                 (grst_cert->errors & GRST_CERT_BAD_OCSP)   ? "BAD_OCSP ":"");

           printf(" Start      : %s",   ctime(&(grst_cert->notbefore)));
           printf(" Finish     : %s",   ctime(&(grst_cert->notafter)));
           printf(" Delegation : %d\n", grst_cert->delegation);

           if (grst_cert->type == GRST_CERT_TYPE_VOMS)
             {
               printf(" User DN    : %s\n", grst_cert->dn);
               printf(" VOMS DN    : %s\n\n", grst_cert->issuer);
             }
           else
             {
               printf(" Serial     : %s\n", grst_cert->serial);
               printf(" Issuer     : %s\n\n", grst_cert->issuer);              
             }
         }
      
      GRSTx509ChainFree(grst_chain);
    }
  /* weirdness */
}
Exemplo n.º 2
0
Arquivo: ossl.c Projeto: genki/ruby
/*
 * OSSL library init
 */
void
Init_openssl()
{
    /*
     * Init timezone info
     */
#if 0
    tzset();
#endif

    /*
     * Init all digests, ciphers
     */
    /* CRYPTO_malloc_init(); */
    /* ENGINE_load_builtin_engines(); */
    OpenSSL_add_ssl_algorithms();
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();
    SSL_load_error_strings();

    /*
     * FIXME:
     * On unload do:
     */
#if 0
    CONF_modules_unload(1);
    destroy_ui_method();
    EVP_cleanup();
    ENGINE_cleanup();
    CRYPTO_cleanup_all_ex_data();
    ERR_remove_state(0);
    ERR_free_strings();
#endif

    /*
     * Init main module
     */
    mOSSL = rb_define_module("OpenSSL");

    /*
     * Constants
     */
    rb_define_const(mOSSL, "VERSION", rb_str_new2(OSSL_VERSION));
    rb_define_const(mOSSL, "OPENSSL_VERSION", rb_str_new2(OPENSSL_VERSION_TEXT));
    rb_define_const(mOSSL, "OPENSSL_VERSION_NUMBER", INT2NUM(OPENSSL_VERSION_NUMBER));

    /*
     * Generic error,
     * common for all classes under OpenSSL module
     */
    eOSSLError = rb_define_class_under(mOSSL,"OpenSSLError",rb_eStandardError);

    /*
     * Verify callback Proc index for ext-data
     */
    if ((ossl_verify_cb_idx = X509_STORE_CTX_get_ex_new_index(0, (void *)"ossl_verify_cb_idx", 0, 0, 0)) < 0)
        ossl_raise(eOSSLError, "X509_STORE_CTX_get_ex_new_index");

    /*
     * Init debug core
     */
    dOSSL = Qfalse;
    rb_define_module_function(mOSSL, "debug", ossl_debug_get, 0);
    rb_define_module_function(mOSSL, "debug=", ossl_debug_set, 1);
    rb_define_module_function(mOSSL, "errors", ossl_get_errors, 0);

    /*
     * Get ID of to_der
     */
    ossl_s_to_der = rb_intern("to_der");

    /*
     * Init components
     */
    Init_ossl_bn();
    Init_ossl_cipher();
    Init_ossl_config();
    Init_ossl_digest();
    Init_ossl_hmac();
    Init_ossl_ns_spki();
    Init_ossl_pkcs12();
    Init_ossl_pkcs7();
    Init_ossl_pkcs5();
    Init_ossl_pkey();
    Init_ossl_rand();
    Init_ossl_ssl();
    Init_ossl_x509();
    Init_ossl_ocsp();
    Init_ossl_engine();
    Init_ossl_asn1();
}
Exemplo n.º 3
0
int
main(int argc, char **argv)
{
	Buffer b;
	Options options;
#define NUM_KEYTYPES 3
	Key *keys[NUM_KEYTYPES], *key = NULL;
	struct passwd *pw;
	int key_fd[NUM_KEYTYPES], i, found, version = 2, fd;
	u_char *signature, *data;
	char *host;
	u_int slen, dlen;
	u_int32_t rnd[256];

	/* Ensure that stdin and stdout are connected */
	if ((fd = open(_PATH_DEVNULL, O_RDWR)) < 2)
		exit(1);
	/* Leave /dev/null fd iff it is attached to stderr */
	if (fd > 2)
		close(fd);

	i = 0;
	key_fd[i++] = open(_PATH_HOST_DSA_KEY_FILE, O_RDONLY);
	key_fd[i++] = open(_PATH_HOST_ECDSA_KEY_FILE, O_RDONLY);
	key_fd[i++] = open(_PATH_HOST_RSA_KEY_FILE, O_RDONLY);

	original_real_uid = getuid();	/* XXX readconf.c needs this */
	if ((pw = getpwuid(original_real_uid)) == NULL)
		fatal("getpwuid failed");
	pw = pwcopy(pw);

	permanently_set_uid(pw);

#ifdef DEBUG_SSH_KEYSIGN
	log_init("ssh-keysign", SYSLOG_LEVEL_DEBUG3, SYSLOG_FACILITY_AUTH, 0);
#endif

	/* verify that ssh-keysign is enabled by the admin */
	initialize_options(&options);
	(void)read_config_file(_PATH_HOST_CONFIG_FILE, "", &options, 0);
	fill_default_options(&options);
	if (options.enable_ssh_keysign != 1)
		fatal("ssh-keysign not enabled in %s",
		    _PATH_HOST_CONFIG_FILE);

	for (i = found = 0; i < NUM_KEYTYPES; i++) {
		if (key_fd[i] != -1)
			found = 1;
	}
	if (found == 0)
		fatal("could not open any host key");

	OpenSSL_add_all_algorithms();
	for (i = 0; i < 256; i++)
		rnd[i] = arc4random();
	RAND_seed(rnd, sizeof(rnd));

	found = 0;
	for (i = 0; i < NUM_KEYTYPES; i++) {
		keys[i] = NULL;
		if (key_fd[i] == -1)
			continue;
		keys[i] = key_load_private_pem(key_fd[i], KEY_UNSPEC,
		    NULL, NULL);
		close(key_fd[i]);
		if (keys[i] != NULL)
			found = 1;
	}
	if (!found)
		fatal("no hostkey found");

	buffer_init(&b);
	if (ssh_msg_recv(STDIN_FILENO, &b) < 0)
		fatal("ssh_msg_recv failed");
	if (buffer_get_char(&b) != version)
		fatal("bad version");
	fd = buffer_get_int(&b);
	if ((fd == STDIN_FILENO) || (fd == STDOUT_FILENO))
		fatal("bad fd");
	if ((host = get_local_name(fd)) == NULL)
		fatal("cannot get local name for fd");

	data = buffer_get_string(&b, &dlen);
	if (valid_request(pw, host, &key, data, dlen) < 0)
		fatal("not a valid request");
	xfree(host);

	found = 0;
	for (i = 0; i < NUM_KEYTYPES; i++) {
		if (keys[i] != NULL &&
		    key_equal_public(key, keys[i])) {
			found = 1;
			break;
		}
	}
	if (!found)
		fatal("no matching hostkey found");

	if (key_sign(keys[i], &signature, &slen, data, dlen) != 0)
		fatal("key_sign failed");
	xfree(data);

	/* send reply */
	buffer_clear(&b);
	buffer_put_string(&b, signature, slen);
	if (ssh_msg_send(STDOUT_FILENO, version, &b) == -1)
		fatal("ssh_msg_send failed");

	return (0);
}
Exemplo n.º 4
0
int main(int argc, char **argv)
{
	int sockfd, len;
	struct sockaddr_in dest;
	char buffer[MAXBUF + 1];
	SSL_CTX *ctx;
	SSL *ssl;

	if (argc != 3) {
		printf("参数格式错误!正确用法如下:\n\t\t%s IP地址 端口\n\t比如:\t%s 127.0.0.1 80\n此程序用来从某个"
		"IP 地址的服务器某个端口接收最多 MAXBUF 个字节的消息",
		argv[0], argv[0]);
		exit(0);
	}


	SSL_library_init();
	OpenSSL_add_all_algorithms();
	SSL_load_error_strings();
	ctx = SSL_CTX_new(SSLv23_client_method());
	if (ctx == NULL) {
		ERR_print_errors_fp(stdout);
		exit(1);
	}


	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
		perror("Socket");
		exit(errno);
	}
	printf("socket created\n");


	bzero(&dest, sizeof(dest));
	dest.sin_family = AF_INET;
	dest.sin_port = htons(atoi(argv[2]));
	if (inet_aton(argv[1], (struct in_addr *) &dest.sin_addr.s_addr) == 0) {
		perror(argv[1]);
		exit(errno);
	}
	printf("address created\n");


	if (connect(sockfd, (struct sockaddr *) &dest, sizeof(dest)) != 0) {
		perror("Connect ");
		exit(errno);
	}
	printf("server connected\n");


	ssl = SSL_new(ctx);
	SSL_set_fd(ssl, sockfd);

	if (SSL_connect(ssl) == -1)
		ERR_print_errors_fp(stderr);
	else {
		printf("Connected with %s encryption\n", SSL_get_cipher(ssl));
		ShowCerts(ssl);
	}


	bzero(buffer, MAXBUF + 1);

	len = SSL_read(ssl, buffer, MAXBUF);
	if (len > 0)
		printf("接收消息成功:'%s',共%d个字节的数据\n",
		buffer, len);
	else {
		printf
		("消息接收失败!错误代码是%d,错误信息是'%s'\n",
		errno, strerror(errno));
		goto finish;
	}
	bzero(buffer, MAXBUF + 1);
	strcpy(buffer, "from client->server");

	len = SSL_write(ssl, buffer, strlen(buffer));
	if (len < 0)
		printf
		("消息'%s'发送失败!错误代码是%d,错误信息是'%s'\n",
		buffer, errno, strerror(errno));
	else
		printf("消息'%s'发送成功,共发送了%d个字节!\n",
		buffer, len);

finish:

	SSL_shutdown(ssl);
	SSL_free(ssl);
	close(sockfd);
	SSL_CTX_free(ctx);
	return 0;
}
Exemplo n.º 5
0
/**
 * init module function
 *    return value: -1: error
 *                   0: else
 */
static int mod_init(void)
{
	LM_INFO("initializing ...\n");

	OpenSSL_add_all_algorithms();
	ERR_load_crypto_strings();

	if(!caList)
	{
		LM_ERR("caList not set\n");
		return 0;
	}

	if(!privKey)
	{
		LM_ERR("modparam privKey not set\n");
		return 0;
	}

	if(!authCert)
	{
		LM_ERR("param authCert not set\n");
		return 0;
	}

	if(!verCert)
	{
		LM_ERR("verCert not set\n");
		return 0;
	}

	if(useCrls && (!crlList))
	{
		LM_ERR("useCrls=1 and crlList not set\n");
		return 0;
	}

	if(!setAuthCertPeriod())
	{
		LM_ERR("initialization failed\n");
		return -1;
	}

	if(!readPrivKey())
	{
		LM_ERR("initialization failed\n");
		return -1;
	}

	if(!certUri)
	{
		LM_ERR("certUri not set\n");
		return -1;
	}

	if(!initVerCertWithSlash())
	{
		LM_ERR("initialization failed\n");
		return -1;
	}

	if(!prepareCertValidation())
	{
		LM_ERR("initialization failed\n");
		return -1;
	}

	return 0;
}
Exemplo n.º 6
0
int main(int argc, char** argv) {

	char *psw, *infile, *dict, *nt, *msgintstring, quiet, isdict, isbrute, *swl_min, *swl_max, *scs, *ics, *base;
	int c;
	unsigned long long *count;
	int wordlength_min = MINWORDLENGTH;
	int wordlength_max = 0;
	quiet = 1;
	psw = NULL;
	infile = NULL;
	dict = NULL;
	nt = NULL;
	msgintstring = NULL;
	scs = NULL;
	ics = NULL;
	nt = NULL;
	isdict = 0;
	isbrute = 0;
	swl_min = NULL;
	swl_max = NULL;
	base = NULL;
	nthreads = sysconf (_SC_NPROCESSORS_ONLN);
	nthreads_total = sysconf (_SC_NPROCESSORS_ONLN);

	while ((c = getopt (argc, argv, "t:d:s:vbm:M:c:")) != -1)
		switch (c) {
			case 'b':
				isbrute = 1;
				break;
			case 'M':
				isbrute = 1;
				swl_max = optarg;				
				break;
			case 'm':
				isbrute = 1;
				swl_min = optarg;				
				break;
			case 'c':
				scs = optarg;				
				break;
			case 's':
				ics = optarg;				
				break;
			case 'd':
				isdict = 1;
				dict = optarg;
				break;
			case 't':
				nt = optarg;
				break;
			case 'v':
				quiet = 0;
				break;
			case '?':
				if (optopt == 't' || optopt == 'd' || optopt == 's') {
					fprintf (stderr, "Option -%c requires an argument.\n", optopt);
				}
			default:
				usage();
		}

	if (!isdict && !isbrute) {
		fprintf(stderr,"Error: Choose at least one attack type (-d for dictionary attack or -b for brute force attack)\n\n");
		usage();
	}

	if (ics != NULL && scs != NULL) {
		fprintf(stderr,"-c and -s are not compatible flags\n\n");
		usage();
	}
	
	
	if (optind != argc-1)
		usage();
	else
		infile = argv[optind];

	if (isdict == 1 && dict == NULL) {
		fprintf(stderr,"Error: No dictionary file specified\n\n");
		usage();
	}

	if (swl_min != NULL) {
		wordlength_min = strtol(swl_min, NULL, 10);
		if (errno == EINVAL)
			usage();
		if (wordlength_min < MINWORDLENGTH) {
			wordlength_min = MINWORDLENGTH;
			printf("\nForcing min word length to %d\n\n",wordlength_min);
		}
	}
	else
	    wordlength_min = DEFAULTMINWORDLENGTH;

	if (swl_max != NULL) {
		wordlength_max = strtol(swl_max, NULL, 10);
		if (errno == EINVAL)
			usage();
		if (wordlength_max > MAXWORDLENGTH) {
			wordlength_max = MAXWORDLENGTH;
			printf("\nForcing max word length to %d\n\n",wordlength_max);
		}
	}
	else
	    wordlength_max = DEFAULTMAXWORDLENGTH;

	if (wordlength_min > wordlength_max) {
		if (swl_min != NULL && swl_max != NULL) {
			fprintf(stderr,"Error: Min length is greater than max length\n\n");
			usage();
		}
		else if (swl_min != NULL && swl_max == NULL)
			wordlength_max = wordlength_min;
		else if (swl_min == NULL && swl_max != NULL)
			wordlength_min = wordlength_max;
	}

	if (isbrute) {
		if (ics != NULL) {
			base = ics;
		}
		else {
			if (scs == NULL)
				scs = "x"; // by default all character sets
			base = getbase(scs);
			if (base == NULL)
				usage();
		}
	}
	else if (scs != NULL || ics != NULL) {
		printf("-c and -s flags require -b, -m or -M flags\n");
		usage();
	}

	if (nt != NULL) {
		nthreads = strtol(nt, NULL, 10);
		if (errno == EINVAL)
			usage();
	}

	if (!quiet)
		nthreads_total++;

	OpenSSL_add_all_algorithms();

	pthread_t *thread = (pthread_t *) calloc(nthreads_total,sizeof(pthread_t));
	int *thread_ret = (int *) calloc(nthreads_total, sizeof(int));
	pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
	count = calloc(nthreads, sizeof(unsigned long long));
	int i;
	if (isdict) {
		// Opening dictionary file
		FILE *dictfile = fopen(dict,"r");
		if (!dictfile) {
			fprintf(stderr,"Dictionary file not found: %s\n",dict);
			exit(20);
		}
		workerdict *wthread = (workerdict *) calloc(nthreads,sizeof(workerdict));
	
		printf("\nDictionary attack - Starting %d threads\n",nthreads);

		for (i=0; i<nthreads; i++) {
			wthread[i].id = i;
			wthread[i].m = &mutex;
			wthread[i].dictfile = dictfile;
			wthread[i].file2crack = infile;
			wthread[i].quiet = quiet;
			wthread[i].count = count+i;
			thread_ret[i] = pthread_create( &thread[i], NULL, work_dict, (void*) &wthread[i]);
		}
		if (!quiet)
			pthread_create(&thread[i], NULL, print_output, (void*) count);
		for (i=0; i<nthreads_total; i++) {
			pthread_join(thread[i], NULL);
		}

		if (!quiet) sleep(ELAPSEDSECONDS);
		printf("\nDictionary attack - Exhausted search\n");
	}
	
	if (isbrute) {
		workerbrute *wthread = (workerbrute *) calloc(nthreads,sizeof(workerbrute));

		printf("\nBrute force attack - Starting %d threads\n",nthreads);
		printf("\nAlphabet: %s", base);
		if (strchr(base,' ') != NULL) printf(" <(including blank)>");		
		printf("\nMin length: %d", wordlength_min);
		if (swl_min == NULL) printf(" [default]");
		printf("\nMax length: %d", wordlength_max);
		if (swl_max == NULL) printf(" [default]");
		printf("\nUse -m and -M flags to modify these values.\n");
	
		for (i=0; i<nthreads; i++) {
			wthread[i].id = i;
			wthread[i].wordlength_min = wordlength_min;
			wthread[i].wordlength = wordlength_max;
			wthread[i].word = (char *) calloc(wordlength_max, sizeof(char));
			wthread[i].base = base;
			wthread[i].baselength = strlen(base);
			wthread[i].m = &mutex;
			wthread[i].file2crack = infile;
			wthread[i].quiet = quiet;
			wthread[i].count = count+i;
			thread_ret[i] = pthread_create( &thread[i], NULL, work_brute, (void*) &wthread[i]);
		}
		if (!quiet)
			pthread_create(&thread[i], NULL, print_output, (void*) count);
		for (i=0; i<nthreads_total; i++)
			pthread_join(thread[i], NULL);

		if (!quiet) sleep(ELAPSEDSECONDS);
		printf("\nBrute force attack - Exhausted search\n");
	}

	printf("\nNo password found\n\n");

	pthread_exit(NULL);
	exit(0);
}
Exemplo n.º 7
0
int
main(int argc, char **argv)
{
	int r;

	struct evhttp_uri *http_uri = NULL;
	const char *url = NULL, *data_file = NULL;
	const char *crt = "/etc/ssl/certs/ca-certificates.crt";
	const char *scheme, *host, *path, *query;
	char uri[256];
	int port;
	int retries = 0;
	int timeout = -1;

	SSL_CTX *ssl_ctx = NULL;
	SSL *ssl = NULL;
	struct bufferevent *bev;
	struct evhttp_connection *evcon = NULL;
	struct evhttp_request *req;
	struct evkeyvalq *output_headers;
	struct evbuffer *output_buffer;

	int i;
	int ret = 0;
	enum { HTTP, HTTPS } type = HTTP;

	for (i = 1; i < argc; i++) {
		if (!strcmp("-url", argv[i])) {
			if (i < argc - 1) {
				url = argv[i + 1];
			} else {
				syntax();
				goto error;
			}
		} else if (!strcmp("-crt", argv[i])) {
			if (i < argc - 1) {
				crt = argv[i + 1];
			} else {
				syntax();
				goto error;
			}
		} else if (!strcmp("-ignore-cert", argv[i])) {
			ignore_cert = 1;
		} else if (!strcmp("-data", argv[i])) {
			if (i < argc - 1) {
				data_file = argv[i + 1];
			} else {
				syntax();
				goto error;
			}
		} else if (!strcmp("-retries", argv[i])) {
			if (i < argc - 1) {
				retries = atoi(argv[i + 1]);
			} else {
				syntax();
				goto error;
			}
		} else if (!strcmp("-timeout", argv[i])) {
			if (i < argc - 1) {
				timeout = atoi(argv[i + 1]);
			} else {
				syntax();
				goto error;
			}
		} else if (!strcmp("-help", argv[i])) {
			syntax();
			goto error;
		}
	}

	if (!url) {
		syntax();
		goto error;
	}

#ifdef _WIN32
	{
		WORD wVersionRequested;
		WSADATA wsaData;
		int err;

		wVersionRequested = MAKEWORD(2, 2);

		err = WSAStartup(wVersionRequested, &wsaData);
		if (err != 0) {
			printf("WSAStartup failed with error: %d\n", err);
			goto error;
		}
	}
#endif // _WIN32

	http_uri = evhttp_uri_parse(url);
	if (http_uri == NULL) {
		err("malformed url");
		goto error;
	}

	scheme = evhttp_uri_get_scheme(http_uri);
	if (scheme == NULL || (strcasecmp(scheme, "https") != 0 &&
	                       strcasecmp(scheme, "http") != 0)) {
		err("url must be http or https");
		goto error;
	}

	host = evhttp_uri_get_host(http_uri);
	if (host == NULL) {
		err("url must have a host");
		goto error;
	}

	port = evhttp_uri_get_port(http_uri);
	if (port == -1) {
		port = (strcasecmp(scheme, "http") == 0) ? 80 : 443;
	}

	path = evhttp_uri_get_path(http_uri);
	if (strlen(path) == 0) {
		path = "/";
	}

	query = evhttp_uri_get_query(http_uri);
	if (query == NULL) {
		snprintf(uri, sizeof(uri) - 1, "%s", path);
	} else {
		snprintf(uri, sizeof(uri) - 1, "%s?%s", path, query);
	}
	uri[sizeof(uri) - 1] = '\0';

#if OPENSSL_VERSION_NUMBER < 0x10100000L
	// Initialize OpenSSL
	SSL_library_init();
	ERR_load_crypto_strings();
	SSL_load_error_strings();
	OpenSSL_add_all_algorithms();
#endif

	/* This isn't strictly necessary... OpenSSL performs RAND_poll
	 * automatically on first use of random number generator. */
	r = RAND_poll();
	if (r == 0) {
		err_openssl("RAND_poll");
		goto error;
	}

	/* Create a new OpenSSL context */
	ssl_ctx = SSL_CTX_new(SSLv23_method());
	if (!ssl_ctx) {
		err_openssl("SSL_CTX_new");
		goto error;
	}

#ifndef _WIN32
	/* TODO: Add certificate loading on Windows as well */

	/* Attempt to use the system's trusted root certificates.
	 * (This path is only valid for Debian-based systems.) */
	if (1 != SSL_CTX_load_verify_locations(ssl_ctx, crt, NULL)) {
		err_openssl("SSL_CTX_load_verify_locations");
		goto error;
	}
	/* Ask OpenSSL to verify the server certificate.  Note that this
	 * does NOT include verifying that the hostname is correct.
	 * So, by itself, this means anyone with any legitimate
	 * CA-issued certificate for any website, can impersonate any
	 * other website in the world.  This is not good.  See "The
	 * Most Dangerous Code in the World" article at
	 * https://crypto.stanford.edu/~dabo/pubs/abstracts/ssl-client-bugs.html
	 */
	SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
	/* This is how we solve the problem mentioned in the previous
	 * comment.  We "wrap" OpenSSL's validation routine in our
	 * own routine, which also validates the hostname by calling
	 * the code provided by iSECPartners.  Note that even though
	 * the "Everything You've Always Wanted to Know About
	 * Certificate Validation With OpenSSL (But Were Afraid to
	 * Ask)" paper from iSECPartners says very explicitly not to
	 * call SSL_CTX_set_cert_verify_callback (at the bottom of
	 * page 2), what we're doing here is safe because our
	 * cert_verify_callback() calls X509_verify_cert(), which is
	 * OpenSSL's built-in routine which would have been called if
	 * we hadn't set the callback.  Therefore, we're just
	 * "wrapping" OpenSSL's routine, not replacing it. */
	SSL_CTX_set_cert_verify_callback(ssl_ctx, cert_verify_callback,
					  (void *) host);
#else // _WIN32
	(void)crt;
#endif // _WIN32

	// Create event base
	base = event_base_new();
	if (!base) {
		perror("event_base_new()");
		goto error;
	}

	// Create OpenSSL bufferevent and stack evhttp on top of it
	ssl = SSL_new(ssl_ctx);
	if (ssl == NULL) {
		err_openssl("SSL_new()");
		goto error;
	}

	#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
	// Set hostname for SNI extension
	SSL_set_tlsext_host_name(ssl, host);
	#endif

	if (strcasecmp(scheme, "http") == 0) {
		bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
	} else {
		type = HTTPS;
		bev = bufferevent_openssl_socket_new(base, -1, ssl,
			BUFFEREVENT_SSL_CONNECTING,
			BEV_OPT_CLOSE_ON_FREE|BEV_OPT_DEFER_CALLBACKS);
	}

	if (bev == NULL) {
		fprintf(stderr, "bufferevent_openssl_socket_new() failed\n");
		goto error;
	}

	bufferevent_openssl_set_allow_dirty_shutdown(bev, 1);

	// For simplicity, we let DNS resolution block. Everything else should be
	// asynchronous though.
	evcon = evhttp_connection_base_bufferevent_new(base, NULL, bev,
		host, port);
	if (evcon == NULL) {
		fprintf(stderr, "evhttp_connection_base_bufferevent_new() failed\n");
		goto error;
	}

	if (retries > 0) {
		evhttp_connection_set_retries(evcon, retries);
	}
	if (timeout >= 0) {
		evhttp_connection_set_timeout(evcon, timeout);
	}

	// Fire off the request
	req = evhttp_request_new(http_request_done, bev);
	if (req == NULL) {
		fprintf(stderr, "evhttp_request_new() failed\n");
		goto error;
	}

	output_headers = evhttp_request_get_output_headers(req);
	evhttp_add_header(output_headers, "Host", host);
	evhttp_add_header(output_headers, "Connection", "close");

	if (data_file) {
		/* NOTE: In production code, you'd probably want to use
		 * evbuffer_add_file() or evbuffer_add_file_segment(), to
		 * avoid needless copying. */
		FILE * f = fopen(data_file, "rb");
		char buf[1024];
		size_t s;
		size_t bytes = 0;

		if (!f) {
			syntax();
			goto error;
		}

		output_buffer = evhttp_request_get_output_buffer(req);
		while ((s = fread(buf, 1, sizeof(buf), f)) > 0) {
			evbuffer_add(output_buffer, buf, s);
			bytes += s;
		}
		evutil_snprintf(buf, sizeof(buf)-1, "%lu", (unsigned long)bytes);
		evhttp_add_header(output_headers, "Content-Length", buf);
		fclose(f);
	}

	r = evhttp_make_request(evcon, req, data_file ? EVHTTP_REQ_POST : EVHTTP_REQ_GET, uri);
	if (r != 0) {
		fprintf(stderr, "evhttp_make_request() failed\n");
		goto error;
	}

	event_base_dispatch(base);
	goto cleanup;

error:
	ret = 1;
cleanup:
	if (evcon)
		evhttp_connection_free(evcon);
	if (http_uri)
		evhttp_uri_free(http_uri);
	event_base_free(base);

	if (ssl_ctx)
		SSL_CTX_free(ssl_ctx);
	if (type == HTTP && ssl)
		SSL_free(ssl);
#if OPENSSL_VERSION_NUMBER < 0x10100000L
	EVP_cleanup();
	ERR_free_strings();

#ifdef EVENT__HAVE_ERR_REMOVE_THREAD_STATE
	ERR_remove_thread_state(NULL);
#else
	ERR_remove_state(0);
#endif
	CRYPTO_cleanup_all_ex_data();

	sk_SSL_COMP_free(SSL_COMP_get_compression_methods());
#endif /*OPENSSL_VERSION_NUMBER < 0x10100000L */

#ifdef _WIN32
	WSACleanup();
#endif

	return ret;
}
Exemplo n.º 8
0
static int pk7_verify(X509_STORE *cert_store, PKCS7 *p7, BIO *detached, char *ebuf, int ebufsize)
{
	PKCS7_SIGNER_INFO *si;
	verify_context vctx;
	BIO *p7bio=NULL;
	char readbuf[1024*4];
	int res = 1;
	int i;
	STACK_OF(PKCS7_SIGNER_INFO) *sk;

	vctx.err = X509_V_OK;
	ebuf[0] = 0;

	OpenSSL_add_all_algorithms();

	EVP_add_digest(EVP_md5());
	EVP_add_digest(EVP_sha1());

	ERR_load_crypto_strings();

	ERR_clear_error();

	X509_VERIFY_PARAM_set_flags(cert_store->param, X509_V_FLAG_CB_ISSUER_CHECK);
	X509_STORE_set_verify_cb_func(cert_store, verify_callback);

	p7bio = PKCS7_dataInit(p7, detached);

	/* We now have to 'read' from p7bio to calculate digests etc. */
	while (BIO_read(p7bio, readbuf, sizeof(readbuf)) > 0)
		;

	/* We can now verify signatures */
	sk = PKCS7_get_signer_info(p7);
	if (sk == NULL)
	{
		/* there are no signatures on this data */
		res = 0;
		fz_strlcpy(ebuf, "No signatures", ebufsize);
		goto exit;
	}

	for (i=0; i<sk_PKCS7_SIGNER_INFO_num(sk); i++)
	{
		int rc;
		si = sk_PKCS7_SIGNER_INFO_value(sk, i);
		rc = PKCS7_dataVerify(cert_store, &vctx.x509_ctx, p7bio,p7, si);
		if (rc <= 0 || vctx.err != X509_V_OK)
		{
			char tbuf[120];

			if (rc <= 0)
			{
				fz_strlcpy(ebuf, ERR_error_string(ERR_get_error(), tbuf), ebufsize);
			}
			else
			{
				/* Error while checking the certificate chain */
				snprintf(ebuf, ebufsize, "%s(%d): %s", X509_verify_cert_error_string(vctx.err), vctx.err, vctx.certdesc);
			}

			res = 0;
			goto exit;
		}
	}

exit:
	X509_STORE_CTX_cleanup(&vctx.x509_ctx);
	ERR_free_strings();

	return res;
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL, *tbio = NULL;
    X509 *rcert = NULL;
    EVP_PKEY *rkey = NULL;
    CMS_ContentInfo *cms = NULL;
    int ret = 1;

    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    /* Read in recipient certificate and private key */
    tbio = BIO_new_file("signer.pem", "r");

    if (!tbio)
        goto err;

    rcert = PEM_read_bio_X509(tbio, NULL, 0, NULL);

    BIO_reset(tbio);

    rkey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);

    if (!rcert || !rkey)
        goto err;

    /* Open S/MIME message to decrypt */

    in = BIO_new_file("smencr.txt", "r");

    if (!in)
        goto err;

    /* Parse message */
    cms = SMIME_read_CMS(in, NULL);

    if (!cms)
        goto err;

    out = BIO_new_file("decout.txt", "w");
    if (!out)
        goto err;

    /* Decrypt S/MIME message */
    if (!CMS_decrypt(cms, rkey, rcert, NULL, out, 0))
        goto err;

    ret = 0;

 err:

    if (ret) {
        fprintf(stderr, "Error Decrypting Data\n");
        ERR_print_errors_fp(stderr);
    }

    if (cms)
        CMS_ContentInfo_free(cms);
    if (rcert)
        X509_free(rcert);
    if (rkey)
        EVP_PKEY_free(rkey);

    if (in)
        BIO_free(in);
    if (out)
        BIO_free(out);
    if (tbio)
        BIO_free(tbio);

    return ret;

}
Exemplo n.º 10
0
int main(int argc, char **argv)
	{
	BIO *in = NULL, *out = NULL, *tbio = NULL;
	X509 *scert = NULL, *scert2 = NULL;
	EVP_PKEY *skey = NULL, *skey2 = NULL;
	CMS_ContentInfo *cms = NULL;
	int ret = 1;

	OpenSSL_add_all_algorithms();
	ERR_load_crypto_strings();

	tbio = BIO_new_file("signer.pem", "r");

	if (!tbio)
		goto err;

	scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);

	BIO_reset(tbio);

	skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);

	BIO_free(tbio);

	tbio = BIO_new_file("signer2.pem", "r");

	if (!tbio)
		goto err;

	scert2 = PEM_read_bio_X509(tbio, NULL, 0, NULL);

	BIO_reset(tbio);

	skey2 = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);

	if (!scert2 || !skey2)
		goto err;

	in = BIO_new_file("sign.txt", "r");

	if (!in)
		goto err;

	cms = CMS_sign(NULL, NULL, NULL, in, CMS_STREAM|CMS_PARTIAL);

	if (!cms)
		goto err;

	/* Add each signer in turn */

	if (!CMS_add1_signer(cms, scert, skey, NULL, 0))
		goto err;

	if (!CMS_add1_signer(cms, scert2, skey2, NULL, 0))
		goto err;

	out = BIO_new_file("smout.txt", "w");
	if (!out)
		goto err;

	/* NB: content included and finalized by SMIME_write_CMS */

	if (!SMIME_write_CMS(out, cms, in, CMS_STREAM))
		goto err;

	ret = 0;

	err:

	if (ret)
		{
		fprintf(stderr, "Error Signing Data\n");
		ERR_print_errors_fp(stderr);
		}

	if (cms)
		CMS_ContentInfo_free(cms);

	if (scert)
		X509_free(scert);
	if (skey)
		EVP_PKEY_free(skey);

	if (scert2)
		X509_free(scert2);
	if (skey)
		EVP_PKEY_free(skey2);

	if (in)
		BIO_free(in);
	if (out)
		BIO_free(out);
	if (tbio)
		BIO_free(tbio);

	return ret;

	}
Exemplo n.º 11
0
static bool _backend_init(Backend *backend) {
    OpenSSL_add_all_algorithms();
    //listTokens(backend);
    return true;
}
Exemplo n.º 12
0
int main() {

  char           dest_url[] = "https://www.hp.com";
  BIO              *certbio = NULL;
  BIO               *outbio = NULL;
  X509                *cert = NULL;
  X509_NAME       *certname = NULL;
  const SSL_METHOD *method;
  SSL_CTX *ctx;
  SSL *ssl;
  int server = 0;
  int ret, i;
  EVP_PKEY *pkey = NULL;

  /* ---------------------------------------------------------- *
   * These function calls initialize openssl for correct work.  *
   * ---------------------------------------------------------- */
  OpenSSL_add_all_algorithms();
  ERR_load_BIO_strings();
  ERR_load_crypto_strings();
  SSL_load_error_strings();

  /* ---------------------------------------------------------- *
   * Create the Input/Output BIO's.                             *
   * ---------------------------------------------------------- */
  certbio = BIO_new(BIO_s_file());
  outbio  = BIO_new_fp(stdout, BIO_NOCLOSE);

  /* ---------------------------------------------------------- *
   * initialize SSL library and register algorithms             *
   * ---------------------------------------------------------- */
  if(SSL_library_init() < 0)
    BIO_printf(outbio, "Could not initialize the OpenSSL library !\n");

  /* ---------------------------------------------------------- *
   * Set SSLv2 client hello, also announce SSLv3 and TLSv1      *
   * ---------------------------------------------------------- */
  method = SSLv23_client_method();

  /* ---------------------------------------------------------- *
   * Try to create a new SSL context                            *
   * ---------------------------------------------------------- */
  if ( (ctx = SSL_CTX_new(method)) == NULL)
    BIO_printf(outbio, "Unable to create a new SSL context structure.\n");

  /* ---------------------------------------------------------- *
   * Disabling SSLv2 will leave v3 and TSLv1 for negotiation    *
   * ---------------------------------------------------------- */
  SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);

  /* ---------------------------------------------------------- *
   * Create new SSL connection state object                     *
   * ---------------------------------------------------------- */
  ssl = SSL_new(ctx);

  /* ---------------------------------------------------------- *
   * Make the underlying TCP socket connection                  *
   * ---------------------------------------------------------- */
  server = create_socket(dest_url, outbio);
  if(server != 0)
    BIO_printf(outbio, "Successfully made the TCP connection to: %s.\n", dest_url);

  /* ---------------------------------------------------------- *
   * Attach the SSL session to the socket descriptor            *
   * ---------------------------------------------------------- */
  SSL_set_fd(ssl, server);

  /* ---------------------------------------------------------- *
   * Try to SSL-connect here, returns 1 for success             *
   * ---------------------------------------------------------- */
  if ( SSL_connect(ssl) != 1 )
    BIO_printf(outbio, "Error: Could not build a SSL session to: %s.\n", dest_url);
  else
    BIO_printf(outbio, "Successfully enabled SSL/TLS session to: %s.\n", dest_url);

  /* ---------------------------------------------------------- *
   * Get the remote certificate into the X509 structure         *
   * ---------------------------------------------------------- */
  cert = SSL_get_peer_certificate(ssl);
  if (cert == NULL)
    BIO_printf(outbio, "Error: Could not get a certificate from: %s.\n", dest_url);
  else
    BIO_printf(outbio, "Retrieved the server's certificate from: %s.\n", dest_url);


if ((pkey = X509_get_pubkey(cert)) == NULL)
    BIO_printf(outbio, "Error getting public key from certificate");

if (pkey) {
    switch (pkey->type) {
      case EVP_PKEY_RSA:
        BIO_printf(outbio, "%d bit RSA Key\n\n", EVP_PKEY_bits(pkey));
        break;
      case EVP_PKEY_DSA:
        BIO_printf(outbio, "%d bit DSA Key\n\n", EVP_PKEY_bits(pkey));
        break;
      default:
        BIO_printf(outbio, "%d bit non-RSA/DSA Key\n\n", EVP_PKEY_bits(pkey));
        break;
    }
  }


  if(!PEM_write_bio_PUBKEY(outbio, pkey))
    BIO_printf(outbio, "Error writing public key data in PEM format");

  /* ---------------------------------------------------------- *
   * extract various certificate information                    *
   * -----------------------------------------------------------*/
  certname = X509_NAME_new();
  certname = X509_get_subject_name(cert);

  /* ---------------------------------------------------------- *
   * display the cert subject here                              *
   * -----------------------------------------------------------*/
  BIO_printf(outbio, "Displaying the certificate subject data:\n");
  X509_NAME_print_ex(outbio, certname, 0, 0);
  BIO_printf(outbio, "\n");

  /* ---------------------------------------------------------- *
   * Free the structures we don't need anymore                  *
   * -----------------------------------------------------------*/
  SSL_free(ssl);
  close(server);
  X509_free(cert);
  SSL_CTX_free(ctx);
  BIO_printf(outbio, "Finished SSL/TLS connection with server: %s.\n", dest_url);
  return(0);
}
Exemplo n.º 13
0
int main(int argc, char * const argv[])
{
	int err = 0, r, c, long_optind = 0;
	int action_count = 0;
	int do_initialize = 0;
	int do_import_dkek_share = 0;
	int do_create_dkek_share = 0;
	int do_wrap_key = 0;
	int do_unwrap_key = 0;
	sc_path_t path;
	sc_file_t *file = NULL;
	const char *opt_so_pin = NULL;
	const char *opt_pin = NULL;
	const char *opt_filename = NULL;
	char *opt_password = NULL;
	int opt_retry_counter = 3;
	int opt_dkek_shares = -1;
	int opt_key_reference = -1;
	int opt_password_shares_threshold = -1;
	int opt_password_shares_total = -1;
	int opt_force = 0;
	int opt_iter = 10000000;
	sc_context_param_t ctx_param;

	setbuf(stderr, NULL);
	setbuf(stdout, NULL);

	while (1) {
		c = getopt_long(argc, argv, "XC:I:W:U:s:i:fr:wv", options, &long_optind);
		if (c == -1)
			break;
		if (c == '?')
			util_print_usage_and_die(app_name, options, option_help, NULL);
		switch (c) {
		case 'X':
			do_initialize = 1;
			action_count++;
			break;
		case 'C':
			do_create_dkek_share = 1;
			opt_filename = optarg;
			action_count++;
			break;
		case 'I':
			do_import_dkek_share = 1;
			opt_filename = optarg;
			action_count++;
			break;
		case 'W':
			do_wrap_key = 1;
			opt_filename = optarg;
			action_count++;
			break;
		case 'U':
			do_unwrap_key = 1;
			opt_filename = optarg;
			action_count++;
			break;
		case OPT_PASSWORD:
			opt_password = optarg;
			break;
		case OPT_SO_PIN:
			opt_so_pin = optarg;
			break;
		case OPT_PIN:
			opt_pin = optarg;
			break;
		case OPT_RETRY:
			opt_retry_counter = atol(optarg);
			break;
		case OPT_PASSWORD_SHARES_THRESHOLD:
			opt_password_shares_threshold = atol(optarg);
			break;
		case OPT_PASSWORD_SHARES_TOTAL:
			opt_password_shares_total = atol(optarg);
			break;
		case 's':
			opt_dkek_shares = atol(optarg);
			break;
		case 'f':
			opt_force = 1;
			break;
		case 'i':
			opt_key_reference = atol(optarg);
			break;
		case 'r':
			opt_reader = optarg;
			break;
		case 'v':
			verbose++;
			break;
		case 'w':
			opt_wait = 1;
			break;
		}
	}

	CRYPTO_malloc_init();
	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();

	memset(&ctx_param, 0, sizeof(sc_context_param_t));
	ctx_param.app_name = app_name;

	r = sc_context_create(&ctx, &ctx_param);
	if (r != SC_SUCCESS) {
		fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r));
		return 1;
	}

	/* Only change if not in opensc.conf */
	if (verbose > 1 && ctx->debug == 0) {
		ctx->debug = verbose;
		sc_ctx_log_to_file(ctx, "stderr");
	}

	err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose);
	if (r != SC_SUCCESS) {
		fprintf(stderr, "Failed to connect to card: %s\n", sc_strerror(r));
		goto end;
	}

	sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0);
	r = sc_select_file(card, &path, &file);

	if (r != SC_SUCCESS) {
		fprintf(stderr, "Failed to select application: %s\n", sc_strerror(r));
		goto end;
	}

	if (do_initialize) {
		initialize(card, opt_so_pin, opt_pin, opt_retry_counter, opt_dkek_shares);
	}

	if (do_create_dkek_share) {
		create_dkek_share(card, opt_filename, opt_iter, opt_password, opt_password_shares_threshold, opt_password_shares_total);
	}

	if (do_import_dkek_share) {
		import_dkek_share(card, opt_filename, opt_iter, opt_password, opt_password_shares_total);
	}

	if (do_wrap_key) {
		wrap_key(card, opt_key_reference, opt_filename, opt_pin);
	}

	if (do_unwrap_key) {
		unwrap_key(card, opt_key_reference, opt_filename, opt_pin, opt_force);
	}

	if (action_count == 0) {
		print_info(card, file);
	}

end:
	if (card) {
		sc_unlock(card);
		sc_disconnect_card(card);
	}
	if (ctx)
		sc_release_context(ctx);

	ERR_print_errors_fp(stderr);
	return err;
}
Exemplo n.º 14
0
int main (int argc, char **argv)
{
    BIO *in = NULL, *out = NULL, *tbio = NULL, *cont = NULL;

    X509_STORE *st = NULL;

    X509 *cacert = NULL;

    CMS_ContentInfo *cms = NULL;

    int ret = 1;

    OpenSSL_add_all_algorithms ();
    ERR_load_crypto_strings ();

    /* Set up trusted CA certificate store */

    st = X509_STORE_new ();

    /* Read in CA certificate */
    tbio = BIO_new_file ("cacert.pem", "r");

    if (!tbio)
        goto err;

    cacert = PEM_read_bio_X509 (tbio, NULL, 0, NULL);

    if (!cacert)
        goto err;

    if (!X509_STORE_add_cert (st, cacert))
        goto err;

    /* Open message being verified */

    in = BIO_new_file ("smout.txt", "r");

    if (!in)
        goto err;

    /* parse message */
    cms = SMIME_read_CMS (in, &cont);

    if (!cms)
        goto err;

    /* File to output verified content to */
    out = BIO_new_file ("smver.txt", "w");
    if (!out)
        goto err;

    if (!CMS_verify (cms, NULL, st, cont, out, 0))
    {
        fprintf (stderr, "Verification Failure\n");
        goto err;
    }

    fprintf (stderr, "Verification Successful\n");

    ret = 0;

  err:

    if (ret)
    {
        fprintf (stderr, "Error Verifying Data\n");
        ERR_print_errors_fp (stderr);
    }

    if (cms)
        CMS_ContentInfo_free (cms);

    if (cacert)
        X509_free (cacert);

    if (in)
        BIO_free (in);
    if (out)
        BIO_free (out);
    if (tbio)
        BIO_free (tbio);

    return ret;

}
Exemplo n.º 15
0
void enc_key_init(int method, const char *pass)
{
    if (method <= TABLE || method >= CIPHER_NUM) {
        LOGE("enc_key_init(): Illegal method");
        return;
    }

    // Inilitialize cache
    cache_create(&iv_cache, 256, NULL);

#if defined(USE_CRYPTO_OPENSSL)
    OpenSSL_add_all_algorithms();
#endif

    uint8_t iv[MAX_IV_LENGTH];

    cipher_kt_t *cipher;
    cipher_kt_t cipher_info;

    if (method == SALSA20 || method == CHACHA20) {
        if (sodium_init() == -1) {
            FATAL("Failed to initialize sodium");
        }
        // Fake cipher
        cipher = (cipher_kt_t *)&cipher_info;
#if defined(USE_CRYPTO_OPENSSL)
        cipher->key_len = supported_ciphers_key_size[method];
        cipher->iv_len  = supported_ciphers_iv_size[method];
#endif
#if defined(USE_CRYPTO_POLARSSL)
        cipher->base       = NULL;
        cipher->key_length = supported_ciphers_key_size[method] * 8;
        cipher->iv_size    = supported_ciphers_iv_size[method];
#endif
#if defined(USE_CRYPTO_MBEDTLS)
        // XXX: key_length changed to key_bitlen in mbed TLS 2.0.0
        cipher->base       = NULL;
        cipher->key_bitlen = supported_ciphers_key_size[method] * 8;
        cipher->iv_size    = supported_ciphers_iv_size[method];
#endif
    } else {
        cipher = (cipher_kt_t *)get_cipher_type(method);
    }

    if (cipher == NULL) {
        do {
#if defined(USE_CRYPTO_POLARSSL) && defined(USE_CRYPTO_APPLECC)
            if (supported_ciphers_applecc[method] != kCCAlgorithmInvalid) {
                cipher_info.base       = NULL;
                cipher_info.key_length = supported_ciphers_key_size[method] * 8;
                cipher_info.iv_size    = supported_ciphers_iv_size[method];
                cipher                 = (cipher_kt_t *)&cipher_info;
                break;
            }
#endif
#if defined(USE_CRYPTO_MBEDTLS) && defined(USE_CRYPTO_APPLECC)
            // XXX: key_length changed to key_bitlen in mbed TLS 2.0.0
            if (supported_ciphers_applecc[method] != kCCAlgorithmInvalid) {
                cipher_info.base       = NULL;
                cipher_info.key_bitlen = supported_ciphers_key_size[method] * 8;
                cipher_info.iv_size    = supported_ciphers_iv_size[method];
                cipher                 = (cipher_kt_t *)&cipher_info;
                break;
            }
#endif
            LOGE("Cipher %s not found in crypto library",
                 supported_ciphers[method]);
            FATAL("Cannot initialize cipher");
        } while (0);
    }

    const digest_type_t *md = get_digest_type("MD5");
    if (md == NULL) {
        FATAL("MD5 Digest not found in crypto library");
    }

    enc_key_len = bytes_to_key(cipher, md, (const uint8_t *)pass, enc_key, iv);
    if (enc_key_len == 0) {
        FATAL("Cannot generate key and IV");
    }
    if (method == RC4_MD5) {
        enc_iv_len = 16;
    } else {
        enc_iv_len = cipher_iv_size(cipher);
    }
    enc_method = method;
}
Exemplo n.º 16
0
void initOpenSSL(void)
{
    OpenSSL_add_all_algorithms();
}
Exemplo n.º 17
0
void ape_ssl_init()
{
	SSL_library_init();            
	SSL_load_error_strings();
	OpenSSL_add_all_algorithms();
}
Exemplo n.º 18
0
pn_ssl_domain_t *pn_ssl_domain( pn_ssl_mode_t mode )
{
  if (!ssl_initialized) {
    ssl_initialized = 1;
    SSL_library_init();
    SSL_load_error_strings();
    OpenSSL_add_all_algorithms();
    ssl_ex_data_index = SSL_get_ex_new_index( 0, (void *) "org.apache.qpid.proton.ssl",
                                              NULL, NULL, NULL);
  }

  pn_ssl_domain_t *domain = (pn_ssl_domain_t *) calloc(1, sizeof(pn_ssl_domain_t));
  if (!domain) return NULL;

  domain->ref_count = 1;
  domain->mode = mode;

  // enable all supported protocol versions, then explicitly disable the
  // known vulnerable ones.  This should allow us to use the latest version
  // of the TLS standard that the installed library supports.
  switch(mode) {
  case PN_SSL_MODE_CLIENT:
    domain->ctx = SSL_CTX_new(SSLv23_client_method()); // and TLSv1+
    if (!domain->ctx) {
      ssl_log_error("Unable to initialize OpenSSL context.");
      free(domain);
      return NULL;
    }
    break;

  case PN_SSL_MODE_SERVER:
    domain->ctx = SSL_CTX_new(SSLv23_server_method()); // and TLSv1+
    if (!domain->ctx) {
      ssl_log_error("Unable to initialize OpenSSL context.");
      free(domain);
      return NULL;
    }
    break;

  default:
    pn_transport_logf(NULL, "Invalid value for pn_ssl_mode_t: %d", mode);
    free(domain);
    return NULL;
  }
  const long reject_insecure = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
  SSL_CTX_set_options(domain->ctx, reject_insecure);
#ifdef SSL_OP_NO_COMPRESSION
  // Mitigate the CRIME vulnerability
  SSL_CTX_set_options(domain->ctx, SSL_OP_NO_COMPRESSION);
#endif

  // by default, allow anonymous ciphers so certificates are not required 'out of the box'
  if (!SSL_CTX_set_cipher_list( domain->ctx, CIPHERS_ANONYMOUS )) {
    ssl_log_error("Failed to set cipher list to %s", CIPHERS_ANONYMOUS);
    pn_ssl_domain_free(domain);
    return NULL;
  }

  // ditto: by default do not authenticate the peer (can be done by SASL).
  if (pn_ssl_domain_set_peer_authentication( domain, PN_SSL_ANONYMOUS_PEER, NULL )) {
    pn_ssl_domain_free(domain);
    return NULL;
  }

  DH *dh = get_dh2048();
  if (dh) {
    SSL_CTX_set_tmp_dh(domain->ctx, dh);
    DH_free(dh);
    SSL_CTX_set_options(domain->ctx, SSL_OP_SINGLE_DH_USE);
  }

  return domain;
}
Exemplo n.º 19
0
SSL_CTX *setup_ssl_listen(void)
{
    const SSL_METHOD *method;

    if (sslctx)
        goto done;

    SSL_library_init();
    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();
    SSL_load_error_strings();

    /* RAND_status initializes the random number generator through a variety of
       platform-dependent methods, then returns 1 if there is enough entropy or
       0 otherwise. This seems to be a good platform-independent way of seeding
       the generator, as well as of refusing to continue without enough
       entropy. */
    if (!RAND_status())
        bye("Failed to seed OpenSSL PRNG (RAND_status returned false).");

    if (!(method = SSLv23_server_method()))
        bye("SSLv23_server_method(): %s.", ERR_error_string(ERR_get_error(), NULL));
    if (!(sslctx = SSL_CTX_new(method)))
        bye("SSL_CTX_new(): %s.", ERR_error_string(ERR_get_error(), NULL));

    SSL_CTX_set_options(sslctx, SSL_OP_ALL | SSL_OP_NO_SSLv2);

    /* Secure ciphers list taken from Nsock. */
    if (!SSL_CTX_set_cipher_list(sslctx, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"))
        bye("Unable to set OpenSSL cipher list: %s", ERR_error_string(ERR_get_error(), NULL));

    if (o.sslcert == NULL && o.sslkey == NULL) {
        X509 *cert;
        EVP_PKEY *key;
        char digest_buf[SHA1_STRING_LENGTH + 1];

        if (o.verbose)
            loguser("Generating a temporary %d-bit RSA key. Use --ssl-key and --ssl-cert to use a permanent one.\n", DEFAULT_KEY_BITS);
        if (ssl_gen_cert(&cert, &key) == 0)
            bye("ssl_gen_cert(): %s.", ERR_error_string(ERR_get_error(), NULL));
        if (o.verbose) {
            assert(ssl_cert_fp_str_sha1(cert, digest_buf, sizeof(digest_buf)) != NULL);
            loguser("SHA-1 fingerprint: %s\n", digest_buf);
        }
        if (SSL_CTX_use_certificate(sslctx, cert) != 1)
            bye("SSL_CTX_use_certificate(): %s.", ERR_error_string(ERR_get_error(), NULL));
        if (SSL_CTX_use_PrivateKey(sslctx, key) != 1)
            bye("SSL_CTX_use_PrivateKey(): %s.", ERR_error_string(ERR_get_error(), NULL));
        X509_free(cert);
        EVP_PKEY_free(key);
    } else {
        if (o.sslcert == NULL || o.sslkey == NULL)
            bye("The --ssl-key and --ssl-cert options must be used together.");
        if (SSL_CTX_use_certificate_file(sslctx, o.sslcert, SSL_FILETYPE_PEM) != 1)
            bye("SSL_CTX_use_certificate_file(): %s.", ERR_error_string(ERR_get_error(), NULL));
        if (SSL_CTX_use_PrivateKey_file(sslctx, o.sslkey, SSL_FILETYPE_PEM) != 1)
            bye("SSL_CTX_use_Privatekey_file(): %s.", ERR_error_string(ERR_get_error(), NULL));
    }

done:
    return sslctx;
}
Exemplo n.º 20
0
int
sign_repo(struct xbps_handle *xhp, const char *repodir,
	const char *privkey, const char *signedby)
{
	struct stat st;
	struct xbps_repo *repo;
	xbps_dictionary_t pkgd, meta = NULL;
	xbps_data_t data = NULL, rpubkey = NULL;
	xbps_object_iterator_t iter = NULL;
	xbps_object_t obj;
	RSA *rsa = NULL;
	unsigned char *sig;
	unsigned int siglen;
	uint16_t rpubkeysize, pubkeysize;
	const char *arch, *pkgver, *rsignedby = NULL;
	char *binpkg = NULL, *binpkg_sig = NULL, *buf = NULL, *defprivkey = NULL;
	int binpkg_fd, binpkg_sig_fd, rv = 0;
	bool flush = false;

	if (signedby == NULL) {
		fprintf(stderr, "--signedby unset! cannot sign repository\n");
		return -1;
	}

	/*
	 * Check that repository index exists and not empty, otherwise bail out.
	 */
	repo = xbps_repo_open(xhp, repodir, true);
	if (repo == NULL) {
		rv = errno;
		fprintf(stderr, "%s: cannot read repository data: %s\n",
		    _XBPS_RINDEX, strerror(errno));
		goto out;
	}
	if (xbps_dictionary_count(repo->idx) == 0) {
		fprintf(stderr, "%s: invalid repository, existing!\n", _XBPS_RINDEX);
		rv = EINVAL;
		goto out;
	}
	/*
	 * If privkey not set, default to ~/.ssh/id_rsa.
	 */
	if (privkey == NULL)
		defprivkey = xbps_xasprintf("%s/.ssh/id_rsa", getenv("HOME"));
	else
		defprivkey = strdup(privkey);

	ERR_load_crypto_strings();
	OpenSSL_add_all_algorithms();
	OpenSSL_add_all_ciphers();
	OpenSSL_add_all_digests();

	if ((rsa = load_rsa_privkey(defprivkey)) == NULL) {
		fprintf(stderr, "%s: failed to read the RSA privkey\n", _XBPS_RINDEX);
		rv = EINVAL;
		goto out;
	}
	/*
	 * Iterate over the idx dictionary and then sign all binary
	 * packages in this repository.
	 */
	iter = xbps_dictionary_iterator(repo->idx);
	assert(iter);

	while ((obj = xbps_object_iterator_next(iter))) {
		pkgd = xbps_dictionary_get_keysym(repo->idx, obj);
		xbps_dictionary_get_cstring_nocopy(pkgd, "architecture", &arch);
		xbps_dictionary_get_cstring_nocopy(pkgd, "pkgver", &pkgver);

		binpkg = xbps_xasprintf("%s/%s.%s.xbps", repodir, pkgver, arch);
		binpkg_sig = xbps_xasprintf("%s.sig", binpkg);
		/*
		 * Skip pkg if file signature exists
		 */
		if ((binpkg_sig_fd = access(binpkg_sig, R_OK)) == 0) {
			if (xhp->flags & XBPS_FLAG_VERBOSE)
				fprintf(stderr, "skipping %s, file signature found.\n", pkgver);
			free(binpkg);
			free(binpkg_sig);
			close(binpkg_sig_fd);
			continue;
		}
		/*
		 * Generate pkg file signature.
		 */
		if ((binpkg_fd = open(binpkg, O_RDONLY)) == -1) {
			fprintf(stderr, "cannot read %s: %s\n", binpkg, strerror(errno));
			free(binpkg);
			free(binpkg_sig);
			continue;
		}
		fstat(binpkg_fd, &st);
		buf = malloc(st.st_size);
		assert(buf);
		if (read(binpkg_fd, buf, st.st_size) != st.st_size) {
			fprintf(stderr, "failed to read %s: %s\n", binpkg, strerror(errno));
			close(binpkg_fd);
			free(buf);
			free(binpkg);
			free(binpkg_sig);
			continue;
		}
		close(binpkg_fd);
		if (!rsa_sign_buf(rsa, buf, st.st_size, &sig, &siglen)) {
			fprintf(stderr, "failed to sign %s: %s\n", binpkg, strerror(errno));
			free(buf);
			free(binpkg);
			free(binpkg_sig);
			continue;
		}
		free(buf);
		free(binpkg);
		/*
		 * Write pkg file signature.
		 */
		binpkg_sig_fd = creat(binpkg_sig, 0644);
		if (binpkg_sig_fd == -1) {
			fprintf(stderr, "failed to create %s: %s\n", binpkg_sig, strerror(errno));
			free(sig);
			free(binpkg_sig);
			continue;
		}
		if (write(binpkg_sig_fd, sig, siglen) != (ssize_t)siglen) {
			fprintf(stderr, "failed to write %s: %s\n", binpkg_sig, strerror(errno));
			free(sig);
			free(binpkg_sig);
			close(binpkg_sig_fd);
			continue;
		}
		free(sig);
		free(binpkg_sig);
		close(binpkg_sig_fd);
		printf("signed successfully %s\n", pkgver);
	}
	xbps_object_iterator_release(iter);
	/*
	 * Check if repository index-meta contains changes compared to its
	 * current state.
	 */
	if ((buf = pubkey_from_privkey(rsa)) == NULL) {
		rv = EINVAL;
		goto out;
	}
	meta = xbps_dictionary_create();

	data = xbps_data_create_data(buf, strlen(buf));
	rpubkey = xbps_dictionary_get(repo->idxmeta, "public-key");
	if (!xbps_data_equals(rpubkey, data))
		flush = true;

	free(buf);

	pubkeysize = RSA_size(rsa) * 8;
	xbps_dictionary_get_uint16(repo->idxmeta, "public-key-size", &rpubkeysize);
	if (rpubkeysize != pubkeysize)
		flush = true;

	xbps_dictionary_get_cstring_nocopy(repo->idxmeta, "signature-by", &rsignedby);
	if (rsignedby == NULL || strcmp(rsignedby, signedby))
		flush = true;

	if (!flush)
		goto out;

	xbps_dictionary_set(meta, "public-key", data);
	xbps_dictionary_set_uint16(meta, "public-key-size", pubkeysize);
	xbps_dictionary_set_cstring_nocopy(meta, "signature-by", signedby);
	xbps_dictionary_set_cstring_nocopy(meta, "signature-type", "rsa");
	xbps_object_release(data);
	data = NULL;

	if (!repodata_flush(xhp, repodir, repo->idx, meta)) {
		fprintf(stderr, "failed to write repodata: %s\n", strerror(errno));
		goto out;
	}
	printf("Signed repository (%u package%s)\n",
	    xbps_dictionary_count(repo->idx),
	    xbps_dictionary_count(repo->idx) == 1 ? "" : "s");

out:
	if (defprivkey) {
		free(defprivkey);
	}
	if (rsa) {
		RSA_free(rsa);
		rsa = NULL;
	}
	if (repo) {
		xbps_repo_close(repo);
	}
	return rv ? -1 : 0;
}
Exemplo n.º 21
0
Arquivo: tincd.c Projeto: Rumko/tinc
int main(int argc, char **argv) {
	program_name = argv[0];

	if(!parse_options(argc, argv))
		return 1;
	
	make_names();

	if(show_version) {
		printf("%s version %s (built %s %s, protocol %d)\n", PACKAGE,
			   VERSION, __DATE__, __TIME__, PROT_CURRENT);
		printf("Copyright (C) 1998-2010 Ivo Timmermans, Guus Sliepen and others.\n"
				"See the AUTHORS file for a complete list.\n\n"
				"tinc comes with ABSOLUTELY NO WARRANTY.  This is free software,\n"
				"and you are welcome to redistribute it under certain conditions;\n"
				"see the file COPYING for details.\n");

		return 0;
	}

	if(show_help) {
		usage(false);
		return 0;
	}

	if(kill_tincd)
		return !kill_other(kill_tincd);

	openlogger("tinc", use_logfile?LOGMODE_FILE:LOGMODE_STDERR);

	g_argv = argv;

	init_configuration(&config_tree);

	/* Slllluuuuuuurrrrp! */

	RAND_load_file("/dev/urandom", 1024);

	ENGINE_load_builtin_engines();
	ENGINE_register_all_complete();

	OpenSSL_add_all_algorithms();

	if(generate_keys) {
		read_server_config();
		return !keygen(generate_keys);
	}

	if(!read_server_config())
		return 1;

#ifdef HAVE_LZO
	if(lzo_init() != LZO_E_OK) {
		logger(LOG_ERR, "Error initializing LZO compressor!");
		return 1;
	}
#endif

#ifdef HAVE_MINGW
	if(WSAStartup(MAKEWORD(2, 2), &wsa_state)) {
		logger(LOG_ERR, "System call `%s' failed: %s", "WSAStartup", winerror(GetLastError()));
		return 1;
	}

	if(!do_detach || !init_service())
		return main2(argc, argv);
	else
		return 1;
}
Exemplo n.º 22
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;
    const EVP_CIPHER *cipher = NULL;
    int informat, outformat;
    int pubin = 0, pubout = 0, pubtext = 0, text = 0, noout = 0;
    EVP_PKEY *pkey = NULL;
    char *passin = NULL, *passout = NULL;
    int badarg = 0;
#ifndef OPENSSL_NO_ENGINE
    char *engine = NULL;
#endif
    int ret = 1;

    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, "-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, "-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 if (strcmp(*args, "-pubin") == 0) {
            pubin = 1;
            pubout = 1;
            pubtext = 1;
        } else if (strcmp(*args, "-pubout") == 0)
            pubout = 1;
        else if (strcmp(*args, "-text_pub") == 0) {
            pubtext = 1;
            text = 1;
        } else if (strcmp(*args, "-text") == 0)
            text = 1;
        else if (strcmp(*args, "-noout") == 0)
            noout = 1;
        else {
            cipher = EVP_get_cipherbyname(*args + 1);
            if (!cipher) {
                BIO_printf(bio_err, "Unknown cipher %s\n", *args + 1);
                badarg = 1;
            }
        }
        args++;
    }

    if (badarg) {
 bad:
        BIO_printf(bio_err, "Usage pkey [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");
#ifndef OPENSSL_NO_ENGINE
        BIO_printf(bio_err,
                   "-engine e       use engine e, possibly a hardware device.\n");
#endif
        return 1;
    }
#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 (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 (pubin)
        pkey = load_pubkey(bio_err, infile, informat, 1,
                           passin, e, "Public Key");
    else
        pkey = load_key(bio_err, infile, informat, 1, passin, e, "key");
    if (!pkey)
        goto end;

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

    }

    if (text) {
        if (pubtext)
            EVP_PKEY_print_public(out, pkey, 0, NULL);
        else
            EVP_PKEY_print_private(out, pkey, 0, NULL);
    }

    ret = 0;

 end:
    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.º 23
0
int main(int argc, char **argv) {
  int c = 0;
  char *ptr, *progname = *argv;
  const char *cmdopts = "hqv", *secret = NULL;

  ptr = strrchr(progname, '/');
  if (ptr != NULL) {
    progname = ptr+1;
  }

  opterr = 0;
  while ((c =
#ifdef HAVE_GETOPT_LONG
	 getopt_long(argc, argv, cmdopts, opts, NULL)
#else /* HAVE_GETOPT_LONG */
	 getopt(argc, argv, cmdopts)
#endif /* HAVE_GETOPT_LONG */
	 ) != -1) {
    switch (c) {
      case 'h':
        show_usage(progname, 0);
        break;

      case 'q':
        verbose = FALSE;
        quiet = TRUE;
        break;

      case 'v':
        quiet = FALSE;
        verbose = TRUE;
        break;

      case '?':
        fprintf(stderr, "unknown option: %c\n", (char) optopt);
        show_usage(progname, 1);
        break;
    }
  }

  auth_otp_pool = make_sub_pool(NULL);

#if OPENSSL_VERSION_NUMBER < 0x10100000L
  OPENSSL_config(NULL);
#endif /* prior to OpenSSL-1.1.x */
  ERR_load_crypto_strings();
  OpenSSL_add_all_algorithms();

  secret = generate_secret(auth_otp_pool);  
  if (secret == NULL) {
    return 1;
  }

  if (quiet) {
    fprintf(stdout, "%s\n", secret);

  } else {
    int code;

    code = generate_code(auth_otp_pool, secret, strlen(secret));
    if (code < 0) {
      fprintf(stderr, "%s: error generating verification code: %s\n", progname,
        strerror(errno));
      destroy_pool(auth_otp_pool);
      return 1;
    }

    fprintf(stdout, "-------------------------------------------------\n");
    fprintf(stdout, "Your new secret key is: %s\n\n", secret);
    fprintf(stdout, "To add this key to your SQL table, you might use:\n\n");
    fprintf(stdout, "  INSERT INTO auth_otp (secret, counter) VALUES ('%s', 0);\n\n",
      secret);
    fprintf(stdout, "Your verification code is: %06d\n", code);
    fprintf(stdout, "-------------------------------------------------\n");
  }

  ERR_free_strings();
  EVP_cleanup();
  RAND_cleanup();

  destroy_pool(auth_otp_pool);
  return 0;
}
Exemplo n.º 24
0
int main(int argc, char **argv)
{
    BIO *in = NULL, *out = NULL, *tbio = NULL;
    X509 *scert = NULL;
    EVP_PKEY *skey = NULL;
    CMS_ContentInfo *cms = NULL;
    int ret = 1;

    /*
     * For simple S/MIME signing use CMS_DETACHED. On OpenSSL 1.0.0 only: for
     * streaming detached set CMS_DETACHED|CMS_STREAM for streaming
     * non-detached set CMS_STREAM
     */
    int flags = CMS_DETACHED | CMS_STREAM;

    OpenSSL_add_all_algorithms();
    ERR_load_crypto_strings();

    /* Read in signer certificate and private key */
    tbio = BIO_new_file("signer.pem", "r");

    if (!tbio)
        goto err;

    scert = PEM_read_bio_X509(tbio, NULL, 0, NULL);

    BIO_reset(tbio);

    skey = PEM_read_bio_PrivateKey(tbio, NULL, 0, NULL);

    if (!scert || !skey)
        goto err;

    /* Open content being signed */

    in = BIO_new_file("sign.txt", "r");

    if (!in)
        goto err;

    /* Sign content */
    cms = CMS_sign(scert, skey, NULL, in, flags);

    if (!cms)
        goto err;

    out = BIO_new_file("smout.txt", "w");
    if (!out)
        goto err;

    if (!(flags & CMS_STREAM))
        BIO_reset(in);

    /* Write out S/MIME message */
    if (!SMIME_write_CMS(out, cms, in, flags))
        goto err;

    ret = 0;

 err:

    if (ret) {
        fprintf(stderr, "Error Signing Data\n");
        ERR_print_errors_fp(stderr);
    }

    if (cms)
        CMS_ContentInfo_free(cms);
    if (scert)
        X509_free(scert);
    EVP_PKEY_free(skey);

    BIO_free(in);
    BIO_free(out);
    BIO_free(tbio);

    return ret;

}
Exemplo n.º 25
0
/** Main routine for unbound-control */
int main(int argc, char* argv[])
{
	int c, ret;
	int quiet = 0;
	const char* cfgfile = CONFIGFILE;
	char* svr = NULL;
#ifdef USE_WINSOCK
	int r;
	WSADATA wsa_data;
#endif
#ifdef USE_THREAD_DEBUG
	/* stop the file output from unbound-control, overwites the servers */
	extern int check_locking_order;
	check_locking_order = 0;
#endif /* USE_THREAD_DEBUG */
	log_ident_set("unbound-control");
	log_init(NULL, 0, NULL);
	checklock_start();
#ifdef USE_WINSOCK
	if((r = WSAStartup(MAKEWORD(2,2), &wsa_data)) != 0)
		fatal_exit("WSAStartup failed: %s", wsa_strerror(r));
	/* use registry config file in preference to compiletime location */
	if(!(cfgfile=w_lookup_reg_str("Software\\Unbound", "ConfigFile")))
		cfgfile = CONFIGFILE;
#endif

	ERR_load_crypto_strings();
	ERR_load_SSL_strings();
	OpenSSL_add_all_algorithms();
	(void)SSL_library_init();

	if(!RAND_status()) {
                /* try to seed it */
                unsigned char buf[256];
                unsigned int seed=(unsigned)time(NULL) ^ (unsigned)getpid();
		unsigned int v = seed;
                size_t i;
                for(i=0; i<256/sizeof(v); i++) {
                        memmove(buf+i*sizeof(v), &v, sizeof(v));
                        v = v*seed + (unsigned int)i;
                }
                RAND_seed(buf, 256);
		log_warn("no entropy, seeding openssl PRNG with time\n");
	}

	/* parse the options */
	while( (c=getopt(argc, argv, "c:s:qh")) != -1) {
		switch(c) {
		case 'c':
			cfgfile = optarg;
			break;
		case 's':
			svr = optarg;
			break;
		case 'q':
			quiet = 1;
			break;
		case '?':
		case 'h':
		default:
			usage();
		}
	}
	argc -= optind;
	argv += optind;
	if(argc == 0)
		usage();
	if(argc >= 1 && strcmp(argv[0], "start")==0) {
		if(execlp("unbound", "unbound", "-c", cfgfile, 
			(char*)NULL) < 0) {
			fatal_exit("could not exec unbound: %s",
				strerror(errno));
		}
	}

	ret = go(cfgfile, svr, quiet, argc, argv);

#ifdef USE_WINSOCK
        WSACleanup();
#endif
	checklock_stop();
	return ret;
}
Exemplo n.º 26
0
int main(int argc, char *argv[])
{
	ENGINE *engine;
	EVP_PKEY *pkey;
	X509 *cert;
	FILE *cert_fp;

	const char *module, *efile, *certfile, *privkey;

	int ret = 0;

	if (argc < 4){
		printf("Too few arguments\n");
		usage(argv);
		return 1;
	}

	certfile = argv[1];
	privkey = argv[2];
	module = argv[3];
	efile = argv[4];

	cert_fp = fopen(certfile, "rb");
	if (!cert_fp) {
		fprintf(stderr, "%s:%d Could not open file %s\n", __FILE__, __LINE__, certfile);
		ret = 1;
		goto end;
	}

	cert = PEM_read_X509(cert_fp, NULL, NULL, NULL);
	if (!cert) {
		fprintf(stderr, "%s:%d Could not read certificate file"
		        "(must be PEM format)\n", __FILE__, __LINE__);
	}

	if (cert_fp) {
		fclose(cert_fp);
	}

	ret = CONF_modules_load_file(efile, "engines", 0);
	if (ret <= 0) {
		fprintf(stderr, "%s:%d cannot load %s\n", __FILE__, __LINE__, efile);
		display_openssl_errors(__LINE__);
		exit(1);
	}

	ENGINE_add_conf_module();
#if OPENSSL_VERSION_NUMBER>=0x10100000
	OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \
		| OPENSSL_INIT_ADD_ALL_DIGESTS \
		| OPENSSL_INIT_LOAD_CONFIG, NULL);
#else
	OpenSSL_add_all_algorithms();
	OpenSSL_add_all_digests();
	ERR_load_crypto_strings();
#endif
	ERR_clear_error();

	ENGINE_load_builtin_engines();

	engine = ENGINE_by_id("pkcs11");
	if (engine == NULL) {
		printf("%s:%d Could not get engine\n", __FILE__, __LINE__);
		display_openssl_errors(__LINE__);
		ret = 1;
		goto end;
	}

	if (!ENGINE_ctrl_cmd_string(engine, "VERBOSE", NULL, 0)) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (!ENGINE_ctrl_cmd_string(engine, "MODULE_PATH", module, 0)) {
		display_openssl_errors(__LINE__);
		exit(1);
	}

	if (!ENGINE_init(engine)) {
		printf("Could not initialize engine\n");
		display_openssl_errors(__LINE__);
		ret = 1;
		goto end;
	}

	pkey = ENGINE_load_private_key(engine, privkey, 0, 0);

	if (pkey == NULL) {
		printf("%s:%d Could not load key\n", __FILE__, __LINE__);
		display_openssl_errors(__LINE__);
		ret = 1;
		goto end;
	}



	ret = X509_check_private_key(cert, pkey);
	if (!ret) {
		printf("%s:%d Could not check private key\n", __FILE__, __LINE__);
		display_openssl_errors(__LINE__);
		ret = 1;
		goto end;
	}

	printf("Key and certificate matched\n");
	ret = 0;

	CONF_modules_unload(1);
end:
	X509_free(cert);
	EVP_PKEY_free(pkey);
	
	ENGINE_finish(engine);

	return ret;
}
Exemplo n.º 27
0
int main(int argc, char *argv[])
{
    TPM_RC		rc = 0;
    int			i;    			/* argc iterator */
    char 		*prc = NULL;		/* pointer return code */
    const char 		*inFilename = NULL;
    const char 		*outFilename = NULL;
    FILE 		*inFile = NULL;
    FILE 		*outFile = NULL;
    UINT32           	sizeInBytes;		/* hash algorithm mapped to size */
    uint32_t	  	pcrmask = 0;		/* pcr register mask */
    TPML_PCR_SELECTION	pcrs;
    unsigned int 	pcrCount = 0;
    TPMU_HA		pcr[IMPLEMENTATION_PCR];	/* all the PCRs */
    int			pr = FALSE;
    TPMT_HA 		digest;
    uint8_t		pcrBytes[IMPLEMENTATION_PCR * MAX_DIGEST_SIZE];
    UINT16		pcrLength;

    /* command line defaults */
    digest.hashAlg = TPM_ALG_SHA256;

    ERR_load_crypto_strings ();
    OpenSSL_add_all_algorithms ();

    for (i=1 ; (i<argc) && (rc == 0) ; i++) {
	if (strcmp(argv[i],"-halg") == 0) {
	    i++;
	    if (i < argc) {
		if (strcmp(argv[i],"sha256") == 0) {
		    digest.hashAlg = TPM_ALG_SHA256;
		}
		else if (strcmp(argv[i],"sha1") == 0) {
		    digest.hashAlg = TPM_ALG_SHA1;
		}
		else {
		    printf("Bad parameter for -halg\n");
		    printUsage();
		}
	    }
	    else {
		printf("Missing parameter for -hi\n");
		printUsage();
	    }
	}
	else if (strcmp(argv[i],"-bm") == 0) {
	    i++;
	    if (i < argc) {
		if (1 != sscanf(argv[i], "%x", &pcrmask)) {
		    printf("Invalid -bm argument '%s'\n", argv[i]);
		    printUsage();
		}
	    }
	    else {
		printf("-bm option needs a value\n");
		printUsage();
	    }
	}
	else if (strcmp(argv[i],"-of") == 0) {
	    i++;
	    if (i < argc) {
		outFilename = argv[i];
	    }
	    else {
		printf("-of option needs a value\n");
		printUsage();
	    }
	}
	else if (strcmp(argv[i],"-if") == 0) {
	    i++;
	    if (i < argc) {
		inFilename = argv[i];
	    }
	    else {
		printf("-if option needs a value\n");
		printUsage();
	    }
	}
	else if (strcmp(argv[i],"-pr") == 0) {
	    pr = TRUE;
	}
	else if (strcmp(argv[i],"-h") == 0) {
	    printUsage();
	}
	else if (strcmp(argv[i],"-v") == 0) {
	    verbose = TRUE;
	    TSE_SetProperty(TPM_TRACE_LEVEL, "2");
	}
	else {
	    printf("\n%s is not a valid option\n", argv[i]);
	    printUsage();
	}
    }
    if (pcrmask == 0) {
	printf("Missing handle parameter -bm\n");
	printUsage();
    }
    if (inFilename == NULL) {
	printf("Missing handle parameter -if\n");
	printUsage();
    }
    /* open the input file */
    if (rc == 0) {
	inFile = fopen(inFilename, "r");
	if (inFile == NULL) {
	    printf("Error opening %s for %s, %s\n", inFilename, "r", strerror(errno));
	    rc = EXIT_FAILURE;
	}
    }
    if (rc == 0) {
	sizeInBytes = _cpri__GetDigestSize(digest.hashAlg);
    }
    /* Table 102 - Definition of TPML_PCR_SELECTION Structure */
    if (rc == 0) {
	pcrs.count = 1;		/* hard code one hash algorithm */
	/* Table 85 - Definition of TPMS_PCR_SELECTION Structure - pcrSelections */
	pcrs.pcrSelections[0].hash = digest.hashAlg;
	pcrs.pcrSelections[0].sizeofSelect= 3;	/* hard code 24 pcrs */
	/* TCG always marshals lower PCR first */
	pcrs.pcrSelections[0].pcrSelect[0] = (pcrmask >>  0) & 0xff;
	pcrs.pcrSelections[0].pcrSelect[1] = (pcrmask >>  8) & 0xff;
	pcrs.pcrSelections[0].pcrSelect[2] = (pcrmask >> 16) & 0xff;
    }
Exemplo n.º 28
0
int 
zc_socket_ssl(zcSocket *s, char *key_file, char *cert_file, zcSSLCertRequire certreq,
        zcSSLVer ver, char *cacerts_file, bool isclient)
{
    char *errstr = NULL;
    int ret;
    //int err;
    //int sockstate;

    if (!isclient && (key_file == NULL || cert_file == NULL)) {
        ZCERROR("both key and cert files must be specified for server");
        goto zc_socket_ssl_fail;
    }

    memset(s->server, '\0', sizeof(char) * X509_NAME_MAXLEN);
    memset(s->issuer, '\0', sizeof(char) * X509_NAME_MAXLEN);

    s->peer_cert = NULL;
    s->ssl = NULL;
    s->ctx = NULL;
    //s->Socket = NULL;

    /* Init OpenSSL */
    SSL_load_error_strings();
    SSL_library_init();
    OpenSSL_add_all_algorithms();

    (void) ERR_get_state();
    ERR_clear_error();

    if ((key_file && !cert_file) || (!key_file && cert_file)) {
        errstr = "Both the key & certificate files must be specified";
        goto zc_socket_ssl_fail;
    }
    
    //SSL_load_error_strings();
    //SSLeay_add_ssl_algorithms();

    if (s->sslver == ZC_SSL_VER_TLS1)
        s->ctx = SSL_CTX_new(TLSv1_method()); /* Set up context */
    else if (ver == ZC_SSL_VER_SSL3)
        s->ctx = SSL_CTX_new(SSLv3_method()); /* Set up context */
    else if (ver == ZC_SSL_VER_SSL2)
        s->ctx = SSL_CTX_new(SSLv2_method()); /* Set up context */
    else if (ver == ZC_SSL_VER_SSL23)
        s->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */

    //s->ctx = SSL_CTX_new(SSLv23_method()); /* Set up context */
    if (s->ctx == NULL) {
        errstr = "SSL_CTX_new error";
        goto zc_socket_ssl_fail;
    }

    if (certreq != ZC_SSL_CERT_NONE) {
        if (cacerts_file == NULL) {
            errstr = "No root certificates specified for verification of other-side certificates.";
            goto zc_socket_ssl_fail;
        } else {
            ret = SSL_CTX_load_verify_locations(s->ctx, cacerts_file, NULL);
            if (ret != 1) {
                //_setSSLError(NULL, 0, __FILE__, __LINE__);
                ZCERROR("load verify locations error: %d", ret);
                goto zc_socket_ssl_fail;
            }
        }
    }


    if (key_file) {
        ret = SSL_CTX_use_PrivateKey_file(s->ctx, key_file,
                                          SSL_FILETYPE_PEM);
        if (ret != 1) {
            //_setSSLError(NULL, ret, __FILE__, __LINE__);
            ZCERROR("use privatekey file error:%d", ret);
            goto zc_socket_ssl_fail;
        }

        ret = SSL_CTX_use_certificate_chain_file(s->ctx, cert_file);
        if (ret != 1) {
            /*
            fprintf(stderr, "ret is %d, errcode is %lu, %lu, with file \"%s\"\n",
                ret, ERR_peek_error(), ERR_peek_last_error(), cert_file);
                */
            if (ERR_peek_last_error() != 0) {
                //_setSSLError(NULL, ret, __FILE__, __LINE__);
                ZCERROR("peek last error failed:%d", ret);
                goto zc_socket_ssl_fail;
            }
        }
    }


    /* ssl compatibility */
    SSL_CTX_set_options(s->ctx, SSL_OP_ALL);

    int verification_mode = SSL_VERIFY_NONE;
    if (certreq == ZC_SSL_CERT_OPTIONAL)
        verification_mode = SSL_VERIFY_PEER;
    else if (certreq == ZC_SSL_CERT_REQUIRED)
        verification_mode = (SSL_VERIFY_PEER |
                             SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
    SSL_CTX_set_verify(s->ctx, verification_mode, NULL); /* set verify lvl */

    
    s->ssl = SSL_new(s->ctx); /* New ssl struct */
    SSL_set_fd(s->ssl, s->fd);       /* Set the socket for SSL */
#ifdef SSL_MODE_AUTO_RETRY
    SSL_set_mode(s->ssl, SSL_MODE_AUTO_RETRY);
#endif

    /* If the socket is in non-blocking mode or timeout mode, set the BIO
     * to non-blocking mode (blocking is the default)
     */
    if (!s->blocked) {
        /* Set both the read and write BIO's to non-blocking mode */
        BIO_set_nbio(SSL_get_rbio(s->ssl), 1);
        BIO_set_nbio(SSL_get_wbio(s->ssl), 1);
    }

    if (isclient) {
        SSL_set_connect_state(s->ssl);
    }else{
        SSL_set_accept_state(s->ssl);
    }
    
    if (isclient) {
        ret = zc_socket_ssl_handshake(s);
        if (ret != ZC_OK) {
            ZCERROR("ssl handshake error: %d", ret);
            goto zc_socket_ssl_fail;
        }
    }
    return ZC_OK;

zc_socket_ssl_fail:
    if (errstr) {
        ZCERROR("ssl error: %s\n", errstr);
    }

    return -1;
}
Exemplo n.º 29
0
int
main(const int argc, char **argv)
{
    int                 n_listeners, i, clnt_length, clnt;
    struct pollfd       *polls;
    LISTENER            *lstn;
    pthread_t           thr;
    pthread_attr_t      attr;
    struct sched_param  sp;
    uid_t               user_id;
    gid_t               group_id;
    FILE                *fpid;
    struct sockaddr_storage clnt_addr;
    char                tmp[MAXBUF];
#ifndef SOL_TCP
    struct protoent     *pe;
#endif

    print_log = 0;
    (void)umask(077);
    control_sock = -1;
    log_facility = -1;
    logmsg(LOG_NOTICE, "starting...");

    signal(SIGHUP, h_shut);
    signal(SIGINT, h_shut);
    signal(SIGTERM, h_term);
    signal(SIGQUIT, h_term);
    signal(SIGPIPE, SIG_IGN);

    srandom(getpid());

    /* SSL stuff */
    SSL_load_error_strings();
    SSL_library_init();
    OpenSSL_add_all_algorithms();
    l_init();
    init_thr_arg();
    CRYPTO_set_id_callback(l_id);
    CRYPTO_set_locking_callback(l_lock);
    init_timer();

    /* prepare regular expressions */
    if(regcomp(&HEADER, "^([a-z0-9!#$%&'*+.^_`|~-]+):[ \t]*(.*)[ \t]*$", REG_ICASE | REG_NEWLINE | REG_EXTENDED)
    || regcomp(&CHUNK_HEAD, "^([0-9a-f]+).*$", REG_ICASE | REG_NEWLINE | REG_EXTENDED)
    || regcomp(&RESP_SKIP, "^HTTP/1.1 100.*$", REG_ICASE | REG_NEWLINE | REG_EXTENDED)
    || regcomp(&RESP_IGN, "^HTTP/1.[01] (10[1-9]|1[1-9][0-9]|204|30[456]).*$", REG_ICASE | REG_NEWLINE | REG_EXTENDED)
    || regcomp(&LOCATION, "(http|https)://([^/]+)(.*)", REG_ICASE | REG_NEWLINE | REG_EXTENDED)
    || regcomp(&AUTHORIZATION, "Authorization:[ \t]*Basic[ \t]*\"?([^ \t]*)\"?[ \t]*", REG_ICASE | REG_NEWLINE | REG_EXTENDED)
    ) {
        logmsg(LOG_ERR, "bad essential Regex - aborted");
        exit(1);
    }

#ifndef SOL_TCP
    /* for systems without the definition */
    if((pe = getprotobyname("tcp")) == NULL) {
        logmsg(LOG_ERR, "missing TCP protocol");
        exit(1);
    }
    SOL_TCP = pe->p_proto;
#endif

    /* read config */
    config_parse(argc, argv);

    if(log_facility != -1)
        openlog("pound", LOG_CONS | LOG_NDELAY, LOG_DAEMON);
    if(ctrl_name != NULL) {
        struct sockaddr_un  ctrl;

        memset(&ctrl, 0, sizeof(ctrl));
        ctrl.sun_family = AF_UNIX;
        strncpy(ctrl.sun_path, ctrl_name, sizeof(ctrl.sun_path) - 1);
        (void)unlink(ctrl.sun_path);
        if((control_sock = socket(PF_UNIX, SOCK_STREAM, 0)) < 0) {
            logmsg(LOG_ERR, "Control \"%s\" create: %s", ctrl.sun_path, strerror(errno));
            exit(1);
        }
        if(bind(control_sock, (struct sockaddr *)&ctrl, (socklen_t)sizeof(ctrl)) < 0) {
            logmsg(LOG_ERR, "Control \"%s\" bind: %s", ctrl.sun_path, strerror(errno));
            exit(1);
        }
        listen(control_sock, 512);
    }

    /* open listeners */
    for(lstn = listeners, n_listeners = 0; lstn; lstn = lstn->next, n_listeners++) {
        int opt;

        /* prepare the socket */
        if((lstn->sock = socket(lstn->addr.ai_family == AF_INET? PF_INET: PF_INET6, SOCK_STREAM, 0)) < 0) {
            addr2str(tmp, MAXBUF - 1, &lstn->addr, 0);
            logmsg(LOG_ERR, "HTTP socket %s create: %s - aborted", tmp, strerror(errno));
            exit(1);
        }
        opt = 1;
        setsockopt(lstn->sock, SOL_SOCKET, SO_REUSEADDR, (void *)&opt, sizeof(opt));
        if(bind(lstn->sock, lstn->addr.ai_addr, (socklen_t)lstn->addr.ai_addrlen) < 0) {
            addr2str(tmp, MAXBUF - 1, &lstn->addr, 0);
            logmsg(LOG_ERR, "HTTP socket bind %s: %s - aborted", tmp, strerror(errno));
            exit(1);
        }
        listen(lstn->sock, 512);
    }

    /* alloc the poll structures */
    if((polls = (struct pollfd *)calloc(n_listeners, sizeof(struct pollfd))) == NULL) {
        logmsg(LOG_ERR, "Out of memory for poll - aborted");
        exit(1);
    }
    for(lstn = listeners, i = 0; lstn; lstn = lstn->next, i++)
        polls[i].fd = lstn->sock;

    /* set uid if necessary */
    if(user) {
        struct passwd   *pw;

        if((pw = getpwnam(user)) == NULL) {
            logmsg(LOG_ERR, "no such user %s - aborted", user);
            exit(1);
        }
        user_id = pw->pw_uid;
    }

    /* set gid if necessary */
    if(group) {
        struct group    *gr;

        if((gr = getgrnam(group)) == NULL) {
            logmsg(LOG_ERR, "no such group %s - aborted", group);
            exit(1);
        }
        group_id = gr->gr_gid;
    }

    /* Turn off verbose messages (if necessary) */
    print_log = 0;

    if(daemonize) {
        /* daemonize - make ourselves a subprocess. */
        switch (fork()) {
            case 0:
                if(log_facility != -1) {
                    close(0);
                    close(1);
                    close(2);
                }
                break;
            case -1:
                logmsg(LOG_ERR, "fork: %s - aborted", strerror(errno));
                exit(1);
            default:
                exit(0);
        }
#ifdef  HAVE_SETSID
        (void) setsid();
#endif
    }

    /* record pid in file */
    if((fpid = fopen(pid_name, "wt")) != NULL) {
        fprintf(fpid, "%d\n", getpid());
        fclose(fpid);
    } else
        logmsg(LOG_NOTICE, "Create \"%s\": %s", pid_name, strerror(errno));

    /* chroot if necessary */
    if(root_jail) {
        if(chroot(root_jail)) {
            logmsg(LOG_ERR, "chroot: %s - aborted", strerror(errno));
            exit(1);
        }
        if(chdir("/")) {
            logmsg(LOG_ERR, "chroot/chdir: %s - aborted", strerror(errno));
            exit(1);
        }
    }

    if(group)
        if(setgid(group_id) || setegid(group_id)) {
            logmsg(LOG_ERR, "setgid: %s - aborted", strerror(errno));
            exit(1);
        }
    if(user)
        if(setuid(user_id) || seteuid(user_id)) {
            logmsg(LOG_ERR, "setuid: %s - aborted", strerror(errno));
            exit(1);
        }

    /* split off into monitor and working process if necessary */
    for(;;) {
#ifdef  UPER
        if((son = fork()) > 0) {
            int status;

            (void)wait(&status);
            if(WIFEXITED(status))
                logmsg(LOG_ERR, "MONITOR: worker exited normally %d, restarting...", WEXITSTATUS(status));
            else if(WIFSIGNALED(status))
                logmsg(LOG_ERR, "MONITOR: worker exited on signal %d, restarting...", WTERMSIG(status));
            else
                logmsg(LOG_ERR, "MONITOR: worker exited (stopped?) %d, restarting...", status);
        } else if (son == 0) {
#endif

            /* thread stuff */
            pthread_attr_init(&attr);
            pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

#ifdef  NEED_STACK
            /* set new stack size - necessary for OpenBSD/FreeBSD and Linux NPTL */
            if(pthread_attr_setstacksize(&attr, 1 << 18)) {
                logmsg(LOG_ERR, "can't set stack size - aborted");
                exit(1);
            }
#endif
            /* start timer */
            if(pthread_create(&thr, &attr, thr_timer, NULL)) {
                logmsg(LOG_ERR, "create thr_resurect: %s - aborted", strerror(errno));
                exit(1);
            }

            /* start the controlling thread (if needed) */
            if(control_sock >= 0 && pthread_create(&thr, &attr, thr_control, NULL)) {
                logmsg(LOG_ERR, "create thr_control: %s - aborted", strerror(errno));
                exit(1);
            }

            /* pause to make sure the service threads were started */
            sleep(1);

            /* create the worker threads */
            for(i = 0; i < numthreads; i++)
                if(pthread_create(&thr, &attr, thr_http, NULL)) {
                    logmsg(LOG_ERR, "create thr_http: %s - aborted", strerror(errno));
                    exit(1);
                }

            /* pause to make sure at least some of the worker threads were started */
            sleep(1);

            /* and start working */
            for(;;) {
                if(shut_down) {
                    logmsg(LOG_NOTICE, "shutting down...");
                    for(lstn = listeners; lstn; lstn = lstn->next)
                        close(lstn->sock);
                    if(grace > 0) {
                        sleep(grace);
                        logmsg(LOG_NOTICE, "grace period expired - exiting...");
                    }
                    if(ctrl_name != NULL)
                        (void)unlink(ctrl_name);
                    exit(0);
                }
                for(lstn = listeners, i = 0; i < n_listeners; lstn = lstn->next, i++) {
                    polls[i].events = POLLIN | POLLPRI;
                    polls[i].revents = 0;
                }
                if(poll(polls, n_listeners, -1) < 0) {
                    logmsg(LOG_WARNING, "poll: %s", strerror(errno));
                } else {
                    for(lstn = listeners, i = 0; lstn; lstn = lstn->next, i++) {
                        if(polls[i].revents & (POLLIN | POLLPRI)) {
                            memset(&clnt_addr, 0, sizeof(clnt_addr));
                            clnt_length = sizeof(clnt_addr);
                            if((clnt = accept(lstn->sock, (struct sockaddr *)&clnt_addr,
                                (socklen_t *)&clnt_length)) < 0) {
                                logmsg(LOG_WARNING, "HTTP accept: %s", strerror(errno));
                            } else if(((struct sockaddr_in *)&clnt_addr)->sin_family == AF_INET
                                   || ((struct sockaddr_in *)&clnt_addr)->sin_family == AF_INET6) {
                                thr_arg arg;

                                if(lstn->disabled) {
                                    /*
                                    addr2str(tmp, MAXBUF - 1, &clnt_addr, 1);
                                    logmsg(LOG_WARNING, "HTTP disabled listener from %s", tmp);
                                    */
                                    close(clnt);
                                }
                                arg.sock = clnt;
                                arg.lstn = lstn;
                                if((arg.from_host.ai_addr = (struct sockaddr *)malloc(clnt_length)) == NULL) {
                                    logmsg(LOG_WARNING, "HTTP arg address: malloc");
                                    close(clnt);
                                    continue;
                                }
                                memcpy(arg.from_host.ai_addr, &clnt_addr, clnt_length);
                                arg.from_host.ai_addrlen = clnt_length;
                                if(((struct sockaddr_in *)&clnt_addr)->sin_family == AF_INET)
                                    arg.from_host.ai_family = AF_INET;
                                else
                                    arg.from_host.ai_family = AF_INET6;
                                if(put_thr_arg(&arg))
                                    close(clnt);
                            } else {
                                /* may happen on FreeBSD, I am told */
                                logmsg(LOG_WARNING, "HTTP connection prematurely closed by peer");
                                close(clnt);
                            }
                        }
                    }
                }
            }
#ifdef  UPER
        } else {
            /* failed to spawn son */
            logmsg(LOG_ERR, "Can't fork worker (%s) - aborted", strerror(errno));
            exit(1);
        }
#endif
    }
}
Exemplo n.º 30
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;
	}