コード例 #1
0
ファイル: t-kdf.c プロジェクト: 0ndorio/libgcrypt
int
main (int argc, char **argv)
{
  int last_argc = -1;
  unsigned long s2kcount = 0;

  if (argc)
    { argc--; argv++; }

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          fputs ("usage: t-kdf [options]"
                 "Options:\n"
                 " --verbose    print timinigs etc.\n"
                 " --debug      flyswatter\n"
                 " --s2k        print the time needed for S2K\n",
                 stdout);
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          verbose += 2;
          debug++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--s2k"))
        {
          s2kcount = 1;
          argc--; argv++;
        }
      else if (!strncmp (*argv, "--", 2))
        die ("unknown option '%s'\n", *argv);
    }

  if (s2kcount)
    {
      if (argc != 1)
        die ("usage: t-kdf --s2k S2KCOUNT\n", stderr );
      s2kcount = strtoul (*argv, NULL, 10);
      if (!s2kcount)
        die ("t-kdf: S2KCOUNT must be positive\n", stderr );
    }

  if (!gcry_check_version (GCRYPT_VERSION))
    die ("version mismatch\n");

  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  if (debug)
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);

  if (s2kcount)
    bench_s2k (s2kcount);
  else
    {
      check_openpgp ();
      check_pbkdf2 ();
      check_scrypt ();
    }

  return error_count ? 1 : 0;
}
コード例 #2
0
/* setup a temporary transfer test file */
int
main (int argc, char *const *argv)
{
  unsigned int errorCount = 0;

  int daemon_flags =
    MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL | MHD_USE_DEBUG;
  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
  if (curl_check_version (MHD_REQ_CURL_VERSION))
    {
      return 0;
    }

  if (0 != curl_global_init (CURL_GLOBAL_ALL))
    {
      fprintf (stderr, "Error: %s\n", strerror (errno));
      return 0; 
    }

  char *aes128_sha = "AES128-SHA";
  char *aes256_sha = "AES256-SHA";
  if (curl_uses_nss_ssl() == 0)
    {
      aes128_sha = "rsa_aes_128_sha";
      aes256_sha = "rsa_aes_256_sha";
    }


  errorCount +=
    test_wrap ("TLS1.0-AES-SHA1",
	       &test_https_transfer, NULL, daemon_flags,
	       aes128_sha,
	       CURL_SSLVERSION_TLSv1,
	       MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
	       MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
	       MHD_OPTION_HTTPS_PRIORITIES, "NONE:+VERS-TLS1.0:+AES-128-CBC:+SHA1:+RSA:+COMP-NULL",
	       MHD_OPTION_END);
  errorCount +=
    test_wrap ("TLS1.0-AES-SHA1",
	       &test_https_transfer, NULL, daemon_flags,
	       aes128_sha,
	       CURL_SSLVERSION_SSLv3,
	       MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
	       MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
	       MHD_OPTION_HTTPS_PRIORITIES, "NONE:+VERS-SSL3.0:+AES-128-CBC:+SHA1:+RSA:+COMP-NULL",
	       MHD_OPTION_END);

  errorCount +=
    test_wrap ("SSL3.0-AES-SHA1",
	       &test_https_transfer, NULL, daemon_flags,
	       aes128_sha,
	       CURL_SSLVERSION_SSLv3,
	       MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
	       MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
	       MHD_OPTION_HTTPS_PRIORITIES, "NONE:+VERS-SSL3.0:+AES-128-CBC:+SHA1:+RSA:+COMP-NULL",
	       MHD_OPTION_END);
#if 0
  /* manual inspection of the handshake suggests that CURL will
     request TLSv1, we send back "SSL3" and CURL takes it *despite*
     being configured to speak SSL3-only.  Notably, the other way
     round (have curl request SSL3, respond with TLSv1 only)
     is properly refused by CURL.  Either way, this does NOT seem
     to be a bug in MHD/gnuTLS but rather in CURL; hence this
     test is commented out here... */
  errorCount +=
    test_wrap ("unmatching version: SSL3 vs. TLS", &test_unmatching_ssl_version,
               NULL, daemon_flags, "AES256-SHA", CURL_SSLVERSION_TLSv1,
               MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
               MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
               MHD_OPTION_CIPHER_ALGORITHM, "SSL3", MHD_OPTION_END);
#endif

  errorCount +=
    test_wrap ("TLS1.0 vs SSL3",
	       &test_unmatching_ssl_version, NULL, daemon_flags,
	       aes256_sha,
	       CURL_SSLVERSION_SSLv3,
	       MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
	       MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
	       MHD_OPTION_HTTPS_PRIORITIES, "NONE:+VERS-TLS1.0:+AES-256-CBC:+SHA1:+RSA:+COMP-NULL",
	       MHD_OPTION_END);
  curl_global_cleanup ();

  return errorCount != 0;
}
コード例 #3
0
ファイル: main.c プロジェクト: gdudek/pianobar
int main (int argc, char **argv) {
	static BarApp_t app;

	memset (&app, 0, sizeof (app));

	/* save terminal attributes, before disabling echoing */
	BarTermInit ();

	/* signals */
	signal (SIGPIPE, SIG_IGN);

	/* init some things */
	gcry_check_version (NULL);
	gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
	gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
	BarPlayerInit ();

	BarSettingsInit (&app.settings);
	BarSettingsRead (&app.settings);

	PianoReturn_t pret;
	if ((pret = PianoInit (&app.ph, app.settings.partnerUser,
			app.settings.partnerPassword, app.settings.device,
			app.settings.inkey, app.settings.outkey)) != PIANO_RET_OK) {
		BarUiMsg (&app.settings, MSG_ERR, "Initialization failed:"
				" %s\n", PianoErrorToStr (pret));
		return 0;
	}

	BarUiMsg (&app.settings, MSG_NONE,
			"Welcome to " PACKAGE " (" VERSION ")! ");
	if (app.settings.keys[BAR_KS_HELP] == BAR_KS_DISABLED) {
		BarUiMsg (&app.settings, MSG_NONE, "\n");
	} else {
		BarUiMsg (&app.settings, MSG_NONE,
				"Press %c for a list of commands.\n",
				app.settings.keys[BAR_KS_HELP]);
	}

	curl_global_init (CURL_GLOBAL_DEFAULT);
	app.http = curl_easy_init ();
	assert (app.http != NULL);

	/* init fds */
	FD_ZERO(&app.input.set);

        int fifo_uses_this_fd = 0;
	app.input.fds[0] = STDIN_FILENO;
        if (isatty(fileno(stdin))) {
	    fifo_uses_this_fd = 1;
	    FD_SET(app.input.fds[0], &app.input.set);
            }

	/* open fifo read/write so it won't EOF if nobody writes to it */
	assert (sizeof (app.input.fds) / sizeof (*app.input.fds) >= 2);
	app.input.fds[fifo_uses_this_fd] = open (app.settings.fifo, O_RDWR);
	if (app.input.fds[fifo_uses_this_fd] != -1) {
		struct stat s;

		/* check for file type, must be fifo */
		fstat (app.input.fds[fifo_uses_this_fd], &s);
		if (!S_ISFIFO (s.st_mode)) {
			BarUiMsg (&app.settings, MSG_ERR, "File at %s is not a fifo\n", app.settings.fifo);
			close (app.input.fds[fifo_uses_this_fd]);
			app.input.fds[fifo_uses_this_fd] = -1;
		} else {
			FD_SET(app.input.fds[fifo_uses_this_fd], &app.input.set);
			BarUiMsg (&app.settings, MSG_INFO, "Control fifo at %s opened\n",
					app.settings.fifo);
		}
	}
        app.input.maxfd = app.input.fds[0];
        if (fifo_uses_this_fd>0)
		app.input.maxfd = app.input.fds[0] > app.input.fds[1] ? app.input.fds[0] : app.input.fds[1];
	++app.input.maxfd;

	BarMainLoop (&app);

	if (app.input.fds[fifo_uses_this_fd] != -1) {
		close (app.input.fds[fifo_uses_this_fd]);
	}

	/* write statefile */
	BarSettingsWrite (app.curStation, &app.settings);

	PianoDestroy (&app.ph);
	PianoDestroyPlaylist (app.songHistory);
	PianoDestroyPlaylist (app.playlist);
	curl_easy_cleanup (app.http);
	curl_global_cleanup ();
	BarPlayerDestroy ();
	BarSettingsDestroy (&app.settings);

	/* restore terminal attributes, zsh doesn't need this, bash does... */
	BarTermRestore ();

	return 0;
}
コード例 #4
0
ファイル: md.c プロジェクト: IFGHou/AIDE
int init_md(struct md_container* md) {
  
  int i;
  /*    First we check the parameter..   */
#ifdef _PARAMETER_CHECK_
  if (md==NULL) {
    return RETFAIL;  
  }
#endif
  error(255,"init_md called\n");
  /*
    We don't have calculator for this yet :)
  */
  md->calc_attr=0;
#ifdef WITH_MHASH
  error(255,"Mhash library initialization\n");
  for(i=0;i<=HASH_MHASH_COUNT;i++) {
    if (((hash_mhash2attr(i)&HASH_USE_MHASH)&md->todo_attr)!=0) {
      DB_ATTR_TYPE h=hash_mhash2attr(i);
      error(255,"inserting %llu\n",h);
      md->mhash_mdh[i]=mhash_init(i);
      if (md->mhash_mdh[i]!=MHASH_FAILED) {
				md->calc_attr|=h;
      } else {
	/*
	  Oops.. 
	  We just don't calculate this.
	 */

				md->todo_attr&=~h;
      }

    } else {
      md->mhash_mdh[i]=MHASH_FAILED;      
    }
  }
#endif 
#ifdef WITH_GCRYPT
  error(255,"Gcrypt library initialization\n");
  	if(!gcry_check_version(GCRYPT_VERSION)) {
		error(0,"libgcrypt version mismatch\n");
		exit(VERSION_MISMATCH_ERROR);
	}
	gcry_control(GCRYCTL_DISABLE_SECMEM, 0);
	gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
	if(gcry_md_open(&md->mdh,0,0)!=GPG_ERR_NO_ERROR){
		error(0,"gcrypt_md_open failed\n");
		exit(IO_ERROR);
	}
  for(i=0;i<=HASH_GCRYPT_COUNT;i++) {
    if (((hash_gcrypt2attr(i)&HASH_USE_GCRYPT)&md->todo_attr)!=0) {
      DB_ATTR_TYPE h=hash_gcrypt2attr(i);
      error(255,"inserting %llu\n",h);
			if(gcry_md_enable(md->mdh,i)==GPG_ERR_NO_ERROR){
				md->calc_attr|=h;
			} else {
				error(0,"gcry_md_enable %i failed",i);
				md->todo_attr&=~h;
			}
		}
	}
#endif
  return RETOK;
}
コード例 #5
0
ファイル: skclist.c プロジェクト: GroovIM/transport
/* Return true if Libgcrypt's RNG is in faked mode.  */
int
random_is_faked (void)
{
  return !!gcry_control ( GCRYCTL_FAKED_RANDOM_P, 0);
}
コード例 #6
0
int
main (int argc, char *const *argv)
{
  int i, errorCount = 0;
  FILE *test_fd;
  struct MHD_Daemon *d;
  gnutls_session_t session;
  gnutls_datum_t key;
  gnutls_datum_t cert;
  gnutls_certificate_credentials_t xcred;

  const int ext_arr[] = {
    GNUTLS_EXTENSION_SERVER_NAME,
    -1
  };

  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
#ifdef GCRYCTL_INITIALIZATION_FINISHED
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
#endif
  MHD_gtls_global_set_log_level (11);

  if ((test_fd = setup_test_file ()) == NULL)
    {
      fprintf (stderr, MHD_E_TEST_FILE_CREAT);
      return -1;
    }

  if (0 != curl_global_init (CURL_GLOBAL_ALL))
    {
      fprintf (stderr, "Error: %s\n", strerror (errno));
      return -1;
    }

  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_SSL |
                        MHD_USE_DEBUG, DEAMON_TEST_PORT,
                        NULL, NULL, &http_ahc, NULL,
                        MHD_OPTION_HTTPS_MEM_KEY, srv_key_pem,
                        MHD_OPTION_HTTPS_MEM_CERT, srv_self_signed_cert_pem,
                        MHD_OPTION_END);

  if (d == NULL)
    {
      fprintf (stderr, "%s\n", MHD_E_SERVER_INIT);
      return -1;
    }

  i = 0;
  setup_session (&session, &key, &cert, &xcred);
  errorCount += test_hello_extension (session, ext_arr[i], 1, 16);
  teardown_session (session, &key, &cert, xcred);
#if 1
  i = 0;
  while (ext_arr[i] != -1)
    {
      setup_session (&session, &key, &cert, &xcred);
      errorCount += test_hello_extension (session, ext_arr[i], 1, 16);
      teardown_session (session, &key, &cert, xcred);

      setup_session (&session, &key, &cert, &xcred);
      errorCount += test_hello_extension (session, ext_arr[i], 3, 8);
      teardown_session (session, &key, &cert, xcred);

      /* this test specifically tests the issue raised in CVE-2008-1948 */
      setup_session (&session, &key, &cert, &xcred);
      errorCount += test_hello_extension (session, ext_arr[i], 6, 0);
      teardown_session (session, &key, &cert, xcred);
      i++;
    }
#endif

  print_test_result (errorCount, argv[0]);

  MHD_stop_daemon (d);

  curl_global_cleanup ();
  fclose (test_fd);

  return errorCount;
}
コード例 #7
0
ファイル: t-sexp.c プロジェクト: hu19891110/libgcrypt
int
main (int argc, char **argv)
{
  int last_argc = -1;

  if (argc)
    {
      argc--; argv++;
    }
  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          puts (
"usage: " PGMNAME " [options]\n"
"\n"
"Options:\n"
"  --verbose      Show what is going on\n"
"  --debug        Flyswatter\n"
);
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          verbose = debug = 1;
          argc--; argv++;
        }
      else if (!strncmp (*argv, "--", 2))
        die ("unknown option '%s'", *argv);
    }

  if (debug)
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);
  gcry_control (GCRYCTL_DISABLE_SECMEM_WARN);
  gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
  if (!gcry_check_version (GCRYPT_VERSION))
    die ("version mismatch");
  /* #include "../src/gcrypt-int.h" indicates that internal interfaces
     may be used; thus better do an exact version check. */
  if (strcmp (gcry_check_version (NULL), GCRYPT_VERSION))
    die ("exact version match failed");
  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);

  basic ();
  canon_len ();
  back_and_forth ();
  check_sscan ();
  check_extract_param ();
  bug_1594 ();

  return errorcount? 1:0;
}
コード例 #8
0
ファイル: ssh.c プロジェクト: cianmcgovern/remote-notify-base
int execute_command(struct remote *rm)
{

    /* Sets up the pthread functionality of gcrypt
     * libssh2 doesn't do this for us so we have to do it ourselves*/
    gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);

    openlog("remote-monitor-base",LOG_PID|LOG_CONS,LOG_USER);

    syslog(LOG_DEBUG,"Starting SSH execution on rm->hostname: %s with rm->username: %s and port: %d",rm->hostname,rm->username,rm->port);

    size_t len;
    int type;

    unsigned long hostaddress;
    int sock;
    const char *fingerprint;
    int bytecount = 0;

    struct sockaddr_in sin;

    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel;
    LIBSSH2_KNOWNHOSTS *nh;

    /* results stores the output from the commands after they're executed
     * Each command  has a corresponding result so the results array is set to the same length as the commands array  */
    rm->results = malloc(rm->num_commands * sizeof(char*));
    for(int i = 0; i < rm->num_commands; i++)
        rm->results[i] = malloc(2048 * sizeof(char));

    /* Initialise libssh2 and check to see if it was initialized properly
     * libssh2_init isn't thread safe so we need to lock the thread while it executes*/
    pthread_mutex_lock(&sshinit_lock);
    int rc = libssh2_init(0);
    pthread_mutex_unlock(&sshinit_lock);
    if(rc!=0) {
        syslog(LOG_ERR,"libssh2 initilization failed");
        return 1;
    }

    /* Creates a socket connection to the specified host on the specified port */
    hostaddress = inet_addr(rm->hostname);
    sock = socket(AF_INET, SOCK_STREAM, 0);
    sin.sin_family = AF_INET;
    sin.sin_port = htons(rm->port);
    sin.sin_addr.s_addr = hostaddress;

    /* Check to see if the connection was successful */
    if(connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in)) != 0) {
        syslog(LOG_ERR,"Failed to connect to %s on port %d", rm->hostname, rm->port);
        return 1;
    }

    /* Initialise the session and check for success */
    session = libssh2_session_init();
    if(!session) {
        syslog(LOG_ERR,"Error creating session on host %s", rm->hostname);
        return 1;
    }

    /* Disable blocking for this session */
    libssh2_session_set_blocking(session,0);

    /* Start the session on the specified socket and check for success */
    while( (rc = libssh2_session_startup(session,sock)) == LIBSSH2_ERROR_EAGAIN);
    if(rc) {
        syslog(LOG_ERR,"Failure establishing SSH session %d on host %s", rc, rm->hostname);
        goto error;
    }

    /* Get the current host key and check to see if it matches with any known hosts */
    nh = libssh2_knownhost_init(session);
    if(!nh) {
        syslog(LOG_ERR,"Error while initialising known hosts collection on host %s",rm->hostname);
        goto error;
    }
    libssh2_knownhost_readfile(nh,"known_hosts",LIBSSH2_KNOWNHOST_FILE_OPENSSH);
    //libssh2_knownhost_writefile(nh,"dumpfile",LIBSSH2_KNOWNHOST_FILE_OPENSSH);
    fingerprint = libssh2_session_hostkey(session,&len,&type);

    if(fingerprint) {
        struct libssh2_knownhost *host;

        int check = libssh2_knownhost_checkp(nh,rm->hostname,rm->port,fingerprint,len
                ,LIBSSH2_KNOWNHOST_TYPE_PLAIN|LIBSSH2_KNOWNHOST_KEYENC_RAW,&host);

        if(check == LIBSSH2_KNOWNHOST_CHECK_MATCH)
            syslog(LOG_DEBUG,"Found matching host key for host %s",rm->hostname);
        else if(check == LIBSSH2_KNOWNHOST_CHECK_MISMATCH)
            syslog(LOG_ERR,"Host key was found but the key's didn't match for host %s",rm->hostname);
            //TODO Some sort of critical error will need to be generated here
        else if(check == LIBSSH2_KNOWNHOST_CHECK_NOTFOUND)
            syslog(LOG_ERR,"No host match was found for %s",rm->hostname);
            //TODO Have the ability to add the host key here
        else
            syslog(LOG_ERR,"There was a failure while attempting to match host keys for host %s",rm->hostname);
    }
    else {
        syslog(LOG_ERR,"Couldn't get host key for host: %s",rm->hostname);
        goto error;
    }

    libssh2_knownhost_free(nh);

    /* Authenticate with the specified rm->username and passwod and check for success */
    // TODO Add ability to authenticate with a private key
    if( (strlen(rm->password)) != 0 ) {
        syslog(LOG_DEBUG,"Using rm->password authentication for host %s",rm->hostname);
        while( (rc = libssh2_userauth_password(session,rm->username,rm->password)) == LIBSSH2_ERROR_EAGAIN);
        if(rc) {
            syslog(LOG_ERR,"Authentication to host %s failed",rm->hostname);
            goto error;
        }
    }
    else if( ( (strlen(rm->publickey)) != 0 ) && ( ( strlen(rm->privatekey)) != 0) ) {
        syslog(LOG_DEBUG,"Using public key authentication for host %s",rm->hostname);
        while( (rc = libssh2_userauth_publickey_fromfile(session,rm->username,rm->publickey,rm->privatekey,NULL)) == LIBSSH2_ERROR_EAGAIN);

        switch(rc) {
            case 0:
                break;
            case LIBSSH2_ERROR_AUTHENTICATION_FAILED:
                syslog(LOG_ERR,"Authentication using the supplied key for host %s was not accepted",rm->hostname);
                goto error;
            case LIBSSH2_ERROR_PUBLICKEY_UNVERIFIED:
                syslog(LOG_ERR,"The rm->username/public key combination was invalid for host %s",rm->hostname);
                goto error;
            default:
                syslog(LOG_ERR,"Authentication to host %s failed",rm->hostname);
                goto error;
        }
    }
    
    /* Open a session for each command */
    for(int i = 0; i < rm->num_commands; i++) {

        /* Open a channel on the current channel and check for success */
        while( (channel = libssh2_channel_open_session(session)) == NULL && libssh2_session_last_error(session,NULL,NULL,0) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock,session);
        }
        if(channel == NULL) {
            syslog(LOG_ERR,"Error opening SSH channel on host %s",rm->hostname);
            asprintf(&(rm->results[i]),NULL);
            break;
        }

        /* Execute the command and check for success */
        while( (rc = libssh2_channel_exec(channel,rm->commands[i])) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock,session);
        }
        if(rc!=0) {
            syslog(LOG_ERR,"Error while executing %s in channel on host %s",rm->commands[i],rm->hostname);
            asprintf(&(rm->results[i]),NULL); 
            break;
        }

        /* Continuously read the returned stream and break once the stream has been read */
        for(;;) {
            int rc;
            do
            {
                char buffer[2048];

                rc = libssh2_channel_read(channel,buffer,sizeof(buffer));

                if(rc > 0) {
                    bytecount += rc;
                    char *output;
                    output = buffer;
                    syslog(LOG_ERR,"Got output from command %s on host %s:%s",rm->commands[i],rm->hostname,output);
                    /* Store the output in the results array */
                    asprintf(&(rm->results[i]),"%s",output);
                    memset(buffer,0,2048);
                }
            } while(rc > 0);

            if(rc == LIBSSH2_ERROR_EAGAIN) {
                waitsocket(sock,session);
            }
            else
                break;
        
        }

        /* Close the channel and check for success */
        while( (rc = libssh2_channel_close(channel)) == LIBSSH2_ERROR_EAGAIN) {
            waitsocket(sock,session);
        }
        if( (libssh2_channel_free(channel)) < 0)
            syslog(LOG_ERR,"Error while freeing channel on host %s",rm->hostname);
        channel = NULL;
    }

shutdown:

    syslog(LOG_DEBUG,"Disconnecting SSH session for host %s",rm->hostname);

    libssh2_session_disconnect(session,"Normal SSH disconnection");
    libssh2_session_free(session);

    close(sock);

    libssh2_exit();

    closelog();

    return 0;

error:

    syslog(LOG_DEBUG,"Disconnection SSH session for host %s",rm->hostname);

    libssh2_session_disconnect(session,"Normal SSH disconnection");
    libssh2_session_free(session);

    close(sock);

    libssh2_exit();

    closelog();

    return 1;
}
コード例 #9
0
ファイル: Crypto.cpp プロジェクト: daniellandau/keepassx
bool Crypto::backendSelfTest()
{
    return (gcry_control(GCRYCTL_SELFTEST) == 0);
}
コード例 #10
0
ファイル: gpg-check-pattern.c プロジェクト: FMayzek/gnupg
int
main (int argc, char **argv )
{
  ARGPARSE_ARGS pargs;
  char *raw_pattern;
  size_t raw_pattern_length;
  pattern_t *patternarray;

  set_strusage (my_strusage);
  gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
  log_set_prefix ("gpg-check-pattern", 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init ();
  init_common_subsystems (&argc, &argv);

  /* We need Libgcrypt for hashing.  */
  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
    {
      log_fatal ( _("%s is too old (need %s, have %s)\n"), "libgcrypt",
                  NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
    }

  setup_libgcrypt_logging ();
  gcry_control (GCRYCTL_INIT_SECMEM, 4096, 0);

  opt.homedir = default_homedir ();

  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags=  1;  /* (do not remove the args) */
  while (arg_parse (&pargs, opts) )
    {
      switch (pargs.r_opt)
        {
        case oVerbose: opt.verbose++; break;
        case oHomedir: opt.homedir = pargs.r.ret_str; break;
        case oCheck: opt.checkonly = 1; break;
        case oNull: opt.null = 1; break;

        default : pargs.err = 2; break;
	}
    }
  if (log_get_errorcount(0))
    exit (2);

  if (argc != 1)
    usage (1);

  /* We read the entire pattern file into our memory and parse it
     using a separate function.  This allows us to eventual do the
     reading while running setuid so that the pattern file can be
     hidden from regular users.  I am not sure whether this makes
     sense, but lets be prepared for it.  */
  raw_pattern = read_file (*argv, &raw_pattern_length);
  if (!raw_pattern)
    exit (2);

  patternarray = parse_pattern_file (raw_pattern, raw_pattern_length);
  if (!patternarray)
    exit (1);
  if (opt.checkonly)
    return 0;

#ifdef HAVE_DOSISH_SYSTEM
  setmode (fileno (stdin) , O_BINARY );
#endif
  process (stdin, patternarray);

  return log_get_errorcount(0)? 1 : 0;
}
コード例 #11
0
ファイル: g13-syshelp.c プロジェクト: 0ndorio/gnupg
int
main ( int argc, char **argv)
{
  ARGPARSE_ARGS pargs;
  int orig_argc;
  char **orig_argv;
  gpg_error_t err = 0;
  /* const char *fname; */
  int may_coredump;
  FILE *configfp = NULL;
  char *configname = NULL;
  unsigned configlineno;
  int parse_debug = 0;
  int no_more_options = 0;
  int default_config =1;
  char *logfile = NULL;
  /* int debug_wait = 0; */
  int use_random_seed = 1;
  /* int nodetach = 0; */
  /* int nokeysetup = 0; */
  struct server_control_s ctrl;

  /*mtrace();*/

  early_system_init ();
  gnupg_reopen_std (G13_NAME "-syshelp");
  set_strusage (my_strusage);
  gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);

  log_set_prefix (G13_NAME "-syshelp", 1);

  /* Make sure that our subsystems are ready.  */
  i18n_init ();
  init_common_subsystems (&argc, &argv);

  /* Check that the Libgcrypt is suitable.  */
  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION) )
    log_fatal (_("%s is too old (need %s, have %s)\n"), "libgcrypt",
               NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );

  /* Take extra care of the random pool.  */
  gcry_control (GCRYCTL_USE_SECURE_RNDPOOL);

  may_coredump = disable_core_dumps ();

  g13_init_signals ();

  dotlock_create (NULL, 0); /* Register locking cleanup.  */

  opt.session_env = session_env_new ();
  if (!opt.session_env)
    log_fatal ("error allocating session environment block: %s\n",
               strerror (errno));

  opt.homedir = default_homedir ();
  /* Fixme: We enable verbose mode here because there is currently no
     way to do this when starting g13-syshelp.  To fix that we should
     add a g13-syshelp.conf file in /etc/gnupg.  */
  opt.verbose = 1;

  /* First check whether we have a debug option on the commandline.  */
  orig_argc = argc;
  orig_argv = argv;
  pargs.argc = &argc;
  pargs.argv = &argv;
  pargs.flags= (ARGPARSE_FLAG_KEEP | ARGPARSE_FLAG_NOVERSION);
  while (arg_parse( &pargs, opts))
    {
      if (pargs.r_opt == oDebug || pargs.r_opt == oDebugAll)
        parse_debug++;
    }

  /* Initialize the secure memory. */
  gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
  maybe_setuid = 0;

  /*
     Now we are now working under our real uid
  */

  /* Setup malloc hooks. */
  {
    struct assuan_malloc_hooks malloc_hooks;

    malloc_hooks.malloc = gcry_malloc;
    malloc_hooks.realloc = gcry_realloc;
    malloc_hooks.free = gcry_free;
    assuan_set_malloc_hooks (&malloc_hooks);
  }

  /* Prepare libassuan.  */
  assuan_set_gpg_err_source (GPG_ERR_SOURCE_DEFAULT);
  /*assuan_set_system_hooks (ASSUAN_SYSTEM_NPTH);*/
  setup_libassuan_logging (&opt.debug);

  /* Setup a default control structure for command line mode.  */
  memset (&ctrl, 0, sizeof ctrl);
  g13_syshelp_init_default_ctrl (&ctrl);
  ctrl.no_server = 1;
  ctrl.status_fd = -1; /* No status output. */

  if (default_config )
    configname = make_filename (gnupg_sysconfdir (),
                                G13_NAME"-syshelp.conf", NULL);

  argc        = orig_argc;
  argv        = orig_argv;
  pargs.argc  = &argc;
  pargs.argv  = &argv;
  pargs.flags =  1;  /* Do not remove the args.  */

 next_pass:
  if (configname)
    {
      configlineno = 0;
      configfp = fopen (configname, "r");
      if (!configfp)
        {
          if (default_config)
            {
              if (parse_debug)
                log_info (_("NOTE: no default option file '%s'\n"), configname);
            }
          else
            {
              log_error (_("option file '%s': %s\n"),
                         configname, strerror(errno));
              g13_exit(2);
            }
          xfree (configname);
          configname = NULL;
        }
      if (parse_debug && configname)
        log_info (_("reading options from '%s'\n"), configname);
      default_config = 0;
    }

  while (!no_more_options
         && optfile_parse (configfp, configname, &configlineno, &pargs, opts))
    {
      switch (pargs.r_opt)
        {
        case oQuiet: opt.quiet = 1; break;

        case oDryRun: opt.dry_run = 1; break;

        case oVerbose:
          opt.verbose++;
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
          break;
        case oNoVerbose:
          opt.verbose = 0;
          gcry_control (GCRYCTL_SET_VERBOSITY, (int)opt.verbose);
          break;

        case oLogFile: logfile = pargs.r.ret_str; break;
        case oNoLogFile: logfile = NULL; break;

        case oNoDetach: /*nodetach = 1; */break;

        case oDebug:
          if (parse_debug_flag (pargs.r.ret_str, &opt.debug, debug_flags))
            {
              pargs.r_opt = ARGPARSE_INVALID_ARG;
              pargs.err = ARGPARSE_PRINT_ERROR;
            }
            break;
        case oDebugAll: debug_value = ~0; break;
        case oDebugNone: debug_value = 0; break;
        case oDebugLevel: debug_level = pargs.r.ret_str; break;
        case oDebugWait: /*debug_wait = pargs.r.ret_int; */break;
        case oDebugAllowCoreDump:
          may_coredump = enable_core_dumps ();
          break;

        case oStatusFD: ctrl.status_fd = pargs.r.ret_int; break;
        case oLoggerFD: log_set_fd (pargs.r.ret_int ); break;

        case oHomedir: opt.homedir = pargs.r.ret_str; break;

        case oFakedSystemTime:
          {
            time_t faked_time = isotime2epoch (pargs.r.ret_str);
            if (faked_time == (time_t)(-1))
              faked_time = (time_t)strtoul (pargs.r.ret_str, NULL, 10);
            gnupg_set_time (faked_time, 0);
          }
          break;

        case oNoSecmemWarn: gcry_control (GCRYCTL_DISABLE_SECMEM_WARN); break;

        case oNoRandomSeedFile: use_random_seed = 0; break;

        default:
          pargs.err = configfp? ARGPARSE_PRINT_WARNING:ARGPARSE_PRINT_ERROR;
          break;
	}
    }

  if (configfp)
    {
      fclose (configfp);
      configfp = NULL;
      /* Keep a copy of the config filename. */
      opt.config_filename = configname;
      configname = NULL;
      goto next_pass;
    }
  xfree (configname);
  configname = NULL;

  if (!opt.config_filename)
    opt.config_filename = make_filename (opt.homedir, G13_NAME".conf", NULL);

  if (log_get_errorcount(0))
    g13_exit(2);

  /* Now that we have the options parsed we need to update the default
     control structure.  */
  g13_syshelp_init_default_ctrl (&ctrl);

  if (may_coredump && !opt.quiet)
    log_info (_("WARNING: program may create a core file!\n"));

  if (logfile)
    {
      log_set_file (logfile);
      log_set_prefix (NULL, 1|2|4);
    }

  if (gnupg_faked_time_p ())
    {
      gnupg_isotime_t tbuf;

      log_info (_("WARNING: running with faked system time: "));
      gnupg_get_isotime (tbuf);
      dump_isotime (tbuf);
      log_printf ("\n");
    }

  /* Print any pending secure memory warnings.  */
  gcry_control (GCRYCTL_RESUME_SECMEM_WARN);

  /* Setup the debug flags for all subsystems.  */
  set_debug ();

  /* Install a regular exit handler to make real sure that the secure
     memory gets wiped out.  */
  g13_install_emergency_cleanup ();

  /* Terminate if we found any error until now.  */
  if (log_get_errorcount(0))
    g13_exit (2);

  /* Set the standard GnuPG random seed file.  */
  if (use_random_seed)
    {
      char *p = make_filename (opt.homedir, "random_seed", NULL);
      gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, p);
      xfree(p);
    }

  /* Get the UID of the caller.  */
#if defined(HAVE_PWD_H) && defined(HAVE_GETPWUID)
  {
    const char *uidstr;
    struct passwd *pwd = NULL;

    uidstr = getenv ("USERV_UID");

    /* Print a quick note if we are not started via userv.  */
    if (!uidstr)
      {
        if (getuid ())
          {
            log_info ("WARNING: Not started via userv\n");
            ctrl.fail_all_cmds = 1;
          }
        ctrl.client.uid = getuid ();
      }
    else
      {
        unsigned long myuid;

        errno = 0;
        myuid = strtoul (uidstr, NULL, 10);
        if (myuid == ULONG_MAX && errno)
          {
            log_info ("WARNING: Started via broken userv: %s\n",
                      strerror (errno));
            ctrl.fail_all_cmds = 1;
            ctrl.client.uid = getuid ();
          }
        else
          ctrl.client.uid = (uid_t)myuid;
      }

    pwd = getpwuid (ctrl.client.uid);
    if (!pwd || !*pwd->pw_name)
      {
        log_info ("WARNING: Name for UID not found: %s\n", strerror (errno));
        ctrl.fail_all_cmds = 1;
        ctrl.client.uname = xstrdup ("?");
      }
    else
      ctrl.client.uname = xstrdup (pwd->pw_name);

    /* Check that the user name does not contain a directory
       separator. */
    if (strchr (ctrl.client.uname, '/'))
      {
        log_info ("WARNING: Invalid user name passed\n");
        ctrl.fail_all_cmds = 1;
      }
  }
#else /*!HAVE_PWD_H || !HAVE_GETPWUID*/
  log_info ("WARNING: System does not support required syscalls\n");
  ctrl.fail_all_cmds = 1;
  ctrl.client.uid = getuid ();
  ctrl.client.uname = xstrdup ("?");
#endif /*!HAVE_PWD_H || !HAVE_GETPWUID*/

  /* Read the table entries for this user.  */
  if (!ctrl.fail_all_cmds
      && !(ctrl.client.tab = parse_g13tab (ctrl.client.uname)))
    ctrl.fail_all_cmds = 1;

  /* Start the server.  */
  err = syshelp_server (&ctrl);
  if (err)
    log_error ("server exited with error: %s <%s>\n",
               gpg_strerror (err), gpg_strsource (err));

  /* Cleanup.  */
  g13_syshelp_deinit_default_ctrl (&ctrl);
  g13_exit (0);
  return 8; /*NOTREACHED*/
}
コード例 #12
0
ファイル: random.c プロジェクト: hu19891110/libgcrypt
int
main (int argc, char **argv)
{
  int last_argc = -1;
  int early_rng = 0;
  int in_recursion = 0;
  const char *program = NULL;

  if (argc)
    {
      program = *argv;
      argc--; argv++;
    }
  else
    die ("argv[0] missing\n");

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          fputs ("usage: random [options]\n", stdout);
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          debug = verbose = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--progress"))
        {
          argc--; argv++;
          with_progress = 1;
        }
      else if (!strcmp (*argv, "--in-recursion"))
        {
          in_recursion = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--early-rng-check"))
        {
          early_rng = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--prefer-standard-rng"))
        {
          /* This is anyway the default, but we may want to use it for
             debugging. */
          gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_STANDARD);
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--prefer-fips-rng"))
        {
          gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_FIPS);
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--prefer-system-rng"))
        {
          gcry_control (GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_SYSTEM);
          argc--; argv++;
        }
    }

#ifndef HAVE_W32_SYSTEM
  signal (SIGPIPE, SIG_IGN);
#endif

  if (early_rng)
    {
      /* Don't switch RNG in fips mode. */
      if (!gcry_fips_mode_active())
        check_early_rng_type_switching ();
    }

  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  if (!gcry_check_version (GCRYPT_VERSION))
    die ("version mismatch\n");

  if (with_progress)
    gcry_set_progress_handler (progress_cb, NULL);

  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  if (debug)
    gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);

  if (!in_recursion)
    {
      check_forking ();
      check_nonce_forking ();
      check_close_random_device ();
    }
  /* For now we do not run the drgb_reinit check from "make check" due
     to its high requirement for entropy.  */
  if (!getenv ("GCRYPT_IN_REGRESSION_TEST"))
    check_drbg_reinit ();

  /* Don't switch RNG in fips mode.  */
  if (!gcry_fips_mode_active())
    check_rng_type_switching ();

  if (!in_recursion)
    run_all_rng_tests (program);

  return 0;
}
コード例 #13
0
ファイル: random.c プロジェクト: hu19891110/libgcrypt
static void
check_drbg_reinit (void)
{
  static struct { const char *flags; } tv[] = {
    { NULL },
    { "" },
    { "sha1" },
    { "sha1 pr" },
    { "sha256" },
    { "sha256 pr" },
    { "sha512" },
    { "sha512 pr" },
    { "hmac sha1" },
    { "hmac sha1 pr" },
    { "hmac sha256" },
    { "hmac sha256 pr" },
    { "hmac sha512" },
    { "hmac sha512 pr" },
    { "aes sym128" },
    { "aes sym128 pr" },
    { "aes sym192" },
    { "aes sym192 pr" },
    { "aes sym256" },
    { "aes sym256 pr" }
  };
  int tidx;
  gpg_error_t err;
  char pers_string[] = "I'm a doctor, not an engineer.";
  gcry_buffer_t pers[1];

  if (verbose)
    inf ("checking DRBG_REINIT\n");

  memset (pers, 0, sizeof pers);
  pers[0].data = pers_string;
  pers[0].len = strlen (pers_string);

  err = gcry_control (GCRYCTL_DRBG_REINIT, "", NULL, 0, &err);
  if (gpg_err_code (err) != GPG_ERR_INV_ARG)
    die ("gcry_control(DRBG_REINIT) guard value did not work\n");

  err = gcry_control (GCRYCTL_DRBG_REINIT, "", NULL, -1, NULL);
  if (gpg_err_code (err) != GPG_ERR_INV_ARG)
    die ("gcry_control(DRBG_REINIT) npers negative detection failed\n");

  if (rng_type () != GCRY_RNG_TYPE_FIPS)
    {
      err = gcry_control (GCRYCTL_DRBG_REINIT, "", NULL, 0, NULL);
      if (gpg_err_code (err) != GPG_ERR_NOT_SUPPORTED)
        die ("DRBG_REINIT worked despite that DRBG is not active\n");
      return;
    }

  err = gcry_control (GCRYCTL_DRBG_REINIT, "", NULL, 1, NULL);
  if (gpg_err_code (err) != GPG_ERR_INV_ARG)
    die ("_gcry_rngdrbg_reinit failed to detact: (!pers && npers)\n");
  err = gcry_control (GCRYCTL_DRBG_REINIT, "", pers, 2, NULL);
  if (gpg_err_code (err) != GPG_ERR_INV_ARG)
    die ("_gcry_rngdrbg_reinit failed to detect: (pers && npers != 1)\n");

  err = gcry_control (GCRYCTL_DRBG_REINIT, "aes sym128 bad pr ", pers, 1, NULL);
  if (gpg_err_code (err) != GPG_ERR_INV_FLAG)
    die ("_gcry_rngdrbg_reinit failed to detect a bad flag\n");

  for (tidx=0; tidx < DIM(tv); tidx++)
    {
      err = gcry_control (GCRYCTL_DRBG_REINIT, tv[tidx].flags, NULL, 0, NULL);
      if (err)
        die ("_gcry_rngdrbg_reinit failed for \"%s\" w/o pers: %s\n",

             tv[tidx].flags, gpg_strerror (err));
      err = gcry_control (GCRYCTL_DRBG_REINIT, tv[tidx].flags, pers, 1, NULL);
      if (err)
        die ("_gcry_rngdrbg_reinit failed for \"%s\" with pers: %s\n",
             tv[tidx].flags, gpg_strerror (err));
      /* fixme: We should extract some random after each test.  */
    }
}
コード例 #14
0
ファイル: zm_user.cpp プロジェクト: SteveGilvarry/ZoneMinder
// Function to validate an authentication string
User *zmLoadAuthUser( const char *auth, bool use_remote_addr ) {
#if HAVE_DECL_MD5 || HAVE_DECL_GNUTLS_FINGERPRINT
#ifdef HAVE_GCRYPT_H
  // Special initialisation for libgcrypt
  if ( !gcry_check_version( GCRYPT_VERSION ) ) {
    Fatal( "Unable to initialise libgcrypt" );
  }
  gcry_control( GCRYCTL_DISABLE_SECMEM, 0 );
  gcry_control( GCRYCTL_INITIALIZATION_FINISHED, 0 );
#endif // HAVE_GCRYPT_H

  const char *remote_addr = "";
  if ( use_remote_addr ) {
    remote_addr = getenv( "REMOTE_ADDR" );
    if ( !remote_addr ) {
      Warning( "Can't determine remote address, using null" );
      remote_addr = "";
    }
  }

  Debug( 1, "Attempting to authenticate user from auth string '%s'", auth );
  char sql[ZM_SQL_SML_BUFSIZ] = "";
  snprintf( sql, sizeof(sql), "SELECT Id, Username, Password, Enabled, Stream+0, Events+0, Control+0, Monitors+0, System+0, MonitorIds FROM Users WHERE Enabled = 1" );

  if ( mysql_query( &dbconn, sql ) ) {
    Error( "Can't run query: %s", mysql_error( &dbconn ) );
    exit( mysql_errno( &dbconn ) );
  }

  MYSQL_RES *result = mysql_store_result( &dbconn );
  if ( !result ) {
    Error( "Can't use query result: %s", mysql_error( &dbconn ) );
    exit( mysql_errno( &dbconn ) );
  }
  int n_users = mysql_num_rows( result );

  if ( n_users < 1 ) {
    mysql_free_result( result );
    Warning( "Unable to authenticate user" );
    return( 0 );
  }

  while( MYSQL_ROW dbrow = mysql_fetch_row( result ) ) {
    const char *user = dbrow[1];
    const char *pass = dbrow[2];

    char auth_key[512] = "";
    char auth_md5[32+1] = "";
    size_t md5len = 16;
    unsigned char md5sum[md5len];

    time_t now = time( 0 );
    unsigned int hours = config.auth_hash_ttl;

    if ( ! hours ) {
      Warning("No value set for ZM_AUTH_HASH_TTL. Defaulting to 2.");
      hours = 2;
    } else {
      Debug( 1, "AUTH_HASH_TTL is %d", hours );
    }

    for ( unsigned int i = 0; i < hours; i++, now -= 3600 ) {
      struct tm *now_tm = localtime( &now );

      snprintf( auth_key, sizeof(auth_key), "%s%s%s%s%d%d%d%d", 
        config.auth_hash_secret,
        user,
        pass,
        remote_addr,
        now_tm->tm_hour,
        now_tm->tm_mday,
        now_tm->tm_mon,
        now_tm->tm_year
      );

#if HAVE_DECL_MD5
      MD5( (unsigned char *)auth_key, strlen(auth_key), md5sum );
#elif HAVE_DECL_GNUTLS_FINGERPRINT
      gnutls_datum_t md5data = { (unsigned char *)auth_key, strlen(auth_key) };
      gnutls_fingerprint( GNUTLS_DIG_MD5, &md5data, md5sum, &md5len );
#endif
      auth_md5[0] = '\0';
      for ( unsigned int j = 0; j < md5len; j++ ) {
        sprintf( &auth_md5[2*j], "%02x", md5sum[j] );
      }
      Debug( 1, "Checking auth_key '%s' -> auth_md5 '%s' == '%s'", auth_key, auth_md5, auth );

      if ( !strcmp( auth, auth_md5 ) ) {
        // We have a match
        User *user = new User( dbrow );
        Debug(1, "Authenticated user '%s'", user->getUsername() );
        mysql_free_result( result );
        return( user );
      } else {
        Debug(1, "No match for %s", auth );
      }
    }
  }
  mysql_free_result( result );
#else // HAVE_DECL_MD5
  Error( "You need to build with gnutls or openssl installed to use hash based authentication" );
#endif // HAVE_DECL_MD5
  Debug(1, "No user found for auth_key %s", auth );
  return 0;
}
コード例 #15
0
ファイル: gnutls_global.c プロジェクト: Chronic-Dev/gnutls
/**
 * gnutls_global_init:
 *
 * This function initializes the global data to defaults.  Every
 * gnutls application has a global data which holds common parameters
 * shared by gnutls session structures.  You should call
 * gnutls_global_deinit() when gnutls usage is no longer needed
 *
 * Note that this function will also initialize libgcrypt, if it has
 * not been initialized before.  Thus if you want to manually
 * initialize libgcrypt you must do it before calling this function.
 * This is useful in cases you want to disable libgcrypt's internal
 * lockings etc.
 *
 * This function increment a global counter, so that
 * gnutls_global_deinit() only releases resources when it has been
 * called as many times as gnutls_global_init().  This is useful when
 * GnuTLS is used by more than one library in an application.  This
 * function can be called many times, but will only do something the
 * first time.
 *
 * Note!  This function is not thread safe.  If two threads call this
 * function simultaneously, they can cause a race between checking
 * the global counter and incrementing it, causing both threads to
 * execute the library initialization code.  That would lead to a
 * memory leak.  To handle this, your application could invoke this
 * function after aquiring a thread mutex.  To ignore the potential
 * memory leak is also an option.
 *
 * Returns: On success, %GNUTLS_E_SUCCESS (zero) is returned,
 *   otherwise an error code is returned.
 **/
int
gnutls_global_init (void)
{
  int result = 0;
  int res;

  if (_gnutls_init++)
    goto out;

  if (gl_sockets_startup (SOCKETS_1_1))
    return GNUTLS_E_LIBRARY_VERSION_MISMATCH;

  bindtextdomain (PACKAGE, LOCALEDIR);

  /* Initialize libgcrypt if it hasn't already been initialized. */
  if (gcry_control (GCRYCTL_ANY_INITIALIZATION_P) == 0)
    {
      const char *p;

      p = gcry_check_version (GNUTLS_MIN_LIBGCRYPT_VERSION);

      if (p == NULL)
	{
	  gnutls_assert ();
	  _gnutls_debug_log ("Checking for libgcrypt failed: %s < %s\n",
			     gcry_check_version (NULL),
			     GNUTLS_MIN_LIBGCRYPT_VERSION);
	  return GNUTLS_E_INCOMPATIBLE_GCRYPT_LIBRARY;
	}

      /* for gcrypt in order to be able to allocate memory */
      gcry_control (GCRYCTL_DISABLE_SECMEM, NULL, 0);

      gcry_control (GCRYCTL_INITIALIZATION_FINISHED, NULL, 0);
    }

  /* initialize ASN.1 parser
   * This should not deal with files in the final
   * version.
   */
  if (asn1_check_version (GNUTLS_MIN_LIBTASN1_VERSION) == NULL)
    {
      gnutls_assert ();
      _gnutls_debug_log ("Checking for libtasn1 failed: %s < %s\n",
			 asn1_check_version (NULL),
			 GNUTLS_MIN_LIBTASN1_VERSION);
      return GNUTLS_E_INCOMPATIBLE_LIBTASN1_LIBRARY;
    }

  res = asn1_array2tree (pkix_asn1_tab, &_gnutls_pkix1_asn, NULL);
  if (res != ASN1_SUCCESS)
    {
      result = _gnutls_asn2err (res);
      goto out;
    }

  res = asn1_array2tree (gnutls_asn1_tab, &_gnutls_gnutls_asn, NULL);
  if (res != ASN1_SUCCESS)
    {
      asn1_delete_structure (&_gnutls_pkix1_asn);
      result = _gnutls_asn2err (res);
      goto out;
    }

  /* Initialize the random generator */
  result = _gnutls_rnd_init ();
  if (result < 0)
    {
      gnutls_assert ();
      goto out;
    }

  /* Initialize the default TLS extensions */
  result = _gnutls_ext_init ();
  if (result < 0)
    {
      gnutls_assert ();
      goto out;
    }

  _gnutls_cryptodev_init ();

out:
  return result;
}
コード例 #16
0
ファイル: version.c プロジェクト: GostCrypt/libgcrypt
int
main (int argc, char **argv)
{
  int last_argc = -1;

  if (argc)
    { argc--; argv++; }

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--debug"))
        {
          /* Dummy option */
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--disable-hwf"))
        {
          argc--;
          argv++;
          if (argc)
            {
              if (gcry_control (GCRYCTL_DISABLE_HWF, *argv, NULL))
                fprintf (stderr,
                        PGM
                        ": unknown hardware feature '%s' - option ignored\n",
                        *argv);
              argc--;
              argv++;
            }
        }
    }

  xgcry_control (GCRYCTL_SET_VERBOSITY, (int)verbose);

  xgcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  if (strcmp (GCRYPT_VERSION, gcry_check_version (NULL)))
    {
      int oops = !gcry_check_version (GCRYPT_VERSION);
      fprintf (stderr, PGM ": %sversion mismatch; pgm=%s, library=%s\n",
               oops? "":"warning: ", GCRYPT_VERSION, gcry_check_version (NULL));
      if (oops)
        exit (1);
    }

  xgcry_control (GCRYCTL_PRINT_CONFIG, NULL);

  test_get_config ();


  return 0;
}
コード例 #17
0
ファイル: epan.c プロジェクト: crondaemon/wireshark
gboolean
epan_init(void (*register_all_protocols_func)(register_cb cb, gpointer client_data),
	  void (*register_all_handoffs_func)(register_cb cb, gpointer client_data),
	  register_cb cb,
	  gpointer client_data)
{
	volatile gboolean status = TRUE;

	/* initialize memory allocation subsystem */
	wmem_init();

	/* initialize the GUID to name mapping table */
	guids_init();

	/* initialize name resolution (addr_resolv.c) */
	addr_resolv_init();

	except_init();
#ifdef HAVE_LIBGCRYPT
	/* initialize libgcrypt (beware, it won't be thread-safe) */
	gcry_check_version(NULL);
	gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
	gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
#endif
#ifdef HAVE_LIBGNUTLS
	gnutls_global_init();
#endif
	TRY {
		tap_init();
		prefs_init();
		expert_init();
		packet_init();
		capture_dissector_init();
		proto_init(register_all_protocols_func, register_all_handoffs_func,
		    cb, client_data);
		packet_cache_proto_handles();
		dfilter_init();
		final_registration_all_protocols();
		print_cache_field_handles();
		expert_packet_init();
		export_pdu_init();
#ifdef HAVE_LUA
		wslua_init(cb, client_data);
#endif
	}
	CATCH(DissectorError) {
		/*
		 * This is probably a dissector, or something it calls,
		 * calling REPORT_DISSECTOR_ERROR() in a registration
		 * routine or something else outside the normal dissection
		 * code path.
		 */
		const char *exception_message = GET_MESSAGE;
		static const char dissector_error_nomsg[] =
		    "Dissector writer didn't bother saying what the error was";

		report_failure("Dissector bug: %s",
			       exception_message == NULL ?
				 dissector_error_nomsg : exception_message);
		if (getenv("WIRESHARK_ABORT_ON_DISSECTOR_BUG") != NULL)
			abort();
		status = FALSE;
	}
	ENDTRY;
	return status;
}
コード例 #18
0
ファイル: rsacvt.c プロジェクト: Distrotech/libgcrypt
int
main (int argc, char **argv)
{
  int last_argc = -1;
  FILE *input;
  gcry_mpi_t  rsa_p, rsa_q, rsa_e;
  int got_eof;
  int any = 0;

  if (argc)
    { argc--; argv++; }

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--help"))
        {
          usage (1);
        }
      else if (!strcmp (*argv, "--version"))
        {
          fputs (PGM " (Libgcrypt) " PACKAGE_VERSION "\n", stdout);
          printf ("libgcrypt %s\n", gcry_check_version (NULL));
          exit (0);
        }
      else if (!strcmp (*argv, "--verbose"))
        {
          verbose++;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--labels"))
        {
          with_labels = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--keep-lz"))
        {
          keep_lz = 1;
          argc--; argv++;
        }
      else if (!strcmp (*argv, "--openpgp"))
        {
          openpgp_mode = 1;
          argc--; argv++;
        }
    }

  if (argc > 1)
    usage (0);

#if !defined (HAVE_W32_SYSTEM) && !defined (_WIN32)
  signal (SIGPIPE, SIG_IGN);
#endif

  if (argc == 1 && strcmp (argv[0], "-"))
    {
      input = fopen (argv[0], "r");
      if (!input)
        die ("can't open `%s': %s\n", argv[0], strerror (errno));
    }
  else
    input = stdin;

  gcry_control (GCRYCTL_SET_VERBOSITY, (int)verbose);
  if (!gcry_check_version ("1.4.0"))
    die ("Libgcrypt is not sufficient enough\n");
  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);

  do
    {
      rsa_p = read_hexmpi_line (input, &got_eof);
      if (!rsa_p && got_eof)
        break;
      if (!rsa_p)
        die ("RSA parameter 'p' missing or not properly hex encoded\n");
      rsa_q = read_hexmpi_line (input, &got_eof);
      if (!rsa_q)
        die ("RSA parameter 'q' missing or not properly hex encoded\n");
      rsa_e = read_hexmpi_line (input, &got_eof);
      if (!rsa_e)
        die ("RSA parameter 'e' missing or not properly hex encoded\n");
      got_eof = skip_to_empty_line (input);

      if (any)
        putchar ('\n');

      compute_missing (rsa_p, rsa_q, rsa_e);

      gcry_mpi_release (rsa_p);
      gcry_mpi_release (rsa_q);
      gcry_mpi_release (rsa_e);

      any = 1;
    }
  while (!got_eof);

  return 0;
}
コード例 #19
0
/* Fork and exec the PGMNAME, see exechelp.h for details.  */
gpg_error_t
gnupg_spawn_process (const char *pgmname, const char *argv[],
                     gpg_err_source_t errsource,
                     void (*preexec)(void), unsigned int flags,
                     estream_t infp,
                     estream_t *r_outfp,
                     estream_t *r_errfp,
                     pid_t *pid)
{
    gpg_error_t err;
    int infd = -1;
    int outpipe[2] = {-1, -1};
    int errpipe[2] = {-1, -1};
    estream_t outfp = NULL;
    estream_t errfp = NULL;

    (void)flags; /* Currently not used.  */

    if (r_outfp)
        *r_outfp = NULL;
    if (r_errfp)
        *r_errfp = NULL;
    *pid = (pid_t)(-1); /* Always required.  */

    if (infp)
    {
        es_fflush (infp);
        es_rewind (infp);
        infd = es_fileno (infp);
        if (infd == -1)
            return gpg_err_make (errsource, GPG_ERR_INV_VALUE);
    }

    if (r_outfp)
    {
        err = create_pipe_and_estream (outpipe, &outfp, errsource);
        if (err)
            return err;
    }

    if (r_errfp)
    {
        err = create_pipe_and_estream (errpipe, &errfp, errsource);
        if (err)
        {
            if (outfp)
                es_fclose (outfp);
            else if (outpipe[0] != -1)
                close (outpipe[0]);
            if (outpipe[1] != -1)
                close (outpipe[1]);
            return err;
        }
    }


    *pid = fork ();
    if (*pid == (pid_t)(-1))
    {
        err = gpg_err_make (errsource, gpg_err_code_from_syserror ());
        log_error (_("error forking process: %s\n"), gpg_strerror (err));

        if (outfp)
            es_fclose (outfp);
        else if (outpipe[0] != -1)
            close (outpipe[0]);
        if (outpipe[1] != -1)
            close (outpipe[1]);

        if (errfp)
            es_fclose (errfp);
        else if (errpipe[0] != -1)
            close (errpipe[0]);
        if (errpipe[1] != -1)
            close (errpipe[1]);
        return err;
    }

    if (!*pid)
    {
        /* This is the child. */
        gcry_control (GCRYCTL_TERM_SECMEM);
        es_fclose (outfp);
        es_fclose (errfp);
        do_exec (pgmname, argv, infd, outpipe[1], errpipe[1], preexec);
        /*NOTREACHED*/
    }

    /* This is the parent. */
    if (outpipe[1] != -1)
        close (outpipe[1]);
    if (errpipe[1] != -1)
        close (errpipe[1]);

    if (r_outfp)
        *r_outfp = outfp;
    if (r_errfp)
        *r_errfp = errfp;

    return 0;
}
コード例 #20
0
ファイル: cli.c プロジェクト: Chronic-Dev/gnutls
int
main (int argc, char **argv)
{
  int err, ret;
  int ii, i;
  char buffer[MAX_BUF + 1];
  char *session_data = NULL;
  char *session_id = NULL;
  size_t session_data_size;
  size_t session_id_size;
  fd_set rset;
  int maxfd;
  struct timeval tv;
  int user_term = 0, retval = 0;
  socket_st hd;
  ssize_t bytes;

  set_program_name (argv[0]);

  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);

#ifdef gcry_fips_mode_active
  /* Libgcrypt manual says that gcry_version_check must be called
     before calling gcry_fips_mode_active. */
  gcry_check_version (NULL);
  if (gcry_fips_mode_active ())
    {
      ret = gnutls_register_md5_handler ();
      if (ret)
	fprintf (stderr, "gnutls_register_md5_handler: %s\n",
		 gnutls_strerror (ret));
    }
#endif

  if ((ret = gnutls_global_init ()) < 0)
    {
      fprintf (stderr, "global_init: %s\n", gnutls_strerror (ret));
      exit (1);
    }

  if ((ret = gnutls_global_init_extra ()) < 0)
    {
      fprintf (stderr, "global_init_extra: %s\n", gnutls_strerror (ret));
      exit (1);
    }

  gaa_parser (argc, argv);
  if (hostname == NULL)
    {
      fprintf (stderr, "No hostname given\n");
      exit (1);
    }

  gnutls_global_set_log_function (tls_log_func);
  gnutls_global_set_log_level (info.debug);

  sockets_init ();

#ifndef _WIN32
  signal (SIGPIPE, SIG_IGN);
#endif

  init_global_tls_stuff ();

  socket_open (&hd, hostname, service);
  socket_connect (&hd);

  hd.session = init_tls_session (hostname);
  if (starttls)
    goto after_handshake;

  for (i = 0; i < 2; i++)
    {


      if (i == 1)
	{
	  hd.session = init_tls_session (hostname);
	  gnutls_session_set_data (hd.session, session_data,
				   session_data_size);
	  free (session_data);
	}

      ret = do_handshake (&hd);

      if (ret < 0)
	{
	  fprintf (stderr, "*** Handshake has failed\n");
	  gnutls_perror (ret);
	  gnutls_deinit (hd.session);
	  return 1;
	}
      else
	{
	  printf ("- Handshake was completed\n");
	  if (gnutls_session_is_resumed (hd.session) != 0)
	    printf ("*** This is a resumed session\n");
	}

      if (resume != 0 && i == 0)
	{

	  gnutls_session_get_data (hd.session, NULL, &session_data_size);
	  session_data = malloc (session_data_size);

	  gnutls_session_get_data (hd.session, session_data,
				   &session_data_size);

	  gnutls_session_get_id (hd.session, NULL, &session_id_size);
	  session_id = malloc (session_id_size);
	  gnutls_session_get_id (hd.session, session_id, &session_id_size);

	  /* print some information */
	  print_info (hd.session, hostname, info.insecure);

	  printf ("- Disconnecting\n");
	  socket_bye (&hd);

	  printf
	    ("\n\n- Connecting again- trying to resume previous session\n");
	  socket_open (&hd, hostname, service);
	  socket_connect (&hd);
	}
      else
	{
	  break;
	}
    }

after_handshake:

  /* Warning!  Do not touch this text string, it is used by external
     programs to search for when gnutls-cli has reached this point. */
  printf ("\n- Simple Client Mode:\n\n");

  if (rehandshake)
    {
      ret = do_handshake (&hd);

      if (ret < 0)
	{
	  fprintf (stderr, "*** ReHandshake has failed\n");
	  gnutls_perror (ret);
	  gnutls_deinit (hd.session);
	  return 1;
	}
      else
	{
	  printf ("- ReHandshake was completed\n");
	}
    }

#ifndef _WIN32
  signal (SIGALRM, &starttls_alarm);
#endif

  fflush(stdout);
  fflush(stderr);

  /* do not buffer */
#if !(defined _WIN32 || defined __WIN32__)
  setbuf (stdin, NULL);
#endif
  setbuf (stdout, NULL);
  setbuf (stderr, NULL);

  for (;;)
    {
      if (starttls_alarmed && !hd.secure)
	{
	  /* Warning!  Do not touch this text string, it is used by
	     external programs to search for when gnutls-cli has
	     reached this point. */
	  fprintf (stderr, "*** Starting TLS handshake\n");
	  ret = do_handshake (&hd);
	  if (ret < 0)
	    {
	      fprintf (stderr, "*** Handshake has failed\n");
	      user_term = 1;
	      retval = 1;
	      break;
	    }
	}

      FD_ZERO (&rset);
      FD_SET (fileno (stdin), &rset);
      FD_SET (hd.fd, &rset);

      maxfd = MAX (fileno (stdin), hd.fd);
      tv.tv_sec = 3;
      tv.tv_usec = 0;

      err = select (maxfd + 1, &rset, NULL, NULL, &tv);
      if (err < 0)
	continue;

      if (FD_ISSET (hd.fd, &rset))
	{
	  memset (buffer, 0, MAX_BUF + 1);
	  ret = socket_recv (&hd, buffer, MAX_BUF);

	  if (ret == 0)
	    {
	      printf ("- Peer has closed the GnuTLS connection\n");
	      break;
	    }
	  else if (handle_error (&hd, ret) < 0 && user_term == 0)
	    {
	      fprintf (stderr,
		       "*** Server has terminated the connection abnormally.\n");
	      retval = 1;
	      break;
	    }
	  else if (ret > 0)
	    {
	      if (verbose != 0)
		printf ("- Received[%d]: ", ret);
	      for (ii = 0; ii < ret; ii++)
		{
		  fputc (buffer[ii], stdout);
		}
	      fflush (stdout);
	    }

	  if (user_term != 0)
	    break;
	}

      if (FD_ISSET (fileno (stdin), &rset))
	{
	  if ((bytes = read (fileno (stdin), buffer, MAX_BUF - 1)) <= 0)
	    {
	      if (hd.secure == 0)
		{
		  /* Warning!  Do not touch this text string, it is
		     used by external programs to search for when
		     gnutls-cli has reached this point. */
		  fprintf (stderr, "*** Starting TLS handshake\n");
		  ret = do_handshake (&hd);
		  clearerr (stdin);
		  if (ret < 0)
		    {
		      fprintf (stderr, "*** Handshake has failed\n");
		      user_term = 1;
		      retval = 1;
		      break;
		    }
		}
	      else
		{
		  user_term = 1;
		  break;
		}
	      continue;
	    }

	  if (crlf != 0)
	    {
	      char *b = strchr (buffer, '\n');
	      if (b != NULL)
		{
		  strcpy (b, "\r\n");
		  bytes++;
		}
	    }

	  ret = socket_send (&hd, buffer, bytes);

	  if (ret > 0)
	    {
	      if (verbose != 0)
		printf ("- Sent: %d bytes\n", ret);
	    }
	  else
	    handle_error (&hd, ret);

	}
    }

  if (info.debug)
    gcry_control (GCRYCTL_DUMP_RANDOM_STATS);

  if (user_term != 0)
    socket_bye (&hd);
  else
    gnutls_deinit (hd.session);

#ifdef ENABLE_SRP
  if (srp_cred)
    gnutls_srp_free_client_credentials (srp_cred);
#endif
#ifdef ENABLE_PSK
  if (psk_cred)
    gnutls_psk_free_client_credentials (psk_cred);
#endif

  gnutls_certificate_free_credentials (xcred);

#ifdef ENABLE_ANON
  gnutls_anon_free_client_credentials (anon_cred);
#endif

  gnutls_global_deinit ();

  return retval;
}
コード例 #21
0
ファイル: UgApp-gtk-main.c プロジェクト: Endz0/uget
void init_locks (void)
{
	gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
}
コード例 #22
0
ファイル: exechelp-posix.c プロジェクト: cuidi/gnupg
/* Fork and exec the PGMNAME, see exechelp.h for details.  */
gpg_error_t
gnupg_spawn_process (const char *pgmname, const char *argv[],
                     int *except, void (*preexec)(void), unsigned int flags,
                     estream_t *r_infp,
                     estream_t *r_outfp,
                     estream_t *r_errfp,
                     pid_t *pid)
{
  gpg_error_t err;
  int inpipe[2] = {-1, -1};
  int outpipe[2] = {-1, -1};
  int errpipe[2] = {-1, -1};
  estream_t infp = NULL;
  estream_t outfp = NULL;
  estream_t errfp = NULL;
  int nonblock = !!(flags & GNUPG_SPAWN_NONBLOCK);

  if (r_infp)
    *r_infp = NULL;
  if (r_outfp)
    *r_outfp = NULL;
  if (r_errfp)
    *r_errfp = NULL;
  *pid = (pid_t)(-1); /* Always required.  */

  if (r_infp)
    {
      err = create_pipe_and_estream (inpipe, &infp, 1, nonblock);
      if (err)
        return err;
    }

  if (r_outfp)
    {
      err = create_pipe_and_estream (outpipe, &outfp, 0, nonblock);
      if (err)
        {
          if (infp)
            es_fclose (infp);
          else if (inpipe[1] != -1)
            close (inpipe[1]);
          if (inpipe[0] != -1)
            close (inpipe[0]);

          return err;
        }
    }

  if (r_errfp)
    {
      err = create_pipe_and_estream (errpipe, &errfp, 0, nonblock);
      if (err)
        {
          if (infp)
            es_fclose (infp);
          else if (inpipe[1] != -1)
            close (inpipe[1]);
          if (inpipe[0] != -1)
            close (inpipe[0]);

          if (outfp)
            es_fclose (outfp);
          else if (outpipe[0] != -1)
            close (outpipe[0]);
          if (outpipe[1] != -1)
            close (outpipe[1]);

          return err;
        }
    }


  *pid = fork ();
  if (*pid == (pid_t)(-1))
    {
      err = my_error_from_syserror ();
      log_error (_("error forking process: %s\n"), gpg_strerror (err));

      if (infp)
        es_fclose (infp);
      else if (inpipe[1] != -1)
        close (inpipe[1]);
      if (inpipe[0] != -1)
        close (inpipe[0]);

      if (outfp)
        es_fclose (outfp);
      else if (outpipe[0] != -1)
        close (outpipe[0]);
      if (outpipe[1] != -1)
        close (outpipe[1]);

      if (errfp)
        es_fclose (errfp);
      else if (errpipe[0] != -1)
        close (errpipe[0]);
      if (errpipe[1] != -1)
        close (errpipe[1]);
      return err;
    }

  if (!*pid)
    {
      /* This is the child. */
      gcry_control (GCRYCTL_TERM_SECMEM);
      es_fclose (outfp);
      es_fclose (errfp);
      do_exec (pgmname, argv, inpipe[0], outpipe[1], errpipe[1],
               except, preexec);
      /*NOTREACHED*/
    }

  /* This is the parent. */
  if (inpipe[0] != -1)
    close (inpipe[0]);
  if (outpipe[1] != -1)
    close (outpipe[1]);
  if (errpipe[1] != -1)
    close (errpipe[1]);

  if (r_infp)
    *r_infp = infp;
  if (r_outfp)
    *r_outfp = outfp;
  if (r_errfp)
    *r_errfp = errfp;

  return 0;
}
コード例 #23
0
ファイル: threaded-ssl.c プロジェクト: 2px/curl
void init_locks(void)
{
  gcry_control(GCRYCTL_SET_THREAD_CBS);
}
コード例 #24
0
ファイル: spgcrypt.c プロジェクト: CCoder123/pproj
int sp_init_gcrypt_pthread()
{
	return gcry_control( GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread );
}
コード例 #25
0
ファイル: keygen.c プロジェクト: ifzz/libgcrypt
int
main (int argc, char **argv)
{
    int last_argc = -1;
    int with_progress = 0;

    if (argc)
    {
        argc--;
        argv++;
    }

    while (argc && last_argc != argc )
    {
        last_argc = argc;
        if (!strcmp (*argv, "--"))
        {
            argc--;
            argv++;
            break;
        }
        else if (!strcmp (*argv, "--help"))
        {
            usage (0);
            exit (0);
        }
        else if (!strcmp (*argv, "--verbose"))
        {
            verbose++;
            argc--;
            argv++;
        }
        else if (!strcmp (*argv, "--debug"))
        {
            verbose += 2;
            debug++;
            argc--;
            argv++;
        }
        else if (!strcmp (*argv, "--progress"))
        {
            argc--;
            argv++;
            with_progress = 1;
        }
        else if (!strncmp (*argv, "--", 2))
            die ("unknown option '%s'", *argv);
        else
            break;
    }

    if (!gcry_check_version (GCRYPT_VERSION))
        die ("version mismatch\n");
    gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
    gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
    if (debug)
        gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u , 0);
    /* No valuable keys are create, so we can speed up our RNG. */
    gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
    if (with_progress)
        gcry_set_progress_handler (progress_cb, NULL);

    if (!argc)
    {
        check_rsa_keys ();
        check_elg_keys ();
        check_dsa_keys ();
        check_ecc_keys ();
        check_nonce ();
    }
    else
    {
        for (; argc; argc--, argv++)
            if (!strcmp (*argv, "rsa"))
                check_rsa_keys ();
            else if (!strcmp (*argv, "elg"))
                check_elg_keys ();
            else if (!strcmp (*argv, "dsa"))
                check_dsa_keys ();
            else if (!strcmp (*argv, "ecc"))
                check_ecc_keys ();
            else if (!strcmp (*argv, "nonce"))
                check_nonce ();
            else
                usage (1);
    }

    return error_count? 1:0;
}
コード例 #26
0
ファイル: tlscert.c プロジェクト: DavidMulder/samba
/* 
   auto-generate a set of self signed certificates
*/
void tls_cert_generate(TALLOC_CTX *mem_ctx, 
		       const char *hostname, 
		       const char *keyfile, const char *certfile,
		       const char *cafile)
{
	gnutls_x509_crt cacrt, crt;
	gnutls_x509_privkey key, cakey;
	uint32_t serial = (uint32_t)time(NULL);
	unsigned char keyid[100];
	char buf[4096];
	size_t bufsize;
	size_t keyidsize = sizeof(keyid);
	time_t activation = time(NULL), expiry = activation + LIFETIME;
	int ret;

	if (file_exist(keyfile) || file_exist(certfile) || file_exist(cafile)) {
		DEBUG(0,("TLS autogeneration skipped - some TLS files already exist\n"));
		return;
	}

#define TLSCHECK(call) do { \
	ret = call; \
	if (ret < 0) { \
		DEBUG(0,("TLS %s - %s\n", #call, gnutls_strerror(ret))); \
		goto failed; \
	} \
} while (0)

	TLSCHECK(gnutls_global_init());

	DEBUG(0,("Attempting to autogenerate TLS self-signed keys for https for hostname '%s'\n", 
		 hostname));
	
#if defined(HAVE_GCRYPT_H) && !defined(HAVE_GNUTLS3)
	DEBUG(3,("Enabling QUICK mode in gcrypt\n"));
	gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
#endif

	DEBUG(3,("Generating private key\n"));
	TLSCHECK(gnutls_x509_privkey_init(&key));
	TLSCHECK(gnutls_x509_privkey_generate(key,   GNUTLS_PK_RSA, RSA_BITS, 0));

	DEBUG(3,("Generating CA private key\n"));
	TLSCHECK(gnutls_x509_privkey_init(&cakey));
	TLSCHECK(gnutls_x509_privkey_generate(cakey, GNUTLS_PK_RSA, RSA_BITS, 0));

	DEBUG(3,("Generating CA certificate\n"));
	TLSCHECK(gnutls_x509_crt_init(&cacrt));
	TLSCHECK(gnutls_x509_crt_set_dn_by_oid(cacrt, 
				      GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
				      ORGANISATION_NAME, strlen(ORGANISATION_NAME)));
	TLSCHECK(gnutls_x509_crt_set_dn_by_oid(cacrt, 
				      GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME, 0,
				      CA_NAME, strlen(CA_NAME)));
	TLSCHECK(gnutls_x509_crt_set_dn_by_oid(cacrt,
				      GNUTLS_OID_X520_COMMON_NAME, 0,
				      hostname, strlen(hostname)));
	TLSCHECK(gnutls_x509_crt_set_key(cacrt, cakey));
	TLSCHECK(gnutls_x509_crt_set_serial(cacrt, &serial, sizeof(serial)));
	TLSCHECK(gnutls_x509_crt_set_activation_time(cacrt, activation));
	TLSCHECK(gnutls_x509_crt_set_expiration_time(cacrt, expiry));
	TLSCHECK(gnutls_x509_crt_set_ca_status(cacrt, 1));
	TLSCHECK(gnutls_x509_crt_set_key_usage(cacrt, GNUTLS_KEY_KEY_CERT_SIGN | GNUTLS_KEY_CRL_SIGN));
	TLSCHECK(gnutls_x509_crt_set_version(cacrt, 3));
	TLSCHECK(gnutls_x509_crt_get_key_id(cacrt, 0, keyid, &keyidsize));
#if HAVE_GNUTLS_X509_CRT_SET_SUBJECT_KEY_ID
	TLSCHECK(gnutls_x509_crt_set_subject_key_id(cacrt, keyid, keyidsize));
#endif
	TLSCHECK(gnutls_x509_crt_sign2(cacrt, cacrt, cakey,
				       GNUTLS_DIG_SHA256, 0));

	DEBUG(3,("Generating TLS certificate\n"));
	TLSCHECK(gnutls_x509_crt_init(&crt));
	TLSCHECK(gnutls_x509_crt_set_dn_by_oid(crt, 
				      GNUTLS_OID_X520_ORGANIZATION_NAME, 0,
				      ORGANISATION_NAME, strlen(ORGANISATION_NAME)));
	TLSCHECK(gnutls_x509_crt_set_dn_by_oid(crt, 
				      GNUTLS_OID_X520_ORGANIZATIONAL_UNIT_NAME, 0,
				      UNIT_NAME, strlen(UNIT_NAME)));
	TLSCHECK(gnutls_x509_crt_set_dn_by_oid(crt,
				      GNUTLS_OID_X520_COMMON_NAME, 0,
				      hostname, strlen(hostname)));
	TLSCHECK(gnutls_x509_crt_set_key(crt, key));
	TLSCHECK(gnutls_x509_crt_set_serial(crt, &serial, sizeof(serial)));
	TLSCHECK(gnutls_x509_crt_set_activation_time(crt, activation));
	TLSCHECK(gnutls_x509_crt_set_expiration_time(crt, expiry));
	TLSCHECK(gnutls_x509_crt_set_ca_status(crt, 0));
#ifdef GNUTLS_KP_TLS_WWW_SERVER
	TLSCHECK(gnutls_x509_crt_set_key_purpose_oid(crt, GNUTLS_KP_TLS_WWW_SERVER, 0));
#endif
	TLSCHECK(gnutls_x509_crt_set_version(crt, 3));
	TLSCHECK(gnutls_x509_crt_get_key_id(crt, 0, keyid, &keyidsize));
#if HAVE_GNUTLS_X509_CRT_SET_SUBJECT_KEY_ID
	TLSCHECK(gnutls_x509_crt_set_subject_key_id(crt, keyid, keyidsize));
#endif
	TLSCHECK(gnutls_x509_crt_sign2(crt, crt, key,
				       GNUTLS_DIG_SHA256, 0));
	TLSCHECK(gnutls_x509_crt_sign2(crt, cacrt, cakey,
				       GNUTLS_DIG_SHA256, 0));

	DEBUG(3,("Exporting TLS keys\n"));

	bufsize = sizeof(buf);
	TLSCHECK(gnutls_x509_crt_export(crt, GNUTLS_X509_FMT_PEM, buf, &bufsize));
	if (!file_save(certfile, buf, bufsize)) {
		DEBUG(0,("Unable to save certificate in %s parent dir exists ?\n", certfile));
		goto failed;
	}

	bufsize = sizeof(buf);
	TLSCHECK(gnutls_x509_crt_export(cacrt, GNUTLS_X509_FMT_PEM, buf, &bufsize));
	if (!file_save(cafile, buf, bufsize)) {
		DEBUG(0,("Unable to save ca cert in %s parent dir exists ?\n", cafile));
		goto failed;
	}

	bufsize = sizeof(buf);
	TLSCHECK(gnutls_x509_privkey_export(key, GNUTLS_X509_FMT_PEM, buf, &bufsize));
	if (!file_save_mode(keyfile, buf, bufsize, 0600)) {
		DEBUG(0,("Unable to save privatekey in %s parent dir exists ?\n", keyfile));
		goto failed;
	}

	gnutls_x509_privkey_deinit(key);
	gnutls_x509_privkey_deinit(cakey);
	gnutls_x509_crt_deinit(cacrt);
	gnutls_x509_crt_deinit(crt);
	gnutls_global_deinit();

	DEBUG(0,("TLS self-signed keys generated OK\n"));
	return;

failed:
	DEBUG(0,("TLS certificate generation failed\n"));
}
コード例 #27
0
ファイル: main.c プロジェクト: antonywu/pianobar
int main (int argc, char **argv) {
	static BarApp_t app;
	/* terminal attributes _before_ we started messing around with ~ECHO */
	struct termios termOrig;

	memset (&app, 0, sizeof (app));

	/* save terminal attributes, before disabling echoing */
	BarTermSave (&termOrig);
	BarTermSetEcho (0);
	BarTermSetBuffer (0);

	/* signals */
	signal (SIGPIPE, SIG_IGN);

	/* init some things */
	ao_initialize ();
	gcry_check_version (NULL);
	gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
	gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
	gnutls_global_init ();

	BarSettingsInit (&app.settings);
	BarSettingsRead (&app.settings);

	PianoInit (&app.ph, app.settings.partnerUser, app.settings.partnerPassword,
			app.settings.device, app.settings.inkey, app.settings.outkey);

	BarUiMsg (&app.settings, MSG_NONE,
			"Welcome to " PACKAGE " (" VERSION ")! ");
	if (app.settings.keys[BAR_KS_HELP] == BAR_KS_DISABLED) {
		BarUiMsg (&app.settings, MSG_NONE, "\n");
	} else {
		BarUiMsg (&app.settings, MSG_NONE,
				"Press %c for a list of commands.\n",
				app.settings.keys[BAR_KS_HELP]);
	}

	WaitressInit (&app.waith);
	app.waith.url.host = app.settings.rpcHost;
	app.waith.tlsFingerprint = app.settings.tlsFingerprint;

	/* init fds */
	FD_ZERO(&app.input.set);
	app.input.fds[0] = STDIN_FILENO;
	FD_SET(app.input.fds[0], &app.input.set);

	/* open fifo read/write so it won't EOF if nobody writes to it */
	assert (sizeof (app.input.fds) / sizeof (*app.input.fds) >= 2);
	app.input.fds[1] = open (app.settings.fifo, O_RDWR);
	if (app.input.fds[1] != -1) {
		struct stat s;

		/* check for file type, must be fifo */
		fstat (app.input.fds[1], &s);
		if (!S_ISFIFO (s.st_mode)) {
			BarUiMsg (&app.settings, MSG_ERR, "File at %s is not a fifo\n", app.settings.fifo);
			close (app.input.fds[1]);
			app.input.fds[1] = -1;
		} else {
			FD_SET(app.input.fds[1], &app.input.set);
			BarUiMsg (&app.settings, MSG_INFO, "Control fifo at %s opened\n",
					app.settings.fifo);
		}
	}
	app.input.maxfd = app.input.fds[0] > app.input.fds[1] ? app.input.fds[0] :
			app.input.fds[1];
	++app.input.maxfd;

	BarMainLoop (&app);

	if (app.input.fds[1] != -1) {
		close (app.input.fds[1]);
	}

	PianoDestroy (&app.ph);
	PianoDestroyPlaylist (app.songHistory);
	PianoDestroyPlaylist (app.playlist);
	WaitressFree (&app.waith);
	ao_shutdown();
	gnutls_global_deinit ();
	BarSettingsDestroy (&app.settings);

	/* restore terminal attributes, zsh doesn't need this, bash does... */
	BarTermRestore (&termOrig);

	return 0;
}
コード例 #28
0
int main(int argc, char *argv[]) {
	/* disable secmem, not available in emscripten */
	gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
	
	return 0;
}
コード例 #29
0
ファイル: mpicalc.c プロジェクト: GostCrypt/libgcrypt
int
main (int argc, char **argv)
{
  const char *pgm;
  int last_argc = -1;
  int print_config = 0;
  int i, c;
  int state = 0;
  char strbuf[4096];
  int stridx = 0;

  if (argc)
    {
      pgm = strrchr (*argv, '/');
      if (pgm)
        pgm++;
      else
        pgm = *argv;
      argc--; argv++;
    }
  else
    pgm = "?";

  while (argc && last_argc != argc )
    {
      last_argc = argc;
      if (!strcmp (*argv, "--"))
        {
          argc--; argv++;
          break;
        }
      else if (!strcmp (*argv, "--version")
               || !strcmp (*argv, "--help"))
        {
          printf ("%s " MPICALC_VERSION "\n"
                  "libgcrypt %s\n"
                  "Copyright (C) 1997, 2013  Werner Koch\n"
                  "License LGPLv2.1+: GNU LGPL version 2.1 or later "
                  "<http://gnu.org/licenses/old-licenses/lgpl-2.1.html>\n"
                  "This is free software: you are free to change and "
                  "redistribute it.\n"
                  "There is NO WARRANTY, to the extent permitted by law.\n"
                  "\n"
                  "Syntax: mpicalc [options]\n"
                  "Simple interactive big integer RPN calculator\n"
                  "\n"
                  "Options:\n"
                  "  --version           print version information\n"
                  "  --print-config      print the Libgcrypt config\n"
                  "  --disable-hwf NAME  disable feature NAME\n",
                  pgm, gcry_check_version (NULL));
          exit (0);
        }
      else if (!strcmp (*argv, "--print-config"))
        {
          argc--; argv++;
          print_config = 1;
        }
      else if (!strcmp (*argv, "--disable-hwf"))
        {
          argc--; argv++;
          if (argc)
            {
              if (gcry_control (GCRYCTL_DISABLE_HWF, *argv, NULL))
                fprintf (stderr, "%s: unknown hardware feature `%s'"
                         " - option ignored\n", pgm, *argv);
              argc--; argv++;
            }
        }
    }

  if (argc)
    {
      fprintf (stderr, "usage: %s [options]  (--help for help)\n", pgm);
      exit (1);
    }

  if (!gcry_check_version (NEED_LIBGCRYPT_VERSION))
    {
      fprintf (stderr, "%s: Libgcrypt is too old (need %s, have %s)\n",
               pgm, NEED_LIBGCRYPT_VERSION, gcry_check_version (NULL) );
      exit (1);
    }
  gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  if (print_config)
    {
      gcry_control (GCRYCTL_PRINT_CONFIG, stdout);
      exit (0);
    }

  for (i = 0; i < STACKSIZE; i++)
    stack[i] = NULL;
  stackidx = 0;

  while ((c = my_getc ()) != EOF)
    {
      if (!state) /* waiting */
	{
	  if (isdigit (c))
	    {
	      state = 1;
	      ungetc (c, stdin);
	      strbuf[0] = '0';
	      strbuf[1] = 'x';
	      stridx = 2;
	    }
	  else if (isspace (c))
	    ;
	  else
	    {
	      switch (c)
		{
                case '#':
                  state = 2;
                  break;
		case '+':
		  if ((c = my_getc ()) == '+')
		    do_inc ();
		  else
		    {
		      ungetc (c, stdin);
		      do_add ();
		    }
		  break;
                case '-':
		  if ((c = my_getc ()) == '-')
		    do_dec ();
		  else if (isdigit (c)
                           || (c >= 'A' && c <= 'F')
                           || (c >= 'a' && c <= 'f'))
		    {
		      state = 1;
		      ungetc (c, stdin);
		      strbuf[0] = '-';
		      strbuf[1] = '0';
		      strbuf[2] = 'x';
		      stridx = 3;
		    }
		  else
		    {
		      ungetc (c, stdin);
		      do_sub ();
		    }
		  break;
		case '*':
		  do_mul ();
		  break;
		case 'm':
		  do_mulm ();
		  break;
		case '/':
		  do_div ();
		  break;
		case '%':
		  do_rem ();
		  break;
		case '^':
		  do_powm ();
		  break;
		case '<':
		  do_lshift ();
		  break;
		case '>':
		  do_rshift ();
		  break;
		case 'I':
		  do_inv ();
		  break;
		case 'G':
		  do_gcd ();
		  break;
		case 'i':	/* dummy */
		  if (!stackidx)
		    fputs ("stack underflow\n", stderr);
		  else
		    {
		      mpi_release (stack[stackidx - 1]);
		      stackidx--;
		    }
		  break;
		case 'd':	/* duplicate the tos */
		  if (!stackidx)
		    fputs ("stack underflow\n", stderr);
		  else if (stackidx < STACKSIZE)
		    {
		      mpi_release (stack[stackidx]);
		      stack[stackidx] = mpi_copy (stack[stackidx - 1]);
		      stackidx++;
		    }
		  else
		    fputs ("stack overflow\n", stderr);
		  break;
		case 'r':	/* swap top elements */
		  if (stackidx < 2)
		    fputs ("stack underflow\n", stderr);
		  else if (stackidx < STACKSIZE)
		    {
		      gcry_mpi_t tmp = stack[stackidx-1];
                      stack[stackidx-1] = stack[stackidx - 2];
                      stack[stackidx-2] = tmp;
		    }
		  break;
                case 'b':
                  do_nbits ();
                  break;
                case 'P':
                  do_primecheck ();
                  break;
		case 'c':
		  for (i = 0; i < stackidx; i++)
                    {
                      mpi_release (stack[i]); stack[i] = NULL;
                    }
		  stackidx = 0;
		  break;
		case 'p':	/* print the tos */
		  if (!stackidx)
		    puts ("stack is empty");
		  else
		    {
		      print_mpi (stack[stackidx - 1]);
		      putchar ('\n');
		    }
		  break;
		case 'f':	/* print the stack */
		  for (i = stackidx - 1; i >= 0; i--)
		    {
		      printf ("[%2d]: ", i);
		      print_mpi (stack[i]);
		      putchar ('\n');
		    }
		  break;
                case '?':
                  print_help ();
                  break;
		default:
		  fputs ("invalid operator\n", stderr);
		}
	    }
	}
      else if (state == 1) /* In a number. */
	{
	  if (!isxdigit (c))
	    {
              /* Store the number */
	      state = 0;
	      ungetc (c, stdin);
	      if (stridx < sizeof strbuf)
		strbuf[stridx] = 0;

	      if (stackidx < STACKSIZE)
		{
		  if (!stack[stackidx])
		    stack[stackidx] = mpi_new (0);
		  if (scan_mpi (stack[stackidx], strbuf))
		    fputs ("invalid number\n", stderr);
		  else
		    stackidx++;
		}
	      else
		fputs ("stack overflow\n", stderr);
	    }
	  else
	    { /* Store a digit.  */
	      if (stridx < sizeof strbuf - 1)
		strbuf[stridx++] = c;
	      else if (stridx == sizeof strbuf - 1)
		{
		  strbuf[stridx] = 0;
		  fputs ("input too large - truncated\n", stderr);
		  stridx++;
		}
	    }
	}
      else if (state == 2) /* In a comment. */
        {
          if (c == '\n')
            state = 0;
        }

    }

  for (i = 0; i < stackidx; i++)
    mpi_release (stack[i]);
  return 0;
}
コード例 #30
0
ファイル: tls_g.c プロジェクト: 1ack/Impala
static void
tlsg_thr_init( void )
{
	gcry_control (GCRYCTL_SET_THREAD_CBS, &tlsg_thread_cbs);
}