diff --git a/.github/scripts/test-otp22.sh b/.github/scripts/test-otp22.sh new file mode 100644 index 0000000..d1bcf47 --- /dev/null +++ b/.github/scripts/test-otp22.sh @@ -0,0 +1,39 @@ +#!/bin/sh +# Run inside the official erlang:22.3 image, in a fresh checkout. +set -eu + +erl -noshell -eval '"22" = erlang:system_info(otp_release), halt().' + +# Current publishing/test plugins may require newer OTP. Keep the project's +# dependencies and test settings, and invoke PropEr directly without a plugin. +config_backup=$(mktemp) +cp rebar.config "$config_backup" +trap 'cp "$config_backup" rebar.config; rm -f "$config_backup"' EXIT + +erl -noshell -eval ' + {ok, Config} = file:consult("rebar.config"), + WithoutPlugins = fun(Options) -> + proplists:delete(project_plugins, proplists:delete(plugins, Options)) + end, + Profiles = [{Name, WithoutPlugins(Options)} || + {Name, Options} <- proplists:get_value(profiles, Config, [])], + Updated = lists:keystore(profiles, 1, WithoutPlugins(Config), + {profiles, Profiles}), + ok = file:write_file("rebar.config", + [io_lib:format("~p.~n", [Term]) || Term <- Updated]), + halt().' + +rebar3 version +make +rebar3 as test eunit +make security-test +ERL_FLAGS="+S 1" rebar3 as test eunit --module=bcrypt_security_tests + +erl -noshell -pa _build/test/lib/*/ebin _build/test/lib/bcrypt/test -eval ' + case proper:module(prop_bcrypt, [{numtests, 100}]) of + [] -> halt(0); + _ -> halt(1) + end.' + +make xref +make dialyzer diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index e545c9c..b1d37cd 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,19 +18,38 @@ jobs: strategy: matrix: - otp_version: [21.3, 22.3, 23, 24] + otp_version: [27,28,29] os: [ubuntu-latest] container: image: erlang:${{ matrix.otp_version }} steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v7 - name: Compile run: make - name: Test run: make test + - name: Native security tests + run: make security-test + - name: Single-scheduler security tests + run: ERL_FLAGS="+S 1" rebar3 as test eunit --module=bcrypt_security_tests - name: XRef run: make xref - name: Dialyzer run: make dialyzer + + otp22: + name: Test on OTP 22.3 + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + # Keep Node-based actions on the host, outside the old Debian image. + - uses: actions/checkout@v7 + - name: Test in the OTP 22.3 toolchain + run: | + docker run --rm \ + --volume "$GITHUB_WORKSPACE:/work" \ + --workdir /work \ + erlang:22.3 \ + sh .github/scripts/test-otp22.sh diff --git a/LICENSE b/LICENSE index f479304..6db51ca 100644 --- a/LICENSE +++ b/LICENSE @@ -51,66 +51,21 @@ subject to the following license: */ The underlying bcrypt (hashing) code is derived from OpenBSD libc and is -subject to the following license: +subject to the following license: /* - * Copyright 1997 Niels Provos - * All rights reserved. + * Copyright (c) 2014 Ted Unangst + * Copyright (c) 1997 Niels Provos * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by Niels Provos. - * 4. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -The asynchronous queue code (c_src/async_queue.c and -c_src/async_queue.h) is from the esnappy project, copyright 2011 -Konstantin V. Sorokin. It is subject to the following license: - -Copyright (c) 2011 Konstantin V. Sorokin -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -3. Neither the name of the copyright holder nor the names of contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -SUCH DAMAGE. diff --git a/Makefile b/Makefile index 790d475..c6e2c1f 100644 --- a/Makefile +++ b/Makefile @@ -38,3 +38,8 @@ edoc_private: $(REBAR) exdoc: $(REBAR) $(REBAR) ex_doc --logo doc/img/logo.png --output edoc + +# Isolated native boundary checks with address/undefined-behavior sanitizers. +.PHONY: security-test +security-test: + $(MAKE) -C c_src security-test diff --git a/README.md b/README.md index 8b6c481..913db36 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ as the basis of the Hex package. OTP Compatibility ----------------- -erlang-bcrypt is compatible with OTP 21.3 to 23. +erlang-bcrypt is compatible with OTP 21.3 to 29. Use version 1.0.3 on OTP versions before 21.3 @@ -75,9 +75,9 @@ Hash a password using a salt with the default number of rounds: ```erlang 1> {ok, Salt} = bcrypt:gen_salt(). -{ok,"$2a$12$sSS8Eg.ovVzaHzi1nUHYK."} +{ok,"$2b$12$sSS8Eg.ovVzaHzi1nUHYK."} 2> {ok, Hash} = bcrypt:hashpw("foo", Salt). -{ok,"$2a$12$sSS8Eg.ovVzaHzi1nUHYK.HbUIOdlQI0iS22Q5rd5z.JVVYH6sfm6"} +{ok,"$2b$12$sSS8Eg.ovVzaHzi1nUHYK.HbUIOdlQI0iS22Q5rd5z.JVVYH6sfm6"} ``` Verify the password: @@ -103,7 +103,7 @@ application's environment: Specifies whether to use the NIF implementation (`'nif'`) or a pool of port programs (`'port'`). Defaults to `'nif'`. - `Note: the NIF implementation no longer blocks the Erlang VM scheduler threads` + `Note: hashing runs on OTP dirty CPU schedulers, not normal scheduler threads.` `pool_size` Specifies the size of the port program pool. Defaults to `4`. @@ -184,3 +184,35 @@ Original authors ---------------- Hunter Morris & [Mrinal Wadhwa](https://github.com/mrinalwadhwa). + +## Password compatibility and native safety + +New salts use `$2b$`. Hashing uses at most the first 72 password bytes, +following OpenBSD bcrypt. Passwords up to 1,024 bytes are accepted; longer +inputs return `{error, invalid_password_length}`. Malformed salts return +`{error, invalid_salt}`. These rules apply to both the NIF and port backends. + +`$2b$` rejects embedded NUL bytes with `{error, invalid_password}`. Pass text +passwords as encoded bytes; do not pass raw binary prehashes containing NULs. +Existing `$2a$` hashes retain historical password-length wraparound and NUL +termination semantics for verification. After a successful legacy verification, +generate a fresh salt and rehash with `$2b$`; do not just change the prefix. +Legacy hashes affected by those behaviors may warrant a password reset. + +The NIF uses OTP dirty CPU schedulers. Its asynchronous `hashpw/5` interface +uses an Erlang helper process and an opaque reference from `create_ctx/0`; +there are no custom native threads, task queues, or blocking destructors. +The public pool still limits concurrent requests. Killing a caller does not +cancel an already running hash; applications should restrict accepted costs +and rate-limit authentication requests. Contexts created before this change +must be recreated when upgrading the application. + +The C core incorporates OpenBSD `bcrypt.c` revision 1.58, including `$2b$`, +strict salt parsing, decoder error checking, output bounds, and secure clearing, +with a bounded input adapter shared by both backends. Upstream source: +[OpenBSD bcrypt.c](https://github.com/openbsd/src/blob/master/lib/libc/crypt/bcrypt.c). + +Run `make security-test` for native boundary checks under ASan/UBSan. Run +`rebar3 as test eunit` for compatibility, malformed-input, and lifecycle tests. +The lifecycle regression can also be run with `ERL_FLAGS="+S 1"` to verify +that owner exit does not block the sole normal scheduler. diff --git a/c_src/Makefile b/c_src/Makefile index 4d3f2db..8e424b9 100644 --- a/c_src/Makefile +++ b/c_src/Makefile @@ -65,13 +65,15 @@ COMPILE_CPP = $(cpp_verbose) $(CXX) $(CXXFLAGS) $(CPPFLAGS) -c all: $(C_SRC_NIF) $(C_SRC_PORT) -$(C_SRC_PORT): $(OBJECTS) +$(C_SRC_PORT): bcrypt_port.o bcrypt.o blowfish.o @mkdir -p $(BASEDIR)/priv/ $(CC) $(CFLAGS) bcrypt_port.o bcrypt.o blowfish.o $(DRV_LDFLAGS) $(LDLIBS) -o ../priv/bcrypt -$(C_SRC_NIF): $(OBJECTS) +$(C_SRC_NIF): bcrypt_nif.o bcrypt.o blowfish.o @mkdir -p $(BASEDIR)/priv/ - $(link_verbose) $(CC) $(OBJECTS) $(LDFLAGS) -shared $(LDLIBS) -o $(C_SRC_NIF) + $(link_verbose) $(CC) bcrypt_nif.o bcrypt.o blowfish.o $(LDFLAGS) -shared $(LDLIBS) -o $(C_SRC_NIF) + +$(OBJECTS): bcrypt.h erl_blf.h %.o: %.c $(COMPILE_C) $(OUTPUT_OPTION) $< @@ -86,4 +88,11 @@ $(C_SRC_NIF): $(OBJECTS) $(COMPILE_CPP) $(OUTPUT_OPTION) $< clean: - @rm -f $(C_SRC_OUTPUT) $(OBJECTS) + @rm -f $(C_SRC_NIF) $(C_SRC_PORT) $(OBJECTS) + +.PHONY: security-test +security-test: + @tmpdir=$$(mktemp -d) || exit 1; trap 'rm -rf "$$tmpdir"' EXIT; \ + $(CC) -std=c99 -D_DEFAULT_SOURCE -g -O1 -fsanitize=address,undefined \ + -fno-omit-frame-pointer -fno-sanitize-recover=all -I. ../test/bcrypt_native_tests.c bcrypt.c blowfish.c \ + -o "$$tmpdir/bcrypt_native_tests" && "$$tmpdir/bcrypt_native_tests" diff --git a/c_src/async_queue.c b/c_src/async_queue.c deleted file mode 100644 index fbe30aa..0000000 --- a/c_src/async_queue.c +++ /dev/null @@ -1,141 +0,0 @@ -/* - From https://github.com/thekvs/esnappy: - Copyright (c) 2011 Konstantin V. Sorokin - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holder nor the names of contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. -*/ -// vim: shiftwidth=4 expandtab -#include "async_queue.h" - -async_queue_t* -async_queue_create(char* mutex_name, char* condvar_name) -{ - async_queue_t *aq; - - aq = ALLOC(sizeof(*aq)); - - if (!aq) { - errx(1, "enif_alloc() failed"); - } - - aq->q = ALLOC(sizeof(*(aq->q))); - - if (!(aq->q)) { - errx(1, "enif_alloc() failed"); - } - - TAILQ_INIT(aq->q); - - aq->waiting_threads = aq->len = 0; - - aq->mutex = enif_mutex_create(mutex_name); - - if (!aq->mutex) { - errx(1, "enif_mutex_create() failed"); - } - - aq->cond = enif_cond_create(condvar_name); - - if (!aq->cond) { - errx(1, "enif_cond_create() failed"); - } - - return aq; -} - -int -async_queue_length(async_queue_t *aq) -{ - int length; - - MUTEX_LOCK(aq->mutex); - length = aq->len - aq->waiting_threads; - MUTEX_UNLOCK(aq->mutex); - - return length; -} - -void * -async_queue_pop(async_queue_t *aq) -{ - struct async_queue_entry *en; - void *d; - - MUTEX_LOCK(aq->mutex); - - d = NULL; - aq->waiting_threads++; - while (TAILQ_EMPTY(aq->q)) { - enif_cond_wait(aq->cond, aq->mutex); - } - aq->waiting_threads--; - - en = TAILQ_FIRST(aq->q); - TAILQ_REMOVE(aq->q, en, entries); - d = en->data; - aq->len--; - enif_free(en); - - MUTEX_UNLOCK(aq->mutex); - - return d; -} - -void -async_queue_push(async_queue_t *aq, void *data) -{ - struct async_queue_entry *en; - - MUTEX_LOCK(aq->mutex); - - en = ALLOC(sizeof(*en)); - en->data = data; - TAILQ_INSERT_TAIL(aq->q, en, entries); - aq->len++; - - COND_SIGNAL(aq->cond); - MUTEX_UNLOCK(aq->mutex); -} - -void -async_queue_destroy(async_queue_t *aq) -{ - struct async_queue_entry *en; - - while (!TAILQ_EMPTY(aq->q)) { - en = TAILQ_FIRST(aq->q); - TAILQ_REMOVE(aq->q, en, entries); - enif_free(en); - } - - COND_DESTROY(aq->cond); - MUTEX_DESTROY(aq->mutex); - - enif_free(aq->q); - enif_free(aq); -} - diff --git a/c_src/async_queue.h b/c_src/async_queue.h deleted file mode 100644 index c7804ea..0000000 --- a/c_src/async_queue.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - From https://github.com/thekvs/esnappy: - Copyright (c) 2011 Konstantin V. Sorokin - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions - are met: - - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holder nor the names of contributors - may be used to endorse or promote products derived from this software - without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE - FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - SUCH DAMAGE. -*/ -// vim: shiftwidth=4 expandtab -#ifndef __ASYNC_QUEUE_H_INCLUDED__ -#define __ASYNC_QUEUE_H_INCLUDED__ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -TAILQ_HEAD(queue, async_queue_entry); - -struct async_queue_entry { - TAILQ_ENTRY(async_queue_entry) entries; - void *data; -}; - -typedef struct __async_queue { - struct queue *q; - ErlNifMutex *mutex; - ErlNifCond *cond; - int waiting_threads; - int len; -} async_queue_t; - -async_queue_t* async_queue_create(char* mutex_name, char* condvar_name); -int async_queue_length(async_queue_t *aq); -void* async_queue_pop(async_queue_t *aq); -void async_queue_push(async_queue_t *aq, void *data); -void async_queue_destroy(async_queue_t *aq); - -#define ALLOC(size) enif_alloc(size) -#define MUTEX_LOCK(mutex) enif_mutex_lock(mutex) -#define MUTEX_UNLOCK(mutex) enif_mutex_unlock(mutex) -#define MUTEX_DESTROY(mutex) enif_mutex_destroy(mutex) -#define COND_SIGNAL(condvar) enif_cond_signal(condvar) -#define COND_DESTROY(condvar) enif_cond_destroy(condvar) - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif diff --git a/c_src/bcrypt.c b/c_src/bcrypt.c index 9875123..d5a0e2a 100644 --- a/c_src/bcrypt.c +++ b/c_src/bcrypt.c @@ -1,206 +1,120 @@ -/* $OpenBSD: bcrypt.c,v 1.24 2008/04/02 19:54:05 millert Exp $ */ +/* $OpenBSD: bcrypt.c,v 1.58 2020/07/06 13:33:05 pirofti Exp $ */ /* - * Copyright 1997 Niels Provos - * All rights reserved. + * Copyright (c) 2014 Ted Unangst + * Copyright (c) 1997 Niels Provos * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by Niels Provos. - * 4. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR - * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, - * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY - * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF - * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ - -/* This password hashing algorithm was designed by David Mazieres - * and works as follows: - * - * 1. state := InitState () - * 2. state := ExpandKey (state, salt, password) 3. - * REPEAT rounds: - * state := ExpandKey (state, 0, salt) - * state := ExpandKey(state, 0, password) - * 4. ctext := "OrpheanBeholderScryDoubt" - * 5. REPEAT 64: - * ctext := Encrypt_ECB (state, ctext); - * 6. RETURN Concatenate (salt, ctext); - * +/* Adapted from OpenBSD bcrypt.c revision 1.58 (2020-07-06). + * Keep the versioned $2a$/$2b$ semantics when updating this core. + * The bounded interface below is shared by the Erlang NIF and port. */ - +#include +#include +#include #include #include -#include #include -#include - #include "erl_blf.h" +#include "bcrypt.h" -/* This implementation is adaptable to current computing power. - * You can have up to 2^31 rounds which should be enough for some - * time to come. - */ - -#define BCRYPT_VERSION '2' -#define BCRYPT_MAXSALT 16 /* Precomputation is just so nice */ -#define BCRYPT_BLOCKS 6 /* Ciphertext blocks */ -#define BCRYPT_MINROUNDS 16 /* we have log2(rounds) in salt */ - -int ts_bcrypt(char *, const char *, const char *); -void encode_salt(char *, u_int8_t *, u_int16_t, u_int8_t); - -static void encode_base64(u_int8_t *, u_int8_t *, u_int16_t); -static void decode_base64(u_int8_t *, u_int16_t, u_int8_t *); - -#define ERROR -1 - -const static u_int8_t Base64Code[] = -"./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - -const static u_int8_t index_64[128] = { - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, - 255, 255, 255, 255, 255, 255, 0, 1, 54, 55, - 56, 57, 58, 59, 60, 61, 62, 63, 255, 255, - 255, 255, 255, 255, 255, 2, 3, 4, 5, 6, - 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, - 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, - 255, 255, 255, 255, 255, 255, 28, 29, 30, - 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, - 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 255, 255, 255, 255, 255 -}; -#define CHAR64(c) ( (c) > 127 ? 255 : index_64[(c)]) - -static void -decode_base64(u_int8_t *buffer, u_int16_t len, u_int8_t *data) +/* Volatile stores provide a portable, non-elidable wipe on supported C99 + * platforms, including platforms without explicit_bzero(). */ +void bcrypt_clear(void *ptr, size_t len) { - u_int8_t *bp = buffer; - u_int8_t *p = data; - u_int8_t c1, c2, c3, c4; - while (bp < buffer + len) { - c1 = CHAR64(*p); - c2 = CHAR64(*(p + 1)); - - /* Invalid data */ - if (c1 == 255 || c2 == 255) - break; - - *bp++ = (c1 << 2) | ((c2 & 0x30) >> 4); - if (bp >= buffer + len) - break; - - c3 = CHAR64(*(p + 2)); - if (c3 == 255) - break; - - *bp++ = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2); - if (bp >= buffer + len) - break; - - c4 = CHAR64(*(p + 3)); - if (c4 == 255) - break; - *bp++ = ((c3 & 0x03) << 6) | c4; - - p += 4; - } + volatile unsigned char *p = ptr; + while (len--) + *p++ = 0; } +#define explicit_bzero bcrypt_clear +#define BCRYPT_VERSION '2' +#define BCRYPT_MAXSALT 16 /* Precomputation is just so nice */ +#define BCRYPT_WORDS 6 /* Ciphertext words */ +#define BCRYPT_MINLOGROUNDS 4 /* we have log2(rounds) in salt */ -void -encode_salt(char *salt, u_int8_t *csalt, u_int16_t clen, u_int8_t logr) -{ - salt[0] = '$'; - salt[1] = BCRYPT_VERSION; - salt[2] = 'a'; - salt[3] = '$'; - - snprintf(salt + 4, 4, "%2.2u$", logr); - - encode_base64((u_int8_t *) salt + 7, csalt, clen); -} +#define BCRYPT_HASHSPACE BCRYPT_HASHSIZE -/* We handle $Vers$log2(NumRounds)$salt+passwd$ - i.e. $2$04$iwouldntknowwhattosayetKdJ6iFtacBqJdKe6aW7ou */ +static int encode_base64(char *, const u_int8_t *, size_t); +static int decode_base64(u_int8_t *, size_t, const char *); -int -ts_bcrypt(char * encrypted, const char *key, const char *salt) +static int +bcrypt_hashpass(const char *key, const char *salt, char *encrypted, + size_t encryptedlen) { blf_ctx state; u_int32_t rounds, i, k; u_int16_t j; - u_int8_t key_len, salt_len, logr, minor; - u_int8_t ciphertext[4 * BCRYPT_BLOCKS] = "OrpheanBeholderScryDoubt"; + size_t key_len; + u_int8_t salt_len, logr, minor; + u_int8_t ciphertext[4 * BCRYPT_WORDS] = "OrpheanBeholderScryDoubt"; u_int8_t csalt[BCRYPT_MAXSALT]; - u_int32_t cdata[BCRYPT_BLOCKS]; - int n; - - /* Discard "$" identifier */ - salt++; + u_int32_t cdata[BCRYPT_WORDS]; - if (*salt > BCRYPT_VERSION) { - /* How do I handle errors ? Return ':' */ - return ERROR; - } + if (encryptedlen < BCRYPT_HASHSPACE) + goto inval; - /* Check for minor versions */ - if (salt[1] != '$') { - switch (salt[1]) { - case 'a': - /* 'ab' should not yield the same as 'abab' */ - minor = salt[1]; - salt++; - break; - default: - return ERROR; - } - } else - minor = 0; + /* Check and discard "$" identifier */ + if (salt[0] != '$') + goto inval; + salt += 1; - /* Discard version + "$" identifier */ - salt += 2; + if (salt[0] != BCRYPT_VERSION) + goto inval; + /* Check for minor versions */ + switch ((minor = salt[1])) { + case 'a': + key_len = (u_int8_t)(strlen(key) + 1); + break; + case 'b': + /* strlen() returns a size_t, but the function calls + * below result in implicit casts to a narrower integer + * type, so cap key_len at the actual maximum supported + * length here to avoid integer wraparound */ + key_len = strlen(key); + if (key_len > 72) + key_len = 72; + key_len++; /* include the NUL */ + break; + default: + goto inval; + } if (salt[2] != '$') - /* Out of sync with passwd entry */ - return ERROR; + goto inval; + /* Discard version + "$" identifier */ + salt += 3; - /* Computer power doesn't increase linear, 2^x should be fine */ - n = atoi(salt); - if (n > 31 || n < 0) - return ERROR; - logr = (u_int8_t)n; - if ((rounds = (u_int32_t) 1 << logr) < BCRYPT_MINROUNDS) - return ERROR; + /* Check and parse num rounds */ + if (!isdigit((unsigned char)salt[0]) || + !isdigit((unsigned char)salt[1]) || salt[2] != '$') + goto inval; + logr = (salt[1] - '0') + ((salt[0] - '0') * 10); + if (logr < BCRYPT_MINLOGROUNDS || logr > 31) + goto inval; + /* Computer power doesn't increase linearly, 2^x should be fine */ + rounds = 1U << logr; /* Discard num rounds + "$" identifier */ salt += 3; if (strlen(salt) * 3 / 4 < BCRYPT_MAXSALT) - return ERROR; + goto inval; /* We dont want the base64 salt but the raw data */ - decode_base64(csalt, BCRYPT_MAXSALT, (u_int8_t *) salt); + if (decode_base64(csalt, BCRYPT_MAXSALT, salt)) + goto inval; salt_len = BCRYPT_MAXSALT; - key_len = strlen(key) + (minor >= 'a' ? 1 : 0); /* Setting up S-Boxes and Subkeys */ Blowfish_initstate(&state); @@ -213,14 +127,14 @@ ts_bcrypt(char * encrypted, const char *key, const char *salt) /* This can be precomputed later */ j = 0; - for (i = 0; i < BCRYPT_BLOCKS; i++) - cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_BLOCKS, &j); + for (i = 0; i < BCRYPT_WORDS; i++) + cdata[i] = Blowfish_stream2word(ciphertext, 4 * BCRYPT_WORDS, &j); /* Now do the encryption */ for (k = 0; k < 64; k++) - blf_enc(&state, cdata, BCRYPT_BLOCKS / 2); + blf_enc(&state, cdata, BCRYPT_WORDS / 2); - for (i = 0; i < BCRYPT_BLOCKS; i++) { + for (i = 0; i < BCRYPT_WORDS; i++) { ciphertext[4 * i + 3] = cdata[i] & 0xff; cdata[i] = cdata[i] >> 8; ciphertext[4 * i + 2] = cdata[i] & 0xff; @@ -231,31 +145,93 @@ ts_bcrypt(char * encrypted, const char *key, const char *salt) } - i = 0; - encrypted[i++] = '$'; - encrypted[i++] = BCRYPT_VERSION; - if (minor) - encrypted[i++] = minor; - encrypted[i++] = '$'; + snprintf(encrypted, 8, "$2%c$%2.2u$", minor, logr); + encode_base64(encrypted + 7, csalt, BCRYPT_MAXSALT); + encode_base64(encrypted + 7 + 22, ciphertext, 4 * BCRYPT_WORDS - 1); + explicit_bzero(&state, sizeof(state)); + explicit_bzero(ciphertext, sizeof(ciphertext)); + explicit_bzero(csalt, sizeof(csalt)); + explicit_bzero(cdata, sizeof(cdata)); + return 0; + +inval: + errno = EINVAL; + return -1; +} + +static const u_int8_t Base64Code[] = +"./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + +static const u_int8_t index_64[128] = { + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 0, 1, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, 255, 255, + 255, 255, 255, 255, 255, 2, 3, 4, 5, 6, + 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, + 255, 255, 255, 255, 255, 255, 28, 29, 30, + 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, + 51, 52, 53, 255, 255, 255, 255, 255 +}; +#define CHAR64(c) ( (c) > 127 ? 255 : index_64[(c)]) + +/* + * read buflen (after decoding) bytes of data from b64data + */ +static int +decode_base64(u_int8_t *buffer, size_t len, const char *b64data) +{ + u_int8_t *bp = buffer; + const u_int8_t *p = (const u_int8_t *)b64data; + u_int8_t c1, c2, c3, c4; + + while (bp < buffer + len) { + c1 = CHAR64(*p); + /* Invalid data */ + if (c1 == 255) + return -1; + + c2 = CHAR64(*(p + 1)); + if (c2 == 255) + return -1; + + *bp++ = (c1 << 2) | ((c2 & 0x30) >> 4); + if (bp >= buffer + len) + break; + + c3 = CHAR64(*(p + 2)); + if (c3 == 255) + return -1; + + *bp++ = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2); + if (bp >= buffer + len) + break; - snprintf(encrypted + i, 4, "%2.2u$", logr); + c4 = CHAR64(*(p + 3)); + if (c4 == 255) + return -1; + *bp++ = ((c3 & 0x03) << 6) | c4; - encode_base64((u_int8_t *) encrypted + i + 3, csalt, BCRYPT_MAXSALT); - encode_base64((u_int8_t *) encrypted + strlen(encrypted), ciphertext, - 4 * BCRYPT_BLOCKS - 1); - memset(&state, 0, sizeof(state)); - memset(ciphertext, 0, sizeof(ciphertext)); - memset(csalt, 0, sizeof(csalt)); - memset(cdata, 0, sizeof(cdata)); + p += 4; + } return 0; } -static void -encode_base64(u_int8_t *buffer, u_int8_t *data, u_int16_t len) +/* + * Turn len bytes of data into base64 encoded data. + * This works without = padding. + */ +static int +encode_base64(char *b64buffer, const u_int8_t *data, size_t len) { - u_int8_t *bp = buffer; - u_int8_t *p = data; + u_int8_t *bp = (u_int8_t *)b64buffer; + const u_int8_t *p = data; u_int8_t c1, c2; + while (p < data + len) { c1 = *p++; *bp++ = Base64Code[(c1 >> 2)]; @@ -278,4 +254,37 @@ encode_base64(u_int8_t *buffer, u_int8_t *data, u_int16_t len) *bp++ = Base64Code[c2 & 0x3f]; } *bp = '\0'; + return 0; +} + + +int bcrypt_hash(char *out, size_t outlen, const unsigned char *password, + size_t password_len, const unsigned char *salt, size_t salt_len) +{ + char key[BCRYPT_MAXPASSWORD + 1] = {0}; + char setting[BCRYPT_HASHSIZE] = {0}; + int result; + + if (password_len > BCRYPT_MAXPASSWORD) + return BCRYPT_INVALID_PASSWORD_LENGTH; + if ((salt_len != 29 && salt_len != 60) || + memchr(salt, 0, salt_len) != NULL) + return BCRYPT_INVALID_SALT; + /* Preserve historical C-string behavior only for legacy verification. */ + if (salt[2] == 'b' && password_len && + memchr(password, 0, password_len) != NULL) + return BCRYPT_INVALID_PASSWORD; + if (password_len) + memcpy(key, password, password_len); + memcpy(setting, salt, salt_len); + result = bcrypt_hashpass(key, setting, out, outlen); + bcrypt_clear(key, sizeof(key)); + bcrypt_clear(setting, sizeof(setting)); + return result == 0 ? BCRYPT_OK : BCRYPT_INVALID_SALT; +} + +void encode_salt(char *salt, u_int8_t *csalt, u_int16_t len, u_int8_t rounds) +{ + snprintf(salt, BCRYPT_SALTSIZE, "$2b$%2.2u$", rounds); + encode_base64(salt + 7, csalt, len); } diff --git a/c_src/bcrypt.h b/c_src/bcrypt.h new file mode 100644 index 0000000..27b938e --- /dev/null +++ b/c_src/bcrypt.h @@ -0,0 +1,23 @@ +#ifndef ERLANG_BCRYPT_H +#define ERLANG_BCRYPT_H + +#include +#include + +#define BCRYPT_MAXPASSWORD 1024 +#define BCRYPT_SALTSIZE 30 +#define BCRYPT_HASHSIZE 61 + +enum bcrypt_result { + BCRYPT_OK, + BCRYPT_INVALID_SALT, + BCRYPT_INVALID_PASSWORD, + BCRYPT_INVALID_PASSWORD_LENGTH +}; + +int bcrypt_hash(char *, size_t, const unsigned char *, size_t, + const unsigned char *, size_t); +void encode_salt(char *, u_int8_t *, u_int16_t, u_int8_t); +void bcrypt_clear(void *, size_t); + +#endif diff --git a/c_src/bcrypt_nif.c b/c_src/bcrypt_nif.c index fd3492a..aabfcc3 100644 --- a/c_src/bcrypt_nif.c +++ b/c_src/bcrypt_nif.c @@ -14,231 +14,65 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#include -#include -#include #include -#include - #include "erl_nif.h" -#include "erl_blf.h" -#include "bcrypt_nif.h" - -static void free_task(task_t* task) -{ - if (task->env != NULL) - enif_free_env(task->env); - enif_free(task); -} - -static task_t* alloc_task(task_type_t type) -{ - task_t* task = (task_t*)enif_alloc(sizeof(task_t)); - if (task == NULL) - return NULL; - (void)memset(task, 0, sizeof(task_t)); - task->type = type; - return task; -} - -static task_t* alloc_init_task(task_type_t type, ERL_NIF_TERM ref, ErlNifPid pid, int num_orig_terms, const ERL_NIF_TERM orig_terms[]) -{ - task_t* task = alloc_task(type); - task->pid = pid; - task->env = enif_alloc_env(); - if (task->env == NULL) { - free_task(task); - return NULL; - } - - if (type == HASH) { - assert(num_orig_terms == 2); - if (!enif_inspect_iolist_as_binary( - task->env, enif_make_copy(task->env, orig_terms[0]), - &task->data.hash.salt)) { - free_task(task); - return NULL; - } - if (!enif_inspect_iolist_as_binary( - task->env, enif_make_copy(task->env, orig_terms[1]), - &task->data.hash.password)) { - free_task(task); - return NULL; - } - } - - task->ref = enif_make_copy(task->env, ref); - return task; -} - -static ERL_NIF_TERM hashpw(task_t* task) -{ - char password[1024] = { 0 }; - char salt[1024] = { 0 }; - char encrypted[1024] = { 0 }; - - size_t password_sz = 1024; - if (password_sz > task->data.hash.password.size) - password_sz = task->data.hash.password.size; - (void)memcpy(&password, task->data.hash.password.data, password_sz); +#include "bcrypt.h" - size_t salt_sz = 1024; - if (salt_sz > task->data.hash.salt.size) - salt_sz = task->data.hash.salt.size; - (void)memcpy(&salt, task->data.hash.salt.data, salt_sz); - - if (ts_bcrypt(encrypted, password, salt)) { - return enif_make_tuple3( - task->env, - enif_make_atom(task->env, "error"), - task->ref, - enif_make_string(task->env, "bcrypt failed", ERL_NIF_LATIN1)); - } - - return enif_make_tuple3( - task->env, - enif_make_atom(task->env, "ok"), - task->ref, - enif_make_string(task->env, encrypted, ERL_NIF_LATIN1)); -} - -static void* async_worker(void* arg) +static ERL_NIF_TERM error(ErlNifEnv *env, const char *reason) { - ctx_t* ctx; - task_t* task; - - ERL_NIF_TERM result; - - ctx = (ctx_t*)arg; - - while (1) { - task = (task_t*)async_queue_pop(ctx->queue); - - if (task->type == SHUTDOWN) { - free_task(task); - break; - } else if (task->type == HASH) { - result = hashpw(task); - } else { - errx(1, "Unexpected task type: %i", task->type); - } - - enif_send(NULL, &task->pid, task->env, result); - free_task(task); - } - - return NULL; + return enif_make_tuple2(env, enif_make_atom(env, "error"), + enif_make_atom(env, reason)); } -static ERL_NIF_TERM bcrypt_encode_salt(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) +static ERL_NIF_TERM bcrypt_encode_salt(ErlNifEnv *env, int argc, + const ERL_NIF_TERM argv[]) { - ErlNifBinary csalt, bin; - unsigned long log_rounds; - ERL_NIF_TERM ret; + ErlNifBinary raw; + unsigned int rounds; + char salt[BCRYPT_SALTSIZE]; - if (!enif_inspect_binary(env, argv[0], &csalt) || 16 != csalt.size) { + if (argc != 2 || !enif_inspect_binary(env, argv[0], &raw) || + raw.size != 16 || !enif_get_uint(env, argv[1], &rounds) || + rounds < 4 || rounds > 31) return enif_make_badarg(env); - } - - if (!enif_get_ulong(env, argv[1], &log_rounds)) { - enif_release_binary(&csalt); - return enif_make_badarg(env); - } - - if (!enif_alloc_binary(64, &bin)) { - enif_release_binary(&csalt); - return enif_make_badarg(env); - } - - encode_salt((char *)bin.data, (u_int8_t*)csalt.data, csalt.size, log_rounds); - enif_release_binary(&csalt); - - ret = enif_make_string(env, (char *)bin.data, ERL_NIF_LATIN1); - enif_release_binary(&bin); - return ret; + /* Inspected binaries belong to the VM; never release them here. */ + encode_salt(salt, raw.data, raw.size, rounds); + return enif_make_string(env, salt, ERL_NIF_LATIN1); } -static ERL_NIF_TERM bcrypt_hashpw(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) +/* OTP owns scheduling and lifetime. There are no native queues, worker + * threads, allocated task environments or blocking resource destructors. */ +static ERL_NIF_TERM bcrypt_hashpw(ErlNifEnv *env, int argc, + const ERL_NIF_TERM argv[]) { - ctx_t *ctx; - task_t *task; - ErlNifPid pid; - - if (argc != 5) - return enif_make_badarg(env); - - bcrypt_privdata_t *priv = (bcrypt_privdata_t*)enif_priv_data(env); - - if (!enif_get_resource(env, argv[0], priv->bcrypt_rt, (void**)(&ctx))) - return enif_make_badarg(env); - - if (!enif_is_ref(env, argv[1])) - return enif_make_badarg(env); - - if (!enif_get_local_pid(env, argv[2], &pid)) - return enif_make_badarg(env); - - ERL_NIF_TERM orig_terms[] = { argv[4], argv[3] }; - task = alloc_init_task(HASH, argv[1], pid, 2, orig_terms); - - if (!task) - return enif_make_badarg(env); - - async_queue_push(ctx->queue, task); - - return enif_make_atom(env, "ok"); -} + ErlNifBinary password, salt; + char encrypted[BCRYPT_HASHSIZE]; + ERL_NIF_TERM result; + int status; -static ERL_NIF_TERM bcrypt_create_ctx(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) -{ - ERL_NIF_TERM ret; - bcrypt_privdata_t *priv = (bcrypt_privdata_t*)enif_priv_data(env); - ctx_t* ctx = (ctx_t*)enif_alloc_resource(priv->bcrypt_rt, sizeof(ctx_t)); - if (ctx == NULL) - return enif_make_badarg(env); - ctx->queue = async_queue_create("bcrypt_queue_mutex", "bcrypt_queue_condvar"); - ctx->topts = enif_thread_opts_create("bcrypt_thread_opts"); - if (enif_thread_create("bcrypt_worker", &ctx->tid, async_worker, ctx, ctx->topts) != 0) { - enif_release_resource(ctx); + if (argc != 2 || !enif_inspect_binary(env, argv[0], &password) || + !enif_inspect_binary(env, argv[1], &salt)) return enif_make_badarg(env); + status = bcrypt_hash(encrypted, sizeof(encrypted), password.data, + password.size, salt.data, salt.size); + switch (status) { + case BCRYPT_OK: + result = enif_make_tuple2(env, enif_make_atom(env, "ok"), + enif_make_string(env, encrypted, ERL_NIF_LATIN1)); + bcrypt_clear(encrypted, sizeof(encrypted)); + return result; + case BCRYPT_INVALID_PASSWORD: + return error(env, "invalid_password"); + case BCRYPT_INVALID_PASSWORD_LENGTH: + return error(env, "invalid_password_length"); + default: + return error(env, "invalid_salt"); } - ret = enif_make_resource(env, ctx); - enif_release_resource(ctx); - return ret; } -static ErlNifFunc bcrypt_nif_funcs[] = -{ - {"encode_salt", 2, bcrypt_encode_salt}, - {"hashpw", 5, bcrypt_hashpw}, - {"create_ctx", 0, bcrypt_create_ctx}, +static ErlNifFunc bcrypt_nif_funcs[] = { + {"encode_salt", 2, bcrypt_encode_salt, 0}, + {"hashpw_dirty", 2, bcrypt_hashpw, ERL_NIF_DIRTY_JOB_CPU_BOUND} }; -static void bcrypt_rt_dtor(ErlNifEnv* env, void* obj) -{ - ctx_t *ctx = (ctx_t*)obj; - task_t *task = alloc_task(SHUTDOWN); - void *result = NULL; - - async_queue_push(ctx->queue, task); - enif_thread_join(ctx->tid, &result); - async_queue_destroy(ctx->queue); - enif_thread_opts_destroy(ctx->topts); -} - -static int on_load(ErlNifEnv* env, void** priv_data, ERL_NIF_TERM load_info) -{ - const char *mod = "bcrypt_nif"; - const char *name = "nif_resource"; - - ErlNifResourceFlags flags = (ErlNifResourceFlags)(ERL_NIF_RT_CREATE | ERL_NIF_RT_TAKEOVER); - - bcrypt_privdata_t *priv = (bcrypt_privdata_t*)enif_alloc(sizeof(bcrypt_privdata_t)); - priv->bcrypt_rt = enif_open_resource_type(env, mod, name, bcrypt_rt_dtor, flags, NULL); - if (priv->bcrypt_rt == NULL) - return -1; - *priv_data = priv; - return 0; -} - -ERL_NIF_INIT(bcrypt_nif, bcrypt_nif_funcs, &on_load, NULL, NULL, NULL) +ERL_NIF_INIT(bcrypt_nif, bcrypt_nif_funcs, NULL, NULL, NULL, NULL) diff --git a/c_src/bcrypt_nif.h b/c_src/bcrypt_nif.h deleted file mode 100644 index 9c1cd69..0000000 --- a/c_src/bcrypt_nif.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef ERLANG_BCRYPT_BCRYPT_NIF_H -#define ERLANG_BCRYPT_BCRYPT_NIF_H - -#include "async_queue.h" - -typedef unsigned char byte; - -int ts_bcrypt(char *, const char *, const char *); -void encode_salt(char *, u_int8_t *, u_int16_t, u_int8_t); - -typedef struct { - ErlNifResourceType *bcrypt_rt; -} bcrypt_privdata_t; - -typedef struct { - async_queue_t *queue; - ErlNifThreadOpts *topts; - ErlNifTid tid; -} ctx_t; - -typedef enum { - UNKNOWN, - SHUTDOWN, - HASH -} task_type_t; - -typedef struct { - task_type_t type; - ErlNifEnv *env; - ErlNifPid pid; - ERL_NIF_TERM ref; - union { - struct { - ErlNifBinary salt; - ErlNifBinary password; - } hash; - } data; -} task_t; - -#endif // ERLANG_BCRYPT_BCRYPT_NIF_H diff --git a/c_src/bcrypt_port.c b/c_src/bcrypt_port.c index 7cafb2b..9117269 100644 --- a/c_src/bcrypt_port.c +++ b/c_src/bcrypt_port.c @@ -20,6 +20,7 @@ #include #include "erl_blf.h" +#include "bcrypt.h" #include "ei.h" #define dec_int16(s) ((((unsigned char*)(s))[0] << 8) | \ @@ -29,11 +30,7 @@ #define CMD_SALT 0 #define CMD_HASHPW 1 -#define DATASIZE 1024 - -extern int ts_bcrypt(char *, const char *, const char *); -extern void encode_salt(char *, u_int8_t *, u_int16_t, u_int8_t); - +#define DATASIZE BCRYPT_MAXPASSWORD static void fail(int place) { @@ -166,14 +163,25 @@ process_hashpw( int salt_size, char *salt) { - char encrypted[DATASIZE+1]; - - memset(encrypted, 0, DATASIZE+1); - if (ts_bcrypt(encrypted, password, salt)) { - process_error_reply(CMD_HASHPW, "invalid_salt"); - } else { - process_reply(CMD_HASHPW, encrypted); + char encrypted[BCRYPT_HASHSIZE]; + int result = bcrypt_hash(encrypted, sizeof(encrypted), + (unsigned char *)password, password_size, + (unsigned char *)salt, salt_size); + switch (result) { + case BCRYPT_OK: + process_reply(CMD_HASHPW, encrypted); + break; + case BCRYPT_INVALID_PASSWORD: + process_error_reply(CMD_HASHPW, "invalid_password"); + break; + case BCRYPT_INVALID_PASSWORD_LENGTH: + process_error_reply(CMD_HASHPW, "invalid_password_length"); + break; + default: + process_error_reply(CMD_HASHPW, "invalid_salt"); } + bcrypt_clear(encrypted, sizeof(encrypted)); + bcrypt_clear(password, password_size); } static void @@ -216,8 +224,11 @@ process_command(char *buf) fail(8); if (type != ERL_BINARY_EXT) fail(9); - if (data_size < 0 || data_size > DATASIZE) - fail(10); + if (data_size < 0 || data_size > DATASIZE) { + process_error_reply(cmd, cmd == CMD_HASHPW ? + "invalid_password_length" : "invalid_salt_length"); + return; + } if (ei_decode_binary(buf, &index, data, &len) != 0) fail(11); @@ -228,8 +239,11 @@ process_command(char *buf) fail(12); if (type != ERL_BINARY_EXT) fail(13); - if (salt_size < 0 || salt_size > DATASIZE) - fail(14); + if (salt_size < 0 || salt_size > DATASIZE) { + process_error_reply(cmd, "invalid_salt"); + bcrypt_clear(data, sizeof(data)); + return; + } if (ei_decode_binary(buf, &index, salt, &len) != 0) fail(15); @@ -254,6 +268,7 @@ loop(void) while (read_cmd(buf) == 1) { process_command(buf); + bcrypt_clear(buf, sizeof(buf)); } } diff --git a/rebar.config b/rebar.config index 12056d8..3b45507 100644 --- a/rebar.config +++ b/rebar.config @@ -12,8 +12,9 @@ {post_hooks, [{"(linux|darwin|solaris)", clean, "make -C c_src clean"}, {"(freebsd|openbsd|dragonfly)", clean, "gmake -C c_src clean"}]}. + {deps, [ - {poolboy, "1.5.2"} + {poolboy, "~> 1.5"} ]}. {profiles, [ @@ -28,6 +29,7 @@ ]}, {dialyzer, [ + {plt_extra_apps, [eunit, proper]}, {warnings, [ no_return ]} diff --git a/src/bcrypt.erl b/src/bcrypt.erl index dce0943..7674a01 100644 --- a/src/bcrypt.erl +++ b/src/bcrypt.erl @@ -11,7 +11,8 @@ -type mechanism() :: nif | port. -type rounds() :: 4..31. --type pwerr() :: invalid_salt | invalid_salt_length | invalid_rounds. +-type pwerr() :: invalid_salt | invalid_salt_length | invalid_rounds + | invalid_password | invalid_password_length. -export_type([ mechanism/0, rounds/0, pwerr/0 ]). @@ -60,7 +61,11 @@ gen_salt(Rounds) when is_integer(Rounds), Rounds < 32, Rounds > 3 -> Hash :: [byte()], ErrorDescription :: pwerr(). hashpw(Password, Salt) -> - do_hashpw(mechanism(), Password, Salt). + case {iolist_size(Password), iolist_size(Salt)} of + {N, _} when N > 1024 -> {error, invalid_password_length}; + {_, N} when N =/= 29, N =/= 60 -> {error, invalid_salt}; + _ -> do_hashpw(mechanism(), Password, Salt) + end. %% @doc Is at least one bcrypt worker currently available for work? diff --git a/src/bcrypt_nif.erl b/src/bcrypt_nif.erl index 348d8df..a132dbe 100644 --- a/src/bcrypt_nif.erl +++ b/src/bcrypt_nif.erl @@ -70,14 +70,14 @@ encode_salt(_R, _LogRounds) -> nif_stub_error(?LINE). %%-------------------------------------------------------------------- -%% @doc Create a context which hashes passwords in a separate thread. +%% @doc Create an opaque token for the asynchronous hashing interface. %% @end %%-------------------------------------------------------------------- -spec create_ctx() -> Context when Context :: term(). create_ctx() -> - nif_stub_error(?LINE). + make_ref(). %%-------------------------------------------------------------------- %% @doc Hash the specified password and the salt using the OpenBSD @@ -89,10 +89,29 @@ create_ctx() -> Ctx :: term(), Ref :: reference(), Pid :: pid(), - Password :: [byte()], - Salt :: [byte()], + Password :: iodata(), + Salt :: iodata(), Result :: ok. -hashpw(_Ctx, _Ref, _Pid, _Password, _Salt) -> +hashpw(Ctx, Ref, Pid, Password, Salt) + when is_reference(Ctx), is_reference(Ref), is_pid(Pid), node(Pid) =:= node() -> + %% Bound inputs before converting iolists or copying them into a helper. + case {iolist_size(Password), iolist_size(Salt)} of + {N, _} when N > 1024 -> + Pid ! {error, Ref, invalid_password_length}; + {_, N} when N =/= 29, N =/= 60 -> + Pid ! {error, Ref, invalid_salt}; + _ -> + Pass = iolist_to_binary(Password), + Setting = iolist_to_binary(Salt), + spawn(fun() -> + {Status, Result} = hashpw_dirty(Pass, Setting), + Pid ! {Status, Ref, Result} + end) + end, + ok. + +%% This NIF runs exclusively on OTP dirty CPU schedulers. +hashpw_dirty(_Password, _Salt) -> nif_stub_error(?LINE). nif_stub_error(Line) -> diff --git a/src/bcrypt_nif_worker.erl b/src/bcrypt_nif_worker.erl index 32d4eeb..039b1dd 100644 --- a/src/bcrypt_nif_worker.erl +++ b/src/bcrypt_nif_worker.erl @@ -89,30 +89,8 @@ terminate(shutdown, _) -> ok. %% @private --spec handle_call(Request, From, State) -> Result when - Request :: gen_salt, - From :: {pid(), atom()}, - State :: state(), - Result :: {reply, Reply, State}, - Reply :: {ok, Salt}, - Salt :: integer(); -(Request, From, State) -> Result when - Request :: {gen_salt, Rounds}, - From :: {pid(), atom()}, - State :: state(), - Rounds :: bcrypt:rounds(), - Result :: {reply, Reply, State}, - Reply :: {ok, Salt}, - Salt :: integer(); -(Request, From, State) -> Result when - Request :: {hashpw, Password, Salt}, - From :: {pid(), atom()}, - State :: state(), - Password :: [byte()], - Salt :: integer(), - Result :: {reply, Reply, State} | {reply, Reply, State}, - Reply :: {ok, ResultInfo} | {error, ResultInfo}, - ResultInfo :: term(). +-spec handle_call(term(), gen_server:from(), state()) -> + {reply, term(), state()}. handle_call(gen_salt, _From, #state{default_log_rounds = R} = State) -> Salt = bcrypt_nif:gen_salt(R), @@ -122,7 +100,7 @@ handle_call({gen_salt, R}, _From, State) -> {reply, {ok, Salt}, State}; handle_call({hashpw, Password, Salt}, _From, #state{context=Ctx}=State) -> Ref = make_ref(), - ok = bcrypt_nif:hashpw(Ctx, Ref, self(), to_list(Password), to_list(Salt)), + ok = bcrypt_nif:hashpw(Ctx, Ref, self(), Password, Salt), receive {ok, Ref, Result} -> {reply, {ok, Result}, State}; @@ -142,12 +120,3 @@ handle_info(Msg, _) -> exit({unknown_info, Msg}). %% @private code_change(_OldVsn, State, _Extra) -> {ok, State}. - --spec to_list(List) -> Result when - List :: [byte()], - Result :: [byte()]; -(Binary) -> Result when - Binary :: binary(), - Result :: [byte()]. -to_list(L) when is_list(L) -> L; -to_list(B) when is_binary(B) -> binary_to_list(B). diff --git a/src/bcrypt_pool.erl b/src/bcrypt_pool.erl index 6b29270..f6820c4 100644 --- a/src/bcrypt_pool.erl +++ b/src/bcrypt_pool.erl @@ -23,7 +23,7 @@ ports = queue:new() }). --record(req, {mon :: reference(), from :: {pid(), atom()}}). +-record(req, {mon :: reference(), from :: gen_server:from()}). -type state() :: #state{size :: 0, busy :: 0, requests :: queue:queue(), ports :: queue:queue()}. @@ -85,8 +85,7 @@ terminate(shutdown, _) -> ok. -spec handle_call(Request, From, State) -> Result when Request :: request, - From :: {RPid, atom()}, - RPid :: pid(), + From :: gen_server:from(), State :: state(), Result :: {noreply, state()} | {reply, {ok, pid()}, state()}. handle_call(request, {RPid, _} = From, #state{ports = P} = State) -> diff --git a/test/bcrypt_native_tests.c b/test/bcrypt_native_tests.c new file mode 100644 index 0000000..09e3ec2 --- /dev/null +++ b/test/bcrypt_native_tests.c @@ -0,0 +1,41 @@ +/* Run under ASan/UBSan with `make security-test`. */ +#include +#include +#include "bcrypt.h" + +int main(void) +{ + unsigned char password[1025]; + unsigned char salt[1024]; + const unsigned char valid[] = "$2b$04$......................"; + char output[BCRYPT_HASHSIZE]; + memset(password, 'A', sizeof(password)); + memset(salt, '.', sizeof(salt)); + memcpy(salt, "$2b$04$", 7); + + /* Inputs are deliberately not NUL terminated. */ + assert(bcrypt_hash(output, sizeof(output), password, 1024, + valid, 29) == BCRYPT_OK); + assert(strlen(output) == 60); + assert(bcrypt_hash(output, 60, password, 72, + valid, 29) == BCRYPT_INVALID_SALT); + assert(bcrypt_hash(output, sizeof(output), password, 1025, + valid, 29) == BCRYPT_INVALID_PASSWORD_LENGTH); + assert(bcrypt_hash(output, sizeof(output), password, 72, + salt, sizeof(salt)) == BCRYPT_INVALID_SALT); + assert(bcrypt_hash(output, sizeof(output), password, 72, + NULL, 0) == BCRYPT_INVALID_SALT); + for (size_t i = 7; i < 29; i++) { + memcpy(salt, valid, 29); + salt[i] = '!'; + assert(bcrypt_hash(output, sizeof(output), password, 72, + salt, 29) == BCRYPT_INVALID_SALT); + } + password[0] = 0; + assert(bcrypt_hash(output, sizeof(output), password, 72, + valid, 29) == BCRYPT_INVALID_PASSWORD); + bcrypt_clear(password, sizeof(password)); + for (size_t i = 0; i < sizeof(password); i++) + assert(password[i] == 0); + return 0; +} diff --git a/test/bcrypt_security_tests.erl b/test/bcrypt_security_tests.erl new file mode 100644 index 0000000..665275f --- /dev/null +++ b/test/bcrypt_security_tests.erl @@ -0,0 +1,135 @@ +-module(bcrypt_security_tests). +-include_lib("eunit/include/eunit.hrl"). + +-define(SALT, <<"$2b$04$......................">>). +-define(LEGACY_SALT, <<"$2a$04$......................">>). + +security_test_() -> + [{atom_to_list(Mechanism), + {setup, fun() -> start(Mechanism) end, + fun(_) -> application:stop(bcrypt) end, + fun(_) -> [ + ?_test(default_version()), + ?_test(known_vectors()), + ?_test(length_boundaries()), + ?_test(legacy_verification()), + ?_test(nul_passwords()), + ?_test(invalid_salts()), + ?_test(reject_oversized_inputs()) + ] end}} + || Mechanism <- [nif, port]]. + +start(Mechanism) -> + application:stop(bcrypt), + application:load(bcrypt), + application:set_env(bcrypt, mechanism, Mechanism), + application:set_env(bcrypt, nif_pool_size, 1), + application:set_env(bcrypt, nif_pool_max_overflow, 0), + application:set_env(bcrypt, pool_size, 1), + {ok, _} = application:ensure_all_started(bcrypt). + +default_version() -> + ?assertMatch({ok, "$2b$12$" ++ _}, bcrypt:gen_salt()), + {ok, "$2b$04$" ++ Encoded} = bcrypt:gen_salt(4), + ?assertEqual(22, length(Encoded)). + +known_vectors() -> + %% Published Openwall vectors; $2b$ agrees with $2a$ for these inputs. + Salt = "$2b$05$CCCCCCCCCCCCCCCCCCCCC.", + lists:foreach(fun({Password, Suffix}) -> + ?assertEqual({ok, Salt ++ Suffix}, bcrypt:hashpw(Password, Salt)) + end, [{"", "7uG0VCzI2bS7j6ymqJi9CdcdxiRTWNy"}, + {"U*U", "E5YPO9kmyuRGyh0XouQYb4YMJKvyOeW"}, + {"U*U*", "VGOzA784oUp/Z0DY336zx7pLYAy0lwK"}]). + +length_boundaries() -> + %% $2b$ consumes the first 72 bytes, without an 8-bit length wrap. + Password = <<"A", (binary:copy(<<"B">>, 1023))/binary>>, + {ok, Expected} = bcrypt:hashpw(binary:part(Password, 0, 72), ?SALT), + lists:foreach(fun(N) -> + ?assertEqual({ok, Expected}, + bcrypt:hashpw(binary:part(Password, 0, N), ?SALT)) + end, [72, 73, 254, 255, 256, 257, 511, 512, 1023, 1024]), + ?assertNotEqual({ok, Expected}, + bcrypt:hashpw(binary:part(Password, 0, 71), ?SALT)), + ?assertNotEqual({ok, Expected}, + bcrypt:hashpw(binary:copy(<<"A">>, 72), ?SALT)), + ?assertEqual({ok, Expected}, bcrypt:hashpw(Password, Expected)). + +legacy_verification() -> + %% Captured from the pre-fix implementation, including its wraparound. + Password = <<"A", (binary:copy(<<"B">>, 255))/binary>>, + Hash = "$2a$04$.......................KyxKLMd5vyP1icw21wqSvz/XeB9gba", + ?assertEqual({ok, Hash}, bcrypt:hashpw(Password, ?LEGACY_SALT)), + ?assertEqual({ok, Hash}, bcrypt:hashpw(Password, Hash)). + +nul_passwords() -> + lists:foreach(fun(P) -> + ?assertEqual({error, invalid_password}, bcrypt:hashpw(P, ?SALT)) + end, [<<0>>, <<"abc", 0, "def">>, <<"abc", 0>>]), + %% Existing $2a$ hashes remain verifiable, even for historical NUL inputs. + Legacy = "$2a$04$......................ini1L2hXWkegMV822DC6vks..mWmZHK", + ?assertEqual({ok, Legacy}, bcrypt:hashpw(<<"abc", 0, "def">>, Legacy)). + +invalid_salts() -> + Invalid = [<<>>, <<"$">>, <<"$2b$04$">>, + <<"X2b$04$......................">>, + <<"$1b$04$......................">>, + <<"$2x$04$......................">>, + <<"$2bX04$......................">>, + <<"$2b$4x$......................">>, + <<"$2b$+4$......................">>, + <<"$2b$03$......................">>, + <<"$2b$32$......................">>, + binary:copy(<<"A">>, 1024)], + lists:foreach(fun(S) -> + ?assertEqual({error, invalid_salt}, bcrypt:hashpw(<<"test">>, S)) + end, Invalid), + %% Exercise every decoder position, including NUL and non-ASCII input. + lists:foreach(fun({Pos, Byte}) -> + <> = ?SALT, + Salt = <>, + ?assertEqual({error, invalid_salt}, bcrypt:hashpw(<<"test">>, Salt)) + end, [{Pos, Byte} || Pos <- lists:seq(7, 28), Byte <- [0, $!, 255]]). + +reject_oversized_inputs() -> + ?assertEqual({error, invalid_password_length}, + bcrypt:hashpw(binary:copy(<<"A">>, 1025), ?SALT)), + ?assertEqual({error, invalid_salt}, + bcrypt:hashpw(<<"test">>, binary:copy(<<"A">>, 1025))), + %% Exercise backend entry points too, bypassing public size checks. + Hash = case bcrypt:mechanism() of + nif -> fun bcrypt_nif_worker:hashpw/2; + port -> fun bcrypt_pool:hashpw/2 + end, + ?assertEqual({error, invalid_password_length}, + Hash(binary:copy(<<"A">>, 1025), ?SALT)), + ?assertEqual({error, invalid_salt}, + Hash(<<"test">>, binary:copy(<<"A">>, 1025))), + %% A rejected request must not break or consume a pool worker. + ?assertMatch({ok, _}, bcrypt:hashpw(<<"test">>, ?SALT)). + +async_owner_exit_test() -> + %% Run with +S 1 as well: owner exit must not join a hashing C thread. + Parent = self(), + Pid = spawn(fun() -> + Ctx = bcrypt_nif:create_ctx(), + ok = bcrypt_nif:hashpw(Ctx, make_ref(), self(), <<"test">>, + <<"$2b$14$......................">>), + Parent ! ready, + receive stop -> Ctx end + end), + receive ready -> ok after 5000 -> error(owner_not_ready) end, + Monitor = monitor(process, Pid), + Started = erlang:monotonic_time(millisecond), + exit(Pid, kill), + receive {'DOWN', Monitor, process, Pid, killed} -> ok + after 200 -> error(owner_exit_blocked) + end, + ?assert(erlang:monotonic_time(millisecond) - Started < 200), + %% Independently prove the asynchronous API still delivers its response. + Ref = make_ref(), + ok = bcrypt_nif:hashpw(bcrypt_nif:create_ctx(), Ref, self(), <<"test">>, ?SALT), + receive {ok, Ref, "$2b$04$" ++ _} -> ok + after 5000 -> error(no_hash_reply) + end. diff --git a/test/bcrypt_tests.erl b/test/bcrypt_tests.erl index e54a6ca..26fdc4f 100644 --- a/test/bcrypt_tests.erl +++ b/test/bcrypt_tests.erl @@ -125,13 +125,15 @@ is_worker_available_nif_test_() -> [{timeout, 5000, fun() -> ?assert(bcrypt:is_worker_available()), - spawn_long_hash(), - {ok, Salt} = bcrypt:gen_salt(), - bcrypt:hashpw("foo", Salt), - ?assert(bcrypt:is_worker_available()), - spawn_long_hash(), - bcrypt:hashpw("foo", Salt), - ?assertNot(bcrypt:is_worker_available()) + First = poolboy:checkout(bcrypt_nif_pool), + Second = poolboy:checkout(bcrypt_nif_pool), + try + ?assertNot(bcrypt:is_worker_available()) + after + poolboy:checkin(bcrypt_nif_pool, Second), + poolboy:checkin(bcrypt_nif_pool, First) + end, + ?assert(bcrypt:is_worker_available()) end}]}. simple_port_test_() -> @@ -158,11 +160,11 @@ is_worker_available_port_test_() -> [{timeout, 5000, fun() -> ?assert(bcrypt:is_worker_available()), - spawn_long_hash(), - spawn_long_hash(), - ?assertNot(bcrypt:is_worker_available()) + {ok, Worker} = gen_server:call(bcrypt_pool, request), + try + ?assertNot(bcrypt:is_worker_available()) + after + bcrypt_pool:available(Worker) + end, + ?assert(bcrypt:is_worker_available()) end}]}. - -spawn_long_hash() -> - {ok, Salt} = bcrypt:gen_salt(15), - spawn(bcrypt, hashpw, ["foo", Salt]). diff --git a/test/prop_bcrypt.erl b/test/prop_bcrypt.erl index 205e34f..c48a157 100644 --- a/test/prop_bcrypt.erl +++ b/test/prop_bcrypt.erl @@ -9,7 +9,7 @@ prop_mechanism_nif() -> - ?SETUP(setup(nif), + with_setup(nif, ?FORALL(_Ok, exactly(ok), begin Mechanism = bcrypt:mechanism(), @@ -18,7 +18,7 @@ prop_mechanism_nif() -> ). prop_mechanism_port() -> - ?SETUP(setup(port), + with_setup(port, ?FORALL(_Ok, exactly(ok), begin Mechanism = bcrypt:mechanism(), @@ -27,28 +27,28 @@ prop_mechanism_port() -> ). prop_salt_rounds_nif() -> - ?SETUP(setup(nif), + with_setup(nif, check_salt_rounds() ). prop_salt_rounds_port() -> - ?SETUP(setup(port), + with_setup(port, check_salt_rounds() ). prop_salt_port() -> - ?SETUP(setup(port), + with_setup(port, check_salt() ). prop_simple_nif() -> - ?SETUP(setup(nif), + with_setup(nif, check_simple() ). prop_simple_port() -> - ?SETUP(setup(port), + with_setup(port, check_simple() ). @@ -56,6 +56,12 @@ prop_simple_port() -> %%% Helpers %%% %%%%%%%%%%%%%%%%%% +%% PropEr distinguishes test/0 from outer_test/0 as opaque types. +%% Use its public conversion before passing a property to the setup wrapper. +-spec with_setup(bcrypt:mechanism(), proper:test()) -> proper:outer_test(). +with_setup(Mechanism, Property) -> + proper:setup(setup(Mechanism), proper:test_to_outer_test(Property)). + setup(Mechanism) -> fun() -> application:start(crypto), @@ -104,5 +110,6 @@ check_simple() -> %%% Generators %%% %%%%%%%%%%%%%%%%%% -password() -> oneof([non_empty(binary()), non_empty(ascii_string())]). -ascii_string() -> list(range(0,255)). +%% $2b$ rejects embedded NUL bytes; explicit rejection is covered by EUnit. +password() -> oneof([?LET(Bytes, ascii_string(), list_to_binary(Bytes)), ascii_string()]). +ascii_string() -> list(range(1,255)).