From f4942134815f95845706993c15ca7e4fd6e44627 Mon Sep 17 00:00:00 2001
From: Bernd Edlinger <bernd.edlinger@hotmail.de>
Date: Fri, 7 Jan 2022 10:18:58 +0100
Subject: [PATCH] Fix password_callback to handle short passwords

Fixes #17426

Reviewed-by: Paul Dale <pauli@openssl.org>
(Merged from https://github.com/openssl/openssl/pull/17439)
---
 apps/apps.c                   | 8 ++++++--
 test/recipes/15-test_genrsa.t | 7 ++++++-
 2 files changed, 12 insertions(+), 3 deletions(-)

diff --git a/apps/apps.c b/apps/apps.c
index c06241abb9..531fbec551 100644
--- a/apps/apps.c
+++ b/apps/apps.c
@@ -300,9 +300,13 @@ int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp)
         int ui_flags = 0;
         const char *prompt_info = NULL;
         char *prompt;
+        int pw_min_len = PW_MIN_LENGTH;
 
         if (cb_data != NULL && cb_data->prompt_info != NULL)
             prompt_info = cb_data->prompt_info;
+        if (cb_data != NULL && cb_data->password != NULL
+                && *(const char*)cb_data->password != '\0')
+            pw_min_len = 1;
         prompt = UI_construct_prompt(ui, "pass phrase", prompt_info);
         if (!prompt) {
             BIO_printf(bio_err, "Out of memory\n");
@@ -317,12 +321,12 @@ int password_callback(char *buf, int bufsiz, int verify, PW_CB_DATA *cb_tmp)
         (void)UI_add_user_data(ui, cb_data);
 
         ok = UI_add_input_string(ui, prompt, ui_flags, buf,
-                                 PW_MIN_LENGTH, bufsiz - 1);
+                                 pw_min_len, bufsiz - 1);
 
         if (ok >= 0 && verify) {
             buff = app_malloc(bufsiz, "password buffer");
             ok = UI_add_verify_string(ui, prompt, ui_flags, buff,
-                                      PW_MIN_LENGTH, bufsiz - 1, buf);
+                                      pw_min_len, bufsiz - 1, buf);
         }
         if (ok >= 0)
             do {
diff --git a/test/recipes/15-test_genrsa.t b/test/recipes/15-test_genrsa.t
index e16a9a4042..c9bc6bdc8a 100644
--- a/test/recipes/15-test_genrsa.t
+++ b/test/recipes/15-test_genrsa.t
@@ -16,7 +16,7 @@ use OpenSSL::Test::Utils;
 
 setup("test_genrsa");
 
-plan tests => 5;
+plan tests => 7;
 
 # We want to know that an absurdly small number of bits isn't support
 is(run(app([ 'openssl', 'genrsa', '-3', '-out', 'genrsatest.pem', '8'])), 0, "genrsa -3 8");
@@ -52,3 +52,8 @@ ok(run(app([ 'openssl', 'genrsa', '-f4', '-out', 'genrsatest.pem', $good ])),
    "genrsa -f4 $good");
 ok(run(app([ 'openssl', 'rsa', '-check', '-in', 'genrsatest.pem', '-noout' ])),
    "rsa -check");
+ok(run(app([ 'openssl', 'rsa', '-in', 'genrsatest.pem', '-out', 'genrsatest-enc.pem',
+   '-aes256', '-passout', 'pass:x' ])),
+   "rsa encrypt");
+ok(run(app([ 'openssl', 'rsa', '-in', 'genrsatest-enc.pem', '-passin', 'pass:x' ])),
+   "rsa decrypt");
-- 
2.17.1

