Add auth helper for no auth or userpass auth

pull/1857/head
myl7 2021-12-28 17:15:08 +08:00
parent 6ab8af1ef5
commit afb45ee0bc
No known key found for this signature in database
GPG Key ID: 04F1013B67177C88
3 changed files with 38 additions and 25 deletions

View File

@ -61,28 +61,9 @@ bool DHTConnectionSocksProxyImpl::startProxy(const std::string& host,
socket_->establish(host, port);
// Authentication negotiation
bool noAuth = user.empty() || passwd.empty();
if (noAuth) {
int authMethod = socket_->negotiateAuth(
std::vector<SocksProxyAuthMethod>{SOCKS_AUTH_NO_AUTH});
if (authMethod < 0) {
return false;
}
}
else {
int authMethod = socket_->negotiateAuth(std::vector<SocksProxyAuthMethod>{
SOCKS_AUTH_NO_AUTH, SOCKS_AUTH_USERPASS});
if (authMethod < 0) {
return false;
}
// Username/Password authentication
if (authMethod == SOCKS_AUTH_USERPASS) {
int status = socket_->authByUserpass(user, passwd);
if (status != 0) {
return false;
}
}
bool res = socket_->authByUserpassOrNone(user, passwd);
if (!res) {
return false;
}
// UDP associate

View File

@ -93,8 +93,8 @@ int SocksProxySocket::negotiateAuth(std::vector<SocksProxyAuthMethod> expected)
return authMethod;
}
char SocksProxySocket::authByUserpass(const std::string& user,
const std::string& passwd)
int SocksProxySocket::authByUserpass(const std::string& user,
const std::string& passwd)
{
std::stringstream req;
req << C_AUTH_USERPASS_VER;
@ -111,6 +111,33 @@ char SocksProxySocket::authByUserpass(const std::string& user,
return res[1];
}
bool SocksProxySocket::authByUserpassOrNone(const std::string& user,
const std::string& passwd)
{
bool noAuth = user.empty() || passwd.empty();
if (noAuth) {
int authMethod =
negotiateAuth(std::vector<SocksProxyAuthMethod>{SOCKS_AUTH_NO_AUTH});
if (authMethod < 0) {
return false;
}
}
else {
int authMethod = negotiateAuth(std::vector<SocksProxyAuthMethod>{
SOCKS_AUTH_NO_AUTH, SOCKS_AUTH_USERPASS});
if (authMethod < 0) {
return false;
}
if (authMethod == SOCKS_AUTH_USERPASS) {
int status = authByUserpass(user, passwd);
if (status != 0) {
return false;
}
}
}
return true;
}
void SocksProxySocket::sendCmd(SocksProxyCmd cmd, const std::string& dstAddr,
uint16_t dstPort, bool allowEmpty)
{

View File

@ -93,7 +93,12 @@ public:
// Username/Password authentication.
// user and pass should not be empty.
// Returns status replied from proxy server. 0 is OK.
char authByUserpass(const std::string& user, const std::string& passwd);
int authByUserpass(const std::string& user, const std::string& passwd);
// Helper to negotiate and auth by username/password authentication, or skip
// it if not required.
// Leave either user or pass empty to force no authentication.
bool authByUserpassOrNone(const std::string& user, const std::string& passwd);
// Create an UDP association to start UDP proxy.
// Leave listen host and port empty / 0 to indicate no receiving from proxy.