keyring/0000755000176200001440000000000015023633252011723 5ustar liggesuserskeyring/tests/0000755000176200001440000000000014521172457013074 5ustar liggesuserskeyring/tests/testthat/0000755000176200001440000000000015023633252014725 5ustar liggesuserskeyring/tests/testthat/test-utils.R0000644000176200001440000000321315006400341017154 0ustar liggesuserstest_that("base64", { expect_equal(base64_encode(charToRaw("foobar")), "Zm9vYmFy") expect_equal(base64_encode(charToRaw(" ")), "IA==") expect_equal(base64_encode(charToRaw("")), "") x <- charToRaw(paste(sample(letters, 10000, replace = TRUE), collapse = "")) expect_equal(base64_decode(base64_encode(x)), x) for (i in 5:32) { mtcars2 <- unserialize(base64_decode(base64_encode( serialize(mtcars[1:i, ], NULL) ))) expect_identical(mtcars[1:i, ], mtcars2) } expect_snapshot( base64_decode("oi7mFx/aLCc3qZ7vQMQQdwwiGq32gB3ylYm6urM9aGY=") ) }) test_that("sha256", { x <- charToRaw(basename(tempfile())) expect_equal(sha256(x), unclass(openssl::sha256(x))) key <- sha256(x) txt <- charToRaw("foobar") expect_equal(sha256(txt, key), unclass(openssl::sha256(txt, key))) }) test_that("aes_cbc_encrypt, aes_cbc_decrypt", { x <- charToRaw("foobar") key <- sha256(charToRaw("secret")) y <- aes_cbc_encrypt(x, key) iv <- attr(y, "iv") expect_equal(y, openssl::aes_cbc_encrypt(x, key, iv = iv)) expect_equal(aes_cbc_decrypt(y, key), x) # wrong key # fix iv, so we don't accidentally get a bad key that actually "works" iv <- as.raw(c( 0xe2, 0x2d, 0x43, 0x22, 0x86, 0x3f, 0x02, 0x11, 0x90, 0x98, 0xd8, 0x97, 0x1a, 0xb2, 0x7b, 0x74 )) y <- aes_cbc_encrypt(x, key, iv = iv) key2 <- sha256(charToRaw("bad")) expect_snapshot(error = TRUE, aes_cbc_decrypt(y, key2)) # other errors expect_snapshot(error = TRUE, { aes_cbc_encrypt(x, raw(5), iv = iv) aes_cbc_encrypt(x, key, iv = raw(10)) aes_cbc_decrypt(raw(17), key, iv) }) }) keyring/tests/testthat/test-secret-service.R0000644000176200001440000000372014521172457020761 0ustar liggesusersopts <- options(keyring_warn_for_env_fallback = FALSE) on.exit(options(opts), add = TRUE) test_that("specify keyring explicitly", { skip_if_not_secret_service() skip_on_cran() service <- random_service() username <- random_username() password <- random_password() kb <- backend_secret_service$new("Login") expect_silent( kb$set_with_value(service, username, password) ) expect_equal(kb$get(service, username), password) expect_silent(kb$delete(service, username)) }) test_that("creating keychains", { skip("requires interaction") skip_if_not_secret_service() skip_on_cran() keyring <- random_keyring() kb <- backend_secret_service$new(keyring = keyring) kb$keyring_create(keyring = keyring) kb$keyring_list() service <- random_service() username <- random_username() password <- random_password() expect_silent( kb$set_with_value(service, username, password) ) expect_equal(kb$get(service, username), password) expect_silent(kb$delete(service, username)) expect_silent(kb$keyring_delete(keyring = keyring)) expect_false(keyring %in% keyring_list()$keyring) }) test_that("lock/unlock keyrings", { skip("requires interaction") skip_if_not_secret_service() skip_on_cran() keyring <- random_keyring() kb <- backend_secret_service$new(keyring = keyring) # interactive kb$.__enclos_env__$private$keyring_create_direct(keyring) ## It is unlocked by default expect_false(kb$keyring_is_locked()) list <- kb$keyring_list() expect_true(keyring %in% list$keyring) expect_false(list$locked[match(keyring, list$keyring)]) ## Lock it kb$keyring_lock() expect_true(kb$keyring_is_locked()) list <- kb$keyring_list() expect_true(list$locked[match(keyring, list$keyring)]) ## Unlock it (interactive) kb$keyring_unlock() expect_false(kb$keyring_is_locked()) list <- keyring_list() expect_false(list$locked[match(keyring, list$keyring)]) expect_silent(kb$keyring_delete(keyring = keyring)) }) keyring/tests/testthat/test-file.R0000644000176200001440000001777715004361550016765 0ustar liggesuserstest_that("specify keyring explicitly", { dir.create(tmp <- tempfile()) on.exit(unlink(tmp, recursive = TRUE)) withr::local_options(list(keyring_file_dir = tmp)) service_1 <- random_service() username <- random_username() password <- random_password() password2 <- random_password() keyring <- random_keyring() kb <- backend_file$new(keyring = keyring) kb$keyring_create(keyring, "secret123!") expect_false(kb$keyring_is_locked(keyring)) kb$keyring_lock(keyring) expect_true(kb$keyring_is_locked(keyring)) expect_silent(kb$keyring_unlock(keyring, password = "secret123!")) expect_false(kb$keyring_is_locked(keyring)) ## Missing expect_error(kb$get(service_1, username), "could not be found") expect_silent(kb$set_with_value(service_1, username, password)) expect_equal(kb$get(service_1, username), password) ## Missing expect_error(kb$get(service_1, "foobar"), "could not be found") ## Overwrite expect_silent(kb$set_with_value(service_1, username, password2)) expect_equal(kb$get(service_1, username), password2) expect_silent(kb$set_with_value(random_service(), username, password)) long_password <- random_string(500L) service_2 <- random_service() expect_silent(kb$set_with_value(service_2, username, long_password)) expect_equal(kb$get(service_2, username), long_password) ## Delete expect_silent(kb$delete(service_1, username)) expect_error(kb$get(service_1, username), "could not be found") ## Delete non-existent is silent expect_silent(kb$delete(service_1, username)) expect_silent(kb$keyring_delete()) }) test_that("key consistency check", { username <- random_username() password <- random_password() keyring <- random_keyring() dir.create(tmp <- tempfile()) on.exit(unlink(tmp, recursive = TRUE), add = TRUE) withr::local_options(list(keyring_file_dir = tmp)) keyring_pwd_1 <- random_password() keyring_pwd_2 <- random_password() kb <- backend_file$new(keyring = keyring) kb$keyring_create(keyring, keyring_pwd_1) expect_silent(kb$keyring_unlock(password = keyring_pwd_1)) expect_silent(kb$set_with_value(random_service(), username, password)) expect_error( kb$keyring_unlock(password = keyring_pwd_2), "cannot unlock keyring" ) expect_silent(kb$keyring_lock()) expect_error( kb$keyring_unlock(password = keyring_pwd_2), "cannot unlock keyring" ) kb$.__enclos_env__$private$set_keyring_pass(keyring_pwd_2) expect_true(kb$keyring_is_locked()) kb$.__enclos_env__$private$unset_keyring_pass() expect_silent(kb$keyring_delete()) }) test_that("use non-default keyring", { dir.create(tmp <- tempfile()) on.exit(unlink(tmp, recursive = TRUE), add = TRUE) withr::local_options(list(keyring_file_dir = tmp)) service <- random_service() username <- random_username() password <- random_password() default_keyring <- random_keyring() keyring <- random_keyring() default_keyring_pwd <- random_password() keyring_pwd <- random_password() kb <- backend_file$new(keyring = default_keyring) kb$keyring_create(password = default_keyring_pwd) kb$keyring_create(keyring, keyring_pwd) expect_silent(kb$keyring_unlock(password = default_keyring_pwd)) expect_false(kb$keyring_is_locked()) expect_silent(kb$keyring_unlock(keyring, keyring_pwd)) expect_false(kb$keyring_is_locked(keyring)) expect_false(kb$keyring_is_locked()) expect_silent(kb$set_with_value(service, username, password, keyring)) expect_equal(kb$get(service, username, keyring), password) expect_silent( all_items <- kb$list(keyring = keyring) ) expect_s3_class(all_items, "data.frame") expect_equal(nrow(all_items), 1L) expect_named(all_items, c("service", "username")) expect_silent(kb$keyring_delete()) expect_silent(kb$keyring_delete(keyring)) }) test_that("list keyring items", { dir.create(tmp <- tempfile()) on.exit(unlink(tmp, recursive = TRUE), add = TRUE) withr::local_options(list(keyring_file_dir = tmp)) service <- random_service() username <- random_username() keyring <- random_keyring() keyring_pwd <- random_password() kb <- backend_file$new(keyring) kb$keyring_create(keyring, keyring_pwd) expect_silent(kb$keyring_unlock(password = keyring_pwd)) expect_silent(kb$set_with_value( random_service(), random_username(), random_password() )) expect_silent(kb$set_with_value( service, random_username(), random_password() )) expect_silent(kb$set_with_value( service, random_username(), random_password() )) expect_silent( all_items <- kb$list() ) expect_s3_class(all_items, "data.frame") expect_equal(nrow(all_items), 3L) expect_named(all_items, c("service", "username")) expect_silent( some_items <- kb$list(service) ) expect_s3_class(some_items, "data.frame") expect_equal(nrow(some_items), 2L) expect_named(some_items, c("service", "username")) invisible(sapply(some_items[["service"]], expect_identical, service)) expect_silent(kb$keyring_delete(keyring)) }) test_that("helper functions work", { secret <- random_password() long_secret <- random_string(500L) nonce <- sodium_random(24L) password <- sodium_hash(charToRaw(random_password())) expect_identical(b_file_split_string(secret), secret) expect_true( is_string( split_key <- b_file_split_string(long_secret) ) ) expect_match(split_key, "\\n") expect_identical(b_file_merge_string(split_key), long_secret) expect_identical( b_file_secret_decrypt( b_file_secret_encrypt(secret, nonce, password), nonce, password ), secret ) expect_identical( b_file_secret_decrypt( b_file_secret_encrypt(long_secret, nonce, password), nonce, password ), long_secret ) }) test_that("keys updated from another session", { skip_on_cran() dir.create(tmp <- tempfile()) on.exit(unlink(tmp, recursive = TRUE), add = TRUE) withr::local_options(list(keyring_file_dir = tmp)) service_1 <- random_service() username <- random_username() username2 <- random_username() password <- random_password() password2 <- random_password() keyring <- random_keyring() kb <- backend_file$new(keyring = keyring) kb$keyring_create(keyring, "foobar") kb$keyring_unlock(password = "foobar") kb$set_with_value(service_1, username, password) ret <- callr::r( function(s, u, p, k, dir) { options(keyring_file_dir = dir) kb <- keyring::backend_file$new(keyring = k) kb$keyring_unlock(password = "foobar") kb$set_with_value(s, u, p) kb$get(s, u) }, args = list( s = service_1, u = username2, p = password2, k = keyring, dir = tmp ) ) expect_equal(ret, password2) expect_equal(kb$get(service_1, username), password) expect_equal(kb$get(service_1, username2), password2) expect_equal(kb$get(service_1, username), password) }) test_that("locking the keyring file", { skip_on_cran() dir.create(tmp <- tempfile()) on.exit(unlink(tmp, recursive = TRUE), add = TRUE) withr::local_options(list(keyring_file_dir = tmp)) service_1 <- random_service() username <- random_username() password <- random_password() keyring <- random_keyring() kb <- backend_file$new(keyring = keyring) kb$keyring_create(password = "foobar") lockfile <- paste0(kb$.__enclos_env__$private$keyring_file(), ".lck") rb <- callr::r_bg( function(lf) { l <- filelock::lock(lf) cat("done\n") Sys.sleep(3) }, args = list(lf = lockfile), stdout = "|" ) on.exit(rb$kill(), add = TRUE) rb$poll_io(3000) withr::with_options( list(keyring_file_lock_timeout = 100), expect_snapshot( error = TRUE, kb$set_with_value(service_1, username, password) ) ) }) test_that("keyring does not exist", { dir.create(tmp <- tempfile()) on.exit(unlink(tmp, recursive = TRUE)) withr::local_options(list(keyring_file_dir = tmp)) kb <- backend_file$new() expect_snapshot(error = TRUE, { kb$list() kb$keyring_is_locked() kb$keyring_unlock() kb$set_with_value("service", "user", "pass") }) }) keyring/tests/testthat/helper.R0000644000176200001440000000243115004361550016325 0ustar liggesusersskip_if_not_macos <- function() { sysname <- tolower(Sys.info()[["sysname"]]) if (sysname != "darwin") skip("Not macOS") invisible(TRUE) } skip_if_not_win <- function() { sysname <- tolower(Sys.info()[["sysname"]]) if (sysname != "windows") skip("Not windows") invisible(TRUE) } skip_if_not_linux <- function() { sysname <- tolower(Sys.info()[["sysname"]]) if (sysname != "linux") skip("Not Linux") invisible(TRUE) } skip_if_not_secret_service <- function() { if (default_backend()$name != "secret service") skip("Not secret service") invisible(TRUE) } random_string <- function(length = 10, use_letters = TRUE, use_numbers = TRUE) { pool <- c( if (use_letters) c(letters, LETTERS), if (use_numbers) 0:9 ) paste( sample(pool, length, replace = TRUE), collapse = "" ) } random_service <- function() { paste0( "R-keyring-test-service-", random_string(15, use_numbers = FALSE) ) } random_username <- function() { random_string(10, use_numbers = FALSE) } random_password <- function() { random_string(16) } random_keyring <- function() { paste0( "Rkeyringtest", random_string(8, use_numbers = FALSE) ) } new_empty_dir <- function() { new <- tempfile() unlink(new, recursive = TRUE, force = TRUE) dir.create(new) new } keyring/tests/testthat/test-wincred.R0000644000176200001440000000570715004361550017467 0ustar liggesuserstest_that("low level API", { skip_if_not_win() skip_on_cran() keyring <- random_keyring() service <- random_service() username <- random_username() password <- random_password() target <- b_wincred_target(keyring, service, username) expect_false(b_wincred_i_exists(target)) expect_silent(b_wincred_i_set( target, charToRaw(password), username, session = TRUE )) expect_true(b_wincred_i_exists(target)) expect_equal(rawToChar(b_wincred_i_get(target)), password) expect_true(target %in% b_wincred_i_enumerate("*")) expect_silent(b_wincred_i_delete(target)) expect_false(b_wincred_i_exists(target)) expect_false(target %in% b_wincred_i_enumerate("*")) }) test_that("creating keychains", { skip_if_not_win() skip_on_cran() keyring <- random_keyring() kb <- backend_wincred$new(keyring = keyring) kb$.__enclos_env__$private$keyring_create_direct(keyring, "secret123!") expect_true(keyring %in% kb$keyring_list()$keyring) list <- kb$list() expect_equal(nrow(list), 0) service <- random_service() username <- random_username() password <- random_password() expect_silent( kb$set_with_value(service, username, password) ) expect_equal(kb$get(service, username), password) expect_silent(kb$delete(service, username)) expect_silent(kb$keyring_delete(keyring = keyring)) expect_false(keyring %in% kb$keyring_list()$keyring) }) test_that("lock/unlock keyrings", { skip_if_not_win() skip_on_cran() keyring <- random_keyring() kb <- backend_wincred$new(keyring = keyring) kb$.__enclos_env__$private$keyring_create_direct(keyring, "secret123!") ## It is unlocked by default expect_false(kb$keyring_is_locked()) list <- kb$keyring_list() expect_true(keyring %in% list$keyring) expect_false(list$locked[match(keyring, list$keyring)]) ## Lock it kb$keyring_lock() expect_true(kb$keyring_is_locked()) list <- keyring_list() expect_true(list$locked[match(keyring, list$keyring)]) ## Unlock it kb$keyring_unlock(password = "secret123!") expect_false(kb$keyring_is_locked()) list <- kb$keyring_list() expect_false(list$locked[match(keyring, list$keyring)]) expect_silent(kb$keyring_delete(keyring = keyring)) }) test_that(": in keyring, service and usernames", { skip_if_not_win() skip_on_cran() keyring <- paste0("foo:", random_keyring()) service <- paste0("bar:", random_service()) username <- paste0("foobar:", random_username()) password <- random_password() target <- b_wincred_target(keyring, service, username) expect_false(b_wincred_i_exists(target)) expect_silent(b_wincred_i_set( target, charToRaw(password), username, session = TRUE )) expect_true(b_wincred_i_exists(target)) expect_equal(rawToChar(b_wincred_i_get(target)), password) expect_true(target %in% b_wincred_i_enumerate("*")) expect_silent(b_wincred_i_delete(target)) expect_false(b_wincred_i_exists(target)) expect_false(target %in% b_wincred_i_enumerate("*")) }) keyring/tests/testthat/helper-fake.R0000644000176200001440000000621414760120011017225 0ustar liggesusersfake <- local({ fake_through_tree <- function(tree, what, how) { for (d in tree) { for (parent in d) { parent_env <- parent[["parent_env"]] func_dict <- parent[["funcs"]] for (func_name in ls(func_dict, all.names = TRUE)) { func <- func_dict[[func_name]] func_env <- new.env(parent = environment(func)) what <- override_seperators(what, func_env) where_name <- override_seperators(func_name, parent_env) if (!is.function(how)) { assign(what, function(...) how, func_env) } else { assign(what, how, func_env) } environment(func) <- func_env locked <- exists(where_name, parent_env, inherits = FALSE) && bindingIsLocked(where_name, parent_env) if (locked) { baseenv()$unlockBinding(where_name, parent_env) } assign(where_name, func, parent_env) if (locked) { lockBinding(where_name, parent_env) } } } } } override_seperators <- function(name, env) { mangled_name <- NULL for (sep in c("::", "$")) { if (grepl(sep, name, fixed = TRUE)) { elements <- strsplit(name, sep, fixed = TRUE) mangled_name <- paste( elements[[1L]][1L], elements[[1L]][2L], sep = "XXX" ) stub_list <- c(mangled_name) if ("stub_list" %in% names(attributes(get(sep, env)))) { stub_list <- c(stub_list, attributes(get(sep, env))[["stub_list"]]) } create_new_name <- create_create_new_name_function( stub_list, env, sep ) assign(sep, create_new_name, env) } } mangled_name %||% name } backtick <- function(x) { encodeString(x, quote = "`", na.encode = FALSE) } create_create_new_name_function <- function(stub_list, env, sep) { force(stub_list) force(env) force(sep) create_new_name <- function(pkg, func) { pkg_name <- deparse(substitute(pkg)) func_name <- deparse(substitute(func)) for (stub in stub_list) { if (paste(pkg_name, func_name, sep = "XXX") == stub) { return(eval(parse(text = backtick(stub)), env)) } } # used to avoid recursively calling the replacement function eval_env <- new.env(parent = parent.frame()) assign(sep, eval(parse(text = paste0("`", sep, "`"))), eval_env) code <- paste(pkg_name, backtick(func_name), sep = sep) return(eval(parse(text = code), eval_env)) } attributes(create_new_name) <- list(stub_list = stub_list) create_new_name } build_function_tree <- function(test_env, where, where_name) { func_dict <- new.env() func_dict[[where_name]] <- where tree <- list( list( list(parent_env = test_env, funcs = func_dict) ) ) tree } fake <- function(where, what, how) { where_name <- deparse(substitute(where)) stopifnot(is.character(what), length(what) == 1) test_env <- parent.frame() tree <- build_function_tree(test_env, where, where_name) fake_through_tree(tree, what, how) } }) keyring/tests/testthat/test-macos.R0000644000176200001440000001231415004361550017126 0ustar liggesuserstest_that("specify keyring explicitly", { skip_if_not_macos() skip_on_cran() service <- random_service() username <- random_username() password <- random_password() kb <- backend_macos$new(keyring = "login") expect_silent( kb$set_with_value(service, username, password) ) expect_equal(kb$get(service, username), password) expect_silent(kb$delete(service, username)) }) test_that("creating keychains", { skip_if_not_macos() skip_on_cran() keyring <- random_keyring() kb <- backend_macos$new() ## To avoid an interactive password kb$.__enclos_env__$private$keyring_create_direct(keyring, "secret123!") list <- kb$list(keyring = keyring) expect_equal(nrow(list), 0) service <- random_service() username <- random_username() password <- random_password() expect_silent( kb$set_with_value(service, username, password) ) expect_equal(kb$get(service, username), password) expect_silent(kb$delete(service, username)) expect_silent(kb$keyring_delete(keyring = keyring)) expect_false(keyring %in% kb$keyring_list()$keyring) }) test_that("creating keychains 2", { skip_if_not_macos() skip_on_cran() keyring <- random_keyring() kb <- backend_macos$new() ## To avoid an interactive password kb$.__enclos_env__$private$keyring_create_direct(keyring, "secret") kb$keyring_set_default(keyring) service <- random_service() username <- random_username() password <- random_password() expect_silent( kb$set_with_value(service, username, password) ) expect_equal(kb$get(service, username), password) expect_silent(kb$delete(service, username)) expect_silent(kb$keyring_delete(keyring = keyring)) expect_false(keyring %in% kb$keyring_list()$keyring) }) test_that("keyring file at special location", { skip_if_not_macos() skip_on_cran() keyring <- tempfile(fileext = ".keychain") kb <- backend_macos$new(keyring = keyring) kb$.__enclos_env__$private$keyring_create_direct(keyring, "secret123!") service <- random_service() username <- random_username() password <- random_password() expect_silent( kb$set_with_value(service, username, password) ) expect_equal(kb$get(service, username), password) expect_silent(kb$delete(service, username)) expect_silent(kb$keyring_delete(keyring = keyring)) expect_false(keyring %in% kb$keyring_list()$keyring) expect_false(file.exists(keyring)) }) test_that("errors", { skip_if_not_macos() skip_on_cran() ## Non-existing keychain expect_snapshot(error = TRUE, backend_macos$new(tempfile())$list()) ## Getting non-existing password expect_snapshot( error = TRUE, backend_macos$new()$get(random_service(), random_username()) ) ## Deleting non-existing password expect_snapshot( error = TRUE, backend_macos$new()$delete(random_service(), random_username()) ) ## Create keychain without access to file kb <- backend_macos$new() expect_snapshot( error = TRUE, kb$.__enclos_env__$private$keyring_create_direct("/xxx", "secret123!") ) }) test_that("lock/unlock keyrings", { skip_if_not_macos() skip_on_cran() keyring <- random_keyring() kb <- backend_macos$new(keyring = keyring) kb$.__enclos_env__$private$keyring_create_direct(keyring, "secret123!") ## It is unlocked by default expect_false(kb$keyring_is_locked()) list <- kb$keyring_list() expect_true(keyring %in% list$keyring) expect_false(list$locked[match(keyring, list$keyring)]) ## Lock it kb$keyring_lock() expect_true(kb$keyring_is_locked()) list <- kb$keyring_list() expect_true(list$locked[match(keyring, list$keyring)]) ## Unlock it kb$keyring_unlock(password = "secret123!") expect_false(kb$keyring_is_locked()) list <- kb$keyring_list() expect_false(list$locked[match(keyring, list$keyring)]) expect_silent(kb$keyring_delete(keyring = keyring)) }) test_that("zero bytes in keys", { # warning for zero bytes ffun <- function(...) { list( c("foo", NA_character_), c("bar", "baz"), list(charToRaw("foo"), as.raw(c(3, 2, 1, 0))), list(charToRaw("bar"), charToRaw("baz")) ) } fake(b_macos_list, ".Call", ffun) fake(b_macos_list_raw, ".Call", ffun) expect_snapshot({ b_macos_list(NULL, list(keyring_file = function(...) NULL)) b_macos_list_raw(NULL, list(keyring_file = function(...) NULL)) }) # --------------------- ffun <- function(...) { list( c("foo", NA_character_), c("bar", NA_character_), list(charToRaw("foo"), as.raw(c(3, 2, 1, 0))), list(charToRaw("bar"), as.raw(c(1, 2, 0, 1, 2))) ) } fake(b_macos_list, ".Call", ffun) fake(b_macos_list_raw, ".Call", ffun) expect_snapshot({ b_macos_list(NULL, list(keyring_file = function(...) NULL)) b_macos_list_raw(NULL, list(keyring_file = function(...) NULL)) }) # --------------------- ffun <- function(...) { list( c("foo", "baz"), c("bar", NA_character_), list(charToRaw("foo"), charToRaw("baz")), list(charToRaw("bar"), as.raw(c(3, 2, 1, 0))) ) } fake(b_macos_list, ".Call", ffun) fake(b_macos_list_raw, ".Call", ffun) expect_snapshot({ b_macos_list(NULL, list(keyring_file = function(...) NULL)) b_macos_list_raw(NULL, list(keyring_file = function(...) NULL)) }) }) keyring/tests/testthat/test-common.R0000644000176200001440000000371415004361550017320 0ustar liggesuserswithr::local_options( keyring_warn_for_env_fallback = FALSE, keyring_file_dir = file.path(tempdir(), "keyrings") ) on.exit(unlink(file.path(tempdir(), "keyrings"), recursive = TRUE), add = TRUE) # The file backend needs a default keyring currently kb <- default_backend() if (kb$name == "file") { if (!"system" %in% kb$keyring_list()$keyring) { kb$.__enclos_env__$private$keyring_create_direct("system", "master") } kb$keyring_unlock("system", "master") } test_that("set, get, delete", { skip_on_cran() service <- random_service() username <- random_username() password <- random_password() expect_silent(key_set_with_value(service, username, password)) expect_equal(key_get(service, username), password) expect_silent(key_delete(service, username)) }) test_that("set, get, delete without username", { skip_on_cran() service <- random_service() password <- random_password() expect_silent(key_set_with_value(service, password = password)) expect_equal(key_get(service), password) expect_silent(key_delete(service)) }) test_that("set can update", { skip_on_cran() service <- random_service() username <- random_username() password <- random_password() expect_silent({ key_set_with_value(service, username, "foobar") key_set_with_value(service, username, password) }) expect_equal(key_get(service, username), password) expect_silent(key_delete(service, username)) }) test_that("list", { skip_on_cran() if (default_backend()$name == "env") skip("'env' backend has no 'list' support") service <- random_service() username <- random_username() password <- random_password() expect_silent({ key_set_with_value(service, username, password) list <- key_list() }) expect_equal(list$username[match(service, list$service)], username) list2 <- key_list(service = service) expect_equal(nrow(list2), 1) expect_equal(list2$username, username) expect_silent(key_delete(service, username)) }) keyring/tests/testthat/test-default-backend.R0000644000176200001440000000412115004361550021032 0ustar liggesusersopts <- options(keyring_warn_for_env_fallback = FALSE) on.exit(options(opts), add = TRUE) test_that("use options", { withr::with_options( list(keyring_backend = "env"), expect_equal(default_backend(), backend_env$new()) ) withr::with_options( list(keyring_backend = "env"), expect_equal(default_backend(), backend_env$new()) ) ## This should run on all OSes currently, as we are not actually ## calling the Keychain API here. withr::with_options( list(keyring_backend = "macos", keyring_keyring = "foobar"), expect_equal(default_backend(), backend_macos$new(keyring = "foobar")) ) }) test_that("use env var", { ## Remove the options withr::with_options( list(keyring_backend = NULL, keyring_keyring = NULL), withr::with_envvar( c(R_KEYRING_BACKEND = "env"), expect_equal(default_backend(), backend_env$new()) ) ) }) test_that("mixing options and env vars", { ## Backend option, keyring env var withr::with_options( list(keyring_backend = "macos", keyring_keyring = NULL), withr::with_envvar( c(R_KEYRING_KEYRING = "foobar"), expect_equal(default_backend(), backend_macos$new(keyring = "foobar")) ) ) ## Backend env var, keyring option withr::with_options( list(keyring_backend = NULL, keyring_keyring = "foobar"), withr::with_envvar( c(R_KEYRING_BACKEND = "macos"), expect_equal(default_backend(), backend_macos$new(keyring = "foobar")) ) ) }) test_that("auto windows", { local_mocked_bindings(Sys.info = function() c(sysname = "Windows")) expect_equal(default_backend_auto(), backend_wincred) }) test_that("auto macos", { local_mocked_bindings(Sys.info = function() c(sysname = "Darwin")) expect_equal(default_backend_auto(), backend_macos) }) test_that("auto linux", { skip_if_not_linux() kb <- default_backend() expect_true( kb$name == "env" || kb$name == "secret service" || kb$name == "file" ) }) test_that("auto other", { local_mocked_bindings(Sys.info = function() c(sysname = "Solaris")) expect_equal(suppressWarnings(default_backend_auto()), backend_env) }) keyring/tests/testthat/test-encoding.R0000644000176200001440000000770315004361550017620 0ustar liggesuserstest_that("No option/env var set returns auto", { skip_if_not_win() withr::local_options(keyring.encoding_windows = NULL) withr::local_envvar(KEYRING_ENCODING_WINDOWS = NA_character_) encoding <- get_encoding_opt() expect_equal(encoding, "auto") }) test_that("Option encoding set and env unset returns option encoding", { skip_if_not_win() withr::local_options(keyring.encoding_windows = "UTF-16LE") withr::local_envvar(KEYRING_ENCODING_WINDOWS = NA_character_) encoding <- get_encoding_opt() expect_equal(encoding, "UTF-16LE") }) test_that("Option encoding unset and env set returns env encoding", { skip_if_not_win() withr::local_options(keyring.encoding_windows = NULL) withr::local_envvar("KEYRING_ENCODING_WINDOWS" = "UTF-8") encoding <- get_encoding_opt() expect_equal(encoding, "UTF-8") }) test_that("Option encoding set and env var set and EQUAL returns expected value", { skip_if_not_win() withr::local_options(keyring.encoding_windows = "UTF-16LE") withr::local_envvar("KEYRING_ENCODING_WINDOWS" = "UTF-16LE") encoding <- get_encoding_opt() expect_equal(encoding, "UTF-16LE") }) test_that("Invalid encoding (not in iconvlist) returns error", { skip_if_not_win() withr::local_options(keyring.encoding_windows = "doesnotexist") withr::local_envvar("KEYRING_ENCODING_WINDOWS" = "doesnotexist") expect_snapshot(error = TRUE, get_encoding_opt()) }) test_that("iconv suggestion works as expected", { skip_if_not_win() withr::local_options(keyring.encoding_windows = "UTF-16LP") withr::local_envvar("KEYRING_ENCODING_WINDOWS" = NA_character_) expect_snapshot(error = TRUE, get_encoding_opt()) }) test_that("Option has precedence", { skip_if_not_win() withr::local_options(keyring.encoding_windows = iconvlist()[1]) withr::local_envvar("KEYRING_ENCODING_WINDOWS" = iconvlist()[2]) expect_identical(get_encoding_opt(), iconvlist()[1]) }) test_that("Set key with UTF-16LE encoding", { skip_if_not_win() skip_on_cran() service <- random_service() user <- random_username() pass <- random_password() # Now, set a key with UTF-16LE encoding using new options withr::local_options(keyring.encoding_windows = NULL) withr::local_envvar("KEYRING_ENCODING_WINDOWS" = "UTF-16LE") keyring::key_set_with_value( service = service, username = user, password = pass ) # Get the password expect_equal(keyring::key_get(service = service, username = user), pass) # Show that it is UTF-16LE raw_password <- keyring:::b_wincred_i_get( target = paste0(":", service, ":", user) ) expect_equal(iconv(list(raw_password), from = "UTF-16LE", to = ""), pass) key_delete(service = service, username = user) }) test_that("Set key with UTF-16LE encoding plus a keyring", { skip_if_not_win() skip_on_cran() withr::local_options(keyring.encoding_windows = NULL) withr::local_envvar("KEYRING_ENCODING_WINDOWS" = "UTF-16LE") keyring <- random_keyring() kb <- backend_wincred$new(keyring = keyring) kb$.__enclos_env__$private$keyring_create_direct(keyring, "secret123!") expect_true(keyring %in% kb$keyring_list()$keyring) list <- kb$list() expect_equal(nrow(list), 0) service <- random_service() username <- random_username() password <- random_password() expect_silent( kb$set_with_value(service, username, password) ) expect_equal(kb$get(service, username), password) expect_silent(kb$delete(service, username)) expect_silent(kb$keyring_delete(keyring = keyring)) expect_false(keyring %in% kb$keyring_list()$keyring) }) test_that("marked UTF-8 strings work", { skip_if_not_win() skip_on_cran() withr::local_options(keyring.encoding_windows = "UTF-8") service <- random_service() user <- random_username() pass <- "this is ok: \u00bc" keyring::key_set_with_value( service = service, username = user, password = pass ) # Get the password expect_equal(keyring::key_get(service = service, username = user), pass) key_delete(service = service, username = user) }) keyring/tests/testthat/_snaps/0000755000176200001440000000000015006370264016212 5ustar liggesuserskeyring/tests/testthat/_snaps/file.md0000644000176200001440000000146115021773336017461 0ustar liggesusers# locking the keyring file Code kb$set_with_value(service_1, username, password) Condition Error in `with_lock()`: ! Cannot lock keyring file # keyring does not exist Code kb$list() Condition Error in `b__file_keyring_autocreate()`: ! The 'system' keyring does not exists, create it first! Code kb$keyring_is_locked() Condition Error in `b__file_keyring_autocreate()`: ! The 'system' keyring does not exists, create it first! Code kb$keyring_unlock() Condition Error in `b_file_keyring_unlock()`: ! Keyring `` does not exist Code kb$set_with_value("service", "user", "pass") Condition Error in `b__file_keyring_autocreate()`: ! The 'system' keyring does not exists, create it first! keyring/tests/testthat/_snaps/encoding.md0000644000176200001440000000061415021773335020326 0ustar liggesusers# Invalid encoding (not in iconvlist) returns error Code get_encoding_opt() Condition Error in `get_encoding_opt()`: ! Encoding not found in iconvlist(). Did you mean macintosh? # iconv suggestion works as expected Code get_encoding_opt() Condition Error in `get_encoding_opt()`: ! Encoding not found in iconvlist(). Did you mean UTF-16LE? keyring/tests/testthat/_snaps/macos.md0000644000176200001440000000522615021773337017650 0ustar liggesusers# errors Code backend_macos$new(tempfile())$list() Condition Error in `b_macos_list()`: ! keyring error (macOS Keychain), cannot open keychain: The specified keychain could not be found. --- Code backend_macos$new()$get(random_service(), random_username()) Condition Error in `b_macos_get()`: ! keyring error (macOS Keychain), cannot get password: The specified item could not be found in the keychain. --- Code backend_macos$new()$delete(random_service(), random_username()) Condition Error in `b_macos_delete()`: ! keyring error (macOS Keychain), cannot delete password: The specified item could not be found in the keychain. --- Code kb$.__enclos_env__$private$keyring_create_direct("/xxx", "secret123!") Condition Error in `b_macos_keyring_create_direct()`: ! keyring error (macOS Keychain), cannot create keychain: UNIX[Read-only file system] # zero bytes in keys Code b_macos_list(NULL, list(keyring_file = function(...) NULL)) Condition Warning in `b_macos_list()`: Some service names contain zero bytes. These are shown as NA. Use `key_list_raw()` to see them. Output service username 1 foo bar 2 baz Code b_macos_list_raw(NULL, list(keyring_file = function(...) NULL)) Output service username service_raw username_raw 1 foo bar 66, 6f, 6f 62, 61, 72 2 baz 03, 02, 01, 00 62, 61, 7a --- Code b_macos_list(NULL, list(keyring_file = function(...) NULL)) Condition Warning in `b_macos_list()`: Some service names and some user names contain zero bytes. These are shown as NA. Use `key_list_raw()` to see them. Output service username 1 foo bar 2 Code b_macos_list_raw(NULL, list(keyring_file = function(...) NULL)) Output service username service_raw username_raw 1 foo bar 66, 6f, 6f 62, 61, 72 2 03, 02, 01, 00 01, 02, 00, 01, 02 --- Code b_macos_list(NULL, list(keyring_file = function(...) NULL)) Condition Warning in `b_macos_list()`: Some user names contain zero bytes. These are shown as NA. Use `key_list_raw()` to see them. Output service username 1 foo bar 2 baz Code b_macos_list_raw(NULL, list(keyring_file = function(...) NULL)) Output service username service_raw username_raw 1 foo bar 66, 6f, 6f 62, 61, 72 2 baz 62, 61, 7a 03, 02, 01, 00 keyring/tests/testthat/_snaps/utils.md0000644000176200001440000000151315021773337017701 0ustar liggesusers# base64 Code base64_decode("oi7mFx/aLCc3qZ7vQMQQdwwiGq32gB3ylYm6urM9aGY=") Output [1] a2 2e e6 17 1f da 2c 27 37 a9 9e ef 40 c4 10 77 0c 22 1a ad f6 80 1d f2 95 [26] 89 ba ba b3 3d 68 66 # aes_cbc_encrypt, aes_cbc_decrypt Code aes_cbc_decrypt(y, key2) Condition Error in `aes_cbc_decrypt()`: ! Cannot decrypt AES CBC, probably wrong key? --- Code aes_cbc_encrypt(x, raw(5), iv = iv) Condition Error in `aes_cbc_encrypt()`: ! Invalid 'key', must have 32 bytes Code aes_cbc_encrypt(x, key, iv = raw(10)) Condition Error in `aes_cbc_encrypt()`: ! Invalid 'iv', must have 16 bytes Code aes_cbc_decrypt(raw(17), key, iv) Condition Error in `aes_cbc_decrypt()`: ! Invalid message length, must be multiple of 16 keyring/tests/testthat/test-env.R0000644000176200001440000000175015004361550016616 0ustar liggesuserstest_that("set, get, delete", { service <- random_service() username <- random_username() password <- random_password() kb <- backend_env$new() var <- kb$.__enclos_env__$private$env_to_var(service, username) expect_silent( kb$set_with_value(service, username, password) ) expect_equal(kb$list(service)$username, c(username)) expect_equal(kb$get(service, username), password) expect_equal(Sys.getenv(var, "foo"), password) expect_silent(kb$delete(service, username)) expect_equal(Sys.getenv(var, "foo"), "foo") }) test_that("set, get, delete, without username", { service <- random_service() password <- random_password() kb <- backend_env$new() var <- kb$.__enclos_env__$private$env_to_var(service, NULL) expect_silent( kb$set_with_value(service, password = password) ) expect_equal(kb$get(service), password) expect_equal(Sys.getenv(var, "foo"), password) expect_silent(kb$delete(service)) expect_equal(Sys.getenv(var, "foo"), "foo") }) keyring/tests/testthat.R0000644000176200001440000000061214521172457015056 0ustar liggesusers# This file is part of the standard setup for testthat. # It is recommended that you do not modify it. # # Where should you do additional test configuration? # Learn more about the roles of various files in: # * https://r-pkgs.org/testing-design.html#sec-tests-files-overview # * https://testthat.r-lib.org/articles/special-files.html library(testthat) library(keyring) test_check("keyring") keyring/MD50000644000176200001440000001741715023633252012245 0ustar liggesusers010881b3ca075539f26e223a9ce29956 *DESCRIPTION 69034a2e8033c09d0549ca014228cd9d *LICENSE 886e52302102e590d25e29067b71d828 *NAMESPACE b7fc6997bf03e1e8f9e41f81ea51bfa0 *NEWS.md 956efe9bf70f88d7c23a7329dee6fe83 *R/aaa-import-standalone-rstudio-detect.R 49d54631191c0bae643fdc88eb570a69 *R/aaassertthat.R 4ba5daea0f1ab5a6924b5334f22cbfcc *R/api.R 3ddb78c4cd1b6646d5858ddcb569dccc *R/assertions.R bb67bf005d2f1197b4b10a8b99bd6cb1 *R/backend-class.R 0f421f392612356e3aa0109706088e39 *R/backend-env.R e5fd13014f9e29368663e3a98aa6566d *R/backend-file.R d541afe087bd4414eb3c4f69d4b31ba0 *R/backend-macos.R 7df57e4744628e5eb3f4eae9f651c7bf *R/backend-secret-service.R 04431141bb199c0bd3f17189858e9062 *R/backend-wincred.R cf6109a63e589bd7f9671d8910a79897 *R/default_backend.R a5a3c39a195cc4ad5d82f612d5b247d2 *R/keyring-package.R 400c8c3773114e0a573d8d1cb7a7cf10 *R/mocks.R 27537c454c0433f06aefa79382c07b1a *R/package.R 3b218c5cb6c9fbf2a13ccd30f182c57a *R/pass.R de7ba4357e86d12fb1aee2e7d3b24af7 *R/rappdirs.R 9cd1d240b33bdd64c7f4222b723d0cb5 *R/sodium.R 7af802f323bcebe1b2d48ff59ace3698 *R/standalone-errors.R 1f452fb4d86418549a29ebcc547c1694 *R/utils.R 2e64ae1aca08ec4e24f30b4970f0f4dd *README.md 548930783cfb34e0ebe65c1b3dbdc706 *cleanup b1b66771f2d6ce31189a13c7b29be46e *configure 9200cbd4e54f788b26db9f03228bc345 *configure.win 313b04e7356cf89ad887125dcbb0adac *inst/COPYRIGHTS d7547609ac71a99ddc3e9b8c98e3652e *inst/development-notes.md 0329e987cce90ef2037153bd138a38ea *man/b_wincred_decode.Rd ecb560392516129010e9dee9d5006736 *man/b_wincred_decode_auto.Rd d5825658b5fa1e0ea31664395155d652 *man/b_wincred_get.Rd f1e5714dd9532c8e86ebe9076dcbb451 *man/b_wincred_set_with_raw_value.Rd 03cf612af2ab0dd74f2b65d0dcd092f9 *man/backend.Rd bf1451d1e551d3f771ad7efeb319c50c *man/backend_env.Rd 2932f4a9eeb8adebda591daab5af5ab0 *man/backend_file.Rd 0c749710ef7c1a9241b89b7054280595 *man/backend_keyrings.Rd 08751ee749884db7a9a83bcdf4949543 *man/backend_macos.Rd 5cedfc75f164b1d92d16d1ea74d4ed11 *man/backend_secret_service.Rd 171785ca293eefae5b39d07bc93aa572 *man/backend_wincred.Rd 3b263a211f1ddb6301d7a5faafbf0210 *man/backends.Rd 11195c7d76b057d18a66c155a15055f2 *man/has_keyring_support.Rd b37b594c95c73c9ad8389d33a57e548c *man/key_get.Rd 40eee0f42b2ec1cb83e720dd6273a1d0 *man/keyring-package.Rd 68b329da9893e34099c7d8ad5cb9c940 *src/Makevars.in 2355bd9f292aac99928bb248b6861e39 *src/Makevars.win ecdd081f1fa3f04d05b66c7017f2adca *src/aes.c 1296dda9c08b1a35b0f1dac196af9e94 *src/aesce.c f3de68c3debfae18925fd91a85ed259c *src/aesce.h afcddf7f4f7aef338fdecd0e7e35c72d *src/aesni.c 5e5485ee98abe59ff74442975be7953b *src/aesni.h 5645ae5375aa572237e77fe2c37ea7d5 *src/alignment.h a77bf2457d832946e503a1dde7d44608 *src/base64.c 46f32aaa843aec648821232572b5c298 *src/blake2.h 817b5658f66bb31172d6cd91211b61bb *src/blake2b-compress-ref.c 146a2ec5ee767ff252d6fc82db6510c0 *src/blake2b-ref.c 2672078295d7c822abf6fcf39cfb173a *src/common.h 4d7d10f4ab1d4ae96082895202cdb2d4 *src/core_hsalsa20_ref2.c 97b2e2fde27b3da79268b0d854208619 *src/core_salsa_ref.c e496848f370f0f2e85215f78a44ca8ec *src/crypto_core_hsalsa20.h 251bf36958958faabe422579e9e0d369 *src/crypto_core_salsa20.h b6de3dc41860aa23bf3a8ce0abc7eaa3 *src/crypto_core_salsa2012.h 5b06ddd5a957269022dd9037cc998c71 *src/crypto_core_salsa208.h 837219c7b338d08ead7656dd4e6395aa *src/crypto_generichash.c 001a59bb8db1d16f23f536d817ebcba8 *src/crypto_generichash.h f39992178d4f986153cadd56422e0041 *src/crypto_generichash_blake2b.h 92bad300dda5c2ae7ae91b6864ce2ed3 *src/crypto_onetimeauth.h d16bc17709668513e3f15f289035e40b *src/crypto_onetimeauth_poly1305.h 9f9402d034989397ef8268d84d7dfc62 *src/crypto_secretbox.h 149d2d4a4cdda29c827ee27350ef8240 *src/crypto_secretbox_easy.c b5cefd61bb2d20e5192206aebf61bd85 *src/crypto_secretbox_xsalsa20poly1305.h dbcd991ff16a4ae54869187f80009736 *src/crypto_stream_salsa20.h f3a70f86d6fea31537cf6999d1b4549b *src/crypto_stream_xsalsa20.h 4f9f6785016d739b1ad84803787f4ac0 *src/crypto_verify_16.h ce2cf96a5f0e6358e2347923ca0d0023 *src/crypto_verify_32.h 8b69cb4ae409878d1050d089c66770bc *src/crypto_verify_64.h 6bbd6e24f3c1d6dba7ce479d1b02699c *src/ctr.h c6d03fe6ddb6a1cfce5c173d7e2fed0c *src/endianness.h acd5decc7308dd4168eecabdde73b382 *src/generichash_blake2b.c 33af73ec0e8098d325d70e083ca8555a *src/init.c d6285fbf3ba4400df843622ee59bc643 *src/keyring_macos.c fa4c3dff4329a8ce55565ea86c2c4bc0 *src/keyring_secret_service.c 26bcbdde4c9090fd184fe4b0bc62730a *src/keyring_wincred.c 8617dc7b625a8ea943c6f392bad96dd7 *src/mbedtls/aes.h cdfffa1a1c4eb31df18b841acee71a59 *src/mbedtls/build_info.h 0def7e4e10fee612f6be413a97283618 *src/mbedtls/check_config.h 3c5a6b9eade45f1db0bfa41f884a5d3e *src/mbedtls/config_adjust_legacy_crypto.h 55109ef14d61bda74c41f542021ed429 *src/mbedtls/config_adjust_psa_from_legacy.h 960efc141a951a6279e7d18e6d2af1d8 *src/mbedtls/config_adjust_psa_superset_legacy.h d55e8abd1e9f5dee0756fdc893361746 *src/mbedtls/config_adjust_ssl.h 97c6c6b993ac01fbf899d4d9cbec7148 *src/mbedtls/config_adjust_x509.h db9a3262fcd2c94920c53d652cd14d55 *src/mbedtls/config_psa.h bf5df968f480c1cafe6473a6ab8dbeb1 *src/mbedtls/error.h 9d7684e68c728e5978f93e2e5c354476 *src/mbedtls/mbedtls_config.h b7901761628c61dc50b6da7c75572ccb *src/mbedtls/platform.h adcbaa9c2a681987100f09cd6618661e *src/mbedtls/platform_time.h 522965d123d0375a487af672a15a5542 *src/mbedtls/platform_util.h b9aaa3ed4a926da96cae29cb1764377f *src/mbedtls/private_access.h b5f9271e954bdb50e638044f81e4a9c3 *src/mbedtls/threading.h 729caf7b1bedf5092fc10415fd244abb *src/onetimeauth_poly1305.c 2a2ac30bbad8db831964e8f452d07ad9 *src/onetimeauth_poly1305.h c4cca2aea3b9c00b3ccdaf205e49a5ed *src/padlock.c 1f53b8e25ca0327c65b0c0a66fe2a171 *src/padlock.h e16df9793d55ea84eaa2588cccc83208 *src/platform_util.c e8007ea93206a0599a6060537510cb8a *src/poly1305_donna.c d0639ad82d1f5433fb7e826a166e8ee8 *src/poly1305_donna.h cb45e53480fb3ab352f622ae89ed6d1b *src/poly1305_donna32.h 776e9d72b698ae858114fce7ca86063a *src/poly1305_donna64.h 64102db00bf218f87c3c23922fe0695c *src/psa/crypto_adjust_auto_enabled.h 2f41d7100d8b549b5b80e2f1be498f0d *src/psa/crypto_adjust_config_dependencies.h dcdf99ac83263ab20d38837a00e9abd2 *src/psa/crypto_adjust_config_key_pair_types.h 956cb2b4cc4de1ad0182fa6340c6970b *src/psa/crypto_adjust_config_synonyms.h 667c8b49b0342f33e09a132ce0eb939b *src/psa/crypto_legacy.h 6e40ceae9aaeb57de95e1e41af6699c5 *src/raes.c 9948bc07a2f564b44b268816efedb970 *src/randombytes_sysrandom.c 54aa624387f86f59eff85a5387040821 *src/salsa20_ref.c f0f3968483dfcf8ca613b56c359a2a6a *src/salsa20_ref.h 52a618b3e19e50b21c307f92463f8fb7 *src/sha256.c e178046cba8695fb2b64bd4bd9f3bc57 *src/sodium-utils.c 21645e7c16266f1197fd1872c1b4a8b2 *src/sodium.c 98be7f4be87c6c427327d84413fe83ca *src/sodium.h fa842705f998ae53c28c780a6f17b732 *src/stream_salsa20.c 0895c663e4d0d88f688c2b4760cd77b2 *src/stream_salsa20.h 264edbba9f24f3e43af6bf878f1fa1f5 *src/verify.c a2539ad776400c2b90ce522e8207ae89 *src/win-path.c c71b2828a99106971be998a78e899343 *tests/testthat.R fa97ef1979b64466fc8f0c3299197e6e *tests/testthat/_snaps/encoding.md a986baaad93e6782cb3c63a29a10c5b0 *tests/testthat/_snaps/file.md 907b9c89fe8aaa0719a06e29fc7a22e4 *tests/testthat/_snaps/macos.md f471f1df740477219eca5556e5c225a1 *tests/testthat/_snaps/utils.md 4b6fa2e0b7091620b9b9f6a34cac3c94 *tests/testthat/helper-fake.R 1e635ec549875994f48f9970081f2173 *tests/testthat/helper.R 1b1f17ad863aa76879594e25fc4210c3 *tests/testthat/test-common.R f4953b81be141f00dc0eba8744ac8d2a *tests/testthat/test-default-backend.R 3acc02606247a9de3a4cce47284ca73d *tests/testthat/test-encoding.R 6cbe42cbd54d6d6938a056d15329595c *tests/testthat/test-env.R 655821bee3a0c6086f48b09810e0ff03 *tests/testthat/test-file.R 942229f50e7acd54511ee07fc31695b4 *tests/testthat/test-macos.R daa33e5c49973769c2a00a6f0f96fb29 *tests/testthat/test-secret-service.R e2720e51ffef7f8da0cfeaa76a536b54 *tests/testthat/test-utils.R d28bbb25c5145094837d671425f7d760 *tests/testthat/test-wincred.R keyring/configure.win0000755000176200001440000000021415006370264014425 0ustar liggesusers#! /usr/bin/env sh echo "PKG_CPPFLAGS=-DMBEDTLS_AES_C -DMBEDTLS_ALLOW_PRIVATE_ACCESS -DMBEDTLS_PLATFORM_PRINTF_ALT -I." > src/Makevars.win keyring/R/0000755000176200001440000000000015015122043012114 5ustar liggesuserskeyring/R/sodium.R0000644000176200001440000000201115004361550013537 0ustar liggesuserssodium_random <- function(n = 1) { assert_that( is.numeric(n), length(n) == 1, !is.na(n) ) .Call(rsodium_randombytes_buf, as.integer(n)) } sodium_bin2hex <- function(bin) { stopifnot(is.raw(bin)) .Call(rsodium_bin2hex, bin) } sodium_hex2bin <- function(hex, ignore = ":") { assert_that( is.character(hex), length(hex) == 1, is.character(ignore), length(ignore) == 1 ) .Call(rsodium_hex2bin, hex, ignore) } sodium_data_encrypt <- function(msg, key, nonce = sodium_random(24)) { assert_that( is.raw(msg), is.raw(key) ) out <- .Call(rsodium_crypto_secret_encrypt, msg, key, nonce) structure(out, nonce = nonce) } sodium_data_decrypt <- function(bin, key, nonce = attr(bin, "nonce")) { assert_that( is.raw(bin), is.raw(key) ) .Call(rsodium_crypto_secret_decrypt, bin, key, nonce) } sodium_hash <- function(buf, key = NULL, size = 32) { assert_that( is.raw(buf), is.null(key) || is.raw(key) ) .Call(rsodium_crypto_generichash, buf, size, key) } keyring/R/backend-macos.R0000644000176200001440000002142315015040505014732 0ustar liggesusers#' macOS Keychain keyring backend #' #' This backend is the default on macOS. It uses the macOS native Keychain #' Service API. #' #' It supports multiple keyrings. #' #' See [backend] for the documentation of the individual methods. #' #' @family keyring backends #' @export #' @examples #' \dontrun{ #' ## This only works on macOS #' kb <- backend_macos$new() #' kb$keyring_create("foobar") #' kb$set_default_keyring("foobar") #' kb$set_with_value("service", password = "secret") #' kb$get("service") #' kb$delete("service") #' kb$delete_keyring("foobar") #' } backend_macos <- R6Class( "backend_macos", inherit = backend_keyrings, public = list( name = "macos", initialize = function(keyring = NULL) b_macos_init(self, private, keyring), get = function(service, username = NULL, keyring = NULL) b_macos_get(self, private, service, username, keyring), get_raw = function(service, username = NULL, keyring = NULL) b_macos_get_raw(self, private, service, username, keyring), set = function( service, username = NULL, keyring = NULL, prompt = "Password: " ) b_macos_set(self, private, service, username, keyring, prompt), set_with_value = function( service, username = NULL, password = NULL, keyring = NULL ) b_macos_set_with_value( self, private, service, username, password, keyring ), set_with_raw_value = function( service, username = NULL, password = NULL, keyring = NULL ) b_macos_set_with_raw_value( self, private, service, username, password, keyring ), delete = function(service, username = NULL, keyring = NULL) b_macos_delete(self, private, service, username, keyring), list = function(service = NULL, keyring = NULL) b_macos_list(self, private, service, keyring), list_raw = function(service = NULL, keyring = NULL) b_macos_list_raw(self, private, service, keyring), keyring_create = function(keyring, password = NULL) b_macos_keyring_create(self, private, keyring, password), keyring_list = function() b_macos_keyring_list(self, private), keyring_delete = function(keyring = NULL) b_macos_keyring_delete(self, private, keyring), keyring_lock = function(keyring = NULL) b_macos_keyring_lock(self, private, keyring), keyring_unlock = function(keyring = NULL, password = NULL) b_macos_keyring_unlock(self, private, keyring, password), keyring_is_locked = function(keyring = NULL) b_macos_keyring_is_locked(self, private, keyring), keyring_default = function() b_macos_keyring_default(self, private), keyring_set_default = function(keyring = NULL) b_macos_keyring_set_default(self, private, keyring), docs = function() { modifyList( super$docs(), list( . = "Store secrets in the macOS Keychain." ) ) } ), private = list( keyring = NULL, keyring_file = function(name) b_macos_keyring_file(self, private, name), keyring_create_direct = function(keyring, password) b_macos_keyring_create_direct(self, private, keyring, password) ) ) b_macos_init <- function(self, private, keyring) { private$keyring <- keyring invisible(self) } b_macos_get <- function(self, private, service, username, keyring) { username <- username %||% getOption("keyring_username") keyring <- private$keyring_file(keyring %||% private$keyring) res <- .Call(keyring_macos_get, utf8(keyring), utf8(service), utf8(username)) if (any(res == 0)) { stop("Key contains embedded null bytes, use get_raw()") } rawToChar(res) } b_macos_get_raw <- function(self, private, service, username, keyring) { username <- username %||% getOption("keyring_username") keyring <- private$keyring_file(keyring %||% private$keyring) .Call(keyring_macos_get, utf8(keyring), utf8(service), utf8(username)) } b_macos_set <- function(self, private, service, username, keyring, prompt) { username <- username %||% getOption("keyring_username") password <- get_pass(prompt) if (is.null(password)) stop("Aborted setting keyring key") b_macos_set_with_value(self, private, service, username, password, keyring) invisible(self) } b_macos_set_with_value <- function( self, private, service, username, password, keyring ) { username <- username %||% getOption("keyring_username") keyring <- private$keyring_file(keyring %||% private$keyring) .Call( keyring_macos_set, utf8(keyring), utf8(service), utf8(username), charToRaw(password) ) invisible(self) } b_macos_set_with_raw_value <- function( self, private, service, username, password, keyring ) { username <- username %||% getOption("keyring_username") keyring <- private$keyring_file(keyring %||% private$keyring) .Call( keyring_macos_set, utf8(keyring), utf8(service), utf8(username), password ) invisible(self) } b_macos_delete <- function(self, private, service, username, keyring) { username <- username %||% getOption("keyring_username") keyring <- private$keyring_file(keyring %||% private$keyring) .Call(keyring_macos_delete, utf8(keyring), utf8(service), utf8(username)) invisible(self) } b_macos_list <- function(self, private, service, keyring) { keyring <- private$keyring_file(keyring %||% private$keyring) res <- .Call(keyring_macos_list, utf8(keyring), utf8(service)) df <- data.frame( service = res[[1]], username = res[[2]], stringsAsFactors = FALSE ) srv_na <- anyNA(df[["service"]]) usr_na <- anyNA(df[["username"]]) if (srv_na | usr_na) { cnd <- structure( list( message = paste0( "Some ", if (srv_na) "service names ", if (srv_na && usr_na) "and some ", if (usr_na) "user names ", "contain zero bytes. These are shown as NA. ", "Use `key_list_raw()` to see them." ) ), class = "keyring_warn_zero_byte_keys" ) warning(cnd) } df } b_macos_list_raw <- function(self, private, service, keyring) { keyring <- private$keyring_file(keyring %||% private$keyring) res <- .Call(keyring_macos_list, utf8(keyring), utf8(service)) df <- data.frame( service = res[[1]], username = res[[2]], stringsAsFactors = FALSE ) df[["service_raw"]] <- res[[3]] df[["username_raw"]] <- res[[4]] df } b_macos_keyring_create <- function(self, private, keyring, password) { password <- password %||% get_pass() if (is.null(password)) stop("Aborted creating keyring") private$keyring_create_direct(keyring, password) invisible(self) } b_macos_keyring_list <- function(self, private) { res <- .Call(keyring_macos_list_keyring) data.frame( keyring = sub("\\.keychain(-db)?$", "", basename(res[[1]])), num_secrets = res[[2]], locked = res[[3]], stringsAsFactors = FALSE ) } b_macos_keyring_delete <- function(self, private, keyring) { self$confirm_delete_keyring(keyring) keyring <- private$keyring_file(keyring %||% private$keyring) .Call(keyring_macos_delete_keyring, utf8(keyring)) invisible(self) } b_macos_keyring_lock <- function(self, private, keyring) { keyring <- private$keyring_file(keyring %||% private$keyring) .Call(keyring_macos_lock_keyring, utf8(keyring)) invisible(self) } b_macos_keyring_unlock <- function(self, private, keyring, password) { password <- password %||% get_pass() if (is.null(password)) stop("Aborted unlocking keyring") keyring <- private$keyring_file(keyring %||% private$keyring) .Call(keyring_macos_unlock_keyring, utf8(keyring), password) invisible(self) } b_macos_keyring_is_locked <- function(self, private, keyring) { keyring <- private$keyring_file(keyring %||% private$keyring) .Call(keyring_macos_is_locked_keyring, utf8(keyring)) } b_macos_keyring_default <- function(self, private) { private$keyring } b_macos_keyring_set_default <- function(self, private, keyring) { private$keyring <- keyring invisible(self) } ## -------------------------------------------------------------------- ## Private b_macos_keyring_file <- function(self, private, name) { if (is.null(name)) { name } else if (substr(name, 1, 1) == "/" || substr(name, 1, 2) == "./") { normalizePath(name, mustWork = FALSE) } else { files <- normalizePath( paste0("~/Library/Keychains/", name, c(".keychain", ".keychain-db")), mustWork = FALSE ) if (file.exists(files[1])) { files[1] } else if (file.exists(files[2])) { files[2] } else if (darwin_version() >= "16.0.0") { files[2] } else { files[1] } } } b_macos_keyring_create_direct <- function(self, private, keyring, password) { keyring <- private$keyring_file(keyring) .Call(keyring_macos_create, utf8(keyring), password) invisible(self) } keyring/R/backend-class.R0000644000176200001440000002020215004361550014733 0ustar liggesusersabstract_method <- function() { stop( "An abstract keyring method is called. This is an internal error. ", "It most likely happends because of a broken keyring backend that ", "does not implement all keyring functions." ) } #' Abstract class of a minimal keyring backend #' #' To implement a new keyring backend, you need to inherit from this #' class and then redefine the `get`, `set`, `set_with_value` and `delete` #' methods. Implementing the `list` method is optional. Additional methods #' can be defined as well. #' #' These are the semantics of the various methods: #' #' ``` #' get(service, username = NULL, keyring = NULL) #' get_raw(service, username = NULL, keyring = NULL) #' set(service, username = NULL, keyring = NULL, prompt = "Password: ") #' set_with_value(service, username = NULL, password = NULL, #' keyring = NULL) #' set_with_raw_value(service, username = NULL, password = NULL, #' keyring = NULL) #' delete(service, username = NULL, keyring = NULL) #' list(service = NULL, keyring = NULL) #' list_raw(service = NULL, keyring = NULL) #' ``` #' #' What these functions do: #' #' * `get()` queries the secret in a keyring item. #' * `get_raw()` is similar to `get()`, but returns the result as a raw #' vector. #' * `set()` sets the secret in a keyring item. The secret itself is read #' in interactively from the keyboard. #' * `set_with_value()` sets the secret in a keyring item to the specified #' value. #' * `set_with_raw_value()` sets the secret in keyring item to the #' byte sequence of a raw vector. #' * `delete()` remotes a keyring item. #' * `list()` lists keyring items. #' * `list_raw()` lists keyring items, also as raw vectors. #' #' The arguments: #' * `service` String, the name of a service. This is used to find the #' secret later. #' * `username` String, the username associated with a secret. It can be #' `NULL`, if no username belongs to the secret. It uses the value of #' the `keyring_username`, if set. #' * `keyring` String, the name of the keyring to work with. This only makes #' sense if the platform supports multiple keyrings. `NULL` selects the #' default (and maybe only) keyring. #' * `password` The value of the secret, typically a password, or other #' credential. #' * `prompt` String, the text to be displayed above the textbox. #' #' @family keyring backend base classes #' @importFrom R6 R6Class #' @name backend NULL #' @export backend <- R6Class( "backend", public = list( name = "abstract backend", has_keyring_support = function() FALSE, get = function(service, username = NULL, keyring = NULL) abstract_method(), get_raw = function(service, username = NULL, keyring = NULL) charToRaw(self$get(service, username, keyring)), set = function( service, username = NULL, keyring = NULL, prompt = "Password: " ) abstract_method(), set_with_value = function( service, username = NULL, password = NULL, keyring = NULL ) abstract_method(), set_with_raw_value = function( service, username = NULL, password = NULL, keyring = NULL ) self$set_with_value(service, username, rawToChar(password), keyring), delete = function(service, username = NULL, keyring = NULL) abstract_method(), list = function(service = NULL, keyring = NULL) stop("Backend does not implement 'list'"), list_raw = function(service = NULL, keyring = NULL) { keys <- self$list(service, keyring) keys$service_raw <- lapply(keys$service, charToRaw) keys$username_raw <- lapply(keys$username, charToRaw) keys }, print = function(...) { d <- self$docs() cat0("\n") cat0(d[[1]], "\n\n") cat0(paste0(" $", format(names(d[-1])), " ", d[-1]), sep = "\n") invisible(self) }, ## This should be 'protected', really, but not possible in R6 confirm_delete_keyring = function(keyring) { if (is.null(keyring)) { stop( "Cannot delete the default keyring. ", "You need to specify the name of the keyring explicitly." ) } list <- self$keyring_list() if ( keyring %in% list$keyring && list$num_secrets[match(keyring, list$keyring)] > 0 ) { confirmation( "The keyring is not empty, type 'yes' to delete it", "yes" ) } }, docs = function() { list( . = "Inherit from this class to implement a basic backend.", get = "query a key from the keyring", set = "set a key in the keyring (interactive)", set_with_value = "set a key in the keyring", delete = "delete a key", list = "list keys in a keyring", list_raw = "list keys in a keyring as raw vectors", has_keyring_support = "TRUE if multiple keyrings are supported" ) } ) ) #' Abstract class of a backend that supports multiple keyrings #' #' To implement a new keyring that supports multiple keyrings, you need to #' inherit from this class and redefine the `get`, `set`, `set_with_value`, #' `delete`, `list` methods, and also the keyring management methods: #' `keyring_create`, `keyring_list`, `keyring_delete`, `keyring_lock`, #' `keyring_unlock`, `keyring_is_locked`, `keyring_default` and #' `keyring_set_default`. #' #' See [backend] for the first set of methods. This is the semantics of the #' keyring management methods: #' #' ``` #' keyring_create(keyring) #' keyring_list() #' keyring_delete(keyring = NULL) #' keyring_lock(keyring = NULL) #' keyring_unlock(keyring = NULL, password = NULL) #' keyring_is_locked(keyring = NULL) #' keyring_default() #' keyring_set_default(keyring = NULL) #' ``` #' #' * `keyring_create()` creates a new keyring. #' * `keyring_list()` lists all keyrings. #' * `keyring_delete()` deletes a keyring. It is a good idea to protect #' the default keyring, and/or a non-empty keyring with a password or #' a confirmation dialog. #' * `keyring_lock()` locks a keyring. #' * `keyring_unlock()` unlocks a keyring. #' * `keyring_is_locked()` checks whether a keyring is locked. #' * `keyring_default()` returns the default keyring. #' * `keyring_set_default()` sets the default keyring. #' #' Arguments: #' * `keyring` is the name of the keyring to use or create. For some #' methods in can be `NULL` to select the default keyring. #' * `password` is the password of the keyring. #' #' @family keyring backend base classes #' @name backend_keyrings NULL #' @export backend_keyrings <- R6Class( "backend_keyrings", inherit = backend, public = list( has_keyring_support = function() TRUE, get = function(service, username = NULL, keyring = NULL) abstract_method(), set = function(service, username = NULL, keyring = NULL) abstract_method(), set_with_value = function( service, username = NULL, password = NULL, keyring = NULL ) abstract_method(), delete = function(service, username = NULL) abstract_method(), list = function(service = NULL, keyring = NULL) abstract_method(), keyring_create = function(keyring, password) abstract_method(), keyring_list = function() abstract_method(), keyring_delete = function(keyring = NULL) abstract_method(), keyring_lock = function(keyring = NULL) abstract_method(), keyring_unlock = function(keyring = NULL, password = NULL) abstract_method(), keyring_is_locked = function(keyring = NULL) abstract_method(), keyring_default = function() abstract_method(), keyring_set_default = function(keyring = NULL) abstract_method(), docs = function() { modifyList( super$docs(), list( . = "Inherit from this class for a new backend with multiple keyrings.", keyring_create = "create new keyring", keyring_list = "list all keyrings", keyring_delete = "delete a keyring", keyring_lock = "lock a keyring", keyring_unlock = "unlock a keyring", keyring_is_locked = "check if a keyring is locked", keyring_default = "query the default keyring", keyring_set_default = "set the default keyring" ) ) } ) ) keyring/R/backend-wincred.R0000644000176200001440000004277015006370264015303 0ustar liggesusers## The windows credential store does not support multiple keyrings, ## so we emulate them. See the inst/development-notes.md file for a ## complete description on how this is done. b_wincred_protocol_version <- "1.0.0" ## This is a low level API b_wincred_i_get <- function(target) { .Call(keyring_wincred_get, target) } b_wincred_i_set <- function( target, password, username = NULL, session = FALSE ) { username <- username %||% getOption("keyring_username") .Call(keyring_wincred_set, target, password, username, session) } b_wincred_i_delete <- function(target) { .Call(keyring_wincred_delete, target) } b_wincred_i_exists <- function(target) { .Call(keyring_wincred_exists, target) } b_wincred_i_enumerate <- function(filter) { .Call(keyring_wincred_enumerate, filter) } b_wincred_i_escape <- function(x) { if (is.null(x)) x else URLencode(x) } #' @importFrom utils URLdecode b_wincred_i_unescape <- function(x) { URLdecode(x) } b_wincred_target <- function(keyring, service, username) { username <- username %||% getOption("keyring_username") keyring <- if (is.null(keyring)) "" else b_wincred_i_escape(keyring) service <- b_wincred_i_escape(service) username <- if (is.null(username)) "" else b_wincred_i_escape(username) paste0(keyring, ":", service, ":", username) } ## For the username we need a workaround, because ## strsplit("foo::")[[1]] gives c("foo", ""), i.e. the third empty element ## is cut off. b_wincred_i_parse_target <- function(target) { parts <- lapply(strsplit(target, ":"), lapply, b_wincred_i_unescape) extract <- function(x, i) x[i][[1]] %||% "" res <- data.frame( stringsAsFactors = FALSE, keyring = vapply(parts, extract, "", 1), service = vapply(parts, extract, "", 2), username = vapply(parts, extract, "", 3) ) } b_wincred_target_keyring <- function(keyring) { b_wincred_target(keyring, "", "") } b_wincred_target_lock <- function(keyring) { b_wincred_target(keyring, "", "unlocked") } b_wincred_parse_keyring_credential <- function(target) { value <- rawToChar(b_wincred_i_get(target)) con <- textConnection(value) on.exit(close(con), add = TRUE) as.list(read.dcf(con)[1, ]) } b_wincred_write_keyring_credential <- function(target, data) { con <- textConnection(NULL, open = "w") mat <- matrix(unlist(data), nrow = 1) colnames(mat) <- names(data) write.dcf(mat, con) value <- paste0(paste(textConnectionValue(con), collapse = "\n"), "\n") close(con) b_wincred_i_set(target, password = charToRaw(value)) } #' @importFrom utils head tail b_wincred_get_encrypted_aes <- function(str) { r <- base64_decode(str) structure(tail(r, -16), iv = head(r, 16)) } ## 1. Try to get the unlock credential ## 2. If it exists, return AES key ## 3. If not, then get the credential of the keyring ## 4. Ask for the keyring password ## 5. Hash the password to get the AES key ## 6. Verify that the AES key is correct, using the Verify field of ## the keyring credential ## 7. Create a SESSION credential, with the decrypted AES key ## 8. Return the decrypted AES key b_wincred_unlock_keyring_internal <- function(keyring, password = NULL) { target_lock <- b_wincred_target_lock(keyring) if (b_wincred_i_exists(target_lock)) { base64_decode(rawToChar(b_wincred_i_get(target_lock))) } else { target_keyring <- b_wincred_target_keyring(keyring) keyring_data <- b_wincred_parse_keyring_credential(target_keyring) if (is.null(password)) { message( "keyring ", sQuote(keyring), " is locked, enter password to unlock" ) password <- get_pass() if (is.null(password)) stop("Aborted unlocking keyring") } aes <- sha256(charToRaw(password), key = keyring_data$Salt) verify <- b_wincred_get_encrypted_aes(keyring_data$Verify) tryCatch( aes_cbc_decrypt(verify, key = aes), error = function(e) { stop("Invalid password, cannot unlock keyring") } ) b_wincred_i_set( target_lock, charToRaw(base64_encode(aes)), session = TRUE ) aes } } b_wincred_is_locked_keyring_internal <- function(keyring) { target_lock <- b_wincred_target_lock(keyring) !b_wincred_i_exists(target_lock) } ## ----------------------------------------------------------------------- #' Windows Credential Store keyring backend #' #' This backend is the default on Windows. It uses the native Windows #' Credential API, and needs at least Windows XP to run. #' #' This backend supports multiple keyrings. Note that multiple keyrings #' are implemented in the `keyring` R package, using some dummy keyring #' keys that represent keyrings and their locked/unlocked state. #' #' See [backend] for the documentation of the individual methods. #' #' @family keyring backends #' @export #' @examples #' \dontrun{ #' ## This only works on Windows #' kb <- backend_wincred$new() #' kb$keyring_create("foobar") #' kb$set_default_keyring("foobar") #' kb$set_with_value("service", password = "secret") #' kb$get("service") #' kb$delete("service") #' kb$delete_keyring("foobar") #' } backend_wincred <- R6Class( "backend_wincred", inherit = backend_keyrings, public = list( name = "windows credential store", initialize = function(keyring = NULL) b_wincred_init(self, private, keyring), get = function(service, username = NULL, keyring = NULL) b_wincred_get(self, private, service, username, keyring), get_raw = function(service, username = NULL, keyring = NULL) b_wincred_get_raw(self, private, service, username, keyring), set = function( service, username = NULL, keyring = NULL, prompt = "Password: " ) b_wincred_set(self, private, service, username, keyring, prompt), set_with_value = function( service, username = NULL, password = NULL, keyring = NULL ) b_wincred_set_with_value( self, private, service, username, password, keyring ), set_with_raw_value = function( service, username = NULL, password = NULL, keyring = NULL ) b_wincred_set_with_value( self, private, service, username, password, keyring ), delete = function(service, username = NULL, keyring = NULL) b_wincred_delete(self, private, service, username, keyring), list = function(service = NULL, keyring = NULL) b_wincred_list(self, private, service, keyring), keyring_create = function(keyring, password = NULL) b_wincred_keyring_create(self, private, keyring, password), keyring_list = function() b_wincred_keyring_list(self, private), keyring_delete = function(keyring = NULL) b_wincred_keyring_delete(self, private, keyring), keyring_lock = function(keyring = NULL) b_wincred_keyring_lock(self, private, keyring), keyring_unlock = function(keyring = NULL, password = NULL) b_wincred_keyring_unlock(self, private, keyring, password), keyring_is_locked = function(keyring = NULL) b_wincred_keyring_is_locked(self, private, keyring), keyring_default = function() b_wincred_keyring_default(self, private), keyring_set_default = function(keyring = NULL) b_wincred_keyring_set_default(self, private, keyring), docs = function() { modifyList( super$docs(), list( . = "Store secrets in the Windows Credential Store." ) ) } ), private = list( keyring = NULL, keyring_create_direct = function(keyring, password) b_wincred_keyring_create_direct(self, private, keyring, password) ) ) b_wincred_init <- function(self, private, keyring) { private$keyring <- keyring invisible(self) } #' Get a key from a Wincred keyring #' #' @param service Service name. Must not be empty. #' @param username Username. Might be empty. #' #' 1. We check if the key is on the default keyring. #' 2. If yes, we just return it. #' 3. Otherwise check if the keyring is locked. #' 4. If locked, then unlock it. #' 5. Get the AES key from the keyring. #' 6. Decrypt the key with the AES key. #' #' Additionally, users may specify an encoding to use when converting the #' password from a byte-string, for compatibility with other software such as #' python's keyring package. This is done via an option, or an environment variable. #' #' @keywords internal b_wincred_get <- function(self, private, service, username, keyring) { password <- self$get_raw(service, username, keyring) encoding <- get_encoding_opt() b_wincred_decode(password, encoding = encoding) } b_wincred_get_raw <- function(self, private, service, username, keyring) { keyring <- keyring %||% private$keyring target <- b_wincred_target(keyring, service, username) password <- b_wincred_i_get(target) if (!is.null(keyring)) { ## If it is encrypted, we need to decrypt it aes <- b_wincred_unlock_keyring_internal(keyring) enc <- b_wincred_get_encrypted_aes(rawToChar(password)) password <- aes_cbc_decrypt(enc, key = aes) } password } #' Decode a raw password obtained by b_wincred_get_raw #' #' Defaults to 'auto' encoding, which uses `b_wincred_decode_auto` to #' accomplish the decoding (this works with decoding either UTF-8 or #' UTF-16LE encodings). In the case where an encoding is specified, #' use that to convert the raw password. #' #' @param password A raw byte string returned from `b_wincred_get_raw`. #' @param encoding A character value, specifying an encoding to use. #' Defaults to 'auto', which will decode either of UTF-8 or UTF-16LE. #' @return A character value containing a password. #' #' @keywords internal b_wincred_decode <- function(password, encoding = 'auto') { if (encoding == 'auto') { b_wincred_decode_auto(password) } else { password <- iconv(list(password), from = encoding, to = "") password } } #' Decode a raw password obtained by b_wincred_get_raw #' (UTF-8 and UTF-16LE only) #' #' It attempts to use UTF-16LE conversion if there are 0 values in #' the password. #' #' @param password Raw vector coming from the keyring. #' #' @keywords internal b_wincred_decode_auto <- function(password) { if (any(password == 0)) { password <- iconv(list(password), from = "UTF-16LE", to = "") if (is.na(password)) { stop("Key contains embedded null bytes, use get_raw()") } password } else { rawToChar(password) } } b_wincred_set <- function(self, private, service, username, keyring, prompt) { password <- get_pass(prompt) if (is.null(password)) stop("Aborted setting keyring key") b_wincred_set_with_value(self, private, service, username, password, keyring) invisible(self) } b_wincred_set_with_value <- function( self, private, service, username, password, keyring ) { encoding <- get_encoding_opt() if (encoding != 'auto') { password <- enc2utf8(password) password <- iconv( x = password, from = 'UTF-8', to = encoding, toRaw = TRUE )[[1]] } else { password <- charToRaw(password) } b_wincred_set_with_raw_value( self, private, service, username, password, keyring ) } #' Set a key on a Wincred keyring #' #' @param service Service name. Must not be empty. #' @param username Username. Might be empty. #' @param password The key text to store. #' #' 1. Check if we are using the default keyring. #' 2. If yes, then just store the key and we are done. #' 3. Otherwise check if keyring exists. #' 4. If not, error and finish. #' 5. If yes, check if it is locked. #' 6. If yes, unlock it. #' 7. Encrypt the key with the AES key, and store it. #' #' If required, an encoding can be specified using either an R option #' (\code{keyring.encoding_windows}) or environment variable #' (\code{KEYRING_ENCODING_WINDOWS}). To set, use one of: #' #' \code{options(keyring.encoding_windows = 'encoding-type')} #' \code{Sys.setenv("KEYRING_ENCODING_WINDOWS" = 'encoding-type')} #' #' For a list of valid encodings, use \code{iconvlist()} #' #' @keywords internal b_wincred_set_with_raw_value <- function( self, private, service, username, password, keyring ) { keyring <- keyring %||% private$keyring target <- b_wincred_target(keyring, service, username) if (is.null(keyring)) { b_wincred_i_set(target, password, username = username) return(invisible(self)) } ## Not the default keyring, we need to encrypt it target_keyring <- b_wincred_target_keyring(keyring) aes <- b_wincred_unlock_keyring_internal(keyring) enc <- aes_cbc_encrypt(password, key = aes) password <- charToRaw(base64_encode(c(attr(enc, "iv"), enc))) b_wincred_i_set(target, password = password, username = username) invisible(self) } b_wincred_delete <- function(self, private, service, username, keyring) { keyring <- keyring %||% private$keyring target <- b_wincred_target(keyring, service, username) b_wincred_i_delete(target) invisible(self) } b_wincred_list <- function(self, private, service, keyring) { keyring <- keyring %||% private$keyring filter <- if (is.null(service)) { paste0(b_wincred_i_escape(keyring), ":*") } else { paste0(b_wincred_i_escape(keyring), ":", b_wincred_i_escape(service), ":*") } list <- b_wincred_i_enumerate(filter) ## Filter out the credentials that belong to the keyring or its lock list <- grep("(::|::unlocked)$", list, value = TRUE, invert = TRUE) parts <- b_wincred_i_parse_target(list) data.frame( service = parts$service, username = parts$username, stringsAsFactors = FALSE ) } b_wincred_keyring_create <- function(self, private, keyring, password) { password <- password %||% get_pass() if (is.null(password)) stop("Aborted creating keyring") private$keyring_create_direct(keyring, password) invisible(self) } ## 1. Check that the keyring does not exist, error if it does ## 2. Create salt. ## 3. SHA256 hash the password, with the salt, to get the AES key. ## 4. Generate 15 random bytes, encrypt it with the AES key, base64 encode it. ## 5. Write metadata to the keyring credential ## 6. Unlock the keyring immediately, create a keyring unlock credential b_wincred_keyring_create_direct <- function(self, private, keyring, password) { target_keyring <- b_wincred_target_keyring(keyring) if (b_wincred_i_exists(target_keyring)) { stop("keyring ", sQuote(keyring), " already exists") } salt <- base64_encode(rand_bytes(32)) aes <- sha256(charToRaw(password), key = salt) verify <- aes_cbc_encrypt(rand_bytes(15), key = aes) verify <- base64_encode(c(attr(verify, "iv"), verify)) dcf <- list( Version = b_wincred_protocol_version, Verify = verify, Salt = salt ) b_wincred_write_keyring_credential(target_keyring, dcf) b_wincred_unlock_keyring_internal(keyring, password) invisible(self) } b_wincred_keyring_list <- function(self, private) { list <- b_wincred_i_enumerate("*") parts <- b_wincred_i_parse_target(list) ## if keyring:: does not exist, then keyring is not a real keyring, assign it ## to the default default <- !paste0(parts$keyring, "::") %in% list if (length(list) > 0 && any(default)) { parts$username[default] <- paste0(parts$service[default], ":", parts$username[default]) parts$service[default] <- parts$keyring[default] parts$keyring[default] <- "" } res <- data.frame( stringsAsFactors = FALSE, keyring = unname(unique(parts$keyring)), num_secrets = as.integer(unlist(tapply( parts$keyring, factor(parts$keyring, levels = unique(parts$keyring)), length, simplify = FALSE ))), locked = vapply( unique(parts$keyring), FUN.VALUE = TRUE, USE.NAMES = FALSE, function(x) { !any(parts$username[parts$keyring == x] == "unlocked") } ) ) ## Subtract keyring::unlocked and also keyring:: for the non-default keyring res$num_secrets <- res$num_secrets - (!res$locked) - (res$keyring != "") ## The default keyring cannot be locked if ("" %in% res$keyring) res$locked[res$keyring == ""] <- FALSE res } b_wincred_keyring_delete <- function(self, private, keyring) { self$confirm_delete_keyring(keyring) keyring <- keyring %||% private$keyring items <- self$list(keyring = keyring) ## Remove the keyring credential and the lock credential first target_keyring <- b_wincred_target_keyring(keyring) b_wincred_i_delete(target_keyring) target_lock <- b_wincred_target_lock(keyring) try(b_wincred_i_delete(target_lock), silent = TRUE) ## Then the items themselves for (i in seq_len(nrow(items))) { target <- b_wincred_target(keyring, items$service[i], items$username[i]) try(b_wincred_i_delete(target), silent = TRUE) } invisible() } b_wincred_keyring_lock <- function(self, private, keyring) { keyring <- keyring %||% private$keyring if (is.null(keyring)) { warning("Cannot lock the default windows credential store keyring") } else { target_lock <- b_wincred_target_lock(keyring) try(b_wincred_i_delete(target_lock), silent = TRUE) invisible() } } b_wincred_keyring_unlock <- function(self, private, keyring, password = NULL) { keyring <- keyring %||% private$keyring if (is.null(password)) password <- get_pass() if (is.null(password)) stop("Aborted unlocking keyring") if (!is.null(keyring)) { b_wincred_unlock_keyring_internal(keyring, password) } invisible() } b_wincred_keyring_is_locked <- function(self, private, keyring) { keyring <- keyring %||% private$keyring if (is.null(keyring)) { FALSE } else { b_wincred_is_locked_keyring_internal(keyring) } } b_wincred_keyring_default <- function(self, private) { private$keyring } b_wincred_keyring_set_default <- function(self, private, keyring) { private$keyring <- keyring invisible(self) } keyring/R/aaa-import-standalone-rstudio-detect.R0000644000176200001440000002032015004361550021357 0ustar liggesusers# Standalone file: do not edit by hand # Source: # ---------------------------------------------------------------------- # # --- # repo: r-lib/cli # file: aaa-standalone-rstudio-detect.R # last-updated: 2022-05-31 # license: https://unlicense.org # --- rstudio <- local({ standalone_env <- environment() parent.env(standalone_env) <- baseenv() # -- Collect data ------------------------------------------------------ data <- NULL get_data <- function() { envs <- c( "R_BROWSER", "R_PDFVIEWER", "RSTUDIO", "RSTUDIO_TERM", "RSTUDIO_CLI_HYPERLINKS", "RSTUDIO_CONSOLE_COLOR", "RSTUDIOAPI_IPC_REQUESTS_FILE", "XPC_SERVICE_NAME", "ASCIICAST" ) d <- list( pid = Sys.getpid(), envs = Sys.getenv(envs), api = tryCatch( asNamespace("rstudioapi")$isAvailable(), error = function(err) FALSE ), tty = isatty(stdin()), gui = .Platform$GUI, args = commandArgs(), search = search() ) d$ver <- if (d$api) asNamespace("rstudioapi")$getVersion() d$desktop <- if (d$api) asNamespace("rstudioapi")$versionInfo()$mode d } # -- Auto-detect environment ------------------------------------------- is_rstudio <- function() { Sys.getenv("RSTUDIO") == "1" } detect <- function(clear_cache = FALSE) { # Check this up front, in case we are in a testthat 3e test block. # We cannot cache this, because we might be in RStudio in reality. if (!is_rstudio()) { return(get_caps(type = "not_rstudio")) } # Cached? if (clear_cache) data <<- NULL if (!is.null(data)) return(get_caps(data)) if ( (rspid <- Sys.getenv("RSTUDIO_SESSION_PID")) != "" && any(c("ps", "cli") %in% loadedNamespaces()) ) { detect_new(rspid, clear_cache) } else { detect_old(clear_cache) } } get_parentpid <- function() { if ("cli" %in% loadedNamespaces()) { asNamespace("cli")$get_ppid() } else { ps::ps_ppid() } } detect_new <- function(rspid, clear_cache) { mypid <- Sys.getpid() new <- get_data() if (mypid == rspid) { return(get_caps(new, type = "rstudio_console")) } # need explicit namespace reference because we mess up the environment parentpid <- get_parentpid() pane <- Sys.getenv("RSTUDIO_CHILD_PROCESS_PANE") # this should not happen, but be defensive and fall back if (pane == "") return(detect_old(clear_cache)) # direct subprocess new$type <- if (rspid == parentpid) { if (pane == "job") { "rstudio_job" } else if (pane == "build") { "rstudio_build_pane" } else if (pane == "render") { "rstudio_render_pane" } else if ( pane == "terminal" && new$tty && new$envs["ASCIICAST"] != "true" ) { # not possible, because there is a shell in between, just in case "rstudio_terminal" } else { # don't know what kind of direct subprocess "rstudio_subprocess" } } else if ( pane == "terminal" && new$tty && new$envs[["ASCIICAST"]] != "true" ) { # not a direct subproces, so check other criteria as well "rstudio_terminal" } else { # don't know what kind of subprocess "rstudio_subprocess" } get_caps(new) } detect_old <- function(clear_cache = FALSE) { # Cache unless told otherwise cache <- TRUE new <- get_data() new$type <- if (new$envs[["RSTUDIO"]] != "1") { # 1. Not RStudio at all "not_rstudio" } else if (new$gui == "RStudio" && new$api) { # 2. RStudio console, properly initialized "rstudio_console" } else if (!new$api && basename(new$args[1]) == "RStudio") { # 3. RStudio console, initializing cache <- FALSE "rstudio_console_starting" } else if (new$gui == "Rgui") { # Still not RStudio, but Rgui that was started from RStudio "not_rstudio" } else if (new$tty && new$envs[["ASCIICAST"]] != "true") { # 4. R in the RStudio terminal # This could also be a subprocess of the console or build pane # with a pseudo-terminal. There isn't really a way to rule that # out, without inspecting some process data with ps::ps_*(). # At least we rule out asciicast "rstudio_terminal" } else if ( !new$tty && new$envs[["RSTUDIO_TERM"]] == "" && new$envs[["R_BROWSER"]] == "false" && new$envs[["R_PDFVIEWER"]] == "false" && is_build_pane_command(new$args) ) { # 5. R in the RStudio build pane # https://github.com/rstudio/rstudio/blob/master/src/cpp/session/ # modules/build/SessionBuild.cpp#L231-L240 "rstudio_build_pane" } else if ( new$envs[["RSTUDIOAPI_IPC_REQUESTS_FILE"]] != "" && grepl("rstudio", new$envs[["XPC_SERVICE_NAME"]]) ) { # RStudio job, XPC_SERVICE_NAME=0 in the subprocess of a job # process. Hopefully this is reliable. "rstudio_job" } else if ( new$envs[["RSTUDIOAPI_IPC_REQUESTS_FILE"]] != "" && any(grepl("SourceWithProgress.R", new$args)) ) { # Or we can check SourceWithProgress.R in the command line, see # https://github.com/r-lib/cli/issues/367 "rstudio_job" } else { # Otherwise it is a subprocess of the console, terminal or # build pane, and it is hard to say which, so we do not try. "rstudio_subprocess" } installing <- Sys.getenv("R_PACKAGE_DIR", "") if (cache && installing == "") data <<- new get_caps(new) } is_build_pane_command <- function(args) { cmd <- gsub("[\"']", "", args[[length(args)]], useBytes = TRUE) calls <- c( "devtools::build", "devtools::test", "devtools::check", "testthat::test_file" ) any(vapply(calls, grepl, logical(1), cmd)) } # -- Capabilities ------------------------------------------------------ caps <- list() caps$not_rstudio <- function(data) { list( type = "not_rstudio", dynamic_tty = FALSE, ansi_tty = FALSE, ansi_color = FALSE, num_colors = 1L, hyperlink = FALSE ) } caps$rstudio_console <- function(data) { list( type = "rstudio_console", dynamic_tty = TRUE, ansi_tty = FALSE, ansi_color = data$envs[["RSTUDIO_CONSOLE_COLOR"]] != "", num_colors = as.integer(data$envs[["RSTUDIO_CONSOLE_COLOR"]]), hyperlink = data$envs[["RSTUDIO_CLI_HYPERLINKS"]] != "" ) } caps$rstudio_console_starting <- function(data) { res <- caps$rstudio_console(data) res$type <- "rstudio_console_starting" res } caps$rstudio_terminal <- function(data) { list( type = "rstudio_terminal", dynamic_tty = TRUE, ansi_tty = FALSE, ansi_color = FALSE, num_colors = 1L, hyperlink = FALSE ) } caps$rstudio_build_pane <- function(data) { list( type = "rstudio_build_pane", dynamic_tty = TRUE, ansi_tty = FALSE, ansi_color = data$envs[["RSTUDIO_CONSOLE_COLOR"]] != "", num_colors = as.integer(data$envs[["RSTUDIO_CONSOLE_COLOR"]]), hyperlink = data$envs[["RSTUDIO_CLI_HYPERLINKS"]] != "" ) } caps$rstudio_job <- function(data) { list( type = "rstudio_job", dynamic_tty = FALSE, ansi_tty = FALSE, ansi_color = data$envs[["RSTUDIO_CONSOLE_COLOR"]] != "", num_colors = as.integer(data$envs[["RSTUDIO_CONSOLE_COLOR"]]), hyperlink = data$envs[["RSTUDIO_CLI_HYPERLINKS"]] != "" ) } caps$rstudio_render_pane <- function(data) { list( type = "rstudio_render_pane", dynamic_tty = TRUE, ansi_tty = FALSE, ansi_color = FALSE, num_colors = 1L, hyperlink = data$envs[["RSTUDIO_CLI_HYPERLINKS"]] != "" ) } caps$rstudio_subprocess <- function(data) { list( type = "rstudio_subprocess", dynamic_tty = FALSE, ansi_tty = FALSE, ansi_color = FALSE, num_colors = 1L, hyperlink = FALSE ) } get_caps <- function(data, type = data$type) caps[[type]](data) structure( list( .internal = standalone_env, is_rstudio = is_rstudio, detect = detect ), class = c("standalone_rstudio_detect", "standalone") ) }) keyring/R/keyring-package.R0000644000176200001440000000016115015040410015273 0ustar liggesusers#' @keywords internal #' @aliases keyring "_PACKAGE" ## usethis namespace: start ## usethis namespace: end NULL keyring/R/backend-file.R0000644000176200001440000004363715015040510014556 0ustar liggesusersb_file_keyrings <- new.env(parent = emptyenv()) #' Encrypted file keyring backend #' #' This is a simple keyring backend, that stores/uses secrets in encrypted #' files. #' #' It supports multiple keyrings. #' #' See [backend] for the documentation of the individual methods. #' #' @family keyring backends #' @export #' @examples #' \dontrun{ #' kb <- backend_file$new() #' } backend_file <- R6Class( "backend_file", inherit = backend_keyrings, public = list( name = "file", initialize = function(keyring = NULL) b_file_init(self, private, keyring), get = function(service, username = NULL, keyring = NULL) b_file_get(self, private, service, username, keyring), get_raw = function(service, username = NULL, keyring = NULL) b_file_get_raw(self, private, service, username, keyring), set = function(service, username = NULL, keyring = NULL, prompt = NULL) b_file_set(self, private, service, username, keyring, prompt), set_with_value = function( service, username = NULL, password = NULL, keyring = NULL ) b_file_set_with_value( self, private, service, username, password, keyring ), delete = function(service, username = NULL, keyring = NULL) b_file_delete(self, private, service, username, keyring), list = function(service = NULL, keyring = NULL) b_file_list(self, private, service, keyring), keyring_create = function(keyring = NULL, password = NULL) b_file_keyring_create(self, private, keyring, password), keyring_delete = function(keyring = NULL) b_file_keyring_delete(self, private, keyring), keyring_lock = function(keyring = NULL) b_file_keyring_lock(self, private, keyring), keyring_unlock = function(keyring = NULL, password = NULL) b_file_keyring_unlock(self, private, keyring, password), keyring_is_locked = function(keyring = NULL) b_file_keyring_is_locked(self, private, keyring), keyring_list = function() b_file_keyring_list(self, private), keyring_default = function() b_file_keyring_default(self, private), keyring_set_default = function(keyring) b_file_keyring_set_default(self, private, keyring), docs = function() { modifyList( super$docs(), list( . = paste0( "Store secrets in encrypted files.\n", private$keyring ) ) ) } ), private = list( keyring = NULL, keyring_create_direct = function( keyring = NULL, password = NULL, prompt = NULL ) b__file_keyring_create_direct(self, private, keyring, password, prompt), keyring_autocreate = function(keyring = NULL) b__file_keyring_autocreate(self, private, keyring), keyring_file = function(keyring = NULL) b__file_keyring_file(self, private, keyring), keyring_read_file = function(keyring = NULL) b__file_keyring_read_file(self, private, keyring), keyring_write_file = function( keyring = NULL, nonce = NULL, items = NULL, key = NULL ) b__file_keyring_write_file(self, private, keyring, nonce, items, key), get_keyring_pass = function(keyring = NULL) b__file_get_keyring_pass(self, private, keyring), set_keyring_pass = function(key = NULL, keyring = NULL) b__file_set_keyring_pass(self, private, key, keyring), unset_keyring_pass = function(keyring = NULL) b__file_unset_keyring_pass(self, private, keyring), is_set_keyring_pass = function(keyring = NULL) b__file_is_set_keyring_pass(self, private, keyring), update_cache = function( keyring = NULL, nonce = NULL, check = NULL, items = NULL ) b__file_update_cache(self, private, keyring, nonce, check, items), get_cache = function(keyring = NULL) b__file_get_cache(self, private, keyring) ) ) b_file_init <- function(self, private, keyring) { self$keyring_set_default(keyring %||% "system") invisible(self) } b_file_get <- function(self, private, service, username, keyring) { private$keyring_autocreate(keyring) username <- username %||% getOption("keyring_username") if (self$keyring_is_locked(keyring)) self$keyring_unlock(keyring) cached <- private$get_cache(keyring) all_items <- cached$items all_services <- vapply(all_items, `[[`, character(1L), "service_name") item_matches <- all_services %in% service if (!is.null(username)) { all_users <- vapply( all_items, function(x) x$user_name %||% NA_character_, character(1L) ) item_matches <- item_matches & all_users %in% username } if (sum(item_matches) < 1L) { b_file_error( "cannot get secret", "The specified item could not be found in the keychain." ) } vapply( lapply(all_items[item_matches], `[[`, "secret"), b_file_secret_decrypt, character(1L), cached$nonce, private$get_keyring_pass(keyring) ) } b_file_set <- function(self, private, service, username, keyring, prompt) { username <- username %||% getOption("keyring_username") keyring <- keyring %||% private$keyring file <- private$keyring_file(keyring) ex <- file.exists(file) # We use a different prompt in this case, to give a heads up prompt <- prompt %||% if (!ex && interactive()) { paste0( "Note: the specified keyring does not exist, you'll have to ", "create it in the next step. Key password: " ) } else { "Password: " } password <- get_pass(prompt) if (is.null(password)) stop("Aborted setting keyring key") private$keyring_autocreate() self$set_with_value(service, username, password, keyring) invisible(self) } b_file_set_with_value <- function( self, private, service, username, password, keyring ) { private$keyring_autocreate(keyring) username <- username %||% getOption("keyring_username") if (self$keyring_is_locked(keyring)) self$keyring_unlock(keyring) keyring_file <- private$keyring_file(keyring) kr_env <- b_file_keyring_env(keyring_file) with_lock(keyring_file, { cached <- private$get_cache(keyring) all_items <- cached$items services <- vapply(all_items, `[[`, character(1L), "service_name") users <- vapply( all_items, function(x) x$user_name %||% NA_character_, character(1) ) existing <- if (!is.null(username)) { services %in% service & users %in% username } else { services %in% service & is.na(users) } if (length(existing)) all_items <- all_items[!existing] new_item <- list( service_name = service, user_name = username, secret = b_file_secret_encrypt( password, cached$nonce, private$get_keyring_pass(keyring) ) ) items <- c(all_items, list(new_item)) private$keyring_write_file(keyring, items = items) kr_env$stamp <- file_stamp(keyring_file) }) kr_env <- b_file_keyring_env(keyring_file) kr_env$items <- items invisible(self) } b_file_delete <- function(self, private, service, username, keyring) { username <- username %||% getOption("keyring_username") if (self$keyring_is_locked(keyring)) self$keyring_unlock(keyring) keyring_file <- private$keyring_file(keyring) kr_env <- b_file_keyring_env(keyring_file) with_lock(keyring_file, { cached <- private$get_cache(keyring) all_items <- cached$items services <- vapply(all_items, `[[`, character(1L), "service_name") users <- vapply( all_items, function(x) x$user_name %||% NA_character_, character(1) ) existing <- if (!is.null(username)) { services %in% service & users %in% username } else { services %in% service & is.na(users) } if (length(existing) == 0) return(invisible(self)) ## Remove items <- all_items[!existing] private$keyring_write_file(keyring, items = items) kr_env$stamp <- file_stamp(keyring_file) }) kr_env$items <- items invisible(self) } b_file_list <- function(self, private, service, keyring) { private$keyring_autocreate(keyring) cached <- private$get_cache(keyring) all_items <- cached$items res <- data.frame( service = vapply(all_items, `[[`, character(1L), "service_name"), username = vapply( all_items, function(x) x$user_name %||% NA_character_, character(1) ), stringsAsFactors = FALSE ) if (!is.null(service)) { res[res[["service"]] == service, ] } else { res } } b_file_keyring_create <- function(self, private, keyring, password) { private$keyring_create_direct(keyring, password) } b_file_keyring_delete <- function(self, private, keyring) { self$keyring_lock(keyring) kr_file <- private$keyring_file(keyring) unlink(kr_file, recursive = TRUE, force = TRUE) invisible(self) } b_file_keyring_lock <- function(self, private, keyring) { keyring <- keyring %||% private$keyring file <- private$keyring_file(keyring) if (!file.exists(file)) { stop("The '", keyring, "' keyring does not exists, create it first!") } private$unset_keyring_pass(keyring) invisible(self) } b_file_keyring_unlock <- function(self, private, keyring, password) { file <- private$keyring_file(keyring) if (!file.exists(file)) { stop("Keyring `", keyring, "` does not exist") } private$set_keyring_pass(password, keyring) if (self$keyring_is_locked(keyring)) { private$unset_keyring_pass(keyring) b_file_error( "cannot unlock keyring", "The supplied password does not work." ) } invisible(self) } b_file_keyring_is_locked <- function(self, private, keyring) { private$keyring_autocreate(keyring) keyring <- keyring %||% private$keyring file_name <- private$keyring_file(keyring) if (!file.exists(file_name)) { stop("Keyring `", keyring, "` does not exist") } if (!file.exists(file_name) || !private$is_set_keyring_pass(keyring)) { TRUE } else { tryCatch( { cached <- private$get_cache(keyring) b_file_secret_decrypt( cached$check, cached$nonce, private$get_keyring_pass(keyring) ) FALSE }, error = function(e) { if (conditionMessage(e) == "Failed to decrypt") TRUE else stop(e) } ) } } b_file_keyring_list <- function(self, private) { kr_dir <- dirname(private$keyring_file(NULL)) files <- dir(kr_dir, pattern = "\\.keyring$", full.names = TRUE) names <- sub("\\.keyring", "", basename(files)) num_secrets <- vapply( files, function(f) length(yaml::yaml.load_file(f)$items), integer(1) ) locked <- vapply( names, function(k) self$keyring_is_locked(keyring = k), logical(1) ) data.frame( keyring = unname(names), num_secrets = unname(num_secrets), locked = unname(locked), stringsAsFactors = FALSE ) } b_file_keyring_default <- function(self, private) { private$keyring } b_file_keyring_set_default <- function(self, private, keyring) { private$keyring <- keyring invisible(self) } ## -------------------------------------------------------------------- ## Private b__file_keyring_create_direct <- function( self, private, keyring, password, prompt ) { keyring <- keyring %||% private$keyring prompt <- prompt %||% "Keyring password: " file_name <- private$keyring_file(keyring) if (file.exists(file_name)) { confirmation( paste( "are you sure you want to overwrite", file_name, "(type `yes` if so)" ), "yes" ) } password <- password %||% get_pass(prompt) if (is.null(password)) stop("Aborted creating keyring") ## File need to exist for $set_keyring_pass() ... dir.create(dirname(file_name), recursive = TRUE, showWarnings = FALSE) cat("", file = file_name) key <- private$set_keyring_pass(password, keyring) with_lock( file_name, private$keyring_write_file( keyring, nonce = sodium_random(24L), items = list(), key = key ) ) invisible(self) } b__file_keyring_file <- function(self, private, keyring) { keyring <- keyring %||% private$keyring keyring_dir <- getOption( "keyring_file_dir", user_config_dir("r-keyring") ) file.path(keyring_dir, paste0(keyring, ".keyring")) } b__file_keyring_read_file <- function(self, private, keyring) { keyring <- keyring %||% private$keyring file_name <- private$keyring_file(keyring) with_lock(file_name, { stamp <- file_stamp(keyring) yml <- yaml::yaml.load_file(file_name) }) assert_that( is_list_with_names(yml, names = c("keyring_info", "items")), is_list_with_names( yml[["keyring_info"]], names = c("keyring_version", "nonce", "integrity_check") ) ) list( nonce = sodium_hex2bin(yml[["keyring_info"]][["nonce"]]), items = lapply(yml[["items"]], b__file_validate_item), check = yml[["keyring_info"]][["integrity_check"]], stamp = stamp ) } b__file_keyring_write_file <- function( self, private, keyring, nonce, items, key ) { keyring <- keyring %||% private$keyring file_name <- private$keyring_file(keyring) nonce <- nonce %||% private$get_cache(keyring)$nonce with_lock( file_name, yaml::write_yaml( list( keyring_info = list( keyring_version = as.character(getNamespaceVersion(.packageName)), nonce = sodium_bin2hex(nonce), integrity_check = b_file_secret_encrypt( paste(sample(letters, 22L, replace = TRUE), collapse = ""), nonce, key %||% private$get_keyring_pass(keyring) ) ), items = items %||% private$get_cache(keyring)$items ), file_name ) ) invisible(self) } b__file_get_keyring_pass <- function(self, private, keyring) { kr_env <- b_file_keyring_env(private$keyring_file(keyring)) if (is.null(kr_env$key)) { key <- private$set_keyring_pass(keyring = keyring) } else { key <- kr_env$key } assert_that(is.raw(key), length(key) > 0L) key } b__file_unset_keyring_pass <- function(self, private, keyring) { kr_env <- b_file_keyring_env(private$keyring_file(keyring)) kr_env$key <- NULL invisible(kr_env) } b__file_is_set_keyring_pass <- function(self, private, keyring) { !is.null(b_file_keyring_env(private$keyring_file(keyring))$key) } b__file_set_keyring_pass <- function(self, private, key, keyring) { key <- key %||% get_pass("Keyring password: ") if (is.null(key)) stop("Aborted setting keyring password") assert_that(is_string(key)) key <- sodium_hash(charToRaw(key)) kr_env <- b_file_keyring_env(private$keyring_file(keyring)) kr_env$key <- key } b__file_update_cache <- function(self, private, keyring, nonce, check, items) { kr_env <- b_file_keyring_env(private$keyring_file(keyring)) kr <- private$keyring_read_file(keyring) nonce <- nonce %||% kr[["nonce"]] assert_that(is.raw(nonce), length(nonce) > 0L) kr_env$nonce <- nonce check <- check %||% kr[["check"]] assert_that(is.character(check), length(check) > 0L) kr_env$check <- check kr_env$items <- lapply(items %||% kr[["items"]], b__file_validate_item) kr_env$stamp <- kr$stamp kr_env } b__file_get_cache <- function(self, private, keyring) { keyring_file <- private$keyring_file(keyring) kr_env <- b_file_keyring_env(keyring_file) if ( is.null(kr_env$nonce) || is.null(kr_env$stamp) || is.na(kr_env$stamp) || file_stamp(keyring_file) != kr_env$stamp ) { kr_env <- private$update_cache(keyring) } assert_that(is.raw(kr_env$nonce), length(kr_env$nonce) > 0L) assert_that(is.character(kr_env$check), length(kr_env$check) > 0L) list( nonce = kr_env$nonce, items = lapply(kr_env$items, b__file_validate_item), check = kr_env$check ) } ## -------------------------------------------------------------------- ## helper functions b_file_secret_encrypt <- function(secret, nonce, key) { res <- sodium_data_encrypt( charToRaw(secret), key, nonce ) b_file_split_string(sodium_bin2hex(res)) } b_file_secret_decrypt <- function(secret, nonce, key) { rawToChar( sodium_data_decrypt( sodium_hex2bin(b_file_merge_string(secret)), key, nonce ) ) } b_file_keyring_env <- function(file_name) { env_name <- normalizePath(file_name, mustWork = TRUE) kr_env <- b_file_keyrings[[env_name]] if (is.null(kr_env)) { kr_env <- b_file_keyrings[[env_name]] <- new.env(parent = emptyenv()) } kr_env } b_file_error <- function(problem, reason = NULL) { if (is.null(reason)) { info <- problem } else { info <- paste0(problem, ": ", reason) } stop("keyring error (file-based keyring), ", info, call. = FALSE) } b__file_validate_item <- function(item) { assert_that( is_list_with_names(item, names = c("service_name", "user_name", "secret")), is_string(item[["service_name"]]), is_string_or_null(item[["user_name"]]), is_string_or_raw(item[["secret"]]) ) invisible(item) } b_file_split_string <- function(string, width = 78L) { assert_that(is_string(string)) paste( lapply( seq.int(ceiling(nchar(string) / width)) - 1L, function(x) substr(string, x * width + 1L, x * width + width) ), collapse = "\n" ) } b_file_merge_string <- function(string) { assert_that(is_string(string)) paste(strsplit(string, "\n")[[1L]], collapse = "") } b__file_keyring_autocreate <- function(self, private, keyring) { keyring <- keyring %||% private$keyring file <- private$keyring_file(keyring) if (!file.exists(file)) { if (is_interactive()) { private$keyring_create_direct( keyring, password = NULL, prompt = paste0( "The '", keyring, "' keyring does not exist, enter a keyring password to create it: " ) ) } else { stop("The '", keyring, "' keyring does not exists, create it first!") } } } with_lock <- function(file, expr) { timeout <- getOption("keyring_file_lock_timeout", 1000) lockfile <- paste0(file, ".lck") l <- filelock::lock(lockfile, timeout = timeout) if (is.null(l)) stop("Cannot lock keyring file") on.exit(filelock::unlock(l), add = TRUE) expr } keyring/R/standalone-errors.R0000644000176200001440000011051115004361550015706 0ustar liggesusers# --- # repo: r-lib/processx # file: standalone-errors.R # last-updated: 2023-01-15 # license: https://unlicense.org # --- # # Standalone file for better error handling. If you can allow package # dependencies, then you are probably better off using rlang's # functions for errors. # # ## Soft-dependency # # - aaa-standalone-rstudio-detect.R in r-lib/cli # # ## Features # # - Throw conditions and errors with the same API. # - Automatically captures the right calls and adds them to the conditions. # - Sets `.Last.error`, so you can easily inspect the errors, even if they # were not caught. # - It only sets `.Last.error` for the errors that are not caught. # - Hierarchical errors, to allow higher level error messages, that are # more meaningful for the users, while also keeping the lower level # details in the error object. (So in `.Last.error` as well.) # - `.Last.error` always includes a stack trace. (The stack trace is # common for the whole error hierarchy.) The trace is accessible within # the error, e.g. `.Last.error$trace`. The trace of the last error is # also at `.Last.error.trace`. # - Can merge errors and traces across multiple processes. # - Pretty-print errors and traces, if the cli package is loaded. # - Automatically hides uninformative parts of the stack trace when # printing. # # ## API # # ``` # new_cond(..., call. = TRUE, srcref = NULL, domain = NA) # new_error(..., call. = TRUE, srcref = NULL, domain = NA) # throw(cond, parent = NULL, frame = environment()) # throw_error(cond, parent = NULL, frame = environment()) # chain_error(expr, err, call = sys.call(-1)) # chain_call(.NAME, ...) # chain_clean_call(.NAME, ...) # onload_hook() # add_trace_back(cond, frame = NULL) # format$advice(x) # format$call(call) # format$class(x) # format$error(x, trace = FALSE, class = FALSE, advice = !trace, ...) # format$error_heading(x, prefix = NULL) # format$header_line(x, prefix = NULL) # format$srcref(call, srcref = NULL) # format$trace(x, ...) # ``` # # ## Roadmap: # - better printing of anonymous function in the trace # # ## Changelog # # ### 1.0.0 -- 2019-06-18 # # * First release. # # ### 1.0.1 -- 2019-06-20 # # * Add `rlib_error_always_trace` option to always add a trace # # ### 1.0.2 -- 2019-06-27 # # * Internal change: change topenv of the functions to baseenv() # # ### 1.1.0 -- 2019-10-26 # # * Register print methods via onload_hook() function, call from .onLoad() # * Print the error manually, and the trace in non-interactive sessions # # ### 1.1.1 -- 2019-11-10 # # * Only use `trace` in parent errors if they are `rlib_error`s. # Because e.g. `rlang_error`s also have a trace, with a slightly # different format. # # ### 1.2.0 -- 2019-11-13 # # * Fix the trace if a non-thrown error is re-thrown. # * Provide print_this() and print_parents() to make it easier to define # custom print methods. # * Fix annotating our throw() methods with the incorrect `base::`. # # ### 1.2.1 -- 2020-01-30 # # * Update wording of error printout to be less intimidating, avoid jargon # * Use default printing in interactive mode, so RStudio can detect the # error and highlight it. # * Add the rethrow_call_with_cleanup function, to work with embedded # cleancall. # # ### 1.2.2 -- 2020-11-19 # # * Add the `call` argument to `catch_rethrow()` and `rethrow()`, to be # able to omit calls. # # ### 1.2.3 -- 2021-03-06 # # * Use cli instead of crayon # # ### 1.2.4 -- 2021-04-01 # # * Allow omitting the call with call. = FALSE in `new_cond()`, etc. # # ### 1.3.0 -- 2021-04-19 # # * Avoid embedding calls in trace with embed = FALSE. # # ### 2.0.0 -- 2021-04-19 # # * Versioned classes and print methods # # ### 2.0.1 -- 2021-06-29 # # * Do not convert error messages to native encoding before printing, # to be able to print UTF-8 error messages on Windows. # # ### 2.0.2 -- 2021-09-07 # # * Do not translate error messages, as this converts them to the native # encoding. We keep messages in UTF-8 now. # # ### 3.0.0 -- 2022-04-19 # # * Major rewrite, use rlang compatible error objects. New API. # # ### 3.0.1 -- 2022-06-17 # # * Remove the `rlang_error` and `rlang_trace` classes, because our new # deparsed `call` column in the trace is not compatible with rlang. # # ### 3.0.2 -- 2022-08-01 # # * Use a `procsrcref` column for processed source references. # Otherwise testthat (and probably other rlang based packages), will # pick up the `srcref` column, and they expect an `srcref` object there. # # ### 3.1.0 -- 2022-10-04 # # * Add ANSI hyperlinks to stack traces, if we have a recent enough # cli package that supports this. # # ### 3.1.1 -- 2022-11-17 # # * Use `[[` instead of `$` to fix some partial matches. # * Use fully qualified `base::stop()` to enable overriding `stop()` # in a package. (Makes sense if compat files use `stop()`. # * The `is_interactive()` function is now exported. # # ### 3.1.2 -- 2022-11-18 # # * The `parent` condition can now be an interrupt. # # ### 3.1.3 -- 2023-01-15 # # * Now we do not load packages when walking the trace. # # ### 3.1.4 -- 2023-04-13 # # * `call.` can now be a frame environment as in `rlang::abort()` err <- local({ # -- dependencies ----------------------------------------------------- rstudio_detect <- rstudio$detect # -- condition constructors ------------------------------------------- #' Create a new condition #' #' @noRd #' @param ... Parts of the error message, they will be converted to #' character and then concatenated, like in [stop()]. #' @param call. A call object to include in the condition, or `TRUE` #' or `NULL`, meaning that [throw()] should add a call object #' automatically. If `FALSE`, then no call is added. #' @param srcref Alternative source reference object to use instead of #' the one of `call.`. #' @param domain Translation domain, see [stop()]. We set this to #' `NA` by default, which means that no translation occurs. This #' has the benefit that the error message is not re-encoded into #' the native locale. #' @return Condition object. Currently a list, but you should not rely #' on that. new_cond <- function(..., call. = TRUE, srcref = NULL, domain = NA) { message <- .makeMessage(..., domain = domain) structure( list(message = message, call = call., srcref = srcref), class = c("condition") ) } #' Create a new error condition #' #' It also adds the `rlib_error` class. #' #' @noRd #' @param ... Passed to [new_cond()]. #' @param call. Passed to [new_cond()]. #' @param srcref Passed tp [new_cond()]. #' @param domain Passed to [new_cond()]. #' @return Error condition object with classes `rlib_error`, `error` #' and `condition`. new_error <- function(..., call. = TRUE, srcref = NULL, domain = NA) { cond <- new_cond(..., call. = call., domain = domain, srcref = srcref) class(cond) <- c("rlib_error_3_0", "rlib_error", "error", "condition") cond } # -- throwing conditions ---------------------------------------------- #' Throw a condition #' #' If the condition is an error, it will also call [stop()], after #' signalling the condition first. This means that if the condition is #' caught by an exiting handler, then [stop()] is not called. #' #' @noRd #' @param cond Condition object to throw. If it is an error condition, #' then it calls [stop()]. #' @param parent Parent condition. #' @param frame The throwing context. Can be used to hide frames from #' the backtrace. throw <- throw_error <- function( cond, parent = NULL, call = parent.frame(), frame = environment() ) { if (!inherits(cond, "condition")) { cond <- new_error(cond) } if (!is.null(parent) && !inherits(parent, "condition")) { throw(new_error("Parent condition must be a condition object")) } if (isTRUE(cond[["call"]])) { cond[["call"]] <- frame_call(call) } else if (identical(cond[["call"]], FALSE)) { cond[["call"]] <- NULL } else if (is.environment(cond[["call"]])) { cond[["call"]] <- frame_call(cond[["call"]]) } cond <- process_call(cond) if (!is.null(parent)) { cond$parent <- process_call(parent) } # We can set an option to always add the trace to the thrown # conditions. This is useful for example in context that always catch # errors, e.g. in testthat tests or knitr. This options is usually not # set and we signal the condition here always_trace <- isTRUE(getOption("rlib_error_always_trace")) .hide_from_trace <- 1L # .error_frame <- cond if (!always_trace) signalCondition(cond) if (is.null(cond$`_pid`)) cond$`_pid` <- Sys.getpid() if (is.null(cond$`_timestamp`)) cond$`_timestamp` <- Sys.time() # If we get here that means that the condition was not caught by # an exiting handler. That means that we need to create a trace. # If there is a hand-constructed trace already in the error object, # then we'll just leave it there. if (is.null(cond$trace)) cond <- add_trace_back(cond, frame = frame) # Set up environment to store .Last.error, it will be just before # baseenv(), so it is almost as if it was in baseenv() itself, like # .Last.value. We save the print methods here as well, and then they # will be found automatically. if (!"org:r-lib" %in% search()) { do.call( "attach", list(new.env(), pos = length(search()), name = "org:r-lib") ) } env <- as.environment("org:r-lib") env$.Last.error <- cond env$.Last.error.trace <- cond$trace # If we always wanted a trace, then we signal the condition here if (always_trace) signalCondition(cond) # If this is not an error, then we'll just return here. This allows # throwing interrupt conditions for example, with the same UI. if (!inherits(cond, "error")) return(invisible()) .hide_from_trace <- NULL # Top-level handler, this is intended for testing only for now, # and its design might change. if ( !is.null(th <- getOption("rlib_error_handler")) && is.function(th) ) { return(th(cond)) } # In non-interactive mode, we print the error + the traceback # manually, to make sure that it won't be truncated by R's error # message length limit. out <- format( cond, trace = !is_interactive(), class = FALSE, full = !is_interactive() ) writeLines(out, con = default_output()) # Dropping the classes and adding "duplicate_condition" is a workaround # for the case when we have non-exiting handlers on throw()-n # conditions. These would get the condition twice, because stop() # will also signal it. If we drop the classes, then only handlers # on "condition" objects (i.e. all conditions) get duplicate signals. # This is probably quite rare, but for this rare case they can also # recognize the duplicates from the "duplicate_condition" extra class. class(cond) <- c("duplicate_condition", "condition") # Turn off the regular error printing to avoid printing # the error twice. opts <- options(show.error.messages = FALSE) on.exit(options(opts), add = TRUE) base::stop(cond) } # -- rethrow with parent ----------------------------------------------- #' Re-throw an error with a better error message #' #' Evaluate `expr` and if it errors, then throw a new error `err`, #' with the original error set as its parent. #' #' @noRd #' @param expr Expression to evaluate. #' @param err Error object or message to use for the child error. #' @param call Call to use in the re-thrown error. See [throw()]. chain_error <- function(expr, err, call = sys.call(-1), srcref = NULL) { .hide_from_trace <- 1 force(call) srcref <- srcref %||% utils::getSrcref(sys.call()) withCallingHandlers( { expr }, error = function(e) { .hide_from_trace <- 0:1 e$srcref <- srcref e$procsrcref <- NULL if (!inherits(err, "condition")) { err <- new_error(err, call. = call) } throw_error(err, parent = e) } ) } # -- rethrowing conditions from C code --------------------------------- #' Version of .Call that throw()s errors #' #' It re-throws error from compiled code. If the error had class #' `simpleError`, like all errors, thrown via `error()` in C do, it also #' adds the `c_error` class. #' #' @noRd #' @param .NAME Compiled function to call, see [.Call()]. #' @param ... Function arguments, see [.Call()]. #' @return Result of the call. chain_call <- function(.NAME, ...) { .hide_from_trace <- 1:3 # withCallingHandlers + do.call + .handleSimpleError (?) call <- sys.call() call1 <- sys.call(-1) srcref <- utils::getSrcref(call) withCallingHandlers( do.call(".Call", list(.NAME, ...)), error = function(e) { .hide_from_trace <- 0:1 e$srcref <- srcref e$procsrcref <- NULL e[["call"]] <- call name <- native_name(.NAME) err <- new_error("Native call to `", name, "` failed", call. = call1) cerror <- if (inherits(e, "simpleError")) "c_error" class(err) <- c( cerror, "rlib_error_3_0", "rlib_error", "error", "condition" ) throw_error(err, parent = e) } ) } package_env <- topenv() #' Version of entrace_call that supports cleancall #' #' This function is the same as [entrace_call()], except that it #' uses cleancall's [.Call()] wrapper, to enable resource cleanup. #' See https://github.com/r-lib/cleancall#readme for more about #' resource cleanup. #' #' @noRd #' @param .NAME Compiled function to call, see [.Call()]. #' @param ... Function arguments, see [.Call()]. #' @return Result of the call. chain_clean_call <- function(.NAME, ...) { .hide_from_trace <- 1:3 call <- sys.call() call1 <- sys.call(-1) srcref <- utils::getSrcref(call) withCallingHandlers( package_env$call_with_cleanup(.NAME, ...), error = function(e) { .hide_from_trace <- 0:1 e$srcref <- srcref e$procsrcref <- NULL e[["call"]] <- call name <- native_name(.NAME) err <- new_error("Native call to `", name, "` failed", call. = call1) cerror <- if (inherits(e, "simpleError")) "c_error" class(err) <- c( cerror, "rlib_error_3_0", "rlib_error", "error", "condition" ) throw_error(err, parent = e) } ) } # -- create traceback ------------------------------------------------- #' Create a traceback #' #' [throw()] calls this function automatically if an error is not caught, #' so there is currently not much use to call it directly. #' #' @param cond Condition to add the trace to #' @param frame Use this context to hide some frames from the traceback. #' #' @return A condition object, with the trace added. add_trace_back <- function(cond, frame = NULL) { idx <- seq_len(sys.parent(1L)) frames <- sys.frames()[idx] # TODO: remove embedded objects from calls calls <- as.list(sys.calls()[idx]) parents <- sys.parents()[idx] namespaces <- unlist(lapply( seq_along(frames), function(i) { if (is_operator(calls[[i]])) { "o" } else { env_label(topenvx(environment(sys.function(i)))) } } )) pids <- rep(cond$`_pid` %||% Sys.getpid(), length(calls)) mch <- match(format(frame), sapply(frames, format)) if (is.na(mch)) { visibles <- TRUE } else { visibles <- c(rep(TRUE, mch), rep(FALSE, length(frames) - mch)) } scopes <- vapply(idx, FUN.VALUE = character(1), function(i) { tryCatch( get_call_scope(calls[[i]], namespaces[[i]]), error = function(e) "" ) }) namespaces <- ifelse(scopes %in% c("::", ":::"), namespaces, NA_character_) funs <- ifelse( is.na(namespaces), ifelse(scopes != "", paste0(scopes, " "), ""), paste0(namespaces, scopes) ) funs <- paste0( funs, vapply(calls, function(x) format_name(x[[1]])[1], character(1)) ) visibles <- visibles & mark_invisible_frames(funs, frames) pcs <- lapply(calls, function(c) process_call(list(call = c))) calls <- lapply(pcs, "[[", "call") srcrefs <- I(lapply(pcs, "[[", "srcref")) procsrcrefs <- I(lapply(pcs, "[[", "procsrcref")) cond$trace <- new_trace( calls, parents, visibles = visibles, namespaces = namespaces, scopes = scopes, srcrefs = srcrefs, procsrcrefs = procsrcrefs, pids ) cond } is_operator <- function(cl) { is.call(cl) && length(cl) >= 1 && is.symbol(cl[[1]]) && grepl("^[^.a-zA-Z]", as.character(cl[[1]])) } mark_invisible_frames <- function(funs, frames) { visibles <- rep(TRUE, length(frames)) hide <- lapply(frames, "[[", ".hide_from_trace") w_hide <- unlist(mapply( seq_along(hide), hide, FUN = function(i, w) { i + w }, SIMPLIFY = FALSE )) w_hide <- w_hide[w_hide <= length(frames)] visibles[w_hide] <- FALSE hide_from <- which(funs %in% names(invisible_frames)) for (start in hide_from) { hide_this <- invisible_frames[[funs[start]]] for (i in seq_along(hide_this)) { if (start + i > length(funs)) break if (funs[start + i] != hide_this[i]) break visibles[start + i] <- FALSE } } visibles } invisible_frames <- list( "base::source" = c("base::withVisible", "base::eval", "base::eval"), "base::stop" = "base::.handleSimpleError", "cli::cli_abort" = c( "rlang::abort", "rlang:::signal_abort", "base::signalCondition" ), "rlang::abort" = c("rlang:::signal_abort", "base::signalCondition") ) call_name <- function(x) { if (is.call(x)) { if (is.symbol(x[[1]])) { as.character(x[[1]]) } else if (x[[1]][[1]] == quote(`::`) || x[[1]][[1]] == quote(`:::`)) { as.character(x[[1]][[2]]) } else { NULL } } else { NULL } } get_call_scope <- function(call, ns) { if (is.na(ns)) return("global") if (!is.call(call)) return("") if ( is.call(call[[1]]) && (call[[1]][[1]] == quote(`::`) || call[[1]][[1]] == quote(`:::`)) ) return("") if (ns == "base") return("::") if (!ns %in% loadedNamespaces()) return("") name <- call_name(call) if (!ns %in% loadedNamespaces()) return("::") nsenv <- asNamespace(ns)$.__NAMESPACE__. if (is.null(nsenv)) return("::") if (is.null(nsenv$exports)) return(":::") if (exists(name, envir = nsenv$exports, inherits = FALSE)) { "::" } else if (exists(name, envir = asNamespace(ns), inherits = FALSE)) { ":::" } else { "local" } } topenvx <- function(x) { topenv(x, matchThisEnv = err_env) } new_trace <- function( calls, parents, visibles, namespaces, scopes, srcrefs, procsrcrefs, pids ) { trace <- data.frame( stringsAsFactors = FALSE, parent = parents, visible = visibles, namespace = namespaces, scope = scopes, srcref = srcrefs, procsrcref = procsrcrefs, pid = pids ) trace[["call"]] <- calls class(trace) <- c("rlib_trace_3_0", "rlib_trace", "tbl", "data.frame") trace } env_label <- function(env) { nm <- env_name(env) if (nzchar(nm)) { nm } else { env_address(env) } } env_address <- function(env) { class(env) <- "environment" sub("^.*(0x[0-9a-f]+)>$", "\\1", format(env), perl = TRUE) } env_name <- function(env) { if (identical(env, err_env)) { return(env_name(package_env)) } if (identical(env, globalenv())) { return(NA_character_) } if (identical(env, baseenv())) { return("base") } if (identical(env, emptyenv())) { return("empty") } nm <- environmentName(env) if (isNamespace(env)) { return(nm) } nm } # -- S3 methods ------------------------------------------------------- format_error <- function( x, trace = FALSE, class = FALSE, advice = !trace, full = trace, header = TRUE, ... ) { if (has_cli()) { format_error_cli(x, trace, class, advice, full, header, ...) } else { format_error_plain(x, trace, class, advice, full, header, ...) } } print_error <- function(x, trace = TRUE, class = TRUE, advice = !trace, ...) { writeLines(format_error(x, trace, class, advice, ...)) } format_trace <- function(x, ...) { if (has_cli()) { format_trace_cli(x, ...) } else { format_trace_plain(x, ...) } } print_trace <- function(x, ...) { writeLines(format_trace(x, ...)) } cnd_message <- function(cond) { paste(cnd_message_(cond, full = FALSE), collapse = "\n") } cnd_message_ <- function(cond, full = FALSE) { if (has_cli()) { cnd_message_cli(cond, full) } else { cnd_message_plain(cond, full) } } # -- format API ------------------------------------------------------- format_advice <- function(x) { if (has_cli()) { format_advice_cli(x) } else { format_advice_plain(x) } } format_call <- function(call) { if (has_cli()) { format_call_cli(call) } else { format_call_plain(call) } } format_class <- function(x) { if (has_cli()) { format_class_cli(x) } else { format_class_plain(x) } } format_error_heading <- function(x, prefix = NULL) { if (has_cli()) { format_error_heading_cli(x, prefix) } else { format_error_heading_plain(x, prefix) } } format_header_line <- function(x, prefix = NULL) { if (has_cli()) { format_header_line_cli(x, prefix) } else { format_header_line_plain(x, prefix) } } format_srcref <- function(call, srcref = NULL) { if (has_cli()) { format_srcref_cli(call, srcref) } else { format_srcref_plain(call, srcref) } } # -- condition message with cli --------------------------------------- cnd_message_robust <- function(cond) { class(cond) <- setdiff(class(cond), "rlib_error_3_0") conditionMessage(cond) %||% (if (inherits(cond, "interrupt")) "interrupt") %||% "" } cnd_message_cli <- function(cond, full = FALSE) { exp <- paste0(cli::col_yellow("!"), " ") add_exp <- is.null(names(cond$message)) msg <- cnd_message_robust(cond) c( paste0(if (add_exp) exp, msg), if (inherits(cond$parent, "condition")) { msg <- if (full && inherits(cond$parent, "rlib_error_3_0")) { format( cond$parent, trace = FALSE, full = TRUE, class = FALSE, header = FALSE, advice = FALSE ) } else if (inherits(cond$parent, "interrupt")) { "interrupt" } else { conditionMessage(cond$parent) } add_exp <- substr(cli::ansi_strip(msg[1]), 1, 1) != "!" if (add_exp) msg[1] <- paste0(exp, msg[1]) c(format_header_line_cli(cond$parent, prefix = "Caused by error"), msg) } ) } # -- condition message w/o cli ---------------------------------------- cnd_message_plain <- function(cond, full = FALSE) { exp <- "! " add_exp <- is.null(names(cond$message)) c( paste0(if (add_exp) exp, cnd_message_robust(cond)), if (inherits(cond$parent, "condition")) { msg <- if (full && inherits(cond$parent, "rlib_error_3_0")) { format( cond$parent, trace = FALSE, full = TRUE, class = FALSE, header = FALSE, advice = FALSE ) } else if (inherits(cond$parent, "interrupt")) { "interrupt" } else { conditionMessage(cond$parent) } add_exp <- substr(msg[1], 1, 1) != "!" if (add_exp) { msg[1] <- paste0(exp, msg[1]) } c( format_header_line_plain(cond$parent, prefix = "Caused by error"), msg ) } ) } # -- printing error with cli ------------------------------------------ # Error parts: # - "Error:" or "Error in " prefix, the latter if the error has a call # - the call, possibly syntax highlightedm possibly trimmed (?) # - source ref, with link to the file, potentially in a new line in cli # - error message, just `conditionMessage()` # - advice about .Last.error and/or .Last.error.trace format_error_cli <- function( x, trace = TRUE, class = TRUE, advice = !trace, full = trace, header = TRUE, ... ) { p_class <- if (class) format_class_cli(x) p_header <- if (header) format_header_line_cli(x) p_msg <- cnd_message_cli(x, full) p_advice <- if (advice) format_advice_cli(x) else NULL p_trace <- if (trace && !is.null(x$trace)) { c("---", "Backtrace:", format_trace_cli(x$trace)) } c(p_class, p_header, p_msg, p_advice, p_trace) } format_header_line_cli <- function(x, prefix = NULL) { p_error <- format_error_heading_cli(x, prefix) p_call <- format_call_cli(x[["call"]]) p_srcref <- format_srcref_cli(conditionCall(x), x$procsrcref %||% x$srcref) paste0(p_error, p_call, p_srcref, if (!is.null(conditionCall(x))) ":") } format_class_cli <- function(x) { cls <- unique(setdiff(class(x), "condition")) cls # silence codetools cli::format_inline("{.cls {cls}}") } format_error_heading_cli <- function(x, prefix = NULL) { str_error <- if (is.null(prefix)) { cli::style_bold(cli::col_yellow("Error")) } else { cli::style_bold(paste0(prefix)) } if (is.null(conditionCall(x))) { paste0(str_error, ": ") } else { paste0(str_error, " in ") } } format_call_cli <- function(call) { if (is.null(call)) { NULL } else { cl <- trimws(format(call)) if (length(cl) > 1) cl <- paste0(cl[1], " ", cli::symbol$ellipsis) cli::format_inline("{.code {cl}}") } } format_srcref_cli <- function(call, srcref = NULL) { ref <- get_srcref(call, srcref) if (is.null(ref)) return("") link <- if (ref$file != "") { if (Sys.getenv("R_CLI_HYPERLINK_STYLE") == "iterm") { cli::style_hyperlink( cli::format_inline("{basename(ref$file)}:{ref$line}:{ref$col}"), paste0("file://", ref$file, "#", ref$line, ":", ref$col) ) } else { cli::style_hyperlink( cli::format_inline("{basename(ref$file)}:{ref$line}:{ref$col}"), paste0("file://", ref$file), params = c(line = ref$line, col = ref$col) ) } } else { paste0("line ", ref$line) } cli::col_silver(paste0(" at ", link)) } str_advice <- "Type .Last.error to see the more details." format_advice_cli <- function(x) { cli::col_silver(str_advice) } format_trace_cli <- function(x, ...) { x$num <- seq_len(nrow(x)) scope <- ifelse( is.na(x$namespace), ifelse(x$scope != "", paste0(x$scope, " "), ""), paste0(x$namespace, x$scope) ) visible <- if ("visible" %in% names(x)) { x$visible } else { rep(TRUE, nrow(x)) } srcref <- if ("srcref" %in% names(x) || "procsrcref" %in% names(x)) { vapply( seq_len(nrow(x)), function(i) format_srcref_cli( x[["call"]][[i]], x$procsrcref[[i]] %||% x$srcref[[i]] ), character(1) ) } else { unname(vapply(x[["call"]], format_srcref_cli, character(1))) } lines <- paste0( cli::col_silver(format(x$num), ". "), ifelse(visible, "", "| "), scope, vapply( seq_along(x$call), function(i) { format_trace_call_cli(x$call[[i]], x$namespace[[i]]) }, character(1) ), srcref ) lines[!visible] <- cli::col_silver(cli::ansi_strip( lines[!visible], link = FALSE )) lines } format_trace_call_cli <- function(call, ns = "") { envir <- tryCatch( { if (!ns %in% loadedNamespaces()) stop("no") asNamespace(ns) }, error = function(e) .GlobalEnv ) cl <- trimws(format(call)) if (length(cl) > 1) { cl <- paste0(cl[1], " ", cli::symbol$ellipsis) } # Older cli does not have 'envir'. if ("envir" %in% names(formals(cli::code_highlight))) { fmc <- cli::code_highlight(cl, envir = envir)[1] } else { fmc <- cli::code_highlight(cl)[1] } cli::ansi_strtrim(fmc, cli::console_width() - 5) } # ---------------------------------------------------------------------- format_error_plain <- function( x, trace = TRUE, class = TRUE, advice = !trace, full = trace, header = TRUE, ... ) { p_class <- if (class) format_class_plain(x) p_header <- if (header) format_header_line_plain(x) p_msg <- cnd_message_plain(x, full) p_advice <- if (advice) format_advice_plain(x) else NULL p_trace <- if (trace && !is.null(x$trace)) { c("---", "Backtrace:", format_trace_plain(x$trace)) } c(p_class, p_header, p_msg, p_advice, p_trace) } format_trace_plain <- function(x, ...) { x$num <- seq_len(nrow(x)) scope <- ifelse( is.na(x$namespace), ifelse(x$scope != "", paste0(x$scope, " "), ""), paste0(x$namespace, x$scope) ) visible <- if ("visible" %in% names(x)) { x$visible } else { rep(TRUE, nrow(x)) } srcref <- if ("srcref" %in% names(x) || "procsrfref" %in% names(x)) { vapply( seq_len(nrow(x)), function(i) format_srcref_plain( x[["call"]][[i]], x$procsrcref[[i]] %||% x$srcref[[i]] ), character(1) ) } else { unname(vapply(x[["call"]], format_srcref_plain, character(1))) } lines <- paste0( paste0(format(x$num), ". "), ifelse(visible, "", "| "), scope, vapply(x[["call"]], format_trace_call_plain, character(1)), srcref ) lines } format_advice_plain <- function(x, ...) { str_advice } format_header_line_plain <- function(x, prefix = NULL) { p_error <- format_error_heading_plain(x, prefix) p_call <- format_call_plain(x[["call"]]) p_srcref <- format_srcref_plain( conditionCall(x), x$procsrcref %||% x$srcref ) paste0(p_error, p_call, p_srcref, if (!is.null(conditionCall(x))) ":") } format_error_heading_plain <- function(x, prefix = NULL) { str_error <- if (is.null(prefix)) "Error" else prefix if (is.null(conditionCall(x))) { paste0(str_error, ": ") } else { paste0(str_error, " in ") } } format_class_plain <- function(x) { cls <- unique(setdiff(class(x), "condition")) paste0("<", paste(cls, collapse = "/"), ">") } format_call_plain <- function(call) { if (is.null(call)) { NULL } else { cl <- trimws(format(call)) if (length(cl) > 1) cl <- paste0(cl[1], " ...") paste0("`", cl, "`") } } format_srcref_plain <- function(call, srcref = NULL) { ref <- get_srcref(call, srcref) if (is.null(ref)) return("") link <- if (ref$file != "") { paste0(basename(ref$file), ":", ref$line, ":", ref$col) } else { paste0("line ", ref$line) } paste0(" at ", link) } format_trace_call_plain <- function(call) { fmc <- trimws(format(call)[1]) if (length(fmc) > 1) { fmc <- paste0(fmc[1], " ...") } strtrim(fmc, getOption("width") - 5) } # -- utilities --------------------------------------------------------- cli_version <- function() { # this loads cli! package_version(asNamespace("cli")[[".__NAMESPACE__."]]$spec[["version"]]) } has_cli <- function() { "cli" %in% loadedNamespaces() && cli_version() >= "3.3.0" } `%||%` <- function(l, r) if (is.null(l)) r else l bytes <- function(x) { nchar(x, type = "bytes") } process_call <- function(cond) { cond[c("call", "srcref", "procsrcref")] <- list( call = if (is.null(cond[["call"]])) { NULL } else if (is.character(cond[["call"]])) { cond[["call"]] } else { deparse(cond[["call"]], nlines = 2) }, srcref = NULL, procsrcref = get_srcref(cond[["call"]], cond$procsrcref %||% cond$srcref) ) cond } get_srcref <- function(call, srcref = NULL) { ref <- srcref %||% utils::getSrcref(call) if (is.null(ref)) return(NULL) if (inherits(ref, "processed_srcref")) return(ref) file <- utils::getSrcFilename(ref, full.names = TRUE)[1] if (is.na(file)) file <- "" line <- utils::getSrcLocation(ref) %||% "" col <- utils::getSrcLocation(ref, which = "column") %||% "" structure( list(file = file, line = line, col = col), class = "processed_srcref" ) } is_interactive <- function() { opt <- getOption("rlib_interactive") if (isTRUE(opt)) { TRUE } else if (identical(opt, FALSE)) { FALSE } else if (tolower(getOption("knitr.in.progress", "false")) == "true") { FALSE } else if ( tolower(getOption("rstudio.notebook.executing", "false")) == "true" ) { FALSE } else if (identical(Sys.getenv("TESTTHAT"), "true")) { FALSE } else { interactive() } } no_sink <- function() { sink.number() == 0 && sink.number("message") == 2 } rstudio_stdout <- function() { rstudio <- rstudio_detect() rstudio$type %in% c( "rstudio_console", "rstudio_console_starting", "rstudio_build_pane", "rstudio_job", "rstudio_render_pane" ) } default_output <- function() { if ((is_interactive() || rstudio_stdout()) && no_sink()) { stdout() } else { stderr() } } onload_hook <- function() { reg_env <- Sys.getenv("R_LIB_ERROR_REGISTER_PRINT_METHODS", "TRUE") if (tolower(reg_env) != "false") { registerS3method("format", "rlib_error_3_0", format_error, baseenv()) registerS3method("format", "rlib_trace_3_0", format_trace, baseenv()) registerS3method("print", "rlib_error_3_0", print_error, baseenv()) registerS3method("print", "rlib_trace_3_0", print_trace, baseenv()) registerS3method( "conditionMessage", "rlib_error_3_0", cnd_message, baseenv() ) } } native_name <- function(x) { if (inherits(x, "NativeSymbolInfo")) { x$name } else { format(x) } } # There is no format() for 'name' in R 3.6.x and before format_name <- function(x) { if (is.name(x)) { as.character(x) } else { format(x) } } frame_call <- function(frame) { out <- NULL delayedAssign("out", base::sys.call(), frame) out } # Useful for snapshots so that they print without an unstable backtrace. # Call `register_testthat_print()` before running tests. testthat_print_error <- function(x, ...) { x[["trace"]] <- NULL x[["srcref"]] <- NULL x[["procsrcref"]] <- NULL attr(x[["call"]], "srcref") <- NULL print(x) } registered <- FALSE register_testthat_print <- function() { if (!registered) { registerS3method( "testthat_print", "rlib_error", testthat_print_error, asNamespace("testthat") ) registered <<- TRUE } } # -- public API -------------------------------------------------------- err_env <- environment() parent.env(err_env) <- baseenv() structure( list( .internal = err_env, new_cond = new_cond, new_error = new_error, throw = throw, throw_error = throw_error, chain_error = chain_error, chain_call = chain_call, chain_clean_call = chain_clean_call, add_trace_back = add_trace_back, process_call = process_call, onload_hook = onload_hook, is_interactive = is_interactive, register_testthat_print = register_testthat_print, format = list( advice = format_advice, call = format_call, class = format_class, error = format_error, error_heading = format_error_heading, header_line = format_header_line, srcref = format_srcref, trace = format_trace ) ), class = c("standalone_errors", "standalone") ) }) # These are optional, and feel free to remove them if you prefer to # call them through the `err` object. new_cond <- err$new_cond new_error <- err$new_error throw <- err$throw throw_error <- err$throw_error chain_error <- err$chain_error chain_call <- err$chain_call chain_clean_call <- err$chain_clean_call keyring/R/package.R0000644000176200001440000000407215004361550013643 0ustar liggesusers#' About the keyring package #' #' Platform independent API to many system credential store #' implementations. Currently supported: #' * Keychain on macOS, #' * Credential Store on Windows, #' * the Secret Service API on Linux, and #' * environment variables on other platforms. #' #' @section Configuring an OS-specific backend: #' #' - The default is operating system specific, and is described in #' [default_backend()]. In most cases you don't have to configure this. #' - MacOS: [backend_macos] #' - Linux: [backend_secret_service] #' - Windows: [backend_wincred] #' - Or store the secrets in environment variables on other operating #' systems: [backend_env] #' #' @section Query secret keys in a keyring: #' #' Each keyring can contain one or many secrets (keys). A key is defined by #' a service name and a password. Once a key is defined, it persists in the #' keyring store of the operating system. This means the keys persist beyond #' the termination of and R session. Specifically, you can define a key #' once, and then read the key value in completely independent R sessions. #' #' - Setting a secret interactively: [key_set()]. #' - Setting a secret from a script, i.e. non-interactively: #' [key_set_with_value()]. #' - Reading a secret: [key_get()], [key_get_raw()]. #' - Listing secrets: [key_list()], [key_list_raw()]. #' - Deleting a secret: [key_delete()]. #' #' @section Managing keyrings: #' #' A keyring is a collection of keys that can be treated as a unit. #' A keyring typically has a name and a password to unlock it. #' #' - [keyring_create()] #' - [keyring_delete()] #' - [keyring_list()] #' - [keyring_lock()] #' - [keyring_unlock()] #' #' Note that all platforms have a default keyring, and `key_get()`, etc. #' will use that automatically. The default keyring is also convenient, #' because the OS unlocks it automatically when you log in, so secrets #' are available immediately. #' #' You only need to explicitly deal with keyrings and the `keyring_*` #' functions if you want to use a different keyring. #' #' @useDynLib keyring, .registration = TRUE "_PACKAGE" keyring/R/utils.R0000644000176200001440000000743715006370264013424 0ustar liggesusersutf8 <- function(x) { if (is.null(x)) return(x) iconv(x, "", "UTF-8") } `%||%` <- function(l, r) if (is.null(l)) r else l cat0 <- function(..., sep = "") { cat(..., sep = sep) } confirmation <- function(prompt, yes) { ans <- readline(paste0(prompt, ": ")) if (ans != yes) stop("Aborted", call. = FALSE) } darwin_version <- function() { info <- Sys.info() if (info[["sysname"]] != "Darwin") stop("Not macOS") package_version(info[["release"]]) } file_stamp <- function(x) { as.character(tools::md5sum(x)) } str_starts_with <- function(x, p) { ncp <- nchar(p) substr(x, 1, nchar(p)) == p } URLencode <- function(URL) { good <- c(LETTERS, letters, 0:9, ".", "_", "~", "-") x <- strsplit(URL, "")[[1L]] bad <- which(!x %in% good) tr <- function(x) { paste0("%", toupper(as.character(charToRaw(x))), collapse = "") } if (length(bad)) x[bad] <- vapply(x[bad], tr, character(1)) paste(x, collapse = "") } get_encoding_opt <- function() { chk <- function(x) is.character(x) && length(x) == 1 && !is.na(x) enc <- getOption("keyring.encoding_windows") if (!is.null(enc) && !chk(enc)) { stop( "Invalid 'keyring.encoding_windows' option, must be an ", "encoding name or 'auto'" ) } enc <- enc %||% Sys.getenv("KEYRING_ENCODING_WINDOWS", "auto") # Confirm valid encoding. Suggest closest match if not found. if (enc != "auto" & !(tolower(enc) %in% tolower(iconvlist()))) { icl <- iconvlist() closest <- icl[which.min(utils::adist(enc, icl))] stop(sprintf( "Encoding not found in iconvlist(). Did you mean %s?", closest )) } enc } is_interactive <- function() { opt <- getOption("rlib_interactive") if (isTRUE(opt)) { TRUE } else if (identical(opt, FALSE)) { FALSE } else if (tolower(getOption("knitr.in.progress", "false")) == "true") { FALSE } else if ( tolower(getOption("rstudio.notebook.executing", "false")) == "true" ) { FALSE } else if (identical(Sys.getenv("TESTTHAT"), "true")) { FALSE } else { interactive() } } base64_decode <- function(x) { if (is.character(x)) { x <- charToRaw(paste(gsub("\\s+", "", x), collapse = "")) } .Call(keyring_base64_decode, x) } base64_encode <- function(x) { if (is.character(x)) { x <- charToRaw(paste(x, collapse = "")) } rawToChar(.Call(keyring_base64_encode, x)) } sha256 <- function(x, key = NULL) { if (is.character(key)) { key <- base64_decode(key) } stopifnot(is.null(key) || is.raw(key)) if (!is.null(key)) { block_size <- 64L if (length(key) > block_size) { key <- .Call(keyring_sha256, key, TRUE) } else if (length(key) < block_size) { key <- c(key, rep(raw(1), block_size - length(key))) } opad <- as.raw(bitwXor(as.integer(key), as.integer(0x5c))) ipad <- as.raw(bitwXor(as.integer(key), as.integer(0x36))) .Call( keyring_sha256, c(opad, .Call(keyring_sha256, c(ipad, x), TRUE)), TRUE ) } else { .Call(keyring_sha256, x, TRUE) } } rand_bytes <- function(n = 1) { sodium_random(n) } aes_cbc_encrypt <- function(data, key, iv = rand_bytes(16)) { data <- path_or_raw(data) if (!is.raw(data)) { stop("The 'data' must path to a file or raw vector") } out <- .Call(keyring_aes_cbc_encrypt, data, key, iv) structure(out, iv = iv) } aes_cbc_decrypt <- function(data, key, iv = attr(data, "iv")) { data <- path_or_raw(data) if (!is.raw(data)) { stop("The 'data' must path to a file or raw vector") } .Call(keyring_aes_cbc_decrypt, data, key, iv) } path_or_raw <- function(x) { if (is.raw(x)) return(x) if (is.character(x) && length(x) == 1) { path <- normalizePath(x, mustWork = TRUE) bin <- readBin(path, raw(), file.info(path)$size) return(bin) } stop("`data` must be raw data vector or path to file on disk.") } keyring/R/assertions.R0000644000176200001440000000271515004361550014444 0ustar liggesusersis_string <- function(x) { is.character(x) && length(x) == 1 && !is.na(x) } on_failure(is_string) <- function(call, env) { paste0(deparse(call$x), " is not a string (length 1 character)") } is_string_or_null <- function(x) { is.null(x) || is_string(x) } on_failure(is_string_or_null) <- function(call, env) { paste0(deparse(call$x), " must be a string (length 1 character) or NULL") } is_non_empty_string <- function(x) { is_string(x) && x != "" } on_failure(is_non_empty_string) <- function(call, env) { paste0(deparse(call$x), " must be a non-empty string (length 1 character)") } is_non_empty_string_or_null <- function(x) { is.null(x) || is_non_empty_string(x) } on_failure(is_non_empty_string_or_null) <- function(call, env) { paste0( deparse(call$x), " must be a non-empty string (length 1 character) or NULL" ) } is_string_or_raw <- function(x) { is.raw(x) || is_string(x) } on_failure(is_string_or_raw) <- function(call, env) { paste0( deparse(call$x), " must be a string (length 1 character) or raw vector" ) } is_list_with_names <- function(x, names) { is.list(x) && length(x) == length(names) && all(vapply(names, function(name) has_name(x, name), logical(1L))) } on_failure(is_list_with_names) <- function(call, env) { paste0( deparse(call$x), " must be a named list of length ", length(call$names), " with entries ", paste(vapply(call$names, sQuote, character(1L)), collapse = ", ") ) } keyring/R/api.R0000644000176200001440000002431715004361550013025 0ustar liggesusers#' Operations on keys #' #' These functions manipulate keys in a keyring. You can think of a keyring #' as a secure key-value store. #' #' `key_get` queries a key from the keyring. #' #' `key_get_raw` queries a key and returns it as a raw vector. #' Most credential stores allow storing a byte sequence with embedded null #' bytes, and these cannot be represented as traditional null bytes #' terminated strings. If you don't know whether the key contains an #' embedded null, it is best to query it with `key_get_raw` instead of #' `key_get`. #' #' `key_set` sets a key in the keyring. The contents of the key is read #' interactively from the terminal. #' #' `key_set_with_value` is the non-interactive pair of `key_set`, to set #' a key in the keyring. #' #' `key_set_raw_with_value` sets a key to a byte sequence from a raw #' vector. #' #' `key_delete` deletes a key. #' #' `key_list` lists all keys of a keyring, or the keys for a certain #' service (if `service` is not `NULL`). #' #' `key_list_raw()` is like `key_list()` but also returns the keys as raw #' values. This is useful if your keys have bytes that cannot appear #' in R strings, e.g. a zero byte. #' #' ## Encodings #' #' On Windows, if required, an encoding can be specified using either #' an R option (`keyring.encoding_windows`) or environment variable #' (`KEYRING_ENCODING_WINDOWS`). This will be applied when both #' getting and setting keys. The option takes precedence over the #' environment variable, if both are set. #' #' This is reserved primarily for compatibility with keys set with #' other software, such as Python's implementation of keyring. For a #' list of encodings, use [iconvlist()], although it should be noted #' that not _every_ encoding can be properly converted, even for #' trivial cases. For best results, use UTF-8 if you can. #' #' @param service Service name, a character scalar. #' @param username Username, a character scalar, or `NULL` if the key #' is not associated with a username. #' @param password The secret to store. For `key_set`, it is read from #' the console, interactively. `key_set_with_value` can be also used #' in non-interactive mode. #' @param keyring For systems that support multiple keyrings, specify #' the name of the keyring to use here. If `NULL`, then the default #' keyring is used. See also [has_keyring_support()]. #' @param prompt The character string displayed when requesting the secret #' #' @return `key_get` returns a character scalar, the password or other #' confidential information that was stored in the key. #' #' `key_list` returns a list of keys, i.e. service names and usernames, #' in a data frame with column names `service` and `username`. If a #' service or user name contains a zero byte, which is not allowed in an #' R string, that entry is shown as `NA` and a warning (of class #' `keyring_warn_zero_byte_keys`) is thrown. You can use the #' `key_list_raw()` function to query these keys. #' #' `key_list_raw` is similar to `key_list` but returns service and #' usernames as raw vectors. This is useful if some service or user #' names) contain zero bytes. All column names: `service`, `username`, #' `service_raw`, `username_raw`. #' #' @export #' @examples #' # These examples use the default keyring, and they are interactive, #' # so, we don't run them by default #' \dontrun{ #' key_set("R-keyring-test-service", "donaldduck") #' key_get("R-keyring-test-service", "donaldduck") #' if (has_keyring_support()) key_list(service = "R-keyring-test-service") #' key_delete("R-keyring-test-service", "donaldduck") #' #' ## This is non-interactive, assuming that that default keyring #' ## is unlocked #' key_set_with_value("R-keyring-test-service", "donaldduck", #' password = "secret") #' key_get("R-keyring-test-service", "donaldduck") #' if (has_keyring_support()) key_list(service = "R-keyring-test-service") #' key_delete("R-keyring-test-service", "donaldduck") #' #' ## This is interactive using backend_file #' ## Set variables to be used in keyring #' kr_name <- "my_keyring" #' kr_service <- "my_database" #' kr_username <- "my_username" #' #' ## Create a keyring and add an entry using the variables above #' kb <- keyring::backend_file$new() #' ## Prompt for the keyring password, used to unlock keyring #' kb$keyring_create(kr_name) #' ## Prompt for the secret/password to be stored in the keyring #' kb$set(kr_service, username=kr_username, keyring=kr_name) #' # Lock the keyring #' kb$keyring_lock(kr_name) #' #' ## The keyring file is stored at ~/.config/r-keyring/ on Linux #' #' ## Output the stored password #' keyring::backend_file$new()$get(service = kr_service, #' user = kr_username, #' keyring = kr_name) #' } key_get <- function(service, username = NULL, keyring = NULL) { assert_that(is_non_empty_string(service)) assert_that(is_string_or_null(username)) default_backend()$get(service, username, keyring = keyring) } #' @export #' @rdname key_get key_get_raw <- function(service, username = NULL, keyring = NULL) { assert_that(is_non_empty_string(service)) assert_that(is_string_or_null(username)) default_backend()$get_raw(service, username, keyring = keyring) } #' @export #' @rdname key_get key_set <- function( service, username = NULL, keyring = NULL, prompt = "Password: " ) { assert_that(is_non_empty_string(service)) assert_that(is_string_or_null(username)) default_backend()$set(service, username, keyring = keyring, prompt = prompt) } #' @export #' @rdname key_get key_set_with_value <- function( service, username = NULL, password = NULL, keyring = NULL ) { assert_that(is_non_empty_string(service)) assert_that(is_string(password)) default_backend()$set_with_value( service, username, password, keyring = keyring ) } #' @export #' @rdname key_get key_set_with_raw_value <- function( service, username = NULL, password = NULL, keyring = NULL ) { assert_that(is_non_empty_string(service)) assert_that(is.raw(password)) default_backend()$set_with_raw_value( service, username, password, keyring = keyring ) } #' @export #' @rdname key_get key_delete <- function(service, username = NULL, keyring = NULL) { assert_that(is_non_empty_string(service)) assert_that(is_string_or_null(username)) default_backend()$delete(service, username, keyring = keyring) } #' @export #' @rdname key_get key_list <- function(service = NULL, keyring = NULL) { assert_that(is_non_empty_string_or_null(service)) default_backend()$list(service, keyring = keyring) } #' @export #' @rdname key_get key_list_raw <- function(service = NULL, keyring = NULL) { assert_that(is_non_empty_string_or_null(service)) default_backend()$list_raw(service, keyring = keyring) } #' Operations on keyrings #' #' On most platforms `keyring` supports multiple keyrings. This includes #' Windows, macOS and Linux (Secret Service) as well. A keyring is a #' collection of keys that can be treated as a unit. A keyring typically #' has a name and a password to unlock it. Once a keyring is unlocked, #' it remains unlocked until the end of the user session, or until it is #' explicitly locked again. #' #' Platforms typically have a default keyring, which is unlocked #' automatically when the user logs in. This keyring does not need to be #' unlocked explicitly. #' #' You can configure the keyring to use via R options or environment #' variables (see [default_backend()]), or you can also specify it #' directly in the [default_backend()] call, or in the individual #' `keyring` calls. #' #' `has_keyring_support` checks if a backend supports multiple keyrings. #' #' `keyring_create` creates a new keyring. It asks for a password if no #' password is specified. #' #' `keyring_list` lists all existing keyrings. #' #' `keyring_delete` deletes a keyring. Deleting a non-empty keyring #' requires confirmation, and the default keyring can only be deleted if #' specified explicitly. On some backends (e.g. Windows Credential Store), #' the default keyring cannot be deleted at all. #' #' `keyring_lock` locks a keyring. On some backends (e.g. Windows #' Credential Store), the default keyring cannot be locked. #' #' `keyring_unlock` unlocks a keyring. If a password is not specified, #' it will be read in interactively. #' #' `keyring_is_locked` queries whether a keyring is locked. #' #' @param keyring The name of the keyring to create or to operate on. #' For functions other than `keyring_create`, it can also be `NULL` to #' select the default keyring. #' @param password The initial password or the password to unlock the #' keyring. If not specified or `NULL`, it will be read from the console. #' #' @export #' @examples #' default_backend() #' has_keyring_support() #' backend_env$new()$has_keyring_support() #' #' ## This might ask for a password, so we do not run it by default #' ## It only works if the default backend supports multiple keyrings #' \dontrun{ #' keyring_create("foobar") #' key_set_with_value("R-test-service", "donaldduck", password = "secret", #' keyring = "foobar") #' key_get("R-test-service", "donaldduck", keyring = "foobar") #' key_list(keyring = "foobar") #' keyring_delete(keyring = "foobar") #' } has_keyring_support <- function() { default_backend()$has_keyring_support() } #' @export #' @rdname has_keyring_support keyring_create <- function(keyring, password = NULL) { assert_that( is_string(keyring), is_string_or_null(password) ) default_backend()$keyring_create(keyring, password) } #' @export #' @rdname has_keyring_support keyring_list <- function() { default_backend()$keyring_list() } #' @export #' @rdname has_keyring_support keyring_delete <- function(keyring = NULL) { assert_that(is_string_or_null(keyring)) default_backend()$keyring_delete(keyring) } #' @export #' @rdname has_keyring_support keyring_lock <- function(keyring = NULL) { assert_that(is_string_or_null(keyring)) default_backend()$keyring_lock(keyring) } #' @export #' @rdname has_keyring_support keyring_unlock <- function(keyring = NULL, password = NULL) { assert_that(is_string_or_null(keyring)) default_backend()$keyring_unlock(keyring, password) } #' @export #' @rdname has_keyring_support keyring_is_locked <- function(keyring = NULL) { assert_that(is_string_or_null(keyring)) default_backend()$keyring_is_locked(keyring) } keyring/R/pass.R0000644000176200001440000000012414144472216013216 0ustar liggesusersget_pass <- function(prompt = "Password: ") { askpass::askpass(prompt = prompt) } keyring/R/aaassertthat.R0000644000176200001440000000533515004361550014737 0ustar liggesusersassert_that <- function(..., env = parent.frame(), msg = NULL) { res <- see_if(..., env = env, msg = msg) if (res) return(TRUE) throw(new_assert_error(attr(res, "msg"))) } new_assert_error <- function(message, call = NULL) { cond <- new_error(message, call. = call) class(cond) <- c("assert_error", class(cond)) cond } see_if <- function(..., env = parent.frame(), msg = NULL) { asserts <- eval(substitute(alist(...))) for (assertion in asserts) { res <- tryCatch( { eval(assertion, env) }, new_assert_error = function(e) { structure(FALSE, msg = e$message) } ) check_result(res) # Failed, so figure out message to produce if (!res) { if (is.null(msg)) msg <- get_message(res, assertion, env) return(structure(FALSE, msg = msg)) } } res } check_result <- function(x) { if (!is.logical(x)) throw(new_assert_error( "assert_that: assertion must return a logical value" )) if (any(is.na(x))) throw(new_assert_error("assert_that: missing values present in assertion")) if (length(x) != 1) { throw(new_assert_error("assert_that: length of assertion is not 1")) } TRUE } get_message <- function(res, call, env = parent.frame()) { stopifnot(is.call(call), length(call) >= 1) if (has_attr(res, "msg")) { return(attr(res, "msg")) } f <- eval(call[[1]], env) if (!is.primitive(f)) call <- match.call(f, call) fname <- deparse(call[[1]]) fail <- on_failure(f) %||% base_fs[[fname]] %||% fail_default fail(call, env) } # The default failure message works in the same way as stopifnot, so you can # continue to use any function that returns a logical value: you just won't # get a friendly error message. # The code below says you get the first 60 characters plus a ... fail_default <- function(call, env) { call_string <- deparse(call, width.cutoff = 60L) if (length(call_string) > 1L) { call_string <- paste0(call_string[1L], "...") } paste0(call_string, " is not TRUE") } on_failure <- function(x) attr(x, "fail") "on_failure<-" <- function(x, value) { stopifnot(is.function(x), identical(names(formals(value)), c("call", "env"))) attr(x, "fail") <- value x } has_attr <- function(x, which) !is.null(attr(x, which, exact = TRUE)) on_failure(has_attr) <- function(call, env) { paste0(deparse(call$x), " does not have attribute ", eval(call$which, env)) } "%has_attr%" <- has_attr base_fs <- new.env(parent = emptyenv()) has_name <- function(x, which) { all(which %in% names(x)) } on_failure(has_name) <- function(call, env) { out_names <- paste0( "'", paste0(eval(call$which, env), collapse = "', '"), "'" ) paste0(deparse(call$x), " does not have all of these name(s): ", out_names) } keyring/R/default_backend.R0000644000176200001440000001052615015122043015336 0ustar liggesusers#' Select the default backend and default keyring #' #' The default backend is selected #' 1. based on the `keyring_backend` option. See [base::options()]. #' This can be set to a character string, and then the #' *backend_*`string` class is used to create the default backend. #' 1. If this is not set, then the `R_KEYRING_BACKEND` environment variable #' is checked. #' 1. If this is not set, either, then the backend is selected #' automatically, based on the OS: #' 1. On Windows, the Windows Credential Store (`"wincred"`) is used. #' 1. On macOS, Keychain services are selected (`"macos"`). #' 1. Linux uses the Secret Service API (`"secret_service"`), #' and it also checks that the service is available. It is typically #' only available on systems with a GUI. #' 1. If the file backend (`"file"`) is available, it is selected. #' 1. On other operating systems, secrets are stored in environment #' variables (`"env"`). #' #' Most backends support multiple keyrings. For these the keyring is #' selected from: #' 1. the supplied `keyring` argument (if not `NULL`), or #' 1. the `keyring_keyring` option. #' - You can change this by using `options(keyring_keyring = "NEWVALUE")` #' 1. If this is not set, the `R_KEYRING_KEYRING` environment variable. #' - Change this value with `Sys.setenv(R_KEYRING_KEYRING = "NEWVALUE")`, #' either in your script or in your `.Renviron` file. #' See [base::Startup] for information about using `.Renviron` #' 1. Finally, if neither of these are set, the OS default keyring is used. #' - Usually the keyring is automatically unlocked when the user logs in. #' #' @param keyring Character string, the name of the keyring to use, #' or `NULL` for the default keyring. #' @return The backend object itself. #' #' #' @seealso [backend_env], [backend_file], [backend_macos], #' [backend_secret_service], [backend_wincred] #' #' @export #' @name backends default_backend <- function(keyring = NULL) { assert_that(is_string_or_null(keyring)) backend <- getOption("keyring_backend", "") if (identical(backend, "")) backend <- default_backend_env_or_auto() ## Is it just a backend name? if (is_string(backend)) backend <- backend_factory(backend) ## At this point 'backend' is a backend R6 class ## Check if a specific keyring is requested if (is.null(keyring)) { keyring <- getOption( "keyring_keyring", Sys.getenv("R_KEYRING_KEYRING", "") ) } if (!is.null(keyring) && nzchar(keyring)) { backend$new(keyring = keyring) } else { backend$new() } } default_backend_env_or_auto <- function() { backend <- Sys.getenv("R_KEYRING_BACKEND", "") if (identical(backend, "")) backend <- default_backend_auto() backend } default_backend_auto <- function() { sysname <- tolower(Sys.info()[["sysname"]]) if (sysname == "windows" && "wincred" %in% names(known_backends)) { backend_wincred } else if (sysname == "darwin" && "macos" %in% names(known_backends)) { backend_macos } else if ( sysname == "linux" && "secret_service" %in% names(known_backends) && backend_secret_service$new()$is_available() ) { backend_secret_service } else if ("file" %in% names(known_backends) && file_backend_works()) { backend_file } else { # silly workaround if (Sys.getenv("TESTTHAT_PKG") != "air") { if (getOption("keyring_warn_for_env_fallback", TRUE)) { warning( "Selecting ", sQuote("env"), " backend. ", "Secrets are stored in environment variables" ) } } backend_env } } file_backend_works <- function() { opt <- options(rlib_interactive = FALSE) on.exit(options(opt), add = TRUE) tryCatch( { kb <- backend_file$new() krs <- kb$keyring_list() def <- kb$keyring_default() if (!def %in% krs$keyring) { return(FALSE) } kb$list() TRUE }, error = function(err) FALSE ) } backend_factory <- function(name) { assert_that(is_string(name)) if (!name %in% names(known_backends)) { stop("Unknown backend: ", sQuote(name)) } class_name <- paste0("backend_", name) get(class_name, envir = parent.frame()) } known_backends <- list( "wincred" = backend_wincred, "macos" = backend_macos, "secret_service" = backend_secret_service, "env" = backend_env, "file" = backend_file ) keyring/R/rappdirs.R0000644000176200001440000000663515004361550014103 0ustar liggesusersrappdirs <- local({ user_config_dir <- function( appname = "r-keyring", appauthor = appname, version = NULL, roaming = TRUE, expand = TRUE, os = NULL ) { if (nzchar(conf <- Sys.getenv("R_PKG_CONFIG_DIR", ""))) { return(conf) } if (nzchar(conf <- Sys.getenv("R_USER_CONFIG_DIR", ""))) { return(file.path(conf, "R")) } os <- os %||% get_os() version <- check_version(version, appname, expand) base <- switch( os, win = win_path(ifelse(roaming, "roaming", "local")), mac = "~/Library/Application Support", unix = Sys.getenv("XDG_CONFIG_HOME", "~/.config") ) file_path(base, if (os == "win") appauthor, appname, version) } get_os <- function() { if (.Platform$OS.type == "windows") { "win" } else if (Sys.info()["sysname"] == "Darwin") { "mac" } else { "unix" } } file_path <- function(...) { normalizePath(do.call("file.path", as.list(c(...))), mustWork = FALSE) } check_version <- function(version, appname, expand = FALSE) { if (is.null(appname) && !is.null(version)) { warning("version is ignored when appname is null", call. = FALSE) NULL } else { if (expand) { version <- expand_r_libs_specifiers(version) } version } } expand_r_libs_specifiers <- function(x) { if (is.null(x)) { return(NULL) } rversion <- getRversion() x <- gsub_special("%V", rversion, x) x <- gsub_special( "%v", paste(rversion$major, rversion$minor, sep = "."), x ) x <- gsub_special("%p", R.version$platform, x) x <- gsub_special("%o", R.version$os, x) x <- gsub_special("%a", R.version$arch, x) x <- gsub("%%", "%", x) x } gsub_special <- function(pattern, replacement, x) { gsub(paste0("([^%]|^)", pattern), paste0("\\1", replacement), x) } win_path <- function(type_appdata = "common") { CSIDL_APPDATA <- 26L CSIDL_COMMON_APPDATA <- 35L CSIDL_LOCAL_APPDATA <- 28L switch( type_appdata, roaming = win_path_csidl(CSIDL_APPDATA) %||% win_path_env("roaming"), local = win_path_csidl(CSIDL_LOCAL_APPDATA) %||% win_path_env("local"), common = win_path_csidl(CSIDL_COMMON_APPDATA) %||% win_path_env("common") ) } win_path_env <- function(type) { if (type == "roaming") { env_fallback("APPDATA") } else if (type == "local") { path <- Sys.getenv("LOCALAPPDATA", unset = NA) if (is.na(path)) { path <- file.path( env_fallback("USERPROFILE"), "Local Settings", "Application Data" ) } path } else if (type == "common") { path <- Sys.getenv("PROGRAMDATA", unset = NA) if (is.na(path)) { path <- file.path(env_fallback("ALLUSERPROFILE"), "Application Data") } path } else { stop("invalid `type` argument") } } win_path_csidl <- function(csidl) { stopifnot(is.integer(csidl), length(csidl) == 1) path <- .Call(win_path_, csidl) path } env_fallback <- function(env) { val <- Sys.getenv(env) if (identical(val, "")) { if (get_os() == "win") { stop("Can't find envvar '", env, "'", call. = FALSE) } else { paste0("<", env, ">") } } else { val } } list( .env = environment(), user_config_dir = user_config_dir ) }) user_config_dir <- rappdirs$user_config_dir keyring/R/backend-env.R0000644000176200001440000001010015015040476014415 0ustar liggesusers#' Environment variable keyring backend #' #' This is a simple keyring backend, that stores/uses secrets in #' environment variables of the R session. #' #' It does not support multiple keyrings. It also does not support listing #' all keys, since there is no way to distinguish keys from regular #' environment variables. #' #' It does support service names and usernames: they will be separated #' with a `:` character in the name of the environment variable. (Note that #' such an environment variable typically cannot be set or queried from a #' shell, but it can be set and queried from R or other programming #' languages.) #' #' See [backend] for the documentation of the class's methods. #' #' @family keyring backends #' @export #' @examples #' \dontrun{ #' env <- backend_env$new() #' env$set("r-keyring-test", username = "donaldduck") #' env$get("r-keyring-test", username = "donaldduck") #' Sys.getenv("r-keyring-test:donaldduck") #' #' # This is an error #' env$list() #' #' # Clean up #' env$delete("r-keyring-test", username = "donaldduck") #' } backend_env <- R6Class( "backend_env", inherit = backend, public = list( name = "env", get = function(service, username = NULL, keyring = NULL) b_env_get(self, private, service, username, keyring), set = function( service, username = NULL, keyring = NULL, prompt = "Password: " ) b_env_set(self, private, service, username, keyring, prompt), set_with_value = function( service, username = NULL, password = NULL, keyring = NULL ) b_env_set_with_value(self, private, service, username, password, keyring), delete = function(service, username = NULL, keyring = NULL) b_env_delete(self, private, service, username, keyring), list = function(service = NULL, keyring = NULL) b_env_list(self, private, service, keyring), docs = function() { modifyList( super$docs(), list( . = "Store secrets in environment variables." ) ) } ), private = list( env_to_var = function(service, username) { b_env_to_var(self, private, service, username) } ) ) warn_for_keyring <- function(keyring) { if (!is.null(keyring)) { warning( "The 'env' backend does not support multiple keyrings, ", "the 'keyring' argument is ignored" ) } } b_env_get <- function(self, private, service, username, keyring) { warn_for_keyring(keyring) username <- username %||% getOption("keyring_username") var <- private$env_to_var(service, username) res <- Sys.getenv(var, NA_character_) if (is.na(res)) stop("Cannot find password") res } b_env_set <- function(self, private, service, username, keyring, prompt) { warn_for_keyring(keyring) password <- get_pass(prompt) if (is.null(password)) stop("Aborted setting keyring key") username <- username %||% getOption("keyring_username") b_env_set_with_value( self, private, service, username, password, keyring = NULL ) invisible(self) } b_env_set_with_value <- function( self, private, service, username, password, keyring ) { warn_for_keyring(keyring) username <- username %||% getOption("keyring_username") var <- private$env_to_var(service, username) do.call(Sys.setenv, structure(list(password), names = var)) invisible(self) } b_env_delete <- function(self, private, service, username, keyring) { warn_for_keyring(keyring) username <- username %||% getOption("keyring_username") var <- private$env_to_var(service, username) Sys.unsetenv(var) invisible(self) } b_env_to_var <- function(self, private, service, username, keyring) { if (is.null(username)) { service } else { paste0(service, ":", username) } } b_env_list <- function(self, private, service, keyring) { if (is.null(service)) stop("'service' is required for 'env' backend.") keys <- gsub( paste(service, ":", sep = ""), "", Filter(function(e) str_starts_with(e, service), names(Sys.getenv())) ) data.frame( service = rep(service, length(keys)), username = keys, stringsAsFactors = FALSE ) } keyring/R/mocks.R0000644000176200001440000000011014675261103013357 0ustar liggesusers# Define these objects so they can be mocked in tests. Sys.info <- NULL keyring/R/backend-secret-service.R0000644000176200001440000001676415015040502016564 0ustar liggesusers#' Linux Secret Service keyring backend #' #' This backend is the default on Linux. It uses the libsecret library, #' and needs a secret service daemon running (e.g. Gnome Keyring, or #' KWallet). It uses DBUS to communicate with the secret service daemon. #' #' This backend supports multiple keyrings. #' #' See [backend] for the documentation of the individual methods. #' The `is_available()` method checks is a Secret Service daemon is #' running on the system, by trying to connect to it. It returns a logical #' scalar, or throws an error, depending on its argument: #' ``` #' is_available = function(report_error = FALSE) #' ``` #' #' Argument: #' * `report_error` Whether to throw an error if the Secret Service is #' not available. #' #' @family keyring backends #' @export #' @examples #' \dontrun{ #' ## This only works on Linux, typically desktop Linux #' kb <- backend_secret_service$new() #' kb$keyring_create("foobar") #' kb$set_default_keyring("foobar") #' kb$set_with_value("service", password = "secret") #' kb$get("service") #' kb$delete("service") #' kb$delete_keyring("foobar") #' } backend_secret_service <- R6Class( "backend_secret_service", inherit = backend_keyrings, public = list( name = "secret service", initialize = function(keyring = NULL) b_ss_init(self, private, keyring), get = function(service, username = NULL, keyring = NULL) b_ss_get(self, private, service, username, keyring), get_raw = function(service, username = NULL, keyring = NULL) b_ss_get_raw(self, private, service, username, keyring), set = function( service, username = NULL, keyring = NULL, prompt = "Password: " ) b_ss_set(self, private, service, username, keyring, prompt), set_with_value = function( service, username = NULL, password = NULL, keyring = NULL ) b_ss_set_with_value(self, private, service, username, password, keyring), set_with_raw_value = function( service, username = NULL, password = NULL, keyring = NULL ) b_ss_set_with_raw_value( self, private, service, username, password, keyring ), delete = function(service, username = NULL, keyring = NULL) b_ss_delete(self, private, service, username, keyring), list = function(service = NULL, keyring = NULL) b_ss_list(self, private, service, keyring), keyring_create = function(keyring, password = NULL) b_ss_keyring_create(self, private, keyring, password), keyring_list = function() b_ss_keyring_list(self, private), keyring_delete = function(keyring = NULL) b_ss_keyring_delete(self, private, keyring), keyring_lock = function(keyring = NULL) b_ss_keyring_lock(self, private, keyring), keyring_unlock = function(keyring = NULL, password = NULL) b_ss_keyring_unlock(self, private, keyring, password), keyring_is_locked = function(keyring = NULL) b_ss_keyring_is_locked(self, private, keyring), keyring_default = function() b_ss_keyring_default(self, private), keyring_set_default = function(keyring = NULL) b_ss_keyring_set_default(self, private, keyring), is_available = function(report_error = FALSE) b_ss_is_available(self, private, report_error), docs = function() { modifyList( super$docs(), list( . = "Store secrets using the Secret Service library and daemon.", is_available = "check is Secret Service is available" ) ) } ), private = list( keyring = NULL, keyring_create_direct = function(keyring, password = NULL) b_ss_keyring_create_direct(self, private, keyring, password) ) ) b_ss_init <- function(self, private, keyring) { private$keyring <- keyring invisible(self) } b_ss_get <- function(self, private, service, username, keyring) { res <- b_ss_get_raw(self, private, service, username, keyring) if (any(res == 0)) { stop("Key contains embedded null bytes, use get_raw()") } rawToChar(res) } b_ss_get_raw <- function(self, private, service, username, keyring) { username <- username %||% getOption("keyring_username") keyring <- keyring %||% private$keyring res <- .Call(keyring_secret_service_get, keyring, service, username) res } b_ss_set <- function(self, private, service, username, keyring, prompt) { username <- username %||% getOption("keyring_username") password <- get_pass(prompt) if (is.null(password)) stop("Aborted setting keyring key") b_ss_set_with_value(self, private, service, username, password, keyring) invisible(self) } b_ss_set_with_value <- function( self, private, service, username, password, keyring ) { username <- username %||% getOption("keyring_username") keyring <- keyring %||% private$keyring .Call( keyring_secret_service_set, keyring, service, username, charToRaw(password) ) invisible(self) } b_ss_set_with_raw_value <- function( self, private, service, username, password, keyring ) { username <- username %||% getOption("keyring_username") keyring <- keyring %||% private$keyring .Call(keyring_secret_service_set, keyring, service, username, password) invisible(self) } b_ss_delete <- function(self, private, service, username, keyring) { username <- username %||% getOption("keyring_username") keyring <- keyring %||% private$keyring .Call(keyring_secret_service_delete, keyring, service, username) invisible(self) } b_ss_list <- function(self, private, service, keyring) { keyring <- keyring %||% private$keyring res <- .Call(keyring_secret_service_list, keyring, service) data.frame( service = res[[1]], username = res[[2]], stringsAsFactors = FALSE ) } b_ss_keyring_create <- function(self, private, keyring, password) { password <- password %||% get_pass() if (is.null(password)) stop("Aborted creating keyring") private$keyring_create_direct(keyring, password) invisible(self) } b_ss_keyring_list <- function(self, private) { res <- .Call(keyring_secret_service_list_keyring) data.frame( keyring = res[[1]], num_secrets = res[[2]], locked = res[[3]], stringsAsFactors = FALSE ) } b_ss_keyring_delete <- function(self, private, keyring) { self$confirm_delete_keyring(keyring) keyring <- keyring %||% private$keyring .Call(keyring_secret_service_delete_keyring, keyring) invisible() } b_ss_keyring_lock <- function(self, private, keyring) { keyring <- keyring %||% private$keyring .Call(keyring_secret_service_lock_keyring, keyring) invisible() } b_ss_keyring_unlock <- function(self, private, keyring, password) { keyring <- keyring %||% private$keyring if (!is.null(password)) warning("password ignored, will be read interactively") .Call(keyring_secret_service_unlock_keyring, keyring, password) invisible() } b_ss_keyring_is_locked <- function(self, private, keyring) { keyring <- keyring %||% private$keyring .Call(keyring_secret_service_is_locked_keyring, keyring) } b_ss_keyring_default <- function(self, private) { private$keyring } b_ss_keyring_set_default <- function(self, private, keyring) { private$keyring <- keyring invisible(self) } b_ss_is_available <- function(self, private, report_error) { .Call(keyring_secret_service_is_available, report_error) } b_ss_keyring_create_direct <- function(self, private, keyring, password) { if (!is.null(password)) { warning("Password ignored, will be read interactively") } keyring <- keyring %||% private$keyring .Call(keyring_secret_service_create_keyring, keyring) invisible(self) } keyring/cleanup0000755000176200001440000000004615023625503013300 0ustar liggesusers#!/usr/bin/env sh rm -f src/Makevars keyring/src/0000755000176200001440000000000015023625503012512 5ustar liggesuserskeyring/src/padlock.h0000644000176200001440000000633515006370264014311 0ustar liggesusers/** * \file padlock.h * * \brief VIA PadLock ACE for HW encryption/decryption supported by some * processors * * \warning These functions are only for internal use by other library * functions; you must not call them directly. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_PADLOCK_H #define MBEDTLS_PADLOCK_H #include "mbedtls/build_info.h" #include "mbedtls/aes.h" #define MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED -0x0030 /**< Input data should be aligned. */ #if defined(__has_feature) #if __has_feature(address_sanitizer) #define MBEDTLS_HAVE_ASAN #endif #endif /* * - `padlock` is implements with GNUC assembly for x86 target. * - Some versions of ASan result in errors about not enough registers. */ #if defined(MBEDTLS_PADLOCK_C) && \ defined(__GNUC__) && defined(MBEDTLS_ARCH_IS_X86) && \ defined(MBEDTLS_HAVE_ASM) && \ !defined(MBEDTLS_HAVE_ASAN) #define MBEDTLS_VIA_PADLOCK_HAVE_CODE #include #define MBEDTLS_PADLOCK_RNG 0x000C #define MBEDTLS_PADLOCK_ACE 0x00C0 #define MBEDTLS_PADLOCK_PHE 0x0C00 #define MBEDTLS_PADLOCK_PMM 0x3000 #define MBEDTLS_PADLOCK_ALIGN16(x) (uint32_t *) (16 + ((int32_t) (x) & ~15)) #ifdef __cplusplus extern "C" { #endif /** * \brief Internal PadLock detection routine * * \note This function is only for internal use by other library * functions; you must not call it directly. * * \param feature The feature to detect * * \return non-zero if CPU has support for the feature, 0 otherwise */ int mbedtls_padlock_has_support(int feature); /** * \brief Internal PadLock AES-ECB block en(de)cryption * * \note This function is only for internal use by other library * functions; you must not call it directly. * * \param ctx AES context * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT * \param input 16-byte input block * \param output 16-byte output block * * \return 0 if success, 1 if operation failed */ int mbedtls_padlock_xcryptecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]); /** * \brief Internal PadLock AES-CBC buffer en(de)cryption * * \note This function is only for internal use by other library * functions; you must not call it directly. * * \param ctx AES context * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT * \param length length of the input data * \param iv initialization vector (updated after use) * \param input buffer holding the input data * \param output buffer holding the output data * * \return 0 if success, 1 if operation failed */ int mbedtls_padlock_xcryptcbc(mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output); #ifdef __cplusplus } #endif #endif /* HAVE_X86 */ #endif /* padlock.h */ keyring/src/onetimeauth_poly1305.h0000644000176200001440000000177014775227066016605 0ustar liggesusers #ifndef onetimeauth_poly1305_H #define onetimeauth_poly1305_H #include "crypto_onetimeauth_poly1305.h" typedef struct crypto_onetimeauth_poly1305_implementation { int (*onetimeauth)(unsigned char *out, const unsigned char *in, unsigned long long inlen, const unsigned char *k); int (*onetimeauth_verify)(const unsigned char *h, const unsigned char *in, unsigned long long inlen, const unsigned char *k); int (*onetimeauth_init)(crypto_onetimeauth_poly1305_state *state, const unsigned char * key); int (*onetimeauth_update)(crypto_onetimeauth_poly1305_state *state, const unsigned char * in, unsigned long long inlen); int (*onetimeauth_final)(crypto_onetimeauth_poly1305_state *state, unsigned char * out); } crypto_onetimeauth_poly1305_implementation; #endif keyring/src/crypto_core_hsalsa20.h0000644000176200001440000000144414775227066016732 0ustar liggesusers#ifndef crypto_core_hsalsa20_H #define crypto_core_hsalsa20_H #include #include "sodium.h" #ifdef __cplusplus extern "C" { #endif #define crypto_core_hsalsa20_OUTPUTBYTES 32U SODIUM_EXPORT size_t crypto_core_hsalsa20_outputbytes(void); #define crypto_core_hsalsa20_INPUTBYTES 16U SODIUM_EXPORT size_t crypto_core_hsalsa20_inputbytes(void); #define crypto_core_hsalsa20_KEYBYTES 32U SODIUM_EXPORT size_t crypto_core_hsalsa20_keybytes(void); #define crypto_core_hsalsa20_CONSTBYTES 16U SODIUM_EXPORT size_t crypto_core_hsalsa20_constbytes(void); SODIUM_EXPORT int crypto_core_hsalsa20(unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c) __attribute__ ((nonnull(1, 2, 3))); #ifdef __cplusplus } #endif #endif keyring/src/stream_salsa20.h0000644000176200001440000000102414775227066015517 0ustar liggesusers #ifndef stream_salsa20_H #define stream_salsa20_H #include typedef struct crypto_stream_salsa20_implementation { int (*stream)(unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k); int (*stream_xor_ic)(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, uint64_t ic, const unsigned char *k); } crypto_stream_salsa20_implementation; #endif keyring/src/crypto_verify_32.h0000644000176200001440000000064314775227066016115 0ustar liggesusers#ifndef crypto_verify_32_H #define crypto_verify_32_H #include #include "sodium.h" #ifdef __cplusplus extern "C" { #endif #define crypto_verify_32_BYTES 32U SODIUM_EXPORT size_t crypto_verify_32_bytes(void); SODIUM_EXPORT int crypto_verify_32(const unsigned char *x, const unsigned char *y) __attribute__ ((warn_unused_result)) __attribute__ ((nonnull)); #ifdef __cplusplus } #endif #endif keyring/src/endianness.h0000644000176200001440000000221614775227066015032 0ustar liggesusers#ifndef ENDIANNESS_H #define ENDIANNESS_H /** * We want to check that it is actually a little endian system at * compile-time. */ #if defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) #define IS_BIG_ENDIAN (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) #elif defined(_WIN32) #define IS_BIG_ENDIAN 0 #else #if defined(__APPLE__) || defined(__FreeBSD__) // defined __BYTE_ORDER__ && defined __ORDER_BIG_ENDIAN__ #include #elif defined(sun) || defined(__sun) // defined(__APPLE__) || defined(__FreeBSD__) #include #else // defined(__APPLE__) || defined(__FreeBSD__) #ifdef __has_include #if __has_include() #include #endif //__has_include() #endif //__has_include #endif // defined(__APPLE__) || defined(__FreeBSD__) #ifndef !defined(__BYTE_ORDER__) || !defined(__ORDER_LITTLE_ENDIAN__) #define IS_BIG_ENDIAN 0 #endif #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #define IS_BIG_ENDIAN 0 #else // __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #define IS_BIG_ENDIAN 1 #endif // __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #endif // defined __BYTE_ORDER__ && defined __ORDER_BIG_ENDIAN__ #endif keyring/src/crypto_verify_64.h0000644000176200001440000000064314775227066016122 0ustar liggesusers#ifndef crypto_verify_64_H #define crypto_verify_64_H #include #include "sodium.h" #ifdef __cplusplus extern "C" { #endif #define crypto_verify_64_BYTES 64U SODIUM_EXPORT size_t crypto_verify_64_bytes(void); SODIUM_EXPORT int crypto_verify_64(const unsigned char *x, const unsigned char *y) __attribute__ ((warn_unused_result)) __attribute__ ((nonnull)); #ifdef __cplusplus } #endif #endif keyring/src/onetimeauth_poly1305.c0000644000176200001440000000450014775227066016572 0ustar liggesusers #include "onetimeauth_poly1305.h" #include "crypto_onetimeauth_poly1305.h" #include "sodium.h" #include "poly1305_donna.h" #if defined(HAVE_TI_MODE) && defined(HAVE_EMMINTRIN_H) # include "sse2/poly1305_sse2.h" #endif static const crypto_onetimeauth_poly1305_implementation *implementation = &crypto_onetimeauth_poly1305_donna_implementation; int crypto_onetimeauth_poly1305(unsigned char *out, const unsigned char *in, unsigned long long inlen, const unsigned char *k) { return implementation->onetimeauth(out, in, inlen, k); } int crypto_onetimeauth_poly1305_verify(const unsigned char *h, const unsigned char *in, unsigned long long inlen, const unsigned char *k) { return implementation->onetimeauth_verify(h, in, inlen, k); } int crypto_onetimeauth_poly1305_init(crypto_onetimeauth_poly1305_state *state, const unsigned char *key) { return implementation->onetimeauth_init(state, key); } int crypto_onetimeauth_poly1305_update(crypto_onetimeauth_poly1305_state *state, const unsigned char *in, unsigned long long inlen) { return implementation->onetimeauth_update(state, in, inlen); } int crypto_onetimeauth_poly1305_final(crypto_onetimeauth_poly1305_state *state, unsigned char *out) { return implementation->onetimeauth_final(state, out); } size_t crypto_onetimeauth_poly1305_bytes(void) { return crypto_onetimeauth_poly1305_BYTES; } size_t crypto_onetimeauth_poly1305_keybytes(void) { return crypto_onetimeauth_poly1305_KEYBYTES; } size_t crypto_onetimeauth_poly1305_statebytes(void) { return sizeof(crypto_onetimeauth_poly1305_state); } void crypto_onetimeauth_poly1305_keygen( unsigned char k[crypto_onetimeauth_poly1305_KEYBYTES]) { randombytes_buf(k, crypto_onetimeauth_poly1305_KEYBYTES); } int _crypto_onetimeauth_poly1305_pick_best_implementation(void) { implementation = &crypto_onetimeauth_poly1305_donna_implementation; #if defined(HAVE_TI_MODE) && defined(HAVE_EMMINTRIN_H) if (sodium_runtime_has_sse2()) { implementation = &crypto_onetimeauth_poly1305_sse2_implementation; } #endif return 0; } keyring/src/crypto_secretbox_xsalsa20poly1305.h0000644000176200001440000000453714775227066021243 0ustar liggesusers#ifndef crypto_secretbox_xsalsa20poly1305_H #define crypto_secretbox_xsalsa20poly1305_H #include #include "crypto_stream_xsalsa20.h" #ifdef __cplusplus # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wlong-long" # endif extern "C" { #endif #define crypto_secretbox_xsalsa20poly1305_KEYBYTES 32U SODIUM_EXPORT size_t crypto_secretbox_xsalsa20poly1305_keybytes(void); #define crypto_secretbox_xsalsa20poly1305_NONCEBYTES 24U SODIUM_EXPORT size_t crypto_secretbox_xsalsa20poly1305_noncebytes(void); #define crypto_secretbox_xsalsa20poly1305_MACBYTES 16U SODIUM_EXPORT size_t crypto_secretbox_xsalsa20poly1305_macbytes(void); /* Only for the libsodium API - The NaCl compatibility API would require BOXZEROBYTES extra bytes */ #define crypto_secretbox_xsalsa20poly1305_MESSAGEBYTES_MAX \ (crypto_stream_xsalsa20_MESSAGEBYTES_MAX - crypto_secretbox_xsalsa20poly1305_MACBYTES) SODIUM_EXPORT size_t crypto_secretbox_xsalsa20poly1305_messagebytes_max(void); SODIUM_EXPORT int crypto_secretbox_xsalsa20poly1305(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, const unsigned char *k) __attribute__ ((nonnull(1, 4, 5))); SODIUM_EXPORT int crypto_secretbox_xsalsa20poly1305_open(unsigned char *m, const unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) __attribute__ ((warn_unused_result)) __attribute__ ((nonnull(2, 4, 5))); SODIUM_EXPORT void crypto_secretbox_xsalsa20poly1305_keygen(unsigned char k[crypto_secretbox_xsalsa20poly1305_KEYBYTES]) __attribute__ ((nonnull)); /* -- NaCl compatibility interface ; Requires padding -- */ #define crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES 16U SODIUM_EXPORT size_t crypto_secretbox_xsalsa20poly1305_boxzerobytes(void); #define crypto_secretbox_xsalsa20poly1305_ZEROBYTES \ (crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES + \ crypto_secretbox_xsalsa20poly1305_MACBYTES) SODIUM_EXPORT size_t crypto_secretbox_xsalsa20poly1305_zerobytes(void); #ifdef __cplusplus } #endif #endif keyring/src/aesni.c0000644000176200001440000010030215006370264013753 0ustar liggesusers/* * AES-NI support functions * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ /* * [AES-WP] https://www.intel.com/content/www/us/en/developer/articles/tool/intel-advanced-encryption-standard-aes-instructions-set.html * [CLMUL-WP] https://www.intel.com/content/www/us/en/develop/download/intel-carry-less-multiplication-instruction-and-its-usage-for-computing-the-gcm-mode.html */ #include "common.h" #if defined(MBEDTLS_AESNI_C) #include "aesni.h" #include #if defined(MBEDTLS_AESNI_HAVE_CODE) #if MBEDTLS_AESNI_HAVE_CODE == 2 #if defined(__GNUC__) #include #elif defined(_MSC_VER) #include #else #error "`__cpuid` required by MBEDTLS_AESNI_C is not supported by the compiler" #endif #include #endif #if defined(MBEDTLS_ARCH_IS_X86) #if defined(MBEDTLS_COMPILER_IS_GCC) #pragma GCC push_options #pragma GCC target ("pclmul,sse2,aes") #define MBEDTLS_POP_TARGET_PRAGMA #elif defined(__clang__) && (__clang_major__ >= 5) #pragma clang attribute push (__attribute__((target("pclmul,sse2,aes"))), apply_to=function) #define MBEDTLS_POP_TARGET_PRAGMA #endif #endif #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) /* * AES-NI support detection routine */ int mbedtls_aesni_has_support(unsigned int what) { static int done = 0; static unsigned int c = 0; if (!done) { #if MBEDTLS_AESNI_HAVE_CODE == 2 static int info[4] = { 0, 0, 0, 0 }; #if defined(_MSC_VER) __cpuid(info, 1); #else __cpuid(1, info[0], info[1], info[2], info[3]); #endif c = info[2]; #else /* AESNI using asm */ asm ("movl $1, %%eax \n\t" "cpuid \n\t" : "=c" (c) : : "eax", "ebx", "edx"); #endif /* MBEDTLS_AESNI_HAVE_CODE */ done = 1; } return (c & what) != 0; } #endif /* !MBEDTLS_AES_USE_HARDWARE_ONLY */ #if MBEDTLS_AESNI_HAVE_CODE == 2 /* * AES-NI AES-ECB block en(de)cryption */ int mbedtls_aesni_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]) { const __m128i *rk = (const __m128i *) (ctx->buf + ctx->rk_offset); unsigned nr = ctx->nr; // Number of remaining rounds // Load round key 0 __m128i state; memcpy(&state, input, 16); state = _mm_xor_si128(state, rk[0]); // state ^= *rk; ++rk; --nr; #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) if (mode == MBEDTLS_AES_DECRYPT) { while (nr != 0) { state = _mm_aesdec_si128(state, *rk); ++rk; --nr; } state = _mm_aesdeclast_si128(state, *rk); } else #else (void) mode; #endif { while (nr != 0) { state = _mm_aesenc_si128(state, *rk); ++rk; --nr; } state = _mm_aesenclast_si128(state, *rk); } memcpy(output, &state, 16); return 0; } /* * GCM multiplication: c = a times b in GF(2^128) * Based on [CLMUL-WP] algorithms 1 (with equation 27) and 5. */ static void gcm_clmul(const __m128i aa, const __m128i bb, __m128i *cc, __m128i *dd) { /* * Caryless multiplication dd:cc = aa * bb * using [CLMUL-WP] algorithm 1 (p. 12). */ *cc = _mm_clmulepi64_si128(aa, bb, 0x00); // a0*b0 = c1:c0 *dd = _mm_clmulepi64_si128(aa, bb, 0x11); // a1*b1 = d1:d0 __m128i ee = _mm_clmulepi64_si128(aa, bb, 0x10); // a0*b1 = e1:e0 __m128i ff = _mm_clmulepi64_si128(aa, bb, 0x01); // a1*b0 = f1:f0 ff = _mm_xor_si128(ff, ee); // e1+f1:e0+f0 ee = ff; // e1+f1:e0+f0 ff = _mm_srli_si128(ff, 8); // 0:e1+f1 ee = _mm_slli_si128(ee, 8); // e0+f0:0 *dd = _mm_xor_si128(*dd, ff); // d1:d0+e1+f1 *cc = _mm_xor_si128(*cc, ee); // c1+e0+f0:c0 } static void gcm_shift(__m128i *cc, __m128i *dd) { /* [CMUCL-WP] Algorithm 5 Step 1: shift cc:dd one bit to the left, * taking advantage of [CLMUL-WP] eq 27 (p. 18). */ // // *cc = r1:r0 // // *dd = r3:r2 __m128i cc_lo = _mm_slli_epi64(*cc, 1); // r1<<1:r0<<1 __m128i dd_lo = _mm_slli_epi64(*dd, 1); // r3<<1:r2<<1 __m128i cc_hi = _mm_srli_epi64(*cc, 63); // r1>>63:r0>>63 __m128i dd_hi = _mm_srli_epi64(*dd, 63); // r3>>63:r2>>63 __m128i xmm5 = _mm_srli_si128(cc_hi, 8); // 0:r1>>63 cc_hi = _mm_slli_si128(cc_hi, 8); // r0>>63:0 dd_hi = _mm_slli_si128(dd_hi, 8); // 0:r1>>63 *cc = _mm_or_si128(cc_lo, cc_hi); // r1<<1|r0>>63:r0<<1 *dd = _mm_or_si128(_mm_or_si128(dd_lo, dd_hi), xmm5); // r3<<1|r2>>62:r2<<1|r1>>63 } static __m128i gcm_reduce(__m128i xx) { // // xx = x1:x0 /* [CLMUL-WP] Algorithm 5 Step 2 */ __m128i aa = _mm_slli_epi64(xx, 63); // x1<<63:x0<<63 = stuff:a __m128i bb = _mm_slli_epi64(xx, 62); // x1<<62:x0<<62 = stuff:b __m128i cc = _mm_slli_epi64(xx, 57); // x1<<57:x0<<57 = stuff:c __m128i dd = _mm_slli_si128(_mm_xor_si128(_mm_xor_si128(aa, bb), cc), 8); // a+b+c:0 return _mm_xor_si128(dd, xx); // x1+a+b+c:x0 = d:x0 } static __m128i gcm_mix(__m128i dx) { /* [CLMUL-WP] Algorithm 5 Steps 3 and 4 */ __m128i ee = _mm_srli_epi64(dx, 1); // e1:x0>>1 = e1:e0' __m128i ff = _mm_srli_epi64(dx, 2); // f1:x0>>2 = f1:f0' __m128i gg = _mm_srli_epi64(dx, 7); // g1:x0>>7 = g1:g0' // e0'+f0'+g0' is almost e0+f0+g0, except for some missing // bits carried from d. Now get those bits back in. __m128i eh = _mm_slli_epi64(dx, 63); // d<<63:stuff __m128i fh = _mm_slli_epi64(dx, 62); // d<<62:stuff __m128i gh = _mm_slli_epi64(dx, 57); // d<<57:stuff __m128i hh = _mm_srli_si128(_mm_xor_si128(_mm_xor_si128(eh, fh), gh), 8); // 0:missing bits of d return _mm_xor_si128(_mm_xor_si128(_mm_xor_si128(_mm_xor_si128(ee, ff), gg), hh), dx); } void mbedtls_aesni_gcm_mult(unsigned char c[16], const unsigned char a[16], const unsigned char b[16]) { __m128i aa = { 0 }, bb = { 0 }, cc, dd; /* The inputs are in big-endian order, so byte-reverse them */ for (size_t i = 0; i < 16; i++) { ((uint8_t *) &aa)[i] = a[15 - i]; ((uint8_t *) &bb)[i] = b[15 - i]; } gcm_clmul(aa, bb, &cc, &dd); gcm_shift(&cc, &dd); /* * Now reduce modulo the GCM polynomial x^128 + x^7 + x^2 + x + 1 * using [CLMUL-WP] algorithm 5 (p. 18). * Currently dd:cc holds x3:x2:x1:x0 (already shifted). */ __m128i dx = gcm_reduce(cc); __m128i xh = gcm_mix(dx); cc = _mm_xor_si128(xh, dd); // x3+h1:x2+h0 /* Now byte-reverse the outputs */ for (size_t i = 0; i < 16; i++) { c[i] = ((uint8_t *) &cc)[15 - i]; } return; } /* * Compute decryption round keys from encryption round keys */ #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) void mbedtls_aesni_inverse_key(unsigned char *invkey, const unsigned char *fwdkey, int nr) { __m128i *ik = (__m128i *) invkey; const __m128i *fk = (const __m128i *) fwdkey + nr; *ik = *fk; for (--fk, ++ik; fk > (const __m128i *) fwdkey; --fk, ++ik) { *ik = _mm_aesimc_si128(*fk); } *ik = *fk; } #endif /* * Key expansion, 128-bit case */ static __m128i aesni_set_rk_128(__m128i state, __m128i xword) { /* * Finish generating the next round key. * * On entry state is r3:r2:r1:r0 and xword is X:stuff:stuff:stuff * with X = rot( sub( r3 ) ) ^ RCON (obtained with AESKEYGENASSIST). * * On exit, xword is r7:r6:r5:r4 * with r4 = X + r0, r5 = r4 + r1, r6 = r5 + r2, r7 = r6 + r3 * and this is returned, to be written to the round key buffer. */ xword = _mm_shuffle_epi32(xword, 0xff); // X:X:X:X xword = _mm_xor_si128(xword, state); // X+r3:X+r2:X+r1:r4 state = _mm_slli_si128(state, 4); // r2:r1:r0:0 xword = _mm_xor_si128(xword, state); // X+r3+r2:X+r2+r1:r5:r4 state = _mm_slli_si128(state, 4); // r1:r0:0:0 xword = _mm_xor_si128(xword, state); // X+r3+r2+r1:r6:r5:r4 state = _mm_slli_si128(state, 4); // r0:0:0:0 state = _mm_xor_si128(xword, state); // r7:r6:r5:r4 return state; } static void aesni_setkey_enc_128(unsigned char *rk_bytes, const unsigned char *key) { __m128i *rk = (__m128i *) rk_bytes; memcpy(&rk[0], key, 16); rk[1] = aesni_set_rk_128(rk[0], _mm_aeskeygenassist_si128(rk[0], 0x01)); rk[2] = aesni_set_rk_128(rk[1], _mm_aeskeygenassist_si128(rk[1], 0x02)); rk[3] = aesni_set_rk_128(rk[2], _mm_aeskeygenassist_si128(rk[2], 0x04)); rk[4] = aesni_set_rk_128(rk[3], _mm_aeskeygenassist_si128(rk[3], 0x08)); rk[5] = aesni_set_rk_128(rk[4], _mm_aeskeygenassist_si128(rk[4], 0x10)); rk[6] = aesni_set_rk_128(rk[5], _mm_aeskeygenassist_si128(rk[5], 0x20)); rk[7] = aesni_set_rk_128(rk[6], _mm_aeskeygenassist_si128(rk[6], 0x40)); rk[8] = aesni_set_rk_128(rk[7], _mm_aeskeygenassist_si128(rk[7], 0x80)); rk[9] = aesni_set_rk_128(rk[8], _mm_aeskeygenassist_si128(rk[8], 0x1B)); rk[10] = aesni_set_rk_128(rk[9], _mm_aeskeygenassist_si128(rk[9], 0x36)); } /* * Key expansion, 192-bit case */ #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) static void aesni_set_rk_192(__m128i *state0, __m128i *state1, __m128i xword, unsigned char *rk) { /* * Finish generating the next 6 quarter-keys. * * On entry state0 is r3:r2:r1:r0, state1 is stuff:stuff:r5:r4 * and xword is stuff:stuff:X:stuff with X = rot( sub( r3 ) ) ^ RCON * (obtained with AESKEYGENASSIST). * * On exit, state0 is r9:r8:r7:r6 and state1 is stuff:stuff:r11:r10 * and those are written to the round key buffer. */ xword = _mm_shuffle_epi32(xword, 0x55); // X:X:X:X xword = _mm_xor_si128(xword, *state0); // X+r3:X+r2:X+r1:X+r0 *state0 = _mm_slli_si128(*state0, 4); // r2:r1:r0:0 xword = _mm_xor_si128(xword, *state0); // X+r3+r2:X+r2+r1:X+r1+r0:X+r0 *state0 = _mm_slli_si128(*state0, 4); // r1:r0:0:0 xword = _mm_xor_si128(xword, *state0); // X+r3+r2+r1:X+r2+r1+r0:X+r1+r0:X+r0 *state0 = _mm_slli_si128(*state0, 4); // r0:0:0:0 xword = _mm_xor_si128(xword, *state0); // X+r3+r2+r1+r0:X+r2+r1+r0:X+r1+r0:X+r0 *state0 = xword; // = r9:r8:r7:r6 xword = _mm_shuffle_epi32(xword, 0xff); // r9:r9:r9:r9 xword = _mm_xor_si128(xword, *state1); // stuff:stuff:r9+r5:r9+r4 *state1 = _mm_slli_si128(*state1, 4); // stuff:stuff:r4:0 xword = _mm_xor_si128(xword, *state1); // stuff:stuff:r9+r5+r4:r9+r4 *state1 = xword; // = stuff:stuff:r11:r10 /* Store state0 and the low half of state1 into rk, which is conceptually * an array of 24-byte elements. Since 24 is not a multiple of 16, * rk is not necessarily aligned so just `*rk = *state0` doesn't work. */ memcpy(rk, state0, 16); memcpy(rk + 16, state1, 8); } static void aesni_setkey_enc_192(unsigned char *rk, const unsigned char *key) { /* First round: use original key */ memcpy(rk, key, 24); /* aes.c guarantees that rk is aligned on a 16-byte boundary. */ __m128i state0 = ((__m128i *) rk)[0]; __m128i state1 = _mm_loadl_epi64(((__m128i *) rk) + 1); aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x01), rk + 24 * 1); aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x02), rk + 24 * 2); aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x04), rk + 24 * 3); aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x08), rk + 24 * 4); aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x10), rk + 24 * 5); aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x20), rk + 24 * 6); aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x40), rk + 24 * 7); aesni_set_rk_192(&state0, &state1, _mm_aeskeygenassist_si128(state1, 0x80), rk + 24 * 8); } #endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */ /* * Key expansion, 256-bit case */ #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) static void aesni_set_rk_256(__m128i state0, __m128i state1, __m128i xword, __m128i *rk0, __m128i *rk1) { /* * Finish generating the next two round keys. * * On entry state0 is r3:r2:r1:r0, state1 is r7:r6:r5:r4 and * xword is X:stuff:stuff:stuff with X = rot( sub( r7 )) ^ RCON * (obtained with AESKEYGENASSIST). * * On exit, *rk0 is r11:r10:r9:r8 and *rk1 is r15:r14:r13:r12 */ xword = _mm_shuffle_epi32(xword, 0xff); xword = _mm_xor_si128(xword, state0); state0 = _mm_slli_si128(state0, 4); xword = _mm_xor_si128(xword, state0); state0 = _mm_slli_si128(state0, 4); xword = _mm_xor_si128(xword, state0); state0 = _mm_slli_si128(state0, 4); state0 = _mm_xor_si128(state0, xword); *rk0 = state0; /* Set xword to stuff:Y:stuff:stuff with Y = subword( r11 ) * and proceed to generate next round key from there */ xword = _mm_aeskeygenassist_si128(state0, 0x00); xword = _mm_shuffle_epi32(xword, 0xaa); xword = _mm_xor_si128(xword, state1); state1 = _mm_slli_si128(state1, 4); xword = _mm_xor_si128(xword, state1); state1 = _mm_slli_si128(state1, 4); xword = _mm_xor_si128(xword, state1); state1 = _mm_slli_si128(state1, 4); state1 = _mm_xor_si128(state1, xword); *rk1 = state1; } static void aesni_setkey_enc_256(unsigned char *rk_bytes, const unsigned char *key) { __m128i *rk = (__m128i *) rk_bytes; memcpy(&rk[0], key, 16); memcpy(&rk[1], key + 16, 16); /* * Main "loop" - Generating one more key than necessary, * see definition of mbedtls_aes_context.buf */ aesni_set_rk_256(rk[0], rk[1], _mm_aeskeygenassist_si128(rk[1], 0x01), &rk[2], &rk[3]); aesni_set_rk_256(rk[2], rk[3], _mm_aeskeygenassist_si128(rk[3], 0x02), &rk[4], &rk[5]); aesni_set_rk_256(rk[4], rk[5], _mm_aeskeygenassist_si128(rk[5], 0x04), &rk[6], &rk[7]); aesni_set_rk_256(rk[6], rk[7], _mm_aeskeygenassist_si128(rk[7], 0x08), &rk[8], &rk[9]); aesni_set_rk_256(rk[8], rk[9], _mm_aeskeygenassist_si128(rk[9], 0x10), &rk[10], &rk[11]); aesni_set_rk_256(rk[10], rk[11], _mm_aeskeygenassist_si128(rk[11], 0x20), &rk[12], &rk[13]); aesni_set_rk_256(rk[12], rk[13], _mm_aeskeygenassist_si128(rk[13], 0x40), &rk[14], &rk[15]); } #endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */ #if defined(MBEDTLS_POP_TARGET_PRAGMA) #if defined(__clang__) #pragma clang attribute pop #elif defined(__GNUC__) #pragma GCC pop_options #endif #undef MBEDTLS_POP_TARGET_PRAGMA #endif #else /* MBEDTLS_AESNI_HAVE_CODE == 1 */ #if defined(__has_feature) #if __has_feature(memory_sanitizer) #warning \ "MBEDTLS_AESNI_C is known to cause spurious error reports with some memory sanitizers as they do not understand the assembly code." #endif #endif /* * Binutils needs to be at least 2.19 to support AES-NI instructions. * Unfortunately, a lot of users have a lower version now (2014-04). * Emit bytecode directly in order to support "old" version of gas. * * Opcodes from the Intel architecture reference manual, vol. 3. * We always use registers, so we don't need prefixes for memory operands. * Operand macros are in gas order (src, dst) as opposed to Intel order * (dst, src) in order to blend better into the surrounding assembly code. */ #define AESDEC(regs) ".byte 0x66,0x0F,0x38,0xDE," regs "\n\t" #define AESDECLAST(regs) ".byte 0x66,0x0F,0x38,0xDF," regs "\n\t" #define AESENC(regs) ".byte 0x66,0x0F,0x38,0xDC," regs "\n\t" #define AESENCLAST(regs) ".byte 0x66,0x0F,0x38,0xDD," regs "\n\t" #define AESIMC(regs) ".byte 0x66,0x0F,0x38,0xDB," regs "\n\t" #define AESKEYGENA(regs, imm) ".byte 0x66,0x0F,0x3A,0xDF," regs "," imm "\n\t" #define PCLMULQDQ(regs, imm) ".byte 0x66,0x0F,0x3A,0x44," regs "," imm "\n\t" #define xmm0_xmm0 "0xC0" #define xmm0_xmm1 "0xC8" #define xmm0_xmm2 "0xD0" #define xmm0_xmm3 "0xD8" #define xmm0_xmm4 "0xE0" #define xmm1_xmm0 "0xC1" #define xmm1_xmm2 "0xD1" /* * AES-NI AES-ECB block en(de)cryption */ int mbedtls_aesni_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]) { asm ("movdqu (%3), %%xmm0 \n\t" // load input "movdqu (%1), %%xmm1 \n\t" // load round key 0 "pxor %%xmm1, %%xmm0 \n\t" // round 0 "add $16, %1 \n\t" // point to next round key "subl $1, %0 \n\t" // normal rounds = nr - 1 "test %2, %2 \n\t" // mode? "jz 2f \n\t" // 0 = decrypt "1: \n\t" // encryption loop "movdqu (%1), %%xmm1 \n\t" // load round key AESENC(xmm1_xmm0) // do round "add $16, %1 \n\t" // point to next round key "subl $1, %0 \n\t" // loop "jnz 1b \n\t" "movdqu (%1), %%xmm1 \n\t" // load round key AESENCLAST(xmm1_xmm0) // last round #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) "jmp 3f \n\t" "2: \n\t" // decryption loop "movdqu (%1), %%xmm1 \n\t" AESDEC(xmm1_xmm0) // do round "add $16, %1 \n\t" "subl $1, %0 \n\t" "jnz 2b \n\t" "movdqu (%1), %%xmm1 \n\t" // load round key AESDECLAST(xmm1_xmm0) // last round #endif "3: \n\t" "movdqu %%xmm0, (%4) \n\t" // export output : : "r" (ctx->nr), "r" (ctx->buf + ctx->rk_offset), "r" (mode), "r" (input), "r" (output) : "memory", "cc", "xmm0", "xmm1", "0", "1"); return 0; } /* * GCM multiplication: c = a times b in GF(2^128) * Based on [CLMUL-WP] algorithms 1 (with equation 27) and 5. */ void mbedtls_aesni_gcm_mult(unsigned char c[16], const unsigned char a[16], const unsigned char b[16]) { unsigned char aa[16], bb[16], cc[16]; size_t i; /* The inputs are in big-endian order, so byte-reverse them */ for (i = 0; i < 16; i++) { aa[i] = a[15 - i]; bb[i] = b[15 - i]; } asm ("movdqu (%0), %%xmm0 \n\t" // a1:a0 "movdqu (%1), %%xmm1 \n\t" // b1:b0 /* * Caryless multiplication xmm2:xmm1 = xmm0 * xmm1 * using [CLMUL-WP] algorithm 1 (p. 12). */ "movdqa %%xmm1, %%xmm2 \n\t" // copy of b1:b0 "movdqa %%xmm1, %%xmm3 \n\t" // same "movdqa %%xmm1, %%xmm4 \n\t" // same PCLMULQDQ(xmm0_xmm1, "0x00") // a0*b0 = c1:c0 PCLMULQDQ(xmm0_xmm2, "0x11") // a1*b1 = d1:d0 PCLMULQDQ(xmm0_xmm3, "0x10") // a0*b1 = e1:e0 PCLMULQDQ(xmm0_xmm4, "0x01") // a1*b0 = f1:f0 "pxor %%xmm3, %%xmm4 \n\t" // e1+f1:e0+f0 "movdqa %%xmm4, %%xmm3 \n\t" // same "psrldq $8, %%xmm4 \n\t" // 0:e1+f1 "pslldq $8, %%xmm3 \n\t" // e0+f0:0 "pxor %%xmm4, %%xmm2 \n\t" // d1:d0+e1+f1 "pxor %%xmm3, %%xmm1 \n\t" // c1+e0+f1:c0 /* * Now shift the result one bit to the left, * taking advantage of [CLMUL-WP] eq 27 (p. 18) */ "movdqa %%xmm1, %%xmm3 \n\t" // r1:r0 "movdqa %%xmm2, %%xmm4 \n\t" // r3:r2 "psllq $1, %%xmm1 \n\t" // r1<<1:r0<<1 "psllq $1, %%xmm2 \n\t" // r3<<1:r2<<1 "psrlq $63, %%xmm3 \n\t" // r1>>63:r0>>63 "psrlq $63, %%xmm4 \n\t" // r3>>63:r2>>63 "movdqa %%xmm3, %%xmm5 \n\t" // r1>>63:r0>>63 "pslldq $8, %%xmm3 \n\t" // r0>>63:0 "pslldq $8, %%xmm4 \n\t" // r2>>63:0 "psrldq $8, %%xmm5 \n\t" // 0:r1>>63 "por %%xmm3, %%xmm1 \n\t" // r1<<1|r0>>63:r0<<1 "por %%xmm4, %%xmm2 \n\t" // r3<<1|r2>>62:r2<<1 "por %%xmm5, %%xmm2 \n\t" // r3<<1|r2>>62:r2<<1|r1>>63 /* * Now reduce modulo the GCM polynomial x^128 + x^7 + x^2 + x + 1 * using [CLMUL-WP] algorithm 5 (p. 18). * Currently xmm2:xmm1 holds x3:x2:x1:x0 (already shifted). */ /* Step 2 (1) */ "movdqa %%xmm1, %%xmm3 \n\t" // x1:x0 "movdqa %%xmm1, %%xmm4 \n\t" // same "movdqa %%xmm1, %%xmm5 \n\t" // same "psllq $63, %%xmm3 \n\t" // x1<<63:x0<<63 = stuff:a "psllq $62, %%xmm4 \n\t" // x1<<62:x0<<62 = stuff:b "psllq $57, %%xmm5 \n\t" // x1<<57:x0<<57 = stuff:c /* Step 2 (2) */ "pxor %%xmm4, %%xmm3 \n\t" // stuff:a+b "pxor %%xmm5, %%xmm3 \n\t" // stuff:a+b+c "pslldq $8, %%xmm3 \n\t" // a+b+c:0 "pxor %%xmm3, %%xmm1 \n\t" // x1+a+b+c:x0 = d:x0 /* Steps 3 and 4 */ "movdqa %%xmm1,%%xmm0 \n\t" // d:x0 "movdqa %%xmm1,%%xmm4 \n\t" // same "movdqa %%xmm1,%%xmm5 \n\t" // same "psrlq $1, %%xmm0 \n\t" // e1:x0>>1 = e1:e0' "psrlq $2, %%xmm4 \n\t" // f1:x0>>2 = f1:f0' "psrlq $7, %%xmm5 \n\t" // g1:x0>>7 = g1:g0' "pxor %%xmm4, %%xmm0 \n\t" // e1+f1:e0'+f0' "pxor %%xmm5, %%xmm0 \n\t" // e1+f1+g1:e0'+f0'+g0' // e0'+f0'+g0' is almost e0+f0+g0, ex\tcept for some missing // bits carried from d. Now get those\t bits back in. "movdqa %%xmm1,%%xmm3 \n\t" // d:x0 "movdqa %%xmm1,%%xmm4 \n\t" // same "movdqa %%xmm1,%%xmm5 \n\t" // same "psllq $63, %%xmm3 \n\t" // d<<63:stuff "psllq $62, %%xmm4 \n\t" // d<<62:stuff "psllq $57, %%xmm5 \n\t" // d<<57:stuff "pxor %%xmm4, %%xmm3 \n\t" // d<<63+d<<62:stuff "pxor %%xmm5, %%xmm3 \n\t" // missing bits of d:stuff "psrldq $8, %%xmm3 \n\t" // 0:missing bits of d "pxor %%xmm3, %%xmm0 \n\t" // e1+f1+g1:e0+f0+g0 "pxor %%xmm1, %%xmm0 \n\t" // h1:h0 "pxor %%xmm2, %%xmm0 \n\t" // x3+h1:x2+h0 "movdqu %%xmm0, (%2) \n\t" // done : : "r" (aa), "r" (bb), "r" (cc) : "memory", "cc", "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5"); /* Now byte-reverse the outputs */ for (i = 0; i < 16; i++) { c[i] = cc[15 - i]; } return; } /* * Compute decryption round keys from encryption round keys */ #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) void mbedtls_aesni_inverse_key(unsigned char *invkey, const unsigned char *fwdkey, int nr) { unsigned char *ik = invkey; const unsigned char *fk = fwdkey + 16 * nr; memcpy(ik, fk, 16); for (fk -= 16, ik += 16; fk > fwdkey; fk -= 16, ik += 16) { asm ("movdqu (%0), %%xmm0 \n\t" AESIMC(xmm0_xmm0) "movdqu %%xmm0, (%1) \n\t" : : "r" (fk), "r" (ik) : "memory", "xmm0"); } memcpy(ik, fk, 16); } #endif /* * Key expansion, 128-bit case */ static void aesni_setkey_enc_128(unsigned char *rk, const unsigned char *key) { asm ("movdqu (%1), %%xmm0 \n\t" // copy the original key "movdqu %%xmm0, (%0) \n\t" // as round key 0 "jmp 2f \n\t" // skip auxiliary routine /* * Finish generating the next round key. * * On entry xmm0 is r3:r2:r1:r0 and xmm1 is X:stuff:stuff:stuff * with X = rot( sub( r3 ) ) ^ RCON. * * On exit, xmm0 is r7:r6:r5:r4 * with r4 = X + r0, r5 = r4 + r1, r6 = r5 + r2, r7 = r6 + r3 * and those are written to the round key buffer. */ "1: \n\t" "pshufd $0xff, %%xmm1, %%xmm1 \n\t" // X:X:X:X "pxor %%xmm0, %%xmm1 \n\t" // X+r3:X+r2:X+r1:r4 "pslldq $4, %%xmm0 \n\t" // r2:r1:r0:0 "pxor %%xmm0, %%xmm1 \n\t" // X+r3+r2:X+r2+r1:r5:r4 "pslldq $4, %%xmm0 \n\t" // etc "pxor %%xmm0, %%xmm1 \n\t" "pslldq $4, %%xmm0 \n\t" "pxor %%xmm1, %%xmm0 \n\t" // update xmm0 for next time! "add $16, %0 \n\t" // point to next round key "movdqu %%xmm0, (%0) \n\t" // write it "ret \n\t" /* Main "loop" */ "2: \n\t" AESKEYGENA(xmm0_xmm1, "0x01") "call 1b \n\t" AESKEYGENA(xmm0_xmm1, "0x02") "call 1b \n\t" AESKEYGENA(xmm0_xmm1, "0x04") "call 1b \n\t" AESKEYGENA(xmm0_xmm1, "0x08") "call 1b \n\t" AESKEYGENA(xmm0_xmm1, "0x10") "call 1b \n\t" AESKEYGENA(xmm0_xmm1, "0x20") "call 1b \n\t" AESKEYGENA(xmm0_xmm1, "0x40") "call 1b \n\t" AESKEYGENA(xmm0_xmm1, "0x80") "call 1b \n\t" AESKEYGENA(xmm0_xmm1, "0x1B") "call 1b \n\t" AESKEYGENA(xmm0_xmm1, "0x36") "call 1b \n\t" : : "r" (rk), "r" (key) : "memory", "cc", "xmm0", "xmm1", "0"); } /* * Key expansion, 192-bit case */ #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) static void aesni_setkey_enc_192(unsigned char *rk, const unsigned char *key) { asm ("movdqu (%1), %%xmm0 \n\t" // copy original round key "movdqu %%xmm0, (%0) \n\t" "add $16, %0 \n\t" "movq 16(%1), %%xmm1 \n\t" "movq %%xmm1, (%0) \n\t" "add $8, %0 \n\t" "jmp 2f \n\t" // skip auxiliary routine /* * Finish generating the next 6 quarter-keys. * * On entry xmm0 is r3:r2:r1:r0, xmm1 is stuff:stuff:r5:r4 * and xmm2 is stuff:stuff:X:stuff with X = rot( sub( r3 ) ) ^ RCON. * * On exit, xmm0 is r9:r8:r7:r6 and xmm1 is stuff:stuff:r11:r10 * and those are written to the round key buffer. */ "1: \n\t" "pshufd $0x55, %%xmm2, %%xmm2 \n\t" // X:X:X:X "pxor %%xmm0, %%xmm2 \n\t" // X+r3:X+r2:X+r1:r4 "pslldq $4, %%xmm0 \n\t" // etc "pxor %%xmm0, %%xmm2 \n\t" "pslldq $4, %%xmm0 \n\t" "pxor %%xmm0, %%xmm2 \n\t" "pslldq $4, %%xmm0 \n\t" "pxor %%xmm2, %%xmm0 \n\t" // update xmm0 = r9:r8:r7:r6 "movdqu %%xmm0, (%0) \n\t" "add $16, %0 \n\t" "pshufd $0xff, %%xmm0, %%xmm2 \n\t" // r9:r9:r9:r9 "pxor %%xmm1, %%xmm2 \n\t" // stuff:stuff:r9+r5:r10 "pslldq $4, %%xmm1 \n\t" // r2:r1:r0:0 "pxor %%xmm2, %%xmm1 \n\t" // xmm1 = stuff:stuff:r11:r10 "movq %%xmm1, (%0) \n\t" "add $8, %0 \n\t" "ret \n\t" "2: \n\t" AESKEYGENA(xmm1_xmm2, "0x01") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x02") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x04") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x08") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x10") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x20") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x40") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x80") "call 1b \n\t" : : "r" (rk), "r" (key) : "memory", "cc", "xmm0", "xmm1", "xmm2", "0"); } #endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */ /* * Key expansion, 256-bit case */ #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) static void aesni_setkey_enc_256(unsigned char *rk, const unsigned char *key) { asm ("movdqu (%1), %%xmm0 \n\t" "movdqu %%xmm0, (%0) \n\t" "add $16, %0 \n\t" "movdqu 16(%1), %%xmm1 \n\t" "movdqu %%xmm1, (%0) \n\t" "jmp 2f \n\t" // skip auxiliary routine /* * Finish generating the next two round keys. * * On entry xmm0 is r3:r2:r1:r0, xmm1 is r7:r6:r5:r4 and * xmm2 is X:stuff:stuff:stuff with X = rot( sub( r7 )) ^ RCON * * On exit, xmm0 is r11:r10:r9:r8 and xmm1 is r15:r14:r13:r12 * and those have been written to the output buffer. */ "1: \n\t" "pshufd $0xff, %%xmm2, %%xmm2 \n\t" "pxor %%xmm0, %%xmm2 \n\t" "pslldq $4, %%xmm0 \n\t" "pxor %%xmm0, %%xmm2 \n\t" "pslldq $4, %%xmm0 \n\t" "pxor %%xmm0, %%xmm2 \n\t" "pslldq $4, %%xmm0 \n\t" "pxor %%xmm2, %%xmm0 \n\t" "add $16, %0 \n\t" "movdqu %%xmm0, (%0) \n\t" /* Set xmm2 to stuff:Y:stuff:stuff with Y = subword( r11 ) * and proceed to generate next round key from there */ AESKEYGENA(xmm0_xmm2, "0x00") "pshufd $0xaa, %%xmm2, %%xmm2 \n\t" "pxor %%xmm1, %%xmm2 \n\t" "pslldq $4, %%xmm1 \n\t" "pxor %%xmm1, %%xmm2 \n\t" "pslldq $4, %%xmm1 \n\t" "pxor %%xmm1, %%xmm2 \n\t" "pslldq $4, %%xmm1 \n\t" "pxor %%xmm2, %%xmm1 \n\t" "add $16, %0 \n\t" "movdqu %%xmm1, (%0) \n\t" "ret \n\t" /* * Main "loop" - Generating one more key than necessary, * see definition of mbedtls_aes_context.buf */ "2: \n\t" AESKEYGENA(xmm1_xmm2, "0x01") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x02") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x04") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x08") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x10") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x20") "call 1b \n\t" AESKEYGENA(xmm1_xmm2, "0x40") "call 1b \n\t" : : "r" (rk), "r" (key) : "memory", "cc", "xmm0", "xmm1", "xmm2", "0"); } #endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */ #endif /* MBEDTLS_AESNI_HAVE_CODE */ /* * Key expansion, wrapper */ int mbedtls_aesni_setkey_enc(unsigned char *rk, const unsigned char *key, size_t bits) { switch (bits) { case 128: aesni_setkey_enc_128(rk, key); break; #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) case 192: aesni_setkey_enc_192(rk, key); break; case 256: aesni_setkey_enc_256(rk, key); break; #endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */ default: return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH; } return 0; } #endif /* MBEDTLS_AESNI_HAVE_CODE */ #endif /* MBEDTLS_AESNI_C */ keyring/src/blake2.h0000644000176200001440000000743014775227066014046 0ustar liggesusers/* BLAKE2 reference source code package - reference C implementations Written in 2012 by Samuel Neves To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. All code is triple-licensed under the [CC0](http://creativecommons.org/publicdomain/zero/1.0), the [OpenSSL Licence](https://www.openssl.org/source/license.html), or the [Apache Public License 2.0](http://www.apache.org/licenses/LICENSE-2.0), at your choosing. */ #ifndef blake2_H #define blake2_H #include #include #include "crypto_generichash_blake2b.h" #include "sodium.h" enum blake2b_constant { BLAKE2B_BLOCKBYTES = 128, BLAKE2B_OUTBYTES = 64, BLAKE2B_KEYBYTES = 64, BLAKE2B_SALTBYTES = 16, BLAKE2B_PERSONALBYTES = 16 }; #ifdef __IBMC__ # pragma pack(1) #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) # pragma pack(1) #else # pragma pack(push, 1) #endif typedef struct blake2b_param_ { uint8_t digest_length; /* 1 */ uint8_t key_length; /* 2 */ uint8_t fanout; /* 3 */ uint8_t depth; /* 4 */ uint8_t leaf_length[4]; /* 8 */ uint8_t node_offset[8]; /* 16 */ uint8_t node_depth; /* 17 */ uint8_t inner_length; /* 18 */ uint8_t reserved[14]; /* 32 */ uint8_t salt[BLAKE2B_SALTBYTES]; /* 48 */ uint8_t personal[BLAKE2B_PERSONALBYTES]; /* 64 */ } blake2b_param; typedef struct blake2b_state { uint64_t h[8]; uint64_t t[2]; uint64_t f[2]; uint8_t buf[2 * 128]; size_t buflen; uint8_t last_node; } blake2b_state; #ifdef __IBMC__ # pragma pack(pop) #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) # pragma pack() #else # pragma pack(pop) #endif /* Streaming API */ int blake2b_init(blake2b_state *S, const uint8_t outlen); int blake2b_init_salt_personal(blake2b_state *S, const uint8_t outlen, const void *salt, const void *personal); int blake2b_init_key(blake2b_state *S, const uint8_t outlen, const void *key, const uint8_t keylen); int blake2b_init_key_salt_personal(blake2b_state *S, const uint8_t outlen, const void *key, const uint8_t keylen, const void *salt, const void *personal); int blake2b_init_param(blake2b_state *S, const blake2b_param *P); int blake2b_update(blake2b_state *S, const uint8_t *in, uint64_t inlen); int blake2b_final(blake2b_state *S, uint8_t *out, uint8_t outlen); /* Simple API */ int blake2b(uint8_t *out, const void *in, const void *key, const uint8_t outlen, const uint64_t inlen, uint8_t keylen); int blake2b_salt_personal(uint8_t *out, const void *in, const void *key, const uint8_t outlen, const uint64_t inlen, uint8_t keylen, const void *salt, const void *personal); typedef int (*blake2b_compress_fn)(blake2b_state *S, const uint8_t block[BLAKE2B_BLOCKBYTES]); int blake2b_pick_best_implementation(void); int blake2b_compress_ref(blake2b_state *S, const uint8_t block[BLAKE2B_BLOCKBYTES]); int blake2b_compress_ssse3(blake2b_state *S, const uint8_t block[BLAKE2B_BLOCKBYTES]); int blake2b_compress_sse41(blake2b_state *S, const uint8_t block[BLAKE2B_BLOCKBYTES]); int blake2b_compress_avx2(blake2b_state *S, const uint8_t block[BLAKE2B_BLOCKBYTES]); #endif keyring/src/Makevars.win0000644000176200001440000000013615006370264015004 0ustar liggesusersPKG_CPPFLAGS=-DMBEDTLS_AES_C -DMBEDTLS_ALLOW_PRIVATE_ACCESS -DMBEDTLS_PLATFORM_PRINTF_ALT -I. keyring/src/crypto_generichash.h0000644000176200001440000000467714775227066016600 0ustar liggesusers#ifndef crypto_generichash_H #define crypto_generichash_H #include #include "crypto_generichash_blake2b.h" #include "sodium.h" #ifdef __cplusplus # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wlong-long" # endif extern "C" { #endif #define crypto_generichash_BYTES_MIN crypto_generichash_blake2b_BYTES_MIN SODIUM_EXPORT size_t crypto_generichash_bytes_min(void); #define crypto_generichash_BYTES_MAX crypto_generichash_blake2b_BYTES_MAX SODIUM_EXPORT size_t crypto_generichash_bytes_max(void); #define crypto_generichash_BYTES crypto_generichash_blake2b_BYTES SODIUM_EXPORT size_t crypto_generichash_bytes(void); #define crypto_generichash_KEYBYTES_MIN crypto_generichash_blake2b_KEYBYTES_MIN SODIUM_EXPORT size_t crypto_generichash_keybytes_min(void); #define crypto_generichash_KEYBYTES_MAX crypto_generichash_blake2b_KEYBYTES_MAX SODIUM_EXPORT size_t crypto_generichash_keybytes_max(void); #define crypto_generichash_KEYBYTES crypto_generichash_blake2b_KEYBYTES SODIUM_EXPORT size_t crypto_generichash_keybytes(void); #define crypto_generichash_PRIMITIVE "blake2b" SODIUM_EXPORT const char *crypto_generichash_primitive(void); /* * Important when writing bindings for other programming languages: * the state address should be 64-bytes aligned. */ typedef crypto_generichash_blake2b_state crypto_generichash_state; SODIUM_EXPORT size_t crypto_generichash_statebytes(void); SODIUM_EXPORT int crypto_generichash(unsigned char *out, size_t outlen, const unsigned char *in, unsigned long long inlen, const unsigned char *key, size_t keylen) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_generichash_init(crypto_generichash_state *state, const unsigned char *key, const size_t keylen, const size_t outlen) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_generichash_update(crypto_generichash_state *state, const unsigned char *in, unsigned long long inlen) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_generichash_final(crypto_generichash_state *state, unsigned char *out, const size_t outlen) __attribute__ ((nonnull)); SODIUM_EXPORT void crypto_generichash_keygen(unsigned char k[crypto_generichash_KEYBYTES]) __attribute__ ((nonnull)); #ifdef __cplusplus } #endif #endif keyring/src/crypto_stream_xsalsa20.h0000644000176200001440000000345414775227066017320 0ustar liggesusers#ifndef crypto_stream_xsalsa20_H #define crypto_stream_xsalsa20_H /* * WARNING: This is just a stream cipher. It is NOT authenticated encryption. * While it provides some protection against eavesdropping, it does NOT * provide any security against active attacks. * Unless you know what you're doing, what you are looking for is probably * the crypto_box functions. */ #include #include #ifdef __cplusplus # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wlong-long" # endif extern "C" { #endif #define crypto_stream_xsalsa20_KEYBYTES 32U SODIUM_EXPORT size_t crypto_stream_xsalsa20_keybytes(void); #define crypto_stream_xsalsa20_NONCEBYTES 24U SODIUM_EXPORT size_t crypto_stream_xsalsa20_noncebytes(void); #define crypto_stream_xsalsa20_MESSAGEBYTES_MAX SODIUM_SIZE_MAX SODIUM_EXPORT size_t crypto_stream_xsalsa20_messagebytes_max(void); SODIUM_EXPORT int crypto_stream_xsalsa20(unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) __attribute__ ((nonnull)); SODIUM_EXPORT int crypto_stream_xsalsa20_xor(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, const unsigned char *k) __attribute__ ((nonnull)); SODIUM_EXPORT int crypto_stream_xsalsa20_xor_ic(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, uint64_t ic, const unsigned char *k) __attribute__ ((nonnull)); SODIUM_EXPORT void crypto_stream_xsalsa20_keygen(unsigned char k[crypto_stream_xsalsa20_KEYBYTES]) __attribute__ ((nonnull)); #ifdef __cplusplus } #endif #endif keyring/src/psa/0000755000176200001440000000000015006370264013277 5ustar liggesuserskeyring/src/psa/crypto_adjust_auto_enabled.h0000644000176200001440000000214515006370264021046 0ustar liggesusers/** * \file psa/crypto_adjust_auto_enabled.h * \brief Adjust PSA configuration: enable always-on features * * This is an internal header. Do not include it directly. * * Always enable certain features which require a negligible amount of code * to implement, to avoid some edge cases in the configuration combinatorics. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef PSA_CRYPTO_ADJUST_AUTO_ENABLED_H #define PSA_CRYPTO_ADJUST_AUTO_ENABLED_H #if !defined(MBEDTLS_CONFIG_FILES_READ) #error "Do not include psa/crypto_adjust_*.h manually! This can lead to problems, " \ "up to and including runtime errors such as buffer overflows. " \ "If you're trying to fix a complaint from check_config.h, just remove " \ "it from your configuration file: since Mbed TLS 3.0, it is included " \ "automatically at the right point." #endif /* */ #define PSA_WANT_KEY_TYPE_DERIVE 1 #define PSA_WANT_KEY_TYPE_PASSWORD 1 #define PSA_WANT_KEY_TYPE_PASSWORD_HASH 1 #define PSA_WANT_KEY_TYPE_RAW_DATA 1 #endif /* PSA_CRYPTO_ADJUST_AUTO_ENABLED_H */ keyring/src/psa/crypto_adjust_config_dependencies.h0000644000176200001440000000374015006370264022401 0ustar liggesusers/** * \file psa/crypto_adjust_config_dependencies.h * \brief Adjust PSA configuration by resolving some dependencies. * * This is an internal header. Do not include it directly. * * See docs/proposed/psa-conditional-inclusion-c.md. * If the Mbed TLS implementation of a cryptographic mechanism A depends on a * cryptographic mechanism B then if the cryptographic mechanism A is enabled * and not accelerated enable B. Note that if A is enabled and accelerated, it * is not necessary to enable B for A support. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef PSA_CRYPTO_ADJUST_CONFIG_DEPENDENCIES_H #define PSA_CRYPTO_ADJUST_CONFIG_DEPENDENCIES_H #if !defined(MBEDTLS_CONFIG_FILES_READ) #error "Do not include psa/crypto_adjust_*.h manually! This can lead to problems, " \ "up to and including runtime errors such as buffer overflows. " \ "If you're trying to fix a complaint from check_config.h, just remove " \ "it from your configuration file: since Mbed TLS 3.0, it is included " \ "automatically at the right point." #endif /* */ #if (defined(PSA_WANT_ALG_TLS12_PRF) && \ !defined(MBEDTLS_PSA_ACCEL_ALG_TLS12_PRF)) || \ (defined(PSA_WANT_ALG_TLS12_PSK_TO_MS) && \ !defined(MBEDTLS_PSA_ACCEL_ALG_TLS12_PSK_TO_MS)) || \ (defined(PSA_WANT_ALG_HKDF) && \ !defined(MBEDTLS_PSA_ACCEL_ALG_HKDF)) || \ (defined(PSA_WANT_ALG_HKDF_EXTRACT) && \ !defined(MBEDTLS_PSA_ACCEL_ALG_HKDF_EXTRACT)) || \ (defined(PSA_WANT_ALG_HKDF_EXPAND) && \ !defined(MBEDTLS_PSA_ACCEL_ALG_HKDF_EXPAND)) || \ (defined(PSA_WANT_ALG_PBKDF2_HMAC) && \ !defined(MBEDTLS_PSA_ACCEL_ALG_PBKDF2_HMAC)) #define PSA_WANT_ALG_HMAC 1 #define PSA_WANT_KEY_TYPE_HMAC 1 #endif #if (defined(PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128) && \ !defined(MBEDTLS_PSA_ACCEL_ALG_PBKDF2_AES_CMAC_PRF_128)) #define PSA_WANT_KEY_TYPE_AES 1 #define PSA_WANT_ALG_CMAC 1 #endif #endif /* PSA_CRYPTO_ADJUST_CONFIG_DEPENDENCIES_H */ keyring/src/psa/crypto_adjust_config_synonyms.h0000644000176200001440000000375415006370264021657 0ustar liggesusers/** * \file psa/crypto_adjust_config_synonyms.h * \brief Adjust PSA configuration: enable quasi-synonyms * * This is an internal header. Do not include it directly. * * When two features require almost the same code, we automatically enable * both when either one is requested, to reduce the combinatorics of * possible configurations. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef PSA_CRYPTO_ADJUST_CONFIG_SYNONYMS_H #define PSA_CRYPTO_ADJUST_CONFIG_SYNONYMS_H #if !defined(MBEDTLS_CONFIG_FILES_READ) #error "Do not include psa/crypto_adjust_*.h manually! This can lead to problems, " \ "up to and including runtime errors such as buffer overflows. " \ "If you're trying to fix a complaint from check_config.h, just remove " \ "it from your configuration file: since Mbed TLS 3.0, it is included " \ "automatically at the right point." #endif /* */ /****************************************************************/ /* De facto synonyms */ /****************************************************************/ #if defined(PSA_WANT_ALG_ECDSA_ANY) && !defined(PSA_WANT_ALG_ECDSA) #define PSA_WANT_ALG_ECDSA PSA_WANT_ALG_ECDSA_ANY #elif !defined(PSA_WANT_ALG_ECDSA_ANY) && defined(PSA_WANT_ALG_ECDSA) #define PSA_WANT_ALG_ECDSA_ANY PSA_WANT_ALG_ECDSA #endif #if defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW) && !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN) #define PSA_WANT_ALG_RSA_PKCS1V15_SIGN PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW #elif !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW) && defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN) #define PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW PSA_WANT_ALG_RSA_PKCS1V15_SIGN #endif #if defined(PSA_WANT_ALG_RSA_PSS_ANY_SALT) && !defined(PSA_WANT_ALG_RSA_PSS) #define PSA_WANT_ALG_RSA_PSS PSA_WANT_ALG_RSA_PSS_ANY_SALT #elif !defined(PSA_WANT_ALG_RSA_PSS_ANY_SALT) && defined(PSA_WANT_ALG_RSA_PSS) #define PSA_WANT_ALG_RSA_PSS_ANY_SALT PSA_WANT_ALG_RSA_PSS #endif #endif /* PSA_CRYPTO_ADJUST_CONFIG_SYNONYMS_H */ keyring/src/psa/crypto_legacy.h0000644000176200001440000000605715006370264016324 0ustar liggesusers/** * \file psa/crypto_legacy.h * * \brief Add temporary suppport for deprecated symbols before they are * removed from the library. * * PSA_WANT_KEY_TYPE_xxx_KEY_PAIR and MBEDTLS_PSA_ACCEL_KEY_TYPE_xxx_KEY_PAIR * symbols are deprecated. * New symols add a suffix to that base name in order to clearly state what is * the expected use for the key (use, import, export, generate, derive). * Here we define some backward compatibility support for uses stil using * the legacy symbols. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_PSA_CRYPTO_LEGACY_H #define MBEDTLS_PSA_CRYPTO_LEGACY_H #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) //no-check-names #if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1 #endif #if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT) #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1 #endif #if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT) #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1 #endif #if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE) #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1 #endif #if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE) #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1 #endif #endif #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) //no-check-names #if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC) #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1 #endif #if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT) #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1 #endif #if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT) #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1 #endif #if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE) #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1 #endif #endif #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) //no-check-names #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC) #define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC #endif #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT) #define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT #endif #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT) #define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT #endif #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE) #define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE #endif #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE) #define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE #endif #endif #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR) //no-check-names #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC) #define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC #endif #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT) #define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT #endif #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT) #define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT #endif #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE) #define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE #endif #endif #endif /* MBEDTLS_PSA_CRYPTO_LEGACY_H */ keyring/src/psa/crypto_adjust_config_key_pair_types.h0000644000176200001440000000743515006370264023007 0ustar liggesusers/** * \file psa/crypto_adjust_config_key_pair_types.h * \brief Adjust PSA configuration for key pair types. * * This is an internal header. Do not include it directly. * * See docs/proposed/psa-conditional-inclusion-c.md. * - Support non-basic operations in a keypair type implicitly enables basic * support for that keypair type. * - Support for a keypair type implicitly enables the corresponding public * key type. * - Basic support for a keypair type implicilty enables import/export support * for that keypair type. Warning: this is implementation-specific (mainly * for the benefit of testing) and may change in the future! */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef PSA_CRYPTO_ADJUST_KEYPAIR_TYPES_H #define PSA_CRYPTO_ADJUST_KEYPAIR_TYPES_H #if !defined(MBEDTLS_CONFIG_FILES_READ) #error "Do not include psa/crypto_adjust_*.h manually! This can lead to problems, " \ "up to and including runtime errors such as buffer overflows. " \ "If you're trying to fix a complaint from check_config.h, just remove " \ "it from your configuration file: since Mbed TLS 3.0, it is included " \ "automatically at the right point." #endif /* */ /***************************************************************** * ANYTHING -> BASIC ****************************************************************/ #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT) || \ defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT) || \ defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE) || \ defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE) #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1 #endif #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT) || \ defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT) || \ defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE) || \ defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE) #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1 #endif #if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT) || \ defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT) || \ defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE) || \ defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE) #define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1 #endif /***************************************************************** * BASIC -> corresponding PUBLIC ****************************************************************/ #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) #define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1 #endif #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC) #define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1 #endif #if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC) #define PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY 1 #endif /***************************************************************** * BASIC -> IMPORT+EXPORT * * (Implementation-specific, may change in the future.) ****************************************************************/ /* Even though KEY_PAIR symbols' feature several level of support (BASIC, IMPORT, * EXPORT, GENERATE, DERIVE) we're not planning to have support only for BASIC * without IMPORT/EXPORT since these last 2 features are strongly used in tests. * In general it is allowed to include more feature than what is strictly * requested. * As a consequence IMPORT and EXPORT features will be automatically enabled * as soon as the BASIC one is. */ #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1 #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1 #endif #if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC) #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1 #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1 #endif #if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC) #define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT 1 #define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT 1 #endif #endif /* PSA_CRYPTO_ADJUST_KEYPAIR_TYPES_H */ keyring/src/crypto_core_salsa20.h0000644000176200001440000000143014775227066016555 0ustar liggesusers#ifndef crypto_core_salsa20_H #define crypto_core_salsa20_H #include #include "sodium.h" #ifdef __cplusplus extern "C" { #endif #define crypto_core_salsa20_OUTPUTBYTES 64U SODIUM_EXPORT size_t crypto_core_salsa20_outputbytes(void); #define crypto_core_salsa20_INPUTBYTES 16U SODIUM_EXPORT size_t crypto_core_salsa20_inputbytes(void); #define crypto_core_salsa20_KEYBYTES 32U SODIUM_EXPORT size_t crypto_core_salsa20_keybytes(void); #define crypto_core_salsa20_CONSTBYTES 16U SODIUM_EXPORT size_t crypto_core_salsa20_constbytes(void); SODIUM_EXPORT int crypto_core_salsa20(unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c) __attribute__ ((nonnull(1, 2, 3))); #ifdef __cplusplus } #endif #endif keyring/src/stream_salsa20.c0000644000176200001440000000513714775227066015523 0ustar liggesusers#include "crypto_stream_salsa20.h" #include "stream_salsa20.h" #ifdef HAVE_AMD64_ASM # include "xmm6/salsa20_xmm6.h" #else # include "salsa20_ref.h" #endif #if !defined(HAVE_AMD64_ASM) && defined(HAVE_EMMINTRIN_H) # include "xmm6int/salsa20_xmm6int-sse2.h" #endif #if defined(HAVE_AVX2INTRIN_H) && defined(HAVE_EMMINTRIN_H) && \ defined(HAVE_TMMINTRIN_H) && defined(HAVE_SMMINTRIN_H) # include "xmm6int/salsa20_xmm6int-avx2.h" #endif #if HAVE_AMD64_ASM static const crypto_stream_salsa20_implementation *implementation = &crypto_stream_salsa20_xmm6_implementation; #else static const crypto_stream_salsa20_implementation *implementation = &crypto_stream_salsa20_ref_implementation; #endif size_t crypto_stream_salsa20_keybytes(void) { return crypto_stream_salsa20_KEYBYTES; } size_t crypto_stream_salsa20_noncebytes(void) { return crypto_stream_salsa20_NONCEBYTES; } size_t crypto_stream_salsa20_messagebytes_max(void) { return crypto_stream_salsa20_MESSAGEBYTES_MAX; } int crypto_stream_salsa20(unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) { return implementation->stream(c, clen, n, k); } int crypto_stream_salsa20_xor_ic(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, uint64_t ic, const unsigned char *k) { return implementation->stream_xor_ic(c, m, mlen, n, ic, k); } int crypto_stream_salsa20_xor(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, const unsigned char *k) { return implementation->stream_xor_ic(c, m, mlen, n, 0U, k); } void crypto_stream_salsa20_keygen(unsigned char k[crypto_stream_salsa20_KEYBYTES]) { randombytes_buf(k, crypto_stream_salsa20_KEYBYTES); } int _crypto_stream_salsa20_pick_best_implementation(void) { #ifdef HAVE_AMD64_ASM implementation = &crypto_stream_salsa20_xmm6_implementation; #else implementation = &crypto_stream_salsa20_ref_implementation; #endif #if defined(HAVE_AVX2INTRIN_H) && defined(HAVE_EMMINTRIN_H) && \ defined(HAVE_TMMINTRIN_H) && defined(HAVE_SMMINTRIN_H) if (sodium_runtime_has_avx2()) { implementation = &crypto_stream_salsa20_xmm6int_avx2_implementation; return 0; } #endif #if !defined(HAVE_AMD64_ASM) && defined(HAVE_EMMINTRIN_H) if (sodium_runtime_has_sse2()) { implementation = &crypto_stream_salsa20_xmm6int_sse2_implementation; return 0; } #endif return 0; /* LCOV_EXCL_LINE */ } keyring/src/win-path.c0000644000176200001440000000126614775244716014432 0ustar liggesusers#include #include #ifdef WIN32 #include // SHGetFolderPath documentation: // http://msdn.microsoft.com/en-us/library/windows/desktop/bb762181.aspx SEXP win_path_(SEXP _folder) { int folder = INTEGER(_folder)[0]; TCHAR startupFolder[MAX_PATH]; HRESULT hr = SHGetFolderPath(0, folder, 0, 0, startupFolder); if (SUCCEEDED(hr)) { // Get short path TCHAR shortPath[MAX_PATH]; GetShortPathName(startupFolder, shortPath, MAX_PATH); return mkString(shortPath); } else { // Return NULL if failed return R_NilValue; } } #else SEXP win_path_(SEXP folder) { return R_NilValue; } #endif keyring/src/padlock.c0000644000176200001440000001033115006370264014273 0ustar liggesusers/* * VIA PadLock support functions * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ /* * This implementation is based on the VIA PadLock Programming Guide: * * http://www.via.com.tw/en/downloads/whitepapers/initiatives/padlock/ * programming_guide.pdf */ #include "common.h" #if defined(MBEDTLS_PADLOCK_C) #include "padlock.h" #include #if defined(MBEDTLS_VIA_PADLOCK_HAVE_CODE) /* * PadLock detection routine */ int mbedtls_padlock_has_support(int feature) { static int flags = -1; int ebx = 0, edx = 0; if (flags == -1) { asm ("movl %%ebx, %0 \n\t" "movl $0xC0000000, %%eax \n\t" "cpuid \n\t" "cmpl $0xC0000001, %%eax \n\t" "movl $0, %%edx \n\t" "jb 1f \n\t" "movl $0xC0000001, %%eax \n\t" "cpuid \n\t" "1: \n\t" "movl %%edx, %1 \n\t" "movl %2, %%ebx \n\t" : "=m" (ebx), "=m" (edx) : "m" (ebx) : "eax", "ecx", "edx"); flags = edx; } return flags & feature; } /* * PadLock AES-ECB block en(de)cryption */ int mbedtls_padlock_xcryptecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]) { int ebx = 0; uint32_t *rk; uint32_t *blk; uint32_t *ctrl; unsigned char buf[256]; rk = ctx->buf + ctx->rk_offset; if (((long) rk & 15) != 0) { return MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED; } blk = MBEDTLS_PADLOCK_ALIGN16(buf); memcpy(blk, input, 16); ctrl = blk + 4; *ctrl = 0x80 | ctx->nr | ((ctx->nr + (mode^1) - 10) << 9); asm ("pushfl \n\t" "popfl \n\t" "movl %%ebx, %0 \n\t" "movl $1, %%ecx \n\t" "movl %2, %%edx \n\t" "movl %3, %%ebx \n\t" "movl %4, %%esi \n\t" "movl %4, %%edi \n\t" ".byte 0xf3,0x0f,0xa7,0xc8 \n\t" "movl %1, %%ebx \n\t" : "=m" (ebx) : "m" (ebx), "m" (ctrl), "m" (rk), "m" (blk) : "memory", "ecx", "edx", "esi", "edi"); memcpy(output, blk, 16); return 0; } #if defined(MBEDTLS_CIPHER_MODE_CBC) /* * PadLock AES-CBC buffer en(de)cryption */ int mbedtls_padlock_xcryptcbc(mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output) { int ebx = 0; size_t count; uint32_t *rk; uint32_t *iw; uint32_t *ctrl; unsigned char buf[256]; rk = ctx->buf + ctx->rk_offset; if (((long) input & 15) != 0 || ((long) output & 15) != 0 || ((long) rk & 15) != 0) { return MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED; } iw = MBEDTLS_PADLOCK_ALIGN16(buf); memcpy(iw, iv, 16); ctrl = iw + 4; *ctrl = 0x80 | ctx->nr | ((ctx->nr + (mode ^ 1) - 10) << 9); count = (length + 15) >> 4; asm ("pushfl \n\t" "popfl \n\t" "movl %%ebx, %0 \n\t" "movl %2, %%ecx \n\t" "movl %3, %%edx \n\t" "movl %4, %%ebx \n\t" "movl %5, %%esi \n\t" "movl %6, %%edi \n\t" "movl %7, %%eax \n\t" ".byte 0xf3,0x0f,0xa7,0xd0 \n\t" "movl %1, %%ebx \n\t" : "=m" (ebx) : "m" (ebx), "m" (count), "m" (ctrl), "m" (rk), "m" (input), "m" (output), "m" (iw) : "memory", "eax", "ecx", "edx", "esi", "edi"); memcpy(iv, iw, 16); return 0; } #endif /* MBEDTLS_CIPHER_MODE_CBC */ #endif /* MBEDTLS_VIA_PADLOCK_HAVE_CODE */ #endif /* MBEDTLS_PADLOCK_C */ keyring/src/keyring_macos.c0000644000176200001440000004571615006352625015530 0ustar liggesusers #ifdef __APPLE__ #include #include #include #include #include #include #include void keyring_macos_error(const char *func, OSStatus status) { CFStringRef str = SecCopyErrorMessageString(status, NULL); CFIndex length = CFStringGetLength(str); CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char *buffer = R_alloc(maxSize, 1); if (CFStringGetCString(str, buffer, maxSize, kCFStringEncodingUTF8)) { error("keyring error (macOS Keychain), %s: %s", func, buffer); } else { error("keyring error (macOS Keychain), %s", func); } } void keyring_macos_handle_status(const char *func, OSStatus status) { if (status != errSecSuccess) keyring_macos_error(func, status); } SecKeychainRef keyring_macos_open_keychain(const char *pathName) { SecKeychainRef keychain; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainOpen(pathName, &keychain); # pragma GCC diagnostic pop keyring_macos_handle_status("cannot open keychain", status); /* We need to query the status, because SecKeychainOpen succeeds, even if the keychain file does not exists. (!) */ SecKeychainStatus keychainStatus = 0; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainGetStatus(keychain, &keychainStatus); # pragma GCC diagnostic pop keyring_macos_handle_status("cannot open keychain", status); return keychain; } SEXP keyring_macos_get(SEXP keyring, SEXP service, SEXP username) { const char* empty = ""; const char* cservice = CHAR(STRING_ELT(service, 0)); const char* cusername = isNull(username) ? empty :CHAR(STRING_ELT(username, 0)); void *data; UInt32 length; SEXP result; SecKeychainRef keychain = isNull(keyring) ? NULL : keyring_macos_open_keychain(CHAR(STRING_ELT(keyring, 0))); # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainFindGenericPassword( keychain, (UInt32) strlen(cservice), cservice, (UInt32) strlen(cusername), cusername, &length, &data, /* itemRef = */ NULL); # pragma GCC diagnostic pop if (keychain != NULL) CFRelease(keychain); keyring_macos_handle_status("cannot get password", status); result = PROTECT(allocVector(RAWSXP, length)); memcpy(RAW(result), data, length); # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" SecKeychainItemFreeContent(NULL, data); # pragma GCC diagnostic pop UNPROTECT(1); return result; } SEXP keyring_macos_set(SEXP keyring, SEXP service, SEXP username, SEXP password) { const char* empty = ""; const char* cservice = CHAR(STRING_ELT(service, 0)); const char* cusername = isNull(username) ? empty : CHAR(STRING_ELT(username, 0)); SecKeychainItemRef item; SecKeychainRef keychain = isNull(keyring) ? NULL : keyring_macos_open_keychain(CHAR(STRING_ELT(keyring, 0))); /* Try to find it, and it is exists, update it */ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainFindGenericPassword( keychain, (UInt32) strlen(cservice), cservice, (UInt32) strlen(cusername), cusername, /* passwordLength = */ NULL, /* passwordData = */ NULL, &item); # pragma GCC diagnostic pop if (status == errSecItemNotFound) { # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainAddGenericPassword( keychain, (UInt32) strlen(cservice), cservice, (UInt32) strlen(cusername), cusername, (UInt32) LENGTH(password), RAW(password), /* itemRef = */ NULL); # pragma GCC diagnostic pop } else { # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainItemModifyAttributesAndData( item, /* attrList= */ NULL, (UInt32) LENGTH(password), RAW(password)); # pragma GCC diagnostic pop CFRelease(item); } if (keychain != NULL) CFRelease(keychain); keyring_macos_handle_status("cannot set password", status); return R_NilValue; } SEXP keyring_macos_delete(SEXP keyring, SEXP service, SEXP username) { const char* empty = ""; const char* cservice = CHAR(STRING_ELT(service, 0)); const char* cusername = isNull(username) ? empty : CHAR(STRING_ELT(username, 0)); SecKeychainRef keychain = isNull(keyring) ? NULL : keyring_macos_open_keychain(CHAR(STRING_ELT(keyring, 0))); SecKeychainItemRef item; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainFindGenericPassword( keychain, (UInt32) strlen(cservice), cservice, (UInt32) strlen(cusername), cusername, /* *passwordLength = */ NULL, /* *passwordData = */ NULL, &item); # pragma GCC diagnostic pop if (status != errSecSuccess) { if (keychain != NULL) CFRelease(keychain); keyring_macos_error("cannot delete password", status); } # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainItemDelete(item); # pragma GCC diagnostic pop if (status != errSecSuccess) { if (keychain != NULL) CFRelease(keychain); keyring_macos_error("cannot delete password", status); } if (keychain != NULL) CFRelease(keychain); CFRelease(item); return R_NilValue; } static void keyring_macos_list_item(SecKeychainItemRef item, SEXP result, int idx) { SecItemClass class; SecKeychainAttribute attrs[] = { { kSecServiceItemAttr }, { kSecAccountItemAttr } }; SecKeychainAttributeList attrList = { 2, attrs }; /* This should not happen, not a keychain... */ # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" if (SecKeychainItemGetTypeID() != CFGetTypeID(item)) { SET_STRING_ELT(VECTOR_ELT(result, 0), idx, mkChar("")); SET_STRING_ELT(VECTOR_ELT(result, 1), idx, mkChar("")); return; } # pragma GCC diagnostic pop # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainItemCopyContent(item, &class, &attrList, /* length = */ NULL, /* outData = */ NULL); # pragma GCC diagnostic pop keyring_macos_handle_status("cannot list passwords", status); SET_VECTOR_ELT(VECTOR_ELT(result, 2), idx, Rf_allocVector(RAWSXP, attrs[0].length)); memcpy( RAW(VECTOR_ELT(VECTOR_ELT(result, 2), idx)), attrs[0].data, attrs[0].length ); if (memchr(attrs[0].data, '\0', attrs[0].length) == NULL) { SET_STRING_ELT(VECTOR_ELT(result, 0), idx, mkCharLen(attrs[0].data, attrs[0].length)); } else { SET_STRING_ELT(VECTOR_ELT(result, 0), idx, NA_STRING); } SET_VECTOR_ELT(VECTOR_ELT(result, 3), idx, Rf_allocVector(RAWSXP, attrs[1].length)); memcpy( RAW(VECTOR_ELT(VECTOR_ELT(result, 3), idx)), attrs[1].data, attrs[1].length ); if (memchr(attrs[0].data, '\0', attrs[0].length) == NULL) { SET_STRING_ELT(VECTOR_ELT(result, 1), idx, mkCharLen(attrs[1].data, attrs[1].length)); } else { SET_STRING_ELT(VECTOR_ELT(result, 1), idx, NA_STRING); } # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" SecKeychainItemFreeContent(&attrList, NULL); # pragma GCC diagnostic pop } CFArrayRef keyring_macos_list_get(const char *ckeyring, const char *cservice) { CFStringRef cfservice = NULL; CFMutableDictionaryRef query = CFDictionaryCreateMutable( kCFAllocatorDefault, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionarySetValue(query, kSecMatchLimit, kSecMatchLimitAll); CFDictionarySetValue(query, kSecReturnData, kCFBooleanFalse); CFDictionarySetValue(query, kSecReturnRef, kCFBooleanTrue); CFDictionarySetValue(query, kSecClass, kSecClassGenericPassword); CFArrayRef searchList = NULL; if (ckeyring) { SecKeychainRef keychain = keyring_macos_open_keychain(ckeyring); searchList = CFArrayCreate(NULL, (const void **) &keychain, 1, &kCFTypeArrayCallBacks); CFDictionaryAddValue(query, kSecMatchSearchList, searchList); } if (cservice) { cfservice = CFStringCreateWithBytes( /* alloc = */ NULL, (const UInt8*) cservice, strlen(cservice), kCFStringEncodingUTF8, /* isExternalRepresentation = */ 0); CFDictionaryAddValue(query, kSecAttrService, cfservice); } CFArrayRef resArray = NULL; OSStatus status = SecItemCopyMatching(query, (CFTypeRef*) &resArray); CFRelease(query); if (cfservice != NULL) CFRelease(cfservice); if (searchList != NULL) CFRelease(searchList); /* If there are no elements in the keychain, then SecItemCopyMatching returns with an error, so we need work around that and return an empty list instead. */ if (status == errSecItemNotFound) { resArray = CFArrayCreate(NULL, NULL, 0, NULL); return resArray; } else if (status != errSecSuccess) { if (resArray != NULL) CFRelease(resArray); keyring_macos_handle_status("cannot list passwords", status); return NULL; } else { return resArray; } } SEXP keyring_macos_list(SEXP keyring, SEXP service) { const char *ckeyring = isNull(keyring) ? NULL : CHAR(STRING_ELT(keyring, 0)); const char *cservice = isNull(service) ? NULL : CHAR(STRING_ELT(service, 0)); CFArrayRef resArray = keyring_macos_list_get(ckeyring, cservice); CFIndex i, num = CFArrayGetCount(resArray); SEXP result; PROTECT(result = allocVector(VECSXP, 4)); SET_VECTOR_ELT(result, 0, allocVector(STRSXP, num)); SET_VECTOR_ELT(result, 1, allocVector(STRSXP, num)); SET_VECTOR_ELT(result, 2, allocVector(VECSXP, num)); SET_VECTOR_ELT(result, 3, allocVector(VECSXP, num)); for (i = 0; i < num; i++) { SecKeychainItemRef item = (SecKeychainItemRef) CFArrayGetValueAtIndex(resArray, i); keyring_macos_list_item(item, result, (int) i); } CFRelease(resArray); UNPROTECT(1); return result; } SEXP keyring_macos_create(SEXP keyring, SEXP password) { const char *ckeyring = CHAR(STRING_ELT(keyring, 0)); const char *cpassword = CHAR(STRING_ELT(password, 0)); SecKeychainRef result = NULL; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainCreate( ckeyring, /* passwordLength = */ (UInt32) strlen(cpassword), (const void*) cpassword, /* promptUser = */ 0, /* initialAccess = */ NULL, &result); # pragma GCC diagnostic pop keyring_macos_handle_status("cannot create keychain", status); CFArrayRef keyrings = NULL; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainCopyDomainSearchList( kSecPreferencesDomainUser, &keyrings); # pragma GCC diagnostic pop if (status) { # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" SecKeychainDelete(result); # pragma GCC diagnostic pop if (result != NULL) CFRelease(result); keyring_macos_handle_status("cannot create keychain", status); } /* We need to add the new keychain to the keychain search list, otherwise applications like Keychain Access will not see it. There is no API to append it, we need to query the current search list, add it, and then set the whole new search list. This is of course a race condition. :/ */ CFIndex count = CFArrayGetCount(keyrings); CFMutableArrayRef newkeyrings = CFArrayCreateMutableCopy(NULL, count + 1, keyrings); CFArrayAppendValue(newkeyrings, result); # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainSetDomainSearchList( kSecPreferencesDomainUser, newkeyrings); # pragma GCC diagnostic pop if (status) { # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" SecKeychainDelete(result); # pragma GCC diagnostic pop if (result) CFRelease(result); if (keyrings) CFRelease(keyrings); if (newkeyrings) CFRelease(newkeyrings); keyring_macos_handle_status("cannot create keychain", status); } CFRelease(result); CFRelease(keyrings); CFRelease(newkeyrings); return R_NilValue; } SEXP keyring_macos_list_keyring(void) { CFArrayRef keyrings = NULL; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainCopyDomainSearchList(kSecPreferencesDomainUser, &keyrings); # pragma GCC diagnostic pop keyring_macos_handle_status("cannot list keyrings", status); CFIndex i, num = CFArrayGetCount(keyrings); SEXP result = PROTECT(allocVector(VECSXP, 3)); SET_VECTOR_ELT(result, 0, allocVector(STRSXP, num)); SET_VECTOR_ELT(result, 1, allocVector(INTSXP, num)); SET_VECTOR_ELT(result, 2, allocVector(LGLSXP, num)); for (i = 0; i < num; i++) { SecKeychainRef keychain = (SecKeychainRef) CFArrayGetValueAtIndex(keyrings, i); UInt32 pathLength = MAXPATHLEN; char pathName[MAXPATHLEN + 1]; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainGetPath(keychain, &pathLength, pathName); # pragma GCC diagnostic pop pathName[pathLength] = '\0'; if (status) { CFRelease(keyrings); keyring_macos_handle_status("cannot list keyrings", status); } SET_STRING_ELT(VECTOR_ELT(result, 0), i, mkCharLen(pathName, pathLength)); CFArrayRef resArray = keyring_macos_list_get(pathName, /* cservice = */ NULL); CFIndex numitems = CFArrayGetCount(resArray); CFRelease(resArray); INTEGER(VECTOR_ELT(result, 1))[i] = (int) numitems; SecKeychainStatus kstatus; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainGetStatus(keychain, &kstatus); # pragma GCC diagnostic pop if (status) { LOGICAL(VECTOR_ELT(result, 2))[i] = NA_LOGICAL; } else { LOGICAL(VECTOR_ELT(result, 2))[i] = ! (kstatus & kSecUnlockStateStatus); } } CFRelease(keyrings); UNPROTECT(1); return result; } SEXP keyring_macos_delete_keyring(SEXP keyring) { const char *ckeyring = CHAR(STRING_ELT(keyring, 0)); /* Need to remove it from the search list as well */ CFArrayRef keyrings = NULL; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainCopyDomainSearchList( kSecPreferencesDomainUser, &keyrings); # pragma GCC diagnostic pop keyring_macos_handle_status("cannot delete keyring", status); CFIndex i, count = CFArrayGetCount(keyrings); CFMutableArrayRef newkeyrings = CFArrayCreateMutableCopy(NULL, count, keyrings); for (i = 0; i < count; i++) { SecKeychainRef item = (SecKeychainRef) CFArrayGetValueAtIndex(keyrings, i); UInt32 pathLength = MAXPATHLEN; char pathName[MAXPATHLEN + 1]; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainGetPath(item, &pathLength, pathName); # pragma GCC diagnostic pop pathName[pathLength] = '\0'; if (status) { CFRelease(keyrings); CFRelease(newkeyrings); keyring_macos_handle_status("cannot delete keyring", status); } if (!strcmp(pathName, ckeyring)) { CFArrayRemoveValueAtIndex(newkeyrings, (CFIndex) i); # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainSetDomainSearchList( kSecPreferencesDomainUser, newkeyrings); # pragma GCC diagnostic pop if (status) { CFRelease(keyrings); CFRelease(newkeyrings); keyring_macos_handle_status("cannot delete keyring", status); } } } /* If we haven't found it on the search list, then we just keep silent about it ... */ CFRelease(keyrings); CFRelease(newkeyrings); /* And now remove the file as well... */ SecKeychainRef keychain = keyring_macos_open_keychain(ckeyring); # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" status = SecKeychainDelete(keychain); # pragma GCC diagnostic pop CFRelease(keychain); keyring_macos_handle_status("cannot delete keyring", status); return R_NilValue; } SEXP keyring_macos_lock_keyring(SEXP keyring) { SecKeychainRef keychain = isNull(keyring) ? NULL : keyring_macos_open_keychain(CHAR(STRING_ELT(keyring, 0))); # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainLock(keychain); # pragma GCC diagnostic pop if (keychain) CFRelease(keychain); keyring_macos_handle_status("cannot lock keychain", status); return R_NilValue; } SEXP keyring_macos_unlock_keyring(SEXP keyring, SEXP password) { const char *cpassword = CHAR(STRING_ELT(password, 0)); SecKeychainRef keychain = isNull(keyring) ? NULL : keyring_macos_open_keychain(CHAR(STRING_ELT(keyring, 0))); # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainUnlock( keychain, (UInt32) strlen(cpassword), (const void*) cpassword, /* usePassword = */ TRUE); # pragma GCC diagnostic pop if (keychain) CFRelease(keychain); keyring_macos_handle_status("cannot unlock keychain", status); return R_NilValue; } SEXP keyring_macos_is_locked_keyring(SEXP keyring) { SecKeychainRef keychain = isNull(keyring) ? NULL : keyring_macos_open_keychain(CHAR(STRING_ELT(keyring, 0))); SecKeychainStatus kstatus; # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wdeprecated-declarations" OSStatus status = SecKeychainGetStatus(keychain, &kstatus); # pragma GCC diagnostic pop if (status) keyring_macos_error("cannot get lock information", status); return ScalarLogical(! (kstatus & kSecUnlockStateStatus)); } #else #include #include #include SEXP keyring_macos_get(SEXP keyring, SEXP service, SEXP username) { error("only works on macOS"); return R_NilValue; } SEXP keyring_macos_set(SEXP keyring, SEXP service, SEXP username, SEXP password) { error("only works on macOS"); return R_NilValue; } SEXP keyring_macos_delete(SEXP keyring, SEXP service, SEXP username) { error("only works on macOS"); return R_NilValue; } SEXP keyring_macos_list(SEXP keyring, SEXP service) { error("only works on macOS"); return R_NilValue; } SEXP keyring_macos_create(SEXP keyring, SEXP password) { error("only works on macOS"); return R_NilValue; } SEXP keyring_macos_list_keyring(void) { error("only works on macOS"); return R_NilValue; } SEXP keyring_macos_delete_keyring(SEXP keyring) { error("only works on macOS"); return R_NilValue; } SEXP keyring_macos_lock_keyring(SEXP keyring) { error("only works on macOS"); return R_NilValue; } SEXP keyring_macos_unlock_keyring(SEXP keyring, SEXP password) { error("only works on macOS"); return R_NilValue; } SEXP keyring_macos_is_locked_keyring(SEXP keyring) { error("only works on macOS"); return R_NilValue; } #endif // __APPLE__ keyring/src/crypto_verify_16.h0000644000176200001440000000064314775227066016117 0ustar liggesusers#ifndef crypto_verify_16_H #define crypto_verify_16_H #include #include "sodium.h" #ifdef __cplusplus extern "C" { #endif #define crypto_verify_16_BYTES 16U SODIUM_EXPORT size_t crypto_verify_16_bytes(void); SODIUM_EXPORT int crypto_verify_16(const unsigned char *x, const unsigned char *y) __attribute__ ((warn_unused_result)) __attribute__ ((nonnull)); #ifdef __cplusplus } #endif #endif keyring/src/poly1305_donna32.h0000644000176200001440000001505014775227066015523 0ustar liggesusers/* poly1305 implementation using 32 bit * 32 bit = 64 bit multiplication and 64 bit addition */ #if defined(_MSC_VER) # define POLY1305_NOINLINE __declspec(noinline) #elif defined(__clang__) || defined(__GNUC__) # define POLY1305_NOINLINE __attribute__((noinline)) #else # define POLY1305_NOINLINE #endif #define poly1305_block_size 16 /* 17 + sizeof(unsigned long long) + 14*sizeof(unsigned long) */ typedef struct poly1305_state_internal_t { unsigned long r[5]; unsigned long h[5]; unsigned long pad[4]; unsigned long long leftover; unsigned char buffer[poly1305_block_size]; unsigned char final; } poly1305_state_internal_t; static void poly1305_init(poly1305_state_internal_t *st, const unsigned char key[32]) { /* r &= 0xffffffc0ffffffc0ffffffc0fffffff - wiped after finalization */ st->r[0] = (LOAD32_LE(&key[0])) & 0x3ffffff; st->r[1] = (LOAD32_LE(&key[3]) >> 2) & 0x3ffff03; st->r[2] = (LOAD32_LE(&key[6]) >> 4) & 0x3ffc0ff; st->r[3] = (LOAD32_LE(&key[9]) >> 6) & 0x3f03fff; st->r[4] = (LOAD32_LE(&key[12]) >> 8) & 0x00fffff; /* h = 0 */ st->h[0] = 0; st->h[1] = 0; st->h[2] = 0; st->h[3] = 0; st->h[4] = 0; /* save pad for later */ st->pad[0] = LOAD32_LE(&key[16]); st->pad[1] = LOAD32_LE(&key[20]); st->pad[2] = LOAD32_LE(&key[24]); st->pad[3] = LOAD32_LE(&key[28]); st->leftover = 0; st->final = 0; } static void poly1305_blocks(poly1305_state_internal_t *st, const unsigned char *m, unsigned long long bytes) { const unsigned long hibit = (st->final) ? 0UL : (1UL << 24); /* 1 << 128 */ unsigned long r0, r1, r2, r3, r4; unsigned long s1, s2, s3, s4; unsigned long h0, h1, h2, h3, h4; unsigned long long d0, d1, d2, d3, d4; unsigned long c; r0 = st->r[0]; r1 = st->r[1]; r2 = st->r[2]; r3 = st->r[3]; r4 = st->r[4]; s1 = r1 * 5; s2 = r2 * 5; s3 = r3 * 5; s4 = r4 * 5; h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; h3 = st->h[3]; h4 = st->h[4]; while (bytes >= poly1305_block_size) { /* h += m[i] */ h0 += (LOAD32_LE(m + 0)) & 0x3ffffff; h1 += (LOAD32_LE(m + 3) >> 2) & 0x3ffffff; h2 += (LOAD32_LE(m + 6) >> 4) & 0x3ffffff; h3 += (LOAD32_LE(m + 9) >> 6) & 0x3ffffff; h4 += (LOAD32_LE(m + 12) >> 8) | hibit; /* h *= r */ d0 = ((unsigned long long) h0 * r0) + ((unsigned long long) h1 * s4) + ((unsigned long long) h2 * s3) + ((unsigned long long) h3 * s2) + ((unsigned long long) h4 * s1); d1 = ((unsigned long long) h0 * r1) + ((unsigned long long) h1 * r0) + ((unsigned long long) h2 * s4) + ((unsigned long long) h3 * s3) + ((unsigned long long) h4 * s2); d2 = ((unsigned long long) h0 * r2) + ((unsigned long long) h1 * r1) + ((unsigned long long) h2 * r0) + ((unsigned long long) h3 * s4) + ((unsigned long long) h4 * s3); d3 = ((unsigned long long) h0 * r3) + ((unsigned long long) h1 * r2) + ((unsigned long long) h2 * r1) + ((unsigned long long) h3 * r0) + ((unsigned long long) h4 * s4); d4 = ((unsigned long long) h0 * r4) + ((unsigned long long) h1 * r3) + ((unsigned long long) h2 * r2) + ((unsigned long long) h3 * r1) + ((unsigned long long) h4 * r0); /* (partial) h %= p */ c = (unsigned long) (d0 >> 26); h0 = (unsigned long) d0 & 0x3ffffff; d1 += c; c = (unsigned long) (d1 >> 26); h1 = (unsigned long) d1 & 0x3ffffff; d2 += c; c = (unsigned long) (d2 >> 26); h2 = (unsigned long) d2 & 0x3ffffff; d3 += c; c = (unsigned long) (d3 >> 26); h3 = (unsigned long) d3 & 0x3ffffff; d4 += c; c = (unsigned long) (d4 >> 26); h4 = (unsigned long) d4 & 0x3ffffff; h0 += c * 5; c = (h0 >> 26); h0 &= 0x3ffffff; h1 += c; m += poly1305_block_size; bytes -= poly1305_block_size; } st->h[0] = h0; st->h[1] = h1; st->h[2] = h2; st->h[3] = h3; st->h[4] = h4; } static POLY1305_NOINLINE void poly1305_finish(poly1305_state_internal_t *st, unsigned char mac[16]) { unsigned long h0, h1, h2, h3, h4, c; unsigned long g0, g1, g2, g3, g4; unsigned long long f; unsigned long mask; /* process the remaining block */ if (st->leftover) { unsigned long long i = st->leftover; st->buffer[i++] = 1; for (; i < poly1305_block_size; i++) { st->buffer[i] = 0; } st->final = 1; poly1305_blocks(st, st->buffer, poly1305_block_size); } /* fully carry h */ h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; h3 = st->h[3]; h4 = st->h[4]; c = h1 >> 26; h1 = h1 & 0x3ffffff; h2 += c; c = h2 >> 26; h2 = h2 & 0x3ffffff; h3 += c; c = h3 >> 26; h3 = h3 & 0x3ffffff; h4 += c; c = h4 >> 26; h4 = h4 & 0x3ffffff; h0 += c * 5; c = h0 >> 26; h0 = h0 & 0x3ffffff; h1 += c; /* compute h + -p */ g0 = h0 + 5; c = g0 >> 26; g0 &= 0x3ffffff; g1 = h1 + c; c = g1 >> 26; g1 &= 0x3ffffff; g2 = h2 + c; c = g2 >> 26; g2 &= 0x3ffffff; g3 = h3 + c; c = g3 >> 26; g3 &= 0x3ffffff; g4 = h4 + c - (1UL << 26); /* select h if h < p, or h + -p if h >= p */ mask = (g4 >> ((sizeof(unsigned long) * 8) - 1)) - 1; g0 &= mask; g1 &= mask; g2 &= mask; g3 &= mask; g4 &= mask; mask = ~mask; h0 = (h0 & mask) | g0; h1 = (h1 & mask) | g1; h2 = (h2 & mask) | g2; h3 = (h3 & mask) | g3; h4 = (h4 & mask) | g4; /* h = h % (2^128) */ h0 = ((h0) | (h1 << 26)) & 0xffffffff; h1 = ((h1 >> 6) | (h2 << 20)) & 0xffffffff; h2 = ((h2 >> 12) | (h3 << 14)) & 0xffffffff; h3 = ((h3 >> 18) | (h4 << 8)) & 0xffffffff; /* mac = (h + pad) % (2^128) */ f = (unsigned long long) h0 + st->pad[0]; h0 = (unsigned long) f; f = (unsigned long long) h1 + st->pad[1] + (f >> 32); h1 = (unsigned long) f; f = (unsigned long long) h2 + st->pad[2] + (f >> 32); h2 = (unsigned long) f; f = (unsigned long long) h3 + st->pad[3] + (f >> 32); h3 = (unsigned long) f; STORE32_LE(mac + 0, (uint32_t) h0); STORE32_LE(mac + 4, (uint32_t) h1); STORE32_LE(mac + 8, (uint32_t) h2); STORE32_LE(mac + 12, (uint32_t) h3); /* zero out the state */ sodium_memzero((void *) st, sizeof *st); } keyring/src/crypto_onetimeauth.h0000644000176200001440000000357014775227066016631 0ustar liggesusers#ifndef crypto_onetimeauth_H #define crypto_onetimeauth_H #include #include "crypto_onetimeauth_poly1305.h" #include "export.h" #ifdef __cplusplus # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wlong-long" # endif extern "C" { #endif typedef crypto_onetimeauth_poly1305_state crypto_onetimeauth_state; SODIUM_EXPORT size_t crypto_onetimeauth_statebytes(void); #define crypto_onetimeauth_BYTES crypto_onetimeauth_poly1305_BYTES SODIUM_EXPORT size_t crypto_onetimeauth_bytes(void); #define crypto_onetimeauth_KEYBYTES crypto_onetimeauth_poly1305_KEYBYTES SODIUM_EXPORT size_t crypto_onetimeauth_keybytes(void); #define crypto_onetimeauth_PRIMITIVE "poly1305" SODIUM_EXPORT const char *crypto_onetimeauth_primitive(void); SODIUM_EXPORT int crypto_onetimeauth(unsigned char *out, const unsigned char *in, unsigned long long inlen, const unsigned char *k) __attribute__ ((nonnull(1, 4))); SODIUM_EXPORT int crypto_onetimeauth_verify(const unsigned char *h, const unsigned char *in, unsigned long long inlen, const unsigned char *k) __attribute__ ((warn_unused_result)) __attribute__ ((nonnull(1, 4))); SODIUM_EXPORT int crypto_onetimeauth_init(crypto_onetimeauth_state *state, const unsigned char *key) __attribute__ ((nonnull)); SODIUM_EXPORT int crypto_onetimeauth_update(crypto_onetimeauth_state *state, const unsigned char *in, unsigned long long inlen) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_onetimeauth_final(crypto_onetimeauth_state *state, unsigned char *out) __attribute__ ((nonnull)); SODIUM_EXPORT void crypto_onetimeauth_keygen(unsigned char k[crypto_onetimeauth_KEYBYTES]) __attribute__ ((nonnull)); #ifdef __cplusplus } #endif #endif keyring/src/raes.c0000644000176200001440000000423615022010144013601 0ustar liggesusers#include #include #include "mbedtls/private_access.h" #include "mbedtls/aes.h" // silence mbedtls functions int mbedtls_printf_(const char *format, ...) { return 0; } int (*mbedtls_printf)(const char *format, ...) = mbedtls_printf_; SEXP keyring_aes_cbc(SEXP msg, SEXP key, SEXP iv, int decrypt) { if (Rf_length(key) != 32) { Rf_error("Invalid 'key', must have 32 bytes"); } if (Rf_length(iv) != 16) { Rf_error("Invalid 'iv', must have 16 bytes"); } const unsigned char *ckey = (const unsigned char*) RAW(key); unsigned char civ[16]; memcpy(civ, RAW(iv), sizeof(civ)); size_t msglen = Rf_length(msg); int rem = msglen % 16; if (decrypt && rem != 0) { Rf_error("Invalid message length, must be multiple of 16"); } int padlen = decrypt ? 0 : 16 - rem; size_t paddedlen = msglen + padlen; SEXP input = PROTECT(Rf_allocVector(RAWSXP, paddedlen)); SEXP output = PROTECT(Rf_allocVector(RAWSXP, paddedlen)); memcpy(RAW(input), RAW(msg), msglen); if (padlen > 0) { memset(RAW(input) + msglen, padlen, padlen); } mbedtls_aes_context aes; mbedtls_aes_init(&aes); int ret; if (decrypt) { ret = mbedtls_aes_setkey_dec(&aes, ckey, 256); } else { ret = mbedtls_aes_setkey_enc(&aes, ckey, 256); } if (ret) { Rf_error("'mbedtls_aes_setkey_enc' failure, internal keyring error"); } ret = mbedtls_aes_crypt_cbc( &aes, decrypt ? MBEDTLS_AES_DECRYPT : MBEDTLS_AES_ENCRYPT, paddedlen, civ, RAW(input), RAW(output) ); if (ret) { Rf_error("'mbedtls_aes_crypt_cbc' failure, internal keyring error"); } if (decrypt) { padlen = RAW(output)[msglen - 1]; if (padlen == 0 || padlen > 16 || padlen > msglen) { Rf_error("Cannot decrypt AES CBC, probably wrong key?"); } output = PROTECT(Rf_lengthgets(output, msglen - padlen)); UNPROTECT(3); return output; } else { UNPROTECT(2); return output; } } SEXP keyring_aes_cbc_encrypt(SEXP msg, SEXP key, SEXP iv) { return keyring_aes_cbc(msg, key, iv, /* decrypt= */ 0); } SEXP keyring_aes_cbc_decrypt(SEXP msg, SEXP key, SEXP iv) { return keyring_aes_cbc(msg, key, iv, /* decrypt= */ 1); } keyring/src/aesce.c0000644000176200001440000004765215006370264013756 0ustar liggesusers/* * Armv8-A Cryptographic Extension support functions for Aarch64 * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #if defined(__clang__) && (__clang_major__ >= 4) /* Ideally, we would simply use MBEDTLS_ARCH_IS_ARMV8_A in the following #if, * but that is defined by build_info.h, and we need this block to happen first. */ #if defined(__ARM_ARCH) #if __ARM_ARCH >= 8 #define MBEDTLS_AESCE_ARCH_IS_ARMV8_A #endif #endif #if defined(MBEDTLS_AESCE_ARCH_IS_ARMV8_A) && !defined(__ARM_FEATURE_CRYPTO) /* TODO: Re-consider above after https://reviews.llvm.org/D131064 merged. * * The intrinsic declaration are guarded by predefined ACLE macros in clang: * these are normally only enabled by the -march option on the command line. * By defining the macros ourselves we gain access to those declarations without * requiring -march on the command line. * * `arm_neon.h` is included by common.h, so we put these defines * at the top of this file, before any includes. */ #define __ARM_FEATURE_CRYPTO 1 /* See: https://arm-software.github.io/acle/main/acle.html#cryptographic-extensions * * `__ARM_FEATURE_CRYPTO` is deprecated, but we need to continue to specify it * for older compilers. */ #define __ARM_FEATURE_AES 1 #define MBEDTLS_ENABLE_ARM_CRYPTO_EXTENSIONS_COMPILER_FLAG #endif #endif /* defined(__clang__) && (__clang_major__ >= 4) */ #include #include "common.h" #if defined(MBEDTLS_AESCE_C) #include "aesce.h" #if defined(MBEDTLS_AESCE_HAVE_CODE) /* Compiler version checks. */ #if defined(__clang__) # if defined(MBEDTLS_ARCH_IS_ARM32) && (__clang_major__ < 11) # error "Minimum version of Clang for MBEDTLS_AESCE_C on 32-bit Arm or Thumb is 11.0." # elif defined(MBEDTLS_ARCH_IS_ARM64) && (__clang_major__ < 4) # error "Minimum version of Clang for MBEDTLS_AESCE_C on aarch64 is 4.0." # endif #elif defined(__GNUC__) # if __GNUC__ < 6 # error "Minimum version of GCC for MBEDTLS_AESCE_C is 6.0." # endif #elif defined(_MSC_VER) /* TODO: We haven't verified MSVC from 1920 to 1928. If someone verified that, * please update this and document of `MBEDTLS_AESCE_C` in * `mbedtls_config.h`. */ # if _MSC_VER < 1929 # error "Minimum version of MSVC for MBEDTLS_AESCE_C is 2019 version 16.11.2." # endif #elif defined(__ARMCC_VERSION) # if defined(MBEDTLS_ARCH_IS_ARM32) && (__ARMCC_VERSION < 6200002) /* TODO: We haven't verified armclang for 32-bit Arm/Thumb prior to 6.20. * If someone verified that, please update this and document of * `MBEDTLS_AESCE_C` in `mbedtls_config.h`. */ # error "Minimum version of armclang for MBEDTLS_AESCE_C on 32-bit Arm is 6.20." # elif defined(MBEDTLS_ARCH_IS_ARM64) && (__ARMCC_VERSION < 6060000) # error "Minimum version of armclang for MBEDTLS_AESCE_C on aarch64 is 6.6." # endif #endif #if !(defined(__ARM_FEATURE_CRYPTO) || defined(__ARM_FEATURE_AES)) || \ defined(MBEDTLS_ENABLE_ARM_CRYPTO_EXTENSIONS_COMPILER_FLAG) # if defined(__ARMCOMPILER_VERSION) # if __ARMCOMPILER_VERSION <= 6090000 # error "Must use minimum -march=armv8-a+crypto for MBEDTLS_AESCE_C" # else # pragma clang attribute push (__attribute__((target("aes"))), apply_to=function) # define MBEDTLS_POP_TARGET_PRAGMA # endif # elif defined(__clang__) # pragma clang attribute push (__attribute__((target("aes"))), apply_to=function) # define MBEDTLS_POP_TARGET_PRAGMA # elif defined(__GNUC__) # pragma GCC push_options # pragma GCC target ("+crypto") # define MBEDTLS_POP_TARGET_PRAGMA # elif defined(_MSC_VER) # error "Required feature(__ARM_FEATURE_AES) is not enabled." # endif #endif /* !(__ARM_FEATURE_CRYPTO || __ARM_FEATURE_AES) || MBEDTLS_ENABLE_ARM_CRYPTO_EXTENSIONS_COMPILER_FLAG */ #if defined(__linux__) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) #include #if !defined(HWCAP_NEON) #define HWCAP_NEON (1 << 12) #endif #if !defined(HWCAP2_AES) #define HWCAP2_AES (1 << 0) #endif #if !defined(HWCAP_AES) #define HWCAP_AES (1 << 3) #endif #if !defined(HWCAP_ASIMD) #define HWCAP_ASIMD (1 << 1) #endif signed char mbedtls_aesce_has_support_result = -1; #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) /* * AES instruction support detection routine */ int mbedtls_aesce_has_support_impl(void) { /* To avoid many calls to getauxval, cache the result. This is * thread-safe, because we store the result in a char so cannot * be vulnerable to non-atomic updates. * It is possible that we could end up setting result more than * once, but that is harmless. */ if (mbedtls_aesce_has_support_result == -1) { #if defined(MBEDTLS_ARCH_IS_ARM32) unsigned long auxval = getauxval(AT_HWCAP); unsigned long auxval2 = getauxval(AT_HWCAP2); if (((auxval & HWCAP_NEON) == HWCAP_NEON) && ((auxval2 & HWCAP2_AES) == HWCAP2_AES)) { mbedtls_aesce_has_support_result = 1; } else { mbedtls_aesce_has_support_result = 0; } #else unsigned long auxval = getauxval(AT_HWCAP); if ((auxval & (HWCAP_ASIMD | HWCAP_AES)) == (HWCAP_ASIMD | HWCAP_AES)) { mbedtls_aesce_has_support_result = 1; } else { mbedtls_aesce_has_support_result = 0; } #endif } return mbedtls_aesce_has_support_result; } #endif #endif /* defined(__linux__) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) */ /* Single round of AESCE encryption */ #define AESCE_ENCRYPT_ROUND \ block = vaeseq_u8(block, vld1q_u8(keys)); \ block = vaesmcq_u8(block); \ keys += 16 /* Two rounds of AESCE encryption */ #define AESCE_ENCRYPT_ROUND_X2 AESCE_ENCRYPT_ROUND; AESCE_ENCRYPT_ROUND MBEDTLS_OPTIMIZE_FOR_PERFORMANCE static uint8x16_t aesce_encrypt_block(uint8x16_t block, unsigned char *keys, int rounds) { /* 10, 12 or 14 rounds. Unroll loop. */ if (rounds == 10) { goto rounds_10; } if (rounds == 12) { goto rounds_12; } AESCE_ENCRYPT_ROUND_X2; rounds_12: AESCE_ENCRYPT_ROUND_X2; rounds_10: AESCE_ENCRYPT_ROUND_X2; AESCE_ENCRYPT_ROUND_X2; AESCE_ENCRYPT_ROUND_X2; AESCE_ENCRYPT_ROUND_X2; AESCE_ENCRYPT_ROUND; /* AES AddRoundKey for the previous round. * SubBytes, ShiftRows for the final round. */ block = vaeseq_u8(block, vld1q_u8(keys)); keys += 16; /* Final round: no MixColumns */ /* Final AddRoundKey */ block = veorq_u8(block, vld1q_u8(keys)); return block; } /* Single round of AESCE decryption * * AES AddRoundKey, SubBytes, ShiftRows * * block = vaesdq_u8(block, vld1q_u8(keys)); * * AES inverse MixColumns for the next round. * * This means that we switch the order of the inverse AddRoundKey and * inverse MixColumns operations. We have to do this as AddRoundKey is * done in an atomic instruction together with the inverses of SubBytes * and ShiftRows. * * It works because MixColumns is a linear operation over GF(2^8) and * AddRoundKey is an exclusive or, which is equivalent to addition over * GF(2^8). (The inverse of MixColumns needs to be applied to the * affected round keys separately which has been done when the * decryption round keys were calculated.) * * block = vaesimcq_u8(block); */ #define AESCE_DECRYPT_ROUND \ block = vaesdq_u8(block, vld1q_u8(keys)); \ block = vaesimcq_u8(block); \ keys += 16 /* Two rounds of AESCE decryption */ #define AESCE_DECRYPT_ROUND_X2 AESCE_DECRYPT_ROUND; AESCE_DECRYPT_ROUND #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) static uint8x16_t aesce_decrypt_block(uint8x16_t block, unsigned char *keys, int rounds) { /* 10, 12 or 14 rounds. Unroll loop. */ if (rounds == 10) { goto rounds_10; } if (rounds == 12) { goto rounds_12; } AESCE_DECRYPT_ROUND_X2; rounds_12: AESCE_DECRYPT_ROUND_X2; rounds_10: AESCE_DECRYPT_ROUND_X2; AESCE_DECRYPT_ROUND_X2; AESCE_DECRYPT_ROUND_X2; AESCE_DECRYPT_ROUND_X2; AESCE_DECRYPT_ROUND; /* The inverses of AES AddRoundKey, SubBytes, ShiftRows finishing up the * last full round. */ block = vaesdq_u8(block, vld1q_u8(keys)); keys += 16; /* Inverse AddRoundKey for inverting the initial round key addition. */ block = veorq_u8(block, vld1q_u8(keys)); return block; } #endif /* * AES-ECB block en(de)cryption */ int mbedtls_aesce_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]) { uint8x16_t block = vld1q_u8(&input[0]); unsigned char *keys = (unsigned char *) (ctx->buf + ctx->rk_offset); #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) if (mode == MBEDTLS_AES_DECRYPT) { block = aesce_decrypt_block(block, keys, ctx->nr); } else #else (void) mode; #endif { block = aesce_encrypt_block(block, keys, ctx->nr); } vst1q_u8(&output[0], block); return 0; } /* * Compute decryption round keys from encryption round keys */ #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) void mbedtls_aesce_inverse_key(unsigned char *invkey, const unsigned char *fwdkey, int nr) { int i, j; j = nr; vst1q_u8(invkey, vld1q_u8(fwdkey + j * 16)); for (i = 1, j--; j > 0; i++, j--) { vst1q_u8(invkey + i * 16, vaesimcq_u8(vld1q_u8(fwdkey + j * 16))); } vst1q_u8(invkey + i * 16, vld1q_u8(fwdkey + j * 16)); } #endif static inline uint32_t aes_rot_word(uint32_t word) { return (word << (32 - 8)) | (word >> 8); } static inline uint32_t aes_sub_word(uint32_t in) { uint8x16_t v = vreinterpretq_u8_u32(vdupq_n_u32(in)); uint8x16_t zero = vdupq_n_u8(0); /* vaeseq_u8 does both SubBytes and ShiftRows. Taking the first row yields * the correct result as ShiftRows doesn't change the first row. */ v = vaeseq_u8(zero, v); return vgetq_lane_u32(vreinterpretq_u32_u8(v), 0); } /* * Key expansion function */ static void aesce_setkey_enc(unsigned char *rk, const unsigned char *key, const size_t key_bit_length) { static uint8_t const rcon[] = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 }; /* See https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.197.pdf * - Section 5, Nr = Nk + 6 * - Section 5.2, the length of round keys is Nb*(Nr+1) */ const size_t key_len_in_words = key_bit_length / 32; /* Nk */ const size_t round_key_len_in_words = 4; /* Nb */ const size_t rounds_needed = key_len_in_words + 6; /* Nr */ const size_t round_keys_len_in_words = round_key_len_in_words * (rounds_needed + 1); /* Nb*(Nr+1) */ const uint32_t *rko_end = (uint32_t *) rk + round_keys_len_in_words; memcpy(rk, key, key_len_in_words * 4); for (uint32_t *rki = (uint32_t *) rk; rki + key_len_in_words < rko_end; rki += key_len_in_words) { size_t iteration = (size_t) (rki - (uint32_t *) rk) / key_len_in_words; uint32_t *rko; rko = rki + key_len_in_words; rko[0] = aes_rot_word(aes_sub_word(rki[key_len_in_words - 1])); rko[0] ^= rcon[iteration] ^ rki[0]; rko[1] = rko[0] ^ rki[1]; rko[2] = rko[1] ^ rki[2]; rko[3] = rko[2] ^ rki[3]; if (rko + key_len_in_words > rko_end) { /* Do not write overflow words.*/ continue; } #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) switch (key_bit_length) { case 128: break; case 192: rko[4] = rko[3] ^ rki[4]; rko[5] = rko[4] ^ rki[5]; break; case 256: rko[4] = aes_sub_word(rko[3]) ^ rki[4]; rko[5] = rko[4] ^ rki[5]; rko[6] = rko[5] ^ rki[6]; rko[7] = rko[6] ^ rki[7]; break; } #endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */ } } /* * Key expansion, wrapper */ int mbedtls_aesce_setkey_enc(unsigned char *rk, const unsigned char *key, size_t bits) { switch (bits) { case 128: case 192: case 256: aesce_setkey_enc(rk, key, bits); break; default: return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH; } return 0; } #if defined(MBEDTLS_GCM_C) #if defined(MBEDTLS_ARCH_IS_ARM32) #if defined(__clang__) /* On clang for A32/T32, work around some missing intrinsics and types which are listed in * [ACLE](https://arm-software.github.io/acle/neon_intrinsics/advsimd.html#polynomial-1) * These are only required for GCM. */ #define vreinterpretq_u64_p64(a) ((uint64x2_t) a) typedef uint8x16_t poly128_t; static inline poly128_t vmull_p64(poly64_t a, poly64_t b) { poly128_t r; asm ("vmull.p64 %[r], %[a], %[b]" : [r] "=w" (r) : [a] "w" (a), [b] "w" (b) :); return r; } /* This is set to cause some more missing intrinsics to be defined below */ #define COMMON_MISSING_INTRINSICS static inline poly128_t vmull_high_p64(poly64x2_t a, poly64x2_t b) { return vmull_p64((poly64_t) (vget_high_u64((uint64x2_t) a)), (poly64_t) (vget_high_u64((uint64x2_t) b))); } #endif /* defined(__clang__) */ static inline uint8x16_t vrbitq_u8(uint8x16_t x) { /* There is no vrbitq_u8 instruction in A32/T32, so provide * an equivalent non-Neon implementation. Reverse bit order in each * byte with 4x rbit, rev. */ asm ("ldm %[p], { r2-r5 } \n\t" "rbit r2, r2 \n\t" "rev r2, r2 \n\t" "rbit r3, r3 \n\t" "rev r3, r3 \n\t" "rbit r4, r4 \n\t" "rev r4, r4 \n\t" "rbit r5, r5 \n\t" "rev r5, r5 \n\t" "stm %[p], { r2-r5 } \n\t" : /* Output: 16 bytes of memory pointed to by &x */ "+m" (*(uint8_t(*)[16]) &x) : [p] "r" (&x) : "r2", "r3", "r4", "r5" ); return x; } #endif /* defined(MBEDTLS_ARCH_IS_ARM32) */ #if defined(MBEDTLS_COMPILER_IS_GCC) && __GNUC__ == 5 /* Some intrinsics are not available for GCC 5.X. */ #define COMMON_MISSING_INTRINSICS #endif /* MBEDTLS_COMPILER_IS_GCC && __GNUC__ == 5 */ #if defined(COMMON_MISSING_INTRINSICS) /* Missing intrinsics common to both GCC 5, and Clang on 32-bit */ #define vreinterpretq_p64_u8(a) ((poly64x2_t) a) #define vreinterpretq_u8_p128(a) ((uint8x16_t) a) static inline poly64x1_t vget_low_p64(poly64x2_t a) { uint64x1_t r = vget_low_u64(vreinterpretq_u64_p64(a)); return (poly64x1_t) r; } #endif /* COMMON_MISSING_INTRINSICS */ /* vmull_p64/vmull_high_p64 wrappers. * * Older compilers miss some intrinsic functions for `poly*_t`. We use * uint8x16_t and uint8x16x3_t as input/output parameters. */ #if defined(MBEDTLS_COMPILER_IS_GCC) /* GCC reports incompatible type error without cast. GCC think poly64_t and * poly64x1_t are different, that is different with MSVC and Clang. */ #define MBEDTLS_VMULL_P64(a, b) vmull_p64((poly64_t) a, (poly64_t) b) #else /* MSVC reports `error C2440: 'type cast'` with cast. Clang does not report * error with/without cast. And I think poly64_t and poly64x1_t are same, no * cast for clang also. */ #define MBEDTLS_VMULL_P64(a, b) vmull_p64(a, b) #endif /* MBEDTLS_COMPILER_IS_GCC */ static inline uint8x16_t pmull_low(uint8x16_t a, uint8x16_t b) { return vreinterpretq_u8_p128( MBEDTLS_VMULL_P64( (poly64_t) vget_low_p64(vreinterpretq_p64_u8(a)), (poly64_t) vget_low_p64(vreinterpretq_p64_u8(b)) )); } static inline uint8x16_t pmull_high(uint8x16_t a, uint8x16_t b) { return vreinterpretq_u8_p128( vmull_high_p64(vreinterpretq_p64_u8(a), vreinterpretq_p64_u8(b))); } /* GHASH does 128b polynomial multiplication on block in GF(2^128) defined by * `x^128 + x^7 + x^2 + x + 1`. * * Arm64 only has 64b->128b polynomial multipliers, we need to do 4 64b * multiplies to generate a 128b. * * `poly_mult_128` executes polynomial multiplication and outputs 256b that * represented by 3 128b due to code size optimization. * * Output layout: * | | | | * |------------|-------------|-------------| * | ret.val[0] | h3:h2:00:00 | high 128b | * | ret.val[1] | :m2:m1:00 | middle 128b | * | ret.val[2] | : :l1:l0 | low 128b | */ static inline uint8x16x3_t poly_mult_128(uint8x16_t a, uint8x16_t b) { uint8x16x3_t ret; uint8x16_t h, m, l; /* retval high/middle/low */ uint8x16_t c, d, e; h = pmull_high(a, b); /* h3:h2:00:00 = a1*b1 */ l = pmull_low(a, b); /* : :l1:l0 = a0*b0 */ c = vextq_u8(b, b, 8); /* :c1:c0 = b0:b1 */ d = pmull_high(a, c); /* :d2:d1:00 = a1*b0 */ e = pmull_low(a, c); /* :e2:e1:00 = a0*b1 */ m = veorq_u8(d, e); /* :m2:m1:00 = d + e */ ret.val[0] = h; ret.val[1] = m; ret.val[2] = l; return ret; } /* * Modulo reduction. * * See: https://www.researchgate.net/publication/285612706_Implementing_GCM_on_ARMv8 * * Section 4.3 * * Modular reduction is slightly more complex. Write the GCM modulus as f(z) = * z^128 +r(z), where r(z) = z^7+z^2+z+ 1. The well known approach is to * consider that z^128 ≡r(z) (mod z^128 +r(z)), allowing us to write the 256-bit * operand to be reduced as a(z) = h(z)z^128 +l(z)≡h(z)r(z) + l(z). That is, we * simply multiply the higher part of the operand by r(z) and add it to l(z). If * the result is still larger than 128 bits, we reduce again. */ static inline uint8x16_t poly_mult_reduce(uint8x16x3_t input) { uint8x16_t const ZERO = vdupq_n_u8(0); uint64x2_t r = vreinterpretq_u64_u8(vdupq_n_u8(0x87)); #if defined(__GNUC__) /* use 'asm' as an optimisation barrier to prevent loading MODULO from * memory. It is for GNUC compatible compilers. */ asm volatile ("" : "+w" (r)); #endif uint8x16_t const MODULO = vreinterpretq_u8_u64(vshrq_n_u64(r, 64 - 8)); uint8x16_t h, m, l; /* input high/middle/low 128b */ uint8x16_t c, d, e, f, g, n, o; h = input.val[0]; /* h3:h2:00:00 */ m = input.val[1]; /* :m2:m1:00 */ l = input.val[2]; /* : :l1:l0 */ c = pmull_high(h, MODULO); /* :c2:c1:00 = reduction of h3 */ d = pmull_low(h, MODULO); /* : :d1:d0 = reduction of h2 */ e = veorq_u8(c, m); /* :e2:e1:00 = m2:m1:00 + c2:c1:00 */ f = pmull_high(e, MODULO); /* : :f1:f0 = reduction of e2 */ g = vextq_u8(ZERO, e, 8); /* : :g1:00 = e1:00 */ n = veorq_u8(d, l); /* : :n1:n0 = d1:d0 + l1:l0 */ o = veorq_u8(n, f); /* o1:o0 = f1:f0 + n1:n0 */ return veorq_u8(o, g); /* = o1:o0 + g1:00 */ } /* * GCM multiplication: c = a times b in GF(2^128) */ void mbedtls_aesce_gcm_mult(unsigned char c[16], const unsigned char a[16], const unsigned char b[16]) { uint8x16_t va, vb, vc; va = vrbitq_u8(vld1q_u8(&a[0])); vb = vrbitq_u8(vld1q_u8(&b[0])); vc = vrbitq_u8(poly_mult_reduce(poly_mult_128(va, vb))); vst1q_u8(&c[0], vc); } #endif /* MBEDTLS_GCM_C */ #if defined(MBEDTLS_POP_TARGET_PRAGMA) #if defined(__clang__) #pragma clang attribute pop #elif defined(__GNUC__) #pragma GCC pop_options #endif #undef MBEDTLS_POP_TARGET_PRAGMA #endif #endif /* MBEDTLS_AESCE_HAVE_CODE */ #endif /* MBEDTLS_AESCE_C */ keyring/src/verify.c0000644000176200001440000000430214775227066014200 0ustar liggesusers #include #include #include "crypto_verify_16.h" #include "crypto_verify_32.h" #include "crypto_verify_64.h" size_t crypto_verify_16_bytes(void) { return crypto_verify_16_BYTES; } size_t crypto_verify_32_bytes(void) { return crypto_verify_32_BYTES; } size_t crypto_verify_64_bytes(void) { return crypto_verify_64_BYTES; } #if defined(HAVE_EMMINTRIN_H) && defined(__SSE2__) # include static inline int crypto_verify_n(const unsigned char *x_, const unsigned char *y_, const int n) { const __m128i zero = _mm_setzero_si128(); volatile __m128i v1, v2, z; volatile int m; int i; const volatile __m128i *volatile x = (const volatile __m128i *volatile) (const void *) x_; const volatile __m128i *volatile y = (const volatile __m128i *volatile) (const void *) y_; v1 = _mm_loadu_si128((const __m128i *) &x[0]); v2 = _mm_loadu_si128((const __m128i *) &y[0]); z = _mm_xor_si128(v1, v2); for (i = 1; i < n / 16; i++) { v1 = _mm_loadu_si128((const __m128i *) &x[i]); v2 = _mm_loadu_si128((const __m128i *) &y[i]); z = _mm_or_si128(z, _mm_xor_si128(v1, v2)); } m = _mm_movemask_epi8(_mm_cmpeq_epi32(z, zero)); v1 = zero; v2 = zero; z = zero; return (int) (((uint32_t) m + 1U) >> 16) - 1; } #else static inline int crypto_verify_n(const unsigned char *x_, const unsigned char *y_, const int n) { const volatile unsigned char *volatile x = (const volatile unsigned char *volatile) x_; const volatile unsigned char *volatile y = (const volatile unsigned char *volatile) y_; volatile uint_fast16_t d = 0U; int i; for (i = 0; i < n; i++) { d |= x[i] ^ y[i]; } return (1 & ((d - 1) >> 8)) - 1; } #endif int crypto_verify_16(const unsigned char *x, const unsigned char *y) { return crypto_verify_n(x, y, crypto_verify_16_BYTES); } int crypto_verify_32(const unsigned char *x, const unsigned char *y) { return crypto_verify_n(x, y, crypto_verify_32_BYTES); } int crypto_verify_64(const unsigned char *x, const unsigned char *y) { return crypto_verify_n(x, y, crypto_verify_64_BYTES); } keyring/src/init.c0000644000176200001440000001233315006370264013625 0ustar liggesusers #include #include #include SEXP keyring_macos_get(SEXP keyring, SEXP service, SEXP username); SEXP keyring_macos_set(SEXP keyring, SEXP service, SEXP username, SEXP password); SEXP keyring_macos_delete(SEXP keyring, SEXP service, SEXP username); SEXP keyring_macos_list(SEXP keyring, SEXP service); SEXP keyring_macos_create(SEXP keyring, SEXP password); SEXP keyring_macos_list_keyring(void); SEXP keyring_macos_delete_keyring(SEXP keyring); SEXP keyring_macos_lock_keyring(SEXP keyring); SEXP keyring_macos_unlock_keyring(SEXP keyring, SEXP password); SEXP keyring_macos_is_locked_keyring(SEXP keyring); SEXP keyring_wincred_get(SEXP); SEXP keyring_wincred_exists(SEXP); SEXP keyring_wincred_set(SEXP, SEXP, SEXP, SEXP); SEXP keyring_wincred_delete(SEXP); SEXP keyring_wincred_enumerate(SEXP); SEXP keyring_secret_service_is_available(SEXP); SEXP keyring_secret_service_get(SEXP, SEXP, SEXP); SEXP keyring_secret_service_set(SEXP, SEXP, SEXP, SEXP); SEXP keyring_secret_service_delete(SEXP, SEXP, SEXP); SEXP keyring_secret_service_list(SEXP, SEXP); SEXP keyring_secret_service_create_keyring(SEXP); SEXP keyring_secret_service_list_keyring(void); SEXP keyring_secret_service_delete_keyring(SEXP); SEXP keyring_secret_service_lock_keyring(SEXP); SEXP keyring_secret_service_unlock_keyring(SEXP, SEXP); SEXP keyring_secret_service_is_locked_keyring(SEXP); SEXP rsodium_randombytes_buf(SEXP); SEXP rsodium_bin2hex(SEXP bin); SEXP rsodium_hex2bin(SEXP hex, SEXP ignore); SEXP rsodium_crypto_secret_encrypt(SEXP message, SEXP key, SEXP nonce); SEXP rsodium_crypto_secret_decrypt(SEXP cipher, SEXP key, SEXP nonce); SEXP rsodium_crypto_generichash(SEXP buf, SEXP size, SEXP key); SEXP keyring_aes_cbc_decrypt(SEXP msg, SEXP key, SEXP iv); SEXP keyring_aes_cbc_encrypt(SEXP msg, SEXP key, SEXP iv); SEXP keyring_base64_decode(SEXP array); SEXP keyring_base64_encode(SEXP array); SEXP keyring_sha256(SEXP x, SEXP raw); SEXP win_path_(SEXP _folder); static const R_CallMethodDef callMethods[] = { { "keyring_macos_get", (DL_FUNC) &keyring_macos_get, 3 }, { "keyring_macos_set", (DL_FUNC) &keyring_macos_set, 4 }, { "keyring_macos_delete", (DL_FUNC) &keyring_macos_delete, 3 }, { "keyring_macos_list", (DL_FUNC) &keyring_macos_list, 2 }, { "keyring_macos_create", (DL_FUNC) &keyring_macos_create, 2 }, { "keyring_macos_list_keyring", (DL_FUNC) &keyring_macos_list_keyring, 0 }, { "keyring_macos_delete_keyring", (DL_FUNC) &keyring_macos_delete_keyring, 1 }, { "keyring_macos_lock_keyring", (DL_FUNC) &keyring_macos_lock_keyring, 1 }, { "keyring_macos_unlock_keyring", (DL_FUNC) &keyring_macos_unlock_keyring, 2 }, { "keyring_macos_is_locked_keyring", (DL_FUNC) &keyring_macos_is_locked_keyring, 1 }, { "keyring_wincred_get", (DL_FUNC) &keyring_wincred_get, 1 }, { "keyring_wincred_exists", (DL_FUNC) &keyring_wincred_exists, 1 }, { "keyring_wincred_set", (DL_FUNC) &keyring_wincred_set, 4 }, { "keyring_wincred_delete", (DL_FUNC) &keyring_wincred_delete, 1 }, { "keyring_wincred_enumerate", (DL_FUNC) &keyring_wincred_enumerate, 1 }, { "keyring_secret_service_is_available", (DL_FUNC) &keyring_secret_service_is_available, 1 }, { "keyring_secret_service_get", (DL_FUNC) &keyring_secret_service_get, 3 }, { "keyring_secret_service_set", (DL_FUNC) &keyring_secret_service_set, 4 }, { "keyring_secret_service_delete", (DL_FUNC) &keyring_secret_service_delete, 3 }, { "keyring_secret_service_list", (DL_FUNC) &keyring_secret_service_list, 2 }, { "keyring_secret_service_create_keyring", (DL_FUNC) &keyring_secret_service_create_keyring, 1 }, { "keyring_secret_service_list_keyring", (DL_FUNC) &keyring_secret_service_list_keyring, 0 }, { "keyring_secret_service_delete_keyring", (DL_FUNC) &keyring_secret_service_delete_keyring, 1 }, { "keyring_secret_service_lock_keyring", (DL_FUNC) &keyring_secret_service_lock_keyring, 1 }, { "keyring_secret_service_unlock_keyring", (DL_FUNC) &keyring_secret_service_unlock_keyring, 2 }, { "keyring_secret_service_is_locked_keyring", (DL_FUNC) &keyring_secret_service_is_locked_keyring, 1 }, { "rsodium_randombytes_buf", (DL_FUNC) &rsodium_randombytes_buf, 1 }, { "rsodium_bin2hex", (DL_FUNC) &rsodium_bin2hex, 1 }, { "rsodium_hex2bin", (DL_FUNC) &rsodium_hex2bin, 2 }, { "rsodium_crypto_secret_encrypt", (DL_FUNC) &rsodium_crypto_secret_encrypt, 3 }, { "rsodium_crypto_secret_decrypt", (DL_FUNC) &rsodium_crypto_secret_decrypt, 3 }, { "rsodium_crypto_generichash", (DL_FUNC) &rsodium_crypto_generichash, 3 }, { "keyring_aes_cbc_decrypt", (DL_FUNC) keyring_aes_cbc_decrypt, 3 }, { "keyring_aes_cbc_encrypt", (DL_FUNC) keyring_aes_cbc_encrypt, 3 }, { "keyring_base64_decode", (DL_FUNC) keyring_base64_decode, 1 }, { "keyring_base64_encode", (DL_FUNC) keyring_base64_encode, 1 }, { "keyring_sha256", (DL_FUNC) keyring_sha256, 2 }, { "win_path_", (DL_FUNC) win_path_, 1 }, { NULL, NULL, 0 } }; void R_init_keyring(DllInfo *dll) { R_registerRoutines(dll, NULL, callMethods, NULL, NULL); R_useDynamicSymbols(dll, FALSE); R_forceSymbols(dll, TRUE); } keyring/src/core_hsalsa20_ref2.c0000644000176200001440000000502714775227066016244 0ustar liggesusers/* version 20080912 D. J. Bernstein Public domain. */ #include #include #include #include "crypto_core_hsalsa20.h" #include "sodium.h" #define ROUNDS 20 #define U32C(v) (v##U) int crypto_core_hsalsa20(unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c) { uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; int i; if (c == NULL) { x0 = U32C(0x61707865); x5 = U32C(0x3320646e); x10 = U32C(0x79622d32); x15 = U32C(0x6b206574); } else { x0 = LOAD32_LE(c + 0); x5 = LOAD32_LE(c + 4); x10 = LOAD32_LE(c + 8); x15 = LOAD32_LE(c + 12); } x1 = LOAD32_LE(k + 0); x2 = LOAD32_LE(k + 4); x3 = LOAD32_LE(k + 8); x4 = LOAD32_LE(k + 12); x11 = LOAD32_LE(k + 16); x12 = LOAD32_LE(k + 20); x13 = LOAD32_LE(k + 24); x14 = LOAD32_LE(k + 28); x6 = LOAD32_LE(in + 0); x7 = LOAD32_LE(in + 4); x8 = LOAD32_LE(in + 8); x9 = LOAD32_LE(in + 12); for (i = ROUNDS; i > 0; i -= 2) { x4 ^= ROTL32(x0 + x12, 7); x8 ^= ROTL32(x4 + x0, 9); x12 ^= ROTL32(x8 + x4, 13); x0 ^= ROTL32(x12 + x8, 18); x9 ^= ROTL32(x5 + x1, 7); x13 ^= ROTL32(x9 + x5, 9); x1 ^= ROTL32(x13 + x9, 13); x5 ^= ROTL32(x1 + x13, 18); x14 ^= ROTL32(x10 + x6, 7); x2 ^= ROTL32(x14 + x10, 9); x6 ^= ROTL32(x2 + x14, 13); x10 ^= ROTL32(x6 + x2, 18); x3 ^= ROTL32(x15 + x11, 7); x7 ^= ROTL32(x3 + x15, 9); x11 ^= ROTL32(x7 + x3, 13); x15 ^= ROTL32(x11 + x7, 18); x1 ^= ROTL32(x0 + x3, 7); x2 ^= ROTL32(x1 + x0, 9); x3 ^= ROTL32(x2 + x1, 13); x0 ^= ROTL32(x3 + x2, 18); x6 ^= ROTL32(x5 + x4, 7); x7 ^= ROTL32(x6 + x5, 9); x4 ^= ROTL32(x7 + x6, 13); x5 ^= ROTL32(x4 + x7, 18); x11 ^= ROTL32(x10 + x9, 7); x8 ^= ROTL32(x11 + x10, 9); x9 ^= ROTL32(x8 + x11, 13); x10 ^= ROTL32(x9 + x8, 18); x12 ^= ROTL32(x15 + x14, 7); x13 ^= ROTL32(x12 + x15, 9); x14 ^= ROTL32(x13 + x12, 13); x15 ^= ROTL32(x14 + x13, 18); } STORE32_LE(out + 0, x0); STORE32_LE(out + 4, x5); STORE32_LE(out + 8, x10); STORE32_LE(out + 12, x15); STORE32_LE(out + 16, x6); STORE32_LE(out + 20, x7); STORE32_LE(out + 24, x8); STORE32_LE(out + 28, x9); return 0; } keyring/src/sha256.c0000644000176200001440000001650615006370264013700 0ustar liggesusers /********************************************************************* * Filename: sha256.h * Author: Brad Conte (brad AT bradconte.com) * Copyright: * Disclaimer: This code is presented "as is" without any guarantees. * Details: Defines the API for the corresponding SHA1 implementation. *********************************************************************/ #ifndef SHA256_H #define SHA256_H /*************************** HEADER FILES ***************************/ #include /****************************** MACROS ******************************/ #define SHA256_BLOCK_SIZE 32 // SHA256 outputs a 32 byte digest /**************************** DATA TYPES ****************************/ typedef unsigned char BYTE; // 8-bit byte typedef unsigned int WORD32; // 32-bit word, change to "long" for 16-bit machines typedef struct { BYTE data[64]; WORD32 datalen; unsigned long long bitlen; WORD32 state[8]; } SHA256_CTX; /*********************** FUNCTION DECLARATIONS **********************/ void sha256_init(SHA256_CTX *ctx); void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len); void sha256_final(SHA256_CTX *ctx, BYTE hash[]); #endif // SHA256_H /********************************************************************* * Filename: sha256.c * Author: Brad Conte (brad AT bradconte.com) * Copyright: * Disclaimer: This code is presented "as is" without any guarantees. * Details: Implementation of the SHA-256 hashing algorithm. SHA-256 is one of the three algorithms in the SHA2 specification. The others, SHA-384 and SHA-512, are not offered in this implementation. Algorithm specification can be found here: * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2withchangenotice.pdf This implementation uses little endian byte order. *********************************************************************/ /*************************** HEADER FILES ***************************/ #include #include /****************************** MACROS ******************************/ #define ROTLEFT(a,b) (((a) << (b)) | ((a) >> (32-(b)))) #define ROTRIGHT(a,b) (((a) >> (b)) | ((a) << (32-(b)))) #define CH(x,y,z) (((x) & (y)) ^ (~(x) & (z))) #define MAJ(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) #define EP0(x) (ROTRIGHT(x,2) ^ ROTRIGHT(x,13) ^ ROTRIGHT(x,22)) #define EP1(x) (ROTRIGHT(x,6) ^ ROTRIGHT(x,11) ^ ROTRIGHT(x,25)) #define SIG0(x) (ROTRIGHT(x,7) ^ ROTRIGHT(x,18) ^ ((x) >> 3)) #define SIG1(x) (ROTRIGHT(x,17) ^ ROTRIGHT(x,19) ^ ((x) >> 10)) /**************************** VARIABLES *****************************/ static const WORD32 k[64] = { 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5, 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174, 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da, 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967, 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85, 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070, 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3, 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2 }; /*********************** FUNCTION DEFINITIONS ***********************/ void sha256_transform(SHA256_CTX *ctx, const BYTE data[]) { WORD32 a, b, c, d, e, f, g, h, i, j, t1, t2, m[64]; for (i = 0, j = 0; i < 16; ++i, j += 4) m[i] = ((WORD32)data[j] << 24) | ((WORD32)data[j + 1] << 16) | ((WORD32)data[j + 2] << 8) | ((WORD32)data[j + 3]); for ( ; i < 64; ++i) m[i] = SIG1(m[i - 2]) + m[i - 7] + SIG0(m[i - 15]) + m[i - 16]; a = ctx->state[0]; b = ctx->state[1]; c = ctx->state[2]; d = ctx->state[3]; e = ctx->state[4]; f = ctx->state[5]; g = ctx->state[6]; h = ctx->state[7]; for (i = 0; i < 64; ++i) { t1 = h + EP1(e) + CH(e,f,g) + k[i] + m[i]; t2 = EP0(a) + MAJ(a,b,c); h = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2; } ctx->state[0] += a; ctx->state[1] += b; ctx->state[2] += c; ctx->state[3] += d; ctx->state[4] += e; ctx->state[5] += f; ctx->state[6] += g; ctx->state[7] += h; } void sha256_init(SHA256_CTX *ctx) { ctx->datalen = 0; ctx->bitlen = 0; ctx->state[0] = 0x6a09e667; ctx->state[1] = 0xbb67ae85; ctx->state[2] = 0x3c6ef372; ctx->state[3] = 0xa54ff53a; ctx->state[4] = 0x510e527f; ctx->state[5] = 0x9b05688c; ctx->state[6] = 0x1f83d9ab; ctx->state[7] = 0x5be0cd19; } void sha256_update(SHA256_CTX *ctx, const BYTE data[], size_t len) { WORD32 i; for (i = 0; i < len; ++i) { ctx->data[ctx->datalen] = data[i]; ctx->datalen++; if (ctx->datalen == 64) { sha256_transform(ctx, ctx->data); ctx->bitlen += 512; ctx->datalen = 0; } } } void sha256_final(SHA256_CTX *ctx, BYTE hash[]) { WORD32 i; i = ctx->datalen; // Pad whatever data is left in the buffer. if (ctx->datalen < 56) { ctx->data[i++] = 0x80; while (i < 56) ctx->data[i++] = 0x00; } else { ctx->data[i++] = 0x80; while (i < 64) ctx->data[i++] = 0x00; sha256_transform(ctx, ctx->data); memset(ctx->data, 0, 56); } // Append to the padding the total message's length in bits and transform. ctx->bitlen += ctx->datalen * 8; ctx->data[63] = ctx->bitlen; ctx->data[62] = ctx->bitlen >> 8; ctx->data[61] = ctx->bitlen >> 16; ctx->data[60] = ctx->bitlen >> 24; ctx->data[59] = ctx->bitlen >> 32; ctx->data[58] = ctx->bitlen >> 40; ctx->data[57] = ctx->bitlen >> 48; ctx->data[56] = ctx->bitlen >> 56; sha256_transform(ctx, ctx->data); // Since this implementation uses little endian byte ordering and SHA uses big endian, // reverse all the bytes when copying the final state to the output hash. for (i = 0; i < 4; ++i) { hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff; hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff; hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff; hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff; hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff; hash[i + 20] = (ctx->state[5] >> (24 - i * 8)) & 0x000000ff; hash[i + 24] = (ctx->state[6] >> (24 - i * 8)) & 0x000000ff; hash[i + 28] = (ctx->state[7] >> (24 - i * 8)) & 0x000000ff; } } static void bin2str(char *to, const unsigned char *p, size_t len) { static const char *hex = "0123456789abcdef"; for (; len--; p++) { *to++ = hex[p[0] >> 4]; *to++ = hex[p[0] & 0x0f]; } } #include #include SEXP keyring_sha256(SEXP r, SEXP raw) { Rbyte *ptr = RAW(r); Rbyte *end = ptr + XLENGTH(r); size_t step = SIZE_MAX < 0x40000000 ? SIZE_MAX & ~63 : 0x40000000; SHA256_CTX ctx; BYTE hash[32]; char hex[64]; sha256_init(&ctx); while (ptr < end) { Rbyte *nxt = ptr + step; if (nxt > end) nxt = end; sha256_update(&ctx, ptr, nxt - ptr); ptr = nxt; } sha256_final(&ctx, hash); if (LOGICAL(raw)[0]) { SEXP res = PROTECT(Rf_allocVector(RAWSXP, sizeof(hash))); memcpy(RAW(res), hash, sizeof(hash)); UNPROTECT(1); return res; } else { bin2str(hex, hash, sizeof(hash)); return Rf_ScalarString(Rf_mkCharLenCE( (const char*) hex, sizeof(hex), CE_UTF8 )); } } keyring/src/aes.c0000644000176200001440000023167115006370264013442 0ustar liggesusers/* * FIPS-197 compliant AES implementation * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ /* * The AES block cipher was designed by Vincent Rijmen and Joan Daemen. * * https://csrc.nist.gov/csrc/media/projects/cryptographic-standards-and-guidelines/documents/aes-development/rijndael-ammended.pdf * http://csrc.nist.gov/publications/fips/fips197/fips-197.pdf */ #if defined(MBEDTLS_AES_C) #include #include "mbedtls/aes.h" #include "mbedtls/platform.h" #include "mbedtls/platform_util.h" #include "mbedtls/error.h" #if defined(MBEDTLS_AES_USE_HARDWARE_ONLY) #if !((defined(MBEDTLS_ARCH_IS_ARMV8_A) && defined(MBEDTLS_AESCE_C)) || \ (defined(MBEDTLS_ARCH_IS_X64) && defined(MBEDTLS_AESNI_C)) || \ (defined(MBEDTLS_ARCH_IS_X86) && defined(MBEDTLS_AESNI_C))) #error "MBEDTLS_AES_USE_HARDWARE_ONLY defined, but not all prerequisites" #endif #endif #if defined(MBEDTLS_ARCH_IS_X86) #if defined(MBEDTLS_PADLOCK_C) #if !defined(MBEDTLS_HAVE_ASM) #error "MBEDTLS_PADLOCK_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_AES_USE_HARDWARE_ONLY) #error "MBEDTLS_AES_USE_HARDWARE_ONLY cannot be defined when " \ "MBEDTLS_PADLOCK_C is set" #endif #endif #endif #if defined(MBEDTLS_PADLOCK_C) #include "padlock.h" #endif #if defined(MBEDTLS_AESNI_C) #include "aesni.h" #endif #if defined(MBEDTLS_AESCE_C) #include "aesce.h" #endif #include "mbedtls/platform.h" #include "ctr.h" /* * This is a convenience shorthand macro to check if we need reverse S-box and * reverse tables. It's private and only defined in this file. */ #if (!defined(MBEDTLS_AES_DECRYPT_ALT) || \ (!defined(MBEDTLS_AES_SETKEY_DEC_ALT) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY))) && \ !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) #define MBEDTLS_AES_NEED_REVERSE_TABLES #endif #if !defined(MBEDTLS_AES_ALT) #if defined(MBEDTLS_VIA_PADLOCK_HAVE_CODE) static int aes_padlock_ace = -1; #endif #if defined(MBEDTLS_AES_ROM_TABLES) /* * Forward S-box */ MBEDTLS_MAYBE_UNUSED static const unsigned char FSb[256] = { 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 }; /* * Forward tables */ #define FT \ \ V(A5, 63, 63, C6), V(84, 7C, 7C, F8), V(99, 77, 77, EE), V(8D, 7B, 7B, F6), \ V(0D, F2, F2, FF), V(BD, 6B, 6B, D6), V(B1, 6F, 6F, DE), V(54, C5, C5, 91), \ V(50, 30, 30, 60), V(03, 01, 01, 02), V(A9, 67, 67, CE), V(7D, 2B, 2B, 56), \ V(19, FE, FE, E7), V(62, D7, D7, B5), V(E6, AB, AB, 4D), V(9A, 76, 76, EC), \ V(45, CA, CA, 8F), V(9D, 82, 82, 1F), V(40, C9, C9, 89), V(87, 7D, 7D, FA), \ V(15, FA, FA, EF), V(EB, 59, 59, B2), V(C9, 47, 47, 8E), V(0B, F0, F0, FB), \ V(EC, AD, AD, 41), V(67, D4, D4, B3), V(FD, A2, A2, 5F), V(EA, AF, AF, 45), \ V(BF, 9C, 9C, 23), V(F7, A4, A4, 53), V(96, 72, 72, E4), V(5B, C0, C0, 9B), \ V(C2, B7, B7, 75), V(1C, FD, FD, E1), V(AE, 93, 93, 3D), V(6A, 26, 26, 4C), \ V(5A, 36, 36, 6C), V(41, 3F, 3F, 7E), V(02, F7, F7, F5), V(4F, CC, CC, 83), \ V(5C, 34, 34, 68), V(F4, A5, A5, 51), V(34, E5, E5, D1), V(08, F1, F1, F9), \ V(93, 71, 71, E2), V(73, D8, D8, AB), V(53, 31, 31, 62), V(3F, 15, 15, 2A), \ V(0C, 04, 04, 08), V(52, C7, C7, 95), V(65, 23, 23, 46), V(5E, C3, C3, 9D), \ V(28, 18, 18, 30), V(A1, 96, 96, 37), V(0F, 05, 05, 0A), V(B5, 9A, 9A, 2F), \ V(09, 07, 07, 0E), V(36, 12, 12, 24), V(9B, 80, 80, 1B), V(3D, E2, E2, DF), \ V(26, EB, EB, CD), V(69, 27, 27, 4E), V(CD, B2, B2, 7F), V(9F, 75, 75, EA), \ V(1B, 09, 09, 12), V(9E, 83, 83, 1D), V(74, 2C, 2C, 58), V(2E, 1A, 1A, 34), \ V(2D, 1B, 1B, 36), V(B2, 6E, 6E, DC), V(EE, 5A, 5A, B4), V(FB, A0, A0, 5B), \ V(F6, 52, 52, A4), V(4D, 3B, 3B, 76), V(61, D6, D6, B7), V(CE, B3, B3, 7D), \ V(7B, 29, 29, 52), V(3E, E3, E3, DD), V(71, 2F, 2F, 5E), V(97, 84, 84, 13), \ V(F5, 53, 53, A6), V(68, D1, D1, B9), V(00, 00, 00, 00), V(2C, ED, ED, C1), \ V(60, 20, 20, 40), V(1F, FC, FC, E3), V(C8, B1, B1, 79), V(ED, 5B, 5B, B6), \ V(BE, 6A, 6A, D4), V(46, CB, CB, 8D), V(D9, BE, BE, 67), V(4B, 39, 39, 72), \ V(DE, 4A, 4A, 94), V(D4, 4C, 4C, 98), V(E8, 58, 58, B0), V(4A, CF, CF, 85), \ V(6B, D0, D0, BB), V(2A, EF, EF, C5), V(E5, AA, AA, 4F), V(16, FB, FB, ED), \ V(C5, 43, 43, 86), V(D7, 4D, 4D, 9A), V(55, 33, 33, 66), V(94, 85, 85, 11), \ V(CF, 45, 45, 8A), V(10, F9, F9, E9), V(06, 02, 02, 04), V(81, 7F, 7F, FE), \ V(F0, 50, 50, A0), V(44, 3C, 3C, 78), V(BA, 9F, 9F, 25), V(E3, A8, A8, 4B), \ V(F3, 51, 51, A2), V(FE, A3, A3, 5D), V(C0, 40, 40, 80), V(8A, 8F, 8F, 05), \ V(AD, 92, 92, 3F), V(BC, 9D, 9D, 21), V(48, 38, 38, 70), V(04, F5, F5, F1), \ V(DF, BC, BC, 63), V(C1, B6, B6, 77), V(75, DA, DA, AF), V(63, 21, 21, 42), \ V(30, 10, 10, 20), V(1A, FF, FF, E5), V(0E, F3, F3, FD), V(6D, D2, D2, BF), \ V(4C, CD, CD, 81), V(14, 0C, 0C, 18), V(35, 13, 13, 26), V(2F, EC, EC, C3), \ V(E1, 5F, 5F, BE), V(A2, 97, 97, 35), V(CC, 44, 44, 88), V(39, 17, 17, 2E), \ V(57, C4, C4, 93), V(F2, A7, A7, 55), V(82, 7E, 7E, FC), V(47, 3D, 3D, 7A), \ V(AC, 64, 64, C8), V(E7, 5D, 5D, BA), V(2B, 19, 19, 32), V(95, 73, 73, E6), \ V(A0, 60, 60, C0), V(98, 81, 81, 19), V(D1, 4F, 4F, 9E), V(7F, DC, DC, A3), \ V(66, 22, 22, 44), V(7E, 2A, 2A, 54), V(AB, 90, 90, 3B), V(83, 88, 88, 0B), \ V(CA, 46, 46, 8C), V(29, EE, EE, C7), V(D3, B8, B8, 6B), V(3C, 14, 14, 28), \ V(79, DE, DE, A7), V(E2, 5E, 5E, BC), V(1D, 0B, 0B, 16), V(76, DB, DB, AD), \ V(3B, E0, E0, DB), V(56, 32, 32, 64), V(4E, 3A, 3A, 74), V(1E, 0A, 0A, 14), \ V(DB, 49, 49, 92), V(0A, 06, 06, 0C), V(6C, 24, 24, 48), V(E4, 5C, 5C, B8), \ V(5D, C2, C2, 9F), V(6E, D3, D3, BD), V(EF, AC, AC, 43), V(A6, 62, 62, C4), \ V(A8, 91, 91, 39), V(A4, 95, 95, 31), V(37, E4, E4, D3), V(8B, 79, 79, F2), \ V(32, E7, E7, D5), V(43, C8, C8, 8B), V(59, 37, 37, 6E), V(B7, 6D, 6D, DA), \ V(8C, 8D, 8D, 01), V(64, D5, D5, B1), V(D2, 4E, 4E, 9C), V(E0, A9, A9, 49), \ V(B4, 6C, 6C, D8), V(FA, 56, 56, AC), V(07, F4, F4, F3), V(25, EA, EA, CF), \ V(AF, 65, 65, CA), V(8E, 7A, 7A, F4), V(E9, AE, AE, 47), V(18, 08, 08, 10), \ V(D5, BA, BA, 6F), V(88, 78, 78, F0), V(6F, 25, 25, 4A), V(72, 2E, 2E, 5C), \ V(24, 1C, 1C, 38), V(F1, A6, A6, 57), V(C7, B4, B4, 73), V(51, C6, C6, 97), \ V(23, E8, E8, CB), V(7C, DD, DD, A1), V(9C, 74, 74, E8), V(21, 1F, 1F, 3E), \ V(DD, 4B, 4B, 96), V(DC, BD, BD, 61), V(86, 8B, 8B, 0D), V(85, 8A, 8A, 0F), \ V(90, 70, 70, E0), V(42, 3E, 3E, 7C), V(C4, B5, B5, 71), V(AA, 66, 66, CC), \ V(D8, 48, 48, 90), V(05, 03, 03, 06), V(01, F6, F6, F7), V(12, 0E, 0E, 1C), \ V(A3, 61, 61, C2), V(5F, 35, 35, 6A), V(F9, 57, 57, AE), V(D0, B9, B9, 69), \ V(91, 86, 86, 17), V(58, C1, C1, 99), V(27, 1D, 1D, 3A), V(B9, 9E, 9E, 27), \ V(38, E1, E1, D9), V(13, F8, F8, EB), V(B3, 98, 98, 2B), V(33, 11, 11, 22), \ V(BB, 69, 69, D2), V(70, D9, D9, A9), V(89, 8E, 8E, 07), V(A7, 94, 94, 33), \ V(B6, 9B, 9B, 2D), V(22, 1E, 1E, 3C), V(92, 87, 87, 15), V(20, E9, E9, C9), \ V(49, CE, CE, 87), V(FF, 55, 55, AA), V(78, 28, 28, 50), V(7A, DF, DF, A5), \ V(8F, 8C, 8C, 03), V(F8, A1, A1, 59), V(80, 89, 89, 09), V(17, 0D, 0D, 1A), \ V(DA, BF, BF, 65), V(31, E6, E6, D7), V(C6, 42, 42, 84), V(B8, 68, 68, D0), \ V(C3, 41, 41, 82), V(B0, 99, 99, 29), V(77, 2D, 2D, 5A), V(11, 0F, 0F, 1E), \ V(CB, B0, B0, 7B), V(FC, 54, 54, A8), V(D6, BB, BB, 6D), V(3A, 16, 16, 2C) #define V(a, b, c, d) 0x##a##b##c##d MBEDTLS_MAYBE_UNUSED static const uint32_t FT0[256] = { FT }; #undef V #define V(a, b, c, d) 0x##b##c##d##a MBEDTLS_MAYBE_UNUSED static const uint32_t FT1[256] = { FT }; #undef V #define V(a, b, c, d) 0x##c##d##a##b MBEDTLS_MAYBE_UNUSED static const uint32_t FT2[256] = { FT }; #undef V #define V(a, b, c, d) 0x##d##a##b##c MBEDTLS_MAYBE_UNUSED static const uint32_t FT3[256] = { FT }; #undef V #undef FT /* * Reverse S-box */ MBEDTLS_MAYBE_UNUSED static const unsigned char RSb[256] = { 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D }; /* * Reverse tables */ #define RT \ \ V(50, A7, F4, 51), V(53, 65, 41, 7E), V(C3, A4, 17, 1A), V(96, 5E, 27, 3A), \ V(CB, 6B, AB, 3B), V(F1, 45, 9D, 1F), V(AB, 58, FA, AC), V(93, 03, E3, 4B), \ V(55, FA, 30, 20), V(F6, 6D, 76, AD), V(91, 76, CC, 88), V(25, 4C, 02, F5), \ V(FC, D7, E5, 4F), V(D7, CB, 2A, C5), V(80, 44, 35, 26), V(8F, A3, 62, B5), \ V(49, 5A, B1, DE), V(67, 1B, BA, 25), V(98, 0E, EA, 45), V(E1, C0, FE, 5D), \ V(02, 75, 2F, C3), V(12, F0, 4C, 81), V(A3, 97, 46, 8D), V(C6, F9, D3, 6B), \ V(E7, 5F, 8F, 03), V(95, 9C, 92, 15), V(EB, 7A, 6D, BF), V(DA, 59, 52, 95), \ V(2D, 83, BE, D4), V(D3, 21, 74, 58), V(29, 69, E0, 49), V(44, C8, C9, 8E), \ V(6A, 89, C2, 75), V(78, 79, 8E, F4), V(6B, 3E, 58, 99), V(DD, 71, B9, 27), \ V(B6, 4F, E1, BE), V(17, AD, 88, F0), V(66, AC, 20, C9), V(B4, 3A, CE, 7D), \ V(18, 4A, DF, 63), V(82, 31, 1A, E5), V(60, 33, 51, 97), V(45, 7F, 53, 62), \ V(E0, 77, 64, B1), V(84, AE, 6B, BB), V(1C, A0, 81, FE), V(94, 2B, 08, F9), \ V(58, 68, 48, 70), V(19, FD, 45, 8F), V(87, 6C, DE, 94), V(B7, F8, 7B, 52), \ V(23, D3, 73, AB), V(E2, 02, 4B, 72), V(57, 8F, 1F, E3), V(2A, AB, 55, 66), \ V(07, 28, EB, B2), V(03, C2, B5, 2F), V(9A, 7B, C5, 86), V(A5, 08, 37, D3), \ V(F2, 87, 28, 30), V(B2, A5, BF, 23), V(BA, 6A, 03, 02), V(5C, 82, 16, ED), \ V(2B, 1C, CF, 8A), V(92, B4, 79, A7), V(F0, F2, 07, F3), V(A1, E2, 69, 4E), \ V(CD, F4, DA, 65), V(D5, BE, 05, 06), V(1F, 62, 34, D1), V(8A, FE, A6, C4), \ V(9D, 53, 2E, 34), V(A0, 55, F3, A2), V(32, E1, 8A, 05), V(75, EB, F6, A4), \ V(39, EC, 83, 0B), V(AA, EF, 60, 40), V(06, 9F, 71, 5E), V(51, 10, 6E, BD), \ V(F9, 8A, 21, 3E), V(3D, 06, DD, 96), V(AE, 05, 3E, DD), V(46, BD, E6, 4D), \ V(B5, 8D, 54, 91), V(05, 5D, C4, 71), V(6F, D4, 06, 04), V(FF, 15, 50, 60), \ V(24, FB, 98, 19), V(97, E9, BD, D6), V(CC, 43, 40, 89), V(77, 9E, D9, 67), \ V(BD, 42, E8, B0), V(88, 8B, 89, 07), V(38, 5B, 19, E7), V(DB, EE, C8, 79), \ V(47, 0A, 7C, A1), V(E9, 0F, 42, 7C), V(C9, 1E, 84, F8), V(00, 00, 00, 00), \ V(83, 86, 80, 09), V(48, ED, 2B, 32), V(AC, 70, 11, 1E), V(4E, 72, 5A, 6C), \ V(FB, FF, 0E, FD), V(56, 38, 85, 0F), V(1E, D5, AE, 3D), V(27, 39, 2D, 36), \ V(64, D9, 0F, 0A), V(21, A6, 5C, 68), V(D1, 54, 5B, 9B), V(3A, 2E, 36, 24), \ V(B1, 67, 0A, 0C), V(0F, E7, 57, 93), V(D2, 96, EE, B4), V(9E, 91, 9B, 1B), \ V(4F, C5, C0, 80), V(A2, 20, DC, 61), V(69, 4B, 77, 5A), V(16, 1A, 12, 1C), \ V(0A, BA, 93, E2), V(E5, 2A, A0, C0), V(43, E0, 22, 3C), V(1D, 17, 1B, 12), \ V(0B, 0D, 09, 0E), V(AD, C7, 8B, F2), V(B9, A8, B6, 2D), V(C8, A9, 1E, 14), \ V(85, 19, F1, 57), V(4C, 07, 75, AF), V(BB, DD, 99, EE), V(FD, 60, 7F, A3), \ V(9F, 26, 01, F7), V(BC, F5, 72, 5C), V(C5, 3B, 66, 44), V(34, 7E, FB, 5B), \ V(76, 29, 43, 8B), V(DC, C6, 23, CB), V(68, FC, ED, B6), V(63, F1, E4, B8), \ V(CA, DC, 31, D7), V(10, 85, 63, 42), V(40, 22, 97, 13), V(20, 11, C6, 84), \ V(7D, 24, 4A, 85), V(F8, 3D, BB, D2), V(11, 32, F9, AE), V(6D, A1, 29, C7), \ V(4B, 2F, 9E, 1D), V(F3, 30, B2, DC), V(EC, 52, 86, 0D), V(D0, E3, C1, 77), \ V(6C, 16, B3, 2B), V(99, B9, 70, A9), V(FA, 48, 94, 11), V(22, 64, E9, 47), \ V(C4, 8C, FC, A8), V(1A, 3F, F0, A0), V(D8, 2C, 7D, 56), V(EF, 90, 33, 22), \ V(C7, 4E, 49, 87), V(C1, D1, 38, D9), V(FE, A2, CA, 8C), V(36, 0B, D4, 98), \ V(CF, 81, F5, A6), V(28, DE, 7A, A5), V(26, 8E, B7, DA), V(A4, BF, AD, 3F), \ V(E4, 9D, 3A, 2C), V(0D, 92, 78, 50), V(9B, CC, 5F, 6A), V(62, 46, 7E, 54), \ V(C2, 13, 8D, F6), V(E8, B8, D8, 90), V(5E, F7, 39, 2E), V(F5, AF, C3, 82), \ V(BE, 80, 5D, 9F), V(7C, 93, D0, 69), V(A9, 2D, D5, 6F), V(B3, 12, 25, CF), \ V(3B, 99, AC, C8), V(A7, 7D, 18, 10), V(6E, 63, 9C, E8), V(7B, BB, 3B, DB), \ V(09, 78, 26, CD), V(F4, 18, 59, 6E), V(01, B7, 9A, EC), V(A8, 9A, 4F, 83), \ V(65, 6E, 95, E6), V(7E, E6, FF, AA), V(08, CF, BC, 21), V(E6, E8, 15, EF), \ V(D9, 9B, E7, BA), V(CE, 36, 6F, 4A), V(D4, 09, 9F, EA), V(D6, 7C, B0, 29), \ V(AF, B2, A4, 31), V(31, 23, 3F, 2A), V(30, 94, A5, C6), V(C0, 66, A2, 35), \ V(37, BC, 4E, 74), V(A6, CA, 82, FC), V(B0, D0, 90, E0), V(15, D8, A7, 33), \ V(4A, 98, 04, F1), V(F7, DA, EC, 41), V(0E, 50, CD, 7F), V(2F, F6, 91, 17), \ V(8D, D6, 4D, 76), V(4D, B0, EF, 43), V(54, 4D, AA, CC), V(DF, 04, 96, E4), \ V(E3, B5, D1, 9E), V(1B, 88, 6A, 4C), V(B8, 1F, 2C, C1), V(7F, 51, 65, 46), \ V(04, EA, 5E, 9D), V(5D, 35, 8C, 01), V(73, 74, 87, FA), V(2E, 41, 0B, FB), \ V(5A, 1D, 67, B3), V(52, D2, DB, 92), V(33, 56, 10, E9), V(13, 47, D6, 6D), \ V(8C, 61, D7, 9A), V(7A, 0C, A1, 37), V(8E, 14, F8, 59), V(89, 3C, 13, EB), \ V(EE, 27, A9, CE), V(35, C9, 61, B7), V(ED, E5, 1C, E1), V(3C, B1, 47, 7A), \ V(59, DF, D2, 9C), V(3F, 73, F2, 55), V(79, CE, 14, 18), V(BF, 37, C7, 73), \ V(EA, CD, F7, 53), V(5B, AA, FD, 5F), V(14, 6F, 3D, DF), V(86, DB, 44, 78), \ V(81, F3, AF, CA), V(3E, C4, 68, B9), V(2C, 34, 24, 38), V(5F, 40, A3, C2), \ V(72, C3, 1D, 16), V(0C, 25, E2, BC), V(8B, 49, 3C, 28), V(41, 95, 0D, FF), \ V(71, 01, A8, 39), V(DE, B3, 0C, 08), V(9C, E4, B4, D8), V(90, C1, 56, 64), \ V(61, 84, CB, 7B), V(70, B6, 32, D5), V(74, 5C, 6C, 48), V(42, 57, B8, D0) #define V(a, b, c, d) 0x##a##b##c##d MBEDTLS_MAYBE_UNUSED static const uint32_t RT0[256] = { RT }; #undef V #define V(a, b, c, d) 0x##b##c##d##a MBEDTLS_MAYBE_UNUSED static const uint32_t RT1[256] = { RT }; #undef V #define V(a, b, c, d) 0x##c##d##a##b MBEDTLS_MAYBE_UNUSED static const uint32_t RT2[256] = { RT }; #undef V #define V(a, b, c, d) 0x##d##a##b##c MBEDTLS_MAYBE_UNUSED static const uint32_t RT3[256] = { RT }; #undef V #undef RT /* * Round constants */ MBEDTLS_MAYBE_UNUSED static const uint32_t round_constants[10] = { 0x00000001, 0x00000002, 0x00000004, 0x00000008, 0x00000010, 0x00000020, 0x00000040, 0x00000080, 0x0000001B, 0x00000036 }; #else /* MBEDTLS_AES_ROM_TABLES */ /* * Forward S-box & tables */ MBEDTLS_MAYBE_UNUSED static unsigned char FSb[256]; MBEDTLS_MAYBE_UNUSED static uint32_t FT0[256]; MBEDTLS_MAYBE_UNUSED static uint32_t FT1[256]; MBEDTLS_MAYBE_UNUSED static uint32_t FT2[256]; MBEDTLS_MAYBE_UNUSED static uint32_t FT3[256]; /* * Reverse S-box & tables */ MBEDTLS_MAYBE_UNUSED static unsigned char RSb[256]; MBEDTLS_MAYBE_UNUSED static uint32_t RT0[256]; MBEDTLS_MAYBE_UNUSED static uint32_t RT1[256]; MBEDTLS_MAYBE_UNUSED static uint32_t RT2[256]; MBEDTLS_MAYBE_UNUSED static uint32_t RT3[256]; /* * Round constants */ MBEDTLS_MAYBE_UNUSED static uint32_t round_constants[10]; /* * Tables generation code */ #define ROTL8(x) (((x) << 8) & 0xFFFFFFFF) | ((x) >> 24) #define XTIME(x) (((x) << 1) ^ (((x) & 0x80) ? 0x1B : 0x00)) #define MUL(x, y) (((x) && (y)) ? pow[(log[(x)]+log[(y)]) % 255] : 0) MBEDTLS_MAYBE_UNUSED static int aes_init_done = 0; MBEDTLS_MAYBE_UNUSED static void aes_gen_tables(void) { int i; uint8_t x, y, z; uint8_t pow[256]; uint8_t log[256]; /* * compute pow and log tables over GF(2^8) */ for (i = 0, x = 1; i < 256; i++) { pow[i] = x; log[x] = (uint8_t) i; x ^= XTIME(x); } /* * calculate the round constants */ for (i = 0, x = 1; i < 10; i++) { round_constants[i] = x; x = XTIME(x); } /* * generate the forward and reverse S-boxes */ FSb[0x00] = 0x63; #if defined(MBEDTLS_AES_NEED_REVERSE_TABLES) RSb[0x63] = 0x00; #endif for (i = 1; i < 256; i++) { x = pow[255 - log[i]]; y = x; y = (y << 1) | (y >> 7); x ^= y; y = (y << 1) | (y >> 7); x ^= y; y = (y << 1) | (y >> 7); x ^= y; y = (y << 1) | (y >> 7); x ^= y ^ 0x63; FSb[i] = x; #if defined(MBEDTLS_AES_NEED_REVERSE_TABLES) RSb[x] = (unsigned char) i; #endif } /* * generate the forward and reverse tables */ for (i = 0; i < 256; i++) { x = FSb[i]; y = XTIME(x); z = y ^ x; FT0[i] = ((uint32_t) y) ^ ((uint32_t) x << 8) ^ ((uint32_t) x << 16) ^ ((uint32_t) z << 24); #if !defined(MBEDTLS_AES_FEWER_TABLES) FT1[i] = ROTL8(FT0[i]); FT2[i] = ROTL8(FT1[i]); FT3[i] = ROTL8(FT2[i]); #endif /* !MBEDTLS_AES_FEWER_TABLES */ #if defined(MBEDTLS_AES_NEED_REVERSE_TABLES) x = RSb[i]; RT0[i] = ((uint32_t) MUL(0x0E, x)) ^ ((uint32_t) MUL(0x09, x) << 8) ^ ((uint32_t) MUL(0x0D, x) << 16) ^ ((uint32_t) MUL(0x0B, x) << 24); #if !defined(MBEDTLS_AES_FEWER_TABLES) RT1[i] = ROTL8(RT0[i]); RT2[i] = ROTL8(RT1[i]); RT3[i] = ROTL8(RT2[i]); #endif /* !MBEDTLS_AES_FEWER_TABLES */ #endif /* MBEDTLS_AES_NEED_REVERSE_TABLES */ } } #undef ROTL8 #endif /* MBEDTLS_AES_ROM_TABLES */ #if defined(MBEDTLS_AES_FEWER_TABLES) #define ROTL8(x) ((uint32_t) ((x) << 8) + (uint32_t) ((x) >> 24)) #define ROTL16(x) ((uint32_t) ((x) << 16) + (uint32_t) ((x) >> 16)) #define ROTL24(x) ((uint32_t) ((x) << 24) + (uint32_t) ((x) >> 8)) #define AES_RT0(idx) RT0[idx] #define AES_RT1(idx) ROTL8(RT0[idx]) #define AES_RT2(idx) ROTL16(RT0[idx]) #define AES_RT3(idx) ROTL24(RT0[idx]) #define AES_FT0(idx) FT0[idx] #define AES_FT1(idx) ROTL8(FT0[idx]) #define AES_FT2(idx) ROTL16(FT0[idx]) #define AES_FT3(idx) ROTL24(FT0[idx]) #else /* MBEDTLS_AES_FEWER_TABLES */ #define AES_RT0(idx) RT0[idx] #define AES_RT1(idx) RT1[idx] #define AES_RT2(idx) RT2[idx] #define AES_RT3(idx) RT3[idx] #define AES_FT0(idx) FT0[idx] #define AES_FT1(idx) FT1[idx] #define AES_FT2(idx) FT2[idx] #define AES_FT3(idx) FT3[idx] #endif /* MBEDTLS_AES_FEWER_TABLES */ void mbedtls_aes_init(mbedtls_aes_context *ctx) { memset(ctx, 0, sizeof(mbedtls_aes_context)); } void mbedtls_aes_free(mbedtls_aes_context *ctx) { if (ctx == NULL) { return; } mbedtls_platform_zeroize(ctx, sizeof(mbedtls_aes_context)); } #if defined(MBEDTLS_CIPHER_MODE_XTS) void mbedtls_aes_xts_init(mbedtls_aes_xts_context *ctx) { mbedtls_aes_init(&ctx->crypt); mbedtls_aes_init(&ctx->tweak); } void mbedtls_aes_xts_free(mbedtls_aes_xts_context *ctx) { if (ctx == NULL) { return; } mbedtls_aes_free(&ctx->crypt); mbedtls_aes_free(&ctx->tweak); } #endif /* MBEDTLS_CIPHER_MODE_XTS */ /* Some implementations need the round keys to be aligned. * Return an offset to be added to buf, such that (buf + offset) is * correctly aligned. * Note that the offset is in units of elements of buf, i.e. 32-bit words, * i.e. an offset of 1 means 4 bytes and so on. */ #if (defined(MBEDTLS_VIA_PADLOCK_HAVE_CODE)) || \ (defined(MBEDTLS_AESNI_C) && MBEDTLS_AESNI_HAVE_CODE == 2) #define MAY_NEED_TO_ALIGN #endif MBEDTLS_MAYBE_UNUSED static unsigned mbedtls_aes_rk_offset(uint32_t *buf) { #if defined(MAY_NEED_TO_ALIGN) int align_16_bytes = 0; #if defined(MBEDTLS_VIA_PADLOCK_HAVE_CODE) if (aes_padlock_ace == -1) { aes_padlock_ace = mbedtls_padlock_has_support(MBEDTLS_PADLOCK_ACE); } if (aes_padlock_ace) { align_16_bytes = 1; } #endif #if defined(MBEDTLS_AESNI_C) && MBEDTLS_AESNI_HAVE_CODE == 2 if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) { align_16_bytes = 1; } #endif if (align_16_bytes) { /* These implementations needs 16-byte alignment * for the round key array. */ unsigned delta = ((uintptr_t) buf & 0x0000000fU) / 4; if (delta == 0) { return 0; } else { return 4 - delta; // 16 bytes = 4 uint32_t } } #else /* MAY_NEED_TO_ALIGN */ (void) buf; #endif /* MAY_NEED_TO_ALIGN */ return 0; } /* * AES key schedule (encryption) */ #if !defined(MBEDTLS_AES_SETKEY_ENC_ALT) int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits) { uint32_t *RK; switch (keybits) { case 128: ctx->nr = 10; break; #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) case 192: ctx->nr = 12; break; case 256: ctx->nr = 14; break; #endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */ default: return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH; } #if !defined(MBEDTLS_AES_ROM_TABLES) if (aes_init_done == 0) { aes_gen_tables(); aes_init_done = 1; } #endif ctx->rk_offset = mbedtls_aes_rk_offset(ctx->buf); RK = ctx->buf + ctx->rk_offset; #if defined(MBEDTLS_AESNI_HAVE_CODE) if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) { return mbedtls_aesni_setkey_enc((unsigned char *) RK, key, keybits); } #endif #if defined(MBEDTLS_AESCE_HAVE_CODE) if (MBEDTLS_AESCE_HAS_SUPPORT()) { return mbedtls_aesce_setkey_enc((unsigned char *) RK, key, keybits); } #endif #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) for (unsigned int i = 0; i < (keybits >> 5); i++) { RK[i] = MBEDTLS_GET_UINT32_LE(key, i << 2); } switch (ctx->nr) { case 10: for (unsigned int i = 0; i < 10; i++, RK += 4) { RK[4] = RK[0] ^ round_constants[i] ^ ((uint32_t) FSb[MBEDTLS_BYTE_1(RK[3])]) ^ ((uint32_t) FSb[MBEDTLS_BYTE_2(RK[3])] << 8) ^ ((uint32_t) FSb[MBEDTLS_BYTE_3(RK[3])] << 16) ^ ((uint32_t) FSb[MBEDTLS_BYTE_0(RK[3])] << 24); RK[5] = RK[1] ^ RK[4]; RK[6] = RK[2] ^ RK[5]; RK[7] = RK[3] ^ RK[6]; } break; #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) case 12: for (unsigned int i = 0; i < 8; i++, RK += 6) { RK[6] = RK[0] ^ round_constants[i] ^ ((uint32_t) FSb[MBEDTLS_BYTE_1(RK[5])]) ^ ((uint32_t) FSb[MBEDTLS_BYTE_2(RK[5])] << 8) ^ ((uint32_t) FSb[MBEDTLS_BYTE_3(RK[5])] << 16) ^ ((uint32_t) FSb[MBEDTLS_BYTE_0(RK[5])] << 24); RK[7] = RK[1] ^ RK[6]; RK[8] = RK[2] ^ RK[7]; RK[9] = RK[3] ^ RK[8]; RK[10] = RK[4] ^ RK[9]; RK[11] = RK[5] ^ RK[10]; } break; case 14: for (unsigned int i = 0; i < 7; i++, RK += 8) { RK[8] = RK[0] ^ round_constants[i] ^ ((uint32_t) FSb[MBEDTLS_BYTE_1(RK[7])]) ^ ((uint32_t) FSb[MBEDTLS_BYTE_2(RK[7])] << 8) ^ ((uint32_t) FSb[MBEDTLS_BYTE_3(RK[7])] << 16) ^ ((uint32_t) FSb[MBEDTLS_BYTE_0(RK[7])] << 24); RK[9] = RK[1] ^ RK[8]; RK[10] = RK[2] ^ RK[9]; RK[11] = RK[3] ^ RK[10]; RK[12] = RK[4] ^ ((uint32_t) FSb[MBEDTLS_BYTE_0(RK[11])]) ^ ((uint32_t) FSb[MBEDTLS_BYTE_1(RK[11])] << 8) ^ ((uint32_t) FSb[MBEDTLS_BYTE_2(RK[11])] << 16) ^ ((uint32_t) FSb[MBEDTLS_BYTE_3(RK[11])] << 24); RK[13] = RK[5] ^ RK[12]; RK[14] = RK[6] ^ RK[13]; RK[15] = RK[7] ^ RK[14]; } break; #endif /* !MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH */ } return 0; #endif /* !MBEDTLS_AES_USE_HARDWARE_ONLY */ } #endif /* !MBEDTLS_AES_SETKEY_ENC_ALT */ /* * AES key schedule (decryption) */ #if !defined(MBEDTLS_AES_SETKEY_DEC_ALT) && !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits) { #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) uint32_t *SK; #endif int ret; mbedtls_aes_context cty; uint32_t *RK; mbedtls_aes_init(&cty); ctx->rk_offset = mbedtls_aes_rk_offset(ctx->buf); RK = ctx->buf + ctx->rk_offset; /* Also checks keybits */ if ((ret = mbedtls_aes_setkey_enc(&cty, key, keybits)) != 0) { goto exit; } ctx->nr = cty.nr; #if defined(MBEDTLS_AESNI_HAVE_CODE) if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) { mbedtls_aesni_inverse_key((unsigned char *) RK, (const unsigned char *) (cty.buf + cty.rk_offset), ctx->nr); goto exit; } #endif #if defined(MBEDTLS_AESCE_HAVE_CODE) if (MBEDTLS_AESCE_HAS_SUPPORT()) { mbedtls_aesce_inverse_key( (unsigned char *) RK, (const unsigned char *) (cty.buf + cty.rk_offset), ctx->nr); goto exit; } #endif #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) SK = cty.buf + cty.rk_offset + cty.nr * 4; *RK++ = *SK++; *RK++ = *SK++; *RK++ = *SK++; *RK++ = *SK++; SK -= 8; for (int i = ctx->nr - 1; i > 0; i--, SK -= 8) { for (int j = 0; j < 4; j++, SK++) { *RK++ = AES_RT0(FSb[MBEDTLS_BYTE_0(*SK)]) ^ AES_RT1(FSb[MBEDTLS_BYTE_1(*SK)]) ^ AES_RT2(FSb[MBEDTLS_BYTE_2(*SK)]) ^ AES_RT3(FSb[MBEDTLS_BYTE_3(*SK)]); } } *RK++ = *SK++; *RK++ = *SK++; *RK++ = *SK++; *RK++ = *SK++; #endif /* !MBEDTLS_AES_USE_HARDWARE_ONLY */ exit: mbedtls_aes_free(&cty); return ret; } #endif /* !MBEDTLS_AES_SETKEY_DEC_ALT && !MBEDTLS_BLOCK_CIPHER_NO_DECRYPT */ #if defined(MBEDTLS_CIPHER_MODE_XTS) static int mbedtls_aes_xts_decode_keys(const unsigned char *key, unsigned int keybits, const unsigned char **key1, unsigned int *key1bits, const unsigned char **key2, unsigned int *key2bits) { const unsigned int half_keybits = keybits / 2; const unsigned int half_keybytes = half_keybits / 8; switch (keybits) { case 256: break; case 512: break; default: return MBEDTLS_ERR_AES_INVALID_KEY_LENGTH; } *key1bits = half_keybits; *key2bits = half_keybits; *key1 = &key[0]; *key2 = &key[half_keybytes]; return 0; } int mbedtls_aes_xts_setkey_enc(mbedtls_aes_xts_context *ctx, const unsigned char *key, unsigned int keybits) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const unsigned char *key1, *key2; unsigned int key1bits, key2bits; ret = mbedtls_aes_xts_decode_keys(key, keybits, &key1, &key1bits, &key2, &key2bits); if (ret != 0) { return ret; } /* Set the tweak key. Always set tweak key for the encryption mode. */ ret = mbedtls_aes_setkey_enc(&ctx->tweak, key2, key2bits); if (ret != 0) { return ret; } /* Set crypt key for encryption. */ return mbedtls_aes_setkey_enc(&ctx->crypt, key1, key1bits); } int mbedtls_aes_xts_setkey_dec(mbedtls_aes_xts_context *ctx, const unsigned char *key, unsigned int keybits) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const unsigned char *key1, *key2; unsigned int key1bits, key2bits; ret = mbedtls_aes_xts_decode_keys(key, keybits, &key1, &key1bits, &key2, &key2bits); if (ret != 0) { return ret; } /* Set the tweak key. Always set tweak key for encryption. */ ret = mbedtls_aes_setkey_enc(&ctx->tweak, key2, key2bits); if (ret != 0) { return ret; } /* Set crypt key for decryption. */ return mbedtls_aes_setkey_dec(&ctx->crypt, key1, key1bits); } #endif /* MBEDTLS_CIPHER_MODE_XTS */ #define AES_FROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \ do \ { \ (X0) = *RK++ ^ AES_FT0(MBEDTLS_BYTE_0(Y0)) ^ \ AES_FT1(MBEDTLS_BYTE_1(Y1)) ^ \ AES_FT2(MBEDTLS_BYTE_2(Y2)) ^ \ AES_FT3(MBEDTLS_BYTE_3(Y3)); \ \ (X1) = *RK++ ^ AES_FT0(MBEDTLS_BYTE_0(Y1)) ^ \ AES_FT1(MBEDTLS_BYTE_1(Y2)) ^ \ AES_FT2(MBEDTLS_BYTE_2(Y3)) ^ \ AES_FT3(MBEDTLS_BYTE_3(Y0)); \ \ (X2) = *RK++ ^ AES_FT0(MBEDTLS_BYTE_0(Y2)) ^ \ AES_FT1(MBEDTLS_BYTE_1(Y3)) ^ \ AES_FT2(MBEDTLS_BYTE_2(Y0)) ^ \ AES_FT3(MBEDTLS_BYTE_3(Y1)); \ \ (X3) = *RK++ ^ AES_FT0(MBEDTLS_BYTE_0(Y3)) ^ \ AES_FT1(MBEDTLS_BYTE_1(Y0)) ^ \ AES_FT2(MBEDTLS_BYTE_2(Y1)) ^ \ AES_FT3(MBEDTLS_BYTE_3(Y2)); \ } while (0) #define AES_RROUND(X0, X1, X2, X3, Y0, Y1, Y2, Y3) \ do \ { \ (X0) = *RK++ ^ AES_RT0(MBEDTLS_BYTE_0(Y0)) ^ \ AES_RT1(MBEDTLS_BYTE_1(Y3)) ^ \ AES_RT2(MBEDTLS_BYTE_2(Y2)) ^ \ AES_RT3(MBEDTLS_BYTE_3(Y1)); \ \ (X1) = *RK++ ^ AES_RT0(MBEDTLS_BYTE_0(Y1)) ^ \ AES_RT1(MBEDTLS_BYTE_1(Y0)) ^ \ AES_RT2(MBEDTLS_BYTE_2(Y3)) ^ \ AES_RT3(MBEDTLS_BYTE_3(Y2)); \ \ (X2) = *RK++ ^ AES_RT0(MBEDTLS_BYTE_0(Y2)) ^ \ AES_RT1(MBEDTLS_BYTE_1(Y1)) ^ \ AES_RT2(MBEDTLS_BYTE_2(Y0)) ^ \ AES_RT3(MBEDTLS_BYTE_3(Y3)); \ \ (X3) = *RK++ ^ AES_RT0(MBEDTLS_BYTE_0(Y3)) ^ \ AES_RT1(MBEDTLS_BYTE_1(Y2)) ^ \ AES_RT2(MBEDTLS_BYTE_2(Y1)) ^ \ AES_RT3(MBEDTLS_BYTE_3(Y0)); \ } while (0) /* * AES-ECB block encryption */ #if !defined(MBEDTLS_AES_ENCRYPT_ALT) int mbedtls_internal_aes_encrypt(mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16]) { int i; uint32_t *RK = ctx->buf + ctx->rk_offset; struct { uint32_t X[4]; uint32_t Y[4]; } t; t.X[0] = MBEDTLS_GET_UINT32_LE(input, 0); t.X[0] ^= *RK++; t.X[1] = MBEDTLS_GET_UINT32_LE(input, 4); t.X[1] ^= *RK++; t.X[2] = MBEDTLS_GET_UINT32_LE(input, 8); t.X[2] ^= *RK++; t.X[3] = MBEDTLS_GET_UINT32_LE(input, 12); t.X[3] ^= *RK++; for (i = (ctx->nr >> 1) - 1; i > 0; i--) { AES_FROUND(t.Y[0], t.Y[1], t.Y[2], t.Y[3], t.X[0], t.X[1], t.X[2], t.X[3]); AES_FROUND(t.X[0], t.X[1], t.X[2], t.X[3], t.Y[0], t.Y[1], t.Y[2], t.Y[3]); } AES_FROUND(t.Y[0], t.Y[1], t.Y[2], t.Y[3], t.X[0], t.X[1], t.X[2], t.X[3]); t.X[0] = *RK++ ^ \ ((uint32_t) FSb[MBEDTLS_BYTE_0(t.Y[0])]) ^ ((uint32_t) FSb[MBEDTLS_BYTE_1(t.Y[1])] << 8) ^ ((uint32_t) FSb[MBEDTLS_BYTE_2(t.Y[2])] << 16) ^ ((uint32_t) FSb[MBEDTLS_BYTE_3(t.Y[3])] << 24); t.X[1] = *RK++ ^ \ ((uint32_t) FSb[MBEDTLS_BYTE_0(t.Y[1])]) ^ ((uint32_t) FSb[MBEDTLS_BYTE_1(t.Y[2])] << 8) ^ ((uint32_t) FSb[MBEDTLS_BYTE_2(t.Y[3])] << 16) ^ ((uint32_t) FSb[MBEDTLS_BYTE_3(t.Y[0])] << 24); t.X[2] = *RK++ ^ \ ((uint32_t) FSb[MBEDTLS_BYTE_0(t.Y[2])]) ^ ((uint32_t) FSb[MBEDTLS_BYTE_1(t.Y[3])] << 8) ^ ((uint32_t) FSb[MBEDTLS_BYTE_2(t.Y[0])] << 16) ^ ((uint32_t) FSb[MBEDTLS_BYTE_3(t.Y[1])] << 24); t.X[3] = *RK++ ^ \ ((uint32_t) FSb[MBEDTLS_BYTE_0(t.Y[3])]) ^ ((uint32_t) FSb[MBEDTLS_BYTE_1(t.Y[0])] << 8) ^ ((uint32_t) FSb[MBEDTLS_BYTE_2(t.Y[1])] << 16) ^ ((uint32_t) FSb[MBEDTLS_BYTE_3(t.Y[2])] << 24); MBEDTLS_PUT_UINT32_LE(t.X[0], output, 0); MBEDTLS_PUT_UINT32_LE(t.X[1], output, 4); MBEDTLS_PUT_UINT32_LE(t.X[2], output, 8); MBEDTLS_PUT_UINT32_LE(t.X[3], output, 12); mbedtls_platform_zeroize(&t, sizeof(t)); return 0; } #endif /* !MBEDTLS_AES_ENCRYPT_ALT */ /* * AES-ECB block decryption */ #if !defined(MBEDTLS_AES_DECRYPT_ALT) && !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) int mbedtls_internal_aes_decrypt(mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16]) { int i; uint32_t *RK = ctx->buf + ctx->rk_offset; struct { uint32_t X[4]; uint32_t Y[4]; } t; t.X[0] = MBEDTLS_GET_UINT32_LE(input, 0); t.X[0] ^= *RK++; t.X[1] = MBEDTLS_GET_UINT32_LE(input, 4); t.X[1] ^= *RK++; t.X[2] = MBEDTLS_GET_UINT32_LE(input, 8); t.X[2] ^= *RK++; t.X[3] = MBEDTLS_GET_UINT32_LE(input, 12); t.X[3] ^= *RK++; for (i = (ctx->nr >> 1) - 1; i > 0; i--) { AES_RROUND(t.Y[0], t.Y[1], t.Y[2], t.Y[3], t.X[0], t.X[1], t.X[2], t.X[3]); AES_RROUND(t.X[0], t.X[1], t.X[2], t.X[3], t.Y[0], t.Y[1], t.Y[2], t.Y[3]); } AES_RROUND(t.Y[0], t.Y[1], t.Y[2], t.Y[3], t.X[0], t.X[1], t.X[2], t.X[3]); t.X[0] = *RK++ ^ \ ((uint32_t) RSb[MBEDTLS_BYTE_0(t.Y[0])]) ^ ((uint32_t) RSb[MBEDTLS_BYTE_1(t.Y[3])] << 8) ^ ((uint32_t) RSb[MBEDTLS_BYTE_2(t.Y[2])] << 16) ^ ((uint32_t) RSb[MBEDTLS_BYTE_3(t.Y[1])] << 24); t.X[1] = *RK++ ^ \ ((uint32_t) RSb[MBEDTLS_BYTE_0(t.Y[1])]) ^ ((uint32_t) RSb[MBEDTLS_BYTE_1(t.Y[0])] << 8) ^ ((uint32_t) RSb[MBEDTLS_BYTE_2(t.Y[3])] << 16) ^ ((uint32_t) RSb[MBEDTLS_BYTE_3(t.Y[2])] << 24); t.X[2] = *RK++ ^ \ ((uint32_t) RSb[MBEDTLS_BYTE_0(t.Y[2])]) ^ ((uint32_t) RSb[MBEDTLS_BYTE_1(t.Y[1])] << 8) ^ ((uint32_t) RSb[MBEDTLS_BYTE_2(t.Y[0])] << 16) ^ ((uint32_t) RSb[MBEDTLS_BYTE_3(t.Y[3])] << 24); t.X[3] = *RK++ ^ \ ((uint32_t) RSb[MBEDTLS_BYTE_0(t.Y[3])]) ^ ((uint32_t) RSb[MBEDTLS_BYTE_1(t.Y[2])] << 8) ^ ((uint32_t) RSb[MBEDTLS_BYTE_2(t.Y[1])] << 16) ^ ((uint32_t) RSb[MBEDTLS_BYTE_3(t.Y[0])] << 24); MBEDTLS_PUT_UINT32_LE(t.X[0], output, 0); MBEDTLS_PUT_UINT32_LE(t.X[1], output, 4); MBEDTLS_PUT_UINT32_LE(t.X[2], output, 8); MBEDTLS_PUT_UINT32_LE(t.X[3], output, 12); mbedtls_platform_zeroize(&t, sizeof(t)); return 0; } #endif /* !MBEDTLS_AES_DECRYPT_ALT && !MBEDTLS_BLOCK_CIPHER_NO_DECRYPT */ /* VIA Padlock and our intrinsics-based implementation of AESNI require * the round keys to be aligned on a 16-byte boundary. We take care of this * before creating them, but the AES context may have moved (this can happen * if the library is called from a language with managed memory), and in later * calls it might have a different alignment with respect to 16-byte memory. * So we may need to realign. */ MBEDTLS_MAYBE_UNUSED static void aes_maybe_realign(mbedtls_aes_context *ctx) { unsigned new_offset = mbedtls_aes_rk_offset(ctx->buf); if (new_offset != ctx->rk_offset) { memmove(ctx->buf + new_offset, // new address ctx->buf + ctx->rk_offset, // current address (ctx->nr + 1) * 16); // number of round keys * bytes per rk ctx->rk_offset = new_offset; } } /* * AES-ECB block encryption/decryption */ int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]) { if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) { return MBEDTLS_ERR_AES_BAD_INPUT_DATA; } #if defined(MAY_NEED_TO_ALIGN) aes_maybe_realign(ctx); #endif #if defined(MBEDTLS_AESNI_HAVE_CODE) if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) { return mbedtls_aesni_crypt_ecb(ctx, mode, input, output); } #endif #if defined(MBEDTLS_AESCE_HAVE_CODE) if (MBEDTLS_AESCE_HAS_SUPPORT()) { return mbedtls_aesce_crypt_ecb(ctx, mode, input, output); } #endif #if defined(MBEDTLS_VIA_PADLOCK_HAVE_CODE) if (aes_padlock_ace > 0) { return mbedtls_padlock_xcryptecb(ctx, mode, input, output); } #endif #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) if (mode == MBEDTLS_AES_DECRYPT) { return mbedtls_internal_aes_decrypt(ctx, input, output); } else #endif { return mbedtls_internal_aes_encrypt(ctx, input, output); } #endif /* !MBEDTLS_AES_USE_HARDWARE_ONLY */ } #if defined(MBEDTLS_CIPHER_MODE_CBC) /* * AES-CBC buffer encryption/decryption */ int mbedtls_aes_crypt_cbc(mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char temp[16]; if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) { return MBEDTLS_ERR_AES_BAD_INPUT_DATA; } /* Nothing to do if length is zero. */ if (length == 0) { return 0; } if (length % 16) { return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; } #if defined(MBEDTLS_VIA_PADLOCK_HAVE_CODE) if (aes_padlock_ace > 0) { if (mbedtls_padlock_xcryptcbc(ctx, mode, length, iv, input, output) == 0) { return 0; } // If padlock data misaligned, we just fall back to // unaccelerated mode // } #endif const unsigned char *ivp = iv; if (mode == MBEDTLS_AES_DECRYPT) { while (length > 0) { memcpy(temp, input, 16); ret = mbedtls_aes_crypt_ecb(ctx, mode, input, output); if (ret != 0) { goto exit; } /* Avoid using the NEON implementation of mbedtls_xor. Because of the dependency on * the result for the next block in CBC, and the cost of transferring that data from * NEON registers, NEON is slower on aarch64. */ mbedtls_xor_no_simd(output, output, iv, 16); memcpy(iv, temp, 16); input += 16; output += 16; length -= 16; } } else { while (length > 0) { mbedtls_xor_no_simd(output, input, ivp, 16); ret = mbedtls_aes_crypt_ecb(ctx, mode, output, output); if (ret != 0) { goto exit; } ivp = output; input += 16; output += 16; length -= 16; } memcpy(iv, ivp, 16); } ret = 0; exit: return ret; } #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_XTS) typedef unsigned char mbedtls_be128[16]; /* * GF(2^128) multiplication function * * This function multiplies a field element by x in the polynomial field * representation. It uses 64-bit word operations to gain speed but compensates * for machine endianness and hence works correctly on both big and little * endian machines. */ #if defined(MBEDTLS_AESCE_C) || defined(MBEDTLS_AESNI_C) MBEDTLS_OPTIMIZE_FOR_PERFORMANCE #endif static inline void mbedtls_gf128mul_x_ble(unsigned char r[16], const unsigned char x[16]) { uint64_t a, b, ra, rb; a = MBEDTLS_GET_UINT64_LE(x, 0); b = MBEDTLS_GET_UINT64_LE(x, 8); ra = (a << 1) ^ 0x0087 >> (8 - ((b >> 63) << 3)); rb = (a >> 63) | (b << 1); MBEDTLS_PUT_UINT64_LE(ra, r, 0); MBEDTLS_PUT_UINT64_LE(rb, r, 8); } /* * AES-XTS buffer encryption/decryption * * Use of MBEDTLS_OPTIMIZE_FOR_PERFORMANCE here and for mbedtls_gf128mul_x_ble() * is a 3x performance improvement for gcc -Os, if we have hardware AES support. */ #if defined(MBEDTLS_AESCE_C) || defined(MBEDTLS_AESNI_C) MBEDTLS_OPTIMIZE_FOR_PERFORMANCE #endif int mbedtls_aes_crypt_xts(mbedtls_aes_xts_context *ctx, int mode, size_t length, const unsigned char data_unit[16], const unsigned char *input, unsigned char *output) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t blocks = length / 16; size_t leftover = length % 16; unsigned char tweak[16]; unsigned char prev_tweak[16]; unsigned char tmp[16]; if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) { return MBEDTLS_ERR_AES_BAD_INPUT_DATA; } /* Data units must be at least 16 bytes long. */ if (length < 16) { return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; } /* NIST SP 800-38E disallows data units larger than 2**20 blocks. */ if (length > (1 << 20) * 16) { return MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH; } /* Compute the tweak. */ ret = mbedtls_aes_crypt_ecb(&ctx->tweak, MBEDTLS_AES_ENCRYPT, data_unit, tweak); if (ret != 0) { return ret; } while (blocks--) { if (MBEDTLS_UNLIKELY(leftover && (mode == MBEDTLS_AES_DECRYPT) && blocks == 0)) { /* We are on the last block in a decrypt operation that has * leftover bytes, so we need to use the next tweak for this block, * and this tweak for the leftover bytes. Save the current tweak for * the leftovers and then update the current tweak for use on this, * the last full block. */ memcpy(prev_tweak, tweak, sizeof(tweak)); mbedtls_gf128mul_x_ble(tweak, tweak); } mbedtls_xor(tmp, input, tweak, 16); ret = mbedtls_aes_crypt_ecb(&ctx->crypt, mode, tmp, tmp); if (ret != 0) { return ret; } mbedtls_xor(output, tmp, tweak, 16); /* Update the tweak for the next block. */ mbedtls_gf128mul_x_ble(tweak, tweak); output += 16; input += 16; } if (leftover) { /* If we are on the leftover bytes in a decrypt operation, we need to * use the previous tweak for these bytes (as saved in prev_tweak). */ unsigned char *t = mode == MBEDTLS_AES_DECRYPT ? prev_tweak : tweak; /* We are now on the final part of the data unit, which doesn't divide * evenly by 16. It's time for ciphertext stealing. */ size_t i; unsigned char *prev_output = output - 16; /* Copy ciphertext bytes from the previous block to our output for each * byte of ciphertext we won't steal. */ for (i = 0; i < leftover; i++) { output[i] = prev_output[i]; } /* Copy the remainder of the input for this final round. */ mbedtls_xor(tmp, input, t, leftover); /* Copy ciphertext bytes from the previous block for input in this * round. */ mbedtls_xor(tmp + i, prev_output + i, t + i, 16 - i); ret = mbedtls_aes_crypt_ecb(&ctx->crypt, mode, tmp, tmp); if (ret != 0) { return ret; } /* Write the result back to the previous block, overriding the previous * output we copied. */ mbedtls_xor(prev_output, tmp, t, 16); } return 0; } #endif /* MBEDTLS_CIPHER_MODE_XTS */ #if defined(MBEDTLS_CIPHER_MODE_CFB) /* * AES-CFB128 buffer encryption/decryption */ int mbedtls_aes_crypt_cfb128(mbedtls_aes_context *ctx, int mode, size_t length, size_t *iv_off, unsigned char iv[16], const unsigned char *input, unsigned char *output) { int c; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t n; if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) { return MBEDTLS_ERR_AES_BAD_INPUT_DATA; } n = *iv_off; if (n > 15) { return MBEDTLS_ERR_AES_BAD_INPUT_DATA; } if (mode == MBEDTLS_AES_DECRYPT) { while (length--) { if (n == 0) { ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, iv, iv); if (ret != 0) { goto exit; } } c = *input++; *output++ = (unsigned char) (c ^ iv[n]); iv[n] = (unsigned char) c; n = (n + 1) & 0x0F; } } else { while (length--) { if (n == 0) { ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, iv, iv); if (ret != 0) { goto exit; } } iv[n] = *output++ = (unsigned char) (iv[n] ^ *input++); n = (n + 1) & 0x0F; } } *iv_off = n; ret = 0; exit: return ret; } /* * AES-CFB8 buffer encryption/decryption */ int mbedtls_aes_crypt_cfb8(mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char c; unsigned char ov[17]; if (mode != MBEDTLS_AES_ENCRYPT && mode != MBEDTLS_AES_DECRYPT) { return MBEDTLS_ERR_AES_BAD_INPUT_DATA; } while (length--) { memcpy(ov, iv, 16); ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, iv, iv); if (ret != 0) { goto exit; } if (mode == MBEDTLS_AES_DECRYPT) { ov[16] = *input; } c = *output++ = (unsigned char) (iv[0] ^ *input++); if (mode == MBEDTLS_AES_ENCRYPT) { ov[16] = c; } memcpy(iv, ov + 1, 16); } ret = 0; exit: return ret; } #endif /* MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_OFB) /* * AES-OFB (Output Feedback Mode) buffer encryption/decryption */ int mbedtls_aes_crypt_ofb(mbedtls_aes_context *ctx, size_t length, size_t *iv_off, unsigned char iv[16], const unsigned char *input, unsigned char *output) { int ret = 0; size_t n; n = *iv_off; if (n > 15) { return MBEDTLS_ERR_AES_BAD_INPUT_DATA; } while (length--) { if (n == 0) { ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, iv, iv); if (ret != 0) { goto exit; } } *output++ = *input++ ^ iv[n]; n = (n + 1) & 0x0F; } *iv_off = n; exit: return ret; } #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) /* * AES-CTR buffer encryption/decryption */ int mbedtls_aes_crypt_ctr(mbedtls_aes_context *ctx, size_t length, size_t *nc_off, unsigned char nonce_counter[16], unsigned char stream_block[16], const unsigned char *input, unsigned char *output) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t offset = *nc_off; if (offset > 0x0F) { return MBEDTLS_ERR_AES_BAD_INPUT_DATA; } for (size_t i = 0; i < length;) { size_t n = 16; if (offset == 0) { ret = mbedtls_aes_crypt_ecb(ctx, MBEDTLS_AES_ENCRYPT, nonce_counter, stream_block); if (ret != 0) { goto exit; } mbedtls_ctr_increment_counter(nonce_counter); } else { n -= offset; } if (n > (length - i)) { n = (length - i); } mbedtls_xor(&output[i], &input[i], &stream_block[offset], n); // offset might be non-zero for the last block, but in that case, we don't use it again offset = 0; i += n; } // capture offset for future resumption *nc_off = (*nc_off + length) % 16; ret = 0; exit: return ret; } #endif /* MBEDTLS_CIPHER_MODE_CTR */ #endif /* !MBEDTLS_AES_ALT */ #if defined(MBEDTLS_SELF_TEST) /* * AES test vectors from: * * http://csrc.nist.gov/archive/aes/rijndael/rijndael-vals.zip */ #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) static const unsigned char aes_test_ecb_dec[][16] = { { 0x44, 0x41, 0x6A, 0xC2, 0xD1, 0xF5, 0x3C, 0x58, 0x33, 0x03, 0x91, 0x7E, 0x6B, 0xE9, 0xEB, 0xE0 }, #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) { 0x48, 0xE3, 0x1E, 0x9E, 0x25, 0x67, 0x18, 0xF2, 0x92, 0x29, 0x31, 0x9C, 0x19, 0xF1, 0x5B, 0xA4 }, { 0x05, 0x8C, 0xCF, 0xFD, 0xBB, 0xCB, 0x38, 0x2D, 0x1F, 0x6F, 0x56, 0x58, 0x5D, 0x8A, 0x4A, 0xDE } #endif }; #endif static const unsigned char aes_test_ecb_enc[][16] = { { 0xC3, 0x4C, 0x05, 0x2C, 0xC0, 0xDA, 0x8D, 0x73, 0x45, 0x1A, 0xFE, 0x5F, 0x03, 0xBE, 0x29, 0x7F }, #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) { 0xF3, 0xF6, 0x75, 0x2A, 0xE8, 0xD7, 0x83, 0x11, 0x38, 0xF0, 0x41, 0x56, 0x06, 0x31, 0xB1, 0x14 }, { 0x8B, 0x79, 0xEE, 0xCC, 0x93, 0xA0, 0xEE, 0x5D, 0xFF, 0x30, 0xB4, 0xEA, 0x21, 0x63, 0x6D, 0xA4 } #endif }; #if defined(MBEDTLS_CIPHER_MODE_CBC) static const unsigned char aes_test_cbc_dec[][16] = { { 0xFA, 0xCA, 0x37, 0xE0, 0xB0, 0xC8, 0x53, 0x73, 0xDF, 0x70, 0x6E, 0x73, 0xF7, 0xC9, 0xAF, 0x86 }, #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) { 0x5D, 0xF6, 0x78, 0xDD, 0x17, 0xBA, 0x4E, 0x75, 0xB6, 0x17, 0x68, 0xC6, 0xAD, 0xEF, 0x7C, 0x7B }, { 0x48, 0x04, 0xE1, 0x81, 0x8F, 0xE6, 0x29, 0x75, 0x19, 0xA3, 0xE8, 0x8C, 0x57, 0x31, 0x04, 0x13 } #endif }; static const unsigned char aes_test_cbc_enc[][16] = { { 0x8A, 0x05, 0xFC, 0x5E, 0x09, 0x5A, 0xF4, 0x84, 0x8A, 0x08, 0xD3, 0x28, 0xD3, 0x68, 0x8E, 0x3D }, #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) { 0x7B, 0xD9, 0x66, 0xD5, 0x3A, 0xD8, 0xC1, 0xBB, 0x85, 0xD2, 0xAD, 0xFA, 0xE8, 0x7B, 0xB1, 0x04 }, { 0xFE, 0x3C, 0x53, 0x65, 0x3E, 0x2F, 0x45, 0xB5, 0x6F, 0xCD, 0x88, 0xB2, 0xCC, 0x89, 0x8F, 0xF0 } #endif }; #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_CFB) /* * AES-CFB128 test vectors from: * * http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf */ static const unsigned char aes_test_cfb128_key[][32] = { { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C }, #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) { 0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, 0x52, 0xC8, 0x10, 0xF3, 0x2B, 0x80, 0x90, 0x79, 0xE5, 0x62, 0xF8, 0xEA, 0xD2, 0x52, 0x2C, 0x6B, 0x7B }, { 0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE, 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81, 0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7, 0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4 } #endif }; static const unsigned char aes_test_cfb128_iv[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; static const unsigned char aes_test_cfb128_pt[64] = { 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A, 0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C, 0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51, 0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11, 0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF, 0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17, 0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10 }; static const unsigned char aes_test_cfb128_ct[][64] = { { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A, 0xC8, 0xA6, 0x45, 0x37, 0xA0, 0xB3, 0xA9, 0x3F, 0xCD, 0xE3, 0xCD, 0xAD, 0x9F, 0x1C, 0xE5, 0x8B, 0x26, 0x75, 0x1F, 0x67, 0xA3, 0xCB, 0xB1, 0x40, 0xB1, 0x80, 0x8C, 0xF1, 0x87, 0xA4, 0xF4, 0xDF, 0xC0, 0x4B, 0x05, 0x35, 0x7C, 0x5D, 0x1C, 0x0E, 0xEA, 0xC4, 0xC6, 0x6F, 0x9F, 0xF7, 0xF2, 0xE6 }, #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) { 0xCD, 0xC8, 0x0D, 0x6F, 0xDD, 0xF1, 0x8C, 0xAB, 0x34, 0xC2, 0x59, 0x09, 0xC9, 0x9A, 0x41, 0x74, 0x67, 0xCE, 0x7F, 0x7F, 0x81, 0x17, 0x36, 0x21, 0x96, 0x1A, 0x2B, 0x70, 0x17, 0x1D, 0x3D, 0x7A, 0x2E, 0x1E, 0x8A, 0x1D, 0xD5, 0x9B, 0x88, 0xB1, 0xC8, 0xE6, 0x0F, 0xED, 0x1E, 0xFA, 0xC4, 0xC9, 0xC0, 0x5F, 0x9F, 0x9C, 0xA9, 0x83, 0x4F, 0xA0, 0x42, 0xAE, 0x8F, 0xBA, 0x58, 0x4B, 0x09, 0xFF }, { 0xDC, 0x7E, 0x84, 0xBF, 0xDA, 0x79, 0x16, 0x4B, 0x7E, 0xCD, 0x84, 0x86, 0x98, 0x5D, 0x38, 0x60, 0x39, 0xFF, 0xED, 0x14, 0x3B, 0x28, 0xB1, 0xC8, 0x32, 0x11, 0x3C, 0x63, 0x31, 0xE5, 0x40, 0x7B, 0xDF, 0x10, 0x13, 0x24, 0x15, 0xE5, 0x4B, 0x92, 0xA1, 0x3E, 0xD0, 0xA8, 0x26, 0x7A, 0xE2, 0xF9, 0x75, 0xA3, 0x85, 0x74, 0x1A, 0xB9, 0xCE, 0xF8, 0x20, 0x31, 0x62, 0x3D, 0x55, 0xB1, 0xE4, 0x71 } #endif }; #endif /* MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_OFB) /* * AES-OFB test vectors from: * * https://csrc.nist.gov/publications/detail/sp/800-38a/final */ static const unsigned char aes_test_ofb_key[][32] = { { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C }, #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) { 0x8E, 0x73, 0xB0, 0xF7, 0xDA, 0x0E, 0x64, 0x52, 0xC8, 0x10, 0xF3, 0x2B, 0x80, 0x90, 0x79, 0xE5, 0x62, 0xF8, 0xEA, 0xD2, 0x52, 0x2C, 0x6B, 0x7B }, { 0x60, 0x3D, 0xEB, 0x10, 0x15, 0xCA, 0x71, 0xBE, 0x2B, 0x73, 0xAE, 0xF0, 0x85, 0x7D, 0x77, 0x81, 0x1F, 0x35, 0x2C, 0x07, 0x3B, 0x61, 0x08, 0xD7, 0x2D, 0x98, 0x10, 0xA3, 0x09, 0x14, 0xDF, 0xF4 } #endif }; static const unsigned char aes_test_ofb_iv[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F }; static const unsigned char aes_test_ofb_pt[64] = { 0x6B, 0xC1, 0xBE, 0xE2, 0x2E, 0x40, 0x9F, 0x96, 0xE9, 0x3D, 0x7E, 0x11, 0x73, 0x93, 0x17, 0x2A, 0xAE, 0x2D, 0x8A, 0x57, 0x1E, 0x03, 0xAC, 0x9C, 0x9E, 0xB7, 0x6F, 0xAC, 0x45, 0xAF, 0x8E, 0x51, 0x30, 0xC8, 0x1C, 0x46, 0xA3, 0x5C, 0xE4, 0x11, 0xE5, 0xFB, 0xC1, 0x19, 0x1A, 0x0A, 0x52, 0xEF, 0xF6, 0x9F, 0x24, 0x45, 0xDF, 0x4F, 0x9B, 0x17, 0xAD, 0x2B, 0x41, 0x7B, 0xE6, 0x6C, 0x37, 0x10 }; static const unsigned char aes_test_ofb_ct[][64] = { { 0x3B, 0x3F, 0xD9, 0x2E, 0xB7, 0x2D, 0xAD, 0x20, 0x33, 0x34, 0x49, 0xF8, 0xE8, 0x3C, 0xFB, 0x4A, 0x77, 0x89, 0x50, 0x8d, 0x16, 0x91, 0x8f, 0x03, 0xf5, 0x3c, 0x52, 0xda, 0xc5, 0x4e, 0xd8, 0x25, 0x97, 0x40, 0x05, 0x1e, 0x9c, 0x5f, 0xec, 0xf6, 0x43, 0x44, 0xf7, 0xa8, 0x22, 0x60, 0xed, 0xcc, 0x30, 0x4c, 0x65, 0x28, 0xf6, 0x59, 0xc7, 0x78, 0x66, 0xa5, 0x10, 0xd9, 0xc1, 0xd6, 0xae, 0x5e }, #if !defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) { 0xCD, 0xC8, 0x0D, 0x6F, 0xDD, 0xF1, 0x8C, 0xAB, 0x34, 0xC2, 0x59, 0x09, 0xC9, 0x9A, 0x41, 0x74, 0xfc, 0xc2, 0x8b, 0x8d, 0x4c, 0x63, 0x83, 0x7c, 0x09, 0xe8, 0x17, 0x00, 0xc1, 0x10, 0x04, 0x01, 0x8d, 0x9a, 0x9a, 0xea, 0xc0, 0xf6, 0x59, 0x6f, 0x55, 0x9c, 0x6d, 0x4d, 0xaf, 0x59, 0xa5, 0xf2, 0x6d, 0x9f, 0x20, 0x08, 0x57, 0xca, 0x6c, 0x3e, 0x9c, 0xac, 0x52, 0x4b, 0xd9, 0xac, 0xc9, 0x2a }, { 0xDC, 0x7E, 0x84, 0xBF, 0xDA, 0x79, 0x16, 0x4B, 0x7E, 0xCD, 0x84, 0x86, 0x98, 0x5D, 0x38, 0x60, 0x4f, 0xeb, 0xdc, 0x67, 0x40, 0xd2, 0x0b, 0x3a, 0xc8, 0x8f, 0x6a, 0xd8, 0x2a, 0x4f, 0xb0, 0x8d, 0x71, 0xab, 0x47, 0xa0, 0x86, 0xe8, 0x6e, 0xed, 0xf3, 0x9d, 0x1c, 0x5b, 0xba, 0x97, 0xc4, 0x08, 0x01, 0x26, 0x14, 0x1d, 0x67, 0xf3, 0x7b, 0xe8, 0x53, 0x8f, 0x5a, 0x8b, 0xe7, 0x40, 0xe4, 0x84 } #endif }; #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) /* * AES-CTR test vectors from: * * http://www.faqs.org/rfcs/rfc3686.html */ static const unsigned char aes_test_ctr_key[][16] = { { 0xAE, 0x68, 0x52, 0xF8, 0x12, 0x10, 0x67, 0xCC, 0x4B, 0xF7, 0xA5, 0x76, 0x55, 0x77, 0xF3, 0x9E }, { 0x7E, 0x24, 0x06, 0x78, 0x17, 0xFA, 0xE0, 0xD7, 0x43, 0xD6, 0xCE, 0x1F, 0x32, 0x53, 0x91, 0x63 }, { 0x76, 0x91, 0xBE, 0x03, 0x5E, 0x50, 0x20, 0xA8, 0xAC, 0x6E, 0x61, 0x85, 0x29, 0xF9, 0xA0, 0xDC } }; static const unsigned char aes_test_ctr_nonce_counter[][16] = { { 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 }, { 0x00, 0x6C, 0xB6, 0xDB, 0xC0, 0x54, 0x3B, 0x59, 0xDA, 0x48, 0xD9, 0x0B, 0x00, 0x00, 0x00, 0x01 }, { 0x00, 0xE0, 0x01, 0x7B, 0x27, 0x77, 0x7F, 0x3F, 0x4A, 0x17, 0x86, 0xF0, 0x00, 0x00, 0x00, 0x01 } }; static const unsigned char aes_test_ctr_pt[][48] = { { 0x53, 0x69, 0x6E, 0x67, 0x6C, 0x65, 0x20, 0x62, 0x6C, 0x6F, 0x63, 0x6B, 0x20, 0x6D, 0x73, 0x67 }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F }, { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23 } }; static const unsigned char aes_test_ctr_ct[][48] = { { 0xE4, 0x09, 0x5D, 0x4F, 0xB7, 0xA7, 0xB3, 0x79, 0x2D, 0x61, 0x75, 0xA3, 0x26, 0x13, 0x11, 0xB8 }, { 0x51, 0x04, 0xA1, 0x06, 0x16, 0x8A, 0x72, 0xD9, 0x79, 0x0D, 0x41, 0xEE, 0x8E, 0xDA, 0xD3, 0x88, 0xEB, 0x2E, 0x1E, 0xFC, 0x46, 0xDA, 0x57, 0xC8, 0xFC, 0xE6, 0x30, 0xDF, 0x91, 0x41, 0xBE, 0x28 }, { 0xC1, 0xCF, 0x48, 0xA8, 0x9F, 0x2F, 0xFD, 0xD9, 0xCF, 0x46, 0x52, 0xE9, 0xEF, 0xDB, 0x72, 0xD7, 0x45, 0x40, 0xA4, 0x2B, 0xDE, 0x6D, 0x78, 0x36, 0xD5, 0x9A, 0x5C, 0xEA, 0xAE, 0xF3, 0x10, 0x53, 0x25, 0xB2, 0x07, 0x2F } }; static const int aes_test_ctr_len[3] = { 16, 32, 36 }; #endif /* MBEDTLS_CIPHER_MODE_CTR */ #if defined(MBEDTLS_CIPHER_MODE_XTS) /* * AES-XTS test vectors from: * * IEEE P1619/D16 Annex B * https://web.archive.org/web/20150629024421/http://grouper.ieee.org/groups/1619/email/pdf00086.pdf * (Archived from original at http://grouper.ieee.org/groups/1619/email/pdf00086.pdf) */ static const unsigned char aes_test_xts_key[][32] = { { 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 }, { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 }, { 0xff, 0xfe, 0xfd, 0xfc, 0xfb, 0xfa, 0xf9, 0xf8, 0xf7, 0xf6, 0xf5, 0xf4, 0xf3, 0xf2, 0xf1, 0xf0, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 }, }; static const unsigned char aes_test_xts_pt32[][32] = { { 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 }, { 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44 }, { 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44 }, }; static const unsigned char aes_test_xts_ct32[][32] = { { 0x91, 0x7c, 0xf6, 0x9e, 0xbd, 0x68, 0xb2, 0xec, 0x9b, 0x9f, 0xe9, 0xa3, 0xea, 0xdd, 0xa6, 0x92, 0xcd, 0x43, 0xd2, 0xf5, 0x95, 0x98, 0xed, 0x85, 0x8c, 0x02, 0xc2, 0x65, 0x2f, 0xbf, 0x92, 0x2e }, { 0xc4, 0x54, 0x18, 0x5e, 0x6a, 0x16, 0x93, 0x6e, 0x39, 0x33, 0x40, 0x38, 0xac, 0xef, 0x83, 0x8b, 0xfb, 0x18, 0x6f, 0xff, 0x74, 0x80, 0xad, 0xc4, 0x28, 0x93, 0x82, 0xec, 0xd6, 0xd3, 0x94, 0xf0 }, { 0xaf, 0x85, 0x33, 0x6b, 0x59, 0x7a, 0xfc, 0x1a, 0x90, 0x0b, 0x2e, 0xb2, 0x1e, 0xc9, 0x49, 0xd2, 0x92, 0xdf, 0x4c, 0x04, 0x7e, 0x0b, 0x21, 0x53, 0x21, 0x86, 0xa5, 0x97, 0x1a, 0x22, 0x7a, 0x89 }, }; static const unsigned char aes_test_xts_data_unit[][16] = { { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x33, 0x33, 0x33, 0x33, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, { 0x33, 0x33, 0x33, 0x33, 0x33, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, }; #endif /* MBEDTLS_CIPHER_MODE_XTS */ /* * Checkup routine */ int mbedtls_aes_self_test(int verbose) { int ret = 0, i, j, u, mode; unsigned int keybits; unsigned char key[32]; unsigned char buf[64]; const unsigned char *aes_tests; #if defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB) || \ defined(MBEDTLS_CIPHER_MODE_OFB) unsigned char iv[16]; #endif #if defined(MBEDTLS_CIPHER_MODE_CBC) unsigned char prv[16]; #endif #if defined(MBEDTLS_CIPHER_MODE_CTR) || defined(MBEDTLS_CIPHER_MODE_CFB) || \ defined(MBEDTLS_CIPHER_MODE_OFB) size_t offset; #endif #if defined(MBEDTLS_CIPHER_MODE_CTR) || defined(MBEDTLS_CIPHER_MODE_XTS) int len; #endif #if defined(MBEDTLS_CIPHER_MODE_CTR) unsigned char nonce_counter[16]; unsigned char stream_block[16]; #endif mbedtls_aes_context ctx; memset(key, 0, 32); mbedtls_aes_init(&ctx); if (verbose != 0) { #if defined(MBEDTLS_AES_ALT) mbedtls_printf(" AES note: alternative implementation.\n"); #else /* MBEDTLS_AES_ALT */ #if defined(MBEDTLS_AESNI_HAVE_CODE) #if MBEDTLS_AESNI_HAVE_CODE == 1 mbedtls_printf(" AES note: AESNI code present (assembly implementation).\n"); #elif MBEDTLS_AESNI_HAVE_CODE == 2 mbedtls_printf(" AES note: AESNI code present (intrinsics implementation).\n"); #else #error "Unrecognised value for MBEDTLS_AESNI_HAVE_CODE" #endif if (mbedtls_aesni_has_support(MBEDTLS_AESNI_AES)) { mbedtls_printf(" AES note: using AESNI.\n"); } else #endif #if defined(MBEDTLS_VIA_PADLOCK_HAVE_CODE) if (mbedtls_padlock_has_support(MBEDTLS_PADLOCK_ACE)) { mbedtls_printf(" AES note: using VIA Padlock.\n"); } else #endif #if defined(MBEDTLS_AESCE_HAVE_CODE) if (MBEDTLS_AESCE_HAS_SUPPORT()) { mbedtls_printf(" AES note: using AESCE.\n"); } else #endif { #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) mbedtls_printf(" AES note: built-in implementation.\n"); #endif } #endif /* MBEDTLS_AES_ALT */ } /* * ECB mode */ { static const int num_tests = sizeof(aes_test_ecb_enc) / sizeof(*aes_test_ecb_enc); for (i = 0; i < num_tests << 1; i++) { u = i >> 1; keybits = 128 + u * 64; mode = i & 1; if (verbose != 0) { mbedtls_printf(" AES-ECB-%3u (%s): ", keybits, (mode == MBEDTLS_AES_DECRYPT) ? "dec" : "enc"); } #if defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) if (mode == MBEDTLS_AES_DECRYPT) { if (verbose != 0) { mbedtls_printf("skipped\n"); } continue; } #endif memset(buf, 0, 16); #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) if (mode == MBEDTLS_AES_DECRYPT) { ret = mbedtls_aes_setkey_dec(&ctx, key, keybits); aes_tests = aes_test_ecb_dec[u]; } else #endif { ret = mbedtls_aes_setkey_enc(&ctx, key, keybits); aes_tests = aes_test_ecb_enc[u]; } /* * AES-192 is an optional feature that may be unavailable when * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ if (ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && keybits == 192) { mbedtls_printf("skipped\n"); continue; } else if (ret != 0) { goto exit; } for (j = 0; j < 10000; j++) { ret = mbedtls_aes_crypt_ecb(&ctx, mode, buf, buf); if (ret != 0) { goto exit; } } if (memcmp(buf, aes_tests, 16) != 0) { ret = 1; goto exit; } if (verbose != 0) { mbedtls_printf("passed\n"); } } if (verbose != 0) { mbedtls_printf("\n"); } } #if defined(MBEDTLS_CIPHER_MODE_CBC) /* * CBC mode */ { static const int num_tests = sizeof(aes_test_cbc_dec) / sizeof(*aes_test_cbc_dec); for (i = 0; i < num_tests << 1; i++) { u = i >> 1; keybits = 128 + u * 64; mode = i & 1; if (verbose != 0) { mbedtls_printf(" AES-CBC-%3u (%s): ", keybits, (mode == MBEDTLS_AES_DECRYPT) ? "dec" : "enc"); } memset(iv, 0, 16); memset(prv, 0, 16); memset(buf, 0, 16); if (mode == MBEDTLS_AES_DECRYPT) { ret = mbedtls_aes_setkey_dec(&ctx, key, keybits); aes_tests = aes_test_cbc_dec[u]; } else { ret = mbedtls_aes_setkey_enc(&ctx, key, keybits); aes_tests = aes_test_cbc_enc[u]; } /* * AES-192 is an optional feature that may be unavailable when * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ if (ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && keybits == 192) { mbedtls_printf("skipped\n"); continue; } else if (ret != 0) { goto exit; } for (j = 0; j < 10000; j++) { if (mode == MBEDTLS_AES_ENCRYPT) { unsigned char tmp[16]; memcpy(tmp, prv, 16); memcpy(prv, buf, 16); memcpy(buf, tmp, 16); } ret = mbedtls_aes_crypt_cbc(&ctx, mode, 16, iv, buf, buf); if (ret != 0) { goto exit; } } if (memcmp(buf, aes_tests, 16) != 0) { ret = 1; goto exit; } if (verbose != 0) { mbedtls_printf("passed\n"); } } if (verbose != 0) { mbedtls_printf("\n"); } } #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_CFB) /* * CFB128 mode */ { static const int num_tests = sizeof(aes_test_cfb128_key) / sizeof(*aes_test_cfb128_key); for (i = 0; i < num_tests << 1; i++) { u = i >> 1; keybits = 128 + u * 64; mode = i & 1; if (verbose != 0) { mbedtls_printf(" AES-CFB128-%3u (%s): ", keybits, (mode == MBEDTLS_AES_DECRYPT) ? "dec" : "enc"); } memcpy(iv, aes_test_cfb128_iv, 16); memcpy(key, aes_test_cfb128_key[u], keybits / 8); offset = 0; ret = mbedtls_aes_setkey_enc(&ctx, key, keybits); /* * AES-192 is an optional feature that may be unavailable when * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ if (ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && keybits == 192) { mbedtls_printf("skipped\n"); continue; } else if (ret != 0) { goto exit; } if (mode == MBEDTLS_AES_DECRYPT) { memcpy(buf, aes_test_cfb128_ct[u], 64); aes_tests = aes_test_cfb128_pt; } else { memcpy(buf, aes_test_cfb128_pt, 64); aes_tests = aes_test_cfb128_ct[u]; } ret = mbedtls_aes_crypt_cfb128(&ctx, mode, 64, &offset, iv, buf, buf); if (ret != 0) { goto exit; } if (memcmp(buf, aes_tests, 64) != 0) { ret = 1; goto exit; } if (verbose != 0) { mbedtls_printf("passed\n"); } } if (verbose != 0) { mbedtls_printf("\n"); } } #endif /* MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_OFB) /* * OFB mode */ { static const int num_tests = sizeof(aes_test_ofb_key) / sizeof(*aes_test_ofb_key); for (i = 0; i < num_tests << 1; i++) { u = i >> 1; keybits = 128 + u * 64; mode = i & 1; if (verbose != 0) { mbedtls_printf(" AES-OFB-%3u (%s): ", keybits, (mode == MBEDTLS_AES_DECRYPT) ? "dec" : "enc"); } memcpy(iv, aes_test_ofb_iv, 16); memcpy(key, aes_test_ofb_key[u], keybits / 8); offset = 0; ret = mbedtls_aes_setkey_enc(&ctx, key, keybits); /* * AES-192 is an optional feature that may be unavailable when * there is an alternative underlying implementation i.e. when * MBEDTLS_AES_ALT is defined. */ if (ret == MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED && keybits == 192) { mbedtls_printf("skipped\n"); continue; } else if (ret != 0) { goto exit; } if (mode == MBEDTLS_AES_DECRYPT) { memcpy(buf, aes_test_ofb_ct[u], 64); aes_tests = aes_test_ofb_pt; } else { memcpy(buf, aes_test_ofb_pt, 64); aes_tests = aes_test_ofb_ct[u]; } ret = mbedtls_aes_crypt_ofb(&ctx, 64, &offset, iv, buf, buf); if (ret != 0) { goto exit; } if (memcmp(buf, aes_tests, 64) != 0) { ret = 1; goto exit; } if (verbose != 0) { mbedtls_printf("passed\n"); } } if (verbose != 0) { mbedtls_printf("\n"); } } #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) /* * CTR mode */ { static const int num_tests = sizeof(aes_test_ctr_key) / sizeof(*aes_test_ctr_key); for (i = 0; i < num_tests << 1; i++) { u = i >> 1; mode = i & 1; if (verbose != 0) { mbedtls_printf(" AES-CTR-128 (%s): ", (mode == MBEDTLS_AES_DECRYPT) ? "dec" : "enc"); } memcpy(nonce_counter, aes_test_ctr_nonce_counter[u], 16); memcpy(key, aes_test_ctr_key[u], 16); offset = 0; if ((ret = mbedtls_aes_setkey_enc(&ctx, key, 128)) != 0) { goto exit; } len = aes_test_ctr_len[u]; if (mode == MBEDTLS_AES_DECRYPT) { memcpy(buf, aes_test_ctr_ct[u], len); aes_tests = aes_test_ctr_pt[u]; } else { memcpy(buf, aes_test_ctr_pt[u], len); aes_tests = aes_test_ctr_ct[u]; } ret = mbedtls_aes_crypt_ctr(&ctx, len, &offset, nonce_counter, stream_block, buf, buf); if (ret != 0) { goto exit; } if (memcmp(buf, aes_tests, len) != 0) { ret = 1; goto exit; } if (verbose != 0) { mbedtls_printf("passed\n"); } } } if (verbose != 0) { mbedtls_printf("\n"); } #endif /* MBEDTLS_CIPHER_MODE_CTR */ #if defined(MBEDTLS_CIPHER_MODE_XTS) /* * XTS mode */ { static const int num_tests = sizeof(aes_test_xts_key) / sizeof(*aes_test_xts_key); mbedtls_aes_xts_context ctx_xts; mbedtls_aes_xts_init(&ctx_xts); for (i = 0; i < num_tests << 1; i++) { const unsigned char *data_unit; u = i >> 1; mode = i & 1; if (verbose != 0) { mbedtls_printf(" AES-XTS-128 (%s): ", (mode == MBEDTLS_AES_DECRYPT) ? "dec" : "enc"); } memset(key, 0, sizeof(key)); memcpy(key, aes_test_xts_key[u], 32); data_unit = aes_test_xts_data_unit[u]; len = sizeof(*aes_test_xts_ct32); if (mode == MBEDTLS_AES_DECRYPT) { ret = mbedtls_aes_xts_setkey_dec(&ctx_xts, key, 256); if (ret != 0) { goto exit; } memcpy(buf, aes_test_xts_ct32[u], len); aes_tests = aes_test_xts_pt32[u]; } else { ret = mbedtls_aes_xts_setkey_enc(&ctx_xts, key, 256); if (ret != 0) { goto exit; } memcpy(buf, aes_test_xts_pt32[u], len); aes_tests = aes_test_xts_ct32[u]; } ret = mbedtls_aes_crypt_xts(&ctx_xts, mode, len, data_unit, buf, buf); if (ret != 0) { goto exit; } if (memcmp(buf, aes_tests, len) != 0) { ret = 1; goto exit; } if (verbose != 0) { mbedtls_printf("passed\n"); } } if (verbose != 0) { mbedtls_printf("\n"); } mbedtls_aes_xts_free(&ctx_xts); } #endif /* MBEDTLS_CIPHER_MODE_XTS */ ret = 0; exit: if (ret != 0 && verbose != 0) { mbedtls_printf("failed\n"); } mbedtls_aes_free(&ctx); return ret; } #endif /* MBEDTLS_SELF_TEST */ #endif /* MBEDTLS_AES_C */ keyring/src/alignment.h0000644000176200001440000006424515006370264014656 0ustar liggesusers/** * \file alignment.h * * \brief Utility code for dealing with unaligned memory accesses */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_LIBRARY_ALIGNMENT_H #define MBEDTLS_LIBRARY_ALIGNMENT_H #include #include #include /* * Define MBEDTLS_EFFICIENT_UNALIGNED_ACCESS for architectures where unaligned memory * accesses are known to be efficient. * * All functions defined here will behave correctly regardless, but might be less * efficient when this is not defined. */ #if defined(__ARM_FEATURE_UNALIGNED) \ || defined(MBEDTLS_ARCH_IS_X86) || defined(MBEDTLS_ARCH_IS_X64) \ || defined(MBEDTLS_PLATFORM_IS_WINDOWS_ON_ARM64) /* * __ARM_FEATURE_UNALIGNED is defined where appropriate by armcc, gcc 7, clang 9 * (and later versions) for Arm v7 and later; all x86 platforms should have * efficient unaligned access. * * https://learn.microsoft.com/en-us/cpp/build/arm64-windows-abi-conventions?view=msvc-170#alignment * specifies that on Windows-on-Arm64, unaligned access is safe (except for uncached * device memory). */ #define MBEDTLS_EFFICIENT_UNALIGNED_ACCESS #endif #if defined(__IAR_SYSTEMS_ICC__) && \ (defined(MBEDTLS_ARCH_IS_ARM64) || defined(MBEDTLS_ARCH_IS_ARM32) \ || defined(__ICCRX__) || defined(__ICCRL78__) || defined(__ICCRISCV__)) #pragma language=save #pragma language=extended #define MBEDTLS_POP_IAR_LANGUAGE_PRAGMA /* IAR recommend this technique for accessing unaligned data in * https://www.iar.com/knowledge/support/technical-notes/compiler/accessing-unaligned-data * This results in a single load / store instruction (if unaligned access is supported). * According to that document, this is only supported on certain architectures. */ #define UINT_UNALIGNED typedef uint16_t __packed mbedtls_uint16_unaligned_t; typedef uint32_t __packed mbedtls_uint32_unaligned_t; typedef uint64_t __packed mbedtls_uint64_unaligned_t; #elif defined(MBEDTLS_COMPILER_IS_GCC) && (MBEDTLS_GCC_VERSION >= 40504) && \ ((MBEDTLS_GCC_VERSION < 60300) || (!defined(MBEDTLS_EFFICIENT_UNALIGNED_ACCESS))) /* * gcc may generate a branch to memcpy for calls like `memcpy(dest, src, 4)` rather than * generating some LDR or LDRB instructions (similar for stores). * * This is architecture dependent: x86-64 seems fine even with old gcc; 32-bit Arm * is affected. To keep it simple, we enable for all architectures. * * For versions of gcc < 5.4.0 this issue always happens. * For gcc < 6.3.0, this issue happens at -O0 * For all versions, this issue happens iff unaligned access is not supported. * * For gcc 4.x, this implementation will generate byte-by-byte loads even if unaligned access is * supported, which is correct but not optimal. * * For performance (and code size, in some cases), we want to avoid the branch and just generate * some inline load/store instructions since the access is small and constant-size. * * The manual states: * "The packed attribute specifies that a variable or structure field should have the smallest * possible alignment—one byte for a variable" * https://gcc.gnu.org/onlinedocs/gcc-4.5.4/gcc/Variable-Attributes.html * * Previous implementations used __attribute__((__aligned__(1)), but had issues with a gcc bug: * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94662 * * Tested with several versions of GCC from 4.5.0 up to 13.2.0 * We don't enable for older than 4.5.0 as this has not been tested. */ #define UINT_UNALIGNED_STRUCT typedef struct { uint16_t x; } __attribute__((packed)) mbedtls_uint16_unaligned_t; typedef struct { uint32_t x; } __attribute__((packed)) mbedtls_uint32_unaligned_t; typedef struct { uint64_t x; } __attribute__((packed)) mbedtls_uint64_unaligned_t; #endif /* * We try to force mbedtls_(get|put)_unaligned_uintXX to be always inline, because this results * in code that is both smaller and faster. IAR and gcc both benefit from this when optimising * for size. */ /** * Read the unsigned 16 bits integer from the given address, which need not * be aligned. * * \param p pointer to 2 bytes of data * \return Data at the given address */ #if defined(__IAR_SYSTEMS_ICC__) #pragma inline = forced #elif defined(__GNUC__) __attribute__((always_inline)) #endif static inline uint16_t mbedtls_get_unaligned_uint16(const void *p) { uint16_t r; #if defined(UINT_UNALIGNED) mbedtls_uint16_unaligned_t *p16 = (mbedtls_uint16_unaligned_t *) p; r = *p16; #elif defined(UINT_UNALIGNED_STRUCT) mbedtls_uint16_unaligned_t *p16 = (mbedtls_uint16_unaligned_t *) p; r = p16->x; #else memcpy(&r, p, sizeof(r)); #endif return r; } /** * Write the unsigned 16 bits integer to the given address, which need not * be aligned. * * \param p pointer to 2 bytes of data * \param x data to write */ #if defined(__IAR_SYSTEMS_ICC__) #pragma inline = forced #elif defined(__GNUC__) __attribute__((always_inline)) #endif static inline void mbedtls_put_unaligned_uint16(void *p, uint16_t x) { #if defined(UINT_UNALIGNED) mbedtls_uint16_unaligned_t *p16 = (mbedtls_uint16_unaligned_t *) p; *p16 = x; #elif defined(UINT_UNALIGNED_STRUCT) mbedtls_uint16_unaligned_t *p16 = (mbedtls_uint16_unaligned_t *) p; p16->x = x; #else memcpy(p, &x, sizeof(x)); #endif } /** * Read the unsigned 32 bits integer from the given address, which need not * be aligned. * * \param p pointer to 4 bytes of data * \return Data at the given address */ #if defined(__IAR_SYSTEMS_ICC__) #pragma inline = forced #elif defined(__GNUC__) __attribute__((always_inline)) #endif static inline uint32_t mbedtls_get_unaligned_uint32(const void *p) { uint32_t r; #if defined(UINT_UNALIGNED) mbedtls_uint32_unaligned_t *p32 = (mbedtls_uint32_unaligned_t *) p; r = *p32; #elif defined(UINT_UNALIGNED_STRUCT) mbedtls_uint32_unaligned_t *p32 = (mbedtls_uint32_unaligned_t *) p; r = p32->x; #else memcpy(&r, p, sizeof(r)); #endif return r; } /** * Write the unsigned 32 bits integer to the given address, which need not * be aligned. * * \param p pointer to 4 bytes of data * \param x data to write */ #if defined(__IAR_SYSTEMS_ICC__) #pragma inline = forced #elif defined(__GNUC__) __attribute__((always_inline)) #endif static inline void mbedtls_put_unaligned_uint32(void *p, uint32_t x) { #if defined(UINT_UNALIGNED) mbedtls_uint32_unaligned_t *p32 = (mbedtls_uint32_unaligned_t *) p; *p32 = x; #elif defined(UINT_UNALIGNED_STRUCT) mbedtls_uint32_unaligned_t *p32 = (mbedtls_uint32_unaligned_t *) p; p32->x = x; #else memcpy(p, &x, sizeof(x)); #endif } /** * Read the unsigned 64 bits integer from the given address, which need not * be aligned. * * \param p pointer to 8 bytes of data * \return Data at the given address */ #if defined(__IAR_SYSTEMS_ICC__) #pragma inline = forced #elif defined(__GNUC__) __attribute__((always_inline)) #endif static inline uint64_t mbedtls_get_unaligned_uint64(const void *p) { uint64_t r; #if defined(UINT_UNALIGNED) mbedtls_uint64_unaligned_t *p64 = (mbedtls_uint64_unaligned_t *) p; r = *p64; #elif defined(UINT_UNALIGNED_STRUCT) mbedtls_uint64_unaligned_t *p64 = (mbedtls_uint64_unaligned_t *) p; r = p64->x; #else memcpy(&r, p, sizeof(r)); #endif return r; } /** * Write the unsigned 64 bits integer to the given address, which need not * be aligned. * * \param p pointer to 8 bytes of data * \param x data to write */ #if defined(__IAR_SYSTEMS_ICC__) #pragma inline = forced #elif defined(__GNUC__) __attribute__((always_inline)) #endif static inline void mbedtls_put_unaligned_uint64(void *p, uint64_t x) { #if defined(UINT_UNALIGNED) mbedtls_uint64_unaligned_t *p64 = (mbedtls_uint64_unaligned_t *) p; *p64 = x; #elif defined(UINT_UNALIGNED_STRUCT) mbedtls_uint64_unaligned_t *p64 = (mbedtls_uint64_unaligned_t *) p; p64->x = x; #else memcpy(p, &x, sizeof(x)); #endif } #if defined(MBEDTLS_POP_IAR_LANGUAGE_PRAGMA) #pragma language=restore #endif /** Byte Reading Macros * * Given a multi-byte integer \p x, MBEDTLS_BYTE_n retrieves the n-th * byte from x, where byte 0 is the least significant byte. */ #define MBEDTLS_BYTE_0(x) ((uint8_t) ((x) & 0xff)) #define MBEDTLS_BYTE_1(x) ((uint8_t) (((x) >> 8) & 0xff)) #define MBEDTLS_BYTE_2(x) ((uint8_t) (((x) >> 16) & 0xff)) #define MBEDTLS_BYTE_3(x) ((uint8_t) (((x) >> 24) & 0xff)) #define MBEDTLS_BYTE_4(x) ((uint8_t) (((x) >> 32) & 0xff)) #define MBEDTLS_BYTE_5(x) ((uint8_t) (((x) >> 40) & 0xff)) #define MBEDTLS_BYTE_6(x) ((uint8_t) (((x) >> 48) & 0xff)) #define MBEDTLS_BYTE_7(x) ((uint8_t) (((x) >> 56) & 0xff)) /* * Detect GCC built-in byteswap routines */ #if defined(__GNUC__) && defined(__GNUC_PREREQ) #if __GNUC_PREREQ(4, 8) #define MBEDTLS_BSWAP16 __builtin_bswap16 #endif /* __GNUC_PREREQ(4,8) */ #if __GNUC_PREREQ(4, 3) #define MBEDTLS_BSWAP32 __builtin_bswap32 #define MBEDTLS_BSWAP64 __builtin_bswap64 #endif /* __GNUC_PREREQ(4,3) */ #endif /* defined(__GNUC__) && defined(__GNUC_PREREQ) */ /* * Detect Clang built-in byteswap routines */ #if defined(__clang__) && defined(__has_builtin) #if __has_builtin(__builtin_bswap16) && !defined(MBEDTLS_BSWAP16) #define MBEDTLS_BSWAP16 __builtin_bswap16 #endif /* __has_builtin(__builtin_bswap16) */ #if __has_builtin(__builtin_bswap32) && !defined(MBEDTLS_BSWAP32) #define MBEDTLS_BSWAP32 __builtin_bswap32 #endif /* __has_builtin(__builtin_bswap32) */ #if __has_builtin(__builtin_bswap64) && !defined(MBEDTLS_BSWAP64) #define MBEDTLS_BSWAP64 __builtin_bswap64 #endif /* __has_builtin(__builtin_bswap64) */ #endif /* defined(__clang__) && defined(__has_builtin) */ /* * Detect MSVC built-in byteswap routines */ #if defined(_MSC_VER) #if !defined(MBEDTLS_BSWAP16) #define MBEDTLS_BSWAP16 _byteswap_ushort #endif #if !defined(MBEDTLS_BSWAP32) #define MBEDTLS_BSWAP32 _byteswap_ulong #endif #if !defined(MBEDTLS_BSWAP64) #define MBEDTLS_BSWAP64 _byteswap_uint64 #endif #endif /* defined(_MSC_VER) */ /* Detect armcc built-in byteswap routine */ #if defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 410000) && !defined(MBEDTLS_BSWAP32) #if defined(__ARM_ACLE) /* ARM Compiler 6 - earlier versions don't need a header */ #include #endif #define MBEDTLS_BSWAP32 __rev #endif /* Detect IAR built-in byteswap routine */ #if defined(__IAR_SYSTEMS_ICC__) #if defined(__ARM_ACLE) #include #define MBEDTLS_BSWAP16(x) ((uint16_t) __rev16((uint32_t) (x))) #define MBEDTLS_BSWAP32 __rev #define MBEDTLS_BSWAP64 __revll #endif #endif /* * Where compiler built-ins are not present, fall back to C code that the * compiler may be able to detect and transform into the relevant bswap or * similar instruction. */ #if !defined(MBEDTLS_BSWAP16) static inline uint16_t mbedtls_bswap16(uint16_t x) { return (x & 0x00ff) << 8 | (x & 0xff00) >> 8; } #define MBEDTLS_BSWAP16 mbedtls_bswap16 #endif /* !defined(MBEDTLS_BSWAP16) */ #if !defined(MBEDTLS_BSWAP32) static inline uint32_t mbedtls_bswap32(uint32_t x) { return (x & 0x000000ff) << 24 | (x & 0x0000ff00) << 8 | (x & 0x00ff0000) >> 8 | (x & 0xff000000) >> 24; } #define MBEDTLS_BSWAP32 mbedtls_bswap32 #endif /* !defined(MBEDTLS_BSWAP32) */ #if !defined(MBEDTLS_BSWAP64) static inline uint64_t mbedtls_bswap64(uint64_t x) { return (x & 0x00000000000000ffULL) << 56 | (x & 0x000000000000ff00ULL) << 40 | (x & 0x0000000000ff0000ULL) << 24 | (x & 0x00000000ff000000ULL) << 8 | (x & 0x000000ff00000000ULL) >> 8 | (x & 0x0000ff0000000000ULL) >> 24 | (x & 0x00ff000000000000ULL) >> 40 | (x & 0xff00000000000000ULL) >> 56; } #define MBEDTLS_BSWAP64 mbedtls_bswap64 #endif /* !defined(MBEDTLS_BSWAP64) */ #if !defined(__BYTE_ORDER__) #if defined(__LITTLE_ENDIAN__) /* IAR defines __xxx_ENDIAN__, but not __BYTE_ORDER__ */ #define MBEDTLS_IS_BIG_ENDIAN 0 #elif defined(__BIG_ENDIAN__) #define MBEDTLS_IS_BIG_ENDIAN 1 #else static const uint16_t mbedtls_byte_order_detector = { 0x100 }; #define MBEDTLS_IS_BIG_ENDIAN (*((unsigned char *) (&mbedtls_byte_order_detector)) == 0x01) #endif #else #if (__BYTE_ORDER__) == (__ORDER_BIG_ENDIAN__) #define MBEDTLS_IS_BIG_ENDIAN 1 #else #define MBEDTLS_IS_BIG_ENDIAN 0 #endif #endif /* !defined(__BYTE_ORDER__) */ /** * Get the unsigned 32 bits integer corresponding to four bytes in * big-endian order (MSB first). * * \param data Base address of the memory to get the four bytes from. * \param offset Offset from \p data of the first and most significant * byte of the four bytes to build the 32 bits unsigned * integer from. */ #define MBEDTLS_GET_UINT32_BE(data, offset) \ ((MBEDTLS_IS_BIG_ENDIAN) \ ? mbedtls_get_unaligned_uint32((data) + (offset)) \ : MBEDTLS_BSWAP32(mbedtls_get_unaligned_uint32((data) + (offset))) \ ) /** * Put in memory a 32 bits unsigned integer in big-endian order. * * \param n 32 bits unsigned integer to put in memory. * \param data Base address of the memory where to put the 32 * bits unsigned integer in. * \param offset Offset from \p data where to put the most significant * byte of the 32 bits unsigned integer \p n. */ #define MBEDTLS_PUT_UINT32_BE(n, data, offset) \ { \ if (MBEDTLS_IS_BIG_ENDIAN) \ { \ mbedtls_put_unaligned_uint32((data) + (offset), (uint32_t) (n)); \ } \ else \ { \ mbedtls_put_unaligned_uint32((data) + (offset), MBEDTLS_BSWAP32((uint32_t) (n))); \ } \ } /** * Get the unsigned 32 bits integer corresponding to four bytes in * little-endian order (LSB first). * * \param data Base address of the memory to get the four bytes from. * \param offset Offset from \p data of the first and least significant * byte of the four bytes to build the 32 bits unsigned * integer from. */ #define MBEDTLS_GET_UINT32_LE(data, offset) \ ((MBEDTLS_IS_BIG_ENDIAN) \ ? MBEDTLS_BSWAP32(mbedtls_get_unaligned_uint32((data) + (offset))) \ : mbedtls_get_unaligned_uint32((data) + (offset)) \ ) /** * Put in memory a 32 bits unsigned integer in little-endian order. * * \param n 32 bits unsigned integer to put in memory. * \param data Base address of the memory where to put the 32 * bits unsigned integer in. * \param offset Offset from \p data where to put the least significant * byte of the 32 bits unsigned integer \p n. */ #define MBEDTLS_PUT_UINT32_LE(n, data, offset) \ { \ if (MBEDTLS_IS_BIG_ENDIAN) \ { \ mbedtls_put_unaligned_uint32((data) + (offset), MBEDTLS_BSWAP32((uint32_t) (n))); \ } \ else \ { \ mbedtls_put_unaligned_uint32((data) + (offset), ((uint32_t) (n))); \ } \ } /** * Get the unsigned 16 bits integer corresponding to two bytes in * little-endian order (LSB first). * * \param data Base address of the memory to get the two bytes from. * \param offset Offset from \p data of the first and least significant * byte of the two bytes to build the 16 bits unsigned * integer from. */ #define MBEDTLS_GET_UINT16_LE(data, offset) \ ((MBEDTLS_IS_BIG_ENDIAN) \ ? MBEDTLS_BSWAP16(mbedtls_get_unaligned_uint16((data) + (offset))) \ : mbedtls_get_unaligned_uint16((data) + (offset)) \ ) /** * Put in memory a 16 bits unsigned integer in little-endian order. * * \param n 16 bits unsigned integer to put in memory. * \param data Base address of the memory where to put the 16 * bits unsigned integer in. * \param offset Offset from \p data where to put the least significant * byte of the 16 bits unsigned integer \p n. */ #define MBEDTLS_PUT_UINT16_LE(n, data, offset) \ { \ if (MBEDTLS_IS_BIG_ENDIAN) \ { \ mbedtls_put_unaligned_uint16((data) + (offset), MBEDTLS_BSWAP16((uint16_t) (n))); \ } \ else \ { \ mbedtls_put_unaligned_uint16((data) + (offset), (uint16_t) (n)); \ } \ } /** * Get the unsigned 16 bits integer corresponding to two bytes in * big-endian order (MSB first). * * \param data Base address of the memory to get the two bytes from. * \param offset Offset from \p data of the first and most significant * byte of the two bytes to build the 16 bits unsigned * integer from. */ #define MBEDTLS_GET_UINT16_BE(data, offset) \ ((MBEDTLS_IS_BIG_ENDIAN) \ ? mbedtls_get_unaligned_uint16((data) + (offset)) \ : MBEDTLS_BSWAP16(mbedtls_get_unaligned_uint16((data) + (offset))) \ ) /** * Put in memory a 16 bits unsigned integer in big-endian order. * * \param n 16 bits unsigned integer to put in memory. * \param data Base address of the memory where to put the 16 * bits unsigned integer in. * \param offset Offset from \p data where to put the most significant * byte of the 16 bits unsigned integer \p n. */ #define MBEDTLS_PUT_UINT16_BE(n, data, offset) \ { \ if (MBEDTLS_IS_BIG_ENDIAN) \ { \ mbedtls_put_unaligned_uint16((data) + (offset), (uint16_t) (n)); \ } \ else \ { \ mbedtls_put_unaligned_uint16((data) + (offset), MBEDTLS_BSWAP16((uint16_t) (n))); \ } \ } /** * Get the unsigned 24 bits integer corresponding to three bytes in * big-endian order (MSB first). * * \param data Base address of the memory to get the three bytes from. * \param offset Offset from \p data of the first and most significant * byte of the three bytes to build the 24 bits unsigned * integer from. */ #define MBEDTLS_GET_UINT24_BE(data, offset) \ ( \ ((uint32_t) (data)[(offset)] << 16) \ | ((uint32_t) (data)[(offset) + 1] << 8) \ | ((uint32_t) (data)[(offset) + 2]) \ ) /** * Put in memory a 24 bits unsigned integer in big-endian order. * * \param n 24 bits unsigned integer to put in memory. * \param data Base address of the memory where to put the 24 * bits unsigned integer in. * \param offset Offset from \p data where to put the most significant * byte of the 24 bits unsigned integer \p n. */ #define MBEDTLS_PUT_UINT24_BE(n, data, offset) \ { \ (data)[(offset)] = MBEDTLS_BYTE_2(n); \ (data)[(offset) + 1] = MBEDTLS_BYTE_1(n); \ (data)[(offset) + 2] = MBEDTLS_BYTE_0(n); \ } /** * Get the unsigned 24 bits integer corresponding to three bytes in * little-endian order (LSB first). * * \param data Base address of the memory to get the three bytes from. * \param offset Offset from \p data of the first and least significant * byte of the three bytes to build the 24 bits unsigned * integer from. */ #define MBEDTLS_GET_UINT24_LE(data, offset) \ ( \ ((uint32_t) (data)[(offset)]) \ | ((uint32_t) (data)[(offset) + 1] << 8) \ | ((uint32_t) (data)[(offset) + 2] << 16) \ ) /** * Put in memory a 24 bits unsigned integer in little-endian order. * * \param n 24 bits unsigned integer to put in memory. * \param data Base address of the memory where to put the 24 * bits unsigned integer in. * \param offset Offset from \p data where to put the least significant * byte of the 24 bits unsigned integer \p n. */ #define MBEDTLS_PUT_UINT24_LE(n, data, offset) \ { \ (data)[(offset)] = MBEDTLS_BYTE_0(n); \ (data)[(offset) + 1] = MBEDTLS_BYTE_1(n); \ (data)[(offset) + 2] = MBEDTLS_BYTE_2(n); \ } /** * Get the unsigned 64 bits integer corresponding to eight bytes in * big-endian order (MSB first). * * \param data Base address of the memory to get the eight bytes from. * \param offset Offset from \p data of the first and most significant * byte of the eight bytes to build the 64 bits unsigned * integer from. */ #define MBEDTLS_GET_UINT64_BE(data, offset) \ ((MBEDTLS_IS_BIG_ENDIAN) \ ? mbedtls_get_unaligned_uint64((data) + (offset)) \ : MBEDTLS_BSWAP64(mbedtls_get_unaligned_uint64((data) + (offset))) \ ) /** * Put in memory a 64 bits unsigned integer in big-endian order. * * \param n 64 bits unsigned integer to put in memory. * \param data Base address of the memory where to put the 64 * bits unsigned integer in. * \param offset Offset from \p data where to put the most significant * byte of the 64 bits unsigned integer \p n. */ #define MBEDTLS_PUT_UINT64_BE(n, data, offset) \ { \ if (MBEDTLS_IS_BIG_ENDIAN) \ { \ mbedtls_put_unaligned_uint64((data) + (offset), (uint64_t) (n)); \ } \ else \ { \ mbedtls_put_unaligned_uint64((data) + (offset), MBEDTLS_BSWAP64((uint64_t) (n))); \ } \ } /** * Get the unsigned 64 bits integer corresponding to eight bytes in * little-endian order (LSB first). * * \param data Base address of the memory to get the eight bytes from. * \param offset Offset from \p data of the first and least significant * byte of the eight bytes to build the 64 bits unsigned * integer from. */ #define MBEDTLS_GET_UINT64_LE(data, offset) \ ((MBEDTLS_IS_BIG_ENDIAN) \ ? MBEDTLS_BSWAP64(mbedtls_get_unaligned_uint64((data) + (offset))) \ : mbedtls_get_unaligned_uint64((data) + (offset)) \ ) /** * Put in memory a 64 bits unsigned integer in little-endian order. * * \param n 64 bits unsigned integer to put in memory. * \param data Base address of the memory where to put the 64 * bits unsigned integer in. * \param offset Offset from \p data where to put the least significant * byte of the 64 bits unsigned integer \p n. */ #define MBEDTLS_PUT_UINT64_LE(n, data, offset) \ { \ if (MBEDTLS_IS_BIG_ENDIAN) \ { \ mbedtls_put_unaligned_uint64((data) + (offset), MBEDTLS_BSWAP64((uint64_t) (n))); \ } \ else \ { \ mbedtls_put_unaligned_uint64((data) + (offset), (uint64_t) (n)); \ } \ } #endif /* MBEDTLS_LIBRARY_ALIGNMENT_H */ keyring/src/poly1305_donna.h0000644000176200001440000000044214775227066015355 0ustar liggesusers#ifndef poly1305_donna_H #define poly1305_donna_H #include #include "onetimeauth_poly1305.h" #include "crypto_onetimeauth_poly1305.h" extern struct crypto_onetimeauth_poly1305_implementation crypto_onetimeauth_poly1305_donna_implementation; #endif /* poly1305_donna_H */ keyring/src/keyring_wincred.c0000644000176200001440000001031514322212134016032 0ustar liggesusers /* Avoid warning about empty compilation unit. */ void keyring_wincred_dummy(void) { } #ifdef _WIN32 #include #include #include #include #include #include void keyring_wincred_handle_status(const char *func, BOOL status) { if (status == FALSE) { DWORD errorcode = GetLastError(); LPVOID lpMsgBuf; char *msg; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errorcode, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &lpMsgBuf, 0, NULL ); msg = R_alloc(1, strlen(lpMsgBuf) + 1); strcpy(msg, lpMsgBuf); LocalFree(lpMsgBuf); error("Windows credential store error in '%s': %s", func, msg); } } SEXP keyring_wincred_get(SEXP target) { const char *ctarget = CHAR(STRING_ELT(target, 0)); CREDENTIAL *cred; BOOL status = CredRead(ctarget, CRED_TYPE_GENERIC, /* Flags = */ 0, &cred); keyring_wincred_handle_status("get", status); SEXP result = PROTECT(allocVector(RAWSXP, cred->CredentialBlobSize)); memcpy(RAW(result), cred->CredentialBlob, cred->CredentialBlobSize); CredFree(cred); UNPROTECT(1); return result; } SEXP keyring_wincred_exists(SEXP target) { const char *ctarget = CHAR(STRING_ELT(target, 0)); CREDENTIAL *cred = NULL; BOOL status = CredRead(ctarget, CRED_TYPE_GENERIC, /* Flags = */ 0, &cred); DWORD errorcode = status ? 0 : GetLastError(); if (errorcode != 0 && errorcode != ERROR_NOT_FOUND) { keyring_wincred_handle_status("exists", status); } if (cred) CredFree(cred); return ScalarLogical(errorcode == 0); } SEXP keyring_wincred_set(SEXP target, SEXP password, SEXP username, SEXP session) { const char *ctarget = CHAR(STRING_ELT(target, 0)); const char *cusername = isNull(username) ? NULL : CHAR(STRING_ELT(username, 0)); int csession = LOGICAL(session)[0]; CREDENTIAL cred = { 0 }; BOOL status; cred.Type = CRED_TYPE_GENERIC; cred.TargetName = (char*) ctarget; cred.CredentialBlobSize = LENGTH(password); cred.CredentialBlob = (LPBYTE) RAW(password); cred.Persist = csession ? CRED_PERSIST_SESSION : CRED_PERSIST_LOCAL_MACHINE; cred.UserName = (char*) cusername; status = CredWrite(&cred, /* Flags = */ 0); keyring_wincred_handle_status("set", status); return R_NilValue; } SEXP keyring_wincred_delete(SEXP target) { const char* ctarget = CHAR(STRING_ELT(target, 0)); BOOL status = CredDelete(ctarget, CRED_TYPE_GENERIC, /* Flags = */ 0); keyring_wincred_handle_status("delete", status); return R_NilValue; } SEXP keyring_wincred_enumerate(SEXP filter) { const char *cfilter = CHAR(STRING_ELT(filter, 0)); DWORD count; PCREDENTIAL *creds = NULL; BOOL status = CredEnumerate(cfilter, /* Flags = */ 0, &count, &creds); DWORD errorcode = status ? 0 : GetLastError(); /* If there are no keys, then an error is thrown. But for us this is a normal result, and we just return an empty table. */ if (status == FALSE && errorcode == ERROR_NOT_FOUND) { SEXP result = PROTECT(allocVector(STRSXP, 0)); UNPROTECT(1); return result; } else if (status == FALSE) { if (creds != NULL) CredFree(creds); keyring_wincred_handle_status("list", status); return R_NilValue; } else { size_t i, num = (size_t) count; SEXP result = PROTECT(allocVector(STRSXP, num)); for (i = 0; i < count; i++) { SET_STRING_ELT(result, i, mkChar(creds[i]->TargetName)); } CredFree(creds); UNPROTECT(1); return result; } } #else #include #include #include SEXP keyring_wincred_get(SEXP target) { error("only works on Windows"); return R_NilValue; } SEXP keyring_wincred_exists(SEXP target) { error("only works on Windows"); return R_NilValue; } SEXP keyring_wincred_set(SEXP target, SEXP password, SEXP username, SEXP session) { error("only works on Windows"); return R_NilValue; } SEXP keyring_wincred_delete(SEXP target) { error("only works on Windows"); return R_NilValue; } SEXP keyring_wincred_enumerate(SEXP filter) { error("only works on Windows"); return R_NilValue; } #endif // _WIN32 keyring/src/crypto_onetimeauth_poly1305.h0000644000176200001440000000422514775227066020203 0ustar liggesusers#ifndef crypto_onetimeauth_poly1305_H #define crypto_onetimeauth_poly1305_H #include #include #include #include #include "sodium.h" #ifdef __cplusplus # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wlong-long" # endif extern "C" { #endif typedef struct CRYPTO_ALIGN(16) crypto_onetimeauth_poly1305_state { unsigned char opaque[256]; } crypto_onetimeauth_poly1305_state; SODIUM_EXPORT size_t crypto_onetimeauth_poly1305_statebytes(void); #define crypto_onetimeauth_poly1305_BYTES 16U SODIUM_EXPORT size_t crypto_onetimeauth_poly1305_bytes(void); #define crypto_onetimeauth_poly1305_KEYBYTES 32U SODIUM_EXPORT size_t crypto_onetimeauth_poly1305_keybytes(void); SODIUM_EXPORT int crypto_onetimeauth_poly1305(unsigned char *out, const unsigned char *in, unsigned long long inlen, const unsigned char *k) __attribute__ ((nonnull(1, 4))); SODIUM_EXPORT int crypto_onetimeauth_poly1305_verify(const unsigned char *h, const unsigned char *in, unsigned long long inlen, const unsigned char *k) __attribute__ ((warn_unused_result)) __attribute__ ((nonnull(1, 4))); SODIUM_EXPORT int crypto_onetimeauth_poly1305_init(crypto_onetimeauth_poly1305_state *state, const unsigned char *key) __attribute__ ((nonnull)); SODIUM_EXPORT int crypto_onetimeauth_poly1305_update(crypto_onetimeauth_poly1305_state *state, const unsigned char *in, unsigned long long inlen) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_onetimeauth_poly1305_final(crypto_onetimeauth_poly1305_state *state, unsigned char *out) __attribute__ ((nonnull)); SODIUM_EXPORT void crypto_onetimeauth_poly1305_keygen(unsigned char k[crypto_onetimeauth_poly1305_KEYBYTES]) __attribute__ ((nonnull)); #ifdef __cplusplus } #endif #endif keyring/src/crypto_core_salsa2012.h0000644000176200001440000000146014775227066016723 0ustar liggesusers#ifndef crypto_core_salsa2012_H #define crypto_core_salsa2012_H #include #include "sodium.h" #ifdef __cplusplus extern "C" { #endif #define crypto_core_salsa2012_OUTPUTBYTES 64U SODIUM_EXPORT size_t crypto_core_salsa2012_outputbytes(void); #define crypto_core_salsa2012_INPUTBYTES 16U SODIUM_EXPORT size_t crypto_core_salsa2012_inputbytes(void); #define crypto_core_salsa2012_KEYBYTES 32U SODIUM_EXPORT size_t crypto_core_salsa2012_keybytes(void); #define crypto_core_salsa2012_CONSTBYTES 16U SODIUM_EXPORT size_t crypto_core_salsa2012_constbytes(void); SODIUM_EXPORT int crypto_core_salsa2012(unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c) __attribute__ ((nonnull(1, 2, 3))); #ifdef __cplusplus } #endif #endif keyring/src/Makevars.in0000644000176200001440000000000115006347672014613 0ustar liggesusers keyring/src/sodium.c0000644000176200001440000001313314775230367014174 0ustar liggesusers#include #include #include #include #include "crypto_generichash.h" #include "crypto_secretbox.h" #include "sodium.h" char *sodium_bin2hex(char *const hex, const size_t hex_maxlen, const unsigned char *const bin, const size_t bin_len) { size_t i = (size_t)0U; unsigned int x; int b; int c; if (bin_len >= SIZE_MAX / 2 || hex_maxlen <= bin_len * 2U) { Rf_error("Internal sodium error"); } while (i < bin_len) { c = bin[i] & 0xf; b = bin[i] >> 4; x = (unsigned char)(87U + c + (((c - 10U) >> 8) & ~38U)) << 8 | (unsigned char)(87U + b + (((b - 10U) >> 8) & ~38U)); hex[i * 2U] = (char)x; x >>= 8; hex[i * 2U + 1U] = (char)x; i++; } hex[i * 2U] = 0U; return hex; } int sodium_hex2bin(unsigned char *const bin, const size_t bin_maxlen, const char *const hex, const size_t hex_len, const char *const ignore, size_t *const bin_len, const char **const hex_end) { size_t bin_pos = (size_t)0U; size_t hex_pos = (size_t)0U; int ret = 0; unsigned char c; unsigned char c_acc = 0U; unsigned char c_alpha0, c_alpha; unsigned char c_num0, c_num; unsigned char c_val; unsigned char state = 0U; while (hex_pos < hex_len) { c = (unsigned char)hex[hex_pos]; c_num = c ^ 48U; c_num0 = (c_num - 10U) >> 8; c_alpha = (c & ~32U) - 55U; c_alpha0 = ((c_alpha - 10U) ^ (c_alpha - 16U)) >> 8; if ((c_num0 | c_alpha0) == 0U) { if (ignore != NULL && state == 0U && strchr(ignore, c) != NULL) { hex_pos++; continue; } break; } c_val = (c_num0 & c_num) | (c_alpha0 & c_alpha); if (bin_pos >= bin_maxlen) { ret = -1; errno = ERANGE; break; } if (state == 0U) { c_acc = c_val * 16U; } else { bin[bin_pos++] = c_acc | c_val; } state = ~state; hex_pos++; } if (state != 0U) { hex_pos--; errno = EINVAL; ret = -1; } if (ret != 0) { bin_pos = (size_t)0U; } if (hex_end != NULL) { *hex_end = &hex[hex_pos]; } else if (hex_pos != hex_len) { errno = EINVAL; ret = -1; } if (bin_len != NULL) { *bin_len = bin_pos; } return ret; } SEXP rsodium_randombytes_buf(SEXP length) { size_t size = Rf_asInteger(length); SEXP res = Rf_allocVector(RAWSXP, size); randombytes_buf(RAW(res), size); return res; } SEXP rsodium_bin2hex(SEXP bin) { size_t bin_len = LENGTH(bin); size_t hex_len = bin_len * 2 + 1; char *hex = malloc(hex_len); if (NULL == sodium_bin2hex(hex, hex_len, RAW(bin), bin_len)) { free(hex); Rf_error("Overflow error, failed to convert to hex"); } SEXP res = Rf_mkString(hex); free(hex); return res; } SEXP rsodium_hex2bin(SEXP hex, SEXP ignore) { int hex_len = LENGTH(STRING_ELT(hex, 0)); int max_len = hex_len / 2; unsigned char *bin = malloc(max_len); size_t bin_len; const char *hex_end; if (sodium_hex2bin(bin, max_len, CHAR(STRING_ELT(hex, 0)), hex_len, CHAR(STRING_ELT(ignore, 0)), &bin_len, &hex_end)) { free(bin); Rf_error("Overflow error, failed to parse hex."); } SEXP res = Rf_allocVector(RAWSXP, bin_len); memcpy(RAW(res), bin, bin_len); free(bin); return res; } SEXP rsodium_crypto_secret_encrypt(SEXP message, SEXP key, SEXP nonce) { if (LENGTH(key) != crypto_secretbox_KEYBYTES) { Rf_error("Invalid key: must be exactly %d bytes", crypto_secretbox_KEYBYTES); } if (LENGTH(nonce) != crypto_secretbox_NONCEBYTES) { Rf_error("Invalid nonce: must be exactly %d bytes", crypto_secretbox_NONCEBYTES); } R_xlen_t mlen = XLENGTH(message); R_xlen_t clen = mlen + crypto_secretbox_MACBYTES; SEXP res = PROTECT(Rf_allocVector(RAWSXP, clen)); if (crypto_secretbox_easy(RAW(res), RAW(message), mlen, RAW(nonce), RAW(key))) { Rf_error("Failed to encrypt"); } UNPROTECT(1); return res; } SEXP rsodium_crypto_secret_decrypt(SEXP cipher, SEXP key, SEXP nonce) { if (LENGTH(key) != crypto_secretbox_KEYBYTES) { Rf_error("Invalid key. Key must be exactly %d bytes", crypto_secretbox_KEYBYTES); } if (LENGTH(nonce) != crypto_secretbox_NONCEBYTES) { Rf_error("Invalid key. Key must be exactly %d bytes", crypto_secretbox_NONCEBYTES); } R_xlen_t clen = XLENGTH(cipher); R_xlen_t mlen = clen - crypto_secretbox_MACBYTES; SEXP res = PROTECT(Rf_allocVector(RAWSXP, mlen)); if (crypto_secretbox_open_easy(RAW(res), RAW(cipher), clen, RAW(nonce), RAW(key))) { Rf_error("Failed to decrypt"); } UNPROTECT(1); return res; } SEXP rsodium_crypto_generichash(SEXP buf, SEXP size, SEXP key) { int outlen = Rf_asInteger(size); if (outlen < crypto_generichash_BYTES_MIN || outlen > crypto_generichash_BYTES_MAX) { Rf_error("Invalid output length, must be in between %d and %d", crypto_generichash_BYTES_MIN, crypto_generichash_BYTES_MAX); } unsigned char *keyval = NULL; int keysize = 0; if (key != R_NilValue) { keysize = LENGTH(key); keyval = RAW(key); if (keysize < crypto_generichash_KEYBYTES_MIN || keysize > crypto_generichash_KEYBYTES_MAX) { Rf_error("Invalid key size, must be between %d and %d bytes", crypto_generichash_KEYBYTES_MIN, crypto_generichash_KEYBYTES_MAX); } } SEXP res = PROTECT(Rf_allocVector(RAWSXP, outlen)); if (crypto_generichash(RAW(res), outlen, RAW(buf), XLENGTH(buf), keyval, keysize)) { Rf_error("Failed to hash"); } UNPROTECT(1); return res; } keyring/src/sodium.h0000644000176200001440000000650414775227066014207 0ustar liggesusers#ifndef KEYRING_SODIUM_H #define KEYRING_SODIUM_H #include #include #include "endianness.h" #if IS_BIG_ENDIAN #define NATIVE_BIG_ENDIAN #else #define NATIVE_LITTLE_ENDIAN #endif void sodium_memzero(void * const pnt, const size_t len); void randombytes_buf(void * const buf, const size_t size); #define SODIUM_EXPORT #define SODIUM_MIN(A, B) ((A) < (B) ? (A) : (B)) #define SODIUM_SIZE_MAX SODIUM_MIN(UINT64_MAX, SIZE_MAX) #define randombytes_BYTES_MAX SODIUM_MIN(SODIUM_SIZE_MAX, 0xffffffffUL) #define COMPILER_ASSERT(X) (void) sizeof(char[(X) ? 1 : -1]) #ifndef SODIUM_C99 # if defined(__cplusplus) || !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L # define SODIUM_C99(X) # else # define SODIUM_C99(X) X # endif #endif #ifndef CRYPTO_ALIGN # if defined(__INTEL_COMPILER) || defined(_MSC_VER) # define CRYPTO_ALIGN(x) __declspec(align(x)) # else # define CRYPTO_ALIGN(x) __attribute__ ((aligned(x))) # endif #endif #define ROTL32(X, B) rotl32((X), (B)) static inline uint32_t rotl32(const uint32_t x, const int b) { return (x << b) | (x >> (32 - b)); } #define ROTR64(X, B) rotr64((X), (B)) static inline uint64_t rotr64(const uint64_t x, const int b) { return (x >> b) | (x << (64 - b)); } #define LOAD32_LE(SRC) load32_le(SRC) static inline uint32_t load32_le(const uint8_t src[4]) { #ifdef NATIVE_LITTLE_ENDIAN uint32_t w; memcpy(&w, src, sizeof w); return w; #else uint32_t w = (uint32_t) src[0]; w |= (uint32_t) src[1] << 8; w |= (uint32_t) src[2] << 16; w |= (uint32_t) src[3] << 24; return w; #endif } #define STORE32_LE(DST, W) store32_le((DST), (W)) static inline void store32_le(uint8_t dst[4], uint32_t w) { #ifdef NATIVE_LITTLE_ENDIAN memcpy(dst, &w, sizeof w); #else dst[0] = (uint8_t) w; w >>= 8; dst[1] = (uint8_t) w; w >>= 8; dst[2] = (uint8_t) w; w >>= 8; dst[3] = (uint8_t) w; #endif } #define LOAD64_LE(SRC) load64_le(SRC) static inline uint64_t load64_le(const uint8_t src[8]) { #ifdef NATIVE_LITTLE_ENDIAN uint64_t w; memcpy(&w, src, sizeof w); return w; #else uint64_t w = (uint64_t) src[0]; w |= (uint64_t) src[1] << 8; w |= (uint64_t) src[2] << 16; w |= (uint64_t) src[3] << 24; w |= (uint64_t) src[4] << 32; w |= (uint64_t) src[5] << 40; w |= (uint64_t) src[6] << 48; w |= (uint64_t) src[7] << 56; return w; #endif } #define STORE64_LE(DST, W) store64_le((DST), (W)) static inline void store64_le(uint8_t dst[8], uint64_t w) { #ifdef NATIVE_LITTLE_ENDIAN memcpy(dst, &w, sizeof w); #else dst[0] = (uint8_t) w; w >>= 8; dst[1] = (uint8_t) w; w >>= 8; dst[2] = (uint8_t) w; w >>= 8; dst[3] = (uint8_t) w; w >>= 8; dst[4] = (uint8_t) w; w >>= 8; dst[5] = (uint8_t) w; w >>= 8; dst[6] = (uint8_t) w; w >>= 8; dst[7] = (uint8_t) w; #endif } typedef struct randombytes_implementation { const char *(*implementation_name)(void); /* required */ uint32_t (*random)(void); /* required */ void (*stir)(void); /* optional */ uint32_t (*uniform)(const uint32_t upper_bound); /* optional, a default implementation will be used if NULL */ void (*buf)(void * const buf, const size_t size); /* required */ int (*close)(void); /* optional */ } randombytes_implementation; #endif // KEYRING_SODIUM_H keyring/src/crypto_secretbox.h0000644000176200001440000000634014775227066016303 0ustar liggesusers#ifndef crypto_secretbox_H #define crypto_secretbox_H #include #include "crypto_secretbox_xsalsa20poly1305.h" #ifdef __cplusplus # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wlong-long" # endif extern "C" { #endif #define crypto_secretbox_KEYBYTES crypto_secretbox_xsalsa20poly1305_KEYBYTES SODIUM_EXPORT size_t crypto_secretbox_keybytes(void); #define crypto_secretbox_NONCEBYTES crypto_secretbox_xsalsa20poly1305_NONCEBYTES SODIUM_EXPORT size_t crypto_secretbox_noncebytes(void); #define crypto_secretbox_MACBYTES crypto_secretbox_xsalsa20poly1305_MACBYTES SODIUM_EXPORT size_t crypto_secretbox_macbytes(void); #define crypto_secretbox_PRIMITIVE "xsalsa20poly1305" SODIUM_EXPORT const char *crypto_secretbox_primitive(void); #define crypto_secretbox_MESSAGEBYTES_MAX crypto_secretbox_xsalsa20poly1305_MESSAGEBYTES_MAX SODIUM_EXPORT size_t crypto_secretbox_messagebytes_max(void); SODIUM_EXPORT int crypto_secretbox_easy(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, const unsigned char *k) __attribute__ ((nonnull(1, 4, 5))); SODIUM_EXPORT int crypto_secretbox_open_easy(unsigned char *m, const unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) __attribute__ ((warn_unused_result)) __attribute__ ((nonnull(2, 4, 5))); SODIUM_EXPORT int crypto_secretbox_detached(unsigned char *c, unsigned char *mac, const unsigned char *m, unsigned long long mlen, const unsigned char *n, const unsigned char *k) __attribute__ ((nonnull(1, 2, 5, 6))); SODIUM_EXPORT int crypto_secretbox_open_detached(unsigned char *m, const unsigned char *c, const unsigned char *mac, unsigned long long clen, const unsigned char *n, const unsigned char *k) __attribute__ ((warn_unused_result)) __attribute__ ((nonnull(2, 3, 5, 6))); SODIUM_EXPORT void crypto_secretbox_keygen(unsigned char k[crypto_secretbox_KEYBYTES]) __attribute__ ((nonnull)); /* -- NaCl compatibility interface ; Requires padding -- */ #define crypto_secretbox_ZEROBYTES crypto_secretbox_xsalsa20poly1305_ZEROBYTES SODIUM_EXPORT size_t crypto_secretbox_zerobytes(void); #define crypto_secretbox_BOXZEROBYTES crypto_secretbox_xsalsa20poly1305_BOXZEROBYTES SODIUM_EXPORT size_t crypto_secretbox_boxzerobytes(void); SODIUM_EXPORT int crypto_secretbox(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, const unsigned char *k) __attribute__ ((nonnull(1, 4, 5))); SODIUM_EXPORT int crypto_secretbox_open(unsigned char *m, const unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) __attribute__ ((warn_unused_result)) __attribute__ ((nonnull(2, 4, 5))); #ifdef __cplusplus } #endif #endif keyring/src/sodium-utils.c0000644000176200001440000000040014775227066015325 0ustar liggesusers#include void sodium_memzero(void * const pnt, const size_t len) { volatile unsigned char *volatile pnt_ = (volatile unsigned char *volatile) pnt; size_t i = (size_t) 0U; while (i < len) { pnt_[i++] = 0U; } } keyring/src/crypto_core_salsa208.h0000644000176200001440000000171014775227066016646 0ustar liggesusers#ifndef crypto_core_salsa208_H #define crypto_core_salsa208_H #include #include "sodium.h" #ifdef __cplusplus extern "C" { #endif #define crypto_core_salsa208_OUTPUTBYTES 64U SODIUM_EXPORT size_t crypto_core_salsa208_outputbytes(void) __attribute__ ((deprecated)); #define crypto_core_salsa208_INPUTBYTES 16U SODIUM_EXPORT size_t crypto_core_salsa208_inputbytes(void) __attribute__ ((deprecated)); #define crypto_core_salsa208_KEYBYTES 32U SODIUM_EXPORT size_t crypto_core_salsa208_keybytes(void) __attribute__ ((deprecated)); #define crypto_core_salsa208_CONSTBYTES 16U SODIUM_EXPORT size_t crypto_core_salsa208_constbytes(void) __attribute__ ((deprecated)); SODIUM_EXPORT int crypto_core_salsa208(unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c) __attribute__ ((nonnull(1, 2, 3))); #ifdef __cplusplus } #endif #endif keyring/src/aesni.h0000644000176200001440000001306115006370264013765 0ustar liggesusers/** * \file aesni.h * * \brief AES-NI for hardware AES acceleration on some Intel processors * * \warning These functions are only for internal use by other library * functions; you must not call them directly. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_AESNI_H #define MBEDTLS_AESNI_H #include "mbedtls/build_info.h" #include "mbedtls/aes.h" #define MBEDTLS_AESNI_AES 0x02000000u #define MBEDTLS_AESNI_CLMUL 0x00000002u #if defined(MBEDTLS_AESNI_C) && \ (defined(MBEDTLS_ARCH_IS_X64) || defined(MBEDTLS_ARCH_IS_X86)) /* Can we do AESNI with intrinsics? * (Only implemented with certain compilers, only for certain targets.) */ #undef MBEDTLS_AESNI_HAVE_INTRINSICS #if defined(_MSC_VER) && !defined(__clang__) /* Visual Studio supports AESNI intrinsics since VS 2008 SP1. We only support * VS 2013 and up for other reasons anyway, so no need to check the version. */ #define MBEDTLS_AESNI_HAVE_INTRINSICS #endif /* GCC-like compilers: currently, we only support intrinsics if the requisite * target flag is enabled when building the library (e.g. `gcc -mpclmul -msse2` * or `clang -maes -mpclmul`). */ #if (defined(__GNUC__) || defined(__clang__)) && defined(__AES__) && defined(__PCLMUL__) #define MBEDTLS_AESNI_HAVE_INTRINSICS #endif /* For 32-bit, we only support intrinsics */ #if defined(MBEDTLS_ARCH_IS_X86) && (defined(__GNUC__) || defined(__clang__)) #define MBEDTLS_AESNI_HAVE_INTRINSICS #endif /* Choose the implementation of AESNI, if one is available. * * Favor the intrinsics-based implementation if it's available, for better * maintainability. * Performance is about the same (see #7380). * In the long run, we will likely remove the assembly implementation. */ #if defined(MBEDTLS_AESNI_HAVE_INTRINSICS) #define MBEDTLS_AESNI_HAVE_CODE 2 // via intrinsics #elif defined(MBEDTLS_HAVE_ASM) && \ (defined(__GNUC__) || defined(__clang__)) && defined(MBEDTLS_ARCH_IS_X64) /* Can we do AESNI with inline assembly? * (Only implemented with gas syntax, only for 64-bit.) */ #define MBEDTLS_AESNI_HAVE_CODE 1 // via assembly #else #error "MBEDTLS_AESNI_C defined, but neither intrinsics nor assembly available" #endif #if defined(MBEDTLS_AESNI_HAVE_CODE) #ifdef __cplusplus extern "C" { #endif /** * \brief Internal function to detect the AES-NI feature in CPUs. * * \note This function is only for internal use by other library * functions; you must not call it directly. * * \param what The feature to detect * (MBEDTLS_AESNI_AES or MBEDTLS_AESNI_CLMUL) * * \return 1 if CPU has support for the feature, 0 otherwise */ #if !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) int mbedtls_aesni_has_support(unsigned int what); #else #define mbedtls_aesni_has_support(what) 1 #endif /** * \brief Internal AES-NI AES-ECB block encryption and decryption * * \note This function is only for internal use by other library * functions; you must not call it directly. * * \param ctx AES context * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT * \param input 16-byte input block * \param output 16-byte output block * * \return 0 on success (cannot fail) */ int mbedtls_aesni_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]); /** * \brief Internal GCM multiplication: c = a * b in GF(2^128) * * \note This function is only for internal use by other library * functions; you must not call it directly. * * \param c Result * \param a First operand * \param b Second operand * * \note Both operands and result are bit strings interpreted as * elements of GF(2^128) as per the GCM spec. */ void mbedtls_aesni_gcm_mult(unsigned char c[16], const unsigned char a[16], const unsigned char b[16]); #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) /** * \brief Internal round key inversion. This function computes * decryption round keys from the encryption round keys. * * \note This function is only for internal use by other library * functions; you must not call it directly. * * \param invkey Round keys for the equivalent inverse cipher * \param fwdkey Original round keys (for encryption) * \param nr Number of rounds (that is, number of round keys minus one) */ void mbedtls_aesni_inverse_key(unsigned char *invkey, const unsigned char *fwdkey, int nr); #endif /* !MBEDTLS_BLOCK_CIPHER_NO_DECRYPT */ /** * \brief Internal key expansion for encryption * * \note This function is only for internal use by other library * functions; you must not call it directly. * * \param rk Destination buffer where the round keys are written * \param key Encryption key * \param bits Key size in bits (must be 128, 192 or 256) * * \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH */ int mbedtls_aesni_setkey_enc(unsigned char *rk, const unsigned char *key, size_t bits); #ifdef __cplusplus } #endif #endif /* MBEDTLS_AESNI_HAVE_CODE */ #endif /* MBEDTLS_AESNI_C && (MBEDTLS_ARCH_IS_X64 || MBEDTLS_ARCH_IS_X86) */ #endif /* MBEDTLS_AESNI_H */ keyring/src/keyring_secret_service.c0000644000176200001440000004044414535445207017431 0ustar liggesusers /* Avoid warning about empty compilation unit. */ void keyring_secret_service_dummy(void) { } #if defined(__linux__) && defined(HAS_LIBSECRET) #include #include #include #define SECRET_WITH_UNSTABLE 1 #define SECRET_API_SUBJECT_TO_CHANGE 1 #include const SecretSchema *keyring_secret_service_schema(void) { static const SecretSchema schema = { "com.rstudio.keyring.password", SECRET_SCHEMA_NONE, { { "service", SECRET_SCHEMA_ATTRIBUTE_STRING }, { "username", SECRET_SCHEMA_ATTRIBUTE_STRING }, { NULL, 0 }, } }; return &schema; } void keyring_secret_service_handle_status(const char *func, gboolean status, GError *err) { if (!status || err) { char *msg = R_alloc(1, strlen(err->message) + 1); strcpy(msg, err->message); g_error_free (err); error("Secret service keyring error in '%s': '%s'", func, msg); } } SEXP keyring_secret_service_is_available(SEXP report_error) { GError *err = NULL; SecretService *secretservice = secret_service_get_sync( /* flags = */ SECRET_SERVICE_LOAD_COLLECTIONS | SECRET_SERVICE_OPEN_SESSION, /* cancellable = */ NULL, &err); if (err || !secretservice) { if (LOGICAL(report_error)[0]) { keyring_secret_service_handle_status("is_available", TRUE, err); error("Cannot connect to secret service"); } else { return ScalarLogical(0); } } return ScalarLogical(1); } SecretCollection* keyring_secret_service_get_collection_default(void) { SecretCollection *collection = NULL; GError *err = NULL; SecretService *secretservice = secret_service_get_sync( /* flags = */ SECRET_SERVICE_LOAD_COLLECTIONS | SECRET_SERVICE_OPEN_SESSION, /* cancellable = */ NULL, &err); if (err || !secretservice) { keyring_secret_service_handle_status("get_keyring", TRUE, err); error("Cannot connect to secret service"); } collection = secret_collection_for_alias_sync( /* service = */ secretservice, /* alias = */ "default", /* flags = */ SECRET_COLLECTION_NONE, /* cancellable = */ NULL, &err); g_object_unref(secretservice); if (err || !collection) { keyring_secret_service_handle_status("get_keyring", TRUE, err); error("Cannot find keyring"); } return collection; } GList* keyring_secret_service_list_collections(void) { GError *err = NULL; SecretService *secretservice = secret_service_get_sync( /* flags = */ SECRET_SERVICE_LOAD_COLLECTIONS | SECRET_SERVICE_OPEN_SESSION, /* cancellable = */ NULL, &err); if (err || !secretservice) { keyring_secret_service_handle_status("create_keyring", TRUE, err); error("Cannot connect to secret service"); } gboolean status = secret_service_load_collections_sync( secretservice, /* cancellable = */ NULL, &err); if (status || err) { keyring_secret_service_handle_status("create_keyring", status, err); } GList *collections = secret_service_get_collections(secretservice); if (!collections) { g_object_unref(secretservice); error("Cannot query keyrings"); } g_object_unref(secretservice); return collections; } SecretCollection* keyring_secret_service_get_collection_other(const char *name) { GList *collections = keyring_secret_service_list_collections(); GList *item; for (item = g_list_first(collections); item; item = g_list_next(item)) { SecretCollection *coll = item->data; gchar *label = secret_collection_get_label(coll); if (! g_strcmp0(label, name)) { SecretCollection *copy = g_object_ref(coll); g_list_free(collections); return copy; } } g_list_free(collections); error("Did not find collection: '%s'", name); return NULL; } SecretCollection* keyring_secret_service_get_collection(SEXP keyring) { if (isNull(keyring)) { return keyring_secret_service_get_collection_default(); } else { const char *ckeyring = CHAR(STRING_ELT(keyring, 0)); return keyring_secret_service_get_collection_other(ckeyring); } } GList* keyring_secret_service_get_item(SEXP keyring, SEXP service, SEXP username) { const char* empty = ""; const char* cservice = CHAR(STRING_ELT(service, 0)); const char* cusername = isNull(username) ? empty : CHAR(STRING_ELT(username, 0)); const char *errormsg = NULL; SecretCollection *collection = NULL; GList *secretlist = NULL; GHashTable *attributes = NULL; GError *err = NULL; collection = keyring_secret_service_get_collection(keyring); attributes = g_hash_table_new( /* hash_func = */ (GHashFunc) g_str_hash, /* key_equal_func = */ (GEqualFunc) g_str_equal); g_hash_table_insert(attributes, g_strdup("service"), g_strdup(cservice)); g_hash_table_insert(attributes, g_strdup("username"), g_strdup(cusername)); secretlist = secret_collection_search_sync( /* self = */ collection, /* schema = */ keyring_secret_service_schema(), /* attributes = */ attributes, /* flags = */ SECRET_SEARCH_ALL | SECRET_SEARCH_UNLOCK | SECRET_SEARCH_LOAD_SECRETS, /* cancellable = */ NULL, &err); if (collection) g_object_unref(collection); if (attributes) g_hash_table_unref(attributes); keyring_secret_service_handle_status("get", TRUE, err); if (errormsg) error("%s", errormsg); return secretlist; } SEXP keyring_secret_service_get(SEXP keyring, SEXP service, SEXP username) { GList *secretlist = keyring_secret_service_get_item(keyring, service, username); guint listlength = g_list_length(secretlist); if (listlength == 0) { g_list_free(secretlist); error("keyring item not found"); } else if (listlength > 1) { warning("Multiple matching keyring items found, returning first"); } SecretItem *secretitem = g_list_first(secretlist)->data; SecretValue *secretvalue = secret_item_get_secret(secretitem); if (!secretvalue) { g_list_free(secretlist); error("Cannot get password"); } gsize passlength; const gchar *password = secret_value_get(secretvalue, &passlength); SEXP result = PROTECT(allocVector(RAWSXP, passlength)); memcpy(RAW(result), password, passlength); g_list_free(secretlist); UNPROTECT(1); return result; } SEXP keyring_secret_service_set(SEXP keyring, SEXP service, SEXP username, SEXP password) { const char* empty = ""; const char* cservice = CHAR(STRING_ELT(service, 0)); const char* cusername = isNull(username) ? empty : CHAR(STRING_ELT(username, 0)); SecretCollection *collection = NULL; GHashTable *attributes = NULL; GError *err = NULL; collection = keyring_secret_service_get_collection(keyring); attributes = g_hash_table_new( /* hash_func = */ (GHashFunc) g_str_hash, /* key_equal_func = */ (GEqualFunc) g_str_equal); g_hash_table_insert(attributes, g_strdup("service"), g_strdup(cservice)); g_hash_table_insert(attributes, g_strdup("username"), g_strdup(cusername)); SecretValue *value = secret_value_new((gchar *)RAW(password), LENGTH(password), /* content_type = */ "text/plain"); SecretItem *item = secret_item_create_sync( collection, keyring_secret_service_schema(), attributes, /* label = */ cservice, value, /* flags = */ SECRET_ITEM_CREATE_REPLACE, /* cancellable = */ NULL, &err); if (item) g_object_unref(item); keyring_secret_service_handle_status("set", TRUE, err); return R_NilValue; } SEXP keyring_secret_service_delete(SEXP keyring, SEXP service, SEXP username) { GList *secretlist = keyring_secret_service_get_item(keyring, service, username); guint listlength = g_list_length(secretlist); if (listlength == 0) { g_list_free(secretlist); error("keyring item not found"); } else if (listlength > 1) { warning("Multiple matching keyring items found, returning first"); } SecretItem *secretitem = g_list_first(secretlist)->data; GError *err = NULL; gboolean status = secret_item_delete_sync( secretitem, /* cancellable = */ NULL, &err); g_list_free(secretlist); if (!status) error("Could not delete keyring item"); keyring_secret_service_handle_status("delete", status, err); return R_NilValue; } SEXP keyring_secret_service_list(SEXP keyring, SEXP service) { const char *cservice = isNull(service) ? NULL : CHAR(STRING_ELT(service, 0)); const char *errormsg = NULL; GList *secretlist = NULL, *iter = NULL; guint listlength, i; GHashTable *attributes = NULL; GError *err = NULL; SEXP result = R_NilValue; SecretCollection *collection = keyring_secret_service_get_collection(keyring); /* If service is not NULL, then we only look for the specified service. */ attributes = g_hash_table_new( /* hash_func = */ (GHashFunc) g_str_hash, /* key_equal_func = */ (GEqualFunc) g_str_equal); if (cservice) { g_hash_table_insert(attributes, g_strdup("service"), g_strdup(cservice)); } secretlist = secret_collection_search_sync( /* self = */ collection, /* schema = */ keyring_secret_service_schema(), /* attributes = */ attributes, /* flags = */ SECRET_SEARCH_ALL, /* cancellable = */ NULL, &err); if (err) goto cleanup; listlength = g_list_length(secretlist); result = PROTECT(allocVector(VECSXP, 2)); SET_VECTOR_ELT(result, 0, allocVector(STRSXP, listlength)); SET_VECTOR_ELT(result, 1, allocVector(STRSXP, listlength)); for (i = 0, iter = g_list_first(secretlist); iter; i++, iter = g_list_next(iter)) { SecretItem *secret = iter->data; GHashTable *attr = secret_item_get_attributes(secret); char *service = g_hash_table_lookup(attr, "service"); char *username = g_hash_table_lookup(attr, "username"); SET_STRING_ELT(VECTOR_ELT(result, 0), i, mkChar(service)); SET_STRING_ELT(VECTOR_ELT(result, 1), i, mkChar(username)); } UNPROTECT(1); /* If an error happened, then err is not NULL, and the handler longjumps. Otherwise if errormsg is not NULL, then we error out with that. This happens for example if the specified keyring is not found. */ cleanup: if (collection) g_object_unref(collection); if (secretlist) g_list_free(secretlist); if (attributes) g_hash_table_unref(attributes); keyring_secret_service_handle_status("list", TRUE, err); if (errormsg) error("%s", errormsg); return result; } SEXP keyring_secret_service_create_keyring(SEXP keyring) { const char *ckeyring = CHAR(STRING_ELT(keyring, 0)); GError *err = NULL; SecretService *secretservice = secret_service_get_sync( /* flags = */ SECRET_SERVICE_LOAD_COLLECTIONS | SECRET_SERVICE_OPEN_SESSION, /* cancellable = */ NULL, &err); if (err || !secretservice) { keyring_secret_service_handle_status("create_keyring", TRUE, err); error("Cannot connect to secret service"); } SecretCollection *collection = secret_collection_create_sync( /* service = */ secretservice, /* label = */ ckeyring, /* alias = */ NULL, /* flags = */ 0, /* cancellable = */ NULL, &err); g_object_unref(secretservice); keyring_secret_service_handle_status("create_keyring", TRUE, err); if (collection) g_object_unref(collection); /* Need to disconnect here, otherwise the proxy is cached, and the new collection is not in this cache. If we disconnect here, a new proxy will be created for the next operation, and this will already include the new collection. */ secret_service_disconnect(); return R_NilValue; } SEXP keyring_secret_service_list_keyring(void) { GList *collections = keyring_secret_service_list_collections(); guint num = g_list_length(collections); SEXP result = PROTECT(allocVector(VECSXP, 3)); SET_VECTOR_ELT(result, 0, allocVector(STRSXP, num)); SET_VECTOR_ELT(result, 1, allocVector(INTSXP, num)); SET_VECTOR_ELT(result, 2, allocVector(LGLSXP, num)); GList *item; int i = 0; for (item = g_list_first(collections); item; item = g_list_next(item), i++) { SecretCollection *coll = item->data; gchar *label = secret_collection_get_label(coll); gboolean locked = secret_collection_get_locked(coll); GList *secrets = secret_collection_get_items(coll); SET_STRING_ELT(VECTOR_ELT(result, 0), i, mkChar((char*) label)); INTEGER(VECTOR_ELT(result, 1))[i] = g_list_length(secrets); LOGICAL(VECTOR_ELT(result, 2))[i] = locked; } g_list_free(collections); UNPROTECT(1); return result; } SEXP keyring_secret_service_delete_keyring(SEXP keyring) { if (isNull(keyring)) error("Cannot delete the default keyring"); const char *ckeyring = CHAR(STRING_ELT(keyring, 0)); SecretCollection* collection = keyring_secret_service_get_collection_other(ckeyring); GError *err = NULL; gboolean status = secret_collection_delete_sync( collection, /* cancellable = */ NULL, &err); g_object_unref(collection); keyring_secret_service_handle_status("delete_keyring", status, err); /* Need to disconnect here, otherwise the proxy is cached, and the deleted collection will be still in the cache. If we disconnect here, a new proxy will be created for the next operation, and this will not include the deleted collection. */ secret_service_disconnect(); return R_NilValue; } SEXP keyring_secret_service_lock_keyring(SEXP keyring) { SecretCollection *collection = keyring_secret_service_get_collection(keyring); GList *list = g_list_append(NULL, collection); GError *err = NULL; gint ret = secret_service_lock_sync( /* service = */ NULL, /* objects = */ list, /* cancellable = */ NULL, /* locked = */ NULL, &err); g_list_free(list); keyring_secret_service_handle_status("lock_keyring", TRUE, err); if (ret == 0) { error("Could not lock keyring"); } return R_NilValue; } SEXP keyring_secret_service_unlock_keyring(SEXP keyring, SEXP password) { SecretCollection *collection = keyring_secret_service_get_collection(keyring); GList *list = g_list_append(NULL, collection); GError *err = NULL; gint ret = secret_service_unlock_sync( /* service = */ NULL, /* objects = */ list, /* cancellable = */ NULL, /* unlocked = */ NULL, &err); g_list_free(list); keyring_secret_service_handle_status("unlock_keyring", TRUE, err); if (ret == 0) { error("Could not unlock keyring"); } return R_NilValue; } SEXP keyring_secret_service_is_locked_keyring(SEXP keyring) { SecretCollection *collection = keyring_secret_service_get_collection(keyring); gboolean locked = secret_collection_get_locked(collection); return ScalarLogical(locked); } void R_unload_keyring(DllInfo *dll) { secret_service_disconnect(); } #else #include #include #include SEXP keyring_secret_service_is_available(SEXP report_error) { #ifdef __linux__ if (LOGICAL(report_error)[0]) { error("keyring build has no libsecret support"); } else { return ScalarLogical(0); } #else error("only works on Linux"); return R_NilValue; #endif } SEXP keyring_secret_service_get(SEXP keyring, SEXP service, SEXP username) { error("only works on Linux with Secret Service support"); return R_NilValue; } SEXP keyring_secret_service_set(SEXP keyring, SEXP service, SEXP username, SEXP password) { error("only works on Linux with Secret Service support"); return R_NilValue; } SEXP keyring_secret_service_delete(SEXP keyring, SEXP service, SEXP username) { error("only works on Linux with Secret Service support"); return R_NilValue; } SEXP keyring_secret_service_list(SEXP keyring, SEXP service) { error("only works on Linux with Secret Service support"); return R_NilValue; } SEXP keyring_secret_service_create_keyring(SEXP keyring) { error("only works on Linux with Secret Service support"); return R_NilValue; } SEXP keyring_secret_service_list_keyring(void) { error("only works on Linux with Secret Service support"); return R_NilValue; } SEXP keyring_secret_service_delete_keyring(SEXP keyring) { error("only works on Linux with Secret Service support"); return R_NilValue; } SEXP keyring_secret_service_lock_keyring(SEXP keyring) { error("only works on Linux with Secret Service support"); return R_NilValue; } SEXP keyring_secret_service_unlock_keyring(SEXP keyring, SEXP password) { error("only works on Linux with Secret Service support"); return R_NilValue; } SEXP keyring_secret_service_is_locked_keyring(SEXP keyring) { error("only works on Linux with Secret Service support"); return R_NilValue; } #endif // __linux__ keyring/src/ctr.h0000644000176200001440000000166315006370264013463 0ustar liggesusers/** * \file ctr.h * * \brief This file contains common functionality for counter algorithms. * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_CTR_H #define MBEDTLS_CTR_H #include "common.h" /** * \brief Increment a big-endian 16-byte value. * This is quite performance-sensitive for AES-CTR and CTR-DRBG. * * \param n A 16-byte value to be incremented. */ static inline void mbedtls_ctr_increment_counter(uint8_t n[16]) { // The 32-bit version seems to perform about the same as a 64-bit version // on 64-bit architectures, so no need to define a 64-bit version. for (int i = 3;; i--) { uint32_t x = MBEDTLS_GET_UINT32_BE(n, i << 2); x += 1; MBEDTLS_PUT_UINT32_BE(x, n, i << 2); if (x != 0 || i == 0) { break; } } } #endif /* MBEDTLS_CTR_H */ keyring/src/generichash_blake2b.c0000644000176200001440000000751014775227066016542 0ustar liggesusers #include #include #include #include "blake2.h" #include "crypto_generichash_blake2b.h" int crypto_generichash_blake2b(unsigned char *out, size_t outlen, const unsigned char *in, unsigned long long inlen, const unsigned char *key, size_t keylen) { if (outlen <= 0U || outlen > BLAKE2B_OUTBYTES || keylen > BLAKE2B_KEYBYTES || inlen > UINT64_MAX) { return -1; } assert(outlen <= UINT8_MAX); assert(keylen <= UINT8_MAX); return blake2b((uint8_t *) out, in, key, (uint8_t) outlen, (uint64_t) inlen, (uint8_t) keylen); } int crypto_generichash_blake2b_salt_personal( unsigned char *out, size_t outlen, const unsigned char *in, unsigned long long inlen, const unsigned char *key, size_t keylen, const unsigned char *salt, const unsigned char *personal) { if (outlen <= 0U || outlen > BLAKE2B_OUTBYTES || keylen > BLAKE2B_KEYBYTES || inlen > UINT64_MAX) { return -1; } assert(outlen <= UINT8_MAX); assert(keylen <= UINT8_MAX); return blake2b_salt_personal((uint8_t *) out, in, key, (uint8_t) outlen, (uint64_t) inlen, (uint8_t) keylen, salt, personal); } int crypto_generichash_blake2b_init(crypto_generichash_blake2b_state *state, const unsigned char *key, const size_t keylen, const size_t outlen) { if (outlen <= 0U || outlen > BLAKE2B_OUTBYTES || keylen > BLAKE2B_KEYBYTES) { return -1; } assert(outlen <= UINT8_MAX); assert(keylen <= UINT8_MAX); COMPILER_ASSERT(sizeof(blake2b_state) <= sizeof *state); if (key == NULL || keylen <= 0U) { if (blake2b_init((blake2b_state *) (void *) state, (uint8_t) outlen) != 0) { return -1; /* LCOV_EXCL_LINE */ } } else if (blake2b_init_key((blake2b_state *) (void *) state, (uint8_t) outlen, key, (uint8_t) keylen) != 0) { return -1; /* LCOV_EXCL_LINE */ } return 0; } int crypto_generichash_blake2b_init_salt_personal( crypto_generichash_blake2b_state *state, const unsigned char *key, const size_t keylen, const size_t outlen, const unsigned char *salt, const unsigned char *personal) { if (outlen <= 0U || outlen > BLAKE2B_OUTBYTES || keylen > BLAKE2B_KEYBYTES) { return -1; } assert(outlen <= UINT8_MAX); assert(keylen <= UINT8_MAX); if (key == NULL || keylen <= 0U) { if (blake2b_init_salt_personal((blake2b_state *) (void *) state, (uint8_t) outlen, salt, personal) != 0) { return -1; /* LCOV_EXCL_LINE */ } } else if (blake2b_init_key_salt_personal((blake2b_state *) (void *) state, (uint8_t) outlen, key, (uint8_t) keylen, salt, personal) != 0) { return -1; /* LCOV_EXCL_LINE */ } return 0; } int crypto_generichash_blake2b_update(crypto_generichash_blake2b_state *state, const unsigned char *in, unsigned long long inlen) { return blake2b_update((blake2b_state *) (void *) state, (const uint8_t *) in, (uint64_t) inlen); } int crypto_generichash_blake2b_final(crypto_generichash_blake2b_state *state, unsigned char *out, const size_t outlen) { assert(outlen <= UINT8_MAX); return blake2b_final((blake2b_state *) (void *) state, (uint8_t *) out, (uint8_t) outlen); } int _crypto_generichash_blake2b_pick_best_implementation(void) { return blake2b_pick_best_implementation(); } keyring/src/blake2b-ref.c0000644000176200001440000002765514775227066014770 0ustar liggesusers/* BLAKE2 reference source code package - C implementations Written in 2012 by Samuel Neves To the extent possible under law, the author(s) have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide. This software is distributed without any warranty. You should have received a copy of the CC0 Public Domain Dedication along with this software. If not, see . */ #include #include #include #include #include #include #include #include "blake2.h" #include "sodium.h" static blake2b_compress_fn blake2b_compress = blake2b_compress_ref; static const uint64_t blake2b_IV[8] = { 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL }; /* LCOV_EXCL_START */ static inline int blake2b_set_lastnode(blake2b_state *S) { S->f[1] = -1; return 0; } /* LCOV_EXCL_STOP */ static inline int blake2b_is_lastblock(const blake2b_state *S) { return S->f[0] != 0; } static inline int blake2b_set_lastblock(blake2b_state *S) { if (S->last_node) { blake2b_set_lastnode(S); } S->f[0] = -1; return 0; } static inline int blake2b_increment_counter(blake2b_state *S, const uint64_t inc) { #ifdef HAVE_TI_MODE uint128_t t = ((uint128_t) S->t[1] << 64) | S->t[0]; t += inc; S->t[0] = (uint64_t)(t >> 0); S->t[1] = (uint64_t)(t >> 64); #else S->t[0] += inc; S->t[1] += (S->t[0] < inc); #endif return 0; } /* Parameter-related functions */ static inline int blake2b_param_set_salt(blake2b_param *P, const uint8_t salt[BLAKE2B_SALTBYTES]) { memcpy(P->salt, salt, BLAKE2B_SALTBYTES); return 0; } static inline int blake2b_param_set_personal(blake2b_param *P, const uint8_t personal[BLAKE2B_PERSONALBYTES]) { memcpy(P->personal, personal, BLAKE2B_PERSONALBYTES); return 0; } static inline int blake2b_init0(blake2b_state *S) { int i; for (i = 0; i < 8; i++) { S->h[i] = blake2b_IV[i]; } /* zero everything between .t and .last_node */ memset((void *) &S->t, 0, offsetof(blake2b_state, last_node) + sizeof(S->last_node) - offsetof(blake2b_state, t)); return 0; } /* init xors IV with input parameter block */ int blake2b_init_param(blake2b_state *S, const blake2b_param *P) { size_t i; const uint8_t *p; COMPILER_ASSERT(sizeof *P == 64); blake2b_init0(S); p = (const uint8_t *) (P); /* IV XOR ParamBlock */ for (i = 0; i < 8; i++) { S->h[i] ^= LOAD64_LE(p + sizeof(S->h[i]) * i); } return 0; } int blake2b_init(blake2b_state *S, const uint8_t outlen) { blake2b_param P[1]; if ((!outlen) || (outlen > BLAKE2B_OUTBYTES)) { Rf_error("Internal sodium error"); } P->digest_length = outlen; P->key_length = 0; P->fanout = 1; P->depth = 1; STORE32_LE(P->leaf_length, 0); STORE64_LE(P->node_offset, 0); P->node_depth = 0; P->inner_length = 0; memset(P->reserved, 0, sizeof(P->reserved)); memset(P->salt, 0, sizeof(P->salt)); memset(P->personal, 0, sizeof(P->personal)); return blake2b_init_param(S, P); } int blake2b_init_salt_personal(blake2b_state *S, const uint8_t outlen, const void *salt, const void *personal) { blake2b_param P[1]; if ((!outlen) || (outlen > BLAKE2B_OUTBYTES)) { Rf_error("Internal sodium error"); } P->digest_length = outlen; P->key_length = 0; P->fanout = 1; P->depth = 1; STORE32_LE(P->leaf_length, 0); STORE64_LE(P->node_offset, 0); P->node_depth = 0; P->inner_length = 0; memset(P->reserved, 0, sizeof(P->reserved)); if (salt != NULL) { blake2b_param_set_salt(P, (const uint8_t *) salt); } else { memset(P->salt, 0, sizeof(P->salt)); } if (personal != NULL) { blake2b_param_set_personal(P, (const uint8_t *) personal); } else { memset(P->personal, 0, sizeof(P->personal)); } return blake2b_init_param(S, P); } int blake2b_init_key(blake2b_state *S, const uint8_t outlen, const void *key, const uint8_t keylen) { blake2b_param P[1]; if ((!outlen) || (outlen > BLAKE2B_OUTBYTES)) { Rf_error("Internal sodium error"); } if (!key || !keylen || keylen > BLAKE2B_KEYBYTES) { Rf_error("Internal sodium error"); /* does not return */ } P->digest_length = outlen; P->key_length = keylen; P->fanout = 1; P->depth = 1; STORE32_LE(P->leaf_length, 0); STORE64_LE(P->node_offset, 0); P->node_depth = 0; P->inner_length = 0; memset(P->reserved, 0, sizeof(P->reserved)); memset(P->salt, 0, sizeof(P->salt)); memset(P->personal, 0, sizeof(P->personal)); if (blake2b_init_param(S, P) < 0) { Rf_error("Internal sodium error"); } { uint8_t block[BLAKE2B_BLOCKBYTES]; memset(block, 0, BLAKE2B_BLOCKBYTES); memcpy(block, key, keylen); /* key and keylen cannot be 0 */ blake2b_update(S, block, BLAKE2B_BLOCKBYTES); sodium_memzero(block, BLAKE2B_BLOCKBYTES); /* Burn the key from stack */ } return 0; } int blake2b_init_key_salt_personal(blake2b_state *S, const uint8_t outlen, const void *key, const uint8_t keylen, const void *salt, const void *personal) { blake2b_param P[1]; if ((!outlen) || (outlen > BLAKE2B_OUTBYTES)) { Rf_error("Internal sodium error"); } if (!key || !keylen || keylen > BLAKE2B_KEYBYTES) { Rf_error("Internal sodium error"); /* does not return */ } P->digest_length = outlen; P->key_length = keylen; P->fanout = 1; P->depth = 1; STORE32_LE(P->leaf_length, 0); STORE64_LE(P->node_offset, 0); P->node_depth = 0; P->inner_length = 0; memset(P->reserved, 0, sizeof(P->reserved)); if (salt != NULL) { blake2b_param_set_salt(P, (const uint8_t *) salt); } else { memset(P->salt, 0, sizeof(P->salt)); } if (personal != NULL) { blake2b_param_set_personal(P, (const uint8_t *) personal); } else { memset(P->personal, 0, sizeof(P->personal)); } if (blake2b_init_param(S, P) < 0) { Rf_error("Internal sodium error"); } { uint8_t block[BLAKE2B_BLOCKBYTES]; memset(block, 0, BLAKE2B_BLOCKBYTES); memcpy(block, key, keylen); /* key and keylen cannot be 0 */ blake2b_update(S, block, BLAKE2B_BLOCKBYTES); sodium_memzero(block, BLAKE2B_BLOCKBYTES); /* Burn the key from stack */ } return 0; } /* inlen now in bytes */ int blake2b_update(blake2b_state *S, const uint8_t *in, uint64_t inlen) { while (inlen > 0) { size_t left = S->buflen; size_t fill = 2 * BLAKE2B_BLOCKBYTES - left; if (inlen > fill) { memcpy(S->buf + left, in, fill); /* Fill buffer */ S->buflen += fill; blake2b_increment_counter(S, BLAKE2B_BLOCKBYTES); blake2b_compress(S, S->buf); /* Compress */ memcpy(S->buf, S->buf + BLAKE2B_BLOCKBYTES, BLAKE2B_BLOCKBYTES); /* Shift buffer left */ S->buflen -= BLAKE2B_BLOCKBYTES; in += fill; inlen -= fill; } else /* inlen <= fill */ { memcpy(S->buf + left, in, inlen); S->buflen += inlen; /* Be lazy, do not compress */ in += inlen; inlen -= inlen; } } return 0; } int blake2b_final(blake2b_state *S, uint8_t *out, uint8_t outlen) { unsigned char buffer[BLAKE2B_OUTBYTES]; if (!outlen || outlen > BLAKE2B_OUTBYTES) { Rf_error("Internal sodium error"); } if (blake2b_is_lastblock(S)) { return -1; } if (S->buflen > BLAKE2B_BLOCKBYTES) { blake2b_increment_counter(S, BLAKE2B_BLOCKBYTES); blake2b_compress(S, S->buf); S->buflen -= BLAKE2B_BLOCKBYTES; assert(S->buflen <= BLAKE2B_BLOCKBYTES); memcpy(S->buf, S->buf + BLAKE2B_BLOCKBYTES, S->buflen); } blake2b_increment_counter(S, S->buflen); blake2b_set_lastblock(S); memset(S->buf + S->buflen, 0, 2 * BLAKE2B_BLOCKBYTES - S->buflen); /* Padding */ blake2b_compress(S, S->buf); COMPILER_ASSERT(sizeof buffer == 64U); STORE64_LE(buffer + 8 * 0, S->h[0]); STORE64_LE(buffer + 8 * 1, S->h[1]); STORE64_LE(buffer + 8 * 2, S->h[2]); STORE64_LE(buffer + 8 * 3, S->h[3]); STORE64_LE(buffer + 8 * 4, S->h[4]); STORE64_LE(buffer + 8 * 5, S->h[5]); STORE64_LE(buffer + 8 * 6, S->h[6]); STORE64_LE(buffer + 8 * 7, S->h[7]); memcpy(out, buffer, outlen); /* outlen <= BLAKE2B_OUTBYTES (64) */ sodium_memzero(S->h, sizeof S->h); sodium_memzero(S->buf, sizeof S->buf); return 0; } /* inlen, at least, should be uint64_t. Others can be size_t. */ int blake2b(uint8_t *out, const void *in, const void *key, const uint8_t outlen, const uint64_t inlen, uint8_t keylen) { CRYPTO_ALIGN(64) blake2b_state S[1]; /* Verify parameters */ if (NULL == in && inlen > 0) { Rf_error("Internal sodium error"); } if (NULL == out) { Rf_error("Internal sodium error"); } if (!outlen || outlen > BLAKE2B_OUTBYTES) { Rf_error("Internal sodium error"); } if (NULL == key && keylen > 0) { Rf_error("Internal sodium error"); } if (keylen > BLAKE2B_KEYBYTES) { Rf_error("Internal sodium error"); } if (keylen > 0) { if (blake2b_init_key(S, outlen, key, keylen) < 0) { Rf_error("Internal sodium error"); } } else { if (blake2b_init(S, outlen) < 0) { Rf_error("Internal sodium error"); } } blake2b_update(S, (const uint8_t *) in, inlen); blake2b_final(S, out, outlen); return 0; } int blake2b_salt_personal(uint8_t *out, const void *in, const void *key, const uint8_t outlen, const uint64_t inlen, uint8_t keylen, const void *salt, const void *personal) { CRYPTO_ALIGN(64) blake2b_state S[1]; /* Verify parameters */ if (NULL == in && inlen > 0) { Rf_error("Internal sodium error"); } if (NULL == out) { Rf_error("Internal sodium error"); } if (!outlen || outlen > BLAKE2B_OUTBYTES) { Rf_error("Internal sodium error"); } if (NULL == key && keylen > 0) { Rf_error("Internal sodium error"); } if (keylen > BLAKE2B_KEYBYTES) { Rf_error("Internal sodium error"); } if (keylen > 0) { if (blake2b_init_key_salt_personal(S, outlen, key, keylen, salt, personal) < 0) { Rf_error("Internal sodium error"); } } else { if (blake2b_init_salt_personal(S, outlen, salt, personal) < 0) { Rf_error("Internal sodium error"); } } blake2b_update(S, (const uint8_t *) in, inlen); blake2b_final(S, out, outlen); return 0; } int blake2b_pick_best_implementation(void) { /* LCOV_EXCL_START */ #if defined(HAVE_AVX2INTRIN_H) && defined(HAVE_TMMINTRIN_H) && \ defined(HAVE_SMMINTRIN_H) if (sodium_runtime_has_avx2()) { blake2b_compress = blake2b_compress_avx2; return 0; } #endif #if defined(HAVE_EMMINTRIN_H) && defined(HAVE_TMMINTRIN_H) && \ defined(HAVE_SMMINTRIN_H) if (sodium_runtime_has_sse41()) { blake2b_compress = blake2b_compress_sse41; return 0; } #endif #if defined(HAVE_EMMINTRIN_H) && defined(HAVE_TMMINTRIN_H) if (sodium_runtime_has_ssse3()) { blake2b_compress = blake2b_compress_ssse3; return 0; } #endif blake2b_compress = blake2b_compress_ref; return 0; /* LCOV_EXCL_STOP */ } keyring/src/crypto_generichash_blake2b.h0000644000176200001440000000763114775227066020153 0ustar liggesusers#ifndef crypto_generichash_blake2b_H #define crypto_generichash_blake2b_H #include #include #include #include "sodium.h" #ifdef __cplusplus # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wlong-long" # endif extern "C" { #endif #ifdef __IBMC__ # pragma pack(1) #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) # pragma pack(1) #else # pragma pack(push, 1) #endif typedef struct CRYPTO_ALIGN(64) crypto_generichash_blake2b_state { unsigned char opaque[384]; } crypto_generichash_blake2b_state; #ifdef __IBMC__ # pragma pack(pop) #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) # pragma pack() #else # pragma pack(pop) #endif #define crypto_generichash_blake2b_BYTES_MIN 16U SODIUM_EXPORT size_t crypto_generichash_blake2b_bytes_min(void); #define crypto_generichash_blake2b_BYTES_MAX 64U SODIUM_EXPORT size_t crypto_generichash_blake2b_bytes_max(void); #define crypto_generichash_blake2b_BYTES 32U SODIUM_EXPORT size_t crypto_generichash_blake2b_bytes(void); #define crypto_generichash_blake2b_KEYBYTES_MIN 16U SODIUM_EXPORT size_t crypto_generichash_blake2b_keybytes_min(void); #define crypto_generichash_blake2b_KEYBYTES_MAX 64U SODIUM_EXPORT size_t crypto_generichash_blake2b_keybytes_max(void); #define crypto_generichash_blake2b_KEYBYTES 32U SODIUM_EXPORT size_t crypto_generichash_blake2b_keybytes(void); #define crypto_generichash_blake2b_SALTBYTES 16U SODIUM_EXPORT size_t crypto_generichash_blake2b_saltbytes(void); #define crypto_generichash_blake2b_PERSONALBYTES 16U SODIUM_EXPORT size_t crypto_generichash_blake2b_personalbytes(void); SODIUM_EXPORT size_t crypto_generichash_blake2b_statebytes(void); SODIUM_EXPORT int crypto_generichash_blake2b(unsigned char *out, size_t outlen, const unsigned char *in, unsigned long long inlen, const unsigned char *key, size_t keylen) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_generichash_blake2b_salt_personal(unsigned char *out, size_t outlen, const unsigned char *in, unsigned long long inlen, const unsigned char *key, size_t keylen, const unsigned char *salt, const unsigned char *personal) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_generichash_blake2b_init(crypto_generichash_blake2b_state *state, const unsigned char *key, const size_t keylen, const size_t outlen) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_generichash_blake2b_init_salt_personal(crypto_generichash_blake2b_state *state, const unsigned char *key, const size_t keylen, const size_t outlen, const unsigned char *salt, const unsigned char *personal) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_generichash_blake2b_update(crypto_generichash_blake2b_state *state, const unsigned char *in, unsigned long long inlen) __attribute__ ((nonnull(1))); SODIUM_EXPORT int crypto_generichash_blake2b_final(crypto_generichash_blake2b_state *state, unsigned char *out, const size_t outlen) __attribute__ ((nonnull)); SODIUM_EXPORT void crypto_generichash_blake2b_keygen(unsigned char k[crypto_generichash_blake2b_KEYBYTES]) __attribute__ ((nonnull)); #ifdef __cplusplus } #endif #endif keyring/src/crypto_secretbox_easy.c0000644000176200001440000001166314775227066017323 0ustar liggesusers #include #include #include #include #include #include #include #include "sodium.h" // #include "core.h" #include "crypto_core_hsalsa20.h" #include "crypto_onetimeauth_poly1305.h" #include "crypto_secretbox.h" #include "crypto_stream_salsa20.h" // #include "private/common.h" // #include "utils.h" int crypto_secretbox_detached(unsigned char *c, unsigned char *mac, const unsigned char *m, unsigned long long mlen, const unsigned char *n, const unsigned char *k) { crypto_onetimeauth_poly1305_state state; unsigned char block0[64U]; unsigned char subkey[crypto_stream_salsa20_KEYBYTES]; unsigned long long i; unsigned long long mlen0; crypto_core_hsalsa20(subkey, n, k, NULL); if (((uintptr_t) c > (uintptr_t) m && (uintptr_t) c - (uintptr_t) m < mlen) || ((uintptr_t) m > (uintptr_t) c && (uintptr_t) m - (uintptr_t) c < mlen)) { /* LCOV_EXCL_LINE */ memmove(c, m, mlen); m = c; } memset(block0, 0U, crypto_secretbox_ZEROBYTES); COMPILER_ASSERT(64U >= crypto_secretbox_ZEROBYTES); mlen0 = mlen; if (mlen0 > 64U - crypto_secretbox_ZEROBYTES) { mlen0 = 64U - crypto_secretbox_ZEROBYTES; } for (i = 0U; i < mlen0; i++) { block0[i + crypto_secretbox_ZEROBYTES] = m[i]; } crypto_stream_salsa20_xor(block0, block0, mlen0 + crypto_secretbox_ZEROBYTES, n + 16, subkey); COMPILER_ASSERT(crypto_secretbox_ZEROBYTES >= crypto_onetimeauth_poly1305_KEYBYTES); crypto_onetimeauth_poly1305_init(&state, block0); for (i = 0U; i < mlen0; i++) { c[i] = block0[crypto_secretbox_ZEROBYTES + i]; } sodium_memzero(block0, sizeof block0); if (mlen > mlen0) { crypto_stream_salsa20_xor_ic(c + mlen0, m + mlen0, mlen - mlen0, n + 16, 1U, subkey); } sodium_memzero(subkey, sizeof subkey); crypto_onetimeauth_poly1305_update(&state, c, mlen); crypto_onetimeauth_poly1305_final(&state, mac); sodium_memzero(&state, sizeof state); return 0; } int crypto_secretbox_easy(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, const unsigned char *k) { if (mlen > crypto_secretbox_MESSAGEBYTES_MAX) { Rf_error("Internal sodium error"); } return crypto_secretbox_detached(c + crypto_secretbox_MACBYTES, c, m, mlen, n, k); } int crypto_secretbox_open_detached(unsigned char *m, const unsigned char *c, const unsigned char *mac, unsigned long long clen, const unsigned char *n, const unsigned char *k) { unsigned char block0[64U]; unsigned char subkey[crypto_stream_salsa20_KEYBYTES]; unsigned long long i; unsigned long long mlen0; crypto_core_hsalsa20(subkey, n, k, NULL); crypto_stream_salsa20(block0, crypto_stream_salsa20_KEYBYTES, n + 16, subkey); if (crypto_onetimeauth_poly1305_verify(mac, c, clen, block0) != 0) { sodium_memzero(subkey, sizeof subkey); return -1; } if (m == NULL) { return 0; } if (((uintptr_t) c > (uintptr_t) m && (uintptr_t) c - (uintptr_t) m < clen) || ((uintptr_t) m > (uintptr_t) c && (uintptr_t) m - (uintptr_t) c < clen)) { /* LCOV_EXCL_LINE */ memmove(m, c, clen); c = m; } mlen0 = clen; if (mlen0 > 64U - crypto_secretbox_ZEROBYTES) { mlen0 = 64U - crypto_secretbox_ZEROBYTES; } for (i = 0U; i < mlen0; i++) { block0[crypto_secretbox_ZEROBYTES + i] = c[i]; } crypto_stream_salsa20_xor(block0, block0, crypto_secretbox_ZEROBYTES + mlen0, n + 16, subkey); for (i = 0U; i < mlen0; i++) { m[i] = block0[i + crypto_secretbox_ZEROBYTES]; } sodium_memzero(block0, sizeof block0); if (clen > mlen0) { crypto_stream_salsa20_xor_ic(m + mlen0, c + mlen0, clen - mlen0, n + 16, 1U, subkey); } sodium_memzero(subkey, sizeof subkey); return 0; } int crypto_secretbox_open_easy(unsigned char *m, const unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) { if (clen < crypto_secretbox_MACBYTES) { return -1; } return crypto_secretbox_open_detached(m, c + crypto_secretbox_MACBYTES, c, clen - crypto_secretbox_MACBYTES, n, k); } keyring/src/crypto_generichash.c0000644000176200001440000000376014775227066016563 0ustar liggesusers #include "crypto_generichash.h" #include "sodium.h" size_t crypto_generichash_bytes_min(void) { return crypto_generichash_BYTES_MIN; } size_t crypto_generichash_bytes_max(void) { return crypto_generichash_BYTES_MAX; } size_t crypto_generichash_bytes(void) { return crypto_generichash_BYTES; } size_t crypto_generichash_keybytes_min(void) { return crypto_generichash_KEYBYTES_MIN; } size_t crypto_generichash_keybytes_max(void) { return crypto_generichash_KEYBYTES_MAX; } size_t crypto_generichash_keybytes(void) { return crypto_generichash_KEYBYTES; } const char * crypto_generichash_primitive(void) { return crypto_generichash_PRIMITIVE; } size_t crypto_generichash_statebytes(void) { return (sizeof(crypto_generichash_state) + (size_t) 63U) & ~(size_t) 63U; } int crypto_generichash(unsigned char *out, size_t outlen, const unsigned char *in, unsigned long long inlen, const unsigned char *key, size_t keylen) { return crypto_generichash_blake2b(out, outlen, in, inlen, key, keylen); } int crypto_generichash_init(crypto_generichash_state *state, const unsigned char *key, const size_t keylen, const size_t outlen) { return crypto_generichash_blake2b_init ((crypto_generichash_blake2b_state *) state, key, keylen, outlen); } int crypto_generichash_update(crypto_generichash_state *state, const unsigned char *in, unsigned long long inlen) { return crypto_generichash_blake2b_update ((crypto_generichash_blake2b_state *) state, in, inlen); } int crypto_generichash_final(crypto_generichash_state *state, unsigned char *out, const size_t outlen) { return crypto_generichash_blake2b_final ((crypto_generichash_blake2b_state *) state, out, outlen); } void crypto_generichash_keygen(unsigned char k[crypto_generichash_KEYBYTES]) { randombytes_buf(k, crypto_generichash_KEYBYTES); } keyring/src/randombytes_sysrandom.c0000644000176200001440000002304415006370264017311 0ustar liggesusers#include #include #include #include #include #include #ifndef _WIN32 # include #endif #include #include #ifndef _WIN32 # include # include #endif #ifdef __linux__ # define _LINUX_SOURCE #endif #ifdef HAVE_SYS_RANDOM_H # include #endif #ifdef __linux__ # ifdef HAVE_GETRANDOM # define HAVE_LINUX_COMPATIBLE_GETRANDOM # else # include # if defined(SYS_getrandom) && defined(__NR_getrandom) # define getrandom(B, S, F) syscall(SYS_getrandom, (B), (int) (S), (F)) # define HAVE_LINUX_COMPATIBLE_GETRANDOM # endif # endif #elif defined(__FreeBSD__) || defined(__DragonFly__) # include # if (defined(__FreeBSD_version) && __FreeBSD_version >= 1200000) || \ (defined(__DragonFly_version) && __DragonFly_version >= 500700) # define HAVE_LINUX_COMPATIBLE_GETRANDOM # endif #endif #if !defined(NO_BLOCKING_RANDOM_POLL) && defined(__linux__) # define BLOCK_ON_DEV_RANDOM #endif #ifdef BLOCK_ON_DEV_RANDOM # include #endif #ifdef _WIN32 /* `RtlGenRandom` is used over `CryptGenRandom` on Microsoft Windows based systems: * - `CryptGenRandom` requires pulling in `CryptoAPI` which causes unnecessary * memory overhead if this API is not being used for other purposes * - `RtlGenRandom` is thus called directly instead. A detailed explanation * can be found here: https://blogs.msdn.microsoft.com/michael_howard/2005/01/14/cryptographically-secure-random-number-on-windows-without-using-cryptoapi/ * * In spite of the disclaimer on the `RtlGenRandom` documentation page that was * written back in the Windows XP days, this function is here to stay. The CRT * function `rand_s()` directly depends on it, so touching it would break many * applications released since Windows XP. * * Also note that Rust, Firefox and BoringSSL (thus, Google Chrome and everything * based on Chromium) also depend on it, and that libsodium allows the RNG to be * replaced without patching nor recompiling the library. */ # include # define RtlGenRandom SystemFunction036 # if defined(__cplusplus) extern "C" # endif BOOLEAN NTAPI RtlGenRandom(PVOID RandomBuffer, ULONG RandomBufferLength); # pragma comment(lib, "advapi32.lib") #endif #if defined(__OpenBSD__) || defined(__CloudABI__) || defined(__wasi__) # define HAVE_SAFE_ARC4RANDOM 1 #endif #ifndef SSIZE_MAX # define SSIZE_MAX (SIZE_MAX / 2 - 1) #endif #undef ERROR #include #include #include "sodium.h" #ifdef HAVE_SAFE_ARC4RANDOM static uint32_t randombytes_sysrandom(void) { return arc4random(); } static void randombytes_sysrandom_stir(void) { } static void randombytes_sysrandom_buf(void * const buf, const size_t size) { arc4random_buf(buf, size); } static int randombytes_sysrandom_close(void) { return 0; } #else /* HAVE_SAFE_ARC4RANDOM */ typedef struct SysRandom_ { int random_data_source_fd; int initialized; int getrandom_available; } SysRandom; static SysRandom stream = { SODIUM_C99(.random_data_source_fd =) -1, SODIUM_C99(.initialized =) 0, SODIUM_C99(.getrandom_available =) 0 }; # ifndef _WIN32 static ssize_t safe_read(const int fd, void * const buf_, size_t size) { unsigned char *buf = (unsigned char *) buf_; ssize_t readnb; assert(size > (size_t) 0U); assert(size <= SSIZE_MAX); do { while ((readnb = read(fd, buf, size)) < (ssize_t) 0 && (errno == EINTR || errno == EAGAIN)); /* LCOV_EXCL_LINE */ if (readnb < (ssize_t) 0) { return readnb; /* LCOV_EXCL_LINE */ } if (readnb == (ssize_t) 0) { break; /* LCOV_EXCL_LINE */ } size -= (size_t) readnb; buf += readnb; } while (size > (ssize_t) 0); return (ssize_t) (buf - (unsigned char *) buf_); } # ifdef BLOCK_ON_DEV_RANDOM static int randombytes_block_on_dev_random(void) { struct pollfd pfd; int fd; int pret; fd = open("/dev/random", O_RDONLY); if (fd == -1) { return 0; } pfd.fd = fd; pfd.events = POLLIN; pfd.revents = 0; do { pret = poll(&pfd, 1, -1); } while (pret < 0 && (errno == EINTR || errno == EAGAIN)); if (pret != 1) { (void) close(fd); errno = EIO; return -1; } return close(fd); } # endif /* BLOCK_ON_DEV_RANDOM */ static int randombytes_sysrandom_random_dev_open(void) { /* LCOV_EXCL_START */ struct stat st; static const char *devices[] = { # ifndef USE_BLOCKING_RANDOM "/dev/urandom", # endif "/dev/random", NULL }; const char **device = devices; int fd; # ifdef BLOCK_ON_DEV_RANDOM if (randombytes_block_on_dev_random() != 0) { return -1; } # endif do { fd = open(*device, O_RDONLY); if (fd != -1) { if (fstat(fd, &st) == 0 && # ifdef __COMPCERT__ 1 # elif defined(S_ISNAM) (S_ISNAM(st.st_mode) || S_ISCHR(st.st_mode)) # else S_ISCHR(st.st_mode) # endif ) { # if defined(F_SETFD) && defined(FD_CLOEXEC) (void) fcntl(fd, F_SETFD, fcntl(fd, F_GETFD) | FD_CLOEXEC); # endif return fd; } (void) close(fd); } else if (errno == EINTR) { continue; } device++; } while (*device != NULL); errno = EIO; return -1; /* LCOV_EXCL_STOP */ } # ifdef HAVE_LINUX_COMPATIBLE_GETRANDOM static int _randombytes_linux_getrandom(void * const buf, const size_t size) { int readnb; assert(size <= 256U); do { readnb = getrandom(buf, size, 0); } while (readnb < 0 && (errno == EINTR || errno == EAGAIN)); return (readnb == (int) size) - 1; } static int randombytes_linux_getrandom(void * const buf_, size_t size) { unsigned char *buf = (unsigned char *) buf_; size_t chunk_size = 256U; do { if (size < chunk_size) { chunk_size = size; assert(chunk_size > (size_t) 0U); } if (_randombytes_linux_getrandom(buf, chunk_size) != 0) { return -1; } size -= chunk_size; buf += chunk_size; } while (size > (size_t) 0U); return 0; } # endif /* HAVE_LINUX_COMPATIBLE_GETRANDOM */ static void randombytes_sysrandom_init(void) { const int errno_save = errno; # ifdef HAVE_LINUX_COMPATIBLE_GETRANDOM { unsigned char fodder[16]; if (randombytes_linux_getrandom(fodder, sizeof fodder) == 0) { stream.getrandom_available = 1; errno = errno_save; return; } stream.getrandom_available = 0; } # endif if ((stream.random_data_source_fd = randombytes_sysrandom_random_dev_open()) == -1) { Rf_error("Internal sodium error"); } errno = errno_save; } # else /* _WIN32 */ static void randombytes_sysrandom_init(void) { } # endif /* _WIN32 */ static void randombytes_sysrandom_stir(void) { if (stream.initialized == 0) { randombytes_sysrandom_init(); stream.initialized = 1; } } static void randombytes_sysrandom_stir_if_needed(void) { if (stream.initialized == 0) { randombytes_sysrandom_stir(); } } static int randombytes_sysrandom_close(void) { int ret = -1; # ifndef _WIN32 if (stream.random_data_source_fd != -1 && close(stream.random_data_source_fd) == 0) { stream.random_data_source_fd = -1; stream.initialized = 0; ret = 0; } # ifdef HAVE_LINUX_COMPATIBLE_GETRANDOM if (stream.getrandom_available != 0) { ret = 0; } # endif # else /* _WIN32 */ if (stream.initialized != 0) { stream.initialized = 0; ret = 0; } # endif /* _WIN32 */ return ret; } static void randombytes_sysrandom_buf(void * const buf, const size_t size) { randombytes_sysrandom_stir_if_needed(); # if defined(ULLONG_MAX) && defined(SIZE_MAX) # if SIZE_MAX > ULLONG_MAX /* coverity[result_independent_of_operands] */ assert(size <= ULLONG_MAX); # endif # endif # ifndef _WIN32 # ifdef HAVE_LINUX_COMPATIBLE_GETRANDOM if (stream.getrandom_available != 0) { if (randombytes_linux_getrandom(buf, size) != 0) { Rf_error("Interla sodium error"); } return; } # endif if (stream.random_data_source_fd == -1 || safe_read(stream.random_data_source_fd, buf, size) != (ssize_t) size) { Rf_error("Interla sodium error"); } # else /* _WIN32 */ COMPILER_ASSERT(randombytes_BYTES_MAX <= 0xffffffffUL); if (size > (size_t) 0xffffffffUL) { Rf_error("Interla sodium error"); } if (! RtlGenRandom((PVOID) buf, (ULONG) size)) { Rf_error("Interla sodium error"); } # endif /* _WIN32 */ } static uint32_t randombytes_sysrandom(void) { uint32_t r; randombytes_sysrandom_buf(&r, sizeof r); return r; } #endif /* HAVE_SAFE_ARC4RANDOM */ static const char * randombytes_sysrandom_implementation_name(void) { return "sysrandom"; } struct randombytes_implementation randombytes_sysrandom_implementation = { SODIUM_C99(.implementation_name =) randombytes_sysrandom_implementation_name, SODIUM_C99(.random =) randombytes_sysrandom, SODIUM_C99(.stir =) randombytes_sysrandom_stir, SODIUM_C99(.uniform =) NULL, SODIUM_C99(.buf =) randombytes_sysrandom_buf, SODIUM_C99(.close =) randombytes_sysrandom_close }; void randombytes_buf(void * const buf, const size_t size) { randombytes_sysrandom_stir(); randombytes_sysrandom_buf(buf, size); } keyring/src/crypto_stream_salsa20.h0000644000176200001440000000345514775227066017131 0ustar liggesusers#ifndef crypto_stream_salsa20_H #define crypto_stream_salsa20_H /* * WARNING: This is just a stream cipher. It is NOT authenticated encryption. * While it provides some protection against eavesdropping, it does NOT * provide any security against active attacks. * Unless you know what you're doing, what you are looking for is probably * the crypto_box functions. */ #include #include #include "sodium.h" #ifdef __cplusplus # ifdef __GNUC__ # pragma GCC diagnostic ignored "-Wlong-long" # endif extern "C" { #endif #define crypto_stream_salsa20_KEYBYTES 32U SODIUM_EXPORT size_t crypto_stream_salsa20_keybytes(void); #define crypto_stream_salsa20_NONCEBYTES 8U SODIUM_EXPORT size_t crypto_stream_salsa20_noncebytes(void); #define crypto_stream_salsa20_MESSAGEBYTES_MAX SODIUM_SIZE_MAX SODIUM_EXPORT size_t crypto_stream_salsa20_messagebytes_max(void); SODIUM_EXPORT int crypto_stream_salsa20(unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) __attribute__ ((nonnull)); SODIUM_EXPORT int crypto_stream_salsa20_xor(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, const unsigned char *k) __attribute__ ((nonnull)); SODIUM_EXPORT int crypto_stream_salsa20_xor_ic(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, uint64_t ic, const unsigned char *k) __attribute__ ((nonnull)); SODIUM_EXPORT void crypto_stream_salsa20_keygen(unsigned char k[crypto_stream_salsa20_KEYBYTES]) __attribute__ ((nonnull)); #ifdef __cplusplus } #endif #endif keyring/src/aesce.h0000644000176200001440000001076515006370264013756 0ustar liggesusers/** * \file aesce.h * * \brief Support hardware AES acceleration on Armv8-A processors with * the Armv8-A Cryptographic Extension. * * \warning These functions are only for internal use by other library * functions; you must not call them directly. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_AESCE_H #define MBEDTLS_AESCE_H #include "mbedtls/build_info.h" #include "common.h" #include "mbedtls/aes.h" #if defined(MBEDTLS_AESCE_C) \ && defined(MBEDTLS_ARCH_IS_ARMV8_A) && defined(MBEDTLS_HAVE_NEON_INTRINSICS) \ && (defined(MBEDTLS_COMPILER_IS_GCC) || defined(__clang__) || defined(MSC_VER)) /* MBEDTLS_AESCE_HAVE_CODE is defined if we have a suitable target platform, and a * potentially suitable compiler (compiler version & flags are not checked when defining * this). */ #define MBEDTLS_AESCE_HAVE_CODE #ifdef __cplusplus extern "C" { #endif #if defined(__linux__) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) extern signed char mbedtls_aesce_has_support_result; /** * \brief Internal function to detect the crypto extension in CPUs. * * \return 1 if CPU has support for the feature, 0 otherwise */ int mbedtls_aesce_has_support_impl(void); #define MBEDTLS_AESCE_HAS_SUPPORT() (mbedtls_aesce_has_support_result == -1 ? \ mbedtls_aesce_has_support_impl() : \ mbedtls_aesce_has_support_result) #else /* defined(__linux__) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) */ /* If we are not on Linux, we can't detect support so assume that it's supported. * Similarly, assume support if MBEDTLS_AES_USE_HARDWARE_ONLY is set. */ #define MBEDTLS_AESCE_HAS_SUPPORT() 1 #endif /* defined(__linux__) && !defined(MBEDTLS_AES_USE_HARDWARE_ONLY) */ /** * \brief Internal AES-ECB block encryption and decryption * * \warning This assumes that the context specifies either 10, 12 or 14 * rounds and will behave incorrectly if this is not the case. * * \param ctx AES context * \param mode MBEDTLS_AES_ENCRYPT or MBEDTLS_AES_DECRYPT * \param input 16-byte input block * \param output 16-byte output block * * \return 0 on success (cannot fail) */ int mbedtls_aesce_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]); /** * \brief Internal GCM multiplication: c = a * b in GF(2^128) * * \note This function is only for internal use by other library * functions; you must not call it directly. * * \param c Result * \param a First operand * \param b Second operand * * \note Both operands and result are bit strings interpreted as * elements of GF(2^128) as per the GCM spec. */ void mbedtls_aesce_gcm_mult(unsigned char c[16], const unsigned char a[16], const unsigned char b[16]); #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) /** * \brief Internal round key inversion. This function computes * decryption round keys from the encryption round keys. * * \param invkey Round keys for the equivalent inverse cipher * \param fwdkey Original round keys (for encryption) * \param nr Number of rounds (that is, number of round keys minus one) */ void mbedtls_aesce_inverse_key(unsigned char *invkey, const unsigned char *fwdkey, int nr); #endif /* !MBEDTLS_BLOCK_CIPHER_NO_DECRYPT */ /** * \brief Internal key expansion for encryption * * \param rk Destination buffer where the round keys are written * \param key Encryption key * \param bits Key size in bits (must be 128, 192 or 256) * * \return 0 if successful, or MBEDTLS_ERR_AES_INVALID_KEY_LENGTH */ int mbedtls_aesce_setkey_enc(unsigned char *rk, const unsigned char *key, size_t bits); #ifdef __cplusplus } #endif #else #if defined(MBEDTLS_AES_USE_HARDWARE_ONLY) && defined(MBEDTLS_ARCH_IS_ARMV8_A) #error "AES hardware acceleration not supported on this platform / compiler" #endif #endif /* MBEDTLS_AESCE_C && MBEDTLS_ARCH_IS_ARMV8_A && MBEDTLS_HAVE_NEON_INTRINSICS && (MBEDTLS_COMPILER_IS_GCC || __clang__ || MSC_VER) */ #endif /* MBEDTLS_AESCE_H */ keyring/src/salsa20_ref.c0000644000176200001440000000514714775227066015005 0ustar liggesusers/* version 20140420 D. J. Bernstein Public domain. */ #include #include "crypto_core_salsa20.h" #include "crypto_stream_salsa20.h" #include "sodium.h" #include "stream_salsa20.h" #include "salsa20_ref.h" #ifndef HAVE_AMD64_ASM static int stream_ref(unsigned char *c, unsigned long long clen, const unsigned char *n, const unsigned char *k) { unsigned char in[16]; unsigned char block[64]; unsigned char kcopy[32]; unsigned int i; unsigned int u; if (!clen) { return 0; } for (i = 0; i < 32; i++) { kcopy[i] = k[i]; } for (i = 0; i < 8; i++) { in[i] = n[i]; } for (i = 8; i < 16; i++) { in[i] = 0; } while (clen >= 64) { crypto_core_salsa20(c, in, kcopy, NULL); u = 1; for (i = 8; i < 16; i++) { u += (unsigned int) in[i]; in[i] = u; u >>= 8; } clen -= 64; c += 64; } if (clen) { crypto_core_salsa20(block, in, kcopy, NULL); for (i = 0; i < (unsigned int) clen; i++) { c[i] = block[i]; } } sodium_memzero(block, sizeof block); sodium_memzero(kcopy, sizeof kcopy); return 0; } static int stream_ref_xor_ic(unsigned char *c, const unsigned char *m, unsigned long long mlen, const unsigned char *n, uint64_t ic, const unsigned char *k) { unsigned char in[16]; unsigned char block[64]; unsigned char kcopy[32]; unsigned int i; unsigned int u; if (!mlen) { return 0; } for (i = 0; i < 32; i++) { kcopy[i] = k[i]; } for (i = 0; i < 8; i++) { in[i] = n[i]; } for (i = 8; i < 16; i++) { in[i] = (unsigned char) (ic & 0xff); ic >>= 8; } while (mlen >= 64) { crypto_core_salsa20(block, in, kcopy, NULL); for (i = 0; i < 64; i++) { c[i] = m[i] ^ block[i]; } u = 1; for (i = 8; i < 16; i++) { u += (unsigned int) in[i]; in[i] = u; u >>= 8; } mlen -= 64; c += 64; m += 64; } if (mlen) { crypto_core_salsa20(block, in, kcopy, NULL); for (i = 0; i < (unsigned int) mlen; i++) { c[i] = m[i] ^ block[i]; } } sodium_memzero(block, sizeof block); sodium_memzero(kcopy, sizeof kcopy); return 0; } struct crypto_stream_salsa20_implementation crypto_stream_salsa20_ref_implementation = { SODIUM_C99(.stream =) stream_ref, SODIUM_C99(.stream_xor_ic =) stream_ref_xor_ic, }; #endif keyring/src/mbedtls/0000755000176200001440000000000015006370264014146 5ustar liggesuserskeyring/src/mbedtls/config_adjust_x509.h0000644000176200001440000000275515006370264017734 0ustar liggesusers/** * \file mbedtls/config_adjust_x509.h * \brief Adjust X.509 configuration * * This is an internal header. Do not include it directly. * * Automatically enable certain dependencies. Generally, MBEDTLS_xxx * configurations need to be explicitly enabled by the user: enabling * MBEDTLS_xxx_A but not MBEDTLS_xxx_B when A requires B results in a * compilation error. However, we do automatically enable certain options * in some circumstances. One case is if MBEDTLS_xxx_B is an internal option * used to identify parts of a module that are used by other module, and we * don't want to make the symbol MBEDTLS_xxx_B part of the public API. * Another case is if A didn't depend on B in earlier versions, and we * want to use B in A but we need to preserve backward compatibility with * configurations that explicitly activate MBEDTLS_xxx_A but not * MBEDTLS_xxx_B. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_CONFIG_ADJUST_X509_H #define MBEDTLS_CONFIG_ADJUST_X509_H #if !defined(MBEDTLS_CONFIG_FILES_READ) #error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \ "up to and including runtime errors such as buffer overflows. " \ "If you're trying to fix a complaint from check_config.h, just remove " \ "it from your configuration file: since Mbed TLS 3.0, it is included " \ "automatically at the right point." #endif /* */ #endif /* MBEDTLS_CONFIG_ADJUST_X509_H */ keyring/src/mbedtls/config_adjust_psa_from_legacy.h0000644000176200001440000002645415006370264022363 0ustar liggesusers/** * \file mbedtls/config_adjust_psa_from_legacy.h * \brief Adjust PSA configuration: construct PSA configuration from legacy * * This is an internal header. Do not include it directly. * * When MBEDTLS_PSA_CRYPTO_CONFIG is disabled, we automatically enable * cryptographic mechanisms through the PSA interface when the corresponding * legacy mechanism is enabled. In many cases, this just enables the PSA * wrapper code around the legacy implementation, but we also do this for * some mechanisms where PSA has its own independent implementation so * that high-level modules that can use either cryptographic API have the * same feature set in both cases. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_CONFIG_ADJUST_PSA_FROM_LEGACY_H #define MBEDTLS_CONFIG_ADJUST_PSA_FROM_LEGACY_H #if !defined(MBEDTLS_CONFIG_FILES_READ) #error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \ "up to and including runtime errors such as buffer overflows. " \ "If you're trying to fix a complaint from check_config.h, just remove " \ "it from your configuration file: since Mbed TLS 3.0, it is included " \ "automatically at the right point." #endif /* */ /* * Ensure PSA_WANT_* defines are setup properly if MBEDTLS_PSA_CRYPTO_CONFIG * is not defined */ #if defined(MBEDTLS_CCM_C) #define MBEDTLS_PSA_BUILTIN_ALG_CCM 1 #define PSA_WANT_ALG_CCM 1 #if defined(MBEDTLS_CIPHER_C) #define MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG 1 #define PSA_WANT_ALG_CCM_STAR_NO_TAG 1 #endif /* MBEDTLS_CIPHER_C */ #endif /* MBEDTLS_CCM_C */ #if defined(MBEDTLS_CMAC_C) #define MBEDTLS_PSA_BUILTIN_ALG_CMAC 1 #define PSA_WANT_ALG_CMAC 1 #endif /* MBEDTLS_CMAC_C */ #if defined(MBEDTLS_ECDH_C) #define MBEDTLS_PSA_BUILTIN_ALG_ECDH 1 #define PSA_WANT_ALG_ECDH 1 #endif /* MBEDTLS_ECDH_C */ #if defined(MBEDTLS_ECDSA_C) #define MBEDTLS_PSA_BUILTIN_ALG_ECDSA 1 #define PSA_WANT_ALG_ECDSA 1 #define PSA_WANT_ALG_ECDSA_ANY 1 // Only add in DETERMINISTIC support if ECDSA is also enabled #if defined(MBEDTLS_ECDSA_DETERMINISTIC) #define MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA 1 #define PSA_WANT_ALG_DETERMINISTIC_ECDSA 1 #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ #endif /* MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_ECP_C) #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1 #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1 #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1 #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1 /* Normally we wouldn't enable this because it's not implemented in ecp.c, * but since it used to be available any time ECP_C was enabled, let's enable * it anyway for the sake of backwards compatibility */ #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_BASIC 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1 /* See comment for PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE above. */ #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY 1 #define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1 #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_DHM_C) #define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1 #define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT 1 #define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT 1 #define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE 1 #define PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY 1 #define PSA_WANT_ALG_FFDH 1 #define PSA_WANT_DH_RFC7919_2048 1 #define PSA_WANT_DH_RFC7919_3072 1 #define PSA_WANT_DH_RFC7919_4096 1 #define PSA_WANT_DH_RFC7919_6144 1 #define PSA_WANT_DH_RFC7919_8192 1 #define MBEDTLS_PSA_BUILTIN_ALG_FFDH 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_BASIC 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_EXPORT 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY 1 #define MBEDTLS_PSA_BUILTIN_DH_RFC7919_2048 1 #define MBEDTLS_PSA_BUILTIN_DH_RFC7919_3072 1 #define MBEDTLS_PSA_BUILTIN_DH_RFC7919_4096 1 #define MBEDTLS_PSA_BUILTIN_DH_RFC7919_6144 1 #define MBEDTLS_PSA_BUILTIN_DH_RFC7919_8192 1 #endif /* MBEDTLS_DHM_C */ #if defined(MBEDTLS_GCM_C) #define MBEDTLS_PSA_BUILTIN_ALG_GCM 1 #define PSA_WANT_ALG_GCM 1 #endif /* MBEDTLS_GCM_C */ /* Enable PSA HKDF algorithm if mbedtls HKDF is supported. * PSA HKDF EXTRACT and PSA HKDF EXPAND have minimal cost when * PSA HKDF is enabled, so enable both algorithms together * with PSA HKDF. */ #if defined(MBEDTLS_HKDF_C) #define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1 #define PSA_WANT_ALG_HMAC 1 #define MBEDTLS_PSA_BUILTIN_ALG_HKDF 1 #define PSA_WANT_ALG_HKDF 1 #define MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT 1 #define PSA_WANT_ALG_HKDF_EXTRACT 1 #define MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND 1 #define PSA_WANT_ALG_HKDF_EXPAND 1 #endif /* MBEDTLS_HKDF_C */ #define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1 #define PSA_WANT_ALG_HMAC 1 #define PSA_WANT_KEY_TYPE_HMAC 1 #if defined(MBEDTLS_MD_C) #define MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF 1 #define PSA_WANT_ALG_TLS12_PRF 1 #define MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS 1 #define PSA_WANT_ALG_TLS12_PSK_TO_MS 1 #endif /* MBEDTLS_MD_C */ #if defined(MBEDTLS_MD5_C) #define MBEDTLS_PSA_BUILTIN_ALG_MD5 1 #define PSA_WANT_ALG_MD5 1 #endif #if defined(MBEDTLS_ECJPAKE_C) #define MBEDTLS_PSA_BUILTIN_PAKE 1 #define MBEDTLS_PSA_BUILTIN_ALG_JPAKE 1 #define PSA_WANT_ALG_JPAKE 1 #endif #if defined(MBEDTLS_RIPEMD160_C) #define MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160 1 #define PSA_WANT_ALG_RIPEMD160 1 #endif #if defined(MBEDTLS_RSA_C) #if defined(MBEDTLS_PKCS1_V15) #define MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT 1 #define PSA_WANT_ALG_RSA_PKCS1V15_CRYPT 1 #define MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN 1 #define PSA_WANT_ALG_RSA_PKCS1V15_SIGN 1 #define PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW 1 #endif /* MBEDTLS_PKCS1_V15 */ #if defined(MBEDTLS_PKCS1_V21) #define MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP 1 #define PSA_WANT_ALG_RSA_OAEP 1 #define MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS 1 #define PSA_WANT_ALG_RSA_PSS 1 #endif /* MBEDTLS_PKCS1_V21 */ #if defined(MBEDTLS_GENPRIME) #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1 #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1 #endif /* MBEDTLS_GENPRIME */ #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_BASIC 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1 #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1 #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1 #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY 1 #define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1 #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_SHA1_C) #define MBEDTLS_PSA_BUILTIN_ALG_SHA_1 1 #define PSA_WANT_ALG_SHA_1 1 #endif #if defined(MBEDTLS_SHA224_C) #define MBEDTLS_PSA_BUILTIN_ALG_SHA_224 1 #define PSA_WANT_ALG_SHA_224 1 #endif #if defined(MBEDTLS_SHA256_C) #define MBEDTLS_PSA_BUILTIN_ALG_SHA_256 1 #define PSA_WANT_ALG_SHA_256 1 #endif #if defined(MBEDTLS_SHA384_C) #define MBEDTLS_PSA_BUILTIN_ALG_SHA_384 1 #define PSA_WANT_ALG_SHA_384 1 #endif #if defined(MBEDTLS_SHA512_C) #define MBEDTLS_PSA_BUILTIN_ALG_SHA_512 1 #define PSA_WANT_ALG_SHA_512 1 #endif #if defined(MBEDTLS_SHA3_C) #define MBEDTLS_PSA_BUILTIN_ALG_SHA3_224 1 #define MBEDTLS_PSA_BUILTIN_ALG_SHA3_256 1 #define MBEDTLS_PSA_BUILTIN_ALG_SHA3_384 1 #define MBEDTLS_PSA_BUILTIN_ALG_SHA3_512 1 #define PSA_WANT_ALG_SHA3_224 1 #define PSA_WANT_ALG_SHA3_256 1 #define PSA_WANT_ALG_SHA3_384 1 #define PSA_WANT_ALG_SHA3_512 1 #endif #if defined(MBEDTLS_AES_C) #define PSA_WANT_KEY_TYPE_AES 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_AES 1 #endif #if defined(MBEDTLS_ARIA_C) #define PSA_WANT_KEY_TYPE_ARIA 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ARIA 1 #endif #if defined(MBEDTLS_CAMELLIA_C) #define PSA_WANT_KEY_TYPE_CAMELLIA 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_CAMELLIA 1 #endif #if defined(MBEDTLS_DES_C) #define PSA_WANT_KEY_TYPE_DES 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES 1 #endif #if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256) #define MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS 1 #define PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS 1 #endif #if defined(MBEDTLS_CHACHA20_C) #define PSA_WANT_KEY_TYPE_CHACHA20 1 #define MBEDTLS_PSA_BUILTIN_KEY_TYPE_CHACHA20 1 /* ALG_STREAM_CIPHER requires CIPHER_C in order to be supported in PSA */ #if defined(MBEDTLS_CIPHER_C) #define PSA_WANT_ALG_STREAM_CIPHER 1 #define MBEDTLS_PSA_BUILTIN_ALG_STREAM_CIPHER 1 #endif #if defined(MBEDTLS_CHACHAPOLY_C) #define PSA_WANT_ALG_CHACHA20_POLY1305 1 #define MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 1 #endif #endif #if defined(MBEDTLS_CIPHER_MODE_CBC) #define MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING 1 #define PSA_WANT_ALG_CBC_NO_PADDING 1 #if defined(MBEDTLS_CIPHER_PADDING_PKCS7) #define MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7 1 #define PSA_WANT_ALG_CBC_PKCS7 1 #endif #endif #if (defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) || \ defined(MBEDTLS_ARIA_C) || defined(MBEDTLS_CAMELLIA_C)) && \ defined(MBEDTLS_CIPHER_C) #define MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING 1 #define PSA_WANT_ALG_ECB_NO_PADDING 1 #endif #if defined(MBEDTLS_CIPHER_MODE_CFB) #define MBEDTLS_PSA_BUILTIN_ALG_CFB 1 #define PSA_WANT_ALG_CFB 1 #endif #if defined(MBEDTLS_CIPHER_MODE_CTR) #define MBEDTLS_PSA_BUILTIN_ALG_CTR 1 #define PSA_WANT_ALG_CTR 1 #endif #if defined(MBEDTLS_CIPHER_MODE_OFB) #define MBEDTLS_PSA_BUILTIN_ALG_OFB 1 #define PSA_WANT_ALG_OFB 1 #endif #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_BRAINPOOL_P_R1_256 1 #define PSA_WANT_ECC_BRAINPOOL_P_R1_256 1 #endif #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_BRAINPOOL_P_R1_384 1 #define PSA_WANT_ECC_BRAINPOOL_P_R1_384 1 #endif #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_BRAINPOOL_P_R1_512 1 #define PSA_WANT_ECC_BRAINPOOL_P_R1_512 1 #endif #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_MONTGOMERY_255 1 #define PSA_WANT_ECC_MONTGOMERY_255 1 #endif #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_MONTGOMERY_448 1 #define PSA_WANT_ECC_MONTGOMERY_448 1 #endif #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_192 1 #define PSA_WANT_ECC_SECP_R1_192 1 #endif #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_224 1 #define PSA_WANT_ECC_SECP_R1_224 1 #endif #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_256 1 #define PSA_WANT_ECC_SECP_R1_256 1 #endif #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_384 1 #define PSA_WANT_ECC_SECP_R1_384 1 #endif #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_521 1 #define PSA_WANT_ECC_SECP_R1_521 1 #endif #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_SECP_K1_192 1 #define PSA_WANT_ECC_SECP_K1_192 1 #endif /* SECP224K1 is buggy via the PSA API (https://github.com/Mbed-TLS/mbedtls/issues/3541) */ #if 0 && defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_SECP_K1_224 1 #define PSA_WANT_ECC_SECP_K1_224 1 #endif #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) #define MBEDTLS_PSA_BUILTIN_ECC_SECP_K1_256 1 #define PSA_WANT_ECC_SECP_K1_256 1 #endif #endif /* MBEDTLS_CONFIG_ADJUST_PSA_FROM_LEGACY_H */ keyring/src/mbedtls/threading.h0000644000176200001440000001204015006370264016261 0ustar liggesusers/** * \file threading.h * * \brief Threading abstraction layer */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_THREADING_H #define MBEDTLS_THREADING_H #include "mbedtls/private_access.h" #include "mbedtls/build_info.h" #include #ifdef __cplusplus extern "C" { #endif /** Bad input parameters to function. */ #define MBEDTLS_ERR_THREADING_BAD_INPUT_DATA -0x001C /** Locking / unlocking / free failed with error code. */ #define MBEDTLS_ERR_THREADING_MUTEX_ERROR -0x001E #if defined(MBEDTLS_THREADING_PTHREAD) #include typedef struct mbedtls_threading_mutex_t { pthread_mutex_t MBEDTLS_PRIVATE(mutex); /* WARNING - state should only be accessed when holding the mutex lock in * framework/tests/src/threading_helpers.c, otherwise corruption can occur. * state will be 0 after a failed init or a free, and nonzero after a * successful init. This field is for testing only and thus not considered * part of the public API of Mbed TLS and may change without notice.*/ char MBEDTLS_PRIVATE(state); } mbedtls_threading_mutex_t; #endif #if defined(MBEDTLS_THREADING_ALT) /* You should define the mbedtls_threading_mutex_t type in your header */ #include "threading_alt.h" /** * \brief Set your alternate threading implementation function * pointers and initialize global mutexes. If used, this * function must be called once in the main thread before any * other Mbed TLS function is called, and * mbedtls_threading_free_alt() must be called once in the main * thread after all other Mbed TLS functions. * * \note mutex_init() and mutex_free() don't return a status code. * If mutex_init() fails, it should leave its argument (the * mutex) in a state such that mutex_lock() will fail when * called with this argument. * * \param mutex_init the init function implementation * \param mutex_free the free function implementation * \param mutex_lock the lock function implementation * \param mutex_unlock the unlock function implementation */ void mbedtls_threading_set_alt(void (*mutex_init)(mbedtls_threading_mutex_t *), void (*mutex_free)(mbedtls_threading_mutex_t *), int (*mutex_lock)(mbedtls_threading_mutex_t *), int (*mutex_unlock)(mbedtls_threading_mutex_t *)); /** * \brief Free global mutexes. */ void mbedtls_threading_free_alt(void); #endif /* MBEDTLS_THREADING_ALT */ #if defined(MBEDTLS_THREADING_C) /* * The function pointers for mutex_init, mutex_free, mutex_ and mutex_unlock * * All these functions are expected to work or the result will be undefined. */ extern void (*mbedtls_mutex_init)(mbedtls_threading_mutex_t *mutex); extern void (*mbedtls_mutex_free)(mbedtls_threading_mutex_t *mutex); extern int (*mbedtls_mutex_lock)(mbedtls_threading_mutex_t *mutex); extern int (*mbedtls_mutex_unlock)(mbedtls_threading_mutex_t *mutex); /* * Global mutexes */ #if defined(MBEDTLS_FS_IO) extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex; #endif #if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_PLATFORM_GMTIME_R_ALT) /* This mutex may or may not be used in the default definition of * mbedtls_platform_gmtime_r(), but in order to determine that, * we need to check POSIX features, hence modify _POSIX_C_SOURCE. * With the current approach, this declaration is orphaned, lacking * an accompanying definition, in case mbedtls_platform_gmtime_r() * doesn't need it, but that's not a problem. */ extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex; #endif /* MBEDTLS_HAVE_TIME_DATE && !MBEDTLS_PLATFORM_GMTIME_R_ALT */ #if defined(MBEDTLS_PSA_CRYPTO_C) /* * A mutex used to make the PSA subsystem thread safe. * * key_slot_mutex protects the registered_readers and * state variable for all key slots in &global_data.key_slots. * * This mutex must be held when any read from or write to a state or * registered_readers field is performed, i.e. when calling functions: * psa_key_slot_state_transition(), psa_register_read(), psa_unregister_read(), * psa_key_slot_has_readers() and psa_wipe_key_slot(). */ extern mbedtls_threading_mutex_t mbedtls_threading_key_slot_mutex; /* * A mutex used to make the non-rng PSA global_data struct members thread safe. * * This mutex must be held when reading or writing to any of the PSA global_data * structure members, other than the rng_state or rng struct. */ extern mbedtls_threading_mutex_t mbedtls_threading_psa_globaldata_mutex; /* * A mutex used to make the PSA global_data rng data thread safe. * * This mutex must be held when reading or writing to the PSA * global_data rng_state or rng struct members. */ extern mbedtls_threading_mutex_t mbedtls_threading_psa_rngdata_mutex; #endif #endif /* MBEDTLS_THREADING_C */ #ifdef __cplusplus } #endif #endif /* threading.h */ keyring/src/mbedtls/platform_time.h0000644000176200001440000000362215006370264017164 0ustar liggesusers/** * \file platform_time.h * * \brief Mbed TLS Platform time abstraction */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_PLATFORM_TIME_H #define MBEDTLS_PLATFORM_TIME_H #include "mbedtls/build_info.h" #ifdef __cplusplus extern "C" { #endif /* * The time_t datatype */ #if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) typedef MBEDTLS_PLATFORM_TIME_TYPE_MACRO mbedtls_time_t; #else /* For time_t */ #include typedef time_t mbedtls_time_t; #endif /* MBEDTLS_PLATFORM_TIME_TYPE_MACRO */ #if defined(MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO) typedef MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO mbedtls_ms_time_t; #else #include #include typedef int64_t mbedtls_ms_time_t; #endif /* MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO */ /** * \brief Get time in milliseconds. * * \return Monotonically-increasing current time in milliseconds. * * \note Define MBEDTLS_PLATFORM_MS_TIME_ALT to be able to provide an * alternative implementation * * \warning This function returns a monotonically-increasing time value from a * start time that will differ from platform to platform, and possibly * from run to run of the process. * */ mbedtls_ms_time_t mbedtls_ms_time(void); /* * The function pointers for time */ #if defined(MBEDTLS_PLATFORM_TIME_ALT) extern mbedtls_time_t (*mbedtls_time)(mbedtls_time_t *time); /** * \brief Set your own time function pointer * * \param time_func the time function implementation * * \return 0 */ int mbedtls_platform_set_time(mbedtls_time_t (*time_func)(mbedtls_time_t *time)); #else #if defined(MBEDTLS_PLATFORM_TIME_MACRO) #define mbedtls_time MBEDTLS_PLATFORM_TIME_MACRO #else #define mbedtls_time time #endif /* MBEDTLS_PLATFORM_TIME_MACRO */ #endif /* MBEDTLS_PLATFORM_TIME_ALT */ #ifdef __cplusplus } #endif #endif /* platform_time.h */ keyring/src/mbedtls/config_adjust_psa_superset_legacy.h0000644000176200001440000001143015006370264023256 0ustar liggesusers/** * \file mbedtls/config_adjust_psa_superset_legacy.h * \brief Adjust PSA configuration: automatic enablement from legacy * * This is an internal header. Do not include it directly. * * To simplify some edge cases, we automatically enable certain cryptographic * mechanisms in the PSA API if they are enabled in the legacy API. The general * idea is that if legacy module M uses mechanism A internally, and A has * both a legacy and a PSA implementation, we enable A through PSA whenever * it's enabled through legacy. This facilitates the transition to PSA * implementations of A for users of M. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_CONFIG_ADJUST_PSA_SUPERSET_LEGACY_H #define MBEDTLS_CONFIG_ADJUST_PSA_SUPERSET_LEGACY_H #if !defined(MBEDTLS_CONFIG_FILES_READ) #error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \ "up to and including runtime errors such as buffer overflows. " \ "If you're trying to fix a complaint from check_config.h, just remove " \ "it from your configuration file: since Mbed TLS 3.0, it is included " \ "automatically at the right point." #endif /* */ /****************************************************************/ /* Hashes that are built in are also enabled in PSA. * This simplifies dependency declarations especially * for modules that obey MBEDTLS_USE_PSA_CRYPTO. */ /****************************************************************/ #if defined(MBEDTLS_MD5_C) #define PSA_WANT_ALG_MD5 1 #endif #if defined(MBEDTLS_RIPEMD160_C) #define PSA_WANT_ALG_RIPEMD160 1 #endif #if defined(MBEDTLS_SHA1_C) #define PSA_WANT_ALG_SHA_1 1 #endif #if defined(MBEDTLS_SHA224_C) #define PSA_WANT_ALG_SHA_224 1 #endif #if defined(MBEDTLS_SHA256_C) #define PSA_WANT_ALG_SHA_256 1 #endif #if defined(MBEDTLS_SHA384_C) #define PSA_WANT_ALG_SHA_384 1 #endif #if defined(MBEDTLS_SHA512_C) #define PSA_WANT_ALG_SHA_512 1 #endif #if defined(MBEDTLS_SHA3_C) #define PSA_WANT_ALG_SHA3_224 1 #define PSA_WANT_ALG_SHA3_256 1 #define PSA_WANT_ALG_SHA3_384 1 #define PSA_WANT_ALG_SHA3_512 1 #endif /* Ensure that the PSA's supported curves (PSA_WANT_ECC_xxx) are always a * superset of the builtin ones (MBEDTLS_ECP_DP_xxx). */ #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) #if !defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256) #define PSA_WANT_ECC_BRAINPOOL_P_R1_256 1 #endif /* PSA_WANT_ECC_BRAINPOOL_P_R1_256 */ #endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) #if !defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384) #define PSA_WANT_ECC_BRAINPOOL_P_R1_384 1 #endif /* PSA_WANT_ECC_BRAINPOOL_P_R1_384 */ #endif /*MBEDTLS_ECP_DP_BP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) #if !defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512) #define PSA_WANT_ECC_BRAINPOOL_P_R1_512 1 #endif /* PSA_WANT_ECC_BRAINPOOL_P_R1_512 */ #endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) #if !defined(PSA_WANT_ECC_MONTGOMERY_255) #define PSA_WANT_ECC_MONTGOMERY_255 1 #endif /* PSA_WANT_ECC_MONTGOMERY_255 */ #endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */ #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) #if !defined(PSA_WANT_ECC_MONTGOMERY_448) #define PSA_WANT_ECC_MONTGOMERY_448 1 #endif /* PSA_WANT_ECC_MONTGOMERY_448 */ #endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) #if !defined(PSA_WANT_ECC_SECP_R1_192) #define PSA_WANT_ECC_SECP_R1_192 1 #endif /* PSA_WANT_ECC_SECP_R1_192 */ #endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) #if !defined(PSA_WANT_ECC_SECP_R1_224) #define PSA_WANT_ECC_SECP_R1_224 1 #endif /* PSA_WANT_ECC_SECP_R1_224 */ #endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) #if !defined(PSA_WANT_ECC_SECP_R1_256) #define PSA_WANT_ECC_SECP_R1_256 1 #endif /* PSA_WANT_ECC_SECP_R1_256 */ #endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) #if !defined(PSA_WANT_ECC_SECP_R1_384) #define PSA_WANT_ECC_SECP_R1_384 1 #endif /* PSA_WANT_ECC_SECP_R1_384 */ #endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) #if !defined(PSA_WANT_ECC_SECP_R1_521) #define PSA_WANT_ECC_SECP_R1_521 1 #endif /* PSA_WANT_ECC_SECP_R1_521 */ #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) #if !defined(PSA_WANT_ECC_SECP_K1_192) #define PSA_WANT_ECC_SECP_K1_192 1 #endif /* PSA_WANT_ECC_SECP_K1_192 */ #endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) #if !defined(PSA_WANT_ECC_SECP_K1_256) #define PSA_WANT_ECC_SECP_K1_256 1 #endif /* PSA_WANT_ECC_SECP_K1_256 */ #endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ #endif /* MBEDTLS_CONFIG_ADJUST_PSA_SUPERSET_LEGACY_H */ keyring/src/mbedtls/config_adjust_legacy_crypto.h0000644000176200001440000004646115006370264022075 0ustar liggesusers/** * \file mbedtls/config_adjust_legacy_crypto.h * \brief Adjust legacy configuration configuration * * This is an internal header. Do not include it directly. * * Automatically enable certain dependencies. Generally, MBEDTLS_xxx * configurations need to be explicitly enabled by the user: enabling * MBEDTLS_xxx_A but not MBEDTLS_xxx_B when A requires B results in a * compilation error. However, we do automatically enable certain options * in some circumstances. One case is if MBEDTLS_xxx_B is an internal option * used to identify parts of a module that are used by other module, and we * don't want to make the symbol MBEDTLS_xxx_B part of the public API. * Another case is if A didn't depend on B in earlier versions, and we * want to use B in A but we need to preserve backward compatibility with * configurations that explicitly activate MBEDTLS_xxx_A but not * MBEDTLS_xxx_B. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_CONFIG_ADJUST_LEGACY_CRYPTO_H #define MBEDTLS_CONFIG_ADJUST_LEGACY_CRYPTO_H #if !defined(MBEDTLS_CONFIG_FILES_READ) #error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \ "up to and including runtime errors such as buffer overflows. " \ "If you're trying to fix a complaint from check_config.h, just remove " \ "it from your configuration file: since Mbed TLS 3.0, it is included " \ "automatically at the right point." #endif /* */ /* Ideally, we'd set those as defaults in mbedtls_config.h, but * putting an #ifdef _WIN32 in mbedtls_config.h would confuse config.py. * * So, adjust it here. * Not related to crypto, but this is the bottom of the stack. */ #if defined(__MINGW32__) || (defined(_MSC_VER) && _MSC_VER <= 1900) #if !defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) && \ !defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) #define MBEDTLS_PLATFORM_SNPRINTF_ALT #endif #if !defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT) && \ !defined(MBEDTLS_PLATFORM_VSNPRINTF_MACRO) #define MBEDTLS_PLATFORM_VSNPRINTF_ALT #endif #endif /* _MINGW32__ || (_MSC_VER && (_MSC_VER <= 1900)) */ /* If MBEDTLS_PSA_CRYPTO_C is defined, make sure MBEDTLS_PSA_CRYPTO_CLIENT * is defined as well to include all PSA code. */ #if defined(MBEDTLS_PSA_CRYPTO_C) #define MBEDTLS_PSA_CRYPTO_CLIENT #endif /* MBEDTLS_PSA_CRYPTO_C */ /* Auto-enable CIPHER_C when any of the unauthenticated ciphers is builtin * in PSA. */ #if defined(MBEDTLS_PSA_CRYPTO_C) && \ (defined(MBEDTLS_PSA_BUILTIN_ALG_STREAM_CIPHER) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CTR) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CFB) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_OFB) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC)) #define MBEDTLS_CIPHER_C #endif /* Auto-enable MBEDTLS_MD_LIGHT based on MBEDTLS_MD_C. * This allows checking for MD_LIGHT rather than MD_LIGHT || MD_C. */ #if defined(MBEDTLS_MD_C) #define MBEDTLS_MD_LIGHT #endif /* Auto-enable MBEDTLS_MD_LIGHT if needed by a module that didn't require it * in a previous release, to ensure backwards compatibility. */ #if defined(MBEDTLS_ECJPAKE_C) || \ defined(MBEDTLS_PEM_PARSE_C) || \ defined(MBEDTLS_ENTROPY_C) || \ defined(MBEDTLS_PK_C) || \ defined(MBEDTLS_PKCS12_C) || \ defined(MBEDTLS_RSA_C) || \ defined(MBEDTLS_SSL_TLS_C) || \ defined(MBEDTLS_X509_USE_C) || \ defined(MBEDTLS_X509_CREATE_C) #define MBEDTLS_MD_LIGHT #endif #if defined(MBEDTLS_MD_LIGHT) /* * - MBEDTLS_MD_CAN_xxx is defined if the md module can perform xxx. * - MBEDTLS_MD_xxx_VIA_PSA is defined if the md module may perform xxx via PSA * (see below). * - MBEDTLS_MD_SOME_PSA is defined if at least one algorithm may be performed * via PSA (see below). * - MBEDTLS_MD_SOME_LEGACY is defined if at least one algorithm may be performed * via a direct legacy call (see below). * * The md module performs an algorithm via PSA if there is a PSA hash * accelerator and the PSA driver subsytem is initialized at the time the * operation is started, and makes a direct legacy call otherwise. */ /* PSA accelerated implementations */ #if defined(MBEDTLS_PSA_CRYPTO_C) #if defined(MBEDTLS_PSA_ACCEL_ALG_MD5) #define MBEDTLS_MD_CAN_MD5 #define MBEDTLS_MD_MD5_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_1) #define MBEDTLS_MD_CAN_SHA1 #define MBEDTLS_MD_SHA1_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_224) #define MBEDTLS_MD_CAN_SHA224 #define MBEDTLS_MD_SHA224_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_256) #define MBEDTLS_MD_CAN_SHA256 #define MBEDTLS_MD_SHA256_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_384) #define MBEDTLS_MD_CAN_SHA384 #define MBEDTLS_MD_SHA384_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_512) #define MBEDTLS_MD_CAN_SHA512 #define MBEDTLS_MD_SHA512_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_RIPEMD160) #define MBEDTLS_MD_CAN_RIPEMD160 #define MBEDTLS_MD_RIPEMD160_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_224) #define MBEDTLS_MD_CAN_SHA3_224 #define MBEDTLS_MD_SHA3_224_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_256) #define MBEDTLS_MD_CAN_SHA3_256 #define MBEDTLS_MD_SHA3_256_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_384) #define MBEDTLS_MD_CAN_SHA3_384 #define MBEDTLS_MD_SHA3_384_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_512) #define MBEDTLS_MD_CAN_SHA3_512 #define MBEDTLS_MD_SHA3_512_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #elif defined(MBEDTLS_PSA_CRYPTO_CLIENT) #if defined(PSA_WANT_ALG_MD5) #define MBEDTLS_MD_CAN_MD5 #define MBEDTLS_MD_MD5_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_SHA_1) #define MBEDTLS_MD_CAN_SHA1 #define MBEDTLS_MD_SHA1_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_SHA_224) #define MBEDTLS_MD_CAN_SHA224 #define MBEDTLS_MD_SHA224_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_SHA_256) #define MBEDTLS_MD_CAN_SHA256 #define MBEDTLS_MD_SHA256_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_SHA_384) #define MBEDTLS_MD_CAN_SHA384 #define MBEDTLS_MD_SHA384_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_SHA_512) #define MBEDTLS_MD_CAN_SHA512 #define MBEDTLS_MD_SHA512_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_RIPEMD160) #define MBEDTLS_MD_CAN_RIPEMD160 #define MBEDTLS_MD_RIPEMD160_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_SHA3_224) #define MBEDTLS_MD_CAN_SHA3_224 #define MBEDTLS_MD_SHA3_224_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_SHA3_256) #define MBEDTLS_MD_CAN_SHA3_256 #define MBEDTLS_MD_SHA3_256_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_SHA3_384) #define MBEDTLS_MD_CAN_SHA3_384 #define MBEDTLS_MD_SHA3_384_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #if defined(PSA_WANT_ALG_SHA3_512) #define MBEDTLS_MD_CAN_SHA3_512 #define MBEDTLS_MD_SHA3_512_VIA_PSA #define MBEDTLS_MD_SOME_PSA #endif #endif /* !MBEDTLS_PSA_CRYPTO_CLIENT && !MBEDTLS_PSA_CRYPTO_C */ /* Built-in implementations */ #if defined(MBEDTLS_MD5_C) #define MBEDTLS_MD_CAN_MD5 #define MBEDTLS_MD_SOME_LEGACY #endif #if defined(MBEDTLS_SHA1_C) #define MBEDTLS_MD_CAN_SHA1 #define MBEDTLS_MD_SOME_LEGACY #endif #if defined(MBEDTLS_SHA224_C) #define MBEDTLS_MD_CAN_SHA224 #define MBEDTLS_MD_SOME_LEGACY #endif #if defined(MBEDTLS_SHA256_C) #define MBEDTLS_MD_CAN_SHA256 #define MBEDTLS_MD_SOME_LEGACY #endif #if defined(MBEDTLS_SHA384_C) #define MBEDTLS_MD_CAN_SHA384 #define MBEDTLS_MD_SOME_LEGACY #endif #if defined(MBEDTLS_SHA512_C) #define MBEDTLS_MD_CAN_SHA512 #define MBEDTLS_MD_SOME_LEGACY #endif #if defined(MBEDTLS_SHA3_C) #define MBEDTLS_MD_CAN_SHA3_224 #define MBEDTLS_MD_CAN_SHA3_256 #define MBEDTLS_MD_CAN_SHA3_384 #define MBEDTLS_MD_CAN_SHA3_512 #define MBEDTLS_MD_SOME_LEGACY #endif #if defined(MBEDTLS_RIPEMD160_C) #define MBEDTLS_MD_CAN_RIPEMD160 #define MBEDTLS_MD_SOME_LEGACY #endif #endif /* MBEDTLS_MD_LIGHT */ /* BLOCK_CIPHER module can dispatch to PSA when: * - PSA is enabled and drivers have been initialized * - desired key type is supported on the PSA side * If the above conditions are not met, but the legacy support is enabled, then * BLOCK_CIPHER will dynamically fallback to it. * * In case BLOCK_CIPHER is defined (see below) the following symbols/helpers * can be used to define its capabilities: * - MBEDTLS_BLOCK_CIPHER_SOME_PSA: there is at least 1 key type between AES, * ARIA and Camellia which is supported through a driver; * - MBEDTLS_BLOCK_CIPHER_xxx_VIA_PSA: xxx key type is supported through a * driver; * - MBEDTLS_BLOCK_CIPHER_xxx_VIA_LEGACY: xxx key type is supported through * a legacy module (i.e. MBEDTLS_xxx_C) */ #if defined(MBEDTLS_PSA_CRYPTO_C) #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_AES) #define MBEDTLS_BLOCK_CIPHER_AES_VIA_PSA #define MBEDTLS_BLOCK_CIPHER_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ARIA) #define MBEDTLS_BLOCK_CIPHER_ARIA_VIA_PSA #define MBEDTLS_BLOCK_CIPHER_SOME_PSA #endif #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_CAMELLIA) #define MBEDTLS_BLOCK_CIPHER_CAMELLIA_VIA_PSA #define MBEDTLS_BLOCK_CIPHER_SOME_PSA #endif #endif /* MBEDTLS_PSA_CRYPTO_C */ #if defined(MBEDTLS_AES_C) #define MBEDTLS_BLOCK_CIPHER_AES_VIA_LEGACY #endif #if defined(MBEDTLS_ARIA_C) #define MBEDTLS_BLOCK_CIPHER_ARIA_VIA_LEGACY #endif #if defined(MBEDTLS_CAMELLIA_C) #define MBEDTLS_BLOCK_CIPHER_CAMELLIA_VIA_LEGACY #endif /* Helpers to state that BLOCK_CIPHER module supports AES, ARIA and/or Camellia * block ciphers via either PSA or legacy. */ #if defined(MBEDTLS_BLOCK_CIPHER_AES_VIA_PSA) || \ defined(MBEDTLS_BLOCK_CIPHER_AES_VIA_LEGACY) #define MBEDTLS_BLOCK_CIPHER_CAN_AES #endif #if defined(MBEDTLS_BLOCK_CIPHER_ARIA_VIA_PSA) || \ defined(MBEDTLS_BLOCK_CIPHER_ARIA_VIA_LEGACY) #define MBEDTLS_BLOCK_CIPHER_CAN_ARIA #endif #if defined(MBEDTLS_BLOCK_CIPHER_CAMELLIA_VIA_PSA) || \ defined(MBEDTLS_BLOCK_CIPHER_CAMELLIA_VIA_LEGACY) #define MBEDTLS_BLOCK_CIPHER_CAN_CAMELLIA #endif /* GCM_C and CCM_C can either depend on (in order of preference) BLOCK_CIPHER_C * or CIPHER_C. The former is auto-enabled when: * - CIPHER_C is not defined, which is also the legacy solution; * - BLOCK_CIPHER_SOME_PSA because in this case BLOCK_CIPHER can take advantage * of the driver's acceleration. */ #if (defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C)) && \ (!defined(MBEDTLS_CIPHER_C) || defined(MBEDTLS_BLOCK_CIPHER_SOME_PSA)) #define MBEDTLS_BLOCK_CIPHER_C #endif /* Helpers for GCM/CCM capabilities */ #if (defined(MBEDTLS_CIPHER_C) && defined(MBEDTLS_AES_C)) || \ (defined(MBEDTLS_BLOCK_CIPHER_C) && defined(MBEDTLS_BLOCK_CIPHER_CAN_AES)) #define MBEDTLS_CCM_GCM_CAN_AES #endif #if (defined(MBEDTLS_CIPHER_C) && defined(MBEDTLS_ARIA_C)) || \ (defined(MBEDTLS_BLOCK_CIPHER_C) && defined(MBEDTLS_BLOCK_CIPHER_CAN_ARIA)) #define MBEDTLS_CCM_GCM_CAN_ARIA #endif #if (defined(MBEDTLS_CIPHER_C) && defined(MBEDTLS_CAMELLIA_C)) || \ (defined(MBEDTLS_BLOCK_CIPHER_C) && defined(MBEDTLS_BLOCK_CIPHER_CAN_CAMELLIA)) #define MBEDTLS_CCM_GCM_CAN_CAMELLIA #endif /* MBEDTLS_ECP_LIGHT is auto-enabled by the following symbols: * - MBEDTLS_ECP_C because now it consists of MBEDTLS_ECP_LIGHT plus functions * for curve arithmetic. As a consequence if MBEDTLS_ECP_C is required for * some reason, then MBEDTLS_ECP_LIGHT should be enabled as well. * - MBEDTLS_PK_PARSE_EC_EXTENDED and MBEDTLS_PK_PARSE_EC_COMPRESSED because * these features are not supported in PSA so the only way to have them is * to enable the built-in solution. * Both of them are temporary dependencies: * - PK_PARSE_EC_EXTENDED will be removed after #7779 and #7789 * - support for compressed points should also be added to PSA, but in this * case there is no associated issue to track it yet. * - PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE because Weierstrass key derivation * still depends on ECP_LIGHT. * - PK_C + USE_PSA + PSA_WANT_ALG_ECDSA is a temporary dependency which will * be fixed by #7453. */ #if defined(MBEDTLS_ECP_C) || \ defined(MBEDTLS_PK_PARSE_EC_EXTENDED) || \ defined(MBEDTLS_PK_PARSE_EC_COMPRESSED) || \ defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE) #define MBEDTLS_ECP_LIGHT #endif /* Backward compatibility: after #8740 the RSA module offers functions to parse * and write RSA private/public keys without relying on the PK one. Of course * this needs ASN1 support to do so, so we enable it here. */ #if defined(MBEDTLS_RSA_C) #define MBEDTLS_ASN1_PARSE_C #define MBEDTLS_ASN1_WRITE_C #endif /* MBEDTLS_PK_PARSE_EC_COMPRESSED is introduced in Mbed TLS version 3.5, while * in previous version compressed points were automatically supported as long * as PK_PARSE_C and ECP_C were enabled. As a consequence, for backward * compatibility, we auto-enable PK_PARSE_EC_COMPRESSED when these conditions * are met. */ #if defined(MBEDTLS_PK_PARSE_C) && defined(MBEDTLS_ECP_C) #define MBEDTLS_PK_PARSE_EC_COMPRESSED #endif /* Helper symbol to state that there is support for ECDH, either through * library implementation (ECDH_C) or through PSA. */ #if (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_ALG_ECDH)) || \ (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_ECDH_C)) #define MBEDTLS_CAN_ECDH #endif /* PK module can achieve ECDSA functionalities by means of either software * implementations (ECDSA_C) or through a PSA driver. The following defines * are meant to list these capabilities in a general way which abstracts how * they are implemented under the hood. */ #if !defined(MBEDTLS_USE_PSA_CRYPTO) #if defined(MBEDTLS_ECDSA_C) #define MBEDTLS_PK_CAN_ECDSA_SIGN #define MBEDTLS_PK_CAN_ECDSA_VERIFY #endif /* MBEDTLS_ECDSA_C */ #else /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(PSA_WANT_ALG_ECDSA) #if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) #define MBEDTLS_PK_CAN_ECDSA_SIGN #endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC */ #if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) #define MBEDTLS_PK_CAN_ECDSA_VERIFY #endif /* PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY */ #endif /* PSA_WANT_ALG_ECDSA */ #endif /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_PK_CAN_ECDSA_VERIFY) || defined(MBEDTLS_PK_CAN_ECDSA_SIGN) #define MBEDTLS_PK_CAN_ECDSA_SOME #endif /* Helpers to state that each key is supported either on the builtin or PSA side. */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_521) #define MBEDTLS_ECP_HAVE_SECP521R1 #endif #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512) #define MBEDTLS_ECP_HAVE_BP512R1 #endif #if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) || defined(PSA_WANT_ECC_MONTGOMERY_448) #define MBEDTLS_ECP_HAVE_CURVE448 #endif #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384) #define MBEDTLS_ECP_HAVE_BP384R1 #endif #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_384) #define MBEDTLS_ECP_HAVE_SECP384R1 #endif #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256) #define MBEDTLS_ECP_HAVE_BP256R1 #endif #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) || defined(PSA_WANT_ECC_SECP_K1_256) #define MBEDTLS_ECP_HAVE_SECP256K1 #endif #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_256) #define MBEDTLS_ECP_HAVE_SECP256R1 #endif #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || defined(PSA_WANT_ECC_MONTGOMERY_255) #define MBEDTLS_ECP_HAVE_CURVE25519 #endif #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || defined(PSA_WANT_ECC_SECP_K1_224) #define MBEDTLS_ECP_HAVE_SECP224K1 #endif #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_224) #define MBEDTLS_ECP_HAVE_SECP224R1 #endif #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || defined(PSA_WANT_ECC_SECP_K1_192) #define MBEDTLS_ECP_HAVE_SECP192K1 #endif #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_192) #define MBEDTLS_ECP_HAVE_SECP192R1 #endif /* Helper symbol to state that the PK module has support for EC keys. This * can either be provided through the legacy ECP solution or through the * PSA friendly MBEDTLS_PK_USE_PSA_EC_DATA (see pk.h for its description). */ #if defined(MBEDTLS_ECP_C) || \ (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)) #define MBEDTLS_PK_HAVE_ECC_KEYS #endif /* MBEDTLS_PK_USE_PSA_EC_DATA || MBEDTLS_ECP_C */ /* Historically pkparse did not check the CBC padding when decrypting * a key. This was a bug, which is now fixed. As a consequence, pkparse * now needs PKCS7 padding support, but existing configurations might not * enable it, so we enable it here. */ #if defined(MBEDTLS_PK_PARSE_C) && defined(MBEDTLS_PKCS5_C) && defined(MBEDTLS_CIPHER_MODE_CBC) #define MBEDTLS_CIPHER_PADDING_PKCS7 #endif /* Backwards compatibility for some macros which were renamed to reflect that * they are related to Armv8, not aarch64. */ #if defined(MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT) && \ !defined(MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT) #define MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT #endif #if defined(MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY) && !defined(MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY) #define MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY #endif /* psa_util file features some ECDSA conversion functions, to convert between * legacy's ASN.1 DER format and PSA's raw one. */ #if (defined(MBEDTLS_PSA_CRYPTO_CLIENT) && \ (defined(PSA_WANT_ALG_ECDSA) || defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA))) #define MBEDTLS_PSA_UTIL_HAVE_ECDSA #endif /* Some internal helpers to determine which keys are available. */ #if (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_AES_C)) || \ (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_KEY_TYPE_AES)) #define MBEDTLS_SSL_HAVE_AES #endif #if (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_ARIA_C)) || \ (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_KEY_TYPE_ARIA)) #define MBEDTLS_SSL_HAVE_ARIA #endif #if (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_CAMELLIA_C)) || \ (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_KEY_TYPE_CAMELLIA)) #define MBEDTLS_SSL_HAVE_CAMELLIA #endif /* Some internal helpers to determine which operation modes are available. */ #if (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_CIPHER_MODE_CBC)) || \ (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_ALG_CBC_NO_PADDING)) #define MBEDTLS_SSL_HAVE_CBC #endif #if (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_GCM_C)) || \ (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_ALG_GCM)) #define MBEDTLS_SSL_HAVE_GCM #endif #if (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_CCM_C)) || \ (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_ALG_CCM)) #define MBEDTLS_SSL_HAVE_CCM #endif #if (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_CHACHAPOLY_C)) || \ (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_ALG_CHACHA20_POLY1305)) #define MBEDTLS_SSL_HAVE_CHACHAPOLY #endif #if defined(MBEDTLS_SSL_HAVE_GCM) || defined(MBEDTLS_SSL_HAVE_CCM) || \ defined(MBEDTLS_SSL_HAVE_CHACHAPOLY) #define MBEDTLS_SSL_HAVE_AEAD #endif #endif /* MBEDTLS_CONFIG_ADJUST_LEGACY_CRYPTO_H */ keyring/src/mbedtls/aes.h0000644000176200001440000006657115006370264015106 0ustar liggesusers/** * \file aes.h * * \brief This file contains AES definitions and functions. * * The Advanced Encryption Standard (AES) specifies a FIPS-approved * cryptographic algorithm that can be used to protect electronic * data. * * The AES algorithm is a symmetric block cipher that can * encrypt and decrypt information. For more information, see * FIPS Publication 197: Advanced Encryption Standard and * ISO/IEC 18033-2:2006: Information technology -- Security * techniques -- Encryption algorithms -- Part 2: Asymmetric * ciphers. * * The AES-XTS block mode is standardized by NIST SP 800-38E * * and described in detail by IEEE P1619 * . */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_AES_H #define MBEDTLS_AES_H #include "mbedtls/private_access.h" #include "mbedtls/build_info.h" #include "mbedtls/platform_util.h" #include #include /* padlock.c and aesni.c rely on these values! */ #define MBEDTLS_AES_ENCRYPT 1 /**< AES encryption. */ #define MBEDTLS_AES_DECRYPT 0 /**< AES decryption. */ /* Error codes in range 0x0020-0x0022 */ /** Invalid key length. */ #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /** Invalid data input length. */ #define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /* Error codes in range 0x0021-0x0025 */ /** Invalid input data. */ #define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021 #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_AES_ALT) // Regular implementation // /** * \brief The AES context-type definition. */ typedef struct mbedtls_aes_context { int MBEDTLS_PRIVATE(nr); /*!< The number of rounds. */ size_t MBEDTLS_PRIVATE(rk_offset); /*!< The offset in array elements to AES round keys in the buffer. */ #if defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) && !defined(MBEDTLS_PADLOCK_C) uint32_t MBEDTLS_PRIVATE(buf)[44]; /*!< Aligned data buffer to hold 10 round keys for 128-bit case. */ #else uint32_t MBEDTLS_PRIVATE(buf)[68]; /*!< Unaligned data buffer. This buffer can hold 32 extra Bytes, which can be used for one of the following purposes:
  • Alignment if VIA padlock is used.
  • Simplifying key expansion in the 256-bit case by generating an extra round key.
*/ #endif /* MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH && !MBEDTLS_PADLOCK_C */ } mbedtls_aes_context; #if defined(MBEDTLS_CIPHER_MODE_XTS) /** * \brief The AES XTS context-type definition. */ typedef struct mbedtls_aes_xts_context { mbedtls_aes_context MBEDTLS_PRIVATE(crypt); /*!< The AES context to use for AES block encryption or decryption. */ mbedtls_aes_context MBEDTLS_PRIVATE(tweak); /*!< The AES context used for tweak computation. */ } mbedtls_aes_xts_context; #endif /* MBEDTLS_CIPHER_MODE_XTS */ #else /* MBEDTLS_AES_ALT */ #include "aes_alt.h" #endif /* MBEDTLS_AES_ALT */ /** * \brief This function initializes the specified AES context. * * It must be the first API called before using * the context. * * \param ctx The AES context to initialize. This must not be \c NULL. */ void mbedtls_aes_init(mbedtls_aes_context *ctx); /** * \brief This function releases and clears the specified AES context. * * \param ctx The AES context to clear. * If this is \c NULL, this function does nothing. * Otherwise, the context must have been at least initialized. */ void mbedtls_aes_free(mbedtls_aes_context *ctx); #if defined(MBEDTLS_CIPHER_MODE_XTS) /** * \brief This function initializes the specified AES XTS context. * * It must be the first API called before using * the context. * * \param ctx The AES XTS context to initialize. This must not be \c NULL. */ void mbedtls_aes_xts_init(mbedtls_aes_xts_context *ctx); /** * \brief This function releases and clears the specified AES XTS context. * * \param ctx The AES XTS context to clear. * If this is \c NULL, this function does nothing. * Otherwise, the context must have been at least initialized. */ void mbedtls_aes_xts_free(mbedtls_aes_xts_context *ctx); #endif /* MBEDTLS_CIPHER_MODE_XTS */ /** * \brief This function sets the encryption key. * * \param ctx The AES context to which the key should be bound. * It must be initialized. * \param key The encryption key. * This must be a readable buffer of size \p keybits bits. * \param keybits The size of data passed in bits. Valid options are: *
  • 128 bits
  • *
  • 192 bits
  • *
  • 256 bits
* * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits); #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) /** * \brief This function sets the decryption key. * * \param ctx The AES context to which the key should be bound. * It must be initialized. * \param key The decryption key. * This must be a readable buffer of size \p keybits bits. * \param keybits The size of data passed. Valid options are: *
  • 128 bits
  • *
  • 192 bits
  • *
  • 256 bits
* * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits); #endif /* !MBEDTLS_BLOCK_CIPHER_NO_DECRYPT */ #if defined(MBEDTLS_CIPHER_MODE_XTS) /** * \brief This function prepares an XTS context for encryption and * sets the encryption key. * * \param ctx The AES XTS context to which the key should be bound. * It must be initialized. * \param key The encryption key. This is comprised of the XTS key1 * concatenated with the XTS key2. * This must be a readable buffer of size \p keybits bits. * \param keybits The size of \p key passed in bits. Valid options are: *
  • 256 bits (each of key1 and key2 is a 128-bit key)
  • *
  • 512 bits (each of key1 and key2 is a 256-bit key)
* * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_xts_setkey_enc(mbedtls_aes_xts_context *ctx, const unsigned char *key, unsigned int keybits); /** * \brief This function prepares an XTS context for decryption and * sets the decryption key. * * \param ctx The AES XTS context to which the key should be bound. * It must be initialized. * \param key The decryption key. This is comprised of the XTS key1 * concatenated with the XTS key2. * This must be a readable buffer of size \p keybits bits. * \param keybits The size of \p key passed in bits. Valid options are: *
  • 256 bits (each of key1 and key2 is a 128-bit key)
  • *
  • 512 bits (each of key1 and key2 is a 256-bit key)
* * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_xts_setkey_dec(mbedtls_aes_xts_context *ctx, const unsigned char *key, unsigned int keybits); #endif /* MBEDTLS_CIPHER_MODE_XTS */ /** * \brief This function performs an AES single-block encryption or * decryption operation. * * It performs the operation defined in the \p mode parameter * (encrypt or decrypt), on the input data buffer defined in * the \p input parameter. * * mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or * mbedtls_aes_setkey_dec() must be called before the first * call to this API with the same context. * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT. * \param input The buffer holding the input data. * It must be readable and at least \c 16 Bytes long. * \param output The buffer where the output data will be written. * It must be writeable and at least \c 16 Bytes long. * \return \c 0 on success. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16]); #if defined(MBEDTLS_CIPHER_MODE_CBC) /** * \brief This function performs an AES-CBC encryption or decryption operation * on full blocks. * * It performs the operation defined in the \p mode * parameter (encrypt/decrypt), on the input data buffer defined in * the \p input parameter. * * It can be called as many times as needed, until all the input * data is processed. mbedtls_aes_init(), and either * mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called * before the first call to this API with the same context. * * \note This function operates on full blocks, that is, the input size * must be a multiple of the AES block size of \c 16 Bytes. * * \note Upon exit, the content of the IV is updated so that you can * call the same function again on the next * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If you need to retain the contents of the IV, you should * either save it manually or use the cipher module instead. * * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT. * \param length The length of the input data in Bytes. This must be a * multiple of the block size (\c 16 Bytes). * \param iv Initialization vector (updated after use). * It must be a readable and writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH * on failure. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_crypt_cbc(mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output); #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_XTS) /** * \brief This function performs an AES-XTS encryption or decryption * operation for an entire XTS data unit. * * AES-XTS encrypts or decrypts blocks based on their location as * defined by a data unit number. The data unit number must be * provided by \p data_unit. * * NIST SP 800-38E limits the maximum size of a data unit to 2^20 * AES blocks. If the data unit is larger than this, this function * returns #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH. * * \param ctx The AES XTS context to use for AES XTS operations. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT. * \param length The length of a data unit in Bytes. This can be any * length between 16 bytes and 2^24 bytes inclusive * (between 1 and 2^20 block cipher blocks). * \param data_unit The address of the data unit encoded as an array of 16 * bytes in little-endian format. For disk encryption, this * is typically the index of the block device sector that * contains the data. * \param input The buffer holding the input data (which is an entire * data unit). This function reads \p length Bytes from \p * input. * \param output The buffer holding the output data (which is an entire * data unit). This function writes \p length Bytes to \p * output. * * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH if \p length is * smaller than an AES block in size (16 Bytes) or if \p * length is larger than 2^20 blocks (16 MiB). */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_crypt_xts(mbedtls_aes_xts_context *ctx, int mode, size_t length, const unsigned char data_unit[16], const unsigned char *input, unsigned char *output); #endif /* MBEDTLS_CIPHER_MODE_XTS */ #if defined(MBEDTLS_CIPHER_MODE_CFB) /** * \brief This function performs an AES-CFB128 encryption or decryption * operation. * * It performs the operation defined in the \p mode * parameter (encrypt or decrypt), on the input data buffer * defined in the \p input parameter. * * For CFB, you must set up the context with mbedtls_aes_setkey_enc(), * regardless of whether you are performing an encryption or decryption * operation, that is, regardless of the \p mode parameter. This is * because CFB mode uses the same key schedule for encryption and * decryption. * * \note Upon exit, the content of the IV is updated so that you can * call the same function again on the next * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If you need to retain the contents of the * IV, you must either save it manually or use the cipher * module instead. * * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT. * \param length The length of the input data in Bytes. * \param iv_off The offset in IV (updated after use). * It must point to a valid \c size_t. * \param iv The initialization vector (updated after use). * It must be a readable and writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_crypt_cfb128(mbedtls_aes_context *ctx, int mode, size_t length, size_t *iv_off, unsigned char iv[16], const unsigned char *input, unsigned char *output); /** * \brief This function performs an AES-CFB8 encryption or decryption * operation. * * It performs the operation defined in the \p mode * parameter (encrypt/decrypt), on the input data buffer defined * in the \p input parameter. * * Due to the nature of CFB, you must use the same key schedule for * both encryption and decryption operations. Therefore, you must * use the context initialized with mbedtls_aes_setkey_enc() for * both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. * * \note Upon exit, the content of the IV is updated so that you can * call the same function again on the next * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If you need to retain the contents of the * IV, you should either save it manually or use the cipher * module instead. * * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT * \param length The length of the input data. * \param iv The initialization vector (updated after use). * It must be a readable and writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_crypt_cfb8(mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output); #endif /*MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_OFB) /** * \brief This function performs an AES-OFB (Output Feedback Mode) * encryption or decryption operation. * * For OFB, you must set up the context with * mbedtls_aes_setkey_enc(), regardless of whether you are * performing an encryption or decryption operation. This is * because OFB mode uses the same key schedule for encryption and * decryption. * * The OFB operation is identical for encryption or decryption, * therefore no operation mode needs to be specified. * * \note Upon exit, the content of iv, the Initialisation Vector, is * updated so that you can call the same function again on the next * block(s) of data and get the same result as if it was encrypted * in one call. This allows a "streaming" usage, by initialising * iv_off to 0 before the first call, and preserving its value * between calls. * * For non-streaming use, the iv should be initialised on each call * to a unique value, and iv_off set to 0 on each call. * * If you need to retain the contents of the initialisation vector, * you must either save it manually or use the cipher module * instead. * * \warning For the OFB mode, the initialisation vector must be unique * every encryption operation. Reuse of an initialisation vector * will compromise security. * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param length The length of the input data. * \param iv_off The offset in IV (updated after use). * It must point to a valid \c size_t. * \param iv The initialization vector (updated after use). * It must be a readable and writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_crypt_ofb(mbedtls_aes_context *ctx, size_t length, size_t *iv_off, unsigned char iv[16], const unsigned char *input, unsigned char *output); #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) /** * \brief This function performs an AES-CTR encryption or decryption * operation. * * Due to the nature of CTR, you must use the same key schedule * for both encryption and decryption operations. Therefore, you * must use the context initialized with mbedtls_aes_setkey_enc() * for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. * * \warning You must never reuse a nonce value with the same key. Doing so * would void the encryption for the two messages encrypted with * the same nonce and key. * * There are two common strategies for managing nonces with CTR: * * 1. You can handle everything as a single message processed over * successive calls to this function. In that case, you want to * set \p nonce_counter and \p nc_off to 0 for the first call, and * then preserve the values of \p nonce_counter, \p nc_off and \p * stream_block across calls to this function as they will be * updated by this function. * * With this strategy, you must not encrypt more than 2**128 * blocks of data with the same key. * * 2. You can encrypt separate messages by dividing the \p * nonce_counter buffer in two areas: the first one used for a * per-message nonce, handled by yourself, and the second one * updated by this function internally. * * For example, you might reserve the first 12 bytes for the * per-message nonce, and the last 4 bytes for internal use. In that * case, before calling this function on a new message you need to * set the first 12 bytes of \p nonce_counter to your chosen nonce * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p * stream_block to be ignored). That way, you can encrypt at most * 2**96 messages of up to 2**32 blocks each with the same key. * * The per-message nonce (or information sufficient to reconstruct * it) needs to be communicated with the ciphertext and must be unique. * The recommended way to ensure uniqueness is to use a message * counter. An alternative is to generate random nonces, but this * limits the number of messages that can be securely encrypted: * for example, with 96-bit random nonces, you should not encrypt * more than 2**32 messages with the same key. * * Note that for both strategies, sizes are measured in blocks and * that an AES block is 16 bytes. * * \warning Upon return, \p stream_block contains sensitive data. Its * content must not be written to insecure storage and should be * securely discarded as soon as it's no longer needed. * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param length The length of the input data. * \param nc_off The offset in the current \p stream_block, for * resuming within the current cipher stream. The * offset pointer should be 0 at the start of a stream. * It must point to a valid \c size_t. * \param nonce_counter The 128-bit nonce and counter. * It must be a readable-writeable buffer of \c 16 Bytes. * \param stream_block The saved stream block for resuming. This is * overwritten by the function. * It must be a readable-writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_aes_crypt_ctr(mbedtls_aes_context *ctx, size_t length, size_t *nc_off, unsigned char nonce_counter[16], unsigned char stream_block[16], const unsigned char *input, unsigned char *output); #endif /* MBEDTLS_CIPHER_MODE_CTR */ /** * \brief Internal AES block encryption function. This is only * exposed to allow overriding it using * \c MBEDTLS_AES_ENCRYPT_ALT. * * \param ctx The AES context to use for encryption. * \param input The plaintext block. * \param output The output (ciphertext) block. * * \return \c 0 on success. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_internal_aes_encrypt(mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16]); #if !defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) /** * \brief Internal AES block decryption function. This is only * exposed to allow overriding it using see * \c MBEDTLS_AES_DECRYPT_ALT. * * \param ctx The AES context to use for decryption. * \param input The ciphertext block. * \param output The output (plaintext) block. * * \return \c 0 on success. */ MBEDTLS_CHECK_RETURN_TYPICAL int mbedtls_internal_aes_decrypt(mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16]); #endif /* !MBEDTLS_BLOCK_CIPHER_NO_DECRYPT */ #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ MBEDTLS_CHECK_RETURN_CRITICAL int mbedtls_aes_self_test(int verbose); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* aes.h */ keyring/src/mbedtls/platform.h0000644000176200001440000004175415006370264016156 0ustar liggesusers/** * \file platform.h * * \brief This file contains the definitions and functions of the * Mbed TLS platform abstraction layer. * * The platform abstraction layer removes the need for the library * to directly link to standard C library functions or operating * system services, making the library easier to port and embed. * Application developers and users of the library can provide their own * implementations of these functions, or implementations specific to * their platform, which can be statically linked to the library or * dynamically configured at runtime. * * When all compilation options related to platform abstraction are * disabled, this header just defines `mbedtls_xxx` function names * as aliases to the standard `xxx` function. * * Most modules in the library and example programs are expected to * include this header. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_PLATFORM_H #define MBEDTLS_PLATFORM_H #include "mbedtls/private_access.h" #include "mbedtls/build_info.h" #if defined(MBEDTLS_HAVE_TIME) #include "mbedtls/platform_time.h" #endif #ifdef __cplusplus extern "C" { #endif /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. * Either change them in mbedtls_config.h or define them on the compiler command line. * \{ */ /* The older Microsoft Windows common runtime provides non-conforming * implementations of some standard library functions, including snprintf * and vsnprintf. This affects MSVC and MinGW builds. */ #if defined(__MINGW32__) || (defined(_MSC_VER) && _MSC_VER <= 1900) #define MBEDTLS_PLATFORM_HAS_NON_CONFORMING_SNPRINTF #define MBEDTLS_PLATFORM_HAS_NON_CONFORMING_VSNPRINTF #endif #if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) #include #include #if defined(MBEDTLS_HAVE_TIME) #include #endif #if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF) #if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_SNPRINTF) #define MBEDTLS_PLATFORM_STD_SNPRINTF mbedtls_platform_win32_snprintf /**< The default \c snprintf function to use. */ #else #define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< The default \c snprintf function to use. */ #endif #endif #if !defined(MBEDTLS_PLATFORM_STD_VSNPRINTF) #if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_VSNPRINTF) #define MBEDTLS_PLATFORM_STD_VSNPRINTF mbedtls_platform_win32_vsnprintf /**< The default \c vsnprintf function to use. */ #else #define MBEDTLS_PLATFORM_STD_VSNPRINTF vsnprintf /**< The default \c vsnprintf function to use. */ #endif #endif #if !defined(MBEDTLS_PLATFORM_STD_PRINTF) #define MBEDTLS_PLATFORM_STD_PRINTF printf /**< The default \c printf function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_FPRINTF) #define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< The default \c fprintf function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_CALLOC) #define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< The default \c calloc function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_FREE) #define MBEDTLS_PLATFORM_STD_FREE free /**< The default \c free function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_SETBUF) #define MBEDTLS_PLATFORM_STD_SETBUF setbuf /**< The default \c setbuf function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_EXIT) #define MBEDTLS_PLATFORM_STD_EXIT exit /**< The default \c exit function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_TIME) #define MBEDTLS_PLATFORM_STD_TIME time /**< The default \c time function to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS) #define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS EXIT_SUCCESS /**< The default exit value to use. */ #endif #if !defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE) #define MBEDTLS_PLATFORM_STD_EXIT_FAILURE EXIT_FAILURE /**< The default exit value to use. */ #endif #if defined(MBEDTLS_FS_IO) #if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) #define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read #endif #if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) #define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write #endif #if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_FILE) #define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile" #endif #endif /* MBEDTLS_FS_IO */ #else /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */ #if defined(MBEDTLS_PLATFORM_STD_MEM_HDR) #include MBEDTLS_PLATFORM_STD_MEM_HDR #endif #endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */ /* Enable certain documented defines only when generating doxygen to avoid * an "unrecognized define" error. */ #if defined(__DOXYGEN__) && !defined(MBEDTLS_PLATFORM_STD_CALLOC) #define MBEDTLS_PLATFORM_STD_CALLOC #endif #if defined(__DOXYGEN__) && !defined(MBEDTLS_PLATFORM_STD_FREE) #define MBEDTLS_PLATFORM_STD_FREE #endif /** \} name SECTION: Module settings */ /* * The function pointers for calloc and free. * Please see MBEDTLS_PLATFORM_STD_CALLOC and MBEDTLS_PLATFORM_STD_FREE * in mbedtls_config.h for more information about behaviour and requirements. */ #if defined(MBEDTLS_PLATFORM_MEMORY) #if defined(MBEDTLS_PLATFORM_FREE_MACRO) && \ defined(MBEDTLS_PLATFORM_CALLOC_MACRO) #undef mbedtls_free #undef mbedtls_calloc #define mbedtls_free MBEDTLS_PLATFORM_FREE_MACRO #define mbedtls_calloc MBEDTLS_PLATFORM_CALLOC_MACRO #else /* For size_t */ #include extern void *mbedtls_calloc(size_t n, size_t size); extern void mbedtls_free(void *ptr); /** * \brief This function dynamically sets the memory-management * functions used by the library, during runtime. * * \param calloc_func The \c calloc function implementation. * \param free_func The \c free function implementation. * * \return \c 0. */ int mbedtls_platform_set_calloc_free(void *(*calloc_func)(size_t, size_t), void (*free_func)(void *)); #endif /* MBEDTLS_PLATFORM_FREE_MACRO && MBEDTLS_PLATFORM_CALLOC_MACRO */ #else /* !MBEDTLS_PLATFORM_MEMORY */ #undef mbedtls_free #undef mbedtls_calloc #define mbedtls_free free #define mbedtls_calloc calloc #endif /* MBEDTLS_PLATFORM_MEMORY && !MBEDTLS_PLATFORM_{FREE,CALLOC}_MACRO */ /* * The function pointers for fprintf */ #if defined(MBEDTLS_PLATFORM_FPRINTF_ALT) /* We need FILE * */ #include extern int (*mbedtls_fprintf)(FILE *stream, const char *format, ...); /** * \brief This function dynamically configures the fprintf * function that is called when the * mbedtls_fprintf() function is invoked by the library. * * \param fprintf_func The \c fprintf function implementation. * * \return \c 0. */ int mbedtls_platform_set_fprintf(int (*fprintf_func)(FILE *stream, const char *, ...)); #else #undef mbedtls_fprintf #if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) #define mbedtls_fprintf MBEDTLS_PLATFORM_FPRINTF_MACRO #else #define mbedtls_fprintf fprintf #endif /* MBEDTLS_PLATFORM_FPRINTF_MACRO */ #endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */ /* * The function pointers for printf */ #if defined(MBEDTLS_PLATFORM_PRINTF_ALT) extern int (*mbedtls_printf)(const char *format, ...); /** * \brief This function dynamically configures the snprintf * function that is called when the mbedtls_snprintf() * function is invoked by the library. * * \param printf_func The \c printf function implementation. * * \return \c 0 on success. */ int mbedtls_platform_set_printf(int (*printf_func)(const char *, ...)); #else /* !MBEDTLS_PLATFORM_PRINTF_ALT */ #undef mbedtls_printf #if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) #define mbedtls_printf MBEDTLS_PLATFORM_PRINTF_MACRO #else #define mbedtls_printf printf #endif /* MBEDTLS_PLATFORM_PRINTF_MACRO */ #endif /* MBEDTLS_PLATFORM_PRINTF_ALT */ /* * The function pointers for snprintf * * The snprintf implementation should conform to C99: * - it *must* always correctly zero-terminate the buffer * (except when n == 0, then it must leave the buffer untouched) * - however it is acceptable to return -1 instead of the required length when * the destination buffer is too short. */ #if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_SNPRINTF) /* For Windows (inc. MSYS2), we provide our own fixed implementation */ int mbedtls_platform_win32_snprintf(char *s, size_t n, const char *fmt, ...); #endif #if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) extern int (*mbedtls_snprintf)(char *s, size_t n, const char *format, ...); /** * \brief This function allows configuring a custom * \c snprintf function pointer. * * \param snprintf_func The \c snprintf function implementation. * * \return \c 0 on success. */ int mbedtls_platform_set_snprintf(int (*snprintf_func)(char *s, size_t n, const char *format, ...)); #else /* MBEDTLS_PLATFORM_SNPRINTF_ALT */ #undef mbedtls_snprintf #if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) #define mbedtls_snprintf MBEDTLS_PLATFORM_SNPRINTF_MACRO #else #define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF #endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */ #endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */ /* * The function pointers for vsnprintf * * The vsnprintf implementation should conform to C99: * - it *must* always correctly zero-terminate the buffer * (except when n == 0, then it must leave the buffer untouched) * - however it is acceptable to return -1 instead of the required length when * the destination buffer is too short. */ #if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_VSNPRINTF) #include /* For Older Windows (inc. MSYS2), we provide our own fixed implementation */ int mbedtls_platform_win32_vsnprintf(char *s, size_t n, const char *fmt, va_list arg); #endif #if defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT) #include extern int (*mbedtls_vsnprintf)(char *s, size_t n, const char *format, va_list arg); /** * \brief Set your own snprintf function pointer * * \param vsnprintf_func The \c vsnprintf function implementation * * \return \c 0 */ int mbedtls_platform_set_vsnprintf(int (*vsnprintf_func)(char *s, size_t n, const char *format, va_list arg)); #else /* MBEDTLS_PLATFORM_VSNPRINTF_ALT */ #undef mbedtls_vsnprintf #if defined(MBEDTLS_PLATFORM_VSNPRINTF_MACRO) #define mbedtls_vsnprintf MBEDTLS_PLATFORM_VSNPRINTF_MACRO #else #define mbedtls_vsnprintf vsnprintf #endif /* MBEDTLS_PLATFORM_VSNPRINTF_MACRO */ #endif /* MBEDTLS_PLATFORM_VSNPRINTF_ALT */ /* * The function pointers for setbuf */ #if defined(MBEDTLS_PLATFORM_SETBUF_ALT) #include /** * \brief Function pointer to call for `setbuf()` functionality * (changing the internal buffering on stdio calls). * * \note The library calls this function to disable * buffering when reading or writing sensitive data, * to avoid having extra copies of sensitive data * remaining in stdio buffers after the file is * closed. If this is not a concern, for example if * your platform's stdio doesn't have any buffering, * you can set mbedtls_setbuf to a function that * does nothing. * * The library always calls this function with * `buf` equal to `NULL`. */ extern void (*mbedtls_setbuf)(FILE *stream, char *buf); /** * \brief Dynamically configure the function that is called * when the mbedtls_setbuf() function is called by the * library. * * \param setbuf_func The \c setbuf function implementation * * \return \c 0 */ int mbedtls_platform_set_setbuf(void (*setbuf_func)( FILE *stream, char *buf)); #else #undef mbedtls_setbuf #if defined(MBEDTLS_PLATFORM_SETBUF_MACRO) /** * \brief Macro defining the function for the library to * call for `setbuf` functionality (changing the * internal buffering on stdio calls). * * \note See extra comments on the mbedtls_setbuf() function * pointer above. * * \return \c 0 on success, negative on error. */ #define mbedtls_setbuf MBEDTLS_PLATFORM_SETBUF_MACRO #else #define mbedtls_setbuf setbuf #endif /* MBEDTLS_PLATFORM_SETBUF_MACRO */ #endif /* MBEDTLS_PLATFORM_SETBUF_ALT */ /* * The function pointers for exit */ #if defined(MBEDTLS_PLATFORM_EXIT_ALT) extern void (*mbedtls_exit)(int status); /** * \brief This function dynamically configures the exit * function that is called when the mbedtls_exit() * function is invoked by the library. * * \param exit_func The \c exit function implementation. * * \return \c 0 on success. */ int mbedtls_platform_set_exit(void (*exit_func)(int status)); #else #undef mbedtls_exit #if defined(MBEDTLS_PLATFORM_EXIT_MACRO) #define mbedtls_exit MBEDTLS_PLATFORM_EXIT_MACRO #else #define mbedtls_exit exit #endif /* MBEDTLS_PLATFORM_EXIT_MACRO */ #endif /* MBEDTLS_PLATFORM_EXIT_ALT */ /* * The default exit values */ #if defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS) #define MBEDTLS_EXIT_SUCCESS MBEDTLS_PLATFORM_STD_EXIT_SUCCESS #else #define MBEDTLS_EXIT_SUCCESS 0 #endif #if defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE) #define MBEDTLS_EXIT_FAILURE MBEDTLS_PLATFORM_STD_EXIT_FAILURE #else #define MBEDTLS_EXIT_FAILURE 1 #endif /* * The function pointers for reading from and writing a seed file to * Non-Volatile storage (NV) in a platform-independent way * * Only enabled when the NV seed entropy source is enabled */ #if defined(MBEDTLS_ENTROPY_NV_SEED) #if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) && defined(MBEDTLS_FS_IO) /* Internal standard platform definitions */ int mbedtls_platform_std_nv_seed_read(unsigned char *buf, size_t buf_len); int mbedtls_platform_std_nv_seed_write(unsigned char *buf, size_t buf_len); #endif #if defined(MBEDTLS_PLATFORM_NV_SEED_ALT) extern int (*mbedtls_nv_seed_read)(unsigned char *buf, size_t buf_len); extern int (*mbedtls_nv_seed_write)(unsigned char *buf, size_t buf_len); /** * \brief This function allows configuring custom seed file writing and * reading functions. * * \param nv_seed_read_func The seed reading function implementation. * \param nv_seed_write_func The seed writing function implementation. * * \return \c 0 on success. */ int mbedtls_platform_set_nv_seed( int (*nv_seed_read_func)(unsigned char *buf, size_t buf_len), int (*nv_seed_write_func)(unsigned char *buf, size_t buf_len) ); #else #undef mbedtls_nv_seed_read #undef mbedtls_nv_seed_write #if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) && \ defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO) #define mbedtls_nv_seed_read MBEDTLS_PLATFORM_NV_SEED_READ_MACRO #define mbedtls_nv_seed_write MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO #else #define mbedtls_nv_seed_read mbedtls_platform_std_nv_seed_read #define mbedtls_nv_seed_write mbedtls_platform_std_nv_seed_write #endif #endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */ #endif /* MBEDTLS_ENTROPY_NV_SEED */ #if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT) /** * \brief The platform context structure. * * \note This structure may be used to assist platform-specific * setup or teardown operations. */ typedef struct mbedtls_platform_context { char MBEDTLS_PRIVATE(dummy); /**< A placeholder member, as empty structs are not portable. */ } mbedtls_platform_context; #else #include "platform_alt.h" #endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */ /** * \brief This function performs any platform-specific initialization * operations. * * \note This function should be called before any other library functions. * * Its implementation is platform-specific, and unless * platform-specific code is provided, it does nothing. * * \note The usage and necessity of this function is dependent on the platform. * * \param ctx The platform context. * * \return \c 0 on success. */ int mbedtls_platform_setup(mbedtls_platform_context *ctx); /** * \brief This function performs any platform teardown operations. * * \note This function should be called after every other Mbed TLS module * has been correctly freed using the appropriate free function. * * Its implementation is platform-specific, and unless * platform-specific code is provided, it does nothing. * * \note The usage and necessity of this function is dependent on the platform. * * \param ctx The platform context. * */ void mbedtls_platform_teardown(mbedtls_platform_context *ctx); #ifdef __cplusplus } #endif #endif /* platform.h */ keyring/src/mbedtls/platform_util.h0000644000176200001440000001750215006370264017205 0ustar liggesusers/** * \file platform_util.h * * \brief Common and shared functions used by multiple modules in the Mbed TLS * library. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_PLATFORM_UTIL_H #define MBEDTLS_PLATFORM_UTIL_H #include "mbedtls/build_info.h" #include #if defined(MBEDTLS_HAVE_TIME_DATE) #include "mbedtls/platform_time.h" #include #endif /* MBEDTLS_HAVE_TIME_DATE */ #ifdef __cplusplus extern "C" { #endif /* Internal helper macros for deprecating API constants. */ #if !defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) #define MBEDTLS_DEPRECATED __attribute__((deprecated)) MBEDTLS_DEPRECATED typedef char const *mbedtls_deprecated_string_constant_t; #define MBEDTLS_DEPRECATED_STRING_CONSTANT(VAL) \ ((mbedtls_deprecated_string_constant_t) (VAL)) MBEDTLS_DEPRECATED typedef int mbedtls_deprecated_numeric_constant_t; #define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT(VAL) \ ((mbedtls_deprecated_numeric_constant_t) (VAL)) #else /* MBEDTLS_DEPRECATED_WARNING */ #define MBEDTLS_DEPRECATED #define MBEDTLS_DEPRECATED_STRING_CONSTANT(VAL) VAL #define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT(VAL) VAL #endif /* MBEDTLS_DEPRECATED_WARNING */ #endif /* MBEDTLS_DEPRECATED_REMOVED */ /* Implementation of the check-return facility. * See the user documentation in mbedtls_config.h. * * Do not use this macro directly to annotate function: instead, * use one of MBEDTLS_CHECK_RETURN_CRITICAL or MBEDTLS_CHECK_RETURN_TYPICAL * depending on how important it is to check the return value. */ #if !defined(MBEDTLS_CHECK_RETURN) #if defined(__GNUC__) #define MBEDTLS_CHECK_RETURN __attribute__((__warn_unused_result__)) #elif defined(_MSC_VER) && _MSC_VER >= 1700 #include #define MBEDTLS_CHECK_RETURN _Check_return_ #else #define MBEDTLS_CHECK_RETURN #endif #endif /** Critical-failure function * * This macro appearing at the beginning of the declaration of a function * indicates that its return value should be checked in all applications. * Omitting the check is very likely to indicate a bug in the application * and will result in a compile-time warning if #MBEDTLS_CHECK_RETURN * is implemented for the compiler in use. * * \note The use of this macro is a work in progress. * This macro may be added to more functions in the future. * Such an extension is not considered an API break, provided that * there are near-unavoidable circumstances under which the function * can fail. For example, signature/MAC/AEAD verification functions, * and functions that require a random generator, are considered * return-check-critical. */ #define MBEDTLS_CHECK_RETURN_CRITICAL MBEDTLS_CHECK_RETURN /** Ordinary-failure function * * This macro appearing at the beginning of the declaration of a function * indicates that its return value should be generally be checked in portable * applications. Omitting the check will result in a compile-time warning if * #MBEDTLS_CHECK_RETURN is implemented for the compiler in use and * #MBEDTLS_CHECK_RETURN_WARNING is enabled in the compile-time configuration. * * You can use #MBEDTLS_IGNORE_RETURN to explicitly ignore the return value * of a function that is annotated with #MBEDTLS_CHECK_RETURN. * * \note The use of this macro is a work in progress. * This macro will be added to more functions in the future. * Eventually this should appear before most functions returning * an error code (as \c int in the \c mbedtls_xxx API or * as ::psa_status_t in the \c psa_xxx API). */ #if defined(MBEDTLS_CHECK_RETURN_WARNING) #define MBEDTLS_CHECK_RETURN_TYPICAL MBEDTLS_CHECK_RETURN #else #define MBEDTLS_CHECK_RETURN_TYPICAL #endif /** Benign-failure function * * This macro appearing at the beginning of the declaration of a function * indicates that it is rarely useful to check its return value. * * This macro has an empty expansion. It exists for documentation purposes: * a #MBEDTLS_CHECK_RETURN_OPTIONAL annotation indicates that the function * has been analyzed for return-check usefulness, whereas the lack of * an annotation indicates that the function has not been analyzed and its * return-check usefulness is unknown. */ #define MBEDTLS_CHECK_RETURN_OPTIONAL /** \def MBEDTLS_IGNORE_RETURN * * Call this macro with one argument, a function call, to suppress a warning * from #MBEDTLS_CHECK_RETURN due to that function call. */ #if !defined(MBEDTLS_IGNORE_RETURN) /* GCC doesn't silence the warning with just (void)(result). * (void)!(result) is known to work up at least up to GCC 10, as well * as with Clang and MSVC. * * https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Non_002dbugs.html * https://stackoverflow.com/questions/40576003/ignoring-warning-wunused-result * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425#c34 */ #define MBEDTLS_IGNORE_RETURN(result) ((void) !(result)) #endif /* If the following macro is defined, the library is being built by the test * framework, and the framework is going to provide a replacement * mbedtls_platform_zeroize() using a preprocessor macro, so the function * declaration should be omitted. */ #if !defined(MBEDTLS_TEST_DEFINES_ZEROIZE) //no-check-names /** * \brief Securely zeroize a buffer * * The function is meant to wipe the data contained in a buffer so * that it can no longer be recovered even if the program memory * is later compromised. Call this function on sensitive data * stored on the stack before returning from a function, and on * sensitive data stored on the heap before freeing the heap * object. * * It is extremely difficult to guarantee that calls to * mbedtls_platform_zeroize() are not removed by aggressive * compiler optimizations in a portable way. For this reason, Mbed * TLS provides the configuration option * MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure * mbedtls_platform_zeroize() to use a suitable implementation for * their platform and needs * * \param buf Buffer to be zeroized * \param len Length of the buffer in bytes * */ void mbedtls_platform_zeroize(void *buf, size_t len); #endif #if defined(MBEDTLS_HAVE_TIME_DATE) /** * \brief Platform-specific implementation of gmtime_r() * * The function is a thread-safe abstraction that behaves * similarly to the gmtime_r() function from Unix/POSIX. * * Mbed TLS will try to identify the underlying platform and * make use of an appropriate underlying implementation (e.g. * gmtime_r() for POSIX and gmtime_s() for Windows). If this is * not possible, then gmtime() will be used. In this case, calls * from the library to gmtime() will be guarded by the mutex * mbedtls_threading_gmtime_mutex if MBEDTLS_THREADING_C is * enabled. It is recommended that calls from outside the library * are also guarded by this mutex. * * If MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, then Mbed TLS will * unconditionally use the alternative implementation for * mbedtls_platform_gmtime_r() supplied by the user at compile time. * * \param tt Pointer to an object containing time (in seconds) since the * epoch to be converted * \param tm_buf Pointer to an object where the results will be stored * * \return Pointer to an object of type struct tm on success, otherwise * NULL */ struct tm *mbedtls_platform_gmtime_r(const mbedtls_time_t *tt, struct tm *tm_buf); #endif /* MBEDTLS_HAVE_TIME_DATE */ #ifdef __cplusplus } #endif #endif /* MBEDTLS_PLATFORM_UTIL_H */ keyring/src/mbedtls/build_info.h0000644000176200001440000001402315006370264016431 0ustar liggesusers/** * \file mbedtls/build_info.h * * \brief Build-time configuration info * * Include this file if you need to depend on the * configuration options defined in mbedtls_config.h or MBEDTLS_CONFIG_FILE */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_BUILD_INFO_H #define MBEDTLS_BUILD_INFO_H /* * This set of compile-time defines can be used to determine the version number * of the Mbed TLS library used. Run-time variables for the same can be found in * version.h */ /** * The version number x.y.z is split into three parts. * Major, Minor, Patchlevel */ #define MBEDTLS_VERSION_MAJOR 3 #define MBEDTLS_VERSION_MINOR 6 #define MBEDTLS_VERSION_PATCH 3 /** * The single version number has the following structure: * MMNNPP00 * Major version | Minor version | Patch version */ #define MBEDTLS_VERSION_NUMBER 0x03060300 #define MBEDTLS_VERSION_STRING "3.6.3" #define MBEDTLS_VERSION_STRING_FULL "Mbed TLS 3.6.3" /* Macros for build-time platform detection */ #if !defined(MBEDTLS_ARCH_IS_ARM64) && \ (defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC)) #define MBEDTLS_ARCH_IS_ARM64 #endif #if !defined(MBEDTLS_ARCH_IS_ARM32) && \ (defined(__arm__) || defined(_M_ARM) || \ defined(_M_ARMT) || defined(__thumb__) || defined(__thumb2__)) #define MBEDTLS_ARCH_IS_ARM32 #endif #if !defined(MBEDTLS_ARCH_IS_X64) && \ (defined(__amd64__) || defined(__x86_64__) || \ ((defined(_M_X64) || defined(_M_AMD64)) && !defined(_M_ARM64EC))) #define MBEDTLS_ARCH_IS_X64 #endif #if !defined(MBEDTLS_ARCH_IS_X86) && \ (defined(__i386__) || defined(_X86_) || \ (defined(_M_IX86) && !defined(_M_I86))) #define MBEDTLS_ARCH_IS_X86 #endif #if !defined(MBEDTLS_PLATFORM_IS_WINDOWS_ON_ARM64) && \ (defined(_M_ARM64) || defined(_M_ARM64EC)) #define MBEDTLS_PLATFORM_IS_WINDOWS_ON_ARM64 #endif /* This is defined if the architecture is Armv8-A, or higher */ #if !defined(MBEDTLS_ARCH_IS_ARMV8_A) #if defined(__ARM_ARCH) && defined(__ARM_ARCH_PROFILE) #if (__ARM_ARCH >= 8) && (__ARM_ARCH_PROFILE == 'A') /* GCC, clang, armclang and IAR */ #define MBEDTLS_ARCH_IS_ARMV8_A #endif #elif defined(__ARM_ARCH_8A) /* Alternative defined by clang */ #define MBEDTLS_ARCH_IS_ARMV8_A #elif defined(_M_ARM64) || defined(_M_ARM64EC) /* MSVC ARM64 is at least Armv8.0-A */ #define MBEDTLS_ARCH_IS_ARMV8_A #endif #endif #if defined(__GNUC__) && !defined(__ARMCC_VERSION) && !defined(__clang__) \ && !defined(__llvm__) && !defined(__INTEL_COMPILER) /* Defined if the compiler really is gcc and not clang, etc */ #define MBEDTLS_COMPILER_IS_GCC #define MBEDTLS_GCC_VERSION \ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #endif #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE) #define _CRT_SECURE_NO_DEPRECATE 1 #endif /* Define `inline` on some non-C99-compliant compilers. */ #if (defined(__ARMCC_VERSION) || defined(_MSC_VER)) && \ !defined(inline) && !defined(__cplusplus) #define inline __inline #endif #if defined(MBEDTLS_CONFIG_FILES_READ) #error "Something went wrong: MBEDTLS_CONFIG_FILES_READ defined before reading the config files!" #endif #if defined(MBEDTLS_CONFIG_IS_FINALIZED) #error "Something went wrong: MBEDTLS_CONFIG_IS_FINALIZED defined before reading the config files!" #endif /* X.509, TLS and non-PSA crypto configuration */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/mbedtls_config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_CONFIG_VERSION) && ( \ MBEDTLS_CONFIG_VERSION < 0x03000000 || \ MBEDTLS_CONFIG_VERSION > MBEDTLS_VERSION_NUMBER) #error "Invalid config version, defined value of MBEDTLS_CONFIG_VERSION is unsupported" #endif /* Target and application specific configurations * * Allow user to override any previous default. * */ #if defined(MBEDTLS_USER_CONFIG_FILE) #include MBEDTLS_USER_CONFIG_FILE #endif /* PSA crypto configuration */ #if defined(MBEDTLS_PSA_CRYPTO_CONFIG) #if defined(MBEDTLS_PSA_CRYPTO_CONFIG_FILE) #include MBEDTLS_PSA_CRYPTO_CONFIG_FILE #else #include "psa/crypto_config.h" #endif #if defined(MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE) #include MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE #endif #endif /* defined(MBEDTLS_PSA_CRYPTO_CONFIG) */ /* Indicate that all configuration files have been read. * It is now time to adjust the configuration (follow through on dependencies, * make PSA and legacy crypto consistent, etc.). */ #define MBEDTLS_CONFIG_FILES_READ /* Auto-enable MBEDTLS_CTR_DRBG_USE_128_BIT_KEY if * MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH and MBEDTLS_CTR_DRBG_C defined * to ensure a 128-bit key size in CTR_DRBG. */ #if defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) && defined(MBEDTLS_CTR_DRBG_C) #define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY #endif /* Auto-enable MBEDTLS_MD_C if needed by a module that didn't require it * in a previous release, to ensure backwards compatibility. */ #if defined(MBEDTLS_PKCS5_C) #define MBEDTLS_MD_C #endif /* PSA crypto specific configuration options * - If config_psa.h reads a configuration option in preprocessor directive, * this symbol should be set before its inclusion. (e.g. MBEDTLS_MD_C) * - If config_psa.h writes a configuration option in conditional directive, * this symbol should be consulted after its inclusion. * (e.g. MBEDTLS_MD_LIGHT) */ #if defined(MBEDTLS_PSA_CRYPTO_CONFIG) /* PSA_WANT_xxx influences MBEDTLS_xxx */ || \ defined(MBEDTLS_PSA_CRYPTO_C) /* MBEDTLS_xxx influences PSA_WANT_xxx */ || \ defined(MBEDTLS_PSA_CRYPTO_CLIENT) /* The same as the previous, but with separation only */ #include "mbedtls/config_psa.h" #endif #include "mbedtls/config_adjust_legacy_crypto.h" #include "mbedtls/config_adjust_x509.h" #include "mbedtls/config_adjust_ssl.h" /* Indicate that all configuration symbols are set, * even the ones that are calculated programmatically. * It is now safe to query the configuration (to check it, to size buffers, * etc.). */ #define MBEDTLS_CONFIG_IS_FINALIZED #include "mbedtls/check_config.h" #endif /* MBEDTLS_BUILD_INFO_H */ keyring/src/mbedtls/config_psa.h0000644000176200001440000000357415006370264016440 0ustar liggesusers/** * \file mbedtls/config_psa.h * \brief PSA crypto configuration options (set of defines) * * This set of compile-time options takes settings defined in * include/mbedtls/mbedtls_config.h and include/psa/crypto_config.h and uses * those definitions to define symbols used in the library code. * * Users and integrators should not edit this file, please edit * include/mbedtls/mbedtls_config.h for MBEDTLS_XXX settings or * include/psa/crypto_config.h for PSA_WANT_XXX settings. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_CONFIG_PSA_H #define MBEDTLS_CONFIG_PSA_H #include "psa/crypto_legacy.h" #include "psa/crypto_adjust_config_synonyms.h" #include "psa/crypto_adjust_config_dependencies.h" #include "mbedtls/config_adjust_psa_superset_legacy.h" #if defined(MBEDTLS_PSA_CRYPTO_CONFIG) /* Require built-in implementations based on PSA requirements */ /* We need this to have a complete list of requirements * before we deduce what built-ins are required. */ #include "psa/crypto_adjust_config_key_pair_types.h" #if defined(MBEDTLS_PSA_CRYPTO_C) /* If we are implementing PSA crypto ourselves, then we want to enable the * required built-ins. Otherwise, PSA features will be provided by the server. */ #include "mbedtls/config_adjust_legacy_from_psa.h" #endif #else /* MBEDTLS_PSA_CRYPTO_CONFIG */ /* Infer PSA requirements from Mbed TLS capabilities */ #include "mbedtls/config_adjust_psa_from_legacy.h" /* Hopefully the file above will have enabled keypair symbols in a consistent * way, but including this here fixes them if that wasn't the case. */ #include "psa/crypto_adjust_config_key_pair_types.h" #endif /* MBEDTLS_PSA_CRYPTO_CONFIG */ #if defined(PSA_WANT_ALG_JPAKE) #define PSA_WANT_ALG_SOME_PAKE 1 #endif #include "psa/crypto_adjust_auto_enabled.h" #endif /* MBEDTLS_CONFIG_PSA_H */ keyring/src/mbedtls/error.h0000644000176200001440000001461715006370264015461 0ustar liggesusers/** * \file error.h * * \brief Error to string translation */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_ERROR_H #define MBEDTLS_ERROR_H #include "mbedtls/build_info.h" #include /** * Error code layout. * * Currently we try to keep all error codes within the negative space of 16 * bits signed integers to support all platforms (-0x0001 - -0x7FFF). In * addition we'd like to give two layers of information on the error if * possible. * * For that purpose the error codes are segmented in the following manner: * * 16 bit error code bit-segmentation * * 1 bit - Unused (sign bit) * 3 bits - High level module ID * 5 bits - Module-dependent error code * 7 bits - Low level module errors * * For historical reasons, low-level error codes are divided in even and odd, * even codes were assigned first, and -1 is reserved for other errors. * * Low-level module errors (0x0002-0x007E, 0x0001-0x007F) * * Module Nr Codes assigned * ERROR 2 0x006E 0x0001 * MPI 7 0x0002-0x0010 * GCM 3 0x0012-0x0016 0x0013-0x0013 * THREADING 3 0x001A-0x001E * AES 5 0x0020-0x0022 0x0021-0x0025 * CAMELLIA 3 0x0024-0x0026 0x0027-0x0027 * BASE64 2 0x002A-0x002C * OID 1 0x002E-0x002E 0x000B-0x000B * PADLOCK 1 0x0030-0x0030 * DES 2 0x0032-0x0032 0x0033-0x0033 * CTR_DBRG 4 0x0034-0x003A * ENTROPY 3 0x003C-0x0040 0x003D-0x003F * NET 13 0x0042-0x0052 0x0043-0x0049 * ARIA 4 0x0058-0x005E * ASN1 7 0x0060-0x006C * CMAC 1 0x007A-0x007A * PBKDF2 1 0x007C-0x007C * HMAC_DRBG 4 0x0003-0x0009 * CCM 3 0x000D-0x0011 * MD5 1 0x002F-0x002F * RIPEMD160 1 0x0031-0x0031 * SHA1 1 0x0035-0x0035 0x0073-0x0073 * SHA256 1 0x0037-0x0037 0x0074-0x0074 * SHA512 1 0x0039-0x0039 0x0075-0x0075 * SHA-3 1 0x0076-0x0076 * CHACHA20 3 0x0051-0x0055 * POLY1305 3 0x0057-0x005B * CHACHAPOLY 2 0x0054-0x0056 * PLATFORM 2 0x0070-0x0072 * LMS 5 0x0011-0x0019 * * High-level module nr (3 bits - 0x0...-0x7...) * Name ID Nr of Errors * PEM 1 9 * PKCS#12 1 4 (Started from top) * X509 2 20 * PKCS5 2 4 (Started from top) * DHM 3 11 * PK 3 15 (Started from top) * RSA 4 11 * ECP 4 10 (Started from top) * MD 5 5 * HKDF 5 1 (Started from top) * PKCS7 5 12 (Started from 0x5300) * SSL 5 3 (Started from 0x5F00) * CIPHER 6 8 (Started from 0x6080) * SSL 6 22 (Started from top, plus 0x6000) * SSL 7 20 (Started from 0x7000, gaps at * 0x7380, 0x7900-0x7980, 0x7A80-0x7E80) * * Module dependent error code (5 bits 0x.00.-0x.F8.) */ #ifdef __cplusplus extern "C" { #endif /** Generic error */ #define MBEDTLS_ERR_ERROR_GENERIC_ERROR -0x0001 /** This is a bug in the library */ #define MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED -0x006E /** Hardware accelerator failed */ #define MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED -0x0070 /** The requested feature is not supported by the platform */ #define MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED -0x0072 /** * \brief Combines a high-level and low-level error code together. * * Wrapper macro for mbedtls_error_add(). See that function for * more details. */ #define MBEDTLS_ERROR_ADD(high, low) \ mbedtls_error_add(high, low, __FILE__, __LINE__) #if defined(MBEDTLS_TEST_HOOKS) /** * \brief Testing hook called before adding/combining two error codes together. * Only used when invasive testing is enabled via MBEDTLS_TEST_HOOKS. */ extern void (*mbedtls_test_hook_error_add)(int, int, const char *, int); #endif /** * \brief Combines a high-level and low-level error code together. * * This function can be called directly however it is usually * called via the #MBEDTLS_ERROR_ADD macro. * * While a value of zero is not a negative error code, it is still an * error code (that denotes success) and can be combined with both a * negative error code or another value of zero. * * \note When invasive testing is enabled via #MBEDTLS_TEST_HOOKS, also try to * call \link mbedtls_test_hook_error_add \endlink. * * \param high high-level error code. See error.h for more details. * \param low low-level error code. See error.h for more details. * \param file file where this error code addition occurred. * \param line line where this error code addition occurred. */ static inline int mbedtls_error_add(int high, int low, const char *file, int line) { #if defined(MBEDTLS_TEST_HOOKS) if (*mbedtls_test_hook_error_add != NULL) { (*mbedtls_test_hook_error_add)(high, low, file, line); } #endif (void) file; (void) line; return high + low; } /** * \brief Translate an Mbed TLS error code into a string representation. * The result is truncated if necessary and always includes a * terminating null byte. * * \param errnum error code * \param buffer buffer to place representation in * \param buflen length of the buffer */ void mbedtls_strerror(int errnum, char *buffer, size_t buflen); /** * \brief Translate the high-level part of an Mbed TLS error code into a string * representation. * * This function returns a const pointer to an un-modifiable string. The caller * must not try to modify the string. It is intended to be used mostly for * logging purposes. * * \param error_code error code * * \return The string representation of the error code, or \c NULL if the error * code is unknown. */ const char *mbedtls_high_level_strerr(int error_code); /** * \brief Translate the low-level part of an Mbed TLS error code into a string * representation. * * This function returns a const pointer to an un-modifiable string. The caller * must not try to modify the string. It is intended to be used mostly for * logging purposes. * * \param error_code error code * * \return The string representation of the error code, or \c NULL if the error * code is unknown. */ const char *mbedtls_low_level_strerr(int error_code); #ifdef __cplusplus } #endif #endif /* error.h */ keyring/src/mbedtls/config_adjust_ssl.h0000644000176200001440000000653115006370264020024 0ustar liggesusers/** * \file mbedtls/config_adjust_ssl.h * \brief Adjust TLS configuration * * This is an internal header. Do not include it directly. * * Automatically enable certain dependencies. Generally, MBEDTLS_xxx * configurations need to be explicitly enabled by the user: enabling * MBEDTLS_xxx_A but not MBEDTLS_xxx_B when A requires B results in a * compilation error. However, we do automatically enable certain options * in some circumstances. One case is if MBEDTLS_xxx_B is an internal option * used to identify parts of a module that are used by other module, and we * don't want to make the symbol MBEDTLS_xxx_B part of the public API. * Another case is if A didn't depend on B in earlier versions, and we * want to use B in A but we need to preserve backward compatibility with * configurations that explicitly activate MBEDTLS_xxx_A but not * MBEDTLS_xxx_B. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_CONFIG_ADJUST_SSL_H #define MBEDTLS_CONFIG_ADJUST_SSL_H #if !defined(MBEDTLS_CONFIG_FILES_READ) #error "Do not include mbedtls/config_adjust_*.h manually! This can lead to problems, " \ "up to and including runtime errors such as buffer overflows. " \ "If you're trying to fix a complaint from check_config.h, just remove " \ "it from your configuration file: since Mbed TLS 3.0, it is included " \ "automatically at the right point." #endif /* */ /* The following blocks make it easier to disable all of TLS, * or of TLS 1.2 or 1.3 or DTLS, without having to manually disable all * key exchanges, options and extensions related to them. */ #if !defined(MBEDTLS_SSL_TLS_C) #undef MBEDTLS_SSL_CLI_C #undef MBEDTLS_SSL_SRV_C #undef MBEDTLS_SSL_PROTO_TLS1_3 #undef MBEDTLS_SSL_PROTO_TLS1_2 #undef MBEDTLS_SSL_PROTO_DTLS #endif #if !(defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SESSION_TICKETS)) #undef MBEDTLS_SSL_TICKET_C #endif #if !defined(MBEDTLS_SSL_PROTO_DTLS) #undef MBEDTLS_SSL_DTLS_ANTI_REPLAY #undef MBEDTLS_SSL_DTLS_CONNECTION_ID #undef MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT #undef MBEDTLS_SSL_DTLS_HELLO_VERIFY #undef MBEDTLS_SSL_DTLS_SRTP #undef MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE #endif #if !defined(MBEDTLS_SSL_PROTO_TLS1_2) #undef MBEDTLS_SSL_ENCRYPT_THEN_MAC #undef MBEDTLS_SSL_EXTENDED_MASTER_SECRET #undef MBEDTLS_SSL_RENEGOTIATION #undef MBEDTLS_KEY_EXCHANGE_RSA_ENABLED #undef MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED #undef MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED #undef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED #undef MBEDTLS_KEY_EXCHANGE_PSK_ENABLED #undef MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED #undef MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED #undef MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED #undef MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED #undef MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED #undef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED #endif #if !defined(MBEDTLS_SSL_PROTO_TLS1_3) #undef MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED #undef MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED #undef MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED #undef MBEDTLS_SSL_EARLY_DATA #undef MBEDTLS_SSL_RECORD_SIZE_LIMIT #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ (defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)) #define MBEDTLS_SSL_TLS1_2_SOME_ECC #endif #endif /* MBEDTLS_CONFIG_ADJUST_SSL_H */ keyring/src/mbedtls/mbedtls_config.h0000644000176200001440000046017515006370264017313 0ustar liggesusers/** * \file mbedtls_config.h * * \brief Configuration options (set of defines) * * This set of compile-time options may be used to enable * or disable features selectively, and reduce the global * memory footprint. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ /** * This is an optional version symbol that enables compatibility handling of * config files. * * It is equal to the #MBEDTLS_VERSION_NUMBER of the Mbed TLS version that * introduced the config format we want to be compatible with. */ //#define MBEDTLS_CONFIG_VERSION 0x03000000 /** * \name SECTION: System support * * This section sets system specific settings. * \{ */ /** * \def MBEDTLS_HAVE_ASM * * The compiler has support for asm(). * * Requires support for asm() in compiler. * * Used in: * library/aesni.h * library/aria.c * library/bn_mul.h * library/constant_time.c * library/padlock.h * * Required by: * MBEDTLS_AESCE_C * MBEDTLS_AESNI_C (on some platforms) * MBEDTLS_PADLOCK_C * * Comment to disable the use of assembly code. */ #define MBEDTLS_HAVE_ASM /** * \def MBEDTLS_NO_UDBL_DIVISION * * The platform lacks support for double-width integer division (64-bit * division on a 32-bit platform, 128-bit division on a 64-bit platform). * * Used in: * include/mbedtls/bignum.h * library/bignum.c * * The bignum code uses double-width division to speed up some operations. * Double-width division is often implemented in software that needs to * be linked with the program. The presence of a double-width integer * type is usually detected automatically through preprocessor macros, * but the automatic detection cannot know whether the code needs to * and can be linked with an implementation of division for that type. * By default division is assumed to be usable if the type is present. * Uncomment this option to prevent the use of double-width division. * * Note that division for the native integer type is always required. * Furthermore, a 64-bit type is always required even on a 32-bit * platform, but it need not support multiplication or division. In some * cases it is also desirable to disable some double-width operations. For * example, if double-width division is implemented in software, disabling * it can reduce code size in some embedded targets. */ //#define MBEDTLS_NO_UDBL_DIVISION /** * \def MBEDTLS_NO_64BIT_MULTIPLICATION * * The platform lacks support for 32x32 -> 64-bit multiplication. * * Used in: * library/poly1305.c * * Some parts of the library may use multiplication of two unsigned 32-bit * operands with a 64-bit result in order to speed up computations. On some * platforms, this is not available in hardware and has to be implemented in * software, usually in a library provided by the toolchain. * * Sometimes it is not desirable to have to link to that library. This option * removes the dependency of that library on platforms that lack a hardware * 64-bit multiplier by embedding a software implementation in Mbed TLS. * * Note that depending on the compiler, this may decrease performance compared * to using the library function provided by the toolchain. */ //#define MBEDTLS_NO_64BIT_MULTIPLICATION /** * \def MBEDTLS_HAVE_SSE2 * * CPU supports SSE2 instruction set. * * Uncomment if the CPU supports SSE2 (IA-32 specific). */ //#define MBEDTLS_HAVE_SSE2 /** * \def MBEDTLS_HAVE_TIME * * System has time.h and time(). * The time does not need to be correct, only time differences are used, * by contrast with MBEDTLS_HAVE_TIME_DATE * * Defining MBEDTLS_HAVE_TIME allows you to specify MBEDTLS_PLATFORM_TIME_ALT, * MBEDTLS_PLATFORM_TIME_MACRO, MBEDTLS_PLATFORM_TIME_TYPE_MACRO and * MBEDTLS_PLATFORM_STD_TIME. * * Comment if your system does not support time functions. * * \note If MBEDTLS_TIMING_C is set - to enable the semi-portable timing * interface - timing.c will include time.h on suitable platforms * regardless of the setting of MBEDTLS_HAVE_TIME, unless * MBEDTLS_TIMING_ALT is used. See timing.c for more information. */ #define MBEDTLS_HAVE_TIME /** * \def MBEDTLS_HAVE_TIME_DATE * * System has time.h, time(), and an implementation for * mbedtls_platform_gmtime_r() (see below). * The time needs to be correct (not necessarily very accurate, but at least * the date should be correct). This is used to verify the validity period of * X.509 certificates. * * Comment if your system does not have a correct clock. * * \note mbedtls_platform_gmtime_r() is an abstraction in platform_util.h that * behaves similarly to the gmtime_r() function from the C standard. Refer to * the documentation for mbedtls_platform_gmtime_r() for more information. * * \note It is possible to configure an implementation for * mbedtls_platform_gmtime_r() at compile-time by using the macro * MBEDTLS_PLATFORM_GMTIME_R_ALT. */ #define MBEDTLS_HAVE_TIME_DATE /** * \def MBEDTLS_PLATFORM_MEMORY * * Enable the memory allocation layer. * * By default Mbed TLS uses the system-provided calloc() and free(). * This allows different allocators (self-implemented or provided) to be * provided to the platform abstraction layer. * * Enabling #MBEDTLS_PLATFORM_MEMORY without the * MBEDTLS_PLATFORM_{FREE,CALLOC}_MACROs will provide * "mbedtls_platform_set_calloc_free()" allowing you to set an alternative calloc() and * free() function pointer at runtime. * * Enabling #MBEDTLS_PLATFORM_MEMORY and specifying * MBEDTLS_PLATFORM_{CALLOC,FREE}_MACROs will allow you to specify the * alternate function at compile time. * * An overview of how the value of mbedtls_calloc is determined: * * - if !MBEDTLS_PLATFORM_MEMORY * - mbedtls_calloc = calloc * - if MBEDTLS_PLATFORM_MEMORY * - if (MBEDTLS_PLATFORM_CALLOC_MACRO && MBEDTLS_PLATFORM_FREE_MACRO): * - mbedtls_calloc = MBEDTLS_PLATFORM_CALLOC_MACRO * - if !(MBEDTLS_PLATFORM_CALLOC_MACRO && MBEDTLS_PLATFORM_FREE_MACRO): * - Dynamic setup via mbedtls_platform_set_calloc_free is now possible with a default value MBEDTLS_PLATFORM_STD_CALLOC. * - How is MBEDTLS_PLATFORM_STD_CALLOC handled? * - if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS: * - MBEDTLS_PLATFORM_STD_CALLOC is not set to anything; * - MBEDTLS_PLATFORM_STD_MEM_HDR can be included if present; * - if !MBEDTLS_PLATFORM_NO_STD_FUNCTIONS: * - if MBEDTLS_PLATFORM_STD_CALLOC is present: * - User-defined MBEDTLS_PLATFORM_STD_CALLOC is respected; * - if !MBEDTLS_PLATFORM_STD_CALLOC: * - MBEDTLS_PLATFORM_STD_CALLOC = calloc * * - At this point the presence of MBEDTLS_PLATFORM_STD_CALLOC is checked. * - if !MBEDTLS_PLATFORM_STD_CALLOC * - MBEDTLS_PLATFORM_STD_CALLOC = uninitialized_calloc * * - mbedtls_calloc = MBEDTLS_PLATFORM_STD_CALLOC. * * Defining MBEDTLS_PLATFORM_CALLOC_MACRO and #MBEDTLS_PLATFORM_STD_CALLOC at the same time is not possible. * MBEDTLS_PLATFORM_CALLOC_MACRO and MBEDTLS_PLATFORM_FREE_MACRO must both be defined or undefined at the same time. * #MBEDTLS_PLATFORM_STD_CALLOC and #MBEDTLS_PLATFORM_STD_FREE do not have to be defined at the same time, as, if they are used, * dynamic setup of these functions is possible. See the tree above to see how are they handled in all cases. * An uninitialized #MBEDTLS_PLATFORM_STD_CALLOC always fails, returning a null pointer. * An uninitialized #MBEDTLS_PLATFORM_STD_FREE does not do anything. * * Requires: MBEDTLS_PLATFORM_C * * Enable this layer to allow use of alternative memory allocators. */ //#define MBEDTLS_PLATFORM_MEMORY /** * \def MBEDTLS_PLATFORM_NO_STD_FUNCTIONS * * Do not assign standard functions in the platform layer (e.g. calloc() to * MBEDTLS_PLATFORM_STD_CALLOC and printf() to MBEDTLS_PLATFORM_STD_PRINTF) * * This makes sure there are no linking errors on platforms that do not support * these functions. You will HAVE to provide alternatives, either at runtime * via the platform_set_xxx() functions or at compile time by setting * the MBEDTLS_PLATFORM_STD_XXX defines, or enabling a * MBEDTLS_PLATFORM_XXX_MACRO. * * Requires: MBEDTLS_PLATFORM_C * * Uncomment to prevent default assignment of standard functions in the * platform layer. */ //#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS /** * \def MBEDTLS_PLATFORM_EXIT_ALT * * MBEDTLS_PLATFORM_XXX_ALT: Uncomment a macro to let Mbed TLS support the * function in the platform abstraction layer. * * Example: In case you uncomment MBEDTLS_PLATFORM_PRINTF_ALT, Mbed TLS will * provide a function "mbedtls_platform_set_printf()" that allows you to set an * alternative printf function pointer. * * All these define require MBEDTLS_PLATFORM_C to be defined! * * \note MBEDTLS_PLATFORM_SNPRINTF_ALT is required on Windows; * it will be enabled automatically by check_config.h * * \warning MBEDTLS_PLATFORM_XXX_ALT cannot be defined at the same time as * MBEDTLS_PLATFORM_XXX_MACRO! * * Requires: MBEDTLS_PLATFORM_TIME_ALT requires MBEDTLS_HAVE_TIME * * Uncomment a macro to enable alternate implementation of specific base * platform function */ //#define MBEDTLS_PLATFORM_SETBUF_ALT //#define MBEDTLS_PLATFORM_EXIT_ALT //#define MBEDTLS_PLATFORM_TIME_ALT //#define MBEDTLS_PLATFORM_FPRINTF_ALT //#define MBEDTLS_PLATFORM_PRINTF_ALT //#define MBEDTLS_PLATFORM_SNPRINTF_ALT //#define MBEDTLS_PLATFORM_VSNPRINTF_ALT //#define MBEDTLS_PLATFORM_NV_SEED_ALT //#define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT //#define MBEDTLS_PLATFORM_MS_TIME_ALT /** * Uncomment the macro to let Mbed TLS use your alternate implementation of * mbedtls_platform_gmtime_r(). This replaces the default implementation in * platform_util.c. * * gmtime() is not a thread-safe function as defined in the C standard. The * library will try to use safer implementations of this function, such as * gmtime_r() when available. However, if Mbed TLS cannot identify the target * system, the implementation of mbedtls_platform_gmtime_r() will default to * using the standard gmtime(). In this case, calls from the library to * gmtime() will be guarded by the global mutex mbedtls_threading_gmtime_mutex * if MBEDTLS_THREADING_C is enabled. We recommend that calls from outside the * library are also guarded with this mutex to avoid race conditions. However, * if the macro MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, Mbed TLS will * unconditionally use the implementation for mbedtls_platform_gmtime_r() * supplied at compile time. */ //#define MBEDTLS_PLATFORM_GMTIME_R_ALT /** * Uncomment the macro to let Mbed TLS use your alternate implementation of * mbedtls_platform_zeroize(), to wipe sensitive data in memory. This replaces * the default implementation in platform_util.c. * * By default, the library uses a system function such as memset_s() * (optional feature of C11), explicit_bzero() (BSD and compatible), or * SecureZeroMemory (Windows). If no such function is detected, the library * falls back to a plain C implementation. Compilers are technically * permitted to optimize this implementation out, meaning that the memory is * not actually wiped. The library tries to prevent that, but the C language * makes it impossible to guarantee that the memory will always be wiped. * * If your platform provides a guaranteed method to wipe memory which * `platform_util.c` does not detect, define this macro to the name of * a function that takes two arguments, a `void *` pointer and a length, * and wipes that many bytes starting at the specified address. For example, * if your platform has explicit_bzero() but `platform_util.c` does not * detect its presence, define `MBEDTLS_PLATFORM_ZEROIZE_ALT` to be * `explicit_bzero` to use that function as mbedtls_platform_zeroize(). */ //#define MBEDTLS_PLATFORM_ZEROIZE_ALT /** * \def MBEDTLS_DEPRECATED_WARNING * * Mark deprecated functions and features so that they generate a warning if * used. Functionality deprecated in one version will usually be removed in the * next version. You can enable this to help you prepare the transition to a * new major version by making sure your code is not using this functionality. * * This only works with GCC and Clang. With other compilers, you may want to * use MBEDTLS_DEPRECATED_REMOVED * * Uncomment to get warnings on using deprecated functions and features. */ //#define MBEDTLS_DEPRECATED_WARNING /** * \def MBEDTLS_DEPRECATED_REMOVED * * Remove deprecated functions and features so that they generate an error if * used. Functionality deprecated in one version will usually be removed in the * next version. You can enable this to help you prepare the transition to a * new major version by making sure your code is not using this functionality. * * Uncomment to get errors on using deprecated functions and features. */ //#define MBEDTLS_DEPRECATED_REMOVED /** \} name SECTION: System support */ /** * \name SECTION: Mbed TLS feature support * * This section sets support for features that are or are not needed * within the modules that are enabled. * \{ */ /** * \def MBEDTLS_TIMING_ALT * * Uncomment to provide your own alternate implementation for * mbedtls_timing_get_timer(), mbedtls_set_alarm(), mbedtls_set/get_delay() * * Only works if you have MBEDTLS_TIMING_C enabled. * * You will need to provide a header "timing_alt.h" and an implementation at * compile time. */ //#define MBEDTLS_TIMING_ALT /** * \def MBEDTLS_AES_ALT * * MBEDTLS__MODULE_NAME__ALT: Uncomment a macro to let Mbed TLS use your * alternate core implementation of a symmetric crypto, an arithmetic or hash * module (e.g. platform specific assembly optimized implementations). Keep * in mind that the function prototypes should remain the same. * * This replaces the whole module. If you only want to replace one of the * functions, use one of the MBEDTLS__FUNCTION_NAME__ALT flags. * * Example: In case you uncomment MBEDTLS_AES_ALT, Mbed TLS will no longer * provide the "struct mbedtls_aes_context" definition and omit the base * function declarations and implementations. "aes_alt.h" will be included from * "aes.h" to include the new function definitions. * * Uncomment a macro to enable alternate implementation of the corresponding * module. * * \warning MD5, DES and SHA-1 are considered weak and their * use constitutes a security risk. If possible, we recommend * avoiding dependencies on them, and considering stronger message * digests and ciphers instead. * */ //#define MBEDTLS_AES_ALT //#define MBEDTLS_ARIA_ALT //#define MBEDTLS_CAMELLIA_ALT //#define MBEDTLS_CCM_ALT //#define MBEDTLS_CHACHA20_ALT //#define MBEDTLS_CHACHAPOLY_ALT //#define MBEDTLS_CMAC_ALT //#define MBEDTLS_DES_ALT //#define MBEDTLS_DHM_ALT //#define MBEDTLS_ECJPAKE_ALT //#define MBEDTLS_GCM_ALT //#define MBEDTLS_NIST_KW_ALT //#define MBEDTLS_MD5_ALT //#define MBEDTLS_POLY1305_ALT //#define MBEDTLS_RIPEMD160_ALT //#define MBEDTLS_RSA_ALT //#define MBEDTLS_SHA1_ALT //#define MBEDTLS_SHA256_ALT //#define MBEDTLS_SHA512_ALT /* * When replacing the elliptic curve module, please consider, that it is * implemented with two .c files: * - ecp.c * - ecp_curves.c * You can replace them very much like all the other MBEDTLS__MODULE_NAME__ALT * macros as described above. The only difference is that you have to make sure * that you provide functionality for both .c files. */ //#define MBEDTLS_ECP_ALT /** * \def MBEDTLS_SHA256_PROCESS_ALT * * MBEDTLS__FUNCTION_NAME__ALT: Uncomment a macro to let Mbed TLS use you * alternate core implementation of symmetric crypto or hash function. Keep in * mind that function prototypes should remain the same. * * This replaces only one function. The header file from Mbed TLS is still * used, in contrast to the MBEDTLS__MODULE_NAME__ALT flags. * * Example: In case you uncomment MBEDTLS_SHA256_PROCESS_ALT, Mbed TLS will * no longer provide the mbedtls_sha1_process() function, but it will still provide * the other function (using your mbedtls_sha1_process() function) and the definition * of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible * with this definition. * * \note If you use the AES_xxx_ALT macros, then it is recommended to also set * MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES * tables. * * Uncomment a macro to enable alternate implementation of the corresponding * function. * * \warning MD5, DES and SHA-1 are considered weak and their use * constitutes a security risk. If possible, we recommend avoiding * dependencies on them, and considering stronger message digests * and ciphers instead. * * \warning If both MBEDTLS_ECDSA_SIGN_ALT and MBEDTLS_ECDSA_DETERMINISTIC are * enabled, then the deterministic ECDH signature functions pass the * the static HMAC-DRBG as RNG to mbedtls_ecdsa_sign(). Therefore * alternative implementations should use the RNG only for generating * the ephemeral key and nothing else. If this is not possible, then * MBEDTLS_ECDSA_DETERMINISTIC should be disabled and an alternative * implementation should be provided for mbedtls_ecdsa_sign_det_ext(). * */ //#define MBEDTLS_MD5_PROCESS_ALT //#define MBEDTLS_RIPEMD160_PROCESS_ALT //#define MBEDTLS_SHA1_PROCESS_ALT //#define MBEDTLS_SHA256_PROCESS_ALT //#define MBEDTLS_SHA512_PROCESS_ALT //#define MBEDTLS_DES_SETKEY_ALT //#define MBEDTLS_DES_CRYPT_ECB_ALT //#define MBEDTLS_DES3_CRYPT_ECB_ALT //#define MBEDTLS_AES_SETKEY_ENC_ALT //#define MBEDTLS_AES_SETKEY_DEC_ALT //#define MBEDTLS_AES_ENCRYPT_ALT //#define MBEDTLS_AES_DECRYPT_ALT //#define MBEDTLS_ECDH_GEN_PUBLIC_ALT //#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT //#define MBEDTLS_ECDSA_VERIFY_ALT //#define MBEDTLS_ECDSA_SIGN_ALT //#define MBEDTLS_ECDSA_GENKEY_ALT /** * \def MBEDTLS_ECP_INTERNAL_ALT * * Expose a part of the internal interface of the Elliptic Curve Point module. * * MBEDTLS_ECP__FUNCTION_NAME__ALT: Uncomment a macro to let Mbed TLS use your * alternative core implementation of elliptic curve arithmetic. Keep in mind * that function prototypes should remain the same. * * This partially replaces one function. The header file from Mbed TLS is still * used, in contrast to the MBEDTLS_ECP_ALT flag. The original implementation * is still present and it is used for group structures not supported by the * alternative. * * The original implementation can in addition be removed by setting the * MBEDTLS_ECP_NO_FALLBACK option, in which case any function for which the * corresponding MBEDTLS_ECP__FUNCTION_NAME__ALT macro is defined will not be * able to fallback to curves not supported by the alternative implementation. * * Any of these options become available by defining MBEDTLS_ECP_INTERNAL_ALT * and implementing the following functions: * unsigned char mbedtls_internal_ecp_grp_capable( * const mbedtls_ecp_group *grp ) * int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp ) * void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp ) * The mbedtls_internal_ecp_grp_capable function should return 1 if the * replacement functions implement arithmetic for the given group and 0 * otherwise. * The functions mbedtls_internal_ecp_init and mbedtls_internal_ecp_free are * called before and after each point operation and provide an opportunity to * implement optimized set up and tear down instructions. * * Example: In case you set MBEDTLS_ECP_INTERNAL_ALT and * MBEDTLS_ECP_DOUBLE_JAC_ALT, Mbed TLS will still provide the ecp_double_jac() * function, but will use your mbedtls_internal_ecp_double_jac() if the group * for the operation is supported by your implementation (i.e. your * mbedtls_internal_ecp_grp_capable() function returns 1 for this group). If the * group is not supported by your implementation, then the original Mbed TLS * implementation of ecp_double_jac() is used instead, unless this fallback * behaviour is disabled by setting MBEDTLS_ECP_NO_FALLBACK (in which case * ecp_double_jac() will return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE). * * The function prototypes and the definition of mbedtls_ecp_group and * mbedtls_ecp_point will not change based on MBEDTLS_ECP_INTERNAL_ALT, so your * implementation of mbedtls_internal_ecp__function_name__ must be compatible * with their definitions. * * Uncomment a macro to enable alternate implementation of the corresponding * function. */ /* Required for all the functions in this section */ //#define MBEDTLS_ECP_INTERNAL_ALT /* Turn off software fallback for curves not supported in hardware */ //#define MBEDTLS_ECP_NO_FALLBACK /* Support for Weierstrass curves with Jacobi representation */ //#define MBEDTLS_ECP_RANDOMIZE_JAC_ALT //#define MBEDTLS_ECP_ADD_MIXED_ALT //#define MBEDTLS_ECP_DOUBLE_JAC_ALT //#define MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT //#define MBEDTLS_ECP_NORMALIZE_JAC_ALT /* Support for curves with Montgomery arithmetic */ //#define MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT //#define MBEDTLS_ECP_RANDOMIZE_MXZ_ALT //#define MBEDTLS_ECP_NORMALIZE_MXZ_ALT /** * \def MBEDTLS_ENTROPY_HARDWARE_ALT * * Uncomment this macro to let Mbed TLS use your own implementation of a * hardware entropy collector. * * Your function must be called \c mbedtls_hardware_poll(), have the same * prototype as declared in library/entropy_poll.h, and accept NULL as first * argument. * * Uncomment to use your own hardware entropy collector. */ //#define MBEDTLS_ENTROPY_HARDWARE_ALT /** * \def MBEDTLS_AES_ROM_TABLES * * Use precomputed AES tables stored in ROM. * * Uncomment this macro to use precomputed AES tables stored in ROM. * Comment this macro to generate AES tables in RAM at runtime. * * Tradeoff: Using precomputed ROM tables reduces RAM usage by ~8kb * (or ~2kb if \c MBEDTLS_AES_FEWER_TABLES is used) and reduces the * initialization time before the first AES operation can be performed. * It comes at the cost of additional ~8kb ROM use (resp. ~2kb if \c * MBEDTLS_AES_FEWER_TABLES below is used), and potentially degraded * performance if ROM access is slower than RAM access. * * This option is independent of \c MBEDTLS_AES_FEWER_TABLES. */ //#define MBEDTLS_AES_ROM_TABLES /** * \def MBEDTLS_AES_FEWER_TABLES * * Use less ROM/RAM for AES tables. * * Uncommenting this macro omits 75% of the AES tables from * ROM / RAM (depending on the value of \c MBEDTLS_AES_ROM_TABLES) * by computing their values on the fly during operations * (the tables are entry-wise rotations of one another). * * Tradeoff: Uncommenting this reduces the RAM / ROM footprint * by ~6kb but at the cost of more arithmetic operations during * runtime. Specifically, one has to compare 4 accesses within * different tables to 4 accesses with additional arithmetic * operations within the same table. The performance gain/loss * depends on the system and memory details. * * This option is independent of \c MBEDTLS_AES_ROM_TABLES. */ //#define MBEDTLS_AES_FEWER_TABLES /** * \def MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH * * Use only 128-bit keys in AES operations to save ROM. * * Uncomment this macro to remove support for AES operations that use 192- * or 256-bit keys. * * Uncommenting this macro reduces the size of AES code by ~300 bytes * on v8-M/Thumb2. * * Module: library/aes.c * * Requires: MBEDTLS_AES_C */ //#define MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH /* * Disable plain C implementation for AES. * * When the plain C implementation is enabled, and an implementation using a * special CPU feature (such as MBEDTLS_AESCE_C) is also enabled, runtime * detection will be used to select between them. * * If only one implementation is present, runtime detection will not be used. * This configuration will crash at runtime if running on a CPU without the * necessary features. It will not build unless at least one of MBEDTLS_AESCE_C * and/or MBEDTLS_AESNI_C is enabled & present in the build. */ //#define MBEDTLS_AES_USE_HARDWARE_ONLY /** * \def MBEDTLS_CAMELLIA_SMALL_MEMORY * * Use less ROM for the Camellia implementation (saves about 768 bytes). * * Uncomment this macro to use less memory for Camellia. */ //#define MBEDTLS_CAMELLIA_SMALL_MEMORY /** * \def MBEDTLS_CHECK_RETURN_WARNING * * If this macro is defined, emit a compile-time warning if application code * calls a function without checking its return value, but the return value * should generally be checked in portable applications. * * This is only supported on platforms where #MBEDTLS_CHECK_RETURN is * implemented. Otherwise this option has no effect. * * Uncomment to get warnings on using fallible functions without checking * their return value. * * \note This feature is a work in progress. * Warnings will be added to more functions in the future. * * \note A few functions are considered critical, and ignoring the return * value of these functions will trigger a warning even if this * macro is not defined. To completely disable return value check * warnings, define #MBEDTLS_CHECK_RETURN with an empty expansion. */ //#define MBEDTLS_CHECK_RETURN_WARNING /** * \def MBEDTLS_CIPHER_MODE_CBC * * Enable Cipher Block Chaining mode (CBC) for symmetric ciphers. */ #define MBEDTLS_CIPHER_MODE_CBC /** * \def MBEDTLS_CIPHER_MODE_CFB * * Enable Cipher Feedback mode (CFB) for symmetric ciphers. */ #define MBEDTLS_CIPHER_MODE_CFB /** * \def MBEDTLS_CIPHER_MODE_CTR * * Enable Counter Block Cipher mode (CTR) for symmetric ciphers. */ #define MBEDTLS_CIPHER_MODE_CTR /** * \def MBEDTLS_CIPHER_MODE_OFB * * Enable Output Feedback mode (OFB) for symmetric ciphers. */ #define MBEDTLS_CIPHER_MODE_OFB /** * \def MBEDTLS_CIPHER_MODE_XTS * * Enable Xor-encrypt-xor with ciphertext stealing mode (XTS) for AES. */ #define MBEDTLS_CIPHER_MODE_XTS /** * \def MBEDTLS_CIPHER_NULL_CIPHER * * Enable NULL cipher. * Warning: Only do so when you know what you are doing. This allows for * encryption or channels without any security! * * To enable the following ciphersuites: * MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA * MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA * MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA * MBEDTLS_TLS_RSA_WITH_NULL_SHA256 * MBEDTLS_TLS_RSA_WITH_NULL_SHA * MBEDTLS_TLS_RSA_WITH_NULL_MD5 * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA * MBEDTLS_TLS_PSK_WITH_NULL_SHA384 * MBEDTLS_TLS_PSK_WITH_NULL_SHA256 * MBEDTLS_TLS_PSK_WITH_NULL_SHA * * Uncomment this macro to enable the NULL cipher and ciphersuites */ //#define MBEDTLS_CIPHER_NULL_CIPHER /** * \def MBEDTLS_CIPHER_PADDING_PKCS7 * * MBEDTLS_CIPHER_PADDING_XXX: Uncomment or comment macros to add support for * specific padding modes in the cipher layer with cipher modes that support * padding (e.g. CBC) * * If you disable all padding modes, only full blocks can be used with CBC. * * Enable padding modes in the cipher layer. */ #define MBEDTLS_CIPHER_PADDING_PKCS7 #define MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS #define MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN #define MBEDTLS_CIPHER_PADDING_ZEROS /** \def MBEDTLS_CTR_DRBG_USE_128_BIT_KEY * * Uncomment this macro to use a 128-bit key in the CTR_DRBG module. * Without this, CTR_DRBG uses a 256-bit key * unless \c MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH is set. */ //#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY /** * Enable the verified implementations of ECDH primitives from Project Everest * (currently only Curve25519). This feature changes the layout of ECDH * contexts and therefore is a compatibility break for applications that access * fields of a mbedtls_ecdh_context structure directly. See also * MBEDTLS_ECDH_LEGACY_CONTEXT in include/mbedtls/ecdh.h. * * The Everest code is provided under the Apache 2.0 license only; therefore enabling this * option is not compatible with taking the library under the GPL v2.0-or-later license. */ //#define MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED /** * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED * * MBEDTLS_ECP_XXXX_ENABLED: Enables specific curves within the Elliptic Curve * module. By default all supported curves are enabled. * * Comment macros to disable the curve and functions for it */ /* Short Weierstrass curves (supporting ECP, ECDH, ECDSA) */ #define MBEDTLS_ECP_DP_SECP192R1_ENABLED #define MBEDTLS_ECP_DP_SECP224R1_ENABLED #define MBEDTLS_ECP_DP_SECP256R1_ENABLED #define MBEDTLS_ECP_DP_SECP384R1_ENABLED #define MBEDTLS_ECP_DP_SECP521R1_ENABLED #define MBEDTLS_ECP_DP_SECP192K1_ENABLED #define MBEDTLS_ECP_DP_SECP224K1_ENABLED #define MBEDTLS_ECP_DP_SECP256K1_ENABLED #define MBEDTLS_ECP_DP_BP256R1_ENABLED #define MBEDTLS_ECP_DP_BP384R1_ENABLED #define MBEDTLS_ECP_DP_BP512R1_ENABLED /* Montgomery curves (supporting ECP) */ #define MBEDTLS_ECP_DP_CURVE25519_ENABLED #define MBEDTLS_ECP_DP_CURVE448_ENABLED /** * \def MBEDTLS_ECP_NIST_OPTIM * * Enable specific 'modulo p' routines for each NIST prime. * Depending on the prime and architecture, makes operations 4 to 8 times * faster on the corresponding curve. * * Comment this macro to disable NIST curves optimisation. */ #define MBEDTLS_ECP_NIST_OPTIM /** * \def MBEDTLS_ECP_RESTARTABLE * * Enable "non-blocking" ECC operations that can return early and be resumed. * * This allows various functions to pause by returning * #MBEDTLS_ERR_ECP_IN_PROGRESS (or, for functions in the SSL module, * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) and then be called later again in * order to further progress and eventually complete their operation. This is * controlled through mbedtls_ecp_set_max_ops() which limits the maximum * number of ECC operations a function may perform before pausing; see * mbedtls_ecp_set_max_ops() for more information. * * This is useful in non-threaded environments if you want to avoid blocking * for too long on ECC (and, hence, X.509 or SSL/TLS) operations. * * This option: * - Adds xxx_restartable() variants of existing operations in the * following modules, with corresponding restart context types: * - ECP (for Short Weierstrass curves only): scalar multiplication (mul), * linear combination (muladd); * - ECDSA: signature generation & verification; * - PK: signature generation & verification; * - X509: certificate chain verification. * - Adds mbedtls_ecdh_enable_restart() in the ECDH module. * - Changes the behaviour of TLS 1.2 clients (not servers) when using the * ECDHE-ECDSA key exchange (not other key exchanges) to make all ECC * computations restartable: * - ECDH operations from the key exchange, only for Short Weierstrass * curves, only when MBEDTLS_USE_PSA_CRYPTO is not enabled. * - verification of the server's key exchange signature; * - verification of the server's certificate chain; * - generation of the client's signature if client authentication is used, * with an ECC key/certificate. * * \note In the cases above, the usual SSL/TLS functions, such as * mbedtls_ssl_handshake(), can now return * MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS. * * \note When this option and MBEDTLS_USE_PSA_CRYPTO are both enabled, * restartable operations in PK, X.509 and TLS (see above) are not * using PSA. On the other hand, ECDH computations in TLS are using * PSA, and are not restartable. These are temporary limitations that * should be lifted in the future. * * \note This option only works with the default software implementation of * elliptic curve functionality. It is incompatible with * MBEDTLS_ECP_ALT, MBEDTLS_ECDH_XXX_ALT, MBEDTLS_ECDSA_XXX_ALT. * * Requires: MBEDTLS_ECP_C * * Uncomment this macro to enable restartable ECC computations. */ //#define MBEDTLS_ECP_RESTARTABLE /** * Uncomment to enable using new bignum code in the ECC modules. * * \warning This is currently experimental, incomplete and therefore should not * be used in production. */ //#define MBEDTLS_ECP_WITH_MPI_UINT /** * \def MBEDTLS_ECDSA_DETERMINISTIC * * Enable deterministic ECDSA (RFC 6979). * Standard ECDSA is "fragile" in the sense that lack of entropy when signing * may result in a compromise of the long-term signing key. This is avoided by * the deterministic variant. * * Requires: MBEDTLS_HMAC_DRBG_C, MBEDTLS_ECDSA_C * * Comment this macro to disable deterministic ECDSA. */ #define MBEDTLS_ECDSA_DETERMINISTIC /** * \def MBEDTLS_KEY_EXCHANGE_PSK_ENABLED * * Enable the PSK based ciphersuite modes in SSL / TLS. * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 */ #define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED * * Enable the DHE-PSK based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_DHM_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 * * \warning Using DHE constitutes a security risk as it * is not possible to validate custom DH parameters. * If possible, it is recommended users should consider * preferring other methods of key exchange. * See dhm.h for more details. * */ #define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED * * Enable the ECDHE-PSK based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH) * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 */ #define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED * * Enable the RSA-PSK based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 */ #define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_RSA_ENABLED * * Enable the RSA-only based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA */ #define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED * * Enable the DHE-RSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_DHM_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA * * \warning Using DHE constitutes a security risk as it * is not possible to validate custom DH parameters. * If possible, it is recommended users should consider * preferring other methods of key exchange. * See dhm.h for more details. * */ #define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED * * Enable the ECDHE-RSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH) * MBEDTLS_RSA_C * MBEDTLS_PKCS1_V15 * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 */ #define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED * * Enable the ECDHE-ECDSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH) * MBEDTLS_ECDSA_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDSA) * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 */ #define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED * * Enable the ECDH-ECDSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH) * MBEDTLS_ECDSA_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDSA) * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 */ #define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED * * Enable the ECDH-RSA based ciphersuite modes in SSL / TLS. * * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH) * MBEDTLS_RSA_C * MBEDTLS_X509_CRT_PARSE_C * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 */ #define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED /** * \def MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED * * Enable the ECJPAKE based ciphersuite modes in SSL / TLS. * * \warning This is currently experimental. EC J-PAKE support is based on the * Thread v1.0.0 specification; incompatible changes to the specification * might still happen. For this reason, this is disabled by default. * * Requires: MBEDTLS_ECJPAKE_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_JPAKE) * SHA-256 (via MBEDTLS_SHA256_C or a PSA driver) * MBEDTLS_ECP_DP_SECP256R1_ENABLED * * \warning If SHA-256 is provided only by a PSA driver, you must call * psa_crypto_init() before the first handshake (even if * MBEDTLS_USE_PSA_CRYPTO is disabled). * * This enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 */ //#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED /** * \def MBEDTLS_PK_PARSE_EC_EXTENDED * * Enhance support for reading EC keys using variants of SEC1 not allowed by * RFC 5915 and RFC 5480. * * Currently this means parsing the SpecifiedECDomain choice of EC * parameters (only known groups are supported, not arbitrary domains, to * avoid validation issues). * * Disable if you only need to support RFC 5915 + 5480 key formats. */ #define MBEDTLS_PK_PARSE_EC_EXTENDED /** * \def MBEDTLS_PK_PARSE_EC_COMPRESSED * * Enable the support for parsing public keys of type Short Weierstrass * (MBEDTLS_ECP_DP_SECP_XXX and MBEDTLS_ECP_DP_BP_XXX) which are using the * compressed point format. This parsing is done through ECP module's functions. * * \note As explained in the description of MBEDTLS_ECP_PF_COMPRESSED (in ecp.h) * the only unsupported curves are MBEDTLS_ECP_DP_SECP224R1 and * MBEDTLS_ECP_DP_SECP224K1. */ #define MBEDTLS_PK_PARSE_EC_COMPRESSED /** * \def MBEDTLS_ERROR_STRERROR_DUMMY * * Enable a dummy error function to make use of mbedtls_strerror() in * third party libraries easier when MBEDTLS_ERROR_C is disabled * (no effect when MBEDTLS_ERROR_C is enabled). * * You can safely disable this if MBEDTLS_ERROR_C is enabled, or if you're * not using mbedtls_strerror() or error_strerror() in your application. * * Disable if you run into name conflicts and want to really remove the * mbedtls_strerror() */ #define MBEDTLS_ERROR_STRERROR_DUMMY /** * \def MBEDTLS_GENPRIME * * Enable the prime-number generation code. * * Requires: MBEDTLS_BIGNUM_C */ #define MBEDTLS_GENPRIME /** * \def MBEDTLS_FS_IO * * Enable functions that use the filesystem. */ #define MBEDTLS_FS_IO /** * \def MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES * * Do not add default entropy sources in mbedtls_entropy_init(). * * This is useful to have more control over the added entropy sources in an * application. * * Uncomment this macro to prevent loading of default entropy functions. */ //#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES /** * \def MBEDTLS_NO_PLATFORM_ENTROPY * * Do not use built-in platform entropy functions. * This is useful if your platform does not support * standards like the /dev/urandom or Windows CryptoAPI. * * Uncomment this macro to disable the built-in platform entropy functions. */ //#define MBEDTLS_NO_PLATFORM_ENTROPY /** * \def MBEDTLS_ENTROPY_FORCE_SHA256 * * Force the entropy accumulator to use a SHA-256 accumulator instead of the * default SHA-512 based one (if both are available). * * Requires: MBEDTLS_SHA256_C * * On 32-bit systems SHA-256 can be much faster than SHA-512. Use this option * if you have performance concerns. * * This option is only useful if both MBEDTLS_SHA256_C and * MBEDTLS_SHA512_C are defined. Otherwise the available hash module is used. */ //#define MBEDTLS_ENTROPY_FORCE_SHA256 /** * \def MBEDTLS_ENTROPY_NV_SEED * * Enable the non-volatile (NV) seed file-based entropy source. * (Also enables the NV seed read/write functions in the platform layer) * * This is crucial (if not required) on systems that do not have a * cryptographic entropy source (in hardware or kernel) available. * * Requires: MBEDTLS_ENTROPY_C, MBEDTLS_PLATFORM_C * * \note The read/write functions that are used by the entropy source are * determined in the platform layer, and can be modified at runtime and/or * compile-time depending on the flags (MBEDTLS_PLATFORM_NV_SEED_*) used. * * \note If you use the default implementation functions that read a seedfile * with regular fopen(), please make sure you make a seedfile with the * proper name (defined in MBEDTLS_PLATFORM_STD_NV_SEED_FILE) and at * least MBEDTLS_ENTROPY_BLOCK_SIZE bytes in size that can be read from * and written to or you will get an entropy source error! The default * implementation will only use the first MBEDTLS_ENTROPY_BLOCK_SIZE * bytes from the file. * * \note The entropy collector will write to the seed file before entropy is * given to an external source, to update it. */ //#define MBEDTLS_ENTROPY_NV_SEED /* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER * * Enable key identifiers that encode a key owner identifier. * * The owner of a key is identified by a value of type ::mbedtls_key_owner_id_t * which is currently hard-coded to be int32_t. * * Note that this option is meant for internal use only and may be removed * without notice. */ //#define MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER /** * \def MBEDTLS_MEMORY_DEBUG * * Enable debugging of buffer allocator memory issues. Automatically prints * (to stderr) all (fatal) messages on memory allocation issues. Enables * function for 'debug output' of allocated memory. * * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C * * Uncomment this macro to let the buffer allocator print out error messages. */ //#define MBEDTLS_MEMORY_DEBUG /** * \def MBEDTLS_MEMORY_BACKTRACE * * Include backtrace information with each allocated block. * * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C * GLIBC-compatible backtrace() and backtrace_symbols() support * * Uncomment this macro to include backtrace information */ //#define MBEDTLS_MEMORY_BACKTRACE /** * \def MBEDTLS_PK_RSA_ALT_SUPPORT * * Support external private RSA keys (eg from a HSM) in the PK layer. * * Comment this macro to disable support for external private RSA keys. */ #define MBEDTLS_PK_RSA_ALT_SUPPORT /** * \def MBEDTLS_PKCS1_V15 * * Enable support for PKCS#1 v1.5 encoding. * * Requires: MBEDTLS_RSA_C * * This enables support for PKCS#1 v1.5 operations. */ #define MBEDTLS_PKCS1_V15 /** * \def MBEDTLS_PKCS1_V21 * * Enable support for PKCS#1 v2.1 encoding. * * Requires: MBEDTLS_RSA_C * * \warning If using a hash that is only provided by PSA drivers, you must * call psa_crypto_init() before doing any PKCS#1 v2.1 operation. * * This enables support for RSAES-OAEP and RSASSA-PSS operations. */ #define MBEDTLS_PKCS1_V21 /** \def MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS * * Enable support for platform built-in keys. If you enable this feature, * you must implement the function mbedtls_psa_platform_get_builtin_key(). * See the documentation of that function for more information. * * Built-in keys are typically derived from a hardware unique key or * stored in a secure element. * * Requires: MBEDTLS_PSA_CRYPTO_C. * * \warning This interface is experimental and may change or be removed * without notice. */ //#define MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS /** \def MBEDTLS_PSA_CRYPTO_CLIENT * * Enable support for PSA crypto client. * * \note This option allows to include the code necessary for a PSA * crypto client when the PSA crypto implementation is not included in * the library (MBEDTLS_PSA_CRYPTO_C disabled). The code included is the * code to set and get PSA key attributes. * The development of PSA drivers partially relying on the library to * fulfill the hardware gaps is another possible usage of this option. * * \warning This interface is experimental and may change or be removed * without notice. */ //#define MBEDTLS_PSA_CRYPTO_CLIENT /** \def MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG * * Make the PSA Crypto module use an external random generator provided * by a driver, instead of Mbed TLS's entropy and DRBG modules. * * \note This random generator must deliver random numbers with cryptographic * quality and high performance. It must supply unpredictable numbers * with a uniform distribution. The implementation of this function * is responsible for ensuring that the random generator is seeded * with sufficient entropy. If you have a hardware TRNG which is slow * or delivers non-uniform output, declare it as an entropy source * with mbedtls_entropy_add_source() instead of enabling this option. * * If you enable this option, you must configure the type * ::mbedtls_psa_external_random_context_t in psa/crypto_platform.h * and define a function called mbedtls_psa_external_get_random() * with the following prototype: * ``` * psa_status_t mbedtls_psa_external_get_random( * mbedtls_psa_external_random_context_t *context, * uint8_t *output, size_t output_size, size_t *output_length); * ); * ``` * The \c context value is initialized to 0 before the first call. * The function must fill the \c output buffer with \c output_size bytes * of random data and set \c *output_length to \c output_size. * * Requires: MBEDTLS_PSA_CRYPTO_C * * \warning If you enable this option, code that uses the PSA cryptography * interface will not use any of the entropy sources set up for * the entropy module, nor the NV seed that MBEDTLS_ENTROPY_NV_SEED * enables. * * \note This option is experimental and may be removed without notice. */ //#define MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG /** * \def MBEDTLS_PSA_CRYPTO_SPM * * When MBEDTLS_PSA_CRYPTO_SPM is defined, the code is built for SPM (Secure * Partition Manager) integration which separates the code into two parts: a * NSPE (Non-Secure Process Environment) and an SPE (Secure Process * Environment). * * If you enable this option, your build environment must include a header * file `"crypto_spe.h"` (either in the `psa` subdirectory of the Mbed TLS * header files, or in another directory on the compiler's include search * path). Alternatively, your platform may customize the header * `psa/crypto_platform.h`, in which case it can skip or replace the * inclusion of `"crypto_spe.h"`. * * Module: library/psa_crypto.c * Requires: MBEDTLS_PSA_CRYPTO_C * */ //#define MBEDTLS_PSA_CRYPTO_SPM /** * \def MBEDTLS_PSA_KEY_STORE_DYNAMIC * * Dynamically resize the PSA key store to accommodate any number of * volatile keys (until the heap memory is exhausted). * * If this option is disabled, the key store has a fixed size * #MBEDTLS_PSA_KEY_SLOT_COUNT for volatile keys and loaded persistent keys * together. * * This option has no effect when #MBEDTLS_PSA_CRYPTO_C is disabled. * * Module: library/psa_crypto.c * Requires: MBEDTLS_PSA_CRYPTO_C */ #define MBEDTLS_PSA_KEY_STORE_DYNAMIC /** * Uncomment to enable p256-m. This is an alternative implementation of * key generation, ECDH and (randomized) ECDSA on the curve SECP256R1. * Compared to the default implementation: * * - p256-m has a much smaller code size and RAM footprint. * - p256-m is only available via the PSA API. This includes the pk module * when #MBEDTLS_USE_PSA_CRYPTO is enabled. * - p256-m does not support deterministic ECDSA, EC-JPAKE, custom protocols * over the core arithmetic, or deterministic derivation of keys. * * We recommend enabling this option if your application uses the PSA API * and the only elliptic curve support it needs is ECDH and ECDSA over * SECP256R1. * * If you enable this option, you do not need to enable any ECC-related * MBEDTLS_xxx option. You do need to separately request support for the * cryptographic mechanisms through the PSA API: * - #MBEDTLS_PSA_CRYPTO_C and #MBEDTLS_PSA_CRYPTO_CONFIG for PSA-based * configuration; * - #MBEDTLS_USE_PSA_CRYPTO if you want to use p256-m from PK, X.509 or TLS; * - #PSA_WANT_ECC_SECP_R1_256; * - #PSA_WANT_ALG_ECDH and/or #PSA_WANT_ALG_ECDSA as needed; * - #PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY, #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC, * #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT, * #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT and/or * #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE as needed. * * \note To benefit from the smaller code size of p256-m, make sure that you * do not enable any ECC-related option not supported by p256-m: this * would cause the built-in ECC implementation to be built as well, in * order to provide the required option. * Make sure #PSA_WANT_ALG_DETERMINISTIC_ECDSA, #PSA_WANT_ALG_JPAKE and * #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE, and curves other than * SECP256R1 are disabled as they are not supported by this driver. * Also, avoid defining #MBEDTLS_PK_PARSE_EC_COMPRESSED or * #MBEDTLS_PK_PARSE_EC_EXTENDED as those currently require a subset of * the built-in ECC implementation, see docs/driver-only-builds.md. */ //#define MBEDTLS_PSA_P256M_DRIVER_ENABLED /** * \def MBEDTLS_PSA_INJECT_ENTROPY * * Enable support for entropy injection at first boot. This feature is * required on systems that do not have a built-in entropy source (TRNG). * This feature is currently not supported on systems that have a built-in * entropy source. * * Requires: MBEDTLS_PSA_CRYPTO_STORAGE_C, MBEDTLS_ENTROPY_NV_SEED * */ //#define MBEDTLS_PSA_INJECT_ENTROPY /** * \def MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS * * Assume all buffers passed to PSA functions are owned exclusively by the * PSA function and are not stored in shared memory. * * This option may be enabled if all buffers passed to any PSA function reside * in memory that is accessible only to the PSA function during its execution. * * This option MUST be disabled whenever buffer arguments are in memory shared * with an untrusted party, for example where arguments to PSA calls are passed * across a trust boundary. * * \note Enabling this option reduces memory usage and code size. * * \note Enabling this option causes overlap of input and output buffers * not to be supported by PSA functions. */ //#define MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS /** * \def MBEDTLS_RSA_NO_CRT * * Do not use the Chinese Remainder Theorem * for the RSA private operation. * * Uncomment this macro to disable the use of CRT in RSA. * */ //#define MBEDTLS_RSA_NO_CRT /** * \def MBEDTLS_SELF_TEST * * Enable the checkup functions (*_self_test). */ #define MBEDTLS_SELF_TEST /** * \def MBEDTLS_SHA256_SMALLER * * Enable an implementation of SHA-256 that has lower ROM footprint but also * lower performance. * * The default implementation is meant to be a reasonable compromise between * performance and size. This version optimizes more aggressively for size at * the expense of performance. Eg on Cortex-M4 it reduces the size of * mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about * 30%. * * Uncomment to enable the smaller implementation of SHA256. */ //#define MBEDTLS_SHA256_SMALLER /** * \def MBEDTLS_SHA512_SMALLER * * Enable an implementation of SHA-512 that has lower ROM footprint but also * lower performance. * * Uncomment to enable the smaller implementation of SHA512. */ //#define MBEDTLS_SHA512_SMALLER /** * \def MBEDTLS_SSL_ALL_ALERT_MESSAGES * * Enable sending of alert messages in case of encountered errors as per RFC. * If you choose not to send the alert messages, Mbed TLS can still communicate * with other servers, only debugging of failures is harder. * * The advantage of not sending alert messages, is that no information is given * about reasons for failures thus preventing adversaries of gaining intel. * * Enable sending of all alert messages */ #define MBEDTLS_SSL_ALL_ALERT_MESSAGES /** * \def MBEDTLS_SSL_DTLS_CONNECTION_ID * * Enable support for the DTLS Connection ID (CID) extension, * which allows to identify DTLS connections across changes * in the underlying transport. The CID functionality is described * in RFC 9146. * * Setting this option enables the SSL APIs `mbedtls_ssl_set_cid()`, * mbedtls_ssl_get_own_cid()`, `mbedtls_ssl_get_peer_cid()` and * `mbedtls_ssl_conf_cid()`. See the corresponding documentation for * more information. * * The maximum lengths of outgoing and incoming CIDs can be configured * through the options * - MBEDTLS_SSL_CID_OUT_LEN_MAX * - MBEDTLS_SSL_CID_IN_LEN_MAX. * * Requires: MBEDTLS_SSL_PROTO_DTLS * * Uncomment to enable the Connection ID extension. */ #define MBEDTLS_SSL_DTLS_CONNECTION_ID /** * \def MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT * * Defines whether RFC 9146 (default) or the legacy version * (version draft-ietf-tls-dtls-connection-id-05, * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05) * is used. * * Set the value to 0 for the standard version, and * 1 for the legacy draft version. * * \deprecated Support for the legacy version of the DTLS * Connection ID feature is deprecated. Please * switch to the standardized version defined * in RFC 9146 enabled by utilizing * MBEDTLS_SSL_DTLS_CONNECTION_ID without use * of MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT. * * Requires: MBEDTLS_SSL_DTLS_CONNECTION_ID */ #define MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT 0 /** * \def MBEDTLS_SSL_ASYNC_PRIVATE * * Enable asynchronous external private key operations in SSL. This allows * you to configure an SSL connection to call an external cryptographic * module to perform private key operations instead of performing the * operation inside the library. * * Requires: MBEDTLS_X509_CRT_PARSE_C */ //#define MBEDTLS_SSL_ASYNC_PRIVATE /** \def MBEDTLS_SSL_CLI_ALLOW_WEAK_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME * * In TLS clients, when a client authenticates a server through its * certificate, the client normally checks three things: * - the certificate chain must be valid; * - the chain must start from a trusted CA; * - the certificate must cover the server name that is expected by the client. * * Omitting any of these checks is generally insecure, and can allow a * malicious server to impersonate a legitimate server. * * The third check may be safely skipped in some unusual scenarios, * such as networks where eavesdropping is a risk but not active attacks, * or a private PKI where the client equally trusts all servers that are * accredited by the root CA. * * You should call mbedtls_ssl_set_hostname() with the expected server name * before starting a TLS handshake on a client (unless the client is * set up to only use PSK-based authentication, which does not rely on the * host name). This configuration option controls what happens if a TLS client * is configured with the authentication mode #MBEDTLS_SSL_VERIFY_REQUIRED * (default), certificate authentication is enabled and the client does not * call mbedtls_ssl_set_hostname(): * * - If this option is unset (default), the connection attempt is aborted * with the error #MBEDTLS_ERR_SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME. * - If this option is set, the TLS library does not check the server name * that the certificate is valid for. This is the historical behavior * of Mbed TLS, but may be insecure as explained above. * * Enable this option for strict backward compatibility if you have * determined that it is secure in the scenario where you are using * Mbed TLS. * * \deprecated This option exists only for backward compatibility and will * be removed in the next major version of Mbed TLS. * */ //#define MBEDTLS_SSL_CLI_ALLOW_WEAK_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME /** * \def MBEDTLS_SSL_CONTEXT_SERIALIZATION * * Enable serialization of the TLS context structures, through use of the * functions mbedtls_ssl_context_save() and mbedtls_ssl_context_load(). * * This pair of functions allows one side of a connection to serialize the * context associated with the connection, then free or re-use that context * while the serialized state is persisted elsewhere, and finally deserialize * that state to a live context for resuming read/write operations on the * connection. From a protocol perspective, the state of the connection is * unaffected, in particular this is entirely transparent to the peer. * * Note: this is distinct from TLS session resumption, which is part of the * protocol and fully visible by the peer. TLS session resumption enables * establishing new connections associated to a saved session with shorter, * lighter handshakes, while context serialization is a local optimization in * handling a single, potentially long-lived connection. * * Enabling these APIs makes some SSL structures larger, as 64 extra bytes are * saved after the handshake to allow for more efficient serialization, so if * you don't need this feature you'll save RAM by disabling it. * * Requires: MBEDTLS_GCM_C or MBEDTLS_CCM_C or MBEDTLS_CHACHAPOLY_C * * Comment to disable the context serialization APIs. */ #define MBEDTLS_SSL_CONTEXT_SERIALIZATION /** * \def MBEDTLS_SSL_DEBUG_ALL * * Enable the debug messages in SSL module for all issues. * Debug messages have been disabled in some places to prevent timing * attacks due to (unbalanced) debugging function calls. * * If you need all error reporting you should enable this during debugging, * but remove this for production servers that should log as well. * * Uncomment this macro to report all debug messages on errors introducing * a timing side-channel. * */ //#define MBEDTLS_SSL_DEBUG_ALL /** \def MBEDTLS_SSL_ENCRYPT_THEN_MAC * * Enable support for Encrypt-then-MAC, RFC 7366. * * This allows peers that both support it to use a more robust protection for * ciphersuites using CBC, providing deep resistance against timing attacks * on the padding or underlying cipher. * * This only affects CBC ciphersuites, and is useless if none is defined. * * Requires: MBEDTLS_SSL_PROTO_TLS1_2 * * Comment this macro to disable support for Encrypt-then-MAC */ #define MBEDTLS_SSL_ENCRYPT_THEN_MAC /** \def MBEDTLS_SSL_EXTENDED_MASTER_SECRET * * Enable support for RFC 7627: Session Hash and Extended Master Secret * Extension. * * This was introduced as "the proper fix" to the Triple Handshake family of * attacks, but it is recommended to always use it (even if you disable * renegotiation), since it actually fixes a more fundamental issue in the * original SSL/TLS design, and has implications beyond Triple Handshake. * * Requires: MBEDTLS_SSL_PROTO_TLS1_2 * * Comment this macro to disable support for Extended Master Secret. */ #define MBEDTLS_SSL_EXTENDED_MASTER_SECRET /** * \def MBEDTLS_SSL_KEEP_PEER_CERTIFICATE * * This option controls the availability of the API mbedtls_ssl_get_peer_cert() * giving access to the peer's certificate after completion of the handshake. * * Unless you need mbedtls_ssl_peer_cert() in your application, it is * recommended to disable this option for reduced RAM usage. * * \note If this option is disabled, mbedtls_ssl_get_peer_cert() is still * defined, but always returns \c NULL. * * \note This option has no influence on the protection against the * triple handshake attack. Even if it is disabled, Mbed TLS will * still ensure that certificates do not change during renegotiation, * for example by keeping a hash of the peer's certificate. * * \note This option is required if MBEDTLS_SSL_PROTO_TLS1_3 is set. * * Comment this macro to disable storing the peer's certificate * after the handshake. */ #define MBEDTLS_SSL_KEEP_PEER_CERTIFICATE /** * \def MBEDTLS_SSL_RENEGOTIATION * * Enable support for TLS renegotiation. * * The two main uses of renegotiation are (1) refresh keys on long-lived * connections and (2) client authentication after the initial handshake. * If you don't need renegotiation, it's probably better to disable it, since * it has been associated with security issues in the past and is easy to * misuse/misunderstand. * * Requires: MBEDTLS_SSL_PROTO_TLS1_2 * * Comment this to disable support for renegotiation. * * \note Even if this option is disabled, both client and server are aware * of the Renegotiation Indication Extension (RFC 5746) used to * prevent the SSL renegotiation attack (see RFC 5746 Sect. 1). * (See \c mbedtls_ssl_conf_legacy_renegotiation for the * configuration of this extension). * */ #define MBEDTLS_SSL_RENEGOTIATION /** * \def MBEDTLS_SSL_MAX_FRAGMENT_LENGTH * * Enable support for RFC 6066 max_fragment_length extension in SSL. * * Comment this macro to disable support for the max_fragment_length extension */ #define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH /** * \def MBEDTLS_SSL_RECORD_SIZE_LIMIT * * Enable support for RFC 8449 record_size_limit extension in SSL (TLS 1.3 only). * * Requires: MBEDTLS_SSL_PROTO_TLS1_3 * * Uncomment this macro to enable support for the record_size_limit extension */ //#define MBEDTLS_SSL_RECORD_SIZE_LIMIT /** * \def MBEDTLS_SSL_PROTO_TLS1_2 * * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled). * * Requires: Without MBEDTLS_USE_PSA_CRYPTO: MBEDTLS_MD_C and * (MBEDTLS_SHA256_C or MBEDTLS_SHA384_C or * SHA-256 or SHA-512 provided by a PSA driver) * With MBEDTLS_USE_PSA_CRYPTO: * PSA_WANT_ALG_SHA_256 or PSA_WANT_ALG_SHA_384 * * \warning If building with MBEDTLS_USE_PSA_CRYPTO, or if the hash(es) used * are only provided by PSA drivers, you must call psa_crypto_init() before * doing any TLS operations. * * Comment this macro to disable support for TLS 1.2 / DTLS 1.2 */ #define MBEDTLS_SSL_PROTO_TLS1_2 /** * \def MBEDTLS_SSL_PROTO_TLS1_3 * * Enable support for TLS 1.3. * * \note See docs/architecture/tls13-support.md for a description of the TLS * 1.3 support that this option enables. * * Requires: MBEDTLS_SSL_KEEP_PEER_CERTIFICATE * Requires: MBEDTLS_PSA_CRYPTO_C * * \note TLS 1.3 uses PSA crypto for cryptographic operations that are * directly performed by TLS 1.3 code. As a consequence, when TLS 1.3 * is enabled, a TLS handshake may call psa_crypto_init(), even * if it ends up negotiating a different TLS version. * * \note Cryptographic operations performed indirectly via another module * (X.509, PK) or by code shared with TLS 1.2 (record protection, * running handshake hash) only use PSA crypto if * #MBEDTLS_USE_PSA_CRYPTO is enabled. * * \note In multithreaded applications, you must also enable * #MBEDTLS_THREADING_C, even if individual TLS contexts are not * shared between threads, unless only one thread ever calls * TLS functions. * * Uncomment this macro to enable the support for TLS 1.3. */ #define MBEDTLS_SSL_PROTO_TLS1_3 /** * \def MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE * * Enable TLS 1.3 middlebox compatibility mode. * * As specified in Section D.4 of RFC 8446, TLS 1.3 offers a compatibility * mode to make a TLS 1.3 connection more likely to pass through middle boxes * expecting TLS 1.2 traffic. * * Turning on the compatibility mode comes at the cost of a few added bytes * on the wire, but it doesn't affect compatibility with TLS 1.3 implementations * that don't use it. Therefore, unless transmission bandwidth is critical and * you know that middlebox compatibility issues won't occur, it is therefore * recommended to set this option. * * Comment to disable compatibility mode for TLS 1.3. If * MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any * effect on the build. * */ #define MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE /** * \def MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED * * Enable TLS 1.3 PSK key exchange mode. * * Comment to disable support for the PSK key exchange mode in TLS 1.3. If * MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any * effect on the build. * */ #define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED /** * \def MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED * * Enable TLS 1.3 ephemeral key exchange mode. * * Requires: PSA_WANT_ALG_ECDH or PSA_WANT_ALG_FFDH * MBEDTLS_X509_CRT_PARSE_C * and at least one of: * MBEDTLS_ECDSA_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDSA) * MBEDTLS_PKCS1_V21 * * Comment to disable support for the ephemeral key exchange mode in TLS 1.3. * If MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any * effect on the build. * */ #define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED /** * \def MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED * * Enable TLS 1.3 PSK ephemeral key exchange mode. * * Requires: PSA_WANT_ALG_ECDH or PSA_WANT_ALG_FFDH * * Comment to disable support for the PSK ephemeral key exchange mode in * TLS 1.3. If MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not * have any effect on the build. * */ #define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED /** * \def MBEDTLS_SSL_EARLY_DATA * * Enable support for RFC 8446 TLS 1.3 early data. * * Requires: MBEDTLS_SSL_SESSION_TICKETS and either * MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED or * MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED * * Comment this to disable support for early data. If MBEDTLS_SSL_PROTO_TLS1_3 * is not enabled, this option does not have any effect on the build. * * \note The maximum amount of early data can be set with * MBEDTLS_SSL_MAX_EARLY_DATA_SIZE. * */ //#define MBEDTLS_SSL_EARLY_DATA /** * \def MBEDTLS_SSL_PROTO_DTLS * * Enable support for DTLS (all available versions). * * Enable this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2. * * Requires: MBEDTLS_SSL_PROTO_TLS1_2 * * Comment this macro to disable support for DTLS */ #define MBEDTLS_SSL_PROTO_DTLS /** * \def MBEDTLS_SSL_ALPN * * Enable support for RFC 7301 Application Layer Protocol Negotiation. * * Comment this macro to disable support for ALPN. */ #define MBEDTLS_SSL_ALPN /** * \def MBEDTLS_SSL_DTLS_ANTI_REPLAY * * Enable support for the anti-replay mechanism in DTLS. * * Requires: MBEDTLS_SSL_TLS_C * MBEDTLS_SSL_PROTO_DTLS * * \warning Disabling this is often a security risk! * See mbedtls_ssl_conf_dtls_anti_replay() for details. * * Comment this to disable anti-replay in DTLS. */ #define MBEDTLS_SSL_DTLS_ANTI_REPLAY /** * \def MBEDTLS_SSL_DTLS_HELLO_VERIFY * * Enable support for HelloVerifyRequest on DTLS servers. * * This feature is highly recommended to prevent DTLS servers being used as * amplifiers in DoS attacks against other hosts. It should always be enabled * unless you know for sure amplification cannot be a problem in the * environment in which your server operates. * * \warning Disabling this can be a security risk! (see above) * * Requires: MBEDTLS_SSL_PROTO_DTLS * * Comment this to disable support for HelloVerifyRequest. */ #define MBEDTLS_SSL_DTLS_HELLO_VERIFY /** * \def MBEDTLS_SSL_DTLS_SRTP * * Enable support for negotiation of DTLS-SRTP (RFC 5764) * through the use_srtp extension. * * \note This feature provides the minimum functionality required * to negotiate the use of DTLS-SRTP and to allow the derivation of * the associated SRTP packet protection key material. * In particular, the SRTP packet protection itself, as well as the * demultiplexing of RTP and DTLS packets at the datagram layer * (see Section 5 of RFC 5764), are not handled by this feature. * Instead, after successful completion of a handshake negotiating * the use of DTLS-SRTP, the extended key exporter API * mbedtls_ssl_conf_export_keys_cb() should be used to implement * the key exporter described in Section 4.2 of RFC 5764 and RFC 5705 * (this is implemented in the SSL example programs). * The resulting key should then be passed to an SRTP stack. * * Setting this option enables the runtime API * mbedtls_ssl_conf_dtls_srtp_protection_profiles() * through which the supported DTLS-SRTP protection * profiles can be configured. You must call this API at * runtime if you wish to negotiate the use of DTLS-SRTP. * * Requires: MBEDTLS_SSL_PROTO_DTLS * * Uncomment this to enable support for use_srtp extension. */ //#define MBEDTLS_SSL_DTLS_SRTP /** * \def MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE * * Enable server-side support for clients that reconnect from the same port. * * Some clients unexpectedly close the connection and try to reconnect using the * same source port. This needs special support from the server to handle the * new connection securely, as described in section 4.2.8 of RFC 6347. This * flag enables that support. * * Requires: MBEDTLS_SSL_DTLS_HELLO_VERIFY * * Comment this to disable support for clients reusing the source port. */ #define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE /** * \def MBEDTLS_SSL_SESSION_TICKETS * * Enable support for RFC 5077 session tickets in SSL. * Client-side, provides full support for session tickets (maintenance of a * session store remains the responsibility of the application, though). * Server-side, you also need to provide callbacks for writing and parsing * tickets, including authenticated encryption and key management. Example * callbacks are provided by MBEDTLS_SSL_TICKET_C. * * Comment this macro to disable support for SSL session tickets */ #define MBEDTLS_SSL_SESSION_TICKETS /** * \def MBEDTLS_SSL_SERVER_NAME_INDICATION * * Enable support for RFC 6066 server name indication (SNI) in SSL. * * Requires: MBEDTLS_X509_CRT_PARSE_C * * Comment this macro to disable support for server name indication in SSL */ #define MBEDTLS_SSL_SERVER_NAME_INDICATION /** * \def MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH * * When this option is enabled, the SSL buffer will be resized automatically * based on the negotiated maximum fragment length in each direction. * * Requires: MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ //#define MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH /** * \def MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN * * Enable testing of the constant-flow nature of some sensitive functions with * clang's MemorySanitizer. This causes some existing tests to also test * this non-functional property of the code under test. * * This setting requires compiling with clang -fsanitize=memory. The test * suites can then be run normally. * * \warning This macro is only used for extended testing; it is not considered * part of the library's API, so it may change or disappear at any time. * * Uncomment to enable testing of the constant-flow nature of selected code. */ //#define MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN /** * \def MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND * * Enable testing of the constant-flow nature of some sensitive functions with * valgrind's memcheck tool. This causes some existing tests to also test * this non-functional property of the code under test. * * This setting requires valgrind headers for building, and is only useful for * testing if the tests suites are run with valgrind's memcheck. This can be * done for an individual test suite with 'valgrind ./test_suite_xxx', or when * using CMake, this can be done for all test suites with 'make memcheck'. * * \warning This macro is only used for extended testing; it is not considered * part of the library's API, so it may change or disappear at any time. * * Uncomment to enable testing of the constant-flow nature of selected code. */ //#define MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND /** * \def MBEDTLS_TEST_HOOKS * * Enable features for invasive testing such as introspection functions and * hooks for fault injection. This enables additional unit tests. * * Merely enabling this feature should not change the behavior of the product. * It only adds new code, and new branching points where the default behavior * is the same as when this feature is disabled. * However, this feature increases the attack surface: there is an added * risk of vulnerabilities, and more gadgets that can make exploits easier. * Therefore this feature must never be enabled in production. * * See `docs/architecture/testing/mbed-crypto-invasive-testing.md` for more * information. * * Uncomment to enable invasive tests. */ //#define MBEDTLS_TEST_HOOKS /** * \def MBEDTLS_THREADING_ALT * * Provide your own alternate threading implementation. * * Requires: MBEDTLS_THREADING_C * * Uncomment this to allow your own alternate threading implementation. */ //#define MBEDTLS_THREADING_ALT /** * \def MBEDTLS_THREADING_PTHREAD * * Enable the pthread wrapper layer for the threading layer. * * Requires: MBEDTLS_THREADING_C * * Uncomment this to enable pthread mutexes. */ //#define MBEDTLS_THREADING_PTHREAD /** * \def MBEDTLS_USE_PSA_CRYPTO * * Make the X.509 and TLS libraries use PSA for cryptographic operations as * much as possible, and enable new APIs for using keys handled by PSA Crypto. * * \note Development of this option is currently in progress, and parts of Mbed * TLS's X.509 and TLS modules are not ported to PSA yet. However, these parts * will still continue to work as usual, so enabling this option should not * break backwards compatibility. * * \warning If you enable this option, you need to call `psa_crypto_init()` * before calling any function from the SSL/TLS, X.509 or PK modules, except * for the various mbedtls_xxx_init() functions which can be called at any time. * * \warning In multithreaded applications, you must also enable * #MBEDTLS_THREADING_C, unless only one thread ever calls PSA functions * (`psa_xxx()`), including indirect calls through SSL/TLS, X.509 or PK. * * \note An important and desirable effect of this option is that it allows * PK, X.509 and TLS to take advantage of PSA drivers. For example, enabling * this option is what allows use of drivers for ECDSA, ECDH and EC J-PAKE in * those modules. However, note that even with this option disabled, some code * in PK, X.509, TLS or the crypto library might still use PSA drivers, if it * can determine it's safe to do so; currently that's the case for hashes. * * \note See docs/use-psa-crypto.md for a complete description this option. * * Requires: MBEDTLS_PSA_CRYPTO_C. * * Uncomment this to enable internal use of PSA Crypto and new associated APIs. */ //#define MBEDTLS_USE_PSA_CRYPTO /** * \def MBEDTLS_PSA_CRYPTO_CONFIG * * This setting allows support for cryptographic mechanisms through the PSA * API to be configured separately from support through the mbedtls API. * * When this option is disabled, the PSA API exposes the cryptographic * mechanisms that can be implemented on top of the `mbedtls_xxx` API * configured with `MBEDTLS_XXX` symbols. * * When this option is enabled, the PSA API exposes the cryptographic * mechanisms requested by the `PSA_WANT_XXX` symbols defined in * include/psa/crypto_config.h. The corresponding `MBEDTLS_XXX` settings are * automatically enabled if required (i.e. if no PSA driver provides the * mechanism). You may still freely enable additional `MBEDTLS_XXX` symbols * in mbedtls_config.h. * * If the symbol #MBEDTLS_PSA_CRYPTO_CONFIG_FILE is defined, it specifies * an alternative header to include instead of include/psa/crypto_config.h. * * \warning This option is experimental, in that the set of `PSA_WANT_XXX` * symbols is not completely finalized yet, and the configuration * tooling is not ideally adapted to having two separate configuration * files. * Future minor releases of Mbed TLS may make minor changes to those * symbols, but we will endeavor to provide a transition path. * Nonetheless, this option is considered mature enough to use in * production, as long as you accept that you may need to make * minor changes to psa/crypto_config.h when upgrading Mbed TLS. */ //#define MBEDTLS_PSA_CRYPTO_CONFIG /** * \def MBEDTLS_VERSION_FEATURES * * Allow run-time checking of compile-time enabled features. Thus allowing users * to check at run-time if the library is for instance compiled with threading * support via mbedtls_version_check_feature(). * * Requires: MBEDTLS_VERSION_C * * Comment this to disable run-time checking and save ROM space */ #define MBEDTLS_VERSION_FEATURES /** * \def MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK * * If set, this enables the X.509 API `mbedtls_x509_crt_verify_with_ca_cb()` * and the SSL API `mbedtls_ssl_conf_ca_cb()` which allow users to configure * the set of trusted certificates through a callback instead of a linked * list. * * This is useful for example in environments where a large number of trusted * certificates is present and storing them in a linked list isn't efficient * enough, or when the set of trusted certificates changes frequently. * * See the documentation of `mbedtls_x509_crt_verify_with_ca_cb()` and * `mbedtls_ssl_conf_ca_cb()` for more information. * * Requires: MBEDTLS_X509_CRT_PARSE_C * * Uncomment to enable trusted certificate callbacks. */ //#define MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK /** * \def MBEDTLS_X509_REMOVE_INFO * * Disable mbedtls_x509_*_info() and related APIs. * * Uncomment to omit mbedtls_x509_*_info(), as well as mbedtls_debug_print_crt() * and other functions/constants only used by these functions, thus reducing * the code footprint by several KB. */ //#define MBEDTLS_X509_REMOVE_INFO /** * \def MBEDTLS_X509_RSASSA_PSS_SUPPORT * * Enable parsing and verification of X.509 certificates, CRLs and CSRS * signed with RSASSA-PSS (aka PKCS#1 v2.1). * * Requires: MBEDTLS_PKCS1_V21 * * Comment this macro to disallow using RSASSA-PSS in certificates. */ #define MBEDTLS_X509_RSASSA_PSS_SUPPORT /** \} name SECTION: Mbed TLS feature support */ /** * \name SECTION: Mbed TLS modules * * This section enables or disables entire modules in Mbed TLS * \{ */ /** * \def MBEDTLS_AESNI_C * * Enable AES-NI support on x86-64 or x86-32. * * \note AESNI is only supported with certain compilers and target options: * - Visual Studio: supported * - GCC, x86-64, target not explicitly supporting AESNI: * requires MBEDTLS_HAVE_ASM. * - GCC, x86-32, target not explicitly supporting AESNI: * not supported. * - GCC, x86-64 or x86-32, target supporting AESNI: supported. * For this assembly-less implementation, you must currently compile * `library/aesni.c` and `library/aes.c` with machine options to enable * SSE2 and AESNI instructions: `gcc -msse2 -maes -mpclmul` or * `clang -maes -mpclmul`. * - Non-x86 targets: this option is silently ignored. * - Other compilers: this option is silently ignored. * * \note * Above, "GCC" includes compatible compilers such as Clang. * The limitations on target support are likely to be relaxed in the future. * * Module: library/aesni.c * Caller: library/aes.c * * Requires: MBEDTLS_HAVE_ASM (on some platforms, see note) * * This modules adds support for the AES-NI instructions on x86. */ #define MBEDTLS_AESNI_C /** * \def MBEDTLS_AESCE_C * * Enable AES cryptographic extension support on Armv8. * * Module: library/aesce.c * Caller: library/aes.c * * Requires: MBEDTLS_AES_C * * \warning Runtime detection only works on Linux. For non-Linux operating * system, Armv8-A Cryptographic Extensions must be supported by * the CPU when this option is enabled. * * \note Minimum compiler versions for this feature when targeting aarch64 * are Clang 4.0; armclang 6.6; GCC 6.0; or MSVC 2019 version 16.11.2. * Minimum compiler versions for this feature when targeting 32-bit * Arm or Thumb are Clang 11.0; armclang 6.20; or GCC 6.0. * * \note \c CFLAGS must be set to a minimum of \c -march=armv8-a+crypto for * armclang <= 6.9 * * This module adds support for the AES Armv8-A Cryptographic Extensions on Armv8 systems. */ #define MBEDTLS_AESCE_C /** * \def MBEDTLS_AES_C * * Enable the AES block cipher. * * Module: library/aes.c * Caller: library/cipher.c * library/pem.c * library/ctr_drbg.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA * * PEM_PARSE uses AES for decrypting encrypted keys. */ //#define MBEDTLS_AES_C 1 /** * \def MBEDTLS_ASN1_PARSE_C * * Enable the generic ASN1 parser. * * Module: library/asn1.c * Caller: library/x509.c * library/dhm.c * library/pkcs12.c * library/pkcs5.c * library/pkparse.c */ #define MBEDTLS_ASN1_PARSE_C /** * \def MBEDTLS_ASN1_WRITE_C * * Enable the generic ASN1 writer. * * Module: library/asn1write.c * Caller: library/ecdsa.c * library/pkwrite.c * library/x509_create.c * library/x509write_crt.c * library/x509write_csr.c */ #define MBEDTLS_ASN1_WRITE_C /** * \def MBEDTLS_BASE64_C * * Enable the Base64 module. * * Module: library/base64.c * Caller: library/pem.c * * This module is required for PEM support (required by X.509). */ #define MBEDTLS_BASE64_C /** * \def MBEDTLS_BLOCK_CIPHER_NO_DECRYPT * * Remove decryption operation for AES, ARIA and Camellia block cipher. * * \note This feature is incompatible with insecure block cipher, * MBEDTLS_DES_C, and cipher modes which always require decryption * operation, MBEDTLS_CIPHER_MODE_CBC, MBEDTLS_CIPHER_MODE_XTS and * MBEDTLS_NIST_KW_C. When #MBEDTLS_PSA_CRYPTO_CONFIG is enabled, * this feature is incompatible with following supported PSA equivalence, * PSA_WANT_ALG_ECB_NO_PADDING, PSA_WANT_ALG_CBC_NO_PADDING, * PSA_WANT_ALG_CBC_PKCS7 and PSA_WANT_KEY_TYPE_DES. * * Module: library/aes.c * library/aesce.c * library/aesni.c * library/aria.c * library/camellia.c * library/cipher.c */ //#define MBEDTLS_BLOCK_CIPHER_NO_DECRYPT /** * \def MBEDTLS_BIGNUM_C * * Enable the multi-precision integer library. * * Module: library/bignum.c * library/bignum_core.c * library/bignum_mod.c * library/bignum_mod_raw.c * Caller: library/dhm.c * library/ecp.c * library/ecdsa.c * library/rsa.c * library/rsa_alt_helpers.c * library/ssl_tls.c * * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support. */ #define MBEDTLS_BIGNUM_C /** * \def MBEDTLS_CAMELLIA_C * * Enable the Camellia block cipher. * * Module: library/camellia.c * Caller: library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 */ #define MBEDTLS_CAMELLIA_C /** * \def MBEDTLS_ARIA_C * * Enable the ARIA block cipher. * * Module: library/aria.c * Caller: library/cipher.c * * This module enables the following ciphersuites (if other requisites are * enabled as well): * * MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 * MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 * MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 * MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 * MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 * MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 */ #define MBEDTLS_ARIA_C /** * \def MBEDTLS_CCM_C * * Enable the Counter with CBC-MAC (CCM) mode for 128-bit block cipher. * * Module: library/ccm.c * * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C or * MBEDTLS_ARIA_C * * This module enables the AES-CCM ciphersuites, if other requisites are * enabled as well. */ #define MBEDTLS_CCM_C /** * \def MBEDTLS_CHACHA20_C * * Enable the ChaCha20 stream cipher. * * Module: library/chacha20.c */ #define MBEDTLS_CHACHA20_C /** * \def MBEDTLS_CHACHAPOLY_C * * Enable the ChaCha20-Poly1305 AEAD algorithm. * * Module: library/chachapoly.c * * This module requires: MBEDTLS_CHACHA20_C, MBEDTLS_POLY1305_C */ #define MBEDTLS_CHACHAPOLY_C /** * \def MBEDTLS_CIPHER_C * * Enable the generic cipher layer. * * Module: library/cipher.c * Caller: library/ccm.c * library/cmac.c * library/gcm.c * library/nist_kw.c * library/pkcs12.c * library/pkcs5.c * library/psa_crypto_aead.c * library/psa_crypto_mac.c * library/ssl_ciphersuites.c * library/ssl_msg.c * library/ssl_ticket.c (unless MBEDTLS_USE_PSA_CRYPTO is enabled) * Auto-enabled by: MBEDTLS_PSA_CRYPTO_C depending on which ciphers are enabled * (see the documentation of that option for details). * * Uncomment to enable generic cipher wrappers. */ #define MBEDTLS_CIPHER_C /** * \def MBEDTLS_CMAC_C * * Enable the CMAC (Cipher-based Message Authentication Code) mode for block * ciphers. * * \note When #MBEDTLS_CMAC_ALT is active, meaning that the underlying * implementation of the CMAC algorithm is provided by an alternate * implementation, that alternate implementation may opt to not support * AES-192 or 3DES as underlying block ciphers for the CMAC operation. * * Module: library/cmac.c * * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_DES_C * */ #define MBEDTLS_CMAC_C /** * \def MBEDTLS_CTR_DRBG_C * * Enable the CTR_DRBG AES-based random generator. * The CTR_DRBG generator uses AES-256 by default. * To use AES-128 instead, enable \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY above. * * AES support can either be achieved through builtin (MBEDTLS_AES_C) or PSA. * Builtin is the default option when MBEDTLS_AES_C is defined otherwise PSA * is used. * * \warning When using PSA, the user should call `psa_crypto_init()` before * using any CTR_DRBG operation (except `mbedtls_ctr_drbg_init()`). * * \note AES-128 will be used if \c MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH is set. * * \note To achieve a 256-bit security strength with CTR_DRBG, * you must use AES-256 *and* use sufficient entropy. * See ctr_drbg.h for more details. * * Module: library/ctr_drbg.c * Caller: * * Requires: MBEDTLS_AES_C or * (PSA_WANT_KEY_TYPE_AES and PSA_WANT_ALG_ECB_NO_PADDING and * MBEDTLS_PSA_CRYPTO_C) * * This module provides the CTR_DRBG AES random number generator. */ #define MBEDTLS_CTR_DRBG_C /** * \def MBEDTLS_DEBUG_C * * Enable the debug functions. * * Module: library/debug.c * Caller: library/ssl_msg.c * library/ssl_tls.c * library/ssl_tls12_*.c * library/ssl_tls13_*.c * * This module provides debugging functions. */ #define MBEDTLS_DEBUG_C /** * \def MBEDTLS_DES_C * * Enable the DES block cipher. * * Module: library/des.c * Caller: library/pem.c * library/cipher.c * * PEM_PARSE uses DES/3DES for decrypting encrypted keys. * * \warning DES/3DES are considered weak ciphers and their use constitutes a * security risk. We recommend considering stronger ciphers instead. */ #define MBEDTLS_DES_C /** * \def MBEDTLS_DHM_C * * Enable the Diffie-Hellman-Merkle module. * * Module: library/dhm.c * Caller: library/ssl_tls.c * library/ssl*_client.c * library/ssl*_server.c * * This module is used by the following key exchanges: * DHE-RSA, DHE-PSK * * \warning Using DHE constitutes a security risk as it * is not possible to validate custom DH parameters. * If possible, it is recommended users should consider * preferring other methods of key exchange. * See dhm.h for more details. * */ #define MBEDTLS_DHM_C /** * \def MBEDTLS_ECDH_C * * Enable the elliptic curve Diffie-Hellman library. * * Module: library/ecdh.c * Caller: library/psa_crypto.c * library/ssl_tls.c * library/ssl*_client.c * library/ssl*_server.c * * This module is used by the following key exchanges: * ECDHE-ECDSA, ECDHE-RSA, DHE-PSK * * Requires: MBEDTLS_ECP_C */ #define MBEDTLS_ECDH_C /** * \def MBEDTLS_ECDSA_C * * Enable the elliptic curve DSA library. * * Module: library/ecdsa.c * Caller: * * This module is used by the following key exchanges: * ECDHE-ECDSA * * Requires: MBEDTLS_ECP_C, MBEDTLS_ASN1_WRITE_C, MBEDTLS_ASN1_PARSE_C, * and at least one MBEDTLS_ECP_DP_XXX_ENABLED for a * short Weierstrass curve. */ #define MBEDTLS_ECDSA_C /** * \def MBEDTLS_ECJPAKE_C * * Enable the elliptic curve J-PAKE library. * * \note EC J-PAKE support is based on the Thread v1.0.0 specification. * It has not been reviewed for compliance with newer standards such as * Thread v1.1 or RFC 8236. * * Module: library/ecjpake.c * Caller: * * This module is used by the following key exchanges: * ECJPAKE * * Requires: MBEDTLS_ECP_C and either MBEDTLS_MD_C or MBEDTLS_PSA_CRYPTO_C * * \warning If using a hash that is only provided by PSA drivers, you must * call psa_crypto_init() before doing any EC J-PAKE operations. */ #define MBEDTLS_ECJPAKE_C /** * \def MBEDTLS_ECP_C * * Enable the elliptic curve over GF(p) library. * * Module: library/ecp.c * Caller: library/ecdh.c * library/ecdsa.c * library/ecjpake.c * * Requires: MBEDTLS_BIGNUM_C and at least one MBEDTLS_ECP_DP_XXX_ENABLED */ #define MBEDTLS_ECP_C /** * \def MBEDTLS_ENTROPY_C * * Enable the platform-specific entropy code. * * Module: library/entropy.c * Caller: * * Requires: MBEDTLS_SHA512_C or MBEDTLS_SHA256_C * * This module provides a generic entropy pool */ #define MBEDTLS_ENTROPY_C /** * \def MBEDTLS_ERROR_C * * Enable error code to error string conversion. * * Module: library/error.c * Caller: * * This module enables mbedtls_strerror(). */ #define MBEDTLS_ERROR_C /** * \def MBEDTLS_GCM_C * * Enable the Galois/Counter Mode (GCM). * * Module: library/gcm.c * * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C or * MBEDTLS_ARIA_C * * This module enables the AES-GCM and CAMELLIA-GCM ciphersuites, if other * requisites are enabled as well. */ #define MBEDTLS_GCM_C /** * \def MBEDTLS_GCM_LARGE_TABLE * * Enable large pre-computed tables for Galois/Counter Mode (GCM). * Can significantly increase throughput on systems without GCM hardware * acceleration (e.g., AESNI, AESCE). * * The mbedtls_gcm_context size will increase by 3840 bytes. * The code size will increase by roughly 344 bytes. * * Module: library/gcm.c * * Requires: MBEDTLS_GCM_C */ //#define MBEDTLS_GCM_LARGE_TABLE /** * \def MBEDTLS_HKDF_C * * Enable the HKDF algorithm (RFC 5869). * * Module: library/hkdf.c * Caller: * * Requires: MBEDTLS_MD_C * * This module adds support for the Hashed Message Authentication Code * (HMAC)-based key derivation function (HKDF). */ #define MBEDTLS_HKDF_C /** * \def MBEDTLS_HMAC_DRBG_C * * Enable the HMAC_DRBG random generator. * * Module: library/hmac_drbg.c * Caller: * * Requires: MBEDTLS_MD_C * * Uncomment to enable the HMAC_DRBG random number generator. */ #define MBEDTLS_HMAC_DRBG_C /** * \def MBEDTLS_LMS_C * * Enable the LMS stateful-hash asymmetric signature algorithm. * * Module: library/lms.c * Caller: * * Requires: MBEDTLS_PSA_CRYPTO_C * * Uncomment to enable the LMS verification algorithm and public key operations. */ #define MBEDTLS_LMS_C /** * \def MBEDTLS_LMS_PRIVATE * * Enable LMS private-key operations and signing code. Functions enabled by this * option are experimental, and should not be used in production. * * Requires: MBEDTLS_LMS_C * * Uncomment to enable the LMS signature algorithm and private key operations. */ //#define MBEDTLS_LMS_PRIVATE /** * \def MBEDTLS_NIST_KW_C * * Enable the Key Wrapping mode for 128-bit block ciphers, * as defined in NIST SP 800-38F. Only KW and KWP modes * are supported. At the moment, only AES is approved by NIST. * * Module: library/nist_kw.c * * Requires: MBEDTLS_AES_C and MBEDTLS_CIPHER_C */ #define MBEDTLS_NIST_KW_C /** * \def MBEDTLS_MD_C * * Enable the generic layer for message digest (hashing) and HMAC. * * Requires: one of: MBEDTLS_MD5_C, MBEDTLS_RIPEMD160_C, MBEDTLS_SHA1_C, * MBEDTLS_SHA224_C, MBEDTLS_SHA256_C, MBEDTLS_SHA384_C, * MBEDTLS_SHA512_C, or MBEDTLS_PSA_CRYPTO_C with at least * one hash. * Module: library/md.c * Caller: library/constant_time.c * library/ecdsa.c * library/ecjpake.c * library/hkdf.c * library/hmac_drbg.c * library/pk.c * library/pkcs5.c * library/pkcs12.c * library/psa_crypto_ecp.c * library/psa_crypto_rsa.c * library/rsa.c * library/ssl_cookie.c * library/ssl_msg.c * library/ssl_tls.c * library/x509.c * library/x509_crt.c * library/x509write_crt.c * library/x509write_csr.c * * Uncomment to enable generic message digest wrappers. */ #define MBEDTLS_MD_C /** * \def MBEDTLS_MD5_C * * Enable the MD5 hash algorithm. * * Module: library/md5.c * Caller: library/md.c * library/pem.c * library/ssl_tls.c * * This module is required for TLS 1.2 depending on the handshake parameters. * Further, it is used for checking MD5-signed certificates, and for PBKDF1 * when decrypting PEM-encoded encrypted keys. * * \warning MD5 is considered a weak message digest and its use constitutes a * security risk. If possible, we recommend avoiding dependencies on * it, and considering stronger message digests instead. * */ #define MBEDTLS_MD5_C /** * \def MBEDTLS_MEMORY_BUFFER_ALLOC_C * * Enable the buffer allocator implementation that makes use of a (stack) * based buffer to 'allocate' dynamic memory. (replaces calloc() and free() * calls) * * Module: library/memory_buffer_alloc.c * * Requires: MBEDTLS_PLATFORM_C * MBEDTLS_PLATFORM_MEMORY (to use it within Mbed TLS) * * Enable this module to enable the buffer memory allocator. */ //#define MBEDTLS_MEMORY_BUFFER_ALLOC_C /** * \def MBEDTLS_NET_C * * Enable the TCP and UDP over IPv6/IPv4 networking routines. * * \note This module only works on POSIX/Unix (including Linux, BSD and OS X) * and Windows. For other platforms, you'll want to disable it, and write your * own networking callbacks to be passed to \c mbedtls_ssl_set_bio(). * * \note See also our Knowledge Base article about porting to a new * environment: * https://mbed-tls.readthedocs.io/en/latest/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS * * Module: library/net_sockets.c * * This module provides networking routines. */ #define MBEDTLS_NET_C /** * \def MBEDTLS_OID_C * * Enable the OID database. * * Module: library/oid.c * Caller: library/asn1write.c * library/pkcs5.c * library/pkparse.c * library/pkwrite.c * library/rsa.c * library/x509.c * library/x509_create.c * library/x509_crl.c * library/x509_crt.c * library/x509_csr.c * library/x509write_crt.c * library/x509write_csr.c * * This modules translates between OIDs and internal values. */ #define MBEDTLS_OID_C /** * \def MBEDTLS_PADLOCK_C * * Enable VIA Padlock support on x86. * * Module: library/padlock.c * Caller: library/aes.c * * Requires: MBEDTLS_HAVE_ASM * * This modules adds support for the VIA PadLock on x86. */ #define MBEDTLS_PADLOCK_C /** * \def MBEDTLS_PEM_PARSE_C * * Enable PEM decoding / parsing. * * Module: library/pem.c * Caller: library/dhm.c * library/pkparse.c * library/x509_crl.c * library/x509_crt.c * library/x509_csr.c * * Requires: MBEDTLS_BASE64_C * optionally MBEDTLS_MD5_C, or PSA Crypto with MD5 (see below) * * \warning When parsing password-protected files, if MD5 is provided only by * a PSA driver, you must call psa_crypto_init() before the first file. * * This modules adds support for decoding / parsing PEM files. */ #define MBEDTLS_PEM_PARSE_C /** * \def MBEDTLS_PEM_WRITE_C * * Enable PEM encoding / writing. * * Module: library/pem.c * Caller: library/pkwrite.c * library/x509write_crt.c * library/x509write_csr.c * * Requires: MBEDTLS_BASE64_C * * This modules adds support for encoding / writing PEM files. */ #define MBEDTLS_PEM_WRITE_C /** * \def MBEDTLS_PK_C * * Enable the generic public (asymmetric) key layer. * * Module: library/pk.c * Caller: library/psa_crypto_rsa.c * library/ssl_tls.c * library/ssl*_client.c * library/ssl*_server.c * library/x509.c * * Requires: MBEDTLS_MD_C, MBEDTLS_RSA_C or MBEDTLS_ECP_C * * Uncomment to enable generic public key wrappers. */ #define MBEDTLS_PK_C /** * \def MBEDTLS_PK_PARSE_C * * Enable the generic public (asymmetric) key parser. * * Module: library/pkparse.c * Caller: library/x509_crt.c * library/x509_csr.c * * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_OID_C, MBEDTLS_PK_C * * Uncomment to enable generic public key parse functions. */ #define MBEDTLS_PK_PARSE_C /** * \def MBEDTLS_PK_WRITE_C * * Enable the generic public (asymmetric) key writer. * * Module: library/pkwrite.c * Caller: library/x509write.c * * Requires: MBEDTLS_ASN1_WRITE_C, MBEDTLS_OID_C, MBEDTLS_PK_C * * Uncomment to enable generic public key write functions. */ #define MBEDTLS_PK_WRITE_C /** * \def MBEDTLS_PKCS5_C * * Enable PKCS#5 functions. * * Module: library/pkcs5.c * * Auto-enables: MBEDTLS_MD_C * * \warning If using a hash that is only provided by PSA drivers, you must * call psa_crypto_init() before doing any PKCS5 operations. * * This module adds support for the PKCS#5 functions. */ #define MBEDTLS_PKCS5_C /** * \def MBEDTLS_PKCS7_C * * Enable PKCS #7 core for using PKCS #7-formatted signatures. * RFC Link - https://tools.ietf.org/html/rfc2315 * * Module: library/pkcs7.c * * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_OID_C, MBEDTLS_PK_PARSE_C, * MBEDTLS_X509_CRT_PARSE_C MBEDTLS_X509_CRL_PARSE_C, * MBEDTLS_BIGNUM_C, MBEDTLS_MD_C * * This module is required for the PKCS #7 parsing modules. */ #define MBEDTLS_PKCS7_C /** * \def MBEDTLS_PKCS12_C * * Enable PKCS#12 PBE functions. * Adds algorithms for parsing PKCS#8 encrypted private keys * * Module: library/pkcs12.c * Caller: library/pkparse.c * * Requires: MBEDTLS_ASN1_PARSE_C and either MBEDTLS_MD_C or * MBEDTLS_PSA_CRYPTO_C. * * \warning If using a hash that is only provided by PSA drivers, you must * call psa_crypto_init() before doing any PKCS12 operations. * * This module enables PKCS#12 functions. */ #define MBEDTLS_PKCS12_C /** * \def MBEDTLS_PLATFORM_C * * Enable the platform abstraction layer that allows you to re-assign * functions like calloc(), free(), snprintf(), printf(), fprintf(), exit(). * * Enabling MBEDTLS_PLATFORM_C enables to use of MBEDTLS_PLATFORM_XXX_ALT * or MBEDTLS_PLATFORM_XXX_MACRO directives, allowing the functions mentioned * above to be specified at runtime or compile time respectively. * * \note This abstraction layer must be enabled on Windows (including MSYS2) * as other modules rely on it for a fixed snprintf implementation. * * Module: library/platform.c * Caller: Most other .c files * * This module enables abstraction of common (libc) functions. */ #define MBEDTLS_PLATFORM_C /** * \def MBEDTLS_POLY1305_C * * Enable the Poly1305 MAC algorithm. * * Module: library/poly1305.c * Caller: library/chachapoly.c */ #define MBEDTLS_POLY1305_C /** * \def MBEDTLS_PSA_CRYPTO_C * * Enable the Platform Security Architecture (PSA) cryptography API. * * \note In multithreaded applications, you must enable #MBEDTLS_THREADING_C, * unless only one thread ever calls `psa_xxx()` functions. * That includes indirect calls, such as: * - performing a TLS handshake if support for TLS 1.3 is enabled; * - using a TLS 1.3 connection; * - indirect calls from PK, X.509 or SSL functions when * #MBEDTLS_USE_PSA_CRYPTO is enabled; * - indirect calls to calculate a hash when #MBEDTLS_MD_C is disabled; * - any other call to a function that requires calling psa_crypto_init() * beforehand. * * Module: library/psa_crypto.c * * Requires: either MBEDTLS_CTR_DRBG_C and MBEDTLS_ENTROPY_C, * or MBEDTLS_HMAC_DRBG_C and MBEDTLS_ENTROPY_C, * or MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG. * Auto-enables: MBEDTLS_CIPHER_C if any unauthenticated (ie, non-AEAD) cipher * is enabled in PSA (unless it's fully accelerated, see * docs/driver-only-builds.md about that). */ #define MBEDTLS_PSA_CRYPTO_C /** * \def MBEDTLS_PSA_CRYPTO_SE_C * * Enable dynamic secure element support in the Platform Security Architecture * cryptography API. * * \deprecated This feature is deprecated. Please switch to the PSA driver * interface. * * \warning This feature is not thread-safe, and should not be used in a * multi-threaded environment. * * Module: library/psa_crypto_se.c * * Requires: MBEDTLS_PSA_CRYPTO_C, MBEDTLS_PSA_CRYPTO_STORAGE_C * */ //#define MBEDTLS_PSA_CRYPTO_SE_C /** * \def MBEDTLS_PSA_CRYPTO_STORAGE_C * * Enable the Platform Security Architecture persistent key storage. * * Module: library/psa_crypto_storage.c * * Requires: MBEDTLS_PSA_CRYPTO_C, * either MBEDTLS_PSA_ITS_FILE_C or a native implementation of * the PSA ITS interface */ #define MBEDTLS_PSA_CRYPTO_STORAGE_C /** * \def MBEDTLS_PSA_ITS_FILE_C * * Enable the emulation of the Platform Security Architecture * Internal Trusted Storage (PSA ITS) over files. * * Module: library/psa_its_file.c * * Requires: MBEDTLS_FS_IO */ #define MBEDTLS_PSA_ITS_FILE_C /** * \def MBEDTLS_PSA_STATIC_KEY_SLOTS * * Statically preallocate memory to store keys' material in PSA instead * of allocating it dynamically when required. This allows builds without a * heap, if none of the enabled cryptographic implementations or other features * require it. * This feature affects both volatile and persistent keys which means that * it's not possible to persistently store a key which is larger than * #MBEDTLS_PSA_STATIC_KEY_SLOT_BUFFER_SIZE. * * \note This feature comes with a (potentially) higher RAM usage since: * - All the key slots are allocated no matter if they are used or not. * - Each key buffer's length is #MBEDTLS_PSA_STATIC_KEY_SLOT_BUFFER_SIZE bytes. * * Requires: MBEDTLS_PSA_CRYPTO_C * */ //#define MBEDTLS_PSA_STATIC_KEY_SLOTS /** * \def MBEDTLS_RIPEMD160_C * * Enable the RIPEMD-160 hash algorithm. * * Module: library/ripemd160.c * Caller: library/md.c * */ #define MBEDTLS_RIPEMD160_C /** * \def MBEDTLS_RSA_C * * Enable the RSA public-key cryptosystem. * * Module: library/rsa.c * library/rsa_alt_helpers.c * Caller: library/pk.c * library/psa_crypto.c * library/ssl_tls.c * library/ssl*_client.c * library/ssl*_server.c * * This module is used by the following key exchanges: * RSA, DHE-RSA, ECDHE-RSA, RSA-PSK * * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C */ #define MBEDTLS_RSA_C /** * \def MBEDTLS_SHA1_C * * Enable the SHA1 cryptographic hash algorithm. * * Module: library/sha1.c * Caller: library/md.c * library/psa_crypto_hash.c * * This module is required for TLS 1.2 depending on the handshake parameters, * and for SHA1-signed certificates. * * \warning SHA-1 is considered a weak message digest and its use constitutes * a security risk. If possible, we recommend avoiding dependencies * on it, and considering stronger message digests instead. * */ #define MBEDTLS_SHA1_C /** * \def MBEDTLS_SHA224_C * * Enable the SHA-224 cryptographic hash algorithm. * * Module: library/sha256.c * Caller: library/md.c * library/ssl_cookie.c * * This module adds support for SHA-224. */ #define MBEDTLS_SHA224_C /** * \def MBEDTLS_SHA256_C * * Enable the SHA-256 cryptographic hash algorithm. * * Module: library/sha256.c * Caller: library/entropy.c * library/md.c * library/ssl_tls.c * library/ssl*_client.c * library/ssl*_server.c * * This module adds support for SHA-256. * This module is required for the SSL/TLS 1.2 PRF function. */ #define MBEDTLS_SHA256_C /** * \def MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT * * Enable acceleration of the SHA-256 and SHA-224 cryptographic hash algorithms * with the ARMv8 cryptographic extensions if they are available at runtime. * If not, the library will fall back to the C implementation. * * \note If MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT is defined when building * for a non-Armv8-A build it will be silently ignored. * * \note Minimum compiler versions for this feature are Clang 4.0, * armclang 6.6 or GCC 6.0. * * \note \c CFLAGS must be set to a minimum of \c -march=armv8-a+crypto for * armclang <= 6.9 * * \note This was previously known as MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT. * That name is deprecated, but may still be used as an alternative form for this * option. * * \warning MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT cannot be defined at the * same time as MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY. * * Requires: MBEDTLS_SHA256_C. * * Module: library/sha256.c * * Uncomment to have the library check for the Armv8-A SHA-256 crypto extensions * and use them if available. */ //#define MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT /** * \def MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT * * \deprecated This is now known as MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT. * This name is now deprecated, but may still be used as an alternative form for * this option. */ //#define MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT /** * \def MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY * * Enable acceleration of the SHA-256 and SHA-224 cryptographic hash algorithms * with the ARMv8 cryptographic extensions, which must be available at runtime * or else an illegal instruction fault will occur. * * \note This allows builds with a smaller code size than with * MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT * * \note Minimum compiler versions for this feature are Clang 4.0, * armclang 6.6 or GCC 6.0. * * \note \c CFLAGS must be set to a minimum of \c -march=armv8-a+crypto for * armclang <= 6.9 * * \note This was previously known as MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY. * That name is deprecated, but may still be used as an alternative form for this * option. * * \warning MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY cannot be defined at the same * time as MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT. * * Requires: MBEDTLS_SHA256_C. * * Module: library/sha256.c * * Uncomment to have the library use the Armv8-A SHA-256 crypto extensions * unconditionally. */ //#define MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY /** * \def MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY * * \deprecated This is now known as MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY. * This name is now deprecated, but may still be used as an alternative form for * this option. */ //#define MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY /** * \def MBEDTLS_SHA384_C * * Enable the SHA-384 cryptographic hash algorithm. * * Module: library/sha512.c * Caller: library/md.c * library/psa_crypto_hash.c * library/ssl_tls.c * library/ssl*_client.c * library/ssl*_server.c * * Comment to disable SHA-384 */ #define MBEDTLS_SHA384_C /** * \def MBEDTLS_SHA512_C * * Enable SHA-512 cryptographic hash algorithms. * * Module: library/sha512.c * Caller: library/entropy.c * library/md.c * library/ssl_tls.c * library/ssl_cookie.c * * This module adds support for SHA-512. */ #define MBEDTLS_SHA512_C /** * \def MBEDTLS_SHA3_C * * Enable the SHA3 cryptographic hash algorithm. * * Module: library/sha3.c * * This module adds support for SHA3. */ #define MBEDTLS_SHA3_C /** * \def MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT * * Enable acceleration of the SHA-512 and SHA-384 cryptographic hash algorithms * with the ARMv8 cryptographic extensions if they are available at runtime. * If not, the library will fall back to the C implementation. * * \note If MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT is defined when building * for a non-Aarch64 build it will be silently ignored. * * \note Minimum compiler versions for this feature are Clang 7.0, * armclang 6.9 or GCC 8.0. * * \note \c CFLAGS must be set to a minimum of \c -march=armv8.2-a+sha3 for * armclang 6.9 * * \warning MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT cannot be defined at the * same time as MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY. * * Requires: MBEDTLS_SHA512_C. * * Module: library/sha512.c * * Uncomment to have the library check for the A64 SHA-512 crypto extensions * and use them if available. */ //#define MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT /** * \def MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY * * Enable acceleration of the SHA-512 and SHA-384 cryptographic hash algorithms * with the ARMv8 cryptographic extensions, which must be available at runtime * or else an illegal instruction fault will occur. * * \note This allows builds with a smaller code size than with * MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT * * \note Minimum compiler versions for this feature are Clang 7.0, * armclang 6.9 or GCC 8.0. * * \note \c CFLAGS must be set to a minimum of \c -march=armv8.2-a+sha3 for * armclang 6.9 * * \warning MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY cannot be defined at the same * time as MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT. * * Requires: MBEDTLS_SHA512_C. * * Module: library/sha512.c * * Uncomment to have the library use the A64 SHA-512 crypto extensions * unconditionally. */ //#define MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY /** * \def MBEDTLS_SSL_CACHE_C * * Enable simple SSL cache implementation. * * Module: library/ssl_cache.c * Caller: * * Requires: MBEDTLS_SSL_CACHE_C */ #define MBEDTLS_SSL_CACHE_C /** * \def MBEDTLS_SSL_COOKIE_C * * Enable basic implementation of DTLS cookies for hello verification. * * Module: library/ssl_cookie.c * Caller: */ #define MBEDTLS_SSL_COOKIE_C /** * \def MBEDTLS_SSL_TICKET_C * * Enable an implementation of TLS server-side callbacks for session tickets. * * Module: library/ssl_ticket.c * Caller: * * Requires: (MBEDTLS_CIPHER_C || MBEDTLS_USE_PSA_CRYPTO) && * (MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C) */ #define MBEDTLS_SSL_TICKET_C /** * \def MBEDTLS_SSL_CLI_C * * Enable the SSL/TLS client code. * * Module: library/ssl*_client.c * Caller: * * Requires: MBEDTLS_SSL_TLS_C * * This module is required for SSL/TLS client support. */ #define MBEDTLS_SSL_CLI_C /** * \def MBEDTLS_SSL_SRV_C * * Enable the SSL/TLS server code. * * Module: library/ssl*_server.c * Caller: * * Requires: MBEDTLS_SSL_TLS_C * * This module is required for SSL/TLS server support. */ #define MBEDTLS_SSL_SRV_C /** * \def MBEDTLS_SSL_TLS_C * * Enable the generic SSL/TLS code. * * Module: library/ssl_tls.c * Caller: library/ssl*_client.c * library/ssl*_server.c * * Requires: MBEDTLS_CIPHER_C, MBEDTLS_MD_C * and at least one of the MBEDTLS_SSL_PROTO_XXX defines * * This module is required for SSL/TLS. */ #define MBEDTLS_SSL_TLS_C /** * \def MBEDTLS_THREADING_C * * Enable the threading abstraction layer. * * Traditionally, Mbed TLS assumes it is used in a non-threaded environment or * that contexts are not shared between threads. If you do intend to use contexts * between threads, you will need to enable this layer to prevent race * conditions. * * The PSA subsystem has an implicit shared context. Therefore, you must * enable this option if more than one thread may use any part of * Mbed TLS that is implemented on top of the PSA subsystem. * * You must enable this option in multithreaded applications where more than * one thread performs any of the following operations: * * - Any call to a PSA function (`psa_xxx()`). * - Any call to a TLS, X.509 or PK function (`mbedtls_ssl_xxx()`, * `mbedtls_x509_xxx()`, `mbedtls_pkcs7_xxx()`, `mbedtls_pk_xxx()`) * if `MBEDTLS_USE_PSA_CRYPTO` is enabled (regardless of whether individual * TLS, X.509 or PK contexts are shared between threads). * - A TLS 1.3 connection, regardless of the compile-time configuration. * - Any library feature that calculates a hash, if `MBEDTLS_MD_C` is disabled. * As an exception, algorithm-specific low-level modules do not require * threading protection unless the contexts are shared between threads. * - Any library feature that performs symmetric encryption or decryption, * if `MBEDTLS_CIPHER_C` is disabled. * As an exception, algorithm-specific low-level modules do not require * threading protection unless the contexts are shared between threads. * - Any use of a cryptographic context if the same context is used in * multiple threads. * - Any call to a function where the documentation specifies that * psa_crypto_init() must be called prior to that function. * * See also our Knowledge Base article about threading: * https://mbed-tls.readthedocs.io/en/latest/kb/development/thread-safety-and-multi-threading * * Module: library/threading.c * * This allows different threading implementations (self-implemented or * provided). * * You will have to enable either MBEDTLS_THREADING_ALT or * MBEDTLS_THREADING_PTHREAD. * * Enable this layer to allow use of mutexes within Mbed TLS */ //#define MBEDTLS_THREADING_C /** * \def MBEDTLS_TIMING_C * * Enable the semi-portable timing interface. * * \note The provided implementation only works on POSIX/Unix (including Linux, * BSD and OS X) and Windows. On other platforms, you can either disable that * module and provide your own implementations of the callbacks needed by * \c mbedtls_ssl_set_timer_cb() for DTLS, or leave it enabled and provide * your own implementation of the whole module by setting * \c MBEDTLS_TIMING_ALT in the current file. * * \note The timing module will include time.h on suitable platforms * regardless of the setting of MBEDTLS_HAVE_TIME, unless * MBEDTLS_TIMING_ALT is used. See timing.c for more information. * * \note See also our Knowledge Base article about porting to a new * environment: * https://mbed-tls.readthedocs.io/en/latest/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS * * Module: library/timing.c */ #define MBEDTLS_TIMING_C /** * \def MBEDTLS_VERSION_C * * Enable run-time version information. * * Module: library/version.c * * This module provides run-time version information. */ #define MBEDTLS_VERSION_C /** * \def MBEDTLS_X509_USE_C * * Enable X.509 core for using certificates. * * Module: library/x509.c * Caller: library/x509_crl.c * library/x509_crt.c * library/x509_csr.c * * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_PARSE_C, * (MBEDTLS_MD_C or MBEDTLS_USE_PSA_CRYPTO) * * \warning If building with MBEDTLS_USE_PSA_CRYPTO, you must call * psa_crypto_init() before doing any X.509 operation. * * This module is required for the X.509 parsing modules. */ #define MBEDTLS_X509_USE_C /** * \def MBEDTLS_X509_CRT_PARSE_C * * Enable X.509 certificate parsing. * * Module: library/x509_crt.c * Caller: library/ssl_tls.c * library/ssl*_client.c * library/ssl*_server.c * * Requires: MBEDTLS_X509_USE_C * * This module is required for X.509 certificate parsing. */ #define MBEDTLS_X509_CRT_PARSE_C /** * \def MBEDTLS_X509_CRL_PARSE_C * * Enable X.509 CRL parsing. * * Module: library/x509_crl.c * Caller: library/x509_crt.c * * Requires: MBEDTLS_X509_USE_C * * This module is required for X.509 CRL parsing. */ #define MBEDTLS_X509_CRL_PARSE_C /** * \def MBEDTLS_X509_CSR_PARSE_C * * Enable X.509 Certificate Signing Request (CSR) parsing. * * Module: library/x509_csr.c * Caller: library/x509_crt_write.c * * Requires: MBEDTLS_X509_USE_C * * This module is used for reading X.509 certificate request. */ #define MBEDTLS_X509_CSR_PARSE_C /** * \def MBEDTLS_X509_CREATE_C * * Enable X.509 core for creating certificates. * * Module: library/x509_create.c * * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_PARSE_C, * (MBEDTLS_MD_C or MBEDTLS_USE_PSA_CRYPTO) * * \warning If building with MBEDTLS_USE_PSA_CRYPTO, you must call * psa_crypto_init() before doing any X.509 create operation. * * This module is the basis for creating X.509 certificates and CSRs. */ #define MBEDTLS_X509_CREATE_C /** * \def MBEDTLS_X509_CRT_WRITE_C * * Enable creating X.509 certificates. * * Module: library/x509_crt_write.c * * Requires: MBEDTLS_X509_CREATE_C * * This module is required for X.509 certificate creation. */ #define MBEDTLS_X509_CRT_WRITE_C /** * \def MBEDTLS_X509_CSR_WRITE_C * * Enable creating X.509 Certificate Signing Requests (CSR). * * Module: library/x509_csr_write.c * * Requires: MBEDTLS_X509_CREATE_C * * This module is required for X.509 certificate request writing. */ #define MBEDTLS_X509_CSR_WRITE_C /** \} name SECTION: Mbed TLS modules */ /** * \name SECTION: General configuration options * * This section contains Mbed TLS build settings that are not associated * with a particular module. * * \{ */ /** * \def MBEDTLS_CONFIG_FILE * * If defined, this is a header which will be included instead of * `"mbedtls/mbedtls_config.h"`. * This header file specifies the compile-time configuration of Mbed TLS. * Unlike other configuration options, this one must be defined on the * compiler command line: a definition in `mbedtls_config.h` would have * no effect. * * This macro is expanded after an \#include directive. This is a popular but * non-standard feature of the C language, so this feature is only available * with compilers that perform macro expansion on an \#include line. * * The value of this symbol is typically a path in double quotes, either * absolute or relative to a directory on the include search path. */ //#define MBEDTLS_CONFIG_FILE "mbedtls/mbedtls_config.h" /** * \def MBEDTLS_USER_CONFIG_FILE * * If defined, this is a header which will be included after * `"mbedtls/mbedtls_config.h"` or #MBEDTLS_CONFIG_FILE. * This allows you to modify the default configuration, including the ability * to undefine options that are enabled by default. * * This macro is expanded after an \#include directive. This is a popular but * non-standard feature of the C language, so this feature is only available * with compilers that perform macro expansion on an \#include line. * * The value of this symbol is typically a path in double quotes, either * absolute or relative to a directory on the include search path. */ //#define MBEDTLS_USER_CONFIG_FILE "/dev/null" /** * \def MBEDTLS_PSA_CRYPTO_CONFIG_FILE * * If defined, this is a header which will be included instead of * `"psa/crypto_config.h"`. * This header file specifies which cryptographic mechanisms are available * through the PSA API when #MBEDTLS_PSA_CRYPTO_CONFIG is enabled, and * is not used when #MBEDTLS_PSA_CRYPTO_CONFIG is disabled. * * This macro is expanded after an \#include directive. This is a popular but * non-standard feature of the C language, so this feature is only available * with compilers that perform macro expansion on an \#include line. * * The value of this symbol is typically a path in double quotes, either * absolute or relative to a directory on the include search path. */ //#define MBEDTLS_PSA_CRYPTO_CONFIG_FILE "psa/crypto_config.h" /** * \def MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE * * If defined, this is a header which will be included after * `"psa/crypto_config.h"` or #MBEDTLS_PSA_CRYPTO_CONFIG_FILE. * This allows you to modify the default configuration, including the ability * to undefine options that are enabled by default. * * This macro is expanded after an \#include directive. This is a popular but * non-standard feature of the C language, so this feature is only available * with compilers that perform macro expansion on an \#include line. * * The value of this symbol is typically a path in double quotes, either * absolute or relative to a directory on the include search path. */ //#define MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE "/dev/null" /** * \def MBEDTLS_PSA_CRYPTO_PLATFORM_FILE * * If defined, this is a header which will be included instead of * `"psa/crypto_platform.h"`. This file should declare the same identifiers * as the one in Mbed TLS, but with definitions adapted to the platform on * which the library code will run. * * \note The required content of this header can vary from one version of * Mbed TLS to the next. Integrators who provide an alternative file * should review the changes in the original file whenever they * upgrade Mbed TLS. * * This macro is expanded after an \#include directive. This is a popular but * non-standard feature of the C language, so this feature is only available * with compilers that perform macro expansion on an \#include line. * * The value of this symbol is typically a path in double quotes, either * absolute or relative to a directory on the include search path. */ //#define MBEDTLS_PSA_CRYPTO_PLATFORM_FILE "psa/crypto_platform_alt.h" /** * \def MBEDTLS_PSA_CRYPTO_STRUCT_FILE * * If defined, this is a header which will be included instead of * `"psa/crypto_struct.h"`. This file should declare the same identifiers * as the one in Mbed TLS, but with definitions adapted to the environment * in which the library code will run. The typical use for this feature * is to provide alternative type definitions on the client side in * client-server integrations of PSA crypto, where operation structures * contain handles instead of cryptographic data. * * \note The required content of this header can vary from one version of * Mbed TLS to the next. Integrators who provide an alternative file * should review the changes in the original file whenever they * upgrade Mbed TLS. * * This macro is expanded after an \#include directive. This is a popular but * non-standard feature of the C language, so this feature is only available * with compilers that perform macro expansion on an \#include line. * * The value of this symbol is typically a path in double quotes, either * absolute or relative to a directory on the include search path. */ //#define MBEDTLS_PSA_CRYPTO_STRUCT_FILE "psa/crypto_struct_alt.h" /** \} name SECTION: General configuration options */ /** * \name SECTION: Module configuration options * * This section allows for the setting of module specific sizes and * configuration options. The default values are already present in the * relevant header files and should suffice for the regular use cases. * * Our advice is to enable options and change their values here * only if you have a good reason and know the consequences. * \{ */ /* The Doxygen documentation here is used when a user comments out a * setting and runs doxygen themselves. On the other hand, when we typeset * the full documentation including disabled settings, the documentation * in specific modules' header files is used if present. When editing this * file, make sure that each option is documented in exactly one place, * plus optionally a same-line Doxygen comment here if there is a Doxygen * comment in the specific module. */ /* MPI / BIGNUM options */ //#define MBEDTLS_MPI_WINDOW_SIZE 2 /**< Maximum window size used. */ //#define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */ /* CTR_DRBG options */ //#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */ //#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ //#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ //#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ //#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ /* HMAC_DRBG options */ //#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ //#define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ //#define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ //#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ /* ECP options */ //#define MBEDTLS_ECP_WINDOW_SIZE 4 /**< Maximum window size used */ //#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up */ /* Entropy options */ //#define MBEDTLS_ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */ //#define MBEDTLS_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */ //#define MBEDTLS_ENTROPY_MIN_HARDWARE 32 /**< Default minimum number of bytes required for the hardware entropy source mbedtls_hardware_poll() before entropy is released */ /* Memory buffer allocator options */ //#define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /**< Align on multiples of this value */ /* Platform options */ //#define MBEDTLS_PLATFORM_STD_MEM_HDR /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */ /** \def MBEDTLS_PLATFORM_STD_CALLOC * * Default allocator to use, can be undefined. * It must initialize the allocated buffer memory to zeroes. * The size of the buffer is the product of the two parameters. * The calloc function returns either a null pointer or a pointer to the allocated space. * If the product is 0, the function may either return NULL or a valid pointer to an array of size 0 which is a valid input to the deallocation function. * An uninitialized #MBEDTLS_PLATFORM_STD_CALLOC always fails, returning a null pointer. * See the description of #MBEDTLS_PLATFORM_MEMORY for more details. * The corresponding deallocation function is #MBEDTLS_PLATFORM_STD_FREE. */ //#define MBEDTLS_PLATFORM_STD_CALLOC calloc /** \def MBEDTLS_PLATFORM_STD_FREE * * Default free to use, can be undefined. * NULL is a valid parameter, and the function must do nothing. * A non-null parameter will always be a pointer previously returned by #MBEDTLS_PLATFORM_STD_CALLOC and not yet freed. * An uninitialized #MBEDTLS_PLATFORM_STD_FREE does not do anything. * See the description of #MBEDTLS_PLATFORM_MEMORY for more details (same principles as for MBEDTLS_PLATFORM_STD_CALLOC apply). */ //#define MBEDTLS_PLATFORM_STD_FREE free //#define MBEDTLS_PLATFORM_STD_SETBUF setbuf /**< Default setbuf to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_EXIT exit /**< Default exit to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ //#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use, can be undefined */ /* Note: your snprintf must correctly zero-terminate the buffer! */ //#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< Default snprintf to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS 0 /**< Default exit value to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE 1 /**< Default exit value to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */ //#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile" /**< Seed file to read/write with default implementation */ /* To use the following function macros, MBEDTLS_PLATFORM_C must be enabled. */ /* MBEDTLS_PLATFORM_XXX_MACRO and MBEDTLS_PLATFORM_XXX_ALT cannot both be defined */ //#define MBEDTLS_PLATFORM_CALLOC_MACRO calloc /**< Default allocator macro to use, can be undefined. See MBEDTLS_PLATFORM_STD_CALLOC for requirements. */ //#define MBEDTLS_PLATFORM_FREE_MACRO free /**< Default free macro to use, can be undefined. See MBEDTLS_PLATFORM_STD_FREE for requirements. */ //#define MBEDTLS_PLATFORM_EXIT_MACRO exit /**< Default exit macro to use, can be undefined */ //#define MBEDTLS_PLATFORM_SETBUF_MACRO setbuf /**< Default setbuf macro to use, can be undefined */ //#define MBEDTLS_PLATFORM_TIME_MACRO time /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ //#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO time_t /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */ //#define MBEDTLS_PLATFORM_FPRINTF_MACRO fprintf /**< Default fprintf macro to use, can be undefined */ //#define MBEDTLS_PLATFORM_PRINTF_MACRO printf /**< Default printf macro to use, can be undefined */ /* Note: your snprintf must correctly zero-terminate the buffer! */ //#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf /**< Default snprintf macro to use, can be undefined */ //#define MBEDTLS_PLATFORM_VSNPRINTF_MACRO vsnprintf /**< Default vsnprintf macro to use, can be undefined */ //#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */ //#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */ //#define MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO int64_t //#define MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO int64_t /**< Default milliseconds time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled. It must be signed, and at least 64 bits. If it is changed from the default, MBEDTLS_PRINTF_MS_TIME must be updated to match.*/ //#define MBEDTLS_PRINTF_MS_TIME PRId64 /**< Default fmt for printf. That's avoid compiler warning if mbedtls_ms_time_t is redefined */ /** \def MBEDTLS_CHECK_RETURN * * This macro is used at the beginning of the declaration of a function * to indicate that its return value should be checked. It should * instruct the compiler to emit a warning or an error if the function * is called without checking its return value. * * There is a default implementation for popular compilers in platform_util.h. * You can override the default implementation by defining your own here. * * If the implementation here is empty, this will effectively disable the * checking of functions' return values. */ //#define MBEDTLS_CHECK_RETURN __attribute__((__warn_unused_result__)) /** \def MBEDTLS_IGNORE_RETURN * * This macro requires one argument, which should be a C function call. * If that function call would cause a #MBEDTLS_CHECK_RETURN warning, this * warning is suppressed. */ //#define MBEDTLS_IGNORE_RETURN( result ) ((void) !(result)) /* PSA options */ /** * Use HMAC_DRBG with the specified hash algorithm for HMAC_DRBG for the * PSA crypto subsystem. * * If this option is unset, the library chooses a hash (currently between * #MBEDTLS_MD_SHA512 and #MBEDTLS_MD_SHA256) based on availability and * unspecified heuristics. * * \note The PSA crypto subsystem uses the first available mechanism amongst * the following: * - #MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG if enabled; * - Entropy from #MBEDTLS_ENTROPY_C plus CTR_DRBG with AES * if #MBEDTLS_CTR_DRBG_C is enabled; * - Entropy from #MBEDTLS_ENTROPY_C plus HMAC_DRBG. * * A future version may reevaluate the prioritization of DRBG mechanisms. */ //#define MBEDTLS_PSA_HMAC_DRBG_MD_TYPE MBEDTLS_MD_SHA256 /** \def MBEDTLS_PSA_KEY_SLOT_COUNT * * When #MBEDTLS_PSA_KEY_STORE_DYNAMIC is disabled, * the maximum amount of PSA keys simultaneously in memory. This counts all * volatile keys, plus loaded persistent keys. * * When #MBEDTLS_PSA_KEY_STORE_DYNAMIC is enabled, * the maximum number of loaded persistent keys. * * Currently, persistent keys do not need to be loaded all the time while * a multipart operation is in progress, only while the operation is being * set up. This may change in future versions of the library. * * Currently, the library traverses of the whole table on each access to a * persistent key. Therefore large values may cause poor performance. * * This option has no effect when #MBEDTLS_PSA_CRYPTO_C is disabled. */ //#define MBEDTLS_PSA_KEY_SLOT_COUNT 32 /** * \def MBEDTLS_PSA_STATIC_KEY_SLOT_BUFFER_SIZE * * Define the size (in bytes) of each static key buffer when * #MBEDTLS_PSA_STATIC_KEY_SLOTS is set. If not * explicitly defined then it's automatically guessed from available PSA keys * enabled in the build through PSA_WANT_xxx symbols. * If required by the application this parameter can be set to higher values * in order to store larger objects (ex: raw keys), but please note that this * will increase RAM usage. */ //#define MBEDTLS_PSA_STATIC_KEY_SLOT_BUFFER_SIZE 256 /* RSA OPTIONS */ //#define MBEDTLS_RSA_GEN_KEY_MIN_BITS 1024 /**< Minimum RSA key size that can be generated in bits (Minimum possible value is 128 bits) */ /* SSL Cache options */ //#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT 86400 /**< 1 day */ //#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */ /* SSL options */ /** \def MBEDTLS_SSL_IN_CONTENT_LEN * * Maximum length (in bytes) of incoming plaintext fragments. * * This determines the size of the incoming TLS I/O buffer in such a way * that it is capable of holding the specified amount of plaintext data, * regardless of the protection mechanism used. * * \note When using a value less than the default of 16KB on the client, it is * recommended to use the Maximum Fragment Length (MFL) extension to * inform the server about this limitation. On the server, there * is no supported, standardized way of informing the client about * restriction on the maximum size of incoming messages, and unless * the limitation has been communicated by other means, it is recommended * to only change the outgoing buffer size #MBEDTLS_SSL_OUT_CONTENT_LEN * while keeping the default value of 16KB for the incoming buffer. * * Uncomment to set the maximum plaintext size of the incoming I/O buffer. */ //#define MBEDTLS_SSL_IN_CONTENT_LEN 16384 /** \def MBEDTLS_SSL_CID_IN_LEN_MAX * * The maximum length of CIDs used for incoming DTLS messages. * */ //#define MBEDTLS_SSL_CID_IN_LEN_MAX 32 /** \def MBEDTLS_SSL_CID_OUT_LEN_MAX * * The maximum length of CIDs used for outgoing DTLS messages. * */ //#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32 /** \def MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY * * This option controls the use of record plaintext padding * in TLS 1.3 and when using the Connection ID extension in DTLS 1.2. * * The padding will always be chosen so that the length of the * padded plaintext is a multiple of the value of this option. * * Note: A value of \c 1 means that no padding will be used * for outgoing records. * * Note: On systems lacking division instructions, * a power of two should be preferred. */ //#define MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY 16 /** \def MBEDTLS_SSL_OUT_CONTENT_LEN * * Maximum length (in bytes) of outgoing plaintext fragments. * * This determines the size of the outgoing TLS I/O buffer in such a way * that it is capable of holding the specified amount of plaintext data, * regardless of the protection mechanism used. * * It is possible to save RAM by setting a smaller outward buffer, while keeping * the default inward 16384 byte buffer to conform to the TLS specification. * * The minimum required outward buffer size is determined by the handshake * protocol's usage. Handshaking will fail if the outward buffer is too small. * The specific size requirement depends on the configured ciphers and any * certificate data which is sent during the handshake. * * Uncomment to set the maximum plaintext size of the outgoing I/O buffer. */ //#define MBEDTLS_SSL_OUT_CONTENT_LEN 16384 /** \def MBEDTLS_SSL_DTLS_MAX_BUFFERING * * Maximum number of heap-allocated bytes for the purpose of * DTLS handshake message reassembly and future message buffering. * * This should be at least 9/8 * MBEDTLS_SSL_IN_CONTENT_LEN * to account for a reassembled handshake message of maximum size, * together with its reassembly bitmap. * * A value of 2 * MBEDTLS_SSL_IN_CONTENT_LEN (32768 by default) * should be sufficient for all practical situations as it allows * to reassembly a large handshake message (such as a certificate) * while buffering multiple smaller handshake messages. * */ //#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768 //#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 or 384 bits) */ //#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */ /** * Complete list of ciphersuites to use, in order of preference. * * \warning No dependency checking is done on that field! This option can only * be used to restrict the set of available ciphersuites. It is your * responsibility to make sure the needed modules are active. * * Use this to save a few hundred bytes of ROM (default ordering of all * available ciphersuites) and a few to a few hundred bytes of RAM. * * The value below is only an example, not the default. */ //#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 /** * \def MBEDTLS_SSL_MAX_EARLY_DATA_SIZE * * The default maximum amount of 0-RTT data. See the documentation of * \c mbedtls_ssl_conf_max_early_data_size() for more information. * * It must be positive and smaller than UINT32_MAX. * * If MBEDTLS_SSL_EARLY_DATA is not defined, this default value does not * have any impact on the build. */ //#define MBEDTLS_SSL_MAX_EARLY_DATA_SIZE 1024 /** * \def MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE * * Maximum allowed ticket age difference in milliseconds tolerated between * server and client. Default value is 6000. This is not used in TLS 1.2. * * - The client ticket age is the time difference between the time when the * client proposes to the server to use the ticket and the time the client * received the ticket from the server. * - The server ticket age is the time difference between the time when the * server receives a proposition from the client to use the ticket and the * time when the ticket was created by the server. * * The ages might be different due to the client and server clocks not running * at the same pace. The typical accuracy of an RTC crystal is ±100 to ±20 parts * per million (360 to 72 milliseconds per hour). Default tolerance window is * 6s, thus in the worst case clients and servers must sync up their system time * every 6000/360/2~=8 hours. * * See section 8.3 of the TLS 1.3 specification(RFC 8446) for more information. */ //#define MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE 6000 /** * \def MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH * * Size in bytes of a ticket nonce. This is not used in TLS 1.2. * * This must be less than 256. */ //#define MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH 32 /** * \def MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS * * Default number of NewSessionTicket messages to be sent by a TLS 1.3 server * after handshake completion. This is not used in TLS 1.2 and relevant only if * the MBEDTLS_SSL_SESSION_TICKETS option is enabled. * */ //#define MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS 1 /* X509 options */ //#define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8 /**< Maximum number of intermediate CAs in a verification chain. */ //#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512 /**< Maximum length of a path/filename string in bytes including the null terminator character ('\0'). */ /** \} name SECTION: Module configuration options */ keyring/src/mbedtls/check_config.h0000644000176200001440000013610415006370264016726 0ustar liggesusers/** * \file check_config.h * * \brief Consistency checks for configuration options * * This is an internal header. Do not include it directly. * * This header is included automatically by all public Mbed TLS headers * (via mbedtls/build_info.h). Do not include it directly in a configuration * file such as mbedtls/mbedtls_config.h or #MBEDTLS_USER_CONFIG_FILE! * It would run at the wrong time due to missing derived symbols. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_CHECK_CONFIG_H #define MBEDTLS_CHECK_CONFIG_H /* *INDENT-OFF* */ #if !defined(MBEDTLS_CONFIG_IS_FINALIZED) #warning "Do not include mbedtls/check_config.h manually! " \ "This may cause spurious errors. " \ "It is included automatically at the right point since Mbed TLS 3.0." #endif /* !MBEDTLS_CONFIG_IS_FINALIZED */ /* * We assume CHAR_BIT is 8 in many places. In practice, this is true on our * target platforms, so not an issue, but let's just be extra sure. */ #include #if CHAR_BIT != 8 #error "Mbed TLS requires a platform with 8-bit chars" #endif #include #if defined(__MINGW32__) || (defined(_MSC_VER) && _MSC_VER <= 1900) #if !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_C is required on Windows" #endif /* See auto-enabling SNPRINTF_ALT and VSNPRINTF_ALT * in * config_adjust_legacy_crypto.h */ #endif /* _MINGW32__ || (_MSC_VER && (_MSC_VER <= 1900)) */ #if defined(TARGET_LIKE_MBED) && defined(MBEDTLS_NET_C) #error "The NET module is not available for mbed OS - please use the network functions provided by Mbed OS" #endif #if defined(MBEDTLS_DEPRECATED_WARNING) && \ !defined(__GNUC__) && !defined(__clang__) #error "MBEDTLS_DEPRECATED_WARNING only works with GCC and Clang" #endif #if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_HAVE_TIME) #error "MBEDTLS_HAVE_TIME_DATE without MBEDTLS_HAVE_TIME does not make sense" #endif /* Limitations on ECC key types acceleration: if we have any of `PUBLIC_KEY`, * `KEY_PAIR_BASIC`, `KEY_PAIR_IMPORT`, `KEY_PAIR_EXPORT` then we must have * all 4 of them. */ #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) || \ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT) || \ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT) #if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) || \ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT) || \ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT) #error "Unsupported partial support for ECC key type acceleration, see docs/driver-only-builds.md" #endif /* not all of public, basic, import, export */ #endif /* one of public, basic, import, export */ /* Limitations on ECC curves acceleration: partial curve acceleration is only * supported with crypto excluding PK, X.509 or TLS. * Note: no need to check X.509 as it depends on PK. */ #if defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_256) || \ defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_384) || \ defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_512) || \ defined(MBEDTLS_PSA_ACCEL_ECC_MONTGOMERY_255) || \ defined(MBEDTLS_PSA_ACCEL_ECC_MONTGOMERY_448) || \ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_192) || \ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_224) || \ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_256) || \ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_192) || \ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_224) || \ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_256) || \ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_384) || \ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_521) #if defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES) #if defined(MBEDTLS_PK_C) || \ defined(MBEDTLS_SSL_TLS_C) #error "Unsupported partial support for ECC curves acceleration, see docs/driver-only-builds.md" #endif /* modules beyond what's supported */ #endif /* not all curves accelerated */ #endif /* some curve accelerated */ #if defined(MBEDTLS_CTR_DRBG_C) && !(defined(MBEDTLS_AES_C) || \ (defined(MBEDTLS_PSA_CRYPTO_CLIENT) && defined(PSA_WANT_KEY_TYPE_AES) && \ defined(PSA_WANT_ALG_ECB_NO_PADDING))) #error "MBEDTLS_CTR_DRBG_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_DHM_C) && !defined(MBEDTLS_BIGNUM_C) #error "MBEDTLS_DHM_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_CMAC_C) && \ ( !defined(MBEDTLS_CIPHER_C ) || ( !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C) ) ) #error "MBEDTLS_CMAC_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_NIST_KW_C) && \ ( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) ) #error "MBEDTLS_NIST_KW_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) && defined(MBEDTLS_PSA_CRYPTO_CONFIG) #if defined(PSA_WANT_ALG_CBC_NO_PADDING) #error "MBEDTLS_BLOCK_CIPHER_NO_DECRYPT and PSA_WANT_ALG_CBC_NO_PADDING cannot be defined simultaneously" #endif #if defined(PSA_WANT_ALG_CBC_PKCS7) #error "MBEDTLS_BLOCK_CIPHER_NO_DECRYPT and PSA_WANT_ALG_CBC_PKCS7 cannot be defined simultaneously" #endif #if defined(PSA_WANT_ALG_ECB_NO_PADDING) #error "MBEDTLS_BLOCK_CIPHER_NO_DECRYPT and PSA_WANT_ALG_ECB_NO_PADDING cannot be defined simultaneously" #endif #if defined(PSA_WANT_KEY_TYPE_DES) #error "MBEDTLS_BLOCK_CIPHER_NO_DECRYPT and PSA_WANT_KEY_TYPE_DES cannot be defined simultaneously" #endif #endif #if defined(MBEDTLS_BLOCK_CIPHER_NO_DECRYPT) #if defined(MBEDTLS_CIPHER_MODE_CBC) #error "MBEDTLS_BLOCK_CIPHER_NO_DECRYPT and MBEDTLS_CIPHER_MODE_CBC cannot be defined simultaneously" #endif #if defined(MBEDTLS_CIPHER_MODE_XTS) #error "MBEDTLS_BLOCK_CIPHER_NO_DECRYPT and MBEDTLS_CIPHER_MODE_XTS cannot be defined simultaneously" #endif #if defined(MBEDTLS_DES_C) #error "MBEDTLS_BLOCK_CIPHER_NO_DECRYPT and MBEDTLS_DES_C cannot be defined simultaneously" #endif #if defined(MBEDTLS_NIST_KW_C) #error "MBEDTLS_BLOCK_CIPHER_NO_DECRYPT and MBEDTLS_NIST_KW_C cannot be defined simultaneously" #endif #endif #if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_ECP_C) #error "MBEDTLS_ECDH_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECDSA_C) && \ ( !defined(MBEDTLS_ECP_C) || \ !( defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) ) || \ !defined(MBEDTLS_ASN1_PARSE_C) || \ !defined(MBEDTLS_ASN1_WRITE_C) ) #error "MBEDTLS_ECDSA_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PK_C) && defined(MBEDTLS_USE_PSA_CRYPTO) #if defined(MBEDTLS_PK_CAN_ECDSA_SIGN) && !defined(MBEDTLS_ASN1_WRITE_C) #error "MBEDTLS_PK_C with MBEDTLS_USE_PSA_CRYPTO needs MBEDTLS_ASN1_WRITE_C for ECDSA signature" #endif #if defined(MBEDTLS_PK_CAN_ECDSA_VERIFY) && !defined(MBEDTLS_ASN1_PARSE_C) #error "MBEDTLS_PK_C with MBEDTLS_USE_PSA_CRYPTO needs MBEDTLS_ASN1_PARSE_C for ECDSA verification" #endif #endif /* MBEDTLS_PK_C && MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_ECJPAKE_C) && \ !defined(MBEDTLS_ECP_C) #error "MBEDTLS_ECJPAKE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_RESTARTABLE) && \ ( defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT) || \ defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT) || \ defined(MBEDTLS_ECDSA_SIGN_ALT) || \ defined(MBEDTLS_ECDSA_VERIFY_ALT) || \ defined(MBEDTLS_ECDSA_GENKEY_ALT) || \ defined(MBEDTLS_ECP_INTERNAL_ALT) || \ defined(MBEDTLS_ECP_ALT) ) #error "MBEDTLS_ECP_RESTARTABLE defined, but it cannot coexist with an alternative ECP implementation" #endif #if defined(MBEDTLS_ECP_RESTARTABLE) && \ !defined(MBEDTLS_ECP_C) #error "MBEDTLS_ECP_RESTARTABLE defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECDSA_DETERMINISTIC) && !defined(MBEDTLS_HMAC_DRBG_C) #error "MBEDTLS_ECDSA_DETERMINISTIC defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_LIGHT) && ( !defined(MBEDTLS_BIGNUM_C) || ( \ !defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) && \ !defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) && \ !defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) ) ) #error "MBEDTLS_ECP_C defined (or a subset enabled), but not all prerequisites" #endif #if defined(MBEDTLS_ENTROPY_C) && \ !(defined(MBEDTLS_MD_CAN_SHA512) || defined(MBEDTLS_MD_CAN_SHA256)) #error "MBEDTLS_ENTROPY_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ENTROPY_C) && \ defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 64) #error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high" #endif #if defined(MBEDTLS_ENTROPY_C) && \ (defined(MBEDTLS_ENTROPY_FORCE_SHA256) || !defined(MBEDTLS_MD_CAN_SHA512)) \ && defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 32) #error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high" #endif #if defined(MBEDTLS_ENTROPY_C) && \ defined(MBEDTLS_ENTROPY_FORCE_SHA256) && !defined(MBEDTLS_MD_CAN_SHA256) #error "MBEDTLS_ENTROPY_FORCE_SHA256 defined, but not all prerequisites" #endif #if defined(__has_feature) #if __has_feature(memory_sanitizer) #define MBEDTLS_HAS_MEMSAN // #undef at the end of this paragraph #endif #endif #if defined(MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN) && !defined(MBEDTLS_HAS_MEMSAN) #error "MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN requires building with MemorySanitizer" #endif #if defined(MBEDTLS_HAS_MEMSAN) && defined(MBEDTLS_HAVE_ASM) #error "MemorySanitizer does not support assembly implementation" #endif #undef MBEDTLS_HAS_MEMSAN // temporary macro defined above #if defined(MBEDTLS_CCM_C) && \ !(defined(MBEDTLS_CCM_GCM_CAN_AES) || defined(MBEDTLS_CCM_GCM_CAN_ARIA) || \ defined(MBEDTLS_CCM_GCM_CAN_CAMELLIA)) #error "MBEDTLS_CCM_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_GCM_C) && \ !(defined(MBEDTLS_CCM_GCM_CAN_AES) || defined(MBEDTLS_CCM_GCM_CAN_ARIA) || \ defined(MBEDTLS_CCM_GCM_CAN_CAMELLIA)) #error "MBEDTLS_GCM_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_CHACHAPOLY_C) && !defined(MBEDTLS_CHACHA20_C) #error "MBEDTLS_CHACHAPOLY_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_CHACHAPOLY_C) && !defined(MBEDTLS_POLY1305_C) #error "MBEDTLS_CHACHAPOLY_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_RANDOMIZE_JAC_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_ADD_MIXED_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_ADD_MIXED_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_DOUBLE_JAC_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_NORMALIZE_JAC_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_RANDOMIZE_MXZ_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_NORMALIZE_MXZ_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_ECP_NO_FALLBACK) && !defined(MBEDTLS_ECP_INTERNAL_ALT) #error "MBEDTLS_ECP_NO_FALLBACK defined, but no alternative implementation enabled" #endif #if defined(MBEDTLS_HKDF_C) && !defined(MBEDTLS_MD_C) #error "MBEDTLS_HKDF_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_HMAC_DRBG_C) && !defined(MBEDTLS_MD_C) #error "MBEDTLS_HMAC_DRBG_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) && \ ( !defined(MBEDTLS_CAN_ECDH) || \ !defined(MBEDTLS_PK_CAN_ECDSA_SIGN) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) ) #error "MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \ ( !defined(MBEDTLS_CAN_ECDH) || !defined(MBEDTLS_RSA_C) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) ) #error "MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) && !defined(MBEDTLS_DHM_C) #error "MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) && \ !defined(MBEDTLS_CAN_ECDH) #error "MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \ ( !defined(MBEDTLS_DHM_C) || !defined(MBEDTLS_RSA_C) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \ ( !defined(MBEDTLS_CAN_ECDH) || !defined(MBEDTLS_RSA_C) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \ ( !defined(MBEDTLS_CAN_ECDH) || \ !defined(MBEDTLS_PK_CAN_ECDSA_SIGN) || \ !defined(MBEDTLS_X509_CRT_PARSE_C) ) #error "MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \ ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \ !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \ ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \ !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_KEY_EXCHANGE_RSA_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_USE_PSA_CRYPTO) #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \ ( !defined(PSA_WANT_ALG_JPAKE) || \ !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \ !defined(PSA_WANT_ECC_SECP_R1_256) ) #error "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites" #endif #else /* MBEDTLS_USE_PSA_CRYPTO */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \ ( !defined(MBEDTLS_ECJPAKE_C) || \ !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) ) #error "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites" #endif #endif /* MBEDTLS_USE_PSA_CRYPTO */ /* Use of EC J-PAKE in TLS requires SHA-256. */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \ !defined(MBEDTLS_MD_CAN_SHA256) #error "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites" #endif #if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) && \ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) && \ !defined(MBEDTLS_MD_CAN_SHA256) && \ !defined(MBEDTLS_MD_CAN_SHA512) && \ !defined(MBEDTLS_MD_CAN_SHA1) #error "!MBEDTLS_SSL_KEEP_PEER_CERTIFICATE requires SHA-512, SHA-256 or SHA-1". #endif #if defined(MBEDTLS_MD_C) && \ !defined(MBEDTLS_MD_CAN_MD5) && \ !defined(MBEDTLS_MD_CAN_RIPEMD160) && \ !defined(MBEDTLS_MD_CAN_SHA1) && \ !defined(MBEDTLS_MD_CAN_SHA224) && \ !defined(MBEDTLS_MD_CAN_SHA256) && \ !defined(MBEDTLS_MD_CAN_SHA384) && \ !defined(MBEDTLS_MD_CAN_SHA512) && \ !defined(MBEDTLS_MD_CAN_SHA3_224) && \ !defined(MBEDTLS_MD_CAN_SHA3_256) && \ !defined(MBEDTLS_MD_CAN_SHA3_384) && \ !defined(MBEDTLS_MD_CAN_SHA3_512) #error "MBEDTLS_MD_C defined, but no hash algorithm" #endif #if defined(MBEDTLS_LMS_C) && \ ! ( defined(MBEDTLS_PSA_CRYPTO_CLIENT) && defined(PSA_WANT_ALG_SHA_256) ) #error "MBEDTLS_LMS_C requires MBEDTLS_PSA_CRYPTO_C and PSA_WANT_ALG_SHA_256" #endif #if defined(MBEDTLS_LMS_PRIVATE) && \ ( !defined(MBEDTLS_LMS_C) ) #error "MBEDTLS_LMS_PRIVATE requires MBEDTLS_LMS_C" #endif #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && \ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) ) #error "MBEDTLS_MEMORY_BUFFER_ALLOC_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_MEMORY_BACKTRACE) && !defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) #error "MBEDTLS_MEMORY_BACKTRACE defined, but not all prerequisites" #endif #if defined(MBEDTLS_MEMORY_DEBUG) && !defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) #error "MBEDTLS_MEMORY_DEBUG defined, but not all prerequisites" #endif #if defined(MBEDTLS_PEM_PARSE_C) && !defined(MBEDTLS_BASE64_C) #error "MBEDTLS_PEM_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PEM_WRITE_C) && !defined(MBEDTLS_BASE64_C) #error "MBEDTLS_PEM_WRITE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PK_C) && \ !defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_PK_HAVE_ECC_KEYS) #error "MBEDTLS_PK_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PK_PARSE_C) && \ (!defined(MBEDTLS_ASN1_PARSE_C) || \ !defined(MBEDTLS_OID_C) || \ !defined(MBEDTLS_PK_C)) #error "MBEDTLS_PK_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PK_WRITE_C) && \ (!defined(MBEDTLS_ASN1_WRITE_C) || \ !defined(MBEDTLS_OID_C) || \ !defined(MBEDTLS_PK_C)) #error "MBEDTLS_PK_WRITE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_EXIT_ALT) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_EXIT_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_EXIT_MACRO) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_EXIT_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_EXIT_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_EXIT) ||\ defined(MBEDTLS_PLATFORM_EXIT_ALT) ) #error "MBEDTLS_PLATFORM_EXIT_MACRO and MBEDTLS_PLATFORM_STD_EXIT/MBEDTLS_PLATFORM_EXIT_ALT cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_SETBUF_ALT) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_SETBUF_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_SETBUF_MACRO) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_SETBUF_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_SETBUF_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_SETBUF) ||\ defined(MBEDTLS_PLATFORM_SETBUF_ALT) ) #error "MBEDTLS_PLATFORM_SETBUF_MACRO and MBEDTLS_PLATFORM_STD_SETBUF/MBEDTLS_PLATFORM_SETBUF_ALT cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_TIME_ALT) &&\ ( !defined(MBEDTLS_PLATFORM_C) ||\ !defined(MBEDTLS_HAVE_TIME) ) #error "MBEDTLS_PLATFORM_TIME_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\ ( !defined(MBEDTLS_PLATFORM_C) ||\ !defined(MBEDTLS_HAVE_TIME) ) #error "MBEDTLS_PLATFORM_TIME_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO) &&\ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_HAVE_TIME) ) #error "MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_MS_TIME_ALT) && \ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_HAVE_TIME) ) #error "MBEDTLS_PLATFORM_MS_TIME_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\ ( !defined(MBEDTLS_PLATFORM_C) ||\ !defined(MBEDTLS_HAVE_TIME) ) #error "MBEDTLS_PLATFORM_TIME_TYPE_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\ defined(MBEDTLS_PLATFORM_TIME_ALT) ) #error "MBEDTLS_PLATFORM_TIME_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\ defined(MBEDTLS_PLATFORM_TIME_ALT) ) #error "MBEDTLS_PLATFORM_TIME_TYPE_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_FPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_FPRINTF_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_FPRINTF_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_FPRINTF) ||\ defined(MBEDTLS_PLATFORM_FPRINTF_ALT) ) #error "MBEDTLS_PLATFORM_FPRINTF_MACRO and MBEDTLS_PLATFORM_STD_FPRINTF/MBEDTLS_PLATFORM_FPRINTF_ALT cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_FREE_MACRO) &&\ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) ) #error "MBEDTLS_PLATFORM_FREE_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_FREE_MACRO) &&\ defined(MBEDTLS_PLATFORM_STD_FREE) #error "MBEDTLS_PLATFORM_FREE_MACRO and MBEDTLS_PLATFORM_STD_FREE cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_FREE_MACRO) && !defined(MBEDTLS_PLATFORM_CALLOC_MACRO) #error "MBEDTLS_PLATFORM_CALLOC_MACRO must be defined if MBEDTLS_PLATFORM_FREE_MACRO is" #endif #if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&\ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) ) #error "MBEDTLS_PLATFORM_CALLOC_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&\ defined(MBEDTLS_PLATFORM_STD_CALLOC) #error "MBEDTLS_PLATFORM_CALLOC_MACRO and MBEDTLS_PLATFORM_STD_CALLOC cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) && !defined(MBEDTLS_PLATFORM_FREE_MACRO) #error "MBEDTLS_PLATFORM_FREE_MACRO must be defined if MBEDTLS_PLATFORM_CALLOC_MACRO is" #endif #if defined(MBEDTLS_PLATFORM_MEMORY) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_MEMORY defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_PRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_PRINTF_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_PRINTF_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_PRINTF) ||\ defined(MBEDTLS_PLATFORM_PRINTF_ALT) ) #error "MBEDTLS_PLATFORM_PRINTF_MACRO and MBEDTLS_PLATFORM_STD_PRINTF/MBEDTLS_PLATFORM_PRINTF_ALT cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_SNPRINTF_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_SNPRINTF_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_SNPRINTF) ||\ defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) ) #error "MBEDTLS_PLATFORM_SNPRINTF_MACRO and MBEDTLS_PLATFORM_STD_SNPRINTF/MBEDTLS_PLATFORM_SNPRINTF_ALT cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_VSNPRINTF_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_VSNPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C) #error "MBEDTLS_PLATFORM_VSNPRINTF_MACRO defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_VSNPRINTF_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_VSNPRINTF) ||\ defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT) ) #error "MBEDTLS_PLATFORM_VSNPRINTF_MACRO and MBEDTLS_PLATFORM_STD_VSNPRINTF/MBEDTLS_PLATFORM_VSNPRINTF_ALT cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_STD_MEM_HDR) &&\ !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) #error "MBEDTLS_PLATFORM_STD_MEM_HDR defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_STD_CALLOC) && !defined(MBEDTLS_PLATFORM_MEMORY) #error "MBEDTLS_PLATFORM_STD_CALLOC defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_STD_FREE) && !defined(MBEDTLS_PLATFORM_MEMORY) #error "MBEDTLS_PLATFORM_STD_FREE defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_STD_EXIT) &&\ !defined(MBEDTLS_PLATFORM_EXIT_ALT) #error "MBEDTLS_PLATFORM_STD_EXIT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_STD_TIME) &&\ ( !defined(MBEDTLS_PLATFORM_TIME_ALT) ||\ !defined(MBEDTLS_HAVE_TIME) ) #error "MBEDTLS_PLATFORM_STD_TIME defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_STD_FPRINTF) &&\ !defined(MBEDTLS_PLATFORM_FPRINTF_ALT) #error "MBEDTLS_PLATFORM_STD_FPRINTF defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_STD_PRINTF) &&\ !defined(MBEDTLS_PLATFORM_PRINTF_ALT) #error "MBEDTLS_PLATFORM_STD_PRINTF defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_STD_SNPRINTF) &&\ !defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) #error "MBEDTLS_PLATFORM_STD_SNPRINTF defined, but not all prerequisites" #endif #if defined(MBEDTLS_ENTROPY_NV_SEED) &&\ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_ENTROPY_C) ) #error "MBEDTLS_ENTROPY_NV_SEED defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_NV_SEED_ALT) &&\ !defined(MBEDTLS_ENTROPY_NV_SEED) #error "MBEDTLS_PLATFORM_NV_SEED_ALT defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) &&\ !defined(MBEDTLS_PLATFORM_NV_SEED_ALT) #error "MBEDTLS_PLATFORM_STD_NV_SEED_READ defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) &&\ !defined(MBEDTLS_PLATFORM_NV_SEED_ALT) #error "MBEDTLS_PLATFORM_STD_NV_SEED_WRITE defined, but not all prerequisites" #endif #if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) ||\ defined(MBEDTLS_PLATFORM_NV_SEED_ALT) ) #error "MBEDTLS_PLATFORM_NV_SEED_READ_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_READ cannot be defined simultaneously" #endif #if defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO) &&\ ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) ||\ defined(MBEDTLS_PLATFORM_NV_SEED_ALT) ) #error "MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_WRITE cannot be defined simultaneously" #endif #if defined(MBEDTLS_PSA_CRYPTO_C) && \ !( ( ( defined(MBEDTLS_CTR_DRBG_C) || defined(MBEDTLS_HMAC_DRBG_C) ) && \ defined(MBEDTLS_ENTROPY_C) ) || \ defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) ) #error "MBEDTLS_PSA_CRYPTO_C defined, but not all prerequisites (missing RNG)" #endif #if defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_HAVE_SOFT_BLOCK_MODE) && \ defined(PSA_HAVE_SOFT_BLOCK_CIPHER) && !defined(MBEDTLS_CIPHER_C) #error "MBEDTLS_PSA_CRYPTO_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PSA_CRYPTO_SPM) && !defined(MBEDTLS_PSA_CRYPTO_C) #error "MBEDTLS_PSA_CRYPTO_SPM defined, but not all prerequisites" #endif #if defined(MBEDTLS_PSA_CRYPTO_SE_C) && \ ! ( defined(MBEDTLS_PSA_CRYPTO_C) && \ defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) ) #error "MBEDTLS_PSA_CRYPTO_SE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PSA_CRYPTO_SE_C) #if defined(MBEDTLS_DEPRECATED_REMOVED) #error "MBEDTLS_PSA_CRYPTO_SE_C is deprecated and will be removed in a future version of Mbed TLS" #elif defined(MBEDTLS_DEPRECATED_WARNING) #warning "MBEDTLS_PSA_CRYPTO_SE_C is deprecated and will be removed in a future version of Mbed TLS" #endif #endif /* MBEDTLS_PSA_CRYPTO_SE_C */ #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) && \ ! defined(MBEDTLS_PSA_CRYPTO_C) #error "MBEDTLS_PSA_CRYPTO_STORAGE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \ !( defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) && \ defined(MBEDTLS_ENTROPY_NV_SEED) ) #error "MBEDTLS_PSA_INJECT_ENTROPY defined, but not all prerequisites" #endif #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \ !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES) #error "MBEDTLS_PSA_INJECT_ENTROPY is not compatible with actual entropy sources" #endif #if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \ defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) #error "MBEDTLS_PSA_INJECT_ENTROPY is not compatible with MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG" #endif #if defined(MBEDTLS_PSA_KEY_STORE_DYNAMIC) && \ defined(MBEDTLS_PSA_STATIC_KEY_SLOTS) #error "MBEDTLS_PSA_KEY_STORE_DYNAMIC and MBEDTLS_PSA_STATIC_KEY_SLOTS cannot be defined simultaneously" #endif #if defined(MBEDTLS_PSA_ITS_FILE_C) && \ !defined(MBEDTLS_FS_IO) #error "MBEDTLS_PSA_ITS_FILE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_BIGNUM_C) || \ !defined(MBEDTLS_OID_C) ) #error "MBEDTLS_RSA_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_PKCS1_V21) && \ !defined(MBEDTLS_PKCS1_V15) ) #error "MBEDTLS_RSA_C defined, but none of the PKCS1 versions enabled" #endif #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) && \ ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_PKCS1_V21) ) #error "MBEDTLS_X509_RSASSA_PSS_SUPPORT defined, but not all prerequisites" #endif #if defined(MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT) && \ defined(MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY) #error "Must only define one of MBEDTLS_SHA512_USE_A64_CRYPTO_*" #endif #if defined(MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT) || \ defined(MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY) #if !defined(MBEDTLS_SHA512_C) #error "MBEDTLS_SHA512_USE_A64_CRYPTO_* defined without MBEDTLS_SHA512_C" #endif #if defined(MBEDTLS_SHA512_ALT) || defined(MBEDTLS_SHA512_PROCESS_ALT) #error "MBEDTLS_SHA512_*ALT can't be used with MBEDTLS_SHA512_USE_A64_CRYPTO_*" #endif #endif /* MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT || MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY */ #if defined(MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY) && !defined(__aarch64__) #error "MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY defined on non-Aarch64 system" #endif #if defined(MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT) && \ defined(MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY) #error "Must only define one of MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_*" #endif #if defined(MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT) || \ defined(MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY) #if !defined(MBEDTLS_SHA256_C) #error "MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_* defined without MBEDTLS_SHA256_C" #endif #if defined(MBEDTLS_SHA256_ALT) || defined(MBEDTLS_SHA256_PROCESS_ALT) #error "MBEDTLS_SHA256_*ALT can't be used with MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_*" #endif #endif #if defined(MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY) && !defined(MBEDTLS_ARCH_IS_ARMV8_A) #error "MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY defined on non-Armv8-A system" #endif /* TLS 1.3 requires separate HKDF parts from PSA, * and at least one ciphersuite, so at least SHA-256 or SHA-384 * from PSA to use with HKDF. * * Note: for dependencies common with TLS 1.2 (running handshake hash), * see MBEDTLS_SSL_TLS_C. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \ !(defined(MBEDTLS_PSA_CRYPTO_CLIENT) && \ defined(PSA_WANT_ALG_HKDF_EXTRACT) && \ defined(PSA_WANT_ALG_HKDF_EXPAND) && \ (defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_384))) #error "MBEDTLS_SSL_PROTO_TLS1_3 defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED) #if !( (defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)) && \ defined(MBEDTLS_X509_CRT_PARSE_C) && \ ( defined(MBEDTLS_PK_CAN_ECDSA_SIGN) || defined(MBEDTLS_PKCS1_V21) ) ) #error "MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED defined, but not all prerequisites" #endif #endif #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED) #if !( defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH) ) #error "MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED defined, but not all prerequisites" #endif #endif /* * The current implementation of TLS 1.3 requires MBEDTLS_SSL_KEEP_PEER_CERTIFICATE. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_3) && !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) #error "MBEDTLS_SSL_PROTO_TLS1_3 defined without MBEDTLS_SSL_KEEP_PEER_CERTIFICATE" #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ !(defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ) #error "One or more versions of the TLS protocol are enabled " \ "but no key exchange methods defined with MBEDTLS_KEY_EXCHANGE_xxxx" #endif #if defined(MBEDTLS_SSL_EARLY_DATA) && \ ( !defined(MBEDTLS_SSL_SESSION_TICKETS) || \ ( !defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED) && \ !defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED) ) ) #error "MBEDTLS_SSL_EARLY_DATA defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C) && \ defined(MBEDTLS_SSL_MAX_EARLY_DATA_SIZE) && \ ((MBEDTLS_SSL_MAX_EARLY_DATA_SIZE < 0) || \ (MBEDTLS_SSL_MAX_EARLY_DATA_SIZE > UINT32_MAX)) #error "MBEDTLS_SSL_MAX_EARLY_DATA_SIZE must be in the range(0..UINT32_MAX)" #endif #if defined(MBEDTLS_SSL_PROTO_DTLS) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_2) #error "MBEDTLS_SSL_PROTO_DTLS defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_CLI_C) && !defined(MBEDTLS_SSL_TLS_C) #error "MBEDTLS_SSL_CLI_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && !defined(MBEDTLS_X509_CRT_PARSE_C) #error "MBEDTLS_SSL_ASYNC_PRIVATE defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_TLS_C) && !(defined(MBEDTLS_CIPHER_C) || \ defined(MBEDTLS_USE_PSA_CRYPTO)) #error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites" #endif /* TLS 1.2 and 1.3 require SHA-256 or SHA-384 (running handshake hash) */ #if defined(MBEDTLS_SSL_TLS_C) #if defined(MBEDTLS_USE_PSA_CRYPTO) #if !(defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_384)) #error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites" #endif #else /* MBEDTLS_USE_PSA_CRYPTO */ #if !defined(MBEDTLS_MD_C) || \ !(defined(MBEDTLS_MD_CAN_SHA256) || defined(MBEDTLS_MD_CAN_SHA384)) #error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites" #endif #endif /* MBEDTLS_USE_PSA_CRYPTO */ #endif /* MBEDTLS_SSL_TLS_C */ #if defined(MBEDTLS_SSL_SRV_C) && !defined(MBEDTLS_SSL_TLS_C) #error "MBEDTLS_SSL_SRV_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_TLS_C) && \ !( defined(MBEDTLS_SSL_PROTO_TLS1_2) || defined(MBEDTLS_SSL_PROTO_TLS1_3) ) #error "MBEDTLS_SSL_TLS_C defined, but no protocols are active" #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && !defined(MBEDTLS_SSL_PROTO_DTLS) #error "MBEDTLS_SSL_DTLS_HELLO_VERIFY defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && \ !defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) #error "MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) && \ ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ) #error "MBEDTLS_SSL_DTLS_ANTI_REPLAY defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \ ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) ) #error "MBEDTLS_SSL_DTLS_CONNECTION_ID defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \ defined(MBEDTLS_SSL_CID_IN_LEN_MAX) && \ MBEDTLS_SSL_CID_IN_LEN_MAX > 255 #error "MBEDTLS_SSL_CID_IN_LEN_MAX too large (max 255)" #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \ defined(MBEDTLS_SSL_CID_OUT_LEN_MAX) && \ MBEDTLS_SSL_CID_OUT_LEN_MAX > 255 #error "MBEDTLS_SSL_CID_OUT_LEN_MAX too large (max 255)" #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT) && \ !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) #error "MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT) && MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT != 0 #if defined(MBEDTLS_DEPRECATED_REMOVED) #error "MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT is deprecated and will be removed in a future version of Mbed TLS" #elif defined(MBEDTLS_DEPRECATED_WARNING) #warning "MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT is deprecated and will be removed in a future version of Mbed TLS" #endif #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT && MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT != 0 */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_2) #error "MBEDTLS_SSL_ENCRYPT_THEN_MAC defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_2) #error "MBEDTLS_SSL_EXTENDED_MASTER_SECRET defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_RENEGOTIATION) && \ !defined(MBEDTLS_SSL_PROTO_TLS1_2) #error "MBEDTLS_SSL_RENEGOTIATION defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_TICKET_C) && ( !defined(MBEDTLS_CIPHER_C) && \ !defined(MBEDTLS_USE_PSA_CRYPTO) ) #error "MBEDTLS_SSL_TICKET_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_TICKET_C) && \ !( defined(MBEDTLS_SSL_HAVE_CCM) || defined(MBEDTLS_SSL_HAVE_GCM) || \ defined(MBEDTLS_SSL_HAVE_CHACHAPOLY) ) #error "MBEDTLS_SSL_TICKET_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH) && \ MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH >= 256 #error "MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH must be less than 256" #endif #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && \ !defined(MBEDTLS_X509_CRT_PARSE_C) #error "MBEDTLS_SSL_SERVER_NAME_INDICATION defined, but not all prerequisites" #endif #if defined(MBEDTLS_THREADING_PTHREAD) #if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL) #error "MBEDTLS_THREADING_PTHREAD defined, but not all prerequisites" #endif #define MBEDTLS_THREADING_IMPL // undef at the end of this paragraph #endif #if defined(MBEDTLS_THREADING_ALT) #if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL) #error "MBEDTLS_THREADING_ALT defined, but not all prerequisites" #endif #define MBEDTLS_THREADING_IMPL // undef at the end of this paragraph #endif #if defined(MBEDTLS_THREADING_C) && !defined(MBEDTLS_THREADING_IMPL) #error "MBEDTLS_THREADING_C defined, single threading implementation required" #endif #undef MBEDTLS_THREADING_IMPL // temporary macro defined above #if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_PSA_CRYPTO_CLIENT) #error "MBEDTLS_USE_PSA_CRYPTO defined, but not all prerequisites" #endif #if defined(MBEDTLS_VERSION_FEATURES) && !defined(MBEDTLS_VERSION_C) #error "MBEDTLS_VERSION_FEATURES defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_USE_C) && \ (!defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_PARSE_C) || \ !defined(MBEDTLS_PK_PARSE_C) || \ ( !defined(MBEDTLS_MD_C) && !defined(MBEDTLS_USE_PSA_CRYPTO) ) ) #error "MBEDTLS_X509_USE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CREATE_C) && \ (!defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_WRITE_C) || \ !defined(MBEDTLS_PK_PARSE_C) || \ ( !defined(MBEDTLS_MD_C) && !defined(MBEDTLS_USE_PSA_CRYPTO) ) ) #error "MBEDTLS_X509_CREATE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CRT_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) ) #error "MBEDTLS_X509_CRT_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CRL_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) ) #error "MBEDTLS_X509_CRL_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CSR_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) ) #error "MBEDTLS_X509_CSR_PARSE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CRT_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) ) #error "MBEDTLS_X509_CRT_WRITE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_CSR_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) ) #error "MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites" #endif #if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) && \ ( !defined(MBEDTLS_X509_CRT_PARSE_C) ) #error "MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK defined, but not all prerequisites" #endif #if defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64) #error "MBEDTLS_HAVE_INT32 and MBEDTLS_HAVE_INT64 cannot be defined simultaneously" #endif /* MBEDTLS_HAVE_INT32 && MBEDTLS_HAVE_INT64 */ #if ( defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64) ) && \ defined(MBEDTLS_HAVE_ASM) #error "MBEDTLS_HAVE_INT32/MBEDTLS_HAVE_INT64 and MBEDTLS_HAVE_ASM cannot be defined simultaneously" #endif /* (MBEDTLS_HAVE_INT32 || MBEDTLS_HAVE_INT64) && MBEDTLS_HAVE_ASM */ #if defined(MBEDTLS_SSL_DTLS_SRTP) && ( !defined(MBEDTLS_SSL_PROTO_DTLS) ) #error "MBEDTLS_SSL_DTLS_SRTP defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) && ( !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) ) #error "MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT) && ( !defined(MBEDTLS_SSL_PROTO_TLS1_3) ) #error "MBEDTLS_SSL_RECORD_SIZE_LIMIT defined, but not all prerequisites" #endif #if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) && \ !( defined(MBEDTLS_SSL_HAVE_CCM) || defined(MBEDTLS_SSL_HAVE_GCM) || \ defined(MBEDTLS_SSL_HAVE_CHACHAPOLY) ) #error "MBEDTLS_SSL_CONTEXT_SERIALIZATION defined, but not all prerequisites" #endif /* Reject attempts to enable options that have been removed and that could * cause a build to succeed but with features removed. */ #if defined(MBEDTLS_HAVEGE_C) //no-check-names #error "MBEDTLS_HAVEGE_C was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/2599" #endif #if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) //no-check-names #error "MBEDTLS_SSL_HW_RECORD_ACCEL was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031" #endif #if defined(MBEDTLS_SSL_PROTO_SSL3) //no-check-names #error "MBEDTLS_SSL_PROTO_SSL3 (SSL v3.0 support) was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031" #endif #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) //no-check-names #error "MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO (SSL v2 ClientHello support) was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031" #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) //no-check-names #error "MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT (compatibility with the buggy implementation of truncated HMAC in Mbed TLS up to 2.7) was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031" #endif #if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES) //no-check-names #error "MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES was removed in Mbed TLS 3.0. See the ChangeLog entry if you really need SHA-1-signed certificates." #endif #if defined(MBEDTLS_ZLIB_SUPPORT) //no-check-names #error "MBEDTLS_ZLIB_SUPPORT was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031" #endif #if defined(MBEDTLS_CHECK_PARAMS) //no-check-names #error "MBEDTLS_CHECK_PARAMS was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4313" #endif #if defined(MBEDTLS_SSL_CID_PADDING_GRANULARITY) //no-check-names #error "MBEDTLS_SSL_CID_PADDING_GRANULARITY was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4335" #endif #if defined(MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY) //no-check-names #error "MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4335" #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) //no-check-names #error "MBEDTLS_SSL_TRUNCATED_HMAC was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4341" #endif #if defined(MBEDTLS_PKCS7_C) && ( ( !defined(MBEDTLS_ASN1_PARSE_C) ) || \ ( !defined(MBEDTLS_OID_C) ) || ( !defined(MBEDTLS_PK_PARSE_C) ) || \ ( !defined(MBEDTLS_X509_CRT_PARSE_C) ) || \ ( !defined(MBEDTLS_X509_CRL_PARSE_C) ) || \ ( !defined(MBEDTLS_MD_C) ) ) #error "MBEDTLS_PKCS7_C is defined, but not all prerequisites" #endif /* * Avoid warning from -pedantic. This is a convenient place for this * workaround since this is included by every single file before the * #if defined(MBEDTLS_xxx_C) that results in empty translation units. */ typedef int mbedtls_iso_c_forbids_empty_translation_units; /* *INDENT-ON* */ #endif /* MBEDTLS_CHECK_CONFIG_H */ keyring/src/mbedtls/private_access.h0000644000176200001440000000066315006370264017317 0ustar liggesusers/** * \file private_access.h * * \brief Macro wrapper for struct's members. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_PRIVATE_ACCESS_H #define MBEDTLS_PRIVATE_ACCESS_H #ifndef MBEDTLS_ALLOW_PRIVATE_ACCESS #define MBEDTLS_PRIVATE(member) private_##member #else #define MBEDTLS_PRIVATE(member) member #endif #endif /* MBEDTLS_PRIVATE_ACCESS_H */ keyring/src/poly1305_donna64.h0000644000176200001440000001223614775227066015533 0ustar liggesusers/* poly1305 implementation using 64 bit * 64 bit = 128 bit multiplication and 128 bit addition */ #include "private/common.h" #define MUL(out, x, y) out = ((uint128_t) x * y) #define ADD(out, in) out += in #define ADDLO(out, in) out += in #define SHR(in, shift) (unsigned long long) (in >> (shift)) #define LO(in) (unsigned long long) (in) #if defined(_MSC_VER) # define POLY1305_NOINLINE __declspec(noinline) #elif defined(__clang__) || defined(__GNUC__) # define POLY1305_NOINLINE __attribute__((noinline)) #else # define POLY1305_NOINLINE #endif #define poly1305_block_size 16 /* 17 + sizeof(unsigned long long) + 8*sizeof(unsigned long long) */ typedef struct poly1305_state_internal_t { unsigned long long r[3]; unsigned long long h[3]; unsigned long long pad[2]; unsigned long long leftover; unsigned char buffer[poly1305_block_size]; unsigned char final; } poly1305_state_internal_t; static void poly1305_init(poly1305_state_internal_t *st, const unsigned char key[32]) { unsigned long long t0, t1; /* r &= 0xffffffc0ffffffc0ffffffc0fffffff */ t0 = LOAD64_LE(&key[0]); t1 = LOAD64_LE(&key[8]); /* wiped after finalization */ st->r[0] = (t0) & 0xffc0fffffff; st->r[1] = ((t0 >> 44) | (t1 << 20)) & 0xfffffc0ffff; st->r[2] = ((t1 >> 24)) & 0x00ffffffc0f; /* h = 0 */ st->h[0] = 0; st->h[1] = 0; st->h[2] = 0; /* save pad for later */ st->pad[0] = LOAD64_LE(&key[16]); st->pad[1] = LOAD64_LE(&key[24]); st->leftover = 0; st->final = 0; } static void poly1305_blocks(poly1305_state_internal_t *st, const unsigned char *m, unsigned long long bytes) { const unsigned long long hibit = (st->final) ? 0ULL : (1ULL << 40); /* 1 << 128 */ unsigned long long r0, r1, r2; unsigned long long s1, s2; unsigned long long h0, h1, h2; unsigned long long c; uint128_t d0, d1, d2, d; r0 = st->r[0]; r1 = st->r[1]; r2 = st->r[2]; h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; s1 = r1 * (5 << 2); s2 = r2 * (5 << 2); while (bytes >= poly1305_block_size) { unsigned long long t0, t1; /* h += m[i] */ t0 = LOAD64_LE(&m[0]); t1 = LOAD64_LE(&m[8]); h0 += t0 & 0xfffffffffff; h1 += ((t0 >> 44) | (t1 << 20)) & 0xfffffffffff; h2 += (((t1 >> 24)) & 0x3ffffffffff) | hibit; /* h *= r */ MUL(d0, h0, r0); MUL(d, h1, s2); ADD(d0, d); MUL(d, h2, s1); ADD(d0, d); MUL(d1, h0, r1); MUL(d, h1, r0); ADD(d1, d); MUL(d, h2, s2); ADD(d1, d); MUL(d2, h0, r2); MUL(d, h1, r1); ADD(d2, d); MUL(d, h2, r0); ADD(d2, d); /* (partial) h %= p */ c = SHR(d0, 44); h0 = LO(d0) & 0xfffffffffff; ADDLO(d1, c); c = SHR(d1, 44); h1 = LO(d1) & 0xfffffffffff; ADDLO(d2, c); c = SHR(d2, 42); h2 = LO(d2) & 0x3ffffffffff; h0 += c * 5; c = (h0 >> 44); h0 &= 0xfffffffffff; h1 += c; m += poly1305_block_size; bytes -= poly1305_block_size; } st->h[0] = h0; st->h[1] = h1; st->h[2] = h2; } static POLY1305_NOINLINE void poly1305_finish(poly1305_state_internal_t *st, unsigned char mac[16]) { unsigned long long h0, h1, h2, c; unsigned long long g0, g1, g2; unsigned long long t0, t1; unsigned long long mask; /* process the remaining block */ if (st->leftover) { unsigned long long i = st->leftover; st->buffer[i] = 1; for (i = i + 1; i < poly1305_block_size; i++) { st->buffer[i] = 0; } st->final = 1; poly1305_blocks(st, st->buffer, poly1305_block_size); } /* fully carry h */ h0 = st->h[0]; h1 = st->h[1]; h2 = st->h[2]; c = h1 >> 44; h1 &= 0xfffffffffff; h2 += c; c = h2 >> 42; h2 &= 0x3ffffffffff; h0 += c * 5; c = h0 >> 44; h0 &= 0xfffffffffff; h1 += c; c = h1 >> 44; h1 &= 0xfffffffffff; h2 += c; c = h2 >> 42; h2 &= 0x3ffffffffff; h0 += c * 5; c = h0 >> 44; h0 &= 0xfffffffffff; h1 += c; /* compute h + -p */ g0 = h0 + 5; c = g0 >> 44; g0 &= 0xfffffffffff; g1 = h1 + c; c = g1 >> 44; g1 &= 0xfffffffffff; g2 = h2 + c - (1ULL << 42); /* select h if h < p, or h + -p if h >= p */ mask = (g2 >> ((sizeof(unsigned long long) * 8) - 1)) - 1; g0 &= mask; g1 &= mask; g2 &= mask; mask = ~mask; h0 = (h0 & mask) | g0; h1 = (h1 & mask) | g1; h2 = (h2 & mask) | g2; /* h = (h + pad) */ t0 = st->pad[0]; t1 = st->pad[1]; h0 += ((t0) &0xfffffffffff); c = (h0 >> 44); h0 &= 0xfffffffffff; h1 += (((t0 >> 44) | (t1 << 20)) & 0xfffffffffff) + c; c = (h1 >> 44); h1 &= 0xfffffffffff; h2 += (((t1 >> 24)) & 0x3ffffffffff) + c; h2 &= 0x3ffffffffff; /* mac = h % (2^128) */ h0 = (h0) | (h1 << 44); h1 = (h1 >> 20) | (h2 << 24); STORE64_LE(&mac[0], h0); STORE64_LE(&mac[8], h1); /* zero out the state */ sodium_memzero((void *) st, sizeof *st); } keyring/src/core_salsa_ref.c0000644000176200001440000001133014775227066015642 0ustar liggesusers #include #include #include "crypto_core_salsa20.h" #include "crypto_core_salsa2012.h" #include "crypto_core_salsa208.h" static void crypto_core_salsa(unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c, const int rounds) { uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; uint32_t j0, j1, j2, j3, j4, j5, j6, j7, j8, j9, j10, j11, j12, j13, j14, j15; int i; j0 = x0 = 0x61707865; j5 = x5 = 0x3320646e; j10 = x10 = 0x79622d32; j15 = x15 = 0x6b206574; if (c != NULL) { j0 = x0 = LOAD32_LE(c + 0); j5 = x5 = LOAD32_LE(c + 4); j10 = x10 = LOAD32_LE(c + 8); j15 = x15 = LOAD32_LE(c + 12); } j1 = x1 = LOAD32_LE(k + 0); j2 = x2 = LOAD32_LE(k + 4); j3 = x3 = LOAD32_LE(k + 8); j4 = x4 = LOAD32_LE(k + 12); j11 = x11 = LOAD32_LE(k + 16); j12 = x12 = LOAD32_LE(k + 20); j13 = x13 = LOAD32_LE(k + 24); j14 = x14 = LOAD32_LE(k + 28); j6 = x6 = LOAD32_LE(in + 0); j7 = x7 = LOAD32_LE(in + 4); j8 = x8 = LOAD32_LE(in + 8); j9 = x9 = LOAD32_LE(in + 12); for (i = 0; i < rounds; i += 2) { x4 ^= ROTL32(x0 + x12, 7); x8 ^= ROTL32(x4 + x0, 9); x12 ^= ROTL32(x8 + x4, 13); x0 ^= ROTL32(x12 + x8, 18); x9 ^= ROTL32(x5 + x1, 7); x13 ^= ROTL32(x9 + x5, 9); x1 ^= ROTL32(x13 + x9, 13); x5 ^= ROTL32(x1 + x13, 18); x14 ^= ROTL32(x10 + x6, 7); x2 ^= ROTL32(x14 + x10, 9); x6 ^= ROTL32(x2 + x14, 13); x10 ^= ROTL32(x6 + x2, 18); x3 ^= ROTL32(x15 + x11, 7); x7 ^= ROTL32(x3 + x15, 9); x11 ^= ROTL32(x7 + x3, 13); x15 ^= ROTL32(x11 + x7, 18); x1 ^= ROTL32(x0 + x3, 7); x2 ^= ROTL32(x1 + x0, 9); x3 ^= ROTL32(x2 + x1, 13); x0 ^= ROTL32(x3 + x2, 18); x6 ^= ROTL32(x5 + x4, 7); x7 ^= ROTL32(x6 + x5, 9); x4 ^= ROTL32(x7 + x6, 13); x5 ^= ROTL32(x4 + x7, 18); x11 ^= ROTL32(x10 + x9, 7); x8 ^= ROTL32(x11 + x10, 9); x9 ^= ROTL32(x8 + x11, 13); x10 ^= ROTL32(x9 + x8, 18); x12 ^= ROTL32(x15 + x14, 7); x13 ^= ROTL32(x12 + x15, 9); x14 ^= ROTL32(x13 + x12, 13); x15 ^= ROTL32(x14 + x13, 18); } STORE32_LE(out + 0, x0 + j0); STORE32_LE(out + 4, x1 + j1); STORE32_LE(out + 8, x2 + j2); STORE32_LE(out + 12, x3 + j3); STORE32_LE(out + 16, x4 + j4); STORE32_LE(out + 20, x5 + j5); STORE32_LE(out + 24, x6 + j6); STORE32_LE(out + 28, x7 + j7); STORE32_LE(out + 32, x8 + j8); STORE32_LE(out + 36, x9 + j9); STORE32_LE(out + 40, x10 + j10); STORE32_LE(out + 44, x11 + j11); STORE32_LE(out + 48, x12 + j12); STORE32_LE(out + 52, x13 + j13); STORE32_LE(out + 56, x14 + j14); STORE32_LE(out + 60, x15 + j15); } int crypto_core_salsa20(unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c) { crypto_core_salsa(out, in, k, c, 20); return 0; } size_t crypto_core_salsa20_outputbytes(void) { return crypto_core_salsa20_OUTPUTBYTES; } size_t crypto_core_salsa20_inputbytes(void) { return crypto_core_salsa20_INPUTBYTES; } size_t crypto_core_salsa20_keybytes(void) { return crypto_core_salsa20_KEYBYTES; } size_t crypto_core_salsa20_constbytes(void) { return crypto_core_salsa20_CONSTBYTES; } #ifndef MINIMAL /* LCOV_EXCL_START */ int crypto_core_salsa2012(unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c) { crypto_core_salsa(out, in, k, c, 12); return 0; } size_t crypto_core_salsa2012_outputbytes(void) { return crypto_core_salsa2012_OUTPUTBYTES; } size_t crypto_core_salsa2012_inputbytes(void) { return crypto_core_salsa2012_INPUTBYTES; } size_t crypto_core_salsa2012_keybytes(void) { return crypto_core_salsa2012_KEYBYTES; } size_t crypto_core_salsa2012_constbytes(void) { return crypto_core_salsa2012_CONSTBYTES; } int crypto_core_salsa208(unsigned char *out, const unsigned char *in, const unsigned char *k, const unsigned char *c) { crypto_core_salsa(out, in, k, c, 8); return 0; } size_t crypto_core_salsa208_outputbytes(void) { return crypto_core_salsa208_OUTPUTBYTES; } size_t crypto_core_salsa208_inputbytes(void) { return crypto_core_salsa208_INPUTBYTES; } size_t crypto_core_salsa208_keybytes(void) { return crypto_core_salsa208_KEYBYTES; } size_t crypto_core_salsa208_constbytes(void) { return crypto_core_salsa208_CONSTBYTES; } /* LCOV_EXCL_END */ #endif keyring/src/platform_util.c0000644000176200001440000002116115006370266015544 0ustar liggesusers/* * Common and shared functions used by multiple modules in the Mbed TLS * library. * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ /* * Ensure gmtime_r is available even with -std=c99; must be defined before * mbedtls_config.h, which pulls in glibc's features.h. Harmless on other platforms * except OpenBSD, where it stops us accessing explicit_bzero. */ #if !defined(_POSIX_C_SOURCE) && !defined(__OpenBSD__) #define _POSIX_C_SOURCE 200112L #endif #if !defined(_GNU_SOURCE) /* Clang requires this to get support for explicit_bzero */ #define _GNU_SOURCE #endif #include "common.h" #include "mbedtls/platform_util.h" #include "mbedtls/platform.h" #include "mbedtls/threading.h" #include #ifndef __STDC_WANT_LIB_EXT1__ #define __STDC_WANT_LIB_EXT1__ 1 /* Ask for the C11 gmtime_s() and memset_s() if available */ #endif #include #if defined(_WIN32) #include #endif // Detect platforms known to support explicit_bzero() #if defined(__GLIBC__) && (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 25) #define MBEDTLS_PLATFORM_HAS_EXPLICIT_BZERO 1 #elif (defined(__FreeBSD__) && (__FreeBSD_version >= 1100037)) || defined(__OpenBSD__) #define MBEDTLS_PLATFORM_HAS_EXPLICIT_BZERO 1 #endif #if !defined(MBEDTLS_PLATFORM_ZEROIZE_ALT) #undef HAVE_MEMORY_SANITIZER #if defined(__has_feature) #if __has_feature(memory_sanitizer) #include #define HAVE_MEMORY_SANITIZER #endif #endif /* * Where possible, we try to detect the presence of a platform-provided * secure memset, such as explicit_bzero(), that is safe against being optimized * out, and use that. * * For other platforms, we provide an implementation that aims not to be * optimized out by the compiler. * * This implementation for mbedtls_platform_zeroize() was inspired from Colin * Percival's blog article at: * * http://www.daemonology.net/blog/2014-09-04-how-to-zero-a-buffer.html * * It uses a volatile function pointer to the standard memset(). Because the * pointer is volatile the compiler expects it to change at * any time and will not optimize out the call that could potentially perform * other operations on the input buffer instead of just setting it to 0. * Nevertheless, as pointed out by davidtgoldblatt on Hacker News * (refer to http://www.daemonology.net/blog/2014-09-05-erratum.html for * details), optimizations of the following form are still possible: * * if (memset_func != memset) * memset_func(buf, 0, len); * * Note that it is extremely difficult to guarantee that * the memset() call will not be optimized out by aggressive compilers * in a portable way. For this reason, Mbed TLS also provides the configuration * option MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure * mbedtls_platform_zeroize() to use a suitable implementation for their * platform and needs. */ #if !defined(MBEDTLS_PLATFORM_HAS_EXPLICIT_BZERO) && !(defined(__STDC_LIB_EXT1__) && \ !defined(__IAR_SYSTEMS_ICC__)) \ && !defined(_WIN32) static void *(*const volatile memset_func)(void *, int, size_t) = memset; #endif void mbedtls_platform_zeroize(void *buf, size_t len) { if (len > 0) { #if defined(MBEDTLS_PLATFORM_HAS_EXPLICIT_BZERO) explicit_bzero(buf, len); #if defined(HAVE_MEMORY_SANITIZER) /* You'd think that Msan would recognize explicit_bzero() as * equivalent to bzero(), but it actually doesn't on several * platforms, including Linux (Ubuntu 20.04). * https://github.com/google/sanitizers/issues/1507 * https://github.com/openssh/openssh-portable/commit/74433a19bb6f4cef607680fa4d1d7d81ca3826aa */ __msan_unpoison(buf, len); #endif #elif defined(__STDC_LIB_EXT1__) && !defined(__IAR_SYSTEMS_ICC__) memset_s(buf, len, 0, len); #elif defined(_WIN32) SecureZeroMemory(buf, len); #else memset_func(buf, 0, len); #endif #if defined(__GNUC__) /* For clang and recent gcc, pretend that we have some assembly that reads the * zero'd memory as an additional protection against being optimised away. */ #if defined(__clang__) || (__GNUC__ >= 10) #if defined(__clang__) # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wvla" #elif defined(MBEDTLS_COMPILER_IS_GCC) # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wvla" #endif asm volatile ("" : : "m" (*(char (*)[len]) buf) :); #if defined(__clang__) # pragma clang diagnostic pop #elif defined(MBEDTLS_COMPILER_IS_GCC) # pragma GCC diagnostic pop #endif #endif #endif } } #endif /* MBEDTLS_PLATFORM_ZEROIZE_ALT */ void mbedtls_zeroize_and_free(void *buf, size_t len) { if (buf != NULL) { mbedtls_platform_zeroize(buf, len); } mbedtls_free(buf); } #if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_PLATFORM_GMTIME_R_ALT) #include #if !defined(_WIN32) && (defined(unix) || \ defined(__unix) || defined(__unix__) || (defined(__APPLE__) && \ defined(__MACH__)) || defined(__midipix__)) #include #endif /* !_WIN32 && (unix || __unix || __unix__ || * (__APPLE__ && __MACH__) || __midipix__) */ #if !((defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L) || \ (defined(_POSIX_THREAD_SAFE_FUNCTIONS) && \ _POSIX_THREAD_SAFE_FUNCTIONS >= 200112L)) /* * This is a convenience shorthand macro to avoid checking the long * preprocessor conditions above. Ideally, we could expose this macro in * platform_util.h and simply use it in platform_util.c, threading.c and * threading.h. However, this macro is not part of the Mbed TLS public API, so * we keep it private by only defining it in this file */ #if !(defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)) || \ (defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)) #define PLATFORM_UTIL_USE_GMTIME #endif #endif /* !( ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L ) || \ ( defined(_POSIX_THREAD_SAFE_FUNCTIONS ) && \ _POSIX_THREAD_SAFE_FUNCTIONS >= 200112L ) ) */ struct tm *mbedtls_platform_gmtime_r(const mbedtls_time_t *tt, struct tm *tm_buf) { #if defined(_WIN32) && !defined(PLATFORM_UTIL_USE_GMTIME) #if defined(__STDC_LIB_EXT1__) return (gmtime_s(tt, tm_buf) == 0) ? NULL : tm_buf; #else /* MSVC and mingw64 argument order and return value are inconsistent with the C11 standard */ return (gmtime_s(tm_buf, tt) == 0) ? tm_buf : NULL; #endif #elif !defined(PLATFORM_UTIL_USE_GMTIME) return gmtime_r(tt, tm_buf); #else struct tm *lt; #if defined(MBEDTLS_THREADING_C) if (mbedtls_mutex_lock(&mbedtls_threading_gmtime_mutex) != 0) { return NULL; } #endif /* MBEDTLS_THREADING_C */ lt = gmtime(tt); if (lt != NULL) { memcpy(tm_buf, lt, sizeof(struct tm)); } #if defined(MBEDTLS_THREADING_C) if (mbedtls_mutex_unlock(&mbedtls_threading_gmtime_mutex) != 0) { return NULL; } #endif /* MBEDTLS_THREADING_C */ return (lt == NULL) ? NULL : tm_buf; #endif /* _WIN32 && !EFIX64 && !EFI32 */ } #endif /* MBEDTLS_HAVE_TIME_DATE && MBEDTLS_PLATFORM_GMTIME_R_ALT */ #if defined(MBEDTLS_TEST_HOOKS) void (*mbedtls_test_hook_test_fail)(const char *, int, const char *); #endif /* MBEDTLS_TEST_HOOKS */ #if defined(MBEDTLS_HAVE_TIME) && !defined(MBEDTLS_PLATFORM_MS_TIME_ALT) #include #if !defined(_WIN32) && \ (defined(unix) || defined(__unix) || defined(__unix__) || \ (defined(__APPLE__) && defined(__MACH__)) || defined(__HAIKU__) || defined(__midipix__)) #include #endif \ /* !_WIN32 && (unix || __unix || __unix__ || (__APPLE__ && __MACH__) || __HAIKU__ || __midipix__) */ #if (defined(_POSIX_VERSION) && _POSIX_VERSION >= 199309L) || defined(__HAIKU__) mbedtls_ms_time_t mbedtls_ms_time(void) { int ret; struct timespec tv; mbedtls_ms_time_t current_ms; #if defined(__linux__) && defined(CLOCK_BOOTTIME) || defined(__midipix__) ret = clock_gettime(CLOCK_BOOTTIME, &tv); #else ret = clock_gettime(CLOCK_MONOTONIC, &tv); #endif if (ret) { return time(NULL) * 1000; } current_ms = tv.tv_sec; return current_ms*1000 + tv.tv_nsec / 1000000; } #elif defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \ defined(__MINGW32__) || defined(_WIN64) #include mbedtls_ms_time_t mbedtls_ms_time(void) { FILETIME ct; mbedtls_ms_time_t current_ms; GetSystemTimeAsFileTime(&ct); current_ms = ((mbedtls_ms_time_t) ct.dwLowDateTime + ((mbedtls_ms_time_t) (ct.dwHighDateTime) << 32LL))/10000; return current_ms; } #else #error "No mbedtls_ms_time available" #endif #endif /* MBEDTLS_HAVE_TIME && !MBEDTLS_PLATFORM_MS_TIME_ALT */ keyring/src/blake2b-compress-ref.c0000644000176200001440000000562314775227066016610 0ustar liggesusers #include #include #include "blake2.h" #include "sodium.h" CRYPTO_ALIGN(64) static const uint64_t blake2b_IV[8] = { 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL }; static const uint8_t blake2b_sigma[12][16] = { { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 }, { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 }, { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 }, { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 }, { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 }, { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 }, { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 }, { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 }, { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0 }, { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 } }; int blake2b_compress_ref(blake2b_state *S, const uint8_t block[BLAKE2B_BLOCKBYTES]) { uint64_t m[16]; uint64_t v[16]; int i; for (i = 0; i < 16; ++i) { m[i] = LOAD64_LE(block + i * sizeof m[i]); } for (i = 0; i < 8; ++i) { v[i] = S->h[i]; } v[8] = blake2b_IV[0]; v[9] = blake2b_IV[1]; v[10] = blake2b_IV[2]; v[11] = blake2b_IV[3]; v[12] = S->t[0] ^ blake2b_IV[4]; v[13] = S->t[1] ^ blake2b_IV[5]; v[14] = S->f[0] ^ blake2b_IV[6]; v[15] = S->f[1] ^ blake2b_IV[7]; #define G(r, i, a, b, c, d) \ do { \ a += b + m[blake2b_sigma[r][2 * i + 0]]; \ d = ROTR64(d ^ a, 32); \ c += d; \ b = ROTR64(b ^ c, 24); \ a += b + m[blake2b_sigma[r][2 * i + 1]]; \ d = ROTR64(d ^ a, 16); \ c += d; \ b = ROTR64(b ^ c, 63); \ } while (0) #define ROUND(r) \ do { \ G(r, 0, v[0], v[4], v[8], v[12]); \ G(r, 1, v[1], v[5], v[9], v[13]); \ G(r, 2, v[2], v[6], v[10], v[14]); \ G(r, 3, v[3], v[7], v[11], v[15]); \ G(r, 4, v[0], v[5], v[10], v[15]); \ G(r, 5, v[1], v[6], v[11], v[12]); \ G(r, 6, v[2], v[7], v[8], v[13]); \ G(r, 7, v[3], v[4], v[9], v[14]); \ } while (0) ROUND(0); ROUND(1); ROUND(2); ROUND(3); ROUND(4); ROUND(5); ROUND(6); ROUND(7); ROUND(8); ROUND(9); ROUND(10); ROUND(11); for (i = 0; i < 8; ++i) { S->h[i] = S->h[i] ^ v[i] ^ v[i + 8]; } #undef G #undef ROUND return 0; } keyring/src/common.h0000644000176200001440000004035015006370264014157 0ustar liggesusers/** * \file common.h * * \brief Utility macros for internal use in the library */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later */ #ifndef MBEDTLS_LIBRARY_COMMON_H #define MBEDTLS_LIBRARY_COMMON_H #include "mbedtls/build_info.h" #include "alignment.h" #include #include #include #include #if defined(__ARM_NEON) #include #define MBEDTLS_HAVE_NEON_INTRINSICS #elif defined(MBEDTLS_PLATFORM_IS_WINDOWS_ON_ARM64) #include #define MBEDTLS_HAVE_NEON_INTRINSICS #endif /** Helper to define a function as static except when building invasive tests. * * If a function is only used inside its own source file and should be * declared `static` to allow the compiler to optimize for code size, * but that function has unit tests, define it with * ``` * MBEDTLS_STATIC_TESTABLE int mbedtls_foo(...) { ... } * ``` * and declare it in a header in the `library/` directory with * ``` * #if defined(MBEDTLS_TEST_HOOKS) * int mbedtls_foo(...); * #endif * ``` */ #if defined(MBEDTLS_TEST_HOOKS) #define MBEDTLS_STATIC_TESTABLE #else #define MBEDTLS_STATIC_TESTABLE static #endif #if defined(MBEDTLS_TEST_HOOKS) extern void (*mbedtls_test_hook_test_fail)(const char *test, int line, const char *file); #define MBEDTLS_TEST_HOOK_TEST_ASSERT(TEST) \ do { \ if ((!(TEST)) && ((*mbedtls_test_hook_test_fail) != NULL)) \ { \ (*mbedtls_test_hook_test_fail)( #TEST, __LINE__, __FILE__); \ } \ } while (0) #else #define MBEDTLS_TEST_HOOK_TEST_ASSERT(TEST) #endif /* defined(MBEDTLS_TEST_HOOKS) */ /** \def ARRAY_LENGTH * Return the number of elements of a static or stack array. * * \param array A value of array (not pointer) type. * * \return The number of elements of the array. */ /* A correct implementation of ARRAY_LENGTH, but which silently gives * a nonsensical result if called with a pointer rather than an array. */ #define ARRAY_LENGTH_UNSAFE(array) \ (sizeof(array) / sizeof(*(array))) #if defined(__GNUC__) /* Test if arg and &(arg)[0] have the same type. This is true if arg is * an array but not if it's a pointer. */ #define IS_ARRAY_NOT_POINTER(arg) \ (!__builtin_types_compatible_p(__typeof__(arg), \ __typeof__(&(arg)[0]))) /* A compile-time constant with the value 0. If `const_expr` is not a * compile-time constant with a nonzero value, cause a compile-time error. */ #define STATIC_ASSERT_EXPR(const_expr) \ (0 && sizeof(struct { unsigned int STATIC_ASSERT : 1 - 2 * !(const_expr); })) /* Return the scalar value `value` (possibly promoted). This is a compile-time * constant if `value` is. `condition` must be a compile-time constant. * If `condition` is false, arrange to cause a compile-time error. */ #define STATIC_ASSERT_THEN_RETURN(condition, value) \ (STATIC_ASSERT_EXPR(condition) ? 0 : (value)) #define ARRAY_LENGTH(array) \ (STATIC_ASSERT_THEN_RETURN(IS_ARRAY_NOT_POINTER(array), \ ARRAY_LENGTH_UNSAFE(array))) #else /* If we aren't sure the compiler supports our non-standard tricks, * fall back to the unsafe implementation. */ #define ARRAY_LENGTH(array) ARRAY_LENGTH_UNSAFE(array) #endif /** Allow library to access its structs' private members. * * Although structs defined in header files are publicly available, * their members are private and should not be accessed by the user. */ #define MBEDTLS_ALLOW_PRIVATE_ACCESS 1 /** * \brief Securely zeroize a buffer then free it. * * Similar to making consecutive calls to * \c mbedtls_platform_zeroize() and \c mbedtls_free(), but has * code size savings, and potential for optimisation in the future. * * Guaranteed to be a no-op if \p buf is \c NULL and \p len is 0. * * \param buf Buffer to be zeroized then freed. * \param len Length of the buffer in bytes */ void mbedtls_zeroize_and_free(void *buf, size_t len); /** Return an offset into a buffer. * * This is just the addition of an offset to a pointer, except that this * function also accepts an offset of 0 into a buffer whose pointer is null. * (`p + n` has undefined behavior when `p` is null, even when `n == 0`. * A null pointer is a valid buffer pointer when the size is 0, for example * as the result of `malloc(0)` on some platforms.) * * \param p Pointer to a buffer of at least n bytes. * This may be \p NULL if \p n is zero. * \param n An offset in bytes. * \return Pointer to offset \p n in the buffer \p p. * Note that this is only a valid pointer if the size of the * buffer is at least \p n + 1. */ static inline unsigned char *mbedtls_buffer_offset( unsigned char *p, size_t n) { return p == NULL ? NULL : p + n; } /** Return an offset into a read-only buffer. * * Similar to mbedtls_buffer_offset(), but for const pointers. * * \param p Pointer to a buffer of at least n bytes. * This may be \p NULL if \p n is zero. * \param n An offset in bytes. * \return Pointer to offset \p n in the buffer \p p. * Note that this is only a valid pointer if the size of the * buffer is at least \p n + 1. */ static inline const unsigned char *mbedtls_buffer_offset_const( const unsigned char *p, size_t n) { return p == NULL ? NULL : p + n; } /* Always inline mbedtls_xor() for similar reasons as mbedtls_xor_no_simd(). */ #if defined(__IAR_SYSTEMS_ICC__) #pragma inline = forced #elif defined(__GNUC__) __attribute__((always_inline)) #endif /** * Perform a fast block XOR operation, such that * r[i] = a[i] ^ b[i] where 0 <= i < n * * \param r Pointer to result (buffer of at least \p n bytes). \p r * may be equal to either \p a or \p b, but behaviour when * it overlaps in other ways is undefined. * \param a Pointer to input (buffer of at least \p n bytes) * \param b Pointer to input (buffer of at least \p n bytes) * \param n Number of bytes to process. * * \note Depending on the situation, it may be faster to use either mbedtls_xor() or * mbedtls_xor_no_simd() (these are functionally equivalent). * If the result is used immediately after the xor operation in non-SIMD code (e.g, in * AES-CBC), there may be additional latency to transfer the data from SIMD to scalar * registers, and in this case, mbedtls_xor_no_simd() may be faster. In other cases where * the result is not used immediately (e.g., in AES-CTR), mbedtls_xor() may be faster. * For targets without SIMD support, they will behave the same. */ static inline void mbedtls_xor(unsigned char *r, const unsigned char *a, const unsigned char *b, size_t n) { size_t i = 0; #if defined(MBEDTLS_EFFICIENT_UNALIGNED_ACCESS) #if defined(MBEDTLS_HAVE_NEON_INTRINSICS) && \ (!(defined(MBEDTLS_COMPILER_IS_GCC) && MBEDTLS_GCC_VERSION < 70300)) /* Old GCC versions generate a warning here, so disable the NEON path for these compilers */ for (; (i + 16) <= n; i += 16) { uint8x16_t v1 = vld1q_u8(a + i); uint8x16_t v2 = vld1q_u8(b + i); uint8x16_t x = veorq_u8(v1, v2); vst1q_u8(r + i, x); } #if defined(__IAR_SYSTEMS_ICC__) /* This if statement helps some compilers (e.g., IAR) optimise out the byte-by-byte tail case * where n is a constant multiple of 16. * For other compilers (e.g. recent gcc and clang) it makes no difference if n is a compile-time * constant, and is a very small perf regression if n is not a compile-time constant. */ if (n % 16 == 0) { return; } #endif #elif defined(MBEDTLS_ARCH_IS_X64) || defined(MBEDTLS_ARCH_IS_ARM64) /* This codepath probably only makes sense on architectures with 64-bit registers */ for (; (i + 8) <= n; i += 8) { uint64_t x = mbedtls_get_unaligned_uint64(a + i) ^ mbedtls_get_unaligned_uint64(b + i); mbedtls_put_unaligned_uint64(r + i, x); } #if defined(__IAR_SYSTEMS_ICC__) if (n % 8 == 0) { return; } #endif #else for (; (i + 4) <= n; i += 4) { uint32_t x = mbedtls_get_unaligned_uint32(a + i) ^ mbedtls_get_unaligned_uint32(b + i); mbedtls_put_unaligned_uint32(r + i, x); } #if defined(__IAR_SYSTEMS_ICC__) if (n % 4 == 0) { return; } #endif #endif #endif for (; i < n; i++) { r[i] = a[i] ^ b[i]; } } /* Always inline mbedtls_xor_no_simd() as we see significant perf regressions when it does not get * inlined (e.g., observed about 3x perf difference in gcm_mult_largetable with gcc 7 - 12) */ #if defined(__IAR_SYSTEMS_ICC__) #pragma inline = forced #elif defined(__GNUC__) __attribute__((always_inline)) #endif /** * Perform a fast block XOR operation, such that * r[i] = a[i] ^ b[i] where 0 <= i < n * * In some situations, this can perform better than mbedtls_xor() (e.g., it's about 5% * better in AES-CBC). * * \param r Pointer to result (buffer of at least \p n bytes). \p r * may be equal to either \p a or \p b, but behaviour when * it overlaps in other ways is undefined. * \param a Pointer to input (buffer of at least \p n bytes) * \param b Pointer to input (buffer of at least \p n bytes) * \param n Number of bytes to process. * * \note Depending on the situation, it may be faster to use either mbedtls_xor() or * mbedtls_xor_no_simd() (these are functionally equivalent). * If the result is used immediately after the xor operation in non-SIMD code (e.g, in * AES-CBC), there may be additional latency to transfer the data from SIMD to scalar * registers, and in this case, mbedtls_xor_no_simd() may be faster. In other cases where * the result is not used immediately (e.g., in AES-CTR), mbedtls_xor() may be faster. * For targets without SIMD support, they will behave the same. */ static inline void mbedtls_xor_no_simd(unsigned char *r, const unsigned char *a, const unsigned char *b, size_t n) { size_t i = 0; #if defined(MBEDTLS_EFFICIENT_UNALIGNED_ACCESS) #if defined(MBEDTLS_ARCH_IS_X64) || defined(MBEDTLS_ARCH_IS_ARM64) /* This codepath probably only makes sense on architectures with 64-bit registers */ for (; (i + 8) <= n; i += 8) { uint64_t x = mbedtls_get_unaligned_uint64(a + i) ^ mbedtls_get_unaligned_uint64(b + i); mbedtls_put_unaligned_uint64(r + i, x); } #if defined(__IAR_SYSTEMS_ICC__) /* This if statement helps some compilers (e.g., IAR) optimise out the byte-by-byte tail case * where n is a constant multiple of 8. * For other compilers (e.g. recent gcc and clang) it makes no difference if n is a compile-time * constant, and is a very small perf regression if n is not a compile-time constant. */ if (n % 8 == 0) { return; } #endif #else for (; (i + 4) <= n; i += 4) { uint32_t x = mbedtls_get_unaligned_uint32(a + i) ^ mbedtls_get_unaligned_uint32(b + i); mbedtls_put_unaligned_uint32(r + i, x); } #if defined(__IAR_SYSTEMS_ICC__) if (n % 4 == 0) { return; } #endif #endif #endif for (; i < n; i++) { r[i] = a[i] ^ b[i]; } } /* Fix MSVC C99 compatible issue * MSVC support __func__ from visual studio 2015( 1900 ) * Use MSVC predefine macro to avoid name check fail. */ #if (defined(_MSC_VER) && (_MSC_VER <= 1900)) #define /*no-check-names*/ __func__ __FUNCTION__ #endif /* Define `asm` for compilers which don't define it. */ /* *INDENT-OFF* */ #ifndef asm #if defined(__IAR_SYSTEMS_ICC__) #define asm __asm #else #define asm __asm__ #endif #endif /* *INDENT-ON* */ /* * Define the constraint used for read-only pointer operands to aarch64 asm. * * This is normally the usual "r", but for aarch64_32 (aka ILP32, * as found in watchos), "p" is required to avoid warnings from clang. * * Note that clang does not recognise '+p' or '=p', and armclang * does not recognise 'p' at all. Therefore, to update a pointer from * aarch64 assembly, it is necessary to use something like: * * uintptr_t uptr = (uintptr_t) ptr; * asm( "ldr x4, [%x0], #8" ... : "+r" (uptr) : : ) * ptr = (void*) uptr; * * Note that the "x" in "%x0" is neccessary; writing "%0" will cause warnings. */ #if defined(__aarch64__) && defined(MBEDTLS_HAVE_ASM) #if UINTPTR_MAX == 0xfffffffful /* ILP32: Specify the pointer operand slightly differently, as per #7787. */ #define MBEDTLS_ASM_AARCH64_PTR_CONSTRAINT "p" #elif UINTPTR_MAX == 0xfffffffffffffffful /* Normal case (64-bit pointers): use "r" as the constraint for pointer operands to asm */ #define MBEDTLS_ASM_AARCH64_PTR_CONSTRAINT "r" #else #error "Unrecognised pointer size for aarch64" #endif #endif /* Always provide a static assert macro, so it can be used unconditionally. * It does nothing on systems where we don't know how to define a static assert. */ /* Can't use the C11-style `defined(static_assert)` on FreeBSD, since it * defines static_assert even with -std=c99, but then complains about it. */ #if defined(static_assert) && !defined(__FreeBSD__) #define MBEDTLS_STATIC_ASSERT(expr, msg) static_assert(expr, msg) #else /* Make sure `MBEDTLS_STATIC_ASSERT(expr, msg);` is valid both inside and * outside a function. We choose a struct declaration, which can be repeated * any number of times and does not need a matching definition. */ #define MBEDTLS_STATIC_ASSERT(expr, msg) \ struct ISO_C_does_not_allow_extra_semicolon_outside_of_a_function #endif #if defined(__has_builtin) #define MBEDTLS_HAS_BUILTIN(x) __has_builtin(x) #else #define MBEDTLS_HAS_BUILTIN(x) 0 #endif /* Define compiler branch hints */ #if MBEDTLS_HAS_BUILTIN(__builtin_expect) #define MBEDTLS_LIKELY(x) __builtin_expect(!!(x), 1) #define MBEDTLS_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define MBEDTLS_LIKELY(x) x #define MBEDTLS_UNLIKELY(x) x #endif /* MBEDTLS_ASSUME may be used to provide additional information to the compiler * which can result in smaller code-size. */ #if MBEDTLS_HAS_BUILTIN(__builtin_assume) /* clang provides __builtin_assume */ #define MBEDTLS_ASSUME(x) __builtin_assume(x) #elif MBEDTLS_HAS_BUILTIN(__builtin_unreachable) /* gcc and IAR can use __builtin_unreachable */ #define MBEDTLS_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while (0) #elif defined(_MSC_VER) /* Supported by MSVC since VS 2005 */ #define MBEDTLS_ASSUME(x) __assume(x) #else #define MBEDTLS_ASSUME(x) do { } while (0) #endif /* For gcc -Os, override with -O2 for a given function. * * This will not affect behaviour for other optimisation settings, e.g. -O0. */ #if defined(MBEDTLS_COMPILER_IS_GCC) && defined(__OPTIMIZE_SIZE__) #define MBEDTLS_OPTIMIZE_FOR_PERFORMANCE __attribute__((optimize("-O2"))) #else #define MBEDTLS_OPTIMIZE_FOR_PERFORMANCE #endif /* Suppress compiler warnings for unused functions and variables. */ #if !defined(MBEDTLS_MAYBE_UNUSED) && defined(__has_attribute) # if __has_attribute(unused) # define MBEDTLS_MAYBE_UNUSED __attribute__((unused)) # endif #endif #if !defined(MBEDTLS_MAYBE_UNUSED) && defined(__GNUC__) # define MBEDTLS_MAYBE_UNUSED __attribute__((unused)) #endif #if !defined(MBEDTLS_MAYBE_UNUSED) && defined(__IAR_SYSTEMS_ICC__) && defined(__VER__) /* IAR does support __attribute__((unused)), but only if the -e flag (extended language support) * is given; the pragma always works. * Unfortunately the pragma affects the rest of the file where it is used, but this is harmless. * Check for version 5.2 or later - this pragma may be supported by earlier versions, but I wasn't * able to find documentation). */ # if (__VER__ >= 5020000) # define MBEDTLS_MAYBE_UNUSED _Pragma("diag_suppress=Pe177") # endif #endif #if !defined(MBEDTLS_MAYBE_UNUSED) && defined(_MSC_VER) # define MBEDTLS_MAYBE_UNUSED __pragma(warning(suppress:4189)) #endif #if !defined(MBEDTLS_MAYBE_UNUSED) # define MBEDTLS_MAYBE_UNUSED #endif #endif /* MBEDTLS_LIBRARY_COMMON_H */ keyring/src/salsa20_ref.h0000644000176200001440000000026714775227066015010 0ustar liggesusers #include #include "stream_salsa20.h" #include "crypto_stream_salsa20.h" extern struct crypto_stream_salsa20_implementation crypto_stream_salsa20_ref_implementation; keyring/src/base64.c0000644000176200001440000001066415006370264013753 0ustar liggesusers #ifndef _GNU_SOURCE #define _GNU_SOURCE 1 #endif #include #include #define BASE64_ENCODE_OUT_SIZE(s) ((unsigned int)((((s) + 2) / 3) * 4)) #define BASE64_DECODE_OUT_SIZE(s) ((unsigned int)(((s) / 4) * 3)) #define BASE64_PAD '=' /* BASE 64 encode table */ static const char base64en[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', }; /* ASCII order for BASE 64 decode, 255 in unused character */ static const unsigned char base64de[] = { /* nul, soh, stx, etx, eot, enq, ack, bel, */ 255, 255, 255, 255, 255, 255, 255, 255, /* bs, ht, nl, vt, np, cr, so, si, */ 255, 255, 255, 255, 255, 255, 255, 255, /* dle, dc1, dc2, dc3, dc4, nak, syn, etb, */ 255, 255, 255, 255, 255, 255, 255, 255, /* can, em, sub, esc, fs, gs, rs, us, */ 255, 255, 255, 255, 255, 255, 255, 255, /* sp, '!', '"', '#', '$', '%', '&', ''', */ 255, 255, 255, 255, 255, 255, 255, 255, /* '(', ')', '*', '+', ',', '-', '.', '/', */ 255, 255, 255, 62, 255, 255, 255, 63, /* '0', '1', '2', '3', '4', '5', '6', '7', */ 52, 53, 54, 55, 56, 57, 58, 59, /* '8', '9', ':', ';', '<', '=', '>', '?', */ 60, 61, 255, 255, 255, 255, 255, 255, /* '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', */ 255, 0, 1, 2, 3, 4, 5, 6, /* 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', */ 7, 8, 9, 10, 11, 12, 13, 14, /* 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', */ 15, 16, 17, 18, 19, 20, 21, 22, /* 'X', 'Y', 'Z', '[', '\', ']', '^', '_', */ 23, 24, 25, 255, 255, 255, 255, 255, /* '`', 'a', 'b', 'c', 'd', 'e', 'f', 'g', */ 255, 26, 27, 28, 29, 30, 31, 32, /* 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', */ 33, 34, 35, 36, 37, 38, 39, 40, /* 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', */ 41, 42, 43, 44, 45, 46, 47, 48, /* 'x', 'y', 'z', '{', '|', '}', '~', del, */ 49, 50, 51, 255, 255, 255, 255, 255 }; SEXP keyring_base64_encode(SEXP array) { const unsigned char *in = RAW(array); unsigned int inlen = LENGTH(array); unsigned int outlen = BASE64_ENCODE_OUT_SIZE(inlen); SEXP rout = PROTECT(allocVector(RAWSXP, outlen)); unsigned char *out = (unsigned char*) RAW(rout); int s; unsigned int i; unsigned int j; unsigned char c; unsigned char l; s = 0; l = 0; for (i = j = 0; i < inlen; i++) { c = in[i]; switch (s) { case 0: s = 1; out[j++] = base64en[(c >> 2) & 0x3F]; break; case 1: s = 2; out[j++] = base64en[((l & 0x3) << 4) | ((c >> 4) & 0xF)]; break; case 2: s = 0; out[j++] = base64en[((l & 0xF) << 2) | ((c >> 6) & 0x3)]; out[j++] = base64en[c & 0x3F]; break; } l = c; } switch (s) { case 1: out[j++] = base64en[(l & 0x3) << 4]; out[j++] = BASE64_PAD; out[j++] = BASE64_PAD; break; case 2: out[j++] = base64en[(l & 0xF) << 2]; out[j++] = BASE64_PAD; break; } UNPROTECT(1); return rout; } SEXP keyring_base64_decode(SEXP array) { const unsigned char *in = (const unsigned char*) RAW(array); unsigned int inlen = LENGTH(array); unsigned int outlen = BASE64_DECODE_OUT_SIZE(inlen); SEXP rout = PROTECT(allocVector(RAWSXP, outlen)); unsigned char *out = RAW(rout); unsigned int i; unsigned int j; unsigned char c; if (inlen & 0x3) { UNPROTECT(1); return rout; } for (i = j = 0; i < inlen; i++) { if (in[i] == BASE64_PAD) { break; } if (in[i] < 0) { UNPROTECT(1); return rout; } c = base64de[in[i]]; if (c == 255) { UNPROTECT(1); return rout; } switch (i & 0x3) { case 0: out[j] = (c << 2) & 0xFF; break; case 1: out[j++] |= (c >> 4) & 0x3; out[j] = (unsigned char)((c & 0xF) << 4); break; case 2: out[j++] |= (c >> 2) & 0xF; out[j] = (unsigned char)((c & 0x3) << 6); break; case 3: out[j++] |= c; break; } } /* We might have allocated to much space, because of the padding... */ if (j < outlen) { SEXP rout2 = PROTECT(allocVector(RAWSXP, j)); memcpy(RAW(rout2), RAW(rout), j); UNPROTECT(2); return rout2; } else { UNPROTECT(1); return rout; } } keyring/src/poly1305_donna.c0000644000176200001440000000656414775227066015363 0ustar liggesusers #include "poly1305_donna.h" #include "crypto_verify_16.h" #ifdef HAVE_TI_MODE #include "poly1305_donna64.h" #else #include "poly1305_donna32.h" #endif #include "onetimeauth_poly1305.h" static void poly1305_update(poly1305_state_internal_t *st, const unsigned char *m, unsigned long long bytes) { unsigned long long i; /* handle leftover */ if (st->leftover) { unsigned long long want = (poly1305_block_size - st->leftover); if (want > bytes) { want = bytes; } for (i = 0; i < want; i++) { st->buffer[st->leftover + i] = m[i]; } bytes -= want; m += want; st->leftover += want; if (st->leftover < poly1305_block_size) { return; } poly1305_blocks(st, st->buffer, poly1305_block_size); st->leftover = 0; } /* process full blocks */ if (bytes >= poly1305_block_size) { unsigned long long want = (bytes & ~(poly1305_block_size - 1)); poly1305_blocks(st, m, want); m += want; bytes -= want; } /* store leftover */ if (bytes) { for (i = 0; i < bytes; i++) { st->buffer[st->leftover + i] = m[i]; } st->leftover += bytes; } } static int crypto_onetimeauth_poly1305_donna(unsigned char *out, const unsigned char *m, unsigned long long inlen, const unsigned char *key) { CRYPTO_ALIGN(64) poly1305_state_internal_t state; poly1305_init(&state, key); poly1305_update(&state, m, inlen); poly1305_finish(&state, out); return 0; } static int crypto_onetimeauth_poly1305_donna_init(crypto_onetimeauth_poly1305_state *state, const unsigned char *key) { COMPILER_ASSERT(sizeof(crypto_onetimeauth_poly1305_state) >= sizeof(poly1305_state_internal_t)); poly1305_init((poly1305_state_internal_t *) (void *) state, key); return 0; } static int crypto_onetimeauth_poly1305_donna_update( crypto_onetimeauth_poly1305_state *state, const unsigned char *in, unsigned long long inlen) { poly1305_update((poly1305_state_internal_t *) (void *) state, in, inlen); return 0; } static int crypto_onetimeauth_poly1305_donna_final( crypto_onetimeauth_poly1305_state *state, unsigned char *out) { poly1305_finish((poly1305_state_internal_t *) (void *) state, out); return 0; } static int crypto_onetimeauth_poly1305_donna_verify(const unsigned char *h, const unsigned char *in, unsigned long long inlen, const unsigned char *k) { unsigned char correct[16]; crypto_onetimeauth_poly1305_donna(correct, in, inlen, k); return crypto_verify_16(h, correct); } struct crypto_onetimeauth_poly1305_implementation crypto_onetimeauth_poly1305_donna_implementation = { SODIUM_C99(.onetimeauth =) crypto_onetimeauth_poly1305_donna, SODIUM_C99(.onetimeauth_verify =) crypto_onetimeauth_poly1305_donna_verify, SODIUM_C99(.onetimeauth_init =) crypto_onetimeauth_poly1305_donna_init, SODIUM_C99(.onetimeauth_update =) crypto_onetimeauth_poly1305_donna_update, SODIUM_C99(.onetimeauth_final =) crypto_onetimeauth_poly1305_donna_final }; keyring/NAMESPACE0000644000176200001440000000127314760120011013134 0ustar liggesusers# Generated by roxygen2: do not edit by hand export(backend) export(backend_env) export(backend_file) export(backend_keyrings) export(backend_macos) export(backend_secret_service) export(backend_wincred) export(default_backend) export(has_keyring_support) export(key_delete) export(key_get) export(key_get_raw) export(key_list) export(key_list_raw) export(key_set) export(key_set_with_raw_value) export(key_set_with_value) export(keyring_create) export(keyring_delete) export(keyring_is_locked) export(keyring_list) export(keyring_lock) export(keyring_unlock) importFrom(R6,R6Class) importFrom(utils,URLdecode) importFrom(utils,head) importFrom(utils,tail) useDynLib(keyring, .registration = TRUE) keyring/LICENSE0000644000176200001440000000010215006370264012723 0ustar liggesusersYEAR: 2025 COPYRIGHT HOLDER: keyring authors, see COPYRIGHTS file keyring/NEWS.md0000644000176200001440000000446415023625455013037 0ustar liggesusers# keyring 1.4.1 * keyring now compiles on FreeBSD, OpenBSD, NetSBD and DragonFlyBSD. # keyring 1.4.0 * Now the "file" backend will only be selected as the default backend (via `default_backend()`) if the system keyring exists for this backend. If you want to use the "file" backend without a system keyring, then you'll need to select it explicitly. See `?default_backend`. * keyring now does not depend on the assertthat, openssl, rappdirs and sodium packages. * New `key_list_raw()` method to return keys as raw vectors (#159). # keyring 1.3.2 * keyring uses safer `*printf()` format strings (Secret Service backend). # keyring 1.3.1 * No user visible changes. # keyring 1.3.0 * `keyring_create()` and also all backends that support multiple keyrings now allow passing the password when creating a new keyring (#114). * `key_set()` can now use a custom prompt (@pnacht, #112). * keyring now handled better the 'Cancel' button when requesting a password in RStudio, and an error is thrown in this case (#106). # keyring 1.2.0 * It is now possible to specify the encoding of secrets on Windows (#88, @awong234). * The `get_raw()` method of the Secret Service backend works now (#87). * Now the file backend is selected by default on Unix systems if Secret Service is not available or does not work (#95, @nwstephens). * The file backend now works with keys that do not have a username. * All backends use the value of the `keyring_username` option, if set, as the default username (#60). # keyring 1.1.0 * File based backend (#53, @nbenn). * Fix bugs in `key_set()` on Linux (#43, #51). * Windows: support non-ascii characters and spaces in `key_list()` `service` and `keyring` (#48, #49, @javierluraschi). * Add support for listing service keys for env backend (#58, @javierluraschi). * keyring is now compatible with R 3.1.x and R 3.2.x. * libsecret is now optional on Linux. If not available, keyring is built without the Secret Service backend (#55). * Fix the `get_raw()` method on Windows. * Windows: `get()` tries the UTF-16LE encoding if the sting has embedded zero bytes. This allows getting secrets that were set in Credential Manager (#56). * Windows: fix `list()` when some secrets have no `:` at all (these were probably set externally) (#44). # keyring 1.0.0 First public release. keyring/inst/0000755000176200001440000000000015006370264012702 5ustar liggesuserskeyring/inst/COPYRIGHTS0000644000176200001440000000303715006370264014323 0ustar liggesusers# libsodium files - `src/blake2.h` - `src/blake2b-compress-ref.c` - `src/blake2b-ref.c` - `src/core_hsalsa20_ref2.c` - `src/core_salsa_ref.c` - `src/crypto_core_hsalsa20.h` - `src/crypto_core_salsa20.h` - `src/crypto_core_salsa2012.h` - `src/crypto_core_salsa208.h` - `src/crypto_generichash.c` - `src/crypto_generichash.h` - `src/crypto_generichash_blake2b.h` - `src/crypto_onetimeauth.h` - `src/crypto_onetimeauth_poly1305.h` - `src/crypto_secretbox.h` - `src/crypto_secretbox_easy.c` - `src/crypto_secretbox_xsalsa20poly1305.h` - `src/crypto_stream_salsa20.h` - `src/crypto_stream_xsalsa20.h` - `src/crypto_verify_16.h` - `src/crypto_verify_32.h` - `src/crypto_verify_64.h` - `src/endianness.h` - `src/generichash_blake2b.c` - `src/onetimeauth_poly1305.c` - `src/onetimeauth_poly1305.h` - `src/poly1305_donna.c` - `src/poly1305_donna.h` - `src/poly1305_donna32.h` - `src/poly1305_donna64.h` - `src/randombytes_sysrandom.c` - `src/salsa20_ref.c` - `src/salsa20_ref.h` - `src/sodium-utils.c` - `src/sodium.c` - `src/sodium.h` - `src/stream_salsa20.c` - `src/stream_salsa20.h` - `src/verify.c` (c) libsodium authors https://github.com/jedisct1/libsodium/graphs/contributors # mbedtls files - `src/aes.c` - `src/aesce.c` - `src/aesni.c` - `src/padlock.c` - `src/aesce.h` - `src/aesni.h` - `src/alignment.h` - `src/common.h` - `src/ctr.h` - `src/padlock.h` - `src/platform_util.c` - `src/mbedtls/*` - `src/psa/*` (c) mbedtls authors https://github.com/Mbed-TLS/mbedtls/graphs/contributors # Other files (c) keyring authors keyring/inst/development-notes.md0000644000176200001440000002256614144472216016711 0ustar liggesusers # Notes for `keyring` developers * [Introduction](#introduction) * [Backend implementation details](#backend-implementation-details) * [macOS Keychain](#macos-keychain) * [Windows Credential Store](#windows-credential-store) * [Multiple keyrings](#multiple-keyrings) * [Secret Service API](#secret-service-api) * [Unloading the package](#unloading-the-package) * [Environment variable backend](#environment-variable-backend) * [Limits on secret sizes](#limits-on-secret-sizes) * [macOS Keychain](#macos-keychain-1) * [Windows Credential Store](#windows-credential-store-1) * [Linux Secret Service](#linux-secret-service) * [Testing the package](#testing-the-package) * [Test keyrings and keyring items](#test-keyrings-and-keyring-items) ## Introduction This document is aimed at developers that want to improve the existing keyring backends, or want to implement new backends. You don't need it for using `keyring`. ## Backend implementation details ### macOS Keychain On macOS, the keyrings are store in files. We handle the user's keyrings, these are in `~/Library/Keychains`. They are files with extension `.keychain` (before Sierra) or `.keychain-db` (starting from Sierra). Whenever a keyring is specified, it can be a symbolic name (e.g. `login`), or an absolute filename (e.g. `/Users/gaborcsardi/Library/Keychains/login.keychain`). If a symbolic name is specified, we look for both `.keychain` and `.keychain-db` files: * If the `.keychain` file exists, we use that. * Otherwise, if the `.keychain-db` file exists, we use that. * Otherwise, if the system is Sierra or later, we use `.keychain-db`. * Otherwise we use the `.keychain` file. ### Windows Credential Store We use the *old* API to the Windows Credential Store. See e.g. https://msdn.microsoft.com/en-us/library/windows/desktop/aa374804%28v%3Dvs.85%29.aspx and also the `CREDENTIAL`, `CredWrite`, `CredDelete`, `CredEnumerate` there. The reason for this is that MinGW does not provide a wrapper to the *new* API, introduced in Windows 8.x. This also means that we don't have access to the secrets stored by recent Windows web browsers (IE and Edge). #### Multiple keyrings The *old* Windows Credential Store does not support multiple keyrings, and it does not support locking and unlocking the (single) keyring, either. For every (non-default) keyring, we create a credential, with target name `keyring::`. This credential contains metadata about the keyring. It currently has the following (DCF, Debian Control File) format: ``` Version: 1.0.0 Verify: NgF+vkkNsOoSnXVXt249u6xknskhDasMIhE8Uuzpl/w= Salt: some random salt ``` The `Verify` tag is used to check if the keyring password that was specified to unlock the keyring, was correct. The `Salt` tag is used to salt the SHA256 hash, to make it more secure. It is generated randomly when the keyring is created. When a keyring is unlocked, the user specifies the pass phrase of the keyring. We create the SHA256 hash of this pass phrase, and this will be the AES key to encrypt/decrypt the items in the keyring. When unlocking a keyring, we use the `Verify` field, to see if the supplied password indeed hashes to the correct AES key. If it can decrypt the `Verify` string, then it is correct. We also store the AES key in the keyring, in a session credential with target name `keyring::unlocked`. A session credential's life time is the life time of a single login session. The AES key is stored in a base64 encoded form, e.g.: ``` JvL7srqc0X1vVnqbSayFnIkJZoe2xMOWoDh+aBR9DJc= ``` The credentials of the keyring itself have target names as `keyring:service:username`, where the username may be empty. If keyring is empty, then the credential is considered to be on the default keyring, and it is not encrypted. Credentials on other keyrings are encrypted using the AES key of the keyring. The random initialization vector of the encryption is stored as the first 16 bytes of the keyring item. When we `set` a key, we need to: 1. Check if the key is on the default keyring. 2. If 1. is TRUE, then just set the key, using target name `:service:username` (username might be empty, servicename not), and finish. 3. Check if the keyring exists. 4. If 3. is FALSE, then error and finish. 5. Check that the keyring is unlocked. 6. If 5. is FALSE, then prompt the user and unlock the keyring. 7. Encrypt the key with the AES key, and store the encrypted key using target name `keyring:service:username` (again, username might be empty, service name not). When we `get` a key, we need to: 1. Check if the key is on the default keyring. 2. If 1. is TRUE, then we just get the key, using target name `:service:username`. 3. Check if the keyring is locked. 4. If 3. is TRUE, then prompt the user and unlock the keyring. 5. Get the AES key from the unlocked keyring. 6. Get the key and use the AES key to decrypt it. To unlock a keyring we need to: 1. Get the keyring password and SHA256 hash it. 2. Try to decrypt the `Verify` field of the keyring metadata, to see if the password was correct. 3. If the password was not correct, then error out. 4. If the password was correct, then store the AES key under target name `keyring::unlocked`. The C functions for this backend do not know about multiple keyrings at all, we just use them to get/set/delete/list "regular" credentials in the credential store. ### Secret Service API The Secret Service API works on DBUS, and multiple daemons support it. On GNOME based systems, typically gnome-keyring, and on KDE based systems typically KWallet is used. Linux systems lacking a GUI typically do not run a secret service daemon, and `keyring` cannot use the OS credential store on these systems. The default backend is the environment variable based one (`backend_env`) on these systems. #### Prompts For the Secret Service backend, it is currently not possible to specify a password for some functions. Instead, the password is read in interactively on this backend, by the system. This currently happens when a new keyring is created, and when a keyring is unlocked. #### Unloading the package `libsecret` uses `libglib`, and `libglib` does not allow unloading the package. More precisely, if you unload the `keyring` package on Linux, then some `libglib` threads will stay around. If you then reload the package, R will crash. This is a known limitation of `libglib`, and there is currently no way around it. For `keyring` a workaround would be to use `libdbus` to communicate with the Secret Service daemon directly. `libdbus` is a standalone DBUS library, it does not use `libglib`. There is an issue for this in our issue tracker, but no plans currently about when it would happen: https://github.com/r-lib/keyring/issues/15 This limitation is especially annoying for development with `devtools`, because `devtools::load_all()`, `devtools::test()`, etc. try to unload and reload the package, which results in crashes. A workaround is to run the tests from the command line: ``` R -e 'devtools::test()' ``` ### Environment variable backend When an item has a username on this backend, the service name and the username is separated with a colon (`:`) character in the created environment variable: ``` service:username ``` Note that shells typically cannot read or write these environment variables. Programming languages, i.e. `Sys.getenv()` and `Sys.setenv()` in R, or the similar functions in Python, C, etc. can read and write them just fine. ## Limits on secret sizes Various backends (and platforms) have various limits on the size of the secrets they can store. In general, the safest to assume that the secret can be maximum about 400 bytes long. If you want to store something longer, encrypt it with AES, and store it in a regular file, and store the AES key in the keyring. See the `openssl` package for AES encryption and decryption. ### macOS Keychain The macOS keychain can store very big secrets. In our experiments it had no problems with a secret of 1GB, although that is already a little slow to encrypt and decrypt. The real limit is probably (much) higher, and it could be the limit on the keychain file's size. ### Windows Credential Store According to the documentation in the Windows Credential Store the maximum secret size is 512 bytes: https://msdn.microsoft.com/en-us/library/windows/desktop/aa374788%28v%3Dvs.85%29.aspx In practice, on Windows 8.1 we managed to store secrets of up to 2560 bytes. Other Windows versions might have other limits, though. Note that if you use the non-default keyring, then the actual secret stored by `keyring` is longer, because it is encrypted manually, and also BASE64 encoded. Hence the advised 400 bytes limit. ### Linux Secret Service According to our tests with the Secret Service, it can store secrets of at least 25MB. We used an Ubuntu 16.04 system and the gnome-keyring daemon for this. Note, however, that these large secrets only work if you first create a small keyring item, and then update its contents. Creating a large keyring item straight away gives an error. ## Testing the package Testing the package on CIs or local machines is tricky. Here are some notes. ### Test keyrings and keyring items When running tests (and examples), the package only creates keyrings with a name prefix `Rkeyringtest`, and on other keyrings it only creates services with the name prefix `R-keyring-test-service-`. This makes it easier to remove the leftover keyrings and keyring items manually from the system keyring. keyring/README.md0000644000176200001440000000721315015035276013210 0ustar liggesusers # keyring [![R-CMD-check](https://github.com/r-lib/keyring/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/r-lib/keyring/actions/workflows/R-CMD-check.yaml) [![Codecov test coverage](https://codecov.io/gh/r-lib/keyring/graph/badge.svg)](https://app.codecov.io/gh/r-lib/keyring) [![](https://www.r-pkg.org/badges/version/keyring)](https://www.r-pkg.org/pkg/keyring) [![CRAN RStudio mirror downloads](https://cranlogs.r-pkg.org/badges/keyring)](https://www.r-pkg.org/pkg/keyring) keyring provides a way to securely manage secrets using your operating system’s credential store. Once a secret is defined, it persists in a “keyring” across multiple R sessions. keyring is an alternative to using environment variables that’s a bit more secure because your secret is never stored in plain text, meaning that you can for instance never accidentally upload it to GitHub. For more security, you can also store secrets in a custom keyring that always requires a password to unlock. keyring currently supports: - The macOS Keychain (`backend_macos`). - The Windows Credential Store (`backend_wincred`). - The Linux Secret Service API (`backend_secret_service`). It also provides two backends that are available on all platforms: - Encrypted files (`backend_file`) - Environment variables (`backend_env`). ## Installation Install the package from CRAN: ``` r # install.packages("pak") pak::pak("keyring") ``` We recommend using pak to install keyring as it will ensure that Linux system requirements are automatically installed (for instance Ubuntu requires `libsecret-1-dev` and `libssl-dev`). To install the development version from GitHub, use: ``` r pak::pak("r-lib/keyring") ``` ## Usage The simplest usage only requires `key_set()` and `key_get()`: ``` r # Interactively save a secret. This avoids typing the value of the secret # into the console as this could be recorded in your `.Rhistory` key_set("secret-name") # Later retrieve that secret key_get("secret-name") ``` Each secret is associated with a keyring. By default, keyring will use the OS keyring (see `default_backend()` for details), which is automatically unlocked when you log into your computer account. That means while the secret is stored securely, it can be accessed by other processes. If you want greater security you can create a custom keyring that you manually lock and unlock. That will require you to enter a custom password every time you want to access your secret. ``` r keyring_create("mypackage") key_set("secret-name", keyring = "mypackage") key_get("secret-name", keyring = "mypackage") ``` Accessing the key unlocks the keyring, so if you’re being really careful, you might want to lock it after you’ve retrieved the value with `keyring_lock()`. ### GitHub When you use keyring on GitHub, it will fall back to the environment variable backend. That means if you want to use `key_get("mysecret")` you need to do two things: - Add a [new action secret](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository) to your repository. - Make the secret available in your workflow `.yml`, for instance ``` yaml env: GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} R_KEEP_PKG_SOURCE: yes MY_SECRET: ${{ secrets.my_secret }} ``` The envvar backend doesn’t support custom keyrings, so if you’re using one locally you’ll need to use the default keyring on GitHub. ## Development documentation Please see our [writeup of some `keyring` internals](https://github.com/r-lib/keyring/blob/main/inst/development-notes.md), and as always, use the source code. keyring/configure0000755000176200001440000000267615023625503013645 0ustar liggesusers#!/usr/bin/env sh UNAME=`uname` echo > src/Makevars PKG_CPPFLAGS="-DMBEDTLS_AES_C -DMBEDTLS_ALLOW_PRIVATE_ACCESS -DMBEDTLS_PLATFORM_PRINTF_ALT -I." if [ "$UNAME" = "Darwin" ]; then echo "PKG_LIBS=-framework Security" >> src/Makevars elif [ -n "$LIBSECRET_CFLAGS" ] && [ -n "$LIBSECRET_LIBS" ]; then echo "Found libsecret from LIBSECRET_CFLAGS and LIBSECRET_LIBS." echo "PKG_CFLAGS=-DHAS_LIBSECRET $LIBSECRET_CFLAGS" >> src/Makevars echo "PKG_LIBS=$LIBSECRET_LIBS" >> src/Makevars elif which pkg-config >/dev/null 2>/dev/null && pkg-config libsecret-1; then echo "Found libsecret via pkg-config." echo "PKG_CFLAGS=-DHAS_LIBSECRET $(pkg-config --cflags libsecret-1)" >> src/Makevars echo "PKG_LIBS=$(pkg-config --libs libsecret-1)" >> src/Makevars else echo "Could not find libsecret headers or libs." echo "On Ubuntu, you need to install libsecret-1-dev via apt." echo "On RedHat, Fedora, and CentOS, you need to install libsecret-devel via yum or dnf." echo "Note that in addition to libsecret, you either need pkg-config or set the" echo "LIBSECRET_CFLAGS and LIBSECRET_LIBS environment variables." echo echo "This keyring build will not support the libsecret backend." fi if [ "$UNAME" = "FreeBSD" ]; then PKG_CPPFLAGS="$PKG_CPPFLAGS -DHAVE_SYS_RANDOM_H" elif [ "$UNAME" = "DragonFly" ]; then PKG_CPPFLAGS="$PKG_CPPFLAGS -DHAVE_SYS_RANDOM_H" fi echo PKG_CPPFLAGS="$PKG_CPPFLAGS" >> src/Makevars keyring/man/0000755000176200001440000000000014760120011012465 5ustar liggesuserskeyring/man/backend.Rd0000644000176200001440000000467514760120011014357 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-class.R \name{backend} \alias{backend} \title{Abstract class of a minimal keyring backend} \description{ To implement a new keyring backend, you need to inherit from this class and then redefine the \code{get}, \code{set}, \code{set_with_value} and \code{delete} methods. Implementing the \code{list} method is optional. Additional methods can be defined as well. } \details{ These are the semantics of the various methods: \if{html}{\out{
}}\preformatted{get(service, username = NULL, keyring = NULL) get_raw(service, username = NULL, keyring = NULL) set(service, username = NULL, keyring = NULL, prompt = "Password: ") set_with_value(service, username = NULL, password = NULL, keyring = NULL) set_with_raw_value(service, username = NULL, password = NULL, keyring = NULL) delete(service, username = NULL, keyring = NULL) list(service = NULL, keyring = NULL) list_raw(service = NULL, keyring = NULL) }\if{html}{\out{
}} What these functions do: \itemize{ \item \code{get()} queries the secret in a keyring item. \item \code{get_raw()} is similar to \code{get()}, but returns the result as a raw vector. \item \code{set()} sets the secret in a keyring item. The secret itself is read in interactively from the keyboard. \item \code{set_with_value()} sets the secret in a keyring item to the specified value. \item \code{set_with_raw_value()} sets the secret in keyring item to the byte sequence of a raw vector. \item \code{delete()} remotes a keyring item. \item \code{list()} lists keyring items. \item \code{list_raw()} lists keyring items, also as raw vectors. } The arguments: \itemize{ \item \code{service} String, the name of a service. This is used to find the secret later. \item \code{username} String, the username associated with a secret. It can be \code{NULL}, if no username belongs to the secret. It uses the value of the \code{keyring_username}, if set. \item \code{keyring} String, the name of the keyring to work with. This only makes sense if the platform supports multiple keyrings. \code{NULL} selects the default (and maybe only) keyring. \item \code{password} The value of the secret, typically a password, or other credential. \item \code{prompt} String, the text to be displayed above the textbox. } } \seealso{ Other keyring backend base classes: \code{\link{backend_keyrings}} } \concept{keyring backend base classes} keyring/man/has_keyring_support.Rd0000644000176200001440000000565114151122155017067 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/api.R \name{has_keyring_support} \alias{has_keyring_support} \alias{keyring_create} \alias{keyring_list} \alias{keyring_delete} \alias{keyring_lock} \alias{keyring_unlock} \alias{keyring_is_locked} \title{Operations on keyrings} \usage{ has_keyring_support() keyring_create(keyring, password = NULL) keyring_list() keyring_delete(keyring = NULL) keyring_lock(keyring = NULL) keyring_unlock(keyring = NULL, password = NULL) keyring_is_locked(keyring = NULL) } \arguments{ \item{keyring}{The name of the keyring to create or to operate on. For functions other than \code{keyring_create}, it can also be \code{NULL} to select the default keyring.} \item{password}{The initial password or the password to unlock the keyring. If not specified or \code{NULL}, it will be read from the console.} } \description{ On most platforms \code{keyring} supports multiple keyrings. This includes Windows, macOS and Linux (Secret Service) as well. A keyring is a collection of keys that can be treated as a unit. A keyring typically has a name and a password to unlock it. Once a keyring is unlocked, it remains unlocked until the end of the user session, or until it is explicitly locked again. } \details{ Platforms typically have a default keyring, which is unlocked automatically when the user logs in. This keyring does not need to be unlocked explicitly. You can configure the keyring to use via R options or environment variables (see \code{\link[=default_backend]{default_backend()}}), or you can also specify it directly in the \code{\link[=default_backend]{default_backend()}} call, or in the individual \code{keyring} calls. \code{has_keyring_support} checks if a backend supports multiple keyrings. \code{keyring_create} creates a new keyring. It asks for a password if no password is specified. \code{keyring_list} lists all existing keyrings. \code{keyring_delete} deletes a keyring. Deleting a non-empty keyring requires confirmation, and the default keyring can only be deleted if specified explicitly. On some backends (e.g. Windows Credential Store), the default keyring cannot be deleted at all. \code{keyring_lock} locks a keyring. On some backends (e.g. Windows Credential Store), the default keyring cannot be locked. \code{keyring_unlock} unlocks a keyring. If a password is not specified, it will be read in interactively. \code{keyring_is_locked} queries whether a keyring is locked. } \examples{ default_backend() has_keyring_support() backend_env$new()$has_keyring_support() ## This might ask for a password, so we do not run it by default ## It only works if the default backend supports multiple keyrings \dontrun{ keyring_create("foobar") key_set_with_value("R-test-service", "donaldduck", password = "secret", keyring = "foobar") key_get("R-test-service", "donaldduck", keyring = "foobar") key_list(keyring = "foobar") keyring_delete(keyring = "foobar") } } keyring/man/b_wincred_decode_auto.Rd0000644000176200001440000000071714144472216017265 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-wincred.R \name{b_wincred_decode_auto} \alias{b_wincred_decode_auto} \title{Decode a raw password obtained by b_wincred_get_raw (UTF-8 and UTF-16LE only)} \usage{ b_wincred_decode_auto(password) } \arguments{ \item{password}{Raw vector coming from the keyring.} } \description{ It attempts to use UTF-16LE conversion if there are 0 values in the password. } \keyword{internal} keyring/man/backend_wincred.Rd0000644000176200001440000000204514144472216016074 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-wincred.R \name{backend_wincred} \alias{backend_wincred} \title{Windows Credential Store keyring backend} \description{ This backend is the default on Windows. It uses the native Windows Credential API, and needs at least Windows XP to run. } \details{ This backend supports multiple keyrings. Note that multiple keyrings are implemented in the \code{keyring} R package, using some dummy keyring keys that represent keyrings and their locked/unlocked state. See \link{backend} for the documentation of the individual methods. } \examples{ \dontrun{ ## This only works on Windows kb <- backend_wincred$new() kb$keyring_create("foobar") kb$set_default_keyring("foobar") kb$set_with_value("service", password = "secret") kb$get("service") kb$delete("service") kb$delete_keyring("foobar") } } \seealso{ Other keyring backends: \code{\link{backend_env}}, \code{\link{backend_file}}, \code{\link{backend_macos}}, \code{\link{backend_secret_service}} } \concept{keyring backends} keyring/man/backend_secret_service.Rd0000644000176200001440000000266414521172457017460 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-secret-service.R \name{backend_secret_service} \alias{backend_secret_service} \title{Linux Secret Service keyring backend} \description{ This backend is the default on Linux. It uses the libsecret library, and needs a secret service daemon running (e.g. Gnome Keyring, or KWallet). It uses DBUS to communicate with the secret service daemon. } \details{ This backend supports multiple keyrings. See \link{backend} for the documentation of the individual methods. The \code{is_available()} method checks is a Secret Service daemon is running on the system, by trying to connect to it. It returns a logical scalar, or throws an error, depending on its argument: \if{html}{\out{
}}\preformatted{is_available = function(report_error = FALSE) }\if{html}{\out{
}} Argument: \itemize{ \item \code{report_error} Whether to throw an error if the Secret Service is not available. } } \examples{ \dontrun{ ## This only works on Linux, typically desktop Linux kb <- backend_secret_service$new() kb$keyring_create("foobar") kb$set_default_keyring("foobar") kb$set_with_value("service", password = "secret") kb$get("service") kb$delete("service") kb$delete_keyring("foobar") } } \seealso{ Other keyring backends: \code{\link{backend_env}}, \code{\link{backend_file}}, \code{\link{backend_macos}}, \code{\link{backend_wincred}} } \concept{keyring backends} keyring/man/key_get.Rd0000644000176200001440000001252614760120011014411 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/api.R \name{key_get} \alias{key_get} \alias{key_get_raw} \alias{key_set} \alias{key_set_with_value} \alias{key_set_with_raw_value} \alias{key_delete} \alias{key_list} \alias{key_list_raw} \title{Operations on keys} \usage{ key_get(service, username = NULL, keyring = NULL) key_get_raw(service, username = NULL, keyring = NULL) key_set(service, username = NULL, keyring = NULL, prompt = "Password: ") key_set_with_value(service, username = NULL, password = NULL, keyring = NULL) key_set_with_raw_value( service, username = NULL, password = NULL, keyring = NULL ) key_delete(service, username = NULL, keyring = NULL) key_list(service = NULL, keyring = NULL) key_list_raw(service = NULL, keyring = NULL) } \arguments{ \item{service}{Service name, a character scalar.} \item{username}{Username, a character scalar, or \code{NULL} if the key is not associated with a username.} \item{keyring}{For systems that support multiple keyrings, specify the name of the keyring to use here. If \code{NULL}, then the default keyring is used. See also \code{\link[=has_keyring_support]{has_keyring_support()}}.} \item{prompt}{The character string displayed when requesting the secret} \item{password}{The secret to store. For \code{key_set}, it is read from the console, interactively. \code{key_set_with_value} can be also used in non-interactive mode.} } \value{ \code{key_get} returns a character scalar, the password or other confidential information that was stored in the key. \code{key_list} returns a list of keys, i.e. service names and usernames, in a data frame with column names \code{service} and \code{username}. If a service or user name contains a zero byte, which is not allowed in an R string, that entry is shown as \code{NA} and a warning (of class \code{keyring_warn_zero_byte_keys}) is thrown. You can use the \code{key_list_raw()} function to query these keys. \code{key_list_raw} is similar to \code{key_list} but returns service and usernames as raw vectors. This is useful if some service or user names) contain zero bytes. All column names: \code{service}, \code{username}, \code{service_raw}, \code{username_raw}. } \description{ These functions manipulate keys in a keyring. You can think of a keyring as a secure key-value store. } \details{ \code{key_get} queries a key from the keyring. \code{key_get_raw} queries a key and returns it as a raw vector. Most credential stores allow storing a byte sequence with embedded null bytes, and these cannot be represented as traditional null bytes terminated strings. If you don't know whether the key contains an embedded null, it is best to query it with \code{key_get_raw} instead of \code{key_get}. \code{key_set} sets a key in the keyring. The contents of the key is read interactively from the terminal. \code{key_set_with_value} is the non-interactive pair of \code{key_set}, to set a key in the keyring. \code{key_set_raw_with_value} sets a key to a byte sequence from a raw vector. \code{key_delete} deletes a key. \code{key_list} lists all keys of a keyring, or the keys for a certain service (if \code{service} is not \code{NULL}). \code{key_list_raw()} is like \code{key_list()} but also returns the keys as raw values. This is useful if your keys have bytes that cannot appear in R strings, e.g. a zero byte. \subsection{Encodings}{ On Windows, if required, an encoding can be specified using either an R option (\code{keyring.encoding_windows}) or environment variable (\code{KEYRING_ENCODING_WINDOWS}). This will be applied when both getting and setting keys. The option takes precedence over the environment variable, if both are set. This is reserved primarily for compatibility with keys set with other software, such as Python's implementation of keyring. For a list of encodings, use \code{\link[=iconvlist]{iconvlist()}}, although it should be noted that not \emph{every} encoding can be properly converted, even for trivial cases. For best results, use UTF-8 if you can. } } \examples{ # These examples use the default keyring, and they are interactive, # so, we don't run them by default \dontrun{ key_set("R-keyring-test-service", "donaldduck") key_get("R-keyring-test-service", "donaldduck") if (has_keyring_support()) key_list(service = "R-keyring-test-service") key_delete("R-keyring-test-service", "donaldduck") ## This is non-interactive, assuming that that default keyring ## is unlocked key_set_with_value("R-keyring-test-service", "donaldduck", password = "secret") key_get("R-keyring-test-service", "donaldduck") if (has_keyring_support()) key_list(service = "R-keyring-test-service") key_delete("R-keyring-test-service", "donaldduck") ## This is interactive using backend_file ## Set variables to be used in keyring kr_name <- "my_keyring" kr_service <- "my_database" kr_username <- "my_username" ## Create a keyring and add an entry using the variables above kb <- keyring::backend_file$new() ## Prompt for the keyring password, used to unlock keyring kb$keyring_create(kr_name) ## Prompt for the secret/password to be stored in the keyring kb$set(kr_service, username=kr_username, keyring=kr_name) # Lock the keyring kb$keyring_lock(kr_name) ## The keyring file is stored at ~/.config/r-keyring/ on Linux ## Output the stored password keyring::backend_file$new()$get(service = kr_service, user = kr_username, keyring = kr_name) } } keyring/man/backend_file.Rd0000644000176200001440000000115214144472216015356 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-file.R \name{backend_file} \alias{backend_file} \title{Encrypted file keyring backend} \description{ This is a simple keyring backend, that stores/uses secrets in encrypted files. } \details{ It supports multiple keyrings. See \link{backend} for the documentation of the individual methods. } \examples{ \dontrun{ kb <- backend_file$new() } } \seealso{ Other keyring backends: \code{\link{backend_env}}, \code{\link{backend_macos}}, \code{\link{backend_secret_service}}, \code{\link{backend_wincred}} } \concept{keyring backends} keyring/man/backend_keyrings.Rd0000644000176200001440000000367314521172457016307 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-class.R \name{backend_keyrings} \alias{backend_keyrings} \title{Abstract class of a backend that supports multiple keyrings} \description{ To implement a new keyring that supports multiple keyrings, you need to inherit from this class and redefine the \code{get}, \code{set}, \code{set_with_value}, \code{delete}, \code{list} methods, and also the keyring management methods: \code{keyring_create}, \code{keyring_list}, \code{keyring_delete}, \code{keyring_lock}, \code{keyring_unlock}, \code{keyring_is_locked}, \code{keyring_default} and \code{keyring_set_default}. } \details{ See \link{backend} for the first set of methods. This is the semantics of the keyring management methods: \if{html}{\out{
}}\preformatted{keyring_create(keyring) keyring_list() keyring_delete(keyring = NULL) keyring_lock(keyring = NULL) keyring_unlock(keyring = NULL, password = NULL) keyring_is_locked(keyring = NULL) keyring_default() keyring_set_default(keyring = NULL) }\if{html}{\out{
}} \itemize{ \item \code{keyring_create()} creates a new keyring. \item \code{keyring_list()} lists all keyrings. \item \code{keyring_delete()} deletes a keyring. It is a good idea to protect the default keyring, and/or a non-empty keyring with a password or a confirmation dialog. \item \code{keyring_lock()} locks a keyring. \item \code{keyring_unlock()} unlocks a keyring. \item \code{keyring_is_locked()} checks whether a keyring is locked. \item \code{keyring_default()} returns the default keyring. \item \code{keyring_set_default()} sets the default keyring. } Arguments: \itemize{ \item \code{keyring} is the name of the keyring to use or create. For some methods in can be \code{NULL} to select the default keyring. \item \code{password} is the password of the keyring. } } \seealso{ Other keyring backend base classes: \code{\link{backend}} } \concept{keyring backend base classes} keyring/man/b_wincred_get.Rd0000644000176200001440000000162014535445650015571 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-wincred.R \name{b_wincred_get} \alias{b_wincred_get} \title{Get a key from a Wincred keyring} \usage{ b_wincred_get(self, private, service, username, keyring) } \arguments{ \item{service}{Service name. Must not be empty.} \item{username}{Username. Might be empty. \enumerate{ \item We check if the key is on the default keyring. \item If yes, we just return it. \item Otherwise check if the keyring is locked. \item If locked, then unlock it. \item Get the AES key from the keyring. \item Decrypt the key with the AES key. } Additionally, users may specify an encoding to use when converting the password from a byte-string, for compatibility with other software such as python's keyring package. This is done via an option, or an environment variable.} } \description{ Get a key from a Wincred keyring } \keyword{internal} keyring/man/backend_env.Rd0000644000176200001440000000243114144472216015230 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-env.R \name{backend_env} \alias{backend_env} \title{Environment variable keyring backend} \description{ This is a simple keyring backend, that stores/uses secrets in environment variables of the R session. } \details{ It does not support multiple keyrings. It also does not support listing all keys, since there is no way to distinguish keys from regular environment variables. It does support service names and usernames: they will be separated with a \code{:} character in the name of the environment variable. (Note that such an environment variable typically cannot be set or queried from a shell, but it can be set and queried from R or other programming languages.) See \link{backend} for the documentation of the class's methods. } \examples{ \dontrun{ env <- backend_env$new() env$set("r-keyring-test", username = "donaldduck") env$get("r-keyring-test", username = "donaldduck") Sys.getenv("r-keyring-test:donaldduck") # This is an error env$list() # Clean up env$delete("r-keyring-test", username = "donaldduck") } } \seealso{ Other keyring backends: \code{\link{backend_file}}, \code{\link{backend_macos}}, \code{\link{backend_secret_service}}, \code{\link{backend_wincred}} } \concept{keyring backends} keyring/man/backend_macos.Rd0000644000176200001440000000150114144472216015537 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-macos.R \name{backend_macos} \alias{backend_macos} \title{macOS Keychain keyring backend} \description{ This backend is the default on macOS. It uses the macOS native Keychain Service API. } \details{ It supports multiple keyrings. See \link{backend} for the documentation of the individual methods. } \examples{ \dontrun{ ## This only works on macOS kb <- backend_macos$new() kb$keyring_create("foobar") kb$set_default_keyring("foobar") kb$set_with_value("service", password = "secret") kb$get("service") kb$delete("service") kb$delete_keyring("foobar") } } \seealso{ Other keyring backends: \code{\link{backend_env}}, \code{\link{backend_file}}, \code{\link{backend_secret_service}}, \code{\link{backend_wincred}} } \concept{keyring backends} keyring/man/backends.Rd0000644000176200001440000000435214144472216014547 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/default_backend.R \name{backends} \alias{backends} \alias{default_backend} \title{Select the default backend and default keyring} \usage{ default_backend(keyring = NULL) } \arguments{ \item{keyring}{Character string, the name of the keyring to use, or \code{NULL} for the default keyring.} } \value{ The backend object itself. } \description{ The default backend is selected \enumerate{ \item based on the \code{keyring_backend} option. See \code{\link[base:options]{base::options()}}. This can be set to a character string, and then the \emph{backend_}\code{string} class is used to create the default backend. \item If this is not set, then the \code{R_KEYRING_BACKEND} environment variable is checked. \item If this is not set, either, then the backend is selected automatically, based on the OS: \enumerate{ \item On Windows, the Windows Credential Store (\code{"wincred"}) is used. \item On macOS, Keychain services are selected (\code{"macos"}). \item Linux uses the Secret Service API (\code{"secret_service"}), and it also checks that the service is available. It is typically only available on systems with a GUI. \item If the file backend (\code{"file"}) is available, it is selected. \item On other operating systems, secrets are stored in environment variables (\code{"env"}). } } } \details{ Most backends support multiple keyrings. For these the keyring is selected from: \enumerate{ \item the supplied \code{keyring} argument (if not \code{NULL}), or \item the \code{keyring_keyring} option. \itemize{ \item You can change this by using \code{options(keyring_keyring = "NEWVALUE")} } \item If this is not set, the \code{R_KEYRING_KEYRING} environment variable. \itemize{ \item Change this value with \code{Sys.setenv(R_KEYRING_KEYRING = "NEWVALUE")}, either in your script or in your \code{.Renviron} file. See \link[base:Startup]{base::Startup} for information about using \code{.Renviron} } \item Finally, if neither of these are set, the OS default keyring is used. \itemize{ \item Usually the keyring is automatically unlocked when the user logs in. } } } \seealso{ \link{backend_env}, \link{backend_file}, \link{backend_macos}, \link{backend_secret_service}, \link{backend_wincred} } keyring/man/b_wincred_set_with_raw_value.Rd0000644000176200001440000000225314144472216020702 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-wincred.R \name{b_wincred_set_with_raw_value} \alias{b_wincred_set_with_raw_value} \title{Set a key on a Wincred keyring} \usage{ b_wincred_set_with_raw_value( self, private, service, username, password, keyring ) } \arguments{ \item{service}{Service name. Must not be empty.} \item{username}{Username. Might be empty.} \item{password}{The key text to store. \enumerate{ \item Check if we are using the default keyring. \item If yes, then just store the key and we are done. \item Otherwise check if keyring exists. \item If not, error and finish. \item If yes, check if it is locked. \item If yes, unlock it. \item Encrypt the key with the AES key, and store it. } If required, an encoding can be specified using either an R option (\code{keyring.encoding_windows}) or environment variable (\code{KEYRING_ENCODING_WINDOWS}). To set, use one of: \code{options(keyring.encoding_windows = 'encoding-type')} \code{Sys.setenv("KEYRING_ENCODING_WINDOWS" = 'encoding-type')} For a list of valid encodings, use \code{iconvlist()}} } \description{ Set a key on a Wincred keyring } \keyword{internal} keyring/man/keyring-package.Rd0000644000176200001440000000705115015040416016024 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/keyring-package.R, R/package.R \docType{package} \name{keyring-package} \alias{keyring-package} \alias{keyring} \title{keyring: Access the System Credential Store from R} \description{ Platform independent 'API' to access the operating system's credential store. Currently supports: 'Keychain' on 'macOS', Credential Store on 'Windows', the Secret Service 'API' on 'Linux', and simple, platform independent stores implemented with environment variables or encrypted files. Additional storage back-ends can be added easily. Platform independent API to many system credential store implementations. Currently supported: \itemize{ \item Keychain on macOS, \item Credential Store on Windows, \item the Secret Service API on Linux, and \item environment variables on other platforms. } } \section{Configuring an OS-specific backend}{ \itemize{ \item The default is operating system specific, and is described in \code{\link[=default_backend]{default_backend()}}. In most cases you don't have to configure this. \item MacOS: \link{backend_macos} \item Linux: \link{backend_secret_service} \item Windows: \link{backend_wincred} \item Or store the secrets in environment variables on other operating systems: \link{backend_env} } } \section{Query secret keys in a keyring}{ Each keyring can contain one or many secrets (keys). A key is defined by a service name and a password. Once a key is defined, it persists in the keyring store of the operating system. This means the keys persist beyond the termination of and R session. Specifically, you can define a key once, and then read the key value in completely independent R sessions. \itemize{ \item Setting a secret interactively: \code{\link[=key_set]{key_set()}}. \item Setting a secret from a script, i.e. non-interactively: \code{\link[=key_set_with_value]{key_set_with_value()}}. \item Reading a secret: \code{\link[=key_get]{key_get()}}, \code{\link[=key_get_raw]{key_get_raw()}}. \item Listing secrets: \code{\link[=key_list]{key_list()}}, \code{\link[=key_list_raw]{key_list_raw()}}. \item Deleting a secret: \code{\link[=key_delete]{key_delete()}}. } } \section{Managing keyrings}{ A keyring is a collection of keys that can be treated as a unit. A keyring typically has a name and a password to unlock it. \itemize{ \item \code{\link[=keyring_create]{keyring_create()}} \item \code{\link[=keyring_delete]{keyring_delete()}} \item \code{\link[=keyring_list]{keyring_list()}} \item \code{\link[=keyring_lock]{keyring_lock()}} \item \code{\link[=keyring_unlock]{keyring_unlock()}} } Note that all platforms have a default keyring, and \code{key_get()}, etc. will use that automatically. The default keyring is also convenient, because the OS unlocks it automatically when you log in, so secrets are available immediately. You only need to explicitly deal with keyrings and the \verb{keyring_*} functions if you want to use a different keyring. } \seealso{ Useful links: \itemize{ \item \url{https://keyring.r-lib.org/} \item \url{https://github.com/r-lib/keyring} \item Report bugs at \url{https://github.com/r-lib/keyring/issues} } Useful links: \itemize{ \item \url{https://keyring.r-lib.org/} \item \url{https://github.com/r-lib/keyring} \item Report bugs at \url{https://github.com/r-lib/keyring/issues} } } \author{ \strong{Maintainer}: Gábor Csárdi \email{csardi.gabor@gmail.com} Other contributors: \itemize{ \item Alec Wong [contributor] \item Posit Software, PBC (\href{https://ror.org/03wc8by49}{ROR}) [copyright holder, funder] } } \keyword{internal} keyring/man/b_wincred_decode.Rd0000644000176200001440000000145414144472216016234 0ustar liggesusers% Generated by roxygen2: do not edit by hand % Please edit documentation in R/backend-wincred.R \name{b_wincred_decode} \alias{b_wincred_decode} \title{Decode a raw password obtained by b_wincred_get_raw} \usage{ b_wincred_decode(password, encoding = "auto") } \arguments{ \item{password}{A raw byte string returned from \code{b_wincred_get_raw}.} \item{encoding}{A character value, specifying an encoding to use. Defaults to 'auto', which will decode either of UTF-8 or UTF-16LE.} } \value{ A character value containing a password. } \description{ Defaults to 'auto' encoding, which uses \code{b_wincred_decode_auto} to accomplish the decoding (this works with decoding either UTF-8 or UTF-16LE encodings). In the case where an encoding is specified, use that to convert the raw password. } \keyword{internal} keyring/DESCRIPTION0000644000176200001440000000303715023633252013434 0ustar liggesusersPackage: keyring Title: Access the System Credential Store from R Version: 1.4.1 Authors@R: c( person("Gábor", "Csárdi", , "csardi.gabor@gmail.com", role = c("aut", "cre")), person("Alec", "Wong", role = "ctb"), person("Posit Software, PBC", role = c("cph", "fnd"), comment = c(ROR = "03wc8by49")) ) Description: Platform independent 'API' to access the operating system's credential store. Currently supports: 'Keychain' on 'macOS', Credential Store on 'Windows', the Secret Service 'API' on 'Linux', and simple, platform independent stores implemented with environment variables or encrypted files. Additional storage back-ends can be added easily. License: MIT + file LICENSE URL: https://keyring.r-lib.org/, https://github.com/r-lib/keyring BugReports: https://github.com/r-lib/keyring/issues Depends: R (>= 3.5) Imports: askpass, filelock, R6, tools, utils, yaml Suggests: callr, covr, openssl, testthat (>= 3.0.0), withr Biarch: true Config/Needs/website: tidyverse/tidytemplate Config/testthat/edition: 3 Config/usethis/last-upkeep: 2025-04-30 Encoding: UTF-8 RoxygenNote: 7.3.2.9000 SystemRequirements: Optional: libsecret on Linux (libsecret-1-dev on Debian/Ubuntu, libsecret-devel on Fedora/CentOS) NeedsCompilation: yes Packaged: 2025-06-15 20:21:23 UTC; gaborcsardi Author: Gábor Csárdi [aut, cre], Alec Wong [ctb], Posit Software, PBC [cph, fnd] (ROR: ) Maintainer: Gábor Csárdi Repository: CRAN Date/Publication: 2025-06-15 21:10:02 UTC