From ba7d256ecf9eddd70a52951e6a52d953c60eee79 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Thu, 29 Jun 2017 14:27:36 +0200 Subject: [PATCH 01/57] Fix test cases: uninitialized memory and non-terminated string compare --- ykcs11/tests/ykcs11_tests.c | 2 +- ykcs11/utils.c | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/ykcs11/tests/ykcs11_tests.c b/ykcs11/tests/ykcs11_tests.c index 027ff51..385d005 100644 --- a/ykcs11/tests/ykcs11_tests.c +++ b/ykcs11/tests/ykcs11_tests.c @@ -138,7 +138,7 @@ static void test_token_info() { if (info.firmwareVersion.major != 4 && info.firmwareVersion.major != 0) asrt(info.firmwareVersion.major, 4, "FW_MAJ"); - asrt(strcmp(info.utcTime, TOKEN_TIME), 0, "TOKEN_TIME"); + asrt(strncmp(info.utcTime, TOKEN_TIME, sizeof(info.utcTime)), 0, "TOKEN_TIME"); asrt(funcs->C_Finalize(NULL), CKR_OK, "FINALIZE"); diff --git a/ykcs11/utils.c b/ykcs11/utils.c index ac4dcc8..f66d995 100644 --- a/ykcs11/utils.c +++ b/ykcs11/utils.c @@ -182,6 +182,7 @@ CK_RV create_token(ykpiv_state *state, CK_BYTE_PTR p, ykcs11_slot_t *slot) { t_info->ulFreePrivateMemory = CK_UNAVAILABLE_INFORMATION; + memset(&t_info->hardwareVersion, 0, sizeof(t_info->hardwareVersion)); // Ignore hardware version, report firmware version if (token.get_token_version(state, &t_info->firmwareVersion) != CKR_OK) { ykpiv_disconnect(state); From 0d2b85fcefb116a9271897d54cf1e878c97db755 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Fri, 30 Jun 2017 09:58:25 +0200 Subject: [PATCH 02/57] Switch test cases to use libcheck framework This keeps the test logic the same, but moves most of them into the libcheck test suite framework. It gives better control over grouping related tests, running them in parallel, and reporting on multiple failures. Running in parallel also brings problems, so libykcs11 tests are left untouched. Parallel access to a single hardware DUT does not make sense, and pcsc-lite doesn't work after a fork() in OS X 10.11+, so it can't run in libcheck's tests anyway. --- configure.ac | 1 + lib/tests/Makefile.am | 4 +- lib/tests/basic.c | 91 +++++++++++++++++++++++++--------------- lib/tests/parse_key.c | 61 +++++++++++++++++---------- tool/tests/Makefile.am | 4 +- tool/tests/parse_name.c | 66 +++++++++++++++++++++-------- tool/tests/test_inout.c | 51 ++++++++++++++++++---- ykcs11/tests/Makefile.am | 4 +- 8 files changed, 194 insertions(+), 88 deletions(-) diff --git a/configure.ac b/configure.ac index 2f5944c..7e5f5e4 100644 --- a/configure.ac +++ b/configure.ac @@ -50,6 +50,7 @@ AM_MISSING_PROG(GENGETOPT, gengetopt, $missing_dir) PKG_PROG_PKG_CONFIG PKG_CHECK_MODULES(OPENSSL, libcrypto) +PKG_CHECK_MODULES([CHECK], [check >= 0.9.6]) gl_LD_VERSION_SCRIPT gl_VALGRIND_TESTS diff --git a/lib/tests/Makefile.am b/lib/tests/Makefile.am index d1ae1b3..f83a46f 100644 --- a/lib/tests/Makefile.am +++ b/lib/tests/Makefile.am @@ -25,10 +25,10 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -AM_CFLAGS = $(WARN_CFLAGS) +AM_CFLAGS = $(WARN_CFLAGS) @CHECK_CFLAGS@ AM_CPPFLAGS = -I$(top_srcdir)/lib -I$(top_builddir)/lib -AM_LDFLAGS = -no-install +AM_LDFLAGS = -no-install @CHECK_LIBS@ LDADD = ../libykpiv.la check_PROGRAMS = basic parse_key diff --git a/lib/tests/basic.c b/lib/tests/basic.c index 85619ac..49b6f6b 100644 --- a/lib/tests/basic.c +++ b/lib/tests/basic.c @@ -35,41 +35,64 @@ #include #include +#include + +START_TEST(test_version_string) { + if (strcmp(YKPIV_VERSION_STRING, ykpiv_check_version(NULL)) != 0) { + ck_abort_msg("version mismatch %s != %s\n", YKPIV_VERSION_STRING, + ykpiv_check_version(NULL)); + } + + if (ykpiv_check_version(YKPIV_VERSION_STRING) == NULL) { + ck_abort_msg("version NULL?\n"); + } + + if (ykpiv_check_version("99.99.99") != NULL) { + ck_abort_msg("version not NULL?\n"); + } + + fprintf(stderr, "ykpiv version: header %s library %s\n", + YKPIV_VERSION_STRING, ykpiv_check_version (NULL)); +} +END_TEST + +START_TEST(test_strerror) { + const char *s; + + if (ykpiv_strerror(YKPIV_OK) == NULL) { + ck_abort_msg("ykpiv_strerror NULL\n"); + } + + s = ykpiv_strerror_name(YKPIV_OK); + if (s == NULL || strcmp(s, "YKPIV_OK") != 0) { + ck_abort_msg("ykpiv_strerror_name %s\n", s); + } +} +END_TEST + +Suite *basic_suite(void) { + Suite *s; + TCase *tc; + + s = suite_create("libykpiv basic"); + tc = tcase_create("basic"); + tcase_add_test(tc, test_version_string); + tcase_add_test(tc, test_strerror); + suite_add_tcase(s, tc); + + return s; +} + int main(void) { - if(strcmp(YKPIV_VERSION_STRING, ykpiv_check_version (NULL)) != 0) { - printf("version mismatch %s != %s\n", YKPIV_VERSION_STRING, - ykpiv_check_version(NULL)); - return EXIT_FAILURE; - } + int number_failed; + Suite *s; + SRunner *sr; - if(ykpiv_check_version(YKPIV_VERSION_STRING) == NULL) { - printf("version NULL?\n"); - return EXIT_FAILURE; - } - - if(ykpiv_check_version("99.99.99") != NULL) { - printf ("version not NULL?\n"); - return EXIT_FAILURE; - } - - printf ("ykpiv version: header %s library %s\n", - YKPIV_VERSION_STRING, ykpiv_check_version (NULL)); - - - if(ykpiv_strerror(YKPIV_OK) == NULL) { - printf ("ykpiv_strerror NULL\n"); - return EXIT_FAILURE; - } - - { - const char *s; - s = ykpiv_strerror_name(YKPIV_OK); - if(s == NULL || strcmp(s, "YKPIV_OK") != 0) { - printf("ykpiv_strerror_name %s\n", s); - return EXIT_FAILURE; - } - } - - return EXIT_SUCCESS; + s = basic_suite(); + sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/lib/tests/parse_key.c b/lib/tests/parse_key.c index 7740823..0a339c9 100644 --- a/lib/tests/parse_key.c +++ b/lib/tests/parse_key.c @@ -32,6 +32,8 @@ #include #include +#include + #include "ykpiv.h" struct key { @@ -57,30 +59,43 @@ static int parse_key(const char *text, const unsigned char *expected, int valid) unsigned char key[24]; size_t len = sizeof(key); ykpiv_rc res = ykpiv_hex_decode(text, strlen(text), key, &len); - if(res != YKPIV_OK && valid == 1) { - printf("key check failed for %s!\n", text); - return EXIT_FAILURE; - } else if(res != YKPIV_OK && valid == 0) { - return EXIT_SUCCESS; - } - - if(memcmp(expected, key, 24) != 0) { - printf("keys not matching for %s!\n", text); - return EXIT_FAILURE; - } - + if (valid) { + ck_assert(res == YKPIV_OK); + ck_assert(memcmp(expected, key, 24) == 0); + } else { + ck_assert(res != YKPIV_OK); + } return EXIT_SUCCESS; } -int main(void) { - size_t i; - - for(i = 0; i < sizeof(keys) / sizeof(struct key); i++) { - int res = parse_key(keys[i].text, keys[i].formatted, keys[i].valid); - if(res != EXIT_SUCCESS) { - return res; - } - } - - return EXIT_SUCCESS; +START_TEST(test_parse_key) { + int res = parse_key(keys[_i].text, keys[_i].formatted, keys[_i].valid); + ck_assert(res == EXIT_SUCCESS); +} +END_TEST + +Suite *parsekey_suite(void) { + Suite *s; + TCase *tc; + + s = suite_create("libykpiv parsekey"); + tc = tcase_create("parsekey"); + tcase_add_loop_test(tc, test_parse_key, 0, sizeof(keys) / sizeof(struct key)); + suite_add_tcase(s, tc); + + return s; +} + +int main(void) +{ + int number_failed; + Suite *s; + SRunner *sr; + + s = parsekey_suite(); + sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/tool/tests/Makefile.am b/tool/tests/Makefile.am index 64fd65f..1d76905 100644 --- a/tool/tests/Makefile.am +++ b/tool/tests/Makefile.am @@ -29,12 +29,12 @@ TESTS_ENVIRONMENT = export VERSION=$(PACKAGE_VERSION); export EXEEXT=$(EXEEXT); LOG_COMPILER = $(VALGRIND) -AM_CFLAGS = $(WARN_CFLAGS) +AM_CFLAGS = $(WARN_CFLAGS) @CHECK_CFLAGS@ AM_CPPFLAGS = -I$(top_srcdir)/lib -I$(top_builddir)/lib AM_CPPFLAGS += -I$(top_srcdir)/tool -I$(top_builddir)/tool AM_CPPFLAGS += $(OPENSSL_CFLAGS) -AM_LDFLAGS = -no-install +AM_LDFLAGS = -no-install @CHECK_LIBS@ parse_name_LDADD = ../libpiv_util.la $(OPENSSL_LIBS) test_inout_LDADD = ../libpiv_util.la diff --git a/tool/tests/parse_name.c b/tool/tests/parse_name.c index d6a103b..455a4e9 100644 --- a/tool/tests/parse_name.c +++ b/tool/tests/parse_name.c @@ -28,6 +28,8 @@ * */ +#include + #include #include @@ -39,18 +41,26 @@ #include "util.h" -static void test_name(const char *name, const char *expected, bool fail) { +struct name { + const char *name; + const char *parsed_name; + bool valid; +} names[] = { + {"/CN=test foo/", "CN = test foo", true}, + {"/CN=test/OU=bar/O=EXAMPLE/", "CN = test, OU = bar, O = EXAMPLE", true}, + {"/CN=test/OU=bar/O=EXAMPLE/", "CN = test, OU = wrong, O = EXAMPLE", false}, + {"/foo/", "", false}, + {"/CN=test/foobar/", "", false}, + {"/CN=test/foo=bar/", "", false}, +}; + +static bool test_name(const char *name, const char *expected) { char buf[1024]; BIO *bio; const char none[] = {0}; X509_NAME *parsed = parse_name(name); if(parsed == NULL) { - if(fail) { - return; - } else { - printf("Failed parsing of '%s'!\n", name); - exit(EXIT_FAILURE); - } + return false; } bio = BIO_new(BIO_s_mem()); @@ -61,17 +71,39 @@ static void test_name(const char *name, const char *expected, bool fail) { BIO_free(bio); X509_NAME_free(parsed); if(strcmp(buf, expected) != 0) { - printf("Names not matching: '%s' != '%s'\n", expected, buf); - exit(EXIT_FAILURE); + fprintf(stderr, "Names not matching: '%s' != '%s'\n", expected, buf); + return false; } + return true; } -int main(void) { - test_name("/CN=test foo/", "CN = test foo", false); - test_name("/CN=test/OU=bar/O=EXAMPLE/", "CN = test, OU = bar, O = EXAMPLE", false); - test_name("/foo/", "", true); - test_name("/CN=test/foobar/", "", true); - test_name("/CN=test/foo=bar/", "", true); - - return EXIT_SUCCESS; +START_TEST(test_parse_name) { + ck_assert(test_name(names[_i].name, names[_i].parsed_name) == names[_i].valid); +} +END_TEST + +Suite *test_suite(void) { + Suite *s; + TCase *tc; + + s = suite_create("yubico-piv-tool parse_name"); + tc = tcase_create("parse_name"); + tcase_add_loop_test(tc, test_parse_name, 0, sizeof(names) / sizeof(struct name)); + suite_add_tcase(s, tc); + + return s; +} + +int main(void) +{ + int number_failed; + Suite *s; + SRunner *sr; + + s = test_suite(); + sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/tool/tests/test_inout.c b/tool/tests/test_inout.c index fb475bf..a93c27c 100644 --- a/tool/tests/test_inout.c +++ b/tool/tests/test_inout.c @@ -28,6 +28,8 @@ * */ +#include + #include #include #include @@ -40,25 +42,58 @@ #define pipe(fds) _pipe(fds,4096, 0) #endif -static void test_inout(enum enum_format format) { +enum enum_format formats[] = { + format_arg_base64, + format_arg_hex, + format_arg_binary, +}; + +static bool inout(enum enum_format format) { const unsigned char buf[] = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; unsigned char buf2[sizeof(buf)]; int pipefd[2]; FILE *tmp1, *tmp2; - assert(pipe(pipefd) == 0); + if (pipe(pipefd) != 0) + return false; tmp1 = fdopen(pipefd[1], "w"); dump_data(buf, sizeof(buf), tmp1, false, format); fclose(tmp1); tmp2 = fdopen(pipefd[0], "r"); read_data(buf2, sizeof(buf2), tmp2, format); - assert(memcmp(buf, buf2, sizeof(buf)) == 0); + if (memcmp(buf, buf2, sizeof(buf)) != 0) + return false; fclose(tmp2); + return true; } -int main(void) { - test_inout(format_arg_base64); - test_inout(format_arg_hex); - test_inout(format_arg_binary); - exit(0); +START_TEST(test_inout) { + ck_assert(inout(formats[_i])); +} +END_TEST + +Suite *test_suite(void) { + Suite *s; + TCase *tc; + + s = suite_create("yubico-piv-tool inout"); + tc = tcase_create("inout"); + tcase_add_loop_test(tc, test_inout, 0, sizeof(formats) / sizeof(*formats)); + suite_add_tcase(s, tc); + + return s; +} + +int main(void) +{ + int number_failed; + Suite *s; + SRunner *sr; + + s = test_suite(); + sr = srunner_create(s); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/ykcs11/tests/Makefile.am b/ykcs11/tests/Makefile.am index 1ee6545..3289626 100644 --- a/ykcs11/tests/Makefile.am +++ b/ykcs11/tests/Makefile.am @@ -29,12 +29,12 @@ #LOG_COMPILER = $(VALGRIND) -AM_CFLAGS = $(WARN_CFLAGS) +AM_CFLAGS = $(WARN_CFLAGS) @CHECK_CFLAGS@ AM_CPPFLAGS = -I$(top_srcdir)/lib -I$(top_builddir)/lib AM_CPPFLAGS += -I$(top_srcdir)/ykcs11 -I$(top_builddir)/ykcs11 AM_CPPFLAGS += $(OPENSSL_CFLAGS) -AM_LDFLAGS = -no-install +AM_LDFLAGS = -no-install @CHECK_LIBS@ ykcs11_tests_LDADD = ../libykcs11.la $(OPENSSL_LIBS) From 86a0e72dbeebcee7aae4e66fe0e6de287ea53809 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 3 Jul 2017 11:15:27 +0200 Subject: [PATCH 03/57] Port fix from ykpiv-minidriver: commit 79ae87153c2be06e8193a491e26b799e3b5ba028 Author: Oscar K So JR Date: Mon Jan 30 22:08:29 2017 +0000 Fixed Issue #78 - P2 Bug: MXCT352 - Importing PKCS#12 with key size 4096 bits crashed CertUtil.exe --- lib/ykpiv.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/lib/ykpiv.c b/lib/ykpiv.c index da4fa44..8b97b41 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -941,6 +941,10 @@ ykpiv_rc ykpiv_import_private_key(ykpiv_state *state, const unsigned char key, u if (state == NULL) return YKPIV_GENERIC_ERROR; + if (p_len + q_len + dp_len + dq_len + qinv_len + ec_data_len >= sizeof(key_data)) { + return YKPIV_SIZE_ERROR; + } + if (key == YKPIV_KEY_CARDMGM || key < YKPIV_KEY_RETIRED1 || (key > YKPIV_KEY_RETIRED20 && key < YKPIV_KEY_AUTHENTICATION) || From 6c5d5545bfc760f4f7ce514068ef8f408b808513 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 4 Jul 2017 16:43:55 +0200 Subject: [PATCH 04/57] WIP port minidriver ykpiv_util_* functions --- lib/Makefile.am | 2 +- lib/internal.h | 42 +- lib/util.c | 1003 +++++++++++++++++++++++++++++++++++++++++++++++ lib/ykpiv.c | 145 +++++-- lib/ykpiv.h | 121 ++++++ 5 files changed, 1279 insertions(+), 34 deletions(-) create mode 100644 lib/util.c diff --git a/lib/Makefile.am b/lib/Makefile.am index 1a4a584..951ea9e 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -32,7 +32,7 @@ AM_CPPFLAGS = $(OPENSSL_CFLAGS) $(PCSC_CFLAGS) lib_LTLIBRARIES = libykpiv.la -libykpiv_la_SOURCES = ykpiv.c version.c ykpiv.pc.in ykpiv.map internal.h +libykpiv_la_SOURCES = ykpiv.c util.c version.c ykpiv.pc.in ykpiv.map internal.h libykpiv_la_SOURCES += error.c libykpiv_la_includedir = $(includedir)/ykpiv libykpiv_la_include_HEADERS = ykpiv.h ykpiv-version.h diff --git a/lib/internal.h b/lib/internal.h index d05436c..6f176d0 100644 --- a/lib/internal.h +++ b/lib/internal.h @@ -45,11 +45,32 @@ #define READER_LEN 32 #define MAX_READERS 16 +#define DES_LEN_3DES 8*3 +#define CB_MGM_KEY DES_LEN_3DES + + typedef void* (*ykpiv_pfn_alloc)(void* alloc_data, size_t size); + typedef void* (*ykpiv_pfn_realloc)(void* alloc_data, void* address, size_t size); + typedef void (*ykpiv_pfn_free)(void* alloc_data, void* address); + typedef struct { + ykpiv_pfn_alloc pfn_alloc; + ykpiv_pfn_realloc pfn_realloc; + ykpiv_pfn_free pfn_free; + void * alloc_data; + } ykpiv_allocator; + +extern ykpiv_allocator _mem_default_allocator; + struct ykpiv_state { SCARDCONTEXT context; SCARDHANDLE card; int verbose; char *pin; + + ykpiv_allocator allocator; + bool isNEO; + uint8_t mgmKey[CB_MGM_KEY]; + bool fMgmKeySet; + }; union u_APDU { @@ -66,8 +87,23 @@ union u_APDU { typedef union u_APDU APDU; -unsigned const char aid[] = { - 0xa0, 0x00, 0x00, 0x03, 0x08 -}; +extern unsigned const char aid[]; + +// the object size is restricted to the firmware's message buffer size, which +// always contains 0x5C + 1 byte len + 3 byte id + 0x53 + 3 byte len = 9 bytes, +// so while the message buffer == CB_BUF_MAX, the maximum object we can store +// is CB_BUF_MAX - 9 +#define CB_OBJ_MAX_NEO (CB_BUF_MAX_NEO - 9) +#define CB_OBJ_MAX_YK4 (CB_BUF_MAX_YK4 - 9) +#define CB_OBJ_MAX CB_OBJ_MAX_YK4 + +#define CB_BUF_MAX_NEO 2048 +#define CB_BUF_MAX_YK4 3072 +#define CB_BUF_MAX CB_BUF_MAX_YK4 + +#define CB_ATR_MAX 33 + +#define ATR_NEO_R3 "\x3b\xfc\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x4e\x45\x4f\x72\x33\xe1" +#define ATR_YK4 "\x3b\xf8\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x34\xd4" #endif diff --git a/lib/util.c b/lib/util.c new file mode 100644 index 0000000..dd58add --- /dev/null +++ b/lib/util.c @@ -0,0 +1,1003 @@ + /* + * Copyright (c) 2014-2016 Yubico AB + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "internal.h" +#include "ykpiv.h" + + +const uint8_t CHUID_TMPL[] = { + 0x30, 0x19, 0xd4, 0xe7, 0x39, 0xda, 0x73, 0x9c, 0xed, 0x39, 0xce, 0x73, 0x9d, + 0x83, 0x68, 0x58, 0x21, 0x08, 0x42, 0x10, 0x84, 0x21, 0x38, 0x42, 0x10, 0xc3, + 0xf5, 0x34, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x35, 0x08, 0x32, 0x30, 0x33, 0x30, 0x30, + 0x31, 0x30, 0x31, 0x3e, 0x00, 0xfe, 0x00, +}; +#define CHUID_GUID_OFFS 29 +#define CB_CARDID 16 + +const uint8_t CCC_TMPL[] = { + 0xf0, 0x15, 0xa0, 0x00, 0x00, 0x01, 0x16, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf1, 0x01, 0x21, + 0xf2, 0x01, 0x21, 0xf3, 0x00, 0xf4, 0x01, 0x00, 0xf5, 0x01, 0x10, 0xf6, 0x00, + 0xf7, 0x00, 0xfa, 0x00, 0xfb, 0x00, 0xfc, 0x00, 0xfd, 0x00, 0xfe, 0x00 +}; + +#define CCC_ID_OFFS 9 +#define CB_CCC_ID 14 + +#define TAG_CERT 0x70 +#define TAG_CERT_COMPRESS 0x71 +#define TAG_CERT_LRC 0xFE +#define TAG_PIVMAN_DATA 0x80 +#define TAG_FLAGS_1 0x81 +#define TAG_SALT 0x82 +#define TAG_PIN_TIMESTAMP 0x83 +#define TAG_MSCMAP 0x81 +#define TAG_MSROOTS_END 0x82 +#define TAG_MSROOTS_MID 0x83 + +#define TAG_RSA_MODULUS 0x81 +#define TAG_RSA_EXP 0x82 +#define TAG_ECC_POINT 0x86 + +#define CB_ECC_POINTP256 65 +#define CB_ECC_POINTP384 97 + + +#define YKPIV_OBJ_PIVMAN_DATA 0x5fff00 +#define YKPIV_OBJ_ATTESTATION 0x5fff01 +#define YKPIV_OBJ_MSCMAP 0x5fff10 +#define YKPIV_OBJ_MSROOTS1 0x5fff11 +#define YKPIV_OBJ_MSROOTS2 0x5fff12 +#define YKPIV_OBJ_MSROOTS3 0x5fff13 +#define YKPIV_OBJ_MSROOTS4 0x5fff14 +#define YKPIV_OBJ_MSROOTS5 0x5fff15 + +#define CB_OBJ_TAG_MIN 2 // 1 byte tag + 1 byte len +#define CB_OBJ_TAG_MAX (CB_OBJ_TAG_MIN + 2) // 1 byte tag + 3 bytes len + +typedef enum { + PRNG_OK = 0, + PRNG_GENERAL_ERROR = -1 +} prng_rc; + +static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf, size_t *buf_len); +static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len); + +prng_rc prng_generate(unsigned char *buffer, const size_t cb_req) { + // TREV TODO: ykpiv.c needs to use this + prng_rc rc = PRNG_OK; + +#ifdef _WINDOWS + HCRYPTPROV hProv = 0; + + if (CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { + if (!CryptGenRandom(hProv, (DWORD)cb_req, buffer)) { + rc = PRNG_GENERAL_ERROR; + } + + CryptReleaseContext(hProv, 0); + } + else { + rc = PRNG_GENERAL_ERROR; + } + +#else + if (-1 == RAND_pseudo_bytes(buffer, cb_req)) { + rc = PRNG_GENERAL_ERROR; + } + +#endif + + return rc; +} + +/* Memory helper functions */ + +static void* _alloc(ykpiv_state *state, size_t size) { + if (!state || !(state->allocator.pfn_alloc)) return NULL; + return state->allocator.pfn_alloc(state->allocator.alloc_data, size); +} + +static void* _realloc(ykpiv_state *state, void *address, size_t size) { + if (!state || !(state->allocator.pfn_realloc)) return NULL; + return state->allocator.pfn_realloc(state->allocator.alloc_data, address, size); +} + +static void _free(ykpiv_state *state, void *data) { + if (!data || !state || (!(state->allocator.pfn_free))) return; + state->allocator.pfn_free(state->allocator.alloc_data, data); +} + +static size_t _obj_size_max(ykpiv_state *state) { + return (state && state->isNEO) ? CB_OBJ_MAX_NEO : CB_OBJ_MAX; +} + +#define MAX(a,b) (a) > (b) ? (a) : (b) +#define MIN(a,b) (a) < (b) ? (a) : (b) + +int _ykpiv_set_length(unsigned char *buffer, size_t length); +int _ykpiv_get_length(const unsigned char *buffer, size_t *len); +ykpiv_rc _ykpiv_begin_transaction(ykpiv_state *state); +ykpiv_rc _ykpiv_end_transaction(ykpiv_state *state); +ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state); + +/* +** YKPIV Utility API - aggregate functions and slightly nicer interface +*/ + +ykpiv_rc ykpiv_util_get_cardid(ykpiv_state *state, ykpiv_cardid *cardid) { + ykpiv_rc res = YKPIV_OK; + uint8_t buf[CB_OBJ_MAX]; + size_t len = sizeof(buf); + + if (!cardid) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + res = ykpiv_fetch_object(state, YKPIV_OBJ_CHUID, buf, (unsigned long *)&len); + if (YKPIV_OK == res) { + if (len != sizeof(CHUID_TMPL)) { + res = YKPIV_GENERIC_ERROR; + } + else { + memcpy(cardid->data, buf + CHUID_GUID_OFFS, CB_CARDID); + } + } + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_set_cardid(ykpiv_state *state, const ykpiv_cardid *cardid) { + ykpiv_rc res = YKPIV_OK; + uint8_t id[CB_CARDID]; + uint8_t buf[sizeof(CHUID_TMPL)]; + size_t len = 0; + + if (!state) return YKPIV_GENERIC_ERROR; + + if (!cardid) { + if (PRNG_OK != prng_generate(id, sizeof(id))) { + return YKPIV_RANDOMNESS_ERROR; + } + } + else { + memcpy(id, cardid->data, sizeof(id)); + } + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + memcpy(buf, CHUID_TMPL, sizeof(CHUID_TMPL)); + memcpy(buf + CHUID_GUID_OFFS, id, sizeof(id)); + len = sizeof(CHUID_TMPL); + + res = ykpiv_save_object(state, YKPIV_OBJ_CHUID, buf, len); + + if (YKPIV_OK == res) { + // also set the CCC for use with systems that require it + len = sizeof(CCC_TMPL); + memcpy(buf, CCC_TMPL, len); + memcpy(buf + CCC_ID_OFFS, id, CB_CCC_ID); + + res = ykpiv_save_object(state, YKPIV_OBJ_CAPABILITY, buf, len); + } + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_devmodel ykpiv_util_devicemodel(ykpiv_state *state) { + if (!state || state->context == SCARD_E_INVALID_HANDLE) + return DEVTYPE_UNKNOWN; + return (state->isNEO ? DEVTYPE_NEOr3 : DEVTYPE_YK4); +} + +ykpiv_rc ykpiv_util_list_keys(ykpiv_state *state, uint8_t *key_count, ykpiv_key **data, size_t *data_len) { + ykpiv_rc res = YKPIV_OK; + ykpiv_key *pKey = NULL; + uint8_t *pData = NULL; + size_t cbData = 0; + size_t offset = 0; + uint8_t buf[CB_BUF_MAX]; + size_t cbBuf = 0; + bool transaction = false; + size_t i = 0; + size_t cbRealloc = 0; + + const size_t CB_PAGE = 4096; + + const uint8_t SLOTS[] = { + YKPIV_KEY_AUTHENTICATION, + YKPIV_KEY_SIGNATURE, + YKPIV_KEY_KEYMGM, + YKPIV_KEY_RETIRED1, + YKPIV_KEY_RETIRED2, + YKPIV_KEY_RETIRED3, + YKPIV_KEY_RETIRED4, + YKPIV_KEY_RETIRED5, + YKPIV_KEY_RETIRED6, + YKPIV_KEY_RETIRED7, + YKPIV_KEY_RETIRED8, + YKPIV_KEY_RETIRED9, + YKPIV_KEY_RETIRED10, + YKPIV_KEY_RETIRED11, + YKPIV_KEY_RETIRED12, + YKPIV_KEY_RETIRED13, + YKPIV_KEY_RETIRED14, + YKPIV_KEY_RETIRED15, + YKPIV_KEY_RETIRED16, + YKPIV_KEY_RETIRED17, + YKPIV_KEY_RETIRED18, + YKPIV_KEY_RETIRED19, + YKPIV_KEY_RETIRED20, + YKPIV_KEY_CARDAUTH + }; + + if ((NULL == data) || (NULL == data_len) || (NULL == key_count)) { return YKPIV_GENERIC_ERROR; } + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + // init return parameters + *key_count = 0; + *data = NULL; + *data_len = 0; + + // allocate initial page of buffer + if (NULL == (pData = _alloc(state, CB_PAGE))) { + res = YKPIV_MEMORY_ERROR; + goto Cleanup; + } + + cbData = CB_PAGE; + + for (i = 0; i < sizeof(SLOTS); i++) { + cbBuf = sizeof(buf); + + if (YKPIV_OK == (res = _read_certificate(state, SLOTS[i], buf, &cbBuf))) { + // add current slot to result, grow result buffer if necessary + + cbRealloc = (sizeof(ykpiv_key) + cbBuf - 1) > (cbData - offset) ? MAX((sizeof(ykpiv_key) + cbBuf - 1) - (cbData - offset), CB_PAGE) : 0; + + if (0 != cbRealloc) { + if (NULL == (pData = _realloc(state, pData, cbData + cbRealloc))) { + res = YKPIV_MEMORY_ERROR; + goto Cleanup; + } + } + + cbData += cbRealloc; + + // If ykpiv_key is misaligned or results in padding, this causes problems + // in the array we return. If this becomes a problem, we'll probably want + // to go with a flat byte array. + + pKey = (ykpiv_key*)(pData + offset); + + pKey->slot = SLOTS[i]; + pKey->cert_len = (uint16_t)cbBuf; + memcpy(pKey->cert, buf, cbBuf); + + offset += sizeof(ykpiv_key) + cbBuf - 1; + (*key_count)++; + } + } + + *data = (ykpiv_key*)pData; + pData = NULL; + + if (data_len) { + *data_len = offset; + } + + res = YKPIV_OK; + +Cleanup: + + if (pData) { _free(state, pData); } + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_free(ykpiv_state *state, void *data) { + if (!data) return YKPIV_OK; + if (!state || (!(state->allocator.pfn_free))) return YKPIV_GENERIC_ERROR; + + _free(state, data); + + return YKPIV_OK; +} + +ykpiv_rc ykpiv_util_read_cert(ykpiv_state *state, uint8_t slot, uint8_t **data, size_t *data_len) { + ykpiv_rc res = YKPIV_OK; + uint8_t buf[CB_BUF_MAX]; + size_t cbBuf = sizeof(buf); + + if ((NULL == data )|| (NULL == data_len)) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + *data = 0; + *data_len = 0; + + if (YKPIV_OK == (res = _read_certificate(state, slot, buf, &cbBuf))) { + if (NULL == (*data = _alloc(state, cbBuf))) { + res = YKPIV_MEMORY_ERROR; + goto Cleanup; + } + + memcpy(*data, buf, cbBuf); + + *data_len = cbBuf; + } + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_write_cert(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len) { + ykpiv_rc res = YKPIV_OK; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + res = _write_certificate(state, slot, data, data_len); + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_delete_cert(ykpiv_state *state, uint8_t slot) { + return ykpiv_util_write_cert(state, slot, NULL, 0); +} + +ykpiv_rc ykpiv_util_read_mscmap(ykpiv_state *state, ykpiv_container **containers, size_t *n_containers) { + ykpiv_rc res = YKPIV_OK; + uint8_t buf[CB_BUF_MAX]; + size_t cbBuf = sizeof(buf); + size_t len = 0; + uint8_t *ptr = NULL; + + if ((NULL == containers) || (NULL == n_containers)) { res = YKPIV_GENERIC_ERROR; goto Cleanup; } + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + *containers = 0; + *n_containers = 0; + + if (YKPIV_OK == (res = ykpiv_fetch_object(state, YKPIV_OBJ_MSCMAP, buf, (unsigned long*)&cbBuf))) { + ptr = buf; + + // check that object contents are at least large enough to read the header + if (cbBuf < CB_OBJ_TAG_MIN) { + res = YKPIV_OK; + goto Cleanup; + } + + if (*ptr++ == TAG_MSCMAP) { + ptr += _ykpiv_get_length(ptr, &len); + + // check that decoded length represents object contents + if (len > (cbBuf - (ptr - buf))) { + res = YKPIV_OK; + goto Cleanup; + } + + if (NULL == (*containers = _alloc(state, len))) { + res = YKPIV_MEMORY_ERROR; + goto Cleanup; + } + + // should check if container map isn't corrupt + + memcpy(*containers, ptr, len); + *n_containers = len / sizeof(ykpiv_container); + } + } + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_write_mscmap(ykpiv_state *state, ykpiv_container *containers, size_t n_containers) { + ykpiv_rc res = YKPIV_OK; + uint8_t buf[CB_OBJ_MAX]; + size_t cbBuf = sizeof(buf); + size_t offset = 0; + size_t req_len = 0; + size_t data_len = n_containers * sizeof(ykpiv_container); + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + // check if data and data_len are zero, this means that + // we intend to delete the object + if ((NULL == containers) || (0 == n_containers)) { + + // if either containers or n_containers are non-zero, return an error, + // that we only delete strictly when both are set properly + if ((NULL != containers) || (0 != n_containers)) { + res = YKPIV_GENERIC_ERROR; + } + else { + res = ykpiv_save_object(state, YKPIV_OBJ_MSCMAP, NULL, 0); + } + + goto Cleanup; + } + + // encode object data for storage + + // calculate the required length of the encoded object + req_len = 1 /* data tag */ + _ykpiv_set_length(buf, data_len) + data_len; + + if (req_len > _obj_size_max(state)) return YKPIV_SIZE_ERROR; + + buf[offset++] = TAG_MSCMAP; + offset += _ykpiv_set_length(buf + offset, data_len); + memcpy(buf + offset, (uint8_t*)containers, data_len); + offset += data_len; + + // write onto device + res = ykpiv_save_object(state, YKPIV_OBJ_MSCMAP, buf, offset); + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_read_msroots(ykpiv_state *state, uint8_t **data, size_t *data_len) { + ykpiv_rc res = YKPIV_OK; + uint8_t buf[CB_BUF_MAX]; + size_t cbBuf = sizeof(buf); + size_t len = 0; + uint8_t *ptr = NULL; + int object_id = 0; + uint8_t tag = 0; + uint8_t *pData = NULL; + size_t cbData = 0; + size_t cbRealloc = 0; + size_t offset = 0; + + if (!data || !data_len) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + *data = 0; + *data_len = 0; + + // allocate first page + cbData = _obj_size_max(state); + if (NULL == (pData = _alloc(state, cbData))) { res = YKPIV_MEMORY_ERROR; goto Cleanup; } + + for (object_id = YKPIV_OBJ_MSROOTS1; object_id <= YKPIV_OBJ_MSROOTS5; object_id++) { + cbBuf = sizeof(buf); + + if (YKPIV_OK != (res = ykpiv_fetch_object(state, object_id, buf, (unsigned long*)&cbBuf))) { + goto Cleanup; + } + + ptr = buf; + + if (cbBuf < CB_OBJ_TAG_MIN) { + res = YKPIV_OK; + goto Cleanup; + } + + tag = *ptr++; + + if (((TAG_MSROOTS_MID != tag) && (TAG_MSROOTS_END != tag)) || + ((YKPIV_OBJ_MSROOTS5 == object_id) && (TAG_MSROOTS_END != tag))) { + // the current object doesn't contain a valid part of a msroots file + res = YKPIV_OK; // treat condition as object isn't found + goto Cleanup; + } + + ptr += _ykpiv_get_length(ptr, &len); + + // check that decoded length represents object contents + if (len > (cbBuf - (ptr - buf))) { + res = YKPIV_OK; + goto Cleanup; + } + + cbRealloc = len > (cbData - offset) ? len - (cbData - offset) : 0; + + if (0 != cbRealloc) { + if (NULL == (pData = _realloc(state, pData, cbData + cbRealloc))) { + res = YKPIV_MEMORY_ERROR; + goto Cleanup; + } + } + + cbData += cbRealloc; + + memcpy(pData + offset, ptr, len); + offset += len; + + if (TAG_MSROOTS_END == tag) { + break; + } + } + + // return data + *data = pData; + pData = NULL; + *data_len = offset; + + res = YKPIV_OK; + +Cleanup: + + if (pData) { _free(state, pData); } + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_write_msroots(ykpiv_state *state, uint8_t *data, size_t data_len) { + ykpiv_rc res = YKPIV_OK; + uint8_t buf[CB_OBJ_MAX]; + size_t offset = 0; + size_t data_offset = 0; + size_t data_chunk = 0; + size_t n_objs = 0; + unsigned int i = 0; + size_t cb_obj_max = _obj_size_max(state); + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + // check if either data and data_len are zero, this means that + // we intend to delete the object + if ((NULL == data) || (0 == data_len)) { + + // if either data or data_len are non-zero, return an error, + // that we only delete strictly when both are set properly + if ((NULL != data) || (0 != data_len)) { + res = YKPIV_GENERIC_ERROR; + } + else { + // it should be sufficient to just delete the first object, though + // to be complete we should erase all of the MSROOTS objects + res = ykpiv_save_object(state, YKPIV_OBJ_MSROOTS1, NULL, 0); + } + + goto Cleanup; + } + + // calculate number of objects required to store blob + n_objs = (data_len / (cb_obj_max - CB_OBJ_TAG_MAX)) + 1; + + // we're allowing 5 objects to be used to span the msroots file + if (n_objs > 5) { + res = YKPIV_SIZE_ERROR; + goto Cleanup; + } + + for (i = 0; i < n_objs; i++) { + offset = 0; + data_chunk = MIN(cb_obj_max - CB_OBJ_TAG_MAX, data_len - data_offset); + + // encode object data for storage + buf[offset++] = (i == (n_objs - 1)) ? TAG_MSROOTS_END : TAG_MSROOTS_MID; + offset += _ykpiv_set_length(buf + offset, data_chunk); + memcpy(buf + offset, data + data_offset, data_chunk); + offset += data_chunk; + + // write onto device + res = ykpiv_save_object(state, YKPIV_OBJ_MSROOTS1 + i, buf, offset); + + if (YKPIV_OK != res) { + goto Cleanup; + } + + data_offset += data_chunk; + } + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_generate_key(ykpiv_state *state, uint8_t slot, uint8_t algorithm, uint8_t pin_policy, uint8_t touch_policy, uint8_t **modulus, size_t *modulus_len, uint8_t **exp, size_t *exp_len, uint8_t **point, size_t *point_len) { + ykpiv_rc res = YKPIV_OK; + unsigned char in_data[11]; + unsigned char *in_ptr = in_data; + unsigned char data[1024]; + unsigned char templ[] = { 0, YKPIV_INS_GENERATE_ASYMMETRIC, 0, 0 }; + unsigned long recv_len = sizeof(data); + int sw; + uint8_t *ptr_modulus = NULL; + size_t cb_modulus = 0; + uint8_t *ptr_exp = NULL; + size_t cb_exp = 0; + uint8_t *ptr_point = NULL; + size_t cb_point = 0; + + switch (algorithm) { + case YKPIV_ALGO_RSA1024: + case YKPIV_ALGO_RSA2048: + if (!modulus || !modulus_len || !exp || !exp_len) { + if (state->verbose) { fprintf(stderr, "Invalid output parameter for RSA algorithm"); } + return YKPIV_GENERIC_ERROR; + } + *modulus = NULL; + *modulus_len = 0; + *exp = NULL; + *exp_len = 0; + break; + + case YKPIV_ALGO_ECCP256: + case YKPIV_ALGO_ECCP384: + if (!point || !point_len) { + if (state->verbose) { fprintf(stderr, "Invalid output parameter for ECC algorithm"); } + return YKPIV_GENERIC_ERROR; + } + *point = NULL; + *point_len = 0; + break; + + default: + if (state->verbose) { fprintf(stderr, "Invalid algorithm specified"); } + return YKPIV_GENERIC_ERROR; + } + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + templ[3] = slot; + + *in_ptr++ = 0xac; + *in_ptr++ = 3; + *in_ptr++ = YKPIV_ALGO_TAG; + *in_ptr++ = 1; + *in_ptr++ = algorithm; + + if (in_data[4] == 0) { + res = YKPIV_ALGORITHM_ERROR; + if (state->verbose) { fprintf(stderr, "Unexpected algorithm.\n"); } + goto Cleanup; + } + + if (pin_policy != YKPIV_PINPOLICY_DEFAULT) { + in_data[1] += 3; + *in_ptr++ = YKPIV_PINPOLICY_TAG; + *in_ptr++ = 1; + *in_ptr++ = pin_policy; + } + + if (touch_policy != YKPIV_TOUCHPOLICY_DEFAULT) { + in_data[1] += 3; + *in_ptr++ = YKPIV_TOUCHPOLICY_TAG; + *in_ptr++ = 1; + *in_ptr++ = touch_policy; + } + + if (YKPIV_OK != (res = ykpiv_transfer_data(state, templ, in_data, (long)(in_ptr - in_data), data, &recv_len, &sw))) { + if (state->verbose) { fprintf(stderr, "Failed to communicate.\n"); } + goto Cleanup; + } + else if (sw != SW_SUCCESS) { + if (state->verbose) { fprintf(stderr, "Failed to generate new key ("); } + + if (sw == SW_ERR_INCORRECT_SLOT) { + res = YKPIV_KEY_ERROR; + if (state->verbose) { fprintf(stderr, "incorrect slot)\n"); } + } + else if (sw == SW_ERR_INCORRECT_PARAM) { + res = YKPIV_ALGORITHM_ERROR; + + if (state->verbose) { + if (pin_policy != YKPIV_PINPOLICY_DEFAULT) { + fprintf(stderr, "pin policy not supported?)\n"); + } + else if (touch_policy != YKPIV_TOUCHPOLICY_DEFAULT) { + fprintf(stderr, "touch policy not supported?)\n"); + } + else { + fprintf(stderr, "algorithm not supported?)\n"); + } + } + } + else { + res = YKPIV_GENERIC_ERROR; + if (state->verbose) { fprintf(stderr, "error %x)\n", sw); } + } + + goto Cleanup; + } + + if ((YKPIV_ALGO_RSA1024 == algorithm) || (YKPIV_ALGO_RSA2048 == algorithm)) { + unsigned char *data_ptr = data + 5; + size_t len = 0; + + if (*data_ptr != TAG_RSA_MODULUS) { + if (state->verbose) { fprintf(stderr, "Failed to parse public key structure (modulus).\n"); } + res = YKPIV_PARSE_ERROR; + goto Cleanup; + } + + data_ptr++; + data_ptr += _ykpiv_get_length(data_ptr, &len); + + cb_modulus = len; + if (NULL == (ptr_modulus = _alloc(state, cb_modulus))) { + if (state->verbose) { fprintf(stderr, "Failed to allocate memory for modulus.\n"); } + res = YKPIV_MEMORY_ERROR; + goto Cleanup; + } + + memcpy(ptr_modulus, data_ptr, cb_modulus); + + data_ptr += len; + + if (*data_ptr != TAG_RSA_EXP) { + if (state->verbose) { fprintf(stderr, "Failed to parse public key structure (public exponent).\n"); } + res = YKPIV_PARSE_ERROR; + goto Cleanup; + } + + data_ptr++; + data_ptr += _ykpiv_get_length(data_ptr, &len); + + cb_exp = len; + if (NULL == (ptr_exp = _alloc(state, cb_exp))) { + if (state->verbose) { fprintf(stderr, "Failed to allocate memory for public exponent.\n"); } + res = YKPIV_MEMORY_ERROR; + goto Cleanup; + } + + memcpy(ptr_exp, data_ptr, cb_exp); + + // set output parameters + + *modulus = ptr_modulus; + ptr_modulus = NULL; + *modulus_len = cb_modulus; + *exp = ptr_exp; + ptr_exp = NULL; + *exp_len = cb_exp; + } + else if ((YKPIV_ALGO_ECCP256 == algorithm) || (YKPIV_ALGO_ECCP384 == algorithm)) { + unsigned char *data_ptr = data + 3; + size_t len; + + if (YKPIV_ALGO_ECCP256 == algorithm) { + len = CB_ECC_POINTP256; + } + else { + len = CB_ECC_POINTP384; + } + + if (*data_ptr++ != TAG_ECC_POINT) { + if (state->verbose) { fprintf(stderr, "Failed to parse public key structure.\n"); } + res = YKPIV_PARSE_ERROR; + goto Cleanup; + } + + if (*data_ptr++ != len) { /* the curve point should always be determined by the curve */ + if (state->verbose) { fprintf(stderr, "Unexpected length.\n"); } + res = YKPIV_ALGORITHM_ERROR; + goto Cleanup; + } + + cb_point = len; + if (NULL == (ptr_point = _alloc(state, cb_point))) { + if (state->verbose) { fprintf(stderr, "Failed to allocate memory for public point.\n"); } + res = YKPIV_MEMORY_ERROR; + goto Cleanup; + } + + memcpy(ptr_point, data_ptr, cb_point); + + // set output parameters + + *point = ptr_point; + ptr_point = NULL; + *point_len = cb_point; + } + else { + if (state->verbose) { fprintf(stderr, "Wrong algorithm.\n"); } + res = YKPIV_ALGORITHM_ERROR; + goto Cleanup; + } + +Cleanup: + + if (ptr_modulus) { _free(state, modulus); } + if (ptr_exp) { _free(state, ptr_exp); } + if (ptr_point) { _free(state, ptr_exp); } + + _ykpiv_end_transaction(state); + return res; +} + + +ykpiv_rc ykpiv_util_reset(ykpiv_state *state) { + unsigned char templ[] = {0, YKPIV_INS_RESET, 0, 0}; + unsigned char data[0xff]; + unsigned long recv_len = sizeof(data); + ykpiv_rc res; + int sw; + + /* note: the reset function is only available when both pins are blocked. */ + res = ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw); + if (SW_SUCCESS == sw) { + return YKPIV_OK; + } + return res; +} + +static int _slot2object(uint8_t slot) { + int object_id = -1; + + switch (slot) { + case YKPIV_KEY_AUTHENTICATION: + object_id = YKPIV_OBJ_AUTHENTICATION; + break; + + case YKPIV_KEY_SIGNATURE: + object_id = YKPIV_OBJ_SIGNATURE; + break; + + case YKPIV_KEY_KEYMGM: + object_id = YKPIV_OBJ_KEY_MANAGEMENT; + break; + + case YKPIV_KEY_CARDAUTH: + object_id = YKPIV_OBJ_CARD_AUTH; + break; + + case YKPIV_KEY_ATTESTATION: + object_id = YKPIV_OBJ_ATTESTATION; + break; + + default: + if ((slot >= YKPIV_KEY_RETIRED1) && (slot <= YKPIV_KEY_RETIRED20)) { + object_id = YKPIV_OBJ_RETIRED1 + (slot - YKPIV_KEY_RETIRED1); + } + break; + } + + return object_id; +} + +static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf, size_t *buf_len) { + ykpiv_rc res = YKPIV_OK; + uint8_t *ptr = NULL; + int object_id = _slot2object(slot); + size_t len = 0; + + if (-1 == object_id) return YKPIV_INVALID_OBJECT; + + if (YKPIV_OK == (res = ykpiv_fetch_object(state, object_id, buf, (unsigned long*)buf_len))) { + ptr = buf; + + // check that object contents are at least large enough to read the tag + if (*buf_len < CB_OBJ_TAG_MIN) { + *buf_len = 0; + return YKPIV_OK; + } + + // check that first byte indicates "certificate" type + + if (*ptr++ == TAG_CERT) { + ptr += _ykpiv_get_length(ptr, &len); + + // check that decoded length represents object contents + if (len > (*buf_len - (ptr - buf))) { + *buf_len = 0; + return YKPIV_OK; + } + + memmove(buf, ptr, len); + *buf_len = len; + } + } + else { + *buf_len = 0; + } + + return res; +} + +static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len) { + uint8_t buf[CB_OBJ_MAX]; + size_t cbBuf = sizeof(buf); + int object_id = _slot2object(slot); + size_t offset = 0; + size_t req_len = 0; + + if (-1 == object_id) return YKPIV_INVALID_OBJECT; + + // check if data or data_len are zero, this means that we intend to delete the object + if ((NULL == data) || (0 == data_len)) { + + // if either data or data_len are non-zero, return an error, + // that we only delete strictly when both are set properly + if ((NULL != data) || (0 != data_len)) { + return YKPIV_GENERIC_ERROR; + } + + return ykpiv_save_object(state, object_id, NULL, 0); + } + + // encode certificate data for storage + + // calculate the required length of the encoded object + req_len = 1 /* cert tag */ + 3 /* compression tag + data*/ + 2 /* lrc */; + req_len += _ykpiv_set_length(buf, data_len); + + if (req_len > _obj_size_max(state)) return YKPIV_SIZE_ERROR; + + buf[offset++] = TAG_CERT; + offset += _ykpiv_set_length(buf + offset, data_len); + memcpy(buf + offset, data, data_len); + offset += data_len; + + // write compression info and LRC trailer + buf[offset++] = TAG_CERT_COMPRESS; + buf[offset++] = 0x01; + buf[offset++] = 0x00; // TODO: Handle compression when certificate exceeds buffer size + buf[offset++] = TAG_CERT_LRC; // LRC + buf[offset++] = 00; + + // write onto device + return ykpiv_save_object(state, object_id, buf, offset); +} diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 8b97b41..16e6c41 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -44,6 +44,33 @@ static ykpiv_rc send_data(ykpiv_state *state, APDU *apdu, unsigned char *data, unsigned long *recv_len, int *sw); +unsigned const char aid[] = { + 0xa0, 0x00, 0x00, 0x03, 0x08 +}; + + +static void* _default_alloc(void *data, size_t cb) { + (void)data; + return calloc(cb, 1); +} + +static void * _default_realloc(void *data, void *p, size_t cb) { + (void)data; + return realloc(p, cb); +} + +static void _default_free(void *data, void *p) { + (void)data; + free(p); +} + +ykpiv_allocator _default_allocator = { + .pfn_alloc = _default_alloc, + .pfn_realloc = _default_realloc, + .pfn_free = _default_free, + .alloc_data = 0 +}; + static void dump_hex(const unsigned char *buf, unsigned int len) { unsigned int i; for (i = 0; i < len; i++) { @@ -51,7 +78,7 @@ static void dump_hex(const unsigned char *buf, unsigned int len) { } } -static int set_length(unsigned char *buffer, size_t length) { +int _ykpiv_set_length(unsigned char *buffer, size_t length) { if(length < 0x80) { *buffer++ = length; return 1; @@ -67,7 +94,7 @@ static int set_length(unsigned char *buffer, size_t length) { } } -static int get_length(const unsigned char *buffer, size_t *len) { +int _ykpiv_get_length(const unsigned char *buffer, size_t *len) { if(buffer[0] < 0x81) { *len = buffer[0]; return 1; @@ -96,19 +123,33 @@ static unsigned char *set_object(int object_id, unsigned char *buffer) { return buffer; } -ykpiv_rc ykpiv_init(ykpiv_state **state, int verbose) { - ykpiv_state *s = malloc(sizeof(ykpiv_state)); - if(s == NULL) { +ykpiv_rc ykpiv_init_with_allocator(ykpiv_state **state, int verbose, const ykpiv_allocator *allocator) { + ykpiv_state *s; + if (NULL == state) { + return YKPIV_GENERIC_ERROR; + } + if (NULL == allocator || !allocator->pfn_alloc || !allocator->pfn_realloc || !allocator->pfn_free) { return YKPIV_MEMORY_ERROR; } + + s = allocator->pfn_alloc(allocator->alloc_data, sizeof(ykpiv_state)); + if (NULL == s) { + return YKPIV_MEMORY_ERROR; + } + memset(s, 0, sizeof(ykpiv_state)); s->pin = NULL; + s->allocator = *allocator; s->verbose = verbose; - s->context = SCARD_E_INVALID_HANDLE; + s->context = SCARD_E_INVALID_HANDLE; // TREV TODO -1 on Windows *state = s; return YKPIV_OK; } +ykpiv_rc ykpiv_init(ykpiv_state **state, int verbose) { + return ykpiv_init_with_allocator(state, verbose, &_default_allocator); +} + ykpiv_rc ykpiv_done(ykpiv_state *state) { ykpiv_disconnect(state); free(state->pin); @@ -130,7 +171,7 @@ ykpiv_rc ykpiv_disconnect(ykpiv_state *state) { return YKPIV_OK; } -static ykpiv_rc select_application(ykpiv_state *state) { +ykpiv_rc _ykpiv_select_application(ykpiv_state *state) { APDU apdu; unsigned char data[0xff]; unsigned long recv_len = sizeof(data); @@ -158,12 +199,32 @@ static ykpiv_rc select_application(ykpiv_state *state) { } } +ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state) { + ykpiv_rc res = YKPIV_OK; + + if (NULL == state) { + return YKPIV_GENERIC_ERROR; + } + + res = ykpiv_verify(state, NULL, 0); + + if ((YKPIV_OK != res) && (YKPIV_WRONG_PIN != res)) { + res = _ykpiv_select_application(state); + } + else { + res = YKPIV_OK; + } + + return res; +} + ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { unsigned long active_protocol; char reader_buf[2048]; size_t num_readers = sizeof(reader_buf); long rc; char *reader_ptr; + SCARDHANDLE card = (SCARDHANDLE)-1; ykpiv_rc ret = ykpiv_list_readers(state, reader_buf, &num_readers); if(ret != YKPIV_OK) { @@ -183,7 +244,7 @@ ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { fprintf(stderr, "trying to connect to reader '%s'.\n", reader_ptr); } rc = SCardConnect(state->context, reader_ptr, SCARD_SHARE_SHARED, - SCARD_PROTOCOL_T1, &state->card, &active_protocol); + SCARD_PROTOCOL_T1, &card, &active_protocol); if(rc != SCARD_S_SUCCESS) { if(state->verbose) { @@ -191,7 +252,24 @@ ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { } continue; } - if (select_application(state) != YKPIV_OK) { + + // if card handle has changed, determine if handle is valid (less efficient, but complete) + if ((card != state->card)) { + char reader[CB_BUF_MAX]; + uint32_t reader_len = (uint32_t)sizeof(reader); + uint8_t atr[CB_ATR_MAX]; + uint32_t atr_len = (uint32_t)sizeof(atr); + + // Cannot set the reader len to NULL. Confirmed in OSX 10.10, so we have to retrieve it even though we don't need it. + if (SCARD_S_SUCCESS != SCardStatus(card, reader, &reader_len, NULL, NULL, atr, &atr_len)) { + return YKPIV_PCSC_ERROR; + } + + state->isNEO = (((sizeof(ATR_NEO_R3) - 1) == atr_len) && (0 == memcmp(ATR_NEO_R3, atr, atr_len))); + } + state->card = card; + + if (_ykpiv_select_application(state) != YKPIV_OK) { continue; } return YKPIV_OK; @@ -226,7 +304,7 @@ static ykpiv_rc reconnect(ykpiv_state *state) { } return YKPIV_PCSC_ERROR; } - if ((res = select_application(state)) != YKPIV_OK) { + if ((res = _ykpiv_select_application(state)) != YKPIV_OK) { return res; } if (state->pin) { @@ -279,7 +357,7 @@ ykpiv_rc ykpiv_list_readers(ykpiv_state *state, char *readers, size_t *len) { return YKPIV_OK; } -static ykpiv_rc begin_transaction(ykpiv_state *state) { +ykpiv_rc _ykpiv_begin_transaction(ykpiv_state *state) { long rc; ykpiv_rc res; @@ -299,7 +377,7 @@ static ykpiv_rc begin_transaction(ykpiv_state *state) { return YKPIV_OK; } -static ykpiv_rc end_transaction(ykpiv_state *state) { +ykpiv_rc _ykpiv_end_transaction(ykpiv_state *state) { long rc = SCardEndTransaction(state->card, SCARD_LEAVE_CARD); if(rc != SCARD_S_SUCCESS && state->verbose) { fprintf(stderr, "error: Failed to end pcsc transaction, rc=%08lx\n", rc); @@ -316,7 +394,7 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, ykpiv_rc res; *out_len = 0; - res = begin_transaction(state); + res = _ykpiv_begin_transaction(state); if (res != YKPIV_OK) { return res; } @@ -340,16 +418,16 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, memcpy(apdu.st.data, in_ptr, this_size); res = send_data(state, &apdu, data, &recv_len, sw); if(res != YKPIV_OK) { - end_transaction(state); + _ykpiv_end_transaction(state); return res; } else if(*sw != SW_SUCCESS && *sw >> 8 != 0x61) { - return end_transaction(state); + return _ykpiv_end_transaction(state); } if(*out_len + recv_len - 2 > max_out) { if(state->verbose) { fprintf(stderr, "Output buffer to small, wanted to write %lu, max was %lu.\n", *out_len + recv_len - 2, max_out); } - end_transaction(state); + _ykpiv_end_transaction(state); return YKPIV_SIZE_ERROR; } if(out_data) { @@ -372,10 +450,10 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, apdu.st.ins = 0xc0; res = send_data(state, &apdu, data, &recv_len, sw); if(res != YKPIV_OK) { - end_transaction(state); + _ykpiv_end_transaction(state); return res; } else if(*sw != SW_SUCCESS && *sw >> 8 != 0x61) { - return end_transaction(state); + return _ykpiv_end_transaction(state); } if(*out_len + recv_len - 2 > max_out) { fprintf(stderr, "Output buffer to small, wanted to write %lu, max was %lu.", *out_len + recv_len - 2, max_out); @@ -386,7 +464,7 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, *out_len += recv_len - 2; } } - return end_transaction(state); + return _ykpiv_end_transaction(state); } static ykpiv_rc send_data(ykpiv_state *state, APDU *apdu, @@ -430,6 +508,8 @@ ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { DES_key_schedule ks1, ks2, ks3; + // TREV TODO: default/derived key + /* set up our key */ { const_DES_cblock key_tmp; @@ -639,11 +719,11 @@ static ykpiv_rc _general_authenticate(ykpiv_state *state, } *dataptr++ = 0x7c; - dataptr += set_length(dataptr, in_len + bytes + 3); + dataptr += _ykpiv_set_length(dataptr, in_len + bytes + 3); *dataptr++ = 0x82; *dataptr++ = 0x00; *dataptr++ = YKPIV_IS_EC(algorithm) && decipher ? 0x85 : 0x81; - dataptr += set_length(dataptr, in_len); + dataptr += _ykpiv_set_length(dataptr, in_len); memcpy(dataptr, sign_in, (size_t)in_len); dataptr += in_len; @@ -670,7 +750,7 @@ static ykpiv_rc _general_authenticate(ykpiv_state *state, return YKPIV_PARSE_ERROR; } dataptr = data + 1; - dataptr += get_length(dataptr, &len); + dataptr += _ykpiv_get_length(dataptr, &len); /* skip the 82 tag */ if(*dataptr != 0x82) { if(state->verbose) { @@ -679,7 +759,7 @@ static ykpiv_rc _general_authenticate(ykpiv_state *state, return YKPIV_PARSE_ERROR; } dataptr++; - dataptr += get_length(dataptr, &len); + dataptr += _ykpiv_get_length(dataptr, &len); if(len > *out_len) { if(state->verbose) { fprintf(stderr, "Wrong size on output buffer.\n"); @@ -768,10 +848,10 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { } return YKPIV_OK; } else if((sw >> 8) == 0x63) { - *tries = (sw & 0xf); + if (tries) *tries = (sw & 0xf); return YKPIV_WRONG_PIN; } else if(sw == SW_ERR_AUTH_BLOCKED) { - *tries = 0; + if (tries) *tries = 0; return YKPIV_WRONG_PIN; } else { return YKPIV_GENERIC_ERROR; @@ -869,7 +949,7 @@ ykpiv_rc ykpiv_fetch_object(ykpiv_state *state, int object_id, if(sw == SW_SUCCESS) { size_t outlen; - int offs = get_length(data + 1, &outlen); + int offs = _ykpiv_get_length(data + 1, &outlen); if(offs == 0) { return YKPIV_SIZE_ERROR; } @@ -884,6 +964,7 @@ ykpiv_rc ykpiv_fetch_object(ykpiv_state *state, int object_id, ykpiv_rc ykpiv_save_object(ykpiv_state *state, int object_id, unsigned char *indata, size_t len) { + // TREV TODO: buffer sizes different in minidriver unsigned char data[3072]; unsigned char *dataptr = data; unsigned char templ[] = {0, YKPIV_INS_PUT_DATA, 0x3f, 0xff}; @@ -899,7 +980,7 @@ ykpiv_rc ykpiv_save_object(ykpiv_state *state, int object_id, return YKPIV_INVALID_OBJECT; } *dataptr++ = 0x53; - dataptr += set_length(dataptr, len); + dataptr += _ykpiv_set_length(dataptr, len); memcpy(dataptr, indata, len); dataptr += len; @@ -908,9 +989,13 @@ ykpiv_rc ykpiv_save_object(ykpiv_state *state, int object_id, return res; } - if(sw == SW_SUCCESS) { + if(SW_SUCCESS == sw) { return YKPIV_OK; - } else { + } + else if (SW_ERR_SECURITY_STATUS == sw) { + return YKPIV_AUTHENTICATION_ERROR; + } + else { return YKPIV_GENERIC_ERROR; } } @@ -1008,7 +1093,7 @@ ykpiv_rc ykpiv_import_private_key(ykpiv_state *state, const unsigned char key, u for (i = 0; i < n_params; i++) { *in_ptr++ = param_tag + i; - in_ptr += set_length(in_ptr, elem_len); + in_ptr += _ykpiv_set_length(in_ptr, elem_len); padding = elem_len - lens[i]; memset(in_ptr, 0, padding); in_ptr += padding; diff --git a/lib/ykpiv.h b/lib/ykpiv.h index d040b4e..2374c02 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -58,6 +58,9 @@ extern "C" YKPIV_INVALID_OBJECT = -11, YKPIV_ALGORITHM_ERROR = -12, YKPIV_PIN_LOCKED = -13, + + YKPIV_ARGUMENT_ERROR = -14, //i.e. invalid input argument + YKPIV_RANGE_ERROR = -15 //i.e. value range error } ykpiv_rc; const char *ykpiv_strerror(ykpiv_rc err); @@ -220,6 +223,124 @@ extern "C" #define YKPIV_IS_EC(a) ((a == YKPIV_ALGO_ECCP256 || a == YKPIV_ALGO_ECCP384)) #define YKPIV_IS_RSA(a) ((a == YKPIV_ALGO_RSA1024 || a == YKPIV_ALGO_RSA2048)) + + + +// +// UTIL +// + +#define DEVTYPE_UNKNOWN 0x00000000 +#define DEVTYPE_NEO 0x4E450000 //"NE" +#define DEVTYPE_YK 0x594B0000 //"YK" +#define DEVTYPE_NEOr3 (DEVTYPE_NEO | 0x00007233) //"r3" +#define DEVTYPE_YK4 (DEVTYPE_YK | 0x00000034) // "4" + typedef uint32_t ykpiv_devmodel; + +#pragma pack(push, 1) + + typedef struct _ykpiv_key { + uint8_t slot; + uint16_t cert_len; + uint8_t cert[1]; + } ykpiv_key; + + typedef struct _ykpiv_container { + wchar_t name[40]; + uint8_t slot; + uint8_t key_spec; + uint16_t key_size_bits; + uint8_t flags; + uint8_t pin_id; + uint8_t associated_echd_container; + uint8_t cert_fingerprint[20]; + } ykpiv_container; + +#pragma pack(pop) + + /* Util api always allocates data on your behalf, if data = 0, *data != 0, or data_len = 0 an invalid parameter will be returned; to free data, call ykpiv_util_free(). */ + + /** + * Free allocated data + * + * @param state state + * @param data pointer to buffer allocated by ykpiv + * + * @return ypiv_rc error code + */ + ykpiv_rc ykpiv_util_free(ykpiv_state *state, void *data); + + ykpiv_rc ykpiv_util_list_keys(ykpiv_state *state, uint8_t *key_count, ykpiv_key **data, size_t *data_len); + ykpiv_rc ykpiv_util_read_cert(ykpiv_state *state, uint8_t slot, uint8_t **data, size_t *data_len); + ykpiv_rc ykpiv_util_write_cert(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len); + ykpiv_rc ykpiv_util_delete_cert(ykpiv_state *state, uint8_t slot); + + /** + * Generate Key + * + * @param state state + * @param slot key slot + * @param algorithm algorithm + * + * @return ykpiv_rc error code + * + * If algorithm is RSA1024 or RSA2048, the modulus, modulus_len, exp, and exp_len output parameters must be supplied. They are filled with with public modulus (big-endian), its size, the public exponent (big-endian), and its size respectively. + * If algorithm is ECCP256 or ECCP384, the point and point_len output parameters must be supplied. They are filled with the public point (uncompressed octet-string encoded per SEC1 section 2.3.4) + * If algorithm is ECCP256, the curve is always ANSI X9.62 Prime 256v1 + * If algorithm is ECCP384, the curve is always secp384r1 + */ + ykpiv_rc ykpiv_util_generate_key(ykpiv_state *state, uint8_t slot, uint8_t algorithm, uint8_t pin_policy, uint8_t touch_policy, uint8_t **modulus, size_t *modulus_len, uint8_t **exp, size_t *exp_len, uint8_t **point, size_t *point_len); + + ykpiv_rc ykpiv_util_read_mscmap(ykpiv_state *state, ykpiv_container **containers, size_t *n_containers); + ykpiv_rc ykpiv_util_write_mscmap(ykpiv_state *state, ykpiv_container *containers, size_t n_containers); + ykpiv_rc ykpiv_util_read_msroots(ykpiv_state *state, uint8_t **data, size_t *data_len); + ykpiv_rc ykpiv_util_write_msroots(ykpiv_state *state, uint8_t *data, size_t data_len); + + ykpiv_rc ykpiv_util_reset(ykpiv_state *state); + + /** + * Card identifier + */ + typedef struct { + uint8_t data[16]; + } ykpiv_cardid; + + /** + * Get card identifier + * + * @param state state + * @param cardid ykpiv_cardid return value + * + * @return ykpiv_rc error code + */ + ykpiv_rc ykpiv_util_get_cardid(ykpiv_state *state, ykpiv_cardid *cardid); + + /** + * Set card identifier + * + * The card must be authenticated to call this function. + * + * @param state state + * @param cardid cardid to set, if NULL, randomly generate + * + * @return ypiv_rc error code + * + */ + ykpiv_rc ykpiv_util_set_cardid(ykpiv_state *state, const ykpiv_cardid *cardid); + + /** + * Get device model + * + * The card must be connected to call this function. + * + * @param state state + * + * @return device model + * + */ + ykpiv_devmodel ykpiv_util_devicemodel(ykpiv_state *state); + + #ifdef __cplusplus } #endif From cffe862bbc7d38fd8d9fc9078117c5e440ead6d3 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 10 Jul 2017 17:16:05 +0200 Subject: [PATCH 05/57] Test cases for ykpiv_util_* functions --- lib/tests/Makefile.am | 2 +- lib/tests/util.c | 211 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 212 insertions(+), 1 deletion(-) create mode 100644 lib/tests/util.c diff --git a/lib/tests/Makefile.am b/lib/tests/Makefile.am index f83a46f..29627af 100644 --- a/lib/tests/Makefile.am +++ b/lib/tests/Makefile.am @@ -31,7 +31,7 @@ AM_CPPFLAGS = -I$(top_srcdir)/lib -I$(top_builddir)/lib AM_LDFLAGS = -no-install @CHECK_LIBS@ LDADD = ../libykpiv.la -check_PROGRAMS = basic parse_key +check_PROGRAMS = basic parse_key util TESTS = $(check_PROGRAMS) LOG_COMPILER = $(VALGRIND) diff --git a/lib/tests/util.c b/lib/tests/util.c new file mode 100644 index 0000000..f8049d2 --- /dev/null +++ b/lib/tests/util.c @@ -0,0 +1,211 @@ +/* + * Copyright (c) 2014-2016 Yubico AB + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "ykpiv.h" +#include "internal.h" + +#include +#include +#include +#include + +#include + +ykpiv_state *g_state; +const uint8_t g_cert[] = { + "0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK" + "0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK" + "0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK" + "0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK" + "0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK" +}; + +void setup(void) { + ykpiv_rc res; + const char *mgm_key = "010203040506070801020304050607080102030405060708"; + unsigned char key[24]; + size_t key_len = sizeof(key); + + res = ykpiv_init(&g_state, true); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_connect(g_state, NULL); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_hex_decode(mgm_key, strlen(mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_authenticate(g_state, key); + ck_assert_int_eq(res, YKPIV_OK); +} +void teardown(void) { + ykpiv_done(g_state); +} + +START_TEST(test_devicemodel) { + ykpiv_devmodel model; + model = ykpiv_util_devicemodel(g_state); + fprintf(stderr, "Model: %u\n", model); + ck_assert(model == DEVTYPE_YK4); +} +END_TEST + +START_TEST(test_get_set_cardid) { + ykpiv_rc res; + ykpiv_cardid set_id; + ykpiv_cardid get_id; + + memset(&set_id.data, 'i', sizeof(set_id.data)); + memset(&get_id.data, 0, sizeof(get_id.data)); + + res = ykpiv_util_set_cardid(g_state, &set_id); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_util_get_cardid(g_state, &get_id); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_mem_eq(&set_id.data, &get_id.data, sizeof(set_id.data)); +} +END_TEST + +START_TEST(test_read_write_list_delete_cert) { + ykpiv_rc res; + uint8_t *read_cert = NULL; + size_t read_cert_len = 0; + + { + res = ykpiv_util_write_cert(g_state, YKPIV_KEY_AUTHENTICATION, (uint8_t*)g_cert, sizeof(g_cert)); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_util_read_cert(g_state, YKPIV_KEY_AUTHENTICATION, &read_cert, &read_cert_len); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_ptr_nonnull(read_cert); + ck_assert_int_eq(read_cert_len, sizeof(g_cert)); + ck_assert_mem_eq(g_cert, read_cert, sizeof(g_cert)); + + res = ykpiv_util_free(g_state, read_cert); + ck_assert_int_eq(res, YKPIV_OK); + } + + { + ykpiv_key *keys = NULL; + size_t data_len; + uint8_t key_count; + res = ykpiv_util_list_keys(g_state, &key_count, &keys, &data_len); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_ptr_nonnull(keys); + ck_assert_int_gt(key_count, 0); + + res = ykpiv_util_free(g_state, keys); + ck_assert_int_eq(res, YKPIV_OK); + } + + { + res = ykpiv_util_delete_cert(g_state, YKPIV_KEY_AUTHENTICATION); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_util_read_cert(g_state, YKPIV_KEY_AUTHENTICATION, &read_cert, &read_cert_len); + ck_assert_int_eq(res, YKPIV_GENERIC_ERROR); + + res = ykpiv_util_free(g_state, read_cert); + ck_assert_int_eq(res, YKPIV_OK); + } +} +END_TEST + +START_TEST(test_generate_key) { + ykpiv_rc res; + uint8_t *mod, *exp; + size_t mod_len, exp_len; + res = ykpiv_util_write_cert(g_state, YKPIV_KEY_AUTHENTICATION, (uint8_t*)g_cert, sizeof(g_cert)); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_util_generate_key(g_state, + YKPIV_KEY_AUTHENTICATION, + YKPIV_ALGO_RSA2048, + YKPIV_PINPOLICY_ONCE, + YKPIV_TOUCHPOLICY_DEFAULT, + &mod, + &mod_len, + &exp, + &exp_len, + NULL, + NULL); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_util_free(g_state, mod); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_util_free(g_state, exp); + ck_assert_int_eq(res, YKPIV_OK); + // TODO: and?? +} +END_TEST + +START_TEST(test_read_write_mscmap) { +} +END_TEST + +START_TEST(test_read_write_msroots) { +} +END_TEST + +START_TEST(test_reset) { +} +END_TEST + +Suite *test_suite(void) { + Suite *s; + TCase *tc; + + s = suite_create("libykpiv util"); + tc = tcase_create("util"); +#ifdef HW_TESTS + tcase_add_unchecked_fixture(tc, setup, teardown); + tcase_add_test(tc, test_devicemodel); + tcase_add_test(tc, test_get_set_cardid); + tcase_add_test(tc, test_read_write_list_delete_cert); + tcase_add_test(tc, test_generate_key); +#endif + suite_add_tcase(s, tc); + + return s; +} + +int main(void) +{ + int number_failed; + Suite *s; + SRunner *sr; + + s = test_suite(); + sr = srunner_create(s); + srunner_set_fork_status(sr, CK_NOFORK); + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; +} From bfafb926a3847964eb2081b94c3e195160f10211 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Wed, 12 Jul 2017 13:19:15 +0200 Subject: [PATCH 06/57] Added tests for authenticate and reset. Fixed bug in reset (always returned success). --- lib/tests/util.c | 84 ++++++++++++++++++++++++++++++++++++++++++------ lib/util.c | 4 +-- 2 files changed, 76 insertions(+), 12 deletions(-) diff --git a/lib/tests/util.c b/lib/tests/util.c index f8049d2..4409333 100644 --- a/lib/tests/util.c +++ b/lib/tests/util.c @@ -38,6 +38,8 @@ #include +int confirm_destruction(void); + ykpiv_state *g_state; const uint8_t g_cert[] = { "0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK0123456789ABCDEFGHIK" @@ -49,22 +51,18 @@ const uint8_t g_cert[] = { void setup(void) { ykpiv_rc res; - const char *mgm_key = "010203040506070801020304050607080102030405060708"; - unsigned char key[24]; - size_t key_len = sizeof(key); + + // Require user confirmation to continue, since this test suite will clear + // any data stored on connected keys. + ck_assert(confirm_destruction()); res = ykpiv_init(&g_state, true); ck_assert_int_eq(res, YKPIV_OK); res = ykpiv_connect(g_state, NULL); ck_assert_int_eq(res, YKPIV_OK); - - res = ykpiv_hex_decode(mgm_key, strlen(mgm_key), key, &key_len); - ck_assert_int_eq(res, YKPIV_OK); - - res = ykpiv_authenticate(g_state, key); - ck_assert_int_eq(res, YKPIV_OK); } + void teardown(void) { ykpiv_done(g_state); } @@ -173,10 +171,68 @@ START_TEST(test_read_write_msroots) { } END_TEST -START_TEST(test_reset) { +START_TEST(test_authenticate) { + ykpiv_rc res; + const char *mgm_key = "010203040506070801020304050607080102030405060708"; + unsigned char key[24]; + size_t key_len = sizeof(key); + + res = ykpiv_hex_decode(mgm_key, strlen(mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_authenticate(g_state, key); + ck_assert_int_eq(res, YKPIV_OK); } END_TEST +START_TEST(test_reset) { + ykpiv_rc res; + int tries = 100; + int i; + + while (tries) { + res = ykpiv_verify(g_state, "AAAAAA", &tries); + if (res == YKPIV_PIN_LOCKED) + break; + ck_assert_int_eq(res, YKPIV_WRONG_PIN); + } + tries = 100; + while (tries) { + res = ykpiv_change_puk(g_state, "AAAAAAAA", 8, "AAAAAAAA", 8, &tries); + if (res == YKPIV_PIN_LOCKED) + break; + ck_assert_int_eq(res, YKPIV_WRONG_PIN); + } + res = ykpiv_util_reset(g_state); + ck_assert_int_eq(res, YKPIV_OK); +} +END_TEST + +int confirm_destruction(void) { + char verify[16]; + + // Use dprintf() to write directly to stdout, since automake eats the standard stdout/stderr pointers. + dprintf(0, "******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******\n"); + dprintf(0, "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING\n"); + dprintf(0, "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING\n"); + dprintf(0, "\n"); + + dprintf(0, "******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******\n"); + dprintf(0, "\n"); + dprintf(0, " ALL DATA WILL BE ERASED ON CONNECTED YUBIKEYS \n"); + dprintf(0, "\n"); + dprintf(0, "******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******\n"); + dprintf(0, "\n"); + + dprintf(0, "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING\n"); + dprintf(0, "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING\n"); + dprintf(0, "******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******\n"); + dprintf(0, "\n"); + dprintf(0, "Are you SURE you wish to proceed? If so, type 'CONFIRM': "); + fgets(verify, 32, stdin); + return strncmp(verify, "CONFIRM", 7) == 0; +} + Suite *test_suite(void) { Suite *s; TCase *tc; @@ -185,6 +241,13 @@ Suite *test_suite(void) { tc = tcase_create("util"); #ifdef HW_TESTS tcase_add_unchecked_fixture(tc, setup, teardown); + + // Reset first. Tests run serially, and depend on a clean slate. + tcase_add_test(tc, test_reset); + + // Authenticate after reset. + tcase_add_test(tc, test_authenticate); + tcase_add_test(tc, test_devicemodel); tcase_add_test(tc, test_get_set_cardid); tcase_add_test(tc, test_read_write_list_delete_cert); @@ -207,5 +270,6 @@ int main(void) srunner_run_all(sr, CK_NORMAL); number_failed = srunner_ntests_failed(sr); srunner_free(sr); + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; } diff --git a/lib/util.c b/lib/util.c index dd58add..b431132 100644 --- a/lib/util.c +++ b/lib/util.c @@ -878,10 +878,10 @@ ykpiv_rc ykpiv_util_reset(ykpiv_state *state) { /* note: the reset function is only available when both pins are blocked. */ res = ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw); - if (SW_SUCCESS == sw) { + if (YKPIV_OK == res && SW_SUCCESS == sw) { return YKPIV_OK; } - return res; + return YKPIV_GENERIC_ERROR; } static int _slot2object(uint8_t slot) { From 2ea0e4cbddee2f78ae1c30e472343a8410f02f43 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Wed, 12 Jul 2017 17:23:52 +0200 Subject: [PATCH 07/57] Port custom allocator from minidriver, and add test case for it. --- lib/internal.h | 14 +------ lib/tests/util.c | 106 +++++++++++++++++++++++++++++++++++++++++++++-- lib/util.c | 50 ++++++++-------------- lib/ykpiv.c | 30 +++++++++++--- lib/ykpiv.h | 11 +++++ 5 files changed, 158 insertions(+), 53 deletions(-) diff --git a/lib/internal.h b/lib/internal.h index 6f176d0..472b3c7 100644 --- a/lib/internal.h +++ b/lib/internal.h @@ -31,6 +31,8 @@ #ifndef YKPIV_INTERNAL_H #define YKPIV_INTERNAL_H +#include "ykpiv.h" + #include #if BACKEND_PCSC @@ -48,18 +50,6 @@ #define DES_LEN_3DES 8*3 #define CB_MGM_KEY DES_LEN_3DES - typedef void* (*ykpiv_pfn_alloc)(void* alloc_data, size_t size); - typedef void* (*ykpiv_pfn_realloc)(void* alloc_data, void* address, size_t size); - typedef void (*ykpiv_pfn_free)(void* alloc_data, void* address); - typedef struct { - ykpiv_pfn_alloc pfn_alloc; - ykpiv_pfn_realloc pfn_realloc; - ykpiv_pfn_free pfn_free; - void * alloc_data; - } ykpiv_allocator; - -extern ykpiv_allocator _mem_default_allocator; - struct ykpiv_state { SCARDCONTEXT context; SCARDHANDLE card; diff --git a/lib/tests/util.c b/lib/tests/util.c index 4409333..997222a 100644 --- a/lib/tests/util.c +++ b/lib/tests/util.c @@ -58,13 +58,24 @@ void setup(void) { res = ykpiv_init(&g_state, true); ck_assert_int_eq(res, YKPIV_OK); + ck_assert_ptr_nonnull(g_state); res = ykpiv_connect(g_state, NULL); ck_assert_int_eq(res, YKPIV_OK); } void teardown(void) { - ykpiv_done(g_state); + ykpiv_rc res; + + // This is the expected case, if the allocator test ran, since it de-inits. + if (NULL == g_state) + return; + + res = ykpiv_disconnect(g_state); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_done(g_state); + ck_assert_int_eq(res, YKPIV_OK); } START_TEST(test_devicemodel) { @@ -208,6 +219,91 @@ START_TEST(test_reset) { } END_TEST + +struct t_alloc_data{ + uint32_t count; +} g_alloc_data; + +static void* _test_alloc(void *data, size_t cb) { + ck_assert_ptr_eq(data, &g_alloc_data); + ((struct t_alloc_data*)data)->count++; + return calloc(cb, 1); +} + +static void * _test_realloc(void *data, void *p, size_t cb) { + ck_assert_ptr_eq(data, &g_alloc_data); + return realloc(p, cb); +} + +static void _test_free(void *data, void *p) { + fflush(stderr); + ck_assert_ptr_eq(data, &g_alloc_data); + ((struct t_alloc_data*)data)->count--; + free(p); +} + +ykpiv_allocator test_allocator_cbs = { + .pfn_alloc = _test_alloc, + .pfn_realloc = _test_realloc, + .pfn_free = _test_free, + .alloc_data = &g_alloc_data +}; + +uint8_t *alloc_auth_cert() { + ykpiv_rc res; + uint8_t *read_cert = NULL; + size_t read_cert_len = 0; + + res = ykpiv_util_write_cert(g_state, YKPIV_KEY_AUTHENTICATION, (uint8_t*)g_cert, sizeof(g_cert)); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_util_read_cert(g_state, YKPIV_KEY_AUTHENTICATION, &read_cert, &read_cert_len); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_ptr_nonnull(read_cert); + ck_assert_int_eq(read_cert_len, sizeof(g_cert)); + ck_assert_mem_eq(g_cert, read_cert, sizeof(g_cert)); + return read_cert; +} + +START_TEST(test_allocator) { + ykpiv_rc res; + const ykpiv_allocator allocator; + uint8_t *cert1, *cert2; + + res = ykpiv_done(g_state); + ck_assert_int_eq(res, YKPIV_OK); + g_state = NULL; + + res = ykpiv_init_with_allocator(&g_state, false, &test_allocator_cbs); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_ptr_nonnull(g_state); + + // Verify we can communicate with device and make some allocations + res = ykpiv_connect(g_state, NULL); + ck_assert_int_eq(res, YKPIV_OK); + test_authenticate(0); + cert1 = alloc_auth_cert(); + cert2 = alloc_auth_cert(); + + // Verify allocations went through custom allocator, and still live + ck_assert_int_gt(g_alloc_data.count, 1); + + // Free and shutdown everything + ykpiv_util_free(g_state, cert2); + ykpiv_util_free(g_state, cert1); + res = ykpiv_disconnect(g_state); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_done(g_state); + ck_assert_int_eq(res, YKPIV_OK); + + // Verify equal number of frees as allocations + ck_assert_int_eq(g_alloc_data.count, 0); + + // Clear g_state so teardown() is skipped + g_state = NULL; +} +END_TEST + int confirm_destruction(void) { char verify[16]; @@ -242,16 +338,20 @@ Suite *test_suite(void) { #ifdef HW_TESTS tcase_add_unchecked_fixture(tc, setup, teardown); - // Reset first. Tests run serially, and depend on a clean slate. + // Must be first: Reset device. Tests run serially, and depend on a clean slate. tcase_add_test(tc, test_reset); // Authenticate after reset. tcase_add_test(tc, test_authenticate); + // Test util functionality tcase_add_test(tc, test_devicemodel); tcase_add_test(tc, test_get_set_cardid); tcase_add_test(tc, test_read_write_list_delete_cert); tcase_add_test(tc, test_generate_key); + + // Must be last: tear down and re-test with custom memory allocator + tcase_add_test(tc, test_allocator); #endif suite_add_tcase(s, tc); @@ -267,7 +367,7 @@ int main(void) s = test_suite(); sr = srunner_create(s); srunner_set_fork_status(sr, CK_NOFORK); - srunner_run_all(sr, CK_NORMAL); + srunner_run_all(sr, CK_VERBOSE); number_failed = srunner_ntests_failed(sr); srunner_free(sr); diff --git a/lib/util.c b/lib/util.c index b431132..442d8be 100644 --- a/lib/util.c +++ b/lib/util.c @@ -129,23 +129,6 @@ prng_rc prng_generate(unsigned char *buffer, const size_t cb_req) { return rc; } -/* Memory helper functions */ - -static void* _alloc(ykpiv_state *state, size_t size) { - if (!state || !(state->allocator.pfn_alloc)) return NULL; - return state->allocator.pfn_alloc(state->allocator.alloc_data, size); -} - -static void* _realloc(ykpiv_state *state, void *address, size_t size) { - if (!state || !(state->allocator.pfn_realloc)) return NULL; - return state->allocator.pfn_realloc(state->allocator.alloc_data, address, size); -} - -static void _free(ykpiv_state *state, void *data) { - if (!data || !state || (!(state->allocator.pfn_free))) return; - state->allocator.pfn_free(state->allocator.alloc_data, data); -} - static size_t _obj_size_max(ykpiv_state *state) { return (state && state->isNEO) ? CB_OBJ_MAX_NEO : CB_OBJ_MAX; } @@ -153,6 +136,9 @@ static size_t _obj_size_max(ykpiv_state *state) { #define MAX(a,b) (a) > (b) ? (a) : (b) #define MIN(a,b) (a) < (b) ? (a) : (b) +void* _ykpiv_alloc(ykpiv_state *state, size_t size); +void* _ykpiv_realloc(ykpiv_state *state, void *address, size_t size); +void _ykpiv_free(ykpiv_state *state, void *data); int _ykpiv_set_length(unsigned char *buffer, size_t length); int _ykpiv_get_length(const unsigned char *buffer, size_t *len); ykpiv_rc _ykpiv_begin_transaction(ykpiv_state *state); @@ -288,7 +274,7 @@ ykpiv_rc ykpiv_util_list_keys(ykpiv_state *state, uint8_t *key_count, ykpiv_key *data_len = 0; // allocate initial page of buffer - if (NULL == (pData = _alloc(state, CB_PAGE))) { + if (NULL == (pData = _ykpiv_alloc(state, CB_PAGE))) { res = YKPIV_MEMORY_ERROR; goto Cleanup; } @@ -304,7 +290,7 @@ ykpiv_rc ykpiv_util_list_keys(ykpiv_state *state, uint8_t *key_count, ykpiv_key cbRealloc = (sizeof(ykpiv_key) + cbBuf - 1) > (cbData - offset) ? MAX((sizeof(ykpiv_key) + cbBuf - 1) - (cbData - offset), CB_PAGE) : 0; if (0 != cbRealloc) { - if (NULL == (pData = _realloc(state, pData, cbData + cbRealloc))) { + if (NULL == (pData = _ykpiv_realloc(state, pData, cbData + cbRealloc))) { res = YKPIV_MEMORY_ERROR; goto Cleanup; } @@ -338,7 +324,7 @@ ykpiv_rc ykpiv_util_list_keys(ykpiv_state *state, uint8_t *key_count, ykpiv_key Cleanup: - if (pData) { _free(state, pData); } + if (pData) { _ykpiv_free(state, pData); } _ykpiv_end_transaction(state); return res; @@ -348,7 +334,7 @@ ykpiv_rc ykpiv_util_free(ykpiv_state *state, void *data) { if (!data) return YKPIV_OK; if (!state || (!(state->allocator.pfn_free))) return YKPIV_GENERIC_ERROR; - _free(state, data); + _ykpiv_free(state, data); return YKPIV_OK; } @@ -367,7 +353,7 @@ ykpiv_rc ykpiv_util_read_cert(ykpiv_state *state, uint8_t slot, uint8_t **data, *data_len = 0; if (YKPIV_OK == (res = _read_certificate(state, slot, buf, &cbBuf))) { - if (NULL == (*data = _alloc(state, cbBuf))) { + if (NULL == (*data = _ykpiv_alloc(state, cbBuf))) { res = YKPIV_MEMORY_ERROR; goto Cleanup; } @@ -433,7 +419,7 @@ ykpiv_rc ykpiv_util_read_mscmap(ykpiv_state *state, ykpiv_container **containers goto Cleanup; } - if (NULL == (*containers = _alloc(state, len))) { + if (NULL == (*containers = _ykpiv_alloc(state, len))) { res = YKPIV_MEMORY_ERROR; goto Cleanup; } @@ -522,7 +508,7 @@ ykpiv_rc ykpiv_util_read_msroots(ykpiv_state *state, uint8_t **data, size_t *dat // allocate first page cbData = _obj_size_max(state); - if (NULL == (pData = _alloc(state, cbData))) { res = YKPIV_MEMORY_ERROR; goto Cleanup; } + if (NULL == (pData = _ykpiv_alloc(state, cbData))) { res = YKPIV_MEMORY_ERROR; goto Cleanup; } for (object_id = YKPIV_OBJ_MSROOTS1; object_id <= YKPIV_OBJ_MSROOTS5; object_id++) { cbBuf = sizeof(buf); @@ -558,7 +544,7 @@ ykpiv_rc ykpiv_util_read_msroots(ykpiv_state *state, uint8_t **data, size_t *dat cbRealloc = len > (cbData - offset) ? len - (cbData - offset) : 0; if (0 != cbRealloc) { - if (NULL == (pData = _realloc(state, pData, cbData + cbRealloc))) { + if (NULL == (pData = _ykpiv_realloc(state, pData, cbData + cbRealloc))) { res = YKPIV_MEMORY_ERROR; goto Cleanup; } @@ -583,7 +569,7 @@ ykpiv_rc ykpiv_util_read_msroots(ykpiv_state *state, uint8_t **data, size_t *dat Cleanup: - if (pData) { _free(state, pData); } + if (pData) { _ykpiv_free(state, pData); } _ykpiv_end_transaction(state); return res; @@ -777,7 +763,7 @@ ykpiv_rc ykpiv_util_generate_key(ykpiv_state *state, uint8_t slot, uint8_t algor data_ptr += _ykpiv_get_length(data_ptr, &len); cb_modulus = len; - if (NULL == (ptr_modulus = _alloc(state, cb_modulus))) { + if (NULL == (ptr_modulus = _ykpiv_alloc(state, cb_modulus))) { if (state->verbose) { fprintf(stderr, "Failed to allocate memory for modulus.\n"); } res = YKPIV_MEMORY_ERROR; goto Cleanup; @@ -797,7 +783,7 @@ ykpiv_rc ykpiv_util_generate_key(ykpiv_state *state, uint8_t slot, uint8_t algor data_ptr += _ykpiv_get_length(data_ptr, &len); cb_exp = len; - if (NULL == (ptr_exp = _alloc(state, cb_exp))) { + if (NULL == (ptr_exp = _ykpiv_alloc(state, cb_exp))) { if (state->verbose) { fprintf(stderr, "Failed to allocate memory for public exponent.\n"); } res = YKPIV_MEMORY_ERROR; goto Cleanup; @@ -838,7 +824,7 @@ ykpiv_rc ykpiv_util_generate_key(ykpiv_state *state, uint8_t slot, uint8_t algor } cb_point = len; - if (NULL == (ptr_point = _alloc(state, cb_point))) { + if (NULL == (ptr_point = _ykpiv_alloc(state, cb_point))) { if (state->verbose) { fprintf(stderr, "Failed to allocate memory for public point.\n"); } res = YKPIV_MEMORY_ERROR; goto Cleanup; @@ -860,9 +846,9 @@ ykpiv_rc ykpiv_util_generate_key(ykpiv_state *state, uint8_t slot, uint8_t algor Cleanup: - if (ptr_modulus) { _free(state, modulus); } - if (ptr_exp) { _free(state, ptr_exp); } - if (ptr_point) { _free(state, ptr_exp); } + if (ptr_modulus) { _ykpiv_free(state, modulus); } + if (ptr_exp) { _ykpiv_free(state, ptr_exp); } + if (ptr_point) { _ykpiv_free(state, ptr_exp); } _ykpiv_end_transaction(state); return res; diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 16e6c41..1d6b21f 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -71,6 +71,23 @@ ykpiv_allocator _default_allocator = { .alloc_data = 0 }; +/* Memory helper functions */ + +void* _ykpiv_alloc(ykpiv_state *state, size_t size) { + if (!state || !(state->allocator.pfn_alloc)) return NULL; + return state->allocator.pfn_alloc(state->allocator.alloc_data, size); +} + +void* _ykpiv_realloc(ykpiv_state *state, void *address, size_t size) { + if (!state || !(state->allocator.pfn_realloc)) return NULL; + return state->allocator.pfn_realloc(state->allocator.alloc_data, address, size); +} + +void _ykpiv_free(ykpiv_state *state, void *data) { + if (!data || !state || (!(state->allocator.pfn_free))) return; + state->allocator.pfn_free(state->allocator.alloc_data, data); +} + static void dump_hex(const unsigned char *buf, unsigned int len) { unsigned int i; for (i = 0; i < len; i++) { @@ -152,8 +169,9 @@ ykpiv_rc ykpiv_init(ykpiv_state **state, int verbose) { ykpiv_rc ykpiv_done(ykpiv_state *state) { ykpiv_disconnect(state); - free(state->pin); - free(state); + if (state->pin) + _ykpiv_free(state, state->pin); + _ykpiv_free(state, state); return YKPIV_OK; } @@ -839,8 +857,8 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { return res; } else if(sw == SW_SUCCESS) { if (pin) { - free(state->pin); - state->pin = malloc(len * sizeof(char) + 1); + _ykpiv_free(state, state->pin); + state->pin = _ykpiv_alloc(state, len * sizeof(char) + 1); if (state->pin == NULL) { return YKPIV_MEMORY_ERROR; } @@ -911,8 +929,8 @@ static ykpiv_rc change_pin_internal(ykpiv_state *state, int action, const char * ykpiv_rc ykpiv_change_pin(ykpiv_state *state, const char * current_pin, size_t current_pin_len, const char * new_pin, size_t new_pin_len, int *tries) { ykpiv_rc res = change_pin_internal(state, CHREF_ACT_CHANGE_PIN, current_pin, current_pin_len, new_pin, new_pin_len, tries); if (res == YKPIV_OK && new_pin != NULL) { - free(state->pin); - state->pin = malloc(new_pin_len * sizeof(char) + 1); + _ykpiv_free(state, state->pin); + state->pin = _ykpiv_alloc(state, new_pin_len * sizeof(char) + 1); if (state->pin == NULL) { return YKPIV_MEMORY_ERROR; } diff --git a/lib/ykpiv.h b/lib/ykpiv.h index 2374c02..a6f5636 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -63,10 +63,21 @@ extern "C" YKPIV_RANGE_ERROR = -15 //i.e. value range error } ykpiv_rc; + typedef void* (*ykpiv_pfn_alloc)(void* alloc_data, size_t size); + typedef void* (*ykpiv_pfn_realloc)(void* alloc_data, void* address, size_t size); + typedef void (*ykpiv_pfn_free)(void* alloc_data, void* address); + typedef struct ykpiv_allocator { + ykpiv_pfn_alloc pfn_alloc; + ykpiv_pfn_realloc pfn_realloc; + ykpiv_pfn_free pfn_free; + void * alloc_data; + } ykpiv_allocator; + const char *ykpiv_strerror(ykpiv_rc err); const char *ykpiv_strerror_name(ykpiv_rc err); ykpiv_rc ykpiv_init(ykpiv_state **state, int verbose); + ykpiv_rc ykpiv_init_with_allocator(ykpiv_state **state, int verbose, const ykpiv_allocator *allocator); ykpiv_rc ykpiv_done(ykpiv_state *state); ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted); ykpiv_rc ykpiv_list_readers(ykpiv_state *state, char *readers, size_t *len); From 89e8e7864ecea687e9ccd9bf2bd0839252023765 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 24 Jul 2017 14:10:13 +0200 Subject: [PATCH 08/57] Tests for ykpiv_list_readers and ykpiv_set_mgmkey --- lib/tests/util.c | 50 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 2 deletions(-) diff --git a/lib/tests/util.c b/lib/tests/util.c index 997222a..de9e756 100644 --- a/lib/tests/util.c +++ b/lib/tests/util.c @@ -81,7 +81,7 @@ void teardown(void) { START_TEST(test_devicemodel) { ykpiv_devmodel model; model = ykpiv_util_devicemodel(g_state); - fprintf(stderr, "Model: %u\n", model); + fprintf(stdout, "Model: %u\n", model); ck_assert(model == DEVTYPE_YK4); } END_TEST @@ -103,6 +103,20 @@ START_TEST(test_get_set_cardid) { } END_TEST +START_TEST(test_list_readers) { + ykpiv_rc res; + char reader_buf[2048]; + size_t num_readers = sizeof(reader_buf); + char *reader_ptr; + res = ykpiv_list_readers(g_state, reader_buf, &num_readers); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_int_gt(num_readers, 0); + for(reader_ptr = reader_buf; *reader_ptr != '\0'; reader_ptr += strlen(reader_ptr) + 1) { + fprintf(stdout, "Found device: %s\n", reader_ptr); + } +} +END_TEST + START_TEST(test_read_write_list_delete_cert) { ykpiv_rc res; uint8_t *read_cert = NULL; @@ -184,13 +198,44 @@ END_TEST START_TEST(test_authenticate) { ykpiv_rc res; - const char *mgm_key = "010203040506070801020304050607080102030405060708"; + const char *default_mgm_key = "010203040506070801020304050607080102030405060708"; + const char *mgm_key = "112233445566778811223344556677881122334455667788"; unsigned char key[24]; size_t key_len = sizeof(key); + // Try new key, fail. res = ykpiv_hex_decode(mgm_key, strlen(mgm_key), key, &key_len); ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_authenticate(g_state, key); + ck_assert_int_eq(res, YKPIV_AUTHENTICATION_ERROR); + // Try default key, succeed + res = ykpiv_hex_decode(default_mgm_key, strlen(default_mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_authenticate(g_state, key); + ck_assert_int_eq(res, YKPIV_OK); + + // Change to new key + res = ykpiv_hex_decode(mgm_key, strlen(mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_set_mgmkey(g_state, key); + ck_assert_int_eq(res, YKPIV_OK); + + // Try new key, succeed. + res = ykpiv_hex_decode(mgm_key, strlen(mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_authenticate(g_state, key); + ck_assert_int_eq(res, YKPIV_OK); + + // Change back to default key + res = ykpiv_hex_decode(default_mgm_key, strlen(default_mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_set_mgmkey(g_state, key); + ck_assert_int_eq(res, YKPIV_OK); + + // Try default key, succeed + res = ykpiv_hex_decode(default_mgm_key, strlen(default_mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); res = ykpiv_authenticate(g_state, key); ck_assert_int_eq(res, YKPIV_OK); } @@ -347,6 +392,7 @@ Suite *test_suite(void) { // Test util functionality tcase_add_test(tc, test_devicemodel); tcase_add_test(tc, test_get_set_cardid); + tcase_add_test(tc, test_list_readers); tcase_add_test(tc, test_read_write_list_delete_cert); tcase_add_test(tc, test_generate_key); From 16d0a519c45346e976f50e0b7f23eb2e8a07b40b Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 7 Aug 2017 14:04:45 +0200 Subject: [PATCH 09/57] Continuing unit tests and minor bug fixes * Support unit tests on Yubikey NEO * Test ykpiv_get_version * Test ykpiv_import_private_key * Test ykpiv_sign_data * Test ykpiv_decipher_data * Test ykpiv_change_pin * Test ykpiv_change_puk * Test ykpiv_get_pin_retries * Test ykpiv_set_pin_retries * Test ykpiv_verify * Fix segfault when |tries| is NULL * Fix segfault when import_private_key algorithm is wrong --- .gitignore | 13 ++ lib/tests/Makefile.am | 6 +- lib/tests/util.c | 370 +++++++++++++++++++++++++++++++++++++++++- lib/ykpiv.c | 50 +++++- lib/ykpiv.h | 15 +- 5 files changed, 440 insertions(+), 14 deletions(-) diff --git a/.gitignore b/.gitignore index 6312246..accae11 100644 --- a/.gitignore +++ b/.gitignore @@ -43,12 +43,19 @@ lib/tests/parse_key lib/tests/parse_key.log lib/tests/parse_key.o lib/tests/parse_key.trs +lib/tests/util +lib/tests/util.log +lib/tests/util.o +lib/tests/util.trs lib/tests/test-suite.log lib/error.lo lib/error.o lib/libykpiv.la lib/version.lo lib/version.o +lib/util.la +lib/util.lo +lib/util.o lib/ykpiv-version.h lib/ykpiv.lo lib/ykpiv.o @@ -97,3 +104,9 @@ ykcs11/tests/ykcs11_tests.o ykcs11/tests/ykcs11_tests.trs ykcs11/tests/test-suite.log yubico-piv-tool.1.txt + +*.plist +.libs +GPATH +GRTAGS +GTAGS diff --git a/lib/tests/Makefile.am b/lib/tests/Makefile.am index 29627af..fb826a1 100644 --- a/lib/tests/Makefile.am +++ b/lib/tests/Makefile.am @@ -25,11 +25,11 @@ # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -AM_CFLAGS = $(WARN_CFLAGS) @CHECK_CFLAGS@ -AM_CPPFLAGS = -I$(top_srcdir)/lib -I$(top_builddir)/lib +AM_CFLAGS = $(WARN_CFLAGS) @CHECK_CFLAGS@ $(OPENSSL_CFLAGS) +AM_CPPFLAGS = -I$(top_srcdir)/lib -I$(top_builddir)/lib $(OPENSSL_CFLAGS) AM_LDFLAGS = -no-install @CHECK_LIBS@ -LDADD = ../libykpiv.la +LDADD = ../libykpiv.la $(OPENSSL_LIBS) check_PROGRAMS = basic parse_key util TESTS = $(check_PROGRAMS) diff --git a/lib/tests/util.c b/lib/tests/util.c index de9e756..11b2dd8 100644 --- a/lib/tests/util.c +++ b/lib/tests/util.c @@ -79,10 +79,32 @@ void teardown(void) { } START_TEST(test_devicemodel) { + ykpiv_rc res; ykpiv_devmodel model; + char version[256]; + char reader_buf[2048]; + size_t num_readers = sizeof(reader_buf); + + res = ykpiv_get_version(g_state, version, sizeof(version)); + ck_assert_int_eq(res, YKPIV_OK); + fprintf(stderr, "Version: %s\n", version); model = ykpiv_util_devicemodel(g_state); fprintf(stdout, "Model: %u\n", model); - ck_assert(model == DEVTYPE_YK4); + ck_assert(model == DEVTYPE_YK4 || model == DEVTYPE_NEOr3); + + res = ykpiv_list_readers(g_state, reader_buf, &num_readers); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_int_gt(num_readers, 0); + if (model == DEVTYPE_YK4) { + ck_assert_ptr_nonnull(strnstr(reader_buf, "Yubikey 4", strlen(reader_buf))); + ck_assert(version[0] == '4'); // Verify app version 4.x + ck_assert(version[1] == '.'); + } + else { + ck_assert_ptr_nonnull(strnstr(reader_buf, "Yubikey NEO", strlen(reader_buf))); + ck_assert(version[0] == '1'); // Verify app version 1.x + ck_assert(version[1] == '.'); + } } END_TEST @@ -162,6 +184,229 @@ START_TEST(test_read_write_list_delete_cert) { } END_TEST +#include +#include +#include +#include + +// RSA2048 private key, generated with: `openssl genrsa 2048 -out private.pem` +static const char *private_key_pem = + "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEpAIBAAKCAQEAwVUwmVbc+ffOy2+RivxBpgleTVN6bUa0q7jNYB+AseFQYaYq\n" + "EGfa+VGdxSGo+8DV1KT9+fNEd5243gXn/tcjtMItKeB+oAQc64s9lIFlYuR8bpq1\n" + "ibr33iW2elnnv9mpecqohdCVwM2McWveoPyb7MwlwVuhqexOzJO29bqJcazLbtkf\n" + "ZETK0oBx53/ylA4Y6nE9Pa46jW2qhj+KShf1iBg+gAyt3eI+wI2Wmub1WxLLH8D2\n" + "w+kow8QhQOa8dHCkRRw771JxVO5+d+Y/Y+x9B1HgF4q0q9xUlhWLK2TR4ChBFzXe\n" + "47sAHsSqi/pl5JbwYrHPOE/VEBLukmjL8NFCSQIDAQABAoIBADmEyOK2DyRnb6Ti\n" + "2qBJEJb/boj+7wuX36S/ZIrWlIlXiXyj3RvoaiOG/rNpokbURknvlIhKsfIMgLW9\n" + "eBo/k6Xxp1IwMjwVPS1uzbFjFfDoHYUijiQd9iSnf7TDDsnrThqoCp9VQViNTt1n\n" + "xGKNBS7cRddTFbPiVEdVIzfUeZPR2oRrc4maBCRCrQgg8WNknawmc8zhkf2NiPj3\n" + "tWLQHMy1/MgW2W1LM9sgzllEtS5CZUnyGy2HbbhS2tbZ6j9kPzOp0pPxxTTzJmmV\n" + "fi1vkJcVW4+MdXjWmhALcPA4dO7Y2Ljiu6VxIxQORRO1DyiCjAs1AVMQxgPAAY41\n" + "YR4Q2EkCgYEA4zE0oytg97aVaBY9CKi7/PqR+NI/uEvfoQCnT+ddaJgp/qsspuXo\n" + "tJt94p13ANd8O7suqQTVNvbZq1rX10xQjJZ9nvlqQa6iHkN6Epq31XBK3Z+acjIV\n" + "A2rAgKBByjz9/CpKHqnOsrTWU1Y7x416IG4BZt42hHdrxRH98/wiDH8CgYEA2djj\n" + "AjwgK+MwDnshwT1NNgCSP/2ZHatBAykZ5BCs9BJ6MNYqqXVGYoqs5Z5kSkow+Db3\n" + "pipkEieo5w2Rd5zkolTThaVCvRkSe5wRiBpZhaeY+b0UFwavGCb6zU/MmJIMDPiI\n" + "2iRGeCXgQDvIS/icIqzbTtp6dZaoMgG7LdSR7TcCgYBtxGhaLas8A8tL7vKuLFgn\n" + "cij0vyBqOr5hW596y54l2t7vXGTGfm5gVIAN7WaB0ZsEgPuaTet2Eu44DDwcmZKR\n" + "WmR3Wqor8eQCGzfvpTEMvqRtT5+fbPMaI4m+m68ttyo/m28UQZbMYPLscM2RLJnE\n" + "8WFcAiD0/33iST8ZksggoQKBgQDE/7Yhsj+hkHxHzB+1QPtOp2uaBHnvc4uCESwB\n" + "qvbMbN0kxrejsJLqz98UcozdBYSNIiAHmvQN2uGJuCJhGXdEORNjGxRkLoUhVPwh\n" + "qTplfC8BQHQncnrqi21oNw6ctg3BuQsAwaccRZwqWiWCVhrT3J8iCr6NEaWeOySK\n" + "iF1CNwKBgQCRpkkZArlccwS0kMvkK+tQ1rG2xWm7c05G34gP/g6dHFRy0gPNMyvi\n" + "SkiLTJmQIEZSAEiq0FFgcVwM6o556ftvQZuwDp5rHUbwqnHCpMJKpD9aJpStvfPi\n" + "4p9JbYdaGqnq4eoNKemmGnbUof0dR9Zr0lGmcMTwwzBib+4E1d7soA==\n" + "-----END RSA PRIVATE KEY-----\n"; + +// Certificate signed with key above: +// `openssl req -x509 -key private.pem -out cert.pem -subj "/CN=bar/OU=test/O=example.com/" -new` +static const char *certificate_pem = + "-----BEGIN CERTIFICATE-----\n" + "MIIC5zCCAc+gAwIBAgIJAOq8A/cmpxF5MA0GCSqGSIb3DQEBCwUAMDMxDDAKBgNV\n" + "BAMMA2JhcjENMAsGA1UECwwEdGVzdDEUMBIGA1UECgwLZXhhbXBsZS5jb20wHhcN\n" + "MTcwODAzMTE1MDI2WhcNMTgwODAzMTE1MDI2WjAzMQwwCgYDVQQDDANiYXIxDTAL\n" + "BgNVBAsMBHRlc3QxFDASBgNVBAoMC2V4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0B\n" + "AQEFAAOCAQ8AMIIBCgKCAQEAwVUwmVbc+ffOy2+RivxBpgleTVN6bUa0q7jNYB+A\n" + "seFQYaYqEGfa+VGdxSGo+8DV1KT9+fNEd5243gXn/tcjtMItKeB+oAQc64s9lIFl\n" + "YuR8bpq1ibr33iW2elnnv9mpecqohdCVwM2McWveoPyb7MwlwVuhqexOzJO29bqJ\n" + "cazLbtkfZETK0oBx53/ylA4Y6nE9Pa46jW2qhj+KShf1iBg+gAyt3eI+wI2Wmub1\n" + "WxLLH8D2w+kow8QhQOa8dHCkRRw771JxVO5+d+Y/Y+x9B1HgF4q0q9xUlhWLK2TR\n" + "4ChBFzXe47sAHsSqi/pl5JbwYrHPOE/VEBLukmjL8NFCSQIDAQABMA0GCSqGSIb3\n" + "DQEBCwUAA4IBAQCamrwdEhNmY2GCQWq6U90Q3XQT6w0HHW/JmtuGeF+BTpVr12gN\n" + "/UvEXTo9geWbGcCTjaMMURTa7mUjVUIttIWEVHZMKqBuvsUM1RcuOEX/vitaJJ8K\n" + "Sw4upjCNa3ZxUXmSA1FBixZgDzFqjEeSiaJjMU0yX5W2p1T4iNYtF3YqzMF5AWSI\n" + "qCO7gP5ezPyg5kDnrO3V7DBgnDiqawq7Pyn9DynKNULX/hc1yls/R+ebb2u8Z+h5\n" + "W4YXbzGZb8qdT27qIZaHD638tL6liLkI6UE4KCXH8X8e3fqdbmqvwrq403nOGmsP\n" + "cbJb2PEXibNEQG234riKxm7x7vNDLL79Jwtc\n" + "-----END CERTIFICATE-----\n"; +bool set_component(unsigned char *in_ptr, const BIGNUM *bn, int element_len) { + int real_len = BN_num_bytes(bn); + + if(real_len > element_len) { + return false; + } + memset(in_ptr, 0, (size_t)(element_len - real_len)); + in_ptr += element_len - real_len; + BN_bn2bin(bn, in_ptr); + + return true; +} +bool prepare_rsa_signature(const unsigned char *in, unsigned int in_len, unsigned char *out, unsigned int *out_len, int nid) { + X509_SIG digestInfo; + X509_ALGOR algor; + ASN1_TYPE parameter; + ASN1_OCTET_STRING digest; + unsigned char data[1024]; + + memcpy(data, in, in_len); + + digestInfo.algor = &algor; + digestInfo.algor->algorithm = OBJ_nid2obj(nid); + digestInfo.algor->parameter = ¶meter; + digestInfo.algor->parameter->type = V_ASN1_NULL; + digestInfo.algor->parameter->value.ptr = NULL; + digestInfo.digest = &digest; + digestInfo.digest->data = data; + digestInfo.digest->length = (int)in_len; + *out_len = (unsigned int)i2d_X509_SIG(&digestInfo, &out); + return true; +} +START_TEST(test_import_key) { + ykpiv_rc res; + + { + unsigned char pp = YKPIV_PINPOLICY_DEFAULT; + unsigned char tp = YKPIV_TOUCHPOLICY_DEFAULT; + EVP_PKEY *private_key = NULL; + BIO *bio = NULL; + RSA *rsa_private_key = NULL; + unsigned char e[4]; + unsigned char p[128]; + unsigned char q[128]; + unsigned char dmp1[128]; + unsigned char dmq1[128]; + unsigned char iqmp[128]; + int element_len = 128; + + bio = BIO_new_mem_buf(private_key_pem, strlen(private_key_pem)); + private_key = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL); + ck_assert_ptr_nonnull(private_key); + BIO_free(bio); + rsa_private_key = EVP_PKEY_get1_RSA(private_key); + ck_assert_ptr_nonnull(rsa_private_key); + ck_assert(set_component(e, rsa_private_key->e, 3)); + ck_assert(set_component(p, rsa_private_key->p, element_len)); + ck_assert(set_component(q, rsa_private_key->q, element_len)); + ck_assert(set_component(dmp1, rsa_private_key->dmp1, element_len)); + ck_assert(set_component(dmq1, rsa_private_key->dmq1, element_len)); + ck_assert(set_component(iqmp, rsa_private_key->iqmp, element_len)); + + // Try wrong algorithm, fail. + res = ykpiv_import_private_key(g_state, + 0x9e, + YKPIV_ALGO_RSA1024, + p, element_len, + q, element_len, + dmp1, element_len, + dmq1, element_len, + iqmp, element_len, + NULL, 0, + pp, tp); + ck_assert_int_eq(res, YKPIV_ALGORITHM_ERROR); + + // Try right algorithm + res = ykpiv_import_private_key(g_state, + 0x9e, + YKPIV_ALGO_RSA2048, + p, element_len, + q, element_len, + dmp1, element_len, + dmq1, element_len, + iqmp, element_len, + NULL, 0, + pp, tp); + ck_assert_int_eq(res, YKPIV_OK); + EVP_PKEY_free(private_key); + } + + // Verify certificate + { + BIO *bio = NULL; + X509 *cert = NULL; + RSA *rsa = NULL; + EVP_PKEY *pub_key = NULL; + const EVP_MD *md = EVP_sha256(); + EVP_MD_CTX *mdctx; + + unsigned char signature[1024]; + unsigned char encoded[1024]; + unsigned char data[1024]; + unsigned char signinput[1024]; + unsigned char rand[128]; + + size_t sig_len = sizeof(signature); + size_t padlen = 256; + unsigned int enc_len; + unsigned int data_len; + + bio = BIO_new_mem_buf(certificate_pem, strlen(certificate_pem)); + cert = PEM_read_bio_X509(bio, NULL, NULL, NULL); + ck_assert_ptr_nonnull(cert); + BIO_free(bio); + pub_key = X509_get_pubkey(cert); + ck_assert_ptr_nonnull(pub_key); + rsa = EVP_PKEY_get1_RSA(pub_key); + ck_assert_ptr_nonnull(rsa); + + ck_assert_int_gt(RAND_pseudo_bytes(rand, 128), 0); + mdctx = EVP_MD_CTX_create(); + EVP_DigestInit_ex(mdctx, md, NULL); + EVP_DigestUpdate(mdctx, rand, 128); + EVP_DigestFinal_ex(mdctx, data, &data_len); + + prepare_rsa_signature(data, data_len, encoded, &enc_len, EVP_MD_type(md)); + ck_assert_int_ne(RSA_padding_add_PKCS1_type_1(signinput, padlen, encoded, enc_len), 0); + res = ykpiv_sign_data(g_state, signinput, padlen, signature, &sig_len, YKPIV_ALGO_RSA2048, 0x9e); + ck_assert_int_eq(res, YKPIV_OK); + + ck_assert_int_eq(RSA_verify(EVP_MD_type(md), data, data_len, signature, sig_len, rsa), 1); + + X509_free(cert); + } + + // Use imported key to decrypt a thing. See that it works. + { + BIO *bio = NULL; + X509 *cert = NULL; + EVP_PKEY *pub_key = NULL; + unsigned char secret[32]; + unsigned char secret2[32]; + unsigned char data[256]; + int len; + size_t len2 = sizeof(data); + RSA *rsa = NULL; + bio = BIO_new_mem_buf(certificate_pem, strlen(certificate_pem)); + cert = PEM_read_bio_X509(bio, NULL, NULL, NULL); + ck_assert_ptr_nonnull(cert); + BIO_free(bio); + pub_key = X509_get_pubkey(cert); + ck_assert_ptr_nonnull(pub_key); + rsa = EVP_PKEY_get1_RSA(pub_key); + ck_assert_ptr_nonnull(rsa); + ck_assert_int_gt(RAND_pseudo_bytes(secret, sizeof(secret)), 0); + len = RSA_public_encrypt(sizeof(secret), secret, data, rsa, RSA_PKCS1_PADDING); + ck_assert_int_ge(len, 0); + res = ykpiv_decipher_data(g_state, data, (size_t)len, data, &len2, YKPIV_ALGO_RSA2048, 0x9e); + ck_assert_int_eq(res, YKPIV_OK); + len = RSA_padding_check_PKCS1_type_2(secret2, sizeof(secret2), data + 1, len2 - 1, RSA_size(rsa)); + ck_assert_int_eq(len, sizeof(secret)); + ck_assert_int_eq(memcmp(secret, secret2, sizeof(secret)), 0); + X509_free(cert); + } +} +END_TEST + START_TEST(test_generate_key) { ykpiv_rc res; uint8_t *mod, *exp; @@ -241,17 +486,78 @@ START_TEST(test_authenticate) { } END_TEST -START_TEST(test_reset) { +START_TEST(test_change_pin) { + ykpiv_rc res; + + res = ykpiv_verify(g_state, "123456", NULL); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_change_pin(g_state, "123456", 6, "ABCDEF", 6, NULL); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_verify(g_state, "123456", NULL); + ck_assert_int_eq(res, YKPIV_WRONG_PIN); + + res = ykpiv_verify(g_state, "ABCDEF", NULL); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_change_pin(g_state, "ABCDEF", 6, "123456", 6, NULL); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_verify(g_state, "ABCDEF", NULL); + ck_assert_int_eq(res, YKPIV_WRONG_PIN); + + res = ykpiv_verify(g_state, "123456", NULL); + ck_assert_int_eq(res, YKPIV_OK); +} +END_TEST + +START_TEST(test_change_puk) { + ykpiv_rc res; + + res = ykpiv_unblock_pin(g_state, "12345678", 8, "123456", 6, NULL); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_change_puk(g_state, "12345678", 8, "ABCDEFGH", 8, NULL); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_unblock_pin(g_state, "12345678", 8, "123456", 6, NULL); + ck_assert_int_eq(res, YKPIV_WRONG_PIN); + + res = ykpiv_unblock_pin(g_state, "ABCDEFGH", 8, "123456", 6, NULL); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_change_puk(g_state, "ABCDEFGH", 8, "12345678", 8, NULL); + ck_assert_int_eq(res, YKPIV_OK); + + res = ykpiv_unblock_pin(g_state, "ABCDEFGH", 8, "123456", 6, NULL); + ck_assert_int_eq(res, YKPIV_WRONG_PIN); + + res = ykpiv_unblock_pin(g_state, "12345678", 8, "123456", 6, NULL); + ck_assert_int_eq(res, YKPIV_OK); +} +END_TEST + +static int block_and_reset() { ykpiv_rc res; int tries = 100; - int i; + int tries_until_blocked; + tries_until_blocked = 0; while (tries) { res = ykpiv_verify(g_state, "AAAAAA", &tries); if (res == YKPIV_PIN_LOCKED) break; ck_assert_int_eq(res, YKPIV_WRONG_PIN); + tries_until_blocked++; } + + // Verify no PIN retries remaining + tries = 100; + res = ykpiv_get_pin_retries(g_state, &tries); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_int_eq(tries, 0); + tries = 100; while (tries) { res = ykpiv_change_puk(g_state, "AAAAAAAA", 8, "AAAAAAAA", 8, &tries); @@ -261,6 +567,61 @@ START_TEST(test_reset) { } res = ykpiv_util_reset(g_state); ck_assert_int_eq(res, YKPIV_OK); + return tries_until_blocked; +} + +START_TEST(test_reset) { + ykpiv_rc res; + int tries = 100; + int tries_until_blocked; + + // Block and reset, with default PIN retries + tries_until_blocked = block_and_reset(); + ck_assert_int_eq(tries_until_blocked, 3); + + // Authenticate and increase PIN retries + test_authenticate(0); + res = ykpiv_verify(g_state, "123456", NULL); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_set_pin_retries(g_state, 8); + ck_assert_int_eq(res, YKPIV_OK); + + // Block and reset again, verifying increased PIN retries + tries_until_blocked = block_and_reset(); + ck_assert_int_eq(tries_until_blocked, 8); + // Note: defaults back to 3 retries after reset + + // Verify default (3) PIN retries remaining + tries = 0; + res = ykpiv_get_pin_retries(g_state, &tries); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_int_eq(tries, 3); + + // Verify still (3) PIN retries remaining + tries = 0; + res = ykpiv_get_pin_retries(g_state, &tries); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_int_eq(tries, 3); + + // Try wrong PIN + res = ykpiv_verify(g_state, "AAAAAA", &tries); + + // Verify 2 PIN retries remaining + tries = 0; + res = ykpiv_get_pin_retries(g_state, &tries); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_int_eq(tries, 2); + + // Verify correct PIN + tries = 100; + res = ykpiv_verify(g_state, "123456", &tries); + ck_assert_int_eq(res, YKPIV_OK); + + // Verify back to 3 PIN retries remaining + tries = 0; + res = ykpiv_get_pin_retries(g_state, &tries); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_int_eq(tries, 3); } END_TEST @@ -390,10 +751,13 @@ Suite *test_suite(void) { tcase_add_test(tc, test_authenticate); // Test util functionality + tcase_add_test(tc, test_change_pin); + tcase_add_test(tc, test_change_puk); tcase_add_test(tc, test_devicemodel); tcase_add_test(tc, test_get_set_cardid); tcase_add_test(tc, test_list_readers); tcase_add_test(tc, test_read_write_list_delete_cert); + tcase_add_test(tc, test_import_key); tcase_add_test(tc, test_generate_key); // Must be last: tear down and re-test with custom memory allocator diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 1d6b21f..0e58ee0 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -864,6 +864,7 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { } strcpy(state->pin, pin); } + if (tries) *tries = (sw & 0xf); return YKPIV_OK; } else if((sw >> 8) == 0x63) { if (tries) *tries = (sw & 0xf); @@ -876,6 +877,48 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { } } +ykpiv_rc ykpiv_get_pin_retries(ykpiv_state *state, int* tries) { + ykpiv_rc res; + ykpiv_rc ykrc; + if (NULL == state || NULL == tries) { + return YKPIV_ARGUMENT_ERROR; + } + res = _ykpiv_select_application(state); + ykrc = ykpiv_verify(state, NULL, tries); + // WRONG_PIN is expected on successful query. + return ykrc == YKPIV_WRONG_PIN ? YKPIV_OK : ykrc; +} + + +ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, const int tries) { + ykpiv_rc res = YKPIV_OK; + unsigned char templ[] = {0, YKPIV_INS_SET_PIN_RETRIES, (unsigned char)tries, YKPIV_RETRIES_DEFAULT}; + unsigned char data[0xff]; + unsigned long recv_len = sizeof(data); + int sw; + + if (0 == tries) { + //zero value means no change in retry count according to minidriver spec + return YKPIV_OK; + } + if (tries > YKPIV_RETRIES_MAX || tries < 1) { + return YKPIV_RANGE_ERROR; + } + + res = ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw); + if (YKPIV_OK == res) { + if (SW_SUCCESS == sw) { + return YKPIV_OK; + } else if (sw == SW_ERR_AUTH_BLOCKED) { + return YKPIV_AUTHENTICATION_ERROR; + } else if (sw == SW_ERR_SECURITY_STATUS) { + return YKPIV_AUTHENTICATION_ERROR; + } + return YKPIV_GENERIC_ERROR; + } + return res; +} + #define CHREF_ACT_CHANGE_PIN 0 #define CHREF_ACT_UNBLOCK_PIN 1 #define CHREF_ACT_CHANGE_PUK 2 @@ -912,7 +955,7 @@ static ykpiv_rc change_pin_internal(ykpiv_state *state, int action, const char * return res; } else if(sw != SW_SUCCESS) { if((sw >> 8) == 0x63) { - *tries = sw & 0xf; + if (tries) *tries = sw & 0xf; return YKPIV_WRONG_PIN; } else if(sw == SW_ERR_AUTH_BLOCKED) { return YKPIV_PIN_LOCKED; @@ -1110,9 +1153,14 @@ ykpiv_rc ykpiv_import_private_key(ykpiv_state *state, const unsigned char key, u return YKPIV_ALGORITHM_ERROR; for (i = 0; i < n_params; i++) { + size_t remaining; *in_ptr++ = param_tag + i; in_ptr += _ykpiv_set_length(in_ptr, elem_len); padding = elem_len - lens[i]; + remaining = (uintptr_t)key_data + sizeof(key_data) - (uintptr_t)in_ptr; + if (padding > remaining) { + return YKPIV_ALGORITHM_ERROR; + } memset(in_ptr, 0, padding); in_ptr += padding; memcpy(in_ptr, params[i], lens[i]); diff --git a/lib/ykpiv.h b/lib/ykpiv.h index a6f5636..0af2e79 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -92,9 +92,7 @@ extern "C" ykpiv_rc ykpiv_sign_data(ykpiv_state *state, const unsigned char *sign_in, size_t in_len, unsigned char *sign_out, size_t *out_len, unsigned char algorithm, unsigned char key); - ykpiv_rc ykpiv_sign_data2(ykpiv_state *state, const unsigned char *sign_in, - size_t in_len, unsigned char *sign_out, size_t *out_len, - unsigned char algorithm, unsigned char key, int padding); // Allow not to add padding + // TODO (TREV): minidriver has ykpiv_sign_data2 ykpiv_rc ykpiv_decipher_data(ykpiv_state *state, const unsigned char *enc_in, size_t in_len, unsigned char *enc_out, size_t *out_len, unsigned char algorithm, unsigned char key); @@ -123,6 +121,8 @@ extern "C" const unsigned char *qinv, size_t qinv_len, const unsigned char *ec_data, unsigned char ec_data_len, const unsigned char pin_policy, const unsigned char touch_policy); + ykpiv_rc ykpiv_get_pin_retries(ykpiv_state *state, int* tries); + ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, const int tries); #define YKPIV_ALGO_TAG 0x80 #define YKPIV_ALGO_3DES 0x03 @@ -234,7 +234,8 @@ extern "C" #define YKPIV_IS_EC(a) ((a == YKPIV_ALGO_ECCP256 || a == YKPIV_ALGO_ECCP384)) #define YKPIV_IS_RSA(a) ((a == YKPIV_ALGO_RSA1024 || a == YKPIV_ALGO_RSA2048)) - +#define YKPIV_RETRIES_DEFAULT 3 +#define YKPIV_RETRIES_MAX 0xff // @@ -310,7 +311,7 @@ extern "C" ykpiv_rc ykpiv_util_reset(ykpiv_state *state); /** - * Card identifier + * Card identifier */ typedef struct { uint8_t data[16]; @@ -318,7 +319,7 @@ extern "C" /** * Get card identifier - * + * * @param state state * @param cardid ykpiv_cardid return value * @@ -328,7 +329,7 @@ extern "C" /** * Set card identifier - * + * * The card must be authenticated to call this function. * * @param state state From 06f2e777ba19bfc782182b51776afdfbe87cf716 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 7 Aug 2017 15:34:45 +0200 Subject: [PATCH 10/57] Backport from minidriver: 11788a4a36bf83a01104700f171774336086e9b4 commit 11788a4a36bf83a01104700f171774336086e9b4 Author: Dave Pate Date: Tue Jul 18 18:28:48 2017 -0700 Fixes #114 - jump to cleanup section in ykpiv_util_write_mscmap on invalid size --- lib/util.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/util.c b/lib/util.c index 442d8be..8c41de4 100644 --- a/lib/util.c +++ b/lib/util.c @@ -239,7 +239,7 @@ ykpiv_rc ykpiv_util_list_keys(ykpiv_state *state, uint8_t *key_count, ykpiv_key const uint8_t SLOTS[] = { YKPIV_KEY_AUTHENTICATION, YKPIV_KEY_SIGNATURE, - YKPIV_KEY_KEYMGM, + YKPIV_KEY_KEYMGM, YKPIV_KEY_RETIRED1, YKPIV_KEY_RETIRED2, YKPIV_KEY_RETIRED3, @@ -298,8 +298,8 @@ ykpiv_rc ykpiv_util_list_keys(ykpiv_state *state, uint8_t *key_count, ykpiv_key cbData += cbRealloc; - // If ykpiv_key is misaligned or results in padding, this causes problems - // in the array we return. If this becomes a problem, we'll probably want + // If ykpiv_key is misaligned or results in padding, this causes problems + // in the array we return. If this becomes a problem, we'll probably want // to go with a flat byte array. pKey = (ykpiv_key*)(pData + offset); @@ -452,7 +452,7 @@ ykpiv_rc ykpiv_util_write_mscmap(ykpiv_state *state, ykpiv_container *containers // we intend to delete the object if ((NULL == containers) || (0 == n_containers)) { - // if either containers or n_containers are non-zero, return an error, + // if either containers or n_containers are non-zero, return an error, // that we only delete strictly when both are set properly if ((NULL != containers) || (0 != n_containers)) { res = YKPIV_GENERIC_ERROR; @@ -469,7 +469,10 @@ ykpiv_rc ykpiv_util_write_mscmap(ykpiv_state *state, ykpiv_container *containers // calculate the required length of the encoded object req_len = 1 /* data tag */ + _ykpiv_set_length(buf, data_len) + data_len; - if (req_len > _obj_size_max(state)) return YKPIV_SIZE_ERROR; + if (req_len > _obj_size_max(state)) { + res = YKPIV_SIZE_ERROR; + goto Cleanup; + } buf[offset++] = TAG_MSCMAP; offset += _ykpiv_set_length(buf + offset, data_len); @@ -592,7 +595,7 @@ ykpiv_rc ykpiv_util_write_msroots(ykpiv_state *state, uint8_t *data, size_t data // we intend to delete the object if ((NULL == data) || (0 == data_len)) { - // if either data or data_len are non-zero, return an error, + // if either data or data_len are non-zero, return an error, // that we only delete strictly when both are set properly if ((NULL != data) || (0 != data_len)) { res = YKPIV_GENERIC_ERROR; @@ -955,7 +958,7 @@ static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *da // check if data or data_len are zero, this means that we intend to delete the object if ((NULL == data) || (0 == data_len)) { - // if either data or data_len are non-zero, return an error, + // if either data or data_len are non-zero, return an error, // that we only delete strictly when both are set properly if ((NULL != data) || (0 != data_len)) { return YKPIV_GENERIC_ERROR; From fb00baf6729d6d8e59accc3539fb3abd7c56a91d Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 28 Aug 2017 12:32:56 +0200 Subject: [PATCH 11/57] Backport from minidriver: commit 90020fea0ac34b2f98b68a5798fa85cb5ad12175 (tag: 3.2) Author: Dave Pate Date: Thu Jul 27 00:31:54 2017 -0700 Release 3.2 Adds automatic PUK blocking Adds feature to turn automatic PUK blocking off Miscellaneous fixes with metadata handling --- lib/Makefile.am | 2 +- lib/internal.h | 12 +- lib/tests/util.c | 6 + lib/util.c | 700 +++++++++++++++++++++++++++++++++++++++++++---- lib/ykpiv.c | 186 ++++++++----- lib/ykpiv.h | 97 ++++++- 6 files changed, 873 insertions(+), 130 deletions(-) diff --git a/lib/Makefile.am b/lib/Makefile.am index 951ea9e..c21df60 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -32,7 +32,7 @@ AM_CPPFLAGS = $(OPENSSL_CFLAGS) $(PCSC_CFLAGS) lib_LTLIBRARIES = libykpiv.la -libykpiv_la_SOURCES = ykpiv.c util.c version.c ykpiv.pc.in ykpiv.map internal.h +libykpiv_la_SOURCES = ykpiv.c util.c des.c des.h version.c ykpiv.pc.in ykpiv.map internal.h libykpiv_la_SOURCES += error.c libykpiv_la_includedir = $(includedir)/ykpiv libykpiv_la_include_HEADERS = ykpiv.h ykpiv-version.h diff --git a/lib/internal.h b/lib/internal.h index 472b3c7..411fd39 100644 --- a/lib/internal.h +++ b/lib/internal.h @@ -55,12 +55,8 @@ struct ykpiv_state { SCARDHANDLE card; int verbose; char *pin; - ykpiv_allocator allocator; bool isNEO; - uint8_t mgmKey[CB_MGM_KEY]; - bool fMgmKeySet; - }; union u_APDU { @@ -93,7 +89,11 @@ extern unsigned const char aid[]; #define CB_ATR_MAX 33 -#define ATR_NEO_R3 "\x3b\xfc\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x4e\x45\x4f\x72\x33\xe1" -#define ATR_YK4 "\x3b\xf8\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x34\xd4" +#define YKPIV_ATR_NEO_R3 "\x3b\xfc\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x4e\x45\x4f\x72\x33\xe1" +#define YKPIV_ATR_YK4 "\x3b\xf8\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x34\xd4" + +#define CHREF_ACT_CHANGE_PIN 0 +#define CHREF_ACT_UNBLOCK_PIN 1 +#define CHREF_ACT_CHANGE_PUK 2 #endif diff --git a/lib/tests/util.c b/lib/tests/util.c index 11b2dd8..6c19f38 100644 --- a/lib/tests/util.c +++ b/lib/tests/util.c @@ -460,6 +460,12 @@ START_TEST(test_authenticate) { res = ykpiv_authenticate(g_state, key); ck_assert_int_eq(res, YKPIV_OK); + // Verify same key works twice + res = ykpiv_hex_decode(default_mgm_key, strlen(default_mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_authenticate(g_state, key); + ck_assert_int_eq(res, YKPIV_OK); + // Change to new key res = ykpiv_hex_decode(mgm_key, strlen(mgm_key), key, &key_len); ck_assert_int_eq(res, YKPIV_OK); diff --git a/lib/util.c b/lib/util.c index 8c41de4..6aa5dc8 100644 --- a/lib/util.c +++ b/lib/util.c @@ -34,6 +34,7 @@ #include #include +#include "des.h" #include #include #include @@ -62,26 +63,29 @@ const uint8_t CCC_TMPL[] = { #define CCC_ID_OFFS 9 #define CB_CCC_ID 14 -#define TAG_CERT 0x70 -#define TAG_CERT_COMPRESS 0x71 -#define TAG_CERT_LRC 0xFE -#define TAG_PIVMAN_DATA 0x80 -#define TAG_FLAGS_1 0x81 -#define TAG_SALT 0x82 -#define TAG_PIN_TIMESTAMP 0x83 -#define TAG_MSCMAP 0x81 -#define TAG_MSROOTS_END 0x82 -#define TAG_MSROOTS_MID 0x83 +#define TAG_CERT 0x70 +#define TAG_CERT_COMPRESS 0x71 +#define TAG_CERT_LRC 0xFE +#define TAG_ADMIN 0x80 +#define TAG_ADMIN_FLAGS_1 0x81 +#define TAG_ADMIN_SALT 0x82 +#define TAG_ADMIN_TIMESTAMP 0x83 +#define TAG_PROTECTED 0x88 +#define TAG_PROTECTED_FLAGS_1 0x81 +#define TAG_PROTECTED_MGM 0x89 +#define TAG_MSCMAP 0x81 +#define TAG_MSROOTS_END 0x82 +#define TAG_MSROOTS_MID 0x83 -#define TAG_RSA_MODULUS 0x81 -#define TAG_RSA_EXP 0x82 -#define TAG_ECC_POINT 0x86 +#define TAG_RSA_MODULUS 0x81 +#define TAG_RSA_EXP 0x82 +#define TAG_ECC_POINT 0x86 #define CB_ECC_POINTP256 65 #define CB_ECC_POINTP384 97 -#define YKPIV_OBJ_PIVMAN_DATA 0x5fff00 +#define YKPIV_OBJ_ADMIN_DATA 0x5fff00 #define YKPIV_OBJ_ATTESTATION 0x5fff01 #define YKPIV_OBJ_MSCMAP 0x5fff10 #define YKPIV_OBJ_MSROOTS1 0x5fff11 @@ -90,45 +94,24 @@ const uint8_t CCC_TMPL[] = { #define YKPIV_OBJ_MSROOTS4 0x5fff14 #define YKPIV_OBJ_MSROOTS5 0x5fff15 +#define ADMIN_FLAGS_1_PUK_BLOCKED 0x01 +#define ADMIN_FLAGS_1_PROTECTED_MGM 0x02 + +#define CB_ADMIN_SALT 16 +#define CB_ADMIN_TIMESTAMP 4 + +#define ITER_MGM_PBKDF2 10000 + +#define PROTECTED_FLAGS_1_PUK_NOBLOCK 0x01 + #define CB_OBJ_TAG_MIN 2 // 1 byte tag + 1 byte len #define CB_OBJ_TAG_MAX (CB_OBJ_TAG_MIN + 2) // 1 byte tag + 3 bytes len -typedef enum { - PRNG_OK = 0, - PRNG_GENERAL_ERROR = -1 -} prng_rc; +#define member_size(type, member) sizeof(((type*)0)->member) static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf, size_t *buf_len); static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len); -prng_rc prng_generate(unsigned char *buffer, const size_t cb_req) { - // TREV TODO: ykpiv.c needs to use this - prng_rc rc = PRNG_OK; - -#ifdef _WINDOWS - HCRYPTPROV hProv = 0; - - if (CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { - if (!CryptGenRandom(hProv, (DWORD)cb_req, buffer)) { - rc = PRNG_GENERAL_ERROR; - } - - CryptReleaseContext(hProv, 0); - } - else { - rc = PRNG_GENERAL_ERROR; - } - -#else - if (-1 == RAND_pseudo_bytes(buffer, cb_req)) { - rc = PRNG_GENERAL_ERROR; - } - -#endif - - return rc; -} - static size_t _obj_size_max(ykpiv_state *state) { return (state && state->isNEO) ? CB_OBJ_MAX_NEO : CB_OBJ_MAX; } @@ -145,6 +128,11 @@ ykpiv_rc _ykpiv_begin_transaction(ykpiv_state *state); ykpiv_rc _ykpiv_end_transaction(ykpiv_state *state); ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state); +static ykpiv_rc _read_metadata(ykpiv_state *state, uint8_t tag, uint8_t* data, size_t* pcb_data); +static ykpiv_rc _write_metadata(ykpiv_state *state, uint8_t tag, uint8_t *data, size_t cb_data); +static ykpiv_rc _get_metadata_item(uint8_t *data, size_t cb_data, uint8_t tag, uint8_t **pp_item, size_t *pcb_item); +static ykpiv_rc _set_metadata_item(uint8_t *data, size_t *pcb_data, size_t cb_data_max, uint8_t tag, uint8_t *p_item, size_t cb_item); + /* ** YKPIV Utility API - aggregate functions and slightly nicer interface */ @@ -387,6 +375,66 @@ ykpiv_rc ykpiv_util_delete_cert(ykpiv_state *state, uint8_t slot) { return ykpiv_util_write_cert(state, slot, NULL, 0); } +ykpiv_rc ykpiv_util_block_puk(ykpiv_state *state) { + ykpiv_rc res = YKPIV_OK; + uint8_t puk[] = { 0x30, 0x42, 0x41, 0x44, 0x46, 0x30, 0x30, 0x44 }; + int tries = -1; + uint8_t data[CB_BUF_MAX]; + size_t cb_data = sizeof(data); + uint8_t *p_item = NULL; + size_t cb_item = 0; + uint8_t flags = 0; + + if (NULL == state) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + while (tries != 0) { + if (YKPIV_OK == (res = ykpiv_change_puk(state, puk, sizeof(puk), puk, sizeof(puk), &tries))) { + /* did we accidentally choose the correct PUK?, change our puk and try again */ + puk[0]++; + } + else { + /* depending on the firmware, tries may not be set to zero when the PUK is blocked, */ + /* instead, the return code will be PIN_LOCKED and tries will be unset */ + if (YKPIV_PIN_LOCKED == res) { + tries = 0; + res = YKPIV_OK; + } + } + } + + /* attempt to set the puk blocked flag in admin data */ + + if (YKPIV_OK == _read_metadata(state, TAG_ADMIN, data, &cb_data)) { + if (YKPIV_OK == _get_metadata_item(data, cb_data, TAG_ADMIN_FLAGS_1, &p_item, &cb_item)) { + if (sizeof(flags) == cb_item) { + memcpy(&flags, p_item, cb_item); + } + else { + if (state->verbose) { fprintf(stderr, "admin flags exist, but are incorrect size = %zu", cb_item); } + } + } + } + + flags |= ADMIN_FLAGS_1_PUK_BLOCKED; + + if (YKPIV_OK != _set_metadata_item(data, &cb_data, CB_OBJ_MAX, TAG_ADMIN_FLAGS_1, (uint8_t*)&flags, sizeof(flags))) { + if (state->verbose) { fprintf(stderr, "could not set admin flags"); } + } + else { + if (YKPIV_OK != _write_metadata(state, TAG_ADMIN, data, cb_data)) { + if (state->verbose) { fprintf(stderr, "could not write admin metadata"); } + } + } + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + ykpiv_rc ykpiv_util_read_mscmap(ykpiv_state *state, ykpiv_container **containers, size_t *n_containers) { ykpiv_rc res = YKPIV_OK; uint8_t buf[CB_BUF_MAX]; @@ -857,6 +905,327 @@ Cleanup: return res; } +ykpiv_rc ykpiv_util_get_config(ykpiv_state *state, ykpiv_config *config) { + ykpiv_rc res = YKPIV_OK; + uint8_t data[CB_BUF_MAX] = { 0 }; + size_t cb_data = sizeof(data); + uint8_t *p_item = NULL; + size_t cb_item = 0; + + if (NULL == state) return YKPIV_GENERIC_ERROR; + if (NULL == config) return YKPIV_GENERIC_ERROR; + + // initialize default values + + config->protected_data_available = false; + config->puk_blocked = false; + config->puk_noblock_on_upgrade = false; + config->pin_last_changed = 0; + config->mgm_type = YKPIV_CONFIG_MGM_MANUAL; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + /* recover admin data */ + if (YKPIV_OK == _read_metadata(state, TAG_ADMIN, data, &cb_data)) { + if (YKPIV_OK == _get_metadata_item(data, cb_data, TAG_ADMIN_FLAGS_1, &p_item, &cb_item)) { + if (*p_item & ADMIN_FLAGS_1_PUK_BLOCKED) config->puk_blocked = true; + if (*p_item & ADMIN_FLAGS_1_PROTECTED_MGM) config->mgm_type = YKPIV_CONFIG_MGM_PROTECTED; + } + + if (YKPIV_OK == _get_metadata_item(data, cb_data, TAG_ADMIN_SALT, &p_item, &cb_item)) { + if (config->mgm_type != YKPIV_CONFIG_MGM_MANUAL) { + if (state->verbose) { + fprintf(stderr, "conflicting types of mgm key administration configured\n"); + } + } + else { + config->mgm_type = YKPIV_CONFIG_MGM_DERIVED; + } + } + + if (YKPIV_OK == _get_metadata_item(data, cb_data, TAG_ADMIN_TIMESTAMP, &p_item, &cb_item)) { + if (CB_ADMIN_TIMESTAMP != cb_item) { + if (state->verbose) { + fprintf(stderr, "pin timestamp in admin metadata is an invalid size"); + } + } + else { + memcpy(&(config->pin_last_changed), p_item, cb_item); + } + } + } + + /* recover protected data */ + cb_data = sizeof(data); + + if (YKPIV_OK == _read_metadata(state, TAG_PROTECTED, data, &cb_data)) { + config->protected_data_available = true; + + if (YKPIV_OK == _get_metadata_item(data, cb_data, TAG_PROTECTED_FLAGS_1, &p_item, &cb_item)) { + if (*p_item & PROTECTED_FLAGS_1_PUK_NOBLOCK) config->puk_noblock_on_upgrade = true; + } + + if (YKPIV_OK == _get_metadata_item(data, cb_data, TAG_PROTECTED_MGM, &p_item, &cb_item)) { + if (config->mgm_type != YKPIV_CONFIG_MGM_PROTECTED) { + if (state->verbose) { + fprintf(stderr, "conflicting types of mgm key administration configured - protected mgm exists\n"); + } + } + config->mgm_type = YKPIV_CONFIG_MGM_PROTECTED; /* always favor protected mgm */ + } + } + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_set_pin_last_changed(ykpiv_state *state) { + ykpiv_rc res = YKPIV_OK; + ykpiv_rc ykrc = YKPIV_OK; + uint8_t data[CB_BUF_MAX] = { 0 }; + size_t cb_data = sizeof(data); + time_t tnow = 0; + + if (NULL == state) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + /* recover admin data */ + if (YKPIV_OK != (ykrc = _read_metadata(state, TAG_ADMIN, data, &cb_data))) { + cb_data = 0; /* set current metadata blob size to zero, we'll add the timestamp to the blank blob */ + } + + tnow = time(NULL); + + if (YKPIV_OK != (res = _set_metadata_item(data, &cb_data, CB_OBJ_MAX, TAG_ADMIN_TIMESTAMP, (uint8_t*)&tnow, CB_ADMIN_TIMESTAMP))) { + if (state->verbose) fprintf(stderr, "could not set pin timestamp, err = %d\n", res); + } + else { + if (YKPIV_OK != (res = _write_metadata(state, TAG_ADMIN, data, cb_data))) { + /* Note: this can fail if authenticate() wasn't called previously - expected behavior */ + if (state->verbose) fprintf(stderr, "could not write admin data, err = %d\n", res); + } + } + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_get_derived_mgm(ykpiv_state *state, const uint8_t *pin, const size_t pin_len, ykpiv_mgm *mgm) { + ykpiv_rc res = YKPIV_OK; + pkcs5_rc p5rc = PKCS5_OK; + uint8_t data[CB_BUF_MAX] = { 0 }; + size_t cb_data = sizeof(data); + uint8_t *p_item = NULL; + size_t cb_item = 0; + + if (NULL == state) return YKPIV_GENERIC_ERROR; + if ((NULL == pin) || (0 == pin_len) || (NULL == mgm)) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + /* recover management key */ + if (YKPIV_OK == (res = _read_metadata(state, TAG_ADMIN, data, &cb_data))) { + if (YKPIV_OK == (res = _get_metadata_item(data, cb_data, TAG_ADMIN_SALT, &p_item, &cb_item))) { + if (cb_item != CB_ADMIN_SALT) { + if (state->verbose) fprintf(stderr, "derived mgm salt exists, but is incorrect size = %zu\n", cb_item); + res = YKPIV_GENERIC_ERROR; + goto Cleanup; + } + + if (PKCS5_OK != (p5rc = pkcs5_pbkdf2_sha1(pin, pin_len, p_item, cb_item, ITER_MGM_PBKDF2, mgm->data, member_size(ykpiv_mgm, data)))) { + if (state->verbose) fprintf(stderr, "pbkdf2 failure, err = %d\n", p5rc); + res = YKPIV_GENERIC_ERROR; + goto Cleanup; + } + } + } + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_get_protected_mgm(ykpiv_state *state, ykpiv_mgm *mgm) { + ykpiv_rc res = YKPIV_OK; + uint8_t data[CB_BUF_MAX] = { 0 }; + size_t cb_data = sizeof(data); + uint8_t *p_item = NULL; + size_t cb_item = 0; + + if (NULL == state) return YKPIV_GENERIC_ERROR; + if (NULL == mgm) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + if (YKPIV_OK != (res = _read_metadata(state, TAG_PROTECTED, data, &cb_data))) { + if (state->verbose) fprintf(stderr, "could not read protected data, err = %d\n", res); + goto Cleanup; + } + + if (YKPIV_OK != (res = _get_metadata_item(data, cb_data, TAG_PROTECTED_MGM, &p_item, &cb_item))) { + if (state->verbose) fprintf(stderr, "could not read protected mgm from metadata, err = %d\n", res); + goto Cleanup; + } + + if (cb_item != member_size(ykpiv_mgm, data)) { + if (state->verbose) fprintf(stderr, "protected data contains mgm, but is the wrong size = %zu\n", cb_item); + res = YKPIV_AUTHENTICATION_ERROR; + goto Cleanup; + } + + memcpy(mgm->data, p_item, cb_item); + +Cleanup: + + memset(data, 0, sizeof(data)); + + _ykpiv_end_transaction(state); + return res; + +} + +/* to set a generated mgm, pass NULL for mgm, or set mgm.data to all zeroes */ +ykpiv_rc ykpiv_util_set_protected_mgm(ykpiv_state *state, ykpiv_mgm *mgm) { + ykpiv_rc res = YKPIV_OK; + ykpiv_rc ykrc = YKPIV_OK; + prng_rc prngrc = PRNG_OK; + bool fGenerate = false; + uint8_t mgm_key[member_size(ykpiv_mgm, data)] = { 0 }; + size_t i = 0; + uint8_t data[CB_BUF_MAX] = { 0 }; + size_t cb_data = sizeof(data); + uint8_t *p_item = NULL; + size_t cb_item = 0; + uint8_t flags_1 = 0; + + if (NULL == state) return YKPIV_GENERIC_ERROR; + + if (!mgm) { + fGenerate = true; + } + else { + fGenerate = true; + memcpy(mgm_key, mgm->data, sizeof(mgm_key)); + + for (i = 0; i < sizeof(mgm_key); i++) { + if (mgm_key[i] != 0) { + fGenerate = false; + break; + } + } + } + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + /* try to set the mgm key as long as we don't encounter a fatal error */ + do { + if (fGenerate) { + /* generate a new mgm key */ + if (PRNG_OK != (prngrc = prng_generate(mgm_key, sizeof(mgm_key)))) { + if (state->verbose) fprintf(stderr, "could not set generate new mgm, err = %d\n", prngrc); + res = YKPIV_RANDOMNESS_ERROR; + goto Cleanup; + } + } + + if (YKPIV_OK != (ykrc = ykpiv_set_mgmkey(state, mgm_key))) { + /* + ** if _set_mgmkey fails with YKPIV_KEY_ERROR, it means the generated key is weak + ** otherwise, log a warning, since the device mgm key is corrupt or we're in + ** a state where we can't set the mgm key + */ + if (YKPIV_KEY_ERROR != ykrc) { + if (state->verbose) fprintf(stderr, "could not set new derived mgm key, err = %d\n", ykrc); + res = ykrc; + goto Cleanup; + } + } + else { + /* _set_mgmkey succeeded, stop generating */ + fGenerate = false; + } + } while (fGenerate); + + /* set output mgm */ + if (mgm) { + memcpy(mgm->data, mgm_key, sizeof(mgm_key)); + } + + /* after this point, we've set the mgm key, so the function should succeed, regardless of being able to set the metadata */ + + /* set the new mgm key in protected data */ + if (YKPIV_OK != (ykrc = _read_metadata(state, TAG_PROTECTED, data, &cb_data))) { + cb_data = 0; /* set current metadata blob size to zero, we'll add to the blank blob */ + } + + if (YKPIV_OK != (ykrc = _set_metadata_item(data, &cb_data, CB_OBJ_MAX, TAG_PROTECTED_MGM, mgm_key, sizeof(mgm_key)))) { + if (state->verbose) fprintf(stderr, "could not set protected mgm item, err = %d\n", ykrc); + } + else { + if (YKPIV_OK != (ykrc = _write_metadata(state, TAG_PROTECTED, data, cb_data))) { + if (state->verbose) fprintf(stderr, "could not write protected data, err = %d\n", ykrc); + goto Cleanup; + } + } + + /* set the protected mgm flag in admin data */ + cb_data = sizeof(data); + + if (YKPIV_OK != (ykrc = _read_metadata(state, TAG_ADMIN, data, &cb_data))) { + cb_data = 0; + } + else { + + if (YKPIV_OK != (ykrc = _get_metadata_item(data, cb_data, TAG_ADMIN_FLAGS_1, &p_item, &cb_item))) { + /* flags are not set */ + if (state->verbose) fprintf(stderr, "admin data exists, but flags are not present\n"); + } + + if (cb_item == sizeof(flags_1)) { + memcpy(&flags_1, p_item, cb_item); + } + else { + if (state->verbose) fprintf(stderr, "admin data flags are an incorrect size = %zu\n", cb_item); + } + + /* remove any existing salt */ + if (YKPIV_OK != (ykrc = _set_metadata_item(data, &cb_data, CB_OBJ_MAX, TAG_ADMIN_SALT, NULL, 0))) { + if (state->verbose) fprintf(stderr, "could not unset derived mgm salt, err = %d\n", ykrc); + } + } + + flags_1 |= ADMIN_FLAGS_1_PROTECTED_MGM; + + if (YKPIV_OK != (ykrc = _set_metadata_item(data, &cb_data, CB_OBJ_MAX, TAG_ADMIN_FLAGS_1, &flags_1, sizeof(flags_1)))) { + if (state->verbose) fprintf(stderr, "could not set admin flags item, err = %d\n", ykrc); + } + else { + if (YKPIV_OK != (ykrc = _write_metadata(state, TAG_ADMIN, data, cb_data))) { + if (state->verbose) fprintf(stderr, "could not write admin data, err = %d\n", ykrc); + goto Cleanup; + } + } + + +Cleanup: + + memset(data, 0, sizeof(data)); + memset(mgm_key, 0, sizeof(mgm_key)); + + _ykpiv_end_transaction(state); + return res; +} ykpiv_rc ykpiv_util_reset(ykpiv_state *state) { unsigned char templ[] = {0, YKPIV_INS_RESET, 0, 0}; @@ -908,6 +1277,7 @@ static int _slot2object(uint8_t slot) { } static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf, size_t *buf_len) { + // TREV TODO: should this select application? ykpiv_rc res = YKPIV_OK; uint8_t *ptr = NULL; int object_id = _slot2object(slot); @@ -947,6 +1317,7 @@ static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf } static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len) { + // TREV TODO: should this select application? uint8_t buf[CB_OBJ_MAX]; size_t cbBuf = sizeof(buf); int object_id = _slot2object(slot); @@ -990,3 +1361,240 @@ static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *da // write onto device return ykpiv_save_object(state, object_id, buf, offset); } + +/* +** PIV Manager data helper functions +** +** These functions allow the PIV Manager to extend the YKPIV_OBJ_ADMIN_DATA object without having to change +** this implementation. New items may be added without modifying these functions. Data items are picked +** from the pivman_data buffer by tag, and replaced either in place if length allows or the data object is +** expanded to fit a new/updated data item. +*/ + +/* +** _get_metadata_item +** +** Parses the metadata blob, specified by data, looking for the specified tag. If found, the item is +** returned in pp_item and its size in pcb_item. +** +** If the item is not found, this function returns YKPIV_GENERIC_ERROR. +*/ +static ykpiv_rc _get_metadata_item(uint8_t *data, size_t cb_data, uint8_t tag, uint8_t **pp_item, size_t *pcb_item) { + uint8_t *p_temp = data; + size_t cb_temp = 0; + uint8_t tag_temp = 0; + + if (!data || !pp_item || !pcb_item) return YKPIV_GENERIC_ERROR; + + *pp_item = NULL; + *pcb_item = 0; + + while (p_temp < (data + cb_data)) { + tag_temp = *p_temp++; + p_temp += _ykpiv_get_length(p_temp, &cb_temp); + + if (tag_temp == tag) { + // found tag + break; + } + + p_temp += cb_temp; + } + + if (p_temp < (data + cb_data)) { + *pp_item = p_temp; + *pcb_item = cb_temp; + return YKPIV_OK; + } + + return YKPIV_GENERIC_ERROR; +} + +static int _get_length_size(size_t length) { + if (length < 0x80) { + return 1; + } + else if (length < 0xff) { + return 2; + } + else { + return 3; + } +} + +/* +** _set_metadata_item +** +** Adds or replaces a data item encoded in a metadata blob, specified by tag to the existing +** metadata blob (data) until it reaches the a maximum buffer size (cb_data_max). +** +** If adding/replacing the item would exceed cb_data_max, this function returns YKPIV_GENERIC_ERROR. +** +** The new size of the blob is returned in pcb_data. +*/ +static ykpiv_rc _set_metadata_item(uint8_t *data, size_t *pcb_data, size_t cb_data_max, uint8_t tag, uint8_t *p_item, size_t cb_item) { + uint8_t *p_temp = data; + size_t cb_temp = 0; + uint8_t tag_temp = 0; + size_t cb_len = 0; + uint8_t *p_next = NULL; + long cb_moved = 0; /* must be signed to have negative offsets */ + + if (!data || !pcb_data) return YKPIV_GENERIC_ERROR; + + while (p_temp < (data + *pcb_data)) { + tag_temp = *p_temp++; + cb_len = _ykpiv_get_length(p_temp, &cb_temp); + p_temp += cb_len; + + if (tag_temp == tag) { + /* found tag */ + + /* check length, if it matches, overwrite */ + if (cb_temp == cb_item) { + memcpy(p_temp, p_item, cb_item); + return YKPIV_OK; + } + + /* length doesn't match, expand/shrink to fit */ + p_next = p_temp + cb_temp; + cb_moved = (long)cb_item - (long)cb_temp + ((long)(cb_item != 0 ? _get_length_size(cb_item) : -1 /* for tag, if deleting */) - (long)cb_len); /* accounts for different length encoding */ + + /* length would cause buffer overflow, return error */ + if (*pcb_data + cb_moved > cb_data_max) { + return YKPIV_GENERIC_ERROR; + } + + /* move remaining data */ + memmove(p_next + cb_moved, p_next, *pcb_data - (p_next - data)); + *pcb_data += cb_moved; + + /* re-encode item and insert */ + if (cb_item != 0) { + p_temp -= cb_len; + p_temp += _ykpiv_set_length(p_temp, cb_item); + memcpy(p_temp, p_item, cb_item); + } + + return YKPIV_OK; + } //if tag found + + p_temp += cb_temp; + } + + if (cb_item == 0) { + /* we've been asked to delete an existing item that isn't in the blob */ + return YKPIV_OK; + } + + // we did not find an existing tag, append + p_temp = data + *pcb_data; + cb_len = _get_length_size(cb_item); + + // length would cause buffer overflow, return error + if (*pcb_data + cb_len + cb_item > cb_data_max) { + return YKPIV_GENERIC_ERROR; + } + + *p_temp++ = tag; + p_temp += _ykpiv_set_length(p_temp, cb_item); + memcpy(p_temp, p_item, cb_item); + *pcb_data += 1 + cb_len + cb_item; + + return YKPIV_OK; +} + +/* +** _read_metadata +** +** Reads admin or protected data (specified by tag) from its associated object. +** +** The data stored in the object is parsed to ensure it has the correct tag and valid length. +** +** data must point to a buffer of at least CB_BUF_MAX bytes, and pcb_data should point to +** the size of data. +** +** To read from protected data, the pin must be verified prior to calling this function. +*/ +static ykpiv_rc _read_metadata(ykpiv_state *state, uint8_t tag, uint8_t* data, size_t* pcb_data) { + // TREV TODO: should this select application? + ykpiv_rc res = YKPIV_OK; + uint8_t *p_temp = NULL; + size_t cb_temp = 0; + int obj_id = 0; + + if (!data || !data || !pcb_data || (CB_BUF_MAX > *pcb_data)) return YKPIV_GENERIC_ERROR; + + switch (tag) { + case TAG_ADMIN: obj_id = YKPIV_OBJ_ADMIN_DATA; break; + case TAG_PROTECTED: obj_id = YKPIV_OBJ_PRINTED; break; + default: return YKPIV_INVALID_OBJECT; + } + + cb_temp = *pcb_data; + *pcb_data = 0; + + if (YKPIV_OK != (res = ykpiv_fetch_object(state, obj_id, data, (unsigned long*)&cb_temp))) { + return res; + } + + if (cb_temp < CB_OBJ_TAG_MIN) return YKPIV_GENERIC_ERROR; + + p_temp = data; + + if (tag != *p_temp++) return YKPIV_GENERIC_ERROR; + + p_temp += _ykpiv_get_length(p_temp, pcb_data); + + if (*pcb_data > ((size_t)cb_temp - (p_temp - data))) { + *pcb_data = 0; + return YKPIV_GENERIC_ERROR; + } + + memmove(data, p_temp, *pcb_data); + + return YKPIV_OK; +} + +/* +** _write_metadata +** +** Writes admin/protected data, specified by tag to its associated object. +** +** To delete the metadata, set data to NULL and cb_data to 0. +** +** To write protected data, the pin must be verified prior to calling this function. +*/ +static ykpiv_rc _write_metadata(ykpiv_state *state, uint8_t tag, uint8_t *data, size_t cb_data) { + // TREV TODO: should this select application? + ykpiv_rc res = YKPIV_OK; + uint8_t buf[CB_OBJ_MAX] = { 0 }; + uint8_t *pTemp = buf; + int obj_id = 0; + + if (cb_data > (_obj_size_max(state) - CB_OBJ_TAG_MAX)) { + return YKPIV_GENERIC_ERROR; + } + + switch (tag) { + case TAG_ADMIN: obj_id = YKPIV_OBJ_ADMIN_DATA; break; + case TAG_PROTECTED: obj_id = YKPIV_OBJ_PRINTED; break; + default: return YKPIV_INVALID_OBJECT; + } + + if (!data || (0 == cb_data)) { + // deleting metadata + res = ykpiv_save_object(state, obj_id, NULL, 0); + } + else { + *pTemp++ = tag; + pTemp += _ykpiv_set_length(pTemp, cb_data); + + memcpy(pTemp, data, cb_data); + pTemp += cb_data; + + res = ykpiv_save_object(state, obj_id, buf, pTemp - buf); + } + + return res; +} diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 0e58ee0..99eaf46 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -34,14 +34,14 @@ #include #include -#include -#include -#include +#include "des.h" #include "internal.h" #include "ykpiv.h" -static ykpiv_rc send_data(ykpiv_state *state, APDU *apdu, +#define YKPIV_MGM_DEFAULT "\x01\x02\x03\x04\x05\x06\x07\x08\x01\x02\x03\x04\x05\x06\x07\x08\x01\x02\x03\x04\x05\x06\x07\x08" + +static ykpiv_rc _send_data(ykpiv_state *state, APDU *apdu, unsigned char *data, unsigned long *recv_len, int *sw); unsigned const char aid[] = { @@ -158,7 +158,7 @@ ykpiv_rc ykpiv_init_with_allocator(ykpiv_state **state, int verbose, const ykpiv s->pin = NULL; s->allocator = *allocator; s->verbose = verbose; - s->context = SCARD_E_INVALID_HANDLE; // TREV TODO -1 on Windows + s->context = SCARD_E_INVALID_HANDLE; // TREV TODO -1 on Windows *state = s; return YKPIV_OK; } @@ -202,7 +202,7 @@ ykpiv_rc _ykpiv_select_application(ykpiv_state *state) { apdu.st.lc = sizeof(aid); memcpy(apdu.st.data, aid, sizeof(aid)); - if((res = send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { + if((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { if(state->verbose) { fprintf(stderr, "Failed communicating with card: '%s'\n", ykpiv_strerror(res)); } @@ -283,7 +283,7 @@ ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { return YKPIV_PCSC_ERROR; } - state->isNEO = (((sizeof(ATR_NEO_R3) - 1) == atr_len) && (0 == memcmp(ATR_NEO_R3, atr, atr_len))); + state->isNEO = (((sizeof(YKPIV_ATR_NEO_R3) - 1) == atr_len) && (0 == memcmp(YKPIV_ATR_NEO_R3, atr, atr_len))); } state->card = card; @@ -434,7 +434,7 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, } apdu.st.lc = this_size; memcpy(apdu.st.data, in_ptr, this_size); - res = send_data(state, &apdu, data, &recv_len, sw); + res = _send_data(state, &apdu, data, &recv_len, sw); if(res != YKPIV_OK) { _ykpiv_end_transaction(state); return res; @@ -466,7 +466,7 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, memset(apdu.raw, 0, sizeof(apdu.raw)); apdu.st.ins = 0xc0; - res = send_data(state, &apdu, data, &recv_len, sw); + res = _send_data(state, &apdu, data, &recv_len, sw); if(res != YKPIV_OK) { _ykpiv_end_transaction(state); return res; @@ -485,7 +485,7 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, return _ykpiv_end_transaction(state); } -static ykpiv_rc send_data(ykpiv_state *state, APDU *apdu, +static ykpiv_rc _send_data(ykpiv_state *state, APDU *apdu, unsigned char *data, unsigned long *recv_len, int *sw) { long rc; unsigned int send_len = (unsigned int)apdu->st.lc + 5; @@ -519,24 +519,24 @@ static ykpiv_rc send_data(ykpiv_state *state, APDU *apdu, ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { APDU apdu; unsigned char data[261]; - DES_cblock challenge; + unsigned char challenge[8]; unsigned long recv_len = sizeof(data); int sw; ykpiv_rc res; + des_key* mgm_key = NULL; + size_t out_len = 0; - DES_key_schedule ks1, ks2, ks3; + if (NULL == state) return YKPIV_GENERIC_ERROR; - // TREV TODO: default/derived key + if (NULL == key) { + /* use the derived mgm key to authenticate, if it hasn't been derived, use default */ + key = YKPIV_MGM_DEFAULT; + } /* set up our key */ - { - const_DES_cblock key_tmp; - memcpy(key_tmp, key, 8); - DES_set_key_unchecked(&key_tmp, &ks1); - memcpy(key_tmp, key + 8, 8); - DES_set_key_unchecked(&key_tmp, &ks2); - memcpy(key_tmp, key + 16, 8); - DES_set_key_unchecked(&key_tmp, &ks3); + if (DES_OK != des_import_key(DES_TYPE_3DES, key, CB_MGM_KEY, &mgm_key)) { + res = YKPIV_ALGORITHM_ERROR; + goto Cleanup; } /* get a challenge from the card */ @@ -549,10 +549,12 @@ ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { apdu.st.data[0] = 0x7c; apdu.st.data[1] = 0x02; apdu.st.data[2] = 0x80; - if((res = send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { - return res; - } else if(sw != SW_SUCCESS) { - return YKPIV_AUTHENTICATION_ERROR; + if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { + goto Cleanup; + } + else if (sw != SW_SUCCESS) { + res = YKPIV_AUTHENTICATION_ERROR; + goto Cleanup; } memcpy(challenge, data + 4, 8); } @@ -560,8 +562,9 @@ ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { /* send a response to the cards challenge and a challenge of our own. */ { unsigned char *dataptr = apdu.st.data; - DES_cblock response; - DES_ecb3_encrypt(&challenge, &response, &ks1, &ks2, &ks3, 0); + unsigned char response[8]; + out_len = sizeof(response); + des_decrypt(mgm_key, challenge, sizeof(challenge), response, &out_len); recv_len = sizeof(data); memset(apdu.raw, 0, sizeof(apdu)); @@ -576,32 +579,45 @@ ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { dataptr += 8; *dataptr++ = 0x81; *dataptr++ = 8; - if(RAND_pseudo_bytes(dataptr, 8) == -1) { - if(state->verbose) { - fprintf(stderr, "Failed getting randomness for authentication.\n"); + if (PRNG_GENERAL_ERROR == prng_generate(dataptr, 8)) { + if (state->verbose) { + fprintf(stderr, "Failed getting randomness for authentication.\n"); } - return YKPIV_RANDOMNESS_ERROR; + res = YKPIV_RANDOMNESS_ERROR; + goto Cleanup; } memcpy(challenge, dataptr, 8); dataptr += 8; - apdu.st.lc = dataptr - apdu.st.data; - if((res = send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { - return res; - } else if(sw != SW_SUCCESS) { - return YKPIV_AUTHENTICATION_ERROR; + apdu.st.lc = (unsigned char)(dataptr - apdu.st.data); + if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { + goto Cleanup; + } + else if (sw != SW_SUCCESS) { + res = YKPIV_AUTHENTICATION_ERROR; + goto Cleanup; } } /* compare the response from the card with our challenge */ { - DES_cblock response; - DES_ecb3_encrypt(&challenge, &response, &ks1, &ks2, &ks3, 1); - if(memcmp(response, data + 4, 8) == 0) { - return YKPIV_OK; - } else { - return YKPIV_AUTHENTICATION_ERROR; + unsigned char response[8]; + out_len = sizeof(response); + des_encrypt(mgm_key, challenge, sizeof(challenge), response, &out_len); + if (memcmp(response, data + 4, 8) == 0) { + res = YKPIV_OK; + } + else { + res = YKPIV_AUTHENTICATION_ERROR; } } + +Cleanup: + + if (mgm_key) { + des_destroy_key(mgm_key); + } + + return res; } ykpiv_rc ykpiv_set_mgmkey(ykpiv_state *state, const unsigned char *new_key) { @@ -613,45 +629,43 @@ ykpiv_rc ykpiv_set_mgmkey2(ykpiv_state *state, const unsigned char *new_key, con unsigned char data[261]; unsigned long recv_len = sizeof(data); int sw; - size_t i; - ykpiv_rc res; + ykpiv_rc res = YKPIV_OK; - for(i = 0; i < 3; i++) { - const_DES_cblock key_tmp; - memcpy(key_tmp, new_key + i * 8, 8); - DES_set_odd_parity(&key_tmp); - if(DES_is_weak_key(&key_tmp) != 0) { - if(state->verbose) { - fprintf(stderr, "Won't set new key '"); - dump_hex(new_key + i * 8, 8); - fprintf(stderr, "' since it's weak (with parity the key is: "); - dump_hex(key_tmp, 8); - fprintf(stderr, ").\n"); - } - return YKPIV_GENERIC_ERROR; + if (yk_des_is_weak_key(new_key, DES_LEN_3DES)) { + if (state->verbose) { + fprintf(stderr, "Won't set new key '"); + dump_hex(new_key, DES_LEN_3DES); + fprintf(stderr, "' since it's weak (with odd parity).\n"); } + return YKPIV_KEY_ERROR; } memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_SET_MGMKEY; apdu.st.p1 = 0xff; - if(touch == 0) { + if (touch == 0) { apdu.st.p2 = 0xff; - } else if(touch == 1) { + } + else if (touch == 1) { apdu.st.p2 = 0xfe; - } else { + } + else { return YKPIV_GENERIC_ERROR; } - apdu.st.lc = DES_KEY_SZ * 3 + 3; + + apdu.st.lc = DES_LEN_3DES + 3; apdu.st.data[0] = YKPIV_ALGO_3DES; apdu.st.data[1] = YKPIV_KEY_CARDMGM; - apdu.st.data[2] = DES_KEY_SZ * 3; - memcpy(apdu.st.data + 3, new_key, DES_KEY_SZ * 3); - if((res = send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { + apdu.st.data[2] = DES_LEN_3DES; + memcpy(apdu.st.data + 3, new_key, DES_LEN_3DES); + + if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { return res; - } else if(sw == SW_SUCCESS) { + } + else if (sw == SW_SUCCESS) { return YKPIV_OK; } + return YKPIV_GENERIC_ERROR; } @@ -793,16 +807,39 @@ ykpiv_rc ykpiv_sign_data(ykpiv_state *state, const unsigned char *raw_in, size_t in_len, unsigned char *sign_out, size_t *out_len, unsigned char algorithm, unsigned char key) { + ykpiv_rc res = YKPIV_OK; - return _general_authenticate(state, raw_in, in_len, sign_out, out_len, - algorithm, key, false); + if (NULL == state) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + // TREV TODO: clean up selections + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + res = _general_authenticate(state, raw_in, in_len, sign_out, out_len, + algorithm, key, false); +Cleanup: + _ykpiv_end_transaction(state); + return res; } ykpiv_rc ykpiv_decipher_data(ykpiv_state *state, const unsigned char *in, size_t in_len, unsigned char *out, size_t *out_len, unsigned char algorithm, unsigned char key) { - return _general_authenticate(state, in, in_len, out, out_len, - algorithm, key, true); + ykpiv_rc res = YKPIV_OK; + + if (NULL == state) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + + res = _general_authenticate(state, in, in_len, out, out_len, + algorithm, key, true); + +Cleanup: + + _ykpiv_end_transaction(state); + return res; } ykpiv_rc ykpiv_get_version(ykpiv_state *state, char *version, size_t len) { @@ -814,7 +851,7 @@ ykpiv_rc ykpiv_get_version(ykpiv_state *state, char *version, size_t len) { memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_GET_VERSION; - if((res = send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { + if((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { return res; } else if(sw == SW_SUCCESS) { int result = snprintf(version, len, "%d.%d.%d", data[0], data[1], data[2]); @@ -828,6 +865,7 @@ ykpiv_rc ykpiv_get_version(ykpiv_state *state, char *version, size_t len) { } ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { + // TREV TODO: pin len? APDU apdu; unsigned char data[261]; unsigned long recv_len = sizeof(data); @@ -853,7 +891,7 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { memset(apdu.st.data + len, 0xff, 8 - len); } } - if((res = send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { + if((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { return res; } else if(sw == SW_SUCCESS) { if (pin) { @@ -895,7 +933,7 @@ ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, const int tries) { unsigned char templ[] = {0, YKPIV_INS_SET_PIN_RETRIES, (unsigned char)tries, YKPIV_RETRIES_DEFAULT}; unsigned char data[0xff]; unsigned long recv_len = sizeof(data); - int sw; + int sw = 0; if (0 == tries) { //zero value means no change in retry count according to minidriver spec @@ -919,10 +957,6 @@ ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, const int tries) { return res; } -#define CHREF_ACT_CHANGE_PIN 0 -#define CHREF_ACT_UNBLOCK_PIN 1 -#define CHREF_ACT_CHANGE_PUK 2 - static ykpiv_rc change_pin_internal(ykpiv_state *state, int action, const char * current_pin, size_t current_pin_len, const char * new_pin, size_t new_pin_len, int *tries) { int sw; unsigned char templ[] = {0, YKPIV_INS_CHANGE_REFERENCE, 0, 0x80}; diff --git a/lib/ykpiv.h b/lib/ykpiv.h index 0af2e79..37221ce 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -70,7 +70,7 @@ extern "C" ykpiv_pfn_alloc pfn_alloc; ykpiv_pfn_realloc pfn_realloc; ykpiv_pfn_free pfn_free; - void * alloc_data; + void * alloc_data; } ykpiv_allocator; const char *ykpiv_strerror(ykpiv_rc err); @@ -308,6 +308,92 @@ extern "C" ykpiv_rc ykpiv_util_read_msroots(ykpiv_state *state, uint8_t **data, size_t *data_len); ykpiv_rc ykpiv_util_write_msroots(ykpiv_state *state, uint8_t *data, size_t data_len); + typedef enum { + YKPIV_CONFIG_MGM_MANUAL = 0, + YKPIV_CONFIG_MGM_DERIVED = 1, + YKPIV_CONFIG_MGM_PROTECTED = 2 + } ykpiv_config_mgm_type; + +#pragma pack(push, 1) + typedef struct _ykpiv_config { + uint8_t protected_data_available; + uint8_t puk_blocked; + uint8_t puk_noblock_on_upgrade; + uint32_t pin_last_changed; + ykpiv_config_mgm_type mgm_type; + } ykpiv_config; + + typedef struct _ykpiv_mgm { + uint8_t data[24]; + } ykpiv_mgm; +#pragma pack(pop) + + /** + * Get current PIV applet administration configuration state + * + * @param state [in] state + * @param config [out] output ykpiv_config struct with current applet data + * + * @return ykpiv_rc error code + */ + ykpiv_rc ykpiv_util_get_config(ykpiv_state *state, ykpiv_config *config); + + /** + * Set last pin changed time to current time + * + * The applet must be authenticated to call this function + * + * @param state state + * + * @return ykpiv_rc error code + */ + ykpiv_rc ykpiv_util_set_pin_last_changed(ykpiv_state *state); + + /** + * Get Derived MGM key + * + * @param state [in] state + * @param pin [in] pin used to derive mgm key + * @param pin_len [in] length of pin + * @param mgm [out] protected mgm key + * + * @return ykpiv_rc error code + */ + ykpiv_rc ykpiv_util_get_derived_mgm(ykpiv_state *state, const uint8_t *pin, const size_t pin_len, ykpiv_mgm *mgm); + + /** + * Get Protected MGM key + * + * The user pin must be verified to call this function + * + * @param state [in] state + * @param mgm [out] returns protected mgm key + * + * @return ykpiv_rc error code + */ + ykpiv_rc ykpiv_util_get_protected_mgm(ykpiv_state *state, ykpiv_mgm *mgm); + + /** + * Set Protected MGM key + * + * The applet must be authenticated and the user pin verified to call this function + * + * @param state state + * @param mgm [in] if mgm is NULL or mgm.data is all zeroes, generate mgm, otherwise set specified key; [out] returns generated mgm key + * + * @return ykpiv_rc error code + */ + ykpiv_rc ykpiv_util_set_protected_mgm(ykpiv_state *state, ykpiv_mgm *mgm); + + /** + * Reset PIV applet + * + * The user pin and puk must be blocked to call this function. + * + * @param state state + * + * @return ykpiv_rc error code + */ ykpiv_rc ykpiv_util_reset(ykpiv_state *state); /** @@ -352,6 +438,15 @@ extern "C" */ ykpiv_devmodel ykpiv_util_devicemodel(ykpiv_state *state); + /** + * Block PUK + * + * Utility function to block the PUK. + * + * To set the PUK blocked flag in the admin data, the applet must be authenticated. + */ + ykpiv_rc ykpiv_util_block_puk(ykpiv_state *state); + #ifdef __cplusplus } From a8b2c2c1c46fdae7b09369afe10c54b12d9db40d Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 11 Sep 2017 10:51:24 +0200 Subject: [PATCH 12/57] Fix DES bugs in Linux. Windows+Linux both pass unit tests. --- lib/Makefile.am | 2 +- lib/internal.c | 447 ++++++++++++++++++++++++++++++++++++++++++++++++ lib/internal.h | 81 ++++++--- lib/util.c | 9 +- lib/ykpiv.c | 104 ++++++++--- lib/ykpiv.h | 10 ++ 6 files changed, 600 insertions(+), 53 deletions(-) create mode 100644 lib/internal.c diff --git a/lib/Makefile.am b/lib/Makefile.am index c21df60..25ab5a8 100644 --- a/lib/Makefile.am +++ b/lib/Makefile.am @@ -32,7 +32,7 @@ AM_CPPFLAGS = $(OPENSSL_CFLAGS) $(PCSC_CFLAGS) lib_LTLIBRARIES = libykpiv.la -libykpiv_la_SOURCES = ykpiv.c util.c des.c des.h version.c ykpiv.pc.in ykpiv.map internal.h +libykpiv_la_SOURCES = ykpiv.c util.c internal.c internal.h version.c ykpiv.pc.in ykpiv.map libykpiv_la_SOURCES += error.c libykpiv_la_includedir = $(includedir)/ykpiv libykpiv_la_include_HEADERS = ykpiv.h ykpiv-version.h diff --git a/lib/internal.c b/lib/internal.c new file mode 100644 index 0000000..adf7e59 --- /dev/null +++ b/lib/internal.c @@ -0,0 +1,447 @@ + +#ifdef _WINDOWS +#include +#include +#else +#include +#endif + +#include +#include + +#include "internal.h" + +/* +** Definitions +*/ + +#ifdef _WINDOWS + +struct des_key { + HCRYPTPROV hProv; + HCRYPTKEY hKey; + ALG_ID alg; +}; + +static const BYTE PRIVATEKEY_EXPOF1_BLOB[] = +{ + 0x07, 0x02, 0x00, 0x00, 0x00, 0xA4, 0x00, 0x00, + 0x52, 0x53, 0x41, 0x32, 0x00, 0x02, 0x00, 0x00, + 0x01, 0x00, 0x00, 0x00, 0xAB, 0xEF, 0xFA, 0xC6, + 0x7D, 0xE8, 0xDE, 0xFB, 0x68, 0x38, 0x09, 0x92, + 0xD9, 0x42, 0x7E, 0x6B, 0x89, 0x9E, 0x21, 0xD7, + 0x52, 0x1C, 0x99, 0x3C, 0x17, 0x48, 0x4E, 0x3A, + 0x44, 0x02, 0xF2, 0xFA, 0x74, 0x57, 0xDA, 0xE4, + 0xD3, 0xC0, 0x35, 0x67, 0xFA, 0x6E, 0xDF, 0x78, + 0x4C, 0x75, 0x35, 0x1C, 0xA0, 0x74, 0x49, 0xE3, + 0x20, 0x13, 0x71, 0x35, 0x65, 0xDF, 0x12, 0x20, + 0xF5, 0xF5, 0xF5, 0xC1, 0xED, 0x5C, 0x91, 0x36, + 0x75, 0xB0, 0xA9, 0x9C, 0x04, 0xDB, 0x0C, 0x8C, + 0xBF, 0x99, 0x75, 0x13, 0x7E, 0x87, 0x80, 0x4B, + 0x71, 0x94, 0xB8, 0x00, 0xA0, 0x7D, 0xB7, 0x53, + 0xDD, 0x20, 0x63, 0xEE, 0xF7, 0x83, 0x41, 0xFE, + 0x16, 0xA7, 0x6E, 0xDF, 0x21, 0x7D, 0x76, 0xC0, + 0x85, 0xD5, 0x65, 0x7F, 0x00, 0x23, 0x57, 0x45, + 0x52, 0x02, 0x9D, 0xEA, 0x69, 0xAC, 0x1F, 0xFD, + 0x3F, 0x8C, 0x4A, 0xD0, + + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + + 0x64, 0xD5, 0xAA, 0xB1, + 0xA6, 0x03, 0x18, 0x92, 0x03, 0xAA, 0x31, 0x2E, + 0x48, 0x4B, 0x65, 0x20, 0x99, 0xCD, 0xC6, 0x0C, + 0x15, 0x0C, 0xBF, 0x3E, 0xFF, 0x78, 0x95, 0x67, + 0xB1, 0x74, 0x5B, 0x60, + + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +const DWORD PRIVATEKEY_EXPOF1_BITLEN = 512; +const ALG_ID PRIVATEKEY_EXPOF1_ALG = CALG_RSA_KEYX; + +#else + +struct des_key { + DES_key_schedule ks1; + DES_key_schedule ks2; + DES_key_schedule ks3; +}; + +#endif + +/* +** Methods +*/ + +des_rc des_import_key(const int type, const unsigned char* keyraw, const size_t keyrawlen, des_key** key) { + des_rc rc = DES_OK; + size_t cb_expectedkey = DES_LEN_3DES; + +#ifdef _WINDOWS + + HCRYPTKEY hNullKey = 0; + ALG_ID alg = 0; + unsigned char* pbSessionBlob = NULL; + DWORD cbSessionBlob = 0; + DWORD cbRandom = 0; + unsigned char* pbTmp = NULL; + size_t n = 0; + + switch (type) { + case DES_TYPE_3DES: + alg = CALG_3DES; + cb_expectedkey = DES_LEN_3DES; + break; + default: + rc = DES_INVALID_PARAMETER; + goto ERROR_EXIT; + } + + if (!keyraw) { rc = DES_INVALID_PARAMETER; goto ERROR_EXIT; } + if (keyrawlen != cb_expectedkey) { rc = DES_INVALID_PARAMETER; goto ERROR_EXIT; } + if (!key) { rc = DES_INVALID_PARAMETER; goto ERROR_EXIT; } + if (!(*key = (des_key*)malloc(sizeof(des_key)))) { rc = DES_MEMORY_ERROR; goto ERROR_EXIT; } + + memset(*key, 0, sizeof(des_key)); + + (*key)->alg = alg; + + if (!CryptAcquireContext(&((*key)->hProv), NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { rc = DES_GENERAL_ERROR; goto ERROR_EXIT; } + + // Import the exponent-of-one private key. + if (!CryptImportKey((*key)->hProv, PRIVATEKEY_EXPOF1_BLOB, sizeof(PRIVATEKEY_EXPOF1_BLOB), 0, 0, &hNullKey)) { rc = DES_GENERAL_ERROR; goto ERROR_EXIT; } + + // calculate Simple blob's length + cbSessionBlob = (PRIVATEKEY_EXPOF1_BITLEN / 8) + sizeof(ALG_ID) + sizeof(BLOBHEADER); + + // allocate simple blob buffer + if (!(pbSessionBlob = malloc(cbSessionBlob))) { rc = DES_MEMORY_ERROR; goto ERROR_EXIT; } + memset(pbSessionBlob, 0, cbSessionBlob); + + pbTmp = pbSessionBlob; + + // SIMPLEBLOB Format is documented in SDK + // Copy header to buffer + ((BLOBHEADER *)pbTmp)->bType = SIMPLEBLOB; + ((BLOBHEADER *)pbTmp)->bVersion = 2; + ((BLOBHEADER *)pbTmp)->reserved = 0; + ((BLOBHEADER *)pbTmp)->aiKeyAlg = alg; + pbTmp += sizeof(BLOBHEADER); + + // Copy private key algorithm to buffer + *((DWORD *)pbTmp) = PRIVATEKEY_EXPOF1_ALG; + pbTmp += sizeof(ALG_ID); + + // Place the key material in reverse order + for (n = 0; n < keyrawlen; n++) { + pbTmp[n] = keyraw[keyrawlen - n - 1]; + } + + // 3 is for the first reserved byte after the key material + the 2 reserved bytes at the end. + cbRandom = cbSessionBlob - (sizeof(ALG_ID) + sizeof(BLOBHEADER) + (DWORD)keyrawlen + 3); + pbTmp += (keyrawlen + 1); + + // Generate random data for the rest of the buffer + // (except that last two bytes) + if (!CryptGenRandom((*key)->hProv, cbRandom, pbTmp)) { rc = DES_GENERAL_ERROR; goto ERROR_EXIT; } + + for (n = 0; n < cbRandom; n++) { + if (pbTmp[n] == 0) pbTmp[n] = 1; + } + + pbSessionBlob[cbSessionBlob - 2] = 2; + + if (!CryptImportKey((*key)->hProv, pbSessionBlob, cbSessionBlob, hNullKey, CRYPT_EXPORTABLE, &((*key)->hKey))) { rc = DES_GENERAL_ERROR; goto ERROR_EXIT; } + +#else + + const_DES_cblock key_tmp; + size_t cb_keysize = 8; + + + switch (type) { + case DES_TYPE_3DES: + cb_expectedkey = DES_LEN_3DES; + cb_keysize = 8; + break; + default: + rc = DES_INVALID_PARAMETER; + goto ERROR_EXIT; + } + + if (cb_keysize > sizeof(key_tmp)) { rc = DES_MEMORY_ERROR; goto ERROR_EXIT; } + if (!keyraw) { rc = DES_INVALID_PARAMETER; goto ERROR_EXIT; } + if (keyrawlen != cb_expectedkey) { rc = DES_INVALID_PARAMETER; goto ERROR_EXIT; } + if (!key) { rc = DES_INVALID_PARAMETER; goto ERROR_EXIT; } + if (!(*key = (des_key*)malloc(sizeof(des_key)))) { rc = DES_MEMORY_ERROR; goto ERROR_EXIT; } + + memset(*key, 0, sizeof(des_key)); + + memcpy(key_tmp, keyraw, cb_keysize); + DES_set_key_unchecked(&key_tmp, &((*key)->ks1)); + memcpy(key_tmp, keyraw + cb_keysize, cb_keysize); + DES_set_key_unchecked(&key_tmp, &((*key)->ks2)); + memcpy(key_tmp, keyraw + (2 * cb_keysize), cb_keysize); + DES_set_key_unchecked(&key_tmp, &((*key)->ks3)); + +#endif + +EXIT: +#ifdef _WINDOWS + if (pbSessionBlob) { + free(pbSessionBlob); + pbSessionBlob = NULL; + } + + if (hNullKey) { + CryptDestroyKey(hNullKey); + hNullKey = 0; + } +#endif + return rc; + +ERROR_EXIT: + des_destroy_key(*key); + *key = NULL; + goto EXIT; + + +} + +des_rc des_destroy_key(des_key* key) { + if (key) { +#ifdef _WINDOWS + if (key->hKey) { + CryptDestroyKey(key->hKey); + key->hKey = 0; + } + + if (key->hProv) { + CryptReleaseContext(key->hProv, 0); + key->hProv = 0; + } +#endif + free(key); + } + + return DES_OK; +} + +des_rc des_encrypt(des_key* key, const unsigned char* in, const size_t inlen, unsigned char* out, size_t* outlen) { + des_rc rc = DES_OK; + +#ifdef _WINDOWS + unsigned char buf[8] = { 0 }; + size_t buflen = sizeof(buf); +#endif + + if (!key || !outlen || (*outlen < inlen) || !in || !out) { rc = DES_INVALID_PARAMETER; goto EXIT; } + +#ifdef _WINDOWS + + if (!key->hKey) { rc = DES_INVALID_PARAMETER; goto EXIT; } + + memcpy(out, in, inlen); + *outlen = inlen; + + if (!CryptEncrypt(key->hKey, 0, FALSE, 0, out, (DWORD*)&inlen, (DWORD)*outlen)) { fwprintf(stderr, L"GetLastError = %x\n", GetLastError()); rc = DES_GENERAL_ERROR; goto EXIT; } + // reset key usage by encrypting a fake padded block + CryptEncrypt(key->hKey, 0, TRUE, 0, buf, (DWORD*)&buflen, (DWORD)buflen); + + //if (CALG_3DES == key->alg) { + // // truncate the final pad block + // *outlen = inlen - 8; + //} + //else { + // *outlen = inlen; + //} + +#else + + /* openssl returns void */ + DES_ecb3_encrypt(in, out, &(key->ks1), &(key->ks2), &(key->ks3), 1); + +#endif + +EXIT: + return rc; +} + +des_rc des_decrypt(des_key* key, const unsigned char* in, const size_t inlen, unsigned char* out, size_t* outlen) { + des_rc rc = DES_OK; + +#ifdef _WINDOWS + unsigned char buf[8] = { 0 }; + size_t buflen = sizeof(buf); +#endif + + if (!key || !outlen || (*outlen < inlen) || !in || !out) { rc = DES_INVALID_PARAMETER; goto EXIT; } + +#ifdef _WINDOWS + + if (!key->hKey) { rc = DES_INVALID_PARAMETER; goto EXIT; } + + memcpy(out, in, inlen); + *outlen = inlen; + + if (!CryptDecrypt(key->hKey, 0, FALSE, 0, out, (DWORD*)outlen)) { fwprintf(stderr, L"GetLastError = %x\n", GetLastError()); rc = DES_GENERAL_ERROR; goto EXIT; } + // reset key usage by decrypting a fake padded block + CryptDecrypt(key->hKey, 0, TRUE, 0, buf, (DWORD*)&buflen); + +#else + + /* openssl returns void */ + DES_ecb3_encrypt(in, out, &(key->ks1), &(key->ks2), &(key->ks3), 0); + +#endif + +EXIT: + return rc; +} + +// TREV TODO: use openssl's implementation when available +bool yk_des_is_weak_key(const unsigned char *key, const size_t cb_key) { + + /* defined weak keys, borrowed from openssl to be consistent across platforms */ + static const unsigned char weak_keys[][DES_LEN_DES] = { + /* weak keys */ + {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01}, + {0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE,0xFE}, + {0x1F,0x1F,0x1F,0x1F,0x0E,0x0E,0x0E,0x0E}, + {0xE0,0xE0,0xE0,0xE0,0xF1,0xF1,0xF1,0xF1}, + /* semi-weak keys */ + {0x01,0xFE,0x01,0xFE,0x01,0xFE,0x01,0xFE}, + {0xFE,0x01,0xFE,0x01,0xFE,0x01,0xFE,0x01}, + {0x1F,0xE0,0x1F,0xE0,0x0E,0xF1,0x0E,0xF1}, + {0xE0,0x1F,0xE0,0x1F,0xF1,0x0E,0xF1,0x0E}, + {0x01,0xE0,0x01,0xE0,0x01,0xF1,0x01,0xF1}, + {0xE0,0x01,0xE0,0x01,0xF1,0x01,0xF1,0x01}, + {0x1F,0xFE,0x1F,0xFE,0x0E,0xFE,0x0E,0xFE}, + {0xFE,0x1F,0xFE,0x1F,0xFE,0x0E,0xFE,0x0E}, + {0x01,0x1F,0x01,0x1F,0x01,0x0E,0x01,0x0E}, + {0x1F,0x01,0x1F,0x01,0x0E,0x01,0x0E,0x01}, + {0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1,0xFE}, + {0xFE,0xE0,0xFE,0xE0,0xFE,0xF1,0xFE,0xF1} }; + + unsigned char tmp[DES_LEN_3DES] = { 0 }; + int i = 0; + unsigned char c = 0x00; + + if (sizeof(tmp) != cb_key) return true; + + /* set odd parity of key */ + + for (i = 0; i < sizeof(tmp); i++) { + /* count number of set bits in byte, excluding the low-order bit - SWAR method */ + c = key[i] & 0xFE; + + c = (c & 0x55) + ((c >> 1) & 0x55); + c = (c & 0x33) + ((c >> 2) & 0x33); + c = (c & 0x0F) + ((c >> 4) & 0x0F); + + /* if count is even, set low key bit to 1, otherwise 0 */ + tmp[i] = (key[i] & 0xFE) | ((c & 0x01) ? 0x00 : 0x01); + } + + /* check odd parity key against table by DES key block*/ + + for (i = 0; i < sizeof(weak_keys) / sizeof(weak_keys[0]); i++) { + if ((0 == memcmp(weak_keys[i], tmp, DES_LEN_DES)) || + (0 == memcmp(weak_keys[i], tmp + DES_LEN_DES, DES_LEN_DES)) || + (0 == memcmp(weak_keys[i], tmp + 2*DES_LEN_DES, DES_LEN_DES))) { + return true; + } + } + + return false; +} + +prng_rc prng_generate(unsigned char *buffer, const size_t cb_req) { + // TREV TODO: ykpiv.c needs to use this + prng_rc rc = PRNG_OK; + +#ifdef _WINDOWS + HCRYPTPROV hProv = 0; + + if (CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { + if (!CryptGenRandom(hProv, (DWORD)cb_req, buffer)) { + rc = PRNG_GENERAL_ERROR; + } + + CryptReleaseContext(hProv, 0); + } + else { + rc = PRNG_GENERAL_ERROR; + } + +#else + if (-1 == RAND_pseudo_bytes(buffer, cb_req)) { + rc = PRNG_GENERAL_ERROR; + } + +#endif + + return rc; +} + +// TREV TODO: what to do with this? + +#ifdef _WINDOWS +#include +#define WIN32_NO_STATUS +#include +#include +#else +#include +#endif + +pkcs5_rc pkcs5_pbkdf2_sha1(const unsigned char* password, const size_t cb_password, const unsigned char* salt, const size_t cb_salt, unsigned long long iterations, unsigned char* key, const size_t cb_key) { + pkcs5_rc rc = PKCS5_OK; + +#ifdef _WINDOWS + BCRYPT_ALG_HANDLE hAlg = 0; + + /* mingw64 defines the BCryptDeriveKeyPBKDF2 function, but its dll link library doesn't include the export. + ** + ** In case this is needed, we'll need to dynamically load the function: + ** + ** typedef NTSTATUS WINAPI (*PFN_BCryptDeriveKeyPBKDF2) (BCRYPT_ALG_HANDLE hPrf, PUCHAR pbPassword, ULONG cbPassword, PUCHAR pbSalt, ULONG cbSalt, ULONGLONG cIterations, PUCHAR pbDerivedKey, ULONG cbDerivedKey, ULONG dwFlags); + ** HMODULE hBCrypt = LoadLibrary("bcrypt.dll"); + ** PFN_BCryptDeriveKeyPBKDF2 pbkdf2 = GetProcAddress(hBCrypt, "BCryptDeriveKeyPBKDF2"); + */ + + if (STATUS_SUCCESS == BCryptOpenAlgorithmProvider(&hAlg, BCRYPT_SHA1_ALGORITHM, NULL, BCRYPT_ALG_HANDLE_HMAC_FLAG)) { + if (STATUS_SUCCESS != BCryptDeriveKeyPBKDF2(hAlg, (PUCHAR)password, (ULONG)cb_password, (PUCHAR)salt, (ULONG)cb_salt, iterations, key, (ULONG)cb_key, 0)) { + rc = PKCS5_GENERAL_ERROR; + } + + BCryptCloseAlgorithmProvider(hAlg, 0); + } + else { + rc = PKCS5_GENERAL_ERROR; + } + +#else + + /* for some reason openssl always returns 1 for PBKDF2 */ + PKCS5_PBKDF2_HMAC_SHA1((const char*)password, cb_password, salt, cb_salt, iterations, cb_key, key); + +#endif + + return rc; +} diff --git a/lib/internal.h b/lib/internal.h index 411fd39..1244f85 100644 --- a/lib/internal.h +++ b/lib/internal.h @@ -44,12 +44,62 @@ #endif #endif +#ifdef __cplusplus +extern "C" +{ +#endif + +#define DES_TYPE_3DES 1 + +#define DES_LEN_DES 8 +#define DES_LEN_3DES DES_LEN_DES*3 + #define READER_LEN 32 #define MAX_READERS 16 -#define DES_LEN_3DES 8*3 #define CB_MGM_KEY DES_LEN_3DES +// the object size is restricted to the firmware's message buffer size, which +// always contains 0x5C + 1 byte len + 3 byte id + 0x53 + 3 byte len = 9 bytes, +// so while the message buffer == CB_BUF_MAX, the maximum object we can store +// is CB_BUF_MAX - 9 +#define CB_OBJ_MAX_NEO (CB_BUF_MAX_NEO - 9) +#define CB_OBJ_MAX_YK4 (CB_BUF_MAX_YK4 - 9) +#define CB_OBJ_MAX CB_OBJ_MAX_YK4 + +#define CB_BUF_MAX_NEO 2048 +#define CB_BUF_MAX_YK4 3072 +#define CB_BUF_MAX CB_BUF_MAX_YK4 + +#define CB_ATR_MAX 33 + +#define CHREF_ACT_CHANGE_PIN 0 +#define CHREF_ACT_UNBLOCK_PIN 1 +#define CHREF_ACT_CHANGE_PUK 2 + +#define TAG_CERT 0x70 +#define TAG_CERT_COMPRESS 0x71 +#define TAG_CERT_LRC 0xFE +// TREV TODO: other tags here? + +typedef enum { + DES_OK = 0, + DES_INVALID_PARAMETER = -1, + DES_BUFFER_TOO_SMALL = -2, + DES_MEMORY_ERROR = -3, + DES_GENERAL_ERROR = -4 +} des_rc; + +typedef enum { + PKCS5_OK = 0, + PKCS5_GENERAL_ERROR = -1 +} pkcs5_rc; + +typedef enum { + PRNG_OK = 0, + PRNG_GENERAL_ERROR = -1 +} prng_rc; + struct ykpiv_state { SCARDCONTEXT context; SCARDHANDLE card; @@ -72,28 +122,19 @@ union u_APDU { }; typedef union u_APDU APDU; +typedef struct des_key des_key; extern unsigned const char aid[]; -// the object size is restricted to the firmware's message buffer size, which -// always contains 0x5C + 1 byte len + 3 byte id + 0x53 + 3 byte len = 9 bytes, -// so while the message buffer == CB_BUF_MAX, the maximum object we can store -// is CB_BUF_MAX - 9 -#define CB_OBJ_MAX_NEO (CB_BUF_MAX_NEO - 9) -#define CB_OBJ_MAX_YK4 (CB_BUF_MAX_YK4 - 9) -#define CB_OBJ_MAX CB_OBJ_MAX_YK4 +des_rc des_import_key(const int type, const unsigned char* keyraw, const size_t keyrawlen, des_key** key); +des_rc des_destroy_key(des_key* key); +des_rc des_encrypt(des_key* key, const unsigned char* in, const size_t inlen, unsigned char* out, size_t* outlen); +des_rc des_decrypt(des_key* key, const unsigned char* in, const size_t inlen, unsigned char* out, size_t* outlen); +bool yk_des_is_weak_key(const unsigned char *key, const size_t cb_key); +pkcs5_rc pkcs5_pbkdf2_sha1(const unsigned char* password, const size_t cb_password, const unsigned char* salt, const size_t cb_salt, unsigned long long iterations, unsigned char* key, const size_t cb_key); -#define CB_BUF_MAX_NEO 2048 -#define CB_BUF_MAX_YK4 3072 -#define CB_BUF_MAX CB_BUF_MAX_YK4 - -#define CB_ATR_MAX 33 - -#define YKPIV_ATR_NEO_R3 "\x3b\xfc\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x4e\x45\x4f\x72\x33\xe1" -#define YKPIV_ATR_YK4 "\x3b\xf8\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x34\xd4" - -#define CHREF_ACT_CHANGE_PIN 0 -#define CHREF_ACT_UNBLOCK_PIN 1 -#define CHREF_ACT_CHANGE_PUK 2 +#ifdef __cplusplus +} +#endif #endif diff --git a/lib/util.c b/lib/util.c index 6aa5dc8..12e2c03 100644 --- a/lib/util.c +++ b/lib/util.c @@ -33,11 +33,7 @@ #include #include #include - -#include "des.h" -#include -#include -#include +#include #include "internal.h" #include "ykpiv.h" @@ -63,9 +59,6 @@ const uint8_t CCC_TMPL[] = { #define CCC_ID_OFFS 9 #define CB_CCC_ID 14 -#define TAG_CERT 0x70 -#define TAG_CERT_COMPRESS 0x71 -#define TAG_CERT_LRC 0xFE #define TAG_ADMIN 0x80 #define TAG_ADMIN_FLAGS_1 0x81 #define TAG_ADMIN_SALT 0x82 diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 99eaf46..cfa7a96 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -34,8 +34,6 @@ #include #include -#include "des.h" - #include "internal.h" #include "ykpiv.h" @@ -236,6 +234,44 @@ ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state) { return res; } +static ykpiv_rc _connect_internal(ykpiv_state *state, uintptr_t context, uintptr_t card) { + ykpiv_rc res = YKPIV_OK; + + if (NULL == state) { + return YKPIV_GENERIC_ERROR; + } + + // if the context has changed, and the new context is not valid, return an error + if ((context != state->context) && (SCARD_S_SUCCESS != SCardIsValidContext(context))) { + return YKPIV_PCSC_ERROR; + } + + // if card handle has changed, determine if handle is valid (less efficient, but complete) + if ((card != state->card)) { + char reader[CB_BUF_MAX]; + uint32_t reader_len = (uint32_t)sizeof(reader); + uint8_t atr[CB_ATR_MAX]; + uint32_t atr_len = (uint32_t)sizeof(atr); + + // Cannot set the reader len to NULL. Confirmed in OSX 10.10, so we have to retrieve it even though we don't need it. + if (SCARD_S_SUCCESS != SCardStatus(card, reader, &reader_len, NULL, NULL, atr, &atr_len)) { + return YKPIV_PCSC_ERROR; + } + + state->isNEO = (((sizeof(YKPIV_ATR_NEO_R3) - 1) == atr_len) && (0 == memcmp(YKPIV_ATR_NEO_R3, atr, atr_len))); + } + + state->context = context; + state->card = card; + + // transact the connect operation + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + res = _ykpiv_ensure_application_selected(state); + _ykpiv_end_transaction(state); + return res; +} + ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { unsigned long active_protocol; char reader_buf[2048]; @@ -271,26 +307,10 @@ ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { continue; } - // if card handle has changed, determine if handle is valid (less efficient, but complete) - if ((card != state->card)) { - char reader[CB_BUF_MAX]; - uint32_t reader_len = (uint32_t)sizeof(reader); - uint8_t atr[CB_ATR_MAX]; - uint32_t atr_len = (uint32_t)sizeof(atr); - - // Cannot set the reader len to NULL. Confirmed in OSX 10.10, so we have to retrieve it even though we don't need it. - if (SCARD_S_SUCCESS != SCardStatus(card, reader, &reader_len, NULL, NULL, atr, &atr_len)) { - return YKPIV_PCSC_ERROR; - } - - state->isNEO = (((sizeof(YKPIV_ATR_NEO_R3) - 1) == atr_len) && (0 == memcmp(YKPIV_ATR_NEO_R3, atr, atr_len))); + // at this point, card should not equal state->card, to allow _connect_internal() to determine device type + if (!_connect_internal(state, state->context, card)) { + return YKPIV_OK; } - state->card = card; - - if (_ykpiv_select_application(state) != YKPIV_OK) { - continue; - } - return YKPIV_OK; } if(*reader_ptr == '\0') { @@ -298,7 +318,7 @@ ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { fprintf(stderr, "error: no usable reader found.\n"); } SCardReleaseContext(state->context); - state->context = SCARD_E_INVALID_HANDLE; + state->context = (SCARDCONTEXT)-1; return YKPIV_PCSC_ERROR; } @@ -900,7 +920,7 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { if (state->pin == NULL) { return YKPIV_MEMORY_ERROR; } - strcpy(state->pin, pin); + memcpy(state->pin, pin, len + 1); } if (tries) *tries = (sw & 0xf); return YKPIV_OK; @@ -1011,7 +1031,7 @@ ykpiv_rc ykpiv_change_pin(ykpiv_state *state, const char * current_pin, size_t c if (state->pin == NULL) { return YKPIV_MEMORY_ERROR; } - strcpy(state->pin, new_pin); + memcpy(state->pin, new_pin, new_pin_len + 1); } return res; } @@ -1225,3 +1245,39 @@ ykpiv_rc ykpiv_import_private_key(ykpiv_state *state, const unsigned char key, u return YKPIV_OK; } + +// TREV TODO: remove these, fix minidriver + +ykpiv_rc ykpiv_done2(ykpiv_state *state, bool disconnect) { + // TODO: why is this needed? windows unit tests pass without it + if (disconnect) + ykpiv_disconnect(state); + if (state->pin) + _ykpiv_free(state, state->pin); + _ykpiv_free(state, state); + return YKPIV_OK; +} + +ykpiv_rc ykpiv_init2(ykpiv_state **state, int verbose, const ykpiv_allocator *allocator) { + return ykpiv_init_with_allocator(state, verbose, allocator); +} + +ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const uint8_t *pin, const size_t pin_len, int *tries, bool force_select) { + ykpiv_rc res = YKPIV_OK; + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) goto Cleanup; +#if 0 + // TODO when is this needed? windows unit tests pass without it + if (force_select) { + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + } +#endif + res = ykpiv_verify(state, pin, tries); +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_connect2(ykpiv_state *state, uintptr_t context, uintptr_t card) { + return _connect_internal(state, context, card); +} diff --git a/lib/ykpiv.h b/lib/ykpiv.h index 37221ce..9ad8df1 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -33,6 +33,7 @@ #include #include +#include #include @@ -242,6 +243,9 @@ extern "C" // UTIL // +#define YKPIV_ATR_NEO_R3 "\x3b\xfc\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x4e\x45\x4f\x72\x33\xe1" +#define YKPIV_ATR_YK4 "\x3b\xf8\x13\x00\x00\x81\x31\xfe\x15\x59\x75\x62\x69\x6b\x65\x79\x34\xd4" + #define DEVTYPE_UNKNOWN 0x00000000 #define DEVTYPE_NEO 0x4E450000 //"NE" #define DEVTYPE_YK 0x594B0000 //"YK" @@ -448,6 +452,12 @@ extern "C" ykpiv_rc ykpiv_util_block_puk(ykpiv_state *state); + // TREV TODO: remove + ykpiv_rc ykpiv_done2(ykpiv_state *state, bool disconnect); + ykpiv_rc ykpiv_init2(ykpiv_state **state, int verbose, const ykpiv_allocator *allocator); + ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const uint8_t *pin, const size_t pin_len, int *tries, bool force_select); + ykpiv_rc ykpiv_connect2(ykpiv_state *state, uintptr_t context, uintptr_t card); + #ifdef __cplusplus } #endif From 97ecb75dd435069b96853d6705af5b9c644d3f70 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 12 Sep 2017 11:02:08 +0200 Subject: [PATCH 13/57] Cleanup function names. Make PIN cache optional. --- lib/internal.c | 22 ++++++----------- lib/internal.h | 1 + lib/ykpiv.c | 67 ++++++++++++++++++++++++++++---------------------- lib/ykpiv.h | 4 +-- 4 files changed, 49 insertions(+), 45 deletions(-) diff --git a/lib/internal.c b/lib/internal.c index adf7e59..9e6c33b 100644 --- a/lib/internal.c +++ b/lib/internal.c @@ -2,8 +2,14 @@ #ifdef _WINDOWS #include #include +#include +#define WIN32_NO_STATUS +#include #else #include +#include +#include +#include #endif #include @@ -274,7 +280,7 @@ des_rc des_encrypt(des_key* key, const unsigned char* in, const size_t inlen, un #else /* openssl returns void */ - DES_ecb3_encrypt(in, out, &(key->ks1), &(key->ks2), &(key->ks3), 1); + DES_ecb3_encrypt((const_DES_cblock *)in, (DES_cblock*)out, &(key->ks1), &(key->ks2), &(key->ks3), 1); #endif @@ -306,7 +312,7 @@ des_rc des_decrypt(des_key* key, const unsigned char* in, const size_t inlen, un #else /* openssl returns void */ - DES_ecb3_encrypt(in, out, &(key->ks1), &(key->ks2), &(key->ks3), 0); + DES_ecb3_encrypt((const_DES_cblock*)in, (DES_cblock*)out, &(key->ks1), &(key->ks2), &(key->ks3), 0); #endif @@ -372,7 +378,6 @@ bool yk_des_is_weak_key(const unsigned char *key, const size_t cb_key) { } prng_rc prng_generate(unsigned char *buffer, const size_t cb_req) { - // TREV TODO: ykpiv.c needs to use this prng_rc rc = PRNG_OK; #ifdef _WINDOWS @@ -399,17 +404,6 @@ prng_rc prng_generate(unsigned char *buffer, const size_t cb_req) { return rc; } -// TREV TODO: what to do with this? - -#ifdef _WINDOWS -#include -#define WIN32_NO_STATUS -#include -#include -#else -#include -#endif - pkcs5_rc pkcs5_pbkdf2_sha1(const unsigned char* password, const size_t cb_password, const unsigned char* salt, const size_t cb_salt, unsigned long long iterations, unsigned char* key, const size_t cb_key) { pkcs5_rc rc = PKCS5_OK; diff --git a/lib/internal.h b/lib/internal.h index 1244f85..66ab628 100644 --- a/lib/internal.h +++ b/lib/internal.h @@ -132,6 +132,7 @@ des_rc des_encrypt(des_key* key, const unsigned char* in, const size_t inlen, un des_rc des_decrypt(des_key* key, const unsigned char* in, const size_t inlen, unsigned char* out, size_t* outlen); bool yk_des_is_weak_key(const unsigned char *key, const size_t cb_key); pkcs5_rc pkcs5_pbkdf2_sha1(const unsigned char* password, const size_t cb_password, const unsigned char* salt, const size_t cb_salt, unsigned long long iterations, unsigned char* key, const size_t cb_key); +prng_rc prng_generate(unsigned char *buffer, const size_t cb_req); #ifdef __cplusplus } diff --git a/lib/ykpiv.c b/lib/ykpiv.c index cfa7a96..02ab7f6 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -156,7 +156,7 @@ ykpiv_rc ykpiv_init_with_allocator(ykpiv_state **state, int verbose, const ykpiv s->pin = NULL; s->allocator = *allocator; s->verbose = verbose; - s->context = SCARD_E_INVALID_HANDLE; // TREV TODO -1 on Windows + s->context = SCARD_E_INVALID_HANDLE; *state = s; return YKPIV_OK; } @@ -167,8 +167,7 @@ ykpiv_rc ykpiv_init(ykpiv_state **state, int verbose) { ykpiv_rc ykpiv_done(ykpiv_state *state) { ykpiv_disconnect(state); - if (state->pin) - _ykpiv_free(state, state->pin); + _cache_pin(state, NULL, 0); _ykpiv_free(state, state); return YKPIV_OK; } @@ -234,7 +233,7 @@ ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state) { return res; } -static ykpiv_rc _connect_internal(ykpiv_state *state, uintptr_t context, uintptr_t card) { +static ykpiv_rc _connect_internal(ykpiv_state *state, uint64_t context, uint64_t card) { ykpiv_rc res = YKPIV_OK; if (NULL == state) { @@ -272,7 +271,12 @@ static ykpiv_rc _connect_internal(ykpiv_state *state, uintptr_t context, uintptr return res; } +ykpiv_rc ykpiv_connect_with_card(ykpiv_state *state, uint64_t context, uint64_t card) { + return _connect_internal(state, context, card); +} + ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { + // TREV TODO: use _connect_internal unsigned long active_protocol; char reader_buf[2048]; size_t num_readers = sizeof(reader_buf); @@ -330,7 +334,6 @@ static ykpiv_rc reconnect(ykpiv_state *state) { long rc; ykpiv_rc res; int tries; - if(state->verbose) { fprintf(stderr, "trying to reconnect to current reader.\n"); } @@ -884,6 +887,29 @@ ykpiv_rc ykpiv_get_version(ykpiv_state *state, char *version, size_t len) { } } +ykpiv_rc _cache_pin(ykpiv_state *state, const char *pin, size_t len) { +#ifdef DISABLE_PIN_CACHE + // Some embedded applications of this library may not want to keep the PIN + // data in RAM for security reasons. + return YKPIV_OK; +#else + if (!state) + return YKPIV_ARGUMENT_ERROR; + if (state->pin) { + _ykpiv_free(state, state->pin); + state->pin = NULL; + } + if (pin && len > 0) { + state->pin = _ykpiv_alloc(state, len * sizeof(char) + 1); + if (state->pin == NULL) { + return YKPIV_MEMORY_ERROR; + } + memcpy(state->pin, pin, len + 1); + } + return YKPIV_OK; +#endif +} + ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { // TREV TODO: pin len? APDU apdu; @@ -914,14 +940,9 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { if((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { return res; } else if(sw == SW_SUCCESS) { - if (pin) { - _ykpiv_free(state, state->pin); - state->pin = _ykpiv_alloc(state, len * sizeof(char) + 1); - if (state->pin == NULL) { - return YKPIV_MEMORY_ERROR; - } - memcpy(state->pin, pin, len + 1); - } + // Intentionally ignore errors. If the PIN fails to save, it will only + // be a problem if a reconnect is attempted. Failure deferred until then. + _cache_pin(state, pin, len + 1); if (tries) *tries = (sw & 0xf); return YKPIV_OK; } else if((sw >> 8) == 0x63) { @@ -1026,12 +1047,9 @@ static ykpiv_rc change_pin_internal(ykpiv_state *state, int action, const char * ykpiv_rc ykpiv_change_pin(ykpiv_state *state, const char * current_pin, size_t current_pin_len, const char * new_pin, size_t new_pin_len, int *tries) { ykpiv_rc res = change_pin_internal(state, CHREF_ACT_CHANGE_PIN, current_pin, current_pin_len, new_pin, new_pin_len, tries); if (res == YKPIV_OK && new_pin != NULL) { - _ykpiv_free(state, state->pin); - state->pin = _ykpiv_alloc(state, new_pin_len * sizeof(char) + 1); - if (state->pin == NULL) { - return YKPIV_MEMORY_ERROR; - } - memcpy(state->pin, new_pin, new_pin_len + 1); + // Intentionally ignore errors. If the PIN fails to save, it will only + // be a problem if a reconnect is attempted. Failure deferred until then. + _cache_pin(state, new_pin, new_pin_len + 1); } return res; } @@ -1252,16 +1270,11 @@ ykpiv_rc ykpiv_done2(ykpiv_state *state, bool disconnect) { // TODO: why is this needed? windows unit tests pass without it if (disconnect) ykpiv_disconnect(state); - if (state->pin) - _ykpiv_free(state, state->pin); + _cache_pin(state, NULL, 0); _ykpiv_free(state, state); return YKPIV_OK; } -ykpiv_rc ykpiv_init2(ykpiv_state **state, int verbose, const ykpiv_allocator *allocator) { - return ykpiv_init_with_allocator(state, verbose, allocator); -} - ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const uint8_t *pin, const size_t pin_len, int *tries, bool force_select) { ykpiv_rc res = YKPIV_OK; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) goto Cleanup; @@ -1277,7 +1290,3 @@ Cleanup: _ykpiv_end_transaction(state); return res; } - -ykpiv_rc ykpiv_connect2(ykpiv_state *state, uintptr_t context, uintptr_t card) { - return _connect_internal(state, context, card); -} diff --git a/lib/ykpiv.h b/lib/ykpiv.h index 9ad8df1..b0f3081 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -452,11 +452,11 @@ extern "C" ykpiv_rc ykpiv_util_block_puk(ykpiv_state *state); + ykpiv_rc ykpiv_connect_with_card(ykpiv_state *state, uint64_t context, uint64_t card); + // TREV TODO: remove ykpiv_rc ykpiv_done2(ykpiv_state *state, bool disconnect); - ykpiv_rc ykpiv_init2(ykpiv_state **state, int verbose, const ykpiv_allocator *allocator); ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const uint8_t *pin, const size_t pin_len, int *tries, bool force_select); - ykpiv_rc ykpiv_connect2(ykpiv_state *state, uintptr_t context, uintptr_t card); #ifdef __cplusplus } From dfd2a9ef9217183adffa6db615a313bf686e05d3 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 12 Sep 2017 12:52:55 +0200 Subject: [PATCH 14/57] Cleanup compiler warnings, and switch to cross-platform data types --- lib/internal.c | 2 +- lib/internal.h | 8 ++++++-- lib/util.c | 9 +++------ lib/ykpiv.c | 34 ++++++++++++++++++---------------- lib/ykpiv.h | 2 +- 5 files changed, 29 insertions(+), 26 deletions(-) diff --git a/lib/internal.c b/lib/internal.c index 9e6c33b..30e5601 100644 --- a/lib/internal.c +++ b/lib/internal.c @@ -377,7 +377,7 @@ bool yk_des_is_weak_key(const unsigned char *key, const size_t cb_key) { return false; } -prng_rc prng_generate(unsigned char *buffer, const size_t cb_req) { +prng_rc _ykpiv_prng_generate(unsigned char *buffer, const size_t cb_req) { prng_rc rc = PRNG_OK; #ifdef _WINDOWS diff --git a/lib/internal.h b/lib/internal.h index 66ab628..f6ade36 100644 --- a/lib/internal.h +++ b/lib/internal.h @@ -130,9 +130,13 @@ des_rc des_import_key(const int type, const unsigned char* keyraw, const size_t des_rc des_destroy_key(des_key* key); des_rc des_encrypt(des_key* key, const unsigned char* in, const size_t inlen, unsigned char* out, size_t* outlen); des_rc des_decrypt(des_key* key, const unsigned char* in, const size_t inlen, unsigned char* out, size_t* outlen); -bool yk_des_is_weak_key(const unsigned char *key, const size_t cb_key); pkcs5_rc pkcs5_pbkdf2_sha1(const unsigned char* password, const size_t cb_password, const unsigned char* salt, const size_t cb_salt, unsigned long long iterations, unsigned char* key, const size_t cb_key); -prng_rc prng_generate(unsigned char *buffer, const size_t cb_req); +bool yk_des_is_weak_key(const unsigned char *key, const size_t cb_key); + +prng_rc _ykpiv_prng_generate(unsigned char *buffer, const size_t cb_req); +ykpiv_rc _ykpiv_begin_transaction(ykpiv_state *state); +ykpiv_rc _ykpiv_end_transaction(ykpiv_state *state); +ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state); #ifdef __cplusplus } diff --git a/lib/util.c b/lib/util.c index 12e2c03..91309cf 100644 --- a/lib/util.c +++ b/lib/util.c @@ -117,9 +117,6 @@ void* _ykpiv_realloc(ykpiv_state *state, void *address, size_t size); void _ykpiv_free(ykpiv_state *state, void *data); int _ykpiv_set_length(unsigned char *buffer, size_t length); int _ykpiv_get_length(const unsigned char *buffer, size_t *len); -ykpiv_rc _ykpiv_begin_transaction(ykpiv_state *state); -ykpiv_rc _ykpiv_end_transaction(ykpiv_state *state); -ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state); static ykpiv_rc _read_metadata(ykpiv_state *state, uint8_t tag, uint8_t* data, size_t* pcb_data); static ykpiv_rc _write_metadata(ykpiv_state *state, uint8_t tag, uint8_t *data, size_t cb_data); @@ -165,7 +162,7 @@ ykpiv_rc ykpiv_util_set_cardid(ykpiv_state *state, const ykpiv_cardid *cardid) { if (!state) return YKPIV_GENERIC_ERROR; if (!cardid) { - if (PRNG_OK != prng_generate(id, sizeof(id))) { + if (PRNG_OK != _ykpiv_prng_generate(id, sizeof(id))) { return YKPIV_RANDOMNESS_ERROR; } } @@ -384,7 +381,7 @@ ykpiv_rc ykpiv_util_block_puk(ykpiv_state *state) { if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; while (tries != 0) { - if (YKPIV_OK == (res = ykpiv_change_puk(state, puk, sizeof(puk), puk, sizeof(puk), &tries))) { + if (YKPIV_OK == (res = ykpiv_change_puk(state, (const char*)puk, sizeof(puk), (const char*)puk, sizeof(puk), &tries))) { /* did we accidentally choose the correct PUK?, change our puk and try again */ puk[0]++; } @@ -1125,7 +1122,7 @@ ykpiv_rc ykpiv_util_set_protected_mgm(ykpiv_state *state, ykpiv_mgm *mgm) { do { if (fGenerate) { /* generate a new mgm key */ - if (PRNG_OK != (prngrc = prng_generate(mgm_key, sizeof(mgm_key)))) { + if (PRNG_OK != (prngrc = _ykpiv_prng_generate(mgm_key, sizeof(mgm_key)))) { if (state->verbose) fprintf(stderr, "could not set generate new mgm, err = %d\n", prngrc); res = YKPIV_RANDOMNESS_ERROR; goto Cleanup; diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 02ab7f6..f29898e 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -39,8 +39,10 @@ #define YKPIV_MGM_DEFAULT "\x01\x02\x03\x04\x05\x06\x07\x08\x01\x02\x03\x04\x05\x06\x07\x08\x01\x02\x03\x04\x05\x06\x07\x08" +static ykpiv_rc _cache_pin(ykpiv_state *state, const char *pin, size_t len); + static ykpiv_rc _send_data(ykpiv_state *state, APDU *apdu, - unsigned char *data, unsigned long *recv_len, int *sw); + unsigned char *data, uint32_t *recv_len, int *sw); unsigned const char aid[] = { 0xa0, 0x00, 0x00, 0x03, 0x08 @@ -189,7 +191,7 @@ ykpiv_rc ykpiv_disconnect(ykpiv_state *state) { ykpiv_rc _ykpiv_select_application(ykpiv_state *state) { APDU apdu; unsigned char data[0xff]; - unsigned long recv_len = sizeof(data); + uint32_t recv_len = sizeof(data); int sw; ykpiv_rc res; @@ -277,7 +279,7 @@ ykpiv_rc ykpiv_connect_with_card(ykpiv_state *state, uint64_t context, uint64_t ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { // TREV TODO: use _connect_internal - unsigned long active_protocol; + uint32_t active_protocol; char reader_buf[2048]; size_t num_readers = sizeof(reader_buf); long rc; @@ -330,7 +332,7 @@ ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { } static ykpiv_rc reconnect(ykpiv_state *state) { - unsigned long active_protocol; + uint32_t active_protocol; long rc; ykpiv_rc res; int tries; @@ -355,7 +357,7 @@ static ykpiv_rc reconnect(ykpiv_state *state) { } ykpiv_rc ykpiv_list_readers(ykpiv_state *state, char *readers, size_t *len) { - unsigned long num_readers = 0; + uint32_t num_readers = 0; long rc; if(SCardIsValidContext(state->context) != SCARD_S_SUCCESS) { @@ -442,7 +444,7 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, do { size_t this_size = 0xff; unsigned char data[261]; - unsigned long recv_len = sizeof(data); + uint32_t recv_len = sizeof(data); APDU apdu; memset(apdu.raw, 0, sizeof(apdu.raw)); @@ -481,7 +483,7 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, while(*sw >> 8 == 0x61) { APDU apdu; unsigned char data[261]; - unsigned long recv_len = sizeof(data); + uint32_t recv_len = sizeof(data); if(state->verbose > 2) { fprintf(stderr, "The card indicates there is %d bytes more data for us.\n", *sw & 0xff); @@ -509,7 +511,7 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, } static ykpiv_rc _send_data(ykpiv_state *state, APDU *apdu, - unsigned char *data, unsigned long *recv_len, int *sw) { + unsigned char *data, uint32_t *recv_len, int *sw) { long rc; unsigned int send_len = (unsigned int)apdu->st.lc + 5; @@ -543,7 +545,7 @@ ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { APDU apdu; unsigned char data[261]; unsigned char challenge[8]; - unsigned long recv_len = sizeof(data); + uint32_t recv_len = sizeof(data); int sw; ykpiv_rc res; des_key* mgm_key = NULL; @@ -553,7 +555,7 @@ ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { if (NULL == key) { /* use the derived mgm key to authenticate, if it hasn't been derived, use default */ - key = YKPIV_MGM_DEFAULT; + key = (unsigned const char*)YKPIV_MGM_DEFAULT; } /* set up our key */ @@ -602,7 +604,7 @@ ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { dataptr += 8; *dataptr++ = 0x81; *dataptr++ = 8; - if (PRNG_GENERAL_ERROR == prng_generate(dataptr, 8)) { + if (PRNG_GENERAL_ERROR == _ykpiv_prng_generate(dataptr, 8)) { if (state->verbose) { fprintf(stderr, "Failed getting randomness for authentication.\n"); } @@ -650,7 +652,7 @@ ykpiv_rc ykpiv_set_mgmkey(ykpiv_state *state, const unsigned char *new_key) { ykpiv_rc ykpiv_set_mgmkey2(ykpiv_state *state, const unsigned char *new_key, const unsigned char touch) { APDU apdu; unsigned char data[261]; - unsigned long recv_len = sizeof(data); + uint32_t recv_len = sizeof(data); int sw; ykpiv_rc res = YKPIV_OK; @@ -868,7 +870,7 @@ Cleanup: ykpiv_rc ykpiv_get_version(ykpiv_state *state, char *version, size_t len) { APDU apdu; unsigned char data[261]; - unsigned long recv_len = sizeof(data); + uint32_t recv_len = sizeof(data); int sw; ykpiv_rc res; @@ -887,7 +889,7 @@ ykpiv_rc ykpiv_get_version(ykpiv_state *state, char *version, size_t len) { } } -ykpiv_rc _cache_pin(ykpiv_state *state, const char *pin, size_t len) { +static ykpiv_rc _cache_pin(ykpiv_state *state, const char *pin, size_t len) { #ifdef DISABLE_PIN_CACHE // Some embedded applications of this library may not want to keep the PIN // data in RAM for security reasons. @@ -914,7 +916,7 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { // TREV TODO: pin len? APDU apdu; unsigned char data[261]; - unsigned long recv_len = sizeof(data); + uint32_t recv_len = sizeof(data); int sw; size_t len = 0; ykpiv_rc res; @@ -1275,7 +1277,7 @@ ykpiv_rc ykpiv_done2(ykpiv_state *state, bool disconnect) { return YKPIV_OK; } -ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const uint8_t *pin, const size_t pin_len, int *tries, bool force_select) { +ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const char *pin, const size_t pin_len, int *tries, bool force_select) { ykpiv_rc res = YKPIV_OK; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) goto Cleanup; #if 0 diff --git a/lib/ykpiv.h b/lib/ykpiv.h index b0f3081..637f655 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -456,7 +456,7 @@ extern "C" // TREV TODO: remove ykpiv_rc ykpiv_done2(ykpiv_state *state, bool disconnect); - ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const uint8_t *pin, const size_t pin_len, int *tries, bool force_select); + ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const char *pin, const size_t pin_len, int *tries, bool force_select); #ifdef __cplusplus } From 48c2b8e99c4147672ef1366320ce319178a5faa7 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 12 Sep 2017 12:57:47 +0200 Subject: [PATCH 15/57] Move shared functionality from util.c to internal.h --- lib/internal.h | 54 ++++++++++++++++++++++++++++++++++++++++- lib/util.c | 66 +++++--------------------------------------------- lib/ykpiv.c | 1 - 3 files changed, 59 insertions(+), 62 deletions(-) diff --git a/lib/internal.h b/lib/internal.h index f6ade36..1efb014 100644 --- a/lib/internal.h +++ b/lib/internal.h @@ -73,6 +73,8 @@ extern "C" #define CB_ATR_MAX 33 +#define CB_CARDID 16 + #define CHREF_ACT_CHANGE_PIN 0 #define CHREF_ACT_UNBLOCK_PIN 1 #define CHREF_ACT_CHANGE_PUK 2 @@ -80,7 +82,51 @@ extern "C" #define TAG_CERT 0x70 #define TAG_CERT_COMPRESS 0x71 #define TAG_CERT_LRC 0xFE -// TREV TODO: other tags here? +#define TAG_ADMIN 0x80 +#define TAG_ADMIN_FLAGS_1 0x81 +#define TAG_ADMIN_SALT 0x82 +#define TAG_ADMIN_TIMESTAMP 0x83 +#define TAG_PROTECTED 0x88 +#define TAG_PROTECTED_FLAGS_1 0x81 +#define TAG_PROTECTED_MGM 0x89 +#define TAG_MSCMAP 0x81 +#define TAG_MSROOTS_END 0x82 +#define TAG_MSROOTS_MID 0x83 + +#define TAG_RSA_MODULUS 0x81 +#define TAG_RSA_EXP 0x82 +#define TAG_ECC_POINT 0x86 + + +#define CCC_ID_OFFS 9 +#define CB_CCC_ID 14 + +#define CB_ECC_POINTP256 65 +#define CB_ECC_POINTP384 97 + +#define YKPIV_OBJ_ADMIN_DATA 0x5fff00 +#define YKPIV_OBJ_ATTESTATION 0x5fff01 +#define YKPIV_OBJ_MSCMAP 0x5fff10 +#define YKPIV_OBJ_MSROOTS1 0x5fff11 +#define YKPIV_OBJ_MSROOTS2 0x5fff12 +#define YKPIV_OBJ_MSROOTS3 0x5fff13 +#define YKPIV_OBJ_MSROOTS4 0x5fff14 +#define YKPIV_OBJ_MSROOTS5 0x5fff15 + +#define ADMIN_FLAGS_1_PUK_BLOCKED 0x01 +#define ADMIN_FLAGS_1_PROTECTED_MGM 0x02 + +#define CB_ADMIN_SALT 16 +#define CB_ADMIN_TIMESTAMP 4 + +#define ITER_MGM_PBKDF2 10000 + +#define PROTECTED_FLAGS_1_PUK_NOBLOCK 0x01 + +#define CB_OBJ_TAG_MIN 2 // 1 byte tag + 1 byte len +#define CB_OBJ_TAG_MAX (CB_OBJ_TAG_MIN + 2) // 1 byte tag + 3 bytes len + +#define member_size(type, member) sizeof(((type*)0)->member) typedef enum { DES_OK = 0, @@ -137,6 +183,12 @@ prng_rc _ykpiv_prng_generate(unsigned char *buffer, const size_t cb_req); ykpiv_rc _ykpiv_begin_transaction(ykpiv_state *state); ykpiv_rc _ykpiv_end_transaction(ykpiv_state *state); ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state); +int _ykpiv_set_length(unsigned char *buffer, size_t length); +int _ykpiv_get_length(const unsigned char *buffer, size_t *len); + +void* _ykpiv_alloc(ykpiv_state *state, size_t size); +void* _ykpiv_realloc(ykpiv_state *state, void *address, size_t size); +void _ykpiv_free(ykpiv_state *state, void *data); #ifdef __cplusplus } diff --git a/lib/util.c b/lib/util.c index 91309cf..f69e146 100644 --- a/lib/util.c +++ b/lib/util.c @@ -38,6 +38,8 @@ #include "internal.h" #include "ykpiv.h" +#define MAX(a,b) (a) > (b) ? (a) : (b) +#define MIN(a,b) (a) < (b) ? (a) : (b) const uint8_t CHUID_TMPL[] = { 0x30, 0x19, 0xd4, 0xe7, 0x39, 0xda, 0x73, 0x9c, 0xed, 0x39, 0xce, 0x73, 0x9d, @@ -47,7 +49,6 @@ const uint8_t CHUID_TMPL[] = { 0x31, 0x30, 0x31, 0x3e, 0x00, 0xfe, 0x00, }; #define CHUID_GUID_OFFS 29 -#define CB_CARDID 16 const uint8_t CCC_TMPL[] = { 0xf0, 0x15, 0xa0, 0x00, 0x00, 0x01, 0x16, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, @@ -56,73 +57,18 @@ const uint8_t CCC_TMPL[] = { 0xf7, 0x00, 0xfa, 0x00, 0xfb, 0x00, 0xfc, 0x00, 0xfd, 0x00, 0xfe, 0x00 }; -#define CCC_ID_OFFS 9 -#define CB_CCC_ID 14 - -#define TAG_ADMIN 0x80 -#define TAG_ADMIN_FLAGS_1 0x81 -#define TAG_ADMIN_SALT 0x82 -#define TAG_ADMIN_TIMESTAMP 0x83 -#define TAG_PROTECTED 0x88 -#define TAG_PROTECTED_FLAGS_1 0x81 -#define TAG_PROTECTED_MGM 0x89 -#define TAG_MSCMAP 0x81 -#define TAG_MSROOTS_END 0x82 -#define TAG_MSROOTS_MID 0x83 - -#define TAG_RSA_MODULUS 0x81 -#define TAG_RSA_EXP 0x82 -#define TAG_ECC_POINT 0x86 - -#define CB_ECC_POINTP256 65 -#define CB_ECC_POINTP384 97 - - -#define YKPIV_OBJ_ADMIN_DATA 0x5fff00 -#define YKPIV_OBJ_ATTESTATION 0x5fff01 -#define YKPIV_OBJ_MSCMAP 0x5fff10 -#define YKPIV_OBJ_MSROOTS1 0x5fff11 -#define YKPIV_OBJ_MSROOTS2 0x5fff12 -#define YKPIV_OBJ_MSROOTS3 0x5fff13 -#define YKPIV_OBJ_MSROOTS4 0x5fff14 -#define YKPIV_OBJ_MSROOTS5 0x5fff15 - -#define ADMIN_FLAGS_1_PUK_BLOCKED 0x01 -#define ADMIN_FLAGS_1_PROTECTED_MGM 0x02 - -#define CB_ADMIN_SALT 16 -#define CB_ADMIN_TIMESTAMP 4 - -#define ITER_MGM_PBKDF2 10000 - -#define PROTECTED_FLAGS_1_PUK_NOBLOCK 0x01 - -#define CB_OBJ_TAG_MIN 2 // 1 byte tag + 1 byte len -#define CB_OBJ_TAG_MAX (CB_OBJ_TAG_MIN + 2) // 1 byte tag + 3 bytes len - -#define member_size(type, member) sizeof(((type*)0)->member) - static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf, size_t *buf_len); static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len); -static size_t _obj_size_max(ykpiv_state *state) { - return (state && state->isNEO) ? CB_OBJ_MAX_NEO : CB_OBJ_MAX; -} - -#define MAX(a,b) (a) > (b) ? (a) : (b) -#define MIN(a,b) (a) < (b) ? (a) : (b) - -void* _ykpiv_alloc(ykpiv_state *state, size_t size); -void* _ykpiv_realloc(ykpiv_state *state, void *address, size_t size); -void _ykpiv_free(ykpiv_state *state, void *data); -int _ykpiv_set_length(unsigned char *buffer, size_t length); -int _ykpiv_get_length(const unsigned char *buffer, size_t *len); - static ykpiv_rc _read_metadata(ykpiv_state *state, uint8_t tag, uint8_t* data, size_t* pcb_data); static ykpiv_rc _write_metadata(ykpiv_state *state, uint8_t tag, uint8_t *data, size_t cb_data); static ykpiv_rc _get_metadata_item(uint8_t *data, size_t cb_data, uint8_t tag, uint8_t **pp_item, size_t *pcb_item); static ykpiv_rc _set_metadata_item(uint8_t *data, size_t *pcb_data, size_t cb_data_max, uint8_t tag, uint8_t *p_item, size_t cb_item); +static size_t _obj_size_max(ykpiv_state *state) { + return (state && state->isNEO) ? CB_OBJ_MAX_NEO : CB_OBJ_MAX; +} + /* ** YKPIV Utility API - aggregate functions and slightly nicer interface */ diff --git a/lib/ykpiv.c b/lib/ykpiv.c index f29898e..3d82c7d 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -278,7 +278,6 @@ ykpiv_rc ykpiv_connect_with_card(ykpiv_state *state, uint64_t context, uint64_t } ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { - // TREV TODO: use _connect_internal uint32_t active_protocol; char reader_buf[2048]; size_t num_readers = sizeof(reader_buf); From 12f35b88847203e8dff56eb211017a30ddc7f58d Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 12 Sep 2017 15:20:56 +0200 Subject: [PATCH 16/57] yubico-piv-tool: use util function for key generation --- tool/yubico-piv-tool.c | 142 +++++++++++++---------------------------- 1 file changed, 45 insertions(+), 97 deletions(-) diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index 757e1c4..700eaa1 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -119,20 +119,20 @@ static bool generate_key(ykpiv_state *state, const char *slot, enum enum_algorithm algorithm, const char *output_file_name, enum enum_key_format key_format, enum enum_pin_policy pin_policy, enum enum_touch_policy touch_policy) { - unsigned char in_data[11]; - unsigned char *in_ptr = in_data; - unsigned char data[1024]; - unsigned char templ[] = {0, YKPIV_INS_GENERATE_ASYMMETRIC, 0, 0}; - unsigned long recv_len = sizeof(data); - int sw; int key = 0; - FILE *output_file = NULL; bool ret = false; + ykpiv_rc res; + FILE *output_file = NULL; EVP_PKEY *public_key = NULL; RSA *rsa = NULL; - BIGNUM *bignum_n = NULL; - BIGNUM *bignum_e = NULL; EC_KEY *eckey = NULL; + EC_POINT *ecpoint = NULL; + uint8_t *mod = NULL; + uint8_t *exp = NULL; + uint8_t *point = NULL; + size_t mod_len = 0; + size_t exp_len = 0; + size_t point_len = 0; EC_POINT *point = NULL; char version[7]; @@ -152,130 +152,69 @@ static bool generate_key(ykpiv_state *state, const char *slot, } sscanf(slot, "%2x", &key); - templ[3] = key; output_file = open_file(output_file_name, OUTPUT); if(!output_file) { return false; } - *in_ptr++ = 0xac; - *in_ptr++ = 3; - *in_ptr++ = YKPIV_ALGO_TAG; - *in_ptr++ = 1; - *in_ptr++ = get_piv_algorithm(algorithm); - if(in_data[4] == 0) { - fprintf(stderr, "Unexpected algorithm.\n"); - goto generate_out; - } - if(pin_policy != pin_policy__NULL) { - in_data[1] += 3; - *in_ptr++ = YKPIV_PINPOLICY_TAG; - *in_ptr++ = 1; - *in_ptr++ = get_pin_policy(pin_policy); - } - if(touch_policy != touch_policy__NULL) { - in_data[1] += 3; - *in_ptr++ = YKPIV_TOUCHPOLICY_TAG; - *in_ptr++ = 1; - *in_ptr++ = get_touch_policy(touch_policy); - } - if(ykpiv_transfer_data(state, templ, in_data, in_ptr - in_data, data, - &recv_len, &sw) != YKPIV_OK) { - fprintf(stderr, "Failed to communicate.\n"); - goto generate_out; - } else if(sw != SW_SUCCESS) { - fprintf(stderr, "Failed to generate new key ("); - if(sw == SW_ERR_INCORRECT_SLOT) { - fprintf(stderr, "slot not supported?)\n"); - } else if(sw == SW_ERR_INCORRECT_PARAM) { - if(pin_policy != pin_policy__NULL) { - fprintf(stderr, "pin policy not supported?)\n"); - } else if(touch_policy != touch_policy__NULL) { - fprintf(stderr, "touch policy not supported?)\n"); - } else { - fprintf(stderr, "algorithm not supported?)\n"); - } - } else { - fprintf(stderr, "error %x)\n", sw); - } + res = ykpiv_util_generate_key(state, + (uint8_t)(key & 0xFF), + get_piv_algorithm(algorithm), + get_pin_policy(pin_policy), + get_touch_policy(touch_policy), + &mod, + &mod_len, + &exp, + &exp_len, + &point, + &point_len); + if (res != YKPIV_OK) { + fprintf(stderr, "Key generation failed.\n"); goto generate_out; } if(key_format == key_format_arg_PEM) { public_key = EVP_PKEY_new(); if(algorithm == algorithm_arg_RSA1024 || algorithm == algorithm_arg_RSA2048) { - unsigned char *data_ptr = data + 5; - int len = 0; rsa = RSA_new(); - - if(*data_ptr != 0x81) { - fprintf(stderr, "Failed to parse public key structure.\n"); - goto generate_out; - } - data_ptr++; - data_ptr += get_length(data_ptr, &len); - bignum_n = BN_bin2bn(data_ptr, len, NULL); - if(bignum_n == NULL) { + rsa->n = BN_bin2bn(mod, mod_len, NULL); + if (rsa->n == NULL) { fprintf(stderr, "Failed to parse public key modulus.\n"); goto generate_out; } - data_ptr += len; - - if(*data_ptr != 0x82) { - fprintf(stderr, "Failed to parse public key structure (2).\n"); - goto generate_out; - } - data_ptr++; - data_ptr += get_length(data_ptr, &len); - bignum_e = BN_bin2bn(data_ptr, len, NULL); - if(bignum_e == NULL) { + rsa->e = BN_bin2bn(exp, exp_len, NULL); + if(rsa->e == NULL) { fprintf(stderr, "Failed to parse public key exponent.\n"); goto generate_out; } - - rsa->n = bignum_n; - rsa->e = bignum_e; EVP_PKEY_set1_RSA(public_key, rsa); } else if(algorithm == algorithm_arg_ECCP256 || algorithm == algorithm_arg_ECCP384) { EC_GROUP *group; - unsigned char *data_ptr = data + 3; int nid; - size_t len; if(algorithm == algorithm_arg_ECCP256) { nid = NID_X9_62_prime256v1; - len = 65; } else { nid = NID_secp384r1; - len = 97; } - eckey = EC_KEY_new(); group = EC_GROUP_new_by_curve_name(nid); EC_GROUP_set_asn1_flag(group, nid); EC_KEY_set_group(eckey, group); - point = EC_POINT_new(group); - if(*data_ptr++ != 0x86) { - fprintf(stderr, "Failed to parse public key structure.\n"); - goto generate_out; - } - if(*data_ptr++ != len) { /* the curve point should always be 65 bytes */ - fprintf(stderr, "Unexpected length.\n"); - goto generate_out; - } - if(!EC_POINT_oct2point(group, point, data_ptr, len, NULL)) { + ecpoint = EC_POINT_new(group); + + if(!EC_POINT_oct2point(group, ecpoint, point, point_len, NULL)) { fprintf(stderr, "Failed to load public point.\n"); goto generate_out; } - if(!EC_KEY_set_public_key(eckey, point)) { + if(!EC_KEY_set_public_key(eckey, ecpoint)) { fprintf(stderr, "Failed to set the public key.\n"); goto generate_out; } EVP_PKEY_set1_EC_KEY(public_key, eckey); } else { fprintf(stderr, "Wrong algorithm.\n"); - goto generate_out; } PEM_write_PUBKEY(output_file, public_key); ret = true; @@ -285,21 +224,30 @@ static bool generate_key(ykpiv_state *state, const char *slot, } generate_out: - if(output_file != stdout) { + if (output_file != stdout) { fclose(output_file); } - if(point) { - EC_POINT_free(point); + if (ecpoint) { + EC_POINT_free(ecpoint); } - if(eckey) { + if (eckey) { EC_KEY_free(eckey); } - if(rsa) { + if (rsa) { RSA_free(rsa); } - if(public_key) { + if (public_key) { EVP_PKEY_free(public_key); } + if (point) { + ykpiv_util_free(state, point); + } + if (mod) { + ykpiv_util_free(state, mod); + } + if (exp) { + ykpiv_util_free(state, exp); + } return ret; } From ec8e2786e634da3c8559870e0df118a017723929 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 12 Sep 2017 15:53:10 +0200 Subject: [PATCH 17/57] yubico-piv-tool: use ykpiv_util_reset() --- tool/yubico-piv-tool.c | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index 700eaa1..2f3ca28 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -253,18 +253,7 @@ generate_out: } static bool reset(ykpiv_state *state) { - unsigned char templ[] = {0, YKPIV_INS_RESET, 0, 0}; - unsigned char data[0xff]; - unsigned long recv_len = sizeof(data); - int sw; - - /* note: the reset function is only available when both pins are blocked. */ - if(ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw) != YKPIV_OK) { - return false; - } else if(sw == SW_SUCCESS) { - return true; - } - return false; + return ykpiv_util_reset(state) == YKPIV_OK; } static bool set_pin_retries(ykpiv_state *state, int pin_retries, int puk_retries, int verbose) { @@ -2000,7 +1989,7 @@ int main(int argc, char *argv[]) { break; case action_arg_reset: if(reset(state) == false) { - fprintf(stderr, "Reset failed, are pincodes blocked?\n"); + fprintf(stderr, "Reset failed, are pincodes blocked?\n"); ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully reset the application.\n"); From 8135a5520089ad71e01e33d1688ab16b1bb2c121 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Wed, 13 Sep 2017 15:55:55 +0200 Subject: [PATCH 18/57] yubico-piv-tool: Switch to ykpiv_set_pin_retries() --- lib/tests/util.c | 2 +- lib/ykpiv.c | 18 +++++++++++++----- lib/ykpiv.h | 5 ++++- tool/yubico-piv-tool.c | 22 ++++++---------------- 4 files changed, 24 insertions(+), 23 deletions(-) diff --git a/lib/tests/util.c b/lib/tests/util.c index 6c19f38..efbce40 100644 --- a/lib/tests/util.c +++ b/lib/tests/util.c @@ -589,7 +589,7 @@ START_TEST(test_reset) { test_authenticate(0); res = ykpiv_verify(g_state, "123456", NULL); ck_assert_int_eq(res, YKPIV_OK); - res = ykpiv_set_pin_retries(g_state, 8); + res = ykpiv_set_pin_retries(g_state, 8, 3); ck_assert_int_eq(res, YKPIV_OK); // Block and reset again, verifying increased PIN retries diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 3d82c7d..2721c50 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -963,28 +963,36 @@ ykpiv_rc ykpiv_get_pin_retries(ykpiv_state *state, int* tries) { if (NULL == state || NULL == tries) { return YKPIV_ARGUMENT_ERROR; } + // Force a re-select to unverify, because once verified the spec dictates that + // subsequent verify calls will return a "verification not needed" instead of + // the number of tries left... res = _ykpiv_select_application(state); + if (res != YKPIV_OK) return res; ykrc = ykpiv_verify(state, NULL, tries); // WRONG_PIN is expected on successful query. return ykrc == YKPIV_WRONG_PIN ? YKPIV_OK : ykrc; } -ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, const int tries) { +ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, int pin_tries, int puk_tries) { ykpiv_rc res = YKPIV_OK; - unsigned char templ[] = {0, YKPIV_INS_SET_PIN_RETRIES, (unsigned char)tries, YKPIV_RETRIES_DEFAULT}; + unsigned char templ[] = {0, YKPIV_INS_SET_PIN_RETRIES, 0, 0}; unsigned char data[0xff]; unsigned long recv_len = sizeof(data); int sw = 0; - if (0 == tries) { - //zero value means no change in retry count according to minidriver spec + // Special case: if either retry count is 0, it's a successful no-op + if (pin_tries == 0 || puk_tries == 0) { return YKPIV_OK; } - if (tries > YKPIV_RETRIES_MAX || tries < 1) { + + if (pin_tries > 0xff || puk_tries > 0xff || pin_tries < 1 || puk_tries < 1) { return YKPIV_RANGE_ERROR; } + templ[2] = (unsigned char)pin_tries; + templ[3] = (unsigned char)puk_tries; + res = ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw); if (YKPIV_OK == res) { if (SW_SUCCESS == sw) { diff --git a/lib/ykpiv.h b/lib/ykpiv.h index 637f655..e39d9a8 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -122,8 +122,10 @@ extern "C" const unsigned char *qinv, size_t qinv_len, const unsigned char *ec_data, unsigned char ec_data_len, const unsigned char pin_policy, const unsigned char touch_policy); + // TREV TODO: document that this only works when NOT verified, as per spec (NIST SP 800-73-3 part 2 page 11) ykpiv_rc ykpiv_get_pin_retries(ykpiv_state *state, int* tries); - ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, const int tries); + // TREV TODO: document that 0 == successful no-op. + ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, int pin_tries, int puk_tries); #define YKPIV_ALGO_TAG 0x80 #define YKPIV_ALGO_3DES 0x03 @@ -203,6 +205,7 @@ extern "C" #define YKPIV_INS_AUTHENTICATE 0x87 #define YKPIV_INS_GET_DATA 0xcb #define YKPIV_INS_PUT_DATA 0xdb + // TREV TODO: why aren't all of them here? ex: select app (0xa4) /* sw is status words, see NIST special publication 800-73-4, section 5.6 */ #define SW_SUCCESS 0x9000 diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index 2f3ca28..58ed1bd 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -257,26 +257,16 @@ static bool reset(ykpiv_state *state) { } static bool set_pin_retries(ykpiv_state *state, int pin_retries, int puk_retries, int verbose) { - unsigned char templ[] = {0, YKPIV_INS_SET_PIN_RETRIES, pin_retries, puk_retries}; - unsigned char data[0xff]; - unsigned long recv_len = sizeof(data); - int sw; - - if(pin_retries > 0xff || puk_retries > 0xff || pin_retries < 1 || puk_retries < 1) { - fprintf(stderr, "pin and puk retries must be between 1 and 255.\n"); - return false; - } + ykpiv_rc res; if(verbose) { fprintf(stderr, "Setting pin retries to %d and puk retries to %d.\n", pin_retries, puk_retries); } - - if(ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw) != YKPIV_OK) { - return false; - } else if(sw == SW_SUCCESS) { - return true; + res = ykpiv_set_pin_retries(state, pin_retries, puk_retries); + if (res == YKPIV_RANGE_ERROR) { + fprintf(stderr, "pin and puk retries must be between 1 and 255.\n"); } - return false; + return res == YKPIV_OK; } static bool import_key(ykpiv_state *state, enum enum_key_format key_format, @@ -1812,7 +1802,7 @@ int main(int argc, char *argv[]) { } break; case action_arg_pinMINUS_retries: - if(!args_info.pin_retries_arg || !args_info.puk_retries_arg) { + if(!args_info.pin_retries_given || !args_info.puk_retries_given) { fprintf(stderr, "The '%s' action needs both --pin-retries and --puk-retries arguments.\n", cmdline_parser_action_values[action]); return EXIT_FAILURE; From ded78751a01c23e0be9c55054602a2899e1e48a6 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 18 Sep 2017 16:24:39 +0200 Subject: [PATCH 19/57] Add gzip support to ykpiv_util_import_certificate(), and use in yubico-piv-tool --- lib/tests/util.c | 6 +++--- lib/util.c | 14 ++++++------- lib/ykpiv.h | 6 +++++- tool/util.c | 45 ++++++++++++++++++++++++++++++++++++++++++ tool/util.h | 1 + tool/yubico-piv-tool.c | 23 +++------------------ 6 files changed, 64 insertions(+), 31 deletions(-) diff --git a/lib/tests/util.c b/lib/tests/util.c index efbce40..8b103c9 100644 --- a/lib/tests/util.c +++ b/lib/tests/util.c @@ -145,7 +145,7 @@ START_TEST(test_read_write_list_delete_cert) { size_t read_cert_len = 0; { - res = ykpiv_util_write_cert(g_state, YKPIV_KEY_AUTHENTICATION, (uint8_t*)g_cert, sizeof(g_cert)); + res = ykpiv_util_write_cert(g_state, YKPIV_KEY_AUTHENTICATION, (uint8_t*)g_cert, sizeof(g_cert), YKPIV_CERTINFO_UNCOMPRESSED); ck_assert_int_eq(res, YKPIV_OK); res = ykpiv_util_read_cert(g_state, YKPIV_KEY_AUTHENTICATION, &read_cert, &read_cert_len); @@ -411,7 +411,7 @@ START_TEST(test_generate_key) { ykpiv_rc res; uint8_t *mod, *exp; size_t mod_len, exp_len; - res = ykpiv_util_write_cert(g_state, YKPIV_KEY_AUTHENTICATION, (uint8_t*)g_cert, sizeof(g_cert)); + res = ykpiv_util_write_cert(g_state, YKPIV_KEY_AUTHENTICATION, (uint8_t*)g_cert, sizeof(g_cert), YKPIV_CERTINFO_UNCOMPRESSED); ck_assert_int_eq(res, YKPIV_OK); res = ykpiv_util_generate_key(g_state, YKPIV_KEY_AUTHENTICATION, @@ -666,7 +666,7 @@ uint8_t *alloc_auth_cert() { uint8_t *read_cert = NULL; size_t read_cert_len = 0; - res = ykpiv_util_write_cert(g_state, YKPIV_KEY_AUTHENTICATION, (uint8_t*)g_cert, sizeof(g_cert)); + res = ykpiv_util_write_cert(g_state, YKPIV_KEY_AUTHENTICATION, (uint8_t*)g_cert, sizeof(g_cert), YKPIV_CERTINFO_UNCOMPRESSED); ck_assert_int_eq(res, YKPIV_OK); res = ykpiv_util_read_cert(g_state, YKPIV_KEY_AUTHENTICATION, &read_cert, &read_cert_len); diff --git a/lib/util.c b/lib/util.c index f69e146..aa2b1f3 100644 --- a/lib/util.c +++ b/lib/util.c @@ -58,7 +58,7 @@ const uint8_t CCC_TMPL[] = { }; static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf, size_t *buf_len); -static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len); +static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len, uint8_t certinfo); static ykpiv_rc _read_metadata(ykpiv_state *state, uint8_t tag, uint8_t* data, size_t* pcb_data); static ykpiv_rc _write_metadata(ykpiv_state *state, uint8_t tag, uint8_t *data, size_t cb_data); @@ -293,13 +293,13 @@ Cleanup: return res; } -ykpiv_rc ykpiv_util_write_cert(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len) { +ykpiv_rc ykpiv_util_write_cert(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len, uint8_t certinfo) { ykpiv_rc res = YKPIV_OK; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; - res = _write_certificate(state, slot, data, data_len); + res = _write_certificate(state, slot, data, data_len, certinfo); Cleanup: @@ -308,7 +308,7 @@ Cleanup: } ykpiv_rc ykpiv_util_delete_cert(ykpiv_state *state, uint8_t slot) { - return ykpiv_util_write_cert(state, slot, NULL, 0); + return ykpiv_util_write_cert(state, slot, NULL, 0, 0); } ykpiv_rc ykpiv_util_block_puk(ykpiv_state *state) { @@ -1252,7 +1252,7 @@ static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf return res; } -static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len) { +static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len, uint8_t certinfo) { // TREV TODO: should this select application? uint8_t buf[CB_OBJ_MAX]; size_t cbBuf = sizeof(buf); @@ -1290,8 +1290,8 @@ static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *da // write compression info and LRC trailer buf[offset++] = TAG_CERT_COMPRESS; buf[offset++] = 0x01; - buf[offset++] = 0x00; // TODO: Handle compression when certificate exceeds buffer size - buf[offset++] = TAG_CERT_LRC; // LRC + buf[offset++] = certinfo == YKPIV_CERTINFO_GZIP ? 0x01 : 0x00; + buf[offset++] = TAG_CERT_LRC; buf[offset++] = 00; // write onto device diff --git a/lib/ykpiv.h b/lib/ykpiv.h index e39d9a8..28d2a73 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -198,6 +198,8 @@ extern "C" #define YKPIV_OBJ_ATTESTATION 0x5fff01 +#define YKPIV_OBJ_MAX_SIZE 3072 + #define YKPIV_INS_VERIFY 0x20 #define YKPIV_INS_CHANGE_REFERENCE 0x24 #define YKPIV_INS_RESET_RETRY 0x2c @@ -241,6 +243,8 @@ extern "C" #define YKPIV_RETRIES_DEFAULT 3 #define YKPIV_RETRIES_MAX 0xff +#define YKPIV_CERTINFO_UNCOMPRESSED 0 +#define YKPIV_CERTINFO_GZIP 1 // // UTIL @@ -291,7 +295,7 @@ extern "C" ykpiv_rc ykpiv_util_list_keys(ykpiv_state *state, uint8_t *key_count, ykpiv_key **data, size_t *data_len); ykpiv_rc ykpiv_util_read_cert(ykpiv_state *state, uint8_t slot, uint8_t **data, size_t *data_len); - ykpiv_rc ykpiv_util_write_cert(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len); + ykpiv_rc ykpiv_util_write_cert(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len, uint8_t certinfo); ykpiv_rc ykpiv_util_delete_cert(ykpiv_state *state, uint8_t slot); /** diff --git a/tool/util.c b/tool/util.c index baea3f1..3ae4119 100644 --- a/tool/util.c +++ b/tool/util.c @@ -255,6 +255,51 @@ int set_length(unsigned char *buffer, int length) { } } +int get_slot_hex(enum enum_slot slot_enum) { + int slot = -1; + + switch (slot_enum) { + case slot_arg_9a: + slot = 0x9a; + break; + case slot_arg_9c: + case slot_arg_9d: + case slot_arg_9e: + slot = 0x9c + ((int)slot_enum - (int)slot_arg_9c); + break; + case slot_arg_82: + case slot_arg_83: + case slot_arg_84: + case slot_arg_85: + case slot_arg_86: + case slot_arg_87: + case slot_arg_88: + case slot_arg_89: + case slot_arg_8a: + case slot_arg_8b: + case slot_arg_8c: + case slot_arg_8d: + case slot_arg_8e: + case slot_arg_8f: + case slot_arg_90: + case slot_arg_91: + case slot_arg_92: + case slot_arg_93: + case slot_arg_94: + case slot_arg_95: + slot = 0x82 + ((int)slot_enum - (int)slot_arg_82); + break; + case slot_arg_f9: + slot = 0xf9; + break; + case slot__NULL: + default: + slot = -1; + } + + return slot; +} + int get_object_id(enum enum_slot slot) { int object; diff --git a/tool/util.h b/tool/util.h index 4f61713..a1f15b5 100644 --- a/tool/util.h +++ b/tool/util.h @@ -47,6 +47,7 @@ int get_length(const unsigned char*, int*); X509_NAME *parse_name(const char*); unsigned char get_algorithm(EVP_PKEY*); FILE *open_file(const char*, int); +int get_slot_hex(enum enum_slot slot_enum); int get_object_id(enum enum_slot slot); int key_to_object_id(int key); bool set_component(unsigned char *in_ptr, const BIGNUM *bn, int element_len); diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index 58ed1bd..adde591 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -495,35 +495,18 @@ static bool import_cert(ykpiv_state *state, enum enum_key_format cert_format, } { - unsigned char certdata[3072]; + unsigned char certdata[YKPIV_OBJ_MAX_SIZE]; unsigned char *certptr = certdata; - int object = get_object_id(slot); ykpiv_rc res; - - if(4 + cert_len + 5 > sizeof(certdata)) { /* 4 is prefix size, 5 is postfix size */ - fprintf(stderr, "Certificate is too large to fit in buffer.\n"); - goto import_cert_out; - } - - *certptr++ = 0x70; - certptr += set_length(certptr, cert_len); if (compress) { - if (fread(certptr, 1, (size_t)cert_len, input_file) != (size_t)cert_len) { + if (fread(certdata, 1, (size_t)cert_len, input_file) != (size_t)cert_len) { fprintf(stderr, "Failed to read compressed certificate\n"); goto import_cert_out; } - certptr += cert_len; } else { - /* i2d_X509 increments certptr here.. */ i2d_X509(cert, &certptr); } - *certptr++ = 0x71; - *certptr++ = 1; - *certptr++ = compress; /* certinfo (gzip etc) */ - *certptr++ = 0xfe; /* LRC */ - *certptr++ = 0; - - if((res = ykpiv_save_object(state, object, certdata, (size_t)(certptr - certdata))) != YKPIV_OK) { + if ((res = ykpiv_util_write_cert(state, get_slot_hex(slot), certdata, cert_len, compress)) != YKPIV_OK) { fprintf(stderr, "Failed commands with device: %s\n", ykpiv_strerror(res)); } else { ret = true; From 3bca63c39ca212f5cd2a2cca82b686783ff7187b Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 19 Sep 2017 15:00:04 +0200 Subject: [PATCH 20/57] yubico-piv-tool: use ykpiv_util_delete_cert --- tool/yubico-piv-tool.c | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index adde591..e082fbc 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -985,15 +985,7 @@ static bool change_pin(ykpiv_state *state, enum enum_action action, const char * } static bool delete_certificate(ykpiv_state *state, enum enum_slot slot) { - int object = get_object_id(slot); - - if(ykpiv_save_object(state, object, NULL, 0) != YKPIV_OK) { - fprintf(stderr, "Failed deleting object.\n"); - return false; - } else { - fprintf(stderr, "Certificate deleted.\n"); - return true; - } + return ykpiv_util_delete_cert(state, get_slot_hex(slot)) == YKPIV_OK; } static bool read_certificate(ykpiv_state *state, enum enum_slot slot, From 248980fe2752bda8aeff6f10ca1f5e714bd32a23 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 19 Sep 2017 17:33:58 +0200 Subject: [PATCH 21/57] yubico-piv-tool: use ykpiv_util_read_cert --- tool/yubico-piv-tool.c | 83 ++++++++++++++++++++---------------------- 1 file changed, 40 insertions(+), 43 deletions(-) diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index e082fbc..c0affd5 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -991,73 +991,70 @@ static bool delete_certificate(ykpiv_state *state, enum enum_slot slot) { static bool read_certificate(ykpiv_state *state, enum enum_slot slot, enum enum_key_format key_format, const char *output_file_name) { FILE *output_file; - int object = get_object_id(slot); - unsigned char data[3072]; - const unsigned char *ptr = data; - unsigned long len = sizeof(data); - int cert_len; - bool ret = false; + uint8_t *data = NULL; + const unsigned char *ptr = NULL; X509 *x509 = NULL; + bool ret = false; + size_t cert_len = 0; - if(key_format != key_format_arg_PEM && - key_format != key_format_arg_DER && - key_format != key_format_arg_SSH) { + if (key_format != key_format_arg_PEM && + key_format != key_format_arg_DER && + key_format != key_format_arg_SSH) { fprintf(stderr, "Only PEM, DER and SSH format are supported for read-certificate.\n"); return false; } output_file = open_file(output_file_name, OUTPUT); - if(!output_file) { + if (!output_file) { return false; } - if(ykpiv_fetch_object(state, object, data, &len) != YKPIV_OK) { + if (ykpiv_util_read_cert(state, get_slot_hex(slot), &data, &cert_len) != YKPIV_OK) { fprintf(stderr, "Failed fetching certificate.\n"); goto read_cert_out; } + ptr = data; - if(*ptr++ == 0x70) { - ptr += get_length(ptr, &cert_len); - if(key_format == key_format_arg_PEM || - key_format == key_format_arg_SSH) { - x509 = X509_new(); - if(!x509) { - fprintf(stderr, "Failed allocating x509 structure.\n"); - goto read_cert_out; - } - x509 = d2i_X509(NULL, &ptr, cert_len); - if(!x509) { - fprintf(stderr, "Failed parsing x509 information.\n"); - goto read_cert_out; - } + if (key_format == key_format_arg_PEM || + key_format == key_format_arg_SSH) { + x509 = X509_new(); + if (!x509) { + fprintf(stderr, "Failed allocating x509 structure.\n"); + goto read_cert_out; + } + x509 = d2i_X509(NULL, (const unsigned char**)&ptr, cert_len); + if (!x509) { + fprintf(stderr, "Failed parsing x509 information.\n"); + goto read_cert_out; + } - if (key_format == key_format_arg_PEM) { - PEM_write_X509(output_file, x509); - ret = true; - } - else { - if (!SSH_write_X509(output_file, x509)) { - fprintf(stderr, "Unable to extract public key or not an RSA key.\n"); - goto read_cert_out; - } - ret = true; - } - } else { /* key_format_arg_DER */ - /* XXX: This will just dump the raw data in tag 0x70.. */ - fwrite(ptr, (size_t)cert_len, 1, output_file); + if (key_format == key_format_arg_PEM) { + PEM_write_X509(output_file, x509); ret = true; } - } else { - fprintf(stderr, "Failed parsing data.\n"); + else { + if (!SSH_write_X509(output_file, x509)) { + fprintf(stderr, "Unable to extract public key or not an RSA key.\n"); + goto read_cert_out; + } + ret = true; + } + } else { /* key_format_arg_DER */ + /* XXX: This will just dump the raw data in tag 0x70.. */ + fwrite(ptr, (size_t)cert_len, 1, output_file); + ret = true; } read_cert_out: - if(output_file != stdout) { + if (output_file != stdout) { fclose(output_file); } - if(x509) { + if (x509) { X509_free(x509); } + if (data) { + ykpiv_util_free(state, data); + } return ret; } From f6b817f0563e81e3574e0333c627fce96e624064 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Wed, 20 Sep 2017 16:29:37 +0200 Subject: [PATCH 22/57] Add ykpiv_attest() and use it in yubico-piv-tool --- lib/ykpiv.c | 22 +++++++++++++++++++ lib/ykpiv.h | 1 + tool/yubico-piv-tool.c | 50 +++++++++++++++++------------------------- 3 files changed, 43 insertions(+), 30 deletions(-) diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 2721c50..6ced031 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -1273,6 +1273,28 @@ ykpiv_rc ykpiv_import_private_key(ykpiv_state *state, const unsigned char key, u } +ykpiv_rc ykpiv_attest(ykpiv_state *state, int object_id, unsigned char *data, size_t *data_len) { + ykpiv_rc res; + bool ret = false; + unsigned char templ[] = {0, YKPIV_INS_ATTEST, object_id, 0}; + int sw; + + if (state == NULL || data == NULL || data_len == NULL) { + return YKPIV_ARGUMENT_ERROR; + } + if ((res = ykpiv_transfer_data(state, templ, NULL, 0, data, data_len, &sw)) != YKPIV_OK) { + return res; + } + else if(SW_SUCCESS != sw) { + return YKPIV_GENERIC_ERROR; + } + if (data[0] != 0x30) { + return YKPIV_GENERIC_ERROR; + } + return YKPIV_OK; +} + + // TREV TODO: remove these, fix minidriver ykpiv_rc ykpiv_done2(ykpiv_state *state, bool disconnect) { diff --git a/lib/ykpiv.h b/lib/ykpiv.h index 28d2a73..6e14328 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -126,6 +126,7 @@ extern "C" ykpiv_rc ykpiv_get_pin_retries(ykpiv_state *state, int* tries); // TREV TODO: document that 0 == successful no-op. ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, int pin_tries, int puk_tries); + ykpiv_rc ykpiv_attest(ykpiv_state *state, int object_id, unsigned char *data, size_t *data_len); #define YKPIV_ALGO_TAG 0x80 #define YKPIV_ALGO_3DES 0x03 diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index c0affd5..af32edf 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -1604,55 +1604,45 @@ static bool list_readers(ykpiv_state *state) { static bool attest(ykpiv_state *state, const char *slot, enum enum_key_format key_format, const char *output_file_name) { - unsigned char data[2048]; + unsigned char data[YKPIV_OBJ_MAX_SIZE]; unsigned long len = sizeof(data); bool ret = false; X509 *x509 = NULL; - unsigned char templ[] = {0, YKPIV_INS_ATTEST, 0, 0}; int key; - int sw; FILE *output_file = open_file(output_file_name, OUTPUT); if(!output_file) { return false; } - sscanf(slot, "%2x", &key); - templ[2] = key; - if(key_format != key_format_arg_PEM && key_format != key_format_arg_DER) { fprintf(stderr, "Only PEM and DER format are supported for attest..\n"); return false; } - if(ykpiv_transfer_data(state, templ, NULL, 0, data, &len, &sw) != YKPIV_OK) { - fprintf(stderr, "Failed to communicate.\n"); - goto attest_out; - } else if(sw != SW_SUCCESS) { - fprintf(stderr, "Failed to attest key.\n"); + sscanf(slot, "%2x", &key); + if (ykpiv_attest(state, key, data, &len) != YKPIV_OK) { + fprintf(stderr, "Failed to attest data.\n"); goto attest_out; } - if(data[0] == 0x30) { - if(key_format == key_format_arg_PEM) { - const unsigned char *ptr = data; - int len2 = len; - x509 = X509_new(); - if(!x509) { - fprintf(stderr, "Failed allocating x509 structure.\n"); - goto attest_out; - } - x509 = d2i_X509(NULL, &ptr, len2); - if(!x509) { - fprintf(stderr, "Failed parsing x509 information.\n"); - goto attest_out; - } - PEM_write_X509(output_file, x509); - ret = true; - } else { - fwrite(data, len, 1, output_file); + if(key_format == key_format_arg_PEM) { + const unsigned char *ptr = data; + int len2 = len; + x509 = X509_new(); + if(!x509) { + fprintf(stderr, "Failed allocating x509 structure.\n"); + goto attest_out; } - ret = true; + x509 = d2i_X509(NULL, &ptr, len2); + if(!x509) { + fprintf(stderr, "Failed parsing x509 information.\n"); + goto attest_out; + } + PEM_write_X509(output_file, x509); + } else { + fwrite(data, len, 1, output_file); } + ret = true; attest_out: if(output_file != stdout) { From 13e02f998da36b6d45602ef4994d5c1a95bc7530 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Wed, 20 Sep 2017 16:59:45 +0200 Subject: [PATCH 23/57] Fix ykpiv_attest slot argument name --- lib/ykpiv.c | 4 ++-- lib/ykpiv.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 6ced031..c0b3f8a 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -1273,10 +1273,10 @@ ykpiv_rc ykpiv_import_private_key(ykpiv_state *state, const unsigned char key, u } -ykpiv_rc ykpiv_attest(ykpiv_state *state, int object_id, unsigned char *data, size_t *data_len) { +ykpiv_rc ykpiv_attest(ykpiv_state *state, const unsigned char key, unsigned char *data, size_t *data_len) { ykpiv_rc res; bool ret = false; - unsigned char templ[] = {0, YKPIV_INS_ATTEST, object_id, 0}; + unsigned char templ[] = {0, YKPIV_INS_ATTEST, key, 0}; int sw; if (state == NULL || data == NULL || data_len == NULL) { diff --git a/lib/ykpiv.h b/lib/ykpiv.h index 6e14328..3455f43 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -126,7 +126,7 @@ extern "C" ykpiv_rc ykpiv_get_pin_retries(ykpiv_state *state, int* tries); // TREV TODO: document that 0 == successful no-op. ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, int pin_tries, int puk_tries); - ykpiv_rc ykpiv_attest(ykpiv_state *state, int object_id, unsigned char *data, size_t *data_len); + ykpiv_rc ykpiv_attest(ykpiv_state *state, const unsigned char key, unsigned char *data, size_t *data_len); #define YKPIV_ALGO_TAG 0x80 #define YKPIV_ALGO_3DES 0x03 From 2e818dd9147d73afc93b573ff03bd5a5265b86d5 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 25 Sep 2017 16:03:48 +0200 Subject: [PATCH 24/57] Add ykpiv_util_(get/set)_cccid(), and use in yubico-piv-tool --- lib/internal.h | 6 --- lib/util.c | 83 ++++++++++++++++++++++++++++++++++++++---- lib/ykpiv.h | 47 ++++++++++++++++++++---- tool/yubico-piv-tool.c | 76 ++++++++++---------------------------- 4 files changed, 135 insertions(+), 77 deletions(-) diff --git a/lib/internal.h b/lib/internal.h index 1efb014..8c3f925 100644 --- a/lib/internal.h +++ b/lib/internal.h @@ -73,8 +73,6 @@ extern "C" #define CB_ATR_MAX 33 -#define CB_CARDID 16 - #define CHREF_ACT_CHANGE_PIN 0 #define CHREF_ACT_UNBLOCK_PIN 1 #define CHREF_ACT_CHANGE_PUK 2 @@ -97,10 +95,6 @@ extern "C" #define TAG_RSA_EXP 0x82 #define TAG_ECC_POINT 0x86 - -#define CCC_ID_OFFS 9 -#define CB_CCC_ID 14 - #define CB_ECC_POINTP256 65 #define CB_ECC_POINTP384 97 diff --git a/lib/util.c b/lib/util.c index aa2b1f3..d0712e3 100644 --- a/lib/util.c +++ b/lib/util.c @@ -41,6 +41,20 @@ #define MAX(a,b) (a) > (b) ? (a) : (b) #define MIN(a,b) (a) < (b) ? (a) : (b) +/* + * Format defined in SP-800-73-4, Appendix A, Table 9 + * + * FASC-N containing S9999F9999F999999F0F1F0000000000300001E encoded in + * 4-bit BCD with 1 bit parity. run through the tools/fasc.pl script to get + * bytes. This CHUID has an expiry of 2030-01-01. + * + * Defined fields: + * - 0x30: FASC-N (hard-coded) + * - 0x34: Card UUID / GUID (settable) + * - 0x35: Exp. Date (hard-coded) + * - 0x3e: Signature (hard-coded, empty) + * - 0xfe: Error Detection Code (hard-coded) + */ const uint8_t CHUID_TMPL[] = { 0x30, 0x19, 0xd4, 0xe7, 0x39, 0xda, 0x73, 0x9c, 0xed, 0x39, 0xce, 0x73, 0x9d, 0x83, 0x68, 0x58, 0x21, 0x08, 0x42, 0x10, 0x84, 0x21, 0x38, 0x42, 0x10, 0xc3, @@ -50,12 +64,18 @@ const uint8_t CHUID_TMPL[] = { }; #define CHUID_GUID_OFFS 29 +// f0: Card Identifier +// - 0xa000000116 == GSC-IS RID +// - 0xff == Manufacturer ID (dummy) +// - 0x02 == Card type (javaCard) +// - next 14 bytes: card ID const uint8_t CCC_TMPL[] = { 0xf0, 0x15, 0xa0, 0x00, 0x00, 0x01, 0x16, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf1, 0x01, 0x21, 0xf2, 0x01, 0x21, 0xf3, 0x00, 0xf4, 0x01, 0x00, 0xf5, 0x01, 0x10, 0xf6, 0x00, 0xf7, 0x00, 0xfa, 0x00, 0xfb, 0x00, 0xfc, 0x00, 0xfd, 0x00, 0xfe, 0x00 }; +#define CCC_ID_OFFS 9 static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf, size_t *buf_len); static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len, uint8_t certinfo); @@ -89,7 +109,7 @@ ykpiv_rc ykpiv_util_get_cardid(ykpiv_state *state, ykpiv_cardid *cardid) { res = YKPIV_GENERIC_ERROR; } else { - memcpy(cardid->data, buf + CHUID_GUID_OFFS, CB_CARDID); + memcpy(cardid->data, buf + CHUID_GUID_OFFS, YKPIV_CARDID_SIZE); } } @@ -101,7 +121,7 @@ Cleanup: ykpiv_rc ykpiv_util_set_cardid(ykpiv_state *state, const ykpiv_cardid *cardid) { ykpiv_rc res = YKPIV_OK; - uint8_t id[CB_CARDID]; + uint8_t id[YKPIV_CARDID_SIZE]; uint8_t buf[sizeof(CHUID_TMPL)]; size_t len = 0; @@ -125,13 +145,30 @@ ykpiv_rc ykpiv_util_set_cardid(ykpiv_state *state, const ykpiv_cardid *cardid) { res = ykpiv_save_object(state, YKPIV_OBJ_CHUID, buf, len); - if (YKPIV_OK == res) { - // also set the CCC for use with systems that require it - len = sizeof(CCC_TMPL); - memcpy(buf, CCC_TMPL, len); - memcpy(buf + CCC_ID_OFFS, id, CB_CCC_ID); +Cleanup: - res = ykpiv_save_object(state, YKPIV_OBJ_CAPABILITY, buf, len); + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_util_get_cccid(ykpiv_state *state, ykpiv_cccid *ccc) { + ykpiv_rc res = YKPIV_OK; + uint8_t buf[CB_OBJ_MAX]; + size_t len = sizeof(buf); + + if (!ccc) return YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + res = ykpiv_fetch_object(state, YKPIV_OBJ_CAPABILITY, buf, (unsigned long *)&len); + if (YKPIV_OK == res) { + if (len != sizeof(CCC_TMPL)) { + res = YKPIV_GENERIC_ERROR; + } + else { + memcpy(ccc->data, buf + CCC_ID_OFFS, YKPIV_CCCID_SIZE); + } } Cleanup: @@ -140,6 +177,36 @@ Cleanup: return res; } +ykpiv_rc ykpiv_util_set_cccid(ykpiv_state *state, const ykpiv_cccid *ccc) { + ykpiv_rc res = YKPIV_OK; + uint8_t id[YKPIV_CCCID_SIZE]; + uint8_t buf[sizeof(CCC_TMPL)]; + size_t len = 0; + + if (!state) return YKPIV_GENERIC_ERROR; + + if (!ccc) { + if (PRNG_OK != _ykpiv_prng_generate(id, sizeof(id))) { + return YKPIV_RANDOMNESS_ERROR; + } + } + else { + memcpy(id, ccc->data, sizeof(id)); + } + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + len = sizeof(CCC_TMPL); + memcpy(buf, CCC_TMPL, len); + memcpy(buf + CCC_ID_OFFS, id, YKPIV_CCCID_SIZE); + res = ykpiv_save_object(state, YKPIV_OBJ_CAPABILITY, buf, len); + +Cleanup: + _ykpiv_end_transaction(state); + return res; +} + ykpiv_devmodel ykpiv_util_devicemodel(ykpiv_state *state) { if (!state || state->context == SCARD_E_INVALID_HANDLE) return DEVTYPE_UNKNOWN; diff --git a/lib/ykpiv.h b/lib/ykpiv.h index 3455f43..c6d8c7f 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -259,8 +259,25 @@ extern "C" #define DEVTYPE_YK 0x594B0000 //"YK" #define DEVTYPE_NEOr3 (DEVTYPE_NEO | 0x00007233) //"r3" #define DEVTYPE_YK4 (DEVTYPE_YK | 0x00000034) // "4" + typedef uint32_t ykpiv_devmodel; + /** + * Card identifier + */ + #define YKPIV_CARDID_SIZE 16 + typedef struct { + uint8_t data[YKPIV_CARDID_SIZE]; + } ykpiv_cardid; + + /** + * Card Capability + */ + #define YKPIV_CCCID_SIZE 14 + typedef struct { + uint8_t data[YKPIV_CCCID_SIZE]; + } ykpiv_cccid; + #pragma pack(push, 1) typedef struct _ykpiv_key { @@ -408,13 +425,6 @@ extern "C" */ ykpiv_rc ykpiv_util_reset(ykpiv_state *state); - /** - * Card identifier - */ - typedef struct { - uint8_t data[16]; - } ykpiv_cardid; - /** * Get card identifier * @@ -438,6 +448,29 @@ extern "C" */ ykpiv_rc ykpiv_util_set_cardid(ykpiv_state *state, const ykpiv_cardid *cardid); + /** + * Get card capabilities identifier + * + * @param state state + * @param cardid ykpiv_cardid return value + * + * @return ykpiv_rc error code + */ + ykpiv_rc ykpiv_util_get_cccid(ykpiv_state *state, ykpiv_cccid *ccc); + + /** + * Set card capabilities identifier + * + * The card must be authenticated to call this function. + * + * @param state state + * @param ccc card ID to set. if NULL, randomly generate + * + * @return ypiv_rc error code + * + */ + ykpiv_rc ykpiv_util_set_cccid(ykpiv_state *state, const ykpiv_cccid *ccc); + /** * Get device model * diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index af32edf..b1bfd09 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -50,26 +50,8 @@ #include "cmdline.h" #include "util.h" -/* FASC-N containing S9999F9999F999999F0F1F0000000000300001E encoded in - * 4-bit BCD with 1 bit parity. run through the tools/fasc.pl script to get - * bytes. */ -/* this CHUID has an expiry of 2030-01-01, maybe that should be variable.. */ -unsigned const char chuid_tmpl[] = { - 0x30, 0x19, 0xd4, 0xe7, 0x39, 0xda, 0x73, 0x9c, 0xed, 0x39, 0xce, 0x73, 0x9d, - 0x83, 0x68, 0x58, 0x21, 0x08, 0x42, 0x10, 0x84, 0x21, 0x38, 0x42, 0x10, 0xc3, - 0xf5, 0x34, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x35, 0x08, 0x32, 0x30, 0x33, 0x30, 0x30, - 0x31, 0x30, 0x31, 0x3e, 0x00, 0xfe, 0x00, -}; -#define CHUID_GUID_OFFS 29 - -unsigned const char ccc_tmpl[] = { - 0xf0, 0x15, 0xa0, 0x00, 0x00, 0x01, 0x16, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf1, 0x01, 0x21, - 0xf2, 0x01, 0x21, 0xf3, 0x00, 0xf4, 0x01, 0x00, 0xf5, 0x01, 0x10, 0xf6, 0x00, - 0xf7, 0x00, 0xfa, 0x00, 0xfb, 0x00, 0xfc, 0x00, 0xfd, 0x00, 0xfe, 0x00 -}; -#define CCC_ID_OFFS 9 +#define MAX(a,b) (a) > (b) ? (a) : (b) +#define MIN(a,b) (a) < (b) ? (a) : (b) #define CHUID 0 #define CCC 1 @@ -530,41 +512,28 @@ import_cert_out: return ret; } -static bool set_dataobject(ykpiv_state *state, int verbose, int type) { - unsigned char obj[1024]; +static bool set_cardid(ykpiv_state *state, int verbose, int type) { ykpiv_rc res; - size_t offs, rand_len, len; - const unsigned char *tmpl; - int id; + unsigned char id[MAX(sizeof(ykpiv_cardid), sizeof(ykpiv_cccid))]; if(type == CHUID) { - offs = CHUID_GUID_OFFS; - len = sizeof(chuid_tmpl); - rand_len = 0x10; - tmpl = chuid_tmpl; - id = YKPIV_OBJ_CHUID; + res = ykpiv_util_set_cardid(state, NULL); } else { - offs = CCC_ID_OFFS; - rand_len = 0xe; - len = sizeof(ccc_tmpl); - tmpl = ccc_tmpl; - id = YKPIV_OBJ_CAPABILITY; - } - memcpy(obj, tmpl, len); - if(RAND_pseudo_bytes(obj + offs, rand_len) == -1) { - fprintf(stderr, "error: no randomness.\n"); - return false; - } - if(verbose) { - fprintf(stderr, "Setting the %s to: ", type == CHUID ? "CHUID" : "CCC"); - dump_data(obj, len, stderr, true, format_arg_hex); - } - if((res = ykpiv_save_object(state, id, obj, len)) != YKPIV_OK) { - fprintf(stderr, "Failed communicating with device: %s\n", ykpiv_strerror(res)); - return false; + res = ykpiv_util_set_cccid(state, NULL); } - return true; + if(res == YKPIV_OK && verbose) { + if (type == CHUID) { + res = ykpiv_util_get_cardid(state, (ykpiv_cardid*)id); + } else { + res = ykpiv_util_get_cccid(state, (ykpiv_cccid*)id); + } + if (res == YKPIV_OK) { + fprintf(stderr, "Set the %s ID to: ", type == CHUID ? "CHUID" : "CCC"); + dump_data(id, type == CHUID ? YKPIV_CARDID_SIZE : YKPIV_CCCID_SIZE, stderr, true, format_arg_hex); + } + } + return res == YKPIV_OK; } static bool request_certificate(ykpiv_state *state, enum enum_key_format key_format, @@ -1166,12 +1135,7 @@ static void print_cert_info(ykpiv_state *state, enum enum_slot slot, const EVP_M return; } - if (slot == slot_arg_9a) - slot_name = 0x9a; - else if (slot >= slot_arg_9c && slot <= slot_arg_9e) - slot_name = 0x9b + slot; - else - slot_name = 0x82 + (slot - slot_arg_82); + slot_name = get_slot_hex(slot); fprintf(output, "Slot %x:\t", slot_name); @@ -1974,7 +1938,7 @@ int main(int argc, char *argv[]) { break; case action_arg_setMINUS_ccc: case action_arg_setMINUS_chuid: - if(set_dataobject(state, verbosity, action == action_arg_setMINUS_chuid ? CHUID : CCC) == false) { + if(set_cardid(state, verbosity, action == action_arg_setMINUS_chuid ? CHUID : CCC) == false) { ret = EXIT_FAILURE; } else { fprintf(stderr, "Successfully set new %s.\n", action == action_arg_setMINUS_chuid ? "CHUID" : "CCC"); From 79464a3d3e9f58a694fb26ffeaa78273d9ecbbe0 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 26 Sep 2017 13:17:07 +0200 Subject: [PATCH 25/57] Use slot enum consistently. Move slot->object translation into libykpiv. --- lib/util.c | 6 +- lib/ykpiv.h | 6 ++ tool/util.c | 168 ----------------------------------------- tool/util.h | 2 - tool/yubico-piv-tool.c | 42 +++++------ ykcs11/token_vendors.c | 2 +- 6 files changed, 31 insertions(+), 195 deletions(-) diff --git a/lib/util.c b/lib/util.c index d0712e3..fef1b24 100644 --- a/lib/util.c +++ b/lib/util.c @@ -1245,7 +1245,7 @@ ykpiv_rc ykpiv_util_reset(ykpiv_state *state) { return YKPIV_GENERIC_ERROR; } -static int _slot2object(uint8_t slot) { +uint32_t ykpiv_util_slot_object(uint8_t slot) { int object_id = -1; switch (slot) { @@ -1283,7 +1283,7 @@ static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf // TREV TODO: should this select application? ykpiv_rc res = YKPIV_OK; uint8_t *ptr = NULL; - int object_id = _slot2object(slot); + int object_id = ykpiv_util_slot_object(slot); size_t len = 0; if (-1 == object_id) return YKPIV_INVALID_OBJECT; @@ -1323,7 +1323,7 @@ static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *da // TREV TODO: should this select application? uint8_t buf[CB_OBJ_MAX]; size_t cbBuf = sizeof(buf); - int object_id = _slot2object(slot); + int object_id = ykpiv_util_slot_object(slot); size_t offset = 0; size_t req_len = 0; diff --git a/lib/ykpiv.h b/lib/ykpiv.h index c6d8c7f..b3f80ed 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -492,6 +492,12 @@ extern "C" */ ykpiv_rc ykpiv_util_block_puk(ykpiv_state *state); + /** + * Object ID of given slot. + * + * @param slot key slot + */ + uint32_t ykpiv_util_slot_object(uint8_t slot); ykpiv_rc ykpiv_connect_with_card(ykpiv_state *state, uint64_t context, uint64_t card); diff --git a/tool/util.c b/tool/util.c index 3ae4119..0284ef2 100644 --- a/tool/util.c +++ b/tool/util.c @@ -300,174 +300,6 @@ int get_slot_hex(enum enum_slot slot_enum) { return slot; } -int get_object_id(enum enum_slot slot) { - int object; - - switch(slot) { - case slot_arg_9a: - object = YKPIV_OBJ_AUTHENTICATION; - break; - case slot_arg_9c: - object = YKPIV_OBJ_SIGNATURE; - break; - case slot_arg_9d: - object = YKPIV_OBJ_KEY_MANAGEMENT; - break; - case slot_arg_9e: - object = YKPIV_OBJ_CARD_AUTH; - break; - case slot_arg_82: - object = YKPIV_OBJ_RETIRED1; - break; - case slot_arg_83: - object = YKPIV_OBJ_RETIRED2; - break; - case slot_arg_84: - object = YKPIV_OBJ_RETIRED3; - break; - case slot_arg_85: - object = YKPIV_OBJ_RETIRED4; - break; - case slot_arg_86: - object = YKPIV_OBJ_RETIRED5; - break; - case slot_arg_87: - object = YKPIV_OBJ_RETIRED6; - break; - case slot_arg_88: - object = YKPIV_OBJ_RETIRED7; - break; - case slot_arg_89: - object = YKPIV_OBJ_RETIRED8; - break; - case slot_arg_8a: - object = YKPIV_OBJ_RETIRED9; - break; - case slot_arg_8b: - object = YKPIV_OBJ_RETIRED10; - break; - case slot_arg_8c: - object = YKPIV_OBJ_RETIRED11; - break; - case slot_arg_8d: - object = YKPIV_OBJ_RETIRED12; - break; - case slot_arg_8e: - object = YKPIV_OBJ_RETIRED13; - break; - case slot_arg_8f: - object = YKPIV_OBJ_RETIRED14; - break; - case slot_arg_90: - object = YKPIV_OBJ_RETIRED15; - break; - case slot_arg_91: - object = YKPIV_OBJ_RETIRED16; - break; - case slot_arg_92: - object = YKPIV_OBJ_RETIRED17; - break; - case slot_arg_93: - object = YKPIV_OBJ_RETIRED18; - break; - case slot_arg_94: - object = YKPIV_OBJ_RETIRED19; - break; - case slot_arg_95: - object = YKPIV_OBJ_RETIRED20; - break; - case slot_arg_f9: - object = YKPIV_OBJ_ATTESTATION; - break; - case slot__NULL: - default: - object = 0; - } - return object; -} - -int key_to_object_id(int key) { - int object; - - switch(key) { - case YKPIV_KEY_AUTHENTICATION: - object = YKPIV_OBJ_AUTHENTICATION; - break; - case YKPIV_KEY_CARDMGM: - object = YKPIV_OBJ_SIGNATURE; - break; - case YKPIV_KEY_KEYMGM: - object = YKPIV_OBJ_KEY_MANAGEMENT; - break; - case YKPIV_KEY_CARDAUTH: - object = YKPIV_OBJ_CARD_AUTH; - break; - case YKPIV_KEY_RETIRED1: - object = YKPIV_OBJ_RETIRED1; - break; - case YKPIV_KEY_RETIRED2: - object = YKPIV_OBJ_RETIRED2; - break; - case YKPIV_KEY_RETIRED3: - object = YKPIV_OBJ_RETIRED3; - break; - case YKPIV_KEY_RETIRED4: - object = YKPIV_OBJ_RETIRED4; - break; - case YKPIV_KEY_RETIRED5: - object = YKPIV_OBJ_RETIRED5; - break; - case YKPIV_KEY_RETIRED6: - object = YKPIV_OBJ_RETIRED6; - break; - case YKPIV_KEY_RETIRED7: - object = YKPIV_OBJ_RETIRED7; - break; - case YKPIV_KEY_RETIRED8: - object = YKPIV_OBJ_RETIRED8; - break; - case YKPIV_KEY_RETIRED9: - object = YKPIV_OBJ_RETIRED9; - break; - case YKPIV_KEY_RETIRED10: - object = YKPIV_OBJ_RETIRED10; - break; - case YKPIV_KEY_RETIRED11: - object = YKPIV_OBJ_RETIRED11; - break; - case YKPIV_KEY_RETIRED12: - object = YKPIV_OBJ_RETIRED12; - break; - case YKPIV_KEY_RETIRED13: - object = YKPIV_OBJ_RETIRED13; - break; - case YKPIV_KEY_RETIRED14: - object = YKPIV_OBJ_RETIRED14; - break; - case YKPIV_KEY_RETIRED15: - object = YKPIV_OBJ_RETIRED15; - break; - case YKPIV_KEY_RETIRED16: - object = YKPIV_OBJ_RETIRED16; - break; - case YKPIV_KEY_RETIRED17: - object = YKPIV_OBJ_RETIRED17; - break; - case YKPIV_KEY_RETIRED18: - object = YKPIV_OBJ_RETIRED18; - break; - case YKPIV_KEY_RETIRED19: - object = YKPIV_OBJ_RETIRED19; - break; - case YKPIV_KEY_RETIRED20: - object = YKPIV_OBJ_RETIRED20; - break; - default: - object = 0; - } - return object; -} - bool set_component(unsigned char *in_ptr, const BIGNUM *bn, int element_len) { int real_len = BN_num_bytes(bn); diff --git a/tool/util.h b/tool/util.h index a1f15b5..f1eb6ac 100644 --- a/tool/util.h +++ b/tool/util.h @@ -48,8 +48,6 @@ X509_NAME *parse_name(const char*); unsigned char get_algorithm(EVP_PKEY*); FILE *open_file(const char*, int); int get_slot_hex(enum enum_slot slot_enum); -int get_object_id(enum enum_slot slot); -int key_to_object_id(int key); bool set_component(unsigned char *in_ptr, const BIGNUM *bn, int element_len); bool prepare_rsa_signature(const unsigned char*, unsigned int, unsigned char*, unsigned int*, int); diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index b1bfd09..9b59d99 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -97,7 +97,7 @@ static bool sign_data(ykpiv_state *state, const unsigned char *in, size_t len, u return false; } -static bool generate_key(ykpiv_state *state, const char *slot, +static bool generate_key(ykpiv_state *state, enum enum_slot slot, enum enum_algorithm algorithm, const char *output_file_name, enum enum_key_format key_format, enum enum_pin_policy pin_policy, enum enum_touch_policy touch_policy) { @@ -133,7 +133,7 @@ static bool generate_key(ykpiv_state *state, const char *slot, } } - sscanf(slot, "%2x", &key); + key = get_slot_hex(slot); output_file = open_file(output_file_name, OUTPUT); if(!output_file) { @@ -252,7 +252,7 @@ static bool set_pin_retries(ykpiv_state *state, int pin_retries, int puk_retries } static bool import_key(ykpiv_state *state, enum enum_key_format key_format, - const char *input_file_name, const char *slot, char *password, + const char *input_file_name, enum enum_slot slot, char *password, enum enum_pin_policy pin_policy, enum enum_touch_policy touch_policy) { int key = 0; FILE *input_file = NULL; @@ -262,7 +262,7 @@ static bool import_key(ykpiv_state *state, enum enum_key_format key_format, bool ret = false; ykpiv_rc rc = YKPIV_GENERIC_ERROR; - sscanf(slot, "%2x", &key); + key = get_slot_hex(slot); input_file = open_file(input_file_name, INPUT); if(!input_file) { @@ -537,7 +537,7 @@ static bool set_cardid(ykpiv_state *state, int verbose, int type) { } static bool request_certificate(ykpiv_state *state, enum enum_key_format key_format, - const char *input_file_name, const char *slot, char *subject, enum enum_hash hash, + const char *input_file_name, enum enum_slot slot, char *subject, enum enum_hash hash, const char *output_file_name) { X509_REQ *req = NULL; X509_NAME *name = NULL; @@ -561,7 +561,7 @@ static bool request_certificate(ykpiv_state *state, enum enum_key_format key_for null_parameter.type = V_ASN1_NULL; null_parameter.value.ptr = NULL; - sscanf(slot, "%2x", &key); + key = get_slot_hex(slot); input_file = open_file(input_file_name, INPUT); output_file = open_file(output_file_name, OUTPUT); @@ -684,7 +684,7 @@ request_out: } static bool selfsign_certificate(ykpiv_state *state, enum enum_key_format key_format, - const char *input_file_name, const char *slot, char *subject, enum enum_hash hash, + const char *input_file_name, enum enum_slot slot, char *subject, enum enum_hash hash, const int *serial, int validDays, const char *output_file_name) { FILE *input_file = NULL; FILE *output_file = NULL; @@ -710,7 +710,7 @@ static bool selfsign_certificate(ykpiv_state *state, enum enum_key_format key_fo null_parameter.type = V_ASN1_NULL; null_parameter.value.ptr = NULL; - sscanf(slot, "%2x", &key); + key = get_slot_hex(slot); input_file = open_file(input_file_name, INPUT); output_file = open_file(output_file_name, OUTPUT); @@ -1028,7 +1028,7 @@ read_cert_out: } static bool sign_file(ykpiv_state *state, const char *input, const char *output, - const char *slot, enum enum_algorithm algorithm, enum enum_hash hash, + enum enum_slot slot, enum enum_algorithm algorithm, enum enum_hash hash, int verbosity) { FILE *input_file = NULL; FILE *output_file = NULL; @@ -1039,7 +1039,7 @@ static bool sign_file(ykpiv_state *state, const char *input, const char *output, int algo; const EVP_MD *md; - sscanf(slot, "%2x", &key); + key = get_slot_hex(slot); input_file = open_file(input, INPUT); if(!input_file) { @@ -1121,7 +1121,7 @@ out: static void print_cert_info(ykpiv_state *state, enum enum_slot slot, const EVP_MD *md, FILE *output) { - int object = get_object_id(slot); + int object = ykpiv_util_slot_object(get_slot_hex(slot)); int slot_name; unsigned char data[3072]; const unsigned char *ptr = data; @@ -1349,7 +1349,7 @@ static bool test_signature(ykpiv_state *state, enum enum_slot slot, if(algorithm == 0) { goto test_out; } - sscanf(cmdline_parser_slot_values[slot], "%2x", &key); + key = get_slot_hex(slot); if(YKPIV_IS_RSA(algorithm)) { prepare_rsa_signature(data, data_len, encoded, &enc_len, EVP_MD_type(md)); ptr = encoded; @@ -1454,7 +1454,7 @@ static bool test_decipher(ykpiv_state *state, enum enum_slot slot, if(algorithm == 0) { goto decipher_out; } - sscanf(cmdline_parser_slot_values[slot], "%2x", &key); + key = get_slot_hex(slot); if(YKPIV_IS_RSA(algorithm)) { unsigned char secret[32]; unsigned char secret2[32]; @@ -1566,7 +1566,7 @@ static bool list_readers(ykpiv_state *state) { return true; } -static bool attest(ykpiv_state *state, const char *slot, +static bool attest(ykpiv_state *state, enum enum_slot slot, enum enum_key_format key_format, const char *output_file_name) { unsigned char data[YKPIV_OBJ_MAX_SIZE]; unsigned long len = sizeof(data); @@ -1583,7 +1583,7 @@ static bool attest(ykpiv_state *state, const char *slot, return false; } - sscanf(slot, "%2x", &key); + key = get_slot_hex(slot); if (ykpiv_attest(state, key, data, &len) != YKPIV_OK) { fprintf(stderr, "Failed to attest data.\n"); goto attest_out; @@ -1866,7 +1866,7 @@ int main(int argc, char *argv[]) { print_version(state, args_info.output_arg); break; case action_arg_generate: - if(generate_key(state, args_info.slot_orig, args_info.algorithm_arg, args_info.output_arg, args_info.key_format_arg, + if(generate_key(state, args_info.slot_arg, args_info.algorithm_arg, args_info.output_arg, args_info.key_format_arg, args_info.pin_policy_arg, args_info.touch_policy_arg) == false) { ret = EXIT_FAILURE; } else { @@ -1921,7 +1921,7 @@ int main(int argc, char *argv[]) { } break; case action_arg_importMINUS_key: - if(import_key(state, args_info.key_format_arg, args_info.input_arg, args_info.slot_orig, password, + if(import_key(state, args_info.key_format_arg, args_info.input_arg, args_info.slot_arg, password, args_info.pin_policy_arg, args_info.touch_policy_arg) == false) { fprintf(stderr, "Unable to import private key\n"); ret = EXIT_FAILURE; @@ -1946,7 +1946,7 @@ int main(int argc, char *argv[]) { break; case action_arg_requestMINUS_certificate: if(request_certificate(state, args_info.key_format_arg, args_info.input_arg, - args_info.slot_orig, args_info.subject_arg, args_info.hash_arg, + args_info.slot_arg, args_info.subject_arg, args_info.hash_arg, args_info.output_arg) == false) { ret = EXIT_FAILURE; } else { @@ -2006,7 +2006,7 @@ int main(int argc, char *argv[]) { } case action_arg_selfsignMINUS_certificate: if(selfsign_certificate(state, args_info.key_format_arg, args_info.input_arg, - args_info.slot_orig, args_info.subject_arg, args_info.hash_arg, + args_info.slot_arg, args_info.subject_arg, args_info.hash_arg, args_info.serial_given ? &args_info.serial_arg : NULL, args_info.valid_days_arg, args_info.output_arg) == false) { ret = EXIT_FAILURE; @@ -2060,7 +2060,7 @@ int main(int argc, char *argv[]) { } break; case action_arg_attest: - if(attest(state, args_info.slot_orig, args_info.key_format_arg, + if(attest(state, args_info.slot_arg, args_info.key_format_arg, args_info.output_arg) == false) { ret = EXIT_FAILURE; } @@ -2081,7 +2081,7 @@ int main(int argc, char *argv[]) { ret = EXIT_FAILURE; } else if(sign_file(state, args_info.input_arg, args_info.output_arg, - args_info.slot_orig, args_info.algorithm_arg, args_info.hash_arg, + args_info.slot_arg, args_info.algorithm_arg, args_info.hash_arg, verbosity)) { fprintf(stderr, "Signature successful!\n"); } else { diff --git a/ykcs11/token_vendors.c b/ykcs11/token_vendors.c index 596d31c..395b7fe 100644 --- a/ykcs11/token_vendors.c +++ b/ykcs11/token_vendors.c @@ -196,7 +196,7 @@ static CK_RV COMMON_token_generate_key(ykpiv_state *state, CK_BBOOL rsa, *certptr++ = 0; // Store the certificate into the token - if (ykpiv_save_object(state, key_to_object_id(key), data, (size_t)(certptr - data)) != YKPIV_OK) + if (ykpiv_save_object(state, ykpiv_util_slot_object(key), data, (size_t)(certptr - data)) != YKPIV_OK) return CKR_DEVICE_ERROR; return CKR_OK; From 5291bc4a631a672497e728b3eed61ca2567fcaef Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 26 Sep 2017 14:55:02 +0200 Subject: [PATCH 26/57] Fix issue #123 - specify text/binary mode for open files --- tool/util.c | 25 +++++++++++++++--- tool/util.h | 10 ++++--- tool/yubico-piv-tool.c | 60 ++++++++++++++++++++++++++++++------------ 3 files changed, 72 insertions(+), 23 deletions(-) diff --git a/tool/util.c b/tool/util.c index 0284ef2..eee4b7e 100644 --- a/tool/util.c +++ b/tool/util.c @@ -46,12 +46,31 @@ #include "cmdline.h" #include "util.h" -FILE *open_file(const char *file_name, int mode) { +FILE *open_file(const char *file_name, enum file_mode mode) { FILE *file; + const char *mod; if(!strcmp(file_name, "-")) { - file = mode == INPUT ? stdin : stdout; + file = (mode == INPUT_TEXT || mode == INPUT_BIN) ? stdin : stdout; } else { - file = fopen(file_name, mode == INPUT ? "r" : "w"); + switch (mode) { + case INPUT_TEXT: + mod = "r"; + break; + case INPUT_BIN: + mod = "rb"; + break; + case OUTPUT_TEXT: + mod = "w"; + break; + case OUTPUT_BIN: + mod = "wb"; + break; + default: + fprintf(stderr, "Invalid file mode.\n"); + return NULL; + break; + } + file = fopen(file_name, mod); if(!file) { fprintf(stderr, "Failed opening '%s'!\n", file_name); return NULL; diff --git a/tool/util.h b/tool/util.h index f1eb6ac..f8820ec 100644 --- a/tool/util.h +++ b/tool/util.h @@ -37,8 +37,12 @@ #include "cmdline.h" -#define INPUT 1 -#define OUTPUT 2 +enum file_mode { + INPUT_TEXT, + OUTPUT_TEXT, + INPUT_BIN, + OUTPUT_BIN, +}; size_t read_data(unsigned char*, size_t, FILE*, enum enum_format); void dump_data(unsigned const char*, unsigned int, FILE*, bool, enum enum_format); @@ -46,7 +50,7 @@ int set_length(unsigned char*, int); int get_length(const unsigned char*, int*); X509_NAME *parse_name(const char*); unsigned char get_algorithm(EVP_PKEY*); -FILE *open_file(const char*, int); +FILE *open_file(const char *file_name, enum file_mode mode); int get_slot_hex(enum enum_slot slot_enum); bool set_component(unsigned char *in_ptr, const BIGNUM *bn, int element_len); bool prepare_rsa_signature(const unsigned char*, unsigned int, unsigned char*, diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index 9b59d99..11a9d71 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -60,9 +60,35 @@ #define KEY_LEN 24 +static enum file_mode key_file_mode(enum enum_key_format fmt, bool output) { + if (fmt == key_format_arg_PEM) { + if (output) { + return OUTPUT_TEXT; + } + return INPUT_TEXT; + } + if (output) { + return OUTPUT_BIN; + } + return INPUT_BIN; +} + +static enum file_mode data_file_mode(enum enum_format fmt, bool output) { + if (fmt == format_arg_binary) { + if (output) { + return OUTPUT_BIN; + } + return INPUT_BIN; + } + if (output) { + return OUTPUT_TEXT; + } + return INPUT_TEXT; +} + static void print_version(ykpiv_state *state, const char *output_file_name) { char version[7]; - FILE *output_file = open_file(output_file_name, OUTPUT); + FILE *output_file = open_file(output_file_name, OUTPUT_TEXT); if(!output_file) { return; } @@ -135,7 +161,7 @@ static bool generate_key(ykpiv_state *state, enum enum_slot slot, key = get_slot_hex(slot); - output_file = open_file(output_file_name, OUTPUT); + output_file = open_file(output_file_name, key_file_mode(key_format, true)); if(!output_file) { return false; } @@ -264,7 +290,7 @@ static bool import_key(ykpiv_state *state, enum enum_key_format key_format, key = get_slot_hex(slot); - input_file = open_file(input_file_name, INPUT); + input_file = open_file(input_file_name, key_file_mode(key_format, false)); if(!input_file) { return false; } @@ -427,7 +453,7 @@ static bool import_cert(ykpiv_state *state, enum enum_key_format cert_format, int compress = 0; int cert_len = -1; - input_file = open_file(input_file_name, INPUT); + input_file = open_file(input_file_name, key_file_mode(cert_format, false)); if(!input_file) { return false; } @@ -563,8 +589,8 @@ static bool request_certificate(ykpiv_state *state, enum enum_key_format key_for key = get_slot_hex(slot); - input_file = open_file(input_file_name, INPUT); - output_file = open_file(output_file_name, OUTPUT); + input_file = open_file(input_file_name, key_file_mode(key_format, false)); + output_file = open_file(output_file_name, key_file_mode(key_format, true)); if(!input_file || !output_file) { goto request_out; } @@ -712,8 +738,8 @@ static bool selfsign_certificate(ykpiv_state *state, enum enum_key_format key_fo key = get_slot_hex(slot); - input_file = open_file(input_file_name, INPUT); - output_file = open_file(output_file_name, OUTPUT); + input_file = open_file(input_file_name, key_file_mode(key_format, false)); + output_file = open_file(output_file_name, key_file_mode(key_format, true)); if(!input_file || !output_file) { goto selfsign_out; } @@ -973,7 +999,7 @@ static bool read_certificate(ykpiv_state *state, enum enum_slot slot, return false; } - output_file = open_file(output_file_name, OUTPUT); + output_file = open_file(output_file_name, key_file_mode(key_format, true)); if (!output_file) { return false; } @@ -1041,7 +1067,7 @@ static bool sign_file(ykpiv_state *state, const char *input, const char *output, key = get_slot_hex(slot); - input_file = open_file(input, INPUT); + input_file = open_file(input, INPUT_BIN); if(!input_file) { return false; } @@ -1050,7 +1076,7 @@ static bool sign_file(ykpiv_state *state, const char *input, const char *output, fprintf(stderr, "Please paste the input...\n"); } - output_file = open_file(output, OUTPUT); + output_file = open_file(output, OUTPUT_BIN); if(!output_file) { if(input_file && input_file != stdin) { fclose(input_file); @@ -1231,7 +1257,7 @@ static bool status(ykpiv_state *state, enum enum_hash hash, unsigned char buf[3072]; long unsigned len = sizeof(buf); int i; - FILE *output_file = open_file(output_file_name, OUTPUT); + FILE *output_file = open_file(output_file_name, OUTPUT_TEXT); if(!output_file) { return false; } @@ -1284,7 +1310,7 @@ static bool test_signature(ykpiv_state *state, enum enum_slot slot, unsigned int data_len; X509 *x509 = NULL; EVP_PKEY *pubkey; - FILE *input_file = open_file(input_file_name, INPUT); + FILE *input_file = open_file(input_file_name, key_file_mode(cert_format, false)); if(!input_file) { fprintf(stderr, "Failed opening input file %s.\n", input_file_name); @@ -1417,7 +1443,7 @@ static bool test_decipher(ykpiv_state *state, enum enum_slot slot, X509 *x509 = NULL; EVP_PKEY *pubkey; EC_KEY *tmpkey = NULL; - FILE *input_file = open_file(input_file_name, INPUT); + FILE *input_file = open_file(input_file_name, key_file_mode(cert_format, false)); if(!input_file) { fprintf(stderr, "Failed opening input file %s.\n", input_file_name); @@ -1573,7 +1599,7 @@ static bool attest(ykpiv_state *state, enum enum_slot slot, bool ret = false; X509 *x509 = NULL; int key; - FILE *output_file = open_file(output_file_name, OUTPUT); + FILE *output_file = open_file(output_file_name, key_file_mode(key_format, true)); if(!output_file) { return false; } @@ -1626,7 +1652,7 @@ static bool write_object(ykpiv_state *state, int id, size_t len = sizeof(data); ykpiv_rc res; - input_file = open_file(input_file_name, INPUT); + input_file = open_file(input_file_name, data_file_mode(format, false)); if(!input_file) { return false; } @@ -1665,7 +1691,7 @@ static bool read_object(ykpiv_state *state, int id, const char *output_file_name unsigned long len = sizeof(data); bool ret = false; - output_file = open_file(output_file_name, OUTPUT); + output_file = open_file(output_file_name, data_file_mode(format, true)); if(!output_file) { return false; } From 90209997cc78eabdd2acc15fdf2458db2d3095e4 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 26 Sep 2017 16:05:39 +0200 Subject: [PATCH 27/57] Unit test for ykpiv_attest() --- lib/tests/util.c | 18 +++++++++++++++++- tool/yubico-piv-tool.c | 2 +- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/lib/tests/util.c b/lib/tests/util.c index 8b103c9..305a086 100644 --- a/lib/tests/util.c +++ b/lib/tests/util.c @@ -404,6 +404,14 @@ START_TEST(test_import_key) { ck_assert_int_eq(memcmp(secret, secret2, sizeof(secret)), 0); X509_free(cert); } + + // Verify that imported key can not be attested + { + unsigned char attest[2048]; + size_t attest_len = sizeof(attest); + res = ykpiv_attest(g_state, 0x9e, attest, &attest_len); + ck_assert_int_eq(res, YKPIV_GENERIC_ERROR); + } } END_TEST @@ -429,7 +437,15 @@ START_TEST(test_generate_key) { ck_assert_int_eq(res, YKPIV_OK); res = ykpiv_util_free(g_state, exp); ck_assert_int_eq(res, YKPIV_OK); - // TODO: and?? + + // Verify that imported key can be attested + { + unsigned char attest[2048]; + size_t attest_len = sizeof(attest); + res = ykpiv_attest(g_state, YKPIV_KEY_AUTHENTICATION, attest, &attest_len); + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_int_gt(attest_len, 0); + } } END_TEST diff --git a/tool/yubico-piv-tool.c b/tool/yubico-piv-tool.c index 11a9d71..37f6c2d 100644 --- a/tool/yubico-piv-tool.c +++ b/tool/yubico-piv-tool.c @@ -1594,7 +1594,7 @@ static bool list_readers(ykpiv_state *state) { static bool attest(ykpiv_state *state, enum enum_slot slot, enum enum_key_format key_format, const char *output_file_name) { - unsigned char data[YKPIV_OBJ_MAX_SIZE]; + unsigned char data[2048]; unsigned long len = sizeof(data); bool ret = false; X509 *x509 = NULL; From 9a7ccf48fa8dc00ec31191fb4e7e6ebd28d9570a Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Wed, 27 Sep 2017 11:28:39 +0200 Subject: [PATCH 28/57] Fix all clang scan-build warnings --- lib/internal.c | 6 ++++-- tool/util.c | 4 +++- ykcs11/openssl_utils.c | 2 +- ykcs11/utils.c | 2 -- ykcs11/ykcs11.c | 6 ++++++ ykcs11/yubico_slot.c | 6 +++--- ykcs11/yubico_token.c | 2 +- 7 files changed, 18 insertions(+), 10 deletions(-) diff --git a/lib/internal.c b/lib/internal.c index 30e5601..969adce 100644 --- a/lib/internal.c +++ b/lib/internal.c @@ -222,8 +222,10 @@ EXIT: return rc; ERROR_EXIT: - des_destroy_key(*key); - *key = NULL; + if (key) { + des_destroy_key(*key); + *key = NULL; + } goto EXIT; diff --git a/tool/util.c b/tool/util.c index eee4b7e..d3f88cd 100644 --- a/tool/util.c +++ b/tool/util.c @@ -543,7 +543,9 @@ int SSH_write_X509(FILE *fp, X509 *x) { rsa = EVP_PKEY_get1_RSA(pkey); - set_component(n, rsa->n, RSA_size(rsa)); + if (!set_component(n, rsa->n, RSA_size(rsa))) { + break; + } uint32_t bytes = BN_num_bytes(rsa->n); char len_buf[5]; diff --git a/ykcs11/openssl_utils.c b/ykcs11/openssl_utils.c index 4ceb704..a53ff6f 100644 --- a/ykcs11/openssl_utils.c +++ b/ykcs11/openssl_utils.c @@ -173,7 +173,7 @@ CK_RV do_create_empty_cert(CK_BYTE_PTR in, CK_ULONG in_len, CK_BBOOL is_rsa, // Manually set a signature (same reason as before) ASN1_BIT_STRING_set_bit(cert->signature, 8, 1); - ASN1_BIT_STRING_set(cert->signature, "\x00", 1); + ASN1_BIT_STRING_set(cert->signature, (unsigned char*)"\x00", 1); len = i2d_X509(cert, NULL); if (len < 0) diff --git a/ykcs11/utils.c b/ykcs11/utils.c index f66d995..fd9867a 100644 --- a/ykcs11/utils.c +++ b/ykcs11/utils.c @@ -258,8 +258,6 @@ void strip_DER_encoding_from_ECSIG(CK_BYTE_PTR data, CK_ULONG_PTR len) { data_ptr++; memcpy(buf_ptr, data_ptr, elem_len); - data_ptr += elem_len; - buf_ptr += elem_len; *len = sig_halflen * 2; memcpy(data, buf, *len); diff --git a/ykcs11/ykcs11.c b/ykcs11/ykcs11.c index 8374ec6..f0ec934 100644 --- a/ykcs11/ykcs11.c +++ b/ykcs11/ykcs11.c @@ -215,6 +215,11 @@ CK_DEFINE_FUNCTION(CK_RV, C_GetSlotList)( return CKR_OK; } + if (!pulCount) { + DOUT; + return CKR_ARGUMENTS_BAD; + } + if ((tokenPresent && *pulCount < n_slots_with_token) || (!tokenPresent && *pulCount < n_slots)) { DBG("Buffer too small: needed %lu, provided %lu", n_slots, *pulCount); return CKR_BUFFER_TOO_SMALL; @@ -1214,6 +1219,7 @@ CK_DEFINE_FUNCTION(CK_RV, C_DestroyObject)( rv = delete_cert(cert_id); if (rv != CKR_OK) { + free(obj_ptr); DBG("Unable to delete certificate data"); return CKR_FUNCTION_FAILED; } diff --git a/ykcs11/yubico_slot.c b/ykcs11/yubico_slot.c index 9db257a..f53787a 100644 --- a/ykcs11/yubico_slot.c +++ b/ykcs11/yubico_slot.c @@ -32,16 +32,16 @@ #include "pkcs11.h" #include -static const CK_UTF8CHAR_PTR slot_manufacturer = "Yubico"; +static const CK_UTF8CHAR_PTR slot_manufacturer = (const CK_UTF8CHAR_PTR)"Yubico"; static const CK_FLAGS slot_flags = CKF_TOKEN_PRESENT | CKF_HW_SLOT; static const CK_VERSION slot_version = {1, 0}; CK_RV YUBICO_get_slot_manufacturer(CK_UTF8CHAR_PTR str, CK_ULONG len) { - if (strlen(slot_manufacturer) > len) + if (strlen((const char*)slot_manufacturer) > len) return CKR_BUFFER_TOO_SMALL; - memcpy(str, slot_manufacturer, strlen(slot_manufacturer)); + memcpy(str, slot_manufacturer, strlen((const char*)slot_manufacturer)); return CKR_OK; } diff --git a/ykcs11/yubico_token.c b/ykcs11/yubico_token.c index e30e789..30d583d 100644 --- a/ykcs11/yubico_token.c +++ b/ykcs11/yubico_token.c @@ -372,7 +372,7 @@ CK_RV YUBICO_token_change_pin(ykpiv_state *state, CK_USER_TYPE user_type, CK_UTF DBG("TODO implement other users pin change"); return CKR_FUNCTION_FAILED; } - res = ykpiv_change_pin(state, pOldPin, ulOldLen, pNewPin, ulNewLen, &tries); + res = ykpiv_change_pin(state, (const char*)pOldPin, ulOldLen, (const char*)pNewPin, ulNewLen, &tries); switch (res) { case YKPIV_OK: return CKR_OK; From ef81054dc25b0ee99f2df9a75deb9a638a088e72 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Thu, 28 Sep 2017 15:31:33 +0200 Subject: [PATCH 29/57] Add automated tests for yubico-piv-tool CLI (hw-tests only) --- tool/tests/basic.sh | 118 +++++++++++++++++++++++++++++++++++++++-- tool/tests/cert.pem | 22 ++++++++ tool/tests/private.pem | 27 ++++++++++ tool/tests/public.pem | 9 ++++ 4 files changed, 171 insertions(+), 5 deletions(-) create mode 100644 tool/tests/cert.pem create mode 100644 tool/tests/private.pem create mode 100644 tool/tests/public.pem diff --git a/tool/tests/basic.sh b/tool/tests/basic.sh index 48f642b..b62d810 100755 --- a/tool/tests/basic.sh +++ b/tool/tests/basic.sh @@ -1,20 +1,20 @@ -#!/bin/sh +#!/bin/bash # Copyright (c) 2014-2016 Yubico AB # All rights reserved. -# +# # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: -# +# # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. -# +# # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. -# +# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR @@ -33,6 +33,7 @@ set -e BIN="../yubico-piv-tool${EXEEXT}" +ROOT_MAKEFILE="../../Makefile" HELP_OUTPUT=$($BIN --help) @@ -42,3 +43,110 @@ if [ "x$VERSION_OUTPUT" != "x$expected" ]; then echo "Version ($VERSION_OUTPUT) not matching expected output $expected." exit 1 fi + + +################################################################################ +################################################################################ +# HARDWARE TESTS +################################################################################ +################################################################################ +# +# Tests below here require a Yubikey to be connected. +# These tests are destructive. +# +################################################################################ +################################################################################ + +# Verify that --enable-hardware-tests was a build flag. +! $(set -e && cat "$ROOT_MAKEFILE" |grep "^DEFS =" | grep -- "-DHW_TESTS" >/dev/null) +HW_TESTS=$? +if [[ $HW_TESTS -eq 0 ]]; then + exit 0 +fi + + +# +# Run basic import/validation tests on included keys/certs. Test keys generated +# with the following commands: +# +# $ openssl genrsa -out private.pem 2048 +# $ openssl rsa -in private.pem -outform PEM -pubout -out public.pem +# $ openssl req -x509 -key private.pem -out cert.pem -subj "/CN=YubicoTest/OU=YubicoTestUnit/O=yubico.com/" -new +# +echo >&0 +echo "Hardware tests enabled!" >&0 +echo >&0 +echo "******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******" >&0 +echo "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING" >&0 +echo "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING" >&0 +echo >&0 +echo "******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******" >&0 +echo >&0 +echo " ALL DATA WILL BE ERASED ON CONNECTED YUBIKEYS " >&0 +echo >&0 +echo "******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******" >&0 +echo >&0 +echo "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING" >&0 +echo "WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING" >&0 +echo "******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* ******* *******" >&0 +echo >&0 +echo -n "Are you SURE you wish to proceed? If so, type 'CONFIRM': " >&0 + +read CONFIRM +if [[ "x$CONFIRM" != "xCONFIRM" ]]; then + exit 1 +fi + +# Reset +$BIN -averify-pin -P000000 || true +$BIN -averify-pin -P000000 || true +$BIN -averify-pin -P000000 || true +$BIN -achange-puk -P000000 -N00000000 || true +$BIN -achange-puk -P000000 -N00000000 || true +$BIN -achange-puk -P000000 -N00000000 || true +$BIN -areset + +# Generate key on-board, issue certificate, and verify it +$BIN -agenerate -s9a -AECCP384 -o key_9a.pub +$BIN -averify -P123456 -s9a -S'/CN=YubicoTest/OU=YubicoGenerated/O=yubico.com/' -aselfsign -i key_9a.pub -o cert_9a.pem +$BIN -averify -P123456 -s9a -atest-signature -i cert_9a.pem +$BIN -aimport-certificate -P123456 -s9a -i cert_9a.pem + +# Import key, generate self-signed certificate, and verify it +$BIN -aimport-key -P123456 -s9e -iprivate.pem +$BIN -arequest-certificate -s9e -S"/CN=bar/OU=test/O=example.com/" -i public.pem -o req_9e.pem +$BIN -averify -P123456 -s9e -S'/CN=bar/OU=test/O=example.com/' -aselfsign -i public.pem -o cert_9e.pem +$BIN -atest-decipher -s9e -i cert_9e.pem +$BIN -aimport-certificate -P123456 -s9e -i cert.pem + + +# Read status and validate fields +STATUS=$($BIN -astatus) +echo "$STATUS" +ALGO_9A=$(echo "$STATUS" |grep "Slot 9a" -A 6 |grep "Algorithm" |tr -d "[:blank:]") +if [[ "x$ALGO_9A" != "xAlgorithm:ECCP384" ]]; then + echo "$ALGO_9A" + echo "Generated algorithm incorrect." >/dev/stderr + exit 1 +fi + +ALGO_9E=$(echo "$STATUS" |grep "Slot 9e" -A 6 |grep "Algorithm" |tr -d "[:blank:]") +if [[ "x$ALGO_9E" != "xAlgorithm:RSA2048" ]]; then + echo "$ALGO_9E" + echo "Generated algorithm incorrect." >/dev/stderr + exit 1 +fi + +SUBJECT_9A=$(echo "$STATUS" |grep "Slot 9a" -A 6 |grep "Subject DN" |tr -d "[:blank:]") +if [[ "x$SUBJECT_9A" != "xSubjectDN:CN=YubicoTest,OU=YubicoGenerated,O=yubico.com" ]]; then + echo "$SUBJECT_9A" + echo "Certificate subject incorrect." >/dev/stderr + exit 1 +fi + +SUBJECT_9E=$(echo "$STATUS" |grep "Slot 9e" -A 6 |grep "Subject DN" |tr -d "[:blank:]") +if [[ "x$SUBJECT_9E" != "xSubjectDN:CN=YubicoTest,OU=YubicoTestUnit,O=yubico.com" ]]; then + echo "$SUBJECT_9E" + echo "Certificate subject incorrect." >/dev/stderr + exit 1 +fi diff --git a/tool/tests/cert.pem b/tool/tests/cert.pem new file mode 100644 index 0000000..97822cc --- /dev/null +++ b/tool/tests/cert.pem @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDrzCCApegAwIBAgIJAM1blQIJfeuCMA0GCSqGSIb3DQEBBQUAMEMxEzARBgNV +BAMTCll1Ymljb1Rlc3QxFzAVBgNVBAsTDll1Ymljb1Rlc3RVbml0MRMwEQYDVQQK +Ewp5dWJpY28uY29tMB4XDTE3MDkyNzEzMzYxNFoXDTE3MTAyNzEzMzYxNFowQzET +MBEGA1UEAxMKWXViaWNvVGVzdDEXMBUGA1UECxMOWXViaWNvVGVzdFVuaXQxEzAR +BgNVBAoTCnl1Ymljby5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB +AQDKRTcyy2rVuV6cex5GdRT3VWntbqVPC4p6BcATEAeSXDgORaWhQOnv7WF9a8Rc +bsWH0j807f+CvqirtFZHbSBsMYlxyko4Mer/gxb2uqy08B4fWeOxeTpNNQ63gfHZ +g4tqnDmFulAiZilVnuiimAdC0iLliXaowkFEcPFGPEmjV/lWTgalgFOe/utySbVs +vUp2EjeBDcOdUqc1oHH1GVoMRKMm7PTT9/8SVawVUneCqOFCNNxyW7PjRpTr5qPq +1ucMOmz2UIPwJVHIQEbL5IL3NtkozmbZ0G9cqnRrYSXGmlBrdcq5fH7qrMcifIMW +QXVinhzbIcrRpW0Vm653efxDAgMBAAGjgaUwgaIwHQYDVR0OBBYEFKEF2ASXCBPt ++4Wh0o36Ee6+HvRRMHMGA1UdIwRsMGqAFKEF2ASXCBPt+4Wh0o36Ee6+HvRRoUek +RTBDMRMwEQYDVQQDEwpZdWJpY29UZXN0MRcwFQYDVQQLEw5ZdWJpY29UZXN0VW5p +dDETMBEGA1UEChMKeXViaWNvLmNvbYIJAM1blQIJfeuCMAwGA1UdEwQFMAMBAf8w +DQYJKoZIhvcNAQEFBQADggEBADaeHhj7vjZ8OGIAOd86UAqJrqyQ6Lhu133pBRoV +4qQprZFRXxsxVyAqKDAWMF/GTidMRlVRAQNnR9kHYuG7zpy+NjlK2khAEflAa6Z5 +nGMntv0+y7NLkKGAAk9qxqpNwj90VzFcvopDFA70FVnWtgkuJuFf5n+fHTUMOzTk +p6+BMRUjJqu7weK+QUI8b9zl7pSzWbcHqxyrJSNRW87xvEQhyJzFqbqQprYGheZk +py5wUX22HBhAuw7cvakeUMIX133UJI7Yxwy5DKoiqsESKGr/oXIU3+M0kqzDwQCA +HI1y9cIY/3Zi3Y7HgQnHX2Oos3k2SY0VpYtO47Ja/oIkolc= +-----END CERTIFICATE----- diff --git a/tool/tests/private.pem b/tool/tests/private.pem new file mode 100644 index 0000000..2381b5a --- /dev/null +++ b/tool/tests/private.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEpQIBAAKCAQEAykU3Mstq1blenHseRnUU91Vp7W6lTwuKegXAExAHklw4DkWl +oUDp7+1hfWvEXG7Fh9I/NO3/gr6oq7RWR20gbDGJccpKODHq/4MW9rqstPAeH1nj +sXk6TTUOt4Hx2YOLapw5hbpQImYpVZ7oopgHQtIi5Yl2qMJBRHDxRjxJo1f5Vk4G +pYBTnv7rckm1bL1KdhI3gQ3DnVKnNaBx9RlaDESjJuz00/f/ElWsFVJ3gqjhQjTc +cluz40aU6+aj6tbnDDps9lCD8CVRyEBGy+SC9zbZKM5m2dBvXKp0a2ElxppQa3XK +uXx+6qzHInyDFkF1Yp4c2yHK0aVtFZuud3n8QwIDAQABAoIBAE1Q9c+Bt/2oFMUl +vqXZ/UCpsorif2felnkcF5ZxyyMkAv1Zm/0ujf17NIe3mOBoKzNGp4h47PEyJdE0 +ZsJ4sSsKKGqJk6M1WYl/t1hqdLfZDPqY5pMhLqryfASjNCobwT/oJYi7dgQgHu6u +hmgYSrY9Er/Ass3BKyeZMHDTfKZlvM8GZ/oF8bhkD1P/fi6xU1bhs1XCTQpkkING +eESbD5ZGMZU4HYusdmOmf2Y4LXqVZkag86Fw7XAg6b80FDR8Af6S9fzoPA7Aapmg +uvH19BHeSH/DiLTQ6d31GijSsx+rW/F5mrs5wldGO/htTJwRx0YoccUMPF2mMx+d +ShOlzckCgYEA9p9rT7kkj1ZglNB1gwo+IdbEZydlK3NvHmXMFa3IkmBg1nK1dpnM +0DK0Ycyb7LIuBN3sc2QV5+D3Yv8LspeTMBVajddts/dIJKQb51hRsC3PvQVUnaMD +3YYqDmZUlIv9bKfvAbOuNUOg4FXkaXFkkNNsLxv92bARKHPLo6eE7UcCgYEA0fYU +ImTKv9W8rpPcc7lf8Ffhw7mRrMTA/qFNSdJvjED9UXzH7Dp0abQ9nK8XxTWEl0oe +l0h+5H5YiV6Li8BXcWgnferbpi0Jwkdvh2Qc7LmJ/o278KLPKIqDItRd0gEgC9hR +H1M91Y1pNcv1Mj95hKx3L0ROXhwBAy4ohddjRyUCgYEAp8VFdEOHynbBVxsEhfNm +1xBKJb5YBZoOgohPsIO7SVCFL/1y0s7H1O5ZZZqSjA+eXLM30jvI5yhUQqUsKP8S +IwizxIBD4cSb8Ekvrk6Xq5lOk9DXgjFORNmrLIaSjUc6TDtlzSuVnCh4fYQQ0WZR +OnCJTPbm1rr+wR0c8CTauasCgYEAqie7eYQlrAITv4elCUQaNDWEiZJCNLnfjnw6 +nrEkJY4lvXxaqV9WKLQhmnFr2i7dHZ672+6sp5CdP/aXMNLYCthV6P4EtE+bsQ8j +m53OsypKYzmKLiJDsJ9QV1G0FxVCW1cbpz9WxVKtCSQZuncmjBcZH/1DZZFcYK9v +t8gudOECgYEAh3hlXVeMv2/oEW21G7D0s3Cv2vOSvBogdwVRP8EGOkn43rh5GXZm +7NVJjJNwURwLcowb0F4B/RILxArtjW2srUo1nbq5UoCiFNJ/00JoRSzAz1ad7S2o +0nRuVLQ50WYG/HBTP2M4yQbpP/E+5PCNMGx2kgyuTUyeCl+LEE8bg5k= +-----END RSA PRIVATE KEY----- diff --git a/tool/tests/public.pem b/tool/tests/public.pem new file mode 100644 index 0000000..abca1a8 --- /dev/null +++ b/tool/tests/public.pem @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAykU3Mstq1blenHseRnUU +91Vp7W6lTwuKegXAExAHklw4DkWloUDp7+1hfWvEXG7Fh9I/NO3/gr6oq7RWR20g +bDGJccpKODHq/4MW9rqstPAeH1njsXk6TTUOt4Hx2YOLapw5hbpQImYpVZ7oopgH +QtIi5Yl2qMJBRHDxRjxJo1f5Vk4GpYBTnv7rckm1bL1KdhI3gQ3DnVKnNaBx9Rla +DESjJuz00/f/ElWsFVJ3gqjhQjTccluz40aU6+aj6tbnDDps9lCD8CVRyEBGy+SC +9zbZKM5m2dBvXKp0a2ElxppQa3XKuXx+6qzHInyDFkF1Yp4c2yHK0aVtFZuud3n8 +QwIDAQAB +-----END PUBLIC KEY----- From f903a432e38e52e58d296676a5a4523b62cd63ea Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 10 Oct 2017 15:36:28 +0200 Subject: [PATCH 30/57] Backport minidriver changes * Port ykpiv_auth_getchallenge and ykpiv_auth_verifyresponse - Commit 8fde607b50b19c57a662c53c6b276b54a78606d8 - Commit 6046b98e477cfef59a590ce2177336d694813e7e - Commit 422cea11745dc67d15039e242ed21ecb5208ae55 - Commit 1d31647e5a27bd2df6bda76512c7d673980f0bec * Rename connect2() and done2() to connect_with_external_card(), etc. * Select applet in ykpiv_change_pin, change_puk, and unblock_pin --- lib/util.c | 4 ++ lib/ykpiv.c | 178 ++++++++++++++++++++++++++++++++++++++++++---------- lib/ykpiv.h | 6 +- 3 files changed, 151 insertions(+), 37 deletions(-) diff --git a/lib/util.c b/lib/util.c index fef1b24..c6d4686 100644 --- a/lib/util.c +++ b/lib/util.c @@ -795,6 +795,10 @@ ykpiv_rc ykpiv_util_generate_key(ykpiv_state *state, uint8_t slot, uint8_t algor } } } + else if (sw == SW_ERR_SECURITY_STATUS) { + res = YKPIV_AUTHENTICATION_ERROR; + if (state->verbose) { fprintf(stderr, "not authenticated)\n"); } + } else { res = YKPIV_GENERIC_ERROR; if (state->verbose) { fprintf(stderr, "error %x)\n", sw); } diff --git a/lib/ykpiv.c b/lib/ykpiv.c index c0b3f8a..f52598e 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -167,13 +167,22 @@ ykpiv_rc ykpiv_init(ykpiv_state **state, int verbose) { return ykpiv_init_with_allocator(state, verbose, &_default_allocator); } -ykpiv_rc ykpiv_done(ykpiv_state *state) { - ykpiv_disconnect(state); +static ykpiv_rc _done_internal(ykpiv_state *state, bool disconnect) { + if (disconnect) + ykpiv_disconnect(state); _cache_pin(state, NULL, 0); _ykpiv_free(state, state); return YKPIV_OK; } +ykpiv_rc ykpiv_done_with_external_card(ykpiv_state *state) { + return _done_internal(state, false); +} + +ykpiv_rc ykpiv_done(ykpiv_state *state) { + return _done_internal(state, true); +} + ykpiv_rc ykpiv_disconnect(ykpiv_state *state) { if(state->card) { SCardDisconnect(state->card, SCARD_RESET_CARD); @@ -265,15 +274,19 @@ static ykpiv_rc _connect_internal(ykpiv_state *state, uint64_t context, uint64_t state->context = context; state->card = card; - // transact the connect operation - - if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; - res = _ykpiv_ensure_application_selected(state); - _ykpiv_end_transaction(state); + /* + ** Do not select the applet here, as we need to accommodate commands that are + ** sensitive to re-select (custom apdu/auth). All commands that can handle explicit + ** selection already check the applet state and select accordingly anyway. + ** ykpiv_verify_select is supplied for those who want to select explicitly. + ** + ** The applet _is_ selected by ykpiv_connect(), but is not selected when bypassing + ** it with ykpiv_connect_with_external_card(). + */ return res; } -ykpiv_rc ykpiv_connect_with_card(ykpiv_state *state, uint64_t context, uint64_t card) { +ykpiv_rc ykpiv_connect_with_external_card(ykpiv_state *state, uint64_t context, uint64_t card, bool select) { return _connect_internal(state, context, card); } @@ -313,8 +326,16 @@ ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { } // at this point, card should not equal state->card, to allow _connect_internal() to determine device type - if (!_connect_internal(state, state->context, card)) { - return YKPIV_OK; + if (YKPIV_OK == _connect_internal(state, state->context, card)) { + /* + * Select applet. This is done here instead of in _connect_internal() because + * you may not want to select the applet when connecting to a card handle that + * was supplied by an external library. + */ + if (YKPIV_OK != (ret = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + ret = _ykpiv_ensure_application_selected(state); + _ykpiv_end_transaction(state); + return ret; } } @@ -926,7 +947,6 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { if(len > 8) { return YKPIV_SIZE_ERROR; } - memset(apdu.raw, 0, sizeof(apdu.raw)); apdu.st.ins = YKPIV_INS_VERIFY; apdu.st.p1 = 0x00; @@ -957,6 +977,19 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { } } +ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const char *pin, const size_t pin_len, int *tries, bool force_select) { + ykpiv_rc res = YKPIV_OK; + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) goto Cleanup; + if (force_select) { + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + } + res = ykpiv_verify(state, pin, tries); +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + ykpiv_rc ykpiv_get_pin_retries(ykpiv_state *state, int* tries) { ykpiv_rc res; ykpiv_rc ykrc; @@ -1054,21 +1087,47 @@ static ykpiv_rc change_pin_internal(ykpiv_state *state, int action, const char * } ykpiv_rc ykpiv_change_pin(ykpiv_state *state, const char * current_pin, size_t current_pin_len, const char * new_pin, size_t new_pin_len, int *tries) { - ykpiv_rc res = change_pin_internal(state, CHREF_ACT_CHANGE_PIN, current_pin, current_pin_len, new_pin, new_pin_len, tries); + ykpiv_rc res = YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + res = change_pin_internal(state, CHREF_ACT_CHANGE_PIN, current_pin, current_pin_len, new_pin, new_pin_len, tries); if (res == YKPIV_OK && new_pin != NULL) { // Intentionally ignore errors. If the PIN fails to save, it will only // be a problem if a reconnect is attempted. Failure deferred until then. _cache_pin(state, new_pin, new_pin_len + 1); } + +Cleanup: + _ykpiv_end_transaction(state); return res; } ykpiv_rc ykpiv_change_puk(ykpiv_state *state, const char * current_puk, size_t current_puk_len, const char * new_puk, size_t new_puk_len, int *tries) { - return change_pin_internal(state, CHREF_ACT_CHANGE_PUK, current_puk, current_puk_len, new_puk, new_puk_len, tries); + ykpiv_rc res = YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + res = change_pin_internal(state, CHREF_ACT_CHANGE_PUK, current_puk, current_puk_len, new_puk, new_puk_len, tries); + +Cleanup: + _ykpiv_end_transaction(state); + return res; } ykpiv_rc ykpiv_unblock_pin(ykpiv_state *state, const char * puk, size_t puk_len, const char * new_pin, size_t new_pin_len, int *tries) { - return change_pin_internal(state, CHREF_ACT_UNBLOCK_PIN, puk, puk_len, new_pin, new_pin_len, tries); + ykpiv_rc res = YKPIV_GENERIC_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + res = change_pin_internal(state, CHREF_ACT_UNBLOCK_PIN, puk, puk_len, new_pin, new_pin_len, tries); + +Cleanup: + _ykpiv_end_transaction(state); + return res; } ykpiv_rc ykpiv_fetch_object(ykpiv_state *state, int object_id, @@ -1295,27 +1354,80 @@ ykpiv_rc ykpiv_attest(ykpiv_state *state, const unsigned char key, unsigned char } -// TREV TODO: remove these, fix minidriver - -ykpiv_rc ykpiv_done2(ykpiv_state *state, bool disconnect) { - // TODO: why is this needed? windows unit tests pass without it - if (disconnect) - ykpiv_disconnect(state); - _cache_pin(state, NULL, 0); - _ykpiv_free(state, state); - return YKPIV_OK; -} - -ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const char *pin, const size_t pin_len, int *tries, bool force_select) { +ykpiv_rc ykpiv_auth_getchallenge(ykpiv_state *state, uint8_t *challenge, const size_t challenge_len) { ykpiv_rc res = YKPIV_OK; - if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) goto Cleanup; -#if 0 - // TODO when is this needed? windows unit tests pass without it - if (force_select) { - if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + APDU apdu = { 0 }; + unsigned char data[261] = { 0 }; + unsigned long recv_len = sizeof(data); + int sw = 0; + + if (NULL == state) return YKPIV_GENERIC_ERROR; + if (NULL == challenge) return YKPIV_GENERIC_ERROR; + if (8 != challenge_len) return YKPIV_SIZE_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + /* get a challenge from the card */ + memset(apdu.raw, 0, sizeof(apdu)); + apdu.st.ins = YKPIV_INS_AUTHENTICATE; + apdu.st.p1 = YKPIV_ALGO_3DES; /* triple des */ + apdu.st.p2 = YKPIV_KEY_CARDMGM; /* management key */ + apdu.st.lc = 0x04; + apdu.st.data[0] = 0x7c; + apdu.st.data[1] = 0x02; + apdu.st.data[2] = 0x81; //0x80; + if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { + goto Cleanup; } -#endif - res = ykpiv_verify(state, pin, tries); + else if (sw != SW_SUCCESS) { + res = YKPIV_AUTHENTICATION_ERROR; + goto Cleanup; + } + memcpy(challenge, data + 4, 8); + +Cleanup: + + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc ykpiv_auth_verifyresponse(ykpiv_state *state, uint8_t *response, const size_t response_len) { + ykpiv_rc res = YKPIV_OK; + APDU apdu = { 0 }; + unsigned char data[261] = { 0 }; + unsigned long recv_len = sizeof(data); + int sw = 0; + unsigned char *dataptr = apdu.st.data; + + if (NULL == state) return YKPIV_GENERIC_ERROR; + if (NULL == response) return YKPIV_GENERIC_ERROR; + if (8 != response_len) return YKPIV_SIZE_ERROR; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + /* note: do not select the applet here, as it resets the challenge state */ + + /* send the response to the card and a challenge of our own. */ + recv_len = sizeof(data); + memset(apdu.raw, 0, sizeof(apdu)); + apdu.st.ins = YKPIV_INS_AUTHENTICATE; + apdu.st.p1 = YKPIV_ALGO_3DES; /* triple des */ + apdu.st.p2 = YKPIV_KEY_CARDMGM; /* management key */ + *dataptr++ = 0x7c; + *dataptr++ = 0x0a; /* 2 + 8 */ + *dataptr++ = 0x82; + *dataptr++ = 8; + memcpy(dataptr, response, response_len); + dataptr += 8; + apdu.st.lc = (unsigned char)(dataptr - apdu.st.data); + if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { + goto Cleanup; + } + else if (sw != SW_SUCCESS) { + res = YKPIV_AUTHENTICATION_ERROR; + goto Cleanup; + } + Cleanup: _ykpiv_end_transaction(state); diff --git a/lib/ykpiv.h b/lib/ykpiv.h index b3f80ed..c5cae45 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -499,10 +499,8 @@ extern "C" */ uint32_t ykpiv_util_slot_object(uint8_t slot); - ykpiv_rc ykpiv_connect_with_card(ykpiv_state *state, uint64_t context, uint64_t card); - - // TREV TODO: remove - ykpiv_rc ykpiv_done2(ykpiv_state *state, bool disconnect); + ykpiv_rc ykpiv_connect_with_exteral_card(ykpiv_state *state, uint64_t context, uint64_t card, bool select); + ykpiv_rc ykpiv_done_with_external_card(ykpiv_state *state); ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const char *pin, const size_t pin_len, int *tries, bool force_select); #ifdef __cplusplus From de065ae36e759849d8b89da22b6b324cf87b7a27 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 10 Oct 2017 16:51:21 +0200 Subject: [PATCH 31/57] Rename util.c test suite to api.c --- lib/tests/Makefile.am | 2 +- lib/tests/{util.c => api.c} | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename lib/tests/{util.c => api.c} (100%) diff --git a/lib/tests/Makefile.am b/lib/tests/Makefile.am index fb826a1..479fbdc 100644 --- a/lib/tests/Makefile.am +++ b/lib/tests/Makefile.am @@ -31,7 +31,7 @@ AM_CPPFLAGS = -I$(top_srcdir)/lib -I$(top_builddir)/lib $(OPENSSL_CFLAGS) AM_LDFLAGS = -no-install @CHECK_LIBS@ LDADD = ../libykpiv.la $(OPENSSL_LIBS) -check_PROGRAMS = basic parse_key util +check_PROGRAMS = basic parse_key api TESTS = $(check_PROGRAMS) LOG_COMPILER = $(VALGRIND) diff --git a/lib/tests/util.c b/lib/tests/api.c similarity index 100% rename from lib/tests/util.c rename to lib/tests/api.c From aa293dcc316325efdd3bfd37b2126899a961ec71 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Tue, 10 Oct 2017 17:42:53 +0200 Subject: [PATCH 32/57] Fix PIN length handling in ykpiv_verify*() --- lib/ykpiv.c | 43 ++++++++++++++++++++++--------------------- 1 file changed, 22 insertions(+), 21 deletions(-) diff --git a/lib/ykpiv.c b/lib/ykpiv.c index f52598e..ed31764 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -926,50 +926,47 @@ static ykpiv_rc _cache_pin(ykpiv_state *state, const char *pin, size_t len) { if (state->pin == NULL) { return YKPIV_MEMORY_ERROR; } - memcpy(state->pin, pin, len + 1); + memcpy(state->pin, pin, len); + state->pin[len] = 0; } return YKPIV_OK; #endif } -ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { - // TREV TODO: pin len? +static ykpiv_rc _verify(ykpiv_state *state, const char *pin, const size_t pin_len, int *tries) { APDU apdu; unsigned char data[261]; uint32_t recv_len = sizeof(data); int sw; - size_t len = 0; ykpiv_rc res; - if(pin) { - len = strlen(pin); - } - if(len > 8) { + if (pin_len > 8) { return YKPIV_SIZE_ERROR; } + memset(apdu.raw, 0, sizeof(apdu.raw)); apdu.st.ins = YKPIV_INS_VERIFY; apdu.st.p1 = 0x00; apdu.st.p2 = 0x80; apdu.st.lc = pin ? 0x08 : 0; - if(pin) { - memcpy(apdu.st.data, pin, len); - if(len < 8) { - memset(apdu.st.data + len, 0xff, 8 - len); + if (pin) { + memcpy(apdu.st.data, pin, pin_len); + if (pin_len < 8) { + memset(apdu.st.data + pin_len, 0xff, 8 - pin_len); } } - if((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { + if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { return res; - } else if(sw == SW_SUCCESS) { + } else if (sw == SW_SUCCESS) { // Intentionally ignore errors. If the PIN fails to save, it will only // be a problem if a reconnect is attempted. Failure deferred until then. - _cache_pin(state, pin, len + 1); + _cache_pin(state, pin, pin_len); if (tries) *tries = (sw & 0xf); return YKPIV_OK; - } else if((sw >> 8) == 0x63) { + } else if ((sw >> 8) == 0x63) { if (tries) *tries = (sw & 0xf); return YKPIV_WRONG_PIN; - } else if(sw == SW_ERR_AUTH_BLOCKED) { + } else if (sw == SW_ERR_AUTH_BLOCKED) { if (tries) *tries = 0; return YKPIV_WRONG_PIN; } else { @@ -977,13 +974,17 @@ ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { } } +ykpiv_rc ykpiv_verify(ykpiv_state *state, const char *pin, int *tries) { + return ykpiv_verify_select(state, pin, pin ? strlen(pin) : 0, tries, false); +} + ykpiv_rc ykpiv_verify_select(ykpiv_state *state, const char *pin, const size_t pin_len, int *tries, bool force_select) { ykpiv_rc res = YKPIV_OK; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) goto Cleanup; if (force_select) { if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; } - res = ykpiv_verify(state, pin, tries); + res = _verify(state, pin, pin_len, tries); Cleanup: _ykpiv_end_transaction(state); @@ -1096,7 +1097,7 @@ ykpiv_rc ykpiv_change_pin(ykpiv_state *state, const char * current_pin, size_t c if (res == YKPIV_OK && new_pin != NULL) { // Intentionally ignore errors. If the PIN fails to save, it will only // be a problem if a reconnect is attempted. Failure deferred until then. - _cache_pin(state, new_pin, new_pin_len + 1); + _cache_pin(state, new_pin, new_pin_len); } Cleanup: @@ -1358,7 +1359,7 @@ ykpiv_rc ykpiv_auth_getchallenge(ykpiv_state *state, uint8_t *challenge, const s ykpiv_rc res = YKPIV_OK; APDU apdu = { 0 }; unsigned char data[261] = { 0 }; - unsigned long recv_len = sizeof(data); + uint32_t recv_len = sizeof(data); int sw = 0; if (NULL == state) return YKPIV_GENERIC_ERROR; @@ -1396,7 +1397,7 @@ ykpiv_rc ykpiv_auth_verifyresponse(ykpiv_state *state, uint8_t *response, const ykpiv_rc res = YKPIV_OK; APDU apdu = { 0 }; unsigned char data[261] = { 0 }; - unsigned long recv_len = sizeof(data); + uint32_t recv_len = sizeof(data); int sw = 0; unsigned char *dataptr = apdu.st.data; From 7177ceda74205a39905a67e978aac8cef6ad684c Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Fri, 20 Oct 2017 10:11:11 +0200 Subject: [PATCH 33/57] Extra attempts for PIN/PUK block in unit test --- tool/tests/basic.sh | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tool/tests/basic.sh b/tool/tests/basic.sh index b62d810..b605795 100755 --- a/tool/tests/basic.sh +++ b/tool/tests/basic.sh @@ -101,6 +101,10 @@ fi $BIN -averify-pin -P000000 || true $BIN -averify-pin -P000000 || true $BIN -averify-pin -P000000 || true +$BIN -averify-pin -P000000 || true +$BIN -averify-pin -P000000 || true +$BIN -achange-puk -P000000 -N00000000 || true +$BIN -achange-puk -P000000 -N00000000 || true $BIN -achange-puk -P000000 -N00000000 || true $BIN -achange-puk -P000000 -N00000000 || true $BIN -achange-puk -P000000 -N00000000 || true From c07355fefb84fc997383cee10a87e57ca86a2bde Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Fri, 20 Oct 2017 12:40:09 +0200 Subject: [PATCH 34/57] Fix unit tests for NEO: use ECCP256 and detect attestation errors --- lib/tests/api.c | 21 ++++++++++++++++++--- lib/ykpiv.c | 3 +++ lib/ykpiv.h | 4 +++- tool/tests/basic.sh | 4 ++-- 4 files changed, 26 insertions(+), 6 deletions(-) diff --git a/lib/tests/api.c b/lib/tests/api.c index 305a086..36e1e5e 100644 --- a/lib/tests/api.c +++ b/lib/tests/api.c @@ -409,8 +409,15 @@ START_TEST(test_import_key) { { unsigned char attest[2048]; size_t attest_len = sizeof(attest); + ykpiv_devmodel model; + model = ykpiv_util_devicemodel(g_state); res = ykpiv_attest(g_state, 0x9e, attest, &attest_len); - ck_assert_int_eq(res, YKPIV_GENERIC_ERROR); + if (model == DEVTYPE_YK4) { + ck_assert_int_eq(res, YKPIV_GENERIC_ERROR); + } + else { + ck_assert_int_eq(res, YKPIV_NOT_SUPPORTED); + } } } END_TEST @@ -440,11 +447,19 @@ START_TEST(test_generate_key) { // Verify that imported key can be attested { + ykpiv_devmodel model; unsigned char attest[2048]; size_t attest_len = sizeof(attest); + model = ykpiv_util_devicemodel(g_state); res = ykpiv_attest(g_state, YKPIV_KEY_AUTHENTICATION, attest, &attest_len); - ck_assert_int_eq(res, YKPIV_OK); - ck_assert_int_gt(attest_len, 0); + // Only works with YK4. NEO should error. + if (model == DEVTYPE_YK4) { + ck_assert_int_eq(res, YKPIV_OK); + ck_assert_int_gt(attest_len, 0); + } + else { + ck_assert_int_eq(res, YKPIV_NOT_SUPPORTED); + } } } END_TEST diff --git a/lib/ykpiv.c b/lib/ykpiv.c index ed31764..7948157 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -1346,6 +1346,9 @@ ykpiv_rc ykpiv_attest(ykpiv_state *state, const unsigned char key, unsigned char return res; } else if(SW_SUCCESS != sw) { + if (sw == SW_ERR_NOT_SUPPORTED) { + return YKPIV_NOT_SUPPORTED; + } return YKPIV_GENERIC_ERROR; } if (data[0] != 0x30) { diff --git a/lib/ykpiv.h b/lib/ykpiv.h index c5cae45..a2ddfa4 100644 --- a/lib/ykpiv.h +++ b/lib/ykpiv.h @@ -61,7 +61,8 @@ extern "C" YKPIV_PIN_LOCKED = -13, YKPIV_ARGUMENT_ERROR = -14, //i.e. invalid input argument - YKPIV_RANGE_ERROR = -15 //i.e. value range error + YKPIV_RANGE_ERROR = -15, //i.e. value range error + YKPIV_NOT_SUPPORTED = -16 } ykpiv_rc; typedef void* (*ykpiv_pfn_alloc)(void* alloc_data, size_t size); @@ -217,6 +218,7 @@ extern "C" #define SW_ERR_INCORRECT_PARAM 0x6a80 /* this is a custom sw for yubikey */ #define SW_ERR_INCORRECT_SLOT 0x6b00 +#define SW_ERR_NOT_SUPPORTED 0x6d00 /* Yubico vendor specific instructions */ #define YKPIV_INS_SET_MGMKEY 0xff diff --git a/tool/tests/basic.sh b/tool/tests/basic.sh index b605795..95a886a 100755 --- a/tool/tests/basic.sh +++ b/tool/tests/basic.sh @@ -111,7 +111,7 @@ $BIN -achange-puk -P000000 -N00000000 || true $BIN -areset # Generate key on-board, issue certificate, and verify it -$BIN -agenerate -s9a -AECCP384 -o key_9a.pub +$BIN -agenerate -s9a -AECCP256 -o key_9a.pub $BIN -averify -P123456 -s9a -S'/CN=YubicoTest/OU=YubicoGenerated/O=yubico.com/' -aselfsign -i key_9a.pub -o cert_9a.pem $BIN -averify -P123456 -s9a -atest-signature -i cert_9a.pem $BIN -aimport-certificate -P123456 -s9a -i cert_9a.pem @@ -128,7 +128,7 @@ $BIN -aimport-certificate -P123456 -s9e -i cert.pem STATUS=$($BIN -astatus) echo "$STATUS" ALGO_9A=$(echo "$STATUS" |grep "Slot 9a" -A 6 |grep "Algorithm" |tr -d "[:blank:]") -if [[ "x$ALGO_9A" != "xAlgorithm:ECCP384" ]]; then +if [[ "x$ALGO_9A" != "xAlgorithm:ECCP256" ]]; then echo "$ALGO_9A" echo "Generated algorithm incorrect." >/dev/stderr exit 1 From 27933eaff8edadc3de5535e42d8d44a809aa34f2 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Fri, 20 Oct 2017 16:13:43 +0200 Subject: [PATCH 35/57] Fix applet selection for whole public API. --- lib/internal.h | 2 + lib/util.c | 36 +++++----- lib/ykpiv.c | 179 +++++++++++++++++++++++++++++++++---------------- 3 files changed, 140 insertions(+), 77 deletions(-) diff --git a/lib/internal.h b/lib/internal.h index 8c3f925..2aef554 100644 --- a/lib/internal.h +++ b/lib/internal.h @@ -183,6 +183,8 @@ int _ykpiv_get_length(const unsigned char *buffer, size_t *len); void* _ykpiv_alloc(ykpiv_state *state, size_t size); void* _ykpiv_realloc(ykpiv_state *state, void *address, size_t size); void _ykpiv_free(ykpiv_state *state, void *data); +ykpiv_rc _ykpiv_save_object(ykpiv_state *state, int object_id, unsigned char *indata, size_t len); +ykpiv_rc _ykpiv_fetch_object(ykpiv_state *state, int object_id, unsigned char *data, unsigned long *len); #ifdef __cplusplus } diff --git a/lib/util.c b/lib/util.c index c6d4686..4ece743 100644 --- a/lib/util.c +++ b/lib/util.c @@ -103,7 +103,7 @@ ykpiv_rc ykpiv_util_get_cardid(ykpiv_state *state, ykpiv_cardid *cardid) { if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; - res = ykpiv_fetch_object(state, YKPIV_OBJ_CHUID, buf, (unsigned long *)&len); + res = _ykpiv_fetch_object(state, YKPIV_OBJ_CHUID, buf, (unsigned long *)&len); if (YKPIV_OK == res) { if (len != sizeof(CHUID_TMPL)) { res = YKPIV_GENERIC_ERROR; @@ -143,7 +143,7 @@ ykpiv_rc ykpiv_util_set_cardid(ykpiv_state *state, const ykpiv_cardid *cardid) { memcpy(buf + CHUID_GUID_OFFS, id, sizeof(id)); len = sizeof(CHUID_TMPL); - res = ykpiv_save_object(state, YKPIV_OBJ_CHUID, buf, len); + res = _ykpiv_save_object(state, YKPIV_OBJ_CHUID, buf, len); Cleanup: @@ -161,7 +161,7 @@ ykpiv_rc ykpiv_util_get_cccid(ykpiv_state *state, ykpiv_cccid *ccc) { if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; - res = ykpiv_fetch_object(state, YKPIV_OBJ_CAPABILITY, buf, (unsigned long *)&len); + res = _ykpiv_fetch_object(state, YKPIV_OBJ_CAPABILITY, buf, (unsigned long *)&len); if (YKPIV_OK == res) { if (len != sizeof(CCC_TMPL)) { res = YKPIV_GENERIC_ERROR; @@ -200,7 +200,7 @@ ykpiv_rc ykpiv_util_set_cccid(ykpiv_state *state, const ykpiv_cccid *ccc) { len = sizeof(CCC_TMPL); memcpy(buf, CCC_TMPL, len); memcpy(buf + CCC_ID_OFFS, id, YKPIV_CCCID_SIZE); - res = ykpiv_save_object(state, YKPIV_OBJ_CAPABILITY, buf, len); + res = _ykpiv_save_object(state, YKPIV_OBJ_CAPABILITY, buf, len); Cleanup: _ykpiv_end_transaction(state); @@ -452,7 +452,7 @@ ykpiv_rc ykpiv_util_read_mscmap(ykpiv_state *state, ykpiv_container **containers *containers = 0; *n_containers = 0; - if (YKPIV_OK == (res = ykpiv_fetch_object(state, YKPIV_OBJ_MSCMAP, buf, (unsigned long*)&cbBuf))) { + if (YKPIV_OK == (res = _ykpiv_fetch_object(state, YKPIV_OBJ_MSCMAP, buf, (unsigned long*)&cbBuf))) { ptr = buf; // check that object contents are at least large enough to read the header @@ -509,7 +509,7 @@ ykpiv_rc ykpiv_util_write_mscmap(ykpiv_state *state, ykpiv_container *containers res = YKPIV_GENERIC_ERROR; } else { - res = ykpiv_save_object(state, YKPIV_OBJ_MSCMAP, NULL, 0); + res = _ykpiv_save_object(state, YKPIV_OBJ_MSCMAP, NULL, 0); } goto Cleanup; @@ -531,7 +531,7 @@ ykpiv_rc ykpiv_util_write_mscmap(ykpiv_state *state, ykpiv_container *containers offset += data_len; // write onto device - res = ykpiv_save_object(state, YKPIV_OBJ_MSCMAP, buf, offset); + res = _ykpiv_save_object(state, YKPIV_OBJ_MSCMAP, buf, offset); Cleanup: @@ -567,7 +567,7 @@ ykpiv_rc ykpiv_util_read_msroots(ykpiv_state *state, uint8_t **data, size_t *dat for (object_id = YKPIV_OBJ_MSROOTS1; object_id <= YKPIV_OBJ_MSROOTS5; object_id++) { cbBuf = sizeof(buf); - if (YKPIV_OK != (res = ykpiv_fetch_object(state, object_id, buf, (unsigned long*)&cbBuf))) { + if (YKPIV_OK != (res = _ykpiv_fetch_object(state, object_id, buf, (unsigned long*)&cbBuf))) { goto Cleanup; } @@ -654,7 +654,7 @@ ykpiv_rc ykpiv_util_write_msroots(ykpiv_state *state, uint8_t *data, size_t data else { // it should be sufficient to just delete the first object, though // to be complete we should erase all of the MSROOTS objects - res = ykpiv_save_object(state, YKPIV_OBJ_MSROOTS1, NULL, 0); + res = _ykpiv_save_object(state, YKPIV_OBJ_MSROOTS1, NULL, 0); } goto Cleanup; @@ -680,7 +680,7 @@ ykpiv_rc ykpiv_util_write_msroots(ykpiv_state *state, uint8_t *data, size_t data offset += data_chunk; // write onto device - res = ykpiv_save_object(state, YKPIV_OBJ_MSROOTS1 + i, buf, offset); + res = _ykpiv_save_object(state, YKPIV_OBJ_MSROOTS1 + i, buf, offset); if (YKPIV_OK != res) { goto Cleanup; @@ -1284,7 +1284,6 @@ uint32_t ykpiv_util_slot_object(uint8_t slot) { } static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf, size_t *buf_len) { - // TREV TODO: should this select application? ykpiv_rc res = YKPIV_OK; uint8_t *ptr = NULL; int object_id = ykpiv_util_slot_object(slot); @@ -1292,7 +1291,7 @@ static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf if (-1 == object_id) return YKPIV_INVALID_OBJECT; - if (YKPIV_OK == (res = ykpiv_fetch_object(state, object_id, buf, (unsigned long*)buf_len))) { + if (YKPIV_OK == (res = _ykpiv_fetch_object(state, object_id, buf, (unsigned long*)buf_len))) { ptr = buf; // check that object contents are at least large enough to read the tag @@ -1324,7 +1323,6 @@ static ykpiv_rc _read_certificate(ykpiv_state *state, uint8_t slot, uint8_t *buf } static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *data, size_t data_len, uint8_t certinfo) { - // TREV TODO: should this select application? uint8_t buf[CB_OBJ_MAX]; size_t cbBuf = sizeof(buf); int object_id = ykpiv_util_slot_object(slot); @@ -1342,7 +1340,7 @@ static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *da return YKPIV_GENERIC_ERROR; } - return ykpiv_save_object(state, object_id, NULL, 0); + return _ykpiv_save_object(state, object_id, NULL, 0); } // encode certificate data for storage @@ -1366,7 +1364,7 @@ static ykpiv_rc _write_certificate(ykpiv_state *state, uint8_t slot, uint8_t *da buf[offset++] = 00; // write onto device - return ykpiv_save_object(state, object_id, buf, offset); + return _ykpiv_save_object(state, object_id, buf, offset); } /* @@ -1524,7 +1522,6 @@ static ykpiv_rc _set_metadata_item(uint8_t *data, size_t *pcb_data, size_t cb_da ** To read from protected data, the pin must be verified prior to calling this function. */ static ykpiv_rc _read_metadata(ykpiv_state *state, uint8_t tag, uint8_t* data, size_t* pcb_data) { - // TREV TODO: should this select application? ykpiv_rc res = YKPIV_OK; uint8_t *p_temp = NULL; size_t cb_temp = 0; @@ -1541,7 +1538,7 @@ static ykpiv_rc _read_metadata(ykpiv_state *state, uint8_t tag, uint8_t* data, s cb_temp = *pcb_data; *pcb_data = 0; - if (YKPIV_OK != (res = ykpiv_fetch_object(state, obj_id, data, (unsigned long*)&cb_temp))) { + if (YKPIV_OK != (res = _ykpiv_fetch_object(state, obj_id, data, (unsigned long*)&cb_temp))) { return res; } @@ -1573,7 +1570,6 @@ static ykpiv_rc _read_metadata(ykpiv_state *state, uint8_t tag, uint8_t* data, s ** To write protected data, the pin must be verified prior to calling this function. */ static ykpiv_rc _write_metadata(ykpiv_state *state, uint8_t tag, uint8_t *data, size_t cb_data) { - // TREV TODO: should this select application? ykpiv_rc res = YKPIV_OK; uint8_t buf[CB_OBJ_MAX] = { 0 }; uint8_t *pTemp = buf; @@ -1591,7 +1587,7 @@ static ykpiv_rc _write_metadata(ykpiv_state *state, uint8_t tag, uint8_t *data, if (!data || (0 == cb_data)) { // deleting metadata - res = ykpiv_save_object(state, obj_id, NULL, 0); + res = _ykpiv_save_object(state, obj_id, NULL, 0); } else { *pTemp++ = tag; @@ -1600,7 +1596,7 @@ static ykpiv_rc _write_metadata(ykpiv_state *state, uint8_t tag, uint8_t *data, memcpy(pTemp, data, cb_data); pTemp += cb_data; - res = ykpiv_save_object(state, obj_id, buf, pTemp - buf); + res = _ykpiv_save_object(state, obj_id, buf, pTemp - buf); } return res; diff --git a/lib/ykpiv.c b/lib/ykpiv.c index 7948157..592261e 100644 --- a/lib/ykpiv.c +++ b/lib/ykpiv.c @@ -167,7 +167,7 @@ ykpiv_rc ykpiv_init(ykpiv_state **state, int verbose) { return ykpiv_init_with_allocator(state, verbose, &_default_allocator); } -static ykpiv_rc _done_internal(ykpiv_state *state, bool disconnect) { +static ykpiv_rc _ykpiv_done(ykpiv_state *state, bool disconnect) { if (disconnect) ykpiv_disconnect(state); _cache_pin(state, NULL, 0); @@ -176,11 +176,11 @@ static ykpiv_rc _done_internal(ykpiv_state *state, bool disconnect) { } ykpiv_rc ykpiv_done_with_external_card(ykpiv_state *state) { - return _done_internal(state, false); + return _ykpiv_done(state, false); } ykpiv_rc ykpiv_done(ykpiv_state *state) { - return _done_internal(state, true); + return _ykpiv_done(state, true); } ykpiv_rc ykpiv_disconnect(ykpiv_state *state) { @@ -244,7 +244,7 @@ ykpiv_rc _ykpiv_ensure_application_selected(ykpiv_state *state) { return res; } -static ykpiv_rc _connect_internal(ykpiv_state *state, uint64_t context, uint64_t card) { +static ykpiv_rc _ykpiv_connect(ykpiv_state *state, uint64_t context, uint64_t card) { ykpiv_rc res = YKPIV_OK; if (NULL == state) { @@ -287,7 +287,7 @@ static ykpiv_rc _connect_internal(ykpiv_state *state, uint64_t context, uint64_t } ykpiv_rc ykpiv_connect_with_external_card(ykpiv_state *state, uint64_t context, uint64_t card, bool select) { - return _connect_internal(state, context, card); + return _ykpiv_connect(state, context, card); } ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { @@ -325,10 +325,10 @@ ykpiv_rc ykpiv_connect(ykpiv_state *state, const char *wanted) { continue; } - // at this point, card should not equal state->card, to allow _connect_internal() to determine device type - if (YKPIV_OK == _connect_internal(state, state->context, card)) { + // at this point, card should not equal state->card, to allow _ykpiv_connect() to determine device type + if (YKPIV_OK == _ykpiv_connect(state, state->context, card)) { /* - * Select applet. This is done here instead of in _connect_internal() because + * Select applet. This is done here instead of in _ykpiv_connect() because * you may not want to select the applet when connecting to a card handle that * was supplied by an external library. */ @@ -457,10 +457,7 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, ykpiv_rc res; *out_len = 0; - res = _ykpiv_begin_transaction(state); - if (res != YKPIV_OK) { - return res; - } + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; do { size_t this_size = 0xff; unsigned char data[261]; @@ -481,17 +478,16 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, memcpy(apdu.st.data, in_ptr, this_size); res = _send_data(state, &apdu, data, &recv_len, sw); if(res != YKPIV_OK) { - _ykpiv_end_transaction(state); - return res; + goto Cleanup; } else if(*sw != SW_SUCCESS && *sw >> 8 != 0x61) { - return _ykpiv_end_transaction(state); + goto Cleanup; } if(*out_len + recv_len - 2 > max_out) { if(state->verbose) { fprintf(stderr, "Output buffer to small, wanted to write %lu, max was %lu.\n", *out_len + recv_len - 2, max_out); } - _ykpiv_end_transaction(state); - return YKPIV_SIZE_ERROR; + res = YKPIV_SIZE_ERROR; + goto Cleanup; } if(out_data) { memcpy(out_data, data, recv_len - 2); @@ -513,10 +509,9 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, apdu.st.ins = 0xc0; res = _send_data(state, &apdu, data, &recv_len, sw); if(res != YKPIV_OK) { - _ykpiv_end_transaction(state); - return res; + goto Cleanup; } else if(*sw != SW_SUCCESS && *sw >> 8 != 0x61) { - return _ykpiv_end_transaction(state); + goto Cleanup; } if(*out_len + recv_len - 2 > max_out) { fprintf(stderr, "Output buffer to small, wanted to write %lu, max was %lu.", *out_len + recv_len - 2, max_out); @@ -527,7 +522,9 @@ ykpiv_rc ykpiv_transfer_data(ykpiv_state *state, const unsigned char *templ, *out_len += recv_len - 2; } } - return _ykpiv_end_transaction(state); +Cleanup: + _ykpiv_end_transaction(state); + return res; } static ykpiv_rc _send_data(ykpiv_state *state, APDU *apdu, @@ -573,6 +570,9 @@ ykpiv_rc ykpiv_authenticate(ykpiv_state *state, unsigned const char *key) { if (NULL == state) return YKPIV_GENERIC_ERROR; + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + if (NULL == key) { /* use the derived mgm key to authenticate, if it hasn't been derived, use default */ key = (unsigned const char*)YKPIV_MGM_DEFAULT; @@ -662,6 +662,7 @@ Cleanup: des_destroy_key(mgm_key); } + _ykpiv_end_transaction(state); return res; } @@ -676,13 +677,17 @@ ykpiv_rc ykpiv_set_mgmkey2(ykpiv_state *state, const unsigned char *new_key, con int sw; ykpiv_rc res = YKPIV_OK; + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + if (yk_des_is_weak_key(new_key, DES_LEN_3DES)) { if (state->verbose) { fprintf(stderr, "Won't set new key '"); dump_hex(new_key, DES_LEN_3DES); fprintf(stderr, "' since it's weak (with odd parity).\n"); } - return YKPIV_KEY_ERROR; + res = YKPIV_KEY_ERROR; + goto Cleanup; } memset(apdu.raw, 0, sizeof(apdu)); @@ -695,7 +700,8 @@ ykpiv_rc ykpiv_set_mgmkey2(ykpiv_state *state, const unsigned char *new_key, con apdu.st.p2 = 0xfe; } else { - return YKPIV_GENERIC_ERROR; + res = YKPIV_GENERIC_ERROR; + goto Cleanup; } apdu.st.lc = DES_LEN_3DES + 3; @@ -705,13 +711,16 @@ ykpiv_rc ykpiv_set_mgmkey2(ykpiv_state *state, const unsigned char *new_key, con memcpy(apdu.st.data + 3, new_key, DES_LEN_3DES); if ((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { - return res; + goto Cleanup; } else if (sw == SW_SUCCESS) { - return YKPIV_OK; + goto Cleanup; } + res = YKPIV_GENERIC_ERROR; - return YKPIV_GENERIC_ERROR; +Cleanup: + _ykpiv_end_transaction(state); + return res; } static char hex_translate[] = "0123456789abcdef"; @@ -857,7 +866,6 @@ ykpiv_rc ykpiv_sign_data(ykpiv_state *state, if (NULL == state) return YKPIV_GENERIC_ERROR; if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; - // TREV TODO: clean up selections if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; res = _general_authenticate(state, raw_in, in_len, sign_out, out_len, @@ -894,19 +902,27 @@ ykpiv_rc ykpiv_get_version(ykpiv_state *state, char *version, size_t len) { int sw; ykpiv_rc res; + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + memset(apdu.raw, 0, sizeof(apdu)); apdu.st.ins = YKPIV_INS_GET_VERSION; if((res = _send_data(state, &apdu, data, &recv_len, &sw)) != YKPIV_OK) { - return res; + goto Cleanup; } else if(sw == SW_SUCCESS) { int result = snprintf(version, len, "%d.%d.%d", data[0], data[1], data[2]); if(result < 0) { - return YKPIV_SIZE_ERROR; + res = YKPIV_SIZE_ERROR; } - return YKPIV_OK; + goto Cleanup; } else { - return YKPIV_GENERIC_ERROR; + res = YKPIV_GENERIC_ERROR; + goto Cleanup; } + +Cleanup: + _ykpiv_end_transaction(state); + return res; } static ykpiv_rc _cache_pin(ykpiv_state *state, const char *pin, size_t len) { @@ -1027,21 +1043,28 @@ ykpiv_rc ykpiv_set_pin_retries(ykpiv_state *state, int pin_tries, int puk_tries) templ[2] = (unsigned char)pin_tries; templ[3] = (unsigned char)puk_tries; + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + res = ykpiv_transfer_data(state, templ, NULL, 0, data, &recv_len, &sw); if (YKPIV_OK == res) { if (SW_SUCCESS == sw) { - return YKPIV_OK; + // success, fall through } else if (sw == SW_ERR_AUTH_BLOCKED) { - return YKPIV_AUTHENTICATION_ERROR; + res = YKPIV_AUTHENTICATION_ERROR; } else if (sw == SW_ERR_SECURITY_STATUS) { - return YKPIV_AUTHENTICATION_ERROR; + res = YKPIV_AUTHENTICATION_ERROR; + } else { + res = YKPIV_GENERIC_ERROR; } - return YKPIV_GENERIC_ERROR; } + +Cleanup: + _ykpiv_end_transaction(state); return res; } -static ykpiv_rc change_pin_internal(ykpiv_state *state, int action, const char * current_pin, size_t current_pin_len, const char * new_pin, size_t new_pin_len, int *tries) { +static ykpiv_rc _ykpiv_change_pin(ykpiv_state *state, int action, const char * current_pin, size_t current_pin_len, const char * new_pin, size_t new_pin_len, int *tries) { int sw; unsigned char templ[] = {0, YKPIV_INS_CHANGE_REFERENCE, 0, 0x80}; unsigned char indata[0x10]; @@ -1093,7 +1116,7 @@ ykpiv_rc ykpiv_change_pin(ykpiv_state *state, const char * current_pin, size_t c if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; - res = change_pin_internal(state, CHREF_ACT_CHANGE_PIN, current_pin, current_pin_len, new_pin, new_pin_len, tries); + res = _ykpiv_change_pin(state, CHREF_ACT_CHANGE_PIN, current_pin, current_pin_len, new_pin, new_pin_len, tries); if (res == YKPIV_OK && new_pin != NULL) { // Intentionally ignore errors. If the PIN fails to save, it will only // be a problem if a reconnect is attempted. Failure deferred until then. @@ -1111,7 +1134,7 @@ ykpiv_rc ykpiv_change_puk(ykpiv_state *state, const char * current_puk, size_t c if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; - res = change_pin_internal(state, CHREF_ACT_CHANGE_PUK, current_puk, current_puk_len, new_puk, new_puk_len, tries); + res = _ykpiv_change_pin(state, CHREF_ACT_CHANGE_PUK, current_puk, current_puk_len, new_puk, new_puk_len, tries); Cleanup: _ykpiv_end_transaction(state); @@ -1124,7 +1147,7 @@ ykpiv_rc ykpiv_unblock_pin(ykpiv_state *state, const char * puk, size_t puk_len, if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; - res = change_pin_internal(state, CHREF_ACT_UNBLOCK_PIN, puk, puk_len, new_pin, new_pin_len, tries); + res = _ykpiv_change_pin(state, CHREF_ACT_UNBLOCK_PIN, puk, puk_len, new_pin, new_pin_len, tries); Cleanup: _ykpiv_end_transaction(state); @@ -1133,6 +1156,20 @@ Cleanup: ykpiv_rc ykpiv_fetch_object(ykpiv_state *state, int object_id, unsigned char *data, unsigned long *len) { + ykpiv_rc res; + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + res = _ykpiv_fetch_object(state, object_id, data, len); + +Cleanup: + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc _ykpiv_fetch_object(ykpiv_state *state, int object_id, + unsigned char *data, unsigned long *len) { int sw; unsigned char indata[5]; unsigned char *inptr = indata; @@ -1165,9 +1202,21 @@ ykpiv_rc ykpiv_fetch_object(ykpiv_state *state, int object_id, ykpiv_rc ykpiv_save_object(ykpiv_state *state, int object_id, unsigned char *indata, size_t len) { + ykpiv_rc res; - // TREV TODO: buffer sizes different in minidriver - unsigned char data[3072]; + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + + res = _ykpiv_save_object(state, object_id, indata, len); + +Cleanup: + _ykpiv_end_transaction(state); + return res; +} + +ykpiv_rc _ykpiv_save_object(ykpiv_state *state, int object_id, + unsigned char *indata, size_t len) { + unsigned char data[CB_BUF_MAX]; unsigned char *dataptr = data; unsigned char templ[] = {0, YKPIV_INS_PUT_DATA, 0x3f, 0xff}; int sw; @@ -1224,6 +1273,7 @@ ykpiv_rc ykpiv_import_private_key(ykpiv_state *state, const unsigned char key, u unsigned char n_params; int i; int param_tag; + ykpiv_rc res; if (state == NULL) return YKPIV_GENERIC_ERROR; @@ -1320,17 +1370,23 @@ ykpiv_rc ykpiv_import_private_key(ykpiv_state *state, const unsigned char key, u *in_ptr++ = touch_policy; } - if (ykpiv_transfer_data(state, templ, key_data, in_ptr - key_data, data, &recv_len, &sw) != YKPIV_OK) - return YKPIV_GENERIC_ERROR; + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; - if (sw == SW_ERR_SECURITY_STATUS) - return YKPIV_AUTHENTICATION_ERROR; - - if (sw != SW_SUCCESS) - return YKPIV_GENERIC_ERROR; - - return YKPIV_OK; + if ((res = ykpiv_transfer_data(state, templ, key_data, in_ptr - key_data, data, &recv_len, &sw)) != YKPIV_OK) { + goto Cleanup; + } + if (SW_SUCCESS != sw) { + res = YKPIV_GENERIC_ERROR; + if (sw == SW_ERR_SECURITY_STATUS) { + res = YKPIV_AUTHENTICATION_ERROR; + } + goto Cleanup; + } +Cleanup: + _ykpiv_end_transaction(state); + return res; } ykpiv_rc ykpiv_attest(ykpiv_state *state, const unsigned char key, unsigned char *data, size_t *data_len) { @@ -1342,19 +1398,28 @@ ykpiv_rc ykpiv_attest(ykpiv_state *state, const unsigned char key, unsigned char if (state == NULL || data == NULL || data_len == NULL) { return YKPIV_ARGUMENT_ERROR; } + + if (YKPIV_OK != (res = _ykpiv_begin_transaction(state))) return YKPIV_PCSC_ERROR; + if (YKPIV_OK != (res = _ykpiv_ensure_application_selected(state))) goto Cleanup; + if ((res = ykpiv_transfer_data(state, templ, NULL, 0, data, data_len, &sw)) != YKPIV_OK) { - return res; + goto Cleanup; } - else if(SW_SUCCESS != sw) { - if (sw == SW_ERR_NOT_SUPPORTED) { - return YKPIV_NOT_SUPPORTED; + if (SW_SUCCESS != sw) { + res = YKPIV_GENERIC_ERROR; + if (SW_ERR_NOT_SUPPORTED == sw) { + res = YKPIV_NOT_SUPPORTED; } - return YKPIV_GENERIC_ERROR; + goto Cleanup; } if (data[0] != 0x30) { - return YKPIV_GENERIC_ERROR; + res = YKPIV_GENERIC_ERROR; + goto Cleanup; } - return YKPIV_OK; + +Cleanup: + _ykpiv_end_transaction(state); + return res; } From 935e05485a51cf0623b4da156db3dbb7eb7dd0cf Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 23 Oct 2017 12:33:44 +0200 Subject: [PATCH 36/57] Use openssl implementation of DES_is_weak_key on non-Windows, and add unit test. --- lib/internal.c | 6 ++++-- lib/tests/api.c | 13 +++++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/internal.c b/lib/internal.c index 969adce..6251924 100644 --- a/lib/internal.c +++ b/lib/internal.c @@ -322,9 +322,8 @@ EXIT: return rc; } -// TREV TODO: use openssl's implementation when available bool yk_des_is_weak_key(const unsigned char *key, const size_t cb_key) { - +#ifdef _WINDOWS /* defined weak keys, borrowed from openssl to be consistent across platforms */ static const unsigned char weak_keys[][DES_LEN_DES] = { /* weak keys */ @@ -377,6 +376,9 @@ bool yk_des_is_weak_key(const unsigned char *key, const size_t cb_key) { } return false; +#else + return DES_is_weak_key((const_DES_cblock *)key); +#endif } prng_rc _ykpiv_prng_generate(unsigned char *buffer, const size_t cb_req) { diff --git a/lib/tests/api.c b/lib/tests/api.c index 36e1e5e..5a5aea5 100644 --- a/lib/tests/api.c +++ b/lib/tests/api.c @@ -476,6 +476,7 @@ START_TEST(test_authenticate) { ykpiv_rc res; const char *default_mgm_key = "010203040506070801020304050607080102030405060708"; const char *mgm_key = "112233445566778811223344556677881122334455667788"; + const char *weak_mgm_key = "FEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFEFE"; unsigned char key[24]; size_t key_len = sizeof(key); @@ -520,6 +521,18 @@ START_TEST(test_authenticate) { ck_assert_int_eq(res, YKPIV_OK); res = ykpiv_authenticate(g_state, key); ck_assert_int_eq(res, YKPIV_OK); + + // Try to set a weak key, fail + res = ykpiv_hex_decode(weak_mgm_key, strlen(weak_mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_set_mgmkey(g_state, key); + ck_assert_int_eq(res, YKPIV_KEY_ERROR); + + // Try default key, succeed + res = ykpiv_hex_decode(default_mgm_key, strlen(default_mgm_key), key, &key_len); + ck_assert_int_eq(res, YKPIV_OK); + res = ykpiv_authenticate(g_state, key); + ck_assert_int_eq(res, YKPIV_OK); } END_TEST From 58abe404f3e6bd5d620c06e7a58de0b6d56a1aa7 Mon Sep 17 00:00:00 2001 From: Trevor Bentley Date: Mon, 23 Oct 2017 14:52:19 +0200 Subject: [PATCH 37/57] Generate Doxygen docs for libykpiv if doxygen is available. --- Makefile.am | 5 + configure.ac | 3 + lib/Doxyfile | 2473 ++++++++++++++++++++++++++++++++++++++++++++++ lib/ykpiv.h | 8 + m4/ac_doxygen.m4 | 312 ++++++ 5 files changed, 2801 insertions(+) create mode 100644 lib/Doxyfile create mode 100644 m4/ac_doxygen.m4 diff --git a/Makefile.am b/Makefile.am index 9c0f090..dbf0219 100644 --- a/Makefile.am +++ b/Makefile.am @@ -63,6 +63,11 @@ endif # Maintainer rules. +if DX_COND_html +doxygen: + doxygen lib/Doxyfile +endif + check-doc-dist: perl -pe "s,^EXTRA_DIST \+= .*,EXTRA_DIST += `cd $(srcdir) && ls doc/*.adoc | xargs echo`," < $(srcdir)/Makefile.am > check-doc-dist.tmp diff -ur $(srcdir)/Makefile.am check-doc-dist.tmp || \ diff --git a/configure.ac b/configure.ac index 7e5f5e4..957b29a 100644 --- a/configure.ac +++ b/configure.ac @@ -52,6 +52,9 @@ PKG_PROG_PKG_CONFIG PKG_CHECK_MODULES(OPENSSL, libcrypto) PKG_CHECK_MODULES([CHECK], [check >= 0.9.6]) +DX_HTML_FEATURE(ON) +DX_INIT_DOXYGEN(libykpiv,lib/Doxyfile) + gl_LD_VERSION_SCRIPT gl_VALGRIND_TESTS diff --git a/lib/Doxyfile b/lib/Doxyfile new file mode 100644 index 0000000..a24a91b --- /dev/null +++ b/lib/Doxyfile @@ -0,0 +1,2473 @@ +# Doxyfile 1.8.13 + +# This file describes the settings to be used by the documentation system +# doxygen (www.doxygen.org) for a project. +# +# All text after a double hash (##) is considered a comment and is placed in +# front of the TAG it is preceding. +# +# All text after a single hash (#) is considered a comment and will be ignored. +# The format is: +# TAG = value [value, ...] +# For lists, items can also be appended using: +# TAG += value [value, ...] +# Values that contain spaces should be placed between quotes (\" \"). + +#--------------------------------------------------------------------------- +# Project related configuration options +#--------------------------------------------------------------------------- + +# This tag specifies the encoding used for all characters in the config file +# that follow. The default is UTF-8 which is also the encoding used for all text +# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv +# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv +# for the list of possible encodings. +# The default value is: UTF-8. + +DOXYFILE_ENCODING = UTF-8 + +# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by +# double-quotes, unless you are using Doxywizard) that should identify the +# project for which the documentation is generated. This name is used in the +# title of most generated pages and in a few other places. +# The default value is: My Project. + +PROJECT_NAME = "libykpiv" + +# The PROJECT_NUMBER tag can be used to enter a project or revision number. This +# could be handy for archiving the generated documentation or if some version +# control system is used. + +PROJECT_NUMBER = + +# Using the PROJECT_BRIEF tag one can provide an optional one line description +# for a project that appears at the top of each page and should give viewer a +# quick idea about the purpose of the project. Keep the description short. + +PROJECT_BRIEF = + +# With the PROJECT_LOGO tag one can specify a logo or an icon that is included +# in the documentation. The maximum height of the logo should not exceed 55 +# pixels and the maximum width should not exceed 200 pixels. Doxygen will copy +# the logo to the output directory. + +PROJECT_LOGO = + +# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path +# into which the generated documentation will be written. If a relative path is +# entered, it will be relative to the location where doxygen was started. If +# left blank the current directory will be used. + +OUTPUT_DIRECTORY = doxygen-doc + +# If the CREATE_SUBDIRS tag is set to YES then doxygen will create 4096 sub- +# directories (in 2 levels) under the output directory of each output format and +# will distribute the generated files over these directories. Enabling this +# option can be useful when feeding doxygen a huge amount of source files, where +# putting all generated files in the same directory would otherwise causes +# performance problems for the file system. +# The default value is: NO. + +CREATE_SUBDIRS = NO + +# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII +# characters to appear in the names of generated files. If set to NO, non-ASCII +# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode +# U+3044. +# The default value is: NO. + +ALLOW_UNICODE_NAMES = NO + +# The OUTPUT_LANGUAGE tag is used to specify the language in which all +# documentation generated by doxygen is written. Doxygen will use this +# information to generate all constant output in the proper language. +# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese, +# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States), +# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian, +# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages), +# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian, +# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian, +# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish, +# Ukrainian and Vietnamese. +# The default value is: English. + +OUTPUT_LANGUAGE = English + +# If the BRIEF_MEMBER_DESC tag is set to YES, doxygen will include brief member +# descriptions after the members that are listed in the file and class +# documentation (similar to Javadoc). Set to NO to disable this. +# The default value is: YES. + +BRIEF_MEMBER_DESC = YES + +# If the REPEAT_BRIEF tag is set to YES, doxygen will prepend the brief +# description of a member or function before the detailed description +# +# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the +# brief descriptions will be completely suppressed. +# The default value is: YES. + +REPEAT_BRIEF = YES + +# This tag implements a quasi-intelligent brief description abbreviator that is +# used to form the text in various listings. Each string in this list, if found +# as the leading text of the brief description, will be stripped from the text +# and the result, after processing the whole list, is used as the annotated +# text. Otherwise, the brief description is used as-is. If left blank, the +# following values are used ($name is automatically replaced with the name of +# the entity):The $name class, The $name widget, The $name file, is, provides, +# specifies, contains, represents, a, an and the. + +ABBREVIATE_BRIEF = "The $name class" \ + "The $name widget" \ + "The $name file" \ + is \ + provides \ + specifies \ + contains \ + represents \ + a \ + an \ + the + +# If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then +# doxygen will generate a detailed section even if there is only a brief +# description. +# The default value is: NO. + +ALWAYS_DETAILED_SEC = NO + +# If the INLINE_INHERITED_MEMB tag is set to YES, doxygen will show all +# inherited members of a class in the documentation of that class as if those +# members were ordinary class members. Constructors, destructors and assignment +# operators of the base classes will not be shown. +# The default value is: NO. + +INLINE_INHERITED_MEMB = NO + +# If the FULL_PATH_NAMES tag is set to YES, doxygen will prepend the full path +# before files name in the file list and in the header files. If set to NO the +# shortest path that makes the file name unique will be used +# The default value is: YES. + +FULL_PATH_NAMES = YES + +# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path. +# Stripping is only done if one of the specified strings matches the left-hand +# part of the path. The tag can be used to show relative paths in the file list. +# If left blank the directory from which doxygen is run is used as the path to +# strip. +# +# Note that you can specify absolute paths here, but also relative paths, which +# will be relative from the directory where doxygen is started. +# This tag requires that the tag FULL_PATH_NAMES is set to YES. + +STRIP_FROM_PATH = + +# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the +# path mentioned in the documentation of a class, which tells the reader which +# header file to include in order to use a class. If left blank only the name of +# the header file containing the class definition is used. Otherwise one should +# specify the list of include paths that are normally passed to the compiler +# using the -I flag. + +STRIP_FROM_INC_PATH = + +# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but +# less readable) file names. This can be useful is your file systems doesn't +# support long names like on DOS, Mac, or CD-ROM. +# The default value is: NO. + +SHORT_NAMES = NO + +# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the +# first line (until the first dot) of a Javadoc-style comment as the brief +# description. If set to NO, the Javadoc-style will behave just like regular Qt- +# style comments (thus requiring an explicit @brief command for a brief +# description.) +# The default value is: NO. + +JAVADOC_AUTOBRIEF = NO + +# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first +# line (until the first dot) of a Qt-style comment as the brief description. If +# set to NO, the Qt-style will behave just like regular Qt-style comments (thus +# requiring an explicit \brief command for a brief description.) +# The default value is: NO. + +QT_AUTOBRIEF = NO + +# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a +# multi-line C++ special comment block (i.e. a block of //! or /// comments) as +# a brief description. This used to be the default behavior. The new default is +# to treat a multi-line C++ comment block as a detailed description. Set this +# tag to YES if you prefer the old behavior instead. +# +# Note that setting this tag to YES also means that rational rose comments are +# not recognized any more. +# The default value is: NO. + +MULTILINE_CPP_IS_BRIEF = NO + +# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the +# documentation from any documented member that it re-implements. +# The default value is: YES. + +INHERIT_DOCS = YES + +# If the SEPARATE_MEMBER_PAGES tag is set to YES then doxygen will produce a new +# page for each member. If set to NO, the documentation of a member will be part +# of the file/class/namespace that contains it. +# The default value is: NO. + +SEPARATE_MEMBER_PAGES = NO + +# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen +# uses this value to replace tabs by spaces in code fragments. +# Minimum value: 1, maximum value: 16, default value: 4. + +TAB_SIZE = 4 + +# This tag can be used to specify a number of aliases that act as commands in +# the documentation. An alias has the form: +# name=value +# For example adding +# "sideeffect=@par Side Effects:\n" +# will allow you to put the command \sideeffect (or @sideeffect) in the +# documentation, which will result in a user-defined paragraph with heading +# "Side Effects:". You can put \n's in the value part of an alias to insert +# newlines. + +ALIASES = + +# This tag can be used to specify a number of word-keyword mappings (TCL only). +# A mapping has the form "name=value". For example adding "class=itcl::class" +# will allow you to use the command class in the itcl::class meaning. + +TCL_SUBST = + +# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources +# only. Doxygen will then generate output that is more tailored for C. For +# instance, some of the names that are used will be different. The list of all +# members will be omitted, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_FOR_C = YES + +# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or +# Python sources only. Doxygen will then generate output that is more tailored +# for that language. For instance, namespaces will be presented as packages, +# qualified scopes will look different, etc. +# The default value is: NO. + +OPTIMIZE_OUTPUT_JAVA = NO + +# Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran +# sources. Doxygen will then generate output that is tailored for Fortran. +# The default value is: NO. + +OPTIMIZE_FOR_FORTRAN = NO + +# Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL +# sources. Doxygen will then generate output that is tailored for VHDL. +# The default value is: NO. + +OPTIMIZE_OUTPUT_VHDL = NO + +# Doxygen selects the parser to use depending on the extension of the files it +# parses. With this tag you can assign which parser to use for a given +# extension. Doxygen has a built-in mapping, but you can override or extend it +# using this tag. The format is ext=language, where ext is a file extension, and +# language is one of the parsers supported by doxygen: IDL, Java, Javascript, +# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran: +# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran: +# Fortran. In the later case the parser tries to guess whether the code is fixed +# or free formatted code, this is the default for Fortran type files), VHDL. For +# instance to make doxygen treat .inc files as Fortran files (default is PHP), +# and .f files as C (default is Fortran), use: inc=Fortran f=C. +# +# Note: For files without extension you can use no_extension as a placeholder. +# +# Note that for custom extensions you also need to set FILE_PATTERNS otherwise +# the files are not read by doxygen. + +EXTENSION_MAPPING = + +# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments +# according to the Markdown format, which allows for more readable +# documentation. See http://daringfireball.net/projects/markdown/ for details. +# The output of markdown processing is further processed by doxygen, so you can +# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in +# case of backward compatibilities issues. +# The default value is: YES. + +MARKDOWN_SUPPORT = YES + +# When the TOC_INCLUDE_HEADINGS tag is set to a non-zero value, all headings up +# to that level are automatically included in the table of contents, even if +# they do not have an id attribute. +# Note: This feature currently applies only to Markdown headings. +# Minimum value: 0, maximum value: 99, default value: 0. +# This tag requires that the tag MARKDOWN_SUPPORT is set to YES. + +TOC_INCLUDE_HEADINGS = 0 + +# When enabled doxygen tries to link words that correspond to documented +# classes, or namespaces to their corresponding documentation. Such a link can +# be prevented in individual cases by putting a % sign in front of the word or +# globally by setting AUTOLINK_SUPPORT to NO. +# The default value is: YES. + +AUTOLINK_SUPPORT = YES + +# If you use STL classes (i.e. std::string, std::vector, etc.) but do not want +# to include (a tag file for) the STL sources as input, then you should set this +# tag to YES in order to let doxygen match functions declarations and +# definitions whose arguments contain STL classes (e.g. func(std::string); +# versus func(std::string) {}). This also make the inheritance and collaboration +# diagrams that involve STL classes more complete and accurate. +# The default value is: NO. + +BUILTIN_STL_SUPPORT = NO + +# If you use Microsoft's C++/CLI language, you should set this option to YES to +# enable parsing support. +# The default value is: NO. + +CPP_CLI_SUPPORT = NO + +# Set the SIP_SUPPORT tag to YES if your project consists of sip (see: +# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen +# will parse them like normal C++ but will assume all classes use public instead +# of private inheritance when no explicit protection keyword is present. +# The default value is: NO. + +SIP_SUPPORT = NO + +# For Microsoft's IDL there are propget and propput attributes to indicate +# getter and setter methods for a property. Setting this option to YES will make +# doxygen to replace the get and set methods by a property in the documentation. +# This will only work if the methods are indeed getting or setting a simple +# type. If this is not the case, or you want to show the methods anyway, you +# should set this option to NO. +# The default value is: YES. + +IDL_PROPERTY_SUPPORT = YES + +# If member grouping is used in the documentation and the DISTRIBUTE_GROUP_DOC +# tag is set to YES then doxygen will reuse the documentation of the first +# member in the group (if any) for the other members of the group. By default +# all members of a group must be documented explicitly. +# The default value is: NO. + +DISTRIBUTE_GROUP_DOC = NO + +# If one adds a struct or class to a group and this option is enabled, then also +# any nested class or struct is added to the same group. By default this option +# is disabled and one has to add nested compounds explicitly via \ingroup. +# The default value is: NO. + +GROUP_NESTED_COMPOUNDS = NO + +# Set the SUBGROUPING tag to YES to allow class member groups of the same type +# (for instance a group of public functions) to be put as a subgroup of that +# type (e.g. under the Public Functions section). Set it to NO to prevent +# subgrouping. Alternatively, this can be done per class using the +# \nosubgrouping command. +# The default value is: YES. + +SUBGROUPING = YES + +# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions +# are shown inside the group in which they are included (e.g. using \ingroup) +# instead of on a separate page (for HTML and Man pages) or section (for LaTeX +# and RTF). +# +# Note that this feature does not work in combination with +# SEPARATE_MEMBER_PAGES. +# The default value is: NO. + +INLINE_GROUPED_CLASSES = NO + +# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions +# with only public data fields or simple typedef fields will be shown inline in +# the documentation of the scope in which they are defined (i.e. file, +# namespace, or group documentation), provided this scope is documented. If set +# to NO, structs, classes, and unions are shown on a separate page (for HTML and +# Man pages) or section (for LaTeX and RTF). +# The default value is: NO. + +INLINE_SIMPLE_STRUCTS = NO + +# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or +# enum is documented as struct, union, or enum with the name of the typedef. So +# typedef struct TypeS {} TypeT, will appear in the documentation as a struct +# with name TypeT. When disabled the typedef will appear as a member of a file, +# namespace, or class. And the struct will be named TypeS. This can typically be +# useful for C code in case the coding convention dictates that all compound +# types are typedef'ed and only the typedef is referenced, never the tag name. +# The default value is: NO. + +TYPEDEF_HIDES_STRUCT = YES + +# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This +# cache is used to resolve symbols given their name and scope. Since this can be +# an expensive process and often the same symbol appears multiple times in the +# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small +# doxygen will become slower. If the cache is too large, memory is wasted. The +# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range +# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536 +# symbols. At the end of a run doxygen will report the cache usage and suggest +# the optimal cache size from a speed point of view. +# Minimum value: 0, maximum value: 9, default value: 0. + +LOOKUP_CACHE_SIZE = 0 + +#--------------------------------------------------------------------------- +# Build related configuration options +#--------------------------------------------------------------------------- + +# If the EXTRACT_ALL tag is set to YES, doxygen will assume all entities in +# documentation are documented, even if no documentation was available. Private +# class members and static file members will be hidden unless the +# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES. +# Note: This will also disable the warnings about undocumented members that are +# normally produced when WARNINGS is set to YES. +# The default value is: NO. + +EXTRACT_ALL = NO + +# If the EXTRACT_PRIVATE tag is set to YES, all private members of a class will +# be included in the documentation. +# The default value is: NO. + +EXTRACT_PRIVATE = NO + +# If the EXTRACT_PACKAGE tag is set to YES, all members with package or internal +# scope will be included in the documentation. +# The default value is: NO. + +EXTRACT_PACKAGE = NO + +# If the EXTRACT_STATIC tag is set to YES, all static members of a file will be +# included in the documentation. +# The default value is: NO. + +EXTRACT_STATIC = NO + +# If the EXTRACT_LOCAL_CLASSES tag is set to YES, classes (and structs) defined +# locally in source files will be included in the documentation. If set to NO, +# only classes defined in header files are included. Does not have any effect +# for Java sources. +# The default value is: YES. + +EXTRACT_LOCAL_CLASSES = NO + +# This flag is only useful for Objective-C code. If set to YES, local methods, +# which are defined in the implementation section but not in the interface are +# included in the documentation. If set to NO, only methods in the interface are +# included. +# The default value is: NO. + +EXTRACT_LOCAL_METHODS = NO + +# If this flag is set to YES, the members of anonymous namespaces will be +# extracted and appear in the documentation as a namespace called +# 'anonymous_namespace{file}', where file will be replaced with the base name of +# the file that contains the anonymous namespace. By default anonymous namespace +# are hidden. +# The default value is: NO. + +EXTRACT_ANON_NSPACES = NO + +# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all +# undocumented members inside documented classes or files. If set to NO these +# members will be included in the various overviews, but no documentation +# section is generated. This option has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_MEMBERS = NO + +# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all +# undocumented classes that are normally visible in the class hierarchy. If set +# to NO, these classes will be included in the various overviews. This option +# has no effect if EXTRACT_ALL is enabled. +# The default value is: NO. + +HIDE_UNDOC_CLASSES = NO + +# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend +# (class|struct|union) declarations. If set to NO, these declarations will be +# included in the documentation. +# The default value is: NO. + +HIDE_FRIEND_COMPOUNDS = NO + +# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any +# documentation blocks found inside the body of a function. If set to NO, these +# blocks will be appended to the function's detailed documentation block. +# The default value is: NO. + +HIDE_IN_BODY_DOCS = NO + +# The INTERNAL_DOCS tag determines if documentation that is typed after a +# \internal command is included. If the tag is set to NO then the documentation +# will be excluded. Set it to YES to include the internal documentation. +# The default value is: NO. + +INTERNAL_DOCS = NO + +# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file +# names in lower-case letters. If set to YES, upper-case letters are also +# allowed. This is useful if you have classes or files whose names only differ +# in case and if your file system supports case sensitive file names. Windows +# and Mac users are advised to set this option to NO. +# The default value is: system dependent. + +CASE_SENSE_NAMES = NO + +# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with +# their full class and namespace scopes in the documentation. If set to YES, the +# scope will be hidden. +# The default value is: NO. + +HIDE_SCOPE_NAMES = NO + +# If the HIDE_COMPOUND_REFERENCE tag is set to NO (default) then doxygen will +# append additional text to a page's title, such as Class Reference. If set to +# YES the compound reference will be hidden. +# The default value is: NO. + +HIDE_COMPOUND_REFERENCE= NO + +# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of +# the files that are included by a file in the documentation of that file. +# The default value is: YES. + +SHOW_INCLUDE_FILES = YES + +# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each +# grouped member an include statement to the documentation, telling the reader +# which file to include in order to use the member. +# The default value is: NO. + +SHOW_GROUPED_MEMB_INC = NO + +# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include +# files with double quotes in the documentation rather than with sharp brackets. +# The default value is: NO. + +FORCE_LOCAL_INCLUDES = NO + +# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the +# documentation for inline members. +# The default value is: YES. + +INLINE_INFO = YES + +# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the +# (detailed) documentation of file and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. +# The default value is: YES. + +SORT_MEMBER_DOCS = YES + +# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief +# descriptions of file, namespace and class members alphabetically by member +# name. If set to NO, the members will appear in declaration order. Note that +# this will also influence the order of the classes in the class list. +# The default value is: NO. + +SORT_BRIEF_DOCS = NO + +# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the +# (brief and detailed) documentation of class members so that constructors and +# destructors are listed first. If set to NO the constructors will appear in the +# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS. +# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief +# member documentation. +# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting +# detailed member documentation. +# The default value is: NO. + +SORT_MEMBERS_CTORS_1ST = NO + +# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy +# of group names into alphabetical order. If set to NO the group names will +# appear in their defined order. +# The default value is: NO. + +SORT_GROUP_NAMES = NO + +# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by +# fully-qualified names, including namespaces. If set to NO, the class list will +# be sorted only by class name, not including the namespace part. +# Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES. +# Note: This option applies only to the class list, not to the alphabetical +# list. +# The default value is: NO. + +SORT_BY_SCOPE_NAME = NO + +# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper +# type resolution of all parameters of a function it will reject a match between +# the prototype and the implementation of a member function even if there is +# only one candidate or it is obvious which candidate to choose by doing a +# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still +# accept a match between prototype and implementation in such cases. +# The default value is: NO. + +STRICT_PROTO_MATCHING = NO + +# The GENERATE_TODOLIST tag can be used to enable (YES) or disable (NO) the todo +# list. This list is created by putting \todo commands in the documentation. +# The default value is: YES. + +GENERATE_TODOLIST = YES + +# The GENERATE_TESTLIST tag can be used to enable (YES) or disable (NO) the test +# list. This list is created by putting \test commands in the documentation. +# The default value is: YES. + +GENERATE_TESTLIST = YES + +# The GENERATE_BUGLIST tag can be used to enable (YES) or disable (NO) the bug +# list. This list is created by putting \bug commands in the documentation. +# The default value is: YES. + +GENERATE_BUGLIST = YES + +# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or disable (NO) +# the deprecated list. This list is created by putting \deprecated commands in +# the documentation. +# The default value is: YES. + +GENERATE_DEPRECATEDLIST= YES + +# The ENABLED_SECTIONS tag can be used to enable conditional documentation +# sections, marked by \if ... \endif and \cond +# ... \endcond blocks. + +ENABLED_SECTIONS = + +# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the +# initial value of a variable or macro / define can have for it to appear in the +# documentation. If the initializer consists of more lines than specified here +# it will be hidden. Use a value of 0 to hide initializers completely. The +# appearance of the value of individual variables and macros / defines can be +# controlled using \showinitializer or \hideinitializer command in the +# documentation regardless of this setting. +# Minimum value: 0, maximum value: 10000, default value: 30. + +MAX_INITIALIZER_LINES = 30 + +# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at +# the bottom of the documentation of classes and structs. If set to YES, the +# list will mention the files that were used to generate the documentation. +# The default value is: YES. + +SHOW_USED_FILES = YES + +# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This +# will remove the Files entry from the Quick Index and from the Folder Tree View +# (if specified). +# The default value is: YES. + +SHOW_FILES = YES + +# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces +# page. This will remove the Namespaces entry from the Quick Index and from the +# Folder Tree View (if specified). +# The default value is: YES. + +SHOW_NAMESPACES = YES + +# The FILE_VERSION_FILTER tag can be used to specify a program or script that +# doxygen should invoke to get the current version for each file (typically from +# the version control system). Doxygen will invoke the program by executing (via +# popen()) the command command input-file, where command is the value of the +# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided +# by doxygen. Whatever the program writes to standard output is used as the file +# version. For an example see the documentation. + +FILE_VERSION_FILTER = + +# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed +# by doxygen. The layout file controls the global structure of the generated +# output files in an output format independent way. To create the layout file +# that represents doxygen's defaults, run doxygen with the -l option. You can +# optionally specify a file name after the option, if omitted DoxygenLayout.xml +# will be used as the name of the layout file. +# +# Note that if you run doxygen from a directory containing a file called +# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE +# tag is left empty. + +LAYOUT_FILE = + +# The CITE_BIB_FILES tag can be used to specify one or more bib files containing +# the reference definitions. This must be a list of .bib files. The .bib +# extension is automatically appended if omitted. This requires the bibtex tool +# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info. +# For LaTeX the style of the bibliography can be controlled using +# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the +# search path. See also \cite for info how to create references. + +CITE_BIB_FILES = + +#--------------------------------------------------------------------------- +# Configuration options related to warning and progress messages +#--------------------------------------------------------------------------- + +# The QUIET tag can be used to turn on/off the messages that are generated to +# standard output by doxygen. If QUIET is set to YES this implies that the +# messages are off. +# The default value is: NO. + +QUIET = NO + +# The WARNINGS tag can be used to turn on/off the warning messages that are +# generated to standard error (stderr) by doxygen. If WARNINGS is set to YES +# this implies that the warnings are on. +# +# Tip: Turn warnings on while writing the documentation. +# The default value is: YES. + +WARNINGS = YES + +# If the WARN_IF_UNDOCUMENTED tag is set to YES then doxygen will generate +# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag +# will automatically be disabled. +# The default value is: YES. + +WARN_IF_UNDOCUMENTED = YES + +# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for +# potential errors in the documentation, such as not documenting some parameters +# in a documented function, or documenting parameters that don't exist or using +# markup commands wrongly. +# The default value is: YES. + +WARN_IF_DOC_ERROR = YES + +# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that +# are documented, but have no documentation for their parameters or return +# value. If set to NO, doxygen will only warn about wrong or incomplete +# parameter documentation, but not about the absence of documentation. +# The default value is: NO. + +WARN_NO_PARAMDOC = NO + +# If the WARN_AS_ERROR tag is set to YES then doxygen will immediately stop when +# a warning is encountered. +# The default value is: NO. + +WARN_AS_ERROR = NO + +# The WARN_FORMAT tag determines the format of the warning messages that doxygen +# can produce. The string should contain the $file, $line, and $text tags, which +# will be replaced by the file and line number from which the warning originated +# and the warning text. Optionally the format may contain $version, which will +# be replaced by the version of the file (if it could be obtained via +# FILE_VERSION_FILTER) +# The default value is: $file:$line: $text. + +WARN_FORMAT = "$file:$line: $text" + +# The WARN_LOGFILE tag can be used to specify a file to which warning and error +# messages should be written. If left blank the output is written to standard +# error (stderr). + +WARN_LOGFILE = + +#--------------------------------------------------------------------------- +# Configuration options related to the input files +#--------------------------------------------------------------------------- + +# The INPUT tag is used to specify the files and/or directories that contain +# documented source files. You may enter file names like myfile.cpp or +# directories like /usr/src/myproject. Separate the files or directories with +# spaces. See also FILE_PATTERNS and EXTENSION_MAPPING +# Note: If this tag is empty the current directory is searched. + +INPUT = lib + +# This tag can be used to specify the character encoding of the source files +# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses +# libiconv (or the iconv built into libc) for the transcoding. See the libiconv +# documentation (see: http://www.gnu.org/software/libiconv) for the list of +# possible encodings. +# The default value is: UTF-8. + +INPUT_ENCODING = UTF-8 + +# If the value of the INPUT tag contains directories, you can use the +# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and +# *.h) to filter out the source-files in the directories. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# read by doxygen. +# +# If left blank the following patterns are tested:*.c, *.cc, *.cxx, *.cpp, +# *.c++, *.java, *.ii, *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, +# *.hh, *.hxx, *.hpp, *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, +# *.m, *.markdown, *.md, *.mm, *.dox, *.py, *.pyw, *.f90, *.f95, *.f03, *.f08, +# *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf and *.qsf. + +FILE_PATTERNS = *.c \ + *.cc \ + *.cxx \ + *.cpp \ + *.c++ \ + *.java \ + *.ii \ + *.ixx \ + *.ipp \ + *.i++ \ + *.inl \ + *.idl \ + *.ddl \ + *.odl \ + *.h \ + *.hh \ + *.hxx \ + *.hpp \ + *.h++ \ + *.cs \ + *.d \ + *.php \ + *.php4 \ + *.php5 \ + *.phtml \ + *.inc \ + *.m \ + *.markdown \ + *.md \ + *.mm \ + *.dox \ + *.py \ + *.pyw \ + *.f90 \ + *.f95 \ + *.f03 \ + *.f08 \ + *.f \ + *.for \ + *.tcl \ + *.vhd \ + *.vhdl \ + *.ucf \ + *.qsf + +# The RECURSIVE tag can be used to specify whether or not subdirectories should +# be searched for input files as well. +# The default value is: NO. + +RECURSIVE = NO + +# The EXCLUDE tag can be used to specify files and/or directories that should be +# excluded from the INPUT source files. This way you can easily exclude a +# subdirectory from a directory tree whose root is specified with the INPUT tag. +# +# Note that relative paths are relative to the directory from which doxygen is +# run. + +EXCLUDE = internal.h internal.c + +# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or +# directories that are symbolic links (a Unix file system feature) are excluded +# from the input. +# The default value is: NO. + +EXCLUDE_SYMLINKS = NO + +# If the value of the INPUT tag contains directories, you can use the +# EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude +# certain files from those directories. +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories for example use the pattern */test/* + +EXCLUDE_PATTERNS = + +# The EXCLUDE_SYMBOLS tag can be used to specify one or more symbol names +# (namespaces, classes, functions, etc.) that should be excluded from the +# output. The symbol name can be a fully qualified name, a word, or if the +# wildcard * is used, a substring. Examples: ANamespace, AClass, +# AClass::ANamespace, ANamespace::*Test +# +# Note that the wildcards are matched against the file with absolute path, so to +# exclude all test directories use the pattern */test/* + +EXCLUDE_SYMBOLS = + +# The EXAMPLE_PATH tag can be used to specify one or more files or directories +# that contain example code fragments that are included (see the \include +# command). + +EXAMPLE_PATH = + +# If the value of the EXAMPLE_PATH tag contains directories, you can use the +# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and +# *.h) to filter out the source-files in the directories. If left blank all +# files are included. + +EXAMPLE_PATTERNS = * + +# If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be +# searched for input files to be used with the \include or \dontinclude commands +# irrespective of the value of the RECURSIVE tag. +# The default value is: NO. + +EXAMPLE_RECURSIVE = NO + +# The IMAGE_PATH tag can be used to specify one or more files or directories +# that contain images that are to be included in the documentation (see the +# \image command). + +IMAGE_PATH = + +# The INPUT_FILTER tag can be used to specify a program that doxygen should +# invoke to filter for each input file. Doxygen will invoke the filter program +# by executing (via popen()) the command: +# +# +# +# where is the value of the INPUT_FILTER tag, and is the +# name of an input file. Doxygen will then use the output that the filter +# program writes to standard output. If FILTER_PATTERNS is specified, this tag +# will be ignored. +# +# Note that the filter must not add or remove lines; it is applied before the +# code is scanned, but not when the output code is generated. If lines are added +# or removed, the anchors will not be placed correctly. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +INPUT_FILTER = + +# The FILTER_PATTERNS tag can be used to specify filters on a per file pattern +# basis. Doxygen will compare the file name with each pattern and apply the +# filter if there is a match. The filters are a list of the form: pattern=filter +# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how +# filters are used. If the FILTER_PATTERNS tag is empty or if none of the +# patterns match the file name, INPUT_FILTER is applied. +# +# Note that for custom extensions or not directly supported extensions you also +# need to set EXTENSION_MAPPING for the extension otherwise the files are not +# properly processed by doxygen. + +FILTER_PATTERNS = + +# If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using +# INPUT_FILTER) will also be used to filter the input files that are used for +# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES). +# The default value is: NO. + +FILTER_SOURCE_FILES = NO + +# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file +# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and +# it is also possible to disable source filtering for a specific pattern using +# *.ext= (so without naming a filter). +# This tag requires that the tag FILTER_SOURCE_FILES is set to YES. + +FILTER_SOURCE_PATTERNS = + +# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that +# is part of the input, its contents will be placed on the main page +# (index.html). This can be useful if you have a project on for instance GitHub +# and want to reuse the introduction page also for the doxygen output. + +USE_MDFILE_AS_MAINPAGE = + +#--------------------------------------------------------------------------- +# Configuration options related to source browsing +#--------------------------------------------------------------------------- + +# If the SOURCE_BROWSER tag is set to YES then a list of source files will be +# generated. Documented entities will be cross-referenced with these sources. +# +# Note: To get rid of all source code in the generated output, make sure that +# also VERBATIM_HEADERS is set to NO. +# The default value is: NO. + +SOURCE_BROWSER = NO + +# Setting the INLINE_SOURCES tag to YES will include the body of functions, +# classes and enums directly into the documentation. +# The default value is: NO. + +INLINE_SOURCES = NO + +# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any +# special comment blocks from generated source code fragments. Normal C, C++ and +# Fortran comments will always remain visible. +# The default value is: YES. + +STRIP_CODE_COMMENTS = YES + +# If the REFERENCED_BY_RELATION tag is set to YES then for each documented +# function all documented functions referencing it will be listed. +# The default value is: NO. + +REFERENCED_BY_RELATION = NO + +# If the REFERENCES_RELATION tag is set to YES then for each documented function +# all documented entities called/used by that function will be listed. +# The default value is: NO. + +REFERENCES_RELATION = NO + +# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set +# to YES then the hyperlinks from functions in REFERENCES_RELATION and +# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will +# link to the documentation. +# The default value is: YES. + +REFERENCES_LINK_SOURCE = YES + +# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the +# source code will show a tooltip with additional information such as prototype, +# brief description and links to the definition and documentation. Since this +# will make the HTML file larger and loading of large files a bit slower, you +# can opt to disable this feature. +# The default value is: YES. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +SOURCE_TOOLTIPS = YES + +# If the USE_HTAGS tag is set to YES then the references to source code will +# point to the HTML generated by the htags(1) tool instead of doxygen built-in +# source browser. The htags tool is part of GNU's global source tagging system +# (see http://www.gnu.org/software/global/global.html). You will need version +# 4.8.6 or higher. +# +# To use it do the following: +# - Install the latest version of global +# - Enable SOURCE_BROWSER and USE_HTAGS in the config file +# - Make sure the INPUT points to the root of the source tree +# - Run doxygen as normal +# +# Doxygen will invoke htags (and that will in turn invoke gtags), so these +# tools must be available from the command line (i.e. in the search path). +# +# The result: instead of the source browser generated by doxygen, the links to +# source code will now point to the output of htags. +# The default value is: NO. +# This tag requires that the tag SOURCE_BROWSER is set to YES. + +USE_HTAGS = NO + +# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a +# verbatim copy of the header file for each class for which an include is +# specified. Set to NO to disable this. +# See also: Section \class. +# The default value is: YES. + +VERBATIM_HEADERS = YES + +#--------------------------------------------------------------------------- +# Configuration options related to the alphabetical class index +#--------------------------------------------------------------------------- + +# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all +# compounds will be generated. Enable this if the project contains a lot of +# classes, structs, unions or interfaces. +# The default value is: YES. + +ALPHABETICAL_INDEX = YES + +# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in +# which the alphabetical index list will be split. +# Minimum value: 1, maximum value: 20, default value: 5. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +COLS_IN_ALPHA_INDEX = 5 + +# In case all classes in a project start with a common prefix, all classes will +# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag +# can be used to specify a prefix (or a list of prefixes) that should be ignored +# while generating the index headers. +# This tag requires that the tag ALPHABETICAL_INDEX is set to YES. + +IGNORE_PREFIX = + +#--------------------------------------------------------------------------- +# Configuration options related to the HTML output +#--------------------------------------------------------------------------- + +# If the GENERATE_HTML tag is set to YES, doxygen will generate HTML output +# The default value is: YES. + +GENERATE_HTML = YES + +# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a +# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of +# it. +# The default directory is: html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_OUTPUT = html + +# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each +# generated HTML page (for example: .htm, .php, .asp). +# The default value is: .html. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FILE_EXTENSION = .html + +# The HTML_HEADER tag can be used to specify a user-defined HTML header file for +# each generated HTML page. If the tag is left blank doxygen will generate a +# standard header. +# +# To get valid HTML the header file that includes any scripts and style sheets +# that doxygen needs, which is dependent on the configuration options used (e.g. +# the setting GENERATE_TREEVIEW). It is highly recommended to start with a +# default header using +# doxygen -w html new_header.html new_footer.html new_stylesheet.css +# YourConfigFile +# and then modify the file new_header.html. See also section "Doxygen usage" +# for information on how to generate the default header that doxygen normally +# uses. +# Note: The header is subject to change so you typically have to regenerate the +# default header when upgrading to a newer version of doxygen. For a description +# of the possible markers and block names see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_HEADER = + +# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each +# generated HTML page. If the tag is left blank doxygen will generate a standard +# footer. See HTML_HEADER for more information on how to generate a default +# footer and what special commands can be used inside the footer. See also +# section "Doxygen usage" for information on how to generate the default footer +# that doxygen normally uses. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_FOOTER = + +# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style +# sheet that is used by each HTML page. It can be used to fine-tune the look of +# the HTML output. If left blank doxygen will generate a default style sheet. +# See also section "Doxygen usage" for information on how to generate the style +# sheet that doxygen normally uses. +# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as +# it is more robust and this tag (HTML_STYLESHEET) will in the future become +# obsolete. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_STYLESHEET = + +# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined +# cascading style sheets that are included after the standard style sheets +# created by doxygen. Using this option one can overrule certain style aspects. +# This is preferred over using HTML_STYLESHEET since it does not replace the +# standard style sheet and is therefore more robust against future updates. +# Doxygen will copy the style sheet files to the output directory. +# Note: The order of the extra style sheet files is of importance (e.g. the last +# style sheet in the list overrules the setting of the previous ones in the +# list). For an example see the documentation. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_STYLESHEET = + +# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or +# other source files which should be copied to the HTML output directory. Note +# that these files will be copied to the base HTML output directory. Use the +# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these +# files. In the HTML_STYLESHEET file, use the file name only. Also note that the +# files will be copied as-is; there are no commands or markers available. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_EXTRA_FILES = + +# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen +# will adjust the colors in the style sheet and background images according to +# this color. Hue is specified as an angle on a colorwheel, see +# http://en.wikipedia.org/wiki/Hue for more information. For instance the value +# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300 +# purple, and 360 is red again. +# Minimum value: 0, maximum value: 359, default value: 220. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_HUE = 220 + +# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors +# in the HTML output. For a value of 0 the output will use grayscales only. A +# value of 255 will produce the most vivid colors. +# Minimum value: 0, maximum value: 255, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_SAT = 100 + +# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the +# luminance component of the colors in the HTML output. Values below 100 +# gradually make the output lighter, whereas values above 100 make the output +# darker. The value divided by 100 is the actual gamma applied, so 80 represents +# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not +# change the gamma. +# Minimum value: 40, maximum value: 240, default value: 80. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_COLORSTYLE_GAMMA = 80 + +# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML +# page will contain the date and time when the page was generated. Setting this +# to YES can help to show when doxygen was last run and thus if the +# documentation is up to date. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_TIMESTAMP = NO + +# If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML +# documentation will contain sections that can be hidden and shown after the +# page has loaded. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_DYNAMIC_SECTIONS = NO + +# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries +# shown in the various tree structured indices initially; the user can expand +# and collapse entries dynamically later on. Doxygen will expand the tree to +# such a level that at most the specified number of entries are visible (unless +# a fully collapsed tree already exceeds this amount). So setting the number of +# entries 1 will produce a full collapsed tree by default. 0 is a special value +# representing an infinite number of entries and will result in a full expanded +# tree by default. +# Minimum value: 0, maximum value: 9999, default value: 100. +# This tag requires that the tag GENERATE_HTML is set to YES. + +HTML_INDEX_NUM_ENTRIES = 100 + +# If the GENERATE_DOCSET tag is set to YES, additional index files will be +# generated that can be used as input for Apple's Xcode 3 integrated development +# environment (see: http://developer.apple.com/tools/xcode/), introduced with +# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a +# Makefile in the HTML output directory. Running make will produce the docset in +# that directory and running make install will install the docset in +# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at +# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html +# for more information. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_DOCSET = NO + +# This tag determines the name of the docset feed. A documentation feed provides +# an umbrella under which multiple documentation sets from a single provider +# (such as a company or product suite) can be grouped. +# The default value is: Doxygen generated docs. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_FEEDNAME = "Doxygen generated docs" + +# This tag specifies a string that should uniquely identify the documentation +# set bundle. This should be a reverse domain-name style string, e.g. +# com.mycompany.MyDocSet. Doxygen will append .docset to the name. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_BUNDLE_ID = org.doxygen.Project + +# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify +# the documentation publisher. This should be a reverse domain-name style +# string, e.g. com.mycompany.MyDocSet.documentation. +# The default value is: org.doxygen.Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_ID = org.doxygen.Publisher + +# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher. +# The default value is: Publisher. +# This tag requires that the tag GENERATE_DOCSET is set to YES. + +DOCSET_PUBLISHER_NAME = Publisher + +# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three +# additional HTML index files: index.hhp, index.hhc, and index.hhk. The +# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop +# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on +# Windows. +# +# The HTML Help Workshop contains a compiler that can convert all HTML output +# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML +# files are now used as the Windows 98 help format, and will replace the old +# Windows help format (.hlp) on all Windows platforms in the future. Compressed +# HTML files also contain an index, a table of contents, and you can search for +# words in the documentation. The HTML workshop also contains a viewer for +# compressed HTML files. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_HTMLHELP = NO + +# The CHM_FILE tag can be used to specify the file name of the resulting .chm +# file. You can add a path in front of the file if the result should not be +# written to the html output directory. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_FILE = + +# The HHC_LOCATION tag can be used to specify the location (absolute path +# including file name) of the HTML help compiler (hhc.exe). If non-empty, +# doxygen will try to run the HTML help compiler on the generated index.hhp. +# The file has to be specified with full path. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +HHC_LOCATION = + +# The GENERATE_CHI flag controls if a separate .chi index file is generated +# (YES) or that it should be included in the master .chm file (NO). +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +GENERATE_CHI = NO + +# The CHM_INDEX_ENCODING is used to encode HtmlHelp index (hhk), content (hhc) +# and project file content. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +CHM_INDEX_ENCODING = + +# The BINARY_TOC flag controls whether a binary table of contents is generated +# (YES) or a normal table of contents (NO) in the .chm file. Furthermore it +# enables the Previous and Next buttons. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +BINARY_TOC = NO + +# The TOC_EXPAND flag can be set to YES to add extra items for group members to +# the table of contents of the HTML help documentation and to the tree view. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTMLHELP is set to YES. + +TOC_EXPAND = NO + +# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and +# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that +# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help +# (.qch) of the generated HTML documentation. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_QHP = NO + +# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify +# the file name of the resulting .qch file. The path specified is relative to +# the HTML output folder. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QCH_FILE = + +# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help +# Project output. For more information please see Qt Help Project / Namespace +# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace). +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_NAMESPACE = org.doxygen.Project + +# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt +# Help Project output. For more information please see Qt Help Project / Virtual +# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual- +# folders). +# The default value is: doc. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_VIRTUAL_FOLDER = doc + +# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom +# filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_NAME = + +# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the +# custom filter to add. For more information please see Qt Help Project / Custom +# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom- +# filters). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_CUST_FILTER_ATTRS = + +# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this +# project's filter section matches. Qt Help Project / Filter Attributes (see: +# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes). +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHP_SECT_FILTER_ATTRS = + +# The QHG_LOCATION tag can be used to specify the location of Qt's +# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the +# generated .qhp file. +# This tag requires that the tag GENERATE_QHP is set to YES. + +QHG_LOCATION = + +# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be +# generated, together with the HTML files, they form an Eclipse help plugin. To +# install this plugin and make it available under the help contents menu in +# Eclipse, the contents of the directory containing the HTML and XML files needs +# to be copied into the plugins directory of eclipse. The name of the directory +# within the plugins directory should be the same as the ECLIPSE_DOC_ID value. +# After copying Eclipse needs to be restarted before the help appears. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_ECLIPSEHELP = NO + +# A unique identifier for the Eclipse help plugin. When installing the plugin +# the directory name containing the HTML and XML files should also have this +# name. Each documentation set should have its own identifier. +# The default value is: org.doxygen.Project. +# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES. + +ECLIPSE_DOC_ID = org.doxygen.Project + +# If you want full control over the layout of the generated HTML pages it might +# be necessary to disable the index and replace it with your own. The +# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top +# of each HTML page. A value of NO enables the index and the value YES disables +# it. Since the tabs in the index contain the same information as the navigation +# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +DISABLE_INDEX = NO + +# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index +# structure should be generated to display hierarchical information. If the tag +# value is set to YES, a side panel will be generated containing a tree-like +# index structure (just like the one that is generated for HTML Help). For this +# to work a browser that supports JavaScript, DHTML, CSS and frames is required +# (i.e. any modern browser). Windows users are probably better off using the +# HTML help feature. Via custom style sheets (see HTML_EXTRA_STYLESHEET) one can +# further fine-tune the look of the index. As an example, the default style +# sheet generated by doxygen has an example that shows how to put an image at +# the root of the tree instead of the PROJECT_NAME. Since the tree basically has +# the same information as the tab index, you could consider setting +# DISABLE_INDEX to YES when enabling this option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +GENERATE_TREEVIEW = YES + +# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that +# doxygen will group on one line in the generated HTML documentation. +# +# Note that a value of 0 will completely suppress the enum values from appearing +# in the overview section. +# Minimum value: 0, maximum value: 20, default value: 4. +# This tag requires that the tag GENERATE_HTML is set to YES. + +ENUM_VALUES_PER_LINE = 4 + +# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used +# to set the initial width (in pixels) of the frame in which the tree is shown. +# Minimum value: 0, maximum value: 1500, default value: 250. +# This tag requires that the tag GENERATE_HTML is set to YES. + +TREEVIEW_WIDTH = 250 + +# If the EXT_LINKS_IN_WINDOW option is set to YES, doxygen will open links to +# external symbols imported via tag files in a separate window. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +EXT_LINKS_IN_WINDOW = NO + +# Use this tag to change the font size of LaTeX formulas included as images in +# the HTML documentation. When you change the font size after a successful +# doxygen run you need to manually remove any form_*.png images from the HTML +# output directory to force them to be regenerated. +# Minimum value: 8, maximum value: 50, default value: 10. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_FONTSIZE = 10 + +# Use the FORMULA_TRANPARENT tag to determine whether or not the images +# generated for formulas are transparent PNGs. Transparent PNGs are not +# supported properly for IE 6.0, but are supported on all modern browsers. +# +# Note that when changing this option you need to delete any form_*.png files in +# the HTML output directory before the changes have effect. +# The default value is: YES. +# This tag requires that the tag GENERATE_HTML is set to YES. + +FORMULA_TRANSPARENT = YES + +# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see +# http://www.mathjax.org) which uses client side Javascript for the rendering +# instead of using pre-rendered bitmaps. Use this if you do not have LaTeX +# installed or if you want to formulas look prettier in the HTML output. When +# enabled you may also need to install MathJax separately and configure the path +# to it using the MATHJAX_RELPATH option. +# The default value is: NO. +# This tag requires that the tag GENERATE_HTML is set to YES. + +USE_MATHJAX = NO + +# When MathJax is enabled you can set the default output format to be used for +# the MathJax output. See the MathJax site (see: +# http://docs.mathjax.org/en/latest/output.html) for more details. +# Possible values are: HTML-CSS (which is slower, but has the best +# compatibility), NativeMML (i.e. MathML) and SVG. +# The default value is: HTML-CSS. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_FORMAT = HTML-CSS + +# When MathJax is enabled you need to specify the location relative to the HTML +# output directory using the MATHJAX_RELPATH option. The destination directory +# should contain the MathJax.js script. For instance, if the mathjax directory +# is located at the same level as the HTML output directory, then +# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax +# Content Delivery Network so you can quickly see the result without installing +# MathJax. However, it is strongly recommended to install a local copy of +# MathJax from http://www.mathjax.org before deployment. +# The default value is: http://cdn.mathjax.org/mathjax/latest. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_RELPATH = http://cdn.mathjax.org/mathjax/latest + +# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax +# extension names that should be enabled during MathJax rendering. For example +# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_EXTENSIONS = + +# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces +# of code that will be used on startup of the MathJax code. See the MathJax site +# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an +# example see the documentation. +# This tag requires that the tag USE_MATHJAX is set to YES. + +MATHJAX_CODEFILE = + +# When the SEARCHENGINE tag is enabled doxygen will generate a search box for +# the HTML output. The underlying search engine uses javascript and DHTML and +# should work on any modern browser. Note that when using HTML help +# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET) +# there is already a search function so this one should typically be disabled. +# For large projects the javascript based search engine can be slow, then +# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to +# search using the keyboard; to jump to the search box use + S +# (what the is depends on the OS and browser, but it is typically +# , /