int
install_package(const char *root_path)
{
    ui_set_background(BACKGROUND_ICON_INSTALLING);
    ui_print("Finding update package...\n");
    ui_show_indeterminate_progress();
    LOGI("Update location: %s\n", root_path);

    if (ensure_root_path_mounted(root_path) != 0) {
        LOGE("Can't mount %s\n", root_path);
        return INSTALL_CORRUPT;
    }

    char path[PATH_MAX] = "";
    if (translate_root_path(root_path, path, sizeof(path)) == NULL) {
        LOGE("Bad path %s\n", root_path);
        return INSTALL_CORRUPT;
    }

    ui_print("Opening update package...\n");
    LOGI("Update file path: %s\n", path);

    int numKeys;
    RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
    if (loadedKeys == NULL) {
        LOGE("Failed to load keys\n");
        return INSTALL_CORRUPT;
    }
    LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);

    // Give verification half the progress bar...
    ui_print("Verifying update package...\n");
    ui_show_progress(
            VERIFICATION_PROGRESS_FRACTION,
            VERIFICATION_PROGRESS_TIME);

    int err;
    err = verify_file(path, loadedKeys, numKeys);
    free(loadedKeys);
    LOGI("verify_file returned %d\n", err);
    if (err != VERIFY_SUCCESS) {
        LOGE("signature verification failed\n");
        return INSTALL_CORRUPT;
    }

    /* Try to open the package.
     */
    ZipArchive zip;
    err = mzOpenZipArchive(path, &zip);
    if (err != 0) {
        LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
        return INSTALL_CORRUPT;
    }

    /* Verify and install the contents of the package.
     */
    int status = handle_update_package(path, &zip);
    mzCloseZipArchive(&zip);
    return status;
}
예제 #2
0
파일: sec-mod.c 프로젝트: xyz12810/ocserv
static void check_other_work(sec_mod_st *sec)
{
	if (need_exit) {
		unsigned i;

		for (i = 0; i < sec->key_size; i++) {
			gnutls_privkey_deinit(sec->key[i]);
		}

		sec_mod_client_db_deinit(sec);
		tls_cache_deinit(&sec->tls_db);
		talloc_free(sec);
		exit(0);
	}

	if (need_reload) {
		seclog(sec, LOG_DEBUG, "reloading configuration");
		reload_cfg_file(sec, sec->perm_config, 0);
		sec->config = sec->perm_config->config;
		load_keys(sec, 0);
		need_reload = 0;
	}

	if (need_maintainance) {
		seclog(sec, LOG_DEBUG, "performing maintenance");
		cleanup_client_entries(sec);
		expire_tls_sessions(sec);
		seclog(sec, LOG_DEBUG, "active sessions %d", 
			sec_mod_client_db_elems(sec));
		alarm(MAINTAINANCE_TIME);
		need_maintainance = 0;
	}
}
예제 #3
0
void diff (const char* keyfile, const char* filename)
{
	keys_t		keys;
	load_keys(keyfile, &keys);

	// Open the file
	std::ifstream	in(filename);
	if (!in) {
		perror(filename);
		std::exit(1);
	}
	in.exceptions(std::fstream::badbit);

	// Read the header to get the nonce and determine if it's actually encrypted
	char		header[22];
	in.read(header, 22);
	if (!in || in.gcount() != 22 || memcmp(header, "\0GITCRYPT\0", 10) != 0) {
		// File not encrypted - just copy it out to stdout
		std::cout.write(header, in.gcount()); // don't forget to include the header which we read!
		char	buffer[1024];
		while (in) {
			in.read(buffer, sizeof(buffer));
			std::cout.write(buffer, in.gcount());
		}
		return;
	}

	process_stream(in, std::cout, &keys.enc, reinterpret_cast<uint8_t*>(header + 10));
}
예제 #4
0
void manage_keys(DHT *dht)
{
    const uint32_t KEYS_SIZE = crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES;
    uint8_t keys[KEYS_SIZE];

    FILE *keys_file = fopen("key", "r");

    if (keys_file != NULL) {
        /* If file was opened successfully -- load keys,
           otherwise save new keys */
        size_t read_size = fread(keys, sizeof(uint8_t), KEYS_SIZE, keys_file);

        if (read_size != KEYS_SIZE) {
            printf("Error while reading the key file\nExiting.\n");
            exit(1);
        }

        load_keys(dht->c, keys);
        printf("Keys loaded successfully.\n");
    } else {
        new_keys(dht->c);
        save_keys(dht->c, keys);
        keys_file = fopen("key", "w");

        if (fwrite(keys, sizeof(uint8_t), KEYS_SIZE, keys_file) != KEYS_SIZE) {
            printf("Error while writing the key file.\nExiting.\n");
            exit(1);
        }

        printf("Keys saved successfully.\n");
    }

    fclose(keys_file);
}
예제 #5
0
static int
really_install_package(const char *path)
{
    ui_set_background(BACKGROUND_ICON_INSTALLING);
    ui_print("正在查找升级包...\n");
    ui_show_indeterminate_progress();
    LOGI("Update location: %s\n", path);

    if (ensure_path_mounted(path) != 0) {
        LOGE("Can't mount %s\n", path);
        return INSTALL_CORRUPT;
    }

    ui_print("正在打开升级包...\n");

    int err;

    if (signature_check_enabled) {
        int numKeys;
        RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
        if (loadedKeys == NULL) {
            LOGE("Failed to load keys\n");
            return INSTALL_CORRUPT;
        }
        LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);

        // Give verification half the progress bar...
        ui_print("正在校验升级包...\n");
        ui_show_progress(
                VERIFICATION_PROGRESS_FRACTION,
                VERIFICATION_PROGRESS_TIME);

        err = verify_file(path, loadedKeys, numKeys);
        free(loadedKeys);
        LOGI("verify_file returned %d\n", err);
        if (err != VERIFY_SUCCESS) {
            LOGE("signature verification failed\n");
            ui_show_text(1);
            if (!confirm_selection("Install Untrusted Package?", "确认 - 安装不严格的zip卡刷包"))
                return INSTALL_CORRUPT;
        }
    }

    /* Try to open the package.
     */
    ZipArchive zip;
    err = mzOpenZipArchive(path, &zip);
    if (err != 0) {
        LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
        return INSTALL_CORRUPT;
    }

    /* Verify and install the contents of the package.
     */
    ui_print("正在安装更新...\n");
    return try_update_binary(path, &zip);
}
예제 #6
0
int
cli_init (void) {
	if (load_keys())
		return 1;

	if (alloc_handlers())
		return 1;

	add_handler(LIST+PATHS, NULL);
	add_handler(LIST+PATHS+FMT, NULL);
	add_handler(LIST+PATHS+RAW+FMT, NULL);
	add_handler(LIST+PATH, NULL);
	add_handler(LIST+STATUS, NULL);
	add_handler(LIST+DAEMON, NULL);
	add_handler(LIST+MAPS, NULL);
	add_handler(LIST+MAPS+STATUS, NULL);
	add_handler(LIST+MAPS+STATS, NULL);
	add_handler(LIST+MAPS+FMT, NULL);
	add_handler(LIST+MAPS+RAW+FMT, NULL);
	add_handler(LIST+MAPS+TOPOLOGY, NULL);
	add_handler(LIST+MAPS+JSON, NULL);
	add_handler(LIST+TOPOLOGY, NULL);
	add_handler(LIST+MAP+TOPOLOGY, NULL);
	add_handler(LIST+MAP+JSON, NULL);
	add_handler(LIST+MAP+FMT, NULL);
	add_handler(LIST+MAP+RAW+FMT, NULL);
	add_handler(LIST+CONFIG, NULL);
	add_handler(LIST+BLACKLIST, NULL);
	add_handler(LIST+DEVICES, NULL);
	add_handler(LIST+WILDCARDS, NULL);
	add_handler(ADD+PATH, NULL);
	add_handler(DEL+PATH, NULL);
	add_handler(ADD+MAP, NULL);
	add_handler(DEL+MAP, NULL);
	add_handler(SWITCH+MAP+GROUP, NULL);
	add_handler(RECONFIGURE, NULL);
	add_handler(SUSPEND+MAP, NULL);
	add_handler(RESUME+MAP, NULL);
	add_handler(RESIZE+MAP, NULL);
	add_handler(RESET+MAP, NULL);
	add_handler(RELOAD+MAP, NULL);
	add_handler(DISABLEQ+MAP, NULL);
	add_handler(RESTOREQ+MAP, NULL);
	add_handler(DISABLEQ+MAPS, NULL);
	add_handler(RESTOREQ+MAPS, NULL);
	add_handler(REINSTATE+PATH, NULL);
	add_handler(FAIL+PATH, NULL);
	add_handler(QUIT, NULL);
	add_handler(SHUTDOWN, NULL);
	add_handler(GETPRSTATUS+MAP, NULL);
	add_handler(SETPRSTATUS+MAP, NULL);
	add_handler(UNSETPRSTATUS+MAP, NULL);
	add_handler(FORCEQ+DAEMON, NULL);
	add_handler(RESTOREQ+DAEMON, NULL);

	return 0;
}
예제 #7
0
static int
really_install_package(const char *path, int* wipe_cache)
{
    ui_set_background(BACKGROUND_ICON_INSTALLING);
    ui_print("Finding update package...\n");
    // Give verification half the progress bar...
    // ui_reset_progress();
    // ui_show_progress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
    ui_show_indeterminate_progress();

    LOGI("Update location: %s\n", path);

    if (ensure_path_mounted(path) != 0) {
        LOGE("Can't mount %s\n", path);
        return INSTALL_CORRUPT;
    }

    ui_print("Opening update package...\n");

    int err;

    if (signature_check_enabled.value) {
        int numKeys;
        Certificate* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
        if (loadedKeys == NULL) {
            LOGE("Failed to load keys\n");
            return INSTALL_CORRUPT;
        }
        LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);

        ui_print("Verifying update package...\n");

        err = verify_file(path, loadedKeys, numKeys);
        free(loadedKeys);
        LOGI("verify_file returned %d\n", err);
        if (err != VERIFY_SUCCESS) {
            LOGE("signature verification failed\n");
            return  INSTALL_CORRUPT;
        }
    }

    /* Try to open the package.
     */
    ZipArchive zip;
    err = mzOpenZipArchive(path, &zip);
    if (err != 0) {
        LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
        return INSTALL_CORRUPT;
    }

    /* Verify and install the contents of the package.
     */
    ui_print("Installing update...\n");
    return try_update_binary(path, &zip, wipe_cache);
}
static int
really_install_package(const char *path, int* wipe_cache)
{
    ui->SetBackground(RecoveryUI::INSTALLING);
    ui->Print("Finding update package...\n");
    ui->SetProgressType(RecoveryUI::INDETERMINATE);
    LOGI("Update location: %s\n", path);

    if (ensure_path_mounted(path) != 0) {
        LOGE("Can't mount %s\n", path);
        return INSTALL_CORRUPT;
    }

    ui->Print("Opening update package...\n");

    int numKeys;
    RSAPublicKey* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
    if (loadedKeys == NULL) {
        LOGE("Failed to load keys\n");
        return INSTALL_CORRUPT;
    }
    LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);

    // Give verification half the progress bar...
    ui->Print("Verifying update package...\n");
    ui->SetProgressType(RecoveryUI::DETERMINATE);
    ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);

    int err;
    err = verify_file(path, loadedKeys, numKeys);
    free(loadedKeys);
    LOGI("verify_file returned %d\n", err);
    if (err != VERIFY_SUCCESS) {
        LOGE("signature verification failed\n");
        return INSTALL_CORRUPT;
    }

    /* Try to open the package.
     */
    ZipArchive zip;
    err = mzOpenZipArchive(path, &zip);
    if (err != 0) {
        LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
        return INSTALL_CORRUPT;
    }

    /* Verify and install the contents of the package.
     */
    ui->Print("Installing update...\n");
    return try_update_binary(path, &zip, wipe_cache);
}
예제 #9
0
int
main (int argc, char *const *argv)
{
  unsigned int error_count = 0;
  struct MHD_Daemon *d;

  gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
#ifdef GCRYCTL_INITIALIZATION_FINISHED
  gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
#endif
  if (0 != curl_global_init (CURL_GLOBAL_ALL))
    {
      fprintf (stderr, "Error: %s\n", strerror (errno));
      return 77;
    }
  load_keys ("host1", ABS_SRCDIR "/host1.crt", ABS_SRCDIR "/host1.key");
  load_keys ("host2", ABS_SRCDIR "/host2.crt", ABS_SRCDIR "/host2.key");
  d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | MHD_USE_ERROR_LOG,
                        4233,
                        NULL, NULL,
                        &http_ahc, NULL,
                        MHD_OPTION_HTTPS_CERT_CALLBACK, &sni_callback,
                        MHD_OPTION_END);
  if (d == NULL)
    {
      fprintf (stderr, MHD_E_SERVER_INIT);
      return -1;
    }
  if (0 != do_get ("https://host1:4233/"))
    error_count++;
  if (0 != do_get ("https://host2:4233/"))
    error_count++;

  MHD_stop_daemon (d);
  curl_global_cleanup ();
  return (0 != error_count) ? 1 : 0;
}
예제 #10
0
// Decrypt contents of stdin and write to stdout
void smudge (const char* keyfile)
{
	keys_t		keys;
	load_keys(keyfile, &keys);

	// Read the header to get the nonce and make sure it's actually encrypted
	char		header[22];
	std::cin.read(header, 22);
	if (!std::cin || std::cin.gcount() != 22 || memcmp(header, "\0GITCRYPT\0", 10) != 0) {
		std::clog << "File not encrypted\n";
		std::exit(1);
	}

	process_stream(std::cin, std::cout, &keys.enc, reinterpret_cast<uint8_t*>(header + 10));
}
예제 #11
0
/**
 * load_properties
 *
 * Description:
 * loads the game properties from a file
 *
 * Returns:
 * TRUE if the properties can be loaded, FALSE otherwise
 **/
gboolean
load_properties (void)
{
  gchar *cname = NULL;
  gint i;
  gchar *bgcolour;

  load_keys ();

  bgcolour = games_conf_get_string_with_default (KEY_PREFERENCES_GROUP,
                                                 KEY_BACKGROUND_COLOR, "#7590AE");
  gdk_color_parse (bgcolour, &properties.bgcolour);
  set_background_color (properties.bgcolour);

  properties.themename = games_conf_get_string_with_default (KEY_PREFERENCES_GROUP,
                                                             KEY_THEME, "robots");

  cname = games_conf_get_string_with_default (KEY_PREFERENCES_GROUP,
                                              KEY_CONFIGURATION, "classic_robots");

  properties.selected_config = 0;
  for (i = 0; i < num_game_configs (); ++i) {
    if (!strcmp (cname, game_config_name (i))) {
      properties.selected_config = i;
      break;
    }
  }
  g_free (cname);

  properties.safe_moves = games_conf_get_boolean (KEY_PREFERENCES_GROUP,
						  KEY_SAFE_MOVES, NULL);
  properties.super_safe_moves = games_conf_get_boolean (KEY_PREFERENCES_GROUP,
						        KEY_SUPER_SAFE_MOVES,
						        NULL);
  properties.sound = games_conf_get_boolean (KEY_PREFERENCES_GROUP,
                                             KEY_ENABLE_SOUND, NULL);
  properties.show_toolbar = games_conf_get_boolean (KEY_PREFERENCES_GROUP,
                                                    KEY_SHOW_TOOLBAR, NULL);

  games_sound_enable (properties.sound);
  set_game_graphics (properties.themename);
  set_game_config (properties.selected_config);
  keyboard_set (properties.keys);
  return TRUE;
}
예제 #12
0
/**
 * load_properties
 *
 * Description:
 * loads the game properties from a file
 *
 * Returns:
 * TRUE if the properties can be loaded, FALSE otherwise
 **/
gboolean
load_properties (void)
{
  gchar *cname = NULL;
  gint i;
  gchar *bgcolour, *config;

  load_keys ();

  bgcolour = g_settings_get_string (settings, KEY_BACKGROUND_COLOR);
  gdk_rgba_parse (&properties.bgcolour, bgcolour);
  set_background_color (properties.bgcolour);

  properties.themename = g_settings_get_string (settings, KEY_THEME);

  cname = g_settings_get_string (settings, KEY_CONFIGURATION);

  properties.selected_config = 0;
  for (i = 0; i < num_game_configs (); ++i) {
    config = game_config_name (i);
    if (!strcmp (cname, config)) {
      g_free (config);
      properties.selected_config = i;
      break;
    }
    g_free (config);
  }
  g_free (cname);

  properties.safe_moves = g_settings_get_boolean (settings,
						  KEY_SAFE_MOVES);
  properties.super_safe_moves = g_settings_get_boolean (settings,
						        KEY_SUPER_SAFE_MOVES);
  properties.sound = g_settings_get_boolean (settings,
                                             KEY_ENABLE_SOUND);
  properties.show_toolbar = g_settings_get_boolean (settings,
                                                    KEY_SHOW_TOOLBAR);

  load_game_graphics ();
  set_game_config (properties.selected_config);
  keyboard_set (properties.keys);
  return TRUE;
}
예제 #13
0
파일: pdsa.c 프로젝트: pete/freenote-probe
/**
	load_probekeys
	Loads public and private keys for the probe.  If it cannot load them,
	it generates and saves them.  Returns 0 if we get actual keys and -1 if
	no keys could be loaded or generated.
*/
static int load_probekeys()
{
	int r;
	char *pubfn, *privfn;

	pubfn = fm_abs(FM_KEY_PROBE_PUBLIC);
	privfn = fm_abs(FM_KEY_PROBE_PRIVATE);
	r = load_keys(pubfn, privfn, &probe);

	if(r == -1 && DSA_generate_key(probe)) {
		save_keys(pubfn, privfn, probe);
		r = 0;
	}

	free(pubfn);
	free(privfn);

	return r;
}
예제 #14
0
int main(int argc, char **argv) {

	int o;
	opterr = 0;
	
	while ((o = getopt(argc, argv, "v")) != EOF) {
		switch (o) {
		case 'v':{
			set_debug() ;
			break;
		}
		default:{
			}
		}
	}
	load_keys("/etc/keymgr/keys") ;
	// printf("%s\n",get_key("duarte_laptop") ) ;
	distribute_keys() ;
	return(0) ;

}
예제 #15
0
/* load the messenger from data of size length. */
int Messenger_load(uint8_t * data, uint32_t length)
{
    if (length == ~0)
        return -1;
    if (length < crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES + sizeof(uint32_t) * 2)
        return -1;
    length -= crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES + sizeof(uint32_t) * 2;
    load_keys(data);
    data += crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES;
    uint32_t size;
    memcpy(&size, data, sizeof(size));
    data += sizeof(size);

    if (length < size)
        return -1;
    length -= size;
    if (DHT_load(data, size) == -1)
        return -1;
    data += size;
    memcpy(&size, data, sizeof(size));
    data += sizeof(size);
    if (length != size || length % sizeof(Friend) != 0)
        return -1;

    Friend * temp = malloc(size);
    memcpy(temp, data, size);

    uint16_t num = size / sizeof(Friend);

    uint32_t i;
    for (i = 0; i < num; ++i) {
        if(temp[i].status != 0) {
            int fnum = m_addfriend_norequest(temp[i].client_id);
            setfriendname(fnum, temp[i].name);
            /* set_friend_statusmessage(fnum, temp[i].statusmessage, temp[i].statusmessage_length); */
        }
    }
    free(temp);
    return 0;
}
int manage_keys(DHT *dht, char *keys_file_path)
{
    const uint32_t KEYS_SIZE = crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES;
    uint8_t keys[KEYS_SIZE];
    FILE *keys_file;

    // Check if file exits, proceed to open and load keys
    keys_file = fopen(keys_file_path, "r");

    if (keys_file != NULL) {
        size_t read_size = fread(keys, sizeof(uint8_t), KEYS_SIZE, keys_file);

        if (read_size != KEYS_SIZE) {
            return 0;
        }

        load_keys(dht->c, keys);
    } else {
        // Otherwise save new keys
        new_keys(dht->c);
        save_keys(dht->c, keys);

        keys_file = fopen(keys_file_path, "w");

        size_t write_size = fwrite(keys, sizeof(uint8_t), KEYS_SIZE, keys_file);

        if (write_size != KEYS_SIZE) {
            return 0;
        }
    }

    fclose(keys_file);

    // We want our DHT public key to be the same as our internal one since this is a bootstrap server
    memcpy(dht->self_public_key, dht->c->self_public_key, crypto_box_PUBLICKEYBYTES);
    memcpy(dht->self_secret_key, dht->c->self_secret_key, crypto_box_SECRETKEYBYTES);

    return 1;
}
예제 #17
0
파일: pdsa.c 프로젝트: pete/freenote-probe
/** dsa_init - this is called at startup.  Errors will return -1, and
 *  should be caught by the try() macro
 */
int dsa_init()
{
	char *fn; 

	ou_seed();	/* initialize the random seed, cannot fail */

	dispatch = NULL;

	probe = DSA_generate_parameters(DSA_KEYLEN, NULL, 0, NULL, NULL, NULL, 
		NULL);
	if(probe == NULL) 
		return -1;

	try(load_probekeys());

	dispatch = DSA_generate_parameters(DSA_KEYLEN, NULL, 0, NULL, NULL, 
		NULL, NULL);
	if(dispatch == NULL)
		return 0;	/* no big deal, yet */

	fn = fm_abs(FM_KEY_DISPATCH_PUBLIC);

	if(load_keys(fn, NULL, &dispatch) == -1) {
		DSA_free(dispatch);
		dispatch = NULL;
	}

	free(fn);
	
	return 0;
}

/** dsa_close -  frees up memory used for key signing and verification, run
 * this at exit */
void dsa_close()
{
	DSA_free(probe);
	DSA_free(dispatch);
}
void manage_keys(DHT *dht, char *keys_file)
{
    const uint32_t KEYS_SIZE = crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES;
    uint8_t keys[KEYS_SIZE];
    struct stat existence;
    FILE *keysf;

    /* Check if file exits, proceed to open and load keys */
    if (stat(keys_file, &existence) >= 0) {
        keysf = fopen(keys_file, "r");
        size_t read_size = fread(keys, sizeof(uint8_t), KEYS_SIZE, keysf);

        if (read_size != KEYS_SIZE) {
            printf("Error while reading the key file\nExiting.\n");
            exit(1);
        } else {
            printf("Keys loaded successfully\n");
        }

        load_keys(dht->c, keys);

    } else {
        /* otherwise save new keys */
        /* Silly work-around to ignore any errors coming from new_keys() */
        new_keys(dht->c);
        save_keys(dht->c, keys);
        keysf = fopen(keys_file, "w");

        if (fwrite(keys, sizeof(uint8_t), KEYS_SIZE, keysf) != KEYS_SIZE) {
            printf("Error while writing the key file.\nExiting.\n");
            exit(1);
        } else {
            printf("Keys saved successfully\n");
        }
    }

    fclose(keysf);
}
예제 #19
0
파일: pdsa.c 프로젝트: pete/freenote-probe
/**
	save_dispatch_key
	Saves a base64 encoded key, as well as keeping it for future use.  Pass
	it a key in the form of a null-terminated string.
	Returns -1 for error, 0 for success.
*/
int save_dispatch_key(const char *key)
{
	int r;
	char *pub;

	if(dispatch != NULL)
		return 0;	/* We have ignored you! */

	dispatch = DSA_generate_parameters(DSA_KEYLEN, NULL, 0, NULL, NULL, 
		NULL, NULL);
	if(dispatch == NULL) {
		io_debug("%s:%s():%d  ", __FILE__, __func__, __LINE__);
		io_err("Not enough free memory!  The walls are closing in!\n");
		return -1;
	}

	pub = fm_abs(FM_KEY_DISPATCH_PUBLIC);

	r = !fm_write(FM_KEY_DISPATCH_PUBLIC, key, strlen(key));
	r |= load_keys(pub, NULL, &dispatch);
	free(pub);

	return r;
}
예제 #20
0
/* load the messenger from data of size length. */
int Messenger_load(Messenger *m, uint8_t *data, uint32_t length)
{
    if (length == ~0)
        return -1;

    if (length < crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES + sizeof(uint32_t) * 3)
        return -1;

    length -= crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES + sizeof(uint32_t) * 3;
    load_keys(data);
    data += crypto_box_PUBLICKEYBYTES + crypto_box_SECRETKEYBYTES;
    uint32_t nospam;
    memcpy(&nospam, data, sizeof(nospam));
    set_nospam(nospam);
    data += sizeof(nospam);
    uint32_t size;
    memcpy(&size, data, sizeof(size));
    data += sizeof(size);

    if (length < size)
        return -1;

    length -= size;

    if (DHT_load(data, size) == -1)
        return -1;

    data += size;
    memcpy(&size, data, sizeof(size));
    data += sizeof(size);

    if (length < size || size % sizeof(Friend) != 0)
        return -1;

    Friend *temp = malloc(size);
    memcpy(temp, data, size);

    uint16_t num = size / sizeof(Friend);

    uint32_t i;

    for (i = 0; i < num; ++i) {
        if (temp[i].status >= 3) {
            int fnum = m_addfriend_norequest(m, temp[i].client_id);
            setfriendname(m, fnum, temp[i].name);
            /* set_friend_statusmessage(fnum, temp[i].statusmessage, temp[i].statusmessage_length); */
        } else if (temp[i].status != 0) {
            /* TODO: this is not a good way to do this. */
            uint8_t address[FRIEND_ADDRESS_SIZE];
            memcpy(address, temp[i].client_id, crypto_box_PUBLICKEYBYTES);
            memcpy(address + crypto_box_PUBLICKEYBYTES, &(temp[i].friendrequest_nospam), sizeof(uint32_t));
            uint16_t checksum = address_checksum(address, FRIEND_ADDRESS_SIZE - sizeof(checksum));
            memcpy(address + crypto_box_PUBLICKEYBYTES + sizeof(uint32_t), &checksum, sizeof(checksum));
            m_addfriend(m, address, temp[i].info, temp[i].info_size);
        }
    }

    free(temp);
    data += size;
    length -= size;

    uint16_t small_size;

    if (length < sizeof(small_size))
        return -1;

    memcpy(&small_size, data, sizeof(small_size));
    data += sizeof(small_size);
    length -= sizeof(small_size);

    if (length != small_size)
        return -1;

    setname(m, data, small_size);

    return 0;
}
예제 #21
0
/**
 * apply_changes
 *
 * Description:
 * Applies the changes made by the user
 **/
static void
apply_changes (void)
{
  load_keys ();
  keyboard_set (properties.keys);
}
예제 #22
0
/**
 * Main function, starts the conftest daemon.
 */
int main(int argc, char *argv[])
{
	struct sigaction action;
	int status = 0;
	sigset_t set;
	int sig;
	char *suite_file = "suite.conf", *test_file = NULL;
	file_logger_t *logger;

	if (!library_init(NULL))
	{
		library_deinit();
		return SS_RC_LIBSTRONGSWAN_INTEGRITY;
	}
	if (!libhydra_init("conftest"))
	{
		libhydra_deinit();
		library_deinit();
		return SS_RC_INITIALIZATION_FAILED;
	}
	if (!libcharon_init("conftest"))
	{
		libcharon_deinit();
		libhydra_deinit();
		library_deinit();
		return SS_RC_INITIALIZATION_FAILED;
	}

	INIT(conftest,
		.creds = mem_cred_create(),
		.config = config_create(),
		.hooks = linked_list_create(),
		.loggers = linked_list_create(),
	);
	lib->credmgr->add_set(lib->credmgr, &conftest->creds->set);

	logger = file_logger_create("stdout");
	logger->set_options(logger, NULL, FALSE);
	logger->open(logger, FALSE, FALSE);
	logger->set_level(logger, DBG_ANY, LEVEL_CTRL);
	charon->bus->add_logger(charon->bus, &logger->logger);
	conftest->loggers->insert_last(conftest->loggers, logger);

	atexit(cleanup);

	while (TRUE)
	{
		struct option long_opts[] = {
			{ "help", no_argument, NULL, 'h' },
			{ "version", no_argument, NULL, 'v' },
			{ "suite", required_argument, NULL, 's' },
			{ "test", required_argument, NULL, 't' },
			{ 0,0,0,0 }
		};
		switch (getopt_long(argc, argv, "", long_opts, NULL))
		{
			case EOF:
				break;
			case 'h':
				usage(stdout);
				return 0;
			case 'v':
				printf("strongSwan %s conftest\n", VERSION);
				return 0;
			case 's':
				suite_file = optarg;
				continue;
			case 't':
				test_file = optarg;
				continue;
			default:
				usage(stderr);
				return 1;
		}
		break;
	}

	if (!load_configs(suite_file, test_file))
	{
		return 1;
	}
	load_loggers(logger);

	if (!lib->plugins->load(lib->plugins, NULL,
			conftest->test->get_str(conftest->test, "preload", "")))
	{
		return 1;
	}
	if (!charon->initialize(charon, PLUGINS))
	{
		return 1;
	}
	if (!load_certs(conftest->test, conftest->suite_dir))
	{
		return 1;
	}
	if (!load_keys(conftest->test, conftest->suite_dir))
	{
		return 1;
	}
	load_cdps(conftest->test);
	if (!load_hooks())
	{
		return 1;
	}
	charon->backends->add_backend(charon->backends, &conftest->config->backend);
	conftest->config->load(conftest->config, conftest->test);
	conftest->actions = actions_create();

	/* set up thread specific handlers */
	action.sa_handler = segv_handler;
	action.sa_flags = 0;
	sigemptyset(&action.sa_mask);
	sigaddset(&action.sa_mask, SIGINT);
	sigaddset(&action.sa_mask, SIGTERM);
	sigaddset(&action.sa_mask, SIGHUP);
	sigaction(SIGSEGV, &action, NULL);
	sigaction(SIGILL, &action, NULL);
	sigaction(SIGBUS, &action, NULL);
	action.sa_handler = SIG_IGN;
	sigaction(SIGPIPE, &action, NULL);
	pthread_sigmask(SIG_SETMASK, &action.sa_mask, NULL);

	/* start thread pool */
	charon->start(charon);

	/* handle SIGINT/SIGTERM in main thread */
	sigemptyset(&set);
	sigaddset(&set, SIGINT);
	sigaddset(&set, SIGHUP);
	sigaddset(&set, SIGTERM);
	sigprocmask(SIG_BLOCK, &set, NULL);

	while (sigwait(&set, &sig) == 0)
	{
		switch (sig)
		{
			case SIGINT:
			case SIGTERM:
				fprintf(stderr, "\nshutting down...\n");
				break;
			default:
				continue;
		}
		break;
	}
	return status;
}
int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Usage: %s [-sha256] [-ec | -f4 | -file <keys>] <package>\n", argv[0]);
        return 2;
    }
    Certificate* certs = NULL;
    int num_keys = 0;

    int argn = 1;
    while (argn < argc) {
        if (strcmp(argv[argn], "-sha256") == 0) {
            if (num_keys == 0) {
                fprintf(stderr, "May only specify -sha256 after key type\n");
                return 2;
            }
            ++argn;
            Certificate* cert = &certs[num_keys - 1];
            cert->hash_len = SHA256_DIGEST_SIZE;
        } else if (strcmp(argv[argn], "-ec") == 0) {
            ++argn;
            Certificate* cert = add_certificate(&certs, &num_keys, Certificate::EC);
            cert->ec = &test_ec_key;
        } else if (strcmp(argv[argn], "-e3") == 0) {
            ++argn;
            Certificate* cert = add_certificate(&certs, &num_keys, Certificate::RSA);
            cert->rsa = &test_key;
        } else if (strcmp(argv[argn], "-f4") == 0) {
            ++argn;
            Certificate* cert = add_certificate(&certs, &num_keys, Certificate::RSA);
            cert->rsa = &test_f4_key;
        } else if (strcmp(argv[argn], "-file") == 0) {
            if (certs != NULL) {
                fprintf(stderr, "Cannot specify -file with other certs specified\n");
                return 2;
            }
            ++argn;
            certs = load_keys(argv[argn], &num_keys);
            ++argn;
        } else if (argv[argn][0] == '-') {
            fprintf(stderr, "Unknown argument %s\n", argv[argn]);
            return 2;
        } else {
            break;
        }
    }

    if (argn == argc) {
        fprintf(stderr, "Must specify package to verify\n");
        return 2;
    }

    if (num_keys == 0) {
        certs = (Certificate*) calloc(1, sizeof(Certificate));
        if (certs == NULL) {
            fprintf(stderr, "Failure allocating memory for default certificate\n");
            return 1;
        }
        certs->key_type = Certificate::RSA;
        certs->rsa = &test_key;
        certs->ec = NULL;
        certs->hash_len = SHA_DIGEST_SIZE;
        num_keys = 1;
    }

    ui = new FakeUI();

    MemMapping map;
    if (sysMapFile(argv[argn], &map) != 0) {
        fprintf(stderr, "failed to mmap %s: %s\n", argv[argn], strerror(errno));
        return 4;
    }

    int result = verify_file(map.addr, map.length, certs, num_keys);
    if (result == VERIFY_SUCCESS) {
        printf("VERIFIED\n");
        return 0;
    } else if (result == VERIFY_FAILURE) {
        printf("NOT VERIFIED\n");
        return 1;
    } else {
        printf("bad return value\n");
        return 3;
    }
}
예제 #24
0
파일: pkcs11d.c 프로젝트: zhulianhai/pkcs11
int main(int argc, char **argv)
{
    CK_ULONG          nslots;
    CK_SLOT_ID        *pslots = NULL;
    CK_FUNCTION_LIST  *funcs = NULL;
    CK_UTF8CHAR_PTR   opt_pin = NULL;
    CK_ULONG          opt_pin_len = 0;
    CK_RV             rc;
    CK_ULONG          opt_slot = -1;
    CK_SESSION_HANDLE h_session;
    char *opt_module = NULL, *opt_dir = NULL;
    /* struct sockaddr_un sockaddr; */
    int long_optind = 0;
    int fd, verbose = 0;
    key_id_t *rsa_keys, *ec_keys;
    CK_ULONG rsa_len = 0, ec_len = 0, i;

    init_crypto();

    while (1) {
        char c = getopt_long(argc, argv, "d:hp:s:m:v",
                             options, &long_optind);
        if (c == -1)
            break;
        switch (c) {
            case 'd':
                opt_dir = optarg;
                break;
            case 'p':
                opt_pin = (CK_UTF8CHAR_PTR) strdup(optarg);
                if(opt_pin) {
                    opt_pin_len = strlen(optarg);
                }
                break;
            case 's':
                opt_slot = (CK_SLOT_ID) atoi(optarg);
                break;
            case 'm':
                opt_module = optarg;
                break;
            case 'v':
                verbose = 1;
                break;
            case 'h':
            default:
                print_usage_and_die(app_name, options, option_help);
        }
    }

    rc = pkcs11_load_init(opt_module, opt_dir, stderr, &funcs);
    if (rc != CKR_OK) {
        return rc;
    }

    rc = pkcs11_get_slots(funcs, stderr, &pslots, &nslots);
    if (rc != CKR_OK) {
        return rc;
    }

    if(opt_slot == -1) {
        if(nslots < 1) {
            /* No slots */
            return -1;
        } else {
            opt_slot = pslots[0];
        }
    } else {
        /* Check selected slot is in pslots */
    }

    fprintf(stderr, "Slot: %ld\n", opt_slot);
    rc = pkcs11_login_session(funcs, stderr, opt_slot, &h_session,
                              CK_TRUE, CKU_USER, opt_pin, opt_pin_len);
    if (rc != CKR_OK) {
        show_error(stderr, "Login", rc);
        return rc;
    }
    
    load_keys(funcs, h_session, CKK_RSA, &rsa_keys, &rsa_len);
    load_keys(funcs, h_session, CKK_EC,  &ec_keys,  &ec_len);


    /* fd = nw_unix_server("pkcs11d.sock", &sockaddr, 0, 0, 0, 64); */
    /* close(fd); */
    fd = nw_tcp_server(1234, 0, 64);
    
    do {
        struct sockaddr address;
        socklen_t a_len = sizeof(address);
        int s = accept(fd, &address, &a_len);
        BIO *b = BIO_new_socket(s, BIO_NOCLOSE);
        BIO *buf = BIO_new(BIO_f_buffer());
        b = BIO_push(buf, b);
        char buffer[4096], sig[4096], keyid[KEY_ID_SIZE + 1];
        int l, slen = 0, plen = 0;
        CK_KEY_TYPE type;
        CK_ATTRIBUTE_TYPE operation;
        EVP_PKEY *pkey = NULL;

        l = BIO_gets(b, buffer, sizeof(buffer));
        if(l <= 0) {
            fprintf(stderr, "Error reading query line\n");
            goto end;
        }

        if(strncmp(buffer, "POST /sign/rsa/", 15) == 0) {
            memcpy(keyid, buffer + 15, KEY_ID_SIZE - 1);
            type = CKK_RSA;
            operation = CKA_SIGN;
        } else if(strncmp(buffer, "POST /decrypt/rsa/", 18) == 0) {
            memcpy(keyid, buffer + 18, KEY_ID_SIZE - 1);
            type = CKK_RSA;
            operation = CKA_DECRYPT;
        } else if(strncmp(buffer, "POST /sign/ec/", 14) == 0) {
            memcpy(keyid, buffer + 14, KEY_ID_SIZE - 1);
            type = CKK_EC;
            operation = CKA_SIGN;
        } else {
            goto end;
        }
        keyid[KEY_ID_SIZE] = '\0';

        l = BIO_gets(b, buffer, sizeof(buffer));
        if((l <= 0) || strncmp(buffer, "Content-Length: ", 16) != 0) {
            fprintf(stderr, "Invalid content length line = %s\n", buffer);
            goto end;
        }
        plen = atoi(buffer + 16);
        l = BIO_gets(b, buffer, sizeof(buffer));
        l = BIO_read(b, buffer, plen);
        if(l < plen) {
            fprintf(stderr, "Error reading payload\n");
            goto end;
        }


        if(type == CKK_RSA) {
            for(i = 0; (i < rsa_len) && (pkey == NULL); i++) {
                if(strncmp(rsa_keys[i].id, keyid, KEY_ID_SIZE - 1) == 0) {
                    pkey = rsa_keys[i].key;
                }
            }
        } else if(type == CKK_EC) {
            for(i = 0; (i < ec_len) && (pkey == NULL); i++) {
                if(strncmp(ec_keys[i].id, keyid, KEY_ID_SIZE - 1) == 0) {
                    pkey = ec_keys[i].key;
                }
            }
        }
        if(pkey == NULL) {
            fprintf(stderr, "Key not found\n");
            goto end;
        } else if(verbose) {
            fprintf(stderr, "Key '%s'found\n", keyid);
        }
        
        if(type == CKK_RSA && operation == CKA_SIGN) {
            if(verbose) {
                fprintf(stderr, "RSA signature operation requested\n");
            }
            l = RSA_private_encrypt(plen, (unsigned char *)buffer, (unsigned char *)sig,
                                    EVP_PKEY_get1_RSA(pkey), RSA_PKCS1_PADDING);
        } else if(type == CKK_RSA && operation == CKA_DECRYPT) {
            if(verbose) {
                fprintf(stderr, "RSA decryption operation requested\n");
            }
            l = RSA_private_decrypt(plen, (unsigned char *)buffer, (unsigned char *)sig,
                                    EVP_PKEY_get1_RSA(pkey), RSA_PKCS1_PADDING);
        } else if (type == CKK_EC && operation == CKA_SIGN) {
            unsigned char *ptr = (unsigned char *)sig;
            ECDSA_SIG *s = ECDSA_do_sign((unsigned char *)buffer, plen, EVP_PKEY_get1_EC_KEY(pkey));
            l = i2d_ECDSA_SIG(s, &ptr);
            ECDSA_SIG_free(s);
        } else {
            if(verbose) {
                fprintf(stderr, "Invalid operation requested\n");
            }
            goto end;
        }

        slen = l;
        if(l <= 0) {
            if(verbose) {
                fprintf(stderr, "Error unsuccessful\n");
            }
            goto end;
        } else if(verbose) {
            fprintf(stderr, "Operation successful\n");
        }

        BIO_printf(b, "200 Ok\r\n");
        BIO_printf(b, "Content-Length: %d\r\n\r\n", slen);

        l = BIO_write(b, sig, slen);
        BIO_flush(b);

        i= 0;
        /*
        for(i = 0; i < rsa_len; i++) {
            BIO_write(b, rsa_keys[i].id, KEY_ID_SIZE);
            BIO_write(b, "\n", 1);
            PEM_write_bio_RSAPrivateKey(b, EVP_PKEY_get1_RSA(rsa_keys[i].key), NULL, NULL, 0, NULL, NULL);
        }
        for(i = 0; i < ec_len; i++) {
            BIO_write(b, ec_keys[i].id, KEY_ID_SIZE);
            BIO_write(b, "\n", 1);
            PEM_write_bio_ECPrivateKey(b, EVP_PKEY_get1_EC_KEY(ec_keys[i].key), NULL, NULL, 0, NULL, NULL);
        }
        */


    end:
        close(s);
        BIO_free(b);
    } while(1);

    close(fd);

    if(opt_pin) {
        funcs->C_CloseAllSessions(opt_slot);
        free(opt_pin);
    }

    rc = funcs->C_Finalize(NULL);
    if (rc != CKR_OK) {
        show_error(stderr, "C_Finalize", rc);
        return rc;
    }
    
    return rc;
}
예제 #25
0
int main(int argc, char *argv[])
{
	char *otp = NULL;
  char nandotp = 0;
	printf("wii-fsck\n");

	char wiiname[256] = {0};

	static const struct option wiifsck_options[] = {
		{ "help", no_argument, 0, 'h' },
		{ "version", no_argument, 0, 'V' },
		{ "name", required_argument, 0, 'n' },
		{ "otp", required_argument, 0, 'o' },
		{ "verbose", no_argument, 0, 'v' },
    { "nandotp", no_argument, 0, 'N' },
		{ 0, 0, 0, 0 }
	};
	int c = 0;
	int optionindex;
  
	while(c >= 0) {
		c = my_getopt_long(argc, argv, "-hvno:", wiifsck_options, &optionindex);
		switch (c) {
			case 'n':
				strncpy(wiiname, my_optarg, 255);
				break;
      case 'N':
        nandotp = 1;
        break;
			case 'v':
				verbosity_level++;
				break;
			case 'h':
				print_help();
				exit(0);
			case 'V':
				printf(WIIFSCK_VERSION_STRING);
				printf("\n");
				exit(0);
			case 'o':
				otp = strdup(my_optarg);
				break;
			case '?':
				printf("Invalid option -%c. Try -h\n", my_optopt);
				exit(-1);
			case 1:
				nand = rawnand_open(my_optarg);
				if (nand == NULL)
					fatal("Unable to open nand %s", argv[1]);
				break;
		}
	}
	
	if (nand == NULL) {
		printf("You must specify a NAND dump file. See -h\n");
		exit(-1);
	}

	if ((otp == NULL) && (nandotp == 0)) {
		if (wiiname[0] == 0) {
			strcpy(wiiname, "default");
		}
		printf("loading keys for wii %s...\n", wiiname);
		load_keys(wiiname);
	} else if (otp != NULL) {
		printf("loading keys from OTP %s...\n", otp);
		load_keys_otp(otp);
		 free(otp);
	} else {
    printf("loading keys from BackupMii nand dump...\n");
    load_keys_nand_otp(nand);
  } 

	printf("doing stuff, please wait...\n");

	printf("checking boot1...\n");
	boot1 = boot1_check(nand);

	printf("checking boot2...\n");
	boot2_load(nand, 0);
	boot2_sig = boot2_check_signature();
	boot2_cnt = boot2_check_contents();

	printf("checking second copy of boot2...\n");
	boot2_load(nand, 1);
	boot2c_sig = boot2_check_signature();
	boot2c_cnt = boot2_check_contents();
	
	printf("checking filesystem...\n");
	struct nandfs *fs = nandfs_mount(nand);
	titles_init(fs);
	uid_init(fs);

	printf("checking 1-2...\n");
	title_12 =  check_title_integrity(1, 2);


	printf("checking 1-2 IOS...\n");
	int title_12_tmd_size, title_12_ios_version;
	struct signed_tmd *title_12_tmd;

	get_signed_tmd_size(1, 2, &title_12_tmd_size);
	title_12_tmd = malloc(title_12_tmd_size);

	if(title_12_tmd == NULL)
		fatal("Could not allocate memory for 1-2 tmd");

	get_signed_tmd(1, 2, title_12_tmd, NULL);
	title_12_ios_version = title_12_tmd->data.sys_version & 0xffffffff;
	title_12_ios = check_title_integrity(1, title_12_ios_version);
	free(title_12_tmd);

	printf("checking channel validity...\n");
	iplsave_init(fs);
	chans_valid = check_channel_validity();

	printf("\nwii-fsck report:\n");
	print_result("boot1", boot1);
	print_result("boot2 signature", boot2_sig);
	print_result("boot2 contents", boot2_cnt);
	print_result("2nd boot2 signature", boot2c_sig);
	print_result("2nd boot2 contents", boot2c_cnt);

	printf("\n");
	print_title_result("System Menu", 1, 2, title_12);
	print_title_result("System Menu IOS", 1, title_12_ios_version, title_12_ios);
	printf("\n");
	print_result("Channel validity", chans_valid);
	
	return 0;
}
예제 #26
0
파일: cli.c 프로젝트: Chronic-Dev/gnutls
static void
init_global_tls_stuff (void)
{
  int ret;

  /* X509 stuff */
  if (gnutls_certificate_allocate_credentials (&xcred) < 0)
    {
      fprintf (stderr, "Certificate allocation memory error\n");
      exit (1);
    }

  if (x509_cafile != NULL)
    {
      ret = gnutls_certificate_set_x509_trust_file (xcred,
						    x509_cafile, x509ctype);
      if (ret < 0)
	{
	  fprintf (stderr, "Error setting the x509 trust file\n");
	}
      else
	{
	  printf ("Processed %d CA certificate(s).\n", ret);
	}
    }
#ifdef ENABLE_PKI
  if (x509_crlfile != NULL)
    {
      ret = gnutls_certificate_set_x509_crl_file (xcred, x509_crlfile,
						  x509ctype);
      if (ret < 0)
	{
	  fprintf (stderr, "Error setting the x509 CRL file\n");
	}
      else
	{
	  printf ("Processed %d CRL(s).\n", ret);
	}
    }
#endif

  load_keys ();

#ifdef ENABLE_OPENPGP
  if (pgp_keyring != NULL)
    {
      ret =
	gnutls_certificate_set_openpgp_keyring_file (xcred, pgp_keyring,
						     GNUTLS_OPENPGP_FMT_BASE64);
      if (ret < 0)
	{
	  fprintf (stderr, "Error setting the OpenPGP keyring file\n");
	}
    }
#endif

#ifdef ENABLE_SRP
  if (srp_username && srp_passwd)
    {
      /* SRP stuff */
      if (gnutls_srp_allocate_client_credentials (&srp_cred) < 0)
	{
	  fprintf (stderr, "SRP authentication error\n");
	}

      gnutls_srp_set_client_credentials_function (srp_cred,
						  srp_username_callback);
    }
#endif

#ifdef ENABLE_PSK
  /* PSK stuff */
  if (gnutls_psk_allocate_client_credentials (&psk_cred) < 0)
    {
      fprintf (stderr, "PSK authentication error\n");
    }

  if (psk_username && psk_key.data)
    {
      ret = gnutls_psk_set_client_credentials (psk_cred,
					       psk_username, &psk_key,
					       GNUTLS_PSK_KEY_HEX);
      if (ret < 0)
	{
	  fprintf (stderr, "Error setting the PSK credentials: %s\n",
		   gnutls_strerror (ret));
	}
    }
  gnutls_psk_set_client_credentials_function (psk_cred, psk_callback);
#endif

#ifdef ENABLE_ANON
  /* ANON stuff */
  if (gnutls_anon_allocate_client_credentials (&anon_cred) < 0)
    {
      fprintf (stderr, "Anonymous authentication error\n");
    }
#endif

}
예제 #27
0
int
main (void)
{
    int ret, sd, ii;
    gnutls_session_t session;
    gnutls_priority_t priorities_cache;
    char buffer[MAX_BUF + 1];
    gnutls_certificate_credentials_t xcred;
    /* Allow connections to servers that have OpenPGP keys as well.
     */

    gnutls_global_init ();

    load_keys ();

    /* X509 stuff */
    gnutls_certificate_allocate_credentials (&xcred);

    /* priorities */
    gnutls_priority_init( &priorities_cache, "NORMAL", NULL);


    /* sets the trusted cas file
     */
    gnutls_certificate_set_x509_trust_file (xcred, CAFILE, GNUTLS_X509_FMT_PEM);

    gnutls_certificate_client_set_retrieve_function (xcred, cert_callback);

    /* Initialize TLS session
     */
    gnutls_init (&session, GNUTLS_CLIENT);

    /* Use default priorities */
    gnutls_priority_set (session, priorities_cache);

    /* put the x509 credentials to the current session
     */
    gnutls_credentials_set (session, GNUTLS_CRD_CERTIFICATE, xcred);

    /* connect to the peer
     */
    sd = tcp_connect ();

    gnutls_transport_set_ptr (session, (gnutls_transport_ptr_t) sd);

    /* Perform the TLS handshake
     */
    ret = gnutls_handshake (session);

    if (ret < 0)
    {
        fprintf (stderr, "*** Handshake failed\n");
        gnutls_perror (ret);
        goto end;
    }
    else
    {
        printf ("- Handshake was completed\n");
    }

    gnutls_record_send (session, MSG, strlen (MSG));

    ret = gnutls_record_recv (session, buffer, MAX_BUF);
    if (ret == 0)
    {
        printf ("- Peer has closed the TLS connection\n");
        goto end;
    }
    else if (ret < 0)
    {
        fprintf (stderr, "*** Error: %s\n", gnutls_strerror (ret));
        goto end;
    }

    printf ("- Received %d bytes: ", ret);
    for (ii = 0; ii < ret; ii++)
    {
        fputc (buffer[ii], stdout);
    }
    fputs ("\n", stdout);

    gnutls_bye (session, GNUTLS_SHUT_RDWR);

end:

    tcp_close (sd);

    gnutls_deinit (session);

    gnutls_certificate_free_credentials (xcred);
    gnutls_priority_deinit( priorities_cache);

    gnutls_global_deinit ();

    return 0;
}
예제 #28
0
static int
really_install_package(const char *path, bool* wipe_cache, bool needs_mount)
{
    ui->SetBackground(RecoveryUI::INSTALLING_UPDATE);
    ui->Print("Finding update package...\n");
    // Give verification half the progress bar...
    ui->SetProgressType(RecoveryUI::DETERMINATE);
    ui->ShowProgress(VERIFICATION_PROGRESS_FRACTION, VERIFICATION_PROGRESS_TIME);
    LOGI("Update location: %s\n", path);

    // Map the update package into memory.
    ui->Print("Opening update package...\n");

    if (path && needs_mount) {
        if (path[0] == '@') {
            ensure_path_mounted(path+1);
        } else {
            ensure_path_mounted(path);
        }
    }

    MemMapping map;
    if (sysMapFile(path, &map) != 0) {
        LOGE("failed to map file\n");
        return INSTALL_CORRUPT;
    }

    int numKeys;
    Certificate* loadedKeys = load_keys(PUBLIC_KEYS_FILE, &numKeys);
    if (loadedKeys == NULL) {
        LOGE("Failed to load keys\n");
        return INSTALL_CORRUPT;
    }
    LOGI("%d key(s) loaded from %s\n", numKeys, PUBLIC_KEYS_FILE);

    ui->Print("Verifying update package...\n");

    int err;
    err = verify_file(map.addr, map.length, loadedKeys, numKeys);
    free(loadedKeys);
    LOGI("verify_file returned %d\n", err);
    if (err != VERIFY_SUCCESS) {
        LOGE("signature verification failed\n");
        sysReleaseMap(&map);
        return INSTALL_CORRUPT;
    }

    /* Try to open the package.
     */
    ZipArchive zip;
    err = mzOpenZipArchive(map.addr, map.length, &zip);
    if (err != 0) {
        LOGE("Can't open %s\n(%s)\n", path, err != -1 ? strerror(err) : "bad");
        sysReleaseMap(&map);
        return INSTALL_CORRUPT;
    }

    /* Verify and install the contents of the package.
     */
    ui->Print("Installing update...\n");
    ui->SetEnableReboot(false);
    int result = try_update_binary(path, &zip, wipe_cache);
    ui->SetEnableReboot(true);
    ui->Print("\n");

    sysReleaseMap(&map);

    return result;
}
예제 #29
0
int start_server (int argc, char *argv[])
{
    int      i;
    int      threadCount = 0;
    int      thread_id;
    HANDLE   g_hThread[MAX_THREAD];
    char     doers_number[MAXDOER][SPACE_FOR_THREAD_ID];
    char     movers_number[MAXMOVER][SPACE_FOR_THREAD_ID];

#ifdef INFORMIX
    MI_CONNECTION_INFO conn_info;

    // This works around a bug in Informix's isqlt09a.dll that causes memory
    // access violation when our program exits.
    memset (&conn_info, '\0', sizeof (conn_info));
    mi_server_connect (&conn_info);
#endif
    // Don't let the user start the middleware server as a standalone program.
    // Check whether the argument matches the magic string.
    if ((argc != 2) || (stricmp(argv[1], SERVER_MAGIC_STR) != 0))
    {
        puts("Vigilert Middleware Server cannot be started as a standalone program.");
        puts("Start the Velara Vigilert service.\n");
        Sleep (4000);
        exit(EXIT_FAILURE);
    }

    // Assign IDs to the multiple movers and doers
    for (i = 0; i < MAXDOER; i++)
    {
        sprintf (doers_number[i], "%d", i + 1);
    }

    for (i = 0; i < MAXMOVER; i++)
    {
        sprintf (movers_number[i], "%d", i + 1);
    }

    /* Initialize the global variables */
    num_doer = 0;
    num_mover = 0;
    g_fTerminate = FALSE;
    num_doers_accessing_global_SPI = 0;

    puts ("\n.:. Vigilert Server .:.");

    // Save the memory state so we can diff against it in vl_gather_stats.
    _CrtMemCheckpoint (&s1);

    // Initialize the mutexes
    InitializeCriticalSection(&suspend_mutex);
    InitializeCriticalSection(&mover_cleaner_mutex);
    InitializeCriticalSection(&doer_num_mutex);
    InitializeCriticalSection(&mover_num_mutex);
    InitializeCriticalSection(&num_doers_accessing_global_SPI_mutex);
    InitializeCriticalSection(&Global_SPI_mutex);

#ifdef _MIDDLE
    init_named_mem();
#endif

    load_keys();

#ifdef _MIDDLE
    InitializeCriticalSection(&logwrite_mutex);
    InitializeCriticalSection(&begin_udr_mutex);
    tm_init_conn_pool();
#endif

    // Initialize the semaphores that wakeup the movers and the doers

    // Doers can be woken up by doer dispatcher, mover (that moves the database tokens
    // to the database task queue) and the TCP-IP server thread that builds and moves the stream
    // tokens to the stream task queue.
    wakeup_doer_by_doer_dispatcher_sem = CreateSemaphore(NULL, 0, MAXDOER, NULL);    // Semaphore for doer-dispatcher
    wakeup_doer_by_mover_sem = CreateSemaphore(NULL, 0, MAXDOER, NULL);              // Semaphore for mover
    wakeup_doer_by_tcpip_server_sem = CreateSemaphore(NULL, 0, MAXDOER, NULL);       // Semahpore for TCP-IP server
    // Mover can be wpken up by mover dispatcher.
    wakeup_mover_by_mover_dispatcher_sem = CreateSemaphore(NULL, 0, MAXMOVER, NULL); // Semaphore for mover-dispatcher

    // Initialize the array of semaphore handles that can wake up the doers
    wakeup_doer_array[0] = wakeup_doer_by_doer_dispatcher_sem;
    wakeup_doer_array[1] = wakeup_doer_by_mover_sem;
    wakeup_doer_array[2] = wakeup_doer_by_tcpip_server_sem;

    // Initialize the event variable to say whether a command execute thread is waiting to access global SPI.
    command_execute_waiting_event = CreateEvent(NULL, TRUE, TRUE, NULL);

    /* start threads */
    g_hThread[threadCount] = chBEGINTHREADEX(NULL, 0, wait_end, NULL, CREATE_SUSPENDED, &thread_id);
    tm_associate_thread_id_to_connection(threadCount, thread_id);
    threadCount++;

    g_hThread[threadCount] = chBEGINTHREADEX(NULL, 0, mover_dispatcher, NULL, CREATE_SUSPENDED, &thread_id);
    tm_associate_thread_id_to_connection(threadCount, thread_id);
    threadCount++;

    g_hThread[threadCount] = chBEGINTHREADEX(NULL, 0, doer_dispatcher, NULL, CREATE_SUSPENDED, &thread_id);
    tm_associate_thread_id_to_connection(threadCount, thread_id);
    threadCount++;

    g_hThread[threadCount] = chBEGINTHREADEX(NULL, 0, TCPIPserver, NULL, CREATE_SUSPENDED, &thread_id);
    tm_associate_thread_id_to_connection(threadCount, thread_id);
    threadCount++;

    g_hThread[threadCount] = chBEGINTHREADEX(NULL, 0, cleaner, NULL, CREATE_SUSPENDED, &thread_id);
    tm_associate_thread_id_to_connection(threadCount, thread_id);
    threadCount++;

#ifdef _DEBUG
    g_hThread[threadCount] = chBEGINTHREADEX(NULL, 0, GatherStatsServer, NULL, CREATE_SUSPENDED, &thread_id);
    tm_associate_thread_id_to_connection(threadCount, thread_id);
    threadCount++;
#endif

    for (i = 0; i < MAXDOER; i++)
    {
        g_hThread[threadCount] = chBEGINTHREADEX(NULL, 0, doer,(LPVOID)doers_number[i], CREATE_SUSPENDED,  &thread_id);
        tm_associate_thread_id_to_connection(threadCount, thread_id);
        threadCount++;
    }

    for (i = 0; i < MAXMOVER; i++)
    {
        g_hThread[threadCount] = chBEGINTHREADEX(NULL, 0, mover,(LPVOID)movers_number[i], CREATE_SUSPENDED,  &thread_id);
        tm_associate_thread_id_to_connection(threadCount, thread_id);
        threadCount++;
    }

    // Before starting the various threads, let the main thread run the initializing routine
    // to initialize all main memory data structures
    tm_associate_thread_id_to_connection(threadCount, tm_get_thread_id());

    tman_init();

    // Resume the various suspended threads one by one
    for (i = 0; i < threadCount; i++)
    {
        int result;
        result = ResumeThread(g_hThread[i]);
        if (result == -1)
        {
#ifdef _MIDDLE
            printf ("Error: unable to start thread %d.\n", tm_own_connpool_1[i].thread_id);
#endif
            exit (EXIT_FAILURE);
        }
    }

    // Wait for all the currently active threads to die or terminate before performing the cleanup
    // of all main memory objects and exiting the middleware server
    WaitForMultipleObjects(threadCount, g_hThread, TRUE, INFINITE);

    for (i = 0; i< threadCount; i++)
        CloseHandle(g_hThread[i]);

    DeleteCriticalSection(&mover_num_mutex);
    DeleteCriticalSection(&doer_num_mutex);
    DeleteCriticalSection(&mover_cleaner_mutex);
    DeleteCriticalSection(&suspend_mutex);
    DeleteCriticalSection(&num_doers_accessing_global_SPI_mutex);
    DeleteCriticalSection(&Global_SPI_mutex);

    CloseHandle(wakeup_mover_by_mover_dispatcher_sem);
    CloseHandle(wakeup_doer_by_doer_dispatcher_sem);
    CloseHandle(wakeup_doer_by_tcpip_server_sem);
    CloseHandle(wakeup_doer_by_mover_sem);
    CloseHandle(command_execute_waiting_event);

#ifdef _MIDDLE
    {
        tm_close_conn_pool();
        close_named_mem();
        DeleteCriticalSection(&begin_udr_mutex);
        DeleteCriticalSection(&logwrite_mutex);
        socket_shutdown();
    }
#endif

    puts ("Vigilert run complete.");
    return EXIT_SUCCESS;
}
예제 #30
0
int 
main(int argc, char **argv) {
    xmlSecKeysMngrPtr mngr;
    
    assert(argv);

    if(argc < 3) {
	fprintf(stderr, "Error: wrong number of arguments.\n");
	fprintf(stderr, "Usage: %s <xml-file> <key-file1> [<key-file2> [...]]\n", argv[0]);
	return(1);
    }

    /* Init libxml and libxslt libraries */
    xmlInitParser();
    LIBXML_TEST_VERSION
    xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
    xmlSubstituteEntitiesDefault(1);
#ifndef XMLSEC_NO_XSLT
    xmlIndentTreeOutput = 1; 
#endif /* XMLSEC_NO_XSLT */
        	
    /* Init xmlsec library */
    if(xmlSecInit() < 0) {
	fprintf(stderr, "Error: xmlsec initialization failed.\n");
	return(-1);
    }

    /* Check loaded library version */
    if(xmlSecCheckVersion() != 1) {
	fprintf(stderr, "Error: loaded xmlsec library version is not compatible.\n");
	return(-1);
    }

    /* Load default crypto engine if we are supporting dynamic
     * loading for xmlsec-crypto libraries. Use the crypto library
     * name ("openssl", "nss", etc.) to load corresponding 
     * xmlsec-crypto library.
     */
#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
    if(xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
	fprintf(stderr, "Error: unable to load default xmlsec-crypto library. Make sure\n"
			"that you have it installed and check shared libraries path\n"
			"(LD_LIBRARY_PATH) envornment variable.\n");
	return(-1);	
    }
#endif /* XMLSEC_CRYPTO_DYNAMIC_LOADING */

    /* Init crypto library */
    if(xmlSecCryptoAppInit(NULL) < 0) {
	fprintf(stderr, "Error: crypto initialization failed.\n");
	return(-1);
    }

    /* Init xmlsec-crypto library */
    if(xmlSecCryptoInit() < 0) {
	fprintf(stderr, "Error: xmlsec-crypto initialization failed.\n");
	return(-1);
    }

    /* create keys manager and load keys */
    mngr = load_keys(&(argv[2]), argc - 2);
    if(mngr == NULL) {
	return(-1);
    }
    
    /* verify file */
    if(verify_file(mngr, argv[1]) < 0) {
	xmlSecKeysMngrDestroy(mngr);	
	return(-1);
    }    
    
    /* destroy keys manager */
    xmlSecKeysMngrDestroy(mngr);
    
    /* Shutdown xmlsec-crypto library */
    xmlSecCryptoShutdown();
    
    /* Shutdown crypto library */
    xmlSecCryptoAppShutdown();
    
    /* Shutdown xmlsec library */
    xmlSecShutdown();

    /* Shutdown libxslt/libxml */
#ifndef XMLSEC_NO_XSLT
    xsltCleanupGlobals();            
#endif /* XMLSEC_NO_XSLT */
    xmlCleanupParser();
    
    return(0);
}