Example #1
0
static bool
remove_all (p11_kit_iter *iter,
            bool *changed)
{
	const char *desc;
	CK_RV rv;

	while ((rv = p11_kit_iter_next (iter)) == CKR_OK) {
		desc = description_for_object_at_iter (iter);
		p11_debug ("removing %s: %lu", desc, p11_kit_iter_get_object (iter));
		rv = p11_kit_iter_destroy_object (iter);
		switch (rv) {
		case CKR_OK:
			*changed = true;
			/* fall through */
		case CKR_OBJECT_HANDLE_INVALID:
			continue;
		case CKR_TOKEN_WRITE_PROTECTED:
		case CKR_SESSION_READ_ONLY:
		case CKR_ATTRIBUTE_READ_ONLY:
			p11_message ("couldn't remove read-only %s", desc);
			continue;
		default:
			p11_message ("couldn't remove %s: %s", desc,
			             p11_kit_strerror (rv));
			break;
		}
	}

	return (rv == CKR_CANCEL);
}
Example #2
0
bool
p11_extract_x509_file (p11_enumerate *ex,
                       const char *destination)
{
	bool found = false;
	p11_save_file *file;
	CK_RV rv;

	while ((rv = p11_kit_iter_next (ex->iter)) == CKR_OK) {
		if (found) {
			p11_message ("multiple certificates found but could only write one to file");
			break;
		}

		file = p11_save_open_file (destination, NULL, ex->flags);
		if (!p11_save_write_and_finish (file, ex->cert_der, ex->cert_len))
			return false;

		/* Wrote something */
		found = true;
	}

	if (rv != CKR_OK && rv != CKR_CANCEL) {
		p11_message ("failed to find certificates: %s", p11_kit_strerror (rv));
		return false;

	/* Remember that an empty DER file is not a valid file, so complain if nothing */
	} else if (!found) {
		p11_message ("no certificate found");
		return false;
	}

	return true;
}
Example #3
0
static CK_SESSION_HANDLE
session_for_store_on_module (const char *name,
                             CK_FUNCTION_LIST *module,
                             bool *found_read_only)
{
	CK_SESSION_HANDLE session = 0;
	CK_SLOT_ID *slots = NULL;
	CK_TOKEN_INFO info;
	CK_ULONG count;
	CK_ULONG i;
	CK_RV rv;

	rv = p11_kit_module_initialize (module);
	if (rv != CKR_OK) {
		p11_message ("%s: couldn't initialize: %s", name, p11_kit_message ());
		return 0UL;
	}

	rv = (module->C_GetSlotList) (CK_TRUE, NULL, &count);
	if (rv == CKR_OK) {
		slots = calloc (count, sizeof (CK_ULONG));
		return_val_if_fail (slots != NULL, 0UL);
		rv = (module->C_GetSlotList) (CK_TRUE, slots, &count);
	}
	if (rv != CKR_OK) {
		p11_message ("%s: couldn't enumerate slots: %s", name, p11_kit_strerror (rv));
		free (slots);
		return 0UL;
	}

	for (i = 0; session == 0 && i < count; i++) {
		rv = (module->C_GetTokenInfo) (slots[i], &info);
		if (rv != CKR_OK) {
			p11_message ("%s: couldn't get token info: %s", name, p11_kit_strerror (rv));
			continue;
		}

		if (info.flags & CKF_WRITE_PROTECTED) {
			*found_read_only = true;
			continue;
		}

		rv = (module->C_OpenSession) (slots[i], CKF_SERIAL_SESSION | CKF_RW_SESSION,
		                              NULL, NULL, &session);
		if (rv != CKR_OK) {
			p11_message ("%s: couldn't open session: %s", name, p11_kit_strerror (rv));
			session = 0;
		}

		p11_debug ("opened writable session on: %s", name);
	}

	free (slots);

	if (session == 0UL)
		p11_kit_module_finalize (module);

	return session;
}
Example #4
0
static p11_array *
files_to_attrs (int argc,
                char *argv[])
{
	p11_parser *parser;
	p11_array *parsed;
	p11_array *array;
	int ret = P11_PARSE_SUCCESS;
	int i, j;

	array = p11_array_new (p11_attrs_free);
	return_val_if_fail (array != NULL, NULL);

	parser = create_arg_file_parser ();
	return_val_if_fail (parser != NULL, NULL);

	for (i = 0; i < argc; i++) {
		ret = p11_parse_file (parser, argv[i], NULL, P11_PARSE_FLAG_ANCHOR);
		switch (ret) {
		case P11_PARSE_SUCCESS:
			p11_debug ("parsed file: %s", argv[i]);
			break;
		case P11_PARSE_UNRECOGNIZED:
			p11_message ("unrecognized file format: %s", argv[i]);
			break;
		default:
			p11_message ("failed to parse file: %s", argv[i]);
			break;
		}

		if (ret != P11_PARSE_SUCCESS)
			break;

		parsed = p11_parser_parsed (parser);
		for (j = 0; j < parsed->num; j++) {
			if (!p11_array_push (array, parsed->elem[j]))
				return_val_if_reached (NULL);
			parsed->elem[j] = NULL;
		}
	}

	p11_parser_free (parser);

	if (ret == P11_PARSE_SUCCESS)
		return array;

	p11_array_free (array);
	return NULL;

}
Example #5
0
static bool
create_anchor (CK_FUNCTION_LIST *module,
               CK_SESSION_HANDLE session,
               CK_ATTRIBUTE *attrs)
{
	CK_BBOOL truev = CK_TRUE;
	CK_OBJECT_HANDLE object;
	char *string;
	CK_RV rv;
	CK_ULONG klass;

	CK_ATTRIBUTE basics_certificate[] = {
		{ CKA_TOKEN, &truev, sizeof (truev) },
		{ CKA_TRUSTED, &truev, sizeof (truev) },
		{ CKA_INVALID, },
	};

	CK_ATTRIBUTE basics_extension[] = {
		{ CKA_TOKEN, &truev, sizeof (truev) },
		{ CKA_INVALID, },
	};

	CK_ATTRIBUTE basics_empty[] = {
		{ CKA_INVALID, },
	};

	CK_ATTRIBUTE *basics = basics_empty;

	if (p11_attrs_find_ulong (attrs, CKA_CLASS, &klass)) {
		switch (klass) {
		case CKO_CERTIFICATE:
			basics = basics_certificate;
			break;
		case CKO_X_CERTIFICATE_EXTENSION:
			basics = basics_extension;
			break;
		}
	}

	attrs = p11_attrs_merge (attrs, p11_attrs_dup (basics), true);
	p11_attrs_remove (attrs, CKA_MODIFIABLE);

	if (p11_debugging) {
		string = p11_attrs_to_string (attrs, -1);
		p11_debug ("storing: %s", string);
		free (string);
	}

	rv = (module->C_CreateObject) (session, attrs,
	                               p11_attrs_count (attrs), &object);

	p11_attrs_free (attrs);

	if (rv != CKR_OK) {
		p11_message ("couldn't create object: %s", p11_kit_strerror (rv));
		return false;
	}

	return true;
}
Example #6
0
static int
anchor_store (int argc,
              char *argv[],
              bool *changed)
{
	CK_ATTRIBUTE *attrs;
	CK_FUNCTION_LIST *module = NULL;
	CK_SESSION_HANDLE session;
	CK_OBJECT_HANDLE object;
	p11_array *anchors;
	int ret;
	int i;

	anchors = files_to_attrs (argc, argv);
	if (anchors == NULL)
		return 1;

	if (anchors->num == 0) {
		p11_message ("specify at least one anchor input file");
		p11_array_free (anchors);
		return 2;
	}

	session = session_for_store (&module);
	if (session == 0UL) {
		p11_array_free (anchors);
		return 1;
	}

	for (i = 0, ret = 0; i < anchors->num; i++) {
		attrs = anchors->elem[i];
		anchors->elem[i] = NULL;

		object = find_anchor (module, session, attrs);
		if (object == 0) {
			p11_debug ("don't yet have this anchor");
			if (create_anchor (module, session, attrs)) {
				*changed = true;
			} else {
				ret = 1;
				break;
			}
		} else {
			p11_debug ("already have this anchor");
			if (modify_anchor (module, session, object, attrs)) {
				*changed = true;
			} else {
				ret = 1;
				break;
			}
		}
	}

	p11_array_free (anchors);
	p11_kit_module_finalize (module);
	p11_kit_module_release (module);

	return ret;
}
Example #7
0
bool
p11_extract_openssl_bundle (p11_enumerate *ex,
                            const char *destination)
{
	p11_save_file *file;
	p11_buffer output;
	p11_buffer buf;
	char *comment;
	bool ret = true;
	bool first;
	CK_RV rv;

	file = p11_save_open_file (destination, NULL, ex->flags);
	if (!file)
		return false;

	first = true;
	p11_buffer_init (&output, 0);
	while ((rv = p11_kit_iter_next (ex->iter)) == CKR_OK) {
		p11_buffer_init (&buf, 1024);
		if (!p11_buffer_reset (&output, 2048))
			return_val_if_reached (false);

		if (prepare_pem_contents (ex, &buf)) {
			if (!p11_pem_write (buf.data, buf.len, "TRUSTED CERTIFICATE", &output))
				return_val_if_reached (false);

			comment = p11_enumerate_comment (ex, first);
			first = false;

			ret = p11_save_write (file, comment, -1) &&
			      p11_save_write (file, output.data, output.len);

			free (comment);
		}

		p11_buffer_uninit (&buf);

		if (!ret)
			break;
	}

	p11_buffer_uninit (&output);

	if (rv != CKR_OK && rv != CKR_CANCEL) {
		p11_message ("failed to find certificates: %s", p11_kit_strerror (rv));
		ret = false;
	}

	/*
	 * This will produce an empty file (which is a valid PEM bundle) if no
	 * certificates were found.
	 */

	if (!p11_save_finish_file (file, NULL, ret))
		ret = false;
	return ret;
}
Example #8
0
static CK_SESSION_HANDLE
session_for_store (CK_FUNCTION_LIST **module)
{
	CK_SESSION_HANDLE session = 0UL;
	CK_FUNCTION_LIST **modules;
	bool found_read_only = false;
	char *name;
	int i;

	modules = p11_kit_modules_load (NULL, P11_KIT_MODULE_TRUSTED);
	if (modules == NULL)
		return 0;

	for (i = 0; modules[i] != NULL; i++) {
		if (session == 0UL) {
			name = p11_kit_module_get_name (modules[i]);
			session = session_for_store_on_module (name, modules[i],
			                                       &found_read_only);

			if (session != 0UL) {
				*module = modules[i];
				modules[i] = NULL;
			}

			free (name);
		}

		if (modules[i])
			p11_kit_module_release (modules[i]);
	}

	if (session == 0UL) {
		if (found_read_only)
			p11_message ("no configured writable location to store anchors");
		else
			p11_message ("no configured location to store anchors");
	}

	free (modules);
	return session;
}
Example #9
0
static int
on_unique_try_rename (void *data,
                      char *path)
{
	p11_save_file *file = data;

	if (rename (file->temp, path) < 0) {
		if (errno == EEXIST)
			return 0; /* Continue trying other names */
		p11_message ("couldn't complete writing of file: %s", path);
		return -1;
	}

	return 1; /* All done */
}
Example #10
0
static bool
modify_anchor (CK_FUNCTION_LIST *module,
               CK_SESSION_HANDLE session,
               CK_OBJECT_HANDLE object,
               CK_ATTRIBUTE *attrs)
{
	CK_BBOOL truev = CK_TRUE;
	CK_ATTRIBUTE *changes;
	CK_ATTRIBUTE *label;
	CK_ULONG klass;
	char *string;
	CK_RV rv;

	CK_ATTRIBUTE trusted = { CKA_TRUSTED, &truev, sizeof (truev) };

	label = p11_attrs_find_valid (attrs, CKA_LABEL);

	if (p11_attrs_find_ulong (attrs, CKA_CLASS, &klass) &&
	    klass == CKO_CERTIFICATE)
		changes = p11_attrs_build (NULL, &trusted, label, NULL);
	else
		changes = p11_attrs_build (NULL, label, NULL);

	return_val_if_fail (attrs != NULL, FALSE);

	/* Don't need the attributes anymore */
	p11_attrs_free (attrs);

	if (p11_debugging) {
		string = p11_attrs_to_string (changes, -1);
		p11_debug ("setting: %s", string);
		free (string);
	}

	rv = (module->C_SetAttributeValue) (session, object, changes,
	                                    p11_attrs_count (changes));

	p11_attrs_free (changes);

	if (rv != CKR_OK) {
		p11_message ("couldn't create object: %s", p11_kit_strerror (rv));
		return false;
	}

	return true;
}
Example #11
0
static bool
load_attached_extension (p11_dict *attached,
                         p11_dict *asn1_defs,
                         const unsigned char *der,
                         size_t len)
{
	char message[ASN1_MAX_ERROR_DESCRIPTION_SIZE];
	node_asn *ext;
	char *oid;
	int length;
	int start;
	int end;
	int ret;

	ext = p11_asn1_decode (asn1_defs, "PKIX1.Extension", der, len, message);
	if (ext == NULL) {
		p11_message ("couldn't parse attached certificate extension: %s", message);
		return false;
	}

	ret = asn1_der_decoding_startEnd (ext, der, len, "extnID", &start, &end);
	return_val_if_fail (ret == ASN1_SUCCESS, false);

	/* Make sure it's a straightforward oid with certain assumptions */
	length = (end - start) + 1;
	if (!p11_oid_simple (der + start, length)) {
		p11_debug ("strange complex certificate extension object id");
		return false;
	}

	oid = memdup (der + start, length);
	return_val_if_fail (oid != NULL, false);

	if (!p11_dict_set (attached, oid, ext))
		return_val_if_reached (false);

	return true;
}
Example #12
0
static int
anchor_remove (int argc,
               char *argv[],
               bool *changed)
{
	CK_FUNCTION_LIST **modules;
	p11_array *iters;
	p11_kit_iter *iter;
	int ret = 0;
	int i;

	iters = uris_or_files_to_iters (argc, argv, P11_KIT_ITER_WANT_WRITABLE);
	return_val_if_fail (iters != NULL, 1);

	if (iters->num == 0) {
		p11_message ("at least one file or uri must be specified");
		p11_array_free (iters);
		return 2;
	}

	modules = p11_kit_modules_load_and_initialize (P11_KIT_MODULE_TRUSTED);
	if (modules == NULL)
		ret = 1;

	for (i = 0; ret == 0 && i < iters->num; i++) {
		iter = iters->elem[i];

		p11_kit_iter_begin (iter, modules);
		if (!remove_all (iter, changed))
			ret = 1;
	}

	p11_array_free (iters);
	p11_kit_modules_finalize_and_release (modules);

	return ret;
}
Example #13
0
bool
p11_extract_x509_directory (p11_enumerate *ex,
                            const char *destination)
{
	p11_save_file *file;
	p11_save_dir *dir;
	char *filename;
	CK_RV rv;
	bool ret;

	dir = p11_save_open_directory (destination, ex->flags);
	if (dir == NULL)
		return false;

	while ((rv = p11_kit_iter_next (ex->iter)) == CKR_OK) {
		filename = p11_enumerate_filename (ex);
		return_val_if_fail (filename != NULL, -1);

		file = p11_save_open_file_in (dir, filename, ".cer");
		free (filename);

		if (!p11_save_write_and_finish (file, ex->cert_der, ex->cert_len)) {
			p11_save_finish_directory (dir, false);
			return false;
		}
	}

	if (rv != CKR_OK && rv != CKR_CANCEL) {
		p11_message ("failed to find certificates: %s", p11_kit_strerror (rv));
		ret = false;
	} else {
		ret = true;
	}

	p11_save_finish_directory (dir, ret);
	return ret;
}
Example #14
0
static p11_array *
uris_or_files_to_iters (int argc,
                        char *argv[],
                        int behavior)
{
	int flags = P11_KIT_URI_FOR_OBJECT_ON_TOKEN_AND_MODULE;
	p11_parser *parser = NULL;
	p11_array *iters;
	p11_array *parsed;
	p11_kit_uri *uri;
	p11_kit_iter *iter;
	int ret;
	int i, j;

	iters = p11_array_new ((p11_destroyer)p11_kit_iter_free);
	return_val_if_fail (iters != NULL, NULL);

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

		/* A PKCS#11 URI */
		if (strncmp (argv[i], "pkcs11:", 7) == 0) {
			uri = p11_kit_uri_new ();
			if (p11_kit_uri_parse (argv[i], flags, uri) != P11_KIT_URI_OK) {
				p11_message ("invalid PKCS#11 uri: %s", argv[i]);
				p11_kit_uri_free (uri);
				break;
			}

			iter = p11_kit_iter_new (uri, behavior);
			return_val_if_fail (iter != NULL, NULL);
			p11_kit_uri_free (uri);

			if (!p11_array_push (iters, iter))
				return_val_if_reached (NULL);

		} else {
			if (parser == NULL)
				parser = create_arg_file_parser ();

			ret = p11_parse_file (parser, argv[i], NULL, P11_PARSE_FLAG_ANCHOR);
			switch (ret) {
			case P11_PARSE_SUCCESS:
				p11_debug ("parsed file: %s", argv[i]);
				break;
			case P11_PARSE_UNRECOGNIZED:
				p11_message ("unrecognized file format: %s", argv[i]);
				break;
			default:
				p11_message ("failed to parse file: %s", argv[i]);
				break;
			}

			if (ret != P11_PARSE_SUCCESS)
				break;

			parsed = p11_parser_parsed (parser);
			for (j = 0; j < parsed->num; j++) {
				iter = p11_kit_iter_new (NULL, behavior);
				return_val_if_fail (iter != NULL, NULL);

				iter_match_anchor (iter, parsed->elem[j]);
				if (!p11_array_push (iters, iter))
					return_val_if_reached (NULL);
			}
		}
	}

	if (parser)
		p11_parser_free (parser);

	if (argc != i) {
		p11_array_free (iters);
		return NULL;
	}

	return iters;
}
Example #15
0
int
p11_trust_anchor (int argc,
                  char **argv)
{
	bool changed = false;
	int action = 0;
	int opt;
	int ret;

	enum {
		opt_verbose = 'v',
		opt_quiet = 'q',
		opt_help = 'h',

		opt_store = 's',
		opt_remove = 'r',
	};

	struct option options[] = {
		{ "store", no_argument, NULL, opt_store },
		{ "remove", no_argument, NULL, opt_remove },
		{ "verbose", no_argument, NULL, opt_verbose },
		{ "quiet", no_argument, NULL, opt_quiet },
		{ "help", no_argument, NULL, opt_help },
		{ 0 },
	};

	p11_tool_desc usages[] = {
		{ 0, "usage: trust anchor --store <file> ...\n"
		     "       trust anchor --remove <file or URI> ..."},
		{ opt_verbose, "show verbose debug output", },
		{ opt_quiet, "suppress command output", },
		{ 0 },
	};

	while ((opt = p11_tool_getopt (argc, argv, options)) != -1) {
		switch (opt) {
		case opt_store:
		case opt_remove:
			if (action == 0) {
				action = opt;
			} else {
				p11_message ("an action was already specified");
				return 2;
			}
			break;
		case opt_verbose:
		case opt_quiet:
			break;
		case opt_help:
			p11_tool_usage (usages, options);
			return 0;
		case '?':
			p11_tool_usage (usages, options);
			return 2;
		default:
			assert_not_reached ();
			break;
		}
	};

	argc -= optind;
	argv += optind;

	if (action == 0)
		action = opt_store;

	/* Store is different, and only accepts files */
	if (action == opt_store)
		ret = anchor_store (argc, argv, &changed);

	else if (action == opt_remove)
		ret = anchor_remove (argc, argv, &changed);

	else
		assert_not_reached ();

	/* Extract the compat bundles after modification */
	if (ret == 0 && changed) {
		char *args[] = { argv[0], NULL };
		ret = p11_trust_extract_compat (1, args);
	}

	return ret;
}
Example #16
0
bool
p11_extract_openssl_directory (p11_enumerate *ex,
                               const char *destination)
{
	char *filename;
	p11_save_file *file;
	p11_save_dir *dir;
	p11_buffer output;
	p11_buffer buf;
	bool ret = true;
	char *path;
	char *name;
	CK_RV rv;

	dir = p11_save_open_directory (destination, ex->flags);
	if (dir == NULL)
		return false;

	p11_buffer_init (&buf, 0);
	p11_buffer_init (&output, 0);

	while ((rv = p11_kit_iter_next (ex->iter)) == CKR_OK) {
		if (!p11_buffer_reset (&buf, 1024))
			return_val_if_reached (false);
		if (!p11_buffer_reset (&output, 2048))
			return_val_if_reached (false);

		if (prepare_pem_contents (ex, &buf)) {
			if (!p11_pem_write (buf.data, buf.len, "TRUSTED CERTIFICATE", &output))
				return_val_if_reached (false);

			name = p11_enumerate_filename (ex);
			return_val_if_fail (name != NULL, false);

			filename = NULL;
			path = NULL;
			ret = false;

			file = p11_save_open_file_in (dir, name, ".pem");
			if (file != NULL) {
				ret = p11_save_write (file, output.data, output.len);
				if (!p11_save_finish_file (file, &path, ret))
					ret = false;
				if (ret)
					filename = p11_path_base (path);
			}
			ret = p11_openssl_symlink(ex, dir, filename);

			free (filename);
			free (path);
			free (name);
		}

		if (!ret)
			break;
	}

	p11_buffer_uninit (&buf);
	p11_buffer_uninit (&output);

	if (rv != CKR_OK && rv != CKR_CANCEL) {
		p11_message ("failed to find certificates: %s", p11_kit_strerror (rv));
		ret = false;
	}

	p11_save_finish_directory (dir, ret);
	return ret;
}
Example #17
0
int
p11_tool_main (int argc,
               char *argv[],
               const p11_tool_command *commands)
{
	const p11_tool_command *fallback = NULL;
	char *command = NULL;
	bool want_help = false;
	bool skip;
	int in, out;
	int i;

	/*
	 * Parse the global options. We rearrange the options as
	 * necessary, in order to pass relevant options through
	 * to the commands, but also have them take effect globally.
	 */

	for (in = 1, out = 1; in < argc; in++, out++) {

		/* The non-option is the command, take it out of the arguments */
		if (argv[in][0] != '-') {
			if (!command) {
				skip = true;
				command = argv[in];
			} else {
				skip = false;
			}

		/* The global long options */
		} else if (argv[in][1] == '-') {
			skip = false;

			if (strcmp (argv[in], "--") == 0) {
				if (!command) {
					p11_message ("no command specified");
					return 2;
				} else {
					break;
				}

			} else if (strcmp (argv[in], "--verbose") == 0) {
				verbose_arg ();

			} else if (strcmp (argv[in], "--quiet") == 0) {
				quiet_arg ();

			} else if (strcmp (argv[in], "--help") == 0) {
				want_help = true;

			} else if (!command) {
				p11_message ("unknown global option: %s", argv[in]);
				return 2;
			}

		/* The global short options */
		} else {
			skip = false;

			for (i = 1; argv[in][i] != '\0'; i++) {
				switch (argv[in][i]) {
				case 'h':
					want_help = true;
					break;

				/* Compatibility option */
				case 'l':
					command = "list-modules";
					break;

				case 'v':
					verbose_arg ();
					break;

				case 'q':
					quiet_arg ();
					break;

				default:
					if (!command) {
						p11_message ("unknown global option: -%c", (int)argv[in][i]);
						return 2;
					}
					break;
				}
			}
		}

		/* Skipping this argument? */
		if (skip)
			out--;
		else
			argv[out] = argv[in];
	}

	/* Initialize tool's debugging after setting env vars above */
	p11_debug_init ();

	if (command == NULL) {
		/* As a special favor if someone just typed the command, help them out */
		if (argc == 1) {
			command_usage (commands);
			return 2;
		} else if (want_help) {
			command_usage (commands);
			return 0;
		} else {
			p11_message ("no command specified");
			return 2;
		}
	}

	argc = out;

	/* Look for the command */
	for (i = 0; commands[i].name != NULL; i++) {
		if (strcmp (commands[i].name, P11_TOOL_FALLBACK) == 0) {
			fallback = commands + i;

		} else if (strcmp (commands[i].name, command) == 0) {
			argv[0] = command;
			return (commands[i].function) (argc, argv);
		}
	}

	/* Got here because no command matched */
	if (fallback != NULL) {
		argv[0] = command;
		return (fallback->function) (argc, argv);
	}

	/* At this point we have no command */
	p11_message ("'%s' is not a valid command. See '%s --help'",
	             command, getprogname ());
	return 2;
}