2 * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
4 * Licensed under the OpenSSL license (the "License"). You may not use
5 * this file except in compliance with the License. You can obtain a copy
6 * in the file LICENSE in the source distribution or at
7 * https://www.openssl.org/source/license.html
11 #include "internal/thread_once.h"
18 int UI_UTIL_read_pw_string(char *buf, int length, const char *prompt,
25 UI_UTIL_read_pw(buf, buff, (length > BUFSIZ) ? BUFSIZ : length,
27 OPENSSL_cleanse(buff, BUFSIZ);
31 int UI_UTIL_read_pw(char *buf, char *buff, int size, const char *prompt,
42 ok = UI_add_input_string(ui, prompt, 0, buf, 0, size - 1);
43 if (ok >= 0 && verify)
44 ok = UI_add_verify_string(ui, prompt, 0, buff, 0, size - 1, buf);
55 * Wrapper around pem_password_cb, a method to help older APIs use newer
58 struct pem_password_cb_data {
63 static void ui_new_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
64 int idx, long argl, void *argp)
67 * Do nothing, the data is allocated externally and assigned later with
68 * CRYPTO_set_ex_data()
72 static int ui_dup_method_data(CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from,
73 void *from_d, int idx, long argl, void *argp)
75 void **pptr = (void **)from_d;
77 *pptr = OPENSSL_memdup(*pptr, sizeof(struct pem_password_cb_data));
81 static void ui_free_method_data(void *parent, void *ptr, CRYPTO_EX_DATA *ad,
82 int idx, long argl, void *argp)
87 static CRYPTO_ONCE get_index_once = CRYPTO_ONCE_STATIC_INIT;
88 DEFINE_RUN_ONCE_STATIC(ui_method_data_index)
90 return CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI_METHOD, 0, NULL,
91 ui_new_method_data, ui_dup_method_data,
95 static int ui_open(UI *ui)
99 static int ui_read(UI *ui, UI_STRING *uis)
101 switch (UI_get_string_type(uis)) {
104 char result[PEM_BUFSIZE];
105 const struct pem_password_cb_data *data =
106 UI_method_get_ex_data(UI_get_method(ui),
107 RUN_ONCE(&get_index_once,
108 ui_method_data_index));
109 int maxsize = UI_get_result_maxsize(uis);
110 int len = data->cb(result,
111 maxsize > PEM_BUFSIZE ? PEM_BUFSIZE : maxsize,
112 data->rwflag, UI_get0_user_data(ui));
116 if (UI_set_result(ui, uis, result) >= 0)
129 static int ui_write(UI *ui, UI_STRING *uis)
133 static int ui_close(UI *ui)
138 UI_METHOD *UI_UTIL_wrap_read_pem_callback(pem_password_cb *cb, int rwflag)
140 struct pem_password_cb_data *data = NULL;
141 UI_METHOD *ui_method = NULL;
144 if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL
145 || (ui_method = UI_create_method("PEM password callback wrapper")) == NULL
146 || UI_method_set_opener(ui_method, ui_open) < 0
147 || UI_method_set_reader(ui_method, ui_read) < 0
148 || UI_method_set_writer(ui_method, ui_write) < 0
149 || UI_method_set_closer(ui_method, ui_close) < 0
150 || (idx = RUN_ONCE(&get_index_once, ui_method_data_index)) <= 0
151 || UI_method_set_ex_data(ui_method, idx, data) < 0) {
152 UI_destroy_method(ui_method);
156 data->rwflag = rwflag;