Skip to content

Commit

Permalink
fix(ssh): support login without password
Browse files Browse the repository at this point in the history
Signed-off-by: Jianhui Zhao <zhaojh329@gmail.com>
  • Loading branch information
zhaojh329 committed Nov 24, 2023
1 parent 50388e3 commit 38097e9
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 5 deletions.
25 changes: 25 additions & 0 deletions ssh.c
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,30 @@ static int lua_ssh_session_handshake(lua_State *L)
return 1;
}

static int lua_ssh_session_userauth_list(lua_State *L)
{
struct eco_ssh_session *session = luaL_checkudata(L, 1, ECO_SSH_SESSION_MT);
const char *username = luaL_checkstring(L, 2);
char *userauthlist;

if (!session->session)
return luaL_error(L, "session freed");

userauthlist = libssh2_userauth_list(session->session, username, strlen(username));
if (!userauthlist) {
char *err_msg;

libssh2_session_last_error(session->session, &err_msg, NULL, 0);
lua_pushnil(L);
lua_pushstring(L, err_msg);

return 2;
}

lua_pushstring(L, userauthlist);
return 1;
}

/* In case of success, it returns true, in case of error锛宨t returns nil with an error code */
static int lua_ssh_session_userauth_password(lua_State *L)
{
Expand Down Expand Up @@ -516,6 +540,7 @@ static int lua_ssh_session_free(lua_State *L)
static const luaL_Reg session_methods[] = {
{"block_directions", lua_ssh_session_block_directions},
{"handshake", lua_ssh_session_handshake},
{"userauth_list", lua_ssh_session_userauth_list},
{"userauth_password", lua_ssh_session_userauth_password},
{"open_channel", lua_ssh_session_open_channel},
{"scp_recv", lua_ssh_session_scp_recv},
Expand Down
27 changes: 22 additions & 5 deletions ssh.lua
Original file line number Diff line number Diff line change
Expand Up @@ -457,17 +457,34 @@ function M.new(ipaddr, port, username, password)
end
end

local userauth_list

while true do
ok, err = session:userauth_password(username, password)
if ok then break end
userauth_list, err = session:userauth_list(username)
if userauth_list or err == '' then break end

if err ~= ssh.ERROR_EAGAIN then
err = session:last_error()
if session:last_errno() ~= ssh.ERROR_EAGAIN then
return nil, err
end

if not waitsocket(obj, 5.0) then
return nil, 'authentication timeout'
return nil, 'userauth_list timeout'
end
end

if userauth_list and userauth_list:match('password') then
while true do
ok, err = session:userauth_password(username, password)
if ok then break end

if err ~= ssh.ERROR_EAGAIN then
err = session:last_error()
return nil, err
end

if not waitsocket(obj, 5.0) then
return nil, 'authentication timeout'
end
end
end

Expand Down

0 comments on commit 38097e9

Please sign in to comment.