Skip to content

Commit

Permalink
pkey: PEM password callback
Browse files Browse the repository at this point in the history
  • Loading branch information
kunkku committed Jul 1, 2018
1 parent ccfb4be commit 42319d0
Showing 1 changed file with 15 additions and 11 deletions.
26 changes: 15 additions & 11 deletions src/openssl.c
Original file line number Diff line number Diff line change
Expand Up @@ -3404,9 +3404,15 @@ static BIO *getbio(lua_State *L) {


static int pem_pw_cb(char *buf, int size, int rwflag, void *u) {
if (!u)
lua_State *L = (lua_State *) u;

if (lua_isnil(L, -1) || (lua_isfunction(L, -1) && lua_pcall(L, 0, 1, 0)))
return 0;

const char *pass = lua_tostring(L, -1);
if (!pass)
return 0;
char *pass = (char *) u;

strncpy(buf, pass, size);
return MIN(strlen(pass), (unsigned int) size);
} /* pem_password_cb() */
Expand Down Expand Up @@ -3622,7 +3628,7 @@ static int pk_new(lua_State *L) {
} else if (lua_isstring(L, 1)) {
int type = optencoding(L, 2, "*", X509_ANY|X509_PEM|X509_DER);
int pubonly = 0, prvtonly = 0;
const char *opt, *data, *pass;
const char *opt, *data;
size_t len;
BIO *bio;
EVP_PKEY *pub = NULL, *prvt = NULL;
Expand All @@ -3640,9 +3646,6 @@ static int pk_new(lua_State *L) {
}

data = luaL_checklstring(L, 1, &len);
pass = luaL_optstring(L, 4, NULL);

ud = prepsimple(L, PKEY_CLASS);

if (!(bio = BIO_new_mem_buf((void *)data, len)))
return auxL_error(L, auxL_EOPENSSL, "pkey.new");
Expand All @@ -3656,14 +3659,14 @@ static int pk_new(lua_State *L) {
*/
BIO_reset(bio);

if (!(pub = PEM_read_bio_PUBKEY(bio, NULL, pem_pw_cb, pass)))
if (!(pub = PEM_read_bio_PUBKEY(bio, NULL, pem_pw_cb, L)))
goterr = 1;
}

if (!pubonly && !prvt) {
BIO_reset(bio);

if (!(prvt = PEM_read_bio_PrivateKey(bio, NULL, pem_pw_cb, pass)))
if (!(prvt = PEM_read_bio_PrivateKey(bio, NULL, pem_pw_cb, L)))
goterr = 1;
}
}
Expand All @@ -3684,6 +3687,8 @@ static int pk_new(lua_State *L) {
}
}

ud = prepsimple(L, PKEY_CLASS);

if (prvt) {
#if 0
/* TODO: Determine if this is necessary. */
Expand Down Expand Up @@ -4092,11 +4097,10 @@ static int pk_toPEM(lua_State *L) {
static int pk_getPrivateKey(lua_State *L) {
EVP_PKEY *key = checksimple(L, 1, PKEY_CLASS);
const char *cname = luaL_optstring(L, 2, NULL);
const char *pass = NULL;
EVP_CIPHER *cipher = NULL;
lua_settop(L, 3);

if (cname) {
pass = luaL_checkstring(L, 3);
cipher = EVP_get_cipherbyname(cname);
if (!cipher)
return luaL_error(L, "pkey:getPrivateKey: unknown cipher: %s", cname);
Expand All @@ -4106,7 +4110,7 @@ static int pk_getPrivateKey(lua_State *L) {
char *str;
long len;

if (!PEM_write_bio_PrivateKey(bio, key, cipher, NULL, 0, pem_pw_cb, pass))
if (!PEM_write_bio_PrivateKey(bio, key, cipher, NULL, 0, pem_pw_cb, L))
return auxL_error(L, auxL_EOPENSSL, "pkey:getPrivateKey");
len = BIO_get_mem_data(bio, &str);
lua_pushlstring(L, str, len);
Expand Down

0 comments on commit 42319d0

Please sign in to comment.